comfy-ts 2.24.0 → 2.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (321) hide show
  1. package/dist/chunk-6mgjbrp6.js +579 -0
  2. package/dist/chunk-6mgjbrp6.js.map +17 -0
  3. package/dist/chunk-6tsg7fm5.js +1876 -0
  4. package/dist/chunk-6tsg7fm5.js.map +31 -0
  5. package/dist/chunk-dvxjvwe7.js +2593 -0
  6. package/dist/chunk-dvxjvwe7.js.map +29 -0
  7. package/dist/chunk-dw0t1nye.js +457 -0
  8. package/dist/chunk-dw0t1nye.js.map +16 -0
  9. package/dist/chunk-he70ewwx.js +444 -0
  10. package/dist/chunk-he70ewwx.js.map +13 -0
  11. package/dist/chunk-n22qz0j1.js +6663 -0
  12. package/dist/chunk-n22qz0j1.js.map +95 -0
  13. package/dist/chunk-n35nffm8.js +4777 -0
  14. package/dist/chunk-n35nffm8.js.map +51 -0
  15. package/dist/cli/serve/hostProtocol.d.cts +74 -0
  16. package/dist/cli/serve/hostProtocol.d.ts +74 -0
  17. package/dist/cli/tui-env.d.cts +2 -0
  18. package/dist/cli/tui-env.d.ts +2 -0
  19. package/dist/cli.js +494 -485
  20. package/dist/cli.js.map +16 -1
  21. package/dist/coreExports.d.cts +45 -0
  22. package/dist/coreExports.d.ts +45 -0
  23. package/dist/errors/InvalidPromptError.d.cts +10 -0
  24. package/dist/errors/InvalidPromptError.d.ts +10 -0
  25. package/dist/exampleAssets.d.cts +24 -0
  26. package/dist/exampleAssets.d.ts +24 -0
  27. package/dist/graph/ComfyNode.d.cts +109 -0
  28. package/dist/graph/ComfyNode.d.ts +109 -0
  29. package/dist/graph/ComfyNodeID.d.cts +15 -0
  30. package/dist/graph/ComfyNodeID.d.ts +15 -0
  31. package/dist/graph/ComfyNodeOutput.d.cts +21 -0
  32. package/dist/graph/ComfyNodeOutput.d.ts +21 -0
  33. package/dist/graph/NodeSlotSize.d.cts +4 -0
  34. package/dist/graph/NodeSlotSize.d.ts +4 -0
  35. package/dist/graph/autoValue.d.cts +16 -0
  36. package/dist/graph/autoValue.d.ts +16 -0
  37. package/dist/host/ComfyHost.d.cts +383 -0
  38. package/dist/host/ComfyHost.d.ts +383 -0
  39. package/dist/host/ComfyInstallType.d.cts +11 -0
  40. package/dist/host/ComfyInstallType.d.ts +11 -0
  41. package/dist/host/ComfyManager.d.cts +152 -0
  42. package/dist/host/ComfyManager.d.ts +152 -0
  43. package/dist/host/ComfyUploader.d.cts +42 -0
  44. package/dist/host/ComfyUploader.d.ts +42 -0
  45. package/dist/host/ComfyWorkflowBuilder.d.cts +19 -0
  46. package/dist/host/ComfyWorkflowBuilder.d.ts +19 -0
  47. package/dist/host/Requirements.d.cts +43 -0
  48. package/dist/host/Requirements.d.ts +43 -0
  49. package/dist/host/ResilientWebsocket.d.cts +122 -0
  50. package/dist/host/ResilientWebsocket.d.ts +122 -0
  51. package/dist/host/hostFile.d.cts +23 -0
  52. package/dist/host/hostFile.d.ts +23 -0
  53. package/dist/host/hostUrl.d.cts +22 -0
  54. package/dist/host/hostUrl.d.ts +22 -0
  55. package/dist/host/leastBusy.d.cts +9 -0
  56. package/dist/host/leastBusy.d.ts +9 -0
  57. package/dist/host/loraInfoCache.d.cts +110 -0
  58. package/dist/host/loraInfoCache.d.ts +110 -0
  59. package/dist/host/loraManagerApi.d.cts +106 -0
  60. package/dist/host/loraManagerApi.d.ts +106 -0
  61. package/dist/host/previewMethod.d.cts +5 -0
  62. package/dist/host/previewMethod.d.ts +5 -0
  63. package/dist/host/schemaDrift.d.cts +54 -0
  64. package/dist/host/schemaDrift.d.ts +54 -0
  65. package/dist/image-utils/_getPngMetadata.d.cts +5 -0
  66. package/dist/image-utils/_getPngMetadata.d.ts +5 -0
  67. package/dist/index.cjs +8197 -8509
  68. package/dist/index.cjs.map +124 -1
  69. package/dist/index.d.cts +4 -19116
  70. package/dist/index.d.ts +4 -19116
  71. package/dist/index.js +8129 -8390
  72. package/dist/index.js.map +124 -1
  73. package/dist/litegraph/CanonicalWorkflow.d.cts +75 -0
  74. package/dist/litegraph/CanonicalWorkflow.d.ts +75 -0
  75. package/dist/litegraph/LiteGraphGroup.d.cts +17 -0
  76. package/dist/litegraph/LiteGraphGroup.d.ts +17 -0
  77. package/dist/litegraph/LiteGraphJSON.d.cts +242 -0
  78. package/dist/litegraph/LiteGraphJSON.d.ts +242 -0
  79. package/dist/litegraph/LiteGraphLink.d.cts +48 -0
  80. package/dist/litegraph/LiteGraphLink.d.ts +48 -0
  81. package/dist/litegraph/LiteGraphLinkID.d.cts +6 -0
  82. package/dist/litegraph/LiteGraphLinkID.d.ts +6 -0
  83. package/dist/litegraph/LiteGraphNode.d.cts +76 -0
  84. package/dist/litegraph/LiteGraphNode.d.ts +76 -0
  85. package/dist/litegraph/LiteGraphNodeInput.d.cts +25 -0
  86. package/dist/litegraph/LiteGraphNodeInput.d.ts +25 -0
  87. package/dist/litegraph/LiteGraphNodeOutput.d.cts +20 -0
  88. package/dist/litegraph/LiteGraphNodeOutput.d.ts +20 -0
  89. package/dist/litegraph/LiteGraphSlotIndex.d.cts +6 -0
  90. package/dist/litegraph/LiteGraphSlotIndex.d.ts +6 -0
  91. package/dist/litegraph/LiteGraphSubgraphDef.d.cts +174 -0
  92. package/dist/litegraph/LiteGraphSubgraphDef.d.ts +174 -0
  93. package/dist/litegraph/convertFlowToLiteGraphJSON.d.cts +12 -0
  94. package/dist/litegraph/convertFlowToLiteGraphJSON.d.ts +12 -0
  95. package/dist/litegraph/expandSubgraphs.d.cts +27 -0
  96. package/dist/litegraph/expandSubgraphs.d.ts +27 -0
  97. package/dist/litegraph/normalizeWorkflow.d.cts +21 -0
  98. package/dist/litegraph/normalizeWorkflow.d.ts +21 -0
  99. package/dist/manager/ComfyRegistry.d.cts +54 -0
  100. package/dist/manager/ComfyRegistry.d.ts +54 -0
  101. package/dist/manager/generated/KnownComfyCustomNodeName.d.cts +1 -0
  102. package/dist/manager/generated/KnownComfyCustomNodeName.d.ts +1 -0
  103. package/dist/manager/generated/KnownComfyPluginTitle.d.cts +12109 -0
  104. package/dist/manager/generated/KnownComfyPluginTitle.d.ts +12109 -0
  105. package/dist/manager/generated/KnownComfyPluginURL.d.cts +1 -0
  106. package/dist/manager/generated/KnownComfyPluginURL.d.ts +1 -0
  107. package/dist/manager/generated/KnownModel_Base.d.cts +2 -0
  108. package/dist/manager/generated/KnownModel_Base.d.ts +2 -0
  109. package/dist/manager/generated/KnownModel_Name.d.cts +2842 -0
  110. package/dist/manager/generated/KnownModel_Name.d.ts +2842 -0
  111. package/dist/manager/generated/KnownModel_SavePath.d.cts +2 -0
  112. package/dist/manager/generated/KnownModel_SavePath.d.ts +2 -0
  113. package/dist/manager/generated/KnownModel_Type.d.cts +2 -0
  114. package/dist/manager/generated/KnownModel_Type.d.ts +2 -0
  115. package/dist/manager/installedView.d.cts +65 -0
  116. package/dist/manager/installedView.d.ts +65 -0
  117. package/dist/manager/json/custom-node-list.extra.d.cts +2 -0
  118. package/dist/manager/json/custom-node-list.extra.d.ts +2 -0
  119. package/dist/manager/json/model-list.extra.d.cts +2 -0
  120. package/dist/manager/json/model-list.extra.d.ts +2 -0
  121. package/dist/manager/loaders/parseReport.d.cts +24 -0
  122. package/dist/manager/loaders/parseReport.d.ts +24 -0
  123. package/dist/manager/loaders/step1_downloadComfyManagerJSONs.d.cts +1 -0
  124. package/dist/manager/loaders/step1_downloadComfyManagerJSONs.d.ts +1 -0
  125. package/dist/manager/loaders/step2_custom-node-list-loader.d.cts +2 -0
  126. package/dist/manager/loaders/step2_custom-node-list-loader.d.ts +2 -0
  127. package/dist/manager/loaders/step3_extension-node-map-loader.d.cts +2 -0
  128. package/dist/manager/loaders/step3_extension-node-map-loader.d.ts +2 -0
  129. package/dist/manager/loaders/step4_model-list-loader.d.cts +2 -0
  130. package/dist/manager/loaders/step4_model-list-loader.d.ts +2 -0
  131. package/dist/manager/loaders/step5_alter-list-loader.d.cts +2 -0
  132. package/dist/manager/loaders/step5_alter-list-loader.d.ts +2 -0
  133. package/dist/manager/loaders/step6_github-stats-loader.d.cts +2 -0
  134. package/dist/manager/loaders/step6_github-stats-loader.d.ts +2 -0
  135. package/dist/manager/types/ComfyManagerAPIFetchPolicy.d.cts +7 -0
  136. package/dist/manager/types/ComfyManagerAPIFetchPolicy.d.ts +7 -0
  137. package/dist/manager/types/ComfyManagerAPIModelList.d.cts +10 -0
  138. package/dist/manager/types/ComfyManagerAPIModelList.d.ts +10 -0
  139. package/dist/manager/types/ComfyManagerAPIPluginList.d.cts +33 -0
  140. package/dist/manager/types/ComfyManagerAPIPluginList.d.ts +33 -0
  141. package/dist/manager/types/ComfyManagerAlterInfo.d.cts +12 -0
  142. package/dist/manager/types/ComfyManagerAlterInfo.d.ts +12 -0
  143. package/dist/manager/types/ComfyManagerFileModelInfo.d.cts +10 -0
  144. package/dist/manager/types/ComfyManagerFileModelInfo.d.ts +10 -0
  145. package/dist/manager/types/ComfyManagerFilePluginContent.d.cts +11 -0
  146. package/dist/manager/types/ComfyManagerFilePluginContent.d.ts +11 -0
  147. package/dist/manager/types/ComfyManagerFilePluginList.d.cts +5 -0
  148. package/dist/manager/types/ComfyManagerFilePluginList.d.ts +5 -0
  149. package/dist/manager/types/ComfyManagerGithubStats.d.cts +7 -0
  150. package/dist/manager/types/ComfyManagerGithubStats.d.ts +7 -0
  151. package/dist/manager/types/ComfyManagerModelInfo.d.cts +12 -0
  152. package/dist/manager/types/ComfyManagerModelInfo.d.ts +12 -0
  153. package/dist/manager/types/ComfyManagerPluginContentMetadata.d.cts +10 -0
  154. package/dist/manager/types/ComfyManagerPluginContentMetadata.d.ts +10 -0
  155. package/dist/manager/types/ComfyManagerPluginEnums.d.cts +5 -0
  156. package/dist/manager/types/ComfyManagerPluginEnums.d.ts +5 -0
  157. package/dist/manager/types/ComfyManagerPluginInfo.d.cts +54 -0
  158. package/dist/manager/types/ComfyManagerPluginInfo.d.ts +54 -0
  159. package/dist/promptEnhancers.d.cts +22 -0
  160. package/dist/promptEnhancers.d.ts +22 -0
  161. package/dist/runner/ComfyExecution.d.cts +230 -0
  162. package/dist/runner/ComfyExecution.d.ts +230 -0
  163. package/dist/runner/ComfyExecutionStatus.d.cts +1 -0
  164. package/dist/runner/ComfyExecutionStatus.d.ts +1 -0
  165. package/dist/runner/ComfyWorkflow.d.cts +141 -0
  166. package/dist/runner/ComfyWorkflow.d.ts +141 -0
  167. package/dist/runner/ComfyWorkflowLayout.d.cts +17 -0
  168. package/dist/runner/ComfyWorkflowLayout.d.ts +17 -0
  169. package/dist/runner/ComfyWsApi.d.cts +2174 -0
  170. package/dist/runner/ComfyWsApi.d.ts +2174 -0
  171. package/dist/runner/MediaImage.d.cts +127 -0
  172. package/dist/runner/MediaImage.d.ts +127 -0
  173. package/dist/runner/comfyOrgApiKey.d.cts +21 -0
  174. package/dist/runner/comfyOrgApiKey.d.ts +21 -0
  175. package/dist/runner/describePromptRejection.d.cts +1 -0
  176. package/dist/runner/describePromptRejection.d.ts +1 -0
  177. package/dist/runner/ephemeral.d.cts +10 -0
  178. package/dist/runner/ephemeral.d.ts +10 -0
  179. package/dist/runner/historyReplay.d.cts +13 -0
  180. package/dist/runner/historyReplay.d.ts +13 -0
  181. package/dist/runner/mediaKinds.d.cts +7 -0
  182. package/dist/runner/mediaKinds.d.ts +7 -0
  183. package/dist/runner/outputPath.d.cts +40 -0
  184. package/dist/runner/outputPath.d.ts +40 -0
  185. package/dist/runner/outputs3d.d.cts +3 -0
  186. package/dist/runner/outputs3d.d.ts +3 -0
  187. package/dist/runner/wsBinaryFrame.d.cts +25 -0
  188. package/dist/runner/wsBinaryFrame.d.ts +25 -0
  189. package/dist/sdk-generator/ComfyNodeSchema.d.cts +25 -0
  190. package/dist/sdk-generator/ComfyNodeSchema.d.ts +25 -0
  191. package/dist/sdk-generator/ComfySchema.d.cts +74 -0
  192. package/dist/sdk-generator/ComfySchema.d.ts +74 -0
  193. package/dist/sdk-generator/ComfyUIObjectInfoTypes.d.cts +3072 -0
  194. package/dist/sdk-generator/ComfyUIObjectInfoTypes.d.ts +3072 -0
  195. package/dist/sdk-generator/Primitives.d.cts +12 -0
  196. package/dist/sdk-generator/Primitives.d.ts +12 -0
  197. package/dist/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.d.cts +2 -0
  198. package/dist/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.d.ts +2 -0
  199. package/dist/sdk-generator/_pythonModuleToNamespace.d.cts +1 -0
  200. package/dist/sdk-generator/_pythonModuleToNamespace.d.ts +1 -0
  201. package/dist/sdk-generator/_toQualifiedNodeKey.d.cts +1 -0
  202. package/dist/sdk-generator/_toQualifiedNodeKey.d.ts +1 -0
  203. package/dist/sdk-generator/comfy-api-json.d.cts +16 -0
  204. package/dist/sdk-generator/comfy-api-json.d.ts +16 -0
  205. package/dist/sdk-generator/comfyui-sdk-codegen.d.cts +23 -0
  206. package/dist/sdk-generator/comfyui-sdk-codegen.d.ts +23 -0
  207. package/dist/sdk-generator/comfyui-types.d.cts +55 -0
  208. package/dist/sdk-generator/comfyui-types.d.ts +55 -0
  209. package/dist/sdk-generator/inputWidgetKind.d.cts +80 -0
  210. package/dist/sdk-generator/inputWidgetKind.d.ts +80 -0
  211. package/dist/sdk-generator/litegraphToApiRequestPayload.d.cts +41 -0
  212. package/dist/sdk-generator/litegraphToApiRequestPayload.d.ts +41 -0
  213. package/dist/serve-web.js +51 -51
  214. package/dist/ssh-host-manager/ssh-config-manager.d.cts +17 -0
  215. package/dist/ssh-host-manager/ssh-config-manager.d.ts +17 -0
  216. package/dist/state.d.cts +80 -0
  217. package/dist/state.d.ts +80 -0
  218. package/dist/storage/ComfyStorage.d.cts +55 -0
  219. package/dist/storage/ComfyStorage.d.ts +55 -0
  220. package/dist/storage/nodeStorage.d.cts +2 -0
  221. package/dist/storage/nodeStorage.d.ts +2 -0
  222. package/dist/types/comfy-sdk.d.cts +85 -0
  223. package/dist/types/comfy-sdk.d.ts +85 -0
  224. package/dist/types/index.d.cts +65 -0
  225. package/dist/types/index.d.ts +65 -0
  226. package/dist/utils/CodeBuffer.d.cts +20 -0
  227. package/dist/utils/CodeBuffer.d.ts +20 -0
  228. package/dist/utils/ComfyColors.d.cts +14 -0
  229. package/dist/utils/ComfyColors.d.ts +14 -0
  230. package/dist/utils/ansi.d.cts +22 -0
  231. package/dist/utils/ansi.d.ts +22 -0
  232. package/dist/utils/bang.d.cts +9 -0
  233. package/dist/utils/bang.d.ts +9 -0
  234. package/dist/utils/deepCopyNaive.d.cts +1 -0
  235. package/dist/utils/deepCopyNaive.d.ts +1 -0
  236. package/dist/utils/downloadFile.d.cts +2 -0
  237. package/dist/utils/downloadFile.d.ts +2 -0
  238. package/dist/utils/escapeJSKey.d.cts +2 -0
  239. package/dist/utils/escapeJSKey.d.ts +2 -0
  240. package/dist/utils/exhaust.d.cts +1 -0
  241. package/dist/utils/exhaust.d.ts +1 -0
  242. package/dist/utils/extractErrorMessage.d.cts +2 -0
  243. package/dist/utils/extractErrorMessage.d.ts +2 -0
  244. package/dist/utils/githubRegexes.d.cts +2 -0
  245. package/dist/utils/githubRegexes.d.ts +2 -0
  246. package/dist/utils/hashArrayBuffer.d.cts +1 -0
  247. package/dist/utils/hashArrayBuffer.d.ts +1 -0
  248. package/dist/utils/isRecord.d.cts +2 -0
  249. package/dist/utils/isRecord.d.ts +2 -0
  250. package/dist/utils/lazySharp.d.cts +3 -0
  251. package/dist/utils/lazySharp.d.ts +3 -0
  252. package/dist/utils/log.d.cts +4 -0
  253. package/dist/utils/log.d.ts +4 -0
  254. package/dist/utils/loraTag.d.cts +8 -0
  255. package/dist/utils/loraTag.d.ts +8 -0
  256. package/dist/utils/matchesRegex.d.cts +2 -0
  257. package/dist/utils/matchesRegex.d.ts +2 -0
  258. package/dist/utils/printArkResultInConsole.d.cts +2 -0
  259. package/dist/utils/printArkResultInConsole.d.ts +2 -0
  260. package/dist/utils/safeName.d.cts +6 -0
  261. package/dist/utils/safeName.d.ts +6 -0
  262. package/dist/utils/sha1.d.cts +2 -0
  263. package/dist/utils/sha1.d.ts +2 -0
  264. package/dist/utils/softValidate.d.cts +2 -0
  265. package/dist/utils/softValidate.d.ts +2 -0
  266. package/dist/utils/stringifyReadable.d.cts +1 -0
  267. package/dist/utils/stringifyReadable.d.ts +1 -0
  268. package/dist/utils/toposort.d.cts +3 -0
  269. package/dist/utils/toposort.d.ts +3 -0
  270. package/dist/vars/ComfyVars.d.cts +607 -0
  271. package/dist/vars/ComfyVars.d.ts +607 -0
  272. package/dist/vars/DefinedWorkflow.d.cts +104 -0
  273. package/dist/vars/DefinedWorkflow.d.ts +104 -0
  274. package/dist/vars/lanes.d.cts +81 -0
  275. package/dist/vars/lanes.d.ts +81 -0
  276. package/dist/vars/loraEntry.d.cts +26 -0
  277. package/dist/vars/loraEntry.d.ts +26 -0
  278. package/dist/vars/loraKeywords.d.cts +19 -0
  279. package/dist/vars/loraKeywords.d.ts +19 -0
  280. package/dist/vars/outputWidgets.d.cts +33 -0
  281. package/dist/vars/outputWidgets.d.ts +33 -0
  282. package/dist/vars/presets.d.cts +9 -0
  283. package/dist/vars/presets.d.ts +9 -0
  284. package/dist/vars/promptSyntax.d.cts +98 -0
  285. package/dist/vars/promptSyntax.d.ts +98 -0
  286. package/dist/web.d.cts +2 -0
  287. package/dist/web.d.ts +2 -19160
  288. package/dist/web.js +8040 -8292
  289. package/dist/web.js.map +119 -1
  290. package/examples/depth-explorer/web/tsconfig.json +1 -2
  291. package/examples/upscale-explorer/web/tsconfig.json +1 -2
  292. package/examples/web/tsconfig.json +1 -4
  293. package/examples/world-explorer/web/tsconfig.json +1 -2
  294. package/package.json +27 -32
  295. package/src/cli/serve/web/components/SideMenu.tsx +1 -1
  296. package/src/cli/serve/web/components/controls/LorasControl.tsx +2 -0
  297. package/src/cli/serve/web/components/controls/RichSelect.tsx +1 -0
  298. package/src/cli/serve/web/state/RunSt.poll.test.ts +2 -1
  299. package/src/cli/serve/web/tsconfig.json +1 -2
  300. package/src/cli/serve/web/widgets/RelightWidget.tsx +1 -0
  301. package/src/cli/tui/state/HostSt.ts +1 -1
  302. package/src/host/loraManagerApi.ts +8 -3
  303. package/src/runner/ComfyExecution.ts +3 -1
  304. package/src/runner/ComfyWsApi.ts +2 -1
  305. package/src/storage/ComfyStorage.ts +5 -4
  306. package/src/types/comfy-sdk.ts +1 -0
  307. package/src/utils/ansi.ts +1 -0
  308. package/dist/ServeApp-fsHtW5zG.js +0 -2689
  309. package/dist/ServeApp-fsHtW5zG.js.map +0 -1
  310. package/dist/exampleAssets-DZynSkZm.js +0 -6674
  311. package/dist/exampleAssets-DZynSkZm.js.map +0 -1
  312. package/dist/findDefinedWorkflow-qyqFea7q.js +0 -625
  313. package/dist/findDefinedWorkflow-qyqFea7q.js.map +0 -1
  314. package/dist/run-run-Cn2JzKlE.js +0 -449
  315. package/dist/run-run-Cn2JzKlE.js.map +0 -1
  316. package/dist/run-serve-BhGegaCI.js +0 -464
  317. package/dist/run-serve-BhGegaCI.js.map +0 -1
  318. package/dist/run-tui-CrM4ijkH.js +0 -4569
  319. package/dist/run-tui-CrM4ijkH.js.map +0 -1
  320. package/dist/schemaDrift-BGYJZGMD.js +0 -2225
  321. package/dist/schemaDrift-BGYJZGMD.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"ServeApp-fsHtW5zG.js","names":["EXT","g"],"sources":["../src/cli/serve/describeVar.ts","../src/cli/serve/thumbs.ts","../src/cli/serve/applyVarPayload.ts","../src/utils/safeName.ts","../src/promptEnhancers.ts","../src/cli/serve/web/llm.ts","../src/cli/serve/llmConfigShape.ts","../src/cli/serve/llmConfigs.ts","../src/cli/serve/managerOnlyLoras.ts","../src/cli/serve/tagList.ts","../src/cli/serve/tagSource.ts","../src/cli/serve/favicon.ts","../src/cli/serve/workflowTags.ts","../src/cli/serve/workspaceLabels.ts","../src/utils/stringMap.ts","../src/cli/serve/resultHistory.ts","../src/cli/serve/serveSettings.ts","../src/cli/serve/runError.ts","../src/cli/serve/web/state/draftTabs.ts","../src/cli/serve/ServeApp.ts"],"sourcesContent":["// PURE var → descriptor: ONE introspection pass feeds GET /drafts (json) AND\n// the startup print (renderDescriptorLine)\nimport { ansi } from 'src/utils/ansi.ts'\nimport type {\n AnyVar,\n AnyChoiceVar,\n ChoiceSelect,\n FloatVar,\n MediaVar,\n IntVar,\n LorasVar,\n PromptVar,\n SeedVar,\n SizePreset,\n SizeVar,\n TextVar,\n VarKind,\n VarUi,\n} from 'src/vars/ComfyVars.ts'\nimport type { VarPreset } from 'src/vars/presets.ts'\nimport type { LoraTriggers } from 'src/host/loraInfoCache.ts'\n\nexport type VarDescriptor = {\n kind: VarKind\n label?: string\n /** what a POST payload accepts for this var, human-readable */\n payload: string\n default: unknown\n /** choice vars: exactly one, one or none (value may be null), or many (value is a list) */\n select?: ChoiceSelect\n /** how the workflow wants this var to look (VarUi): icon, colors, description */\n ui?: VarUi\n choices?: readonly string[]\n /** loras: the resolved option list */\n options?: readonly string[]\n /** loras: human display names from the lora-manager mirror, keyed by option — entries only where the label differs (filled by ServeApp.describeModule, which knows the host) */\n optionLabels?: Record<string, string>\n /** prompt: the name of the loras var whose ACTIVE keywords prefix this prompt\n * (`v.prompt(…, { loraKeywordsFrom })`), filled by ServeApp.describeModule, which is the\n * only place that knows both vars by name. The panel previews the injection from it */\n keywordsFrom?: string\n /** loras: the regex the workflow narrowed the list with (`/krea-?2/i`), when it did */\n optionsFilter?: string\n /** loras: hand-assigned keyword (or trigger words) per option, entries only where one\n * exists, what a prompt with `loraKeywordsFrom` will prepend */\n optionKeywords?: Record<string, string>\n /** loras: names the lora-manager mirror knows and ComfyUI's enum does NOT (yet). Offered in\n * the picker with a warning, because a lora present on disk usually runs even when the\n * server has not rescanned its list, filled by ServeApp.describeModule */\n managerOnlyOptions?: readonly string[]\n /** loras: when each file landed on the host (epoch seconds, the lora manager's date), entries\n * only where the mirror has one. The popup's `date added` sort reads it */\n optionAddedAt?: Record<string, number>\n /** loras: trigger words per option as the mirror knows them (words, fetched and empty, or\n * civitai never asked). An option ABSENT from this record is not in the mirror at all */\n optionTriggers?: Record<string, LoraTriggers>\n /** prompt: tag completion is on (`v.prompt(…, { tags })`), with the insert rules. The list\n * itself stays on the server: the editor asks `GET /tags/<module>/<var>?q=` */\n tags?: { underscores: boolean; artistPrefix?: string }\n /** prompt: false when the model ignores `(text:1.2)` weights */\n weights?: false\n /** text: this one wants a box, not a line (`v.text(…, { multiline: true })`) */\n multiline?: boolean\n /** text + prompt: named starting texts (`{ presets: { label: text } }`). NOT `presets`, which\n * a size var already owns with a different shape — one flat descriptor type, two kinds */\n textPresets?: VarPreset[]\n min?: number\n max?: number\n presets?: SizePreset[]\n /** size: preset labels starred by default (quick buttons before the list) */\n starredPresets?: string[]\n extensions?: readonly string[]\n /** image, audio, video: one-click starting files. `thumb` (a url the page can show) and\n * `missing` (a local file not on this machine) are filled by ServeApp.describeModule */\n mediaPresets?: MediaPresetDescriptor[]\n}\n\nexport type MediaPresetDescriptor = { label: string; value: string; thumb?: string; missing?: boolean }\n\n/** an empty list is absent from the json: every var without presets would otherwise carry `[]` */\nfunction presetsOrUndefined(presets: VarPreset[]): VarPreset[] | undefined {\n return presets.length === 0 ? undefined : presets\n}\n\nfunction rangeText(opts: { min?: number; max?: number }): string {\n if (opts.min == null && opts.max == null) return ''\n return ` (${opts.min ?? '-∞'}..${opts.max ?? '∞'})`\n}\n\nexport function describeVar(varDef: AnyVar): VarDescriptor {\n const base = {\n kind: varDef.kind,\n label: varDef.label,\n default: varDef.defaultValue,\n // absent unless the workflow set something: most vars carry no looks\n ...(Object.keys(varDef.uiOpts).length > 0 ? { ui: varDef.uiOpts } : {}),\n }\n // kind, never instanceof: the cli bundle and the consumer's `comfy-ts` import hold\n // different copies of every class (VarKind owns the WHY). Casts are the sanctioned\n // kind-narrowing family (agent/coding.md cast whitelist 6)\n switch (varDef.kind) {\n case 'prompt': {\n const v = varDef as PromptVar\n return {\n ...base,\n payload: 'string (\"//\" starts a comment, \"- \" lines = negative)',\n textPresets: presetsOrUndefined(v.presets),\n tags:\n v.tags == null\n ? undefined\n : { underscores: v.tags.underscores === true, artistPrefix: v.tags.artistPrefix },\n weights: v.promptOpts.weights === false ? false : undefined,\n }\n }\n case 'text': {\n const v = varDef as TextVar\n return { ...base, payload: 'string', multiline: v.opts.multiline, textPresets: presetsOrUndefined(v.presets) }\n }\n case 'int': {\n const v = varDef as IntVar\n return { ...base, payload: `integer${rangeText(v.opts)}`, min: v.opts.min, max: v.opts.max }\n }\n case 'float': {\n const v = varDef as FloatVar\n return { ...base, payload: `number${rangeText(v.opts)}`, min: v.opts.min, max: v.opts.max }\n }\n case 'seed': {\n const v = varDef as SeedVar\n return {\n ...base,\n // defaultMode, never the LIVE mode: serve's vars are shared mutable state, so a\n // run under '?' would otherwise leak its mode into every fileless draft's defaults\n // (and the web ui autosaves those defaults straight back into the draft file)\n default: { mode: v.defaultMode, value: v.defaultValue },\n payload: 'number (fixed) or {\"mode\":\"=|+|-|?\",\"value\":number}',\n }\n }\n case 'toggle':\n return { ...base, payload: 'true or false' }\n case 'choice': {\n const v = varDef as AnyChoiceVar<string>\n const list = v.choices.join(' | ')\n const payload =\n v.select === 'many'\n ? `a list of: ${list}`\n : v.select === 'zero-or-one'\n ? `null or one of: ${list}`\n : `one of: ${list}`\n return { ...base, payload, choices: v.choices, select: v.select }\n }\n case 'loras': {\n const v = varDef as LorasVar<string>\n return {\n ...base,\n payload: '{\"<lora name>\": false | true | strength | [model, clip]}',\n options: v.options,\n // the workflow's own narrowing, shown in the picker so the list is explainable\n optionsFilter: v.optionsFilter == null ? undefined : String(v.optionsFilter),\n }\n }\n case 'size': {\n const v = varDef as SizeVar\n return {\n ...base,\n payload: '{\"width\":W,\"height\":H} or \"WxH\" or a preset label',\n presets: v.presets,\n starredPresets: [...v.starred],\n }\n }\n case 'image':\n case 'audio':\n case 'video': {\n const v = varDef as MediaVar\n const presets = v.presets\n return {\n ...base,\n payload: 'local file path or http(s) url',\n extensions: v.extensions,\n ...(presets.length > 0 ? { mediaPresets: presets } : {}),\n }\n }\n default: {\n // an unknown kind CAN reach here: a globally installed cli against a project on a\n // newer comfy-ts (wire tolerance, agent/coding.md whitelist 4). The `never` binding\n // is the compile-time exhaustiveness check; the RUNTIME path must degrade, because\n // printStartup calls d.kind.padEnd() before the server ever listens\n const unknownKind: never = varDef.kind\n return { ...base, payload: `string (unrecognised kind '${String(unknownKind)}')` }\n }\n }\n}\n\n/** one aligned console line per var (startup print). Padding happens on the PLAIN text: colors are wrapped around the\n * already-padded cells, so a colored and an uncolored print line up identically */\nexport function renderDescriptorLine(name: string, d: VarDescriptor, nameWidth: number, color = false): string {\n const def = typeof d.default === 'string' ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default)\n const cells = { name: name.padEnd(nameWidth), kind: d.kind.padEnd(6), value: truncate(def ?? 'null', 60) }\n if (!color) return ` ${cells.name} ${cells.kind} ${d.payload} · default: ${cells.value}`\n return ` ${ansi.bold(cells.name)} ${ansi.yellow(cells.kind)} ${ansi.gray(d.payload)} ${ansi.gray('· default:')} ${cells.value}`\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : s.slice(0, n - 1) + '…'\n}\n","// small previews of LOCAL images for the panel: a choice option's thumb, a media preset, the\n// current value of an image var. Not a file server: a path is served only when a served module\n// declared it (a thumb, a preset, a default) or it lies under an allowed root (the output root,\n// a served module's folder). An http(s) image is never proxied: the page loads it itself.\nimport { existsSync, statSync } from 'node:fs'\nimport { resolve } from 'pathe'\nimport { importSharp } from 'src/utils/lazySharp.ts'\n\nexport const isHttpUrl = (s: string): boolean => /^https?:\\/\\//i.test(s)\n\n/** the url the page loads for a local image's preview */\nexport function thumbUrl(abs: string, width = 160): string {\n return `/thumb?src=${encodeURIComponent(abs)}&w=${width}`\n}\n\n/** Bun's own image pipeline when the server runs on Bun, sharp only under Node (the cli runs on\n * both). Both read the EXIF orientation */\nasync function webpThumb(path: string, width: number): Promise<Uint8Array> {\n if (typeof Bun !== 'undefined')\n return new Bun.Image(path)\n .resize(width, width, { fit: 'inside', withoutEnlargement: true })\n .webp({ quality: 78 })\n .bytes()\n const sharp = await importSharp('a thumbnail')\n return new Uint8Array(\n await sharp(path)\n .rotate()\n .resize({ width, height: width, fit: 'inside', withoutEnlargement: true })\n .webp({ quality: 78 })\n .toBuffer(),\n )\n}\n\nconst MAX_WIDTH = 640\nconst MAX_CACHED = 400\n\nexport class ThumbStore {\n private allowed = new Set<string>()\n private roots = new Set<string>()\n private cache = new Map<string, Uint8Array>()\n\n /** one file a served module declared */\n allow(abs: string): void {\n this.allowed.add(resolve(abs))\n }\n\n /** every image under this folder */\n allowRoot(dir: string): void {\n this.roots.add(resolve(dir))\n }\n\n isAllowed(abs: string): boolean {\n const p = resolve(abs)\n if (this.allowed.has(p)) return true\n for (const root of this.roots) if (p.startsWith(`${root}/`)) return true\n return false\n }\n\n /** a webp at most `width` wide, or why not: 'forbidden' (not declared, not under a root),\n * 'missing' (not on this machine) */\n async render(abs: string, width: number): Promise<Uint8Array | 'forbidden' | 'missing'> {\n if (!this.isAllowed(abs)) return 'forbidden'\n const p = resolve(abs)\n if (!existsSync(p)) return 'missing'\n const w = Math.max(16, Math.min(MAX_WIDTH, Math.round(width)))\n const key = `${p}|${statSync(p).mtimeMs}|${w}`\n const hit = this.cache.get(key)\n if (hit != null) return hit\n const bytes = await webpThumb(p, w)\n if (this.cache.size >= MAX_CACHED) {\n const oldest = this.cache.keys().next().value\n if (oldest != null) this.cache.delete(oldest)\n }\n this.cache.set(key, bytes)\n return bytes\n }\n}\n","// PURE payload → var application: one POST body value onto one var, per kind.\n// Returns an error message (nothing applied) or null. No fs here — ImageVar\n// url download + existence checks are ServeApp's job.\n//\n// Discrimination is by `kind`, NEVER instanceof: a consumer's `.cflow.ts` imports\n// `comfy-ts` (dist/index.js) while `comfy-ts serve` runs from the cli bundle, and the\n// two hold different copies of every class, so instanceof was false for EVERY var and\n// every payload override answered \"unsupported kind\". The casts\n// below are the sanctioned kind-narrowing family (agent/coding.md cast whitelist 6).\nimport type {\n AnyVar,\n AnyChoiceVar,\n FloatVar,\n MediaVar,\n IntVar,\n LorasVar,\n PromptVar,\n SeedVar,\n SizeVar,\n TextVar,\n ToggleVar,\n} from 'src/vars/ComfyVars.ts'\nimport { isLoraLanes, isLorasInput, isPromptInput } from 'src/vars/lanes.ts'\nimport { isLoraStrength } from 'src/vars/loraEntry.ts'\n\nfunction isFiniteNumber(x: unknown): x is number {\n return typeof x === 'number' && Number.isFinite(x)\n}\n\n/** cap long option lists in error messages */\nfunction listSome(items: readonly string[], cap: number = 20): string {\n if (items.length <= cap) return items.join(', ')\n return `${items.slice(0, cap).join(', ')} … +${items.length - cap} more`\n}\n\n/** `extraLoraOptions`: names the lora-manager mirror knows that ComfyUI's enum does not.\n * they are accepted like any option, the file is on disk, so the run usually works, but\n * ONLY those: an arbitrary name still fails, so a typo cannot reach the host */\nexport function applyVarPayload(\n varDef: AnyVar,\n raw: unknown,\n opts: { extraLoraOptions?: readonly string[] } = {},\n): string | null {\n const name = varDef.name ?? varDef.label ?? varDef.kind\n\n switch (varDef.kind) {\n case 'text': {\n if (typeof raw !== 'string') return `var '${name}' expects a string`\n ;(varDef as TextVar).set(raw)\n return null\n }\n\n case 'prompt': {\n if (!isPromptInput(raw))\n return `var '${name}' expects a string or {\"lanes\": [{\"name\": string, \"prompt\": string, \"active\": boolean}]}`\n ;(varDef as PromptVar).set(raw)\n return null\n }\n\n case 'int':\n case 'float': {\n const v = varDef as IntVar | FloatVar\n if (isFiniteNumber(raw)) {\n v.set(raw) // set() clamps to min/max\n return null\n }\n if (typeof raw === 'string' && v.parse(raw)) return null\n const o = v.opts\n const range = o.min == null && o.max == null ? '' : ` (${o.min ?? '-∞'}..${o.max ?? '∞'})`\n return `var '${name}' expects a number${range}`\n }\n\n case 'seed': {\n const v = varDef as SeedVar\n if (isFiniteNumber(raw)) {\n // an explicit payload seed is FIXED for this request\n v.setMode('=')\n v.set(raw)\n return null\n }\n if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {\n const o = raw as { mode?: unknown; value?: unknown }\n const mode = o.mode === '=' || o.mode === '+' || o.mode === '-' || o.mode === '?' ? o.mode : null\n if (o.mode !== undefined && mode == null) return `var '${name}': mode must be one of = + - ?`\n if (o.value !== undefined && !isFiniteNumber(o.value)) return `var '${name}': value must be a number`\n if (mode == null && o.value === undefined) return `var '${name}': give \"mode\" and/or \"value\"`\n if (mode != null) v.setMode(mode)\n if (isFiniteNumber(o.value)) v.set(o.value)\n return null\n }\n return `var '${name}' expects a number or {\"mode\":\"=|+|-|?\",\"value\":number}`\n }\n\n case 'toggle': {\n if (typeof raw !== 'boolean') return `var '${name}' expects true or false`\n ;(varDef as ToggleVar).set(raw)\n return null\n }\n\n case 'choice': {\n const v = varDef as AnyChoiceVar<string>\n const known = (x: unknown): x is string => typeof x === 'string' && v.choices.includes(x)\n if (v.select === 'many') {\n // one value is a list of one: a tab or a draft from when this was a single choice\n if (known(raw)) {\n v.set([raw])\n return null\n }\n if (Array.isArray(raw) && raw.every(known)) {\n v.set(v.choices.filter((c) => raw.includes(c)))\n return null\n }\n return `var '${name}' expects a list of: ${listSome(v.choices)}`\n }\n if (v.select === 'zero-or-one') {\n if (raw === null || known(raw)) {\n v.set(raw)\n return null\n }\n return `var '${name}' expects null or one of: ${listSome(v.choices)}`\n }\n if (known(raw)) {\n v.set(raw)\n return null\n }\n return `var '${name}' expects one of: ${listSome(v.choices)}`\n }\n\n case 'loras': {\n const v = varDef as LorasVar<string>\n const SHAPE = `{\"<lora name>\": false | true | strength | [model, clip] | {strength, off?, mute?}} or {\"lanes\": [{\"name\", \"active\", \"loras\": {…}}]}`\n if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) return `var '${name}' expects ${SHAPE}`\n const records = isLoraLanes(raw) ? raw.lanes.map((l) => l.loras) : [raw as Record<string, unknown>]\n const known = new Set<string>([...v.options, ...(opts.extraLoraOptions ?? [])])\n for (const record of records) {\n const unknownNames = Object.keys(record).filter((k) => !known.has(k))\n if (unknownNames.length > 0)\n return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome([...known])}`\n for (const [k, st] of Object.entries(record))\n if (!isLoraStrength(st))\n return `var '${name}': '${k}' must be false | true | number | [model, clip] | { strength: [model, clip], off?, mute? }`\n }\n if (!isLorasInput(raw)) return `var '${name}' expects ${SHAPE}`\n v.set(raw) // every lane and entry validated just above\n return null\n }\n\n case 'size': {\n const v = varDef as SizeVar\n if (typeof raw === 'string' && v.parse(raw)) return null\n if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {\n const o = raw as { width?: unknown; height?: unknown }\n if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {\n v.set({ width: o.width, height: o.height })\n return null\n }\n }\n return `var '${name}' expects {\"width\":W,\"height\":H}, \"WxH\", or a preset label`\n }\n\n case 'image':\n case 'audio':\n case 'video': {\n if (typeof raw !== 'string') return `var '${name}' expects a file path or http(s) url string`\n ;(varDef as MediaVar).set(raw)\n return null\n }\n\n default: {\n // same as describeVar: `never` is the compile-time check, the runtime path keeps\n // the message a caller can act on instead of answering a bare token\n const unknownKind: never = varDef.kind\n return `var '${name}' has unsupported kind '${String(unknownKind)}'`\n }\n }\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","// browser → an OpenAI-wire LLM. Three providers: openrouter (cloud), open webui\n// (a local box), and any openai-compatible server (llama.cpp, ollama, vllm). The second http module after api.ts, and the only one that leaves\n// this origin. Keys are parameters, never module state: they live in localStorage\n// (EnhancerSt) and never reach the serve process.\n// parsing is pure and DOM-free so tests/serve-web-enhancer.test.ts covers it.\n\nexport type ProviderId = 'openrouter' | 'openwebui' | 'openai'\n\nexport type Endpoint = { provider: ProviderId; baseUrl: string; key: string }\n\nexport const OPENROUTER_BASE = 'https://openrouter.ai/api/v1'\nexport const OPENWEBUI_BASE = 'http://localhost:3000'\nexport const OPENAI_COMPAT_BASE = 'http://localhost:8080/v1'\n\nexport function defaultBaseUrl(provider: ProviderId): string {\n if (provider === 'openrouter') return OPENROUTER_BASE\n return provider === 'openwebui' ? OPENWEBUI_BASE : OPENAI_COMPAT_BASE\n}\n\nfunction trimSlash(url: string): string {\n return url.trim().replace(/\\/+$/, '')\n}\n\n/** open webui hangs its OpenAI-compatible api under /api, every other base already carries /v1 */\nfunction apiBase(e: Endpoint): string {\n const base = trimSlash(e.baseUrl) === '' ? defaultBaseUrl(e.provider) : trimSlash(e.baseUrl)\n return e.provider === 'openwebui' ? `${base}/api` : base\n}\n\nexport function modelsUrl(e: Endpoint): string {\n return `${apiBase(e)}/models`\n}\n\nexport function chatUrl(e: Endpoint): string {\n return `${apiBase(e)}/chat/completions`\n}\n\n/** reasoning: true = says so · false = says it cannot · null = the provider does not tell\n * (open webui reports no capabilities, and hiding every local model would be the wrong answer) */\nexport type LlmModel = { id: string; name: string; reasoning: boolean | null }\n\nexport type ReasoningEffort = 'off' | 'low' | 'medium' | 'high'\n\n/** an external api drifts: every field is shape-checked before it is kept (coding.md cast family 10) */\nfunction obj(raw: unknown): Record<string, unknown> {\n return typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {}\n}\n\nfunction str(raw: unknown): string {\n return typeof raw === 'string' ? raw : ''\n}\n\nexport function parseModelsReply(raw: unknown): LlmModel[] {\n const data = obj(raw).data\n if (!Array.isArray(data)) return []\n const out: LlmModel[] = []\n for (const entry of data) {\n const m = obj(entry)\n const id = str(m.id)\n if (id === '') continue\n const params = m.supported_parameters\n const reasoning = Array.isArray(params) ? params.includes('reasoning') : null\n out.push({ id, name: str(m.name) === '' ? id : str(m.name), reasoning })\n }\n out.sort((a, b) => a.id.localeCompare(b.id))\n return out\n}\n\nasync function failure(res: Response, what: string): Promise<Error> {\n // never fail silently, and never let a gateway's html body masquerade as json\n const body = await res.text().catch(() => '')\n return new Error(`llm ${what} failed: http ${res.status} ${body.slice(0, 300)}`)\n}\n\n/** a browser fetch that dies on CORS throws a bare TypeError with no detail — say what it\n * probably is, because \"Failed to fetch\" against a local box is otherwise unactionable */\nfunction transportError(e: unknown, url: string): Error {\n if (e instanceof Error && e.name === 'AbortError') return e\n const msg = e instanceof Error ? e.message : String(e)\n return new Error(\n `could not reach ${url} (${msg}) — is it running, and does it allow this origin? open webui needs CORS_ALLOW_ORIGIN`,\n )\n}\n\nexport async function fetchModels(e: Endpoint): Promise<LlmModel[]> {\n const url = modelsUrl(e)\n let res: Response\n try {\n res = await fetch(url, { headers: authHeaders(e) })\n } catch (err) {\n throw transportError(err, url)\n }\n if (!res.ok) throw await failure(res, 'model list')\n return parseModelsReply(await res.json())\n}\n\nfunction authHeaders(e: Endpoint): Record<string, string> {\n // open webui on a trusted local box may run without a key: send the header only when there is one\n return e.key.trim() === '' ? {} : { Authorization: `Bearer ${e.key.trim()}` }\n}\n\nexport type RefineRequest = { model: string; system: string; user: string; effort: ReasoningEffort }\n\n/** the chat body. `reasoning` rides OPENROUTER only: a local backend rejects the unknown field.\n * an openai-compatible server gets the chat template's thinking switch instead: a local thinking\n * model left on can spend the whole budget reasoning and answer nothing */\nexport function buildRefineBody(p: RefineRequest & { provider: ProviderId }): Record<string, unknown> {\n const reasoning =\n p.provider === 'openrouter' && p.effort !== 'off'\n ? { reasoning: { effort: p.effort } }\n : p.provider === 'openai'\n ? { chat_template_kwargs: { enable_thinking: p.effort !== 'off' } }\n : {}\n return {\n model: p.model,\n stream: true,\n messages: [\n { role: 'system', content: p.system },\n { role: 'user', content: p.user },\n ],\n ...reasoning,\n }\n}\n\n/** SSE framing: complete lines come out, the trailing partial stays in `rest` for the next chunk */\nexport function splitSseBuffer(buffer: string): { events: string[]; rest: string } {\n const lines = buffer.split('\\n')\n const rest = lines.pop() ?? ''\n const events: string[] = []\n for (const line of lines) {\n const trimmed = line.trim()\n // \": OPENROUTER PROCESSING\" keep-alive comments are not events\n if (trimmed === '' || trimmed.startsWith(':')) continue\n if (trimmed.startsWith('data:')) events.push(trimmed.slice(5).trim())\n }\n return { events, rest }\n}\n\nexport type StreamDelta = { content: string; reasoning: string }\n\n/** one `data:` payload → what it adds. Cloud thinking models put the answer in `content`\n * and their work in `reasoning`; both are streamed, only content is the prompt */\nexport function readStreamDelta(payload: string): StreamDelta | null {\n if (payload === '' || payload === '[DONE]') return null\n let parsed: unknown\n try {\n parsed = JSON.parse(payload)\n } catch {\n return null\n }\n const root = obj(parsed)\n const err = obj(root.error)\n if (str(err.message) !== '') throw new Error(`llm stream error: ${str(err.message)}`)\n const choices = root.choices\n if (!Array.isArray(choices)) return null\n const delta = obj(obj(choices[0]).delta)\n const content = str(delta.content)\n // some backends spell it reasoning_content\n const reasoning = str(delta.reasoning) === '' ? str(delta.reasoning_content) : str(delta.reasoning)\n if (content === '' && reasoning === '') return null\n return { content, reasoning }\n}\n\n/**\n * local thinking models (qwen3, deepseek-r1 through ollama) stream their reasoning INLINE,\n * as `<think>…</think>` at the head of content. Left alone it lands in the prompt, so it is\n * routed to the thinking pane instead. Stateful because a tag can straddle two chunks.\n */\nexport class ThinkSplitter {\n private inside = false\n /** a partial tag held back until the next chunk decides what it is */\n private pending = ''\n\n feed(chunk: string): StreamDelta {\n let text = this.pending + chunk\n this.pending = ''\n let content = ''\n let reasoning = ''\n for (;;) {\n const tag = this.inside ? '</think>' : '<think>'\n const at = text.indexOf(tag)\n if (at === -1) break\n const before = text.slice(0, at)\n if (this.inside) reasoning += before\n else content += before\n text = text.slice(at + tag.length)\n this.inside = !this.inside\n }\n // a trailing '<' or '</thin' may be the start of a tag: hold it, do not emit it\n const cut = lastOpenTagStart(text)\n if (cut !== -1) {\n this.pending = text.slice(cut)\n text = text.slice(0, cut)\n }\n if (this.inside) reasoning += text\n else content += text\n return { content, reasoning }\n }\n\n /** end of stream: whatever was held back was never a tag, so it is real text */\n flush(): StreamDelta {\n const rest = this.pending\n this.pending = ''\n return this.inside ? { content: '', reasoning: rest } : { content: rest, reasoning: '' }\n }\n}\n\n/** index of a trailing fragment that could still become `<think>` or `</think>`, else -1 */\nfunction lastOpenTagStart(text: string): number {\n const at = text.lastIndexOf('<')\n if (at === -1) return -1\n const tail = text.slice(at)\n return '<think>'.startsWith(tail) || '</think>'.startsWith(tail) ? at : -1\n}\n\n/** streamed refine. onDelta fires per chunk so a slow thinking model shows work, not a spinner */\nexport async function streamRefine(\n p: RefineRequest & { endpoint: Endpoint; signal: AbortSignal; onDelta: (d: StreamDelta) => void },\n): Promise<StreamDelta> {\n if (p.endpoint.provider === 'openrouter' && p.endpoint.key.trim() === '')\n throw new Error('no openrouter api key — paste one in the enhancer settings')\n if (p.model.trim() === '') throw new Error('no model selected')\n const url = chatUrl(p.endpoint)\n let res: Response\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: { ...authHeaders(p.endpoint), 'content-type': 'application/json' },\n body: JSON.stringify(buildRefineBody({ ...p, provider: p.endpoint.provider })),\n signal: p.signal,\n })\n } catch (e) {\n throw transportError(e, url)\n }\n if (!res.ok) throw await failure(res, 'refine')\n const reader = res.body?.getReader()\n if (reader == null) throw new Error('llm refine failed: the response carried no stream')\n const decoder = new TextDecoder()\n const splitter = new ThinkSplitter()\n const total: StreamDelta = { content: '', reasoning: '' }\n const emit = (d: StreamDelta): void => {\n if (d.content === '' && d.reasoning === '') return\n total.content += d.content\n total.reasoning += d.reasoning\n p.onDelta(d)\n }\n let buffer = ''\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n buffer += decoder.decode(chunk.value, { stream: true })\n const split = splitSseBuffer(buffer)\n buffer = split.rest\n for (const event of split.events) {\n const delta = readStreamDelta(event)\n if (delta == null) continue\n // inline <think> is split out of CONTENT; a provider-reported reasoning field rides along\n const parts = splitter.feed(delta.content)\n emit({ content: parts.content, reasoning: parts.reasoning + delta.reasoning })\n }\n }\n emit(splitter.flush())\n if (total.content.trim() === '') throw new Error('the model returned no prompt text — try another model')\n return total\n}\n","// one LLM config of the prompt enhancer: where the model runs and how it is asked. PURE (the\n// browser bundle and serve both read it), every field runtime-checked, since the file is\n// hand-editable. No api key here: keys stay in the browser (architecture item 13)\nimport { defaultBaseUrl, type ProviderId, type ReasoningEffort } from 'src/cli/serve/web/llm.ts'\n\nexport type LlmConfig = {\n provider: ProviderId\n baseUrl: string\n model: string\n effort: ReasoningEffort\n /** hide models that report no reasoning support */\n thinkingOnly: boolean\n}\n\nexport type LlmConfigEntry = { name: string; config: LlmConfig }\n\nexport function isProvider(raw: unknown): raw is ProviderId {\n return raw === 'openrouter' || raw === 'openwebui' || raw === 'openai'\n}\n\nexport function isEffort(raw: unknown): raw is ReasoningEffort {\n return raw === 'off' || raw === 'low' || raw === 'medium' || raw === 'high'\n}\n\n/** explicit model ids, never an alias: behaviour and cost stay reproducible */\nconst DEFAULT_MODEL: Record<ProviderId, string> = {\n openrouter: 'anthropic/claude-sonnet-5',\n openwebui: '',\n openai: '',\n}\n\n/** a stored file → a usable config: a half-written or hand-broken field degrades to its\n * default, never breaks the modal */\nexport function normalizeLlmConfig(raw: unknown): LlmConfig {\n const o = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {}\n const provider = isProvider(o.provider) ? o.provider : 'openrouter'\n return {\n provider,\n baseUrl: typeof o.baseUrl === 'string' && o.baseUrl.trim() !== '' ? o.baseUrl.trim() : defaultBaseUrl(provider),\n model: typeof o.model === 'string' ? o.model : DEFAULT_MODEL[provider],\n effort: isEffort(o.effort) ? o.effort : 'medium',\n thinkingOnly: o.thinkingOnly !== false,\n }\n}\n\n/** switching provider resets what belongs to the old one: an openrouter model id sent to a\n * local box, or a local base url sent to openrouter, is never what anyone means */\nexport function withProvider(c: LlmConfig, provider: ProviderId): LlmConfig {\n if (provider === c.provider) return c\n return { ...c, provider, baseUrl: defaultBaseUrl(provider), model: DEFAULT_MODEL[provider] }\n}\n","// the prompt enhancer's LLM configs as FILES: `.comfy-ts/llm-configs/<name>.json`, the drafts\n// model. The FILENAME is the identity (a rename is a write plus a delete), validStoreName is the\n// same gate the draft routes use. SERVE-ONLY: no workflow reads these\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'pathe'\nimport { normalizeLlmConfig, type LlmConfig, type LlmConfigEntry } from 'src/cli/serve/llmConfigShape.ts'\nimport { validStoreName } from 'src/utils/safeName.ts'\n\nconst EXT = '.json'\n\nexport function llmConfigsDir(): string {\n return comfyts.resolveFromLlmConfigs('')\n}\n\nfunction llmConfigPath(name: string): string | null {\n const safe = validStoreName(name)\n return safe == null ? null : join(llmConfigsDir(), `${safe}${EXT}`)\n}\n\nexport function listLlmConfigs(): LlmConfigEntry[] {\n const dir = llmConfigsDir()\n if (!existsSync(dir)) return []\n const out: LlmConfigEntry[] = []\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 broken file is skipped loudly, the rest still list\n try {\n out.push({ name, config: normalizeLlmConfig(JSON.parse(readFileSync(join(dir, file), 'utf8'))) })\n } catch (e) {\n console.error(`[serve] llm config '${name}' unreadable, skipped:`, e)\n }\n }\n return out\n}\n\nexport function writeLlmConfig(name: string, config: LlmConfig): string | null {\n const path = llmConfigPath(name)\n if (path == null) return null\n mkdirSync(llmConfigsDir(), { recursive: true })\n writeFileSync(path, `${JSON.stringify(normalizeLlmConfig(config), null, 3)}\\n`)\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 deleteLlmConfig(name: string): boolean {\n const path = llmConfigPath(name)\n if (path == null) return false\n if (existsSync(path)) rmSync(path)\n return true\n}\n","// the loras a host's lora-manager knows but its object_info enum does not yet list.\n// ONE function, because the picker and the payload validator must agree exactly: whatever\n// the ui offers, `applyVarPayload` compares by RAW STRING, so a name built with the wrong\n// separator is offered and then refused as an unknown lora.\nimport { loraMirrorEntries } from 'src/host/loraInfoCache.ts'\nimport { loraKey } from 'src/host/loraManagerApi.ts'\nimport { statelessRegex } from 'src/utils/matchesRegex.ts'\n\n/**\n * `options` is the host enum for this var: it decides both what counts as already-known\n * (compared by normalized key, never raw, the enum keeps case, extension and separators)\n * and which separator the rebuilt names must use.\n */\nexport function managerOnlyLoraOptions(p: {\n hostId: string\n options: readonly string[]\n /** the var's own narrowing, `v.loras(/krea-?2/i)`: it applies to the mirror too */\n filter?: RegExp | null\n}): string[] {\n const filter = p.filter == null ? null : statelessRegex(p.filter)\n const known = new Set(p.options.map((o) => loraKey(o)))\n const separator = p.options.some((o) => o.includes('\\\\')) ? '\\\\' : '/'\n return loraMirrorEntries(p.hostId, { separator })\n .filter((e) => !known.has(e.key))\n .map((e) => e.serverName)\n .filter((n) => filter == null || filter.test(n))\n}\n","// a booru tag list in memory: parsed once per source, searched per keystroke. PURE (text in, hits\n// out). Formats: the a1111 tagcomplete csv `name,category,count,\"alias,alias\"`, or one tag per line\n\nexport type TagEntry = { name: string; category: number | null; count: number; aliases: string[] }\nexport type TagHit = { name: string; category: number | null; count: number; alias?: string }\n\n/** one csv line, double-quoted fields with `\"\"` escapes */\nfunction csvFields(line: string): string[] {\n const out: string[] = []\n let cur = ''\n let quoted = false\n for (let i = 0; i < line.length; i++) {\n const ch = line[i]\n if (quoted) {\n if (ch === '\"' && line[i + 1] === '\"') {\n cur += '\"'\n i++\n } else if (ch === '\"') quoted = false\n else cur += ch\n } else if (ch === '\"') quoted = true\n else if (ch === ',') {\n out.push(cur)\n cur = ''\n } else cur += ch\n }\n out.push(cur)\n return out\n}\n\nconst intOrNull = (s: string | undefined): number | null => (s != null && /^\\d+$/.test(s.trim()) ? Number(s) : null)\n\nexport function parseTagList(text: string): TagEntry[] {\n const out: TagEntry[] = []\n for (const raw of text.split(/\\r?\\n/)) {\n const line = raw.trim()\n if (line === '' || line.startsWith('#')) continue\n const f = csvFields(line)\n const name = (f[0] ?? '').trim()\n if (name === '') continue\n // `name,count` (two columns) is a counted plain list; three and more is the tagcomplete shape\n const twoCols = f.length === 2\n out.push({\n name,\n category: twoCols ? null : intOrNull(f[1]),\n count: (twoCols ? intOrNull(f[1]) : intOrNull(f[2])) ?? 0,\n aliases: (f[3] ?? '')\n .split(',')\n .map((a) => a.trim())\n .filter((a) => a !== ''),\n })\n }\n return out\n}\n\n/** the searchable form: lowercase, spaces as underscores (the lists write `long_hair`) */\nconst key = (s: string): string => s.trim().toLowerCase().replace(/\\s+/g, '_')\n\nexport class TagList {\n private rows: { e: TagEntry; name: string; aliases: string[] }[]\n constructor(public readonly entries: TagEntry[]) {\n this.rows = entries.map((e) => ({ e, name: key(e.name), aliases: e.aliases.map(key) }))\n this.rows.sort((a, b) => b.e.count - a.e.count)\n }\n\n static parse(text: string): TagList {\n return new TagList(parseTagList(text))\n }\n\n /** prefix of the name first, then prefix of an alias (answered with the name it points to),\n * then a word inside the name (`hair` finds `long_hair`), each by post count */\n search(query: string, limit = 20): TagHit[] {\n const q = key(query)\n if (q === '') return []\n const hits: TagHit[] = []\n const seen = new Set<string>()\n const take = (e: TagEntry, alias?: string): boolean => {\n if (seen.has(e.name)) return false\n seen.add(e.name)\n hits.push(alias == null ? { name: e.name, category: e.category, count: e.count } : { ...pick(e), alias })\n return hits.length >= limit\n }\n for (const r of this.rows) if (r.name.startsWith(q) && take(r.e)) return hits\n for (const r of this.rows) {\n const a = r.aliases.find((x) => x.startsWith(q))\n if (a != null && take(r.e, a)) return hits\n }\n for (const r of this.rows) if (r.name.includes(`_${q}`) && take(r.e)) return hits\n return hits\n }\n}\n\nconst pick = (e: TagEntry): TagHit => ({ name: e.name, category: e.category, count: e.count })\n","// where a prompt's tag list comes from: `v.prompt(…, { tags })` names a url, serve reads it once and\n// keeps it in memory. The list never ships with the code: a remote one is fetched on first use and\n// kept under the cache dir, a local one is re-read when its file changes\nimport { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, isAbsolute, join, resolve } from 'pathe'\nimport { TagList } from 'src/cli/serve/tagList.ts'\nimport { sha1HexOfString } from 'src/utils/sha1.ts'\n\nexport type TagSourceRef = { kind: 'file'; path: string } | { kind: 'http'; url: string }\n\n/** http(s) stays a url; `file://`, `~/`, absolute and relative (to the workflow file) become a path */\nexport function resolveTagSource(url: string, moduleFile: string): TagSourceRef {\n if (/^https?:\\/\\//i.test(url)) return { kind: 'http', url }\n if (url.startsWith('file://')) return { kind: 'file', path: fileURLToPath(url) }\n if (url === '~' || url.startsWith('~/')) return { kind: 'file', path: join(homedir(), url.slice(1)) }\n if (isAbsolute(url)) return { kind: 'file', path: url }\n return { kind: 'file', path: resolve(dirname(moduleFile), url) }\n}\n\nexport class TagSources {\n private files = new Map<string, { mtimeMs: number; list: TagList }>()\n private remote = new Map<string, Promise<TagList>>()\n\n constructor(\n private p: {\n /** where remote lists are kept between runs */\n cacheDir: () => string\n /** a capped download: a tag list url pointing at something huge must not exhaust serve */\n fetchText: (url: string) => Promise<string>\n },\n ) {}\n\n async load(ref: TagSourceRef): Promise<TagList> {\n if (ref.kind === 'file') return this.loadFile(ref.path)\n const hit = this.remote.get(ref.url)\n if (hit != null) return hit\n const pending = this.loadRemote(ref.url)\n this.remote.set(ref.url, pending)\n // a failure is not remembered: the next keystroke retries (the network may be back)\n pending.catch(() => this.remote.delete(ref.url))\n return pending\n }\n\n private loadFile(path: string): TagList {\n if (!existsSync(path)) throw new Error(`tag list not found: ${path}`)\n const mtimeMs = statSync(path).mtimeMs\n const cached = this.files.get(path)\n if (cached != null && cached.mtimeMs === mtimeMs) return cached.list\n const list = TagList.parse(readFileSync(path, 'utf8'))\n if (list.entries.length === 0) throw new Error(`tag list is empty: ${path}`)\n this.files.set(path, { mtimeMs, list })\n return list\n }\n\n private async loadRemote(url: string): Promise<TagList> {\n const file = join(this.p.cacheDir(), `${sha1HexOfString(url)}.txt`)\n if (existsSync(file)) return TagList.parse(readFileSync(file, 'utf8'))\n console.log(`[serve] fetching tag list ${url}`)\n const text = await this.p.fetchText(url)\n const list = TagList.parse(text)\n if (list.entries.length === 0) throw new Error(`tag list is empty: ${url}`)\n mkdirSync(dirname(file), { recursive: true })\n writeFileSync(file, text)\n console.log(`[serve] tag list ${url}: ${list.entries.length} tags, kept in ${file}`)\n return list\n }\n}\n","// generated by scripts/gen-favicon.ts from .shipkit/identity/icon.png, never ed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8RYVjWTQgAuzU0TI51jCRgD+EOyiYPkuLCFxi4muAKQkUp6AQ0Hu2nC51daHTBHqsr8OJKh3Tr9Qk+qX0uLh6aoDBLe3lHgd3d4UEgLWaPFLOWR3jhSwNclIoNX1tZUSXWcjyWdfECp8T2fNyDBknJ02/G+JySYH3xjrPT9O92OG6Q/yxRiEh6ISE2V49U+mYWlUmrcLkstTtbd1md/ibcwX2EajiEBnrMVBbBDs8vF3oCAyYkBZe6NQqRDj4u6wb9X4FsoQjVsFIA4HrZ8LHY1TUXbiXcUtHHbeWRTpvj7D1XvsO7qspw5NhsH4wVYB3KuwYNmAZw5UvS3bh8brW4gvvRKL/zlQKfSiEqCcaR/HnWzfWfZMX6snq1evtMZCITmchEJjKRiUxkIhM3ZfwPK9dyLD4coj4AAAAASUVORK5CYII='\n","// search tags of a workflow, read from its built graph. PURE, tests/serve-workflow-tags.test.ts.\n// the graph is the truth: a file named t2a that grew a video output says video\n\n/** one node of a built graph, reduced to what tagging reads */\nexport type TagNode = {\n id: string\n classType: string\n outputNode: boolean\n /** the node's output slot types, by index */\n outputTypes: readonly string[]\n /** the inputs linked to another node's output: [producer id, output index] */\n links: readonly (readonly [string, number])[]\n}\n\n/** display order: what the workflow makes first, then how it works, then free tags */\nconst MEDIA_BY_TYPE: Record<string, string> = { IMAGE: 'image', AUDIO: 'audio', VIDEO: 'video', STRING: 'text' }\nconst MEDIA_ORDER = ['image', 'audio', 'video', 'text']\n\nexport function workflowTags(p: {\n nodes: readonly TagNode[]\n varKinds: readonly string[]\n extra?: readonly string[]\n}): string[] {\n const byId = new Map(p.nodes.map((n) => [n.id, n]))\n const media = new Set<string>()\n for (const node of p.nodes) {\n if (!node.outputNode) continue\n for (const [producerId, ix] of node.links) {\n const type = byId.get(producerId)?.outputTypes[ix]\n const tag = type == null ? undefined : MEDIA_BY_TYPE[type]\n if (tag != null) media.add(tag)\n }\n }\n const out = MEDIA_ORDER.filter((t) => media.has(t))\n if (p.nodes.some((n) => /textgenerate/i.test(n.classType))) out.push('llm')\n if (p.varKinds.includes('image')) out.push('edit')\n for (const tag of p.extra ?? []) {\n const t = tag.trim().toLowerCase()\n if (t !== '' && !out.includes(t)) out.push(t)\n }\n return out\n}\n","// the menu column's two read-only cards. PURE, tests/serve-workspace-labels.test.ts.\n// the full path is what a click copies; the label is what fits in a 220px card\n\nexport type PathLabel = { path: string; label: string }\n\nfunction tilde(path: string, home: string): string {\n if (home === '' || home === '/') return path\n if (path === home) return '~'\n return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path\n}\n\nexport function workspaceLabels(p: { workspace: string; root: string; home: string }): {\n workspace: PathLabel\n root: PathLabel\n} {\n const ws = p.workspace.replace(/\\/+$/, '')\n const root = p.root.replace(/\\/+$/, '')\n const rootLabel = root === ws ? '.' : root.startsWith(`${ws}/`) ? root.slice(ws.length + 1) : tilde(root, p.home)\n return {\n workspace: { path: ws, label: tilde(ws, p.home) },\n root: { path: root, label: rootLabel },\n }\n}\n","// unknown json → a plain record of strings. Every localStorage blob and every settings file\n// crossing into this process needs the same shape check; two copies of it drift.\nexport function stringMap(raw: unknown): Record<string, string> {\n const out: Record<string, string> = {}\n if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) {\n for (const [k, v] of Object.entries(raw)) if (typeof v === 'string') out[k] = v\n }\n return out\n}\n","// the serve process's memory of its last runs: a page reload (or a second window) shows them\n// again. Unsaved outputs keep their bytes here, the ONLY copy, under one byte budget, FIFO.\n// Nothing is written to disk: a server restart forgets it all. PURE, headless-tested\n\nimport type { OutputWidget } from 'src/vars/outputWidgets.ts'\n\n/** `tags`: the save node's metadata tags, which output widgets read (absent on older records) */\nexport type RunOutput = { filename: string; url: string | null; absPath: string | null; tags?: string[] }\nexport type RunAudioOutput = RunOutput & { mime: string }\n/** a mesh, point cloud or splat: `format` the lowercase extension, `size` in bytes */\nexport type RunModel3DOutput = RunAudioOutput & { format: string; size: number }\n\n/** the run reply `POST /generate` answers, and what `GET /results` lists */\nexport type RunRecord = {\n ok: true\n module: string\n draft: string\n promptId: string\n durationMs: number\n /** epoch ms: the panel formats it, the server's clock is the one every window shares */\n finishedAt: number\n seeds: Record<string, number>\n savedToDisk: boolean\n texts: { nodeKey: string | null; text: string }[]\n images: RunOutput[]\n audios: RunAudioOutput[]\n /** absent on a record from an older server */\n videos?: RunAudioOutput[]\n /** absent on a record from an older server */\n models3d?: RunModel3DOutput[]\n /** the module's output widgets at run time, so a kept result draws them after a reload */\n widgets?: OutputWidget[]\n}\n\nexport type MemoryUsage = { usedBytes: number; budgetBytes: number; outputs: number; runs: number }\n\n/** the bytes of one unsaved output, under the key its url names */\nexport type KeptBlob = { key: string; bytes: Uint8Array; contentType: string }\n\n/** how many runs the list keeps, saved or not. The panel shows as many */\nexport const KEPT_RUNS = 50\n\nexport const DEFAULT_MEMORY_BUDGET_MB = 100\n\n/** a run and the memory key of each output (null = saved on disk, or never had bytes) */\ntype Kept = {\n record: RunRecord\n imageKeys: (string | null)[]\n audioKeys: (string | null)[]\n videoKeys: (string | null)[]\n model3dKeys: (string | null)[]\n}\n\nexport class ResultHistory {\n /** newest first */\n private runs: Kept[] = []\n /** insertion order IS the eviction order */\n private blobs = new Map<string, { bytes: Uint8Array; contentType: string }>()\n private used = 0\n\n constructor(private budgetBytes: number) {}\n\n add(p: {\n record: RunRecord\n imageKeys: (string | null)[]\n audioKeys: (string | null)[]\n videoKeys?: (string | null)[]\n model3dKeys?: (string | null)[]\n blobs: KeptBlob[]\n }): void {\n this.remove(p.record.promptId)\n for (const b of p.blobs) {\n this.blobs.set(b.key, { bytes: b.bytes, contentType: b.contentType })\n this.used += b.bytes.byteLength\n }\n const kept = {\n record: p.record,\n imageKeys: p.imageKeys,\n audioKeys: p.audioKeys,\n videoKeys: p.videoKeys ?? [],\n model3dKeys: p.model3dKeys ?? [],\n }\n this.runs = [kept, ...this.runs]\n for (const dropped of this.runs.slice(KEPT_RUNS)) this.freeRun(dropped)\n this.runs = this.runs.slice(0, KEPT_RUNS)\n this.evict()\n }\n\n blob(key: string): { bytes: Uint8Array; contentType: string } | null {\n return this.blobs.get(key) ?? null\n }\n\n /** an output whose bytes were evicted lists with url null: the panel says it is gone */\n list(): RunRecord[] {\n return this.runs.map((k) => ({\n ...k.record,\n images: k.record.images.map((img, ix) => this.withLiveUrl(img, k.imageKeys[ix])),\n audios: k.record.audios.map((a, ix) => this.withLiveUrl(a, k.audioKeys[ix])),\n videos: (k.record.videos ?? []).map((a, ix) => this.withLiveUrl(a, k.videoKeys[ix])),\n models3d: (k.record.models3d ?? []).map((a, ix) => this.withLiveUrl(a, k.model3dKeys[ix])),\n }))\n }\n\n remove(promptId: string): void {\n const hit = this.runs.find((k) => k.record.promptId === promptId)\n if (hit == null) return\n this.freeRun(hit)\n this.runs = this.runs.filter((k) => k !== hit)\n }\n\n clear(): void {\n this.runs = []\n this.blobs.clear()\n this.used = 0\n }\n\n setBudget(bytes: number): void {\n this.budgetBytes = bytes\n this.evict()\n }\n\n usage(): MemoryUsage {\n return { usedBytes: this.used, budgetBytes: this.budgetBytes, outputs: this.blobs.size, runs: this.runs.length }\n }\n\n private withLiveUrl<T extends RunOutput>(out: T, key: string | null | undefined): T {\n if (key == null || this.blobs.has(key)) return out\n return { ...out, url: null }\n }\n\n private freeRun(k: Kept): void {\n for (const key of [...k.imageKeys, ...k.audioKeys, ...k.videoKeys, ...k.model3dKeys]) {\n if (key == null) continue\n const b = this.blobs.get(key)\n if (b == null) continue\n this.used -= b.bytes.byteLength\n this.blobs.delete(key)\n }\n }\n\n /** the NEWEST output always stays, even alone over budget: the run that just finished must\n * not reply with a url that already 404s */\n private evict(): void {\n while (this.used > this.budgetBytes && this.blobs.size > 1) {\n const oldest = this.blobs.entries().next()\n if (oldest.done === true) break\n this.used -= oldest.value[1].bytes.byteLength\n this.blobs.delete(oldest.value[0])\n }\n // a run with nothing left to show is noise in the list\n this.runs = this.runs.filter((k) => {\n const live = (keys: (string | null)[]): boolean => keys.some((key) => key == null || this.blobs.has(key))\n const hasText = k.record.texts.length > 0\n const hasNothing =\n k.record.images.length === 0 &&\n k.record.audios.length === 0 &&\n (k.record.videos ?? []).length === 0 &&\n (k.record.models3d ?? []).length === 0\n return (\n hasText || hasNothing || live(k.imageKeys) || live(k.audioKeys) || live(k.videoKeys) || live(k.model3dKeys)\n )\n })\n }\n}\n","// serve's own slice of `.comfy-ts/settings.json`, under a `serve` key.\n// MERGE, never rewrite: the TUI owns the rest of that file and a whole-blob write\n// from here would silently drop its preview mode, last draft and lora prefixes.\n// deliberately NOT the TUI's `saveToDisk`: that one governs TUI runs, this one\n// governs the api's, so the two surfaces cannot fight over one value.\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { stringMap } from 'src/utils/stringMap.ts'\nimport { validSavePrefix } from 'src/utils/safeName.ts'\nimport { dirname } from 'pathe'\nimport { DEFAULT_MEMORY_BUDGET_MB } from 'src/cli/serve/resultHistory.ts'\n\nexport type ServeSettings = {\n /** false = generations stay in memory, streamed to the client, nothing written to outputs/ */\n saveToDisk: boolean\n /** module key → host id the runs go to, when it is not the one the module defined\n * (the TUI's host override, per module because serve holds many workflows at once) */\n hostOverride: Record<string, string>\n /** module key → subfolder under outputs/ its images land in. Empty/absent = the module key,\n * which is what serve always used before it was choosable */\n savePrefix: Record<string, string>\n /** byte budget of the unsaved outputs the process keeps for a reload, oldest dropped first */\n memoryBudgetMb: number\n}\n\nconst DEFAULT_SERVE_SETTINGS: ServeSettings = {\n saveToDisk: true,\n hostOverride: {},\n savePrefix: {},\n memoryBudgetMb: DEFAULT_MEMORY_BUDGET_MB,\n}\n\n/** null = not a budget. A hand-written file goes through the same gate as PUT /settings */\nexport function validMemoryBudgetMb(raw: unknown): number | null {\n if (typeof raw !== 'number' || !Number.isFinite(raw)) return null\n if (raw < 1 || raw > 100_000) return null\n return Math.round(raw)\n}\n\n/** null when no comfyts is registered yet: a ServeApp can be constructed before the global\n * exists (tests do), and reading a setting must degrade to defaults, never throw */\nfunction settingsPath(): string | null {\n const g = globalThis as { comfyts?: { settingsPath?: string } }\n const path = g.comfyts?.settingsPath\n return typeof path === 'string' ? path : null\n}\n\n/** `readable: false` says the file EXISTS but could not be parsed — the one case where a write\n * must refuse. Merging onto `{}` there would rewrite the file from nothing and take the TUI's\n * keys with it, and these files are documented as hand-editable, so the user would lose the\n * chance to repair it. */\nfunction readBlob(): { blob: Record<string, unknown>; readable: boolean } {\n const path = settingsPath()\n if (path == null || !existsSync(path)) return { blob: {}, readable: true }\n try {\n const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))\n const ok = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)\n if (!ok) console.error(`[serve] settings is not an object (${path}), using defaults`)\n return { blob: ok ? (parsed as Record<string, unknown>) : {}, readable: ok }\n } catch (e) {\n // reading must not take the server down: log loud, use defaults, and refuse to WRITE\n console.error(`[serve] settings unreadable (${path}), using defaults:`, e)\n return { blob: {}, readable: false }\n }\n}\n\n/** keeps the CLEANED value, not the raw one: storing the raw form let the same input mean two\n * different directories depending on whether it arrived by PUT or by hand */\nfunction cleanValues(map: Record<string, string>, clean: (v: string) => string | null): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(map)) {\n const ok = clean(v)\n if (ok != null) out[k] = ok\n }\n return out\n}\n\nexport function readServeSettings(): ServeSettings {\n const serve = readBlob().blob.serve\n const o = typeof serve === 'object' && serve !== null ? (serve as Record<string, unknown>) : {}\n return {\n saveToDisk: typeof o.saveToDisk === 'boolean' ? o.saveToDisk : DEFAULT_SERVE_SETTINGS.saveToDisk,\n hostOverride: stringMap(o.hostOverride),\n // validated on the way IN as well as on the way out: PUT /settings gates it, but a\n // hand-written file did not go through that route, and this value becomes an output\n // directory. One gate on one side is not a gate\n savePrefix: cleanValues(stringMap(o.savePrefix), validSavePrefix),\n memoryBudgetMb: validMemoryBudgetMb(o.memoryBudgetMb) ?? DEFAULT_SERVE_SETTINGS.memoryBudgetMb,\n }\n}\n\nexport function writeServeSettings(next: ServeSettings): void {\n const path = settingsPath()\n // loud: the caller reports \"applied for this session but not saved\" rather than pretending\n if (path == null) throw new Error('no comfyts instance registered — cannot persist serve settings')\n const current = readBlob()\n if (!current.readable)\n throw new Error(\n `serve settings not saved: ${path} is not readable json. Fix or delete it — overwriting would drop the keys it still holds`,\n )\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify({ ...current.blob, serve: next }, null, 2))\n}\n","// a failed run's error as ONE readable line. ComfyExecution stores ComfyUI's whole\n// execution_error message; every client reads `error` as text\nexport function describeRunError(error: unknown): string {\n if (error == null) return 'execution failed'\n if (typeof error === 'string') return error\n if (error instanceof Error) return error.message\n if (typeof error === 'object') {\n const data = (error as { data?: unknown }).data\n if (typeof data === 'object' && data !== null) {\n const d = data as Record<string, unknown>\n if (typeof d.exception_message === 'string') {\n const where = typeof d.node_type === 'string' ? `${d.node_type} (node ${String(d.node_id)}): ` : ''\n const kind = typeof d.exception_type === 'string' && d.exception_type !== '' ? `${d.exception_type}: ` : ''\n return `${where}${kind}${d.exception_message.trim()}`\n }\n }\n }\n try {\n return JSON.stringify(error)\n } catch {\n return String(error)\n }\n}\n","// the open drafts as tabs: pure list operations and key reads, the store (WebSt) owns when they run\nexport type DraftTab = { module: string; draft: string }\n\n/** where the serve process keeps them, under .comfy-ts/: draft names are private, so this file\n * must stay gitignored (tests/serve-tabs.test.ts runs git check-ignore on it) */\nexport const SERVE_TABS_FILE = 'serve-tabs.json'\n\nconst same = (a: DraftTab, b: DraftTab): boolean => a.module === b.module && a.draft === b.draft\n\n/** a draft you open gets a tab at the end; one already open keeps its place */\nexport function openTab(tabs: readonly DraftTab[], t: DraftTab): readonly DraftTab[] {\n return tabs.some((x) => same(x, t)) ? tabs : [...tabs, { module: t.module, draft: t.draft }]\n}\n\n/** `next` is where to go: the right neighbour of the closed OPEN tab, else its left one, null\n * when the open tab stays. The last tab stays: a draft is always open */\nexport function closeTab(\n tabs: readonly DraftTab[],\n t: DraftTab,\n active: DraftTab | null,\n): { tabs: readonly DraftTab[]; next: DraftTab | null } {\n const ix = tabs.findIndex((x) => same(x, t))\n if (ix < 0 || tabs.length <= 1) return { tabs, next: null }\n const rest = tabs.filter((_, i) => i !== ix)\n if (active == null || !same(active, t)) return { tabs: rest, next: null }\n return { tabs: rest, next: rest[Math.min(ix, rest.length - 1)] ?? null }\n}\n\n/** the renamed draft keeps the tab's place, even when the switch already opened it at the end */\nexport function renameTab(tabs: readonly DraftTab[], from: DraftTab, to: DraftTab): readonly DraftTab[] {\n const ix = tabs.findIndex((x) => same(x, from))\n const rest = tabs.filter((x) => !same(x, to))\n if (ix < 0) return openTab(rest, to)\n return rest.map((x) => (same(x, from) ? { module: to.module, draft: to.draft } : x))\n}\n\n/** ⌘1 to ⌘8 (ctrl elsewhere) the nth tab, ⌘9 the last one, as browsers do */\nexport function tabForKey(\n tabs: readonly DraftTab[],\n e: { key: string; metaKey: boolean; ctrlKey: boolean; altKey: boolean; shiftKey: boolean },\n): DraftTab | null {\n if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return null\n if (!/^[1-9]$/.test(e.key)) return null\n const n = Number(e.key)\n return (n === 9 ? tabs[tabs.length - 1] : tabs[n - 1]) ?? null\n}\n\n/** ⌘PageUp / ⌘PageDown (ctrl elsewhere): the previous or next tab, wrapping at the ends */\nexport function tabStepForKey(\n tabs: readonly DraftTab[],\n active: DraftTab | null,\n e: { key: string; metaKey: boolean; ctrlKey: boolean; altKey: boolean; shiftKey: boolean },\n): DraftTab | null {\n if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return null\n const dir = e.key === 'PageDown' ? 1 : e.key === 'PageUp' ? -1 : 0\n if (dir === 0 || tabs.length < 2) return null\n const ix = active == null ? -1 : tabs.findIndex((x) => same(x, active))\n if (ix < 0) return (dir > 0 ? tabs[0] : tabs[tabs.length - 1]) ?? null\n return tabs[(ix + dir + tabs.length) % tabs.length] ?? null\n}\n\n/** ⌘W (ctrl elsewhere): the open tab, while another one is left. On the last tab it is null, so\n * the key goes through and the desktop shell closes its window */\nexport function tabToCloseForKey(\n tabs: readonly DraftTab[],\n active: DraftTab | null,\n e: { key: string; metaKey: boolean; ctrlKey: boolean; altKey: boolean; shiftKey: boolean },\n): DraftTab | null {\n if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return null\n if (e.key.toLowerCase() !== 'w' || active == null || tabs.length < 2) return null\n return tabs.find((x) => same(x, active)) ?? null\n}\n\n/** a stored list, shape-checked, keeping only drafts that still exist */\nexport function readTabs(raw: unknown, modules: readonly { module: string; drafts: readonly string[] }[]): DraftTab[] {\n if (!Array.isArray(raw)) return []\n const out: DraftTab[] = []\n for (const x of raw as unknown[]) {\n if (x == null || typeof x !== 'object') continue\n const o = x as { module?: unknown; draft?: unknown }\n if (typeof o.module !== 'string' || typeof o.draft !== 'string') continue\n const t = { module: o.module, draft: o.draft }\n if (!modules.some((m) => m.module === t.module && m.drafts.includes(t.draft))) continue\n if (!out.some((y) => same(y, t))) out.push(t)\n }\n return out\n}\n","// `comfy-ts serve` request handling, transport-free: run-serve owns node:http,\n// tests call handle() directly with an injected starter. Full contract:\n// agent/architecture.md item 12.\nimport {\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n realpathSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { createHash } from 'node:crypto'\nimport { nanoid } from 'nanoid'\nimport { basename, dirname, extname, isAbsolute, join, resolve } from 'pathe'\nimport { isHttpUrl, ThumbStore, thumbUrl } from 'src/cli/serve/thumbs.ts'\nimport { applyVarPayload } from 'src/cli/serve/applyVarPayload.ts'\nimport { describeVar, type VarDescriptor } from 'src/cli/serve/describeVar.ts'\nimport { deletePromptEnhancer, listPromptEnhancers, writePromptEnhancer } from 'src/promptEnhancers.ts'\nimport { deleteLlmConfig, listLlmConfigs, writeLlmConfig } from 'src/cli/serve/llmConfigs.ts'\nimport { normalizeLlmConfig } from 'src/cli/serve/llmConfigShape.ts'\nimport { ENHANCE_KEY, isDraftMetaKey } from 'src/cli/draftMeta.ts'\nimport { managerOnlyLoraOptions } from 'src/cli/serve/managerOnlyLoras.ts'\nimport { resolveTagSource, TagSources } from 'src/cli/serve/tagSource.ts'\nimport { FAVICON_DATA_URI } from 'src/cli/serve/favicon.ts'\nimport { type TagNode, workflowTags } from 'src/cli/serve/workflowTags.ts'\nimport { workspaceLabels } from 'src/cli/serve/workspaceLabels.ts'\nimport { driftChanged, summarizeDrift } from 'src/host/schemaDrift.ts'\nimport { validSavePrefix, validStoreName } from 'src/utils/safeName.ts'\nimport {\n readServeSettings,\n validMemoryBudgetMb,\n writeServeSettings,\n type ServeSettings,\n} from 'src/cli/serve/serveSettings.ts'\nimport { describeRunError } from 'src/cli/serve/runError.ts'\nimport { ResultHistory, type KeptBlob, type RunRecord } from 'src/cli/serve/resultHistory.ts'\nimport { readTabs, SERVE_TABS_FILE, type DraftTab } from 'src/cli/serve/web/state/draftTabs.ts'\nimport { assembleLogChunks } from 'src/cli/tui/state/LogsSt.ts'\nimport { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'\nimport {\n buildLoraMirror,\n getLoraAddedAt,\n getLoraTriggers,\n type LoraTriggers,\n recordCivitaiMiss,\n getLoraDisplayName,\n getLoraInfo,\n lorasMissingFromMirror,\n getLoraPreviewUrl,\n getLoraTriggerWords,\n refreshLoraInfoCacheIfChanged,\n reloadLoraInfoCache,\n writeLoraMirror,\n} from 'src/host/loraInfoCache.ts'\nimport {\n fetchLoraCivitai,\n fetchLoraDescription,\n fetchLoraExampleImages,\n fetchLoraList,\n fetchLoraPreviewBytes,\n lmBaseModel,\n lmCivitai,\n lmFilePath,\n lmFileSize,\n lmSha256,\n lmFolder,\n lmNotes,\n lmTags,\n loraKey,\n loraPreviewMapFrom,\n} from 'src/host/loraManagerApi.ts'\nimport { getLoraKeyword } from 'src/vars/loraKeywords.ts'\nimport type { ComfyHost } from 'src/host/ComfyHost.ts'\nimport { DEFAULT_MEDIA_EXTENSIONS, MEDIA_KINDS, type MediaKind } from 'src/runner/mediaKinds.ts'\nimport { MODEL_3D_MIMES } from 'src/runner/outputs3d.ts'\nimport type {\n ChoiceOptionLook,\n ChoiceVar,\n LorasVar,\n MediaVar,\n OptionalChoiceVar,\n PromptVar,\n SeedVar,\n} from 'src/vars/ComfyVars.ts'\nimport type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'\nimport { bang } from 'src/utils/bang.ts'\nimport { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'\n\nexport type ServeModule = { key: string; file: string; dw: DefinedWorkflow }\n\n/** structural face of ComfyExecution — tests inject a fake starter.\n * absPath is null for in-memory images (a ws-saver run with saving off) */\nexport type ServeExecution = {\n done: Promise<unknown>\n status: string\n /** buffer is the ONLY copy for an in-memory image (saving off); reading it on a\n * SAVED image would hit the disk, so it is only touched when absPath is null */\n images: { absPath: string | null; filename: string; buffer?: Uint8Array; tags?: string[] }[]\n /** STRING outputs (PreviewAny, i.e. every llm graph). A text-only workflow has no images at\n * all, so without these its run reply is empty and the panel shows nothing */\n texts?: { nodeId: string; nodeKey: string | null; text: string }[]\n /** audio files (SaveAudio*, PreviewAudio). absPath null = saving off, bytes the only copy */\n audios?: { absPath: string | null; filename: string; mime: string; bytes: Uint8Array }[]\n /** video files (SaveVideo, SaveWEBM, VHS_VideoCombine), same shape as audios */\n videos?: { absPath: string | null; filename: string; mime: string; bytes: Uint8Array }[]\n /** 3D files (SaveGLB, SaveGaussianSplat, SavePointCloud), the same shape plus `format` */\n models3d?: { absPath: string | null; filename: string; mime: string; format: string; bytes: Uint8Array }[]\n data: { id: string; error?: unknown }\n /** live global progress (ComfyExecution has it; fakes may omit) — the /run/<module> poll reads it */\n progressGlobal?: { percent: number }\n /** the executing node and ITS counter, in its own unit (sampler steps, generated tokens).\n * the only live signal a text node has: ComfyUI sends no partial text */\n progress?: {\n nodeName: string | null\n nodeProgress: { value: number; max: number } | null\n /** a node's live display text while it runs — a streaming generator's partial answer */\n progressText?: string | null\n }\n}\n\nexport type ServeStarter = (\n mod: ServeModule,\n opts: {\n saveToDisk: boolean\n savePrefix: string\n host?: ComfyHost\n /** the run's live preview frames, feeding the /run/<module>/preview poll */\n onPreview?: (p: { bytes: Uint8Array; mime: string }) => void\n },\n) => Promise<ServeExecution>\n\nexport type ServeRequest = { method: string; url: string; accept?: string; body?: string }\nexport type ServeReply = {\n status: number\n contentType: string\n body: string | Uint8Array\n /** extra response headers, lowercase keys — the transport writes them verbatim */\n headers?: Record<string, string>\n}\n\n/** what serve will read off the disk and upload, per medium. Wider than the picker defaults:\n * ComfyUI's LoadImage takes bmp and tiff too, and a var declaring one of those must not be refused */\nconst SERVE_MEDIA_FLOOR: Record<MediaKind, Set<string>> = {\n image: new Set([...DEFAULT_MEDIA_EXTENSIONS.image, 'bmp', 'tif', 'tiff', 'avif']),\n audio: new Set([...DEFAULT_MEDIA_EXTENSIONS.audio, 'aac']),\n video: new Set([...DEFAULT_MEDIA_EXTENSIONS.video, 'avi']),\n}\n\n/** the first bytes say what a file IS; the name only says what it claims. Cheap, and it stops\n * a .png that holds a key or a script from being read and uploaded to the host.\n * HONEST LIMIT: this is checked before the run, and the file is read again when the graph\n * builds, so a local writer who can swap the path in between still wins. Closing that needs\n * the upload to hold an fd, which is a bigger change than this gate. */\nfunction looksLikeMedia(kind: MediaKind, path: string): boolean {\n let fd: number | null = null\n try {\n fd = openSync(path, 'r')\n const head = new Uint8Array(16)\n const n = readSync(fd, head, 0, 16, 0)\n return isMediaMagic(kind, head.subarray(0, n))\n } catch {\n return false\n } finally {\n if (fd != null) closeSync(fd)\n }\n}\n\n/** what `POST /generate` will read off this machine and upload to a ComfyUI host. A var's own\n * `extensions` is documented as a PICKER filter that never affects the value, so it cannot be\n * the gate: a workflow author narrowing (or emptying) it for listing reasons must not be able\n * to widen what an unauthenticated request can make the server read. The var may narrow this\n * floor, never leave it. */\nfunction serveAcceptsMediaExt(kind: MediaKind, declared: readonly string[], ext: string): boolean {\n const floor = SERVE_MEDIA_FLOOR[kind]\n if (ext === '') return false\n if (!floor.has(ext)) return false\n // a declared list NARROWS the floor by its intersection. When that intersection is empty\n // the declaration says nothing this bridge can honour (a picker filter for a format serve\n // does not read), so the floor stands: narrowing to NOTHING would refuse every image,\n // including the ones the var was declared for\n const narrowed = declared.map((e) => e.toLowerCase().replace(/^\\./, '')).filter((e) => floor.has(e))\n return narrowed.length === 0 || narrowed.includes(ext)\n}\n\n/** an image var pointing at a url downloads it: capped, because the inbound BODY cap does not\n * apply to what serve fetches on your behalf, and one url at a big file would OOM the process */\nclass DownloadRefused extends Error {\n constructor(url: string) {\n super(`could not fetch ${url}`)\n this.name = 'DownloadRefused'\n }\n}\n\nconst INPUT_DOWNLOAD_CAP = 50_000_000\nconst INPUT_DOWNLOAD_TIMEOUT_MS = 60_000\n/** the danbooru list is ~3.5 MB; ten times that is still a tag list, beyond is a wrong url */\nconst TAG_LIST_CAP = 40_000_000\nconst TAG_LIST_TIMEOUT_MS = 120_000\nconst MB = 1024 * 1024\n\n/** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the\n * whole body first, so a chunked reply with no content-length could exhaust the process before\n * anything checked its size, the cap then reported a number nobody survived to read. */\nexport async function readCapped(res: Response, cap: number, what: string): Promise<Uint8Array> {\n const body = res.body\n if (body == null) return new Uint8Array(0)\n const reader = body.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n try {\n for (;;) {\n const step = await reader.read()\n if (step.done) break\n total += step.value.length\n if (total > cap) {\n await reader.cancel()\n throw new Error(`download too large (over ${cap} bytes): ${what}`)\n }\n chunks.push(step.value)\n }\n } finally {\n reader.releaseLock()\n }\n const out = new Uint8Array(total)\n let at = 0\n for (const c of chunks) {\n out.set(c, at)\n at += c.length\n }\n return out\n}\n\n/** the panel is REBUILT per serve process, so a cached copy is always the wrong one. With no\n * cache header at all a browser applies heuristic freshness and reuses app.js across reloads,\n * which makes every fix look like it never landed */\nconst NO_STORE = { 'cache-control': 'no-store, must-revalidate' }\n\n/** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex.\n * serve OPTS INTO local saving (library default is memory-only, architecture.md\n * item 14): the /outputs/ routes serve files, grouped per module */\nconst realStarter: ServeStarter = async (mod, opts) => {\n // the override substitutes the host the graph is BUILT against too (DefinedWorkflow.build's\n // own rule): a node missing there must surface as a workflow problem, not a silent run\n const host = opts.host ?? mod.dw.host\n await host.connect()\n const wf = await mod.dw.build({ advance: true, host })\n // saving is a SETTING now (GET/PUT /settings): off keeps outputs in memory and the\n // reply points at /images/<promptId>/<ix> instead of a file url\n return await wf.start({ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false, onPreview: opts.onPreview })\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.webp': 'image/webp',\n '.gif': 'image/gif',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.m4v': 'video/mp4',\n '.mov': 'video/quicktime',\n '.mkv': 'video/x-matroska',\n '.avi': 'video/x-msvideo',\n '.aac': 'audio/aac',\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 '.json': 'application/json',\n '.txt': 'text/plain',\n ...Object.fromEntries(Object.entries(MODEL_3D_MIMES).map(([ext, mime]) => [`.${ext}`, mime])),\n}\n\n/** magic-byte sniff for the preview proxy — fetchLoraPreviewBytes already guarantees an image */\nfunction sniffImageContentType(bytes: Uint8Array): string {\n if (bytes[0] === 0x89 && bytes[1] === 0x50) return 'image/png'\n if (bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg'\n if (bytes[0] === 0x47 && bytes[1] === 0x49) return 'image/gif'\n if (bytes[0] === 0x52 && bytes[1] === 0x49) return 'image/webp' // RIFF container\n return 'application/octet-stream'\n}\n\n/** the FULL signature, not the first two bytes: `RI` alone matched a wav renamed .webp, and a\n * two-byte file matched png. bmp/tiff/avif are here because the floor accepts them */\nexport function isImageMagic(b: Uint8Array): boolean {\n const at = (i: number, ...want: number[]): boolean => want.every((w, k) => b[i + k] === w)\n if (at(0, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return true // png\n if (at(0, 0xff, 0xd8, 0xff)) return true // jpeg\n if (at(0, 0x47, 0x49, 0x46, 0x38)) return true // gif87a/89a\n if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50)) return true // riff....webp\n if (at(0, 0x42, 0x4d)) return true // bmp\n if (at(0, 0x49, 0x49, 0x2a, 0x00) || at(0, 0x4d, 0x4d, 0x00, 0x2a)) return true // tiff le/be\n if (at(4, 0x66, 0x74, 0x79, 0x70)) return true // isobmff box: avif/heif\n return false\n}\n\n/** the same full-signature sniff for every medium: a var of one kind never reads a file of\n * another. mp4, mov and m4a share the isobmff `ftyp` box, the extension floor tells them apart */\nexport function isMediaMagic(kind: MediaKind, b: Uint8Array): boolean {\n const at = (i: number, ...want: number[]): boolean => want.every((w, k) => b[i + k] === w)\n const isobmff = at(4, 0x66, 0x74, 0x79, 0x70)\n if (kind === 'image') return isImageMagic(b)\n if (kind === 'audio') {\n if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x41, 0x56, 0x45)) return true // riff....wave\n if (at(0, 0x66, 0x4c, 0x61, 0x43)) return true // flac\n if (at(0, 0x4f, 0x67, 0x67, 0x53)) return true // ogg (vorbis, opus)\n if (at(0, 0x49, 0x44, 0x33)) return true // mp3 with an id3 tag\n // an mpeg frame sync: 11 set bits, a version and a layer that are not reserved, then a\n // bitrate and a sample rate that are not the invalid 1111 and 11. FF FE is refused whole:\n // it is the utf-16le BOM, and a layer I header is never what a real file starts with\n const b0 = b[0]\n const b1 = b[1]\n const b2 = b[2]\n if (\n b0 === 0xff &&\n b1 != null &&\n b1 !== 0xfe &&\n b2 != null &&\n (b1 & 0xe0) === 0xe0 &&\n (b1 & 0x18) !== 0x08 &&\n (b1 & 0x06) !== 0 &&\n b2 >> 4 !== 0xf &&\n ((b2 >> 2) & 3) !== 3\n )\n return true\n if (b0 === 0xff && b1 != null && (b1 & 0xf6) === 0xf0) return true // aac adts\n return isobmff // m4a\n }\n if (at(0, 0x1a, 0x45, 0xdf, 0xa3)) return true // ebml: webm, mkv\n if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x41, 0x56, 0x49, 0x20)) return true // riff....avi\n return isobmff // mp4, mov, m4v\n}\n\nfunction isMediaKind(kind: string): kind is MediaKind {\n return (MEDIA_KINDS as readonly string[]).includes(kind)\n}\n\nfunction json(status: number, payload: unknown): ServeReply {\n return { status, contentType: 'application/json', body: JSON.stringify(payload, null, 2) }\n}\n\nconst USAGE = [\n 'GET / in a browser — web control panel (every var as a form control)',\n 'GET /drafts — every served workflow, its drafts and var descriptors',\n 'GET /drafts/<module>/<draft> — one draft with its stored values',\n 'POST /generate/<module>/<draft> with { ...vars } — run, blocking',\n 'POST /generate/<draft> — unqualified, when unambiguous',\n 'POST /preview/<module> with { ...draft values } — the workflow previews for those values, nothing is run',\n 'PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft',\n 'DELETE /drafts/<module>/<draft> — delete that draft file',\n 'GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes',\n 'POST /upload with {\"name\",\"dataBase64\"} — store a browser file for an image, audio or video var',\n 'GET /images|audio|video|model3d/<promptId>/<ix> — an output kept in memory (saving off)',\n 'GET /tags/<module>/<var>?q=<text>&limit=<n> — tag completion from the list a prompt var declares (`tags`)',\n 'GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)',\n 'GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)',\n 'POST /hosts/<hostId>/lora-civitai/<lora> — fetch its civitai metadata (trigger words) through the lora manager, then re-sync the mirror',\n 'GET /lora-preview/<hostId>/<lora> — preview image bytes',\n 'GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)',\n 'GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)',\n 'PUT /prompt-enhancers/<name> with {\"text\"} — write one · DELETE /prompt-enhancers/<name> — remove it',\n 'GET /llm-configs — the enhancer LLM configs (.comfy-ts/llm-configs/*.json)',\n 'PUT /llm-configs/<name> with {provider, baseUrl, model, effort, thinkingOnly} · DELETE /llm-configs/<name>',\n 'GET /settings — { saveToDisk, memoryBudgetMb } · PUT /settings with {\"saveToDisk\"} — write outputs to disk, or keep them in memory; {\"memoryBudgetMb\"} caps what memory keeps',\n 'GET /hosts — every host this process knows · PUT /hosts/<module> with {\"host\"} — run that workflow elsewhere',\n 'POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host',\n 'GET /hosts/<hostId>/ping — is that host answering right now (restart watch)',\n 'GET /hosts/<hostId>/logs — the last lines of that host console',\n 'GET /images/<promptId>/<ix> — an in-memory output (saving off), while the process lives',\n 'GET /audio/<promptId>/<ix> — the same for an in-memory audio output',\n 'GET /results — the last runs this process kept, for a reload · DELETE /results[/<promptId>] — forget them, freeing their memory',\n 'GET /outputs/<path> — generated files',\n]\n\n/** content hash of the bundle, so the script URL CHANGES whenever the code does. no-store\n * alone does not help a browser that already has app.js cached under a plain url, and a panel\n * running stale javascript is indistinguishable from a broken fix */\nfunction buildId(js: string): string {\n let h = 5381\n for (let i = 0; i < js.length; i++) h = ((h << 5) + h + js.charCodeAt(i)) | 0\n return (h >>> 0).toString(36)\n}\n\n/** the html shell; the app itself is ONE bundle at /web/app.js */\nconst WEB_SHELL = `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>comfy-ts serve</title>\n<link rel=\"icon\" type=\"image/png\" href=\"${FAVICON_DATA_URI}\">\n<style>html{background:#101217;color:#e8eaf0}</style>\n</head>\n<body>\n<div id=\"root\"></div>\n<script type=\"module\" src=\"/web/app.js?v=__BUILD__\"></script>\n</body>\n</html>\n`\n\nexport class ServeApp {\n private starter: ServeStarter\n /** last SERVED seed per `module/draft/var` — '+'/'-' modes continue from it.\n * draftBase remembers which DRAFT value the continuation grew from, served every seed\n * the chain handed out: a draft holding one of them is the panel's write-back (it lags a\n * queued run), anything else is a typed value, which wins and restarts the chain there */\n private seedState = new Map<string, { last: number; draftBase: number; served: number[] }>()\n /** per-module promise chain: vars are shared mutable state, apply→send is exclusive */\n private chains = new Map<string, Promise<unknown>>()\n /** saving + host overrides are live settings (the web ui flips them). LAZY: a ServeApp can\n * be constructed before a comfyts instance is registered, and reading the file then would\n * throw at construction time */\n private settingsCache: ServeSettings | null = null\n private get settings(): ServeSettings {\n this.settingsCache ??= readServeSettings()\n return this.settingsCache\n }\n private set settings(next: ServeSettings) {\n this.settingsCache = next\n }\n /** the last runs, for a reload, and the bytes of their unsaved outputs: the ONLY copy.\n * LAZY for the same reason as settings: its budget is a setting */\n private keptCache: ResultHistory | null = null\n private get kept(): ResultHistory {\n this.keptCache ??= new ResultHistory(this.settings.memoryBudgetMb * MB)\n return this.keptCache\n }\n\n constructor(\n public modules: ServeModule[],\n private opts: {\n starter?: ServeStarter\n outputRoot?: string\n loadErrors?: Record<string, string>\n /** where `.comfy-ts/` lives and the folder serve scanned: the menu's read-only cards.\n * absent = the index leaves both out */\n workspace?: string\n root?: string\n /** web ui bundle provider (run-serve wires loadOrBuildWebJs), called on every page load\n * and owning its own cache; absent = api only */\n webJs?: () => Promise<string | null>\n } = {},\n ) {\n this.starter = opts.starter ?? realStarter\n }\n\n private get outputRoot(): string {\n return this.opts.outputRoot ?? comfyts.outputPath\n }\n\n // #region routing ----------------------------------------------------------\n async handle(req: ServeRequest): Promise<ServeReply> {\n try {\n const path = (req.url.split('?')[0] ?? '/').split('#')[0] ?? '/'\n let segs: string[]\n try {\n segs = path\n .split('/')\n .filter((s) => s !== '')\n .map(decodeURIComponent)\n } catch {\n return json(400, { error: `bad url encoding: ${path}` })\n }\n if (req.method === 'GET') {\n // a browser lands on the control panel; every other client keeps the json index.\n // the bundle resolves BEFORE the shell ships: a shell whose /web/app.js 404s is\n // a blank dark page, the json index is a usable answer\n if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes('text/html') === true) {\n const js = await this.opts.webJs()\n if (js != null)\n return {\n status: 200,\n contentType: 'text/html; charset=utf-8',\n body: WEB_SHELL.replace('__BUILD__', buildId(js)),\n headers: NO_STORE,\n }\n }\n if (segs.length === 0 || (segs[0] === 'drafts' && segs.length === 1)) return await this.replyIndex()\n if (segs[0] === 'web' && segs[1] === 'app.js' && segs.length === 2) return await this.replyWebJs()\n if (segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return this.replyDraft(segs[1], segs[2])\n if (segs[0] === 'run' && segs.length === 2 && segs[1] != null) return this.replyRunStatus(segs[1])\n if (segs[0] === 'run' && segs.length === 3 && segs[1] != null && segs[2] === 'preview')\n return this.replyRunPreview(segs[1])\n if (segs[0] === 'lora-info' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return this.replyLoraInfo(segs[1], segs[2])\n if (segs[0] === 'lora-preview' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replyLoraPreview(segs[1], segs[2])\n if (segs[0] === 'lora-about' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replyLoraAbout(segs[1], segs[2])\n if (segs[0] === 'prompt-enhancers' && segs.length === 1) return this.replyPromptEnhancers()\n if (segs[0] === 'llm-configs' && segs.length === 1) return this.replyLlmConfigs()\n if (segs[0] === 'tags' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replyTags(segs[1], segs[2], req.url)\n if (segs[0] === 'settings' && segs.length === 1) return this.replySettings()\n if (segs[0] === 'thumb' && segs.length === 1) return await this.replyThumb(req.url)\n if (segs[0] === 'tabs' && segs.length === 1) return this.replyTabs()\n if (segs[0] === 'hosts' && segs.length === 1) return this.replyHosts()\n if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'logs')\n return await this.replyHostLogs(segs[1])\n if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'ping')\n return await this.replyHostPing(segs[1])\n if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'drift')\n return await this.replyHostDrift(segs[1], req.url.includes('full=1'))\n if (segs[0] === 'images' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return this.replyMemoryImage(`${segs[1]}/${segs[2]}`)\n if (segs[0] === 'audio' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return this.replyMemoryImage(`audio/${segs[1]}/${segs[2]}`)\n if (segs[0] === 'video' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return this.replyMemoryImage(`video/${segs[1]}/${segs[2]}`)\n if (segs[0] === 'model3d' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return this.replyMemoryImage(`model3d/${segs[1]}/${segs[2]}`)\n if (segs[0] === 'results' && segs.length === 1)\n return json(200, { runs: this.kept.list(), memory: this.kept.usage() })\n if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))\n return json(404, { error: `no route: GET ${path}`, usage: USAGE })\n }\n if (req.method === 'POST' && segs[0] === 'generate') {\n const target = this.resolveDraft(segs.slice(1))\n if ('error' in target) return json(target.status, { error: target.error })\n return await this.generate(target.mod, target.draft, req)\n }\n if (req.method === 'POST' && segs[0] === 'preview' && segs.length === 2 && segs[1] != null)\n return await this.replyPreview(segs[1], req)\n if (req.method === 'POST' && segs[0] === 'upload' && segs.length === 1) return this.replyUpload(req)\n if (req.method === 'PUT' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replySaveDraft(segs[1], segs[2], req)\n if (req.method === 'DELETE' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replyDeleteDraft(segs[1], segs[2])\n if (req.method === 'PUT' && segs[0] === 'settings' && segs.length === 1) return this.replySaveSettings(req)\n if (req.method === 'DELETE' && segs[0] === 'results' && segs.length <= 2) {\n if (segs[1] == null) this.kept.clear()\n else this.kept.remove(segs[1])\n return json(200, { memory: this.kept.usage() })\n }\n if (req.method === 'PUT' && segs[0] === 'tabs' && segs.length === 1) return this.replySaveTabs(req)\n if (req.method === 'PUT' && segs[0] === 'hosts' && segs.length === 2 && segs[1] != null)\n return this.replySetHost(segs[1], req)\n if (req.method === 'POST' && segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] != null)\n return await this.replyHostAction(segs[1], segs[2])\n if (\n req.method === 'POST' &&\n segs[0] === 'hosts' &&\n segs.length === 4 &&\n segs[1] != null &&\n segs[2] === 'lora-civitai' &&\n segs[3] != null\n )\n return await this.replyLoraCivitaiFetch(segs[1], segs[3])\n if (req.method === 'PUT' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)\n return this.replySavePromptEnhancer(segs[1], req)\n if (req.method === 'DELETE' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)\n return this.replyDeletePromptEnhancer(segs[1])\n if (req.method === 'PUT' && segs[0] === 'llm-configs' && segs.length === 2 && segs[1] != null)\n return this.replySaveLlmConfig(segs[1], req)\n if (req.method === 'DELETE' && segs[0] === 'llm-configs' && segs.length === 2 && segs[1] != null)\n return this.replyDeleteLlmConfig(segs[1])\n return json(404, { error: `no route: ${req.method} ${path}`, usage: USAGE })\n } catch (e) {\n console.error('[serve] request crashed:', e)\n return json(500, { error: extractErrorMessage(e) })\n }\n }\n\n moduleByKey(key: string): ServeModule | null {\n return this.modules.find((m) => m.key === key) ?? null\n }\n\n /** 'default' always exists (spec defaults); files under .comfy-ts/drafts/<module>/ add the rest */\n draftsFor(mod: ServeModule): string[] {\n const onDisk = listDraftsForFile(mod.file)\n return ['default', ...onDisk.filter((n) => n !== 'default')]\n }\n\n /** THE draft-name gate, shared by every route that turns a url segment into a path\n * (safeName.ts owns the rule, the prompt-enhancer routes call the same function) */\n private validDraftName(raw: string): string | null {\n return validStoreName(raw)\n }\n\n /** absolute path of a draft file, or null when the name is not one we accept */\n private draftPath(mod: ServeModule, draft: string): string | null {\n const name = this.validDraftName(draft)\n return name == null ? null : join(draftsDirForFile(mod.file), `${name}.json`)\n }\n\n private draftExists(mod: ServeModule, draft: string): boolean {\n const path = this.draftPath(mod, draft)\n if (path == null) return false\n return draft === 'default' || existsSync(path)\n }\n\n private resolveDraft(segs: string[]): { mod: ServeModule; draft: string } | { error: string; status: number } {\n if (segs.length === 2 && segs[0] != null && segs[1] != null) {\n const mod = this.moduleByKey(segs[0])\n if (mod == null)\n return {\n status: 404,\n error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(', ')}`,\n }\n if (!this.draftExists(mod, segs[1]))\n return {\n status: 404,\n error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(', ')}`,\n }\n return { mod, draft: segs[1] }\n }\n if (segs.length === 1 && segs[0] != null) {\n const draft = segs[0]\n if (this.modules.length === 1 && this.modules[0] != null) {\n const mod = this.modules[0]\n if (!this.draftExists(mod, draft))\n return {\n status: 404,\n error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(', ')}`,\n }\n return { mod, draft }\n }\n const hits = this.modules.filter((m) => this.draftExists(m, draft))\n if (hits.length === 1 && hits[0] != null) return { mod: hits[0], draft }\n if (hits.length === 0) return { status: 404, error: `no module has a draft '${draft}'` }\n return {\n status: 400,\n error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(' or ')}`,\n }\n }\n return { status: 400, error: 'use POST /generate/<module>/<draft> or /generate/<draft>' }\n }\n\n // #region introspection ----------------------------------------------------\n /** the pictures of a descriptor made concrete for the page: a local thumb or preset becomes a\n * /thumb url the store allows, a local preset not on this machine is flagged missing, a url\n * stays as it is. Relative paths are relative to the workflow file */\n private decorateLooks(desc: VarDescriptor, mod: ServeModule): void {\n const dir = dirname(mod.file)\n this.thumbs.allowRoot(dir)\n this.thumbs.allowRoot(this.outputRoot)\n const local = (p: string): string => (isAbsolute(p) ? p : resolve(dir, p))\n const options = desc.ui?.options\n if (desc.ui != null && options != null) {\n const looks: Record<string, ChoiceOptionLook> = {}\n for (const [value, look] of Object.entries(options)) {\n if (look.thumb == null || isHttpUrl(look.thumb)) {\n looks[value] = look\n continue\n }\n const abs = local(look.thumb)\n this.thumbs.allow(abs)\n looks[value] = { ...look, thumb: thumbUrl(abs, 128) }\n }\n // a copy: the var's own ui object must keep the authored paths\n desc.ui = { ...desc.ui, options: looks }\n }\n if (desc.mediaPresets != null)\n desc.mediaPresets = desc.mediaPresets.map((preset) => {\n if (isHttpUrl(preset.value)) {\n // once a run fetched it, the tile is a small local thumb, not the whole remote file\n const cached = this.urlInputPath(preset.value, basename(new URL(preset.value).pathname))\n return { ...preset, thumb: existsSync(cached) ? thumbUrl(cached, 160) : preset.value }\n }\n const abs = local(preset.value)\n this.thumbs.allow(abs)\n return existsSync(abs)\n ? { ...preset, value: abs, thumb: thumbUrl(abs, 160) }\n : { ...preset, value: abs, missing: true }\n })\n if (MEDIA_KINDS.includes(desc.kind as MediaKind) && typeof desc.default === 'string' && desc.default !== '')\n if (!isHttpUrl(desc.default)) this.thumbs.allow(local(desc.default))\n }\n\n private async replyThumb(url: string): Promise<ServeReply> {\n const q = new URLSearchParams(url.split('?')[1] ?? '')\n const src = q.get('src')\n if (src == null || src === '') return json(400, { error: 'thumb needs ?src=<local path>' })\n const out = await this.thumbs.render(src, Number(q.get('w') ?? 160) || 160)\n if (out === 'forbidden')\n return json(403, { error: 'not a picture a served workflow declared, nor under its folder or the outputs' })\n if (out === 'missing') return json(404, { error: 'not on this machine' })\n return { status: 200, contentType: 'image/webp', body: out, headers: { 'cache-control': 'max-age=300' } }\n }\n\n private describeModule(mod: ServeModule): Record<string, unknown> {\n refreshLoraInfoCacheIfChanged()\n const hostId = mod.dw.host.data.id\n const vars: Record<string, VarDescriptor> = {}\n for (const [name, varDef] of mod.dw.entries()) {\n const desc = describeVar(varDef)\n this.decorateLooks(desc, mod)\n // the raw enum values stay the payload keys; the mirror's names are for humans\n if (desc.kind === 'loras' && desc.options != null) {\n const labels: Record<string, string> = {}\n for (const option of desc.options) {\n const label = getLoraDisplayName(option, hostId)\n if (label !== option) labels[option] = label\n }\n if (Object.keys(labels).length > 0) desc.optionLabels = labels\n // the UNION: a lora the manager mirror knows but ComfyUI's enum does not. It is on\n // disk, so it usually runs, the picker offers it, flagged, rather than hiding it\n // by normalized key, never raw: an enum value keeps its case, extension and\n // windows separators. the var's own regex narrows the mirror too\n const extras = managerOnlyLoraOptions({\n hostId,\n options: desc.options,\n filter: (varDef as LorasVar<string>).optionsFilter,\n })\n if (extras.length > 0) {\n desc.managerOnlyOptions = extras\n desc.options = [...desc.options, ...extras]\n for (const extra of extras) {\n const label = getLoraDisplayName(extra, hostId)\n if (label !== extra) (desc.optionLabels ??= {})[extra] = label\n }\n }\n // what a prompt with loraKeywordsFrom will PREPEND, per option: the panel shows\n // the injection instead of leaving you to discover it in the generated image\n const keywords: Record<string, string> = {}\n for (const option of desc.options) {\n const kw = getLoraKeyword(option, hostId)\n if (kw !== '') keywords[option] = kw\n }\n if (Object.keys(keywords).length > 0) desc.optionKeywords = keywords\n const addedAt: Record<string, number> = {}\n for (const option of desc.options) {\n const t = getLoraAddedAt(option, hostId)\n if (t != null) addedAt[option] = t\n }\n if (Object.keys(addedAt).length > 0) desc.optionAddedAt = addedAt\n const triggers: Record<string, LoraTriggers> = {}\n for (const option of desc.options) {\n const t = getLoraTriggers(option, hostId)\n if (t != null) triggers[option] = t\n }\n if (Object.keys(triggers).length > 0) desc.optionTriggers = triggers\n }\n vars[name] = desc\n }\n // a prompt knows its lora SOURCE by identity only; naming it needs both vars, which is\n // exactly what this loop has. Without it the panel cannot preview the keyword prefix\n for (const [name, varDef] of mod.dw.entries()) {\n if (varDef.kind !== 'prompt') continue\n const source = (varDef as PromptVar).promptOpts.loraKeywordsFrom\n if (source == null) continue\n // identity across two unrelated faces (AnyVar vs ActiveLoraSource): compare as unknown,\n // the LorasVar instance IS both\n const sourceName = mod.dw.entries().find(([, other]) => (other as unknown) === (source as unknown))?.[0]\n const desc = vars[name]\n if (sourceName != null && desc != null) desc.keywordsFrom = sourceName\n }\n return {\n module: mod.key,\n file: mod.file,\n host: mod.dw.host.data.id,\n drafts: this.draftsFor(mod),\n routes: this.draftsFor(mod).map(\n (d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`,\n ),\n vars,\n // the names of the workflow's live previews: the panel asks POST /preview/<module>\n previews: Object.keys(mod.dw.spec.previews ?? {}),\n tags: this.tagsByModule.get(mod.key) ?? mod.dw.spec.tags ?? [],\n }\n }\n\n /** per module, read once from a dry build: the omnibox searches and shows them */\n private tagsByModule = new Map<string, string[]>()\n /** the local images the page may preview (GET /thumb), filled by describeModule */\n private thumbs = new ThumbStore()\n\n private async tagsFor(mod: ServeModule): Promise<string[]> {\n const known = this.tagsByModule.get(mod.key)\n if (known != null) return known\n const extra = mod.dw.spec.tags ?? []\n const varKinds = mod.dw.entries().map(([, varDef]) => varDef.kind)\n let tags: string[]\n try {\n const wf = await mod.dw.build({ dry: true })\n const nodes: TagNode[] = wf.nodes.map((n) => ({\n id: n.uid,\n classType: n.json.class_type,\n outputNode: n.$schema.raw.output_node,\n outputTypes: n.$schema.outputs.map((o) => o.typeName),\n links: Object.values(n.json.inputs).flatMap((v): [string, number][] =>\n Array.isArray(v) && v.length === 2 && typeof v[1] === 'number' ? [[String(v[0]), v[1]]] : [],\n ),\n }))\n tags = workflowTags({ nodes, varKinds, extra })\n } catch (e) {\n console.error(`[serve] 🔴 tags for ${mod.key}: dry build failed, spec tags only: ${extractErrorMessage(e)}`)\n tags = workflowTags({ nodes: [], varKinds, extra })\n }\n this.tagsByModule.set(mod.key, tags)\n return tags\n }\n\n private async replyIndex(): Promise<ServeReply> {\n for (const m of this.modules) await this.tagsFor(m)\n return json(200, {\n server: 'comfy-ts serve',\n usage: USAGE,\n workflows: this.modules.map((m) => this.describeModule(m)),\n ...(this.opts.workspace == null\n ? {}\n : workspaceLabels({\n workspace: this.opts.workspace,\n root: this.opts.root ?? this.opts.workspace,\n home: process.env.HOME ?? '',\n })),\n ...(this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0\n ? { loadErrors: this.opts.loadErrors }\n : {}),\n })\n }\n\n private replyDraft(modKey: string, draft: string): ServeReply {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n if (!this.draftExists(mod, draft))\n return json(404, {\n error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(', ')}`,\n })\n return json(200, { ...this.describeModule(mod), draft, values: this.draftValues(mod, draft) })\n }\n\n /** the workflow's previews for the values the panel holds right now. The vars are SHARED\n * state (a run reads them), so this runs under the module lock: load the values, compute,\n * put the old values back. Nothing is queued, nothing is written */\n private async replyPreview(key: string, req: ServeRequest): Promise<ServeReply> {\n const mod = this.moduleByKey(key)\n if (mod == null) return json(404, { error: `unknown workflow '${key}'` })\n let values: unknown\n try {\n values = JSON.parse(req.body ?? '{}')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (values == null || typeof values !== 'object' || Array.isArray(values))\n return json(400, { error: 'expects { \"<var>\": value, … }' })\n const incoming = values as Record<string, unknown>\n const previews = await this.exclusive(mod.key, () => {\n const saved = mod.dw.entries().map(([k, v]) => [k, v.toJSON()] as const)\n try {\n for (const [k, v] of mod.dw.entries()) if (k in incoming) v.loadJSON(incoming[k])\n return Promise.resolve(mod.dw.computePreviews())\n } finally {\n const byName = new Map(mod.dw.entries())\n for (const [k, json] of saved) byName.get(k)?.loadJSON(json)\n }\n })\n return json(200, { previews })\n }\n\n /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */\n private draftValues(mod: ServeModule, draft: string): Record<string, unknown> {\n const path = this.draftPath(mod, draft)\n if (path != null && existsSync(path)) return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>\n const out: Record<string, unknown> = {}\n for (const [name, varDef] of mod.dw.entries()) out[name] = describeVar(varDef).default\n return out\n }\n\n // #region outputs ----------------------------------------------------------\n private replyOutput(segs: string[]): ServeReply {\n const abs = resolve(this.outputRoot, ...segs)\n // traversal guard: the resolved path must stay under the output root\n if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + '/'))\n return json(400, { error: 'path escapes the outputs root' })\n if (!existsSync(abs) || !statSync(abs).isFile())\n return json(404, { error: `no such output file: /${segs.join('/')}` })\n const contentType = CONTENT_TYPES[extname(abs).toLowerCase()] ?? 'application/octet-stream'\n return { status: 200, contentType, body: new Uint8Array(readFileSync(abs)) }\n }\n\n private async replyWebJs(): Promise<ServeReply> {\n if (this.opts.webJs == null) return json(404, { error: 'web ui not enabled on this server' })\n const js = await this.opts.webJs()\n if (js == null) return json(404, { error: 'web ui bundle unavailable — see the server log' })\n return { status: 200, contentType: 'text/javascript; charset=utf-8', body: js, headers: NO_STORE }\n }\n\n /** browser file → local file a media var can point at (downloadInput family) */\n private replyUpload(req: ServeRequest): ServeReply {\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n const o = (parsed ?? {}) as { name?: unknown; dataBase64?: unknown }\n if (typeof o.name !== 'string' || o.name === '' || typeof o.dataBase64 !== 'string' || o.dataBase64 === '')\n return json(400, { error: 'upload expects {\"name\":\"<filename>\",\"dataBase64\":\"<base64 bytes>\"}' })\n const bytes = Buffer.from(o.dataBase64, 'base64')\n if (bytes.length === 0) return json(400, { error: 'dataBase64 decoded to zero bytes' })\n // the same 100-char cap validStoreName carries: without it a long name reached the fs and\n // came back as a 500 quoting the absolute path\n const safe = (basename(o.name).replace(/[^\\w.-]+/g, '_') || 'upload').slice(0, 100)\n const abs = join(this.outputRoot, 'serve-inputs', `${nanoid(6)}-${safe}`)\n mkdirSync(dirname(abs), { recursive: true })\n writeFileSync(abs, bytes)\n console.log(`[serve] upload → ${abs} (${bytes.length} bytes)`)\n return json(200, { ok: true, path: abs, url: this.outputUrl(abs) })\n }\n\n // #region drafts write (the web ui's autosave + duplicate ride this) --------\n private async replySaveDraft(modKey: string, rawDraft: string, req: ServeRequest): Promise<ServeReply> {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n const draft = this.validDraftName(rawDraft)\n if (draft == null)\n return json(400, { error: `invalid draft name '${rawDraft}' — letters/digits then letters, digits, \". -_\"` })\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))\n return json(400, { error: 'body must be a json object: { \"<var>\": value, … }' })\n const values = parsed as Record<string, unknown>\n const known = new Set(mod.dw.entries().map(([k]) => k))\n // `$enhance` rides beside the values (src/cli/draftMeta.ts): a string map, checked whole\n if (ENHANCE_KEY in values) {\n const raw = values[ENHANCE_KEY]\n const ok =\n raw != null &&\n typeof raw === 'object' &&\n !Array.isArray(raw) &&\n Object.values(raw).every((v) => typeof v === 'string')\n if (!ok) return json(400, { error: `${ENHANCE_KEY} must be { \"<prompt var>\": \"<intent>\" }` })\n }\n const unknown = Object.keys(values).filter((k) => !known.has(k) && !isDraftMetaKey(k))\n if (unknown.length > 0)\n return json(400, { error: `unknown var(s) ${unknown.join(', ')} — vars: ${[...known].join(', ')}` })\n // values are written VERBATIM (toJSON shapes, loadJSON re-validates on read) —\n // under the module mutex, so a save cannot interleave a generate's draft read\n const path = bang(this.draftPath(mod, draft), 'draft name validated just above')\n await this.exclusive(mod.key, () => {\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, JSON.stringify(values, null, 2))\n return Promise.resolve()\n })\n return json(200, { ok: true, module: mod.key, draft, drafts: this.draftsFor(mod) })\n }\n\n /** delete the draft FILE. `default` is deletable like any other: the implicit `default`\n * draft (spec values, no file) survives it, which is exactly the reset. Missing file is\n * still a 200, the caller asked for it to be gone, and it is */\n private async replyDeleteDraft(modKey: string, rawDraft: string): Promise<ServeReply> {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n const path = this.draftPath(mod, rawDraft)\n if (path == null) return json(400, { error: `invalid draft name '${rawDraft}'` })\n await this.exclusive(mod.key, () => {\n if (existsSync(path)) rmSync(path)\n return Promise.resolve()\n })\n console.log(`[serve] draft deleted: ${mod.key}/${rawDraft.trim()}`)\n return json(200, { ok: true, module: mod.key, draft: rawDraft.trim(), drafts: this.draftsFor(mod) })\n }\n\n // #region hosts (run a workflow somewhere else, the TUI's host override) ----\n /** every host this process registered: the modules' own, plus anything they created */\n private knownHosts(): { id: string; url: string; httpUrl: string | null; modules: string[] }[] {\n const byId = new Map<string, { id: string; url: string; httpUrl: string | null; modules: string[] }>()\n for (const [id, host] of comfyts.hosts)\n byId.set(id, {\n id,\n url: host.addressLabel,\n // the browser needs the REAL base to open the host's own pages (lora manager)\n httpUrl: host.noAddress == null ? host.getServerHostHTTP() : null,\n modules: [],\n })\n for (const mod of this.modules) {\n const entry = byId.get(mod.dw.host.data.id)\n if (entry != null) entry.modules.push(mod.key)\n }\n return [...byId.values()].sort((a, b) => a.id.localeCompare(b.id))\n }\n\n /** the host a run goes to: the override if it still exists, else the module's own.\n * A stale override (a host id that is gone) must never silently swallow the run */\n private runHostFor(mod: ServeModule): ComfyHost | null {\n const wanted = this.settings.hostOverride[mod.key]\n if (wanted == null || wanted === mod.dw.host.data.id) return null\n return comfyts.hosts.get(wanted) ?? null\n }\n\n /** the host actions the TUI's host panel has, minus re-codegen: regenerating the sdk\n * rewrites a .d.ts for your EDITOR, while the running modules keep the builder they were\n * imported with, a button that changes nothing in this process would be a lie */\n private async replyHostAction(hostId: string, action: string): Promise<ServeReply> {\n const host = comfyts.hosts.get(hostId)\n if (host == null)\n return json(404, { error: `unknown host '${hostId}' — known: ${[...comfyts.hosts.keys()].join(', ')}` })\n try {\n if (action === 'interrupt') {\n await host.interrupt()\n return json(200, { ok: true, host: hostId, action, note: 'interrupt requested' })\n }\n if (action === 'clear-queue') {\n await host.clearQueue()\n return json(200, { ok: true, host: hostId, action, note: 'pending prompts dropped' })\n }\n if (action === 'refresh-loras') return await this.refreshLoraMirror(hostId, host)\n if (action === 'refresh-schema') {\n await host.fetchAndUpdateSchema()\n // the ONE refresh re-reads the lora manager's list too, BEFORE the rebind reads it:\n // a lora the host just learned gets its name, preview and trigger words in the same\n // pass. A host without the extension, or one that fails the sweep, keeps its old\n // list and the note says so; the schema refetch itself still stands\n const unmirrored = lorasMissingFromMirror(host.schema.getLoras(), (n) => getLoraInfo(n, hostId) != null)\n const synced = await this.refreshLoraMirror(hostId, host)\n const lorasNote =\n synced.status === 200\n ? unmirrored.length > 0\n ? `, lora list re-read (${unmirrored.length} new)`\n : ', lora list re-read'\n : ', the lora manager list could not be re-read'\n const rebound = await this.rebindHostVars(hostId, host)\n const nodes = host.schema.nodes.length\n const loras = host.schema.getLoras().length\n const dropped =\n rebound.stale.length === 0\n ? ''\n : `. ${rebound.stale.length} selection(s) this host no longer lists (a lora is dropped, a model stays picked)`\n return json(200, {\n ok: true,\n host: hostId,\n action,\n stale: rebound.stale,\n note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora or model var(s) changed${dropped}${lorasNote}`,\n })\n }\n if (action === 'restart') {\n // restartComfyUI already treats the mid-reboot disconnect as success, so what\n // reaches here is a host that REFUSED, swallowing it reported a reboot that\n // never happened, which is worse than saying nothing\n await host.manager.restartComfyUI()\n return json(200, { ok: true, host: hostId, action, note: 'reboot requested — it reconnects when back' })\n }\n return json(400, {\n error: `unknown host action '${action}' — interrupt | clear-queue | restart | refresh-loras | refresh-schema`,\n })\n } catch (e) {\n return json(502, { error: `host '${hostId}' refused '${action}': ${extractErrorMessage(e)}` })\n }\n }\n\n /** re-sweep ComfyUI-Lora-Manager and rewrite the mirror — what `comfy-ts loras` does, with\n * its refusals kept: a partial or unreachable sweep NEVER overwrites, because writing it\n * would delete loras from the mirror that are alive on the host */\n /** re-resolve the host-bound lora vars of the modules DEFINED on this host: LorasVar only\n * resolves its RegExp inside bindHost, so nothing else picks up a widened enum.\n *\n * the defining host, not the override: rebinding an overridden module against another box\n * rewrites its options AND its hostId (which picks the metadata mirror) with no way back,\n * since dropping the override cannot un-resolve them.\n *\n * runs under each module's mutex, so it cannot swap the options out from under a generate\n * that already validated its payload against the old list. */\n private async rebindHostVars(hostId: string, host: ComfyHost): Promise<{ widened: number; stale: string[] }> {\n let widened = 0\n const stale: string[] = []\n for (const mod of this.modules) {\n if (mod.dw.host.data.id !== hostId) continue\n await this.exclusive(mod.key, () => {\n for (const [name, varDef] of mod.dw.entries()) {\n if (varDef.kind === 'choice') {\n const choice = varDef as ChoiceVar<string> | OptionalChoiceVar<string>\n if (choice.hostSlot == null) continue\n const before = choice.choices.length\n choice.bindHost(host)\n if (choice.choices.length !== before) widened++\n // a model the box no longer lists stays picked: the run then fails on the host,\n // naming the file, instead of silently running another model\n if (choice.value != null && !choice.choices.includes(choice.value))\n stale.push(`${mod.key}/${name}: ${choice.value}`)\n continue\n }\n if (varDef.kind !== 'loras') continue\n const lorasVar = varDef as LorasVar<string>\n if (lorasVar.optionsFilter == null) continue // a plain array never re-resolves\n const before = lorasVar.options.length\n lorasVar.bindHost(host)\n if (lorasVar.options.length !== before) widened++\n // a SELECTED lora the host no longer lists would still ride into the graph and\n // be refused there: it leaves the record, and the reply says which\n const known = new Set<string>(lorasVar.options)\n const value = lorasVar.value as Record<string, unknown>\n for (const picked of Object.keys(value)) {\n if (known.has(picked)) continue\n stale.push(`${mod.key}/${name}: ${picked}`)\n delete value[picked]\n }\n }\n return Promise.resolve()\n })\n }\n return { widened, stale }\n }\n\n private async refreshLoraMirror(hostId: string, host: ComfyHost): Promise<ServeReply> {\n const sweep = await fetchLoraList(host)\n if (sweep.status === 'absent')\n return json(400, {\n error: `${hostId} has no ComfyUI-Lora-Manager: the extension is not installed there. Mirror left untouched.`,\n })\n if (sweep.status === 'unreachable')\n return json(502, { error: `${hostId} unreachable — ${sweep.reason}. Mirror left untouched.` })\n if (sweep.status === 'partial')\n return json(502, {\n error: `the sweep broke off after ${sweep.items.length} loras (${sweep.reason}). Writing that would drop every lora past it, so the mirror is left untouched.`,\n })\n const mirror = buildLoraMirror({\n hostId,\n hostUrl: host.getServerHostHTTP(),\n fetchedAt: new Date().toISOString(),\n items: sweep.items,\n })\n writeLoraMirror(mirror)\n // the in-process cache reads the file by mtime, so every surface sees the new names\n reloadLoraInfoCache()\n console.log(`[serve] lora mirror refreshed for ${hostId}: ${mirror.count} loras`)\n return json(200, {\n ok: true,\n host: hostId,\n action: 'refresh-loras',\n count: mirror.count,\n note: `${mirror.count} loras synced`,\n })\n }\n\n /** fetch ONE lora's civitai metadata through the lora manager, then re-sync the mirror so its\n * trigger words reach every surface. The extension keys the request by the file path ON THE\n * HOST, which only the mirror knows, so a lora outside the mirror needs a sync first */\n private async replyLoraCivitaiFetch(hostId: string, lora: string): Promise<ServeReply> {\n const host = comfyts.hosts.get(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}'` })\n const info = getLoraInfo(lora, hostId)\n const filePath = info == null ? null : lmFilePath(info)\n if (filePath == null)\n return json(404, { error: `'${lora}' is not in the lora manager mirror of ${hostId}: sync the mirror first` })\n const fetched = await fetchLoraCivitai(host, filePath)\n const sha256 = info == null ? null : lmSha256(info)\n // civitai ANSWERED that it has no version for this hash: a definite result, kept so the\n // card stops offering a fetch. Any other failure (network, the extension) stays an error\n if (!fetched.ok && /no version data found/i.test(fetched.reason) && sha256 != null) {\n recordCivitaiMiss({ hostId, sha256, miss: true })\n return json(200, {\n ok: true,\n host: hostId,\n lora,\n triggers: { state: 'not-on-civitai' },\n note: `civitai does not know '${lora}' (a private or local lora): no trigger words to fetch`,\n })\n }\n if (!fetched.ok) return json(502, { error: `civitai fetch failed for '${lora}': ${fetched.reason}` })\n if (sha256 != null) recordCivitaiMiss({ hostId, sha256, miss: false })\n const synced = await this.refreshLoraMirror(hostId, host)\n if (synced.status !== 200) return synced\n const t = getLoraTriggers(lora, hostId)\n const note =\n t?.state === 'words'\n ? `trigger words: ${t.words.join(', ')}`\n : t?.state === 'none'\n ? `civitai lists no trigger words for '${lora}'`\n : `civitai has no metadata for '${lora}'`\n return json(200, { ok: true, host: hostId, lora, triggers: t, note })\n }\n\n /** has the host changed since this process loaded its schema: new or removed model files (and\n * node types on a full check). A host whose catalog is COMMITTED rather than live-synced\n * (sdkAutoWrite: false, the cloud catalog) is not compared: its live list moves on purpose */\n private async replyHostDrift(hostId: string, full: boolean): Promise<ServeReply> {\n const host = comfyts.hosts.get(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}'` })\n if (host.data.sdkAutoWrite === false)\n return json(200, { host: hostId, checked: false, changed: false, summary: '' })\n try {\n const drift = await host.checkSchemaDrift({ full })\n return json(200, {\n host: hostId,\n checked: true,\n full,\n changed: driftChanged(drift),\n summary: summarizeDrift(drift),\n drift,\n })\n } catch (e) {\n return json(502, { error: `${hostId} unreachable: ${extractErrorMessage(e)}` })\n }\n }\n\n /** is the host answering RIGHT NOW: what the panel polls while a restart is in flight, so\n * \"restarting…\" ends on a fact rather than on a guess */\n private async replyHostPing(hostId: string): Promise<ServeReply> {\n const host = comfyts.hosts.get(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}'` })\n try {\n const res = await host.fetch('/system_stats', {})\n return json(200, { host: hostId, up: res.ok, status: res.status })\n } catch (e) {\n return json(200, { host: hostId, up: false, reason: extractErrorMessage(e) })\n }\n }\n\n /** the ComfyUI console, the TUI's logs panel over http — through the SAME assembly the TUI\n * uses (assembleLogChunks): entries are write CHUNKS, so lines are folded there, ANSI is\n * stripped, tqdm redraws collapse to their last state, and the cp1252 mojibake a windows\n * host emits is repaired. Re-implementing any of that here would drift from the TUI */\n private async replyHostLogs(hostId: string): Promise<ServeReply> {\n const host = comfyts.hosts.get(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}'` })\n try {\n const raw = await host.fetchRawLogs()\n const lines: string[] = []\n const partial = assembleLogChunks({ lines, partial: '', entries: raw.entries })\n // the tail has no newline yet (a live progress bar): show it, it is the current state\n if (partial.trim() !== '') lines.push(partial)\n return json(200, { host: hostId, lines: lines.slice(-200) })\n } catch (e) {\n return json(502, { error: `could not read the logs of '${hostId}': ${extractErrorMessage(e)}` })\n }\n }\n\n private replyHosts(): ServeReply {\n return json(200, {\n hosts: this.knownHosts(),\n defaults: Object.fromEntries(this.modules.map((m) => [m.key, m.dw.host.data.id])),\n overrides: this.settings.hostOverride,\n })\n }\n\n private replySetHost(modKey: string, req: ServeRequest): ServeReply {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n const wanted = parsed != null && typeof parsed === 'object' ? (parsed as { host?: unknown }).host : null\n if (wanted != null && typeof wanted !== 'string')\n return json(400, { error: 'body must be { \"host\": \"<host id>\" } or { \"host\": null } to reset' })\n const next = { ...this.settings.hostOverride }\n if (wanted == null || wanted === mod.dw.host.data.id) delete next[mod.key]\n else {\n if (!comfyts.hosts.has(wanted))\n return json(400, {\n error: `unknown host '${wanted}' — known: ${[...comfyts.hosts.keys()].join(', ')}`,\n })\n next[mod.key] = wanted\n }\n this.settings = { ...this.settings, hostOverride: next }\n try {\n writeServeSettings(this.settings)\n } catch (e) {\n return json(500, { error: `host applied for this session but not saved: ${extractErrorMessage(e)}` })\n }\n const target = next[mod.key] ?? mod.dw.host.data.id\n console.log(`[serve] ${mod.key} runs on ${target}${next[mod.key] != null ? ' (override)' : ''}`)\n return json(200, { ok: true, module: mod.key, host: target, overrides: this.settings.hostOverride })\n }\n\n // #region settings + in-memory outputs --------------------------------------\n private memoryBlob(key: string, bytes: Uint8Array, filename: string): KeptBlob {\n const contentType = CONTENT_TYPES[extname(filename).toLowerCase()] ?? sniffImageContentType(bytes)\n return { key, bytes, contentType }\n }\n\n private replyMemoryImage(key: string): ServeReply {\n const hit = this.kept.blob(key)\n if (hit == null)\n return json(404, {\n error: `no in-memory output '${key}' — it was deleted, dropped past the ${this.settings.memoryBudgetMb} MB memory budget, or the server restarted. Turn saving on to keep outputs.`,\n })\n return { status: 200, contentType: hit.contentType, body: hit.bytes }\n }\n\n /** the subfolder under outputs/ a module's images land in. Falls back to the module key,\n * which is what every serve run used before the prefix was choosable */\n private savePrefixFor(modKey: string): string {\n const stored = this.settings.savePrefix[modKey]?.trim() ?? ''\n return stored === '' ? modKey : stored\n }\n\n private replySaveSettings(req: ServeRequest): ServeReply {\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))\n return json(400, {\n error: 'body must be { \"saveToDisk\"?: true | false, \"savePrefix\"?: { \"<module>\": \"path\" }, \"memoryBudgetMb\"?: number }',\n })\n const wanted = parsed as { saveToDisk?: unknown; savePrefix?: unknown; memoryBudgetMb?: unknown }\n let next = this.settings\n if (wanted.saveToDisk != null) {\n if (typeof wanted.saveToDisk !== 'boolean') return json(400, { error: '\"saveToDisk\" must be true or false' })\n next = { ...next, saveToDisk: wanted.saveToDisk }\n }\n if (wanted.savePrefix != null) {\n if (typeof wanted.savePrefix !== 'object' || Array.isArray(wanted.savePrefix))\n return json(400, { error: '\"savePrefix\" must be { \"<module>\": \"path\" }' })\n const prefixes = { ...next.savePrefix }\n for (const [modKey, raw] of Object.entries(wanted.savePrefix as Record<string, unknown>)) {\n if (this.moduleByKey(modKey) == null) return json(404, { error: `unknown module '${modKey}'` })\n if (typeof raw !== 'string') return json(400, { error: `prefix for '${modKey}' must be a string` })\n const clean = validSavePrefix(raw)\n if (clean == null)\n return json(400, {\n error: `invalid prefix '${raw}' — folder names only, \"a/b\" allowed, no \"..\" and no absolute path`,\n })\n // empty means \"back to the default\", so the stored map keeps only real choices\n if (clean === '') delete prefixes[modKey]\n else prefixes[modKey] = clean\n }\n next = { ...next, savePrefix: prefixes }\n }\n if (wanted.memoryBudgetMb != null) {\n const mb = validMemoryBudgetMb(wanted.memoryBudgetMb)\n if (mb == null) return json(400, { error: '\"memoryBudgetMb\" must be a number of MB, 1 to 100000' })\n next = { ...next, memoryBudgetMb: mb }\n }\n const saveToDisk = next.saveToDisk\n this.settings = next\n this.kept.setBudget(next.memoryBudgetMb * MB)\n try {\n writeServeSettings(this.settings)\n } catch (e) {\n // the live setting still applies; say the persistence failed rather than lying\n return json(500, { error: `setting applied for this session but not saved: ${extractErrorMessage(e)}` })\n }\n console.log(`[serve] outputs ${saveToDisk ? 'SAVE to disk' : 'stay in MEMORY'}`)\n return this.replySettings()\n }\n\n /** the stored settings PLUS the prefix each module actually uses, so the ui can show the\n * effective folder without re-deriving the fallback rule */\n private replySettings(): ServeReply {\n return json(200, {\n ...this.settings,\n effectivePrefix: Object.fromEntries(this.modules.map((m) => [m.key, this.savePrefixFor(m.key)])),\n })\n }\n\n // #region open draft tabs (the web ui's tab bar) ------------------------------\n /** held by the process, so every window and reload sees the same tabs, and mirrored to a file\n * under .comfy-ts/ (gitignored wholesale) so a restart keeps them. null = not read yet */\n private tabs: DraftTab[] | null = null\n\n private tabsFile(): string {\n return join(comfyts.baseFolder, SERVE_TABS_FILE)\n }\n\n /** only drafts that still exist: a tab whose file was deleted elsewhere is dropped on read */\n private liveTabs(raw: unknown): DraftTab[] {\n return readTabs(\n raw,\n this.modules.map((m) => ({ module: m.key, drafts: this.draftsFor(m) })),\n )\n }\n\n private replyTabs(): ServeReply {\n if (this.tabs == null) {\n const path = this.tabsFile()\n let raw: unknown = []\n try {\n if (existsSync(path)) raw = JSON.parse(readFileSync(path, 'utf8'))\n } catch (e) {\n console.error(`[serve] 🔴 open tabs unreadable (${path}), starting with none:`, e)\n }\n this.tabs = this.liveTabs(raw)\n }\n this.tabs = this.liveTabs(this.tabs)\n return json(200, { tabs: this.tabs })\n }\n\n private replySaveTabs(req: ServeRequest): ServeReply {\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n const raw = parsed != null && typeof parsed === 'object' ? (parsed as { tabs?: unknown }).tabs : undefined\n if (!Array.isArray(raw) || raw.length > 100)\n return json(400, { error: 'expects { \"tabs\": [{ \"module\", \"draft\" }, …] }' })\n this.tabs = this.liveTabs(raw)\n try {\n mkdirSync(comfyts.baseFolder, { recursive: true })\n writeFileSync(this.tabsFile(), JSON.stringify(this.tabs, null, 2))\n } catch (e) {\n // kept for this process either way: only the restart loses them, and the reply says so\n console.error(`[serve] 🔴 open tabs not saved to ${this.tabsFile()}:`, e)\n return json(200, { tabs: this.tabs, warning: `not saved: ${extractErrorMessage(e)}` })\n }\n return json(200, { tabs: this.tabs })\n }\n\n // #region prompt enhancers (the web ui's master prompts, as .md files) ------\n /** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */\n /** tag lists by source, loaded on the first query and kept for the process */\n private tagSources = new TagSources({\n cacheDir: () => join(comfyts.baseFolder, 'cache', 'tags'),\n fetchText: async (url) => {\n const res = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(TAG_LIST_TIMEOUT_MS) })\n if (!res.ok) throw new Error(`tag list download failed (http ${res.status}): ${url}`)\n return new TextDecoder().decode(await readCapped(res, TAG_LIST_CAP, url))\n },\n })\n\n private async replyTags(modKey: string, varName: string, url: string): Promise<ServeReply> {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown workflow '${modKey}'` })\n const found = mod.dw.entries().find(([k]) => k === varName)?.[1]\n if (found == null) return json(404, { error: `workflow '${modKey}' has no var '${varName}'` })\n // cast: whitelist family 6, narrowed by kind\n const tags = found.kind === 'prompt' ? (found as PromptVar).tags : null\n if (tags == null) return json(404, { error: `var '${varName}' declares no tag list (v.prompt(…, { tags }))` })\n const params = new URLSearchParams(url.split('?')[1] ?? '')\n const limit = Math.min(100, Math.max(1, Number(params.get('limit') ?? '20') || 20))\n try {\n const list = await this.tagSources.load(resolveTagSource(tags.url, mod.file))\n return json(200, { hits: list.search(params.get('q') ?? '', limit) })\n } catch (e) {\n console.error(`[serve] 🔴 tag list for ${modKey}/${varName}: ${extractErrorMessage(e)}`)\n return json(502, { error: extractErrorMessage(e) })\n }\n }\n\n private replyPromptEnhancers(): ServeReply {\n try {\n return json(200, { enhancers: listPromptEnhancers() })\n } catch (e) {\n return json(500, { error: `prompt-enhancers folder unreadable: ${extractErrorMessage(e)}` })\n }\n }\n\n private replySavePromptEnhancer(rawName: string, req: ServeRequest): ServeReply {\n const name = validStoreName(rawName)\n if (name == null)\n return json(400, { error: `invalid enhancer name '${rawName}' — letters/digits then letters, digits, \". -_\"` })\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))\n return json(400, { error: 'body must be { \"text\": \"<master prompt>\" }' })\n const text = (parsed as Record<string, unknown>).text\n if (typeof text !== 'string') return json(400, { error: 'body must be { \"text\": \"<master prompt>\" }' })\n try {\n writePromptEnhancer(name, text)\n } catch (e) {\n return json(500, { error: `could not write enhancer '${name}': ${extractErrorMessage(e)}` })\n }\n return json(200, { ok: true, name, enhancers: listPromptEnhancers() })\n }\n\n private replyDeletePromptEnhancer(rawName: string): ServeReply {\n const name = validStoreName(rawName)\n if (name == null) return json(400, { error: `invalid enhancer name '${rawName}'` })\n try {\n deletePromptEnhancer(name)\n } catch (e) {\n return json(500, { error: `could not delete enhancer '${name}': ${extractErrorMessage(e)}` })\n }\n console.log(`[serve] prompt enhancer deleted: ${name}`)\n return json(200, { ok: true, name, enhancers: listPromptEnhancers() })\n }\n\n private replyLlmConfigs(): ServeReply {\n try {\n return json(200, { configs: listLlmConfigs() })\n } catch (e) {\n return json(500, { error: `llm-configs folder unreadable: ${extractErrorMessage(e)}` })\n }\n }\n\n private replySaveLlmConfig(rawName: string, req: ServeRequest): ServeReply {\n const name = validStoreName(rawName)\n if (name == null)\n return json(400, { error: `invalid config name '${rawName}' — letters/digits then letters, digits, \". -_\"` })\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body ?? '')\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))\n return json(400, { error: 'body must be { provider, baseUrl, model, effort, thinkingOnly }' })\n try {\n writeLlmConfig(name, normalizeLlmConfig(parsed))\n } catch (e) {\n return json(500, { error: `could not write llm config '${name}': ${extractErrorMessage(e)}` })\n }\n return json(200, { ok: true, name, configs: listLlmConfigs() })\n }\n\n private replyDeleteLlmConfig(rawName: string): ServeReply {\n const name = validStoreName(rawName)\n if (name == null) return json(400, { error: `invalid config name '${rawName}'` })\n try {\n deleteLlmConfig(name)\n } catch (e) {\n return json(500, { error: `could not delete llm config '${name}': ${extractErrorMessage(e)}` })\n }\n console.log(`[serve] llm config deleted: ${name}`)\n return json(200, { ok: true, name, configs: listLlmConfigs() })\n }\n\n // #region live run state (web ui polling: progress + latent preview) --------\n private liveRuns = new Map<string, ServeExecution>()\n /** seq counts frames so the poller refetches only on a NEW one, not every tick */\n private latentPreviews = new Map<string, { bytes: Uint8Array; mime: string; seq: number }>()\n private latentSeq = 0\n\n private replyRunStatus(modKey: string): ServeReply {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n const exec = this.liveRuns.get(mod.key)\n const running = exec != null && exec.status !== 'Success' && exec.status !== 'Failure'\n return json(200, {\n running,\n status: exec?.status ?? 'idle',\n percent: running ? (exec.progressGlobal?.percent ?? null) : null,\n // the node and ITS counter: on a text graph this is the ONLY thing that moves, since\n // ComfyUI publishes no partial text (probed: 90 progress messages, then one `executed`)\n node: running ? (exec.progress?.nodeName ?? null) : null,\n // value/max ONLY: the raw ws progress message also carries prompt_id and node, and\n // echoing a whole wire message into our own api makes its extra fields look like ours\n nodeProgress:\n running && exec.progress?.nodeProgress != null\n ? { value: exec.progress.nodeProgress.value, max: exec.progress.nodeProgress.max }\n : null,\n // live text a node publishes WHILE it runs (send_progress_text): the only channel\n // on which a generator's partial answer can reach a client at all\n progressText: running ? (exec.progress?.progressText ?? null) : null,\n hasPreview: this.latentPreviews.has(mod.key),\n previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null,\n })\n }\n\n private replyRunPreview(modKey: string): ServeReply {\n const mod = this.moduleByKey(modKey)\n if (mod == null) return json(404, { error: `unknown module '${modKey}'` })\n const preview = this.latentPreviews.get(mod.key)\n if (preview == null) return json(404, { error: 'no latent preview yet' })\n return {\n status: 200,\n contentType: preview.mime !== '' ? preview.mime : sniffImageContentType(preview.bytes),\n body: preview.bytes,\n }\n }\n\n // #region lora hover data ---------------------------------------------------\n private hostById(hostId: string): ComfyHost | null {\n return this.modules.map((m) => m.dw.host).find((h) => h.data.id === hostId) ?? null\n }\n\n private hostIds(): string {\n return [...new Set(this.modules.map((m) => m.dw.host.data.id))].join(', ')\n }\n\n /** mirror-backed text for the hover pane, no network */\n private replyLoraInfo(hostId: string, lora: string): ServeReply {\n if (this.hostById(hostId) == null)\n return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })\n refreshLoraInfoCacheIfChanged()\n // everything the mirror holds that a human wants when they click a card. Read through the\n // lm* accessors, never off the raw json: the extension's field names are its business\n const item = getLoraInfo(lora, hostId)\n const civitai = item == null ? null : lmCivitai(item)\n return json(200, {\n name: lora,\n displayName: getLoraDisplayName(lora, hostId),\n triggerWords: getLoraTriggerWords(lora, hostId),\n known: item != null,\n baseModel: item == null ? null : lmBaseModel(item),\n folder: item == null ? null : lmFolder(item),\n filePath: item == null ? null : lmFilePath(item),\n fileSize: item == null ? null : lmFileSize(item),\n tags: item == null ? [] : lmTags(item),\n notes: item == null ? '' : lmNotes(item),\n civitaiUrl: civitai?.modelId == null ? null : `https://civitai.com/models/${civitai.modelId}`,\n civitaiVersion: civitai?.name ?? null,\n })\n }\n\n /** what the mirror does NOT hold: civitai's description and the example images, both live\n * from the extension. A SEPARATE route from /lora-info on purpose, that one is mirror-only\n * and instant, this one talks to the host and is fetched when a details panel opens */\n private async replyLoraAbout(hostId: string, lora: string): Promise<ServeReply> {\n const host = this.hostById(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })\n refreshLoraInfoCacheIfChanged()\n const item = getLoraInfo(lora, hostId)\n if (item == null) return json(200, { known: false, description: null, examples: [], examplesReason: null })\n const filePath = lmFilePath(item)\n const sha = lmSha256(item)\n const [description, examples] = await Promise.all([\n filePath == null ? Promise.resolve(null) : fetchLoraDescription(host, filePath),\n sha == null ? Promise.resolve({ files: [], reason: null }) : fetchLoraExampleImages(host, sha),\n ])\n return json(200, {\n known: true,\n description,\n examples: examples.files,\n examplesReason: examples.reason,\n })\n }\n\n /** preview url resolution misses per host, so an absent lora-manager costs ONE sweep, not one\n * per hover. An UNREACHABLE host evicts itself: the host coming back must not stay 404 forever */\n private previewSweeps = new Map<string, Promise<{ status: string; map: Map<string, string> | null }>>()\n\n private async replyLoraPreview(hostId: string, lora: string): Promise<ServeReply> {\n const host = this.hostById(hostId)\n if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })\n refreshLoraInfoCacheIfChanged()\n let url = getLoraPreviewUrl(lora, hostId)\n if (url == null) {\n // the TUI's fallback: unsynced mirror (or a lora it never saw) → ask the live host once\n let sweep = this.previewSweeps.get(hostId)\n if (sweep == null) {\n sweep = fetchLoraList(host).then((r) => {\n if (r.status === 'unreachable') {\n this.previewSweeps.delete(hostId)\n return { status: r.status, map: null }\n }\n return { status: r.status, map: r.status === 'absent' ? null : loraPreviewMapFrom(r.items) }\n })\n this.previewSweeps.set(hostId, sweep)\n }\n const swept = await sweep\n url = swept.map?.get(loraKey(lora)) ?? null\n // each miss has its OWN cause (the LorasSt rule): the wrong advice sends the user hunting\n if (url == null && swept.status === 'unreachable')\n return json(404, { error: `host '${hostId}' is unreachable — no preview to fetch` })\n if (url == null && swept.status === 'absent')\n return json(404, { error: `lora-manager extension not detected on '${hostId}'` })\n }\n if (url == null)\n return json(404, { error: `no preview known for '${lora}' (run: comfy-ts loras --id ${hostId})` })\n const bytes = await fetchLoraPreviewBytes(host, url)\n // one 404 for two causes on purpose: unreachable host and no-image both mean \"nothing to show\"\n if (bytes == null)\n return json(404, { error: `no image preview for '${lora}' (host '${hostId}' unreachable, or not an image)` })\n return { status: 200, contentType: sniffImageContentType(bytes), body: bytes }\n }\n\n private outputUrl(absPath: string): string | null {\n if (!absPath.startsWith(this.outputRoot + '/')) return null\n const rel = absPath.slice(this.outputRoot.length + 1)\n return '/outputs/' + rel.split('/').map(encodeURIComponent).join('/')\n }\n\n // #region generate ---------------------------------------------------------\n private async generate(mod: ServeModule, draft: string, req: ServeRequest): Promise<ServeReply> {\n let payload: Record<string, unknown> = {}\n if (req.body != null && req.body.trim() !== '') {\n let parsed: unknown\n try {\n parsed = JSON.parse(req.body)\n } catch (e) {\n return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })\n }\n if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))\n return json(400, { error: 'body must be a json object: { \"<var>\": value, … }' })\n payload = parsed as Record<string, unknown>\n }\n\n const t0 = Date.now()\n const seeds: Record<string, number> = {}\n const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds))\n if ('error' in started) return json(started.status, { error: started.error })\n\n const execution = started.execution\n this.liveRuns.set(mod.key, execution)\n console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`)\n await execution.done\n const durationMs = Date.now() - t0\n\n if (execution.status === 'Failure') {\n const error = describeRunError(execution.data.error)\n console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms: ${error}`)\n return json(500, { ok: false, module: mod.key, draft, promptId: execution.data.id, durationMs, error })\n }\n\n const produced = [`${execution.images.length} image(s)`]\n const audios = execution.audios ?? []\n if (audios.length > 0) produced.push(`${audios.length} audio(s)`)\n const videos = execution.videos ?? []\n if (videos.length > 0) produced.push(`${videos.length} video(s)`)\n const models3d = execution.models3d ?? []\n if (models3d.length > 0) produced.push(`${models3d.length} 3d model(s)`)\n if ((execution.texts ?? []).length > 0) produced.push(`${(execution.texts ?? []).length} text(s)`)\n console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${produced.join(' · ')}`)\n\n // saving off → the buffer is the only copy: keep it addressable so the gallery (and\n // curl) still get an image instead of a null url\n const blobs: KeptBlob[] = []\n const imageKeys = execution.images.map((img, ix) => {\n if (img.absPath != null || img.buffer == null) return null\n const key = `${execution.data.id}/${ix}`\n blobs.push(this.memoryBlob(key, img.buffer, img.filename))\n return key\n })\n // same store as the images, own key space: the audio route adds the `audio/` prefix\n const audioKeys = audios.map((a, ix) => {\n if (a.absPath != null) return null\n const key = `audio/${execution.data.id}/${ix}`\n blobs.push(this.memoryBlob(key, a.bytes, a.filename))\n return key\n })\n const videoKeys = videos.map((a, ix) => {\n if (a.absPath != null) return null\n const key = `video/${execution.data.id}/${ix}`\n blobs.push(this.memoryBlob(key, a.bytes, a.filename))\n return key\n })\n const model3dKeys = models3d.map((m, ix) => {\n if (m.absPath != null) return null\n const key = `model3d/${execution.data.id}/${ix}`\n blobs.push(this.memoryBlob(key, m.bytes, m.filename))\n return key\n })\n // the KEY is raw (`<promptId>/<ix>`); the url encodes each segment, and handle() decodes\n // per segment, so the lookup gets the raw key back\n const memoryUrl = (route: string, key: string): string =>\n `/${route}/${key\n .split('/')\n .slice(route === 'images' ? 0 : 1)\n .map((seg) => encodeURIComponent(seg))\n .join('/')}`\n const record: RunRecord = {\n ok: true,\n module: mod.key,\n draft,\n promptId: execution.data.id,\n durationMs,\n finishedAt: Date.now(),\n seeds,\n savedToDisk: this.settings.saveToDisk,\n texts: (execution.texts ?? []).map((t) => ({ nodeKey: t.nodeKey, text: t.text })),\n images: execution.images.map((img, ix) => {\n const key = imageKeys[ix]\n return {\n filename: img.filename,\n url: img.absPath != null ? this.outputUrl(img.absPath) : key != null ? memoryUrl('images', key) : null,\n absPath: img.absPath,\n ...(img.tags != null && img.tags.length > 0 ? { tags: [...img.tags] } : {}),\n }\n }),\n audios: audios.map((a, ix) => {\n const key = audioKeys[ix]\n return {\n filename: a.filename,\n mime: a.mime,\n url: a.absPath != null ? this.outputUrl(a.absPath) : key != null ? memoryUrl('audio', key) : null,\n absPath: a.absPath,\n }\n }),\n videos: videos.map((a, ix) => {\n const key = videoKeys[ix]\n return {\n filename: a.filename,\n mime: a.mime,\n url: a.absPath != null ? this.outputUrl(a.absPath) : key != null ? memoryUrl('video', key) : null,\n absPath: a.absPath,\n }\n }),\n models3d: models3d.map((m, ix) => {\n const key = model3dKeys[ix]\n return {\n filename: m.filename,\n mime: m.mime,\n format: m.format,\n size: m.bytes.byteLength,\n url: m.absPath != null ? this.outputUrl(m.absPath) : key != null ? memoryUrl('model3d', key) : null,\n absPath: m.absPath,\n }\n }),\n ...(mod.dw.spec.widgets != null && mod.dw.spec.widgets.length > 0 ? { widgets: mod.dw.spec.widgets } : {}),\n }\n this.kept.add({ record, imageKeys, audioKeys, videoKeys, model3dKeys, blobs })\n\n // Accept: image/* → first image's bytes directly (curl -o, <img src>)\n const first = execution.images[0]\n if (req.accept?.includes('image/') && first != null) {\n if (first.absPath != null) {\n const contentType = CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? 'application/octet-stream'\n return { status: 200, contentType, body: new Uint8Array(readFileSync(first.absPath)) }\n }\n const inMemory = this.kept.blob(imageKeys[0] ?? '')\n if (inMemory != null) return { status: 200, contentType: inMemory.contentType, body: inMemory.bytes }\n }\n\n return json(200, record)\n }\n\n /** everything that touches the module's SHARED vars, under the module mutex */\n private async prepareAndStart(\n mod: ServeModule,\n draft: string,\n payload: Record<string, unknown>,\n seeds: Record<string, number>,\n ): Promise<{ execution: ServeExecution } | { error: string; status: number }> {\n // 1. reset, then load the draft FRESH from disk (TUI edits between requests apply)\n for (const [, varDef] of mod.dw.entries()) varDef.reset()\n const draftPath = this.draftPath(mod, draft)\n if (draftPath == null) return { status: 404, error: `no draft '${draft}'` }\n if (existsSync(draftPath)) {\n try {\n const values = JSON.parse(readFileSync(draftPath, 'utf8')) as Record<string, unknown>\n for (const [k, varDef] of mod.dw.entries()) if (k in values) varDef.loadJSON(values[k])\n } catch (e) {\n return { status: 500, error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}` }\n }\n }\n\n // the DRAFT's seed values, before payload overrides: the +/- continuation\n // compares against what the draft file says, not what a payload injected\n const draftSeedValues = new Map<string, number>()\n for (const [k, varDef] of mod.dw.entries())\n if (varDef.kind === 'seed') draftSeedValues.set(k, (varDef as SeedVar).value)\n\n // 2. payload overrides (image urls download first, so the var gets a local path)\n const varMap = new Map(mod.dw.entries())\n for (const [k, rawValue] of Object.entries(payload)) {\n const varDef = varMap.get(k)\n if (varDef == null)\n return { status: 400, error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(', ')}` }\n let value = rawValue\n // kind, never instanceof: consumer and cli hold different class copies (VarKind\n // owns the WHY); casts are the kind-narrowing family, agent/coding.md whitelist 6\n if (isMediaKind(varDef.kind) && typeof rawValue === 'string' && /^https?:\\/\\//.test(rawValue)) {\n try {\n value = await this.downloadInput(rawValue)\n } catch (e) {\n return { status: 400, error: `var '${k}': ${extractErrorMessage(e)}` }\n }\n }\n // a lora the mirror knows but the enum does not is a legal choice here too, else the\n // picker would offer something the api then refuses\n const err = applyVarPayload(varDef, value, {\n // narrowed by the var's OWN filter, exactly like the picker: what the ui offers and\n // what the api accepts must be the same set, or one of them is lying\n // the SAME function the picker used: it derives the separator from this var's own\n // enum, so a backslash host cannot be offered `a/b` and then refused it\n extraLoraOptions:\n varDef.kind === 'loras'\n ? managerOnlyLoraOptions({\n hostId: mod.dw.host.data.id,\n options: (varDef as LorasVar<string>).options,\n filter: (varDef as LorasVar<string>).optionsFilter,\n })\n : undefined,\n })\n if (err != null) return { status: 400, error: err }\n }\n\n // 3. media vars must point at a real FILE of a declared type BEFORE anything is queued.\n // the path a request hands us is read off this box and uploaded to the ComfyUI host, so\n // the extension list the descriptor advertises is enforced here, not merely advertised:\n // a var that accepts .png must not be talked into reading a key or a config file\n for (const [k, varDef] of varMap) {\n const kind = varDef.kind\n if (!isMediaKind(kind)) continue\n const media = varDef as MediaVar\n if (!media.isSet()) continue\n const abs = media.absPath()\n // ONE message for every rejection below: distinct ones told an unauthenticated caller\n // whether any path exists, is a file, and what type it is\n const refuse = { status: 400, error: `${kind} var '${k}': not a usable ${kind} file` }\n if (!existsSync(abs)) return refuse\n // the REAL path: statSync follows symlinks, so `pic.png -> id_rsa` passed a check made\n // on the link's name. Resolving first means the gate judges the file being read\n let real: string\n try {\n real = realpathSync(abs)\n } catch {\n return refuse\n }\n try {\n if (!statSync(real).isFile()) return refuse\n } catch {\n return refuse\n }\n if (!serveAcceptsMediaExt(kind, media.extensions, extname(real).toLowerCase().replace(/^\\./, '')))\n return refuse\n if (!looksLikeMedia(kind, real)) return refuse\n }\n\n // 4. seed policy (architecture item 12): payload wins; '?' rerolls;\n // '+'/'-' continue from the last SERVED value; '=' keeps the draft value\n for (const [k, varDef] of varMap) {\n if (varDef.kind !== 'seed') continue\n const seedVar = varDef as SeedVar\n const stateKey = `${mod.key}/${draft}/${k}`\n const draftValue = draftSeedValues.get(k) ?? seedVar.value\n const prev = this.seedState.get(stateKey)\n const continues =\n !(k in payload) &&\n (seedVar.mode === '+' || seedVar.mode === '-') &&\n prev != null &&\n (prev.draftBase === draftValue || prev.served.includes(draftValue))\n if (!(k in payload) && seedVar.mode === '?') seedVar.randomize()\n if (continues) {\n seedVar.set(prev.last + (seedVar.mode === '+' ? 1 : -1))\n // bounded: a write-back never lags by more than the queue\n const served = [...prev.served, seedVar.value].slice(-256)\n this.seedState.set(stateKey, { last: seedVar.value, draftBase: prev.draftBase, served })\n } else this.seedState.set(stateKey, { last: seedVar.value, draftBase: draftValue, served: [seedVar.value] })\n seeds[k] = seedVar.value\n }\n\n // 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex.\n // the run's own preview frames feed the web ui's /run/<module>/preview poll; the\n // previous run's preview must not linger over the new one\n this.latentPreviews.delete(mod.key)\n const runHost = this.runHostFor(mod)\n try {\n return {\n execution: await this.starter(mod, {\n saveToDisk: this.settings.saveToDisk,\n savePrefix: this.savePrefixFor(mod.key),\n host: runHost ?? undefined,\n onPreview: (p) =>\n this.latentPreviews.set(mod.key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq }),\n }),\n }\n } catch (e) {\n // name, not instanceof: same two-copies problem as the var classes\n // both names: a project on an older comfy-ts still throws the image-only one\n if (e instanceof Error && (e.name === 'MediaVarEmptyError' || e.name === 'ImageVarEmptyError'))\n return { status: 400, error: e.message }\n // the ComfyUI host is upstream of this bridge: 502, not \"serve crashed\".\n // The connect deadline (ConnectOptions.timeoutMs) is what makes this\n // this runs inside the module mutex: a url that never answers would hold it\n if (e instanceof Error && e.name === 'ComfyHostUnreachableError') return { status: 502, error: e.message }\n return { status: 500, error: extractErrorMessage(e) }\n }\n }\n\n /** serialize fn per module key; the stored chain never rejects */\n private exclusive<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = this.chains.get(key) ?? Promise.resolve()\n const next = prev.then(fn)\n this.chains.set(\n key,\n next.catch(() => {}),\n )\n return next\n }\n\n /** one file per url: a preset or a pasted url downloads once per output root, not per run */\n private urlInputPath(url: string, name: string): string {\n const hash = createHash('sha1').update(url).digest('hex').slice(0, 16)\n return join(this.outputRoot, 'serve-inputs', `url-${hash}${extname(name)}`)\n }\n\n /** payload image urls land as local files under outputs/serve-inputs/ */\n private async downloadInput(url: string): Promise<string> {\n const cached = this.urlInputPath(url, basename(new URL(url).pathname))\n if (existsSync(cached)) return cached\n // every failure below answers the SAME thing. Refused, DNS miss, 403 and 200-of-the-wrong\n // -type were four distinguishable replies, which is a port and host scanner for anything\n // this box can reach. The reason goes to the server log\n try {\n return await this.fetchInput(url)\n } catch (e) {\n if (!(e instanceof DownloadRefused)) console.error(`[serve] input download failed: ${url}:`, e)\n throw new DownloadRefused(url)\n }\n }\n\n private async fetchInput(url: string): Promise<string> {\n // a timeout, because this runs INSIDE the module mutex: a url that accepts the connection\n // and then trickles would wedge that workflow's queue for as long as it liked\n const res = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(INPUT_DOWNLOAD_TIMEOUT_MS) })\n // the upstream STATUS is not reported back: reflecting it turns an image var into a port\n // and route scanner for everything this box can reach (loopback, tailnet, metadata\n // endpoints). The caller learns the fetch failed, not what answered\n if (!res.ok) {\n console.error(`[serve] input download failed (http ${res.status}): ${url}`)\n throw new DownloadRefused(url)\n }\n const declared = Number(res.headers.get('content-length') ?? '0')\n if (declared > INPUT_DOWNLOAD_CAP) throw new Error(`download too large (${declared} bytes): ${url}`)\n const bytes = await readCapped(res, INPUT_DOWNLOAD_CAP, url)\n const name = basename(new URL(url).pathname) || 'input'\n const abs = this.urlInputPath(url, name)\n mkdirSync(dirname(abs), { recursive: true })\n writeFileSync(abs, bytes)\n return abs\n }\n}\n"],"mappings":";;;;;;;;;;AAgFA,SAAS,mBAAmB,SAA+C;CACxE,OAAO,QAAQ,WAAW,IAAI,KAAA,IAAY;AAC7C;AAEA,SAAS,UAAU,MAA8C;CAC9D,IAAI,KAAK,OAAO,QAAQ,KAAK,OAAO,MAAM,OAAO;CACjD,OAAO,KAAK,KAAK,OAAO,KAAK,IAAI,KAAK,OAAO,IAAI;AACpD;AAEA,SAAgB,YAAY,QAA+B;CACxD,MAAM,OAAO;EACV,MAAM,OAAO;EACb,OAAO,O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