comfy-ts 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +363 -0
  3. package/dist/cli.js +764 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index.cjs +4171 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +9910 -0
  8. package/dist/index.d.ts +9894 -58
  9. package/dist/index.js +4092 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/log-CdfgILde.js +10 -0
  12. package/dist/log-CdfgILde.js.map +1 -0
  13. package/dist/run-tui-SDSJo1Qf.js +3896 -0
  14. package/dist/run-tui-SDSJo1Qf.js.map +1 -0
  15. package/package.json +103 -75
  16. package/src/cli/comfy-ts-cli.ts +36 -0
  17. package/src/cli/gen.ts +47 -0
  18. package/src/cli/outline.ts +82 -0
  19. package/src/cli/tui/components/DraftsOverlay.tsx +44 -0
  20. package/src/cli/tui/components/EditField.tsx +27 -0
  21. package/src/cli/tui/components/Header.tsx +56 -0
  22. package/src/cli/tui/components/HostPanel.tsx +37 -0
  23. package/src/cli/tui/components/LogsPanel.tsx +23 -0
  24. package/src/cli/tui/components/LorasOverlay.tsx +49 -0
  25. package/src/cli/tui/components/OverlayList.tsx +25 -0
  26. package/src/cli/tui/components/PickerOverlays.tsx +66 -0
  27. package/src/cli/tui/components/PreviewPanel.tsx +78 -0
  28. package/src/cli/tui/components/PromptOverlay.tsx +16 -0
  29. package/src/cli/tui/components/StatusBar.tsx +171 -0
  30. package/src/cli/tui/components/TextOverlay.tsx +72 -0
  31. package/src/cli/tui/components/TreePanel.tsx +51 -0
  32. package/src/cli/tui/components/TuiApp.tsx +246 -0
  33. package/src/cli/tui/components/VarsPanel.tsx +86 -0
  34. package/src/cli/tui/findDefinedWorkflow.ts +16 -0
  35. package/src/cli/tui/keys.ts +20 -0
  36. package/src/cli/tui/protocolImagePainter.ts +95 -0
  37. package/src/cli/tui/run-tui.tsx +76 -0
  38. package/src/cli/tui/state/DraftsSt.ts +273 -0
  39. package/src/cli/tui/state/EditorSt.ts +289 -0
  40. package/src/cli/tui/state/ExecSt.ts +173 -0
  41. package/src/cli/tui/state/HostSt.ts +230 -0
  42. package/src/cli/tui/state/LogsSt.ts +107 -0
  43. package/src/cli/tui/state/LorasSt.ts +185 -0
  44. package/src/cli/tui/state/PickerSt.ts +112 -0
  45. package/src/cli/tui/state/PreviewSt.ts +288 -0
  46. package/src/cli/tui/state/QueueSt.ts +59 -0
  47. package/src/cli/tui/state/SettingsSt.ts +100 -0
  48. package/src/cli/tui/state/TreeSt.ts +122 -0
  49. package/src/cli/tui/state/TuiSt.ts +175 -0
  50. package/src/cli/tui/state/WorkflowsSt.ts +93 -0
  51. package/src/cli/tui-env.ts +8 -0
  52. package/src/errors/InvalidPromptError.ts +12 -0
  53. package/src/graph/ComfyNode.ts +403 -0
  54. package/src/graph/ComfyNodeID.ts +28 -0
  55. package/src/graph/ComfyNodeOutput.ts +16 -0
  56. package/src/graph/NodeSlotSize.ts +4 -0
  57. package/src/graph/autoValue.ts +17 -0
  58. package/src/host/ComfyHost.ts +690 -0
  59. package/src/host/ComfyInstallType.ts +15 -0
  60. package/src/host/ComfyManager.ts +232 -0
  61. package/src/host/ComfyUploader.ts +110 -0
  62. package/src/host/ComfyWorkflowBuilder.ts +60 -0
  63. package/src/host/Requirements.ts +55 -0
  64. package/src/host/ResilientWebsocket.ts +147 -0
  65. package/src/host/loraManagerApi.ts +98 -0
  66. package/src/image-utils/_getPngMetadata.ts +53 -0
  67. package/src/image-utils/_getWebpMetadata.ts +38 -0
  68. package/src/image-utils/_parseExifData.ts +53 -0
  69. package/src/index.ts +89 -0
  70. package/src/litegraph/LiteGraphGroup.ts +22 -0
  71. package/src/litegraph/LiteGraphJSON.ts +46 -0
  72. package/src/litegraph/LiteGraphLink.ts +23 -0
  73. package/src/litegraph/LiteGraphLinkID.ts +6 -0
  74. package/src/litegraph/LiteGraphNode.ts +69 -0
  75. package/src/litegraph/LiteGraphNodeInput.ts +27 -0
  76. package/src/litegraph/LiteGraphNodeOutput.ts +23 -0
  77. package/src/litegraph/LiteGraphSlotIndex.ts +6 -0
  78. package/src/litegraph/convertFlowToLiteGraphJSON.ts +114 -0
  79. package/src/manager/ComfyRegistry.ts +124 -0
  80. package/src/manager/generated/KnownComfyCustomNodeName.ts +19280 -0
  81. package/src/manager/generated/KnownComfyPluginTitle.ts +5130 -0
  82. package/src/manager/generated/KnownComfyPluginURL.ts +2589 -0
  83. package/src/manager/generated/KnownModel_Base.ts +126 -0
  84. package/src/manager/generated/KnownModel_FileName.ts +2287 -0
  85. package/src/manager/generated/KnownModel_Name.ts +2287 -0
  86. package/src/manager/generated/KnownModel_SavePath.ts +263 -0
  87. package/src/manager/generated/KnownModel_Type.ts +97 -0
  88. package/src/manager/json/alter-list.json +224 -0
  89. package/src/manager/json/custom-node-list.extra.ts +13 -0
  90. package/src/manager/json/custom-node-list.json +21948 -0
  91. package/src/manager/json/extension-node-map.json +31282 -0
  92. package/src/manager/json/github-stats.json +12602 -0
  93. package/src/manager/json/model-list.extra.ts +26 -0
  94. package/src/manager/json/model-list.json +5052 -0
  95. package/src/manager/loaders/step1_downloadComfyManagerJSONs.ts +56 -0
  96. package/src/manager/loaders/step2_custom-node-list-loader.ts +149 -0
  97. package/src/manager/loaders/step3_extension-node-map-loader.ts +189 -0
  98. package/src/manager/loaders/step4_model-list-loader.ts +159 -0
  99. package/src/manager/script-update-manager.bun.ts +18 -0
  100. package/src/manager/types/ComfyManagerAPIFetchPolicy.ts +9 -0
  101. package/src/manager/types/ComfyManagerAPIModelList.ts +10 -0
  102. package/src/manager/types/ComfyManagerAPIPluginList.ts +11 -0
  103. package/src/manager/types/ComfyManagerFileModelInfo.ts +5 -0
  104. package/src/manager/types/ComfyManagerFilePluginContent.ts +13 -0
  105. package/src/manager/types/ComfyManagerFilePluginList.ts +5 -0
  106. package/src/manager/types/ComfyManagerModelInfo.ts +18 -0
  107. package/src/manager/types/ComfyManagerPluginContentMetadata.ts +16 -0
  108. package/src/manager/types/ComfyManagerPluginEnums.ts +8 -0
  109. package/src/manager/types/ComfyManagerPluginInfo.ts +50 -0
  110. package/src/runner/ComfyExecution.ts +301 -0
  111. package/src/runner/ComfyExecutionStatus.ts +2 -0
  112. package/src/runner/ComfyWorkflow.ts +395 -0
  113. package/src/runner/ComfyWorkflowLayout.ts +96 -0
  114. package/src/runner/ComfyWsApi.ts +170 -0
  115. package/src/runner/MediaImage.ts +262 -0
  116. package/src/sdk-generator/ComfyNodeSchema.ts +79 -0
  117. package/src/sdk-generator/ComfySchema.ts +369 -0
  118. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +95 -0
  119. package/src/sdk-generator/Primitives.ts +76 -0
  120. package/src/sdk-generator/_getUnionNameBasedOnFirstFoundEnumName.ts +39 -0
  121. package/src/sdk-generator/_pythonModuleToNamespace.ts +27 -0
  122. package/src/sdk-generator/_toQualifiedNodeKey.ts +5 -0
  123. package/src/sdk-generator/comfy-api-json.ts +16 -0
  124. package/src/sdk-generator/comfyui-sdk-codegen.ts +287 -0
  125. package/src/sdk-generator/comfyui-types.ts +56 -0
  126. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -0
  127. package/src/ssh-host-manager/ssh-config-manager.ts +89 -0
  128. package/src/ssh-host-manager/ssh-config.windows.md +32 -0
  129. package/src/ssh-host-manager/ssh-manager.ts +114 -0
  130. package/src/state.ts +136 -0
  131. package/src/types/comfy-sdk.ts +106 -0
  132. package/src/types/index.ts +55 -0
  133. package/src/utils/CodeBuffer.ts +61 -0
  134. package/src/utils/ComfyColors.ts +38 -0
  135. package/src/utils/ansi.ts +33 -0
  136. package/src/utils/ansiImage.ts +36 -0
  137. package/src/utils/bang.ts +39 -0
  138. package/src/utils/deepCopyNaive.ts +1 -0
  139. package/src/utils/downloadFile.ts +77 -0
  140. package/src/utils/escapeJSKey.ts +32 -0
  141. package/src/utils/exhaust.ts +4 -0
  142. package/src/utils/extractErrorMessage.ts +11 -0
  143. package/src/utils/fuzzyMatch.ts +8 -0
  144. package/src/utils/githubRegexes.ts +2 -0
  145. package/src/utils/hashArrayBuffer.ts +6 -0
  146. package/src/utils/log.ts +9 -0
  147. package/src/utils/loraTag.ts +10 -0
  148. package/src/utils/mojibake.ts +60 -0
  149. package/src/utils/printArkResultInConsole.ts +16 -0
  150. package/src/utils/softValidate.ts +8 -0
  151. package/src/utils/stringifyReadable.ts +32 -0
  152. package/src/utils/toposort.ts +59 -0
  153. package/src/utils/tryExtracting.ts +41 -0
  154. package/src/utils/writeFile.ts +16 -0
  155. package/src/vars/ComfyVars.ts +531 -0
  156. package/src/vars/DefinedWorkflow.ts +112 -0
  157. package/src/vars/loraKeywords.ts +56 -0
  158. package/dist/index.d.mts +0 -74
  159. package/dist/index.mjs +0 -3
  160. package/dist/index.mjs.map +0 -1
  161. package/readme.md +0 -40
@@ -0,0 +1,690 @@
1
+ import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'
2
+ import { type } from 'arktype'
3
+ import type { MessageEvent } from 'ws'
4
+ import type { KnownComfyPluginTitle } from 'src/manager/generated/KnownComfyPluginTitle.ts'
5
+ import type { KnownComfyPluginURL } from 'src/manager/generated/KnownComfyPluginURL.ts'
6
+ import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPluginInfo.ts'
7
+ import type { ComfyExecution } from 'src/runner/ComfyExecution.ts'
8
+ import type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'
9
+ import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
10
+ import { convertLiteGraphToPrompt } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'
11
+ import { asComfyWorkflowID, ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
12
+ import {
13
+ type ComfyStatusData,
14
+ type LogEntry,
15
+ type PromptID,
16
+ type PromptRelated_WsMsg,
17
+ type WsMsg,
18
+ WsMsg_ark,
19
+ WsMsgLogsData_ark,
20
+ } from 'src/runner/ComfyWsApi.ts'
21
+ import { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
22
+ import { type ComfySchemaJSON, ComfySchemaJSON_ark } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
23
+ import type { EmbeddingName } from 'src/sdk-generator/comfyui-types.ts'
24
+ import { type AbsolutePath, type Maybe, type number_Timestamp, type Tagged } from 'src/types/index.ts'
25
+ import { exhaust } from 'src/utils/exhaust.ts'
26
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
27
+ import { printArkResultInConsole } from 'src/utils/printArkResultInConsole.ts'
28
+ import { readableStringify } from 'src/utils/stringifyReadable.ts'
29
+ import { logError as toastError, logInfo } from 'src/utils/log.ts'
30
+ import { writeFileAsync } from 'src/utils/writeFile.ts'
31
+ import type { ComfyInstallType } from 'src/host/ComfyInstallType.ts'
32
+ import { ComfyManager } from 'src/host/ComfyManager.ts'
33
+ import { ComfyUploader } from 'src/host/ComfyUploader.ts'
34
+ import type { Requirements } from 'src/host/Requirements.ts'
35
+ import { ResilientWebSocketClient } from 'src/host/ResilientWebsocket.ts'
36
+ import { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'
37
+ import type { VarsSpec } from 'src/vars/ComfyVars.ts'
38
+
39
+ export type ComfyHostID = Tagged<string, { HostID: true }>
40
+ export type ComfyHostData = {
41
+ id: string
42
+ host: string
43
+ port: number
44
+ https?: boolean
45
+
46
+ // for extra features using path manipulation
47
+ installType?: ComfyInstallType
48
+
49
+ // misc
50
+ onWsMessageAny?: (e: MessageEvent) => void
51
+ onWsMessageArrayBuffer?: (e: ArrayBuffer) => void
52
+ onWsMessageJSON?: (e: WsMsg) => void
53
+ }
54
+
55
+ export type ConnectOptions = {
56
+ /** 'auto' (default): reuse cache when fresh · 'refresh': always fetch · 'cache': never fetch */
57
+ schema?: 'auto' | 'refresh' | 'cache'
58
+ /** max cache age for 'auto' (default 24h) */
59
+ maxAgeMs?: number
60
+ }
61
+
62
+ // biome-ignore format: misc
63
+ type SchemaUpdateResult = Maybe<{ type: 'success' } | { type: 'error'; error: unknown }>
64
+
65
+ type ServerLog = {
66
+ at: string
67
+ content: string
68
+ id: number
69
+ }
70
+
71
+ export class ComfyHost<ID extends string = string> {
72
+ // ----- misc paths where we'll store host-related files -----
73
+ cacheFolder: AbsolutePath
74
+
75
+ comfyJSONPath: AbsolutePath
76
+ embeddingsPath: AbsolutePath
77
+ sdkDTSPath: AbsolutePath
78
+
79
+ /** the schema instance with all methods to interract with the host schema */
80
+ schema: ComfySchema
81
+ uploader = new ComfyUploader(this)
82
+
83
+ constructor(public data: ComfyHostData & { id: ID }) {
84
+ /** folder where file related to the host config will be cached */
85
+ this.cacheFolder = comfyts.resolveFromHosts(this.data.id)
86
+
87
+ // create the folder if it does not exist
88
+ const exists = existsSync(this.cacheFolder)
89
+ if (!exists) {
90
+ console.log('🟢 creating folder', this.cacheFolder)
91
+ mkdirSync(this.cacheFolder, { recursive: true })
92
+ }
93
+
94
+ this.comfyJSONPath = comfyts.resolve(this.cacheFolder, `object_info.json`)
95
+ this.embeddingsPath = comfyts.resolve(this.cacheFolder, `embeddings.json`)
96
+ this.sdkDTSPath = comfyts.resolve(this.cacheFolder, `sdk.d.ts`)
97
+
98
+ /** create a new schema */
99
+ this.schema = new ComfySchema({ embeddings: [], spec: {} })
100
+ }
101
+
102
+ /** helper to check if your host have whatever it needs to run your workflow */
103
+ matchRequirements = (requirements: Requirements[]): boolean => {
104
+ const repo = comfyts.registry
105
+ for (const req of requirements) {
106
+ if (req.optional) continue
107
+ if (req.type === 'customNodesByNodeKey') {
108
+ const plugins: ComfyManagerPluginInfo[] = repo.plugins_byNodeKey.get(req.nodeName) ?? []
109
+ if (!plugins.find((i) => this.manager.isPluginInstalled(i.title))) {
110
+ // console.log(`[❌ A] ${JSON.stringify(req)} NOT MATCHED`)
111
+ return false
112
+ }
113
+ } else if (req.type === 'customNodesByTitle') {
114
+ const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byTitle.get(req.title)
115
+ if (plugin == null) continue
116
+ if (!this.manager.isPluginInstalled(plugin.title)) {
117
+ // console.log(`[❌ B] ${JSON.stringify(req)} NOT MATCHED`)
118
+ return false
119
+ }
120
+ } else if (req.type === 'customNodesByURI') {
121
+ const plugin: ComfyManagerPluginInfo | undefined = repo.plugins_byFile.get(req.uri)
122
+ if (plugin == null) continue
123
+ if (!this.manager.isPluginInstalled(plugin.title)) {
124
+ // console.log(`[❌ C] ${JSON.stringify(req)} NOT MATCHED`)
125
+ return false
126
+ }
127
+ } else if (req.type === 'modelInManager') {
128
+ if (!this.manager.isModelInstalled(req.modelName)) {
129
+ // console.log(`[❌ D] ${JSON.stringify(req)} NOT MATCHED`)
130
+ return false
131
+ }
132
+ } else {
133
+ // exhaust(req.type)
134
+ }
135
+ }
136
+ return true
137
+ }
138
+
139
+ // ----- Rotating srever logs -----
140
+
141
+ /** server sent by the comfy-manager plugin */
142
+ readonly serverLogs: ServerLog[] = []
143
+
144
+ /** if true, request ComfyUI to forward logs */
145
+ private wantLog: boolean = true
146
+
147
+ /** maximum amount of logs to keep in memory */
148
+ readonly maxLogs: number = 200
149
+
150
+ /** last log id received */
151
+ private logId: number = 0
152
+
153
+ /** toggle server log forwarding so comfy-ts can */
154
+ toggleServerLogs = (): Promise<unknown> => {
155
+ this.wantLog = !this.wantLog
156
+ return this.manager.configureLogging(this.wantLog)
157
+ }
158
+
159
+ addLog = (content: string): void => {
160
+ if (this.serverLogs.length > this.maxLogs) this.serverLogs.shift()
161
+ const d = new Date().toISOString().slice(11, 19)
162
+ this.serverLogs.push({ content, id: this.logId++, at: d })
163
+ }
164
+
165
+ // ----- Misc helpers if you work with a local Comfy -----
166
+
167
+ /** root install of ComfyUI on the host filesystem */
168
+ get absolutePathToComfyUI(): Maybe<string> {
169
+ return this.data.installType?.absolutePathToComfyRoot
170
+ }
171
+
172
+ // ----- Misc helpers if you work with a local Comfy -----
173
+
174
+ get manager(): ComfyManager {
175
+ const value = new ComfyManager(this)
176
+ Object.defineProperty(this, 'manager', { value })
177
+ return value
178
+ }
179
+
180
+ // INIT -----------------------------------------------------------------------------
181
+ installCustomNodeByFile = async (customNodeFile: KnownComfyPluginURL): Promise<boolean> => {
182
+ const manager = comfyts.registry
183
+ const plugin: ComfyManagerPluginInfo | undefined = manager.plugins_byFile.get(customNodeFile)
184
+ if (plugin == null) throw new Error(`Unknown custom node for file: "${customNodeFile}"`)
185
+ return this.manager.installPlugin(plugin)
186
+ }
187
+
188
+ installCustomNodeByTitle = async (customNodeTitle: KnownComfyPluginTitle): Promise<boolean> => {
189
+ const manager = comfyts.registry
190
+ const plugin: ComfyManagerPluginInfo | undefined = manager.plugins_byTitle.get(customNodeTitle)
191
+ if (plugin == null) throw new Error(`Unknown custom node for title: "${customNodeTitle}"`)
192
+ return this.manager.installPlugin(plugin)
193
+ }
194
+
195
+ installCustomNode = async (customNode: ComfyManagerPluginInfo): Promise<boolean> => {
196
+ return this.manager.installPlugin(customNode)
197
+ }
198
+
199
+ // URLS -----------------------------------------------------------------------------
200
+ getServerHostHTTP(): string {
201
+ const method = this.data.https ? 'https' : 'http'
202
+ const host = this.data.host
203
+ const port = this.data.port
204
+ return `${method}://${host}:${port}`
205
+ }
206
+
207
+ getWSUrl = (): string => {
208
+ const method = this.data.https ? 'wss' : 'ws'
209
+ const host = this.data.host
210
+ const port = this.data.port
211
+ return `${method}://${host}:${port}/ws`
212
+ }
213
+
214
+ // LOGS -----------------------------------------------------------------------------
215
+ schemaRetrievalLogs: string[] = []
216
+
217
+ resetLog = (): void => {
218
+ this.schemaRetrievalLogs.splice(0, this.schemaRetrievalLogs.length)
219
+ }
220
+
221
+ // STARTING -----------------------------------------------------------------------------
222
+ get isConnected(): boolean {
223
+ return this.ws?.isOpen ?? false
224
+ }
225
+
226
+ workflow = (p: { id?: string } = {}): ComfyWorkflow<ID> => {
227
+ return new ComfyWorkflow(this, {
228
+ metadata: {},
229
+ id: p.id ? asComfyWorkflowID(p.id) : undefined,
230
+ })
231
+ }
232
+
233
+ /**
234
+ * define a re-runnable workflow: `build` re-executes with the current var
235
+ * values on every run(). The standard contract for tweak & re-run drivers
236
+ * (scripts, the TUI).
237
+ */
238
+ defineWorkflow = <V extends VarsSpec>(spec: DefineWorkflowSpec<ID, V>): DefinedWorkflow<ID, V> => {
239
+ return new DefinedWorkflow(this, spec)
240
+ }
241
+
242
+ /** import a workflow.json (litegraph format) as a live, editable workflow */
243
+ importWorkflowJson = (json: LiteGraphJSON, p: { id?: string } = {}): ComfyWorkflow<ID> => {
244
+ const apiJson = convertLiteGraphToPrompt(this.schema, json)
245
+ return this.importApiJson(apiJson, p)
246
+ }
247
+
248
+ /** import an api.json (ComfyUI prompt format) as a live, editable workflow */
249
+ importApiJson = (json: ComfyApiJson, p: { id?: string } = {}): ComfyWorkflow<ID> => {
250
+ const wf = new ComfyWorkflow(this, {
251
+ apiJson: json,
252
+ metadata: {},
253
+ id: p.id ? asComfyWorkflowID(p.id) : undefined,
254
+ })
255
+ wf.onUpdate(null, wf.data) // hydrate ComfyNode instances from the json
256
+ return wf
257
+ }
258
+
259
+ private _ready: Promise<void> | null = null
260
+ private _readyResolve: (() => void) | null = null
261
+ private _readyReject: ((e: unknown) => void) | null = null
262
+ private _schemaStrategy: NonNullable<ConnectOptions['schema']> = 'auto'
263
+ private _schemaMaxAgeMs: number = 24 * 3600_000
264
+
265
+ /**
266
+ * open the websocket; resolves once connected AND the schema is loaded.
267
+ * Schema strategy:
268
+ * - 'auto' (default): reuse .comfy-ts/ cache when younger than maxAgeMs — fast starts
269
+ * - 'refresh': always fetch object_info + regen the sdk
270
+ * - 'cache': never fetch (throws when no cache exists)
271
+ */
272
+ connect = (p: ConnectOptions = {}): Promise<void> => {
273
+ if (this._ready == null) {
274
+ this._schemaStrategy = p.schema ?? 'auto'
275
+ this._schemaMaxAgeMs = p.maxAgeMs ?? 24 * 3600_000
276
+ this._ready = new Promise<void>((res, rej) => {
277
+ this._readyResolve = res
278
+ this._readyReject = rej
279
+ })
280
+ this.initWebsocket()
281
+ }
282
+ return this._ready
283
+ }
284
+
285
+ /** close the websocket (e.g. to let a script exit) */
286
+ disconnect = (): void => {
287
+ this.ws?.disconnectPermanently()
288
+ this.ws = null
289
+ this._ready = null
290
+ }
291
+
292
+ private markReady(): void {
293
+ this._readyResolve?.()
294
+ this._readyResolve = null
295
+ this._readyReject = null
296
+ }
297
+
298
+ private markFailed(error: unknown): void {
299
+ // reject the pending connect() so callers fail fast instead of hanging
300
+ this._readyReject?.(error)
301
+ this._readyResolve = null
302
+ this._readyReject = null
303
+ }
304
+
305
+ private async writeSDKToDisk(): Promise<void> {
306
+ const comfySchemaTs = this.schema.codegenDTS({ hostId: this.data.id })
307
+ // skip the 4MB write when nothing changed (fast re-connects)
308
+ if (existsSync(this.sdkDTSPath) && readFileSync(this.sdkDTSPath, 'utf-8') === comfySchemaTs) return
309
+ await writeFileAsync(this.sdkDTSPath, comfySchemaTs, 'utf-8')
310
+ }
311
+
312
+ private shouldUseSchemaCache(): boolean {
313
+ if (this._schemaStrategy === 'refresh') return false
314
+ const exists = existsSync(this.comfyJSONPath)
315
+ if (this._schemaStrategy === 'cache') {
316
+ if (!exists) throw new Error(`connect({schema:'cache'}) but no cache at ${this.comfyJSONPath}`)
317
+ return true
318
+ }
319
+ if (!exists) return false
320
+ const ageMs = Date.now() - statSync(this.comfyJSONPath).mtimeMs
321
+ return ageMs < this._schemaMaxAgeMs
322
+ }
323
+
324
+ // WEBSCKET -----------------------------------------------------------------------------
325
+ /**
326
+ * will be created only after we've loaded cnfig file
327
+ * so we don't attempt to connect to some default server
328
+ * */
329
+ ws: Maybe<ResilientWebSocketClient> = null
330
+
331
+ /** resolves once the server assigned us a session id (first ws 'status' message) */
332
+ private _sessionResolve: (() => void) | null = null
333
+ private waitForSession(timeoutMs: number = 5000): Promise<void> {
334
+ if (this.comfySessionId !== 'temp') return Promise.resolve()
335
+ return new Promise<void>((res) => {
336
+ this._sessionResolve = res
337
+ // some setups never send a sid — proceed after the timeout, loudly
338
+ setTimeout(() => {
339
+ if (this._sessionResolve != null) {
340
+ console.error(
341
+ `🔴 no session id from ${this.data.id} after ${timeoutMs}ms — executions may not route back`,
342
+ )
343
+ this._sessionResolve = null
344
+ res()
345
+ }
346
+ }, timeoutMs).unref?.()
347
+ })
348
+ }
349
+
350
+ private initWebsocket(): ResilientWebSocketClient {
351
+ logInfo(`[👢] WEBSOCKET: starting client to ComfyUI host ${this.data.id}`)
352
+ this.ws = new ResilientWebSocketClient({
353
+ onConnectOrReconnect: async (): Promise<void> => {
354
+ logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`)
355
+ if (this.shouldUseSchemaCache()) {
356
+ try {
357
+ await this.loadSchemaFromCache()
358
+ // the server routes execution events by client_id: without the
359
+ // session id from the first 'status' message, prompts we POST
360
+ // would report to nobody. The slow fetch path masked this race.
361
+ await this.waitForSession()
362
+ this.markReady()
363
+ return
364
+ } catch (error) {
365
+ console.error(`🔴 schema cache load failed, falling back to fetch`, extractErrorMessage(error))
366
+ }
367
+ }
368
+ await this.fetchAndUpdateSchema()
369
+ await this.waitForSession()
370
+ this.markReady()
371
+ },
372
+ onMessage: (e: MessageEvent): void => this.onMessage(e),
373
+ url: () => this.getWSUrl(),
374
+ onClose: (): void => {
375
+ logInfo(`[👢] WEBSOCKET: closed connection to ComfyUI host ${this.data.id}`)
376
+ },
377
+ })
378
+ return this.ws
379
+ }
380
+
381
+ _isUpdatingSchema: boolean = false
382
+ get isUpdatingSchema(): boolean {
383
+ return this._isUpdatingSchema
384
+ }
385
+ set isUpdatingSchema(v: boolean) {
386
+ this._isUpdatingSchema = v
387
+ }
388
+
389
+ schemaUpdateResult: SchemaUpdateResult = null
390
+
391
+ private _schemaFromCache: Promise<void> | null = null
392
+
393
+ /** load the schema from .comfy-ts/hosts/<id>/ without connecting (offline workflows, fast starts).
394
+ * idempotent like connect(): N co-imported modules parse the ~4MB cache once */
395
+ loadSchemaFromCache(): Promise<void> {
396
+ this._schemaFromCache ??= (async (): Promise<void> => {
397
+ const object_info_json = comfyts.readJSON_<ComfySchemaJSON>(this.comfyJSONPath)
398
+ const embeddings_json = comfyts.readJSON_<string[]>(this.embeddingsPath, [])
399
+
400
+ // update schema
401
+ this.schema.update({ spec: object_info_json, embeddings: embeddings_json })
402
+ this.schema.RUN_BASIC_CHECKS()
403
+
404
+ // the on-disk sdk was generated from this same cache — only write when missing
405
+ if (!existsSync(this.sdkDTSPath)) await this.writeSDKToDisk()
406
+ })().catch((e: unknown) => {
407
+ this._schemaFromCache = null // a missing cache must stay retryable (e.g. after gen:sdk)
408
+ throw e
409
+ })
410
+ return this._schemaFromCache
411
+ }
412
+
413
+ /** POST a JSON route, preferring the /api prefix, falling back to the bare route */
414
+ private postJSON_ = async (route: string, body: unknown): Promise<void> => {
415
+ const base = this.getServerHostHTTP()
416
+ for (const url of [`${base}/api${route}`, `${base}${route}`]) {
417
+ const res = await fetch(url, {
418
+ method: 'POST',
419
+ headers: { 'Content-Type': 'application/json' },
420
+ body: JSON.stringify(body),
421
+ })
422
+ if (res.ok) return
423
+ }
424
+ throw new Error(`POST ${route} failed on ${base} (tried /api${route} and ${route})`)
425
+ }
426
+
427
+ /** drop every PENDING prompt from the server queue (the running one keeps going) */
428
+ clearQueue = (): Promise<void> => {
429
+ return this.postJSON_('/queue', { clear: true })
430
+ }
431
+
432
+ /** interrupt the CURRENTLY RUNNING prompt */
433
+ interrupt = (): Promise<void> => {
434
+ return this.postJSON_('/interrupt', {})
435
+ }
436
+
437
+ // SERVER LOGS ----------------------------------------------------------------------
438
+ // /internal routes are served bare (no /api prefix, no custom-node hijacks)
439
+
440
+ /** the server's recent console buffer (entries are write CHUNKS, not lines) */
441
+ fetchRawLogs = async (): Promise<{ entries: LogEntry[] }> => {
442
+ const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/raw`)
443
+ if (!res.ok) throw new Error(`GET /internal/logs/raw failed: ${res.status}`)
444
+ const json: unknown = await res.json()
445
+ // wire tolerance (agent/coding.md cast #4): soft-validate, log, still cast
446
+ const checked = WsMsgLogsData_ark(json)
447
+ if (checked instanceof type.errors) {
448
+ console.log(`[🔴] /!\\ /internal/logs/raw payload does not match schema.`)
449
+ printArkResultInConsole(checked)
450
+ }
451
+ return json as { entries: LogEntry[] }
452
+ }
453
+
454
+ /** (un)subscribe THIS session to ws 'logs' messages — per-sid server state,
455
+ * must be re-sent after every reconnect (see onSession) */
456
+ subscribeLogs = async (p: { enabled: boolean; clientId: string }): Promise<void> => {
457
+ const res = await fetch(`${this.getServerHostHTTP()}/internal/logs/subscribe`, {
458
+ method: 'PATCH',
459
+ headers: { 'Content-Type': 'application/json' },
460
+ body: JSON.stringify({ enabled: p.enabled, clientId: p.clientId }),
461
+ })
462
+ if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`)
463
+ }
464
+
465
+ /** GET a JSON route, preferring the /api prefix, falling back to the bare route */
466
+ private fetchJSON_ = async <T>(route: string): Promise<T> => {
467
+ const base = this.getServerHostHTTP()
468
+ for (const url of [`${base}/api${route}`, `${base}${route}`]) {
469
+ const res = await fetch(url, { method: 'GET' })
470
+ if (!res.ok) continue
471
+ if (!(res.headers.get('content-type') ?? '').includes('json')) continue
472
+ return (await res.json()) as T
473
+ }
474
+ throw new Error(`GET ${route} failed on ${base} (tried /api${route} and ${route})`)
475
+ }
476
+
477
+ /** retrieve the comfy spec from the schema*/
478
+ fetchAndUpdateSchema = async (): Promise<void> => {
479
+ try {
480
+ this.isUpdatingSchema = true
481
+ // 1 ------------------------------------
482
+ // download object_info (prefer /api/*: custom nodes hijack bare routes,
483
+ // e.g. lora-manager serves HTML at /embeddings)
484
+ const object_info_json = await this.fetchJSON_<{ [key: string]: ComfySchemaJSON[string] }>('/object_info')
485
+ const object_info_str = readableStringify(object_info_json, 4)
486
+ void writeFileAsync(this.comfyJSONPath, object_info_str, 'utf-8')
487
+ // use ark to check if payload match the type, and display errors if not
488
+ const res = ComfySchemaJSON_ark(object_info_json)
489
+ if (res instanceof type.errors) {
490
+ printArkResultInConsole(res)
491
+ }
492
+
493
+ // 2 ------------------------------------
494
+ // download embeddings
495
+ const embeddings_json = await this.fetchJSON_<EmbeddingName[]>('/embeddings').catch(
496
+ () => [] as EmbeddingName[],
497
+ )
498
+ void writeFileAsync(this.embeddingsPath, JSON.stringify(embeddings_json), 'utf-8')
499
+
500
+ // 3 ------------------------------------
501
+ // update schema
502
+ this.schema.update({ spec: object_info_json, embeddings: embeddings_json })
503
+ this.schema.RUN_BASIC_CHECKS()
504
+
505
+ // 3 ------------------------------------
506
+ // regen sdk
507
+ await this.writeSDKToDisk()
508
+ this.isUpdatingSchema = false
509
+ this.schemaUpdateResult = { type: 'success' }
510
+ } catch (error) {
511
+ this.isUpdatingSchema = false
512
+ this.schemaUpdateResult = { type: 'error', error: error }
513
+
514
+ console.error(error)
515
+ console.error('🔴 FAILURE TO GENERATE the typed sdk', extractErrorMessage(error))
516
+
517
+ const schemaExists = existsSync(this.sdkDTSPath)
518
+ if (!schemaExists) await this.writeSDKToDisk()
519
+ this.markFailed(error)
520
+ } finally {
521
+ this.isUpdatingSchema = false
522
+ }
523
+ }
524
+
525
+ /** executions we started */
526
+ executions: Map<PromptID, ComfyExecution> = new Map()
527
+
528
+ /** buffer in case we receive packets out of order */
529
+ _pendingMsgs = new Map<PromptID, PromptRelated_WsMsg[]>()
530
+
531
+ /** the active prompt currently running on this host */
532
+ private activePromptID: PromptID | null = null
533
+
534
+ /** method to either execute or buffer the incoming message */
535
+ routeOrBuffer(prompt_id: PromptID, msg: PromptRelated_WsMsg): void {
536
+ this.activePromptID = prompt_id
537
+ const prompt = this.executions.get(prompt_id)
538
+
539
+ // case 1. no prompt yet => just store the messages
540
+ if (prompt == null) {
541
+ const msgs = this._pendingMsgs.get(prompt_id)
542
+ if (msgs) msgs.push(msg)
543
+ else this._pendingMsgs.set(prompt_id, [msg])
544
+ return
545
+ }
546
+ // case 2. prompt exists => send the messages
547
+ prompt.onPromptRelatedMessage(msg)
548
+ }
549
+
550
+ /** the latent image beeing generated, in case you want to display it */
551
+ latentPreview: Maybe<{
552
+ promptID: Maybe<PromptID>
553
+ receivedAt: number_Timestamp
554
+ blob: Blob
555
+ url: string
556
+ }> = null
557
+
558
+ /** byte-level latent-preview hook (e.g. TUI live preview panel) */
559
+ onLatentPreview: Maybe<(p: { bytes: Uint8Array; mime: string; promptID: Maybe<PromptID> }) => void> = null
560
+
561
+ /** fires on every ws 'status' message (queue length lives there) */
562
+ onStatus: Maybe<(p: { queueRemaining: number }) => void> = null
563
+
564
+ /** fires when the server assigns a NEW session id (first connect AND every
565
+ * reconnect — per-sid server state like log subscriptions must be redone) */
566
+ onSession: Maybe<(sid: string) => void> = null
567
+
568
+ /** fires on ws 'logs' messages (server console stream, see subscribeLogs) */
569
+ onLogs: Maybe<(p: { entries: LogEntry[] }) => void> = null
570
+
571
+ /** the session assigned to us by the server */
572
+ comfySessionId: string = 'temp' /** send by ComfyUI server */
573
+
574
+ /** handy to keep around */
575
+ status: ComfyStatusData['status'] | null = null
576
+
577
+ onMessage(e: MessageEvent): void {
578
+ if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
579
+ if (e.data instanceof ArrayBuffer) {
580
+ // 🔴 console.log('[👢] WEBSOCKET: received ArrayBuffer', e.data)
581
+ const view = new DataView(e.data)
582
+ const eventType = view.getUint32(0)
583
+ const buffer = e.data.slice(4)
584
+ switch (eventType) {
585
+ case 1: {
586
+ const view2 = new DataView(e.data)
587
+ const imageType = view2.getUint32(4)
588
+ let imageMime: string
589
+ switch (imageType) {
590
+ case 1:
591
+ imageMime = 'image/jpeg'
592
+ break
593
+ case 2:
594
+ imageMime = 'image/png'
595
+ break
596
+ default:
597
+ imageMime = 'image/jpeg'
598
+ break
599
+ }
600
+ const imageBytes = buffer.slice(4)
601
+ const imageBlob = new Blob([imageBytes], { type: imageMime })
602
+ const imagePreview = URL.createObjectURL(imageBlob)
603
+ this.latentPreview = {
604
+ blob: imageBlob,
605
+ url: imagePreview,
606
+ receivedAt: Date.now() as number_Timestamp,
607
+ promptID: this.activePromptID,
608
+ }
609
+ this.onLatentPreview?.({
610
+ bytes: new Uint8Array(imageBytes),
611
+ mime: imageMime,
612
+ promptID: this.activePromptID,
613
+ })
614
+ break
615
+ }
616
+ default:
617
+ throw new Error(`Unknown binary websocket message of type ${eventType}`)
618
+ }
619
+ return
620
+ }
621
+
622
+ const msg_: unknown = JSON.parse(String(e.data))
623
+
624
+ // ----- crystools silent fix -----
625
+ if (typeof msg_ === 'object' && msg_ != null && 'type' in msg_) {
626
+ if (msg_.type === 'crystools.monitor') return
627
+ }
628
+
629
+ // ----- soft-validate against the schema -----
630
+ const res = WsMsg_ark(msg_)
631
+ if (res instanceof type.errors) {
632
+ console.log(`[🔴] /!\\ Websocket payload does not match schema.`)
633
+ printArkResultInConsole(res)
634
+ }
635
+ // wire tolerance (agent/coding.md): ComfyUI drifts faster than our schema;
636
+ // failures are logged above, then we still route best-effort
637
+ const msg = msg_ as WsMsg
638
+
639
+ if (msg.type === 'status') {
640
+ if (msg.data.sid) {
641
+ const sidChanged = msg.data.sid !== this.comfySessionId
642
+ this.comfySessionId = msg.data.sid
643
+ this._sessionResolve?.()
644
+ this._sessionResolve = null
645
+ if (sidChanged) this.onSession?.(msg.data.sid)
646
+ }
647
+ this.status = msg.data.status
648
+ this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 })
649
+ return
650
+ }
651
+
652
+ // defer accumulation to ScriptStep_prompt
653
+ if (msg.type === 'progress') {
654
+ const activePromptID = this.activePromptID
655
+ if (activePromptID == null) {
656
+ console.log(`❌ received a 'progress' msg, but activePromptID is not set`)
657
+ return
658
+ }
659
+ this.routeOrBuffer(activePromptID, msg)
660
+ return
661
+ }
662
+ if (
663
+ msg.type === 'execution_start' ||
664
+ msg.type === 'execution_cached' ||
665
+ msg.type === 'execution_error' ||
666
+ msg.type === 'execution_success' ||
667
+ msg.type === 'executing' ||
668
+ msg.type === 'executed' ||
669
+ msg.type === 'progress_state'
670
+ ) {
671
+ this.routeOrBuffer(msg.data.prompt_id, msg)
672
+ return
673
+ }
674
+
675
+ if (msg.type === 'manager-terminal-feedback') {
676
+ this.addLog(msg.data.data)
677
+ return
678
+ }
679
+
680
+ if (msg.type === 'logs') {
681
+ this.onLogs?.(msg.data)
682
+ return
683
+ }
684
+ exhaust(msg)
685
+ console.log('❌', 'Unknown message:', msg)
686
+
687
+ toastError('Unknown message type: ' + JSON.stringify(msg.type))
688
+ // throw new Error('Unknown message type: ' + JSON.stringify(msg))
689
+ }
690
+ }