comfyui-prompt.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /**
  2. * @node comfyui-prompt
  3. * @name ComfyUI Prompt
  4. * @category ai
  5. * @version 1.0.0
  6. * @description Submit an API-format workflow graph to ComfyUI, wait for it to finish, and return the generated image
  7. * @icon image
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. baseUrl: {
  13. type: 'string',
  14. title: 'ComfyUI Base URL',
  15. description: 'Base URL of the ComfyUI server',
  16. default: 'http://127.0.0.1:8188'
  17. },
  18. workflowJson: {
  19. type: 'string',
  20. title: 'Workflow Graph',
  21. description: 'ComfyUI API-format graph, as produced by Save (API Format) in ComfyUI. Placeholders use double angle brackets around a dot path, and a seed placeholder yields a random seed. Double braces are deliberately not used, because the engine already interpolates those in node config.',
  22. format: 'json',
  23. openUrlFrom: 'baseUrl',
  24. importFrom: 'comfyui',
  25. default: ''
  26. },
  27. outputNodeId: {
  28. type: 'string',
  29. title: 'Output Node ID',
  30. description: 'Graph node whose images are returned, normally the SaveImage node',
  31. default: '9'
  32. },
  33. imageIndex: {
  34. type: 'number',
  35. title: 'Image Index',
  36. description: 'Which image to return when the output node produced several',
  37. default: 0
  38. },
  39. pollIntervalMs: {
  40. type: 'number',
  41. title: 'Poll Interval (ms)',
  42. description: 'How often to check whether the job has finished',
  43. default: 3000
  44. },
  45. timeoutMs: {
  46. type: 'number',
  47. title: 'Generation Timeout (ms)',
  48. description: 'Give up waiting after this long. A cold model load can take minutes.',
  49. default: 600000
  50. },
  51. returnImage: {
  52. type: 'boolean',
  53. title: 'Return Image Data',
  54. description: 'Download the result and return it base64-encoded. Disable to return only the filename.',
  55. default: true
  56. },
  57. retryCount: {
  58. type: 'number',
  59. title: 'Retries',
  60. description: 'Extra attempts after a failed submission or generation',
  61. default: 0
  62. },
  63. retryDelayMs: {
  64. type: 'number',
  65. title: 'Retry Delay (ms)',
  66. description: 'Pause before the first retry. Doubles on each further attempt.',
  67. default: 3000
  68. },
  69. retryMaxDelayMs: {
  70. type: 'number',
  71. title: 'Max Retry Delay (ms)',
  72. description: 'Upper bound for the exponential backoff',
  73. default: 30000
  74. },
  75. skipOnError: {
  76. type: 'boolean',
  77. title: 'Skip On Error',
  78. description: 'Return success false instead of failing the workflow. Useful inside a loop.',
  79. default: false
  80. }
  81. },
  82. required: ['baseUrl', 'workflowJson']
  83. };
  84. const inputSchema = {
  85. type: 'object',
  86. properties: {
  87. data: {
  88. type: 'any',
  89. description: 'Values available to placeholder substitution in the graph'
  90. }
  91. }
  92. };
  93. const outputSchema = {
  94. type: 'object',
  95. properties: {
  96. success: { type: 'boolean', description: 'False when generation failed and Skip On Error is enabled' },
  97. error: { type: 'string', description: 'Failure reason when success is false' },
  98. imageBase64: { type: 'string', description: 'Generated image, base64-encoded' },
  99. filename: { type: 'string', description: 'Filename ComfyUI assigned to the result' },
  100. subfolder: { type: 'string', description: 'ComfyUI output subfolder' },
  101. mimeType: { type: 'string', description: 'MIME type of the returned image' },
  102. size: { type: 'number', description: 'Image size in bytes' },
  103. promptId: { type: 'string', description: 'ComfyUI prompt id for the job' },
  104. elapsedMs: { type: 'number', description: 'Time from submission to completion' },
  105. attempts: { type: 'number', description: 'How many attempts were made' }
  106. }
  107. };
  108. function getPath(root, path) {
  109. if (!root || !path) {
  110. return undefined;
  111. }
  112. const parts = String(path).split('.');
  113. let current = root;
  114. for (let i = 0; i < parts.length; i++) {
  115. if (current === null || typeof current !== 'object') {
  116. return undefined;
  117. }
  118. current = current[parts[i]];
  119. }
  120. return current;
  121. }
  122. // The graph is a JSON document, so substituted values must be JSON-escaped or a
  123. // prompt containing a quote or newline would produce an unparseable graph.
  124. function jsonFragment(value) {
  125. if (value === undefined || value === null) {
  126. return '';
  127. }
  128. if (typeof value === 'number' || typeof value === 'boolean') {
  129. return String(value);
  130. }
  131. const encoded = JSON.stringify(String(value));
  132. return encoded.substring(1, encoded.length - 1);
  133. }
  134. // Placeholders are <<path>>, deliberately not {{path}}: the workflow engine
  135. // interpolates {{...}} in node config before the node ever runs, which would
  136. // blank these out. Substitution uses split/join rather than String.replace
  137. // because this QuickJS build mishandles literal braces in regex patterns and
  138. // silently drops the replacement.
  139. function findPlaceholders(text) {
  140. const found = [];
  141. let rest = String(text);
  142. while (true) {
  143. const start = rest.indexOf('<<');
  144. if (start === -1) { break; }
  145. const end = rest.indexOf('>>', start + 2);
  146. if (end === -1) { break; }
  147. const key = rest.substring(start + 2, end).trim();
  148. if (key.length > 0 && found.indexOf(key) === -1) {
  149. found.push(key);
  150. }
  151. rest = rest.substring(end + 2);
  152. }
  153. return found;
  154. }
  155. // Inside a loop the engine hands a node the loop item rather than the upstream
  156. // node's output, and the upstream result is nested somewhere under it. Resolve a
  157. // path against the obvious roots first, then search the tree for it.
  158. function deepResolve(root, path, depth) {
  159. if (!root || typeof root !== 'object' || depth > 6) {
  160. return undefined;
  161. }
  162. const direct = getPath(root, path);
  163. if (direct !== undefined) {
  164. return direct;
  165. }
  166. const keys = Object.keys(root);
  167. for (let i = 0; i < keys.length; i++) {
  168. const found = deepResolve(root[keys[i]], path, depth + 1);
  169. if (found !== undefined) {
  170. return found;
  171. }
  172. }
  173. return undefined;
  174. }
  175. function substitute(template, data) {
  176. let out = String(template);
  177. const keys = findPlaceholders(out);
  178. for (let i = 0; i < keys.length; i++) {
  179. const key = keys[i];
  180. let value = deepResolve(data, key, 0);
  181. if (value === undefined && key === 'seed') {
  182. value = Math.floor(Math.random() * 1000000000000000);
  183. }
  184. if (value === undefined) {
  185. continue;
  186. }
  187. out = out.split('<<' + key + '>>').join(jsonFragment(value));
  188. }
  189. return out;
  190. }
  191. function httpJson(method, url, body) {
  192. const options = { method: method, url: url, timeout: 60000 };
  193. if (body) {
  194. options.headers = { 'Content-Type': 'application/json' };
  195. options.body = body;
  196. }
  197. const response = smartbotic.http.request(options);
  198. if (response.status < 200 || response.status >= 300) {
  199. const detail = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
  200. throw new Error('ComfyUI HTTP ' + response.status + ': ' + String(detail).substring(0, 300));
  201. }
  202. return typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
  203. }
  204. function runOnce(config, data, base) {
  205. const graphText = substitute(config.workflowJson, data);
  206. // An unresolved placeholder is the usual cause of a parse failure, and the raw
  207. // JSON error does not say which one, so name them explicitly.
  208. const unresolved = findPlaceholders(graphText);
  209. if (unresolved.length > 0) {
  210. const available = data && typeof data === 'object' ? Object.keys(data).join(', ') : '(none)';
  211. throw new Error('Unresolved placeholders in workflow graph: <<' + unresolved.join('>>, <<') +
  212. '>>. Paths are relative to the previous node output, whose top-level keys are: ' + available);
  213. }
  214. let graph;
  215. try {
  216. graph = JSON.parse(graphText);
  217. } catch (e) {
  218. // Show where it broke: an empty substitution leaves "key": , which is the
  219. // usual cause and is impossible to spot from the parser message alone.
  220. let where = graphText.indexOf(': ,');
  221. if (where === -1) { where = graphText.indexOf(':,'); }
  222. if (where === -1) { where = 0; }
  223. const snippet = graphText.substring(Math.max(0, where - 80), where + 80);
  224. throw new Error('Workflow graph is not valid JSON after substitution: ' + e.message +
  225. ' | near: ' + snippet);
  226. }
  227. const payload = graph.prompt ? graph : { prompt: graph };
  228. payload.client_id = 'smartbotic-' + (config.clientSuffix || 'node');
  229. const submitted = httpJson('POST', base + '/prompt', JSON.stringify(payload));
  230. if (!submitted || !submitted.prompt_id) {
  231. throw new Error('ComfyUI did not return a prompt_id');
  232. }
  233. if (submitted.node_errors && Object.keys(submitted.node_errors).length > 0) {
  234. throw new Error('ComfyUI rejected the graph: ' + JSON.stringify(submitted.node_errors).substring(0, 300));
  235. }
  236. const promptId = submitted.prompt_id;
  237. const interval = Number(config.pollIntervalMs) || 3000;
  238. const timeout = Number(config.timeoutMs) || 600000;
  239. const deadline = Date.now() + timeout;
  240. const startedAt = Date.now();
  241. let history = null;
  242. while (Date.now() < deadline) {
  243. smartbotic.utils.sleep(interval);
  244. const entry = httpJson('GET', base + '/history/' + promptId, null);
  245. if (entry && entry[promptId]) {
  246. history = entry[promptId];
  247. break;
  248. }
  249. }
  250. if (!history) {
  251. throw new Error('ComfyUI generation timed out after ' + timeout + 'ms (prompt ' + promptId + ')');
  252. }
  253. if (history.status && history.status.status_str && history.status.status_str !== 'success') {
  254. throw new Error('ComfyUI generation failed: ' + history.status.status_str);
  255. }
  256. const outputs = history.outputs || {};
  257. const nodeId = String(config.outputNodeId || '9');
  258. const nodeOutput = outputs[nodeId];
  259. if (!nodeOutput || !nodeOutput.images || nodeOutput.images.length === 0) {
  260. throw new Error('Output node ' + nodeId + ' produced no images. Available: ' + Object.keys(outputs).join(', '));
  261. }
  262. const index = Number(config.imageIndex) || 0;
  263. const image = nodeOutput.images[index] || nodeOutput.images[0];
  264. const result = {
  265. promptId: promptId,
  266. filename: image.filename || '',
  267. subfolder: image.subfolder || '',
  268. elapsedMs: Date.now() - startedAt,
  269. imageBase64: '',
  270. mimeType: 'image/png',
  271. size: 0
  272. };
  273. if (config.returnImage === false) {
  274. return result;
  275. }
  276. const viewUrl = base + '/view?filename=' + encodeURIComponent(result.filename) +
  277. '&subfolder=' + encodeURIComponent(result.subfolder) + '&type=output';
  278. const download = smartbotic.http.request({ method: 'GET', url: viewUrl, timeout: 120000 });
  279. if (download.status < 200 || download.status >= 300) {
  280. throw new Error('Failed to download generated image: HTTP ' + download.status);
  281. }
  282. // dataBase64 carries the raw bytes; response.data is UTF-8 validated and
  283. // would destroy the PNG.
  284. if (typeof download.dataBase64 !== 'string' || download.dataBase64.length === 0) {
  285. throw new Error('Runtime returned no binary data for the generated image');
  286. }
  287. result.imageBase64 = download.dataBase64;
  288. result.size = Math.floor(result.imageBase64.replace(/=+$/, '').length * 3 / 4);
  289. const headers = download.headers || {};
  290. if (headers['content-type']) {
  291. result.mimeType = String(headers['content-type']).split(';')[0].trim();
  292. }
  293. return result;
  294. }
  295. module.exports = {
  296. configSchema,
  297. inputSchema,
  298. outputSchema,
  299. async execute(config, input, context) {
  300. if (!config.workflowJson || String(config.workflowJson).trim().length === 0) {
  301. throw new Error('A ComfyUI workflow graph is required');
  302. }
  303. // Resolve against the whole input: the upstream result may be nested under
  304. // the loop item rather than sitting at input.data.
  305. const data = input;
  306. const base = String(config.baseUrl).replace(/\/+$/, '');
  307. const attempts = 1 + (Number(config.retryCount) > 0 ? Number(config.retryCount) : 0);
  308. let lastError = '';
  309. let used = 0;
  310. for (let attempt = 1; attempt <= attempts; attempt++) {
  311. used = attempt;
  312. try {
  313. const result = runOnce(config, data, base);
  314. return {
  315. success: true,
  316. error: '',
  317. imageBase64: result.imageBase64,
  318. filename: result.filename,
  319. subfolder: result.subfolder,
  320. mimeType: result.mimeType,
  321. size: result.size,
  322. promptId: result.promptId,
  323. elapsedMs: result.elapsedMs,
  324. attempts: used
  325. };
  326. } catch (err) {
  327. lastError = err && err.message ? err.message : String(err);
  328. smartbotic.log.warn('comfyui-prompt: attempt ' + attempt + ' of ' + attempts + ' failed: ' + lastError);
  329. if (attempt < attempts) {
  330. const baseDelay = Number(config.retryDelayMs) || 3000;
  331. const cap = Number(config.retryMaxDelayMs) || 30000;
  332. let delay = baseDelay * Math.pow(2, attempt - 1);
  333. if (delay > cap) { delay = cap; }
  334. smartbotic.utils.sleep(delay);
  335. }
  336. }
  337. }
  338. if (config.skipOnError !== true) {
  339. throw new Error('comfyui-prompt failed after ' + used + ' attempt(s): ' + lastError);
  340. }
  341. smartbotic.log.warn('comfyui-prompt: skipping after ' + used + ' attempt(s)');
  342. return {
  343. success: false,
  344. error: lastError,
  345. imageBase64: '',
  346. filename: '',
  347. subfolder: '',
  348. mimeType: '',
  349. size: 0,
  350. promptId: '',
  351. elapsedMs: 0,
  352. attempts: used
  353. };
  354. }
  355. };