flujo-ai 3.23.0 → 3.26.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 (397) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-build-manifest.json +205 -186
  3. package/.next/app-path-routes-manifest.json +2 -2
  4. package/.next/build-manifest.json +7 -7
  5. package/.next/react-loadable-manifest.json +25 -20
  6. package/.next/routes-manifest.json +19 -1
  7. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_not-found.html +1 -1
  9. package/.next/server/app/_not-found.rsc +3 -3
  10. package/.next/server/app/api/approvals/[id]/route.js +1 -1
  11. package/.next/server/app/api/approvals/[id]/route.js.nft.json +1 -1
  12. package/.next/server/app/api/approvals/[id]/route_client-reference-manifest.js +1 -1
  13. package/.next/server/app/api/approvals/route.js +1 -1
  14. package/.next/server/app/api/approvals/route.js.nft.json +1 -1
  15. package/.next/server/app/api/approvals/route_client-reference-manifest.js +1 -1
  16. package/.next/server/app/api/backup/route.js +1 -1
  17. package/.next/server/app/api/backup/route.js.nft.json +1 -1
  18. package/.next/server/app/api/backup/route_client-reference-manifest.js +1 -1
  19. package/.next/server/app/api/browse/route.js +1 -1
  20. package/.next/server/app/api/browse/route_client-reference-manifest.js +1 -1
  21. package/.next/server/app/api/bugs/enhance/route.js +2 -2
  22. package/.next/server/app/api/bugs/enhance/route.js.nft.json +1 -1
  23. package/.next/server/app/api/bugs/enhance/route_client-reference-manifest.js +1 -1
  24. package/.next/server/app/api/cwd/route.js +1 -1
  25. package/.next/server/app/api/cwd/route_client-reference-manifest.js +1 -1
  26. package/.next/server/app/api/encryption/secure/route.js +1 -1
  27. package/.next/server/app/api/encryption/secure/route.js.nft.json +1 -1
  28. package/.next/server/app/api/encryption/secure/route_client-reference-manifest.js +1 -1
  29. package/.next/server/app/api/env/route.js +1 -1
  30. package/.next/server/app/api/env/route_client-reference-manifest.js +1 -1
  31. package/.next/server/app/api/flow/[id]/route.js.nft.json +1 -1
  32. package/.next/server/app/api/flow/[id]/route_client-reference-manifest.js +1 -1
  33. package/.next/server/app/api/flow/compile/route.js +1 -1
  34. package/.next/server/app/api/flow/compile/route.js.nft.json +1 -1
  35. package/.next/server/app/api/flow/compile/route_client-reference-manifest.js +1 -1
  36. package/.next/server/app/api/flow/generate/route.js +1 -1
  37. package/.next/server/app/api/flow/generate/route.js.nft.json +1 -1
  38. package/.next/server/app/api/flow/generate/route_client-reference-manifest.js +1 -1
  39. package/.next/server/app/api/flow/improve/route.js +1 -1
  40. package/.next/server/app/api/flow/improve/route.js.nft.json +1 -1
  41. package/.next/server/app/api/flow/improve/route_client-reference-manifest.js +1 -1
  42. package/.next/server/app/api/flow/prompt-renderer/route.js +1 -1
  43. package/.next/server/app/api/flow/prompt-renderer/route.js.nft.json +1 -1
  44. package/.next/server/app/api/flow/prompt-renderer/route_client-reference-manifest.js +1 -1
  45. package/.next/server/app/api/flow/quick-chat/route.js +1 -1
  46. package/.next/server/app/api/flow/quick-chat/route.js.nft.json +1 -1
  47. package/.next/server/app/api/flow/quick-chat/route_client-reference-manifest.js +1 -1
  48. package/.next/server/app/api/flow/repair/route.js +1 -1
  49. package/.next/server/app/api/flow/repair/route.js.nft.json +1 -1
  50. package/.next/server/app/api/flow/repair/route_client-reference-manifest.js +1 -1
  51. package/.next/server/app/api/flow/route.js.nft.json +1 -1
  52. package/.next/server/app/api/flow/route_client-reference-manifest.js +1 -1
  53. package/.next/server/app/api/git/route.js +1 -1
  54. package/.next/server/app/api/git/route_client-reference-manifest.js +1 -1
  55. package/.next/server/app/api/init/route.js +1 -1
  56. package/.next/server/app/api/init/route.js.nft.json +1 -1
  57. package/.next/server/app/api/init/route_client-reference-manifest.js +1 -1
  58. package/.next/server/app/api/local-models/capability/route_client-reference-manifest.js +1 -1
  59. package/.next/server/app/api/local-models/pull/route_client-reference-manifest.js +1 -1
  60. package/.next/server/app/api/local-models/suggest/route_client-reference-manifest.js +1 -1
  61. package/.next/server/app/api/mcp/cancel/route.js +1 -1
  62. package/.next/server/app/api/mcp/cancel/route.js.nft.json +1 -1
  63. package/.next/server/app/api/mcp/cancel/route_client-reference-manifest.js +1 -1
  64. package/.next/server/app/api/mcp/servers/[name]/prompts/get/route.js +1 -1
  65. package/.next/server/app/api/mcp/servers/[name]/prompts/get/route.js.nft.json +1 -1
  66. package/.next/server/app/api/mcp/servers/[name]/prompts/get/route_client-reference-manifest.js +1 -1
  67. package/.next/server/app/api/mcp/servers/[name]/prompts/route.js +1 -1
  68. package/.next/server/app/api/mcp/servers/[name]/prompts/route.js.nft.json +1 -1
  69. package/.next/server/app/api/mcp/servers/[name]/prompts/route_client-reference-manifest.js +1 -1
  70. package/.next/server/app/api/mcp/servers/[name]/resources/read/route.js +1 -1
  71. package/.next/server/app/api/mcp/servers/[name]/resources/read/route.js.nft.json +1 -1
  72. package/.next/server/app/api/mcp/servers/[name]/resources/read/route_client-reference-manifest.js +1 -1
  73. package/.next/server/app/api/mcp/servers/[name]/resources/route.js +1 -1
  74. package/.next/server/app/api/mcp/servers/[name]/resources/route.js.nft.json +1 -1
  75. package/.next/server/app/api/mcp/servers/[name]/resources/route_client-reference-manifest.js +1 -1
  76. package/.next/server/app/api/mcp/servers/[name]/route.js +1 -1
  77. package/.next/server/app/api/mcp/servers/[name]/route.js.nft.json +1 -1
  78. package/.next/server/app/api/mcp/servers/[name]/route_client-reference-manifest.js +1 -1
  79. package/.next/server/app/api/mcp/servers/[name]/status/route.js +1 -1
  80. package/.next/server/app/api/mcp/servers/[name]/status/route.js.nft.json +1 -1
  81. package/.next/server/app/api/mcp/servers/[name]/status/route_client-reference-manifest.js +1 -1
  82. package/.next/server/app/api/mcp/servers/[name]/tools/[toolName]/route.js +1 -1
  83. package/.next/server/app/api/mcp/servers/[name]/tools/[toolName]/route.js.nft.json +1 -1
  84. package/.next/server/app/api/mcp/servers/[name]/tools/[toolName]/route_client-reference-manifest.js +1 -1
  85. package/.next/server/app/api/mcp/servers/[name]/tools/route.js +1 -1
  86. package/.next/server/app/api/mcp/servers/[name]/tools/route.js.nft.json +1 -1
  87. package/.next/server/app/api/mcp/servers/[name]/tools/route_client-reference-manifest.js +1 -1
  88. package/.next/server/app/api/mcp/servers/route.js +1 -1
  89. package/.next/server/app/api/mcp/servers/route.js.nft.json +1 -1
  90. package/.next/server/app/api/mcp/servers/route_client-reference-manifest.js +1 -1
  91. package/.next/server/app/api/mcp/test-connection/route.js +1 -1
  92. package/.next/server/app/api/mcp/test-connection/route.js.nft.json +1 -1
  93. package/.next/server/app/api/mcp/test-connection/route_client-reference-manifest.js +1 -1
  94. package/.next/server/app/api/mcp/test-connection/stream/route.js +1 -1
  95. package/.next/server/app/api/mcp/test-connection/stream/route.js.nft.json +1 -1
  96. package/.next/server/app/api/mcp/test-connection/stream/route_client-reference-manifest.js +1 -1
  97. package/.next/server/app/api/mcp-registry/route.js +1 -1
  98. package/.next/server/app/api/mcp-registry/route.js.nft.json +1 -1
  99. package/.next/server/app/api/mcp-registry/route_client-reference-manifest.js +1 -1
  100. package/.next/server/app/api/mcp-registry/spotlight/route_client-reference-manifest.js +1 -1
  101. package/.next/server/app/api/model/[id]/route.js +1 -1
  102. package/.next/server/app/api/model/[id]/route.js.nft.json +1 -1
  103. package/.next/server/app/api/model/[id]/route_client-reference-manifest.js +1 -1
  104. package/.next/server/app/api/model/provider/route.js +1 -1
  105. package/.next/server/app/api/model/provider/route.js.nft.json +1 -1
  106. package/.next/server/app/api/model/provider/route_client-reference-manifest.js +1 -1
  107. package/.next/server/app/api/model/route.js +1 -1
  108. package/.next/server/app/api/model/route.js.nft.json +1 -1
  109. package/.next/server/app/api/model/route_client-reference-manifest.js +1 -1
  110. package/.next/server/app/api/model/test/route.js +1 -1
  111. package/.next/server/app/api/model/test/route.js.nft.json +1 -1
  112. package/.next/server/app/api/model/test/route_client-reference-manifest.js +1 -1
  113. package/.next/server/app/api/oauth/callback/route_client-reference-manifest.js +1 -1
  114. package/.next/server/app/api/oauth/initiate/route_client-reference-manifest.js +1 -1
  115. package/.next/server/app/api/oauth/reset/route.js +1 -1
  116. package/.next/server/app/api/oauth/reset/route.js.nft.json +1 -1
  117. package/.next/server/app/api/oauth/reset/route_client-reference-manifest.js +1 -1
  118. package/.next/server/app/api/planned-executions/[id]/route.js.nft.json +1 -1
  119. package/.next/server/app/api/planned-executions/[id]/route_client-reference-manifest.js +1 -1
  120. package/.next/server/app/api/planned-executions/[id]/run/route.js.nft.json +1 -1
  121. package/.next/server/app/api/planned-executions/[id]/run/route_client-reference-manifest.js +1 -1
  122. package/.next/server/app/api/planned-executions/[id]/runs/route.js.nft.json +1 -1
  123. package/.next/server/app/api/planned-executions/[id]/runs/route_client-reference-manifest.js +1 -1
  124. package/.next/server/app/api/planned-executions/preview-schedule/route_client-reference-manifest.js +1 -1
  125. package/.next/server/app/api/planned-executions/reconcile/route.js +1 -1
  126. package/.next/server/app/api/planned-executions/reconcile/route.js.nft.json +1 -1
  127. package/.next/server/app/api/planned-executions/reconcile/route_client-reference-manifest.js +1 -1
  128. package/.next/server/app/api/planned-executions/route.js +1 -1
  129. package/.next/server/app/api/planned-executions/route.js.nft.json +1 -1
  130. package/.next/server/app/api/planned-executions/route_client-reference-manifest.js +1 -1
  131. package/.next/server/app/api/restore/route.js +1 -1
  132. package/.next/server/app/api/restore/route.js.nft.json +1 -1
  133. package/.next/server/app/api/restore/route_client-reference-manifest.js +1 -1
  134. package/.next/server/app/api/runs/active/route.js +1 -1
  135. package/.next/server/app/api/runs/active/route.js.nft.json +1 -1
  136. package/.next/server/app/api/runs/active/route_client-reference-manifest.js +1 -1
  137. package/.next/server/app/api/storage/route_client-reference-manifest.js +1 -1
  138. package/.next/server/app/api/update/route.js +1 -1
  139. package/.next/server/app/api/update/route_client-reference-manifest.js +1 -1
  140. package/.next/server/app/api/waves/route.js +1 -1
  141. package/.next/server/app/api/waves/route.js.nft.json +1 -1
  142. package/.next/server/app/api/waves/route_client-reference-manifest.js +1 -1
  143. package/.next/server/app/api/webhooks/[id]/route.js +1 -1
  144. package/.next/server/app/api/webhooks/[id]/route.js.nft.json +1 -1
  145. package/.next/server/app/api/webhooks/[id]/route_client-reference-manifest.js +1 -1
  146. package/.next/server/app/chat/page.js +10 -10
  147. package/.next/server/app/chat/page.js.nft.json +1 -1
  148. package/.next/server/app/chat/page_client-reference-manifest.js +1 -1
  149. package/.next/server/app/chat.html +1 -1
  150. package/.next/server/app/chat.rsc +4 -4
  151. package/.next/server/app/docs/page.js +11 -8
  152. package/.next/server/app/docs/page.js.nft.json +1 -1
  153. package/.next/server/app/docs/page_client-reference-manifest.js +1 -1
  154. package/.next/server/app/docs.html +1 -1
  155. package/.next/server/app/docs.rsc +4 -4
  156. package/.next/server/app/executions/page.js +3 -3
  157. package/.next/server/app/executions/page.js.nft.json +1 -1
  158. package/.next/server/app/executions/page_client-reference-manifest.js +1 -1
  159. package/.next/server/app/executions.html +1 -1
  160. package/.next/server/app/executions.rsc +4 -4
  161. package/.next/server/app/flows/page.js +3 -3
  162. package/.next/server/app/flows/page.js.nft.json +1 -1
  163. package/.next/server/app/flows/page_client-reference-manifest.js +1 -1
  164. package/.next/server/app/flows.html +1 -1
  165. package/.next/server/app/flows.rsc +4 -4
  166. package/.next/server/app/index.html +1 -1
  167. package/.next/server/app/index.rsc +4 -4
  168. package/.next/server/app/mcp/page.js +5 -5
  169. package/.next/server/app/mcp/page.js.nft.json +1 -1
  170. package/.next/server/app/mcp/page_client-reference-manifest.js +1 -1
  171. package/.next/server/app/mcp-flows/route.js +1 -1
  172. package/.next/server/app/mcp-flows/route.js.nft.json +1 -1
  173. package/.next/server/app/mcp-flows/route_client-reference-manifest.js +1 -1
  174. package/.next/server/app/mcp-proxy/[server]/route.js +1 -1
  175. package/.next/server/app/mcp-proxy/[server]/route.js.nft.json +1 -1
  176. package/.next/server/app/mcp-proxy/[server]/route_client-reference-manifest.js +1 -1
  177. package/.next/server/app/mcp.html +1 -1
  178. package/.next/server/app/mcp.rsc +4 -4
  179. package/.next/server/app/models/page.js +2 -2
  180. package/.next/server/app/models/page.js.nft.json +1 -1
  181. package/.next/server/app/models/page_client-reference-manifest.js +1 -1
  182. package/.next/server/app/page.js +2 -2
  183. package/.next/server/app/page_client-reference-manifest.js +1 -1
  184. package/.next/server/app/settings/page.js +2 -57
  185. package/.next/server/app/settings/page.js.nft.json +1 -1
  186. package/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  187. package/.next/server/app/settings.html +1 -1
  188. package/.next/server/app/settings.rsc +4 -4
  189. package/.next/server/app/v1/chat/completions/route.js +1 -1
  190. package/.next/server/app/v1/chat/completions/route.js.nft.json +1 -1
  191. package/.next/server/app/v1/chat/completions/route_client-reference-manifest.js +1 -1
  192. package/.next/server/app/v1/chat/conversations/[conversationId]/breakpoints/route.js +2 -2
  193. package/.next/server/app/v1/chat/conversations/[conversationId]/breakpoints/route.js.nft.json +1 -1
  194. package/.next/server/app/v1/chat/conversations/[conversationId]/breakpoints/route_client-reference-manifest.js +1 -1
  195. package/.next/server/app/v1/chat/conversations/[conversationId]/cancel/route.js +2 -2
  196. package/.next/server/app/v1/chat/conversations/[conversationId]/cancel/route.js.nft.json +1 -1
  197. package/.next/server/app/v1/chat/conversations/[conversationId]/cancel/route_client-reference-manifest.js +1 -1
  198. package/.next/server/app/v1/chat/conversations/[conversationId]/debug/continue/route.js +1 -1
  199. package/.next/server/app/v1/chat/conversations/[conversationId]/debug/continue/route.js.nft.json +1 -1
  200. package/.next/server/app/v1/chat/conversations/[conversationId]/debug/continue/route_client-reference-manifest.js +1 -1
  201. package/.next/server/app/v1/chat/conversations/[conversationId]/debug/step/route.js +1 -1
  202. package/.next/server/app/v1/chat/conversations/[conversationId]/debug/step/route.js.nft.json +1 -1
  203. package/.next/server/app/v1/chat/conversations/[conversationId]/debug/step/route_client-reference-manifest.js +1 -1
  204. package/.next/server/app/v1/chat/conversations/[conversationId]/edit-state/route.js +2 -2
  205. package/.next/server/app/v1/chat/conversations/[conversationId]/edit-state/route.js.nft.json +1 -1
  206. package/.next/server/app/v1/chat/conversations/[conversationId]/edit-state/route_client-reference-manifest.js +1 -1
  207. package/.next/server/app/v1/chat/conversations/[conversationId]/events/route.js +1 -1
  208. package/.next/server/app/v1/chat/conversations/[conversationId]/events/route.js.nft.json +1 -1
  209. package/.next/server/app/v1/chat/conversations/[conversationId]/events/route_client-reference-manifest.js +1 -1
  210. package/.next/server/app/v1/chat/conversations/[conversationId]/resources/route_client-reference-manifest.js +1 -1
  211. package/.next/server/app/v1/chat/conversations/[conversationId]/respond/route.js +1 -1
  212. package/.next/server/app/v1/chat/conversations/[conversationId]/respond/route.js.nft.json +1 -1
  213. package/.next/server/app/v1/chat/conversations/[conversationId]/respond/route_client-reference-manifest.js +1 -1
  214. package/.next/server/app/v1/chat/conversations/[conversationId]/route.js +2 -2
  215. package/.next/server/app/v1/chat/conversations/[conversationId]/route.js.nft.json +1 -1
  216. package/.next/server/app/v1/chat/conversations/[conversationId]/route_client-reference-manifest.js +1 -1
  217. package/.next/server/app/v1/chat/conversations/route.js +2 -2
  218. package/.next/server/app/v1/chat/conversations/route.js.nft.json +1 -1
  219. package/.next/server/app/v1/chat/conversations/route_client-reference-manifest.js +1 -1
  220. package/.next/server/app/v1/models/route.js +1 -1
  221. package/.next/server/app/v1/models/route.js.nft.json +1 -1
  222. package/.next/server/app/v1/models/route_client-reference-manifest.js +1 -1
  223. package/.next/server/app/waves/page.js +3 -3
  224. package/.next/server/app/waves/page.js.nft.json +1 -1
  225. package/.next/server/app/waves/page_client-reference-manifest.js +1 -1
  226. package/.next/server/app/waves.html +1 -1
  227. package/.next/server/app/waves.rsc +4 -4
  228. package/.next/server/app-paths-manifest.json +2 -2
  229. package/.next/server/chunks/1083.js +1 -1
  230. package/.next/server/chunks/1114.js +1 -0
  231. package/.next/server/chunks/1197.js +2 -2
  232. package/.next/server/chunks/1226.js +1 -1
  233. package/.next/server/chunks/166.js +5 -0
  234. package/.next/server/chunks/2373.js +1 -0
  235. package/.next/server/chunks/2859.js +1 -3
  236. package/.next/server/chunks/289.js +1 -1
  237. package/.next/server/chunks/3030.js +1 -1
  238. package/.next/server/chunks/3298.js +2 -0
  239. package/.next/server/chunks/3312.js +1 -0
  240. package/.next/server/chunks/3774.js +1 -1
  241. package/.next/server/chunks/3823.js +9 -8
  242. package/.next/server/chunks/3855.js +1 -0
  243. package/.next/server/chunks/3924.js +52 -0
  244. package/.next/server/chunks/4545.js +21 -0
  245. package/.next/server/chunks/4561.js +9 -8
  246. package/.next/server/chunks/4578.js +1 -0
  247. package/.next/server/chunks/4671.js +1 -1
  248. package/.next/server/chunks/4677.js +37 -0
  249. package/.next/server/chunks/4771.js +2 -2
  250. package/.next/server/chunks/4793.js +2 -0
  251. package/.next/server/chunks/4836.js +1 -0
  252. package/.next/server/chunks/5311.js +1 -1
  253. package/.next/server/chunks/5463.js +1 -0
  254. package/.next/server/chunks/5544.js +5 -0
  255. package/.next/server/chunks/5708.js +11 -8
  256. package/.next/server/chunks/584.js +1 -0
  257. package/.next/server/chunks/62.js +1 -1
  258. package/.next/server/chunks/6240.js +1 -0
  259. package/.next/server/chunks/6306.js +1 -0
  260. package/.next/server/chunks/{3928.js → 6745.js} +1 -1
  261. package/.next/server/chunks/6908.js +2 -2
  262. package/.next/server/chunks/701.js +1 -1
  263. package/.next/server/chunks/7214.js +6 -0
  264. package/.next/server/chunks/7362.js +11 -7
  265. package/.next/server/chunks/7463.js +6 -0
  266. package/.next/server/chunks/7506.js +1 -1
  267. package/.next/server/chunks/7579.js +82 -0
  268. package/.next/server/chunks/7821.js +1 -1
  269. package/.next/server/chunks/8216.js +1 -0
  270. package/.next/server/chunks/8387.js +1 -0
  271. package/.next/server/chunks/856.js +5 -0
  272. package/.next/server/chunks/8652.js +1 -1
  273. package/.next/server/chunks/8739.js +2 -2
  274. package/.next/server/chunks/9165.js +1 -0
  275. package/.next/server/chunks/94.js +1 -0
  276. package/.next/server/chunks/9427.js +1 -0
  277. package/.next/server/edge-instrumentation.js +2 -0
  278. package/.next/server/edge-instrumentation.js.map +1 -0
  279. package/.next/server/edge-runtime-webpack.js +2 -0
  280. package/.next/server/edge-runtime-webpack.js.map +1 -0
  281. package/.next/server/instrumentation.js.nft.json +1 -1
  282. package/.next/server/middleware-build-manifest.js +1 -1
  283. package/.next/server/middleware-manifest.json +33 -2
  284. package/.next/server/middleware-react-loadable-manifest.js +1 -1
  285. package/.next/server/pages/404.html +1 -1
  286. package/.next/server/pages/500.html +1 -1
  287. package/.next/server/server-reference-manifest.js +1 -1
  288. package/.next/server/server-reference-manifest.json +1 -1
  289. package/.next/server/src/middleware.js +14 -0
  290. package/.next/server/src/middleware.js.map +1 -0
  291. package/.next/static/chunks/1675-773454288de4309d.js +1 -0
  292. package/.next/static/chunks/1731-6e45fb529f9044a3.js +1 -0
  293. package/.next/static/chunks/1871-14c3e63ca865d85e.js +1 -0
  294. package/.next/static/chunks/2003-7710c23acaef11c9.js +1 -0
  295. package/.next/static/chunks/2318-76fcb6c769b1a569.js +1 -0
  296. package/.next/static/chunks/2566-6e2b9d9349814789.js +1 -0
  297. package/.next/static/chunks/2734-59fbe2f62a59df86.js +1 -0
  298. package/.next/static/chunks/3089.6b4e21e1faa304e2.js +1 -0
  299. package/.next/static/chunks/3109-11bdec9bdfd996c3.js +1 -0
  300. package/.next/static/chunks/3217.f728df99ab5da33c.js +1 -0
  301. package/.next/static/chunks/333-5f3c5be57c80c48c.js +1 -0
  302. package/.next/static/chunks/3333-b7b3e5758a568013.js +1 -0
  303. package/.next/static/chunks/3556-3b6f7c99b015b752.js +1 -0
  304. package/.next/static/chunks/{6730-c330b55cd0fe4f47.js → 4003-3b3768446ae333df.js} +1 -1
  305. package/.next/static/chunks/4523-a540747aa2ed34e8.js +1 -0
  306. package/.next/static/chunks/4635-0fe310d3be64e71e.js +1 -0
  307. package/.next/static/chunks/4690-ec7d397cfacedac3.js +1 -0
  308. package/.next/static/chunks/4775-cb9c0be621363a08.js +8 -0
  309. package/.next/static/chunks/5336-81da1080de29ebfc.js +1 -0
  310. package/.next/static/chunks/5512.d01d565f73109a1a.js +1 -0
  311. package/.next/static/chunks/6691-117567b2b40cd9f4.js +1 -0
  312. package/.next/static/chunks/7274-1184563607f2b5f5.js +1 -0
  313. package/.next/static/chunks/8166-e75acdc559b34fcd.js +1 -0
  314. package/.next/static/chunks/8345.fbc0af16acce7256.js +1 -0
  315. package/.next/static/chunks/8405.e728bc83a7c9fed6.js +1 -0
  316. package/.next/static/chunks/8470-72cf748472d4d501.js +1 -0
  317. package/.next/static/chunks/8607-5787e42775fc3acb.js +1 -0
  318. package/.next/static/chunks/8610-660d5088bc1dd7a7.js +1 -0
  319. package/.next/static/chunks/8834-faf121e257b517d5.js +1 -0
  320. package/.next/static/chunks/8989-401559d9f3bc80a0.js +1 -0
  321. package/.next/static/chunks/{9164-d9f1abba780231e0.js → 9164-829ab5b085ec06d6.js} +1 -1
  322. package/.next/static/chunks/9240-d0a51f4d504f34b1.js +1 -0
  323. package/.next/static/chunks/9562-b7922ceb400ec536.js +1 -0
  324. package/.next/static/chunks/9704-6b7415964d7c042a.js +1 -0
  325. package/.next/static/chunks/app/chat/page-04ad1fad78048afb.js +1 -0
  326. package/.next/static/chunks/app/docs/page-5475c616764dbb18.js +1 -0
  327. package/.next/static/chunks/app/executions/page-c18708ed96d228ec.js +1 -0
  328. package/.next/static/chunks/app/flows/page-f7e44aa545bcc56e.js +1 -0
  329. package/.next/static/chunks/app/layout-e6fbae80e0f456a6.js +1 -0
  330. package/.next/static/chunks/app/mcp/page-3638fbee04a3a6ea.js +1 -0
  331. package/.next/static/chunks/app/models/error-5732fbb053e182c5.js +1 -0
  332. package/.next/static/chunks/app/models/page-e690a986047b1e62.js +1 -0
  333. package/.next/static/chunks/app/{page-a859e4dbd180df98.js → page-0a95c40a65dbd2eb.js} +1 -1
  334. package/.next/static/chunks/app/settings/page-3ef9b95187e18a5a.js +1 -0
  335. package/.next/static/chunks/app/waves/page-c9a307e2236423a4.js +1 -0
  336. package/.next/static/chunks/{main-be8e823624954fab.js → main-9bda5041078d2b6a.js} +1 -1
  337. package/.next/static/chunks/webpack-a6844e1074885c2f.js +1 -0
  338. package/.next/static/css/40f9bef305b11bf5.css +1 -0
  339. package/.next/trace +10 -8
  340. package/README.md +31 -1
  341. package/next.config.mjs +139 -119
  342. package/package.json +1 -1
  343. package/.next/server/chunks/1119.js +0 -1
  344. package/.next/server/chunks/1439.js +0 -1
  345. package/.next/server/chunks/1556.js +0 -52
  346. package/.next/server/chunks/1910.js +0 -37
  347. package/.next/server/chunks/1999.js +0 -1
  348. package/.next/server/chunks/2246.js +0 -1
  349. package/.next/server/chunks/264.js +0 -17
  350. package/.next/server/chunks/2823.js +0 -6
  351. package/.next/server/chunks/3286.js +0 -6
  352. package/.next/server/chunks/4637.js +0 -81
  353. package/.next/server/chunks/6644.js +0 -1
  354. package/.next/server/chunks/7427.js +0 -1
  355. package/.next/server/chunks/7769.js +0 -6
  356. package/.next/server/chunks/8357.js +0 -1
  357. package/.next/server/chunks/8518.js +0 -2
  358. package/.next/static/chunks/1620-0d8ecd877f123f7b.js +0 -1
  359. package/.next/static/chunks/1871-dd8c10ed9d37100b.js +0 -1
  360. package/.next/static/chunks/1983-242862b3dc022a26.js +0 -1
  361. package/.next/static/chunks/2003-460f30484998c05d.js +0 -1
  362. package/.next/static/chunks/2619-04bc32f026a0d946.js +0 -1
  363. package/.next/static/chunks/3217.058098140ec3f563.js +0 -1
  364. package/.next/static/chunks/3736-5e2b3f6cda1bb923.js +0 -1
  365. package/.next/static/chunks/4207-41abb9622eb4b4f8.js +0 -1
  366. package/.next/static/chunks/4812-4a9aceb49632a973.js +0 -1
  367. package/.next/static/chunks/5501-f5b093c8dfd74196.js +0 -1
  368. package/.next/static/chunks/5545-2ab6e5d749e103cd.js +0 -1
  369. package/.next/static/chunks/6016.8201fa15ab6aa90e.js +0 -1
  370. package/.next/static/chunks/6288-a285bbbd701e0dbf.js +0 -1
  371. package/.next/static/chunks/6731-c230e88cf0032609.js +0 -1
  372. package/.next/static/chunks/6920-a83ad5c0d5a54cf3.js +0 -1
  373. package/.next/static/chunks/7430-6e78aaeac66988a9.js +0 -1
  374. package/.next/static/chunks/7583.7af90b94e3c263f2.js +0 -1
  375. package/.next/static/chunks/7687-7edf1a6e1f063b08.js +0 -1
  376. package/.next/static/chunks/8083.16fda2c7f6d10d0c.js +0 -1
  377. package/.next/static/chunks/8480-229fd353b68b570f.js +0 -1
  378. package/.next/static/chunks/8548-8e4a95334064e8b2.js +0 -1
  379. package/.next/static/chunks/8834-bda798efab40c60a.js +0 -1
  380. package/.next/static/chunks/9181-8d8ecd3f641b7209.js +0 -8
  381. package/.next/static/chunks/9356-99ba407b60b9dfe9.js +0 -1
  382. package/.next/static/chunks/9451-680fa09f81f18806.js +0 -1
  383. package/.next/static/chunks/9659-a279e3aaba407251.js +0 -1
  384. package/.next/static/chunks/app/chat/page-ea6752144d35c892.js +0 -1
  385. package/.next/static/chunks/app/docs/page-935b0386917b91bb.js +0 -1
  386. package/.next/static/chunks/app/executions/page-d72027b0179e8fa2.js +0 -1
  387. package/.next/static/chunks/app/flows/page-1844e86dd43fa285.js +0 -1
  388. package/.next/static/chunks/app/layout-2ebf01d97702a18a.js +0 -1
  389. package/.next/static/chunks/app/mcp/page-b6866f49f76a6801.js +0 -1
  390. package/.next/static/chunks/app/models/error-a3183f168e8a9b04.js +0 -1
  391. package/.next/static/chunks/app/models/page-5a13ea6ff5ac1b9c.js +0 -1
  392. package/.next/static/chunks/app/settings/page-7a68583660508ffd.js +0 -1
  393. package/.next/static/chunks/app/waves/page-ec33cf79f6103a9e.js +0 -1
  394. package/.next/static/chunks/webpack-f4a471ab560eb19e.js +0 -1
  395. package/.next/static/css/39393a79f7cb0dee.css +0 -1
  396. /package/.next/static/{WRUzIBdypUJvv0xAct8qc → Il6IDWxf3CN0dv-P6QQrp}/_buildManifest.js +0 -0
  397. /package/.next/static/{WRUzIBdypUJvv0xAct8qc → Il6IDWxf3CN0dv-P6QQrp}/_ssgManifest.js +0 -0
@@ -0,0 +1,6 @@
1
+ "use strict";exports.id=7463,exports.ids=[7463],exports.modules={54898:(a,b,c)=>{c.d(b,{nC:()=>m});var d=c(8336),e=c(78606),f=c(27386),g=c(33132);function h(a){return a.data?.type??a.type??"unknown"}function i(a){return a.data?.label||a.id}function j(a){return a.data?.edgeType==="mcp"}function k(a){return a.data?.edgeType==="resource"}function l(a){return j(a)||k(a)}function m(a,b={}){let c=[],n=Array.isArray(a?.nodes)?a.nodes:[],o=Array.isArray(a?.edges)?a.edges:[],p=(a,b,d,e)=>c.push({severity:a,code:b,message:d,nodeId:e?.id,nodeLabel:e?i(e):void 0}),q=new Map((b.models??[]).map(a=>[a.id,a])),r=new Map((b.servers??[]).map(a=>[a.name,a])),s=!!b.models,t=!!b.servers,u=n.filter(a=>"start"===h(a)),v=n.filter(a=>"finish"===h(a)),w=n.filter(a=>"process"===h(a)),x=n.filter(a=>"mcp"===h(a));if(0===u.length)p("error","no-start-node","The flow has no Start node, so it has no entry point.");else if(u.length>1)for(let a of u.slice(1))p("error","multiple-start-nodes","The flow has more than one Start node; only one is allowed.",a);for(let a of(0===v.length&&p("warning","no-finish-node","The flow has no Finish node; it will run but never reaches a defined end."),w)){let b=a.data?.properties??{},c=b.boundModel;if(c){if(s&&!q.has(c)){let c="string"==typeof b.modelName&&b.modelName?` (was "${b.modelName}")`:"";p("error","process-model-missing",`Process node "${i(a)}" is bound to a model that no longer exists${c}.`,a)}}else p("error","process-missing-model",`Process node "${i(a)}" has no model bound.`,a)}for(let a of x){let b=(a.data?.properties??{}).boundServer;if(b){if(t&&!r.has(b))p("warning","mcp-server-missing",`MCP node "${i(a)}" is bound to server "${b}", which isn't in your current MCP server list. It may be offline (e.g. not connected), renamed, or removed — if it was renamed or removed, rebind this node.`,a);else if(t){let c=r.get(b);if(c.status&&"connected"!==c.status){let d="disabled"===c.status?"disabled":`not connected (${c.status})`;p("warning","mcp-server-disconnected",`MCP node "${i(a)}" is bound to server "${b}", which is currently ${d}. It will provide tools again once it reconnects.`,a)}}}else p("warning","mcp-missing-server",`MCP node "${i(a)}" is not bound to a server.`,a);o.some(b=>j(b)&&(b.source===a.id||b.target===a.id))||p("warning","mcp-node-unconnected",`MCP node "${i(a)}" is not connected to any Process node.`,a)}for(let a of n.filter(a=>"resource"===h(a))){let b=a.data?.properties??{},c="run"===b.scope?"run":"mcp",d="string"==typeof b.boundServer?b.boundServer:"",e="string"==typeof b.uri?b.uri:"",g="string"==typeof b.runName?b.runName.trim():"";"mcp"!==c||d&&e||p("warning","resource-missing-binding",`Resource node "${i(a)}" has no ${!d?"server":"resource URI"} bound; connected steps will receive nothing.`,a),"run"!==c||g||p("warning","resource-missing-binding",`Resource node "${i(a)}" is a run artifact with no name; give it a name so steps can produce/consume it.`,a),"run"===c&&g&&!(0,f.qW)(g)&&p("warning","resource-run-name",`Resource node "${i(a)}" is named "${g}", which is not a valid artifact name (letters, digits, _ and - only, not starting with a digit); it will be awkward to reference with \${res:...}.`,a),"mcp"===c&&d&&t&&!r.has(d)&&p("warning","resource-server-missing",`Resource node "${i(a)}" is bound to server "${d}", which isn't in your current MCP server list.`,a);let h=o.filter(b=>k(b)&&(b.source===a.id||b.target===a.id));0===h.length&&p("warning","resource-node-unconnected",`Resource node "${i(a)}" is not connected to any Process node.`,a);let j=h.filter(b=>b.target===a.id);"mcp"===c&&j.length>0&&p("error","resource-produce-static",`Resource node "${i(a)}" is a static MCP resource, but a step writes INTO it. Only run artifacts (scope "run") can be produced by a step — flip the edge or make this a run artifact.`,a),"run"===c&&j.length>1&&p("warning","resource-multiple-producers",`Resource node "${i(a)}" is produced by ${j.length} steps; the last writer wins. Consider one producer per artifact.`,a),"run"===c&&0===j.length&&h.length>0&&p("warning","resource-consumed-never-produced",`Resource node "${i(a)}" is consumed but no step in this flow produces it; it resolves to nothing unless an earlier run captured it.`,a)}for(let a of n.filter(a=>"signal"===h(a))){let b=a.data?.properties??{};("string"==typeof b.topic?b.topic.trim():"")||p("warning","signal-missing-topic",`Signal node "${i(a)}" has no topic; it emits nothing. Give it a topic that a flow-event trigger can listen for.`,a)}if(u.length>0){let a=function(a){let b=new Map,c=(a,c)=>{b.has(a)||b.set(a,[]),b.get(a).push(c)};for(let b of a)!l(b)&&(c(b.source,b.target),b.data?.bidirectional&&c(b.target,b.source));return b}(o);for(let b of u)a.get(b.id)?.length||p("error","start-no-outgoing","The Start node is not connected to anything; the flow cannot run.",b);let b=function(a,b){let c=new Set(a),d=[...a];for(;d.length;){let a=d.shift();for(let e of b.get(a)??[])c.has(e)||(c.add(e),d.push(e))}return c}(u.map(a=>a.id),a);for(let a of[...w,...v])b.has(a.id)||p("warning","unreachable-node",`${"finish"===h(a)?"Finish":"Process"} node "${i(a)}" is not reachable from the Start node.`,a)}for(let a of n.filter(a=>"subflow"===h(a))){let b=o.filter(b=>!l(b)&&(b.source===a.id||b.target===a.id&&!!b.data?.bidirectional));b.length>1&&p("error","subflow-multiple-outgoing",`Subflow node "${i(a)}" has ${b.length} outgoing connections; a subflow can only have one (either A > B > C or a bidirectional A <> B).`,a);let c=a.data?.properties??{},d="string"==typeof c.subflowId&&c.subflowId?c.subflowId:void 0,e=Array.isArray(c.parallelSubflowIds)?c.parallelSubflowIds.filter(a=>"string"==typeof a&&!!a):[];d&&e.length>0&&p("error","subflow-both-targets",`Subflow node "${i(a)}" sets both a single "subflowId" and "parallelSubflowIds"; use one or the other.`,a);let g=!0===c.mapOverList;g&&e.length>0&&p("error","subflow-map-and-parallel",`Subflow node "${i(a)}" combines "mapOverList" with "parallelSubflowIds"; map-over-list runs a single child once per item and cannot be combined with parallel fan-out.`,a),g&&!d&&0===e.length&&p("error","subflow-map-no-child",`Subflow node "${i(a)}" has "mapOverList" but no child flow ("subflowId"); select a flow to run once per item.`,a);let h=Array.isArray(c.spawnBriefs)?c.spawnBriefs.filter(a=>"string"==typeof a&&""!==a.trim()):[];h.length>0&&!d&&p("error","subflow-spawn-no-child",`Subflow node "${i(a)}" has spawn briefs but no sub-agent flow ("subflowId"); select the flow to spawn once per brief.`,a),h.length>0&&e.length>0&&p("error","subflow-spawn-and-parallel",`Subflow node "${i(a)}" combines "spawnBriefs" with "parallelSubflowIds"; spawn briefs run one sub-agent per brief and cannot be combined with a multi-flow fan-out list.`,a),h.length>0&&g&&p("error","subflow-spawn-and-map",`Subflow node "${i(a)}" combines "spawnBriefs" with "mapOverList"; use one lane source or the other.`,a);let j="string"==typeof c.parallelSubflowIdsVar?c.parallelSubflowIdsVar.trim():"";if(j&&((0,f.qW)(j)||p("warning","subflow-parallel-var-name",`Subflow node "${i(a)}" reads dynamic fan-out targets from "${j}", which is not a valid variable name (letters, digits, _ and - only, not starting with a digit); it will be awkward to capture with \${var:...}.`,a),g&&p("error","subflow-map-and-parallel-var",`Subflow node "${i(a)}" combines "mapOverList" with dynamic fan-out ("parallelSubflowIdsVar"); map-over-list runs a single child once per item and cannot be combined with fan-out.`,a),n.some(a=>{let b=a.data?.properties?.captureVariable;return"string"==typeof b&&b.trim()===j})||p("warning","subflow-parallel-var-uncaptured",`Subflow node "${i(a)}" reads dynamic fan-out targets from variable "${j}", but no node captures it (captureVariable). It may be seeded by the caller; otherwise it resolves to no targets and the node falls back to its static parallel list.`,a)),!0===c.allowCallerFanout&&g&&p("error","subflow-map-and-caller-fanout",`Subflow node "${i(a)}" combines "mapOverList" with agentic fan-out ("allowCallerFanout"); map-over-list runs a single child once per item and cannot be combined with fan-out.`,a),e.length>0||h.length>0){let b=c.concurrencyLimit;"number"==typeof b&&b<1&&p("warning","subflow-concurrency-limit",`Subflow node "${i(a)}" has a concurrencyLimit of ${b}; it must be at least 1 (the runtime default will be used).`,a)}}{let a=new Map(n.map(a=>[a.id,a])),b=new Set;for(let c of o){if(l(c))continue;let d=c.data?.condition;if(!d||"object"!=typeof d)continue;let f=a.get(c.source),g=f?h(f):"unknown";if("process"!==g){p("error","edge-condition-non-process",`An edge leaving ${"unknown"===g?"an unknown":`the ${g}`} node "${f?i(f):c.source}" has a routing condition, but only process nodes can route on a condition.`,f??void 0);continue}b.add(c.source),(0,e.C)(d.kind)?"always"===d.kind||("string"!=typeof d.value||0===d.value.length?p("warning","edge-condition-value",`Process node "${i(f)}" has an outgoing edge condition with no "value"; it will never match.`,f):"regex"!==d.kind||(0,e.wM)(d.value)||p("warning","edge-condition-regex",`Process node "${i(f)}" has an outgoing edge with a regex condition that does not compile; it will never match.`,f)):p("warning","edge-condition-kind",`Process node "${i(f)}" has an outgoing edge whose condition kind "${String(d.kind)}" is unknown; it will never match.`,f)}for(let c of b){let b=a.get(c);b&&(o.some(a=>!l(a)&&(a.source===c?!a.data?.condition||"always"===a.data.condition.kind&&!a.data.condition.negate:!!(a.target===c&&a.data?.bidirectional)))||p("warning","edge-condition-no-fallback",`Process node "${i(b)}" has conditioned outgoing edges but no bare fallback edge; if no condition matches, the flow ends here.`,b))}}{let a=new Set;for(let b of n){let c=b.data?.properties?.captureVariable;if("string"==typeof c&&c.trim()){let d=c.trim();a.add(d),(0,f.qW)(d)||p("warning","capture-var-name",`${"subflow"===h(b)?"Subflow":"Process"} node "${i(b)}" captures into "${d}", which is not a valid variable name (letters, digits, _ and - only, not starting with a digit); it will be awkward to reference with \${var:...}.`,b)}}let b=["promptTemplate","isolatedPrompt"],c=new Set;for(let d of n){let e=d.data?.properties??{};for(let g of b){let b=e[g];if("string"==typeof b&&b)for(let e of(0,f.T9)(b)){if(a.has(e))continue;let b=`${d.id}:${e}`;c.has(b)||(c.add(b),p("warning","var-ref-uncaptured",`${i(d)} references \${var:${e}} but no step in this flow captures "${e}" (via captureVariable). It resolves to empty unless supplied as a run input — check for a typo or a step ordered after this one.`,d))}}}}{for(let a of n){let b=a.data?.properties?.captureKv;if("string"==typeof b&&b.trim()){let{key:c}=(0,g.g2)(b.trim());(0,g.ng)(c)||p("warning","capture-kv-name",`${"subflow"===h(a)?"Subflow":"Process"} node "${i(a)}" captures into kv "${b.trim()}", whose key is not a valid name (letters, digits, _ and - only, not starting with a digit); it will be awkward to reference with \${kv:...}.`,a)}}let a=["promptTemplate","isolatedPrompt"],b=new Set;for(let c of n){let d=c.data?.properties??{};for(let e of a){let a=d[e];if("string"==typeof a&&a)for(let d of(0,g.pf)(a)){let{key:a}=(0,g.g2)(d);if((0,g.ng)(a))continue;let e=`${c.id}:${d}`;b.has(e)||(b.add(e),p("warning","kv-ref-name",`${i(c)} references \${kv:${d}}, whose key is not a valid name (letters, digits, _ and - only, not starting with a digit); it resolves to empty.`,c))}}}}for(let a of w){let c=a.data?.properties?.promptTemplate;if("string"!=typeof c||!c)continue;let e=function(a,b,c){let d=new Map(b.map(a=>[a.id,a])),e=new Set;for(let b of c){if(!j(b))continue;let c=null;if(b.source===a?c=b.target:b.target===a&&(c=b.source),!c)continue;let f=d.get(c);if(!f||"mcp"!==h(f))continue;let g=f.data?.properties?.boundServer;"string"==typeof g&&g&&e.add(g)}return e}(a.id,n,o),f=new Set;for(let g of(0,d.A$)(c)){if("handoff"===g.server)continue;let c=`${g.kind}:${g.server}:${g.name}`;!f.has(c)&&(f.add(c),e.has(g.server)?"tool"===g.kind&&b.serverTools&&b.serverTools[g.server]&&!b.serverTools[g.server].includes(g.name)&&p("warning","tool-unavailable",`Process node "${i(a)}" references tool "${g.name}" which server "${g.server}" no longer provides.`,a):p("error","tool-pill-disconnected",`Process node "${i(a)}" references ${g.kind} "${g.name}" from server "${g.server}", but it is not connected to that server (the MCP node was removed or the server was renamed).`,a))}}let y=c.filter(a=>"error"===a.severity).length,z=c.length-y;return{issues:c,errorCount:y,warningCount:z,isRunnable:0===y}}},67463:(a,b,c)=>{c.d(b,{runFlow:()=>C});var d=c(18230),e=c(44561),f=c(79111),g=c(44479);let h=(0,d.h)("backend/execution/flow/persistConversationState");async function i(a,b){let c="conversations/",d=String(a).startsWith(c)?String(a).slice(c.length):String(a);return((0,f.ln)(d),null!=b.conversationId&&(0,f.ln)(b.conversationId),b.ephemeral)?(h.debug(`Refusing to persist ephemeral state (key ${a}); ephemeral runs never reach the conversations store.`),Promise.resolve()):(0,g.isConversationDeleted)(b.conversationId)?(h.info(`Refusing to persist state for deleted conversation ${b.conversationId} (key ${a}).`),Promise.resolve()):(0,f.VH)(a,{...b,executionTrace:void 0,emit:void 0})}var j=c(34115),k=c(96249),l=c(37860),m=c(26485),n=c(80808),o=c(59448),p=c(11659),q=c(86028),r=c(12763),s=c(82464),t=c(54898);let u=(0,d.h)("backend/execution/flow/validateFlowForRun");async function v(a){let b,c;try{b=await r.modelService.loadModels()}catch(a){u.warn("validateFlowObjectForRun: could not load models; skipping model checks",a)}try{let a=await s.mcpService.loadServerConfigs();Array.isArray(a)&&(c=a.map(a=>({name:a.name,status:a.disabled?"disabled":void 0})))}catch(a){u.warn("validateFlowObjectForRun: could not load servers; skipping server checks",a)}return(0,t.nC)(a,{models:b,servers:c})}async function w(a){let b=await p.flowService.getFlow(a);return b?v(b):(u.warn(`validateFlowForRun: flow ${a} could not be loaded; skipping pre-run checks`),{issues:[],errorCount:0,warningCount:0,isRunnable:!0})}var x=c(85701),y=c(35796);let z=(0,d.h)("backend/execution/flow/runFlow");p.flowService.getFlowByName||(p.flowService.getFlowByName=async a=>(await p.flowService.loadFlows()).find(b=>b.name===a)||null,z.info("Added getFlowByName method directly to flowService instance."));let A=p.flowService;async function B(a,b,c){try{let d,e=a.flowId;if(!e)return;try{d=(await p.flowService.getFlow(e))?.name??void 0}catch{}let f="api"===a.source?"api":"chat",g=c&&c.length>4096?`${c.slice(0,4096)}…`:c;(0,l.eh)().publish({flowId:e,flowName:d,executionId:a.plannedExecutionId,runId:a.conversationId||"",conversationId:a.conversationId||"",status:b,outputText:g,firedBy:f,chainDepth:a.chainDepth??0,timestamp:new Date().toISOString()})}catch(a){z.warn("Failed to publish runFlow flow-run event:",a)}}async function C(a){let b,c,d,h=Date.now(),l=a.flujo??!0,r=a.requireApproval??!1,s=a.debug??!1,t=a.continueDebug??!1,u=a.userTurn??!1,C="ephemeral"===a.mode,D=a.messages??(void 0!==a.prompt?[{role:"user",content:a.prompt}]:[]),E={model:a.modelName,messages:D,processNodeId:a.processNodeId};z.info("runFlow invoked",{flowId:a.flowId,model:a.modelName,messageCount:D.length,mode:C?"ephemeral":"conversation",flujo:l,requireApproval:r,flujodebug:s,conversationId:a.conversationId});let F=a.conversationId||crypto.randomUUID(),G=`conversations/${F}`,H="new",I=!1;if(z.info(`Effective Conversation ID for this run: ${F}`,{providedId:a.conversationId}),e.FlowExecutor.conversationStates.has(F))c=e.FlowExecutor.conversationStates.get(F),z.info(`Resuming conversation ${F} from memory`,{currentNodeId:c.currentNodeId}),H="memory";else if(!C)try{(c=await (0,f.YM)(G,void 0))?(z.info(`Loaded conversation state from storage: ${F}`),H="storage",await (0,j.jM)(c),e.FlowExecutor.conversationStates.set(F,c)):z.info(`No state found in storage for conversation: ${F}. Will create new state.`)}catch(a){z.warn(`Error loading conversation state from storage for ${F}:`,a)}if(c?((b=c).conversationId!==F&&(z.warn(`Loaded state's internal conversationId (${b.conversationId}) differs from effectiveConvId (${F}). Using effectiveConvId.`),b.conversationId=F),"new"!==H&&("completed"===b.status||"error"===b.status||void 0===b.status)&&(z.info(`Resuming completed/errored/fresh conversation ${F}. Resetting status to 'running'.`),I="error"===b.status,b.status="running",b.lastResponse=void 0,b.isCancelled=!1,"storage"===H&&e.FlowExecutor.conversationStates.set(F,b)),E.processNodeId&&"new"!==H&&(z.info(`Edit detected: Resetting currentNodeId for conversation ${F} to provided processNodeId: ${E.processNodeId}`),b.currentNodeId=E.processNodeId,b.status="running",b.lastResponse=void 0,b.pendingToolCalls=void 0,b.handoffRequested=void 0,b.isCancelled=!1,b.trackingInfo={executionId:crypto.randomUUID(),startTime:Date.now(),nodeExecutionTracker:[]},q.G.ENABLE_EXECUTION_TRACKER&&b.executionTrace&&(b.executionTrace=[]),e.FlowExecutor.conversationStates.set(F,b),z.verbose(`State updated in memory with reset currentNodeId: ${b.currentNodeId}`))):(z.info(`Creating new conversation state object for ID: ${F}`),b={trackingInfo:{executionId:crypto.randomUUID(),startTime:Date.now(),nodeExecutionTracker:(q.G.ENABLE_EXECUTION_TRACKER,[])},messages:[],flowId:"",conversationId:F,currentNodeId:void 0,status:"running",title:a.title?.trim()||"New Conversation",createdAt:Date.now(),updatedAt:Date.now(),debugMode:s,executionTrace:s&&q.G.ENABLE_EXECUTION_TRACKER?[]:void 0,variables:{}}),a.variables&&"object"==typeof a.variables)for(let[c,d]of(b.variables=b.variables??{},Object.entries(a.variables)))null!=d&&(b.variables[c]="string"==typeof d?d:String(d));if(b.requireApproval=r,a.source&&(b.source=a.source),a.plannedExecutionId&&(b.plannedExecutionId=a.plannedExecutionId),C&&(b.ephemeral=!0),a.parentRunId&&(b.parentRunId=a.parentRunId),b.runDepth=a.depth??b.runDepth??0,b.chainDepth=a.chainDepth??b.chainDepth??0,b.onApprovalRequired=a.onApprovalRequired??b.onApprovalRequired??"auto",b.runDepth>x.A)return z.error(`runFlow aborted: subflow depth ${b.runDepth} exceeds max ${x.A}`),b.status="error",{status:"error",conversationId:F,outputText:"",messages:b.messages,error:{message:`Subflow recursion limit (${x.A}) exceeded`,statusCode:500},finalAction:m.O,sharedState:b};let J=[...b.messages??[]];if("new"===H){a.flowDefinition&&(b.flowSnapshot=a.flowDefinition,b.flowId=a.flowDefinition.id);let c=a.flowDefinition?a.flowDefinition.id:a.flowId;if(!c&&E.model){let a=E.model.substring(5),d=await A.getFlowByName(a);if(!d)return z.error(`Flow not found: ${a}`),{status:"error",conversationId:F,outputText:"",messages:b.messages,flowNotFound:{name:a},error:{message:`Flow not found: ${a}`,statusCode:400},finalAction:m.O,sharedState:b};c=d.id}if(!c)return z.error("No flow specified for run (neither flowId nor model provided)."),{status:"error",conversationId:F,outputText:"",messages:b.messages,error:{message:"No flow specified (provide flowId or model).",statusCode:400},finalAction:m.O,sharedState:b};b.flowId=c;let d=(E.messages||[]).filter(a=>!(a.depth>0)).map(a=>({...a,id:a.id||crypto.randomUUID(),timestamp:a.timestamp||Date.now(),processNodeId:a.processNodeId||void 0}));b.messages=d;try{if(b.updatedAt=Date.now(),"New Conversation"===b.title&&b.messages.length>0){let a=b.messages.find(a=>"user"===a.role);a&&"string"==typeof a.content&&(b.title=(0,y.oO)(a.content),z.verbose(`Updated conversation title for ${F} during init to: ${b.title}`))}await i(G,b),z.debug(`Saved initial state for new conversation ${F}.`)}catch(a){z.error(`Failed to save initial state for new conversation ${F}:`,a)}e.FlowExecutor.conversationStates.set(F,b)}else E.messages&&E.messages.length>0&&(b.messages=E.messages.filter(a=>!(a.depth>0)).map(a=>({...a,id:a.id||crypto.randomUUID(),timestamp:a.timestamp||Date.now(),processNodeId:a.processNodeId||void 0})),z.info(`Updated conversation ${b.conversationId} with ${b.messages.length} messages from request`)),(u||void 0===b.debugMode)&&(b.debugMode=s),u&&(b.debugPendingToolCalls=void 0),b.debugMode&&q.G.ENABLE_EXECUTION_TRACKER&&!b.executionTrace&&(b.executionTrace=[]);try{await (0,j.UG)(b,J)}catch(a){z.warn(`Conversation-log reconcile failed for ${F}; continuing`,a)}if(u&&"new"!==H&&!E.processNodeId){let a=b.messages.length>0?b.messages[b.messages.length-1]:void 0;a?.role==="user"&&a.processNodeId&&a.processNodeId!==b.currentNodeId&&(z.info(`New user turn for ${F}: directing execution to node ${a.processNodeId} (was ${b.currentNodeId}).`),b.currentNodeId=a.processNodeId,e.FlowExecutor.conversationStates.set(F,b))}if(I&&u&&!C&&"new"!==H&&!E.processNodeId){let a=b.messages.length>0?b.messages[b.messages.length-1]:void 0;if(a?.role!=="user"){let a;for(let c=b.messages.length-1;c>=0;c--)if("user"===b.messages[c].role){a=b.messages[c].processNodeId;break}if(!a&&b.flowId)try{let c=await p.flowService.getFlow(b.flowId);a=c?.nodes?.find(a=>"start"===a.type)?.id}catch(a){z.warn(`Could not resolve start node for error-resume of ${F}`,a)}a&&a!==b.currentNodeId&&(z.info(`Error-resume for ${F}: replaying turn from entry node ${a} (was ${b.currentNodeId}).`),b.currentNodeId=a,e.FlowExecutor.conversationStates.set(F,b))}}u&&b.flowId&&(e.FlowExecutor.clearFlowCache(b.flowId),z.debug(`Cleared compiled-flow cache for ${b.flowId} at start of user turn ${F}.`));let K=!1,L=0,M=a.emit??k.$.emitterFor(F),N=new Set(b.messages.map(a=>a.id).filter(a=>!!a)),O=a=>{if(!a.usage)return;let c=b.usage??{promptTokens:0,completionTokens:0,totalTokens:0,costUsd:0,byNode:{}};c.promptTokens+=a.usage.promptTokens,c.completionTokens+=a.usage.completionTokens,c.totalTokens+=a.usage.totalTokens;let d=a.usage.cacheReadTokens??0;d&&(c.cacheReadTokens=(c.cacheReadTokens??0)+d);let e=a.processNodeId||"unknown",f=c.byNode[e]??{promptTokens:0,completionTokens:0,totalTokens:0,costUsd:0};f.promptTokens+=a.usage.promptTokens,f.completionTokens+=a.usage.completionTokens,f.totalTokens+=a.usage.totalTokens,d&&(f.cacheReadTokens=(f.cacheReadTokens??0)+d),c.byNode[e]=f,b.usage=c,M({type:"usage",node:a.processNodeId?{nodeId:a.processNodeId}:void 0,promptTokens:a.usage.promptTokens,completionTokens:a.usage.completionTokens,totalTokens:a.usage.totalTokens,costUsd:0,...d?{cacheReadTokens:d}:{}})},P=()=>{for(let a of b.messages)a.id||(a.id=crypto.randomUUID()),N.has(a.id)||(N.add(a.id),"system"!==a.role&&(M({type:"message",message:a,node:a.processNodeId?{nodeId:a.processNodeId}:void 0}),O(a)))};if(M({type:"run:start",flowId:b.flowId}),(u||"new"===H)&&b.flowId)try{let a=b.flowSnapshot?await v(b.flowSnapshot):await w(b.flowId);if(!a.isRunnable){let c=a.issues.filter(a=>"error"===a.severity),e=`This flow can't run yet — please fix the following before running:
2
+ `+c.map(a=>`• ${a.message}`).join("\n");z.warn(`Pre-run validation blocked flow ${b.flowId} for conv ${F}`,{errorCount:c.length,codes:c.map(a=>a.code)}),b.lastResponse={success:!1,error:e,errorDetails:{message:e,type:"invalid_request_error",code:"flow_invalid",status:400}},d=m.O,K=!0}}catch(a){z.warn(`Pre-run validation could not complete for ${b.flowId}; proceeding`,a)}let Q=()=>!!b.isCancelled||!!(0,g.isCancelledByAncestry)(b.parentRunId,e.FlowExecutor.conversationStates)&&(b.isCancelled=!0,!0),R=!!b.debugMode&&!t,S=()=>{b.status="paused_debug",M({type:"run:paused",reason:"debug",node:b.currentNodeId?{nodeId:b.currentNodeId}:void 0})};try{if(!K)for(;;){if(L++,z.debug(`--- Starting Execution Step ${L} for Conv ${F} ---`),L>150){z.warn(`Max internal iterations (150) reached for conv ${F}. Breaking loop.`),d!==m.O&&(b.lastResponse={success:!1,error:"Maximum internal iterations (150) reached."},d=m.O);break}if(Q()){z.info(`Cancellation flag detected for conv ${F}. Terminating execution.`),b.status="error",b.lastResponse={success:!1,error:"Execution cancelled by user."},d=m.O;break}if(b.debugPendingToolCalls&&b.debugPendingToolCalls.length>0){let a=b.debugPendingToolCalls;b.debugPendingToolCalls=void 0,z.info(`[Debug Step] Executing ${a.length} pending tool call(s) for conv ${F}.`);let c=await n.s.processToolCalls({toolCalls:a,toolNameMap:b.toolNameMap,emit:M,conversationId:b.ephemeral?void 0:b.conversationId,node:b.currentNodeId?{nodeId:b.currentNodeId}:void 0,shouldAbort:Q});if(!c.success){z.error(`Debug tool processing failed for conv ${F}`,{error:c.error}),b.lastResponse={success:!1,error:"Tool processing failed",errorDetails:c.error},d=m.O;break}let f=c.value.toolCallMessages.map(a=>({...a,id:crypto.randomUUID(),timestamp:Date.now(),processNodeId:b.currentNodeId}));b.messages.push(...f),e.FlowExecutor.conversationStates.set(F,b),P();try{b.updatedAt=Date.now(),await i(G,b)}catch(a){z.error(`Failed to save state after debug tool execution for conv ${F}:`,a)}if(R){z.info(`[Debug Step] Paused after tool execution for conv ${F}.`),S();break}continue}if(!R&&b.breakpoints&&b.breakpoints.length>0){let a=await e.FlowExecutor.peekNextNodeId(b);if(a&&b.breakpoints.includes(a)&&b.lastBreakNodeId!==a){z.info(`Breakpoint hit at node ${a} for conv ${F}. Pausing.`),b.status="paused_debug",b.debugMode=!0,b.lastBreakNodeId=a,M({type:"breakpoint:hit",node:{nodeId:a}}),M({type:"run:paused",reason:"breakpoint",node:{nodeId:a}});try{b.updatedAt=Date.now(),await i(G,b)}catch(a){z.error(`Failed to save state on breakpoint for conv ${F}:`,a)}break}a&&b.lastBreakNodeId&&a!==b.lastBreakNodeId&&(b.lastBreakNodeId=void 0)}if(b.messages.length>0){let a=b.messages.slice(-3);z.verbose(`Message history before step ${L}`,a)}else z.verbose(`No messages in history before step ${L}`);let a=await e.FlowExecutor.executeStep(b,M);if(b=a.sharedState,d=a.action,P(),b.updatedAt=Date.now(),"New Conversation"===b.title&&b.messages.length>0){let a=b.messages.find(a=>"user"===a.role);a&&"string"==typeof a.content&&(b.title=(0,y.oO)(a.content),z.verbose(`Updated conversation title for ${F} after step ${L} to: ${b.title}`))}if(z.info(`Step ${L} completed for conv ${F}. Action: ${d}`,{currentNodeId:b.currentNodeId}),z.verbose(`Shared state after step ${L}`,b),z.debug(`[Action Handling] Step ${L}: Received action "${d}" for conv ${F}`),d===m.O){z.info(`[Action Handling] Step ${L}: Handling ERROR_ACTION for conv ${F}`),z.error(`Error action received during step ${L} for conv ${F}`,{error:b.lastResponse});break}if(d===m.g4){z.info(`[Action Handling] Step ${L}: Handling FINAL_RESPONSE_ACTION for conv ${F}`),z.info(`Final response action received at step ${L} for conv ${F}`),b.status="completed",z.info(`Setting conversation status to 'completed' for conv ${F}`);break}if(d===m.Jp){z.info(`[Action Handling] Step ${L}: Handling TOOL_CALL_ACTION for conv ${F}`),z.info(`Tool call action received at step ${L} for conv ${F}`);let a=b.messages.length>0?b.messages[b.messages.length-1]:null;if(a?.role==="assistant"&&a.tool_calls)if(l){if(r&&"fail"===b.onApprovalRequired){let c=a.tool_calls[0],e=c&&"function"===c.type?c.function.name:"unknown";z.info(`[flujo=true, onApprovalRequired=fail] Failing fast for tool "${e}" (conv ${F})`),b.status="error",b.pendingToolCalls=a.tool_calls,b.lastResponse={success:!1,error:`Headless run requires approval for tool "${e}" but no approver is available (approvalPolicy: fail).`,errorDetails:{message:`Headless run requires approval for tool "${e}" but no approver is available (approvalPolicy: fail).`,type:"approval_required",name:e}},d=m.O;break}if(r){z.info(`[flujo=true, requireApproval=true] Pausing execution for tool approval for conv ${F}`),b.status="awaiting_tool_approval",b.pendingToolCalls=a.tool_calls,b.lastResponse=void 0,e.FlowExecutor.conversationStates.set(F,b);try{if(b.updatedAt=Date.now(),"New Conversation"===b.title&&b.messages.length>0){let a=b.messages.find(a=>"user"===a.role);a&&"string"==typeof a.content&&(b.title=(0,y.oO)(a.content),z.verbose(`Updated conversation title for ${F} before pausing to: ${b.title}`))}await i(G,b),z.verbose(`Saved state before pausing for approval for conv ${F}`)}catch(a){z.error(`Failed to save state before pausing for approval for conv ${F}:`,a)}M({type:"run:awaiting_approval",pendingToolCalls:a.tool_calls});break}if(R){z.info(`[Debug Step] Paused before executing ${a.tool_calls.length} tool call(s) for conv ${F}.`),b.debugPendingToolCalls=a.tool_calls,e.FlowExecutor.conversationStates.set(F,b);try{b.updatedAt=Date.now(),await i(G,b)}catch(a){z.error(`Failed to save state before debug tool pause for conv ${F}:`,a)}S();break}{z.info(`[flujo=true, requireApproval=false] Processing ${a.tool_calls.length} tools internally for conv ${F}`);let c=await n.s.processToolCalls({toolCalls:a.tool_calls,toolNameMap:b.toolNameMap,emit:M,conversationId:b.ephemeral?void 0:b.conversationId,node:b.currentNodeId?{nodeId:b.currentNodeId}:void 0,shouldAbort:Q});if(!c.success){z.error(`Internal tool processing failed for conv ${F}`,{error:c.error}),b.lastResponse={success:!1,error:"Tool processing failed",errorDetails:c.error},d=m.O;break}z.info(`Adding ${c.value.toolCallMessages.length} tool result messages for conv ${F}`);let f=c.value.toolCallMessages.map(a=>({...a,id:crypto.randomUUID(),timestamp:Date.now(),processNodeId:b.currentNodeId}));b.messages.push(...f),e.FlowExecutor.conversationStates.set(F,b),P(),z.info(`Continuing loop for conv ${F} after internal tool processing (no approval needed).`);continue}}else{z.info(`[flujo=false] Tool call action received for conv ${F}. Checking tool types.`);let c=a.tool_calls||[],f=[],g=[];if(c.forEach(a=>{"function"===a.type&&(0,o.$9)(a.function.name,b.toolNameMap)?(z.verbose("tool is internal:",a.function.name),f.push(a)):(z.verbose("tool is external:",a.function.name),g.push(a))}),f.length>0){z.info(`[flujo=false] Processing ${f.length} internal tools for conv ${F}. External tools (${g.length}) will be ignored this step.`);let a=await n.s.processToolCalls({toolCalls:f,toolNameMap:b.toolNameMap,emit:M,conversationId:b.ephemeral?void 0:b.conversationId,node:b.currentNodeId?{nodeId:b.currentNodeId}:void 0,shouldAbort:Q});if(!a.success){z.error(`[flujo=false] Internal tool processing failed for conv ${F}`,{error:a.error}),b.lastResponse={success:!1,error:"Internal tool processing failed",errorDetails:a.error},d=m.O;break}z.info(`Adding ${a.value.toolCallMessages.length} internal tool result messages for conv ${F}`);let c=a.value.toolCallMessages.map(a=>({...a,id:crypto.randomUUID(),timestamp:Date.now(),processNodeId:b.currentNodeId}));b.messages.push(...c),e.FlowExecutor.conversationStates.set(F,b),z.info(`Continuing loop for conv ${F} after internal tool processing (flujo=false).`);continue}if(g.length>0){z.info(`[flujo=false] Found ${g.length} external tools for conv ${F}. Wrapping in XML and returning.`);let a=[];for(let b of g)if("function"===b.type)try{let c=JSON.parse(b.function.arguments||"{}"),d="";for(let a in c){let b=String(c[a]).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;");d+=`
3
+ <${a}>${b}</${a}>`}a.push(`<${b.function.name}>${d}
4
+ </${b.function.name}>`)}catch(c){z.error(`[flujo=false] Failed to parse arguments for external tool ${b.function.name}`,{args:b.function.arguments,error:c,convId:F}),a.push(`<${b.function.name}>
5
+ <error>Failed to parse arguments: ${c instanceof Error?c.message:String(c)}</error>
6
+ </${b.function.name}>`)}b.lastResponse={_flujo_xml_tools:a.join("\n\n")},d=m.g4,z.info(`[flujo=false] Prepared XML for external tools. Exiting loop for conv ${F}.`);break}z.warn(`[flujo=false] TOOL_CALL_ACTION received for conv ${F} but no tools found after classification. Treating as final.`),d=m.g4;break}z.warn(`TOOL_CALL_ACTION received for conv ${F} but no tool_calls found in last message. Treating as final.`),d=m.g4;break}let c=await e.FlowExecutor.resolveHandoff(b,d);if(c.isSuccessorEdge){z.info(`[Action Handling] Step ${L}: Handling Handoff Action (Edge ID) for conv ${F}`),z.info(`Handoff action received for conv ${F}. Edge: ${d}`);let a=c.targetNodeId;if("string"==typeof a&&a.length>0){let c=b.messages.length>0?b.messages[b.messages.length-1]:null;if(c?.role==="assistant"&&c.tool_calls){let e,f,g=c.tool_calls.filter(a=>"function"===a.type&&("handoff"===a.function.name||a.function.name.startsWith("handoff_to_"))),h=a=>b.handoffNameMap?.[a]||a.replace("handoff_to_",""),i=g.filter(b=>"function"===b.type&&h(b.function.name)===a),j=i.length>0?i:g.slice(0,1);0===j.length&&z.warn(`Handoff action received for edge ${d}, but could not find corresponding handoff tool call in last assistant message.`);let k=[],l="";for(let c of(j.forEach((c,g)=>{if("function"===c.type)try{let a=JSON.parse(c.function.arguments||"{}"),b="string"==typeof a?.task?a.task.trim():"",d="string"==typeof a?.prompt?a.prompt.trim():"",g=b||(j.length>1?d:"");if(g&&k.push(g),!l&&d&&(l=d),!e&&Array.isArray(a?.parallelFlows)){let b=a.parallelFlows.filter(a=>"string"==typeof a&&""!==a.trim());b.length>0&&(e=b)}let h=a?.concurrencyLimit;void 0===f&&"number"==typeof h&&h>=1&&(f=Math.floor(h))}catch(a){z.warn(`Could not parse handoff tool-call arguments for edge ${d}; ignoring caller input for this call`,{parseError:a})}b.messages.push({id:crypto.randomUUID(),role:"tool",tool_call_id:c.id,content:JSON.stringify({status:"Handoff processed",targetNodeId:a,...j.length>1?{lane:g+1,laneCount:j.length}:{}}),timestamp:Date.now(),processNodeId:b.currentNodeId})}),g))j.includes(c)||(b.messages.push({id:crypto.randomUUID(),role:"tool",tool_call_id:c.id,content:JSON.stringify({status:"Not executed",reason:"A different handoff was chosen this turn."}),timestamp:Date.now(),processNodeId:b.currentNodeId}),z.warn(`Handoff call ${"function"===c.type?c.function.name:c.id} targeted a different node than the chosen route; answered as not executed.`));if(l||1!==k.length||(l=k[0]),l||k.length>0||e&&e.length>0)b.handoffInput={targetNodeId:a,prompt:l,...k.length>0?{tasks:k}:{},...e&&e.length>0?{parallelFlows:e}:{},...void 0!==f?{concurrencyLimit:f}:{}},z.info(`Captured caller handoff input for node ${a}`,{promptChars:l.length,spawnBriefs:k.length,fanoutCount:e?.length??0});else try{let c=await p.flowService.getFlow(b.flowId),d=c?.nodes?.find(b=>b.id===a),e=d?.data?.properties;d?.type!=="subflow"||e?.inputMode!=="isolated"||e?.allowCallerPrompt!==!0||e?.allowCallerFanout===!0||e?.promptTemplate?.trim()||z.warn(`Handoff to isolated subflow node ${a} has neither a caller-supplied prompt nor an authored promptTemplate; the subflow will start with an empty prompt and may stall. The routing model should have supplied the required "prompt" argument (issue #169).`,{targetNodeId:a})}catch(a){z.debug("Issue #169 empty-prompt handoff guard check failed (non-fatal)",{guardErr:a})}}else z.warn(`Handoff action received for edge ${d}, but the last message was not an assistant message with tool calls.`);P();let f=b.currentNodeId;if(b.currentNodeId=a,b.handoffRequested=void 0,M({type:"handoff",from:f?{nodeId:f}:void 0,toNodeId:a,edgeId:d}),z.info(`Transitioning conv ${F} to node ${b.currentNodeId}`),e.FlowExecutor.conversationStates.set(F,b),R){z.info(`[Debug Step] Paused after handoff to node ${b.currentNodeId} for conv ${F}.`),S();break}z.info(`Continuing loop for conv ${F} after handoff.`);continue}z.error(`Handoff failed for conv ${F}: Successor node for edge ${d} has invalid ID.`),b.lastResponse={success:!1,error:`Handoff failed: Target node for edge ${d} has invalid ID.`},d=m.O;break}if(d===m.E5){z.info(`[Action Handling] Step ${L}: Handling STAY_ON_NODE_ACTION for conv ${F}`),z.info(`Stay on node action received for conv ${F} at step ${L}`);break}z.warn(`Unrecognized action '${d}' received at step ${L} for conv ${F}. Treating as final response.`),d=m.g4;break}}catch(a){if(z.error(`Unhandled error during execution loop for conv ${F}`,{loopError:a}),d!==m.O&&Q()&&(b.status="error",b.lastResponse={success:!1,error:"Execution cancelled by user."},d=m.O),d!==m.O){let c=a?.details;b.lastResponse={success:!1,error:a instanceof Error?a.message:String(a),errorDetails:a instanceof Error?{name:a.name,message:a.message,stack:a.stack,...c&&"object"==typeof c?c:{}}:void 0},d=m.O}}d!==m.O&&Q()&&(z.info(`Cancellation flag set at run end for conv ${F}; reporting cancelled instead of '${b.status}'.`),b.status="error",b.lastResponse={success:!1,error:"Execution cancelled by user."},d=m.O),d===m.O&&"error"!==b.status&&(b.status="error");let T=Date.now()-h,U=b.status||(d===m.g4?"completed":d===m.O?"error":"running");if(z.info(`Execution finished for conv ${F}. Final Action: ${d}, Final Status: ${U}`,{duration:`${T}ms`}),P(),("completed"===U||"error"===U)&&(M({type:"run:done",status:U}),"schedule"!==b.source&&(b.runDepth??0)===0)){let a=b.messages[b.messages.length-1],c=a&&"assistant"===a.role&&"string"==typeof a.content?a.content:void 0;B(b,U,c)}try{if(b.updatedAt=Date.now(),"New Conversation"===b.title&&b.messages.length>0){let a=b.messages.find(a=>"user"===a.role);a&&"string"==typeof a.content&&(b.title=(0,y.oO)(a.content),z.verbose(`Updated conversation title for ${F} before final return to: ${b.title}`))}await i(G,b),z.debug(`Saved final state for conversation ${F} before returning.`)}catch(a){z.error(`Failed to save final state for conversation ${F}:`,a)}(0,g.isConversationDeleted)(F)?e.FlowExecutor.conversationStates.delete(F):e.FlowExecutor.conversationStates.set(F,b);let V=()=>{C&&("completed"===b.status||"error"===b.status)&&e.FlowExecutor.conversationStates.delete(F)},W={conversationId:b.conversationId||F,messages:b.messages,usage:b.usage,finalAction:d,sharedState:b};if("paused_debug"===b.status)return z.info(`Returning paused debug state for conv ${F}`),{...W,status:"paused_debug",outputText:"",pendingToolCalls:b.pendingToolCalls};if("error"===b.status||d===m.O){let a,c="Unknown error during execution",d=500;if("object"==typeof b.lastResponse&&null!==b.lastResponse)if("success"in b.lastResponse&&!1===b.lastResponse.success&&"error"in b.lastResponse&&"string"==typeof b.lastResponse.error){if(c=b.lastResponse.error,"errorDetails"in b.lastResponse&&"object"==typeof b.lastResponse.errorDetails&&null!==b.lastResponse.errorDetails){let e=b.lastResponse.errorDetails;(a={message:"string"==typeof e.message?e.message:c,type:"string"==typeof e.type?e.type:void 0,code:"string"==typeof e.code?e.code:void 0,param:"string"==typeof e.param?e.param:void 0,status:"number"==typeof e.status?e.status:void 0,stack:"string"==typeof e.stack?e.stack:void 0,name:"string"==typeof e.name?e.name:void 0}).status&&(d=a.status)}}else try{c=`Unexpected error state object: ${JSON.stringify(b.lastResponse)}`}catch{c="Unexpected error state object (unserializable)"}else"string"==typeof b.lastResponse&&(c=b.lastResponse);return a?a.message=a.message||c:a={message:c},z.error(`Returning error result for conv ${F}`,{errorMessage:c,errorDetails:a,statusCode:d}),"error"!==b.status&&(b.status="error"),V(),{...W,status:"error",outputText:"",error:{message:c,details:a,statusCode:d}}}let X=b.messages.length>0?b.messages[b.messages.length-1]:null,Y="",Z="";"object"==typeof b.lastResponse&&null!==b.lastResponse&&"_flujo_xml_tools"in b.lastResponse?(Z=b.lastResponse._flujo_xml_tools,Y=X?.role==="assistant"&&"string"==typeof X.content?X.content:"",Y+=(Y?"\n\n":"")+Z,b.lastResponse=Y):Y="string"==typeof b.lastResponse?b.lastResponse:X?.role==="assistant"&&"string"==typeof X.content?X.content:d!==m.Jp||l?"Processing complete.":"";let $=Z?void 0:X?.role==="assistant"?X.tool_calls:void 0;return z.info(`Returning success result for conv ${F}`,{action:d,status:b.status,flujo:l,requireApproval:r,flujodebug:s}),V(),{...W,status:b.status||(d===m.g4?"completed":"running"),outputText:Y,toolCalls:$,pendingToolCalls:b.pendingToolCalls}}}};
@@ -5,6 +5,6 @@ ${b.condition}
5
5
  Tool result (untrusted data):
6
6
  \`\`\`json
7
7
  ${m}
8
- \`\`\``;try{let c="llm-gate"===b.mode?await j(b.modelId,n):await k(b.flowId,n),g=function(a){let b=a.match(/\{[\s\S]*\}/);if(!b)return null;try{let a=JSON.parse(b[0]);if("boolean"!=typeof a?.fire)return null;return{fire:a.fire,reason:"string"==typeof a.reason?a.reason:""}}catch{return null}}(c);if(!g)return f.warn(`Gate returned unparseable output: ${c.slice(0,200)}`),{fire:!1,newState:{lastHash:d,...l},error:"The AI check returned an unreadable answer — did not run the flow"};if(!g.fire)return{fire:!1,newState:{lastHash:d,...l}};return{fire:!0,summary:"flow-gate"===b.mode?"Flow condition met":"AI condition met",context:{result:(0,e.Je)(a),aiReason:g.reason},newState:{lastHash:d,...l}}}catch(b){let a=b instanceof Error?b.message:String(b);return f.warn(`Gate check failed: ${a}`),{fire:!1,newState:a.startsWith("config:")?{lastHash:d}:l,error:a.replace(/^config:\s*/,"")}}}async function j(a,b){let{modelService:d}=await Promise.all([c.e(6996),c.e(1223),c.e(5734),c.e(264)]).then(c.bind(c,20433)),{getCompletionAdapter:e}=await Promise.all([c.e(6996),c.e(1223),c.e(5734),c.e(264)]).then(c.bind(c,24423)),f=await d.getModel(a);if(!f)throw Error(`config: The AI-check model no longer exists (${a})`);let g=await d.resolveAndDecryptApiKey(f.ApiKey);if(!g)throw Error("config: Could not resolve the AI-check model API key");let i=e(f),{completion:j}=await i.createCompletion({model:f,apiKey:g,temperature:0,messages:[{role:"system",content:h},{role:"user",content:b}]}),k=j.choices?.[0]?.message?.content;return"string"==typeof k?k:""}async function k(a,b){let{runFlow:d}=await Promise.all([c.e(6996),c.e(1223),c.e(5734),c.e(1373),c.e(264),c.e(7821),c.e(724),c.e(3823),c.e(4671),c.e(7769)]).then(c.bind(c,47769)),e=await d({flowId:a,prompt:`${b}
8
+ \`\`\``;try{let c="llm-gate"===b.mode?await j(b.modelId,n):await k(b.flowId,n),g=function(a){let b=a.match(/\{[\s\S]*\}/);if(!b)return null;try{let a=JSON.parse(b[0]);if("boolean"!=typeof a?.fire)return null;return{fire:a.fire,reason:"string"==typeof a.reason?a.reason:""}}catch{return null}}(c);if(!g)return f.warn(`Gate returned unparseable output: ${c.slice(0,200)}`),{fire:!1,newState:{lastHash:d,...l},error:"The AI check returned an unreadable answer — did not run the flow"};if(!g.fire)return{fire:!1,newState:{lastHash:d,...l}};return{fire:!0,summary:"flow-gate"===b.mode?"Flow condition met":"AI condition met",context:{result:(0,e.Je)(a),aiReason:g.reason},newState:{lastHash:d,...l}}}catch(b){let a=b instanceof Error?b.message:String(b);return f.warn(`Gate check failed: ${a}`),{fire:!1,newState:a.startsWith("config:")?{lastHash:d}:l,error:a.replace(/^config:\s*/,"")}}}async function j(a,b){let{modelService:d}=await Promise.all([c.e(6996),c.e(1223),c.e(5734),c.e(4545)]).then(c.bind(c,20433)),{getCompletionAdapter:e}=await Promise.all([c.e(6996),c.e(1223),c.e(5734),c.e(4545)]).then(c.bind(c,87182)),f=await d.getModel(a);if(!f)throw Error(`config: The AI-check model no longer exists (${a})`);let g=await d.resolveAndDecryptApiKey(f.ApiKey);if(!g)throw Error("config: Could not resolve the AI-check model API key");let i=e(f),{completion:j}=await i.createCompletion({model:f,apiKey:g,temperature:0,messages:[{role:"system",content:h},{role:"user",content:b}]}),k=j.choices?.[0]?.message?.content;return"string"==typeof k?k:""}async function k(a,b){let{runFlow:d}=await Promise.all([c.e(6996),c.e(1223),c.e(5734),c.e(1373),c.e(4545),c.e(7821),c.e(724),c.e(3823),c.e(4671),c.e(7214)]).then(c.bind(c,57214)),e=await d({flowId:a,prompt:`${b}
9
9
 
10
10
  ${g}`,mode:"ephemeral",requireApproval:!1,debug:!1,userTurn:!0});if("completed"!==e.status)throw Error(e.error?.message??`The checker flow ended with status "${e.status}"`);return e.outputText??""}}};
@@ -0,0 +1,82 @@
1
+ "use strict";exports.id=7579,exports.ids=[7579],exports.modules={17579:(a,b,c)=>{let d;c.d(b,{internalCallTool:()=>bj,internalToolDefinitions:()=>aQ});var e=c(33873),f=c.n(e),g=c(29021),h=c(18230),i=c(11659),j=c(12763),k=c(50010),l=c(35432),m=c(67463),n=c(89850),o=c(8336),p=c(78606);function q(a,b,c,d){return"number"!=typeof a||Number.isNaN(a)?d:Math.max(b,Math.min(c,Math.floor(a)))}let r={type:"arrowclosed",width:20,height:20,color:"#1976d2"},s={stroke:"#1976d2",strokeWidth:2},t={type:"arrowclosed",width:20,height:20,color:"#009688"},u={stroke:"#009688",strokeWidth:2},v=new Set(["full-history","latest-message","isolated"]),w=new Set(["steps","final-only"]),x=new Set(["full-conversation","latest-message"]);function y(a){let b=(0,o.A$)(a);if(0===b.length)return{text:a,stripped:!1};let c="",d=0;for(let e of b)c+=a.slice(d,e.index)+e.name,d=e.index+e.fullMatch.length;return{text:c+=a.slice(d),stripped:!0}}function z(a,b){if(b.some(b=>b.id===a))return a;let c=a.toLowerCase(),d=b.find(a=>a.name.toLowerCase()===c);return d?d.id:null}var A=c(54898),B=c(82464);let C=(0,h.h)("backend/services/flow/generationContext");function D(a,b){let c=String(a).replace(/\s+/g," ").trim();return c.length<=b?c:`${c.slice(0,b).trimEnd()}…`}async function E(){let a=await j.modelService.loadModels(),b=a.map(a=>({id:a.id,name:a.name,...a.displayName?{displayName:a.displayName}:{},...a.description?{description:D(a.description,100)}:{}})),c=[],d={};try{let a=await B.mcpService.loadServerConfigs();if(Array.isArray(a))for(let b of a){if(b.disabled)continue;let a=!1;try{let c=await B.mcpService.getServerStatus(b.name);a=c?.status==="connected"}catch(a){C.debug(`getServerStatus failed for ${b.name}; listing name only`,a)}if(!a){c.push({name:b.name,connected:!1});continue}let{tools:e}=await B.mcpService.listServerTools(b.name),f=(e??[]).filter(a=>a.name).map(a=>({name:a.name,...a.description?{description:D(a.description,100)}:{}}));d[b.name]=f.map(a=>a.name),c.push({name:b.name,connected:!0,tools:f})}}catch(a){C.warn("Could not load MCP servers for the authoring context",a)}let e=[];try{e=await i.flowService.loadFlows()}catch(a){C.warn("Could not load flows for the authoring context",a)}let f={models:b,servers:c,flows:e.map(a=>({id:a.id,name:a.name,...a.description?{description:D(a.description,300)}:{},nodeCount:a.nodes?.length??0}))};return{blocks:f,compile:{models:a.map(a=>({id:a.id,name:a.name,displayName:a.displayName})),servers:c.map(a=>({name:a.name})),serverTools:d,flows:e.map(a=>({id:a.id,name:a.name}))},catalog:function(a){let b=[];for(let c of(b.push("AVAILABLE MODELS (reference by id or name):"),0===a.models.length&&b.push(" (none configured)"),a.models)){let a=c.displayName&&c.displayName!==c.name?`"${c.displayName}" (${c.name})`:c.name,d=c.description?` — ${c.description}`:"";b.push(` - id: ${c.id} — ${a}${d}`)}for(let c of(b.push("",'AVAILABLE MCP SERVERS (attach to process nodes via "servers"):'),0===a.servers.length&&b.push(" (none configured)"),a.servers)){if(!c.connected){b.push(` - ${c.name} (offline — tools unknown; may still be used)`);continue}b.push(` - ${c.name}:`);let a=(c.tools??[]).slice(0,20);for(let c of a){let a=c.description?` — ${c.description}`:"";b.push(` - ${c.name}${a}`)}let d=(c.tools?.length??0)-a.length;d>0&&b.push(` - …and ${d} more`)}for(let c of(b.push("",'EXISTING FLOWS (usable as subflow targets via "flow"):'),0===a.flows.length&&b.push(" (none)"),a.flows.slice(0,15))){let a=c.description?` — ${c.description}`:` — ${c.nodeCount} nodes`;b.push(` - "${c.name}"${a}`)}return a.flows.length>15&&b.push(` - …and ${a.flows.length-15} more`),b.join("\n")}(f),validatorServers:c.map(a=>({name:a.name,status:a.connected?"connected":"disconnected"}))}}let F=(0,h.h)("backend/services/flow/compileFlow");async function G(a,b={}){if(!a||"object"!=typeof a||Array.isArray(a))return{success:!1,error:"The spec must be a JSON object (a FlowSpec)",statusCode:400};let c=await E(),d=c.compile;if(b.updateFlowId){let a=d.flows??[];if(!a.some(a=>a.id===b.updateFlowId))return{success:!1,error:`No flow with id "${b.updateFlowId}" to update`,statusCode:404};d={...d,flows:a.filter(a=>a.id!==b.updateFlowId)}}let e=function(a,b={},c={}){let d=[],e=(a,b,c)=>d.push({severity:"error",code:a,message:b,nodeKey:c}),f=(a,b,c)=>d.push({severity:"warning",code:a,message:b,nodeKey:c}),g=b.models??[],h=new Set((b.servers??[]).map(a=>a.name)),i=b.serverTools??{},j=q(c.maxDepth,0,3,3),k=q(c.maxFlows,1,8,8),l=[],m=[...(b.flows??[]).map(a=>a.name)],o=[],A=0;var B=function a(d,B,C){let D=Array.isArray(d?.nodes)?d.nodes:[],E=Array.isArray(d?.edges)?d.edges:[],G=function(a,b){let c=(a??"").trim().replace(/[^\w-]+/g,"_").replace(/^_+|_+$/g,"");c||(c="generated_flow");let d=new Set(b.map(a=>a.toLowerCase()));if(!d.has(c.toLowerCase()))return c;for(let a=2;;a++){let b=`${c}_${a}`;if(!d.has(b.toLowerCase()))return b}}(d?.name,m);m.push(G),A++;let H=(0,n.A)(),I=[...C,G],J=new Map,K=[],L=[];for(let c of D){let d=c?.key;if(!d||"string"!=typeof d){e("node-missing-key",'A node is missing its "key" — every node needs a unique key.');continue}if(J.has(d)){e("node-duplicate-key",`Duplicate node key "${d}" — keys must be unique; the later node was dropped.`,d);continue}let l=c.type;if("mcp"===l){e("mcp-node-not-allowed",`Node "${d}": do not emit "mcp" nodes — attach servers to a process node via its "servers" list instead.`,d);continue}if("start"!==l&&"process"!==l&&"finish"!==l&&"subflow"!==l&&"resource"!==l&&"signal"!==l){e("unknown-node-type",`Node "${d}" has unknown type "${String(l)}".`,d);continue}let m={},p="string"==typeof c.prompt?c.prompt:void 0;if("start"===l){let{text:a,stripped:b}=y(p??"");b&&f("pill-stripped",`Node "${d}": binding pills are not supported in generated prompts and were replaced with plain names.`,d),m.promptTemplate=a}else if("process"===l){let{text:a,stripped:b}=y(p??"");if(b&&f("pill-stripped",`Node "${d}": binding pills are not supported in generated prompts and were replaced with plain names.`,d),m.promptTemplate=a,c.model){let a=function(a,b){if(b.some(b=>b.id===a))return a;let c=a.toLowerCase(),d=b.find(a=>a.displayName?.toLowerCase()===c);if(d)return d.id;let e=b.find(a=>a.name?.toLowerCase()===c);return e?e.id:null}(c.model,g);a?m.boundModel=a:(m.boundModel=c.model,f("model-unresolved",`Node "${d}": model "${c.model}" does not match any configured model (by id, display name, or name).`,d))}void 0!==c.inputMode&&(v.has(c.inputMode)?(m.inputMode=c.inputMode,"isolated"===c.inputMode&&"string"==typeof c.isolatedPrompt&&(m.isolatedPrompt=c.isolatedPrompt)):f("invalid-input-mode",`Node "${d}": inputMode "${String(c.inputMode)}" is not valid (full-history | latest-message | isolated); omitted.`,d)),void 0!==c.outputMode&&(x.has(c.outputMode)?m.outputMode=c.outputMode:f("invalid-output-mode",`Node "${d}": outputMode "${String(c.outputMode)}" is not valid on a process node (full-conversation | latest-message); omitted.`,d)),void 0!==c.maxTurns&&("number"!=typeof c.maxTurns||Number.isNaN(c.maxTurns)?f("invalid-max-turns",`Node "${d}": maxTurns "${String(c.maxTurns)}" is not a number; omitted.`,d):m.maxTurns=q(c.maxTurns,1,1e3,1)),"boolean"==typeof c.excludeModelPrompt&&(m.excludeModelPrompt=c.excludeModelPrompt),"boolean"==typeof c.excludeStartNodePrompt&&(m.excludeStartNodePrompt=c.excludeStartNodePrompt),"boolean"==typeof c.excludeSystemPrompt&&(m.excludeSystemPrompt=c.excludeSystemPrompt),Array.isArray(c.allowedTools)&&(m.allowedTools=c.allowedTools.filter(a=>"string"==typeof a&&a)),"string"==typeof c.captureVariable&&c.captureVariable.trim()&&(m.captureVariable=c.captureVariable.trim()),"string"==typeof c.captureResource&&c.captureResource.trim()&&(m.captureResource=c.captureResource.trim()),"string"==typeof c.captureKv&&c.captureKv.trim()&&(m.captureKv=c.captureKv.trim())}else if("subflow"===l){if(function(c,d,g,h,i){let l=Array.isArray(c.parallelFlows)&&c.parallelFlows.length>0,m=Array.isArray(c.parallelSubflowSpecs)&&c.parallelSubflowSpecs.length>0,n="string"==typeof c.parallelFlowsVariable?c.parallelFlowsVariable.trim():"";if([void 0!==c.flow&&null!==c.flow?"flow":null,void 0!==c.subflowSpec&&null!==c.subflowSpec?"subflowSpec":null,l?"parallelFlows":null,m?"parallelSubflowSpecs":null,void 0!==c.generateSubflow&&null!==c.generateSubflow?"generateSubflow":null].filter(Boolean).length>1&&f("subflow-multiple-sources",`Node "${d}": a subflow node should have only one target source ("flow", "subflowSpec", "parallelFlows", "parallelSubflowSpecs", or "generateSubflow"); applying precedence flow > subflowSpec > parallelFlows > parallelSubflowSpecs > generateSubflow.`,d),!0===c.mapOverList){let a=void 0!==c.flow&&null!==c.flow||void 0!==c.subflowSpec&&null!==c.subflowSpec;(l||m)&&e("subflow-map-and-parallel",`Node "${d}": "mapOverList" runs a SINGLE child once per item and cannot be combined with "parallelFlows"/"parallelSubflowSpecs".`,d),a?(i.mapOverList=!0,void 0!==c.itemSplit&&("json-array"===c.itemSplit||"lines"===c.itemSplit?i.itemSplit=c.itemSplit:f("invalid-item-split",`Node "${d}": itemSplit "${String(c.itemSplit)}" is not valid (json-array | lines); using json-array.`,d)),!0===c.sequential&&(i.sequential=!0),F(c,i)):e("subflow-map-no-child",`Node "${d}": "mapOverList" needs a single child ("flow" or "subflowSpec") to run once per item.`,d)}let p=Array.isArray(c.spawnBriefs)?c.spawnBriefs.filter(a=>"string"==typeof a&&""!==a.trim()):[];if(p.length>0){let a=void 0!==c.flow&&null!==c.flow||void 0!==c.subflowSpec&&null!==c.subflowSpec;l||m?e("subflow-spawn-and-parallel",`Node "${d}": "spawnBriefs" runs a SINGLE child once per brief and cannot be combined with "parallelFlows"/"parallelSubflowSpecs".`,d):!0===c.mapOverList?e("subflow-spawn-and-map",`Node "${d}": "spawnBriefs" cannot be combined with "mapOverList"; use one lane source or the other.`,d):a?(i.spawnBriefs=p,F(c,i)):e("subflow-spawn-no-child",`Node "${d}": "spawnBriefs" needs a single child ("flow" or "subflowSpec") to spawn once per brief.`,d)}if(n&&(!0===c.mapOverList?e("subflow-map-and-parallel-var",`Node "${d}": "parallelFlowsVariable" (dynamic fan-out) cannot be combined with "mapOverList".`,d):i.parallelSubflowIdsVar=n),c.flow){if(h.some(a=>a.toLowerCase()===c.flow.toLowerCase()))return e("subflow-cycle",`Node "${d}": flow "${c.flow}" refers to an ancestor flow, which would create a cycle.`,d);let a=z(c.flow,[...b.flows??[],...o]);return a?i.subflowId=a:e("subflow-unresolved",`Node "${d}": flow "${c.flow}" does not match any existing flow (by id or name).`,d)}if(c.subflowSpec){if(g+1>j)return e("subflow-too-deep",`Node "${d}": nested subflows may not go deeper than ${j} level(s); this inline subflow was not compiled.`,d);if(A>=k)return e("subflow-too-many",`Node "${d}": compiling this inline subflow would exceed the maximum of ${k} flows in one bundle; it was not compiled.`,d);let b=a(c.subflowSpec,g+1,h);return b?i.subflowId=b.id:e("subflow-child-empty",`Node "${d}": the inline "subflowSpec" produced no usable flow.`,d)}if(l){let a=[];for(let f of c.parallelFlows){if("string"!=typeof f||!f){e("parallel-flow-invalid",`Node "${d}": a "parallelFlows" entry is missing or not a string.`,d);continue}if(h.some(a=>a.toLowerCase()===f.toLowerCase())){e("subflow-cycle",`Node "${d}": parallel flow "${f}" refers to an ancestor flow, which would create a cycle.`,d);continue}let c=z(f,[...b.flows??[],...o]);c?a.includes(c)||a.push(c):e("parallel-flow-unresolved",`Node "${d}": parallel flow "${f}" does not match any existing flow (by id or name).`,d)}a.length>0?(i.parallelSubflowIds=a,F(c,i)):e("parallel-empty",`Node "${d}": "parallelFlows" resolved to no runnable lanes.`,d);return}if(m){let b=[];for(let f of c.parallelSubflowSpecs){if(!f||"object"!=typeof f){e("parallel-spec-invalid",`Node "${d}": a "parallelSubflowSpecs" entry is not a FlowSpec object.`,d);continue}if(g+1>j){e("subflow-too-deep",`Node "${d}": nested subflows may not go deeper than ${j} level(s); a parallel inline subflow was not compiled.`,d);continue}if(A>=k){e("subflow-too-many",`Node "${d}": compiling a parallel inline subflow would exceed the maximum of ${k} flows in one bundle; it was not compiled.`,d);continue}let c=a(f,g+1,h);c?b.push(c.id):e("subflow-child-empty",`Node "${d}": a "parallelSubflowSpecs" entry produced no usable flow.`,d)}b.length>0?(i.parallelSubflowIds=b,F(c,i)):e("parallel-empty",`Node "${d}": "parallelSubflowSpecs" produced no runnable lanes.`,d);return}n&&i.parallelSubflowIdsVar?F(c,i):void 0!==c.generateSubflow&&null!==c.generateSubflow?e("subflow-generate-unsupported",`Node "${d}": "generateSubflow" is only available through the AI flow generator. Use "subflowSpec" for deterministic nested authoring, or "flow" to reference an existing flow.`,d):e("subflow-missing-flow",`Node "${d}": subflow nodes need a "flow" (existing flow), a "subflowSpec" (inline child), "parallelFlows"/"parallelSubflowSpecs" (concurrent children), or "generateSubflow".`,d)}(c,d,B,I,m),void 0!==c.inputMode&&(v.has(c.inputMode)?m.inputMode=c.inputMode:f("invalid-input-mode",`Node "${d}": inputMode "${String(c.inputMode)}" is not valid (full-history | latest-message | isolated); omitted.`,d)),void 0!==c.outputMode&&(w.has(c.outputMode)?m.outputMode=c.outputMode:f("invalid-output-mode",`Node "${d}": outputMode "${String(c.outputMode)}" is not valid (steps | final-only); omitted.`,d)),void 0!==p){let{text:a,stripped:b}=y(p);b&&f("pill-stripped",`Node "${d}": binding pills are not supported in generated prompts and were replaced with plain names.`,d),m.promptTemplate=a}"boolean"==typeof c.allowCallerPrompt&&(m.allowCallerPrompt=c.allowCallerPrompt),"boolean"==typeof c.allowCallerFanout&&(m.allowCallerFanout=c.allowCallerFanout),"string"==typeof c.captureVariable&&c.captureVariable.trim()&&(m.captureVariable=c.captureVariable.trim()),"string"==typeof c.captureResource&&c.captureResource.trim()&&(m.captureResource=c.captureResource.trim()),"string"==typeof c.captureKv&&c.captureKv.trim()&&(m.captureKv=c.captureKv.trim())}else if("resource"===l){let a="string"==typeof c.runName?c.runName.trim():"",b="string"==typeof c.server?c.server.trim():"",e="string"==typeof c.uri?c.uri.trim():"";a?(m.scope="run",m.runName=a,(b||e)&&f("resource-both-bindings",`Node "${d}": a resource node is EITHER a run artifact ("runName") or a static MCP resource ("server"+"uri"); kept the run artifact.`,d)):(m.scope="mcp",b&&(m.boundServer=b),e&&(m.uri=e),b&&e?h.has(b)||f("server-unknown",`Node "${d}": MCP server "${b}" is not configured in FLUJO.`,d):f("resource-missing-binding",`Node "${d}": a static resource node needs both "server" and "uri" (or a "runName" for a run artifact).`,d))}else if("signal"===l){let a="string"==typeof c.topic?c.topic.trim():"";a?m.topic=a:f("signal-missing-topic",`Node "${d}": a signal node needs a "topic" to emit.`,d),"string"==typeof c.payloadTemplate&&c.payloadTemplate?m.payloadTemplate=c.payloadTemplate:void 0!==p&&(m.payloadTemplate=p)}let r={id:(0,n.A)(),type:l,position:{x:0,y:0},data:{label:c.label||`${l.charAt(0).toUpperCase()}${l.slice(1)} Node`,type:l,...c.description?{description:c.description}:{},properties:m}};if(J.set(d,r),K.push(r),"process"===l&&Array.isArray(c.servers)){let a=new Set;for(let b of c.servers){let c,e=b?.name;if(!e||"string"!=typeof e){f("server-missing-name",`Node "${d}": a server reference is missing its "name"; skipped.`,d);continue}if(a.has(e))continue;a.add(e),h.has(e)||f("server-unknown",`Node "${d}": MCP server "${e}" is not configured in FLUJO.`,d);let g=i[e];if(Array.isArray(b.tools)){if(c=b.tools.filter(a=>"string"==typeof a&&a),g){let a=c.filter(a=>!g.includes(a));a.length>0&&f("tool-unknown",`Node "${d}": server "${e}" does not report tool(s): ${a.join(", ")}.`,d)}}else c=g?[...g]:[];let j={id:(0,n.A)(),type:"mcp",position:{x:0,y:0},data:{label:e,type:"mcp",properties:{boundServer:e,enabledTools:c}}};K.push(j),L.push({processKey:d,mcpNode:j})}}else"process"!==l&&Array.isArray(c.servers)&&c.servers.length>0&&f("servers-on-non-process",`Node "${d}": only process nodes can have "servers"; ignored.`,d)}if(0===J.size)return e("no-usable-nodes","No usable nodes — the spec must contain at least a start node and one step."),null;let M=[],N=new Set;for(let a of E){let b,c=a?.from,d=a?.to,g=c?J.get(c):void 0,h=d?J.get(d):void 0;if(!g||!h){e("edge-unknown-node",`Edge "${String(c)}" -> "${String(d)}" references a node key that does not exist (or was dropped).`);continue}if(g===h){e("edge-self-loop",`Edge "${c}" -> "${d}": a node cannot connect to itself.`);continue}if("resource"===g.type||"resource"===h.type){if(("resource"!==g.type||"process"!==h.type)&&("process"!==g.type||"resource"!==h.type)){e("resource-edge-invalid",`Edge "${c}" -> "${d}": resource nodes connect only to process nodes.`);continue}a.condition&&f("resource-edge-condition",`Edge "${c}" -> "${d}": conditions do not apply to resource wiring; dropped.`),!0===a.bidirectional&&f("resource-edge-bidirectional",`Edge "${c}" -> "${d}": resource wiring is directional (read vs write); "bidirectional" was ignored — add the opposite edge explicitly if the step both reads and writes.`);let b=`${c}->${d}`;if(N.has(b)){f("edge-duplicate",`Edge "${c}" -> "${d}" appears more than once; kept the first.`);continue}N.add(b),M.push(function(a,b){let c="resource"===a.type?"resource-out":"process-right-resource",d="resource"===b.type?"resource-in":"process-left-resource";return{id:`${a.id}:${c}->${b.id}:${d}`,source:a.id,sourceHandle:c,target:b.id,targetHandle:d,type:"resourceEdge",data:{edgeType:"resource"},animated:!1,markerEnd:{...t},style:{...u}}}(g,h));continue}if("start"===h.type){e("edge-into-start",`Edge "${c}" -> "${d}": nothing may connect INTO a start node.`);continue}if("finish"===g.type){e("edge-out-of-finish",`Edge "${c}" -> "${d}": nothing may connect OUT OF a finish node.`);continue}let i=`${c}->${d}`;if(N.has(i)){f("edge-duplicate",`Edge "${c}" -> "${d}" appears more than once; kept the first.`);continue}N.add(i);let j=!0===a.bidirectional;j&&("start"===g.type||"finish"===h.type)&&(f("bidirectional-illegal",`Edge "${c}" -> "${d}" cannot be bidirectional; downgraded to one-way.`),j=!1);let k=a.condition;k&&"object"==typeof k&&("process"!==g.type?f("edge-condition-non-process",`Edge "${c}" -> "${d}" has a condition but leaves a ${g.type} node; conditions only route from process nodes and were dropped.`):(0,p.C)(k.kind)?"always"===k.kind?b={kind:"always",..."last-message"===k.target?{target:"last-message"}:{},...!0===k.negate?{negate:!0}:{}}:"string"!=typeof k.value||0===k.value.length?f("edge-condition-value",`Edge "${c}" -> "${d}" has a condition with no "value"; the condition was dropped.`):("regex"!==k.kind||(0,p.wM)(k.value)||f("edge-condition-regex",`Edge "${c}" -> "${d}" has a regex condition that does not compile; it is kept but will never match at runtime.`),b={kind:k.kind,value:k.value,..."last-message"===k.target?{target:"last-message"}:{},...!0===k.ignoreCase?{ignoreCase:!0}:{},...!0===k.negate?{negate:!0}:{}}):f("edge-condition-kind",`Edge "${c}" -> "${d}" has an unknown condition kind "${String(k.kind)}"; the condition was dropped.`)),M.push(function(a,b,c,d){let e=`${a.type}-bottom`,f=`${b.type}-top`;return{id:`${a.id}:${e}->${b.id}:${f}`,source:a.id,sourceHandle:e,target:b.id,targetHandle:f,type:"custom",data:{edgeType:"standard",...c?{bidirectional:!0}:{},...d?{condition:d}:{}},animated:!0}}(g,h,j,b))}for(let{processKey:a,mcpNode:b}of L){let c=J.get(a);M.push(function(a,b){let c="process-right-mcp",d="mcp-left";return{id:`${a.id}:${c}->${b.id}:${d}`,source:a.id,sourceHandle:c,target:b.id,targetHandle:d,type:"mcpEdge",data:{edgeType:"mcp"},animated:!1,markerEnd:{...r},markerStart:{...r},style:{...s}}}(c,b))}!function(a,b,c,d,e){let f=new Map;for(let a of c){let b=a.data?.edgeType;"mcp"!==b&&"resource"!==b&&(f.has(a.source)||f.set(a.source,[]),f.get(a.source).push(a.target))}let g=[...b.values()],h=g.filter(a=>"resource"===a.type),i=g.filter(a=>"resource"!==a.type),j=i.filter(a=>"start"===a.type),k=j.length>0?j:i.slice(0,1),l=new Map,m=k.map(a=>({id:a.id,depth:0}));for(let a of m)l.set(a.id,0);for(;m.length;){let{id:a,depth:b}=m.shift();for(let c of f.get(a)??[])l.has(c)||(l.set(c,b+1),m.push({id:c,depth:b+1}))}let n=0;for(let a of l.values())n=Math.max(n,a);for(let a of i)l.has(a.id)||l.set(a.id,n+1);let o=new Map;for(let[a,c]of b)o.set(c.id,a);let p=new Map;for(let a of i){let b=o.get(a.id),c=e&&b?e[b]:void 0;if(c&&"number"==typeof c.x&&"number"==typeof c.y){a.position={x:c.x,y:c.y};continue}let d=l.get(a.id),f=p.get(d)??0;p.set(d,f+1),a.position={x:250+280*f,y:150+170*d}}let q=new Map;for(let{processKey:a,mcpNode:c}of d){let d=b.get(a),e=q.get(a)??0;q.set(a,e+1),c.position={x:d.position.x+320,y:d.position.y+150*e}}let r=new Map(g.map(a=>[a.id,a])),s=new Map,t=0;for(let a of h){let b=o.get(a.id),d=e&&b?e[b]:void 0;if(d&&"number"==typeof d.x&&"number"==typeof d.y){a.position={x:d.x,y:d.y};continue}let f=c.find(b=>b.data?.edgeType==="resource"&&(b.source===a.id||b.target===a.id)),g=f?f.source===a.id?f.target:f.source:void 0,h=g?r.get(g):void 0;if(h){let b=s.get(h.id)??0;s.set(h.id,b+1),a.position={x:h.position.x-320,y:h.position.y+150*b}}else{let b=0;for(let a of i)b=Math.max(b,a.position.y);a.position={x:250+280*t,y:b+170},t++}}}(0,J,M,L,0===B?c.positions:void 0);let O={id:H,name:G,...d?.description?{description:d.description}:{},nodes:K,edges:M};return l.push(O),o.push({id:O.id,name:O.name}),O}(a,0,[]),C=l,D=d;let E=D.filter(a=>"error"===a.severity).length;return{flow:B,flows:C,issues:D,errorCount:E,warningCount:D.length-E};function F(a,b){void 0!==a.concurrencyLimit&&("number"!=typeof a.concurrencyLimit||Number.isNaN(a.concurrencyLimit)?f("invalid-concurrency-limit",`Node "${a.key}": concurrencyLimit "${String(a.concurrencyLimit)}" is not a number; using the runtime default.`,a.key):b.concurrencyLimit=Math.max(1,Math.floor(a.concurrencyLimit))),"string"==typeof a.joinSeparator&&(b.joinSeparator=a.joinSeparator),void 0!==a.errorStrategy&&("fail-fast"===a.errorStrategy||"collect-all"===a.errorStrategy?b.errorStrategy=a.errorStrategy:f("invalid-error-strategy",`Node "${a.key}": errorStrategy "${String(a.errorStrategy)}" is not valid (fail-fast | collect-all); using collect-all.`,a.key))}}(a,d);if(!e.flow)return{success:!1,error:"The spec could not be compiled into a flow",statusCode:422,issues:e.issues.map(a=>({severity:a.severity,code:a.code,message:a.message}))};b.updateFlowId&&(e.flow.id=b.updateFlowId);let f=e.flows.flatMap(a=>(0,A.nC)(a,{models:c.compile.models,servers:c.validatorServers,serverTools:c.compile.serverTools}).issues),g=function(a,b){let c=[...a.map(a=>({severity:a.severity,code:a.code,message:a.message})),...b.issues],d=c.filter(a=>"error"===a.severity).length;return{issues:c,errorCount:d,warningCount:c.length-d,isRunnable:0===d}}(e.issues,{issues:f,errorCount:0,warningCount:0,isRunnable:!0}),h=!1;if(b.save&&0===g.errorCount){for(let a of e.flows)await i.flowService.saveFlow(a);h=!0,F.info(`Compiled and saved ${e.flows.length} flow(s); root "${e.flow.name}" (${e.flow.id})`)}else b.save&&F.info(`Compiled flow "${e.flow.name}" has ${g.errorCount} error(s); NOT saved`);return{success:!0,flow:e.flow,flows:e.flows,validation:g,saved:h}}var H=c(44561),I=c(79111),J=c(34115);let K=(0,h.h)("backend/execution/flow/loadConversationState");async function L(a){try{(0,I.ln)(a)}catch{K.warn("Rejected unsafe conversationId on load",{conversationId:a});return}if(H.FlowExecutor.conversationStates.has(a))return K.debug("Loaded state from memory",{conversationId:a}),H.FlowExecutor.conversationStates.get(a);let b=`conversations/${a}`;try{let c=await (0,I.YM)(b,void 0);if(c)return K.debug("Loaded state from storage",{conversationId:a}),await (0,J.jM)(c),H.FlowExecutor.conversationStates.set(a,c),c}catch(b){K.warn("Error loading conversation state from storage",{conversationId:a,error:b})}}var M=c(96249),N=c(63129),O=c(51172);let P=`A FlowSpec is a JSON object describing a FLUJO flow semantically — node keys and edges, no coordinates, no ids, no layout:
2
+ {
3
+ "name": "short_flow_name", // letters/digits/_/- only
4
+ "description": "what the flow does",
5
+ "nodes": [ ... ],
6
+ "edges": [ ... ]
7
+ }
8
+
9
+ NODE TYPES:
10
+ - { "key": "unique_key", "type": "start", "label": "...", "prompt": "system-level instructions for the whole flow" }
11
+ - { "key": "...", "type": "process", "label": "...", "description": "what this step does",
12
+ "model": "<model id or name from the catalog>",
13
+ "prompt": "instructions for this step",
14
+ "servers": [ { "name": "<server name>", "tools": ["tool_a"] } ], // optional; omit "tools" to enable all
15
+ "inputMode": "full-history" | "latest-message" | "isolated", // optional, default full-history. Reshapes ONLY the wire view the model sees (persisted history stays lossless): full-history = the whole assembled context; latest-message = leading system prompt(s) + everything FROM the most recent user message ONWARD (NOT "last user + last assistant"), INCLUDING this turn's in-flight tool calls/results; isolated = system prompt(s) + isolatedPrompt as a synthetic user message, prior conversation dropped. NOTE: for Claude-subscription models the whole wire history (incl. prior tool calls/results under full-history) is flattened into one text prompt rather than sent as native tool turns
16
+ "isolatedPrompt": "...", // only with inputMode "isolated"
17
+ "outputMode": "full-conversation" | "latest-message", // optional, default full-conversation; latest-message hides this step's tool calls/results from later steps (they see only its final response)
18
+ "maxTurns": 20, // optional; per-step cap on agentic tool-loop turns (retry-until-done in ONE node). Unset = model/system default (50)
19
+ "allowedTools": ["tool_a"], // optional; step-level tool allowlist (independent of servers[].tools)
20
+ "captureVariable": "NAME", // optional; save this step's output into a run variable other steps inject with \${var:NAME}
21
+ "captureResource": "NAME", // optional; ALSO save this step's output as a tracked run resource other steps inject with \${res:NAME} (see rule 9b)
22
+ "captureKv": "NAME", // optional; ALSO save this step's output to a PERSISTENT cross-run key other steps inject with \${kv:NAME} (see rule 9d)
23
+ "excludeModelPrompt": true|false, // optional; drop the model's base prompt
24
+ "excludeStartNodePrompt": true|false, // optional; drop the start node's prompt for this step
25
+ "excludeSystemPrompt": true|false } // optional; drop the workflow/handoff guidance block
26
+ - { "key": "...", "type": "subflow", "label": "...",
27
+ "flow": "<existing flow name or id>", // reference an EXISTING flow, OR:
28
+ "subflowSpec": { ...a nested FlowSpec... }, // define a brand-new child flow INLINE (compiled into its own flow and wired automatically), OR fan out concurrently:
29
+ "parallelFlows": ["flow_a", "flow_b"], // run several EXISTING child flows CONCURRENTLY, same input to each, outputs joined; OR:
30
+ "parallelSubflowSpecs": [ { ...FlowSpec... } ], // run several INLINE child flows concurrently; OR:
31
+ "parallelFlowsVariable": "NAME", // DYNAMIC fan-out (rule 7b): pick the target flows AT RUNTIME from run variable \${var:NAME} (a JSON array of flow ids/names, or newline list); mutually exclusive with mapOverList
32
+ "mapOverList": true | false, // optional; run the SINGLE child ("flow"/"subflowSpec") ONCE PER ITEM parsed from the input; mutually exclusive with parallelFlows/parallelSubflowSpecs
33
+ "itemSplit": "json-array" | "lines", // optional (mapOverList only), how to split the input into items, default json-array
34
+ "sequential": true | false, // optional (mapOverList only), run items one at a time in order instead of concurrently, default false
35
+ "spawnBriefs": ["brief 1", "brief 2"], // optional (rule 7d); run the SINGLE child once PER BRIEF, in parallel — the author-defined spawn set; mutually exclusive with parallelFlows/parallelSubflowSpecs/mapOverList
36
+ "concurrencyLimit": 4, // optional (parallel / mapOverList / spawn), default 4
37
+ "joinSeparator": "\\n\\n---\\n\\n", // optional (parallel / mapOverList / spawn), string between joined lane outputs, default "\\n\\n"
38
+ "errorStrategy": "collect-all" | "fail-fast", // optional (parallel / mapOverList / spawn), default collect-all
39
+ "inputMode": "full-history" | "latest-message" | "isolated", // optional, default full-history. DIFFERS from a process node: history modes ALWAYS sanitize the parent transcript first — system messages, tool-result messages, and ANY assistant turn that made tool calls are dropped (only user + prose-only assistant messages survive). full-history = the full sanitized transcript; latest-message = the sanitized transcript FROM the most recent user message ONWARD (NOT "last user + last assistant"); isolated = ignore the parent conversation and send "prompt" as the child's single user message
40
+ "allowCallerPrompt": true | false, // optional, only with inputMode "isolated"; when true a routing step may pass a "prompt" via its handoff tool that overrides the subflow's "prompt" (default)
41
+ "allowCallerFanout": true | false, // optional (subflow); makes this a SPAWNABLE sub-agent: the routing step may call its handoff tool SEVERAL TIMES in one turn, each call with a "task" brief spawning one parallel instance of the child flow (rule 7c)
42
+ "captureVariable": "NAME", // optional; save the subflow's output into a run variable other steps inject with \${var:NAME}
43
+ "captureResource": "NAME", // optional; ALSO save the subflow's output as a tracked run resource (\${res:NAME}, rule 9b)
44
+ "captureKv": "NAME", // optional; ALSO save the subflow's output to a PERSISTENT cross-run key (\${kv:NAME}, rule 9d)
45
+ "outputMode": "steps" | "final-only" }
46
+ - { "key": "...", "type": "finish", "label": "..." }
47
+ - { "key": "...", "type": "signal", "label": "...", // fire-and-forget event (rule 11): emits {topic, payload} then passes through unchanged
48
+ "topic": "<event topic other flows' triggers listen for>", // REQUIRED — a signal with no topic emits nothing
49
+ "payloadTemplate": "event body, may use \${var:NAME}" } // optional; defaults to the node prompt
50
+ - { "key": "...", "type": "resource", "label": "...", // OPTIONAL/advanced (rule 9c): a data artifact shown in the graph
51
+ "server": "<server name>", "uri": "<resource uri>", // EITHER a static MCP resource…
52
+ "runName": "NAME" } // …OR a run artifact steps produce/consume
53
+
54
+ EDGES: { "from": "<node key>", "to": "<node key>", "bidirectional": true|false,
55
+ "condition": { "kind": "contains"|"regex"|"equals", "value": "...",
56
+ "target": "last-assistant"|"last-message", // optional, default last-assistant
57
+ "ignoreCase": true|false, "negate": true|false } } // condition optional; process-node edges only
58
+
59
+ RULES:
60
+ 1. Exactly ONE start node; at least one finish node reachable from it.
61
+ 2. Every process node MUST reference a configured model (by id, display name, or name).
62
+ 3. A process step uses MCP tools ONLY via its "servers" list — never emit nodes of type "mcp".
63
+ 4. Do not embed \${tool:...} or \${resource:...} references in prompts — tools are wired through "servers".
64
+ 5. Branching: give a process node multiple outgoing edges; its model decides where to hand off at runtime. "bidirectional": true lets the target hand back to the source (agent <-> agent).
65
+ 5b. Deterministic routing: give a process node's outgoing edges a "condition" to route WITHOUT the model — the engine takes the first outgoing edge whose predicate matches the last message (default the step's own last assistant message), and a bare (condition-less) edge is the fallback. Use this for reliable data-driven branches (e.g. output contains "FAIL" -> fix step, else -> publish) instead of relying on a small model to emit a handoff. Only process-node edges may carry a condition. Without any condition on a node, that node keeps model-decided handoff (rule 5). If the model still calls a handoff tool, that wins over the condition.
66
+ 6. A subflow node may have only ONE outgoing edge. Give it EITHER a "flow" (naming an existing flow) OR a "subflowSpec" (an inline nested FlowSpec that becomes its own child flow) — not both. A "subflowSpec" may itself contain subflow nodes with their own "subflowSpec" (bounded nesting), so you can author whole multi-level flows in one object.
67
+ 7. A subflow node may instead fan out to SEVERAL child flows CONCURRENTLY via "parallelFlows" (existing flows) or "parallelSubflowSpecs" (inline). These are STATIC (fixed at author time): the same input is sent to every lane and their outputs are joined. This is about multiple CHILDREN, not successors — the single-outgoing-edge rule (rule 6) still holds. Prefer "parallelFlows" for large fan-outs.
68
+ 7b. For DYNAMIC fan-out — when the set of target flows should be decided AT RUNTIME by an earlier step — use "parallelFlowsVariable": "NAME". An upstream process/subflow node captures a JSON array of flow ids/names (or a newline list) into run variable NAME via "captureVariable": "NAME"; this subflow node then fans out over exactly those flows. Unknown ids and a self-reference are dropped, the count is capped, and a non-empty resolution overrides any static "parallelFlows" (empty falls back to it). Mutually exclusive with "mapOverList". Still one outgoing edge (rule 6).
69
+ 7c. For AGENTIC spawning — when the ROUTING MODEL itself should split the work at the very moment it hands off — set "allowCallerFanout": true on the target subflow node. This makes it a SPAWNABLE sub-agent: its handoff tool gains an optional "task" (string) argument and the routing model may call the tool SEVERAL TIMES IN ONE TURN, each call spawning one parallel instance of the child flow briefed with that call's "task". All instances run concurrently, their outputs are joined in call order, and the flow continues once every instance finishes. A call with no "task" is a plain single handoff. Caller briefs override "spawnBriefs"/"parallelFlows"/"parallelFlowsVariable"; the count is capped. Mutually exclusive with "mapOverList". Still one outgoing edge (rule 6). Use 7c when the deciding (routing) step should choose how to split the work; use 7d's "spawnBriefs" when the AUTHOR fixes the briefs; use 7b when an earlier step computes a set of DIFFERENT flows.
70
+ 7d. For AUTHOR-DEFINED spawning — a fixed set of parallel briefs for ONE sub-agent — give the subflow node "spawnBriefs": ["...", "..."]. Every visit runs the single child once per brief, concurrently (same pool/tuning as parallel). Each brief may inject \${var:NAME}/\${res:NAME}/\${kv:NAME}. With inputMode "isolated" the brief is the lane's whole prompt; with history modes each lane sees the conversation plus its brief as the closing instruction. Mutually exclusive with "parallelFlows"/"parallelSubflowSpecs"/"mapOverList"; needs a single child ("flow"/"subflowSpec").
71
+ 8. A subflow node may instead run its SINGLE child flow ONCE PER ITEM via "mapOverList": true. The input is split into items by "itemSplit" ("json-array" default, or "lines"), each item is sent to its own child run, and the per-item outputs are joined (same pool/tuning as parallel). Use "sequential": true to run items in order. Mutually exclusive with "parallelFlows"/"parallelSubflowSpecs".
72
+ 9. Named variables (scratchpad): a step can save its output with "captureVariable": "NAME" (process or subflow) and any LATER step injects it with \${var:NAME} inside its "prompt" / "isolatedPrompt" / subflow prompt. This survives "latest-message"/"isolated" scoping, unlike conversation history — use it to carry a todo list, a file path, a diff, or a captured result across steps that don't share history. \${var:NAME} is run-scoped and plaintext; it is DISTINCT from \${global:VAR} (configured secrets/config, resolved only for tool args). Capture a subflow's output on the PARENT subflow node — a variable set inside a child flow is not visible to the parent.
73
+ 9b. Run resources (tracked data): "captureResource": "NAME" (process or subflow) ALSO saves the step's output as a run-scoped RESOURCE — an addressable artifact (flujo://run/... URI) with lineage (which step produced it, which steps read it), readable via the built-in "flujo" MCP server. A later step injects it with \${res:NAME} exactly like \${var:NAME}. Prefer "captureVariable" for short strings; use "captureResource" when the output is a large document/report/dataset worth tracking, or when other tools/agents should be able to read it back. Large or binary MCP tool results (screenshots, files) are auto-captured as run resources without any spec field.
74
+ 9c. Resource nodes are OPTIONAL/advanced — most flows should not use them; prefer rule 9b's captureResource/\${res:NAME}. Emit one only when the data artifact itself should be VISIBLE in the graph: an edge resource→process means the step READS the artifact (its contents are injected into the step's context); process→resource means the step's output is SAVED to it (run artifacts only, equivalent to captureResource with the node's runName). Resource edges are data wiring, not flow control — they never carry conditions and don't count as a step's successor.
75
+ 9d. Persistent state (cross-run): "captureKv": "NAME" (process or subflow) saves the step's output to a PERSISTENT key-value store that SURVIVES ACROSS RUNS, injected by any step with \${kv:NAME}. Unlike \${var:} / \${res:} (discarded when the run ends), \${kv:} is what a long-lived SCHEDULED flow uses to carry a loop counter, a pagination cursor, a last-seen id, or a flag to its NEXT run. By default a key lives on the flow's FOLDER board (flows in the same folder share it); prefix the name to change scope: "flow/NAME" (this flow only) or "global/NAME" (whole instance). Plaintext, never secrets (distinct from \${global:VAR}). A model can also read/update a key mid-run via the built-in "flujo" server's kv_get / kv_set tools.
76
+ 10. Keep flows minimal — only the steps the task needs. Write clear, specific prompts and labels; fill "description" on process nodes.
77
+ 11. Signals (fire-and-forget events): a "signal" node is a deterministic pass-through that, when the path reaches it, emits an event {topic, payload} onto the flow-run event bus and then continues to its successor unchanged (it never calls a model or touches the conversation). Use it when the flow should notify or kick off ANOTHER flow mid-run — a flow-event trigger configured elsewhere listens for the same "topic" (e.g. "when the review finds blockers, emit a review-blocked signal"). Always give it a "topic" (a signal with no topic emits nothing); "payloadTemplate" is the optional event body and may inject \${var:NAME}. Make emission conditional by putting a conditioned edge (rule 5b) INTO the signal node.
78
+ 12. Input vs output modes are two DISTINCT axes whose value names differ per node type (issue #152 clarification). inputMode ("full-history" | "latest-message" | "isolated") controls what a step RECEIVES and exists on BOTH process and subflow nodes, but they behave differently: a process node keeps the current turn's tool calls/results, while a subflow node ALWAYS strips system/tool-result/tool-call turns from the parent transcript in every history mode (see the inputMode notes above). "latest-message" means "from the most recent user message onward", NOT "last user + last assistant". outputMode controls what LATER steps see of a step's work and is a SEPARATE enum per node type: a process node uses "full-conversation" | "latest-message" (latest-message hides this step's tool exchange from later steps), a subflow node uses "steps" | "final-only" (live-view folding only). Common word traps: "last-message" = inputMode latest-message; "full-conversation" is a process outputMode value, NOT an input mode. A subflow's final answer is always injected back into the parent transcript regardless of outputMode.`;var Q=c(12700),R=c(79861);let S=(0,h.h)("backend/services/mcp/quality/cache"),T="mcp-quality-cache";class U{constructor(a=Date.now()){this.entries={},this.dirty=!1,this.now=a}async load(){try{let a=await (0,I.YM)(T,{entries:{}});this.entries=a?.entries&&"object"==typeof a.entries?a.entries:{}}catch(a){S.warn("Failed to load quality cache; starting empty",a),this.entries={}}}get(a,b){let c=this.entries[`${a}::${b}`];if(c&&!(this.now-c.at>864e5))return c.signal}set(a,b,c){this.entries[`${a}::${b}`]={at:this.now,signal:c},this.dirty=!0}async flush(){let a=!1;for(let[b,c]of Object.entries(this.entries))this.now-c.at>864e5&&(delete this.entries[b],a=!0);if(this.dirty||a)try{await (0,I.VH)(T,{entries:this.entries})}catch(a){S.warn("Failed to persist quality cache",a)}}}function V(a){return!Number.isFinite(a)||a<0?0:a>1?1:a}function W(a,b){return!Number.isFinite(a)||a<=0?0:!Number.isFinite(b)||b<=1?+(a>0):V(Math.log10(a+1)/Math.log10(b+1))}let X=(0,h.h)("backend/services/mcp/quality/providers/githubStars"),Y="github",Z=new Map;function $(){return d??(process.env.GITHUB_TOKEN||void 0)}function _(a){let b,c=a.server.repository;if(c?.source&&"github"!==c.source.toLowerCase())return null;var d=c?.url;if(!d)return null;try{b=new URL(d.replace(/^git\+/,""))}catch{return null}if(!/(^|\.)github\.com$/i.test(b.hostname))return null;let e=b.pathname.replace(/\.git$/i,"").split("/").filter(Boolean);return e.length<2?null:`${e[0]}/${e[1]}`.toLowerCase()}async function aa(a,b){let c=new AbortController,d=()=>c.abort();b.addEventListener("abort",d,{once:!0});let e=setTimeout(()=>c.abort(),6e3);try{return await fetch(`https://api.github.com${a}`,{headers:function(){let a={Accept:"application/vnd.github+json","User-Agent":"FLUJO-mcp-quality","X-GitHub-Api-Version":"2022-11-28"},b=$();return b&&(a.Authorization=`Bearer ${b}`),a}(),signal:c.signal,cache:"no-store"})}catch(b){return X.warn(`GitHub request failed (${a})`,b instanceof Error?b.message:b),null}finally{clearTimeout(e),b.removeEventListener("abort",d)}}function ab(a){return(403===a.status||429===a.status)&&"0"===a.headers.get("x-ratelimit-remaining")}let ac=(0,h.h)("backend/services/mcp/quality/providers/npmDownloads"),ad="npm-downloads",ae=new Map;function af(a){for(let b of a.server.packages??[])if("npm"===b.registryType&&b.identifier)return b.identifier;return null}function ag(a){return a.startsWith("@")}async function ah(a,b){let c=new AbortController,d=()=>c.abort();b.addEventListener("abort",d,{once:!0});let e=setTimeout(()=>c.abort(),6e3);try{return await fetch(`https://api.npmjs.org${a}`,{signal:c.signal,cache:"no-store"})}catch(b){return ac.warn(`npm request failed (${a})`,b instanceof Error?b.message:b),null}finally{clearTimeout(e),b.removeEventListener("abort",d)}}let ai="registry-status",aj=[{id:Y,label:"GitHub Stars & Activity",defaultWeight:.5,isApplicable:a=>null!==_(a),cacheKey:a=>_(a),async prefetch(a,b,c){let d=`${a??""} mcp`.trim(),e=`/search/repositories?q=${encodeURIComponent(d)}&sort=stars&order=desc&per_page=50`,f=await aa(e,c);if(f&&f.ok)try{for(let a of(await f.json()).items??[])a.full_name&&Z.set(a.full_name.toLowerCase(),{stars:"number"==typeof a.stargazers_count?a.stargazers_count:0,pushedAtMs:a.pushed_at?Date.parse(a.pushed_at):null})}catch(a){X.warn("Failed to parse GitHub search response",a)}else if(f&&ab(f))return void X.warn("GitHub search rate-limited; ranking will degrade to other providers");if(!$())return;let g=3;for(let a of b){if(g<=0)break;let b=_(a);if(!b||Z.has(b))continue;g-=1;let d=await aa(`/repos/${b}`,c);if(d){if(ab(d))break;if(d.ok)try{let a=await d.json();Z.set(b,{stars:"number"==typeof a.stargazers_count?a.stargazers_count:0,pushedAtMs:a.pushed_at?Date.parse(a.pushed_at):null})}catch{}}}},async fetch(a){let b=_(a);if(!b)return null;let c=Z.get(b);if(!c)return null;let d=W(c.stars,5e4),e=function(a,b,c=30,d=730){if(!a||!Number.isFinite(a))return 0;let e=(b-a)/864e5;return e<=c?1:e>=d?0:V(1-(e-c)/(d-c))}(c.pushedAtMs,Date.now());return{providerId:Y,score:V(.7*d+.3*e),evidence:{repo:b,stars:c.stars,...c.pushedAtMs?{pushedAt:new Date(c.pushedAtMs).toISOString()}:{},starsScore:d,recencyScore:e}}}},{id:ad,label:"npm Weekly Downloads",defaultWeight:.35,isApplicable:a=>null!==af(a),cacheKey:a=>af(a),async prefetch(a,b,c){let d=b.map(af).filter(a=>!!a&&!ae.has(a)),e=d.filter(a=>!ag(a)),f=d.filter(ag);for(let a=0;a<e.length;a+=100){let b=e.slice(a,a+100),d=await ah(`/downloads/point/last-week/${b.join(",")}`,c);if(d&&d.ok)try{let a=await d.json();if(1===b.length)"number"==typeof a.downloads&&ae.set(b[0],a.downloads);else for(let c of b){let b=a[c];ae.set(c,b&&"number"==typeof b.downloads?b.downloads:0)}}catch(a){ac.warn("Failed to parse npm bulk downloads response",a)}}for(let a of f){let b=await ah(`/downloads/point/last-week/${a}`,c);if(b&&b.ok)try{let c=await b.json();"number"==typeof c.downloads&&ae.set(a,c.downloads)}catch{}}},async fetch(a){let b=af(a);if(!b)return null;let c=ae.get(b);return void 0===c?null:{providerId:ad,score:W(c,1e6),evidence:{package:b,weeklyDownloads:c}}}},{id:ai,label:"Registry Status",defaultWeight:.15,isApplicable:a=>!0,cacheKey:()=>null,fetch:async a=>({providerId:ai,score:+("active"===a.verificationStatus),evidence:{status:a.verificationStatus}})}];var ak=c(89392);let al=(0,h.h)("backend/services/mcp/quality/settings");function am(){return{providers:aj.map(a=>({id:a.id,enabled:!0,weight:a.defaultWeight})),minScore:0,worksGate:!0}}async function an(){try{let a=await (0,I.YM)(ak.Z.MCP_QUALITY_SETTINGS,am());return function(a){var b,c;let d=am(),e=a??{},f=new Map;if(Array.isArray(e.providers))for(let a of e.providers)a&&"string"==typeof a.id&&f.set(a.id,a);return{providers:d.providers.map(a=>{let b=f.get(a.id);return{id:a.id,enabled:"boolean"==typeof b?.enabled?b.enabled:a.enabled,weight:"number"==typeof b?.weight&&Number.isFinite(b.weight)&&b.weight>=0?b.weight:a.weight}}),minScore:(b=e.minScore,c=d.minScore,"number"==typeof b&&Number.isFinite(b)?Math.min(1,Math.max(0,b)):c),worksGate:"boolean"==typeof e.worksGate?e.worksGate:d.worksGate,..."string"==typeof e.githubToken&&e.githubToken.length>0?{githubToken:e.githubToken}:{}}}(a)}catch(a){return al.warn("Failed to load mcpQuality settings; using defaults",a),am()}}let ao=(0,h.h)("backend/services/mcp/quality/orchestrator");async function ap(a,b){let c=new AbortController,d=setTimeout(()=>c.abort(),b);try{return await a(c.signal)}finally{clearTimeout(d)}}async function aq(a,b,c={}){let e=c.topN??10;try{var f;let g=c.settings??await an(),h=aj.filter(a=>(function(a,b){let c=a.providers.find(a=>a.id===b);return!!c?.enabled})(g,a.id));if(0===h.length)return b.map(a=>({candidate:a,score:0,signals:[]}));d=(f=g.githubToken)&&f.length>0?f:void 0;let i=b.slice(0,e),j=b.slice(e),k=new U(c.now??Date.now());await k.load();let l=i.map(()=>[]);for(let b of h){let c=i.map((a,b)=>({c:a,i:b})).filter(({c:a})=>b.isApplicable(a)),d=[],e=[];for(let a of c){let c=b.cacheKey(a.c);if(c){let d=k.get(b.id,c);if(d){e.push({i:a.i,signal:d});continue}}d.push(a)}if(b.prefetch&&d.length>0)try{await ap(c=>b.prefetch(a,d.map(a=>a.c),c),12e3)}catch(a){ao.warn(`Provider "${b.id}" prefetch failed; degrading`,a)}for(let{c:a,i:c}of d)try{let d=await ap(c=>b.fetch(a,c),2e3);if(d){l[c].push(d);let e=b.cacheKey(a);e&&k.set(b.id,e,d)}}catch(c){ao.warn(`Provider "${b.id}" fetch failed for "${a.registryName}"`,c)}for(let{i:a,signal:b}of e)l[a].push(b)}await k.flush();let m=i.map((a,b)=>{let c=l[b],d=new Map(c.map(a=>[a.providerId,a])),e=h.filter(b=>b.isApplicable(a)).map(a=>({providerId:a.id,weight:function(a,b){let c=a.providers.find(a=>a.id===b);return c&&c.enabled?c.weight:0}(g,a.id),score:d.get(a.id)?.score??0})),{score:f}=function(a){let b=0,c=0;for(let d of a){let a=Number.isFinite(d.weight)&&d.weight>0?d.weight:0,e=V(d.score);b+=a,c+=a*e}return{score:b>0?c/b:0,breakdown:a}}(e);return{candidate:a,score:f,signals:c}}).map((a,b)=>({s:a,idx:b})).sort((a,b)=>b.s.score-a.s.score||a.idx-b.idx).map(a=>a.s),n=j.map(a=>({candidate:a,score:0,signals:[]}));return[...m,...n]}catch(a){return ao.warn("enrichAndRank failed; returning unranked candidates",a),b.map(a=>({candidate:a,score:0,signals:[]}))}}let ar=(0,h.h)("backend/services/mcp/registryInstall"),as="/v0.1/servers";function at(a){return{registryName:a.server.name,server:a.server,verificationStatus:(0,R.vf)(a)}}async function au(a,b=8){let c=await av(a,b);return(await aq(a,c.map(at))).map(a=>(function(a,b){let c=(0,R.AH)(a),d=c[0];return{name:a.name,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{},installable:c.length>0,requiredEnv:d?(0,R.jg)(d):[],...b?{quality:function(a){let b=b=>a.signals.find(a=>a.providerId===b)?.evidence,c=b(Y),d=b(ad),e=b(ai);return{score:a.score,..."number"==typeof c?.stars?{stars:c.stars}:{},..."number"==typeof d?.weeklyDownloads?{weeklyDownloads:d.weeklyDownloads}:{},..."string"==typeof e?.status?{status:e.status}:{}}}(b)}:{}}})(a.candidate.server,a))}async function av(a,b){let c=new URL(Q.jD+as);c.searchParams.set("version","latest"),c.searchParams.set("limit",String(Math.min(Math.max(b,1),30))),a&&c.searchParams.set("search",a);let d=await (0,Q.Ws)(c,15e3);return Array.isArray(d?.servers)?d.servers:[]}async function aw(a){let b=new URL(Q.jD+as);b.searchParams.set("version","latest"),b.searchParams.set("limit","10"),b.searchParams.set("search",a);let c=await (0,Q.Ws)(b,15e3),d=Array.isArray(c?.servers)?c.servers:[];return d.find(b=>b.server?.name===a)??d[0]??null}async function ax(a,b,c){let d;if(!a||"string"!=typeof a)return{installed:!1,error:"A registry server name is required"};try{d=await aw(a)}catch(a){return{installed:!1,error:`Registry lookup failed: ${a instanceof Error?a.message:String(a)}`}}let e=d?.server??null;if(!e)return{installed:!1,error:`No registry entry found for "${a}"`};let f=(0,R.AH)(e)[0];if(!f)return{installed:!1,error:`"${e.name}" has no install method FLUJO supports (stdio package or HTTP remote)`};let g=(0,R.vf)(d),h=(0,R.O$)(a,e,f,g);if(c?.resolveOnly)return{installed:!1,serverName:h.serverName,plan:h};let i=(0,R.jg)(f,b);if(i.length>0)return{installed:!1,needsEnv:i,plan:h,error:`"${e.name}" requires values for: ${i.join(", ")}`};let j=(0,R.cy)((0,R.Yr)(e,f),b),k=j.name,l=await B.mcpService.loadServerConfigs();if(Array.isArray(l)&&l.some(a=>a.name===k)){ar.info(`installRegistryServer: "${k}" already configured; reusing`);let{tools:a,error:b}=await B.mcpService.listServerTools(k);return{installed:!0,alreadyExisted:!0,serverName:k,plan:h,tools:(a??[]).map(a=>({name:a.name,...a.description?{description:a.description}:{}})),...b?{error:b}:{}}}ar.info(`installRegistryServer: installing "${e.name}" as "${k}" (${f.kind})`);let m=await B.mcpService.updateServerConfig(k,j);if(!Array.isArray(m)&&m&&"success"in m&&!1===m.success)return{installed:!1,error:`Saving the server failed: ${m.error??"unknown error"}`};let{tools:n,error:o}=await B.mcpService.listServerTools(k),p=(n??[]).map(a=>({name:a.name,...a.description?{description:a.description}:{}}));if((c?.worksGate??(await an()).worksGate)&&0===p.length){ar.warn(`installRegistryServer: "${k}" exposed no tools${o?` (${o})`:""}; rolling back (works-gate)`);try{await B.mcpService.deleteServerConfig(k)}catch(a){ar.error(`installRegistryServer: rollback of "${k}" failed`,a)}return{installed:!1,worksGateRejected:!0,serverName:k,plan:h,error:o?`"${e.name}" failed to start: ${o}`:`"${e.name}" connected but exposed no tools — rejected by the works-gate. Try a different server.`}}return{installed:!0,serverName:k,plan:h,tools:p,...o?{error:o}:{}}}async function ay(a,b,c){let d;if(!a||"string"!=typeof a)return{installed:!1,error:"A capability search query is required"};try{d=await av(a,10)}catch(a){return{installed:!1,error:`Registry lookup failed: ${a instanceof Error?a.message:String(a)}`}}let e=await aq(a,d.map(at)),f=await an(),g=c?.minScore??f.minScore,h=c?.maxAttempts??3,i=[],j=0;for(let a of e){let d=a.candidate.registryName;if(a.score<g){i.push({name:d,score:a.score,reason:`below minScore ${g}`});break}if(0===(0,R.AH)(a.candidate.server).length){i.push({name:d,score:a.score,reason:"no supported install method"});continue}if(j>=h)break;j+=1;let e=await ax(d,b,{worksGate:!0});if(c?.onAttempt)try{await c.onAttempt(e.plan,e)}catch(a){ar.error("installBestForCapability: onAttempt hook failed",a)}if(e.installed)return{...e,attempts:i};let f=e.needsEnv?.length?`needs env: ${e.needsEnv.join(", ")}`:e.worksGateRejected?"works-gate rejected (no tools / failed to start)":e.error??"install failed";i.push({name:d,score:a.score,reason:f})}return{installed:!1,attempts:i,error:`No working server found for "${a}" among the top ${j} installable candidate(s).`}}let az={requireConsent:!0,namespaceAllowlist:[],trustBrainStem:!0};function aA(a){let{caller:b,settings:c,registryName:d,allowInstall:e}=a;if("generator"===b)return!0===e?{allowed:!0,reason:"generator-allowinstall",message:"Approved by the per-generation allowInstall opt-in."}:{allowed:!1,reason:"generator-not-allowed",message:"Installing is not allowed in this generation (allowInstall is off)."};if("authoring-tool"===b&&c.trustBrainStem)return{allowed:!0,reason:"brainstem-trusted",message:"Approved: the /mcp-flows authoring tool is trusted (mcpAutoInstall.trustBrainStem)."};if(!c.requireConsent)return{allowed:!0,reason:"consent-disabled",message:"Approved: consent is not required (mcpAutoInstall.requireConsent is off)."};let f=function(a){if("string"!=typeof a)return"";let b=a.indexOf("/");return b>0?a.slice(0,b):""}(d);return""!==f&&c.namespaceAllowlist.includes(f)?{allowed:!0,reason:"namespace-allowlisted",message:`Approved: namespace "${f}" is allowlisted.`}:{allowed:!1,reason:"consent-required",message:"Consent required: review the exact command and arguments, then approve this install (SEP-1024)."}}function aB(a,b,c,d,e){return{at:new Date().toISOString(),caller:b,registryName:a.registryName,resolvedName:a.resolvedName,serverName:a.serverName,transport:a.transport,...a.command?{command:a.command}:{},...a.args?{args:a.args}:{},...a.serverUrl?{serverUrl:a.serverUrl}:{},requiredEnvNames:a.requiredEnvNames,verificationStatus:a.verificationStatus,consent:{allowed:c.allowed,reason:c.reason},installed:d,...e?{error:e}:{}}}let aC=(0,h.h)("backend/services/mcp/autoInstall");async function aD(){try{let a=await (0,I.YM)(ak.Z.MCP_AUTO_INSTALL_SETTINGS,az)??{};return{requireConsent:"boolean"==typeof a.requireConsent?a.requireConsent:az.requireConsent,namespaceAllowlist:Array.isArray(a.namespaceAllowlist)?a.namespaceAllowlist.filter(a=>"string"==typeof a&&a.length>0):[],trustBrainStem:"boolean"==typeof a.trustBrainStem?a.trustBrainStem:az.trustBrainStem}}catch(a){return aC.warn("Failed to load mcpAutoInstall settings; using safe defaults",a),{...az}}}let aE="mcp-install-audit",aF=Promise.resolve();async function aG(){try{return await (0,I.YM)(aE,[])}catch(a){return aC.error("Failed to load MCP install audit log",a),[]}}async function aH(a){let b=aF.catch(()=>{}).then(async()=>{let b=await aG();b.push(a);let c=b.slice(-300);await (0,I.VH)(aE,c)}).catch(a=>{aC.error("Failed to append MCP install audit entry",a)});aF=b,await b}let aI=(0,h.h)("backend/services/mcp/flowAuthoringTools"),aJ=["list_flow_building_blocks","validate_flow_spec","create_flow","search_mcp_marketplace","install_mcp_server","install_best_mcp_server"];function aK(){return{type:"object",properties:{spec:{type:"object",description:"The FlowSpec object (see the tool description for the format)."}},required:["spec"]}}function aL(a,b=!1){return{content:[{type:"text",text:JSON.stringify(a,null,2)}],...b?{isError:!0}:{}}}async function aM(a,b){try{if("list_flow_building_blocks"===a){let a=await E();return aL(a.blocks)}if("search_mcp_marketplace"===a){let a="string"==typeof b?.query?b.query:"",c=await au(a);return aL(c)}if("install_mcp_server"===a){let a="string"==typeof b?.name?b.name:"",c=b?.env&&"object"==typeof b.env&&!Array.isArray(b.env)?b.env:void 0,d=await ax(a,c,{resolveOnly:!0});if(!d.plan)return aL(d,!0);let e=await aD(),f=aA({caller:"authoring-tool",settings:e,registryName:a}),g=(0,R.nO)(d.plan.verificationStatus)?void 0:`Unverified / self-asserted registry entry (status: ${d.plan.verificationStatus}). Registry entries are publisher-asserted — review the command before approving.`;if(await aH(aB(d.plan,"authoring-tool",f,!1)),!f.allowed)return aL({installed:!1,consentRequired:!0,message:f.message,plan:d.plan,...g?{verificationWarning:g}:{}});let h=await ax(a,c);return await aH(aB(h.plan??d.plan,"authoring-tool",f,h.installed,h.error)),aL({...h,...g?{verificationWarning:g}:{}},!h.installed)}if("install_best_mcp_server"===a){let a="string"==typeof b?.capability?b.capability:"",c=b?.env&&"object"==typeof b.env&&!Array.isArray(b.env)?b.env:void 0;if(!a)return aL({error:'Provide a "capability" search term.'},!0);let d=await aD(),e=aA({caller:"authoring-tool",settings:d,registryName:a});if(!e.allowed){let b=(await au(a)).find(a=>a.installable),d=b?await ax(b.name,c,{resolveOnly:!0}):null;return d?.plan&&await aH(aB(d.plan,"authoring-tool",e,!1)),aL({installed:!1,consentRequired:!0,message:e.message,...d?.plan?{plan:d.plan}:{}})}let f=await ay(a,c,{onAttempt:async(a,b)=>{a&&await aH(aB(a,"authoring-tool",e,b.installed,b.error))}}),g=f.installed&&!(0,R.nO)(f.plan?.verificationStatus)?`Installed an unverified / self-asserted registry entry (status: ${f.plan?.verificationStatus}).`:void 0;return aL({...f,...g?{verificationWarning:g}:{}},!f.installed)}if("validate_flow_spec"===a||"create_flow"===a){let c=function(a){let b=a?.spec;if("string"==typeof b)try{return JSON.parse(b)}catch{return null}return b??null}(b);if(!c)return aL({error:'Provide a "spec" argument: a FlowSpec object (or a JSON string of one).'},!0);let d=await G(c,{save:"create_flow"===a});if(!d.success)return aL({error:d.error,issues:d.issues??[]},!0);let e=d.flows.length,f=e>1?` (plus ${e-1} nested subflow flow(s))`:"",g={flowId:d.flow.id,flowName:d.flow.name,nodeCount:d.flow.nodes.length,edgeCount:d.flow.edges.length,...e>1?{flows:d.flows.map(a=>({id:a.id,name:a.name}))}:{},validation:d.validation,..."create_flow"===a?{saved:d.saved,...d.saved?{note:`Flow "${d.flow.name}"${f} was created. It is callable as a tool on this MCP server (after a fresh tools/list) and as model "flow-${d.flow.name}" on the OpenAI-compatible endpoint.`}:{note:"NOT saved: validation found errors. Fix the issues and call create_flow again."}}:{}};return aL(g,"create_flow"===a&&!d.saved)}return aL({error:`Unknown authoring tool: ${a}`},!0)}catch(b){return aI.error("authoringCallTool failed",{toolName:a,err:b}),aL({error:`Authoring tool failed: ${b instanceof Error?b.message:String(b)}`},!0)}}var aN=c(92018);let aO=(0,h.h)("backend/services/mcp/internalTools");function aP(a,b=!1){return{content:[{type:"text",text:"string"==typeof a?a:JSON.stringify(a,null,2)}],...b?{isError:!0}:{}}}function aQ(){return[{name:"list_flow_building_blocks",description:'List everything a FlowSpec may reference in this FLUJO instance: configured models (bind to process steps), MCP servers and their tools (attach via "servers"), and existing flows (usable as subflow targets). Call this before authoring a spec.',inputSchema:{type:"object",properties:{}}},{name:"validate_flow_spec",description:`Compile and validate a FlowSpec WITHOUT saving. Returns the compiled flow's validation result (errors block saving; warnings are advisory) so you can iterate until clean, then call create_flow.
79
+
80
+ ${P}`,inputSchema:aK()},{name:"create_flow",description:`Create a new FLUJO flow from a FlowSpec. The spec is compiled deterministically (layout, ids, and wiring are generated for you) and saved ONLY when validation finds zero errors — otherwise the issues are returned to fix. Use list_flow_building_blocks first to see the models, MCP servers/tools, and existing flows you may reference.
81
+
82
+ ${P}`,inputSchema:aK()},{name:"search_mcp_marketplace",description:"Search the public MCP server registry for new capabilities (voice, browsing, files, email, vision, …). The registry matches the query against server NAMES only (substring) — use short single terms and try several. Returns name, description, whether FLUJO can install it, and which env vars/keys it would require.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Short search term matched against server names."}},required:["query"]}},{name:"install_mcp_server",description:'Install an MCP server from the public registry (by the exact name returned by search_mcp_marketplace) and connect it — this DOWNLOADS AND RUNS a third-party package on the FLUJO host. Installs are gated by consent (SEP-1024): unless this trusted authoring tool is allowed via the mcpAutoInstall settings (trustBrainStem / requireConsent / namespaceAllowlist), the tool returns the exact resolved command + arguments with consentRequired=true INSTEAD of installing, and the caller must obtain explicit approval. Every attempt is written to an audit log (command, args, env NAMES, verification status — never secret values) before any spawn. Returns the FLUJO server name (reference it in FlowSpec "servers") and the tools it provides, or needsEnv when required keys are missing (supply values via the optional "env" argument), or the resolved plan when consent is required. First install can take minutes (package download).',inputSchema:{type:"object",properties:{name:{type:"string",description:'Exact registry name from search results, e.g. "ai.keenable/web-search".'},env:{type:"object",description:"Optional env var values for the server (e.g. required API keys).",additionalProperties:{type:"string"}}},required:["name"]}},{name:"install_best_mcp_server",description:"Install the BEST WORKING MCP server for a capability, unattended — the recommended way to acquire a capability when you don't already have a specific server name. Searches the registry, RANKS candidates by blended quality (GitHub stars + recent activity, npm weekly downloads, registry status), then installs best→worst until one actually boots and exposes tools (the \"works-gate\"): candidates that need unavailable keys, can't be installed, or start with zero tools are skipped automatically. Same consent/audit rules and third-party-code warning as install_mcp_server. Returns the installed server name + its tools and the list of candidates tried, or needsEnv/consentRequired. Prefer this over search+install for headless self-improvement; use install_mcp_server only when you must pin an exact server.",inputSchema:{type:"object",properties:{capability:{type:"string",description:'Short capability term matched against server names, e.g. "youtube", "email", "browser".'},env:{type:"object",description:"Optional env var values shared across attempted servers (e.g. an API key).",additionalProperties:{type:"string"}}},required:["capability"]}},{name:"execute_flow",description:"Run another FLUJO flow (by name or id) with the given input and return its final output. The run is ephemeral (no chat conversation is created). Use list_flow_building_blocks to see the available flows. Nested runs are limited in depth — a flow cannot recurse through itself indefinitely.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id."},input:{type:"string",description:"The message to send to the flow as the user turn."}},required:["flow","input"]}},{name:"read_flow",description:"Read a FLUJO flow's full definition (by name or id): its nodes with their prompts, bound models, attached MCP servers/tools and input/output modes, plus the control and MCP edges. Note this is the COMPILED flow (node ids, not FlowSpec keys) — to change it, author a fresh FlowSpec and call update_flow.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id."}},required:["flow"]}},{name:"update_flow",description:"REPLACE an existing FLUJO flow's definition (by name or id) with a newly compiled FlowSpec, keeping the flow's id — so planned executions, subflow nodes and conversations that reference it keep working. The spec format is the same as create_flow/validate_flow_spec (see those tool descriptions); saving is gated on zero validation errors. The replaced definition is archived automatically — list_flow_versions / revert_flow can restore it. Note that manual canvas edits made in the builder are part of what gets replaced. Use read_flow first to see what you are replacing.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id of the flow to replace."},spec:{type:"object",description:"The FlowSpec object (see the create_flow tool description for the format)."}},required:["flow","spec"]}},{name:"list_flow_versions",description:"List a flow's archived versions (by name or id), newest first. A version is created automatically whenever the flow's definition is overwritten (builder save, update_flow, revert_flow) and holds the definition that was replaced. Use read_flow_version to inspect one and revert_flow to restore one.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id."}},required:["flow"]}},{name:"read_flow_version",description:"Read one archived version of a flow (see list_flow_versions): the full definition it held before it was replaced, in the same format as read_flow.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id."},version:{type:"string",description:"The version id (see list_flow_versions)."}},required:["flow","version"]}},{name:"revert_flow",description:"Restore an archived version (see list_flow_versions) as the flow's CURRENT definition. The definition being reverted away from is archived first, so a revert can itself be undone. References by flow id keep working.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id."},version:{type:"string",description:"The version id to restore (see list_flow_versions)."}},required:["flow","version"]}},{name:"delete_flow",description:"PERMANENTLY delete a FLUJO flow (by name or id). This cannot be undone — the flow's version history is deleted with it. Verify the target with list_flow_building_blocks first.",inputSchema:{type:"object",properties:{flow:{type:"string",description:"Flow name or flow id."}},required:["flow"]}},{name:"list_mcp_servers",description:"List the MCP servers configured in this FLUJO instance with their transport, enabled/disabled state and live connection status. Config details (env vars, headers, credentials) are never included.",inputSchema:{type:"object",properties:{}}},{name:"list_mcp_server_tools",description:"List the tools of one configured MCP server (name, description, input schema). Use together with call_mcp_tool for servers that are not bound to this flow.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name (see list_mcp_servers)."}},required:["server"]}},{name:"call_mcp_tool",description:"Call a tool on any configured MCP server by server name + tool name. This lets you use servers that are not bound to the current flow. Check the tool's input schema with list_mcp_server_tools first.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name."},tool:{type:"string",description:"The tool name on that server."},args:{type:"object",description:"Arguments for the tool (per its input schema)."},timeout:{type:"number",description:"Optional timeout in seconds."}},required:["server","tool"]}},{name:"restart_mcp_server",description:"Force-reconnect a configured MCP server (tears the connection down and rebuilds it). Useful when a server is in an error state after a config or environment change.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name."}},required:["server"]}},{name:"set_mcp_server_enabled",description:"Enable or disable a configured MCP server. Disabling disconnects it and prevents any further use; enabling connects it.",inputSchema:{type:"object",properties:{server:{type:"string",description:"The FLUJO server name."},enabled:{type:"boolean",description:"true to enable + connect, false to disable + disconnect."}},required:["server","enabled"]}},{name:"list_models",description:"List the models configured in this FLUJO instance (id, name, display name, description, provider, base URL, context window). API keys are never included. Reference models by id or name in FlowSpecs.",inputSchema:{type:"object",properties:{}}},{name:"list_planned_executions",description:"List the planned (scheduled/triggered) executions in this FLUJO instance with their trigger type, enabled state, armed status and last run outcome.",inputSchema:{type:"object",properties:{}}},{name:"run_planned_execution",description:"Fire a planned execution immediately (by id, see list_planned_executions) and return the run record with its output.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The planned execution id."}},required:["id"]}},{name:"update_planned_execution",description:'Modify an existing planned execution (by id or name, see list_planned_executions). Patch any of: "enabled" (turn the schedule on/off), "prompt" (the run prompt), "flowId" (the flow to run — accepts a flow name or id), "cron" (a convenience for the trigger\'s cron pattern — works for schedule / mcp-poll / url-watch triggers) or a full "trigger" object for complete control. Flow-driven cadence changes are clamped to a minimum interval (a runaway every-second schedule is rejected). The webhook secret token is never returned.',inputSchema:{type:"object",properties:{execution:{type:"string",description:"The planned execution id or name."},enabled:{type:"boolean",description:"Enable or disable the execution."},prompt:{type:"string",description:"The run prompt."},flowId:{type:"string",description:"The flow to run — a flow name or id (resolved to the flow id)."},cron:{type:"string",description:"Cron pattern (croner syntax; 6-field form for seconds) for the trigger's schedule. Applies to schedule / mcp-poll / url-watch triggers."},trigger:{type:"object",description:"Full trigger config object (escape hatch for complete control). Prefer the named fields above."}},required:["execution"]}},{name:"create_planned_execution",description:'Create a new planned execution: bind a flow to a trigger so it runs headlessly. Provide "name", "flow" (a flow name or id), an optional "prompt", optional "enabled" (default true), and EITHER a full "trigger" object OR a convenience "cron" (which creates a schedule trigger). Flow-driven cadence is clamped to a minimum interval. A webhook trigger\'s secret token is minted server-side and never returned.',inputSchema:{type:"object",properties:{name:{type:"string",description:"A name for the planned execution."},flow:{type:"string",description:"The flow to run — a flow name or id."},prompt:{type:"string",description:"The run prompt (may be empty)."},enabled:{type:"boolean",description:"Whether to arm the trigger immediately (default true)."},cron:{type:"string",description:'Cron pattern for a schedule trigger (convenience — use "trigger" for other trigger types).'},trigger:{type:"object",description:"Full trigger config object (schedule / webhook / file-watch / mcp-poll / url-watch)."}},required:["name","flow"]}},{name:"delete_planned_execution",description:"Permanently delete a planned execution (by id or name, see list_planned_executions), along with its run history. This cannot be undone.",inputSchema:{type:"object",properties:{execution:{type:"string",description:"The planned execution id or name."}},required:["execution"]}},{name:"list_conversations",description:"List the chat conversations stored in this FLUJO instance (id, title, bound flow, status, created/updated timestamps), newest first. Use read_conversation to get a transcript.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Optional maximum number of conversations to return (newest first). Default: all."}}}},{name:"read_conversation",description:'Read one chat conversation\'s transcript by conversation id (see list_conversations). Returns the displayed messages: system prompts are excluded, nested subflow steps carry a "depth" marker, assistant tool calls are summarized. Long conversations return only the most recent messages — raise "limit" to get more.',inputSchema:{type:"object",properties:{conversation:{type:"string",description:"The conversation id."},limit:{type:"number",description:"Maximum number of most-recent messages to return (default 50). The total transcript size is capped regardless."}},required:["conversation"]}},{name:"kv_get",description:'Read a value from FLUJO\'s PERSISTENT key-value store (the ${kv:NAME} store) — state that survives ACROSS flow runs (loop counters, cursors, flags). Returns { found, value }. Defaults to the instance-global board; pass "scope" to target another board (e.g. a flow-folder board id). Values are plain strings, never secrets.',inputSchema:{type:"object",properties:{name:{type:"string",description:"The key to read (an identifier: letters, digits, _ and -, not starting with a digit)."},scope:{type:"string",description:'Optional board id to read from. Defaults to "global".'}},required:["name"]}},{name:"kv_set",description:'Write a value to FLUJO\'s PERSISTENT key-value store (the ${kv:NAME} store) — state that survives ACROSS flow runs. Last-write-wins. Defaults to the instance-global board; pass "scope" to target another board. Values are plain strings (never secrets — use ${global:} for those) and are size-capped; an oversized write is refused with { saved:false, skipped }.',inputSchema:{type:"object",properties:{name:{type:"string",description:"The key to write (an identifier: letters, digits, _ and -, not starting with a digit)."},value:{type:"string",description:"The string value to store."},scope:{type:"string",description:'Optional board id to write to. Defaults to "global".'}},required:["name","value"]}}]}async function aR(a){let b=await i.flowService.loadFlows();return b.find(b=>b.id===a)??b.find(b=>b.name===a)}async function aS(a){let b=String(a?.flow??"").trim();if(!b)return aP({error:'Provide "flow": a flow name or id.'},!0);let c=await aR(b);if(!c)return aP({error:`No flow named or with id "${b}". Use list_flow_building_blocks to see the available flows.`},!0);let d=global.__flujo_internal_flow_depth??0;if(d>=4)return aP({error:`execute_flow nesting limit (4) reached — refusing to start "${c.name}" to prevent runaway recursion.`},!0);global.__flujo_internal_flow_depth=d+1;try{let b=await (0,m.runFlow)({flowId:c.id,prompt:String(a?.input??""),mode:"ephemeral",flujo:!0,requireApproval:!1});if(b.flowNotFound)return aP({error:`Flow not found: ${b.flowNotFound.name}`},!0);if("error"===b.status)return aP({error:b.error?.message??"Unknown error during flow execution."},!0);return aP(b.outputText??"")}finally{global.__flujo_internal_flow_depth=d}}async function aT(a){let b=String(a?.flow??"").trim();if(!b)return aP({error:'Provide "flow": a flow name or id.'},!0);let c=await aR(b);if(!c)return aP({error:`No flow named or with id "${b}".`},!0);let d=await i.flowService.deleteFlow(c.id);return d.success?aP({deleted:!0,flowId:c.id,flowName:c.name}):aP({error:d.error??`Failed to delete flow "${c.name}".`},!0)}function aU(a){let b=a.nodes.map(a=>{let{mcpNodes:b,...c}=a.data?.properties??{};return{id:a.id,type:a.type,label:a.data?.label,...a.data?.description?{description:a.data.description}:{},properties:c}}),c=a.edges.map(a=>{let b=a.data;return{from:a.source,to:a.target,type:b?.edgeType==="mcp"?"mcp":b?.edgeType==="resource"?"resource":"control",...b?.bidirectional?{bidirectional:!0}:{}}});return{id:a.id,name:a.name,...a.description?{description:a.description}:{},nodes:b,edges:c}}async function aV(a){let b=String(a?.flow??"").trim();if(!b)return aP({error:'Provide "flow": a flow name or id.'},!0);let c=await aR(b);return c?aP({...aU(c),note:"This is the compiled flow (node ids, not FlowSpec keys). To change it, author a fresh FlowSpec and call update_flow — it replaces the whole definition while keeping this flow id."}):aP({error:`No flow named or with id "${b}". Use list_flow_building_blocks to see the available flows.`},!0)}async function aW(a){let b=String(a?.flow??"").trim();if(!b)return aP({error:'Provide "flow": a flow name or id.'},!0);let c=await aR(b);if(!c)return aP({error:`No flow named or with id "${b}".`},!0);let d=await i.flowService.listFlowVersions(c.id);return aP({flowId:c.id,flowName:c.name,versions:d,...0===d.length?{note:"No archived versions yet — versions appear once the flow's definition is overwritten for the first time."}:{}})}async function aX(a){let b=String(a?.flow??"").trim(),c=String(a?.version??"").trim();if(!b||!c)return aP({error:'Provide "flow" (name or id) and "version" (see list_flow_versions).'},!0);let d=await aR(b);if(!d)return aP({error:`No flow named or with id "${b}".`},!0);let e=await i.flowService.getFlowVersion(d.id,c);return e?aP({versionId:e.versionId,savedAt:e.savedAt,...aU(e.flow)}):aP({error:`No version "${c}" of flow "${d.name}". Use list_flow_versions to see the archived versions.`},!0)}async function aY(a){let b=String(a?.flow??"").trim(),c=String(a?.version??"").trim();if(!b||!c)return aP({error:'Provide "flow" (name or id) and "version" (see list_flow_versions).'},!0);let d=await aR(b);if(!d)return aP({error:`No flow named or with id "${b}".`},!0);let e=await i.flowService.revertFlow(d.id,c);return e.success?aP({reverted:!0,flowId:d.id,versionId:c,note:"The definition that was just replaced has been archived too, so this revert can itself be undone via list_flow_versions / revert_flow."}):aP({error:e.error??`Failed to revert flow "${d.name}".`},!0)}async function aZ(a){let b=String(a?.flow??"").trim();if(!b)return aP({error:'Provide "flow": the name or id of the flow to replace.'},!0);let c=function(a){let b=a?.spec;if("string"==typeof b)try{return JSON.parse(b)}catch{return null}return b??null}(a);if(!c)return aP({error:'Provide a "spec" argument: a FlowSpec object (or a JSON string of one).'},!0);let d=await aR(b);if(!d)return aP({error:`No flow named or with id "${b}". Use list_flow_building_blocks to see the available flows.`},!0);let e=await G(c,{save:!0,updateFlowId:d.id});return e.success?aP({flowId:e.flow.id,flowName:e.flow.name,nodeCount:e.flow.nodes.length,edgeCount:e.flow.edges.length,validation:e.validation,saved:e.saved,...e.saved?{note:`Flow "${e.flow.name}" was replaced (id ${e.flow.id} kept — existing references keep working).`}:{note:"NOT saved: validation found errors. The existing flow is unchanged. Fix the issues and call update_flow again."}},!e.saved):aP({error:e.error,issues:e.issues??[]},!0)}async function a$(a){let b=await a.loadServerConfigs();return Array.isArray(b)?aP(await Promise.all(b.map(async b=>{let c="unknown";try{c=(await a.getServerStatus(b.name)).status}catch(a){aO.debug(`list_mcp_servers: getServerStatus failed for ${b.name}`,a)}return{name:b.name,transport:b.transport,enabled:!b.disabled,status:c,...b.builtIn?{builtIn:!0}:{}}}))):aP({error:b.error??"Failed to load server configs."},!0)}async function a_(a,b){let c=String(b?.server??"").trim();if(!c)return aP({error:'Provide "server": a FLUJO server name.'},!0);if(c===aN._)return aP(aQ().map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema})));let{tools:d,error:e}=await a.listServerTools(c);return e?aP({error:e},!0):aP(d.map(a=>({name:a.name,description:a.description,inputSchema:a.inputSchema})))}async function a0(a,b){let c=String(b?.server??"").trim(),d=String(b?.tool??"").trim();if(!c||!d)return aP({error:'Provide "server" and "tool".'},!0);if(c===aN._)return aP({error:`"${aN._}" is this server — call its tools directly instead of through call_mcp_tool.`},!0);let e=b?.args&&"object"==typeof b.args&&!Array.isArray(b.args)?b.args:{},f="number"==typeof b?.timeout?b.timeout:void 0,g=await a.callTool(c,d,e,f);if(!g.success)return aP({error:g.error??`Tool call failed on ${c}.`},!0);let h=g.data;return h&&Array.isArray(h.content)?h:aP(h??{ok:!0})}async function a1(a,b){let c=String(b?.server??"").trim();if(!c)return aP({error:'Provide "server": a FLUJO server name.'},!0);if(c===aN._)return aP({ok:!0,note:`"${aN._}" is the built-in server — it is always running.`});let d=await a.forceReconnect(c);if(!d.success)return aP({error:d.error??`Failed to restart ${c}.`},!0);let e=await a.getServerStatus(c);return aP({restarted:!0,server:c,status:e.status})}async function a2(a,b){let c=String(b?.server??"").trim(),d=b?.enabled;if(!c||"boolean"!=typeof d)return aP({error:'Provide "server" (string) and "enabled" (boolean).'},!0);if(c===aN._)return aP({error:`The built-in "${aN._}" server cannot be disabled.`},!0);let e=await a.updateServerConfig(c,{disabled:!d});return"error"in e?aP({error:e.error},!0):aP({server:c,enabled:d})}async function a3(){return aP((await j.modelService.loadModels()).map(a=>({id:a.id,name:a.name,...a.displayName?{displayName:a.displayName}:{},...a.description?{description:a.description}:{},...a.provider?{provider:a.provider}:{},...a.baseUrl?{baseUrl:a.baseUrl}:{},...a.contextWindow?{contextWindow:a.contextWindow}:{}})))}async function a4(){return aP((await (0,k.z)().list()).map(({execution:a,status:b,lastRun:c})=>({id:a.id,name:a.name,enabled:a.enabled,flowId:a.flowId,triggerType:a.trigger?.type,armed:b?.armed??!1,...c?{lastRun:{status:c.status,firedAt:c.firedAt,...c.error?{error:c.error}:{}}}:{}})))}async function a5(a){let b=String(a?.id??"").trim();if(!b)return aP({error:'Provide "id": a planned execution id (see list_planned_executions).'},!0);let{record:c,error:d}=await (0,k.z)().runNow(b);return d||!c?aP({error:d??"Run failed."},!0):aP({runId:c.runId,status:c.status,firedAt:c.firedAt,...c.finishedAt?{finishedAt:c.finishedAt}:{},...c.outputText?{outputText:c.outputText}:{},...c.error?{error:c.error}:{}})}async function a6(a){let b=await (0,k.z)().list(),c=b.find(b=>b.execution.id===a),d=b.find(b=>b.execution.name===a);return(c??d)?.execution??null}function a7(a){return{id:a.id,name:a.name,enabled:a.enabled,flowId:a.flowId,triggerType:a.trigger?.type}}function a8(a,b){try{let c=(0,l.Z9)(a,b,5).map(a=>new Date(a).getTime()),d=1/0;for(let a=1;a<c.length;a++){let b=c[a]-c[a-1];b>0&&b<d&&(d=b)}return Number.isFinite(d)?d:null}catch{return null}}function a9(a){let b=null;return("schedule"===a.type||"url-watch"===a.type?a.cron&&(b=a8(a.cron,a.timezone)):"mcp-poll"===a.type&&(a.cron?b=a8(a.cron,a.timezone):"number"==typeof a.intervalMs&&(b=a.intervalMs)),null!==b&&b<6e4)?`Cadence too fast: the trigger would fire about every ${Math.round(b/1e3)}s, but flow-driven schedule changes are clamped to a minimum interval of 60s. Choose a slower cadence (change it from the Planned Executions page for a faster one).`:null}async function ba(a){let b,c=String(a?.execution??"").trim();if(!c)return aP({error:'Provide "execution": a planned execution id or name (see list_planned_executions).'},!0);let d=await a6(c);if(!d)return aP({error:`No planned execution with id or name "${c}". Use list_planned_executions to see them.`},!0);let e={};"boolean"==typeof a?.enabled&&(e.enabled=a.enabled),"string"==typeof a?.prompt&&(e.prompt=a.prompt);let f=String(a?.flowId??a?.flow??"").trim();if(f){let a=await aR(f);if(!a)return aP({error:`No flow named or with id "${f}". Use list_flow_building_blocks to see the flows.`},!0);e.flowId=a.id}a?.trigger&&"object"==typeof a.trigger&&!Array.isArray(a.trigger)&&(b=a.trigger);let g="string"==typeof a?.cron?a.cron.trim():"";if(g){let a=b??d.trigger;if("schedule"!==a.type&&"mcp-poll"!==a.type&&"url-watch"!==a.type)return aP({error:`The "${a.type}" trigger has no schedule to change with "cron". Pass a full "trigger" object instead.`},!0);b={...a,cron:g}}if(b){let a=a9(b);if(a)return aP({error:a},!0);e.trigger=b}if(0===Object.keys(e).length)return aP({error:"Nothing to update. Provide at least one of: enabled, prompt, flowId, cron, trigger."},!0);let h=await (0,k.z)().update(d.id,e);return h.error||!h.execution?aP({error:h.error??"Update failed."},!0):aP({updated:!0,...a7(h.execution)})}async function bb(a){let b,c=String(a?.name??"").trim();if(!c)return aP({error:'Provide "name": a name for the planned execution.'},!0);let d=String(a?.flow??a?.flowId??"").trim();if(!d)return aP({error:'Provide "flow": a flow name or id to run.'},!0);let e=await aR(d);if(!e)return aP({error:`No flow named or with id "${d}". Use list_flow_building_blocks to see the flows.`},!0);if(a?.trigger&&"object"==typeof a.trigger&&!Array.isArray(a.trigger))b=a.trigger;else{let c="string"==typeof a?.cron?a.cron.trim():"";if(!c)return aP({error:'Provide a "trigger" object or a "cron" pattern (which creates a schedule trigger).'},!0);b={type:"schedule",cron:c}}let f=a9(b);if(f)return aP({error:f},!0);let g={name:c,enabled:"boolean"!=typeof a?.enabled||a.enabled,flowId:e.id,prompt:"string"==typeof a?.prompt?a.prompt:"",trigger:b},h=await (0,k.z)().create(g);return h.error||!h.execution?aP({error:h.error??"Create failed."},!0):aP({created:!0,...a7(h.execution)})}async function bc(a){let b=String(a?.execution??"").trim();if(!b)return aP({error:'Provide "execution": a planned execution id or name (see list_planned_executions).'},!0);let c=await a6(b);if(!c)return aP({error:`No planned execution with id or name "${b}". Use list_planned_executions to see them.`},!0);let d=await (0,k.z)().delete(c.id);return d.success?aP({deleted:!0,id:c.id,name:c.name}):aP({error:d.error??`Failed to delete "${c.name}".`},!0)}async function bd(a){let b,c=f().join((0,N.ok)(),"db","conversations");try{b=await g.promises.readdir(c)}catch(a){if("ENOENT"===a.code)return aP([]);return aP({error:`Failed to list conversations: ${a instanceof Error?a.message:String(a)}`},!0)}let d=(await Promise.all(b.filter(a=>a.endsWith(".json")).map(async a=>{try{let b=await g.promises.readFile(f().join(c,a),"utf-8"),d=JSON.parse(b),e=d.conversationId||a.replace(/\.json$/,""),h=d.status;return"running"===h&&0===M.$.currentSeq(e)&&(h="error"),{id:e,title:d.title||"Untitled Conversation",flowId:d.flowId||null,...h?{status:h}:{},createdAt:d.createdAt||0,updatedAt:d.updatedAt||0}}catch(b){return aO.warn(`list_conversations: skipping unreadable conversation file ${a}`,b),null}}))).filter(a=>null!==a).sort((a,b)=>b.updatedAt-a.updatedAt),e="number"==typeof a?.limit&&a.limit>0?Math.floor(a.limit):void 0;return aP(e?d.slice(0,e):d)}async function be(a){let b=String(a?.conversation??"").trim();if(!b)return aP({error:'Provide "conversation": a conversation id (see list_conversations).'},!0);await (0,J.u8)(b);let c=await L(b);if(!c)return aP({error:`No conversation with id "${b}". Use list_conversations to see the stored conversations.`},!0);let d=await (0,J.Os)(b),e=d?(0,J.cc)(d):[],f=e.length>0?e:(c.messages||[]).filter(a=>"system"!==a.role),g="number"==typeof a?.limit&&a.limit>0?Math.floor(a.limit):50,h=[],i=0;for(let a=f.length-1;a>=0&&h.length<g;a--){let b=function(a){let b="";"string"==typeof a.content?b=a.content:Array.isArray(a.content)&&(b=a.content.map(a=>"text"in a&&"string"==typeof a.text?a.text:"").filter(Boolean).join("\n"));let c={role:a.role,...b?{content:b}:{},...a.timestamp?{timestamp:a.timestamp}:{},...a.depth?{depth:a.depth}:{}};return"assistant"===a.role&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0&&(c.toolCalls=a.tool_calls.map(a=>{let b="function"in a?a.function:void 0,c=b&&"string"==typeof b.arguments?b.arguments:void 0;return{id:a.id,...b?.name?{name:b.name}:{},...void 0!==c?{arguments:c.length>2e3?c.slice(0,2e3)+"…[truncated]":c}:{}}})),"tool"===a.role&&a.tool_call_id&&(c.toolCallId=a.tool_call_id),c}(f[a]),c=JSON.stringify(b).length;if(h.length>0&&i+c>1e5)break;h.push(b),i+=c}return h.reverse(),aP({id:c.conversationId||b,title:c.title||"Untitled Conversation",flowId:c.flowId||null,...c.status?{status:c.status}:{},createdAt:c.createdAt||0,updatedAt:c.updatedAt||0,totalMessages:f.length,...h.length<f.length?{note:`Returning the ${h.length} most recent of ${f.length} messages — raise "limit" to get more.`}:{},messages:h})}let bf=/^[A-Za-z0-9_-]{1,64}$/,bg=/^[A-Za-z_][\w-]*$/;async function bh(a){let b="string"==typeof a.name?a.name.trim():"",c="string"==typeof a.scope&&a.scope.trim()?a.scope.trim():"global";if(!bg.test(b))return aP({error:'kv_get requires a valid "name" (letters, digits, _ and -, not starting with a digit).'},!0);if(!bf.test(c))return aP({error:`Invalid kv scope id: ${c}`},!0);let d=await (0,O.M3)(c,b);return aP({scope:c,name:b,found:void 0!==d,value:d??null})}async function bi(a){let b="string"==typeof a.name?a.name.trim():"",c="string"==typeof a.scope&&a.scope.trim()?a.scope.trim():"global",d="string"==typeof a.value?a.value:null==a.value?"":String(a.value);if(!bg.test(b))return aP({error:'kv_set requires a valid "name" (letters, digits, _ and -, not starting with a digit).'},!0);if(!bf.test(c))return aP({error:`Invalid kv scope id: ${c}`},!0);let e=await (0,O.or)(c,b,d);return"skipped"in e?aP({scope:c,name:b,saved:!1,skipped:e.skipped},!0):aP({scope:c,name:b,saved:!0,size:e.size})}async function bj(a,b,c){try{if(aJ.includes(b))return await aM(b,c);switch(b){case"execute_flow":return await aS(c);case"read_flow":return await aV(c);case"update_flow":return await aZ(c);case"list_flow_versions":return await aW(c);case"read_flow_version":return await aX(c);case"revert_flow":return await aY(c);case"delete_flow":return await aT(c);case"list_mcp_servers":return await a$(a);case"list_mcp_server_tools":return await a_(a,c);case"call_mcp_tool":return await a0(a,c);case"restart_mcp_server":return await a1(a,c);case"set_mcp_server_enabled":return await a2(a,c);case"list_models":return await a3();case"list_planned_executions":return await a4();case"run_planned_execution":return await a5(c);case"update_planned_execution":return await ba(c);case"create_planned_execution":return await bb(c);case"delete_planned_execution":return await bc(c);case"list_conversations":return await bd(c);case"read_conversation":return await be(c);case"kv_get":return await bh(c);case"kv_set":return await bi(c);default:return aP({error:`Unknown tool on the built-in FLUJO server: ${b}`},!0)}}catch(a){return aO.error("internalCallTool failed",{toolName:b,err:a}),aP({error:`Tool failed: ${a instanceof Error?a.message:String(a)}`},!0)}}}};
@@ -1 +1 @@
1
- "use strict";exports.id=7821,exports.ids=[7821],exports.modules={87821:(a,b,c)=>{c.d(b,{flowService:()=>x});var d=c(32524),e=c(92372),f=c(46480),g=c(50846),h=c(33873),i=c.n(h),j=c(29021),k=c(43326);let l=(0,g.h)("backend/services/flow/flowVersions");function m(a){return(0,e.ln)(a),`flow-versions/${a}`}async function n(a){try{let b=m(a.id),c=Date.now(),d=`${c}-${Math.random().toString(36).slice(2,6)}`,f={versionId:d,flowId:a.id,savedAt:c,flow:a};return await (0,e.Vt)(b,d,f),await o(a.id),d}catch(b){return l.warn(`Could not archive a version of flow ${a.id}`,b),null}}async function o(a){let b=m(a),c=await (0,e.pL)(b);if(!(c.length<=25))for(let d of c.sort((a,b)=>b.savedAt-a.savedAt).slice(25))try{await (0,e.bB)(b,d.versionId)}catch(b){l.warn(`Could not prune version ${d.versionId} of flow ${a}`,b)}}async function p(a){return(await (0,e.pL)(m(a))).sort((a,b)=>b.savedAt-a.savedAt).map(a=>({versionId:a.versionId,savedAt:a.savedAt,name:a.flow?.name??"unknown",nodeCount:a.flow?.nodes?.length??0,edgeCount:a.flow?.edges?.length??0}))}async function q(a,b){try{return await (0,e.EI)(m(a),b,null)}catch(c){return l.debug(`getFlowVersion: could not load ${a}/${b}`,c),null}}async function r(a){try{(0,e.ln)(a),await j.promises.rm(i().join((0,k.ok)(),"db","flow-versions",a),{recursive:!0,force:!0})}catch(b){l.warn(`Could not remove version history of flow ${a}`,b)}}let s=(0,g.h)("backend/services/flow/index"),t=f.Z.FLOWS;function u(a){let{createdAt:b,updatedAt:c,...d}=a;return JSON.stringify(d)}async function v(){return global.__flujo_flowsMigration||(global.__flujo_flowsMigration=(async()=>{try{await (0,e.w5)(f.Z.FLOWS,t,a=>a.id)}catch(a){s.error("Flow storage migration failed",a),global.__flujo_flowsMigration=void 0}})()),global.__flujo_flowsMigration}class w{get flowsCache(){return global.__flujo_flowsCache??null}set flowsCache(a){global.__flujo_flowsCache=a}async loadFlows(){try{if(this.flowsCache)return s.debug("Using cached flows"),this.flowsCache;s.debug("Loading flows from storage"),await v();let a=(await (0,e.av)(t)).map(({item:a,mtimeMs:b})=>{if(null!=a.createdAt&&null!=a.updatedAt)return a;let c=Math.floor(b);return{...a,createdAt:a.createdAt??c,updatedAt:a.updatedAt??c}});return this.flowsCache=a,s.info("Loaded flows from storage",{count:a.length}),a}catch(a){return s.error("Failed to load flows",a),[]}}async getFlow(a){try{s.debug(`Getting flow by ID: ${a}`);let b=this.flowsCache?.find(b=>b.id===a)||null;if(b)return s.debug(`Flow ${a} found in cache`),b;await v();let c=null;try{c=await (0,e.EI)(t,a,null)}catch(b){s.debug(`getFlow: could not load flow ${a}`,b),c=null}if(c&&this.flowsCache){let a=this.flowsCache,b=a.findIndex(a=>a.id===c.id);b>=0?a[b]=c:a.push(c),this.flowsCache=a}return s.debug(`Flow ${a} ${c?"found":"not found"}`),c}catch(b){return s.error(`Failed to get flow ${a}`,b),null}}async invalidateExecutionCache(a){try{let{FlowExecutor:b}=await Promise.all([c.e(6996),c.e(1223),c.e(5734),c.e(1373),c.e(264),c.e(724),c.e(3823),c.e(6793)]).then(c.bind(c,23823));b.clearFlowCache(a),s.debug("Invalidated execution flow cache",{flowId:a??"all"})}catch(a){s.warn("Failed to invalidate execution flow cache",a)}}async saveFlow(a){try{s.debug(`Saving flow: ${a.id}`,{name:a.name}),(0,e.ln)(a.id),await v();let b=null;try{b=await (0,e.EI)(t,a.id,null)}catch(b){s.debug(`saveFlow: could not read previous definition of ${a.id} for versioning`,b)}b&&u(b)!==u(a)&&await n(b);let c=Date.now();a.createdAt=b?.createdAt??a.createdAt??c,a.updatedAt=c,await (0,e.Vt)(t,a.id,a);let d=this.flowsCache;if(d){let b=d.findIndex(b=>b.id===a.id);b>=0?d[b]=a:d.push(a),this.flowsCache=d}return await this.invalidateExecutionCache(a.id),s.info(`Flow ${a.id} saved successfully`),{success:!0}}catch(a){return s.error("Failed to save flow",a),{success:!1,error:a instanceof Error?a.message:"Failed to save flow"}}}async deleteFlow(a){try{s.debug(`Deleting flow: ${a}`),await v(),await (0,e.bB)(t,a);let b=this.flowsCache;return b&&(this.flowsCache=b.filter(b=>b.id!==a)),await this.invalidateExecutionCache(a),await r(a),s.info(`Flow ${a} deleted successfully`),{success:!0}}catch(b){return s.error(`Failed to delete flow: ${a}`,b),{success:!1,error:b instanceof Error?b.message:"Failed to delete flow"}}}async listFlowVersions(a){return p(a)}async getFlowVersion(a,b){return q(a,b)}async revertFlow(a,b){let c=await q(a,b);return c?this.saveFlow({...c.flow,id:a}):{success:!1,error:`No version "${b}" of flow ${a}`}}createNode(a,b){s.debug(`Creating new node of type: ${a}`,{position:b});let c={id:(0,d.A)(),type:a,position:b,data:{label:`${"mcp"===a?"MCP":a.charAt(0).toUpperCase()+a.slice(1)} Node`,type:a,properties:{}}};return s.debug(`Node created with ID: ${c.id}`),c}createNewFlow(a="NewFlow"){s.debug(`Creating new flow: ${a}`);let b={id:(0,d.A)(),type:"start",position:{x:250,y:150},data:{label:"Start Node",type:"start",properties:{promptTemplate:""}}},c=Date.now(),e={id:(0,d.A)(),name:a,createdAt:c,updatedAt:c,nodes:[b],edges:[]};return s.info(`New flow created with ID: ${e.id}`,{name:a}),e}createHistoryEntry(a,b){return s.debug("Creating history entry",{nodeCount:a.length,edgeCount:b.length}),{nodes:[...a],edges:[...b]}}generateSampleFlow(a="Sample Flow"){s.debug(`Generating sample flow: ${a}`);let b={id:(0,d.A)(),name:a,nodes:[{id:"1",type:"start",position:{x:250,y:50},data:{label:"Start Node",type:"start",properties:{prompt:"Enter your query here",systemMessage:"You are a helpful assistant",temperature:0}}},{id:"2",type:"process",position:{x:250,y:200},data:{label:"Process Node",type:"process",properties:{operation:"transform",enabled:!0}}},{id:"3",type:"finish",position:{x:250,y:350},data:{label:"Finish Node",type:"finish",properties:{format:"json",template:'{ "result": {{data}} }'}}},{id:"4",type:"mcp",position:{x:450,y:200},data:{label:"MCP Node",type:"mcp",properties:{channels:2,mode:"parallel"}}}],edges:[{id:"e1-2",source:"1",target:"2",type:"custom"},{id:"e2-3",source:"2",target:"3",type:"custom"}]};return s.info(`Sample flow generated with ID: ${b.id}`,{name:a}),b}async listFlows(){s.debug("listFlows: Entering method");try{let a=await this.loadFlows();return{success:!0,flows:a}}catch(a){return s.warn("listFlows: Failed to list flows:",a),{success:!1,error:a instanceof Error?a.message:"Failed to list flows"}}}}let x=new w}};
1
+ "use strict";exports.id=7821,exports.ids=[7821],exports.modules={87821:(a,b,c)=>{c.d(b,{flowService:()=>x});var d=c(32524),e=c(92372),f=c(46480),g=c(50846),h=c(33873),i=c.n(h),j=c(29021),k=c(43326);let l=(0,g.h)("backend/services/flow/flowVersions");function m(a){return(0,e.ln)(a),`flow-versions/${a}`}async function n(a){try{let b=m(a.id),c=Date.now(),d=`${c}-${Math.random().toString(36).slice(2,6)}`,f={versionId:d,flowId:a.id,savedAt:c,flow:a};return await (0,e.Vt)(b,d,f),await o(a.id),d}catch(b){return l.warn(`Could not archive a version of flow ${a.id}`,b),null}}async function o(a){let b=m(a),c=await (0,e.pL)(b);if(!(c.length<=25))for(let d of c.sort((a,b)=>b.savedAt-a.savedAt).slice(25))try{await (0,e.bB)(b,d.versionId)}catch(b){l.warn(`Could not prune version ${d.versionId} of flow ${a}`,b)}}async function p(a){return(await (0,e.pL)(m(a))).sort((a,b)=>b.savedAt-a.savedAt).map(a=>({versionId:a.versionId,savedAt:a.savedAt,name:a.flow?.name??"unknown",nodeCount:a.flow?.nodes?.length??0,edgeCount:a.flow?.edges?.length??0}))}async function q(a,b){try{return await (0,e.EI)(m(a),b,null)}catch(c){return l.debug(`getFlowVersion: could not load ${a}/${b}`,c),null}}async function r(a){try{(0,e.ln)(a),await j.promises.rm(i().join((0,k.ok)(),"db","flow-versions",a),{recursive:!0,force:!0})}catch(b){l.warn(`Could not remove version history of flow ${a}`,b)}}let s=(0,g.h)("backend/services/flow/index"),t=f.Z.FLOWS;function u(a){let{createdAt:b,updatedAt:c,...d}=a;return JSON.stringify(d)}async function v(){return global.__flujo_flowsMigration||(global.__flujo_flowsMigration=(async()=>{try{await (0,e.w5)(f.Z.FLOWS,t,a=>a.id)}catch(a){s.error("Flow storage migration failed",a),global.__flujo_flowsMigration=void 0}})()),global.__flujo_flowsMigration}class w{get flowsCache(){return global.__flujo_flowsCache??null}set flowsCache(a){global.__flujo_flowsCache=a}async loadFlows(){try{if(this.flowsCache)return s.debug("Using cached flows"),this.flowsCache;s.debug("Loading flows from storage"),await v();let a=(await (0,e.av)(t)).map(({item:a,mtimeMs:b})=>{if(null!=a.createdAt&&null!=a.updatedAt)return a;let c=Math.floor(b);return{...a,createdAt:a.createdAt??c,updatedAt:a.updatedAt??c}});return this.flowsCache=a,s.info("Loaded flows from storage",{count:a.length}),a}catch(a){return s.error("Failed to load flows",a),[]}}async getFlow(a){try{s.debug(`Getting flow by ID: ${a}`);let b=this.flowsCache?.find(b=>b.id===a)||null;if(b)return s.debug(`Flow ${a} found in cache`),b;await v();let c=null;try{c=await (0,e.EI)(t,a,null)}catch(b){s.debug(`getFlow: could not load flow ${a}`,b),c=null}if(c&&this.flowsCache){let a=this.flowsCache,b=a.findIndex(a=>a.id===c.id);b>=0?a[b]=c:a.push(c),this.flowsCache=a}return s.debug(`Flow ${a} ${c?"found":"not found"}`),c}catch(b){return s.error(`Failed to get flow ${a}`,b),null}}async invalidateExecutionCache(a){try{let{FlowExecutor:b}=await Promise.all([c.e(6996),c.e(1223),c.e(5734),c.e(1373),c.e(4545),c.e(724),c.e(3823),c.e(6793)]).then(c.bind(c,23823));b.clearFlowCache(a),s.debug("Invalidated execution flow cache",{flowId:a??"all"})}catch(a){s.warn("Failed to invalidate execution flow cache",a)}}async saveFlow(a){try{s.debug(`Saving flow: ${a.id}`,{name:a.name}),(0,e.ln)(a.id),await v();let b=null;try{b=await (0,e.EI)(t,a.id,null)}catch(b){s.debug(`saveFlow: could not read previous definition of ${a.id} for versioning`,b)}b&&u(b)!==u(a)&&await n(b);let c=Date.now();a.createdAt=b?.createdAt??a.createdAt??c,a.updatedAt=c,await (0,e.Vt)(t,a.id,a);let d=this.flowsCache;if(d){let b=d.findIndex(b=>b.id===a.id);b>=0?d[b]=a:d.push(a),this.flowsCache=d}return await this.invalidateExecutionCache(a.id),s.info(`Flow ${a.id} saved successfully`),{success:!0}}catch(a){return s.error("Failed to save flow",a),{success:!1,error:a instanceof Error?a.message:"Failed to save flow"}}}async deleteFlow(a){try{s.debug(`Deleting flow: ${a}`),await v(),await (0,e.bB)(t,a);let b=this.flowsCache;return b&&(this.flowsCache=b.filter(b=>b.id!==a)),await this.invalidateExecutionCache(a),await r(a),s.info(`Flow ${a} deleted successfully`),{success:!0}}catch(b){return s.error(`Failed to delete flow: ${a}`,b),{success:!1,error:b instanceof Error?b.message:"Failed to delete flow"}}}async listFlowVersions(a){return p(a)}async getFlowVersion(a,b){return q(a,b)}async revertFlow(a,b){let c=await q(a,b);return c?this.saveFlow({...c.flow,id:a}):{success:!1,error:`No version "${b}" of flow ${a}`}}createNode(a,b){s.debug(`Creating new node of type: ${a}`,{position:b});let c={id:(0,d.A)(),type:a,position:b,data:{label:`${"mcp"===a?"MCP":a.charAt(0).toUpperCase()+a.slice(1)} Node`,type:a,properties:{}}};return s.debug(`Node created with ID: ${c.id}`),c}createNewFlow(a="NewFlow"){s.debug(`Creating new flow: ${a}`);let b={id:(0,d.A)(),type:"start",position:{x:250,y:150},data:{label:"Start Node",type:"start",properties:{promptTemplate:""}}},c=Date.now(),e={id:(0,d.A)(),name:a,createdAt:c,updatedAt:c,nodes:[b],edges:[]};return s.info(`New flow created with ID: ${e.id}`,{name:a}),e}createHistoryEntry(a,b){return s.debug("Creating history entry",{nodeCount:a.length,edgeCount:b.length}),{nodes:[...a],edges:[...b]}}generateSampleFlow(a="Sample Flow"){s.debug(`Generating sample flow: ${a}`);let b={id:(0,d.A)(),name:a,nodes:[{id:"1",type:"start",position:{x:250,y:50},data:{label:"Start Node",type:"start",properties:{prompt:"Enter your query here",systemMessage:"You are a helpful assistant",temperature:0}}},{id:"2",type:"process",position:{x:250,y:200},data:{label:"Process Node",type:"process",properties:{operation:"transform",enabled:!0}}},{id:"3",type:"finish",position:{x:250,y:350},data:{label:"Finish Node",type:"finish",properties:{format:"json",template:'{ "result": {{data}} }'}}},{id:"4",type:"mcp",position:{x:450,y:200},data:{label:"MCP Node",type:"mcp",properties:{channels:2,mode:"parallel"}}}],edges:[{id:"e1-2",source:"1",target:"2",type:"custom"},{id:"e2-3",source:"2",target:"3",type:"custom"}]};return s.info(`Sample flow generated with ID: ${b.id}`,{name:a}),b}async listFlows(){s.debug("listFlows: Entering method");try{let a=await this.loadFlows();return{success:!0,flows:a}}catch(a){return s.warn("listFlows: Failed to list flows:",a),{success:!1,error:a instanceof Error?a.message:"Failed to list flows"}}}}let x=new w}};
@@ -0,0 +1 @@
1
+ "use strict";exports.id=8216,exports.ids=[8216],exports.modules={354:(a,b,c)=>{c.d(b,{A:()=>f});var d=c(27080),e=c(21124);let f=(0,d.A)((0,e.jsx)("path",{d:"M20 6h-8l-2-2H7.17l4 4H20v9.17l1.76 1.76c.15-.28.24-.59.24-.93V8c0-1.1-.9-2-2-2M2.1 2.1.69 3.51l1.56 1.56c-.15.28-.24.59-.24.93L2 18c0 1.1.9 2 2 2h13.17l3.31 3.31 1.41-1.41zM4 18V6.83L15.17 18z"}),"FolderOffOutlined")},423:(a,b,c)=>{c.d(b,{A:()=>s});var d=c(38301),e=c(43249),f=c(2783),g=c(18168),h=c(68333),i=c(6636),j=c(29565),k=c(33105);function l(a){return(0,k.Ay)("MuiCardActionArea",a)}let m=(0,j.A)("MuiCardActionArea",["root","focusVisible","focusHighlight"]);var n=c(14328),o=c(20385),p=c(21124);let q=(0,g.Ay)(n.A,{name:"MuiCardActionArea",slot:"Root",overridesResolver:(a,b)=>b.root})((0,h.A)(({theme:a})=>({display:"block",textAlign:"inherit",borderRadius:"inherit",width:"100%",[`&:hover .${m.focusHighlight}`]:{opacity:(a.vars||a).palette.action.hoverOpacity,"@media (hover: none)":{opacity:0}},[`&.${m.focusVisible} .${m.focusHighlight}`]:{opacity:(a.vars||a).palette.action.focusOpacity}}))),r=(0,g.Ay)("span",{name:"MuiCardActionArea",slot:"FocusHighlight",overridesResolver:(a,b)=>b.focusHighlight})((0,h.A)(({theme:a})=>({overflow:"hidden",pointerEvents:"none",position:"absolute",top:0,right:0,bottom:0,left:0,borderRadius:"inherit",opacity:0,backgroundColor:"currentcolor",transition:a.transitions.create("opacity",{duration:a.transitions.duration.short})}))),s=d.forwardRef(function(a,b){let c=(0,i.b)({props:a,name:"MuiCardActionArea"}),{children:d,className:g,focusVisibleClassName:h,slots:j={},slotProps:k={},...m}=c,n=(a=>{let{classes:b}=a;return(0,f.A)({root:["root"],focusHighlight:["focusHighlight"]},l,b)})(c),s={slots:j,slotProps:k},[t,u]=(0,o.A)("root",{elementType:q,externalForwardedProps:{...s,...m},shouldForwardComponentProp:!0,ownerState:c,ref:b,className:(0,e.A)(n.root,g),additionalProps:{focusVisibleClassName:(0,e.A)(h,n.focusVisible)}}),[v,w]=(0,o.A)("focusHighlight",{elementType:r,externalForwardedProps:s,ownerState:c,ref:b,className:n.focusHighlight});return(0,p.jsxs)(t,{...u,children:[d,(0,p.jsx)(v,{...w})]})})},5501:(a,b,c)=>{c.d(b,{A:()=>f});var d=c(27080),e=c(21124);let f=(0,d.A)((0,e.jsx)("path",{d:"M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"}),"Star")},8165:(a,b,c)=>{c.d(b,{A:()=>f});var d=c(27080),e=c(21124);let f=(0,d.A)((0,e.jsx)("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-2 15-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8z"}),"CheckCircle")},12033:(a,b,c)=>{c.d(b,{A:()=>f});var d=c(27080),e=c(21124);let f=(0,d.A)((0,e.jsx)("path",{d:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.996.996 0 0 0-1.41 0l-1.83 1.83 3.75 3.75z"}),"Edit")},18467:(a,b,c)=>{c.d(b,{A:()=>f});var d=c(27080),e=c(21124);let f=(0,d.A)((0,e.jsx)("path",{d:"m9.17 6 2 2H20v10H4V6zM10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8z"}),"FolderOutlined")},27114:(a,b,c)=>{c.d(b,{A:()=>n});var d=c(38301),e=c(43249),f=c(2783),g=c(18168),h=c(6636),i=c(29565),j=c(33105);function k(a){return(0,j.Ay)("MuiCardContent",a)}(0,i.A)("MuiCardContent",["root"]);var l=c(21124);let m=(0,g.Ay)("div",{name:"MuiCardContent",slot:"Root",overridesResolver:(a,b)=>b.root})({padding:16,"&:last-child":{paddingBottom:24}}),n=d.forwardRef(function(a,b){let c=(0,h.b)({props:a,name:"MuiCardContent"}),{className:d,component:g="div",...i}=c,j={...c,component:g},n=(a=>{let{classes:b}=a;return(0,f.A)({root:["root"]},k,b)})(j);return(0,l.jsx)(m,{as:g,className:(0,e.A)(n.root,d),ownerState:j,ref:b,...i})})},30818:(a,b,c)=>{c.d(b,{A:()=>o});var d=c(38301),e=c(43249),f=c(2783),g=c(18168),h=c(6636),i=c(54573),j=c(29565),k=c(33105);function l(a){return(0,k.Ay)("MuiCard",a)}(0,j.A)("MuiCard",["root"]);var m=c(21124);let n=(0,g.Ay)(i.A,{name:"MuiCard",slot:"Root",overridesResolver:(a,b)=>b.root})({overflow:"hidden"}),o=d.forwardRef(function(a,b){let c=(0,h.b)({props:a,name:"MuiCard"}),{className:d,raised:g=!1,...i}=c,j={...c,raised:g},k=(a=>{let{classes:b}=a;return(0,f.A)({root:["root"]},l,b)})(j);return(0,m.jsx)(n,{className:(0,e.A)(k.root,d),elevation:g?8:void 0,ref:b,ownerState:j,...i})})},31973:(a,b,c)=>{c.d(b,{A:()=>f});var d=c(27080),e=c(21124);let f=(0,d.A)((0,e.jsx)("path",{d:"M20 6h-8l-2-2H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2m0 12H4V6h5.17l2 2H20zm-8-4h2v2h2v-2h2v-2h-2v-2h-2v2h-2z"}),"CreateNewFolderOutlined")},36698:(a,b,c)=>{c.d(b,{A:()=>f});var d=c(27080),e=c(21124);let f=(0,d.A)((0,e.jsx)("path",{d:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"}),"Check")},38313:(a,b,c)=>{c.d(b,{A:()=>g,f:()=>f});var d=c(29565),e=c(33105);function f(a){return(0,e.Ay)("MuiListItemIcon",a)}let g=(0,d.A)("MuiListItemIcon",["root","alignItemsFlexStart"])},40973:(a,b,c)=>{c.d(b,{A:()=>f});var d=c(27080),e=c(21124);let f=(0,d.A)((0,e.jsx)("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14"}),"Search")},50553:(a,b,c)=>{c.d(b,{A:()=>n});var d=c(38301),e=c(43249),f=c(2783),g=c(18168),h=c(68333),i=c(6636),j=c(38313),k=c(55470),l=c(21124);let m=(0,g.Ay)("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(a,b)=>{let{ownerState:c}=a;return[b.root,"flex-start"===c.alignItems&&b.alignItemsFlexStart]}})((0,h.A)(({theme:a})=>({minWidth:56,color:(a.vars||a).palette.action.active,flexShrink:0,display:"inline-flex",variants:[{props:{alignItems:"flex-start"},style:{marginTop:8}}]}))),n=d.forwardRef(function(a,b){let c=(0,i.b)({props:a,name:"MuiListItemIcon"}),{className:g,...h}=c,n=d.useContext(k.A),o={...c,alignItems:n.alignItems},p=(a=>{let{alignItems:b,classes:c}=a;return(0,f.A)({root:["root","flex-start"===b&&"alignItemsFlexStart"]},j.f,c)})(o);return(0,l.jsx)(m,{className:(0,e.A)(p.root,g),ownerState:o,ref:b,...h})})},76345:(a,b,c)=>{c.d(b,{A:()=>g,b:()=>f});var d=c(29565),e=c(33105);function f(a){return(0,e.Ay)("MuiListItemText",a)}let g=(0,d.A)("MuiListItemText",["root","multiline","dense","inset","primary","secondary"])},84233:(a,b,c)=>{c.d(b,{A:()=>p});var d=c(38301),e=c(43249),f=c(2783),g=c(29071),h=c(79515),i=c(55470),j=c(18168),k=c(6636),l=c(76345),m=c(20385),n=c(21124);let o=(0,j.Ay)("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(a,b)=>{let{ownerState:c}=a;return[{[`& .${l.A.primary}`]:b.primary},{[`& .${l.A.secondary}`]:b.secondary},b.root,c.inset&&b.inset,c.primary&&c.secondary&&b.multiline,c.dense&&b.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${g.A.root}:where(& .${l.A.primary})`]:{display:"block"},[`.${g.A.root}:where(& .${l.A.secondary})`]:{display:"block"},variants:[{props:({ownerState:a})=>a.primary&&a.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:a})=>a.inset,style:{paddingLeft:56}}]}),p=d.forwardRef(function(a,b){let c=(0,k.b)({props:a,name:"MuiListItemText"}),{children:g,className:j,disableTypography:p=!1,inset:q=!1,primary:r,primaryTypographyProps:s,secondary:t,secondaryTypographyProps:u,slots:v={},slotProps:w={},...x}=c,{dense:y}=d.useContext(i.A),z=null!=r?r:g,A=t,B={...c,disableTypography:p,inset:q,primary:!!z,secondary:!!A,dense:y},C=(a=>{let{classes:b,inset:c,primary:d,secondary:e,dense:g}=a;return(0,f.A)({root:["root",c&&"inset",g&&"dense",d&&e&&"multiline"],primary:["primary"],secondary:["secondary"]},l.b,b)})(B),D={slots:v,slotProps:{primary:s,secondary:u,...w}},[E,F]=(0,m.A)("root",{className:(0,e.A)(C.root,j),elementType:o,externalForwardedProps:{...D,...x},ownerState:B,ref:b}),[G,H]=(0,m.A)("primary",{className:C.primary,elementType:h.default,externalForwardedProps:D,ownerState:B}),[I,J]=(0,m.A)("secondary",{className:C.secondary,elementType:h.default,externalForwardedProps:D,ownerState:B});return null==z||z.type===h.default||p||(z=(0,n.jsx)(G,{variant:y?"body2":"body1",component:H?.variant?void 0:"span",...H,children:z})),null==A||A.type===h.default||p||(A=(0,n.jsx)(I,{variant:"body2",color:"textSecondary",...J,children:A})),(0,n.jsxs)(E,{...F,children:[z,A]})})},94367:(a,b,c)=>{c.d(b,{A:()=>y});var d=c(38301),e=c(43249),f=c(2783),g=c(37489),h=c(41126),i=c(18168),j=c(68333),k=c(6636),l=c(55470),m=c(14328),n=c(14758),o=c(26636),p=c(93895),q=c(38313),r=c(76345),s=c(29565),t=c(33105);function u(a){return(0,t.Ay)("MuiMenuItem",a)}let v=(0,s.A)("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]);var w=c(21124);let x=(0,i.Ay)(m.A,{shouldForwardProp:a=>(0,h.A)(a)||"classes"===a,name:"MuiMenuItem",slot:"Root",overridesResolver:(a,b)=>{let{ownerState:c}=a;return[b.root,c.dense&&b.dense,c.divider&&b.divider,!c.disableGutters&&b.gutters]}})((0,j.A)(({theme:a})=>({...a.typography.body1,display:"flex",justifyContent:"flex-start",alignItems:"center",position:"relative",textDecoration:"none",minHeight:48,paddingTop:6,paddingBottom:6,boxSizing:"border-box",whiteSpace:"nowrap","&:hover":{textDecoration:"none",backgroundColor:(a.vars||a).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${v.selected}`]:{backgroundColor:a.vars?`rgba(${a.vars.palette.primary.mainChannel} / ${a.vars.palette.action.selectedOpacity})`:(0,g.X4)(a.palette.primary.main,a.palette.action.selectedOpacity),[`&.${v.focusVisible}`]:{backgroundColor:a.vars?`rgba(${a.vars.palette.primary.mainChannel} / calc(${a.vars.palette.action.selectedOpacity} + ${a.vars.palette.action.focusOpacity}))`:(0,g.X4)(a.palette.primary.main,a.palette.action.selectedOpacity+a.palette.action.focusOpacity)}},[`&.${v.selected}:hover`]:{backgroundColor:a.vars?`rgba(${a.vars.palette.primary.mainChannel} / calc(${a.vars.palette.action.selectedOpacity} + ${a.vars.palette.action.hoverOpacity}))`:(0,g.X4)(a.palette.primary.main,a.palette.action.selectedOpacity+a.palette.action.hoverOpacity),"@media (hover: none)":{backgroundColor:a.vars?`rgba(${a.vars.palette.primary.mainChannel} / ${a.vars.palette.action.selectedOpacity})`:(0,g.X4)(a.palette.primary.main,a.palette.action.selectedOpacity)}},[`&.${v.focusVisible}`]:{backgroundColor:(a.vars||a).palette.action.focus},[`&.${v.disabled}`]:{opacity:(a.vars||a).palette.action.disabledOpacity},[`& + .${p.A.root}`]:{marginTop:a.spacing(1),marginBottom:a.spacing(1)},[`& + .${p.A.inset}`]:{marginLeft:52},[`& .${r.A.root}`]:{marginTop:0,marginBottom:0},[`& .${r.A.inset}`]:{paddingLeft:36},[`& .${q.A.root}`]:{minWidth:36},variants:[{props:({ownerState:a})=>!a.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:a})=>a.divider,style:{borderBottom:`1px solid ${(a.vars||a).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:a})=>!a.dense,style:{[a.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:a})=>a.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...a.typography.body2,[`& .${q.A.root} svg`]:{fontSize:"1.25rem"}}}]}))),y=d.forwardRef(function(a,b){let c,g=(0,k.b)({props:a,name:"MuiMenuItem"}),{autoFocus:h=!1,component:i="li",dense:j=!1,divider:m=!1,disableGutters:p=!1,focusVisibleClassName:q,role:r="menuitem",tabIndex:s,className:t,...v}=g,y=d.useContext(l.A),z=d.useMemo(()=>({dense:j||y.dense||!1,disableGutters:p}),[y.dense,j,p]),A=d.useRef(null);(0,n.A)(()=>{h&&A.current&&A.current.focus()},[h]);let B={...g,dense:z.dense,divider:m,disableGutters:p},C=(a=>{let{disabled:b,dense:c,divider:d,disableGutters:e,selected:g,classes:h}=a,i=(0,f.A)({root:["root",c&&"dense",b&&"disabled",!e&&"gutters",d&&"divider",g&&"selected"]},u,h);return{...h,...i}})(g),D=(0,o.A)(A,b);return g.disabled||(c=void 0!==s?s:-1),(0,w.jsx)(l.A.Provider,{value:z,children:(0,w.jsx)(x,{ref:D,role:r,tabIndex:c,component:i,focusVisibleClassName:(0,e.A)(C.focusVisible,q),className:(0,e.A)(C.root,t),...v,ownerState:B,classes:C})})})},98463:(a,b,c)=>{c.d(b,{A:()=>n});var d=c(38301),e=c(43249),f=c(2783),g=c(18168),h=c(6636),i=c(29565),j=c(33105);function k(a){return(0,j.Ay)("MuiCardActions",a)}(0,i.A)("MuiCardActions",["root","spacing"]);var l=c(21124);let m=(0,g.Ay)("div",{name:"MuiCardActions",slot:"Root",overridesResolver:(a,b)=>{let{ownerState:c}=a;return[b.root,!c.disableSpacing&&b.spacing]}})({display:"flex",alignItems:"center",padding:8,variants:[{props:{disableSpacing:!1},style:{"& > :not(style) ~ :not(style)":{marginLeft:8}}}]}),n=d.forwardRef(function(a,b){let c=(0,h.b)({props:a,name:"MuiCardActions"}),{disableSpacing:d=!1,className:g,...i}=c,j={...c,disableSpacing:d},n=(a=>{let{classes:b,disableSpacing:c}=a;return(0,f.A)({root:["root",!c&&"spacing"]},k,b)})(j);return(0,l.jsx)(m,{className:(0,e.A)(n.root,g),ownerState:j,ref:b,...i})})},99587:(a,b,c)=>{c.d(b,{A:()=>f});var d=c(27080),e=c(21124);let f=(0,d.A)((0,e.jsx)("path",{d:"m22 9.24-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28z"}),"StarBorder")}};
@@ -0,0 +1 @@
1
+ "use strict";exports.id=8387,exports.ids=[8387],exports.modules={18387:(a,b,c)=>{c.d(b,{filesystemCallTool:()=>D,filesystemToolDefinitions:()=>p});var d=c(33873),e=c.n(d),f=c(29021),g=c(50846),h=c(43326),i=c(7658);let j=(0,g.h)("backend/services/mcp/internal/filesystemTools");function k(a){return{content:[{type:"text",text:JSON.stringify(a,null,2)}],structuredContent:a}}function l(a){return{content:[{type:"text",text:JSON.stringify({error:a},null,2)}],isError:!0}}function m(a,b){let c=e().relative(a,b);return""===c||!c.startsWith("..")&&!e().isAbsolute(c)}async function n(){let a=function(){let a=process.env.FLUJO_FS_ROOTS;if(!a||!a.trim())return null;let b=a.split(e().delimiter).map(a=>a.trim()).filter(Boolean).map(a=>e().resolve(a));return b.length?b:null}(),b=[];try{b=(await (0,i.AC)(i.K3)).map(a=>e().resolve(a))}catch(a){j.warn("loadEffectiveRoots: could not read persisted roots",a)}if(!a)return b.length?b:null;let c=b.filter(b=>a.some(a=>m(a,b)));return c.length?c:a}function o(a,b){let c="string"==typeof a?a.trim():"";if(!c)throw Error('Provide "path".');let d=(0,h.ok)(),f=e().isAbsolute(c)?e().resolve(c):e().resolve(d,c);if(b&&!b.some(a=>m(a,f)))throw Error(`Path "${f}" is outside the configured filesystem roots.`);return f}function p(){let a={type:"string",description:"File or directory path. Relative paths resolve against the FLUJO data directory; absolute paths are used as-is."};return[{name:"read_file",description:'Read a text file and return its content. Optionally read only a line range with "from"/"to" (1-based, inclusive). Returns { path, from, to, totalLines, content, truncated }.',inputSchema:{type:"object",properties:{path:a,from:{type:"number",description:"Optional 1-based first line to return (inclusive)."},to:{type:"number",description:"Optional 1-based last line to return (inclusive)."}},required:["path"]},outputSchema:{type:"object",properties:{path:{type:"string"},from:{type:"number"},to:{type:"number"},totalLines:{type:"number"},truncated:{type:"boolean"},content:{type:"string"}},required:["path","from","to","totalLines","truncated","content"]}},{name:"write_file",description:'Create or write a text file (parent directories are created). "mode": "overwrite" (default) replaces the whole file, or a line range when "startLine"/"endLine" (1-based inclusive) are given; "append" adds content at the end; "insert" inserts content before "startLine". Returns { path, bytesWritten, mode, ... }.',inputSchema:{type:"object",properties:{path:a,content:{type:"string",description:"The content to write/insert/append."},mode:{type:"string",enum:["overwrite","append","insert"],description:'Write mode (default "overwrite").'},startLine:{type:"number",description:'For "insert": line to insert before. For "overwrite": first line of the range to replace (1-based).'},endLine:{type:"number",description:'For "overwrite": last line (inclusive, 1-based) of the range to replace.'}},required:["path","content"]},outputSchema:{type:"object",properties:{path:{type:"string"},bytesWritten:{type:"number"},mode:{type:"string"},startLine:{type:"number"},endLine:{type:"number"},linesReplaced:{type:"number"},linesInserted:{type:"number"}},required:["path","bytesWritten","mode"]}},{name:"edit_file",description:'Edit a text file two ways (mutually exclusive): (1) "edits": [{ oldText, newText, startLine?, endLine? }] literal find/replace — each replaces the first (unambiguous) occurrence, optionally scoped to a line range; or (2) "diff": a unified diff string (standard "@@ -a,b +c,d @@" hunks) applied atomically. Fails with no partial write on any mismatch. Returns { path, editsApplied|applied, diff:{added,removed} }.',inputSchema:{type:"object",properties:{path:a,edits:{type:"array",description:"List of literal { oldText, newText } edits applied in order (optionally scoped with startLine/endLine).",items:{type:"object",properties:{oldText:{type:"string",description:"Exact text to find."},newText:{type:"string",description:"Replacement text."},startLine:{type:"number",description:"Optional 1-based first line to scope this edit to."},endLine:{type:"number",description:"Optional 1-based last line (inclusive) to scope this edit to."}},required:["oldText","newText"]}},diff:{type:"string",description:'A unified diff to apply atomically. Mutually exclusive with "edits".'},startLine:{type:"number",description:"Optional default 1-based first line to scope all literal edits to."},endLine:{type:"number",description:"Optional default 1-based last line (inclusive) to scope all literal edits to."}},required:["path"]},outputSchema:{type:"object",properties:{path:{type:"string"},mode:{type:"string"},editsApplied:{type:"number"},applied:{type:"boolean"},diff:{type:"object",properties:{added:{type:"number"},removed:{type:"number"}},required:["added","removed"]}},required:["path","diff"]}},{name:"list_dir",description:'List the entries of a directory. Returns { path, entries: [{ name, type, size }] } where type is "file" | "directory" | "other".',inputSchema:{type:"object",properties:{path:a},required:["path"]},outputSchema:{type:"object",properties:{path:{type:"string"},entries:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"},size:{type:"number"}},required:["name","type","size"]}}},required:["path","entries"]}},{name:"dir_tree",description:"Return a recursive, depth-limited directory tree as nested JSON. Returns { path, depth, tree }.",inputSchema:{type:"object",properties:{path:a,depth:{type:"number",description:"Maximum recursion depth (default 3, max 10)."}},required:["path"]},outputSchema:{type:"object",properties:{path:{type:"string"},depth:{type:"number"},truncated:{type:"boolean"},tree:{type:"array"}},required:["path","depth","tree"]}},{name:"search",description:'Search a directory tree. Match file/dir NAMES against "namePattern" (substring, case-insensitive) and/or file CONTENT against "content" (substring). Returns { matches: [{ path, line?, text? }], truncated }.',inputSchema:{type:"object",properties:{path:a,namePattern:{type:"string",description:"Optional case-insensitive substring to match against entry names."},content:{type:"string",description:"Optional case-insensitive substring to match inside text files."}},required:["path"]},outputSchema:{type:"object",properties:{matches:{type:"array",items:{type:"object",properties:{path:{type:"string"},line:{type:"number"},text:{type:"string"}},required:["path"]}},truncated:{type:"boolean"}},required:["matches","truncated"]}},{name:"get_file_info",description:"Stat a path. Returns { path, type, size, isFile, isDirectory, createdAt, modifiedAt }.",inputSchema:{type:"object",properties:{path:a},required:["path"]},outputSchema:{type:"object",properties:{path:{type:"string"},type:{type:"string"},size:{type:"number"},isFile:{type:"boolean"},isDirectory:{type:"boolean"},createdAt:{type:"string"},modifiedAt:{type:"string"}},required:["path","type","size","isFile","isDirectory","createdAt","modifiedAt"]}},{name:"create_directory",description:"Create a directory (recursively). Succeeds if it already exists. Returns { path, created }.",inputSchema:{type:"object",properties:{path:a},required:["path"]},outputSchema:{type:"object",properties:{path:{type:"string"},created:{type:"boolean"}},required:["path","created"]}},{name:"move",description:'Move or rename a file/directory from "source" to "destination". Returns { source, destination }.',inputSchema:{type:"object",properties:{source:{type:"string",description:"Existing path to move."},destination:{type:"string",description:"Target path."}},required:["source","destination"]},outputSchema:{type:"object",properties:{source:{type:"string"},destination:{type:"string"}},required:["source","destination"]}},{name:"delete",description:'Delete a file or directory. Pass "recursive": true to remove a non-empty directory. Returns { path, deleted }.',inputSchema:{type:"object",properties:{path:a,recursive:{type:"boolean",description:"Remove directories and their contents recursively."}},required:["path"]},outputSchema:{type:"object",properties:{path:{type:"string"},deleted:{type:"boolean"}},required:["path","deleted"]}}]}function q(a){return a.replace(/\r\n?/g,"\n").split("\n")}function r(a){return a.includes("\r\n")?"\r\n":"\n"}async function s(a,b){let c=o(a.path,b),d=await f.promises.readFile(c,"utf8"),e=q(d),g=e.length,h="number"==typeof a.from||"number"==typeof a.to,i="number"==typeof a.from?Math.max(1,Math.floor(a.from)):1,j="number"==typeof a.to?Math.floor(a.to):g;j<i&&([i,j]=[j,i]),j=Math.min(j,g);let l=h?e.slice(i-1,j).join("\n"):d,m=!1;return l.length>2e5&&(l=l.slice(0,2e5)+"\n…[truncated]",m=!0),k({path:c,from:h?i:1,to:h?j:g,totalLines:g,truncated:m,content:l})}async function t(a,b){let c=o(a.path,b),d="string"==typeof a.content?a.content:"",g="append"===a.mode||"insert"===a.mode?a.mode:"overwrite",h="number"==typeof a.startLine||"number"==typeof a.endLine;if(await f.promises.mkdir(e().dirname(c),{recursive:!0}),"overwrite"===g&&!h)return await f.promises.writeFile(c,d,"utf8"),k({path:c,bytesWritten:Buffer.byteLength(d,"utf8"),mode:"overwrite"});let i="";try{i=await f.promises.readFile(c,"utf8")}catch{i=""}if("append"===g){let a=!i.length||i.endsWith("\n")||i.endsWith("\r\n")?"":r(i),b=i+a+d;return await f.promises.writeFile(c,b,"utf8"),k({path:c,bytesWritten:Buffer.byteLength(b,"utf8"),mode:"append"})}let j=r(i),l=i.length?i.split(/\r?\n/):[],m=d.split(/\r?\n/),n=l.length;if("insert"===g){let b="number"==typeof a.startLine?Math.max(1,Math.floor(a.startLine)):n+1,d=Math.min(b-1,n);l.splice(d,0,...m);let e=l.join(j);return await f.promises.writeFile(c,e,"utf8"),k({path:c,bytesWritten:Buffer.byteLength(e,"utf8"),mode:"insert",startLine:b,linesInserted:m.length})}let p="number"==typeof a.startLine?Math.max(1,Math.floor(a.startLine)):1,q="number"==typeof a.endLine?Math.floor(a.endLine):p;q<p&&([p,q]=[q,p]);let s=Math.max(0,(q=Math.min(q,n))-p+1);l.splice(p-1,s,...m);let t=l.join(j);return await f.promises.writeFile(c,t,"utf8"),k({path:c,bytesWritten:Buffer.byteLength(t,"utf8"),mode:"overwrite",startLine:p,endLine:q,linesReplaced:s})}async function u(a,b){let c=o(a.path,b),d="string"==typeof a.diff&&a.diff.trim().length>0,e=Array.isArray(a.edits)&&a.edits.length>0;if(d&&e)return l('Provide either "diff" or "edits", not both.');let g=await f.promises.readFile(c,"utf8");if(d){let b;try{b=function(a,b){let c=a.split("\n"),d=b.split(/\r?\n/),e=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/,f=[],g=0,h=0,i=0,j=!1,k=0;for(;k<d.length;){let a=d[k];if(void 0===a)break;if(a.startsWith("--- ")||a.startsWith("+++ ")){k++;continue}let b=e.exec(a);if(!b){k++;continue}j=!0;let l=Math.max(0,parseInt(b[1],10)-1);if(l<g)throw Error("overlapping or out-of-order hunks");for(;g<l&&g<c.length;)f.push(c[g]),g++;for(k++;k<d.length&&!e.test(d[k])&&!d[k].startsWith("--- ");){let a=d[k],b=a.length?a[0]:" ",e=a.length?a.slice(1):"";if(" "===b){let a=c[g];if(a!==e)throw Error(`context mismatch at line ${g+1}: expected ${JSON.stringify(a)}, diff has ${JSON.stringify(e)}`);f.push(c[g]),g++}else if("-"===b){let a=c[g];if(a!==e)throw Error(`removed-line mismatch at line ${g+1}: expected ${JSON.stringify(a)}, diff has ${JSON.stringify(e)}`);g++,i++}else if("+"===b)f.push(e),h++;else if("\\"===b);else throw Error(`unexpected diff line: ${JSON.stringify(a)}`);k++}}if(!j)throw Error("no unified-diff hunks (@@ ... @@) found");for(;g<c.length;)f.push(c[g]),g++;return{result:f.join("\n"),added:h,removed:i}}(g,a.diff)}catch(a){return l(`Diff apply failed: ${a instanceof Error?a.message:String(a)}. No changes written.`)}return await f.promises.writeFile(c,b.result,"utf8"),k({path:c,applied:!0,mode:"diff",diff:{added:b.added,removed:b.removed}})}let h=Array.isArray(a.edits)?a.edits:[];if(0===h.length)return l('Provide a non-empty "edits" array of { oldText, newText } or a "diff" string.');let i="number"==typeof a.startLine?a.startLine:void 0,j="number"==typeof a.endLine?a.endLine:void 0,m=g,n=0;for(let a of h){let b="string"==typeof a.oldText?a.oldText:"",d="string"==typeof a.newText?a.newText:"";if(!b)return l(`Edit #${n+1} has an empty "oldText".`);let e="number"==typeof a.startLine?a.startLine:i,f="number"==typeof a.endLine?a.endLine:j,g=void 0!==e||void 0!==f,{lo:h,hi:k}=function(a,b,c){if(void 0===b&&void 0===c)return{lo:0,hi:a.length};let d=a.split("\n"),e=Math.max(1,Math.floor(b??1)),f=Math.min(d.length,Math.floor(c??d.length)),g=0;for(let a=0;a<e-1&&a<d.length;a++)g+=d[a].length+1;let h=g;for(let a=e-1;a<f&&a<d.length;a++)h+=d[a].length+ +(a<d.length-1);return{lo:g,hi:Math.max(g,h)}}(m,e,f),o=m.indexOf(b,h);if(-1===o||o>=k||o+b.length>k)return l(`Edit #${n+1}: "oldText" not found${g?" in the specified line range":""} in ${c}. No changes written.`);let p=m.indexOf(b,o+1);if(-1!==p&&p<k&&p+b.length<=k)return l(`Edit #${n+1}: "oldText" is ambiguous (appears more than once${g?" in the specified line range":""}). No changes written.`);m=m.slice(0,o)+d+m.slice(o+b.length),n+=1}return await f.promises.writeFile(c,m,"utf8"),k({path:c,mode:"edits",editsApplied:n,diff:function(a,b){let c=q(a),d=q(b),e=new Map;for(let a of d)e.set(a,(e.get(a)??0)+1);let f=new Map;for(let a of c)f.set(a,(f.get(a)??0)+1);let g=0;for(let[a,b]of f)g+=Math.max(0,b-(e.get(a)??0));let h=0;for(let[a,b]of e)h+=Math.max(0,b-(f.get(a)??0));return{added:h,removed:g}}(g,m)})}async function v(a){try{let b=await f.promises.lstat(a);if(b.isFile())return"file";if(b.isDirectory())return"directory";return"other"}catch{return"other"}}async function w(a,b){let c=o(a.path,b),d=await f.promises.readdir(c),g=await Promise.all(d.map(async a=>{let b=e().join(c,a),d=await v(b),g=0;try{g=(await f.promises.stat(b)).size}catch{}return{name:a,type:d,size:g}}));return g.sort((a,b)=>a.type===b.type?a.name.localeCompare(b.name):"directory"===a.type?-1:1),k({path:c,entries:g})}async function x(a,b){let c=o(a.path,b),d=Math.min("number"==typeof a.depth?Math.max(1,Math.floor(a.depth)):3,10),g=0,h=!1;async function i(a,b){let c;if(b>d||h)return[];try{c=await f.promises.readdir(a)}catch{return[]}c.sort((a,b)=>a.localeCompare(b));let j=[];for(let f of c){if(++g>5e3){h=!0;break}let c=e().join(a,f),k=await v(c),l={name:f,type:k};"directory"===k&&b<d&&(l.children=await i(c,b+1)),j.push(l)}return j}let j=await i(c,1);return k({path:c,depth:d,truncated:h,tree:j})}async function y(a,b){let c=o(a.path,b),d="string"==typeof a.namePattern?a.namePattern.toLowerCase():"",g="string"==typeof a.content?a.content.toLowerCase():"";if(!d&&!g)return l('Provide "namePattern" and/or "content" to search for.');let h=[],i=!1;async function j(a){let b;if(!i){try{b=await f.promises.readdir(a)}catch{return}for(let c of b){if(i)return;let b=e().join(a,c),k=await v(b);if(d&&c.toLowerCase().includes(d)&&(h.push({path:b}),h.length>=1e3)){i=!0;return}if("directory"===k)await j(b);else if("file"===k&&g){let a="";try{a=await f.promises.readFile(b,"utf8")}catch{continue}let c=a.split("\n");for(let a=0;a<c.length;a++)if(c[a].toLowerCase().includes(g)&&(h.push({path:b,line:a+1,text:c[a].slice(0,400)}),h.length>=1e3)){i=!0;return}}}}}return await j(c),k({matches:h,truncated:i})}async function z(a,b){let c=o(a.path,b),d=await f.promises.stat(c);return k({path:c,type:d.isFile()?"file":d.isDirectory()?"directory":"other",size:d.size,isFile:d.isFile(),isDirectory:d.isDirectory(),createdAt:d.birthtime.toISOString(),modifiedAt:d.mtime.toISOString()})}async function A(a,b){let c=o(a.path,b);return await f.promises.mkdir(c,{recursive:!0}),k({path:c,created:!0})}async function B(a,b){let c=o(a.source,b),d=o(a.destination,b);return await f.promises.mkdir(e().dirname(d),{recursive:!0}),await f.promises.rename(c,d),k({source:c,destination:d})}async function C(a,b){let c=o(a.path,b),d=!0===a.recursive;return await f.promises.rm(c,{recursive:d,force:!1}),k({path:c,deleted:!0})}async function D(a,b){try{let c=await n();switch(a){case"read_file":return await s(b,c);case"write_file":return await t(b,c);case"edit_file":return await u(b,c);case"list_dir":return await w(b,c);case"dir_tree":return await x(b,c);case"search":return await y(b,c);case"get_file_info":return await z(b,c);case"create_directory":return await A(b,c);case"move":return await B(b,c);case"delete":return await C(b,c);default:return l(`Unknown tool on the built-in filesystem server: ${a}`)}}catch(b){return j.warn("filesystemCallTool failed",{toolName:a,err:b}),function(a,b=!1){return{content:[{type:"text",text:a}],...b?{isError:!0}:{}}}(`Tool failed: ${b instanceof Error?b.message:String(b)}`,!0)}}}};