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.
- package/dist/chunk-6mgjbrp6.js +579 -0
- package/dist/chunk-6mgjbrp6.js.map +17 -0
- package/dist/chunk-6tsg7fm5.js +1876 -0
- package/dist/chunk-6tsg7fm5.js.map +31 -0
- package/dist/chunk-dvxjvwe7.js +2593 -0
- package/dist/chunk-dvxjvwe7.js.map +29 -0
- package/dist/chunk-dw0t1nye.js +457 -0
- package/dist/chunk-dw0t1nye.js.map +16 -0
- package/dist/chunk-he70ewwx.js +444 -0
- package/dist/chunk-he70ewwx.js.map +13 -0
- package/dist/chunk-n22qz0j1.js +6663 -0
- package/dist/chunk-n22qz0j1.js.map +95 -0
- package/dist/chunk-n35nffm8.js +4777 -0
- package/dist/chunk-n35nffm8.js.map +51 -0
- package/dist/cli/serve/hostProtocol.d.cts +74 -0
- package/dist/cli/serve/hostProtocol.d.ts +74 -0
- package/dist/cli/tui-env.d.cts +2 -0
- package/dist/cli/tui-env.d.ts +2 -0
- package/dist/cli.js +494 -485
- package/dist/cli.js.map +16 -1
- package/dist/coreExports.d.cts +45 -0
- package/dist/coreExports.d.ts +45 -0
- package/dist/errors/InvalidPromptError.d.cts +10 -0
- package/dist/errors/InvalidPromptError.d.ts +10 -0
- package/dist/exampleAssets.d.cts +24 -0
- package/dist/exampleAssets.d.ts +24 -0
- package/dist/graph/ComfyNode.d.cts +109 -0
- package/dist/graph/ComfyNode.d.ts +109 -0
- package/dist/graph/ComfyNodeID.d.cts +15 -0
- package/dist/graph/ComfyNodeID.d.ts +15 -0
- package/dist/graph/ComfyNodeOutput.d.cts +21 -0
- package/dist/graph/ComfyNodeOutput.d.ts +21 -0
- package/dist/graph/NodeSlotSize.d.cts +4 -0
- package/dist/graph/NodeSlotSize.d.ts +4 -0
- package/dist/graph/autoValue.d.cts +16 -0
- package/dist/graph/autoValue.d.ts +16 -0
- package/dist/host/ComfyHost.d.cts +383 -0
- package/dist/host/ComfyHost.d.ts +383 -0
- package/dist/host/ComfyInstallType.d.cts +11 -0
- package/dist/host/ComfyInstallType.d.ts +11 -0
- package/dist/host/ComfyManager.d.cts +152 -0
- package/dist/host/ComfyManager.d.ts +152 -0
- package/dist/host/ComfyUploader.d.cts +42 -0
- package/dist/host/ComfyUploader.d.ts +42 -0
- package/dist/host/ComfyWorkflowBuilder.d.cts +19 -0
- package/dist/host/ComfyWorkflowBuilder.d.ts +19 -0
- package/dist/host/Requirements.d.cts +43 -0
- package/dist/host/Requirements.d.ts +43 -0
- package/dist/host/ResilientWebsocket.d.cts +122 -0
- package/dist/host/ResilientWebsocket.d.ts +122 -0
- package/dist/host/hostFile.d.cts +23 -0
- package/dist/host/hostFile.d.ts +23 -0
- package/dist/host/hostUrl.d.cts +22 -0
- package/dist/host/hostUrl.d.ts +22 -0
- package/dist/host/leastBusy.d.cts +9 -0
- package/dist/host/leastBusy.d.ts +9 -0
- package/dist/host/loraInfoCache.d.cts +110 -0
- package/dist/host/loraInfoCache.d.ts +110 -0
- package/dist/host/loraManagerApi.d.cts +106 -0
- package/dist/host/loraManagerApi.d.ts +106 -0
- package/dist/host/previewMethod.d.cts +5 -0
- package/dist/host/previewMethod.d.ts +5 -0
- package/dist/host/schemaDrift.d.cts +54 -0
- package/dist/host/schemaDrift.d.ts +54 -0
- package/dist/image-utils/_getPngMetadata.d.cts +5 -0
- package/dist/image-utils/_getPngMetadata.d.ts +5 -0
- package/dist/index.cjs +8197 -8509
- package/dist/index.cjs.map +124 -1
- package/dist/index.d.cts +4 -19116
- package/dist/index.d.ts +4 -19116
- package/dist/index.js +8129 -8390
- package/dist/index.js.map +124 -1
- package/dist/litegraph/CanonicalWorkflow.d.cts +75 -0
- package/dist/litegraph/CanonicalWorkflow.d.ts +75 -0
- package/dist/litegraph/LiteGraphGroup.d.cts +17 -0
- package/dist/litegraph/LiteGraphGroup.d.ts +17 -0
- package/dist/litegraph/LiteGraphJSON.d.cts +242 -0
- package/dist/litegraph/LiteGraphJSON.d.ts +242 -0
- package/dist/litegraph/LiteGraphLink.d.cts +48 -0
- package/dist/litegraph/LiteGraphLink.d.ts +48 -0
- package/dist/litegraph/LiteGraphLinkID.d.cts +6 -0
- package/dist/litegraph/LiteGraphLinkID.d.ts +6 -0
- package/dist/litegraph/LiteGraphNode.d.cts +76 -0
- package/dist/litegraph/LiteGraphNode.d.ts +76 -0
- package/dist/litegraph/LiteGraphNodeInput.d.cts +25 -0
- package/dist/litegraph/LiteGraphNodeInput.d.ts +25 -0
- package/dist/litegraph/LiteGraphNodeOutput.d.cts +20 -0
- package/dist/litegraph/LiteGraphNodeOutput.d.ts +20 -0
- package/dist/litegraph/LiteGraphSlotIndex.d.cts +6 -0
- package/dist/litegraph/LiteGraphSlotIndex.d.ts +6 -0
- package/dist/litegraph/LiteGraphSubgraphDef.d.cts +174 -0
- package/dist/litegraph/LiteGraphSubgraphDef.d.ts +174 -0
- package/dist/litegraph/convertFlowToLiteGraphJSON.d.cts +12 -0
- package/dist/litegraph/convertFlowToLiteGraphJSON.d.ts +12 -0
- package/dist/litegraph/expandSubgraphs.d.cts +27 -0
- package/dist/litegraph/expandSubgraphs.d.ts +27 -0
- package/dist/litegraph/normalizeWorkflow.d.cts +21 -0
- package/dist/litegraph/normalizeWorkflow.d.ts +21 -0
- package/dist/manager/ComfyRegistry.d.cts +54 -0
- package/dist/manager/ComfyRegistry.d.ts +54 -0
- package/dist/manager/generated/KnownComfyCustomNodeName.d.cts +1 -0
- package/dist/manager/generated/KnownComfyCustomNodeName.d.ts +1 -0
- package/dist/manager/generated/KnownComfyPluginTitle.d.cts +12109 -0
- package/dist/manager/generated/KnownComfyPluginTitle.d.ts +12109 -0
- package/dist/manager/generated/KnownComfyPluginURL.d.cts +1 -0
- package/dist/manager/generated/KnownComfyPluginURL.d.ts +1 -0
- package/dist/manager/generated/KnownModel_Base.d.cts +2 -0
- package/dist/manager/generated/KnownModel_Base.d.ts +2 -0
- package/dist/manager/generated/KnownModel_Name.d.cts +2842 -0
- package/dist/manager/generated/KnownModel_Name.d.ts +2842 -0
- package/dist/manager/generated/KnownModel_SavePath.d.cts +2 -0
- package/dist/manager/generated/KnownModel_SavePath.d.ts +2 -0
- package/dist/manager/generated/KnownModel_Type.d.cts +2 -0
- package/dist/manager/generated/KnownModel_Type.d.ts +2 -0
- package/dist/manager/installedView.d.cts +65 -0
- package/dist/manager/installedView.d.ts +65 -0
- package/dist/manager/json/custom-node-list.extra.d.cts +2 -0
- package/dist/manager/json/custom-node-list.extra.d.ts +2 -0
- package/dist/manager/json/model-list.extra.d.cts +2 -0
- package/dist/manager/json/model-list.extra.d.ts +2 -0
- package/dist/manager/loaders/parseReport.d.cts +24 -0
- package/dist/manager/loaders/parseReport.d.ts +24 -0
- package/dist/manager/loaders/step1_downloadComfyManagerJSONs.d.cts +1 -0
- package/dist/manager/loaders/step1_downloadComfyManagerJSONs.d.ts +1 -0
- package/dist/manager/loaders/step2_custom-node-list-loader.d.cts +2 -0
- package/dist/manager/loaders/step2_custom-node-list-loader.d.ts +2 -0
- package/dist/manager/loaders/step3_extension-node-map-loader.d.cts +2 -0
- package/dist/manager/loaders/step3_extension-node-map-loader.d.ts +2 -0
- package/dist/manager/loaders/step4_model-list-loader.d.cts +2 -0
- package/dist/manager/loaders/step4_model-list-loader.d.ts +2 -0
- package/dist/manager/loaders/step5_alter-list-loader.d.cts +2 -0
- package/dist/manager/loaders/step5_alter-list-loader.d.ts +2 -0
- package/dist/manager/loaders/step6_github-stats-loader.d.cts +2 -0
- package/dist/manager/loaders/step6_github-stats-loader.d.ts +2 -0
- package/dist/manager/types/ComfyManagerAPIFetchPolicy.d.cts +7 -0
- package/dist/manager/types/ComfyManagerAPIFetchPolicy.d.ts +7 -0
- package/dist/manager/types/ComfyManagerAPIModelList.d.cts +10 -0
- package/dist/manager/types/ComfyManagerAPIModelList.d.ts +10 -0
- package/dist/manager/types/ComfyManagerAPIPluginList.d.cts +33 -0
- package/dist/manager/types/ComfyManagerAPIPluginList.d.ts +33 -0
- package/dist/manager/types/ComfyManagerAlterInfo.d.cts +12 -0
- package/dist/manager/types/ComfyManagerAlterInfo.d.ts +12 -0
- package/dist/manager/types/ComfyManagerFileModelInfo.d.cts +10 -0
- package/dist/manager/types/ComfyManagerFileModelInfo.d.ts +10 -0
- package/dist/manager/types/ComfyManagerFilePluginContent.d.cts +11 -0
- package/dist/manager/types/ComfyManagerFilePluginContent.d.ts +11 -0
- package/dist/manager/types/ComfyManagerFilePluginList.d.cts +5 -0
- package/dist/manager/types/ComfyManagerFilePluginList.d.ts +5 -0
- package/dist/manager/types/ComfyManagerGithubStats.d.cts +7 -0
- package/dist/manager/types/ComfyManagerGithubStats.d.ts +7 -0
- package/dist/manager/types/ComfyManagerModelInfo.d.cts +12 -0
- package/dist/manager/types/ComfyManagerModelInfo.d.ts +12 -0
- package/dist/manager/types/ComfyManagerPluginContentMetadata.d.cts +10 -0
- package/dist/manager/types/ComfyManagerPluginContentMetadata.d.ts +10 -0
- package/dist/manager/types/ComfyManagerPluginEnums.d.cts +5 -0
- package/dist/manager/types/ComfyManagerPluginEnums.d.ts +5 -0
- package/dist/manager/types/ComfyManagerPluginInfo.d.cts +54 -0
- package/dist/manager/types/ComfyManagerPluginInfo.d.ts +54 -0
- package/dist/promptEnhancers.d.cts +22 -0
- package/dist/promptEnhancers.d.ts +22 -0
- package/dist/runner/ComfyExecution.d.cts +230 -0
- package/dist/runner/ComfyExecution.d.ts +230 -0
- package/dist/runner/ComfyExecutionStatus.d.cts +1 -0
- package/dist/runner/ComfyExecutionStatus.d.ts +1 -0
- package/dist/runner/ComfyWorkflow.d.cts +141 -0
- package/dist/runner/ComfyWorkflow.d.ts +141 -0
- package/dist/runner/ComfyWorkflowLayout.d.cts +17 -0
- package/dist/runner/ComfyWorkflowLayout.d.ts +17 -0
- package/dist/runner/ComfyWsApi.d.cts +2174 -0
- package/dist/runner/ComfyWsApi.d.ts +2174 -0
- package/dist/runner/MediaImage.d.cts +127 -0
- package/dist/runner/MediaImage.d.ts +127 -0
- package/dist/runner/comfyOrgApiKey.d.cts +21 -0
- package/dist/runner/comfyOrgApiKey.d.ts +21 -0
- package/dist/runner/describePromptRejection.d.cts +1 -0
- package/dist/runner/describePromptRejection.d.ts +1 -0
- package/dist/runner/ephemeral.d.cts +10 -0
- package/dist/runner/ephemeral.d.ts +10 -0
- package/dist/runner/historyReplay.d.cts +13 -0
- package/dist/runner/historyReplay.d.ts +13 -0
- package/dist/runner/mediaKinds.d.cts +7 -0
- package/dist/runner/mediaKinds.d.ts +7 -0
- package/dist/runner/outputPath.d.cts +40 -0
- package/dist/runner/outputPath.d.ts +40 -0
- package/dist/runner/outputs3d.d.cts +3 -0
- package/dist/runner/outputs3d.d.ts +3 -0
- package/dist/runner/wsBinaryFrame.d.cts +25 -0
- package/dist/runner/wsBinaryFrame.d.ts +25 -0
- package/dist/sdk-generator/ComfyNodeSchema.d.cts +25 -0
- package/dist/sdk-generator/ComfyNodeSchema.d.ts +25 -0
- package/dist/sdk-generator/ComfySchema.d.cts +74 -0
- package/dist/sdk-generator/ComfySchema.d.ts +74 -0
- package/dist/sdk-generator/ComfyUIObjectInfoTypes.d.cts +3072 -0
- package/dist/sdk-generator/ComfyUIObjectInfoTypes.d.ts +3072 -0
- package/dist/sdk-generator/Primitives.d.cts +12 -0
- package/dist/sdk-generator/Primitives.d.ts +12 -0
- package/dist/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.d.cts +2 -0
- package/dist/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.d.ts +2 -0
- package/dist/sdk-generator/_pythonModuleToNamespace.d.cts +1 -0
- package/dist/sdk-generator/_pythonModuleToNamespace.d.ts +1 -0
- package/dist/sdk-generator/_toQualifiedNodeKey.d.cts +1 -0
- package/dist/sdk-generator/_toQualifiedNodeKey.d.ts +1 -0
- package/dist/sdk-generator/comfy-api-json.d.cts +16 -0
- package/dist/sdk-generator/comfy-api-json.d.ts +16 -0
- package/dist/sdk-generator/comfyui-sdk-codegen.d.cts +23 -0
- package/dist/sdk-generator/comfyui-sdk-codegen.d.ts +23 -0
- package/dist/sdk-generator/comfyui-types.d.cts +55 -0
- package/dist/sdk-generator/comfyui-types.d.ts +55 -0
- package/dist/sdk-generator/inputWidgetKind.d.cts +80 -0
- package/dist/sdk-generator/inputWidgetKind.d.ts +80 -0
- package/dist/sdk-generator/litegraphToApiRequestPayload.d.cts +41 -0
- package/dist/sdk-generator/litegraphToApiRequestPayload.d.ts +41 -0
- package/dist/serve-web.js +51 -51
- package/dist/ssh-host-manager/ssh-config-manager.d.cts +17 -0
- package/dist/ssh-host-manager/ssh-config-manager.d.ts +17 -0
- package/dist/state.d.cts +80 -0
- package/dist/state.d.ts +80 -0
- package/dist/storage/ComfyStorage.d.cts +55 -0
- package/dist/storage/ComfyStorage.d.ts +55 -0
- package/dist/storage/nodeStorage.d.cts +2 -0
- package/dist/storage/nodeStorage.d.ts +2 -0
- package/dist/types/comfy-sdk.d.cts +85 -0
- package/dist/types/comfy-sdk.d.ts +85 -0
- package/dist/types/index.d.cts +65 -0
- package/dist/types/index.d.ts +65 -0
- package/dist/utils/CodeBuffer.d.cts +20 -0
- package/dist/utils/CodeBuffer.d.ts +20 -0
- package/dist/utils/ComfyColors.d.cts +14 -0
- package/dist/utils/ComfyColors.d.ts +14 -0
- package/dist/utils/ansi.d.cts +22 -0
- package/dist/utils/ansi.d.ts +22 -0
- package/dist/utils/bang.d.cts +9 -0
- package/dist/utils/bang.d.ts +9 -0
- package/dist/utils/deepCopyNaive.d.cts +1 -0
- package/dist/utils/deepCopyNaive.d.ts +1 -0
- package/dist/utils/downloadFile.d.cts +2 -0
- package/dist/utils/downloadFile.d.ts +2 -0
- package/dist/utils/escapeJSKey.d.cts +2 -0
- package/dist/utils/escapeJSKey.d.ts +2 -0
- package/dist/utils/exhaust.d.cts +1 -0
- package/dist/utils/exhaust.d.ts +1 -0
- package/dist/utils/extractErrorMessage.d.cts +2 -0
- package/dist/utils/extractErrorMessage.d.ts +2 -0
- package/dist/utils/githubRegexes.d.cts +2 -0
- package/dist/utils/githubRegexes.d.ts +2 -0
- package/dist/utils/hashArrayBuffer.d.cts +1 -0
- package/dist/utils/hashArrayBuffer.d.ts +1 -0
- package/dist/utils/isRecord.d.cts +2 -0
- package/dist/utils/isRecord.d.ts +2 -0
- package/dist/utils/lazySharp.d.cts +3 -0
- package/dist/utils/lazySharp.d.ts +3 -0
- package/dist/utils/log.d.cts +4 -0
- package/dist/utils/log.d.ts +4 -0
- package/dist/utils/loraTag.d.cts +8 -0
- package/dist/utils/loraTag.d.ts +8 -0
- package/dist/utils/matchesRegex.d.cts +2 -0
- package/dist/utils/matchesRegex.d.ts +2 -0
- package/dist/utils/printArkResultInConsole.d.cts +2 -0
- package/dist/utils/printArkResultInConsole.d.ts +2 -0
- package/dist/utils/safeName.d.cts +6 -0
- package/dist/utils/safeName.d.ts +6 -0
- package/dist/utils/sha1.d.cts +2 -0
- package/dist/utils/sha1.d.ts +2 -0
- package/dist/utils/softValidate.d.cts +2 -0
- package/dist/utils/softValidate.d.ts +2 -0
- package/dist/utils/stringifyReadable.d.cts +1 -0
- package/dist/utils/stringifyReadable.d.ts +1 -0
- package/dist/utils/toposort.d.cts +3 -0
- package/dist/utils/toposort.d.ts +3 -0
- package/dist/vars/ComfyVars.d.cts +607 -0
- package/dist/vars/ComfyVars.d.ts +607 -0
- package/dist/vars/DefinedWorkflow.d.cts +104 -0
- package/dist/vars/DefinedWorkflow.d.ts +104 -0
- package/dist/vars/lanes.d.cts +81 -0
- package/dist/vars/lanes.d.ts +81 -0
- package/dist/vars/loraEntry.d.cts +26 -0
- package/dist/vars/loraEntry.d.ts +26 -0
- package/dist/vars/loraKeywords.d.cts +19 -0
- package/dist/vars/loraKeywords.d.ts +19 -0
- package/dist/vars/outputWidgets.d.cts +33 -0
- package/dist/vars/outputWidgets.d.ts +33 -0
- package/dist/vars/presets.d.cts +9 -0
- package/dist/vars/presets.d.ts +9 -0
- package/dist/vars/promptSyntax.d.cts +98 -0
- package/dist/vars/promptSyntax.d.ts +98 -0
- package/dist/web.d.cts +2 -0
- package/dist/web.d.ts +2 -19160
- package/dist/web.js +8040 -8292
- package/dist/web.js.map +119 -1
- package/examples/depth-explorer/web/tsconfig.json +1 -2
- package/examples/upscale-explorer/web/tsconfig.json +1 -2
- package/examples/web/tsconfig.json +1 -4
- package/examples/world-explorer/web/tsconfig.json +1 -2
- package/package.json +27 -32
- package/src/cli/serve/web/components/SideMenu.tsx +1 -1
- package/src/cli/serve/web/components/controls/LorasControl.tsx +2 -0
- package/src/cli/serve/web/components/controls/RichSelect.tsx +1 -0
- package/src/cli/serve/web/state/RunSt.poll.test.ts +2 -1
- package/src/cli/serve/web/tsconfig.json +1 -2
- package/src/cli/serve/web/widgets/RelightWidget.tsx +1 -0
- package/src/cli/tui/state/HostSt.ts +1 -1
- package/src/host/loraManagerApi.ts +8 -3
- package/src/runner/ComfyExecution.ts +3 -1
- package/src/runner/ComfyWsApi.ts +2 -1
- package/src/storage/ComfyStorage.ts +5 -4
- package/src/types/comfy-sdk.ts +1 -0
- package/src/utils/ansi.ts +1 -0
- package/dist/ServeApp-fsHtW5zG.js +0 -2689
- package/dist/ServeApp-fsHtW5zG.js.map +0 -1
- package/dist/exampleAssets-DZynSkZm.js +0 -6674
- package/dist/exampleAssets-DZynSkZm.js.map +0 -1
- package/dist/findDefinedWorkflow-qyqFea7q.js +0 -625
- package/dist/findDefinedWorkflow-qyqFea7q.js.map +0 -1
- package/dist/run-run-Cn2JzKlE.js +0 -449
- package/dist/run-run-Cn2JzKlE.js.map +0 -1
- package/dist/run-serve-BhGegaCI.js +0 -464
- package/dist/run-serve-BhGegaCI.js.map +0 -1
- package/dist/run-tui-CrM4ijkH.js +0 -4569
- package/dist/run-tui-CrM4ijkH.js.map +0 -1
- package/dist/schemaDrift-BGYJZGMD.js +0 -2225
- package/dist/schemaDrift-BGYJZGMD.js.map +0 -1
|
@@ -0,0 +1,2593 @@
|
|
|
1
|
+
import {
|
|
2
|
+
extractErrorMessage,
|
|
3
|
+
sha1HexOfString,
|
|
4
|
+
statelessRegex,
|
|
5
|
+
bang,
|
|
6
|
+
importSharp,
|
|
7
|
+
MEDIA_KINDS,
|
|
8
|
+
DEFAULT_MEDIA_EXTENSIONS,
|
|
9
|
+
MODEL_3D_MIMES,
|
|
10
|
+
ansi,
|
|
11
|
+
lmFolder,
|
|
12
|
+
lmBaseModel,
|
|
13
|
+
lmSha256,
|
|
14
|
+
lmFileSize,
|
|
15
|
+
lmNotes,
|
|
16
|
+
lmCivitai,
|
|
17
|
+
lmTags,
|
|
18
|
+
lmFilePath,
|
|
19
|
+
loraKey,
|
|
20
|
+
fetchLoraCivitai,
|
|
21
|
+
fetchLoraDescription,
|
|
22
|
+
fetchLoraExampleImages,
|
|
23
|
+
fetchLoraList,
|
|
24
|
+
loraPreviewMapFrom,
|
|
25
|
+
fetchLoraPreviewBytes,
|
|
26
|
+
buildLoraMirror,
|
|
27
|
+
writeLoraMirror,
|
|
28
|
+
refreshLoraInfoCacheIfChanged,
|
|
29
|
+
reloadLoraInfoCache,
|
|
30
|
+
getLoraInfo,
|
|
31
|
+
getLoraTriggerWords,
|
|
32
|
+
getLoraDisplayName,
|
|
33
|
+
getLoraTriggers,
|
|
34
|
+
recordCivitaiMiss,
|
|
35
|
+
getLoraAddedAt,
|
|
36
|
+
getLoraPreviewUrl,
|
|
37
|
+
loraMirrorEntries,
|
|
38
|
+
lorasMissingFromMirror,
|
|
39
|
+
getLoraKeyword,
|
|
40
|
+
isLoraStrength,
|
|
41
|
+
isPromptInput,
|
|
42
|
+
isLoraLanes,
|
|
43
|
+
isLorasInput,
|
|
44
|
+
driftChanged,
|
|
45
|
+
summarizeDrift
|
|
46
|
+
} from "./chunk-6tsg7fm5.js";
|
|
47
|
+
import {
|
|
48
|
+
ENHANCE_KEY,
|
|
49
|
+
isDraftMetaKey,
|
|
50
|
+
assembleLogChunks,
|
|
51
|
+
draftsDirForFile,
|
|
52
|
+
listDraftsForFile
|
|
53
|
+
} from "./chunk-6mgjbrp6.js";
|
|
54
|
+
|
|
55
|
+
// src/cli/serve/describeVar.ts
|
|
56
|
+
function presetsOrUndefined(presets) {
|
|
57
|
+
return presets.length === 0 ? undefined : presets;
|
|
58
|
+
}
|
|
59
|
+
function rangeText(opts) {
|
|
60
|
+
if (opts.min == null && opts.max == null)
|
|
61
|
+
return "";
|
|
62
|
+
return ` (${opts.min ?? "-∞"}..${opts.max ?? "∞"})`;
|
|
63
|
+
}
|
|
64
|
+
function describeVar(varDef) {
|
|
65
|
+
const base = {
|
|
66
|
+
kind: varDef.kind,
|
|
67
|
+
label: varDef.label,
|
|
68
|
+
default: varDef.defaultValue,
|
|
69
|
+
...Object.keys(varDef.uiOpts).length > 0 ? { ui: varDef.uiOpts } : {}
|
|
70
|
+
};
|
|
71
|
+
switch (varDef.kind) {
|
|
72
|
+
case "prompt": {
|
|
73
|
+
const v = varDef;
|
|
74
|
+
return {
|
|
75
|
+
...base,
|
|
76
|
+
payload: 'string ("//" starts a comment, "- " lines = negative)',
|
|
77
|
+
textPresets: presetsOrUndefined(v.presets),
|
|
78
|
+
tags: v.tags == null ? undefined : { underscores: v.tags.underscores === true, artistPrefix: v.tags.artistPrefix },
|
|
79
|
+
weights: v.promptOpts.weights === false ? false : undefined
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
case "text": {
|
|
83
|
+
const v = varDef;
|
|
84
|
+
return { ...base, payload: "string", multiline: v.opts.multiline, textPresets: presetsOrUndefined(v.presets) };
|
|
85
|
+
}
|
|
86
|
+
case "int": {
|
|
87
|
+
const v = varDef;
|
|
88
|
+
return { ...base, payload: `integer${rangeText(v.opts)}`, min: v.opts.min, max: v.opts.max };
|
|
89
|
+
}
|
|
90
|
+
case "float": {
|
|
91
|
+
const v = varDef;
|
|
92
|
+
return { ...base, payload: `number${rangeText(v.opts)}`, min: v.opts.min, max: v.opts.max };
|
|
93
|
+
}
|
|
94
|
+
case "seed": {
|
|
95
|
+
const v = varDef;
|
|
96
|
+
return {
|
|
97
|
+
...base,
|
|
98
|
+
default: { mode: v.defaultMode, value: v.defaultValue },
|
|
99
|
+
payload: 'number (fixed) or {"mode":"=|+|-|?","value":number}'
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
case "toggle":
|
|
103
|
+
return { ...base, payload: "true or false" };
|
|
104
|
+
case "choice": {
|
|
105
|
+
const v = varDef;
|
|
106
|
+
const list = v.choices.join(" | ");
|
|
107
|
+
const payload = v.select === "many" ? `a list of: ${list}` : v.select === "zero-or-one" ? `null or one of: ${list}` : `one of: ${list}`;
|
|
108
|
+
return { ...base, payload, choices: v.choices, select: v.select };
|
|
109
|
+
}
|
|
110
|
+
case "loras": {
|
|
111
|
+
const v = varDef;
|
|
112
|
+
return {
|
|
113
|
+
...base,
|
|
114
|
+
payload: '{"<lora name>": false | true | strength | [model, clip]}',
|
|
115
|
+
options: v.options,
|
|
116
|
+
optionsFilter: v.optionsFilter == null ? undefined : String(v.optionsFilter)
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
case "size": {
|
|
120
|
+
const v = varDef;
|
|
121
|
+
return {
|
|
122
|
+
...base,
|
|
123
|
+
payload: '{"width":W,"height":H} or "WxH" or a preset label',
|
|
124
|
+
presets: v.presets,
|
|
125
|
+
starredPresets: [...v.starred]
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
case "image":
|
|
129
|
+
case "audio":
|
|
130
|
+
case "video": {
|
|
131
|
+
const v = varDef;
|
|
132
|
+
const presets = v.presets;
|
|
133
|
+
return {
|
|
134
|
+
...base,
|
|
135
|
+
payload: "local file path or http(s) url",
|
|
136
|
+
extensions: v.extensions,
|
|
137
|
+
...presets.length > 0 ? { mediaPresets: presets } : {}
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
default: {
|
|
141
|
+
const unknownKind = varDef.kind;
|
|
142
|
+
return { ...base, payload: `string (unrecognised kind '${String(unknownKind)}')` };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function renderDescriptorLine(name, d, nameWidth, color = false) {
|
|
147
|
+
const def = typeof d.default === "string" ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default);
|
|
148
|
+
const cells = { name: name.padEnd(nameWidth), kind: d.kind.padEnd(6), value: truncate(def ?? "null", 60) };
|
|
149
|
+
if (!color)
|
|
150
|
+
return ` ${cells.name} ${cells.kind} ${d.payload} · default: ${cells.value}`;
|
|
151
|
+
return ` ${ansi.bold(cells.name)} ${ansi.yellow(cells.kind)} ${ansi.gray(d.payload)} ${ansi.gray("· default:")} ${cells.value}`;
|
|
152
|
+
}
|
|
153
|
+
function truncate(s, n) {
|
|
154
|
+
return s.length <= n ? s : s.slice(0, n - 1) + "…";
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/cli/serve/ServeApp.ts
|
|
158
|
+
import {
|
|
159
|
+
closeSync,
|
|
160
|
+
existsSync as existsSync6,
|
|
161
|
+
mkdirSync as mkdirSync5,
|
|
162
|
+
openSync,
|
|
163
|
+
readFileSync as readFileSync5,
|
|
164
|
+
readSync,
|
|
165
|
+
realpathSync,
|
|
166
|
+
rmSync as rmSync3,
|
|
167
|
+
statSync as statSync3,
|
|
168
|
+
writeFileSync as writeFileSync5
|
|
169
|
+
} from "node:fs";
|
|
170
|
+
import { createHash } from "node:crypto";
|
|
171
|
+
import { nanoid } from "nanoid";
|
|
172
|
+
import { basename, dirname as dirname3, extname, isAbsolute as isAbsolute2, join as join4, resolve as resolve3 } from "pathe";
|
|
173
|
+
|
|
174
|
+
// src/cli/serve/thumbs.ts
|
|
175
|
+
import { existsSync, statSync } from "node:fs";
|
|
176
|
+
import { resolve } from "pathe";
|
|
177
|
+
var isHttpUrl = (s) => /^https?:\/\//i.test(s);
|
|
178
|
+
function thumbUrl(abs, width = 160) {
|
|
179
|
+
return `/thumb?src=${encodeURIComponent(abs)}&w=${width}`;
|
|
180
|
+
}
|
|
181
|
+
async function webpThumb(path, width) {
|
|
182
|
+
if (typeof Bun !== "undefined")
|
|
183
|
+
return new Bun.Image(path).resize(width, width, { fit: "inside", withoutEnlargement: true }).webp({ quality: 78 }).bytes();
|
|
184
|
+
const sharp = await importSharp("a thumbnail");
|
|
185
|
+
return new Uint8Array(await sharp(path).rotate().resize({ width, height: width, fit: "inside", withoutEnlargement: true }).webp({ quality: 78 }).toBuffer());
|
|
186
|
+
}
|
|
187
|
+
var MAX_WIDTH = 640;
|
|
188
|
+
var MAX_CACHED = 400;
|
|
189
|
+
|
|
190
|
+
class ThumbStore {
|
|
191
|
+
allowed = new Set;
|
|
192
|
+
roots = new Set;
|
|
193
|
+
cache = new Map;
|
|
194
|
+
allow(abs) {
|
|
195
|
+
this.allowed.add(resolve(abs));
|
|
196
|
+
}
|
|
197
|
+
allowRoot(dir) {
|
|
198
|
+
this.roots.add(resolve(dir));
|
|
199
|
+
}
|
|
200
|
+
isAllowed(abs) {
|
|
201
|
+
const p = resolve(abs);
|
|
202
|
+
if (this.allowed.has(p))
|
|
203
|
+
return true;
|
|
204
|
+
for (const root of this.roots)
|
|
205
|
+
if (p.startsWith(`${root}/`))
|
|
206
|
+
return true;
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
async render(abs, width) {
|
|
210
|
+
if (!this.isAllowed(abs))
|
|
211
|
+
return "forbidden";
|
|
212
|
+
const p = resolve(abs);
|
|
213
|
+
if (!existsSync(p))
|
|
214
|
+
return "missing";
|
|
215
|
+
const w = Math.max(16, Math.min(MAX_WIDTH, Math.round(width)));
|
|
216
|
+
const key = `${p}|${statSync(p).mtimeMs}|${w}`;
|
|
217
|
+
const hit = this.cache.get(key);
|
|
218
|
+
if (hit != null)
|
|
219
|
+
return hit;
|
|
220
|
+
const bytes = await webpThumb(p, w);
|
|
221
|
+
if (this.cache.size >= MAX_CACHED) {
|
|
222
|
+
const oldest = this.cache.keys().next().value;
|
|
223
|
+
if (oldest != null)
|
|
224
|
+
this.cache.delete(oldest);
|
|
225
|
+
}
|
|
226
|
+
this.cache.set(key, bytes);
|
|
227
|
+
return bytes;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// src/cli/serve/applyVarPayload.ts
|
|
232
|
+
function isFiniteNumber(x) {
|
|
233
|
+
return typeof x === "number" && Number.isFinite(x);
|
|
234
|
+
}
|
|
235
|
+
function listSome(items, cap = 20) {
|
|
236
|
+
if (items.length <= cap)
|
|
237
|
+
return items.join(", ");
|
|
238
|
+
return `${items.slice(0, cap).join(", ")} … +${items.length - cap} more`;
|
|
239
|
+
}
|
|
240
|
+
function applyVarPayload(varDef, raw, opts = {}) {
|
|
241
|
+
const name = varDef.name ?? varDef.label ?? varDef.kind;
|
|
242
|
+
switch (varDef.kind) {
|
|
243
|
+
case "text": {
|
|
244
|
+
if (typeof raw !== "string")
|
|
245
|
+
return `var '${name}' expects a string`;
|
|
246
|
+
varDef.set(raw);
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
case "prompt": {
|
|
250
|
+
if (!isPromptInput(raw))
|
|
251
|
+
return `var '${name}' expects a string or {"lanes": [{"name": string, "prompt": string, "active": boolean}]}`;
|
|
252
|
+
varDef.set(raw);
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
case "int":
|
|
256
|
+
case "float": {
|
|
257
|
+
const v = varDef;
|
|
258
|
+
if (isFiniteNumber(raw)) {
|
|
259
|
+
v.set(raw);
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
if (typeof raw === "string" && v.parse(raw))
|
|
263
|
+
return null;
|
|
264
|
+
const o = v.opts;
|
|
265
|
+
const range = o.min == null && o.max == null ? "" : ` (${o.min ?? "-∞"}..${o.max ?? "∞"})`;
|
|
266
|
+
return `var '${name}' expects a number${range}`;
|
|
267
|
+
}
|
|
268
|
+
case "seed": {
|
|
269
|
+
const v = varDef;
|
|
270
|
+
if (isFiniteNumber(raw)) {
|
|
271
|
+
v.setMode("=");
|
|
272
|
+
v.set(raw);
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
276
|
+
const o = raw;
|
|
277
|
+
const mode = o.mode === "=" || o.mode === "+" || o.mode === "-" || o.mode === "?" ? o.mode : null;
|
|
278
|
+
if (o.mode !== undefined && mode == null)
|
|
279
|
+
return `var '${name}': mode must be one of = + - ?`;
|
|
280
|
+
if (o.value !== undefined && !isFiniteNumber(o.value))
|
|
281
|
+
return `var '${name}': value must be a number`;
|
|
282
|
+
if (mode == null && o.value === undefined)
|
|
283
|
+
return `var '${name}': give "mode" and/or "value"`;
|
|
284
|
+
if (mode != null)
|
|
285
|
+
v.setMode(mode);
|
|
286
|
+
if (isFiniteNumber(o.value))
|
|
287
|
+
v.set(o.value);
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
return `var '${name}' expects a number or {"mode":"=|+|-|?","value":number}`;
|
|
291
|
+
}
|
|
292
|
+
case "toggle": {
|
|
293
|
+
if (typeof raw !== "boolean")
|
|
294
|
+
return `var '${name}' expects true or false`;
|
|
295
|
+
varDef.set(raw);
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
case "choice": {
|
|
299
|
+
const v = varDef;
|
|
300
|
+
const known = (x) => typeof x === "string" && v.choices.includes(x);
|
|
301
|
+
if (v.select === "many") {
|
|
302
|
+
if (known(raw)) {
|
|
303
|
+
v.set([raw]);
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
if (Array.isArray(raw) && raw.every(known)) {
|
|
307
|
+
v.set(v.choices.filter((c) => raw.includes(c)));
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
return `var '${name}' expects a list of: ${listSome(v.choices)}`;
|
|
311
|
+
}
|
|
312
|
+
if (v.select === "zero-or-one") {
|
|
313
|
+
if (raw === null || known(raw)) {
|
|
314
|
+
v.set(raw);
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
return `var '${name}' expects null or one of: ${listSome(v.choices)}`;
|
|
318
|
+
}
|
|
319
|
+
if (known(raw)) {
|
|
320
|
+
v.set(raw);
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
return `var '${name}' expects one of: ${listSome(v.choices)}`;
|
|
324
|
+
}
|
|
325
|
+
case "loras": {
|
|
326
|
+
const v = varDef;
|
|
327
|
+
const SHAPE = `{"<lora name>": false | true | strength | [model, clip] | {strength, off?, mute?}} or {"lanes": [{"name", "active", "loras": {…}}]}`;
|
|
328
|
+
if (raw == null || typeof raw !== "object" || Array.isArray(raw))
|
|
329
|
+
return `var '${name}' expects ${SHAPE}`;
|
|
330
|
+
const records = isLoraLanes(raw) ? raw.lanes.map((l) => l.loras) : [raw];
|
|
331
|
+
const known = new Set([...v.options, ...opts.extraLoraOptions ?? []]);
|
|
332
|
+
for (const record of records) {
|
|
333
|
+
const unknownNames = Object.keys(record).filter((k) => !known.has(k));
|
|
334
|
+
if (unknownNames.length > 0)
|
|
335
|
+
return `var '${name}': unknown lora(s) ${unknownNames.join(", ")} — available: ${listSome([...known])}`;
|
|
336
|
+
for (const [k, st] of Object.entries(record))
|
|
337
|
+
if (!isLoraStrength(st))
|
|
338
|
+
return `var '${name}': '${k}' must be false | true | number | [model, clip] | { strength: [model, clip], off?, mute? }`;
|
|
339
|
+
}
|
|
340
|
+
if (!isLorasInput(raw))
|
|
341
|
+
return `var '${name}' expects ${SHAPE}`;
|
|
342
|
+
v.set(raw);
|
|
343
|
+
return null;
|
|
344
|
+
}
|
|
345
|
+
case "size": {
|
|
346
|
+
const v = varDef;
|
|
347
|
+
if (typeof raw === "string" && v.parse(raw))
|
|
348
|
+
return null;
|
|
349
|
+
if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
350
|
+
const o = raw;
|
|
351
|
+
if (isFiniteNumber(o.width) && isFiniteNumber(o.height)) {
|
|
352
|
+
v.set({ width: o.width, height: o.height });
|
|
353
|
+
return null;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`;
|
|
357
|
+
}
|
|
358
|
+
case "image":
|
|
359
|
+
case "audio":
|
|
360
|
+
case "video": {
|
|
361
|
+
if (typeof raw !== "string")
|
|
362
|
+
return `var '${name}' expects a file path or http(s) url string`;
|
|
363
|
+
varDef.set(raw);
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
default: {
|
|
367
|
+
const unknownKind = varDef.kind;
|
|
368
|
+
return `var '${name}' has unsupported kind '${String(unknownKind)}'`;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// src/promptEnhancers.ts
|
|
374
|
+
import { existsSync as existsSync2, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
375
|
+
import { join } from "pathe";
|
|
376
|
+
|
|
377
|
+
// src/utils/safeName.ts
|
|
378
|
+
function validStoreName(raw) {
|
|
379
|
+
const name = raw.trim();
|
|
380
|
+
if (name.length > 100)
|
|
381
|
+
return null;
|
|
382
|
+
return /^[\w][\w .-]*$/.test(name) ? name : null;
|
|
383
|
+
}
|
|
384
|
+
function validSavePrefix(raw) {
|
|
385
|
+
const clean = raw.trim().replaceAll("\\", "/");
|
|
386
|
+
if (clean === "")
|
|
387
|
+
return "";
|
|
388
|
+
if (clean.startsWith("/") || /^[a-z]:/i.test(clean))
|
|
389
|
+
return null;
|
|
390
|
+
if (clean.length > 200)
|
|
391
|
+
return null;
|
|
392
|
+
const segments = clean.split("/").filter((s) => s !== "");
|
|
393
|
+
if (segments.length === 0 || segments.some((s) => validStoreName(s) == null))
|
|
394
|
+
return null;
|
|
395
|
+
return segments.join("/");
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// src/promptEnhancers.ts
|
|
399
|
+
var EXT = ".md";
|
|
400
|
+
function promptEnhancersDir() {
|
|
401
|
+
return comfyts.resolveFromPromptEnhancers("");
|
|
402
|
+
}
|
|
403
|
+
function promptEnhancerPath(name) {
|
|
404
|
+
const safe = validStoreName(name);
|
|
405
|
+
return safe == null ? null : join(promptEnhancersDir(), `${safe}${EXT}`);
|
|
406
|
+
}
|
|
407
|
+
var SEED = {
|
|
408
|
+
name: "refine-krea2-prompt",
|
|
409
|
+
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.
|
|
410
|
+
|
|
411
|
+
Rewrite it into ONE paragraph a reader could picture with their eyes closed:
|
|
412
|
+
|
|
413
|
+
- 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.
|
|
414
|
+
- 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).
|
|
415
|
+
- 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.
|
|
416
|
+
- 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.
|
|
417
|
+
- an input that is already dense gets polished and finished, not inflated. Keep its phrasing and its direction, add only what is genuinely missing.
|
|
418
|
+
- 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.
|
|
419
|
+
- text that must appear inside the image is spelled out in "quotes", exactly as it should be rendered.
|
|
420
|
+
- roughly 60 to 150 words, one paragraph, no lists, no headings, no quotes around the result itself.
|
|
421
|
+
- never write a negative ("- ...") line or a comment ("// ...") line: the panel keeps the user's own and adds them back after your prompt.
|
|
422
|
+
|
|
423
|
+
Answer with the rewritten prompt and nothing else: no preamble, no explanation.
|
|
424
|
+
`
|
|
425
|
+
};
|
|
426
|
+
function listPromptEnhancers() {
|
|
427
|
+
if (!existsSync2(promptEnhancersDir()))
|
|
428
|
+
writePromptEnhancer(SEED.name, SEED.text);
|
|
429
|
+
return readPromptEnhancers();
|
|
430
|
+
}
|
|
431
|
+
function readPromptEnhancers() {
|
|
432
|
+
const dir = promptEnhancersDir();
|
|
433
|
+
if (!existsSync2(dir))
|
|
434
|
+
return [];
|
|
435
|
+
const out = [];
|
|
436
|
+
for (const file of readdirSync(dir).sort()) {
|
|
437
|
+
if (!file.endsWith(EXT))
|
|
438
|
+
continue;
|
|
439
|
+
const name = file.slice(0, -EXT.length);
|
|
440
|
+
if (validStoreName(name) == null)
|
|
441
|
+
continue;
|
|
442
|
+
try {
|
|
443
|
+
out.push({ name, text: readFileSync(join(dir, file), "utf8") });
|
|
444
|
+
} catch (e) {
|
|
445
|
+
console.error(`[serve] prompt enhancer '${name}' unreadable, skipped:`, e);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return out;
|
|
449
|
+
}
|
|
450
|
+
function writePromptEnhancer(name, text) {
|
|
451
|
+
const path = promptEnhancerPath(name);
|
|
452
|
+
if (path == null)
|
|
453
|
+
return null;
|
|
454
|
+
mkdirSync(promptEnhancersDir(), { recursive: true });
|
|
455
|
+
writeFileSync(path, text);
|
|
456
|
+
return path;
|
|
457
|
+
}
|
|
458
|
+
function deletePromptEnhancer(name) {
|
|
459
|
+
const path = promptEnhancerPath(name);
|
|
460
|
+
if (path == null)
|
|
461
|
+
return false;
|
|
462
|
+
if (existsSync2(path))
|
|
463
|
+
rmSync(path);
|
|
464
|
+
return true;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// src/cli/serve/llmConfigs.ts
|
|
468
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
469
|
+
import { join as join2 } from "pathe";
|
|
470
|
+
|
|
471
|
+
// src/cli/serve/web/llm.ts
|
|
472
|
+
var OPENROUTER_BASE = "https://openrouter.ai/api/v1";
|
|
473
|
+
var OPENWEBUI_BASE = "http://localhost:3000";
|
|
474
|
+
var OPENAI_COMPAT_BASE = "http://localhost:8080/v1";
|
|
475
|
+
function defaultBaseUrl(provider) {
|
|
476
|
+
if (provider === "openrouter")
|
|
477
|
+
return OPENROUTER_BASE;
|
|
478
|
+
return provider === "openwebui" ? OPENWEBUI_BASE : OPENAI_COMPAT_BASE;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// src/cli/serve/llmConfigShape.ts
|
|
482
|
+
function isProvider(raw) {
|
|
483
|
+
return raw === "openrouter" || raw === "openwebui" || raw === "openai";
|
|
484
|
+
}
|
|
485
|
+
function isEffort(raw) {
|
|
486
|
+
return raw === "off" || raw === "low" || raw === "medium" || raw === "high";
|
|
487
|
+
}
|
|
488
|
+
var DEFAULT_MODEL = {
|
|
489
|
+
openrouter: "anthropic/claude-sonnet-5",
|
|
490
|
+
openwebui: "",
|
|
491
|
+
openai: ""
|
|
492
|
+
};
|
|
493
|
+
function normalizeLlmConfig(raw) {
|
|
494
|
+
const o = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : {};
|
|
495
|
+
const provider = isProvider(o.provider) ? o.provider : "openrouter";
|
|
496
|
+
return {
|
|
497
|
+
provider,
|
|
498
|
+
baseUrl: typeof o.baseUrl === "string" && o.baseUrl.trim() !== "" ? o.baseUrl.trim() : defaultBaseUrl(provider),
|
|
499
|
+
model: typeof o.model === "string" ? o.model : DEFAULT_MODEL[provider],
|
|
500
|
+
effort: isEffort(o.effort) ? o.effort : "medium",
|
|
501
|
+
thinkingOnly: o.thinkingOnly !== false
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// src/cli/serve/llmConfigs.ts
|
|
506
|
+
var EXT2 = ".json";
|
|
507
|
+
function llmConfigsDir() {
|
|
508
|
+
return comfyts.resolveFromLlmConfigs("");
|
|
509
|
+
}
|
|
510
|
+
function llmConfigPath(name) {
|
|
511
|
+
const safe = validStoreName(name);
|
|
512
|
+
return safe == null ? null : join2(llmConfigsDir(), `${safe}${EXT2}`);
|
|
513
|
+
}
|
|
514
|
+
function listLlmConfigs() {
|
|
515
|
+
const dir = llmConfigsDir();
|
|
516
|
+
if (!existsSync3(dir))
|
|
517
|
+
return [];
|
|
518
|
+
const out = [];
|
|
519
|
+
for (const file of readdirSync2(dir).sort()) {
|
|
520
|
+
if (!file.endsWith(EXT2))
|
|
521
|
+
continue;
|
|
522
|
+
const name = file.slice(0, -EXT2.length);
|
|
523
|
+
if (validStoreName(name) == null)
|
|
524
|
+
continue;
|
|
525
|
+
try {
|
|
526
|
+
out.push({ name, config: normalizeLlmConfig(JSON.parse(readFileSync2(join2(dir, file), "utf8"))) });
|
|
527
|
+
} catch (e) {
|
|
528
|
+
console.error(`[serve] llm config '${name}' unreadable, skipped:`, e);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return out;
|
|
532
|
+
}
|
|
533
|
+
function writeLlmConfig(name, config) {
|
|
534
|
+
const path = llmConfigPath(name);
|
|
535
|
+
if (path == null)
|
|
536
|
+
return null;
|
|
537
|
+
mkdirSync2(llmConfigsDir(), { recursive: true });
|
|
538
|
+
writeFileSync2(path, `${JSON.stringify(normalizeLlmConfig(config), null, 3)}
|
|
539
|
+
`);
|
|
540
|
+
return path;
|
|
541
|
+
}
|
|
542
|
+
function deleteLlmConfig(name) {
|
|
543
|
+
const path = llmConfigPath(name);
|
|
544
|
+
if (path == null)
|
|
545
|
+
return false;
|
|
546
|
+
if (existsSync3(path))
|
|
547
|
+
rmSync2(path);
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// src/cli/serve/managerOnlyLoras.ts
|
|
552
|
+
function managerOnlyLoraOptions(p) {
|
|
553
|
+
const filter = p.filter == null ? null : statelessRegex(p.filter);
|
|
554
|
+
const known = new Set(p.options.map((o) => loraKey(o)));
|
|
555
|
+
const separator = p.options.some((o) => o.includes("\\")) ? "\\" : "/";
|
|
556
|
+
return loraMirrorEntries(p.hostId, { separator }).filter((e) => !known.has(e.key)).map((e) => e.serverName).filter((n) => filter == null || filter.test(n));
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// src/cli/serve/tagSource.ts
|
|
560
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, statSync as statSync2, writeFileSync as writeFileSync3 } from "node:fs";
|
|
561
|
+
import { homedir } from "node:os";
|
|
562
|
+
import { fileURLToPath } from "node:url";
|
|
563
|
+
import { dirname, isAbsolute, join as join3, resolve as resolve2 } from "pathe";
|
|
564
|
+
|
|
565
|
+
// src/cli/serve/tagList.ts
|
|
566
|
+
function csvFields(line) {
|
|
567
|
+
const out = [];
|
|
568
|
+
let cur = "";
|
|
569
|
+
let quoted = false;
|
|
570
|
+
for (let i = 0;i < line.length; i++) {
|
|
571
|
+
const ch = line[i];
|
|
572
|
+
if (quoted) {
|
|
573
|
+
if (ch === '"' && line[i + 1] === '"') {
|
|
574
|
+
cur += '"';
|
|
575
|
+
i++;
|
|
576
|
+
} else if (ch === '"')
|
|
577
|
+
quoted = false;
|
|
578
|
+
else
|
|
579
|
+
cur += ch;
|
|
580
|
+
} else if (ch === '"')
|
|
581
|
+
quoted = true;
|
|
582
|
+
else if (ch === ",") {
|
|
583
|
+
out.push(cur);
|
|
584
|
+
cur = "";
|
|
585
|
+
} else
|
|
586
|
+
cur += ch;
|
|
587
|
+
}
|
|
588
|
+
out.push(cur);
|
|
589
|
+
return out;
|
|
590
|
+
}
|
|
591
|
+
var intOrNull = (s) => s != null && /^\d+$/.test(s.trim()) ? Number(s) : null;
|
|
592
|
+
function parseTagList(text) {
|
|
593
|
+
const out = [];
|
|
594
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
595
|
+
const line = raw.trim();
|
|
596
|
+
if (line === "" || line.startsWith("#"))
|
|
597
|
+
continue;
|
|
598
|
+
const f = csvFields(line);
|
|
599
|
+
const name = (f[0] ?? "").trim();
|
|
600
|
+
if (name === "")
|
|
601
|
+
continue;
|
|
602
|
+
const twoCols = f.length === 2;
|
|
603
|
+
out.push({
|
|
604
|
+
name,
|
|
605
|
+
category: twoCols ? null : intOrNull(f[1]),
|
|
606
|
+
count: (twoCols ? intOrNull(f[1]) : intOrNull(f[2])) ?? 0,
|
|
607
|
+
aliases: (f[3] ?? "").split(",").map((a) => a.trim()).filter((a) => a !== "")
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
return out;
|
|
611
|
+
}
|
|
612
|
+
var key = (s) => s.trim().toLowerCase().replace(/\s+/g, "_");
|
|
613
|
+
|
|
614
|
+
class TagList {
|
|
615
|
+
entries;
|
|
616
|
+
rows;
|
|
617
|
+
constructor(entries) {
|
|
618
|
+
this.entries = entries;
|
|
619
|
+
this.rows = entries.map((e) => ({ e, name: key(e.name), aliases: e.aliases.map(key) }));
|
|
620
|
+
this.rows.sort((a, b) => b.e.count - a.e.count);
|
|
621
|
+
}
|
|
622
|
+
static parse(text) {
|
|
623
|
+
return new TagList(parseTagList(text));
|
|
624
|
+
}
|
|
625
|
+
search(query, limit = 20) {
|
|
626
|
+
const q = key(query);
|
|
627
|
+
if (q === "")
|
|
628
|
+
return [];
|
|
629
|
+
const hits = [];
|
|
630
|
+
const seen = new Set;
|
|
631
|
+
const take = (e, alias) => {
|
|
632
|
+
if (seen.has(e.name))
|
|
633
|
+
return false;
|
|
634
|
+
seen.add(e.name);
|
|
635
|
+
hits.push(alias == null ? { name: e.name, category: e.category, count: e.count } : { ...pick(e), alias });
|
|
636
|
+
return hits.length >= limit;
|
|
637
|
+
};
|
|
638
|
+
for (const r of this.rows)
|
|
639
|
+
if (r.name.startsWith(q) && take(r.e))
|
|
640
|
+
return hits;
|
|
641
|
+
for (const r of this.rows) {
|
|
642
|
+
const a = r.aliases.find((x) => x.startsWith(q));
|
|
643
|
+
if (a != null && take(r.e, a))
|
|
644
|
+
return hits;
|
|
645
|
+
}
|
|
646
|
+
for (const r of this.rows)
|
|
647
|
+
if (r.name.includes(`_${q}`) && take(r.e))
|
|
648
|
+
return hits;
|
|
649
|
+
return hits;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
var pick = (e) => ({ name: e.name, category: e.category, count: e.count });
|
|
653
|
+
|
|
654
|
+
// src/cli/serve/tagSource.ts
|
|
655
|
+
function resolveTagSource(url, moduleFile) {
|
|
656
|
+
if (/^https?:\/\//i.test(url))
|
|
657
|
+
return { kind: "http", url };
|
|
658
|
+
if (url.startsWith("file://"))
|
|
659
|
+
return { kind: "file", path: fileURLToPath(url) };
|
|
660
|
+
if (url === "~" || url.startsWith("~/"))
|
|
661
|
+
return { kind: "file", path: join3(homedir(), url.slice(1)) };
|
|
662
|
+
if (isAbsolute(url))
|
|
663
|
+
return { kind: "file", path: url };
|
|
664
|
+
return { kind: "file", path: resolve2(dirname(moduleFile), url) };
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
class TagSources {
|
|
668
|
+
p;
|
|
669
|
+
files = new Map;
|
|
670
|
+
remote = new Map;
|
|
671
|
+
constructor(p) {
|
|
672
|
+
this.p = p;
|
|
673
|
+
}
|
|
674
|
+
async load(ref) {
|
|
675
|
+
if (ref.kind === "file")
|
|
676
|
+
return this.loadFile(ref.path);
|
|
677
|
+
const hit = this.remote.get(ref.url);
|
|
678
|
+
if (hit != null)
|
|
679
|
+
return hit;
|
|
680
|
+
const pending = this.loadRemote(ref.url);
|
|
681
|
+
this.remote.set(ref.url, pending);
|
|
682
|
+
pending.catch(() => this.remote.delete(ref.url));
|
|
683
|
+
return pending;
|
|
684
|
+
}
|
|
685
|
+
loadFile(path) {
|
|
686
|
+
if (!existsSync4(path))
|
|
687
|
+
throw new Error(`tag list not found: ${path}`);
|
|
688
|
+
const mtimeMs = statSync2(path).mtimeMs;
|
|
689
|
+
const cached = this.files.get(path);
|
|
690
|
+
if (cached != null && cached.mtimeMs === mtimeMs)
|
|
691
|
+
return cached.list;
|
|
692
|
+
const list = TagList.parse(readFileSync3(path, "utf8"));
|
|
693
|
+
if (list.entries.length === 0)
|
|
694
|
+
throw new Error(`tag list is empty: ${path}`);
|
|
695
|
+
this.files.set(path, { mtimeMs, list });
|
|
696
|
+
return list;
|
|
697
|
+
}
|
|
698
|
+
async loadRemote(url) {
|
|
699
|
+
const file = join3(this.p.cacheDir(), `${sha1HexOfString(url)}.txt`);
|
|
700
|
+
if (existsSync4(file))
|
|
701
|
+
return TagList.parse(readFileSync3(file, "utf8"));
|
|
702
|
+
console.log(`[serve] fetching tag list ${url}`);
|
|
703
|
+
const text = await this.p.fetchText(url);
|
|
704
|
+
const list = TagList.parse(text);
|
|
705
|
+
if (list.entries.length === 0)
|
|
706
|
+
throw new Error(`tag list is empty: ${url}`);
|
|
707
|
+
mkdirSync3(dirname(file), { recursive: true });
|
|
708
|
+
writeFileSync3(file, text);
|
|
709
|
+
console.log(`[serve] tag list ${url}: ${list.entries.length} tags, kept in ${file}`);
|
|
710
|
+
return list;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// src/cli/serve/favicon.ts
|
|
715
|
+
var FAVICON_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAKUklEQVR42u1aaWxU1xW2DWEJZCENNgaK8iNRU5UAAYKBWW1ImwbaoqiuQkrUVlRdlDZSGpqAcTKrFyAoJRCRKmpRidKA98Sm0MQhRClOs7CIggiTtniZN4sZe8AeL/Puvef23LeMnwePQdWwhTnS9XvP8zzvft/5znfPfXJWViYykYlMZCITmchEJjKRiUxc4eCcj8ExFkfOzQg+23huvL5pwFNKf8wYexmvZ2m/H6cpQlHFV5IYIXvtaMEh4+CM83/hIS9ZGSOUSvYNnXUNyC3iGgA2KuAZ7+NqvI3jZ6iKp3GsIYQsw+sZOmFJZIy5Ec0uRzufhOMHjMGnGnAUAAdtJALUqxgwOIYs7UBCViFptycTekNkXcv4eMzsL/Hap2Pkw0MQQbTBkj/UbvDjj514ukQvh+uWCOPE8LgUpX7UAJxpY7QAzqh6b1+rzPslZuANvZMdIoR/3/CMMdfNcqqBVyZDOV+P53FV1kCNwCEFbi5uA/U2GjoI5MBsYJFPlTIBRqnxTxnAYTws056bc83VoAP3+XzjMUu7E8AZYRyIBkwreQDDuQBNlHMl7SwO5IvtIFdNAHr8GfUmhb9hJaOTKb71L7FYLN+40lwz8HicgODrtMmRlMkeIf2MxoH53wF6sAjI3vFA6/OA9ZwWAEFXRbI1aMoSdXFWlmXzNSFBb1q09bpGmxvRpU7P7AB6ZhvQ7qPA+kPA5Bhw0seY3Ass1g48/D6jp7wgN5sw65M5rbqNk6o7gDRbFVJUIUFq4phGAhfLKvmeNqexV63dNmR/hyZQYqx01lbNSP00kGvuBLnxXhhs+ibI+7/F5H3fALlhFpDaO4FU3QK0ZgqXa/G+uumM7EH5tzyh1QiDodUxlWsmlBAzKCFHm2B21pVqpAxO/Bt1AsOLVa9r2tsK5O8Pgbx3IsRr7gJScwcSMgXB5qLU84E2TMcjgq+9m+CR0KpJwA7/kCeMgolMj06CwRf+PSizXTJhf8Y/fQavc1N1munK/DwcF0YyeDV1qiDohdNAGu8TIBF4PiN1uaiMPAQ/DUhdHo6pEK/LpagWSpAcXAE4i0eHqUCQcEkvGZqDQsjeT/qPZi0+eVdCDene2OBTmgxLHb+IAM0SxJH4/ohynwRC6ghakKCBz0NScNTnIQE48DO55lYgrbvVr6CyAoxdhqnKuO7sOx6TPQ3R+GN/CA+aKy9w89Yem5hrcXHVmHRL/1GNarhUb6PcF+8C8rfZoGQYVYCAgdRPVbKvkFGfSxUS6vIJegaT92Mf0O/XyoCMaoh6C3m8dZDP39gOD6yXqGXTILe4g589/OzxSdrMs9OafTzWpcr+iFYlVHD4cYjvmYgZn0bluqlMrs0FMUh9Po+jF8j1+YzWTSNy/XRKqicD/fBRYINdWj+QmmeqOcDuf/TAvBI/FJWFwOwO1Fk2fvn1tMrfkP0ZCLx71OYuyaMUQ/zs17jOTxSARbZZvBalL4yxejKX944DuXq8MElGUAGk+nagb2YB3Xc/0NC7cKlHIQmw9vVOusgZ4csrAs8qsq8S800f+BwDASsuT/7DZUo/XoNgbwPSMFMtBQRNm+4B0rIa2KlNQFvfACY1qqPtLWA+7CE++SnQd+cCC7+n9pAouEQvCUPZP3hqkC0sDXKrR6JFXmm+mKfN8cHYtIB3OBy66+fh7u53uOae0vb17HLkr3phL7r7IrHmoxlOwPN5CHA7sL6AbnDDBhjNlA7g6OPDfgdDtR8bYPDEq520wBXhVm/wy4e3pLHu9SUP9+bfppQFjaiMk0iNX7UIFj7E4lWTUd63AzuxAWhimdPMTdkzEG1/oA1GeIpWWJW99uxtB87DnBK/XLSlVxDwmpq0NHSBuuHtbI7MiBMmac+ND8iMnuwYhM4LijsrE4GLcm7Y4QoYLY9TWj2JUalhaH2nRNn+jtblqJ8Nf3cCBuNrPjkABS9KYHJ2gMUT5uay0LK0LXs6i8srw+Z1ewd5eVOMr3urGx7bFmL4UPajV0LstBTXNuuqGgCSpyoSOQD0n08yFnpflbuyrDEY6a1Qyn7CEEQDf6JDhqKKECxxSsReHuUWT+QQTleXfXq7v7nPt5fPWe+Pzi/xxxe7OpnVE2AFpQFm9wbY20d62dBbi5RloTY06guP5DFi5kdShp75L4IEVmzthAJHAMRcrN5z3OYJP5LWpic5ntru/9qTlSdn2T2db1g39eIDA7LJJcGDJX72+z1drO2czBKvfy7yB9CrNjGM5qe1uhcN/TuMjn/k7CB8d0sYFqH0Le4AsW/u59ay0C5VtldqByi+WFsNbI72e23l0U5LWYSb3BKzugMwfyM2IOUB9sqBKAS6yTAnFxMXylCzOqyoRx3iXtz4c0L1P+PQdKwf1Sdh5hG8J0gs3m5u84Z9RWX/yUt7zz+CK2Yv+MXnyituuye41o4qMLkDFLsuZvMGweQKwtwNHbCsMsDKG6PsWBu+4UkycUGEAESTMs5GaHXVclIJO9/PwNsQhQWlaHhuAd5PLe4wWMvO9Vsc/7VeUeknh/4gm0tyFiIJZk+ImjEbZiQAywKWuPwwDxWx2CnBT14Lw58+7IGT/kGQaQqZM5UQNnLNw/4T/cJ44cGN6PQI3uTyM3wes1Vg9j3S6qGu7yqGTkKhq3WdvaKbmcu7uXDjpS6JCV+we0NgcQVgYWkA5pZICimrXw1DxTtRaDwaA18wDtjAsCQlGI0PPjozwH7++jnMekBZ6qweobIANXk6qb0iys3O1t9eE/AJErQH2zz+5ejAPmFGZndQEEBMeMTdmDApEOWBZaKAmLtBggUvIBi8XrklwNYiwOf3RMBV2wU73zsPcTLU8D21qxPuX9cGdqx5QSZ+JzF7z4HVG6EWl/9XaW13/09TyNZJWFHRNsXqkjZbPKE+++YYt3g7ccIBQQQ1aUQIEnDJQkLw3BmEpQ4/PFTqR2n7YfZz7XjeAYGonNDAX1su4ArTgWQpqiK2ivPY6ESiZkf7qusAvFEKSIK2/FjdHfcVYjuKkz5vq8SlUkwagSMAWRAiDNPsEhmVQBwFIVbF1ERtS9Di60+URPOpPrbwhQ6KpLJCQaoz8LnV3f7ANZX9qMtk8dD20+bwzbS7pOfMLv8RYVjWTQgAuzU0TI51jCRgD+EOyiYPkuLCFxi4muAKQkUp6AQ0Hu2nC51daHTBHqsr8OJKh3Tr9Qk+qX0uLh6aoDBLe3lHgd3d4UEgLWaPFLOWR3jhSwNclIoNX1tZUSXWcjyWdfECp8T2fNyDBknJ02/G+JySYH3xjrPT9O92OG6Q/yxRiEh6ISE2V49U+mYWlUmrcLkstTtbd1md/ibcwX2EajiEBnrMVBbBDs8vF3oCAyYkBZe6NQqRDj4u6wb9X4FsoQjVsFIA4HrZ8LHY1TUXbiXcUtHHbeWRTpvj7D1XvsO7qspw5NhsH4wVYB3KuwYNmAZw5UvS3bh8brW4gvvRKL/zlQKfSiEqCcaR/HnWzfWfZMX6snq1evtMZCITmchEJjKRiUxkIhM3ZfwPK9dyLD4coj4AAAAASUVORK5CYII=";
|
|
716
|
+
|
|
717
|
+
// src/cli/serve/workflowTags.ts
|
|
718
|
+
var MEDIA_BY_TYPE = { IMAGE: "image", AUDIO: "audio", VIDEO: "video", STRING: "text" };
|
|
719
|
+
var MEDIA_ORDER = ["image", "audio", "video", "text"];
|
|
720
|
+
function workflowTags(p) {
|
|
721
|
+
const byId = new Map(p.nodes.map((n) => [n.id, n]));
|
|
722
|
+
const media = new Set;
|
|
723
|
+
for (const node of p.nodes) {
|
|
724
|
+
if (!node.outputNode)
|
|
725
|
+
continue;
|
|
726
|
+
for (const [producerId, ix] of node.links) {
|
|
727
|
+
const type = byId.get(producerId)?.outputTypes[ix];
|
|
728
|
+
const tag = type == null ? undefined : MEDIA_BY_TYPE[type];
|
|
729
|
+
if (tag != null)
|
|
730
|
+
media.add(tag);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
const out = MEDIA_ORDER.filter((t) => media.has(t));
|
|
734
|
+
if (p.nodes.some((n) => /textgenerate/i.test(n.classType)))
|
|
735
|
+
out.push("llm");
|
|
736
|
+
if (p.varKinds.includes("image"))
|
|
737
|
+
out.push("edit");
|
|
738
|
+
for (const tag of p.extra ?? []) {
|
|
739
|
+
const t = tag.trim().toLowerCase();
|
|
740
|
+
if (t !== "" && !out.includes(t))
|
|
741
|
+
out.push(t);
|
|
742
|
+
}
|
|
743
|
+
return out;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// src/cli/serve/workspaceLabels.ts
|
|
747
|
+
function tilde(path, home) {
|
|
748
|
+
if (home === "" || home === "/")
|
|
749
|
+
return path;
|
|
750
|
+
if (path === home)
|
|
751
|
+
return "~";
|
|
752
|
+
return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
|
|
753
|
+
}
|
|
754
|
+
function workspaceLabels(p) {
|
|
755
|
+
const ws = p.workspace.replace(/\/+$/, "");
|
|
756
|
+
const root = p.root.replace(/\/+$/, "");
|
|
757
|
+
const rootLabel = root === ws ? "." : root.startsWith(`${ws}/`) ? root.slice(ws.length + 1) : tilde(root, p.home);
|
|
758
|
+
return {
|
|
759
|
+
workspace: { path: ws, label: tilde(ws, p.home) },
|
|
760
|
+
root: { path: root, label: rootLabel }
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// src/cli/serve/serveSettings.ts
|
|
765
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
|
|
766
|
+
|
|
767
|
+
// src/utils/stringMap.ts
|
|
768
|
+
function stringMap(raw) {
|
|
769
|
+
const out = {};
|
|
770
|
+
if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
|
|
771
|
+
for (const [k, v] of Object.entries(raw))
|
|
772
|
+
if (typeof v === "string")
|
|
773
|
+
out[k] = v;
|
|
774
|
+
}
|
|
775
|
+
return out;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// src/cli/serve/serveSettings.ts
|
|
779
|
+
import { dirname as dirname2 } from "pathe";
|
|
780
|
+
|
|
781
|
+
// src/cli/serve/resultHistory.ts
|
|
782
|
+
var KEPT_RUNS = 50;
|
|
783
|
+
var DEFAULT_MEMORY_BUDGET_MB = 100;
|
|
784
|
+
|
|
785
|
+
class ResultHistory {
|
|
786
|
+
budgetBytes;
|
|
787
|
+
runs = [];
|
|
788
|
+
blobs = new Map;
|
|
789
|
+
used = 0;
|
|
790
|
+
constructor(budgetBytes) {
|
|
791
|
+
this.budgetBytes = budgetBytes;
|
|
792
|
+
}
|
|
793
|
+
add(p) {
|
|
794
|
+
this.remove(p.record.promptId);
|
|
795
|
+
for (const b of p.blobs) {
|
|
796
|
+
this.blobs.set(b.key, { bytes: b.bytes, contentType: b.contentType });
|
|
797
|
+
this.used += b.bytes.byteLength;
|
|
798
|
+
}
|
|
799
|
+
const kept = {
|
|
800
|
+
record: p.record,
|
|
801
|
+
imageKeys: p.imageKeys,
|
|
802
|
+
audioKeys: p.audioKeys,
|
|
803
|
+
videoKeys: p.videoKeys ?? [],
|
|
804
|
+
model3dKeys: p.model3dKeys ?? []
|
|
805
|
+
};
|
|
806
|
+
this.runs = [kept, ...this.runs];
|
|
807
|
+
for (const dropped of this.runs.slice(KEPT_RUNS))
|
|
808
|
+
this.freeRun(dropped);
|
|
809
|
+
this.runs = this.runs.slice(0, KEPT_RUNS);
|
|
810
|
+
this.evict();
|
|
811
|
+
}
|
|
812
|
+
blob(key) {
|
|
813
|
+
return this.blobs.get(key) ?? null;
|
|
814
|
+
}
|
|
815
|
+
list() {
|
|
816
|
+
return this.runs.map((k) => ({
|
|
817
|
+
...k.record,
|
|
818
|
+
images: k.record.images.map((img, ix) => this.withLiveUrl(img, k.imageKeys[ix])),
|
|
819
|
+
audios: k.record.audios.map((a, ix) => this.withLiveUrl(a, k.audioKeys[ix])),
|
|
820
|
+
videos: (k.record.videos ?? []).map((a, ix) => this.withLiveUrl(a, k.videoKeys[ix])),
|
|
821
|
+
models3d: (k.record.models3d ?? []).map((a, ix) => this.withLiveUrl(a, k.model3dKeys[ix]))
|
|
822
|
+
}));
|
|
823
|
+
}
|
|
824
|
+
remove(promptId) {
|
|
825
|
+
const hit = this.runs.find((k) => k.record.promptId === promptId);
|
|
826
|
+
if (hit == null)
|
|
827
|
+
return;
|
|
828
|
+
this.freeRun(hit);
|
|
829
|
+
this.runs = this.runs.filter((k) => k !== hit);
|
|
830
|
+
}
|
|
831
|
+
clear() {
|
|
832
|
+
this.runs = [];
|
|
833
|
+
this.blobs.clear();
|
|
834
|
+
this.used = 0;
|
|
835
|
+
}
|
|
836
|
+
setBudget(bytes) {
|
|
837
|
+
this.budgetBytes = bytes;
|
|
838
|
+
this.evict();
|
|
839
|
+
}
|
|
840
|
+
usage() {
|
|
841
|
+
return { usedBytes: this.used, budgetBytes: this.budgetBytes, outputs: this.blobs.size, runs: this.runs.length };
|
|
842
|
+
}
|
|
843
|
+
withLiveUrl(out, key) {
|
|
844
|
+
if (key == null || this.blobs.has(key))
|
|
845
|
+
return out;
|
|
846
|
+
return { ...out, url: null };
|
|
847
|
+
}
|
|
848
|
+
freeRun(k) {
|
|
849
|
+
for (const key of [...k.imageKeys, ...k.audioKeys, ...k.videoKeys, ...k.model3dKeys]) {
|
|
850
|
+
if (key == null)
|
|
851
|
+
continue;
|
|
852
|
+
const b = this.blobs.get(key);
|
|
853
|
+
if (b == null)
|
|
854
|
+
continue;
|
|
855
|
+
this.used -= b.bytes.byteLength;
|
|
856
|
+
this.blobs.delete(key);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
evict() {
|
|
860
|
+
while (this.used > this.budgetBytes && this.blobs.size > 1) {
|
|
861
|
+
const oldest = this.blobs.entries().next();
|
|
862
|
+
if (oldest.done === true)
|
|
863
|
+
break;
|
|
864
|
+
this.used -= oldest.value[1].bytes.byteLength;
|
|
865
|
+
this.blobs.delete(oldest.value[0]);
|
|
866
|
+
}
|
|
867
|
+
this.runs = this.runs.filter((k) => {
|
|
868
|
+
const live = (keys) => keys.some((key) => key == null || this.blobs.has(key));
|
|
869
|
+
const hasText = k.record.texts.length > 0;
|
|
870
|
+
const hasNothing = k.record.images.length === 0 && k.record.audios.length === 0 && (k.record.videos ?? []).length === 0 && (k.record.models3d ?? []).length === 0;
|
|
871
|
+
return hasText || hasNothing || live(k.imageKeys) || live(k.audioKeys) || live(k.videoKeys) || live(k.model3dKeys);
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// src/cli/serve/serveSettings.ts
|
|
877
|
+
var DEFAULT_SERVE_SETTINGS = {
|
|
878
|
+
saveToDisk: true,
|
|
879
|
+
hostOverride: {},
|
|
880
|
+
savePrefix: {},
|
|
881
|
+
memoryBudgetMb: DEFAULT_MEMORY_BUDGET_MB
|
|
882
|
+
};
|
|
883
|
+
function validMemoryBudgetMb(raw) {
|
|
884
|
+
if (typeof raw !== "number" || !Number.isFinite(raw))
|
|
885
|
+
return null;
|
|
886
|
+
if (raw < 1 || raw > 1e5)
|
|
887
|
+
return null;
|
|
888
|
+
return Math.round(raw);
|
|
889
|
+
}
|
|
890
|
+
function settingsPath() {
|
|
891
|
+
const g = globalThis;
|
|
892
|
+
const path = g.comfyts?.settingsPath;
|
|
893
|
+
return typeof path === "string" ? path : null;
|
|
894
|
+
}
|
|
895
|
+
function readBlob() {
|
|
896
|
+
const path = settingsPath();
|
|
897
|
+
if (path == null || !existsSync5(path))
|
|
898
|
+
return { blob: {}, readable: true };
|
|
899
|
+
try {
|
|
900
|
+
const parsed = JSON.parse(readFileSync4(path, "utf8"));
|
|
901
|
+
const ok = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed);
|
|
902
|
+
if (!ok)
|
|
903
|
+
console.error(`[serve] settings is not an object (${path}), using defaults`);
|
|
904
|
+
return { blob: ok ? parsed : {}, readable: ok };
|
|
905
|
+
} catch (e) {
|
|
906
|
+
console.error(`[serve] settings unreadable (${path}), using defaults:`, e);
|
|
907
|
+
return { blob: {}, readable: false };
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
function cleanValues(map, clean) {
|
|
911
|
+
const out = {};
|
|
912
|
+
for (const [k, v] of Object.entries(map)) {
|
|
913
|
+
const ok = clean(v);
|
|
914
|
+
if (ok != null)
|
|
915
|
+
out[k] = ok;
|
|
916
|
+
}
|
|
917
|
+
return out;
|
|
918
|
+
}
|
|
919
|
+
function readServeSettings() {
|
|
920
|
+
const serve = readBlob().blob.serve;
|
|
921
|
+
const o = typeof serve === "object" && serve !== null ? serve : {};
|
|
922
|
+
return {
|
|
923
|
+
saveToDisk: typeof o.saveToDisk === "boolean" ? o.saveToDisk : DEFAULT_SERVE_SETTINGS.saveToDisk,
|
|
924
|
+
hostOverride: stringMap(o.hostOverride),
|
|
925
|
+
savePrefix: cleanValues(stringMap(o.savePrefix), validSavePrefix),
|
|
926
|
+
memoryBudgetMb: validMemoryBudgetMb(o.memoryBudgetMb) ?? DEFAULT_SERVE_SETTINGS.memoryBudgetMb
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
function writeServeSettings(next) {
|
|
930
|
+
const path = settingsPath();
|
|
931
|
+
if (path == null)
|
|
932
|
+
throw new Error("no comfyts instance registered — cannot persist serve settings");
|
|
933
|
+
const current = readBlob();
|
|
934
|
+
if (!current.readable)
|
|
935
|
+
throw new Error(`serve settings not saved: ${path} is not readable json. Fix or delete it — overwriting would drop the keys it still holds`);
|
|
936
|
+
mkdirSync4(dirname2(path), { recursive: true });
|
|
937
|
+
writeFileSync4(path, JSON.stringify({ ...current.blob, serve: next }, null, 2));
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// src/cli/serve/runError.ts
|
|
941
|
+
function describeRunError(error) {
|
|
942
|
+
if (error == null)
|
|
943
|
+
return "execution failed";
|
|
944
|
+
if (typeof error === "string")
|
|
945
|
+
return error;
|
|
946
|
+
if (error instanceof Error)
|
|
947
|
+
return error.message;
|
|
948
|
+
if (typeof error === "object") {
|
|
949
|
+
const data = error.data;
|
|
950
|
+
if (typeof data === "object" && data !== null) {
|
|
951
|
+
const d = data;
|
|
952
|
+
if (typeof d.exception_message === "string") {
|
|
953
|
+
const where = typeof d.node_type === "string" ? `${d.node_type} (node ${String(d.node_id)}): ` : "";
|
|
954
|
+
const kind = typeof d.exception_type === "string" && d.exception_type !== "" ? `${d.exception_type}: ` : "";
|
|
955
|
+
return `${where}${kind}${d.exception_message.trim()}`;
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
try {
|
|
960
|
+
return JSON.stringify(error);
|
|
961
|
+
} catch {
|
|
962
|
+
return String(error);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
// src/cli/serve/web/state/draftTabs.ts
|
|
967
|
+
var SERVE_TABS_FILE = "serve-tabs.json";
|
|
968
|
+
var same = (a, b) => a.module === b.module && a.draft === b.draft;
|
|
969
|
+
function readTabs(raw, modules) {
|
|
970
|
+
if (!Array.isArray(raw))
|
|
971
|
+
return [];
|
|
972
|
+
const out = [];
|
|
973
|
+
for (const x of raw) {
|
|
974
|
+
if (x == null || typeof x !== "object")
|
|
975
|
+
continue;
|
|
976
|
+
const o = x;
|
|
977
|
+
if (typeof o.module !== "string" || typeof o.draft !== "string")
|
|
978
|
+
continue;
|
|
979
|
+
const t = { module: o.module, draft: o.draft };
|
|
980
|
+
if (!modules.some((m) => m.module === t.module && m.drafts.includes(t.draft)))
|
|
981
|
+
continue;
|
|
982
|
+
if (!out.some((y) => same(y, t)))
|
|
983
|
+
out.push(t);
|
|
984
|
+
}
|
|
985
|
+
return out;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// src/cli/serve/ServeApp.ts
|
|
989
|
+
var SERVE_MEDIA_FLOOR = {
|
|
990
|
+
image: new Set([...DEFAULT_MEDIA_EXTENSIONS.image, "bmp", "tif", "tiff", "avif"]),
|
|
991
|
+
audio: new Set([...DEFAULT_MEDIA_EXTENSIONS.audio, "aac"]),
|
|
992
|
+
video: new Set([...DEFAULT_MEDIA_EXTENSIONS.video, "avi"])
|
|
993
|
+
};
|
|
994
|
+
function looksLikeMedia(kind, path) {
|
|
995
|
+
let fd = null;
|
|
996
|
+
try {
|
|
997
|
+
fd = openSync(path, "r");
|
|
998
|
+
const head = new Uint8Array(16);
|
|
999
|
+
const n = readSync(fd, head, 0, 16, 0);
|
|
1000
|
+
return isMediaMagic(kind, head.subarray(0, n));
|
|
1001
|
+
} catch {
|
|
1002
|
+
return false;
|
|
1003
|
+
} finally {
|
|
1004
|
+
if (fd != null)
|
|
1005
|
+
closeSync(fd);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
function serveAcceptsMediaExt(kind, declared, ext) {
|
|
1009
|
+
const floor = SERVE_MEDIA_FLOOR[kind];
|
|
1010
|
+
if (ext === "")
|
|
1011
|
+
return false;
|
|
1012
|
+
if (!floor.has(ext))
|
|
1013
|
+
return false;
|
|
1014
|
+
const narrowed = declared.map((e) => e.toLowerCase().replace(/^\./, "")).filter((e) => floor.has(e));
|
|
1015
|
+
return narrowed.length === 0 || narrowed.includes(ext);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
class DownloadRefused extends Error {
|
|
1019
|
+
constructor(url) {
|
|
1020
|
+
super(`could not fetch ${url}`);
|
|
1021
|
+
this.name = "DownloadRefused";
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
var INPUT_DOWNLOAD_CAP = 50000000;
|
|
1025
|
+
var INPUT_DOWNLOAD_TIMEOUT_MS = 60000;
|
|
1026
|
+
var TAG_LIST_CAP = 40000000;
|
|
1027
|
+
var TAG_LIST_TIMEOUT_MS = 120000;
|
|
1028
|
+
var MB = 1024 * 1024;
|
|
1029
|
+
async function readCapped(res, cap, what) {
|
|
1030
|
+
const body = res.body;
|
|
1031
|
+
if (body == null)
|
|
1032
|
+
return new Uint8Array(0);
|
|
1033
|
+
const reader = body.getReader();
|
|
1034
|
+
const chunks = [];
|
|
1035
|
+
let total = 0;
|
|
1036
|
+
try {
|
|
1037
|
+
for (;; ) {
|
|
1038
|
+
const step = await reader.read();
|
|
1039
|
+
if (step.done)
|
|
1040
|
+
break;
|
|
1041
|
+
total += step.value.length;
|
|
1042
|
+
if (total > cap) {
|
|
1043
|
+
await reader.cancel();
|
|
1044
|
+
throw new Error(`download too large (over ${cap} bytes): ${what}`);
|
|
1045
|
+
}
|
|
1046
|
+
chunks.push(step.value);
|
|
1047
|
+
}
|
|
1048
|
+
} finally {
|
|
1049
|
+
reader.releaseLock();
|
|
1050
|
+
}
|
|
1051
|
+
const out = new Uint8Array(total);
|
|
1052
|
+
let at = 0;
|
|
1053
|
+
for (const c of chunks) {
|
|
1054
|
+
out.set(c, at);
|
|
1055
|
+
at += c.length;
|
|
1056
|
+
}
|
|
1057
|
+
return out;
|
|
1058
|
+
}
|
|
1059
|
+
var NO_STORE = { "cache-control": "no-store, must-revalidate" };
|
|
1060
|
+
var realStarter = async (mod, opts) => {
|
|
1061
|
+
const host = opts.host ?? mod.dw.host;
|
|
1062
|
+
await host.connect();
|
|
1063
|
+
const wf = await mod.dw.build({ advance: true, host });
|
|
1064
|
+
return await wf.start({ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false, onPreview: opts.onPreview });
|
|
1065
|
+
};
|
|
1066
|
+
var CONTENT_TYPES = {
|
|
1067
|
+
".png": "image/png",
|
|
1068
|
+
".jpg": "image/jpeg",
|
|
1069
|
+
".jpeg": "image/jpeg",
|
|
1070
|
+
".webp": "image/webp",
|
|
1071
|
+
".gif": "image/gif",
|
|
1072
|
+
".mp4": "video/mp4",
|
|
1073
|
+
".webm": "video/webm",
|
|
1074
|
+
".m4v": "video/mp4",
|
|
1075
|
+
".mov": "video/quicktime",
|
|
1076
|
+
".mkv": "video/x-matroska",
|
|
1077
|
+
".avi": "video/x-msvideo",
|
|
1078
|
+
".aac": "audio/aac",
|
|
1079
|
+
".flac": "audio/flac",
|
|
1080
|
+
".mp3": "audio/mpeg",
|
|
1081
|
+
".opus": "audio/ogg",
|
|
1082
|
+
".ogg": "audio/ogg",
|
|
1083
|
+
".wav": "audio/wav",
|
|
1084
|
+
".m4a": "audio/mp4",
|
|
1085
|
+
".json": "application/json",
|
|
1086
|
+
".txt": "text/plain",
|
|
1087
|
+
...Object.fromEntries(Object.entries(MODEL_3D_MIMES).map(([ext, mime]) => [`.${ext}`, mime]))
|
|
1088
|
+
};
|
|
1089
|
+
function sniffImageContentType(bytes) {
|
|
1090
|
+
if (bytes[0] === 137 && bytes[1] === 80)
|
|
1091
|
+
return "image/png";
|
|
1092
|
+
if (bytes[0] === 255 && bytes[1] === 216)
|
|
1093
|
+
return "image/jpeg";
|
|
1094
|
+
if (bytes[0] === 71 && bytes[1] === 73)
|
|
1095
|
+
return "image/gif";
|
|
1096
|
+
if (bytes[0] === 82 && bytes[1] === 73)
|
|
1097
|
+
return "image/webp";
|
|
1098
|
+
return "application/octet-stream";
|
|
1099
|
+
}
|
|
1100
|
+
function isImageMagic(b) {
|
|
1101
|
+
const at = (i, ...want) => want.every((w, k) => b[i + k] === w);
|
|
1102
|
+
if (at(0, 137, 80, 78, 71, 13, 10, 26, 10))
|
|
1103
|
+
return true;
|
|
1104
|
+
if (at(0, 255, 216, 255))
|
|
1105
|
+
return true;
|
|
1106
|
+
if (at(0, 71, 73, 70, 56))
|
|
1107
|
+
return true;
|
|
1108
|
+
if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80))
|
|
1109
|
+
return true;
|
|
1110
|
+
if (at(0, 66, 77))
|
|
1111
|
+
return true;
|
|
1112
|
+
if (at(0, 73, 73, 42, 0) || at(0, 77, 77, 0, 42))
|
|
1113
|
+
return true;
|
|
1114
|
+
if (at(4, 102, 116, 121, 112))
|
|
1115
|
+
return true;
|
|
1116
|
+
return false;
|
|
1117
|
+
}
|
|
1118
|
+
function isMediaMagic(kind, b) {
|
|
1119
|
+
const at = (i, ...want) => want.every((w, k) => b[i + k] === w);
|
|
1120
|
+
const isobmff = at(4, 102, 116, 121, 112);
|
|
1121
|
+
if (kind === "image")
|
|
1122
|
+
return isImageMagic(b);
|
|
1123
|
+
if (kind === "audio") {
|
|
1124
|
+
if (at(0, 82, 73, 70, 70) && at(8, 87, 65, 86, 69))
|
|
1125
|
+
return true;
|
|
1126
|
+
if (at(0, 102, 76, 97, 67))
|
|
1127
|
+
return true;
|
|
1128
|
+
if (at(0, 79, 103, 103, 83))
|
|
1129
|
+
return true;
|
|
1130
|
+
if (at(0, 73, 68, 51))
|
|
1131
|
+
return true;
|
|
1132
|
+
const b0 = b[0];
|
|
1133
|
+
const b1 = b[1];
|
|
1134
|
+
const b2 = b[2];
|
|
1135
|
+
if (b0 === 255 && b1 != null && b1 !== 254 && b2 != null && (b1 & 224) === 224 && (b1 & 24) !== 8 && (b1 & 6) !== 0 && b2 >> 4 !== 15 && (b2 >> 2 & 3) !== 3)
|
|
1136
|
+
return true;
|
|
1137
|
+
if (b0 === 255 && b1 != null && (b1 & 246) === 240)
|
|
1138
|
+
return true;
|
|
1139
|
+
return isobmff;
|
|
1140
|
+
}
|
|
1141
|
+
if (at(0, 26, 69, 223, 163))
|
|
1142
|
+
return true;
|
|
1143
|
+
if (at(0, 82, 73, 70, 70) && at(8, 65, 86, 73, 32))
|
|
1144
|
+
return true;
|
|
1145
|
+
return isobmff;
|
|
1146
|
+
}
|
|
1147
|
+
function isMediaKind(kind) {
|
|
1148
|
+
return MEDIA_KINDS.includes(kind);
|
|
1149
|
+
}
|
|
1150
|
+
function json(status, payload) {
|
|
1151
|
+
return { status, contentType: "application/json", body: JSON.stringify(payload, null, 2) };
|
|
1152
|
+
}
|
|
1153
|
+
var USAGE = [
|
|
1154
|
+
"GET / in a browser — web control panel (every var as a form control)",
|
|
1155
|
+
"GET /drafts — every served workflow, its drafts and var descriptors",
|
|
1156
|
+
"GET /drafts/<module>/<draft> — one draft with its stored values",
|
|
1157
|
+
"POST /generate/<module>/<draft> with { ...vars } — run, blocking",
|
|
1158
|
+
"POST /generate/<draft> — unqualified, when unambiguous",
|
|
1159
|
+
"POST /preview/<module> with { ...draft values } — the workflow previews for those values, nothing is run",
|
|
1160
|
+
"PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft",
|
|
1161
|
+
"DELETE /drafts/<module>/<draft> — delete that draft file",
|
|
1162
|
+
"GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes",
|
|
1163
|
+
'POST /upload with {"name","dataBase64"} — store a browser file for an image, audio or video var',
|
|
1164
|
+
"GET /images|audio|video|model3d/<promptId>/<ix> — an output kept in memory (saving off)",
|
|
1165
|
+
"GET /tags/<module>/<var>?q=<text>&limit=<n> — tag completion from the list a prompt var declares (`tags`)",
|
|
1166
|
+
"GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)",
|
|
1167
|
+
"GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)",
|
|
1168
|
+
"POST /hosts/<hostId>/lora-civitai/<lora> — fetch its civitai metadata (trigger words) through the lora manager, then re-sync the mirror",
|
|
1169
|
+
"GET /lora-preview/<hostId>/<lora> — preview image bytes",
|
|
1170
|
+
"GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)",
|
|
1171
|
+
"GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)",
|
|
1172
|
+
'PUT /prompt-enhancers/<name> with {"text"} — write one · DELETE /prompt-enhancers/<name> — remove it',
|
|
1173
|
+
"GET /llm-configs — the enhancer LLM configs (.comfy-ts/llm-configs/*.json)",
|
|
1174
|
+
"PUT /llm-configs/<name> with {provider, baseUrl, model, effort, thinkingOnly} · DELETE /llm-configs/<name>",
|
|
1175
|
+
'GET /settings — { saveToDisk, memoryBudgetMb } · PUT /settings with {"saveToDisk"} — write outputs to disk, or keep them in memory; {"memoryBudgetMb"} caps what memory keeps',
|
|
1176
|
+
'GET /hosts — every host this process knows · PUT /hosts/<module> with {"host"} — run that workflow elsewhere',
|
|
1177
|
+
"POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host",
|
|
1178
|
+
"GET /hosts/<hostId>/ping — is that host answering right now (restart watch)",
|
|
1179
|
+
"GET /hosts/<hostId>/logs — the last lines of that host console",
|
|
1180
|
+
"GET /images/<promptId>/<ix> — an in-memory output (saving off), while the process lives",
|
|
1181
|
+
"GET /audio/<promptId>/<ix> — the same for an in-memory audio output",
|
|
1182
|
+
"GET /results — the last runs this process kept, for a reload · DELETE /results[/<promptId>] — forget them, freeing their memory",
|
|
1183
|
+
"GET /outputs/<path> — generated files"
|
|
1184
|
+
];
|
|
1185
|
+
function buildId(js) {
|
|
1186
|
+
let h = 5381;
|
|
1187
|
+
for (let i = 0;i < js.length; i++)
|
|
1188
|
+
h = (h << 5) + h + js.charCodeAt(i) | 0;
|
|
1189
|
+
return (h >>> 0).toString(36);
|
|
1190
|
+
}
|
|
1191
|
+
var WEB_SHELL = `<!doctype html>
|
|
1192
|
+
<html lang="en">
|
|
1193
|
+
<head>
|
|
1194
|
+
<meta charset="utf-8">
|
|
1195
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1196
|
+
<title>comfy-ts serve</title>
|
|
1197
|
+
<link rel="icon" type="image/png" href="${FAVICON_DATA_URI}">
|
|
1198
|
+
<style>html{background:#101217;color:#e8eaf0}</style>
|
|
1199
|
+
</head>
|
|
1200
|
+
<body>
|
|
1201
|
+
<div id="root"></div>
|
|
1202
|
+
<script type="module" src="/web/app.js?v=__BUILD__"></script>
|
|
1203
|
+
</body>
|
|
1204
|
+
</html>
|
|
1205
|
+
`;
|
|
1206
|
+
|
|
1207
|
+
class ServeApp {
|
|
1208
|
+
modules;
|
|
1209
|
+
opts;
|
|
1210
|
+
starter;
|
|
1211
|
+
seedState = new Map;
|
|
1212
|
+
chains = new Map;
|
|
1213
|
+
settingsCache = null;
|
|
1214
|
+
get settings() {
|
|
1215
|
+
this.settingsCache ??= readServeSettings();
|
|
1216
|
+
return this.settingsCache;
|
|
1217
|
+
}
|
|
1218
|
+
set settings(next) {
|
|
1219
|
+
this.settingsCache = next;
|
|
1220
|
+
}
|
|
1221
|
+
keptCache = null;
|
|
1222
|
+
get kept() {
|
|
1223
|
+
this.keptCache ??= new ResultHistory(this.settings.memoryBudgetMb * MB);
|
|
1224
|
+
return this.keptCache;
|
|
1225
|
+
}
|
|
1226
|
+
constructor(modules, opts = {}) {
|
|
1227
|
+
this.modules = modules;
|
|
1228
|
+
this.opts = opts;
|
|
1229
|
+
this.starter = opts.starter ?? realStarter;
|
|
1230
|
+
}
|
|
1231
|
+
get outputRoot() {
|
|
1232
|
+
return this.opts.outputRoot ?? comfyts.outputPath;
|
|
1233
|
+
}
|
|
1234
|
+
async handle(req) {
|
|
1235
|
+
try {
|
|
1236
|
+
const path = (req.url.split("?")[0] ?? "/").split("#")[0] ?? "/";
|
|
1237
|
+
let segs;
|
|
1238
|
+
try {
|
|
1239
|
+
segs = path.split("/").filter((s) => s !== "").map(decodeURIComponent);
|
|
1240
|
+
} catch {
|
|
1241
|
+
return json(400, { error: `bad url encoding: ${path}` });
|
|
1242
|
+
}
|
|
1243
|
+
if (req.method === "GET") {
|
|
1244
|
+
if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes("text/html") === true) {
|
|
1245
|
+
const js = await this.opts.webJs();
|
|
1246
|
+
if (js != null)
|
|
1247
|
+
return {
|
|
1248
|
+
status: 200,
|
|
1249
|
+
contentType: "text/html; charset=utf-8",
|
|
1250
|
+
body: WEB_SHELL.replace("__BUILD__", buildId(js)),
|
|
1251
|
+
headers: NO_STORE
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
if (segs.length === 0 || segs[0] === "drafts" && segs.length === 1)
|
|
1255
|
+
return await this.replyIndex();
|
|
1256
|
+
if (segs[0] === "web" && segs[1] === "app.js" && segs.length === 2)
|
|
1257
|
+
return await this.replyWebJs();
|
|
1258
|
+
if (segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1259
|
+
return this.replyDraft(segs[1], segs[2]);
|
|
1260
|
+
if (segs[0] === "run" && segs.length === 2 && segs[1] != null)
|
|
1261
|
+
return this.replyRunStatus(segs[1]);
|
|
1262
|
+
if (segs[0] === "run" && segs.length === 3 && segs[1] != null && segs[2] === "preview")
|
|
1263
|
+
return this.replyRunPreview(segs[1]);
|
|
1264
|
+
if (segs[0] === "lora-info" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1265
|
+
return this.replyLoraInfo(segs[1], segs[2]);
|
|
1266
|
+
if (segs[0] === "lora-preview" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1267
|
+
return await this.replyLoraPreview(segs[1], segs[2]);
|
|
1268
|
+
if (segs[0] === "lora-about" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1269
|
+
return await this.replyLoraAbout(segs[1], segs[2]);
|
|
1270
|
+
if (segs[0] === "prompt-enhancers" && segs.length === 1)
|
|
1271
|
+
return this.replyPromptEnhancers();
|
|
1272
|
+
if (segs[0] === "llm-configs" && segs.length === 1)
|
|
1273
|
+
return this.replyLlmConfigs();
|
|
1274
|
+
if (segs[0] === "tags" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1275
|
+
return await this.replyTags(segs[1], segs[2], req.url);
|
|
1276
|
+
if (segs[0] === "settings" && segs.length === 1)
|
|
1277
|
+
return this.replySettings();
|
|
1278
|
+
if (segs[0] === "thumb" && segs.length === 1)
|
|
1279
|
+
return await this.replyThumb(req.url);
|
|
1280
|
+
if (segs[0] === "tabs" && segs.length === 1)
|
|
1281
|
+
return this.replyTabs();
|
|
1282
|
+
if (segs[0] === "hosts" && segs.length === 1)
|
|
1283
|
+
return this.replyHosts();
|
|
1284
|
+
if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "logs")
|
|
1285
|
+
return await this.replyHostLogs(segs[1]);
|
|
1286
|
+
if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "ping")
|
|
1287
|
+
return await this.replyHostPing(segs[1]);
|
|
1288
|
+
if (segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] === "drift")
|
|
1289
|
+
return await this.replyHostDrift(segs[1], req.url.includes("full=1"));
|
|
1290
|
+
if (segs[0] === "images" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1291
|
+
return this.replyMemoryImage(`${segs[1]}/${segs[2]}`);
|
|
1292
|
+
if (segs[0] === "audio" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1293
|
+
return this.replyMemoryImage(`audio/${segs[1]}/${segs[2]}`);
|
|
1294
|
+
if (segs[0] === "video" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1295
|
+
return this.replyMemoryImage(`video/${segs[1]}/${segs[2]}`);
|
|
1296
|
+
if (segs[0] === "model3d" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1297
|
+
return this.replyMemoryImage(`model3d/${segs[1]}/${segs[2]}`);
|
|
1298
|
+
if (segs[0] === "results" && segs.length === 1)
|
|
1299
|
+
return json(200, { runs: this.kept.list(), memory: this.kept.usage() });
|
|
1300
|
+
if (segs[0] === "outputs")
|
|
1301
|
+
return this.replyOutput(segs.slice(1));
|
|
1302
|
+
return json(404, { error: `no route: GET ${path}`, usage: USAGE });
|
|
1303
|
+
}
|
|
1304
|
+
if (req.method === "POST" && segs[0] === "generate") {
|
|
1305
|
+
const target = this.resolveDraft(segs.slice(1));
|
|
1306
|
+
if ("error" in target)
|
|
1307
|
+
return json(target.status, { error: target.error });
|
|
1308
|
+
return await this.generate(target.mod, target.draft, req);
|
|
1309
|
+
}
|
|
1310
|
+
if (req.method === "POST" && segs[0] === "preview" && segs.length === 2 && segs[1] != null)
|
|
1311
|
+
return await this.replyPreview(segs[1], req);
|
|
1312
|
+
if (req.method === "POST" && segs[0] === "upload" && segs.length === 1)
|
|
1313
|
+
return this.replyUpload(req);
|
|
1314
|
+
if (req.method === "PUT" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1315
|
+
return await this.replySaveDraft(segs[1], segs[2], req);
|
|
1316
|
+
if (req.method === "DELETE" && segs[0] === "drafts" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1317
|
+
return await this.replyDeleteDraft(segs[1], segs[2]);
|
|
1318
|
+
if (req.method === "PUT" && segs[0] === "settings" && segs.length === 1)
|
|
1319
|
+
return this.replySaveSettings(req);
|
|
1320
|
+
if (req.method === "DELETE" && segs[0] === "results" && segs.length <= 2) {
|
|
1321
|
+
if (segs[1] == null)
|
|
1322
|
+
this.kept.clear();
|
|
1323
|
+
else
|
|
1324
|
+
this.kept.remove(segs[1]);
|
|
1325
|
+
return json(200, { memory: this.kept.usage() });
|
|
1326
|
+
}
|
|
1327
|
+
if (req.method === "PUT" && segs[0] === "tabs" && segs.length === 1)
|
|
1328
|
+
return this.replySaveTabs(req);
|
|
1329
|
+
if (req.method === "PUT" && segs[0] === "hosts" && segs.length === 2 && segs[1] != null)
|
|
1330
|
+
return this.replySetHost(segs[1], req);
|
|
1331
|
+
if (req.method === "POST" && segs[0] === "hosts" && segs.length === 3 && segs[1] != null && segs[2] != null)
|
|
1332
|
+
return await this.replyHostAction(segs[1], segs[2]);
|
|
1333
|
+
if (req.method === "POST" && segs[0] === "hosts" && segs.length === 4 && segs[1] != null && segs[2] === "lora-civitai" && segs[3] != null)
|
|
1334
|
+
return await this.replyLoraCivitaiFetch(segs[1], segs[3]);
|
|
1335
|
+
if (req.method === "PUT" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null)
|
|
1336
|
+
return this.replySavePromptEnhancer(segs[1], req);
|
|
1337
|
+
if (req.method === "DELETE" && segs[0] === "prompt-enhancers" && segs.length === 2 && segs[1] != null)
|
|
1338
|
+
return this.replyDeletePromptEnhancer(segs[1]);
|
|
1339
|
+
if (req.method === "PUT" && segs[0] === "llm-configs" && segs.length === 2 && segs[1] != null)
|
|
1340
|
+
return this.replySaveLlmConfig(segs[1], req);
|
|
1341
|
+
if (req.method === "DELETE" && segs[0] === "llm-configs" && segs.length === 2 && segs[1] != null)
|
|
1342
|
+
return this.replyDeleteLlmConfig(segs[1]);
|
|
1343
|
+
return json(404, { error: `no route: ${req.method} ${path}`, usage: USAGE });
|
|
1344
|
+
} catch (e) {
|
|
1345
|
+
console.error("[serve] request crashed:", e);
|
|
1346
|
+
return json(500, { error: extractErrorMessage(e) });
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
moduleByKey(key) {
|
|
1350
|
+
return this.modules.find((m) => m.key === key) ?? null;
|
|
1351
|
+
}
|
|
1352
|
+
draftsFor(mod) {
|
|
1353
|
+
const onDisk = listDraftsForFile(mod.file);
|
|
1354
|
+
return ["default", ...onDisk.filter((n) => n !== "default")];
|
|
1355
|
+
}
|
|
1356
|
+
validDraftName(raw) {
|
|
1357
|
+
return validStoreName(raw);
|
|
1358
|
+
}
|
|
1359
|
+
draftPath(mod, draft) {
|
|
1360
|
+
const name = this.validDraftName(draft);
|
|
1361
|
+
return name == null ? null : join4(draftsDirForFile(mod.file), `${name}.json`);
|
|
1362
|
+
}
|
|
1363
|
+
draftExists(mod, draft) {
|
|
1364
|
+
const path = this.draftPath(mod, draft);
|
|
1365
|
+
if (path == null)
|
|
1366
|
+
return false;
|
|
1367
|
+
return draft === "default" || existsSync6(path);
|
|
1368
|
+
}
|
|
1369
|
+
resolveDraft(segs) {
|
|
1370
|
+
if (segs.length === 2 && segs[0] != null && segs[1] != null) {
|
|
1371
|
+
const mod = this.moduleByKey(segs[0]);
|
|
1372
|
+
if (mod == null)
|
|
1373
|
+
return {
|
|
1374
|
+
status: 404,
|
|
1375
|
+
error: `unknown module '${segs[0]}' — modules: ${this.modules.map((m) => m.key).join(", ")}`
|
|
1376
|
+
};
|
|
1377
|
+
if (!this.draftExists(mod, segs[1]))
|
|
1378
|
+
return {
|
|
1379
|
+
status: 404,
|
|
1380
|
+
error: `module '${mod.key}' has no draft '${segs[1]}' — drafts: ${this.draftsFor(mod).join(", ")}`
|
|
1381
|
+
};
|
|
1382
|
+
return { mod, draft: segs[1] };
|
|
1383
|
+
}
|
|
1384
|
+
if (segs.length === 1 && segs[0] != null) {
|
|
1385
|
+
const draft = segs[0];
|
|
1386
|
+
if (this.modules.length === 1 && this.modules[0] != null) {
|
|
1387
|
+
const mod = this.modules[0];
|
|
1388
|
+
if (!this.draftExists(mod, draft))
|
|
1389
|
+
return {
|
|
1390
|
+
status: 404,
|
|
1391
|
+
error: `no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}`
|
|
1392
|
+
};
|
|
1393
|
+
return { mod, draft };
|
|
1394
|
+
}
|
|
1395
|
+
const hits = this.modules.filter((m) => this.draftExists(m, draft));
|
|
1396
|
+
if (hits.length === 1 && hits[0] != null)
|
|
1397
|
+
return { mod: hits[0], draft };
|
|
1398
|
+
if (hits.length === 0)
|
|
1399
|
+
return { status: 404, error: `no module has a draft '${draft}'` };
|
|
1400
|
+
return {
|
|
1401
|
+
status: 400,
|
|
1402
|
+
error: `draft '${draft}' is ambiguous — use: ${hits.map((m) => `/generate/${m.key}/${draft}`).join(" or ")}`
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
return { status: 400, error: "use POST /generate/<module>/<draft> or /generate/<draft>" };
|
|
1406
|
+
}
|
|
1407
|
+
decorateLooks(desc, mod) {
|
|
1408
|
+
const dir = dirname3(mod.file);
|
|
1409
|
+
this.thumbs.allowRoot(dir);
|
|
1410
|
+
this.thumbs.allowRoot(this.outputRoot);
|
|
1411
|
+
const local = (p) => isAbsolute2(p) ? p : resolve3(dir, p);
|
|
1412
|
+
const options = desc.ui?.options;
|
|
1413
|
+
if (desc.ui != null && options != null) {
|
|
1414
|
+
const looks = {};
|
|
1415
|
+
for (const [value, look] of Object.entries(options)) {
|
|
1416
|
+
if (look.thumb == null || isHttpUrl(look.thumb)) {
|
|
1417
|
+
looks[value] = look;
|
|
1418
|
+
continue;
|
|
1419
|
+
}
|
|
1420
|
+
const abs = local(look.thumb);
|
|
1421
|
+
this.thumbs.allow(abs);
|
|
1422
|
+
looks[value] = { ...look, thumb: thumbUrl(abs, 128) };
|
|
1423
|
+
}
|
|
1424
|
+
desc.ui = { ...desc.ui, options: looks };
|
|
1425
|
+
}
|
|
1426
|
+
if (desc.mediaPresets != null)
|
|
1427
|
+
desc.mediaPresets = desc.mediaPresets.map((preset) => {
|
|
1428
|
+
if (isHttpUrl(preset.value)) {
|
|
1429
|
+
const cached = this.urlInputPath(preset.value, basename(new URL(preset.value).pathname));
|
|
1430
|
+
return { ...preset, thumb: existsSync6(cached) ? thumbUrl(cached, 160) : preset.value };
|
|
1431
|
+
}
|
|
1432
|
+
const abs = local(preset.value);
|
|
1433
|
+
this.thumbs.allow(abs);
|
|
1434
|
+
return existsSync6(abs) ? { ...preset, value: abs, thumb: thumbUrl(abs, 160) } : { ...preset, value: abs, missing: true };
|
|
1435
|
+
});
|
|
1436
|
+
if (MEDIA_KINDS.includes(desc.kind) && typeof desc.default === "string" && desc.default !== "") {
|
|
1437
|
+
if (!isHttpUrl(desc.default))
|
|
1438
|
+
this.thumbs.allow(local(desc.default));
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
async replyThumb(url) {
|
|
1442
|
+
const q = new URLSearchParams(url.split("?")[1] ?? "");
|
|
1443
|
+
const src = q.get("src");
|
|
1444
|
+
if (src == null || src === "")
|
|
1445
|
+
return json(400, { error: "thumb needs ?src=<local path>" });
|
|
1446
|
+
const out = await this.thumbs.render(src, Number(q.get("w") ?? 160) || 160);
|
|
1447
|
+
if (out === "forbidden")
|
|
1448
|
+
return json(403, { error: "not a picture a served workflow declared, nor under its folder or the outputs" });
|
|
1449
|
+
if (out === "missing")
|
|
1450
|
+
return json(404, { error: "not on this machine" });
|
|
1451
|
+
return { status: 200, contentType: "image/webp", body: out, headers: { "cache-control": "max-age=300" } };
|
|
1452
|
+
}
|
|
1453
|
+
describeModule(mod) {
|
|
1454
|
+
refreshLoraInfoCacheIfChanged();
|
|
1455
|
+
const hostId = mod.dw.host.data.id;
|
|
1456
|
+
const vars = {};
|
|
1457
|
+
for (const [name, varDef] of mod.dw.entries()) {
|
|
1458
|
+
const desc = describeVar(varDef);
|
|
1459
|
+
this.decorateLooks(desc, mod);
|
|
1460
|
+
if (desc.kind === "loras" && desc.options != null) {
|
|
1461
|
+
const labels = {};
|
|
1462
|
+
for (const option of desc.options) {
|
|
1463
|
+
const label = getLoraDisplayName(option, hostId);
|
|
1464
|
+
if (label !== option)
|
|
1465
|
+
labels[option] = label;
|
|
1466
|
+
}
|
|
1467
|
+
if (Object.keys(labels).length > 0)
|
|
1468
|
+
desc.optionLabels = labels;
|
|
1469
|
+
const extras = managerOnlyLoraOptions({
|
|
1470
|
+
hostId,
|
|
1471
|
+
options: desc.options,
|
|
1472
|
+
filter: varDef.optionsFilter
|
|
1473
|
+
});
|
|
1474
|
+
if (extras.length > 0) {
|
|
1475
|
+
desc.managerOnlyOptions = extras;
|
|
1476
|
+
desc.options = [...desc.options, ...extras];
|
|
1477
|
+
for (const extra of extras) {
|
|
1478
|
+
const label = getLoraDisplayName(extra, hostId);
|
|
1479
|
+
if (label !== extra)
|
|
1480
|
+
(desc.optionLabels ??= {})[extra] = label;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
const keywords = {};
|
|
1484
|
+
for (const option of desc.options) {
|
|
1485
|
+
const kw = getLoraKeyword(option, hostId);
|
|
1486
|
+
if (kw !== "")
|
|
1487
|
+
keywords[option] = kw;
|
|
1488
|
+
}
|
|
1489
|
+
if (Object.keys(keywords).length > 0)
|
|
1490
|
+
desc.optionKeywords = keywords;
|
|
1491
|
+
const addedAt = {};
|
|
1492
|
+
for (const option of desc.options) {
|
|
1493
|
+
const t = getLoraAddedAt(option, hostId);
|
|
1494
|
+
if (t != null)
|
|
1495
|
+
addedAt[option] = t;
|
|
1496
|
+
}
|
|
1497
|
+
if (Object.keys(addedAt).length > 0)
|
|
1498
|
+
desc.optionAddedAt = addedAt;
|
|
1499
|
+
const triggers = {};
|
|
1500
|
+
for (const option of desc.options) {
|
|
1501
|
+
const t = getLoraTriggers(option, hostId);
|
|
1502
|
+
if (t != null)
|
|
1503
|
+
triggers[option] = t;
|
|
1504
|
+
}
|
|
1505
|
+
if (Object.keys(triggers).length > 0)
|
|
1506
|
+
desc.optionTriggers = triggers;
|
|
1507
|
+
}
|
|
1508
|
+
vars[name] = desc;
|
|
1509
|
+
}
|
|
1510
|
+
for (const [name, varDef] of mod.dw.entries()) {
|
|
1511
|
+
if (varDef.kind !== "prompt")
|
|
1512
|
+
continue;
|
|
1513
|
+
const source = varDef.promptOpts.loraKeywordsFrom;
|
|
1514
|
+
if (source == null)
|
|
1515
|
+
continue;
|
|
1516
|
+
const sourceName = mod.dw.entries().find(([, other]) => other === source)?.[0];
|
|
1517
|
+
const desc = vars[name];
|
|
1518
|
+
if (sourceName != null && desc != null)
|
|
1519
|
+
desc.keywordsFrom = sourceName;
|
|
1520
|
+
}
|
|
1521
|
+
return {
|
|
1522
|
+
module: mod.key,
|
|
1523
|
+
file: mod.file,
|
|
1524
|
+
host: mod.dw.host.data.id,
|
|
1525
|
+
drafts: this.draftsFor(mod),
|
|
1526
|
+
routes: this.draftsFor(mod).map((d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
|
|
1527
|
+
vars,
|
|
1528
|
+
previews: Object.keys(mod.dw.spec.previews ?? {}),
|
|
1529
|
+
tags: this.tagsByModule.get(mod.key) ?? mod.dw.spec.tags ?? []
|
|
1530
|
+
};
|
|
1531
|
+
}
|
|
1532
|
+
tagsByModule = new Map;
|
|
1533
|
+
thumbs = new ThumbStore;
|
|
1534
|
+
async tagsFor(mod) {
|
|
1535
|
+
const known = this.tagsByModule.get(mod.key);
|
|
1536
|
+
if (known != null)
|
|
1537
|
+
return known;
|
|
1538
|
+
const extra = mod.dw.spec.tags ?? [];
|
|
1539
|
+
const varKinds = mod.dw.entries().map(([, varDef]) => varDef.kind);
|
|
1540
|
+
let tags;
|
|
1541
|
+
try {
|
|
1542
|
+
const wf = await mod.dw.build({ dry: true });
|
|
1543
|
+
const nodes = wf.nodes.map((n) => ({
|
|
1544
|
+
id: n.uid,
|
|
1545
|
+
classType: n.json.class_type,
|
|
1546
|
+
outputNode: n.$schema.raw.output_node,
|
|
1547
|
+
outputTypes: n.$schema.outputs.map((o) => o.typeName),
|
|
1548
|
+
links: Object.values(n.json.inputs).flatMap((v) => Array.isArray(v) && v.length === 2 && typeof v[1] === "number" ? [[String(v[0]), v[1]]] : [])
|
|
1549
|
+
}));
|
|
1550
|
+
tags = workflowTags({ nodes, varKinds, extra });
|
|
1551
|
+
} catch (e) {
|
|
1552
|
+
console.error(`[serve] \uD83D\uDD34 tags for ${mod.key}: dry build failed, spec tags only: ${extractErrorMessage(e)}`);
|
|
1553
|
+
tags = workflowTags({ nodes: [], varKinds, extra });
|
|
1554
|
+
}
|
|
1555
|
+
this.tagsByModule.set(mod.key, tags);
|
|
1556
|
+
return tags;
|
|
1557
|
+
}
|
|
1558
|
+
async replyIndex() {
|
|
1559
|
+
for (const m of this.modules)
|
|
1560
|
+
await this.tagsFor(m);
|
|
1561
|
+
return json(200, {
|
|
1562
|
+
server: "comfy-ts serve",
|
|
1563
|
+
usage: USAGE,
|
|
1564
|
+
workflows: this.modules.map((m) => this.describeModule(m)),
|
|
1565
|
+
...this.opts.workspace == null ? {} : workspaceLabels({
|
|
1566
|
+
workspace: this.opts.workspace,
|
|
1567
|
+
root: this.opts.root ?? this.opts.workspace,
|
|
1568
|
+
home: process.env.HOME ?? ""
|
|
1569
|
+
}),
|
|
1570
|
+
...this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0 ? { loadErrors: this.opts.loadErrors } : {}
|
|
1571
|
+
});
|
|
1572
|
+
}
|
|
1573
|
+
replyDraft(modKey, draft) {
|
|
1574
|
+
const mod = this.moduleByKey(modKey);
|
|
1575
|
+
if (mod == null)
|
|
1576
|
+
return json(404, { error: `unknown module '${modKey}'` });
|
|
1577
|
+
if (!this.draftExists(mod, draft))
|
|
1578
|
+
return json(404, {
|
|
1579
|
+
error: `module '${modKey}' has no draft '${draft}' — drafts: ${this.draftsFor(mod).join(", ")}`
|
|
1580
|
+
});
|
|
1581
|
+
return json(200, { ...this.describeModule(mod), draft, values: this.draftValues(mod, draft) });
|
|
1582
|
+
}
|
|
1583
|
+
async replyPreview(key, req) {
|
|
1584
|
+
const mod = this.moduleByKey(key);
|
|
1585
|
+
if (mod == null)
|
|
1586
|
+
return json(404, { error: `unknown workflow '${key}'` });
|
|
1587
|
+
let values;
|
|
1588
|
+
try {
|
|
1589
|
+
values = JSON.parse(req.body ?? "{}");
|
|
1590
|
+
} catch (e) {
|
|
1591
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
1592
|
+
}
|
|
1593
|
+
if (values == null || typeof values !== "object" || Array.isArray(values))
|
|
1594
|
+
return json(400, { error: 'expects { "<var>": value, … }' });
|
|
1595
|
+
const incoming = values;
|
|
1596
|
+
const previews = await this.exclusive(mod.key, () => {
|
|
1597
|
+
const saved = mod.dw.entries().map(([k, v]) => [k, v.toJSON()]);
|
|
1598
|
+
try {
|
|
1599
|
+
for (const [k, v] of mod.dw.entries())
|
|
1600
|
+
if (k in incoming)
|
|
1601
|
+
v.loadJSON(incoming[k]);
|
|
1602
|
+
return Promise.resolve(mod.dw.computePreviews());
|
|
1603
|
+
} finally {
|
|
1604
|
+
const byName = new Map(mod.dw.entries());
|
|
1605
|
+
for (const [k, json] of saved)
|
|
1606
|
+
byName.get(k)?.loadJSON(json);
|
|
1607
|
+
}
|
|
1608
|
+
});
|
|
1609
|
+
return json(200, { previews });
|
|
1610
|
+
}
|
|
1611
|
+
draftValues(mod, draft) {
|
|
1612
|
+
const path = this.draftPath(mod, draft);
|
|
1613
|
+
if (path != null && existsSync6(path))
|
|
1614
|
+
return JSON.parse(readFileSync5(path, "utf8"));
|
|
1615
|
+
const out = {};
|
|
1616
|
+
for (const [name, varDef] of mod.dw.entries())
|
|
1617
|
+
out[name] = describeVar(varDef).default;
|
|
1618
|
+
return out;
|
|
1619
|
+
}
|
|
1620
|
+
replyOutput(segs) {
|
|
1621
|
+
const abs = resolve3(this.outputRoot, ...segs);
|
|
1622
|
+
if (abs !== this.outputRoot && !abs.startsWith(this.outputRoot + "/"))
|
|
1623
|
+
return json(400, { error: "path escapes the outputs root" });
|
|
1624
|
+
if (!existsSync6(abs) || !statSync3(abs).isFile())
|
|
1625
|
+
return json(404, { error: `no such output file: /${segs.join("/")}` });
|
|
1626
|
+
const contentType = CONTENT_TYPES[extname(abs).toLowerCase()] ?? "application/octet-stream";
|
|
1627
|
+
return { status: 200, contentType, body: new Uint8Array(readFileSync5(abs)) };
|
|
1628
|
+
}
|
|
1629
|
+
async replyWebJs() {
|
|
1630
|
+
if (this.opts.webJs == null)
|
|
1631
|
+
return json(404, { error: "web ui not enabled on this server" });
|
|
1632
|
+
const js = await this.opts.webJs();
|
|
1633
|
+
if (js == null)
|
|
1634
|
+
return json(404, { error: "web ui bundle unavailable — see the server log" });
|
|
1635
|
+
return { status: 200, contentType: "text/javascript; charset=utf-8", body: js, headers: NO_STORE };
|
|
1636
|
+
}
|
|
1637
|
+
replyUpload(req) {
|
|
1638
|
+
let parsed;
|
|
1639
|
+
try {
|
|
1640
|
+
parsed = JSON.parse(req.body ?? "");
|
|
1641
|
+
} catch (e) {
|
|
1642
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
1643
|
+
}
|
|
1644
|
+
const o = parsed ?? {};
|
|
1645
|
+
if (typeof o.name !== "string" || o.name === "" || typeof o.dataBase64 !== "string" || o.dataBase64 === "")
|
|
1646
|
+
return json(400, { error: 'upload expects {"name":"<filename>","dataBase64":"<base64 bytes>"}' });
|
|
1647
|
+
const bytes = Buffer.from(o.dataBase64, "base64");
|
|
1648
|
+
if (bytes.length === 0)
|
|
1649
|
+
return json(400, { error: "dataBase64 decoded to zero bytes" });
|
|
1650
|
+
const safe = (basename(o.name).replace(/[^\w.-]+/g, "_") || "upload").slice(0, 100);
|
|
1651
|
+
const abs = join4(this.outputRoot, "serve-inputs", `${nanoid(6)}-${safe}`);
|
|
1652
|
+
mkdirSync5(dirname3(abs), { recursive: true });
|
|
1653
|
+
writeFileSync5(abs, bytes);
|
|
1654
|
+
console.log(`[serve] upload → ${abs} (${bytes.length} bytes)`);
|
|
1655
|
+
return json(200, { ok: true, path: abs, url: this.outputUrl(abs) });
|
|
1656
|
+
}
|
|
1657
|
+
async replySaveDraft(modKey, rawDraft, req) {
|
|
1658
|
+
const mod = this.moduleByKey(modKey);
|
|
1659
|
+
if (mod == null)
|
|
1660
|
+
return json(404, { error: `unknown module '${modKey}'` });
|
|
1661
|
+
const draft = this.validDraftName(rawDraft);
|
|
1662
|
+
if (draft == null)
|
|
1663
|
+
return json(400, { error: `invalid draft name '${rawDraft}' — letters/digits then letters, digits, ". -_"` });
|
|
1664
|
+
let parsed;
|
|
1665
|
+
try {
|
|
1666
|
+
parsed = JSON.parse(req.body ?? "");
|
|
1667
|
+
} catch (e) {
|
|
1668
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
1669
|
+
}
|
|
1670
|
+
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
1671
|
+
return json(400, { error: 'body must be a json object: { "<var>": value, … }' });
|
|
1672
|
+
const values = parsed;
|
|
1673
|
+
const known = new Set(mod.dw.entries().map(([k]) => k));
|
|
1674
|
+
if (ENHANCE_KEY in values) {
|
|
1675
|
+
const raw = values[ENHANCE_KEY];
|
|
1676
|
+
const ok = raw != null && typeof raw === "object" && !Array.isArray(raw) && Object.values(raw).every((v) => typeof v === "string");
|
|
1677
|
+
if (!ok)
|
|
1678
|
+
return json(400, { error: `${ENHANCE_KEY} must be { "<prompt var>": "<intent>" }` });
|
|
1679
|
+
}
|
|
1680
|
+
const unknown = Object.keys(values).filter((k) => !known.has(k) && !isDraftMetaKey(k));
|
|
1681
|
+
if (unknown.length > 0)
|
|
1682
|
+
return json(400, { error: `unknown var(s) ${unknown.join(", ")} — vars: ${[...known].join(", ")}` });
|
|
1683
|
+
const path = bang(this.draftPath(mod, draft), "draft name validated just above");
|
|
1684
|
+
await this.exclusive(mod.key, () => {
|
|
1685
|
+
mkdirSync5(dirname3(path), { recursive: true });
|
|
1686
|
+
writeFileSync5(path, JSON.stringify(values, null, 2));
|
|
1687
|
+
return Promise.resolve();
|
|
1688
|
+
});
|
|
1689
|
+
return json(200, { ok: true, module: mod.key, draft, drafts: this.draftsFor(mod) });
|
|
1690
|
+
}
|
|
1691
|
+
async replyDeleteDraft(modKey, rawDraft) {
|
|
1692
|
+
const mod = this.moduleByKey(modKey);
|
|
1693
|
+
if (mod == null)
|
|
1694
|
+
return json(404, { error: `unknown module '${modKey}'` });
|
|
1695
|
+
const path = this.draftPath(mod, rawDraft);
|
|
1696
|
+
if (path == null)
|
|
1697
|
+
return json(400, { error: `invalid draft name '${rawDraft}'` });
|
|
1698
|
+
await this.exclusive(mod.key, () => {
|
|
1699
|
+
if (existsSync6(path))
|
|
1700
|
+
rmSync3(path);
|
|
1701
|
+
return Promise.resolve();
|
|
1702
|
+
});
|
|
1703
|
+
console.log(`[serve] draft deleted: ${mod.key}/${rawDraft.trim()}`);
|
|
1704
|
+
return json(200, { ok: true, module: mod.key, draft: rawDraft.trim(), drafts: this.draftsFor(mod) });
|
|
1705
|
+
}
|
|
1706
|
+
knownHosts() {
|
|
1707
|
+
const byId = new Map;
|
|
1708
|
+
for (const [id, host] of comfyts.hosts)
|
|
1709
|
+
byId.set(id, {
|
|
1710
|
+
id,
|
|
1711
|
+
url: host.addressLabel,
|
|
1712
|
+
httpUrl: host.noAddress == null ? host.getServerHostHTTP() : null,
|
|
1713
|
+
modules: []
|
|
1714
|
+
});
|
|
1715
|
+
for (const mod of this.modules) {
|
|
1716
|
+
const entry = byId.get(mod.dw.host.data.id);
|
|
1717
|
+
if (entry != null)
|
|
1718
|
+
entry.modules.push(mod.key);
|
|
1719
|
+
}
|
|
1720
|
+
return [...byId.values()].sort((a, b) => a.id.localeCompare(b.id));
|
|
1721
|
+
}
|
|
1722
|
+
runHostFor(mod) {
|
|
1723
|
+
const wanted = this.settings.hostOverride[mod.key];
|
|
1724
|
+
if (wanted == null || wanted === mod.dw.host.data.id)
|
|
1725
|
+
return null;
|
|
1726
|
+
return comfyts.hosts.get(wanted) ?? null;
|
|
1727
|
+
}
|
|
1728
|
+
async replyHostAction(hostId, action) {
|
|
1729
|
+
const host = comfyts.hosts.get(hostId);
|
|
1730
|
+
if (host == null)
|
|
1731
|
+
return json(404, { error: `unknown host '${hostId}' — known: ${[...comfyts.hosts.keys()].join(", ")}` });
|
|
1732
|
+
try {
|
|
1733
|
+
if (action === "interrupt") {
|
|
1734
|
+
await host.interrupt();
|
|
1735
|
+
return json(200, { ok: true, host: hostId, action, note: "interrupt requested" });
|
|
1736
|
+
}
|
|
1737
|
+
if (action === "clear-queue") {
|
|
1738
|
+
await host.clearQueue();
|
|
1739
|
+
return json(200, { ok: true, host: hostId, action, note: "pending prompts dropped" });
|
|
1740
|
+
}
|
|
1741
|
+
if (action === "refresh-loras")
|
|
1742
|
+
return await this.refreshLoraMirror(hostId, host);
|
|
1743
|
+
if (action === "refresh-schema") {
|
|
1744
|
+
await host.fetchAndUpdateSchema();
|
|
1745
|
+
const unmirrored = lorasMissingFromMirror(host.schema.getLoras(), (n) => getLoraInfo(n, hostId) != null);
|
|
1746
|
+
const synced = await this.refreshLoraMirror(hostId, host);
|
|
1747
|
+
const lorasNote = synced.status === 200 ? unmirrored.length > 0 ? `, lora list re-read (${unmirrored.length} new)` : ", lora list re-read" : ", the lora manager list could not be re-read";
|
|
1748
|
+
const rebound = await this.rebindHostVars(hostId, host);
|
|
1749
|
+
const nodes = host.schema.nodes.length;
|
|
1750
|
+
const loras = host.schema.getLoras().length;
|
|
1751
|
+
const dropped = rebound.stale.length === 0 ? "" : `. ${rebound.stale.length} selection(s) this host no longer lists (a lora is dropped, a model stays picked)`;
|
|
1752
|
+
return json(200, {
|
|
1753
|
+
ok: true,
|
|
1754
|
+
host: hostId,
|
|
1755
|
+
action,
|
|
1756
|
+
stale: rebound.stale,
|
|
1757
|
+
note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora or model var(s) changed${dropped}${lorasNote}`
|
|
1758
|
+
});
|
|
1759
|
+
}
|
|
1760
|
+
if (action === "restart") {
|
|
1761
|
+
await host.manager.restartComfyUI();
|
|
1762
|
+
return json(200, { ok: true, host: hostId, action, note: "reboot requested — it reconnects when back" });
|
|
1763
|
+
}
|
|
1764
|
+
return json(400, {
|
|
1765
|
+
error: `unknown host action '${action}' — interrupt | clear-queue | restart | refresh-loras | refresh-schema`
|
|
1766
|
+
});
|
|
1767
|
+
} catch (e) {
|
|
1768
|
+
return json(502, { error: `host '${hostId}' refused '${action}': ${extractErrorMessage(e)}` });
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
async rebindHostVars(hostId, host) {
|
|
1772
|
+
let widened = 0;
|
|
1773
|
+
const stale = [];
|
|
1774
|
+
for (const mod of this.modules) {
|
|
1775
|
+
if (mod.dw.host.data.id !== hostId)
|
|
1776
|
+
continue;
|
|
1777
|
+
await this.exclusive(mod.key, () => {
|
|
1778
|
+
for (const [name, varDef] of mod.dw.entries()) {
|
|
1779
|
+
if (varDef.kind === "choice") {
|
|
1780
|
+
const choice = varDef;
|
|
1781
|
+
if (choice.hostSlot == null)
|
|
1782
|
+
continue;
|
|
1783
|
+
const before = choice.choices.length;
|
|
1784
|
+
choice.bindHost(host);
|
|
1785
|
+
if (choice.choices.length !== before)
|
|
1786
|
+
widened++;
|
|
1787
|
+
if (choice.value != null && !choice.choices.includes(choice.value))
|
|
1788
|
+
stale.push(`${mod.key}/${name}: ${choice.value}`);
|
|
1789
|
+
continue;
|
|
1790
|
+
}
|
|
1791
|
+
if (varDef.kind !== "loras")
|
|
1792
|
+
continue;
|
|
1793
|
+
const lorasVar = varDef;
|
|
1794
|
+
if (lorasVar.optionsFilter == null)
|
|
1795
|
+
continue;
|
|
1796
|
+
const before = lorasVar.options.length;
|
|
1797
|
+
lorasVar.bindHost(host);
|
|
1798
|
+
if (lorasVar.options.length !== before)
|
|
1799
|
+
widened++;
|
|
1800
|
+
const known = new Set(lorasVar.options);
|
|
1801
|
+
const value = lorasVar.value;
|
|
1802
|
+
for (const picked of Object.keys(value)) {
|
|
1803
|
+
if (known.has(picked))
|
|
1804
|
+
continue;
|
|
1805
|
+
stale.push(`${mod.key}/${name}: ${picked}`);
|
|
1806
|
+
delete value[picked];
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
return Promise.resolve();
|
|
1810
|
+
});
|
|
1811
|
+
}
|
|
1812
|
+
return { widened, stale };
|
|
1813
|
+
}
|
|
1814
|
+
async refreshLoraMirror(hostId, host) {
|
|
1815
|
+
const sweep = await fetchLoraList(host);
|
|
1816
|
+
if (sweep.status === "absent")
|
|
1817
|
+
return json(400, {
|
|
1818
|
+
error: `${hostId} has no ComfyUI-Lora-Manager: the extension is not installed there. Mirror left untouched.`
|
|
1819
|
+
});
|
|
1820
|
+
if (sweep.status === "unreachable")
|
|
1821
|
+
return json(502, { error: `${hostId} unreachable — ${sweep.reason}. Mirror left untouched.` });
|
|
1822
|
+
if (sweep.status === "partial")
|
|
1823
|
+
return json(502, {
|
|
1824
|
+
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.`
|
|
1825
|
+
});
|
|
1826
|
+
const mirror = buildLoraMirror({
|
|
1827
|
+
hostId,
|
|
1828
|
+
hostUrl: host.getServerHostHTTP(),
|
|
1829
|
+
fetchedAt: new Date().toISOString(),
|
|
1830
|
+
items: sweep.items
|
|
1831
|
+
});
|
|
1832
|
+
writeLoraMirror(mirror);
|
|
1833
|
+
reloadLoraInfoCache();
|
|
1834
|
+
console.log(`[serve] lora mirror refreshed for ${hostId}: ${mirror.count} loras`);
|
|
1835
|
+
return json(200, {
|
|
1836
|
+
ok: true,
|
|
1837
|
+
host: hostId,
|
|
1838
|
+
action: "refresh-loras",
|
|
1839
|
+
count: mirror.count,
|
|
1840
|
+
note: `${mirror.count} loras synced`
|
|
1841
|
+
});
|
|
1842
|
+
}
|
|
1843
|
+
async replyLoraCivitaiFetch(hostId, lora) {
|
|
1844
|
+
const host = comfyts.hosts.get(hostId);
|
|
1845
|
+
if (host == null)
|
|
1846
|
+
return json(404, { error: `unknown host '${hostId}'` });
|
|
1847
|
+
const info = getLoraInfo(lora, hostId);
|
|
1848
|
+
const filePath = info == null ? null : lmFilePath(info);
|
|
1849
|
+
if (filePath == null)
|
|
1850
|
+
return json(404, { error: `'${lora}' is not in the lora manager mirror of ${hostId}: sync the mirror first` });
|
|
1851
|
+
const fetched = await fetchLoraCivitai(host, filePath);
|
|
1852
|
+
const sha256 = info == null ? null : lmSha256(info);
|
|
1853
|
+
if (!fetched.ok && /no version data found/i.test(fetched.reason) && sha256 != null) {
|
|
1854
|
+
recordCivitaiMiss({ hostId, sha256, miss: true });
|
|
1855
|
+
return json(200, {
|
|
1856
|
+
ok: true,
|
|
1857
|
+
host: hostId,
|
|
1858
|
+
lora,
|
|
1859
|
+
triggers: { state: "not-on-civitai" },
|
|
1860
|
+
note: `civitai does not know '${lora}' (a private or local lora): no trigger words to fetch`
|
|
1861
|
+
});
|
|
1862
|
+
}
|
|
1863
|
+
if (!fetched.ok)
|
|
1864
|
+
return json(502, { error: `civitai fetch failed for '${lora}': ${fetched.reason}` });
|
|
1865
|
+
if (sha256 != null)
|
|
1866
|
+
recordCivitaiMiss({ hostId, sha256, miss: false });
|
|
1867
|
+
const synced = await this.refreshLoraMirror(hostId, host);
|
|
1868
|
+
if (synced.status !== 200)
|
|
1869
|
+
return synced;
|
|
1870
|
+
const t = getLoraTriggers(lora, hostId);
|
|
1871
|
+
const note = t?.state === "words" ? `trigger words: ${t.words.join(", ")}` : t?.state === "none" ? `civitai lists no trigger words for '${lora}'` : `civitai has no metadata for '${lora}'`;
|
|
1872
|
+
return json(200, { ok: true, host: hostId, lora, triggers: t, note });
|
|
1873
|
+
}
|
|
1874
|
+
async replyHostDrift(hostId, full) {
|
|
1875
|
+
const host = comfyts.hosts.get(hostId);
|
|
1876
|
+
if (host == null)
|
|
1877
|
+
return json(404, { error: `unknown host '${hostId}'` });
|
|
1878
|
+
if (host.data.sdkAutoWrite === false)
|
|
1879
|
+
return json(200, { host: hostId, checked: false, changed: false, summary: "" });
|
|
1880
|
+
try {
|
|
1881
|
+
const drift = await host.checkSchemaDrift({ full });
|
|
1882
|
+
return json(200, {
|
|
1883
|
+
host: hostId,
|
|
1884
|
+
checked: true,
|
|
1885
|
+
full,
|
|
1886
|
+
changed: driftChanged(drift),
|
|
1887
|
+
summary: summarizeDrift(drift),
|
|
1888
|
+
drift
|
|
1889
|
+
});
|
|
1890
|
+
} catch (e) {
|
|
1891
|
+
return json(502, { error: `${hostId} unreachable: ${extractErrorMessage(e)}` });
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
async replyHostPing(hostId) {
|
|
1895
|
+
const host = comfyts.hosts.get(hostId);
|
|
1896
|
+
if (host == null)
|
|
1897
|
+
return json(404, { error: `unknown host '${hostId}'` });
|
|
1898
|
+
try {
|
|
1899
|
+
const res = await host.fetch("/system_stats", {});
|
|
1900
|
+
return json(200, { host: hostId, up: res.ok, status: res.status });
|
|
1901
|
+
} catch (e) {
|
|
1902
|
+
return json(200, { host: hostId, up: false, reason: extractErrorMessage(e) });
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
async replyHostLogs(hostId) {
|
|
1906
|
+
const host = comfyts.hosts.get(hostId);
|
|
1907
|
+
if (host == null)
|
|
1908
|
+
return json(404, { error: `unknown host '${hostId}'` });
|
|
1909
|
+
try {
|
|
1910
|
+
const raw = await host.fetchRawLogs();
|
|
1911
|
+
const lines = [];
|
|
1912
|
+
const partial = assembleLogChunks({ lines, partial: "", entries: raw.entries });
|
|
1913
|
+
if (partial.trim() !== "")
|
|
1914
|
+
lines.push(partial);
|
|
1915
|
+
return json(200, { host: hostId, lines: lines.slice(-200) });
|
|
1916
|
+
} catch (e) {
|
|
1917
|
+
return json(502, { error: `could not read the logs of '${hostId}': ${extractErrorMessage(e)}` });
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
replyHosts() {
|
|
1921
|
+
return json(200, {
|
|
1922
|
+
hosts: this.knownHosts(),
|
|
1923
|
+
defaults: Object.fromEntries(this.modules.map((m) => [m.key, m.dw.host.data.id])),
|
|
1924
|
+
overrides: this.settings.hostOverride
|
|
1925
|
+
});
|
|
1926
|
+
}
|
|
1927
|
+
replySetHost(modKey, req) {
|
|
1928
|
+
const mod = this.moduleByKey(modKey);
|
|
1929
|
+
if (mod == null)
|
|
1930
|
+
return json(404, { error: `unknown module '${modKey}'` });
|
|
1931
|
+
let parsed;
|
|
1932
|
+
try {
|
|
1933
|
+
parsed = JSON.parse(req.body ?? "");
|
|
1934
|
+
} catch (e) {
|
|
1935
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
1936
|
+
}
|
|
1937
|
+
const wanted = parsed != null && typeof parsed === "object" ? parsed.host : null;
|
|
1938
|
+
if (wanted != null && typeof wanted !== "string")
|
|
1939
|
+
return json(400, { error: 'body must be { "host": "<host id>" } or { "host": null } to reset' });
|
|
1940
|
+
const next = { ...this.settings.hostOverride };
|
|
1941
|
+
if (wanted == null || wanted === mod.dw.host.data.id)
|
|
1942
|
+
delete next[mod.key];
|
|
1943
|
+
else {
|
|
1944
|
+
if (!comfyts.hosts.has(wanted))
|
|
1945
|
+
return json(400, {
|
|
1946
|
+
error: `unknown host '${wanted}' — known: ${[...comfyts.hosts.keys()].join(", ")}`
|
|
1947
|
+
});
|
|
1948
|
+
next[mod.key] = wanted;
|
|
1949
|
+
}
|
|
1950
|
+
this.settings = { ...this.settings, hostOverride: next };
|
|
1951
|
+
try {
|
|
1952
|
+
writeServeSettings(this.settings);
|
|
1953
|
+
} catch (e) {
|
|
1954
|
+
return json(500, { error: `host applied for this session but not saved: ${extractErrorMessage(e)}` });
|
|
1955
|
+
}
|
|
1956
|
+
const target = next[mod.key] ?? mod.dw.host.data.id;
|
|
1957
|
+
console.log(`[serve] ${mod.key} runs on ${target}${next[mod.key] != null ? " (override)" : ""}`);
|
|
1958
|
+
return json(200, { ok: true, module: mod.key, host: target, overrides: this.settings.hostOverride });
|
|
1959
|
+
}
|
|
1960
|
+
memoryBlob(key, bytes, filename) {
|
|
1961
|
+
const contentType = CONTENT_TYPES[extname(filename).toLowerCase()] ?? sniffImageContentType(bytes);
|
|
1962
|
+
return { key, bytes, contentType };
|
|
1963
|
+
}
|
|
1964
|
+
replyMemoryImage(key) {
|
|
1965
|
+
const hit = this.kept.blob(key);
|
|
1966
|
+
if (hit == null)
|
|
1967
|
+
return json(404, {
|
|
1968
|
+
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.`
|
|
1969
|
+
});
|
|
1970
|
+
return { status: 200, contentType: hit.contentType, body: hit.bytes };
|
|
1971
|
+
}
|
|
1972
|
+
savePrefixFor(modKey) {
|
|
1973
|
+
const stored = this.settings.savePrefix[modKey]?.trim() ?? "";
|
|
1974
|
+
return stored === "" ? modKey : stored;
|
|
1975
|
+
}
|
|
1976
|
+
replySaveSettings(req) {
|
|
1977
|
+
let parsed;
|
|
1978
|
+
try {
|
|
1979
|
+
parsed = JSON.parse(req.body ?? "");
|
|
1980
|
+
} catch (e) {
|
|
1981
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
1982
|
+
}
|
|
1983
|
+
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
1984
|
+
return json(400, {
|
|
1985
|
+
error: 'body must be { "saveToDisk"?: true | false, "savePrefix"?: { "<module>": "path" }, "memoryBudgetMb"?: number }'
|
|
1986
|
+
});
|
|
1987
|
+
const wanted = parsed;
|
|
1988
|
+
let next = this.settings;
|
|
1989
|
+
if (wanted.saveToDisk != null) {
|
|
1990
|
+
if (typeof wanted.saveToDisk !== "boolean")
|
|
1991
|
+
return json(400, { error: '"saveToDisk" must be true or false' });
|
|
1992
|
+
next = { ...next, saveToDisk: wanted.saveToDisk };
|
|
1993
|
+
}
|
|
1994
|
+
if (wanted.savePrefix != null) {
|
|
1995
|
+
if (typeof wanted.savePrefix !== "object" || Array.isArray(wanted.savePrefix))
|
|
1996
|
+
return json(400, { error: '"savePrefix" must be { "<module>": "path" }' });
|
|
1997
|
+
const prefixes = { ...next.savePrefix };
|
|
1998
|
+
for (const [modKey, raw] of Object.entries(wanted.savePrefix)) {
|
|
1999
|
+
if (this.moduleByKey(modKey) == null)
|
|
2000
|
+
return json(404, { error: `unknown module '${modKey}'` });
|
|
2001
|
+
if (typeof raw !== "string")
|
|
2002
|
+
return json(400, { error: `prefix for '${modKey}' must be a string` });
|
|
2003
|
+
const clean = validSavePrefix(raw);
|
|
2004
|
+
if (clean == null)
|
|
2005
|
+
return json(400, {
|
|
2006
|
+
error: `invalid prefix '${raw}' — folder names only, "a/b" allowed, no ".." and no absolute path`
|
|
2007
|
+
});
|
|
2008
|
+
if (clean === "")
|
|
2009
|
+
delete prefixes[modKey];
|
|
2010
|
+
else
|
|
2011
|
+
prefixes[modKey] = clean;
|
|
2012
|
+
}
|
|
2013
|
+
next = { ...next, savePrefix: prefixes };
|
|
2014
|
+
}
|
|
2015
|
+
if (wanted.memoryBudgetMb != null) {
|
|
2016
|
+
const mb = validMemoryBudgetMb(wanted.memoryBudgetMb);
|
|
2017
|
+
if (mb == null)
|
|
2018
|
+
return json(400, { error: '"memoryBudgetMb" must be a number of MB, 1 to 100000' });
|
|
2019
|
+
next = { ...next, memoryBudgetMb: mb };
|
|
2020
|
+
}
|
|
2021
|
+
const saveToDisk = next.saveToDisk;
|
|
2022
|
+
this.settings = next;
|
|
2023
|
+
this.kept.setBudget(next.memoryBudgetMb * MB);
|
|
2024
|
+
try {
|
|
2025
|
+
writeServeSettings(this.settings);
|
|
2026
|
+
} catch (e) {
|
|
2027
|
+
return json(500, { error: `setting applied for this session but not saved: ${extractErrorMessage(e)}` });
|
|
2028
|
+
}
|
|
2029
|
+
console.log(`[serve] outputs ${saveToDisk ? "SAVE to disk" : "stay in MEMORY"}`);
|
|
2030
|
+
return this.replySettings();
|
|
2031
|
+
}
|
|
2032
|
+
replySettings() {
|
|
2033
|
+
return json(200, {
|
|
2034
|
+
...this.settings,
|
|
2035
|
+
effectivePrefix: Object.fromEntries(this.modules.map((m) => [m.key, this.savePrefixFor(m.key)]))
|
|
2036
|
+
});
|
|
2037
|
+
}
|
|
2038
|
+
tabs = null;
|
|
2039
|
+
tabsFile() {
|
|
2040
|
+
return join4(comfyts.baseFolder, SERVE_TABS_FILE);
|
|
2041
|
+
}
|
|
2042
|
+
liveTabs(raw) {
|
|
2043
|
+
return readTabs(raw, this.modules.map((m) => ({ module: m.key, drafts: this.draftsFor(m) })));
|
|
2044
|
+
}
|
|
2045
|
+
replyTabs() {
|
|
2046
|
+
if (this.tabs == null) {
|
|
2047
|
+
const path = this.tabsFile();
|
|
2048
|
+
let raw = [];
|
|
2049
|
+
try {
|
|
2050
|
+
if (existsSync6(path))
|
|
2051
|
+
raw = JSON.parse(readFileSync5(path, "utf8"));
|
|
2052
|
+
} catch (e) {
|
|
2053
|
+
console.error(`[serve] \uD83D\uDD34 open tabs unreadable (${path}), starting with none:`, e);
|
|
2054
|
+
}
|
|
2055
|
+
this.tabs = this.liveTabs(raw);
|
|
2056
|
+
}
|
|
2057
|
+
this.tabs = this.liveTabs(this.tabs);
|
|
2058
|
+
return json(200, { tabs: this.tabs });
|
|
2059
|
+
}
|
|
2060
|
+
replySaveTabs(req) {
|
|
2061
|
+
let parsed;
|
|
2062
|
+
try {
|
|
2063
|
+
parsed = JSON.parse(req.body ?? "");
|
|
2064
|
+
} catch (e) {
|
|
2065
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
2066
|
+
}
|
|
2067
|
+
const raw = parsed != null && typeof parsed === "object" ? parsed.tabs : undefined;
|
|
2068
|
+
if (!Array.isArray(raw) || raw.length > 100)
|
|
2069
|
+
return json(400, { error: 'expects { "tabs": [{ "module", "draft" }, …] }' });
|
|
2070
|
+
this.tabs = this.liveTabs(raw);
|
|
2071
|
+
try {
|
|
2072
|
+
mkdirSync5(comfyts.baseFolder, { recursive: true });
|
|
2073
|
+
writeFileSync5(this.tabsFile(), JSON.stringify(this.tabs, null, 2));
|
|
2074
|
+
} catch (e) {
|
|
2075
|
+
console.error(`[serve] \uD83D\uDD34 open tabs not saved to ${this.tabsFile()}:`, e);
|
|
2076
|
+
return json(200, { tabs: this.tabs, warning: `not saved: ${extractErrorMessage(e)}` });
|
|
2077
|
+
}
|
|
2078
|
+
return json(200, { tabs: this.tabs });
|
|
2079
|
+
}
|
|
2080
|
+
tagSources = new TagSources({
|
|
2081
|
+
cacheDir: () => join4(comfyts.baseFolder, "cache", "tags"),
|
|
2082
|
+
fetchText: async (url) => {
|
|
2083
|
+
const res = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(TAG_LIST_TIMEOUT_MS) });
|
|
2084
|
+
if (!res.ok)
|
|
2085
|
+
throw new Error(`tag list download failed (http ${res.status}): ${url}`);
|
|
2086
|
+
return new TextDecoder().decode(await readCapped(res, TAG_LIST_CAP, url));
|
|
2087
|
+
}
|
|
2088
|
+
});
|
|
2089
|
+
async replyTags(modKey, varName, url) {
|
|
2090
|
+
const mod = this.moduleByKey(modKey);
|
|
2091
|
+
if (mod == null)
|
|
2092
|
+
return json(404, { error: `unknown workflow '${modKey}'` });
|
|
2093
|
+
const found = mod.dw.entries().find(([k]) => k === varName)?.[1];
|
|
2094
|
+
if (found == null)
|
|
2095
|
+
return json(404, { error: `workflow '${modKey}' has no var '${varName}'` });
|
|
2096
|
+
const tags = found.kind === "prompt" ? found.tags : null;
|
|
2097
|
+
if (tags == null)
|
|
2098
|
+
return json(404, { error: `var '${varName}' declares no tag list (v.prompt(…, { tags }))` });
|
|
2099
|
+
const params = new URLSearchParams(url.split("?")[1] ?? "");
|
|
2100
|
+
const limit = Math.min(100, Math.max(1, Number(params.get("limit") ?? "20") || 20));
|
|
2101
|
+
try {
|
|
2102
|
+
const list = await this.tagSources.load(resolveTagSource(tags.url, mod.file));
|
|
2103
|
+
return json(200, { hits: list.search(params.get("q") ?? "", limit) });
|
|
2104
|
+
} catch (e) {
|
|
2105
|
+
console.error(`[serve] \uD83D\uDD34 tag list for ${modKey}/${varName}: ${extractErrorMessage(e)}`);
|
|
2106
|
+
return json(502, { error: extractErrorMessage(e) });
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
replyPromptEnhancers() {
|
|
2110
|
+
try {
|
|
2111
|
+
return json(200, { enhancers: listPromptEnhancers() });
|
|
2112
|
+
} catch (e) {
|
|
2113
|
+
return json(500, { error: `prompt-enhancers folder unreadable: ${extractErrorMessage(e)}` });
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
replySavePromptEnhancer(rawName, req) {
|
|
2117
|
+
const name = validStoreName(rawName);
|
|
2118
|
+
if (name == null)
|
|
2119
|
+
return json(400, { error: `invalid enhancer name '${rawName}' — letters/digits then letters, digits, ". -_"` });
|
|
2120
|
+
let parsed;
|
|
2121
|
+
try {
|
|
2122
|
+
parsed = JSON.parse(req.body ?? "");
|
|
2123
|
+
} catch (e) {
|
|
2124
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
2125
|
+
}
|
|
2126
|
+
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
2127
|
+
return json(400, { error: 'body must be { "text": "<master prompt>" }' });
|
|
2128
|
+
const text = parsed.text;
|
|
2129
|
+
if (typeof text !== "string")
|
|
2130
|
+
return json(400, { error: 'body must be { "text": "<master prompt>" }' });
|
|
2131
|
+
try {
|
|
2132
|
+
writePromptEnhancer(name, text);
|
|
2133
|
+
} catch (e) {
|
|
2134
|
+
return json(500, { error: `could not write enhancer '${name}': ${extractErrorMessage(e)}` });
|
|
2135
|
+
}
|
|
2136
|
+
return json(200, { ok: true, name, enhancers: listPromptEnhancers() });
|
|
2137
|
+
}
|
|
2138
|
+
replyDeletePromptEnhancer(rawName) {
|
|
2139
|
+
const name = validStoreName(rawName);
|
|
2140
|
+
if (name == null)
|
|
2141
|
+
return json(400, { error: `invalid enhancer name '${rawName}'` });
|
|
2142
|
+
try {
|
|
2143
|
+
deletePromptEnhancer(name);
|
|
2144
|
+
} catch (e) {
|
|
2145
|
+
return json(500, { error: `could not delete enhancer '${name}': ${extractErrorMessage(e)}` });
|
|
2146
|
+
}
|
|
2147
|
+
console.log(`[serve] prompt enhancer deleted: ${name}`);
|
|
2148
|
+
return json(200, { ok: true, name, enhancers: listPromptEnhancers() });
|
|
2149
|
+
}
|
|
2150
|
+
replyLlmConfigs() {
|
|
2151
|
+
try {
|
|
2152
|
+
return json(200, { configs: listLlmConfigs() });
|
|
2153
|
+
} catch (e) {
|
|
2154
|
+
return json(500, { error: `llm-configs folder unreadable: ${extractErrorMessage(e)}` });
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
replySaveLlmConfig(rawName, req) {
|
|
2158
|
+
const name = validStoreName(rawName);
|
|
2159
|
+
if (name == null)
|
|
2160
|
+
return json(400, { error: `invalid config name '${rawName}' — letters/digits then letters, digits, ". -_"` });
|
|
2161
|
+
let parsed;
|
|
2162
|
+
try {
|
|
2163
|
+
parsed = JSON.parse(req.body ?? "");
|
|
2164
|
+
} catch (e) {
|
|
2165
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
2166
|
+
}
|
|
2167
|
+
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
2168
|
+
return json(400, { error: "body must be { provider, baseUrl, model, effort, thinkingOnly }" });
|
|
2169
|
+
try {
|
|
2170
|
+
writeLlmConfig(name, normalizeLlmConfig(parsed));
|
|
2171
|
+
} catch (e) {
|
|
2172
|
+
return json(500, { error: `could not write llm config '${name}': ${extractErrorMessage(e)}` });
|
|
2173
|
+
}
|
|
2174
|
+
return json(200, { ok: true, name, configs: listLlmConfigs() });
|
|
2175
|
+
}
|
|
2176
|
+
replyDeleteLlmConfig(rawName) {
|
|
2177
|
+
const name = validStoreName(rawName);
|
|
2178
|
+
if (name == null)
|
|
2179
|
+
return json(400, { error: `invalid config name '${rawName}'` });
|
|
2180
|
+
try {
|
|
2181
|
+
deleteLlmConfig(name);
|
|
2182
|
+
} catch (e) {
|
|
2183
|
+
return json(500, { error: `could not delete llm config '${name}': ${extractErrorMessage(e)}` });
|
|
2184
|
+
}
|
|
2185
|
+
console.log(`[serve] llm config deleted: ${name}`);
|
|
2186
|
+
return json(200, { ok: true, name, configs: listLlmConfigs() });
|
|
2187
|
+
}
|
|
2188
|
+
liveRuns = new Map;
|
|
2189
|
+
latentPreviews = new Map;
|
|
2190
|
+
latentSeq = 0;
|
|
2191
|
+
replyRunStatus(modKey) {
|
|
2192
|
+
const mod = this.moduleByKey(modKey);
|
|
2193
|
+
if (mod == null)
|
|
2194
|
+
return json(404, { error: `unknown module '${modKey}'` });
|
|
2195
|
+
const exec = this.liveRuns.get(mod.key);
|
|
2196
|
+
const running = exec != null && exec.status !== "Success" && exec.status !== "Failure";
|
|
2197
|
+
return json(200, {
|
|
2198
|
+
running,
|
|
2199
|
+
status: exec?.status ?? "idle",
|
|
2200
|
+
percent: running ? exec.progressGlobal?.percent ?? null : null,
|
|
2201
|
+
node: running ? exec.progress?.nodeName ?? null : null,
|
|
2202
|
+
nodeProgress: running && exec.progress?.nodeProgress != null ? { value: exec.progress.nodeProgress.value, max: exec.progress.nodeProgress.max } : null,
|
|
2203
|
+
progressText: running ? exec.progress?.progressText ?? null : null,
|
|
2204
|
+
hasPreview: this.latentPreviews.has(mod.key),
|
|
2205
|
+
previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null
|
|
2206
|
+
});
|
|
2207
|
+
}
|
|
2208
|
+
replyRunPreview(modKey) {
|
|
2209
|
+
const mod = this.moduleByKey(modKey);
|
|
2210
|
+
if (mod == null)
|
|
2211
|
+
return json(404, { error: `unknown module '${modKey}'` });
|
|
2212
|
+
const preview = this.latentPreviews.get(mod.key);
|
|
2213
|
+
if (preview == null)
|
|
2214
|
+
return json(404, { error: "no latent preview yet" });
|
|
2215
|
+
return {
|
|
2216
|
+
status: 200,
|
|
2217
|
+
contentType: preview.mime !== "" ? preview.mime : sniffImageContentType(preview.bytes),
|
|
2218
|
+
body: preview.bytes
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
hostById(hostId) {
|
|
2222
|
+
return this.modules.map((m) => m.dw.host).find((h) => h.data.id === hostId) ?? null;
|
|
2223
|
+
}
|
|
2224
|
+
hostIds() {
|
|
2225
|
+
return [...new Set(this.modules.map((m) => m.dw.host.data.id))].join(", ");
|
|
2226
|
+
}
|
|
2227
|
+
replyLoraInfo(hostId, lora) {
|
|
2228
|
+
if (this.hostById(hostId) == null)
|
|
2229
|
+
return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
|
|
2230
|
+
refreshLoraInfoCacheIfChanged();
|
|
2231
|
+
const item = getLoraInfo(lora, hostId);
|
|
2232
|
+
const civitai = item == null ? null : lmCivitai(item);
|
|
2233
|
+
return json(200, {
|
|
2234
|
+
name: lora,
|
|
2235
|
+
displayName: getLoraDisplayName(lora, hostId),
|
|
2236
|
+
triggerWords: getLoraTriggerWords(lora, hostId),
|
|
2237
|
+
known: item != null,
|
|
2238
|
+
baseModel: item == null ? null : lmBaseModel(item),
|
|
2239
|
+
folder: item == null ? null : lmFolder(item),
|
|
2240
|
+
filePath: item == null ? null : lmFilePath(item),
|
|
2241
|
+
fileSize: item == null ? null : lmFileSize(item),
|
|
2242
|
+
tags: item == null ? [] : lmTags(item),
|
|
2243
|
+
notes: item == null ? "" : lmNotes(item),
|
|
2244
|
+
civitaiUrl: civitai?.modelId == null ? null : `https://civitai.com/models/${civitai.modelId}`,
|
|
2245
|
+
civitaiVersion: civitai?.name ?? null
|
|
2246
|
+
});
|
|
2247
|
+
}
|
|
2248
|
+
async replyLoraAbout(hostId, lora) {
|
|
2249
|
+
const host = this.hostById(hostId);
|
|
2250
|
+
if (host == null)
|
|
2251
|
+
return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
|
|
2252
|
+
refreshLoraInfoCacheIfChanged();
|
|
2253
|
+
const item = getLoraInfo(lora, hostId);
|
|
2254
|
+
if (item == null)
|
|
2255
|
+
return json(200, { known: false, description: null, examples: [], examplesReason: null });
|
|
2256
|
+
const filePath = lmFilePath(item);
|
|
2257
|
+
const sha = lmSha256(item);
|
|
2258
|
+
const [description, examples] = await Promise.all([
|
|
2259
|
+
filePath == null ? Promise.resolve(null) : fetchLoraDescription(host, filePath),
|
|
2260
|
+
sha == null ? Promise.resolve({ files: [], reason: null }) : fetchLoraExampleImages(host, sha)
|
|
2261
|
+
]);
|
|
2262
|
+
return json(200, {
|
|
2263
|
+
known: true,
|
|
2264
|
+
description,
|
|
2265
|
+
examples: examples.files,
|
|
2266
|
+
examplesReason: examples.reason
|
|
2267
|
+
});
|
|
2268
|
+
}
|
|
2269
|
+
previewSweeps = new Map;
|
|
2270
|
+
async replyLoraPreview(hostId, lora) {
|
|
2271
|
+
const host = this.hostById(hostId);
|
|
2272
|
+
if (host == null)
|
|
2273
|
+
return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` });
|
|
2274
|
+
refreshLoraInfoCacheIfChanged();
|
|
2275
|
+
let url = getLoraPreviewUrl(lora, hostId);
|
|
2276
|
+
if (url == null) {
|
|
2277
|
+
let sweep = this.previewSweeps.get(hostId);
|
|
2278
|
+
if (sweep == null) {
|
|
2279
|
+
sweep = fetchLoraList(host).then((r) => {
|
|
2280
|
+
if (r.status === "unreachable") {
|
|
2281
|
+
this.previewSweeps.delete(hostId);
|
|
2282
|
+
return { status: r.status, map: null };
|
|
2283
|
+
}
|
|
2284
|
+
return { status: r.status, map: r.status === "absent" ? null : loraPreviewMapFrom(r.items) };
|
|
2285
|
+
});
|
|
2286
|
+
this.previewSweeps.set(hostId, sweep);
|
|
2287
|
+
}
|
|
2288
|
+
const swept = await sweep;
|
|
2289
|
+
url = swept.map?.get(loraKey(lora)) ?? null;
|
|
2290
|
+
if (url == null && swept.status === "unreachable")
|
|
2291
|
+
return json(404, { error: `host '${hostId}' is unreachable — no preview to fetch` });
|
|
2292
|
+
if (url == null && swept.status === "absent")
|
|
2293
|
+
return json(404, { error: `lora-manager extension not detected on '${hostId}'` });
|
|
2294
|
+
}
|
|
2295
|
+
if (url == null)
|
|
2296
|
+
return json(404, { error: `no preview known for '${lora}' (run: comfy-ts loras --id ${hostId})` });
|
|
2297
|
+
const bytes = await fetchLoraPreviewBytes(host, url);
|
|
2298
|
+
if (bytes == null)
|
|
2299
|
+
return json(404, { error: `no image preview for '${lora}' (host '${hostId}' unreachable, or not an image)` });
|
|
2300
|
+
return { status: 200, contentType: sniffImageContentType(bytes), body: bytes };
|
|
2301
|
+
}
|
|
2302
|
+
outputUrl(absPath) {
|
|
2303
|
+
if (!absPath.startsWith(this.outputRoot + "/"))
|
|
2304
|
+
return null;
|
|
2305
|
+
const rel = absPath.slice(this.outputRoot.length + 1);
|
|
2306
|
+
return "/outputs/" + rel.split("/").map(encodeURIComponent).join("/");
|
|
2307
|
+
}
|
|
2308
|
+
async generate(mod, draft, req) {
|
|
2309
|
+
let payload = {};
|
|
2310
|
+
if (req.body != null && req.body.trim() !== "") {
|
|
2311
|
+
let parsed;
|
|
2312
|
+
try {
|
|
2313
|
+
parsed = JSON.parse(req.body);
|
|
2314
|
+
} catch (e) {
|
|
2315
|
+
return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` });
|
|
2316
|
+
}
|
|
2317
|
+
if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
2318
|
+
return json(400, { error: 'body must be a json object: { "<var>": value, … }' });
|
|
2319
|
+
payload = parsed;
|
|
2320
|
+
}
|
|
2321
|
+
const t0 = Date.now();
|
|
2322
|
+
const seeds = {};
|
|
2323
|
+
const started = await this.exclusive(mod.key, () => this.prepareAndStart(mod, draft, payload, seeds));
|
|
2324
|
+
if ("error" in started)
|
|
2325
|
+
return json(started.status, { error: started.error });
|
|
2326
|
+
const execution = started.execution;
|
|
2327
|
+
this.liveRuns.set(mod.key, execution);
|
|
2328
|
+
console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`);
|
|
2329
|
+
await execution.done;
|
|
2330
|
+
const durationMs = Date.now() - t0;
|
|
2331
|
+
if (execution.status === "Failure") {
|
|
2332
|
+
const error = describeRunError(execution.data.error);
|
|
2333
|
+
console.error(`[serve] \uD83D\uDD34 ${mod.key}/${draft} failed after ${durationMs}ms: ${error}`);
|
|
2334
|
+
return json(500, { ok: false, module: mod.key, draft, promptId: execution.data.id, durationMs, error });
|
|
2335
|
+
}
|
|
2336
|
+
const produced = [`${execution.images.length} image(s)`];
|
|
2337
|
+
const audios = execution.audios ?? [];
|
|
2338
|
+
if (audios.length > 0)
|
|
2339
|
+
produced.push(`${audios.length} audio(s)`);
|
|
2340
|
+
const videos = execution.videos ?? [];
|
|
2341
|
+
if (videos.length > 0)
|
|
2342
|
+
produced.push(`${videos.length} video(s)`);
|
|
2343
|
+
const models3d = execution.models3d ?? [];
|
|
2344
|
+
if (models3d.length > 0)
|
|
2345
|
+
produced.push(`${models3d.length} 3d model(s)`);
|
|
2346
|
+
if ((execution.texts ?? []).length > 0)
|
|
2347
|
+
produced.push(`${(execution.texts ?? []).length} text(s)`);
|
|
2348
|
+
console.log(`[serve] \uD83D\uDFE2 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${produced.join(" · ")}`);
|
|
2349
|
+
const blobs = [];
|
|
2350
|
+
const imageKeys = execution.images.map((img, ix) => {
|
|
2351
|
+
if (img.absPath != null || img.buffer == null)
|
|
2352
|
+
return null;
|
|
2353
|
+
const key = `${execution.data.id}/${ix}`;
|
|
2354
|
+
blobs.push(this.memoryBlob(key, img.buffer, img.filename));
|
|
2355
|
+
return key;
|
|
2356
|
+
});
|
|
2357
|
+
const audioKeys = audios.map((a, ix) => {
|
|
2358
|
+
if (a.absPath != null)
|
|
2359
|
+
return null;
|
|
2360
|
+
const key = `audio/${execution.data.id}/${ix}`;
|
|
2361
|
+
blobs.push(this.memoryBlob(key, a.bytes, a.filename));
|
|
2362
|
+
return key;
|
|
2363
|
+
});
|
|
2364
|
+
const videoKeys = videos.map((a, ix) => {
|
|
2365
|
+
if (a.absPath != null)
|
|
2366
|
+
return null;
|
|
2367
|
+
const key = `video/${execution.data.id}/${ix}`;
|
|
2368
|
+
blobs.push(this.memoryBlob(key, a.bytes, a.filename));
|
|
2369
|
+
return key;
|
|
2370
|
+
});
|
|
2371
|
+
const model3dKeys = models3d.map((m, ix) => {
|
|
2372
|
+
if (m.absPath != null)
|
|
2373
|
+
return null;
|
|
2374
|
+
const key = `model3d/${execution.data.id}/${ix}`;
|
|
2375
|
+
blobs.push(this.memoryBlob(key, m.bytes, m.filename));
|
|
2376
|
+
return key;
|
|
2377
|
+
});
|
|
2378
|
+
const memoryUrl = (route, key) => `/${route}/${key.split("/").slice(route === "images" ? 0 : 1).map((seg) => encodeURIComponent(seg)).join("/")}`;
|
|
2379
|
+
const record = {
|
|
2380
|
+
ok: true,
|
|
2381
|
+
module: mod.key,
|
|
2382
|
+
draft,
|
|
2383
|
+
promptId: execution.data.id,
|
|
2384
|
+
durationMs,
|
|
2385
|
+
finishedAt: Date.now(),
|
|
2386
|
+
seeds,
|
|
2387
|
+
savedToDisk: this.settings.saveToDisk,
|
|
2388
|
+
texts: (execution.texts ?? []).map((t) => ({ nodeKey: t.nodeKey, text: t.text })),
|
|
2389
|
+
images: execution.images.map((img, ix) => {
|
|
2390
|
+
const key = imageKeys[ix];
|
|
2391
|
+
return {
|
|
2392
|
+
filename: img.filename,
|
|
2393
|
+
url: img.absPath != null ? this.outputUrl(img.absPath) : key != null ? memoryUrl("images", key) : null,
|
|
2394
|
+
absPath: img.absPath,
|
|
2395
|
+
...img.tags != null && img.tags.length > 0 ? { tags: [...img.tags] } : {}
|
|
2396
|
+
};
|
|
2397
|
+
}),
|
|
2398
|
+
audios: audios.map((a, ix) => {
|
|
2399
|
+
const key = audioKeys[ix];
|
|
2400
|
+
return {
|
|
2401
|
+
filename: a.filename,
|
|
2402
|
+
mime: a.mime,
|
|
2403
|
+
url: a.absPath != null ? this.outputUrl(a.absPath) : key != null ? memoryUrl("audio", key) : null,
|
|
2404
|
+
absPath: a.absPath
|
|
2405
|
+
};
|
|
2406
|
+
}),
|
|
2407
|
+
videos: videos.map((a, ix) => {
|
|
2408
|
+
const key = videoKeys[ix];
|
|
2409
|
+
return {
|
|
2410
|
+
filename: a.filename,
|
|
2411
|
+
mime: a.mime,
|
|
2412
|
+
url: a.absPath != null ? this.outputUrl(a.absPath) : key != null ? memoryUrl("video", key) : null,
|
|
2413
|
+
absPath: a.absPath
|
|
2414
|
+
};
|
|
2415
|
+
}),
|
|
2416
|
+
models3d: models3d.map((m, ix) => {
|
|
2417
|
+
const key = model3dKeys[ix];
|
|
2418
|
+
return {
|
|
2419
|
+
filename: m.filename,
|
|
2420
|
+
mime: m.mime,
|
|
2421
|
+
format: m.format,
|
|
2422
|
+
size: m.bytes.byteLength,
|
|
2423
|
+
url: m.absPath != null ? this.outputUrl(m.absPath) : key != null ? memoryUrl("model3d", key) : null,
|
|
2424
|
+
absPath: m.absPath
|
|
2425
|
+
};
|
|
2426
|
+
}),
|
|
2427
|
+
...mod.dw.spec.widgets != null && mod.dw.spec.widgets.length > 0 ? { widgets: mod.dw.spec.widgets } : {}
|
|
2428
|
+
};
|
|
2429
|
+
this.kept.add({ record, imageKeys, audioKeys, videoKeys, model3dKeys, blobs });
|
|
2430
|
+
const first = execution.images[0];
|
|
2431
|
+
if (req.accept?.includes("image/") && first != null) {
|
|
2432
|
+
if (first.absPath != null) {
|
|
2433
|
+
const contentType = CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? "application/octet-stream";
|
|
2434
|
+
return { status: 200, contentType, body: new Uint8Array(readFileSync5(first.absPath)) };
|
|
2435
|
+
}
|
|
2436
|
+
const inMemory = this.kept.blob(imageKeys[0] ?? "");
|
|
2437
|
+
if (inMemory != null)
|
|
2438
|
+
return { status: 200, contentType: inMemory.contentType, body: inMemory.bytes };
|
|
2439
|
+
}
|
|
2440
|
+
return json(200, record);
|
|
2441
|
+
}
|
|
2442
|
+
async prepareAndStart(mod, draft, payload, seeds) {
|
|
2443
|
+
for (const [, varDef] of mod.dw.entries())
|
|
2444
|
+
varDef.reset();
|
|
2445
|
+
const draftPath = this.draftPath(mod, draft);
|
|
2446
|
+
if (draftPath == null)
|
|
2447
|
+
return { status: 404, error: `no draft '${draft}'` };
|
|
2448
|
+
if (existsSync6(draftPath)) {
|
|
2449
|
+
try {
|
|
2450
|
+
const values = JSON.parse(readFileSync5(draftPath, "utf8"));
|
|
2451
|
+
for (const [k, varDef] of mod.dw.entries())
|
|
2452
|
+
if (k in values)
|
|
2453
|
+
varDef.loadJSON(values[k]);
|
|
2454
|
+
} catch (e) {
|
|
2455
|
+
return { status: 500, error: `draft file unreadable: ${draftPath} — ${extractErrorMessage(e)}` };
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
const draftSeedValues = new Map;
|
|
2459
|
+
for (const [k, varDef] of mod.dw.entries())
|
|
2460
|
+
if (varDef.kind === "seed")
|
|
2461
|
+
draftSeedValues.set(k, varDef.value);
|
|
2462
|
+
const varMap = new Map(mod.dw.entries());
|
|
2463
|
+
for (const [k, rawValue] of Object.entries(payload)) {
|
|
2464
|
+
const varDef = varMap.get(k);
|
|
2465
|
+
if (varDef == null)
|
|
2466
|
+
return { status: 400, error: `unknown var '${k}' — vars: ${[...varMap.keys()].join(", ")}` };
|
|
2467
|
+
let value = rawValue;
|
|
2468
|
+
if (isMediaKind(varDef.kind) && typeof rawValue === "string" && /^https?:\/\//.test(rawValue)) {
|
|
2469
|
+
try {
|
|
2470
|
+
value = await this.downloadInput(rawValue);
|
|
2471
|
+
} catch (e) {
|
|
2472
|
+
return { status: 400, error: `var '${k}': ${extractErrorMessage(e)}` };
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
const err = applyVarPayload(varDef, value, {
|
|
2476
|
+
extraLoraOptions: varDef.kind === "loras" ? managerOnlyLoraOptions({
|
|
2477
|
+
hostId: mod.dw.host.data.id,
|
|
2478
|
+
options: varDef.options,
|
|
2479
|
+
filter: varDef.optionsFilter
|
|
2480
|
+
}) : undefined
|
|
2481
|
+
});
|
|
2482
|
+
if (err != null)
|
|
2483
|
+
return { status: 400, error: err };
|
|
2484
|
+
}
|
|
2485
|
+
for (const [k, varDef] of varMap) {
|
|
2486
|
+
const kind = varDef.kind;
|
|
2487
|
+
if (!isMediaKind(kind))
|
|
2488
|
+
continue;
|
|
2489
|
+
const media = varDef;
|
|
2490
|
+
if (!media.isSet())
|
|
2491
|
+
continue;
|
|
2492
|
+
const abs = media.absPath();
|
|
2493
|
+
const refuse = { status: 400, error: `${kind} var '${k}': not a usable ${kind} file` };
|
|
2494
|
+
if (!existsSync6(abs))
|
|
2495
|
+
return refuse;
|
|
2496
|
+
let real;
|
|
2497
|
+
try {
|
|
2498
|
+
real = realpathSync(abs);
|
|
2499
|
+
} catch {
|
|
2500
|
+
return refuse;
|
|
2501
|
+
}
|
|
2502
|
+
try {
|
|
2503
|
+
if (!statSync3(real).isFile())
|
|
2504
|
+
return refuse;
|
|
2505
|
+
} catch {
|
|
2506
|
+
return refuse;
|
|
2507
|
+
}
|
|
2508
|
+
if (!serveAcceptsMediaExt(kind, media.extensions, extname(real).toLowerCase().replace(/^\./, "")))
|
|
2509
|
+
return refuse;
|
|
2510
|
+
if (!looksLikeMedia(kind, real))
|
|
2511
|
+
return refuse;
|
|
2512
|
+
}
|
|
2513
|
+
for (const [k, varDef] of varMap) {
|
|
2514
|
+
if (varDef.kind !== "seed")
|
|
2515
|
+
continue;
|
|
2516
|
+
const seedVar = varDef;
|
|
2517
|
+
const stateKey = `${mod.key}/${draft}/${k}`;
|
|
2518
|
+
const draftValue = draftSeedValues.get(k) ?? seedVar.value;
|
|
2519
|
+
const prev = this.seedState.get(stateKey);
|
|
2520
|
+
const continues = !(k in payload) && (seedVar.mode === "+" || seedVar.mode === "-") && prev != null && (prev.draftBase === draftValue || prev.served.includes(draftValue));
|
|
2521
|
+
if (!(k in payload) && seedVar.mode === "?")
|
|
2522
|
+
seedVar.randomize();
|
|
2523
|
+
if (continues) {
|
|
2524
|
+
seedVar.set(prev.last + (seedVar.mode === "+" ? 1 : -1));
|
|
2525
|
+
const served = [...prev.served, seedVar.value].slice(-256);
|
|
2526
|
+
this.seedState.set(stateKey, { last: seedVar.value, draftBase: prev.draftBase, served });
|
|
2527
|
+
} else
|
|
2528
|
+
this.seedState.set(stateKey, { last: seedVar.value, draftBase: draftValue, served: [seedVar.value] });
|
|
2529
|
+
seeds[k] = seedVar.value;
|
|
2530
|
+
}
|
|
2531
|
+
this.latentPreviews.delete(mod.key);
|
|
2532
|
+
const runHost = this.runHostFor(mod);
|
|
2533
|
+
try {
|
|
2534
|
+
return {
|
|
2535
|
+
execution: await this.starter(mod, {
|
|
2536
|
+
saveToDisk: this.settings.saveToDisk,
|
|
2537
|
+
savePrefix: this.savePrefixFor(mod.key),
|
|
2538
|
+
host: runHost ?? undefined,
|
|
2539
|
+
onPreview: (p) => this.latentPreviews.set(mod.key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq })
|
|
2540
|
+
})
|
|
2541
|
+
};
|
|
2542
|
+
} catch (e) {
|
|
2543
|
+
if (e instanceof Error && (e.name === "MediaVarEmptyError" || e.name === "ImageVarEmptyError"))
|
|
2544
|
+
return { status: 400, error: e.message };
|
|
2545
|
+
if (e instanceof Error && e.name === "ComfyHostUnreachableError")
|
|
2546
|
+
return { status: 502, error: e.message };
|
|
2547
|
+
return { status: 500, error: extractErrorMessage(e) };
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
exclusive(key, fn) {
|
|
2551
|
+
const prev = this.chains.get(key) ?? Promise.resolve();
|
|
2552
|
+
const next = prev.then(fn);
|
|
2553
|
+
this.chains.set(key, next.catch(() => {}));
|
|
2554
|
+
return next;
|
|
2555
|
+
}
|
|
2556
|
+
urlInputPath(url, name) {
|
|
2557
|
+
const hash = createHash("sha1").update(url).digest("hex").slice(0, 16);
|
|
2558
|
+
return join4(this.outputRoot, "serve-inputs", `url-${hash}${extname(name)}`);
|
|
2559
|
+
}
|
|
2560
|
+
async downloadInput(url) {
|
|
2561
|
+
const cached = this.urlInputPath(url, basename(new URL(url).pathname));
|
|
2562
|
+
if (existsSync6(cached))
|
|
2563
|
+
return cached;
|
|
2564
|
+
try {
|
|
2565
|
+
return await this.fetchInput(url);
|
|
2566
|
+
} catch (e) {
|
|
2567
|
+
if (!(e instanceof DownloadRefused))
|
|
2568
|
+
console.error(`[serve] input download failed: ${url}:`, e);
|
|
2569
|
+
throw new DownloadRefused(url);
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
async fetchInput(url) {
|
|
2573
|
+
const res = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(INPUT_DOWNLOAD_TIMEOUT_MS) });
|
|
2574
|
+
if (!res.ok) {
|
|
2575
|
+
console.error(`[serve] input download failed (http ${res.status}): ${url}`);
|
|
2576
|
+
throw new DownloadRefused(url);
|
|
2577
|
+
}
|
|
2578
|
+
const declared = Number(res.headers.get("content-length") ?? "0");
|
|
2579
|
+
if (declared > INPUT_DOWNLOAD_CAP)
|
|
2580
|
+
throw new Error(`download too large (${declared} bytes): ${url}`);
|
|
2581
|
+
const bytes = await readCapped(res, INPUT_DOWNLOAD_CAP, url);
|
|
2582
|
+
const name = basename(new URL(url).pathname) || "input";
|
|
2583
|
+
const abs = this.urlInputPath(url, name);
|
|
2584
|
+
mkdirSync5(dirname3(abs), { recursive: true });
|
|
2585
|
+
writeFileSync5(abs, bytes);
|
|
2586
|
+
return abs;
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
export { describeVar, renderDescriptorLine, ServeApp };
|
|
2591
|
+
|
|
2592
|
+
//# debugId=F6DD40C33AA95C2364756E2164756E21
|
|
2593
|
+
//# sourceMappingURL=chunk-dvxjvwe7.js.map
|