comfyui-prompt.js 14 KB

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