n8n 2.15.1 → 2.17.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 (615) hide show
  1. package/README.md +1 -1
  2. package/dist/active-workflow-manager.d.ts +3 -1
  3. package/dist/active-workflow-manager.js +62 -16
  4. package/dist/active-workflow-manager.js.map +1 -1
  5. package/dist/auth/auth.service.d.ts +5 -2
  6. package/dist/auth/auth.service.js +11 -6
  7. package/dist/auth/auth.service.js.map +1 -1
  8. package/dist/build.tsbuildinfo +1 -1
  9. package/dist/commands/base-command.js +13 -1
  10. package/dist/commands/base-command.js.map +1 -1
  11. package/dist/commands/start.d.ts +1 -0
  12. package/dist/commands/start.js +7 -0
  13. package/dist/commands/start.js.map +1 -1
  14. package/dist/constants.d.ts +2 -0
  15. package/dist/constants.js +5 -1
  16. package/dist/constants.js.map +1 -1
  17. package/dist/controllers/ai.controller.d.ts +11 -2
  18. package/dist/controllers/ai.controller.js +56 -4
  19. package/dist/controllers/ai.controller.js.map +1 -1
  20. package/dist/controllers/auth.controller.js +1 -1
  21. package/dist/controllers/auth.controller.js.map +1 -1
  22. package/dist/controllers/e2e.controller.js +5 -0
  23. package/dist/controllers/e2e.controller.js.map +1 -1
  24. package/dist/controllers/me.controller.d.ts +1 -0
  25. package/dist/controllers/me.controller.js +12 -0
  26. package/dist/controllers/me.controller.js.map +1 -1
  27. package/dist/controllers/project.controller.d.ts +3 -1
  28. package/dist/controllers/project.controller.js +9 -2
  29. package/dist/controllers/project.controller.js.map +1 -1
  30. package/dist/controllers/role.controller.d.ts +6 -4
  31. package/dist/controllers/role.controller.js +28 -8
  32. package/dist/controllers/role.controller.js.map +1 -1
  33. package/dist/controllers/users.controller.d.ts +4 -1
  34. package/dist/controllers/users.controller.js +8 -2
  35. package/dist/controllers/users.controller.js.map +1 -1
  36. package/dist/credentials/credentials.controller.js +4 -1
  37. package/dist/credentials/credentials.controller.js.map +1 -1
  38. package/dist/credentials/credentials.service.d.ts +10 -6
  39. package/dist/credentials/credentials.service.js +98 -26
  40. package/dist/credentials/credentials.service.js.map +1 -1
  41. package/dist/credentials/validation.js +2 -2
  42. package/dist/credentials/validation.js.map +1 -1
  43. package/dist/credentials-helper.d.ts +3 -1
  44. package/dist/credentials-helper.js +21 -3
  45. package/dist/credentials-helper.js.map +1 -1
  46. package/dist/errors/http-error-classifier.d.ts +31 -0
  47. package/dist/errors/http-error-classifier.js +60 -0
  48. package/dist/errors/http-error-classifier.js.map +1 -0
  49. package/dist/errors/http-error-serializers.d.ts +18 -0
  50. package/dist/errors/http-error-serializers.js +64 -0
  51. package/dist/errors/http-error-serializers.js.map +1 -0
  52. package/dist/eventbus/event-message-classes/index.d.ts +2 -2
  53. package/dist/eventbus/event-message-classes/index.js +10 -0
  54. package/dist/eventbus/event-message-classes/index.js.map +1 -1
  55. package/dist/events/maps/relay.event-map.d.ts +114 -0
  56. package/dist/events/relays/log-streaming.event-relay.d.ts +10 -0
  57. package/dist/events/relays/log-streaming.event-relay.js +108 -2
  58. package/dist/events/relays/log-streaming.event-relay.js.map +1 -1
  59. package/dist/events/relays/telemetry.event-relay.d.ts +5 -0
  60. package/dist/events/relays/telemetry.event-relay.js +58 -5
  61. package/dist/events/relays/telemetry.event-relay.js.map +1 -1
  62. package/dist/execution-lifecycle/execution-lifecycle-hooks.d.ts +1 -1
  63. package/dist/execution-lifecycle/execution-lifecycle-hooks.js +24 -9
  64. package/dist/execution-lifecycle/execution-lifecycle-hooks.js.map +1 -1
  65. package/dist/executions/execution.service.js +2 -1
  66. package/dist/executions/execution.service.js.map +1 -1
  67. package/dist/instance-settings-loader/instance-settings-loader.service.d.ts +9 -0
  68. package/dist/instance-settings-loader/instance-settings-loader.service.js +36 -0
  69. package/dist/instance-settings-loader/instance-settings-loader.service.js.map +1 -0
  70. package/dist/instance-settings-loader/loaders/owner.instance-settings-loader.d.ts +10 -0
  71. package/dist/instance-settings-loader/loaders/owner.instance-settings-loader.js +72 -0
  72. package/dist/instance-settings-loader/loaders/owner.instance-settings-loader.js.map +1 -0
  73. package/dist/modules/chat-hub/chat-hub-workflow.service.d.ts +1 -0
  74. package/dist/modules/chat-hub/chat-hub-workflow.service.js +18 -2
  75. package/dist/modules/chat-hub/chat-hub-workflow.service.js.map +1 -1
  76. package/dist/modules/chat-hub/chat-hub.types.d.ts +5 -0
  77. package/dist/modules/chat-hub/chat-hub.types.js +1 -0
  78. package/dist/modules/chat-hub/chat-hub.types.js.map +1 -1
  79. package/dist/modules/chat-hub/context-limits.js +10 -0
  80. package/dist/modules/chat-hub/context-limits.js.map +1 -1
  81. package/dist/modules/chat-hub/stream-capturer.js +3 -0
  82. package/dist/modules/chat-hub/stream-capturer.js.map +1 -1
  83. package/dist/modules/community-packages/community-node-types-utils.d.ts +2 -2
  84. package/dist/modules/community-packages/community-node-types-utils.js +4 -4
  85. package/dist/modules/community-packages/community-node-types-utils.js.map +1 -1
  86. package/dist/modules/community-packages/strapi-utils.d.ts +1 -1
  87. package/dist/modules/data-table/data-table-proxy.service.d.ts +44 -2
  88. package/dist/modules/data-table/data-table-proxy.service.js +86 -2
  89. package/dist/modules/data-table/data-table-proxy.service.js.map +1 -1
  90. package/dist/modules/dynamic-credentials.ee/credential-resolvers/identifiers/oauth2-introspection-identifier.d.ts +2 -2
  91. package/dist/modules/dynamic-credentials.ee/services/resolver-config-expression.service.js +10 -4
  92. package/dist/modules/dynamic-credentials.ee/services/resolver-config-expression.service.js.map +1 -1
  93. package/dist/modules/external-secrets.ee/external-secrets-settings.controller.ee.d.ts +5 -2
  94. package/dist/modules/external-secrets.ee/external-secrets-settings.controller.ee.js +10 -3
  95. package/dist/modules/external-secrets.ee/external-secrets-settings.controller.ee.js.map +1 -1
  96. package/dist/modules/external-secrets.ee/secrets-providers-connections.controller.ee.js +5 -5
  97. package/dist/modules/external-secrets.ee/secrets-providers-connections.controller.ee.js.map +1 -1
  98. package/dist/modules/external-secrets.ee/secrets-providers-connections.service.ee.d.ts +6 -6
  99. package/dist/modules/external-secrets.ee/secrets-providers-connections.service.ee.js +14 -9
  100. package/dist/modules/external-secrets.ee/secrets-providers-connections.service.ee.js.map +1 -1
  101. package/dist/modules/external-secrets.ee/secrets-providers-project.controller.ee.js +3 -3
  102. package/dist/modules/external-secrets.ee/secrets-providers-project.controller.ee.js.map +1 -1
  103. package/dist/modules/instance-ai/compaction.service.d.ts +19 -0
  104. package/dist/modules/instance-ai/compaction.service.js +213 -0
  105. package/dist/modules/instance-ai/compaction.service.js.map +1 -0
  106. package/dist/modules/instance-ai/entities/index.d.ts +7 -0
  107. package/dist/modules/instance-ai/entities/index.js +18 -0
  108. package/dist/modules/instance-ai/entities/index.js.map +1 -0
  109. package/dist/modules/instance-ai/entities/instance-ai-iteration-log.entity.d.ts +7 -0
  110. package/dist/modules/instance-ai/entities/instance-ai-iteration-log.entity.js +38 -0
  111. package/dist/modules/instance-ai/entities/instance-ai-iteration-log.entity.js.map +1 -0
  112. package/dist/modules/instance-ai/entities/instance-ai-message.entity.d.ts +9 -0
  113. package/dist/modules/instance-ai/entities/instance-ai-message.entity.js +47 -0
  114. package/dist/modules/instance-ai/entities/instance-ai-message.entity.js.map +1 -0
  115. package/dist/modules/instance-ai/entities/instance-ai-observational-memory.entity.d.ts +33 -0
  116. package/dist/modules/instance-ai/entities/instance-ai-observational-memory.entity.js +145 -0
  117. package/dist/modules/instance-ai/entities/instance-ai-observational-memory.entity.js.map +1 -0
  118. package/dist/modules/instance-ai/entities/instance-ai-resource.entity.d.ts +6 -0
  119. package/dist/modules/instance-ai/entities/instance-ai-resource.entity.js +33 -0
  120. package/dist/modules/instance-ai/entities/instance-ai-resource.entity.js.map +1 -0
  121. package/dist/modules/instance-ai/entities/instance-ai-run-snapshot.entity.d.ts +8 -0
  122. package/dist/modules/instance-ai/entities/instance-ai-run-snapshot.entity.js +43 -0
  123. package/dist/modules/instance-ai/entities/instance-ai-run-snapshot.entity.js.map +1 -0
  124. package/dist/modules/instance-ai/entities/instance-ai-thread.entity.d.ts +7 -0
  125. package/dist/modules/instance-ai/entities/instance-ai-thread.entity.js +38 -0
  126. package/dist/modules/instance-ai/entities/instance-ai-thread.entity.js.map +1 -0
  127. package/dist/modules/instance-ai/entities/instance-ai-workflow-snapshot.entity.d.ts +8 -0
  128. package/dist/modules/instance-ai/entities/instance-ai-workflow-snapshot.entity.js +41 -0
  129. package/dist/modules/instance-ai/entities/instance-ai-workflow-snapshot.entity.js.map +1 -0
  130. package/dist/modules/instance-ai/eval/api-docs.d.ts +1 -0
  131. package/dist/modules/instance-ai/eval/api-docs.js +78 -0
  132. package/dist/modules/instance-ai/eval/api-docs.js.map +1 -0
  133. package/dist/modules/instance-ai/eval/execution.service.d.ts +25 -0
  134. package/dist/modules/instance-ai/eval/execution.service.js +291 -0
  135. package/dist/modules/instance-ai/eval/execution.service.js.map +1 -0
  136. package/dist/modules/instance-ai/eval/mock-handler.d.ts +9 -0
  137. package/dist/modules/instance-ai/eval/mock-handler.js +264 -0
  138. package/dist/modules/instance-ai/eval/mock-handler.js.map +1 -0
  139. package/dist/modules/instance-ai/eval/node-config.d.ts +2 -0
  140. package/dist/modules/instance-ai/eval/node-config.js +15 -0
  141. package/dist/modules/instance-ai/eval/node-config.js.map +1 -0
  142. package/dist/modules/instance-ai/eval/pin-data-generator.d.ts +12 -0
  143. package/dist/modules/instance-ai/eval/pin-data-generator.js +301 -0
  144. package/dist/modules/instance-ai/eval/pin-data-generator.js.map +1 -0
  145. package/dist/modules/instance-ai/eval/request-sanitizer.d.ts +3 -0
  146. package/dist/modules/instance-ai/eval/request-sanitizer.js +50 -0
  147. package/dist/modules/instance-ai/eval/request-sanitizer.js.map +1 -0
  148. package/dist/modules/instance-ai/eval/workflow-analysis.d.ts +16 -0
  149. package/dist/modules/instance-ai/eval/workflow-analysis.js +217 -0
  150. package/dist/modules/instance-ai/eval/workflow-analysis.js.map +1 -0
  151. package/dist/modules/instance-ai/event-bus/in-process-event-bus.d.ts +19 -0
  152. package/dist/modules/instance-ai/event-bus/in-process-event-bus.js +98 -0
  153. package/dist/modules/instance-ai/event-bus/in-process-event-bus.js.map +1 -0
  154. package/dist/modules/instance-ai/filesystem/index.d.ts +3 -0
  155. package/dist/modules/instance-ai/filesystem/index.js +8 -0
  156. package/dist/modules/instance-ai/filesystem/index.js.map +1 -0
  157. package/dist/modules/instance-ai/filesystem/local-gateway-registry.d.ts +29 -0
  158. package/dist/modules/instance-ai/filesystem/local-gateway-registry.js +137 -0
  159. package/dist/modules/instance-ai/filesystem/local-gateway-registry.js.map +1 -0
  160. package/dist/modules/instance-ai/filesystem/local-gateway.d.ts +35 -0
  161. package/dist/modules/instance-ai/filesystem/local-gateway.js +99 -0
  162. package/dist/modules/instance-ai/filesystem/local-gateway.js.map +1 -0
  163. package/dist/modules/instance-ai/instance-ai-memory.service.d.ts +40 -0
  164. package/dist/modules/instance-ai/instance-ai-memory.service.js +245 -0
  165. package/dist/modules/instance-ai/instance-ai-memory.service.js.map +1 -0
  166. package/dist/modules/instance-ai/instance-ai-settings.service.d.ts +59 -0
  167. package/dist/modules/instance-ai/instance-ai-settings.service.js +450 -0
  168. package/dist/modules/instance-ai/instance-ai-settings.service.js.map +1 -0
  169. package/dist/modules/instance-ai/instance-ai.adapter.service.d.ts +91 -0
  170. package/dist/modules/instance-ai/instance-ai.adapter.service.js +1885 -0
  171. package/dist/modules/instance-ai/instance-ai.adapter.service.js.map +1 -0
  172. package/dist/modules/instance-ai/instance-ai.controller.d.ts +101 -0
  173. package/dist/modules/instance-ai/instance-ai.controller.js +670 -0
  174. package/dist/modules/instance-ai/instance-ai.controller.js.map +1 -0
  175. package/dist/modules/instance-ai/instance-ai.module.d.ts +12 -0
  176. package/dist/modules/instance-ai/instance-ai.module.js +118 -0
  177. package/dist/modules/instance-ai/instance-ai.module.js.map +1 -0
  178. package/dist/modules/instance-ai/instance-ai.service.d.ts +133 -0
  179. package/dist/modules/instance-ai/instance-ai.service.js +1802 -0
  180. package/dist/modules/instance-ai/instance-ai.service.js.map +1 -0
  181. package/dist/modules/instance-ai/internal-messages.d.ts +2 -0
  182. package/dist/modules/instance-ai/internal-messages.js +11 -0
  183. package/dist/modules/instance-ai/internal-messages.js.map +1 -0
  184. package/dist/modules/instance-ai/message-parser.d.ts +12 -0
  185. package/dist/modules/instance-ai/message-parser.js +171 -0
  186. package/dist/modules/instance-ai/message-parser.js.map +1 -0
  187. package/dist/modules/instance-ai/node-definition-resolver.d.ts +19 -0
  188. package/dist/modules/instance-ai/node-definition-resolver.js +290 -0
  189. package/dist/modules/instance-ai/node-definition-resolver.js.map +1 -0
  190. package/dist/modules/instance-ai/proxy-token-manager.d.ts +15 -0
  191. package/dist/modules/instance-ai/proxy-token-manager.js +64 -0
  192. package/dist/modules/instance-ai/proxy-token-manager.js.map +1 -0
  193. package/dist/modules/instance-ai/repositories/index.d.ts +7 -0
  194. package/dist/modules/instance-ai/repositories/index.js +18 -0
  195. package/dist/modules/instance-ai/repositories/index.js.map +1 -0
  196. package/dist/modules/instance-ai/repositories/instance-ai-iteration-log.repository.d.ts +5 -0
  197. package/dist/modules/instance-ai/repositories/instance-ai-iteration-log.repository.js +26 -0
  198. package/dist/modules/instance-ai/repositories/instance-ai-iteration-log.repository.js.map +1 -0
  199. package/dist/modules/instance-ai/repositories/instance-ai-message.repository.d.ts +5 -0
  200. package/dist/modules/instance-ai/repositories/instance-ai-message.repository.js +26 -0
  201. package/dist/modules/instance-ai/repositories/instance-ai-message.repository.js.map +1 -0
  202. package/dist/modules/instance-ai/repositories/instance-ai-observational-memory.repository.d.ts +5 -0
  203. package/dist/modules/instance-ai/repositories/instance-ai-observational-memory.repository.js +26 -0
  204. package/dist/modules/instance-ai/repositories/instance-ai-observational-memory.repository.js.map +1 -0
  205. package/dist/modules/instance-ai/repositories/instance-ai-resource.repository.d.ts +5 -0
  206. package/dist/modules/instance-ai/repositories/instance-ai-resource.repository.js +26 -0
  207. package/dist/modules/instance-ai/repositories/instance-ai-resource.repository.js.map +1 -0
  208. package/dist/modules/instance-ai/repositories/instance-ai-run-snapshot.repository.d.ts +5 -0
  209. package/dist/modules/instance-ai/repositories/instance-ai-run-snapshot.repository.js +26 -0
  210. package/dist/modules/instance-ai/repositories/instance-ai-run-snapshot.repository.js.map +1 -0
  211. package/dist/modules/instance-ai/repositories/instance-ai-thread.repository.d.ts +5 -0
  212. package/dist/modules/instance-ai/repositories/instance-ai-thread.repository.js +26 -0
  213. package/dist/modules/instance-ai/repositories/instance-ai-thread.repository.js.map +1 -0
  214. package/dist/modules/instance-ai/repositories/instance-ai-workflow-snapshot.repository.d.ts +5 -0
  215. package/dist/modules/instance-ai/repositories/instance-ai-workflow-snapshot.repository.js +26 -0
  216. package/dist/modules/instance-ai/repositories/instance-ai-workflow-snapshot.repository.js.map +1 -0
  217. package/dist/modules/instance-ai/snapshot-pruning.service.d.ts +17 -0
  218. package/dist/modules/instance-ai/snapshot-pruning.service.js +89 -0
  219. package/dist/modules/instance-ai/snapshot-pruning.service.js.map +1 -0
  220. package/dist/modules/instance-ai/storage/db-iteration-log-storage.d.ts +9 -0
  221. package/dist/modules/instance-ai/storage/db-iteration-log-storage.js +45 -0
  222. package/dist/modules/instance-ai/storage/db-iteration-log-storage.js.map +1 -0
  223. package/dist/modules/instance-ai/storage/db-snapshot-storage.d.ts +14 -0
  224. package/dist/modules/instance-ai/storage/db-snapshot-storage.js +99 -0
  225. package/dist/modules/instance-ai/storage/db-snapshot-storage.js.map +1 -0
  226. package/dist/modules/instance-ai/storage/index.d.ts +5 -0
  227. package/dist/modules/instance-ai/storage/index.js +14 -0
  228. package/dist/modules/instance-ai/storage/index.js.map +1 -0
  229. package/dist/modules/instance-ai/storage/typeorm-composite-store.d.ts +9 -0
  230. package/dist/modules/instance-ai/storage/typeorm-composite-store.js +33 -0
  231. package/dist/modules/instance-ai/storage/typeorm-composite-store.js.map +1 -0
  232. package/dist/modules/instance-ai/storage/typeorm-memory-storage.d.ts +96 -0
  233. package/dist/modules/instance-ai/storage/typeorm-memory-storage.js +853 -0
  234. package/dist/modules/instance-ai/storage/typeorm-memory-storage.js.map +1 -0
  235. package/dist/modules/instance-ai/storage/typeorm-workflows-storage.d.ts +44 -0
  236. package/dist/modules/instance-ai/storage/typeorm-workflows-storage.js +156 -0
  237. package/dist/modules/instance-ai/storage/typeorm-workflows-storage.js.map +1 -0
  238. package/dist/modules/instance-ai/web-research/brave-search.d.ts +10 -0
  239. package/dist/modules/instance-ai/web-research/brave-search.js +44 -0
  240. package/dist/modules/instance-ai/web-research/brave-search.js.map +1 -0
  241. package/dist/modules/instance-ai/web-research/cache.d.ts +13 -0
  242. package/dist/modules/instance-ai/web-research/cache.js +43 -0
  243. package/dist/modules/instance-ai/web-research/cache.js.map +1 -0
  244. package/dist/modules/instance-ai/web-research/fetch-and-extract.d.ts +8 -0
  245. package/dist/modules/instance-ai/web-research/fetch-and-extract.js +231 -0
  246. package/dist/modules/instance-ai/web-research/fetch-and-extract.js.map +1 -0
  247. package/dist/modules/instance-ai/web-research/index.d.ts +7 -0
  248. package/dist/modules/instance-ai/web-research/index.js +16 -0
  249. package/dist/modules/instance-ai/web-research/index.js.map +1 -0
  250. package/dist/modules/instance-ai/web-research/searxng-search.d.ts +6 -0
  251. package/dist/modules/instance-ai/web-research/searxng-search.js +39 -0
  252. package/dist/modules/instance-ai/web-research/searxng-search.js.map +1 -0
  253. package/dist/modules/instance-ai/web-research/ssrf-guard.d.ts +1 -0
  254. package/dist/modules/instance-ai/web-research/ssrf-guard.js +85 -0
  255. package/dist/modules/instance-ai/web-research/ssrf-guard.js.map +1 -0
  256. package/dist/modules/instance-ai/web-research/summarize-content.d.ts +4 -0
  257. package/dist/modules/instance-ai/web-research/summarize-content.js +34 -0
  258. package/dist/modules/instance-ai/web-research/summarize-content.js.map +1 -0
  259. package/dist/modules/instance-registry/instance-registry.types.d.ts +1 -0
  260. package/dist/modules/instance-registry/instance-registry.types.js +2 -1
  261. package/dist/modules/instance-registry/instance-registry.types.js.map +1 -1
  262. package/dist/modules/instance-registry/storage/instance-storage.interface.d.ts +1 -0
  263. package/dist/modules/instance-registry/storage/lua-scripts.d.ts +4 -0
  264. package/dist/modules/instance-registry/storage/lua-scripts.js +39 -0
  265. package/dist/modules/instance-registry/storage/lua-scripts.js.map +1 -0
  266. package/dist/modules/instance-registry/storage/memory-storage.d.ts +1 -0
  267. package/dist/modules/instance-registry/storage/memory-storage.js +1 -0
  268. package/dist/modules/instance-registry/storage/memory-storage.js.map +1 -1
  269. package/dist/modules/instance-registry/storage/redis-instance-storage.d.ts +25 -0
  270. package/dist/modules/instance-registry/storage/redis-instance-storage.js +185 -0
  271. package/dist/modules/instance-registry/storage/redis-instance-storage.js.map +1 -0
  272. package/dist/modules/instance-version-history/database/entities/instance-version-history.entity.d.ts +7 -0
  273. package/dist/modules/instance-version-history/database/entities/instance-version-history.entity.js +37 -0
  274. package/dist/modules/instance-version-history/database/entities/instance-version-history.entity.js.map +1 -0
  275. package/dist/modules/instance-version-history/database/repositories/instance-version-history.repository.d.ts +5 -0
  276. package/dist/modules/instance-version-history/database/repositories/instance-version-history.repository.js +26 -0
  277. package/dist/modules/instance-version-history/database/repositories/instance-version-history.repository.js.map +1 -0
  278. package/dist/modules/instance-version-history/instance-version-history.controller.d.ts +26 -0
  279. package/dist/modules/instance-version-history/instance-version-history.controller.js +85 -0
  280. package/dist/modules/instance-version-history/instance-version-history.controller.js.map +1 -0
  281. package/dist/modules/instance-version-history/instance-version-history.module.d.ts +5 -0
  282. package/dist/modules/instance-version-history/instance-version-history.module.js +60 -0
  283. package/dist/modules/instance-version-history/instance-version-history.module.js.map +1 -0
  284. package/dist/modules/instance-version-history/instance-version-history.service.d.ts +18 -0
  285. package/dist/modules/instance-version-history/instance-version-history.service.js +120 -0
  286. package/dist/modules/instance-version-history/instance-version-history.service.js.map +1 -0
  287. package/dist/modules/instance-version-history/instance-version-history.types.d.ts +12 -0
  288. package/dist/modules/instance-version-history/instance-version-history.types.js +27 -0
  289. package/dist/modules/instance-version-history/instance-version-history.types.js.map +1 -0
  290. package/dist/modules/log-streaming.ee/log-streaming.controller.js.map +1 -1
  291. package/dist/modules/mcp/mcp.service.d.ts +3 -1
  292. package/dist/modules/mcp/mcp.service.js +22 -3
  293. package/dist/modules/mcp/mcp.service.js.map +1 -1
  294. package/dist/modules/mcp/mcp.types.d.ts +1 -1
  295. package/dist/modules/mcp/tools/data-table/add-data-table-column.tool.d.ts +13 -0
  296. package/dist/modules/mcp/tools/data-table/add-data-table-column.tool.js +69 -0
  297. package/dist/modules/mcp/tools/data-table/add-data-table-column.tool.js.map +1 -0
  298. package/dist/modules/mcp/tools/data-table/add-data-table-rows.tool.d.ts +12 -0
  299. package/dist/modules/mcp/tools/data-table/add-data-table-rows.tool.js +77 -0
  300. package/dist/modules/mcp/tools/data-table/add-data-table-rows.tool.js.map +1 -0
  301. package/dist/modules/mcp/tools/data-table/create-data-table.tool.d.ts +21 -0
  302. package/dist/modules/mcp/tools/data-table/create-data-table.tool.js +92 -0
  303. package/dist/modules/mcp/tools/data-table/create-data-table.tool.js.map +1 -0
  304. package/dist/modules/mcp/tools/data-table/delete-data-table-column.tool.d.ts +12 -0
  305. package/dist/modules/mcp/tools/data-table/delete-data-table-column.tool.js +60 -0
  306. package/dist/modules/mcp/tools/data-table/delete-data-table-column.tool.js.map +1 -0
  307. package/dist/modules/mcp/tools/data-table/index.d.ts +7 -0
  308. package/dist/modules/mcp/tools/data-table/index.js +18 -0
  309. package/dist/modules/mcp/tools/data-table/index.js.map +1 -0
  310. package/dist/modules/mcp/tools/data-table/rename-data-table-column.tool.d.ts +13 -0
  311. package/dist/modules/mcp/tools/data-table/rename-data-table-column.tool.js +70 -0
  312. package/dist/modules/mcp/tools/data-table/rename-data-table-column.tool.js.map +1 -0
  313. package/dist/modules/mcp/tools/data-table/rename-data-table.tool.d.ts +12 -0
  314. package/dist/modules/mcp/tools/data-table/rename-data-table.tool.js +60 -0
  315. package/dist/modules/mcp/tools/data-table/rename-data-table.tool.js.map +1 -0
  316. package/dist/modules/mcp/tools/data-table/search-data-tables.tool.d.ts +12 -0
  317. package/dist/modules/mcp/tools/data-table/search-data-tables.tool.js +93 -0
  318. package/dist/modules/mcp/tools/data-table/search-data-tables.tool.js.map +1 -0
  319. package/dist/modules/mcp/tools/execute-workflow.tool.d.ts +3 -4
  320. package/dist/modules/mcp/tools/execute-workflow.tool.js +10 -25
  321. package/dist/modules/mcp/tools/execute-workflow.tool.js.map +1 -1
  322. package/dist/modules/mcp/tools/get-execution.tool.js +4 -8
  323. package/dist/modules/mcp/tools/get-execution.tool.js.map +1 -1
  324. package/dist/modules/mcp/tools/schemas.d.ts +73 -2
  325. package/dist/modules/mcp/tools/schemas.js +41 -1
  326. package/dist/modules/mcp/tools/schemas.js.map +1 -1
  327. package/dist/modules/mcp/tools/search-folders.tool.js +2 -7
  328. package/dist/modules/mcp/tools/search-folders.tool.js.map +1 -1
  329. package/dist/modules/mcp/tools/search-projects.tool.js +2 -7
  330. package/dist/modules/mcp/tools/search-projects.tool.js.map +1 -1
  331. package/dist/modules/mcp/tools/search-workflows.tool.js +2 -7
  332. package/dist/modules/mcp/tools/search-workflows.tool.js.map +1 -1
  333. package/dist/modules/mcp/tools/workflow-builder/get-suggested-workflow-nodes.tool.js +1 -37
  334. package/dist/modules/mcp/tools/workflow-builder/get-suggested-workflow-nodes.tool.js.map +1 -1
  335. package/dist/modules/mcp/tools/workflow-builder/get-workflow-node-types.tool.js +1 -37
  336. package/dist/modules/mcp/tools/workflow-builder/get-workflow-node-types.tool.js.map +1 -1
  337. package/dist/modules/mcp/tools/workflow-builder/search-workflow-nodes.tool.js +1 -37
  338. package/dist/modules/mcp/tools/workflow-builder/search-workflow-nodes.tool.js.map +1 -1
  339. package/dist/modules/mcp/tools/workflow-builder/workflow-builder-tools.service.d.ts +17 -0
  340. package/dist/modules/mcp/tools/workflow-builder/workflow-builder-tools.service.js +48 -0
  341. package/dist/modules/mcp/tools/workflow-builder/workflow-builder-tools.service.js.map +1 -1
  342. package/dist/modules/otel/handlers/node-end.handler.d.ts +8 -0
  343. package/dist/modules/otel/handlers/node-end.handler.js +71 -0
  344. package/dist/modules/otel/handlers/node-end.handler.js.map +1 -0
  345. package/dist/modules/otel/handlers/node-start.handler.d.ts +7 -0
  346. package/dist/modules/otel/handlers/node-start.handler.js +37 -0
  347. package/dist/modules/otel/handlers/node-start.handler.js.map +1 -0
  348. package/dist/modules/otel/handlers/workflow-end.handler.d.ts +1 -0
  349. package/dist/modules/otel/handlers/workflow-end.handler.js +8 -0
  350. package/dist/modules/otel/handlers/workflow-end.handler.js.map +1 -1
  351. package/dist/modules/otel/n8n-instrumentation.d.ts +8 -2
  352. package/dist/modules/otel/n8n-instrumentation.js +32 -1
  353. package/dist/modules/otel/n8n-instrumentation.js.map +1 -1
  354. package/dist/modules/otel/otel.config.d.ts +1 -0
  355. package/dist/modules/otel/otel.config.js +5 -0
  356. package/dist/modules/otel/otel.config.js.map +1 -1
  357. package/dist/modules/otel/otel.constants.d.ts +7 -0
  358. package/dist/modules/otel/otel.constants.js +7 -0
  359. package/dist/modules/otel/otel.constants.js.map +1 -1
  360. package/dist/modules/otel/otel.service.d.ts +1 -1
  361. package/dist/modules/otel/otel.service.js +20 -23
  362. package/dist/modules/otel/otel.service.js.map +1 -1
  363. package/dist/modules/otel/span-registry.d.ts +1 -0
  364. package/dist/modules/otel/span-registry.js +11 -0
  365. package/dist/modules/otel/span-registry.js.map +1 -1
  366. package/dist/modules/provisioning.ee/provisioning.service.ee.d.ts +17 -3
  367. package/dist/modules/provisioning.ee/provisioning.service.ee.js +195 -8
  368. package/dist/modules/provisioning.ee/provisioning.service.ee.js.map +1 -1
  369. package/dist/modules/provisioning.ee/role-mapping-rule.controller.ee.d.ts +7 -5
  370. package/dist/modules/provisioning.ee/role-mapping-rule.controller.ee.js +40 -10
  371. package/dist/modules/provisioning.ee/role-mapping-rule.controller.ee.js.map +1 -1
  372. package/dist/modules/provisioning.ee/role-mapping-rule.service.ee.d.ts +3 -1
  373. package/dist/modules/provisioning.ee/role-mapping-rule.service.ee.js +1 -0
  374. package/dist/modules/provisioning.ee/role-mapping-rule.service.ee.js.map +1 -1
  375. package/dist/modules/provisioning.ee/role-resolver-types.d.ts +14 -2
  376. package/dist/modules/provisioning.ee/role-resolver.service.ee.js +16 -6
  377. package/dist/modules/provisioning.ee/role-resolver.service.ee.js.map +1 -1
  378. package/dist/modules/redaction/executions/execution-redaction.service.d.ts +3 -2
  379. package/dist/modules/redaction/executions/execution-redaction.service.js +5 -1
  380. package/dist/modules/redaction/executions/execution-redaction.service.js.map +1 -1
  381. package/dist/modules/redaction/redaction.module.js +0 -6
  382. package/dist/modules/redaction/redaction.module.js.map +1 -1
  383. package/dist/modules/source-control.ee/source-control-context.factory.d.ts +12 -0
  384. package/dist/modules/source-control.ee/source-control-context.factory.js +112 -0
  385. package/dist/modules/source-control.ee/source-control-context.factory.js.map +1 -0
  386. package/dist/modules/source-control.ee/source-control-export.service.ee.d.ts +2 -2
  387. package/dist/modules/source-control.ee/source-control-export.service.ee.js +9 -11
  388. package/dist/modules/source-control.ee/source-control-export.service.ee.js.map +1 -1
  389. package/dist/modules/source-control.ee/source-control-git.service.ee.js +3 -3
  390. package/dist/modules/source-control.ee/source-control-git.service.ee.js.map +1 -1
  391. package/dist/modules/source-control.ee/source-control-import.service.ee.d.ts +6 -4
  392. package/dist/modules/source-control.ee/source-control-import.service.ee.js +29 -85
  393. package/dist/modules/source-control.ee/source-control-import.service.ee.js.map +1 -1
  394. package/dist/modules/source-control.ee/source-control-scoped.service.d.ts +4 -4
  395. package/dist/modules/source-control.ee/source-control-scoped.service.js +9 -40
  396. package/dist/modules/source-control.ee/source-control-scoped.service.js.map +1 -1
  397. package/dist/modules/source-control.ee/source-control-status.service.ee.d.ts +3 -1
  398. package/dist/modules/source-control.ee/source-control-status.service.ee.js +99 -59
  399. package/dist/modules/source-control.ee/source-control-status.service.ee.js.map +1 -1
  400. package/dist/modules/source-control.ee/source-control.service.ee.d.ts +3 -1
  401. package/dist/modules/source-control.ee/source-control.service.ee.js +6 -4
  402. package/dist/modules/source-control.ee/source-control.service.ee.js.map +1 -1
  403. package/dist/modules/source-control.ee/types/source-control-context.d.ts +12 -4
  404. package/dist/modules/source-control.ee/types/source-control-context.js +32 -6
  405. package/dist/modules/source-control.ee/types/source-control-context.js.map +1 -1
  406. package/dist/modules/sso-oidc/oidc.controller.ee.d.ts +4 -1
  407. package/dist/modules/sso-oidc/oidc.controller.ee.js +39 -3
  408. package/dist/modules/sso-oidc/oidc.controller.ee.js.map +1 -1
  409. package/dist/modules/sso-oidc/oidc.service.ee.d.ts +14 -2
  410. package/dist/modules/sso-oidc/oidc.service.ee.js +86 -8
  411. package/dist/modules/sso-oidc/oidc.service.ee.js.map +1 -1
  412. package/dist/modules/sso-oidc/views/oidc-test-result.d.ts +5 -0
  413. package/dist/modules/sso-oidc/views/oidc-test-result.js +58 -0
  414. package/dist/modules/sso-oidc/views/oidc-test-result.js.map +1 -0
  415. package/dist/modules/sso-saml/saml-helpers.d.ts +1 -0
  416. package/dist/modules/sso-saml/saml-helpers.js +2 -0
  417. package/dist/modules/sso-saml/saml-helpers.js.map +1 -1
  418. package/dist/modules/sso-saml/saml.controller.ee.d.ts +2 -3
  419. package/dist/modules/sso-saml/saml.controller.ee.js +3 -15
  420. package/dist/modules/sso-saml/saml.controller.ee.js.map +1 -1
  421. package/dist/modules/sso-saml/saml.service.ee.d.ts +4 -1
  422. package/dist/modules/sso-saml/saml.service.ee.js +13 -7
  423. package/dist/modules/sso-saml/saml.service.ee.js.map +1 -1
  424. package/dist/modules/token-exchange/controllers/embed-auth.controller.d.ts +19 -0
  425. package/dist/modules/token-exchange/controllers/embed-auth.controller.js +106 -0
  426. package/dist/modules/token-exchange/controllers/embed-auth.controller.js.map +1 -0
  427. package/dist/modules/token-exchange/controllers/token-exchange.controller.d.ts +9 -0
  428. package/dist/modules/token-exchange/controllers/token-exchange.controller.js +148 -0
  429. package/dist/modules/token-exchange/controllers/token-exchange.controller.js.map +1 -0
  430. package/dist/modules/token-exchange/database/entities/token-exchange-jti.entity.d.ts +5 -0
  431. package/dist/modules/token-exchange/database/entities/token-exchange-jti.entity.js +33 -0
  432. package/dist/modules/token-exchange/database/entities/token-exchange-jti.entity.js.map +1 -0
  433. package/dist/modules/token-exchange/database/entities/trusted-key-source.entity.d.ts +10 -0
  434. package/dist/modules/token-exchange/database/entities/trusted-key-source.entity.js +45 -0
  435. package/dist/modules/token-exchange/database/entities/trusted-key-source.entity.js.map +1 -0
  436. package/dist/modules/token-exchange/database/entities/trusted-key.entity.d.ts +9 -0
  437. package/dist/modules/token-exchange/database/entities/trusted-key.entity.js +43 -0
  438. package/dist/modules/token-exchange/database/entities/trusted-key.entity.js.map +1 -0
  439. package/dist/modules/token-exchange/database/repositories/token-exchange-jti.repository.d.ts +10 -0
  440. package/dist/modules/token-exchange/database/repositories/token-exchange-jti.repository.js +106 -0
  441. package/dist/modules/token-exchange/database/repositories/token-exchange-jti.repository.js.map +1 -0
  442. package/dist/modules/token-exchange/database/repositories/trusted-key-source.repository.d.ts +5 -0
  443. package/dist/modules/token-exchange/database/repositories/trusted-key-source.repository.js +26 -0
  444. package/dist/modules/token-exchange/database/repositories/trusted-key-source.repository.js.map +1 -0
  445. package/dist/modules/token-exchange/database/repositories/trusted-key.repository.d.ts +7 -0
  446. package/dist/modules/token-exchange/database/repositories/trusted-key.repository.js +32 -0
  447. package/dist/modules/token-exchange/database/repositories/trusted-key.repository.js.map +1 -0
  448. package/dist/modules/token-exchange/services/identity-resolution.service.d.ts +23 -0
  449. package/dist/modules/token-exchange/services/identity-resolution.service.js +195 -0
  450. package/dist/modules/token-exchange/services/identity-resolution.service.js.map +1 -0
  451. package/dist/modules/token-exchange/services/jti-cleanup.service.d.ts +18 -0
  452. package/dist/modules/token-exchange/services/jti-cleanup.service.js +90 -0
  453. package/dist/modules/token-exchange/services/jti-cleanup.service.js.map +1 -0
  454. package/dist/modules/token-exchange/services/jti-store.service.d.ts +6 -0
  455. package/dist/modules/token-exchange/services/jti-store.service.js +30 -0
  456. package/dist/modules/token-exchange/services/jti-store.service.js.map +1 -0
  457. package/dist/modules/token-exchange/services/jwks-resolver.d.ts +30 -0
  458. package/dist/modules/token-exchange/services/jwks-resolver.js +190 -0
  459. package/dist/modules/token-exchange/services/jwks-resolver.js.map +1 -0
  460. package/dist/modules/token-exchange/services/scoped-jwt.strategy.d.ts +12 -0
  461. package/dist/modules/token-exchange/services/scoped-jwt.strategy.js +92 -0
  462. package/dist/modules/token-exchange/services/scoped-jwt.strategy.js.map +1 -0
  463. package/dist/modules/token-exchange/services/token-exchange.service.d.ts +31 -0
  464. package/dist/modules/token-exchange/services/token-exchange.service.js +152 -0
  465. package/dist/modules/token-exchange/services/token-exchange.service.js.map +1 -0
  466. package/dist/modules/token-exchange/services/trusted-key.service.d.ts +47 -0
  467. package/dist/modules/token-exchange/services/trusted-key.service.js +465 -0
  468. package/dist/modules/token-exchange/services/trusted-key.service.js.map +1 -0
  469. package/dist/modules/token-exchange/token-exchange.config.d.ts +11 -0
  470. package/dist/modules/token-exchange/token-exchange.config.js +67 -0
  471. package/dist/modules/token-exchange/token-exchange.config.js.map +1 -0
  472. package/dist/modules/token-exchange/token-exchange.module.d.ts +5 -0
  473. package/dist/modules/token-exchange/token-exchange.module.js +79 -0
  474. package/dist/modules/token-exchange/token-exchange.module.js.map +1 -0
  475. package/dist/modules/token-exchange/token-exchange.schemas.d.ts +161 -0
  476. package/dist/modules/token-exchange/token-exchange.schemas.js +69 -0
  477. package/dist/modules/token-exchange/token-exchange.schemas.js.map +1 -0
  478. package/dist/modules/token-exchange/token-exchange.types.d.ts +53 -0
  479. package/dist/modules/token-exchange/token-exchange.types.js +5 -0
  480. package/dist/modules/token-exchange/token-exchange.types.js.map +1 -0
  481. package/dist/oauth/oauth.service.d.ts +1 -0
  482. package/dist/oauth/oauth.service.js +39 -2
  483. package/dist/oauth/oauth.service.js.map +1 -1
  484. package/dist/public-api/index.js +37 -9
  485. package/dist/public-api/index.js.map +1 -1
  486. package/dist/public-api/types.d.ts +28 -1
  487. package/dist/public-api/v1/handlers/community-packages/community-packages.handler.d.ts +19 -0
  488. package/dist/public-api/v1/handlers/community-packages/community-packages.handler.js +71 -0
  489. package/dist/public-api/v1/handlers/community-packages/community-packages.handler.js.map +1 -0
  490. package/dist/public-api/v1/handlers/community-packages/community-packages.mapper.d.ts +27 -0
  491. package/dist/public-api/v1/handlers/community-packages/community-packages.mapper.js +35 -0
  492. package/dist/public-api/v1/handlers/community-packages/community-packages.mapper.js.map +1 -0
  493. package/dist/public-api/v1/handlers/credentials/credentials.handler.js +7 -12
  494. package/dist/public-api/v1/handlers/credentials/credentials.handler.js.map +1 -1
  495. package/dist/public-api/v1/handlers/credentials/credentials.service.d.ts +3 -4
  496. package/dist/public-api/v1/handlers/credentials/credentials.service.js +21 -33
  497. package/dist/public-api/v1/handlers/credentials/credentials.service.js.map +1 -1
  498. package/dist/public-api/v1/handlers/data-tables/data-tables.handler.js +5 -5
  499. package/dist/public-api/v1/handlers/data-tables/data-tables.rows.handler.js +5 -5
  500. package/dist/public-api/v1/handlers/executions/executions.handler.js +56 -12
  501. package/dist/public-api/v1/handlers/executions/executions.handler.js.map +1 -1
  502. package/dist/public-api/v1/handlers/insights/insights.handler.d.ts +6 -0
  503. package/dist/public-api/v1/handlers/insights/insights.handler.js +57 -0
  504. package/dist/public-api/v1/handlers/insights/insights.handler.js.map +1 -0
  505. package/dist/public-api/v1/handlers/workflows/workflows.handler.js +14 -35
  506. package/dist/public-api/v1/handlers/workflows/workflows.handler.js.map +1 -1
  507. package/dist/public-api/v1/handlers/workflows/workflows.service.d.ts +6 -4
  508. package/dist/public-api/v1/handlers/workflows/workflows.service.js +7 -15
  509. package/dist/public-api/v1/handlers/workflows/workflows.service.js.map +1 -1
  510. package/dist/public-api/v1/openapi.yml +530 -9
  511. package/dist/public-api/v1/public-api-error-response.d.ts +2 -0
  512. package/dist/public-api/v1/public-api-error-response.js +11 -0
  513. package/dist/public-api/v1/public-api-error-response.js.map +1 -0
  514. package/dist/public-api/v1/shared/middlewares/global.middleware.d.ts +1 -1
  515. package/dist/public-api/v1/shared/middlewares/global.middleware.js +19 -8
  516. package/dist/public-api/v1/shared/middlewares/global.middleware.js.map +1 -1
  517. package/dist/push/abstract.push.d.ts +1 -0
  518. package/dist/push/abstract.push.js +3 -0
  519. package/dist/push/abstract.push.js.map +1 -1
  520. package/dist/push/sse.push.js +5 -1
  521. package/dist/push/sse.push.js.map +1 -1
  522. package/dist/push/websocket.push.js +3 -1
  523. package/dist/push/websocket.push.js.map +1 -1
  524. package/dist/response-helper.js +6 -29
  525. package/dist/response-helper.js.map +1 -1
  526. package/dist/scaling/pubsub/subscriber.service.d.ts +2 -0
  527. package/dist/scaling/pubsub/subscriber.service.js +17 -8
  528. package/dist/scaling/pubsub/subscriber.service.js.map +1 -1
  529. package/dist/scaling/redis/redis.types.d.ts +1 -1
  530. package/dist/security-audit/risk-reporters/credentials-risk-reporter.d.ts +2 -3
  531. package/dist/security-audit/risk-reporters/credentials-risk-reporter.js +2 -5
  532. package/dist/security-audit/risk-reporters/credentials-risk-reporter.js.map +1 -1
  533. package/dist/services/ai-gateway.service.d.ts +44 -0
  534. package/dist/services/ai-gateway.service.js +228 -0
  535. package/dist/services/ai-gateway.service.js.map +1 -0
  536. package/dist/services/ai-workflow-builder.service.d.ts +2 -2
  537. package/dist/services/ai-workflow-builder.service.js +4 -4
  538. package/dist/services/ai-workflow-builder.service.js.map +1 -1
  539. package/dist/services/ai.service.d.ts +4 -0
  540. package/dist/services/ai.service.js +20 -18
  541. package/dist/services/ai.service.js.map +1 -1
  542. package/dist/services/api-key-auth.strategy.d.ts +10 -0
  543. package/dist/services/api-key-auth.strategy.js +71 -0
  544. package/dist/services/api-key-auth.strategy.js.map +1 -0
  545. package/dist/services/auth-strategy.registry.d.ts +7 -0
  546. package/dist/services/auth-strategy.registry.js +32 -0
  547. package/dist/services/auth-strategy.registry.js.map +1 -0
  548. package/dist/services/auth-strategy.types.d.ts +4 -0
  549. package/dist/services/auth-strategy.types.js +3 -0
  550. package/dist/services/auth-strategy.types.js.map +1 -0
  551. package/dist/services/credentials-tester.service.js +2 -0
  552. package/dist/services/credentials-tester.service.js.map +1 -1
  553. package/dist/services/db-clock.service.d.ts +10 -0
  554. package/dist/services/db-clock.service.js +48 -0
  555. package/dist/services/db-clock.service.js.map +1 -0
  556. package/dist/services/frontend.service.js +9 -0
  557. package/dist/services/frontend.service.js.map +1 -1
  558. package/dist/services/import.service.d.ts +1 -0
  559. package/dist/services/import.service.js +25 -2
  560. package/dist/services/import.service.js.map +1 -1
  561. package/dist/services/ownership.service.d.ts +4 -1
  562. package/dist/services/ownership.service.js +11 -5
  563. package/dist/services/ownership.service.js.map +1 -1
  564. package/dist/services/project.service.ee.js +1 -1
  565. package/dist/services/project.service.ee.js.map +1 -1
  566. package/dist/services/pruning/workflow-history-compaction.service.js +4 -4
  567. package/dist/services/pruning/workflow-history-compaction.service.js.map +1 -1
  568. package/dist/services/public-api-key.service.d.ts +6 -13
  569. package/dist/services/public-api-key.service.js +12 -80
  570. package/dist/services/public-api-key.service.js.map +1 -1
  571. package/dist/services/user.service.js +6 -0
  572. package/dist/services/user.service.js.map +1 -1
  573. package/dist/utils/validate-redirect-url.d.ts +1 -0
  574. package/dist/utils/validate-redirect-url.js +17 -0
  575. package/dist/utils/validate-redirect-url.js.map +1 -0
  576. package/dist/wait-tracker.d.ts +6 -2
  577. package/dist/wait-tracker.js +94 -63
  578. package/dist/wait-tracker.js.map +1 -1
  579. package/dist/webhooks/live-webhooks.js +24 -18
  580. package/dist/webhooks/live-webhooks.js.map +1 -1
  581. package/dist/webhooks/test-webhooks.js +96 -78
  582. package/dist/webhooks/test-webhooks.js.map +1 -1
  583. package/dist/webhooks/waiting-webhooks.js +27 -21
  584. package/dist/webhooks/waiting-webhooks.js.map +1 -1
  585. package/dist/webhooks/webhook-form-data.js +6 -2
  586. package/dist/webhooks/webhook-form-data.js.map +1 -1
  587. package/dist/webhooks/webhook-helpers.js +21 -6
  588. package/dist/webhooks/webhook-helpers.js.map +1 -1
  589. package/dist/webhooks/webhook-last-node-response-extractor.d.ts +5 -2
  590. package/dist/webhooks/webhook-last-node-response-extractor.js +5 -8
  591. package/dist/webhooks/webhook-last-node-response-extractor.js.map +1 -1
  592. package/dist/webhooks/webhook.service.js +19 -4
  593. package/dist/webhooks/webhook.service.js.map +1 -1
  594. package/dist/workflow-execute-additional-data.js +2 -0
  595. package/dist/workflow-execute-additional-data.js.map +1 -1
  596. package/dist/workflow-helpers.d.ts +1 -0
  597. package/dist/workflow-helpers.js +21 -0
  598. package/dist/workflow-helpers.js.map +1 -1
  599. package/dist/workflow-runner.js +25 -1
  600. package/dist/workflow-runner.js.map +1 -1
  601. package/dist/workflows/workflow-creation.service.d.ts +8 -5
  602. package/dist/workflows/workflow-creation.service.js +40 -17
  603. package/dist/workflows/workflow-creation.service.js.map +1 -1
  604. package/dist/workflows/workflow-execution.service.js +1 -1
  605. package/dist/workflows/workflow-execution.service.js.map +1 -1
  606. package/dist/workflows/workflow-history/workflow-history.service.js +1 -0
  607. package/dist/workflows/workflow-history/workflow-history.service.js.map +1 -1
  608. package/dist/workflows/workflow-validation.service.js +3 -3
  609. package/dist/workflows/workflow-validation.service.js.map +1 -1
  610. package/dist/workflows/workflow.service.ee.js +4 -1
  611. package/dist/workflows/workflow.service.ee.js.map +1 -1
  612. package/dist/workflows/workflow.service.js +16 -2
  613. package/dist/workflows/workflow.service.js.map +1 -1
  614. package/dist/workflows/workflows.controller.d.ts +4 -4
  615. package/package.json +32 -30
@@ -0,0 +1,1802 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.InstanceAiService = void 0;
46
+ const api_types_1 = require("@n8n/api-types");
47
+ const backend_common_1 = require("@n8n/backend-common");
48
+ const config_1 = require("@n8n/config");
49
+ const constants_1 = require("@n8n/constants");
50
+ const di_1 = require("@n8n/di");
51
+ const url_service_1 = require("../../services/url.service");
52
+ const instance_ai_1 = require("@n8n/instance-ai");
53
+ const workflow_sdk_1 = require("@n8n/workflow-sdk");
54
+ const nanoid_1 = require("nanoid");
55
+ const source_control_preferences_service_ee_1 = require("../../modules/source-control.ee/source-control-preferences.service.ee");
56
+ const ai_service_1 = require("../../services/ai.service");
57
+ const push_1 = require("../../push");
58
+ const telemetry_1 = require("../../telemetry");
59
+ const in_process_event_bus_1 = require("./event-bus/in-process-event-bus");
60
+ const filesystem_1 = require("./filesystem");
61
+ const instance_ai_settings_service_1 = require("./instance-ai-settings.service");
62
+ const instance_ai_adapter_service_1 = require("./instance-ai.adapter.service");
63
+ const internal_messages_1 = require("./internal-messages");
64
+ const typeorm_composite_store_1 = require("./storage/typeorm-composite-store");
65
+ const db_snapshot_storage_1 = require("./storage/db-snapshot-storage");
66
+ const db_iteration_log_storage_1 = require("./storage/db-iteration-log-storage");
67
+ const compaction_service_1 = require("./compaction.service");
68
+ const proxy_token_manager_1 = require("./proxy-token-manager");
69
+ const instance_ai_thread_repository_1 = require("./repositories/instance-ai-thread.repository");
70
+ function getErrorMessage(error) {
71
+ return error instanceof Error ? error.message : String(error);
72
+ }
73
+ function createInertAbortSignal() {
74
+ return new AbortController().signal;
75
+ }
76
+ const ORCHESTRATOR_AGENT_ID = 'agent-001';
77
+ const MAX_CONCURRENT_BACKGROUND_TASKS_PER_THREAD = 5;
78
+ let InstanceAiService = class InstanceAiService {
79
+ constructor(logger, globalConfig, adapterService, eventBus, settingsService, compositeStore, compactionService, aiService, push, threadRepo, urlService, dbSnapshotStorage, dbIterationLogStorage, sourceControlPreferencesService, telemetry) {
80
+ this.adapterService = adapterService;
81
+ this.eventBus = eventBus;
82
+ this.settingsService = settingsService;
83
+ this.compositeStore = compositeStore;
84
+ this.compactionService = compactionService;
85
+ this.aiService = aiService;
86
+ this.push = push;
87
+ this.threadRepo = threadRepo;
88
+ this.urlService = urlService;
89
+ this.dbSnapshotStorage = dbSnapshotStorage;
90
+ this.dbIterationLogStorage = dbIterationLogStorage;
91
+ this.sourceControlPreferencesService = sourceControlPreferencesService;
92
+ this.telemetry = telemetry;
93
+ this.mcpClientManager = new instance_ai_1.McpClientManager();
94
+ this.runState = new instance_ai_1.RunStateRegistry();
95
+ this.backgroundTasks = new instance_ai_1.BackgroundTaskManager(MAX_CONCURRENT_BACKGROUND_TASKS_PER_THREAD);
96
+ this.traceContextsByRunId = new Map();
97
+ this.sandboxes = new Map();
98
+ this.gatewayRegistry = new filesystem_1.LocalGatewayRegistry();
99
+ this.domainAccessTrackersByThread = new Map();
100
+ this.threadPushRef = new Map();
101
+ this.schedulerLocks = new Map();
102
+ this.creditedThreads = new Set();
103
+ this.logger = logger.scoped('instance-ai');
104
+ this.instanceAiConfig = globalConfig.instanceAi;
105
+ this.defaultTimeZone = globalConfig.generic.timezone;
106
+ const editorBaseUrl = globalConfig.editorBaseUrl || `http://localhost:${globalConfig.port}`;
107
+ const restEndpoint = globalConfig.endpoints.rest;
108
+ this.oauth2CallbackUrl = `${editorBaseUrl.replace(/\/$/, '')}/${restEndpoint}/oauth2-credential/callback`;
109
+ this.webhookBaseUrl = `${this.urlService.getWebhookBaseUrl()}${globalConfig.endpoints.webhook}`;
110
+ this.startConfirmationTimeoutSweep();
111
+ }
112
+ startConfirmationTimeoutSweep() {
113
+ const timeoutMs = this.instanceAiConfig.confirmationTimeout;
114
+ if (timeoutMs <= 0)
115
+ return;
116
+ this.confirmationTimeoutInterval = setInterval(() => {
117
+ const { suspendedThreadIds, confirmationRequestIds } = this.runState.sweepTimedOut(timeoutMs);
118
+ for (const threadId of suspendedThreadIds) {
119
+ this.logger.debug('Auto-rejecting timed-out suspended run', { threadId });
120
+ this.cancelRun(threadId);
121
+ }
122
+ for (const reqId of confirmationRequestIds) {
123
+ this.logger.debug('Auto-rejecting timed-out sub-agent confirmation', {
124
+ requestId: reqId,
125
+ });
126
+ this.runState.rejectPendingConfirmation(reqId);
127
+ }
128
+ }, constants_1.Time.minutes.toMilliseconds);
129
+ }
130
+ getSandboxConfigFromEnv() {
131
+ const { sandboxEnabled, sandboxProvider, daytonaApiUrl, daytonaApiKey, n8nSandboxServiceUrl, n8nSandboxServiceApiKey, sandboxImage, sandboxTimeout, } = this.instanceAiConfig;
132
+ if (!sandboxEnabled) {
133
+ return {
134
+ enabled: false,
135
+ provider: sandboxProvider === 'n8n-sandbox'
136
+ ? 'n8n-sandbox'
137
+ : sandboxProvider === 'daytona'
138
+ ? 'daytona'
139
+ : 'local',
140
+ timeout: sandboxTimeout,
141
+ };
142
+ }
143
+ if (sandboxProvider === 'daytona') {
144
+ return {
145
+ enabled: true,
146
+ provider: 'daytona',
147
+ daytonaApiUrl: daytonaApiUrl || undefined,
148
+ daytonaApiKey: daytonaApiKey || undefined,
149
+ image: sandboxImage || undefined,
150
+ timeout: sandboxTimeout,
151
+ };
152
+ }
153
+ if (sandboxProvider === 'n8n-sandbox') {
154
+ return {
155
+ enabled: true,
156
+ provider: 'n8n-sandbox',
157
+ serviceUrl: n8nSandboxServiceUrl || undefined,
158
+ apiKey: n8nSandboxServiceApiKey || undefined,
159
+ timeout: sandboxTimeout,
160
+ };
161
+ }
162
+ return {
163
+ enabled: true,
164
+ provider: 'local',
165
+ timeout: sandboxTimeout,
166
+ };
167
+ }
168
+ async resolveSandboxConfig(user) {
169
+ const base = this.getSandboxConfigFromEnv();
170
+ if (!base.enabled)
171
+ return base;
172
+ if (base.provider === 'daytona') {
173
+ if (this.aiService.isProxyEnabled()) {
174
+ const client = await this.aiService.getClient();
175
+ const proxyConfig = await client.getSandboxProxyConfig();
176
+ return {
177
+ ...base,
178
+ daytonaApiUrl: client.getSandboxProxyBaseUrl(),
179
+ image: proxyConfig.image,
180
+ getAuthToken: async () => {
181
+ const token = await client.getBuilderApiProxyToken({ id: user.id }, { userMessageId: (0, nanoid_1.nanoid)() });
182
+ return token.accessToken;
183
+ },
184
+ };
185
+ }
186
+ const daytona = await this.settingsService.resolveDaytonaConfig(user);
187
+ return {
188
+ ...base,
189
+ daytonaApiUrl: daytona.apiUrl ?? base.daytonaApiUrl,
190
+ daytonaApiKey: daytona.apiKey ?? base.daytonaApiKey,
191
+ };
192
+ }
193
+ if (base.provider === 'n8n-sandbox') {
194
+ const sandbox = await this.settingsService.resolveN8nSandboxConfig(user);
195
+ return {
196
+ ...base,
197
+ serviceUrl: sandbox.serviceUrl ?? base.serviceUrl,
198
+ apiKey: sandbox.apiKey ?? base.apiKey,
199
+ };
200
+ }
201
+ return base;
202
+ }
203
+ async createBuilderFactory(user) {
204
+ const config = await this.resolveSandboxConfig(user);
205
+ if (!config.enabled)
206
+ return undefined;
207
+ if (config.provider === 'daytona') {
208
+ return new instance_ai_1.BuilderSandboxFactory(config, new instance_ai_1.SnapshotManager(config.image, this.logger));
209
+ }
210
+ return new instance_ai_1.BuilderSandboxFactory(config);
211
+ }
212
+ async getOrCreateWorkspace(threadId, user) {
213
+ const existing = this.sandboxes.get(threadId);
214
+ if (existing)
215
+ return existing;
216
+ const config = await this.resolveSandboxConfig(user);
217
+ if (!config.enabled)
218
+ return undefined;
219
+ const sandbox = await (0, instance_ai_1.createSandbox)(config);
220
+ const workspace = (0, instance_ai_1.createWorkspace)(sandbox);
221
+ if (!sandbox || !workspace)
222
+ return undefined;
223
+ const entry = { sandbox, workspace };
224
+ this.sandboxes.set(threadId, entry);
225
+ return entry;
226
+ }
227
+ async destroySandbox(threadId) {
228
+ const entry = this.sandboxes.get(threadId);
229
+ if (!entry?.sandbox)
230
+ return;
231
+ this.sandboxes.delete(threadId);
232
+ try {
233
+ if ('destroy' in entry.sandbox && typeof entry.sandbox.destroy === 'function') {
234
+ await entry.sandbox.destroy();
235
+ }
236
+ }
237
+ catch (error) {
238
+ this.logger.warn('Failed to destroy sandbox', {
239
+ threadId,
240
+ error: error instanceof Error ? error.message : String(error),
241
+ });
242
+ }
243
+ }
244
+ async getProxyAuth(user) {
245
+ const client = await this.aiService.getClient();
246
+ const token = await client.getBuilderApiProxyToken({ id: user.id }, { userMessageId: (0, nanoid_1.nanoid)() });
247
+ return {
248
+ client,
249
+ headers: { Authorization: `${token.tokenType} ${token.accessToken}` },
250
+ };
251
+ }
252
+ async resolveProxyModel(user, proxyBaseUrl, tokenManager) {
253
+ const modelName = await this.settingsService.resolveModelName(user);
254
+ const { createAnthropic } = await Promise.resolve().then(() => __importStar(require('@ai-sdk/anthropic')));
255
+ const provider = createAnthropic({
256
+ baseURL: proxyBaseUrl + '/anthropic/v1',
257
+ apiKey: 'proxy-managed',
258
+ fetch: async (input, init) => {
259
+ const headers = new Headers(init?.headers);
260
+ const auth = await tokenManager.getAuthHeaders();
261
+ for (const [k, v] of Object.entries(auth)) {
262
+ headers.set(k, v);
263
+ }
264
+ return await globalThis.fetch(input, { ...init, headers });
265
+ },
266
+ });
267
+ return provider(modelName);
268
+ }
269
+ async countCreditsIfFirst(user, threadId, runId) {
270
+ if (!this.aiService.isProxyEnabled())
271
+ return;
272
+ if (this.creditedThreads.has(threadId))
273
+ return;
274
+ const thread = await this.threadRepo.findOneBy({ id: threadId });
275
+ if (!thread)
276
+ return;
277
+ if (thread.metadata?.creditCounted) {
278
+ this.creditedThreads.add(threadId);
279
+ return;
280
+ }
281
+ try {
282
+ this.creditedThreads.add(threadId);
283
+ const { client, headers: authHeaders } = await this.getProxyAuth(user);
284
+ const info = await client.markBuilderSuccess({ id: user.id }, authHeaders);
285
+ if (info) {
286
+ thread.metadata = { ...thread.metadata, creditCounted: true };
287
+ await this.threadRepo.save(thread);
288
+ this.push.sendToUsers({
289
+ type: 'updateInstanceAiCredits',
290
+ data: { creditsQuota: info.creditsQuota, creditsClaimed: info.creditsClaimed },
291
+ }, [user.id]);
292
+ }
293
+ }
294
+ catch (error) {
295
+ this.creditedThreads.delete(threadId);
296
+ this.logger.warn('Failed to count Instance AI credits', {
297
+ error: getErrorMessage(error),
298
+ threadId,
299
+ runId,
300
+ });
301
+ }
302
+ }
303
+ isProxyEnabled() {
304
+ return this.aiService.isProxyEnabled();
305
+ }
306
+ async getCredits(user) {
307
+ if (!this.aiService.isProxyEnabled()) {
308
+ return { creditsQuota: api_types_1.UNLIMITED_CREDITS, creditsClaimed: 0 };
309
+ }
310
+ const client = await this.aiService.getClient();
311
+ return await client.getBuilderInstanceCredits({ id: user.id });
312
+ }
313
+ isEnabled() {
314
+ return this.settingsService.isAgentEnabled() && !!this.instanceAiConfig.model;
315
+ }
316
+ hasActiveRun(threadId) {
317
+ return this.runState.hasLiveRun(threadId);
318
+ }
319
+ getThreadStatus(threadId) {
320
+ return this.runState.getThreadStatus(threadId, this.backgroundTasks.getTaskSnapshots(threadId));
321
+ }
322
+ storeTraceContext(runId, threadId, tracing, messageGroupId) {
323
+ this.traceContextsByRunId.set(runId, { threadId, messageGroupId, tracing });
324
+ }
325
+ getTraceContext(runId) {
326
+ return this.traceContextsByRunId.get(runId)?.tracing;
327
+ }
328
+ async finalizeMessageTraceRoot(runId, tracing, options) {
329
+ if (tracing.rootRun.endTime)
330
+ return;
331
+ const outputs = options.outputs ?? {
332
+ status: options.status,
333
+ runId,
334
+ ...(options.outputText ? { response: options.outputText } : {}),
335
+ ...(options.reason ? { reason: options.reason } : {}),
336
+ };
337
+ const metadata = {
338
+ final_status: options.status,
339
+ ...(options.modelId !== undefined ? { model_id: options.modelId } : {}),
340
+ ...options.metadata,
341
+ };
342
+ try {
343
+ await tracing.finishRun(tracing.rootRun, {
344
+ outputs,
345
+ metadata,
346
+ ...(options.error
347
+ ? { error: options.error }
348
+ : options.status === 'error' && options.reason
349
+ ? { error: options.reason }
350
+ : {}),
351
+ });
352
+ }
353
+ catch (error) {
354
+ this.logger.warn('Failed to finalize Instance AI message trace root', {
355
+ runId,
356
+ threadId: tracing.rootRun.metadata?.thread_id,
357
+ error: getErrorMessage(error),
358
+ });
359
+ }
360
+ finally {
361
+ (0, instance_ai_1.releaseTraceClient)(tracing.rootRun.traceId);
362
+ }
363
+ }
364
+ async maybeFinalizeRunTraceRoot(runId, options) {
365
+ const tracing = this.getTraceContext(runId);
366
+ if (!tracing)
367
+ return;
368
+ await this.finalizeMessageTraceRoot(runId, tracing, options);
369
+ }
370
+ async finalizeRemainingMessageTraceRoots(threadId, options) {
371
+ const finalizedMessageRuns = new Set();
372
+ for (const [runId, entry] of this.traceContextsByRunId) {
373
+ if (entry.threadId !== threadId)
374
+ continue;
375
+ if (finalizedMessageRuns.has(entry.tracing.rootRun.id))
376
+ continue;
377
+ finalizedMessageRuns.add(entry.tracing.rootRun.id);
378
+ await this.finalizeMessageTraceRoot(runId, entry.tracing, options);
379
+ }
380
+ }
381
+ deleteTraceContextsForThread(threadId) {
382
+ for (const [runId, entry] of this.traceContextsByRunId) {
383
+ if (entry.threadId === threadId) {
384
+ (0, instance_ai_1.releaseTraceClient)(entry.tracing.rootRun.traceId);
385
+ this.traceContextsByRunId.delete(runId);
386
+ }
387
+ }
388
+ }
389
+ async finalizeDetachedTraceRun(taskId, traceContext, options) {
390
+ if (!traceContext)
391
+ return;
392
+ try {
393
+ await traceContext.finishRun(traceContext.rootRun, {
394
+ outputs: {
395
+ status: options.status,
396
+ ...options.outputs,
397
+ },
398
+ metadata: {
399
+ final_status: options.status,
400
+ ...options.metadata,
401
+ },
402
+ ...(options.error ? { error: options.error } : {}),
403
+ });
404
+ }
405
+ catch (error) {
406
+ this.logger.warn('Failed to finalize Instance AI detached trace run', {
407
+ taskId,
408
+ traceRunId: traceContext.rootRun.id,
409
+ error: getErrorMessage(error),
410
+ });
411
+ }
412
+ finally {
413
+ (0, instance_ai_1.releaseTraceClient)(traceContext.rootRun.traceId);
414
+ }
415
+ }
416
+ async finalizeRunTracing(runId, tracing, options) {
417
+ if (!tracing)
418
+ return;
419
+ const outputs = {
420
+ status: options.status,
421
+ runId,
422
+ ...(options.outputText ? { response: options.outputText } : {}),
423
+ ...(options.reason ? { reason: options.reason } : {}),
424
+ };
425
+ const metadata = {
426
+ final_status: options.status,
427
+ ...(options.modelId !== undefined ? { model_id: options.modelId } : {}),
428
+ };
429
+ try {
430
+ await tracing.finishRun(tracing.actorRun, {
431
+ outputs,
432
+ metadata,
433
+ ...(options.status === 'error' && options.reason ? { error: options.reason } : {}),
434
+ });
435
+ }
436
+ catch (error) {
437
+ this.logger.warn('Failed to finalize Instance AI run tracing', {
438
+ runId,
439
+ threadId: tracing.actorRun.metadata?.thread_id,
440
+ error: getErrorMessage(error),
441
+ });
442
+ }
443
+ }
444
+ async finalizeBackgroundTaskTracing(task, status) {
445
+ await this.finalizeDetachedTraceRun(task.taskId, task.traceContext, {
446
+ status,
447
+ outputs: {
448
+ taskId: task.taskId,
449
+ agentId: task.agentId,
450
+ role: task.role,
451
+ ...(task.result ? { result: task.result } : {}),
452
+ },
453
+ ...(status === 'failed' && task.error ? { error: task.error } : {}),
454
+ metadata: {
455
+ ...(task.plannedTaskId ? { planned_task_id: task.plannedTaskId } : {}),
456
+ ...(task.workItemId ? { work_item_id: task.workItemId } : {}),
457
+ },
458
+ });
459
+ }
460
+ startRun(user, threadId, message, researchMode, attachments, timeZone, pushRef) {
461
+ const { runId, abortController, messageGroupId } = this.runState.startRun({
462
+ threadId,
463
+ user,
464
+ researchMode,
465
+ });
466
+ if (pushRef !== undefined) {
467
+ this.threadPushRef.set(threadId, pushRef);
468
+ }
469
+ void this.executeRun(user, threadId, runId, message, abortController, researchMode, attachments, messageGroupId, timeZone);
470
+ return runId;
471
+ }
472
+ getMessageGroupId(threadId) {
473
+ return this.runState.getMessageGroupId(threadId);
474
+ }
475
+ getLiveMessageGroupId(threadId) {
476
+ return this.runState.getLiveMessageGroupId(threadId, this.backgroundTasks.getTaskSnapshots(threadId));
477
+ }
478
+ getRunIdsForMessageGroup(messageGroupId) {
479
+ return this.runState.getRunIdsForMessageGroup(messageGroupId);
480
+ }
481
+ getActiveRunId(threadId) {
482
+ return this.runState.getActiveRunId(threadId);
483
+ }
484
+ cancelRun(threadId) {
485
+ const cancelledTasks = this.backgroundTasks.cancelThread(threadId);
486
+ const user = this.runState.getThreadUser(threadId);
487
+ for (const task of cancelledTasks) {
488
+ void this.finalizeBackgroundTaskTracing(task, 'cancelled');
489
+ this.eventBus.publish(threadId, {
490
+ type: 'agent-completed',
491
+ runId: task.runId,
492
+ agentId: task.agentId,
493
+ payload: { role: task.role, result: '', error: 'Cancelled by user' },
494
+ });
495
+ void this.saveAgentTreeSnapshot(threadId, task.runId, this.dbSnapshotStorage, true, task.messageGroupId);
496
+ if (user) {
497
+ void this.handlePlannedTaskSettlement(user, task, 'cancelled');
498
+ }
499
+ }
500
+ const { active, suspended } = this.runState.cancelThread(threadId);
501
+ if (active) {
502
+ active.abortController.abort();
503
+ return;
504
+ }
505
+ if (suspended) {
506
+ suspended.abortController.abort();
507
+ void this.finalizeRunTracing(suspended.runId, suspended.tracing, {
508
+ status: 'cancelled',
509
+ reason: 'user_cancelled',
510
+ });
511
+ this.eventBus.publish(threadId, {
512
+ type: 'run-finish',
513
+ runId: suspended.runId,
514
+ agentId: ORCHESTRATOR_AGENT_ID,
515
+ payload: { status: 'cancelled', reason: 'user_cancelled' },
516
+ });
517
+ void this.saveAgentTreeSnapshot(threadId, suspended.runId, this.dbSnapshotStorage, true);
518
+ if (suspended.mastraRunId) {
519
+ void this.cleanupMastraSnapshots(suspended.mastraRunId);
520
+ }
521
+ void this.maybeFinalizeRunTraceRoot(suspended.runId, {
522
+ status: 'cancelled',
523
+ reason: 'user_cancelled',
524
+ metadata: { completion_source: 'orchestrator' },
525
+ });
526
+ }
527
+ }
528
+ sendCorrectionToTask(threadId, taskId, correction) {
529
+ return this.backgroundTasks.queueCorrection(threadId, taskId, correction);
530
+ }
531
+ cancelBackgroundTask(threadId, taskId) {
532
+ const task = this.backgroundTasks.cancelTask(threadId, taskId);
533
+ if (!task)
534
+ return;
535
+ void this.finalizeBackgroundTaskTracing(task, 'cancelled');
536
+ this.eventBus.publish(threadId, {
537
+ type: 'agent-completed',
538
+ runId: task.runId,
539
+ agentId: task.agentId,
540
+ payload: { role: task.role, result: '', error: 'Cancelled by user' },
541
+ });
542
+ void this.saveAgentTreeSnapshot(threadId, task.runId, this.dbSnapshotStorage, true, task.messageGroupId);
543
+ const user = this.runState.getThreadUser(threadId);
544
+ if (user) {
545
+ void this.handlePlannedTaskSettlement(user, task, 'cancelled');
546
+ }
547
+ }
548
+ getUserIdForApiKey(key) {
549
+ return this.gatewayRegistry.getUserIdForApiKey(key);
550
+ }
551
+ generatePairingToken(userId) {
552
+ return this.gatewayRegistry.generatePairingToken(userId);
553
+ }
554
+ getPairingToken(userId) {
555
+ return this.gatewayRegistry.getPairingToken(userId);
556
+ }
557
+ consumePairingToken(userId, token) {
558
+ return this.gatewayRegistry.consumePairingToken(userId, token);
559
+ }
560
+ getActiveSessionKey(userId) {
561
+ return this.gatewayRegistry.getActiveSessionKey(userId);
562
+ }
563
+ clearActiveSessionKey(userId) {
564
+ this.gatewayRegistry.clearActiveSessionKey(userId);
565
+ }
566
+ getLocalGateway(userId) {
567
+ return this.gatewayRegistry.getGateway(userId);
568
+ }
569
+ initGateway(userId, data) {
570
+ this.gatewayRegistry.initGateway(userId, data);
571
+ }
572
+ resolveGatewayRequest(userId, requestId, result, error) {
573
+ return this.gatewayRegistry.resolveGatewayRequest(userId, requestId, result, error);
574
+ }
575
+ disconnectGateway(userId) {
576
+ this.gatewayRegistry.disconnectGateway(userId);
577
+ }
578
+ isLocalGatewayDisabled() {
579
+ return this.settingsService.isLocalGatewayDisabled();
580
+ }
581
+ getGatewayStatus(userId) {
582
+ return this.gatewayRegistry.getGatewayStatus(userId);
583
+ }
584
+ startDisconnectTimer(userId, onDisconnect) {
585
+ this.gatewayRegistry.startDisconnectTimer(userId, onDisconnect);
586
+ }
587
+ clearDisconnectTimer(userId) {
588
+ this.gatewayRegistry.clearDisconnectTimer(userId);
589
+ }
590
+ async clearThreadState(threadId) {
591
+ const { active, suspended } = this.runState.clearThread(threadId);
592
+ if (active) {
593
+ active.abortController.abort();
594
+ await this.finalizeRunTracing(active.runId, active.tracing, {
595
+ status: 'cancelled',
596
+ reason: 'thread_cleared',
597
+ });
598
+ }
599
+ if (suspended) {
600
+ suspended.abortController.abort();
601
+ await this.finalizeRunTracing(suspended.runId, suspended.tracing, {
602
+ status: 'cancelled',
603
+ reason: 'thread_cleared',
604
+ });
605
+ }
606
+ for (const task of this.backgroundTasks.cancelThread(threadId)) {
607
+ task.abortController.abort();
608
+ await this.finalizeBackgroundTaskTracing(task, 'cancelled');
609
+ }
610
+ await this.finalizeRemainingMessageTraceRoots(threadId, {
611
+ status: 'cancelled',
612
+ reason: 'thread_cleared',
613
+ metadata: { completion_source: 'service_cleanup' },
614
+ });
615
+ this.creditedThreads.delete(threadId);
616
+ this.schedulerLocks.delete(threadId);
617
+ this.domainAccessTrackersByThread.delete(threadId);
618
+ this.threadPushRef.delete(threadId);
619
+ this.deleteTraceContextsForThread(threadId);
620
+ await this.destroySandbox(threadId);
621
+ this.eventBus.clearThread(threadId);
622
+ }
623
+ async shutdown() {
624
+ if (this.confirmationTimeoutInterval) {
625
+ clearInterval(this.confirmationTimeoutInterval);
626
+ this.confirmationTimeoutInterval = undefined;
627
+ }
628
+ const { activeRuns, suspendedRuns } = this.runState.shutdown();
629
+ for (const run of activeRuns) {
630
+ run.abortController.abort();
631
+ await this.finalizeRunTracing(run.runId, run.tracing, {
632
+ status: 'cancelled',
633
+ reason: 'service_shutdown',
634
+ });
635
+ }
636
+ for (const run of suspendedRuns) {
637
+ run.abortController.abort();
638
+ await this.finalizeRunTracing(run.runId, run.tracing, {
639
+ status: 'cancelled',
640
+ reason: 'service_shutdown',
641
+ });
642
+ }
643
+ for (const task of this.backgroundTasks.cancelAll()) {
644
+ task.abortController.abort();
645
+ await this.finalizeBackgroundTaskTracing(task, 'cancelled');
646
+ }
647
+ const threadsWithTraces = new Set([...this.traceContextsByRunId.values()].map((entry) => entry.threadId));
648
+ for (const threadId of threadsWithTraces) {
649
+ await this.finalizeRemainingMessageTraceRoots(threadId, {
650
+ status: 'cancelled',
651
+ reason: 'service_shutdown',
652
+ metadata: { completion_source: 'service_cleanup' },
653
+ });
654
+ }
655
+ this.gatewayRegistry.disconnectAll();
656
+ const sandboxCleanups = [...this.sandboxes.keys()].map(async (threadId) => await this.destroySandbox(threadId));
657
+ await Promise.allSettled(sandboxCleanups);
658
+ this.domainAccessTrackersByThread.clear();
659
+ this.traceContextsByRunId.clear();
660
+ this.eventBus.clear();
661
+ await this.mcpClientManager.disconnect();
662
+ this.logger.debug('Instance AI service shut down');
663
+ }
664
+ createMemoryConfig() {
665
+ return {
666
+ storage: this.compositeStore,
667
+ embedderModel: this.instanceAiConfig.embedderModel || undefined,
668
+ lastMessages: this.instanceAiConfig.lastMessages,
669
+ semanticRecallTopK: this.instanceAiConfig.semanticRecallTopK,
670
+ };
671
+ }
672
+ async ensureThreadExists(memory, threadId, resourceId) {
673
+ const existingThread = await memory.getThreadById({ threadId });
674
+ if (existingThread)
675
+ return;
676
+ const now = new Date();
677
+ await memory.saveThread({
678
+ thread: {
679
+ id: threadId,
680
+ resourceId,
681
+ title: '',
682
+ createdAt: now,
683
+ updatedAt: now,
684
+ },
685
+ });
686
+ }
687
+ projectPlannedTaskList(graph) {
688
+ return {
689
+ tasks: graph.tasks.map((task) => ({
690
+ id: task.id,
691
+ description: task.title,
692
+ status: task.status === 'planned'
693
+ ? 'todo'
694
+ : task.status === 'running'
695
+ ? 'in_progress'
696
+ : task.status === 'succeeded'
697
+ ? 'done'
698
+ : task.status,
699
+ })),
700
+ };
701
+ }
702
+ buildPlannedTaskFollowUpMessage(type, graph, failedTask) {
703
+ const payload = {
704
+ tasks: graph.tasks.map((task) => ({
705
+ id: task.id,
706
+ title: task.title,
707
+ kind: task.kind,
708
+ status: task.status,
709
+ result: task.result,
710
+ error: task.error,
711
+ outcome: task.outcome,
712
+ })),
713
+ };
714
+ if (failedTask) {
715
+ payload.failedTask = {
716
+ id: failedTask.id,
717
+ title: failedTask.title,
718
+ kind: failedTask.kind,
719
+ error: failedTask.error,
720
+ result: failedTask.result,
721
+ };
722
+ }
723
+ return `<planned-task-follow-up type="${type}">\n${JSON.stringify(payload, null, 2)}\n</planned-task-follow-up>\n\n${internal_messages_1.AUTO_FOLLOW_UP_MESSAGE}`;
724
+ }
725
+ async createPlannedTaskState() {
726
+ const memory = (0, instance_ai_1.createMemory)(this.createMemoryConfig());
727
+ const taskStorage = new instance_ai_1.MastraTaskStorage(memory);
728
+ const plannedTaskStorage = new instance_ai_1.PlannedTaskStorage(memory);
729
+ const plannedTaskService = new instance_ai_1.PlannedTaskCoordinator(plannedTaskStorage);
730
+ return { memory, taskStorage, plannedTaskService };
731
+ }
732
+ async syncPlannedTasksToUi(threadId, graph) {
733
+ const { taskStorage } = await this.createPlannedTaskState();
734
+ const tasks = this.projectPlannedTaskList(graph);
735
+ await taskStorage.save(threadId, tasks);
736
+ this.eventBus.publish(threadId, {
737
+ type: 'tasks-update',
738
+ runId: graph.planRunId,
739
+ agentId: ORCHESTRATOR_AGENT_ID,
740
+ payload: { tasks },
741
+ });
742
+ }
743
+ async createExecutionEnvironment(user, threadId, runId, abortSignal, researchMode, messageGroupId, pushRef) {
744
+ const localGatewayDisabled = this.settingsService.isLocalGatewayDisabled();
745
+ const userGateway = this.gatewayRegistry.findGateway(user.id);
746
+ let searchProxyConfig;
747
+ let tracingProxyConfig;
748
+ let tokenManager;
749
+ let proxyBaseUrl;
750
+ if (this.aiService.isProxyEnabled()) {
751
+ const client = await this.aiService.getClient();
752
+ proxyBaseUrl = client.getApiProxyBaseUrl();
753
+ const manager = new proxy_token_manager_1.ProxyTokenManager(async () => {
754
+ return await client.getBuilderApiProxyToken({ id: user.id }, { userMessageId: (0, nanoid_1.nanoid)() });
755
+ });
756
+ tokenManager = manager;
757
+ searchProxyConfig = {
758
+ apiUrl: proxyBaseUrl + '/brave-search',
759
+ getAuthHeaders: async () => await manager.getAuthHeaders(),
760
+ };
761
+ tracingProxyConfig = {
762
+ apiUrl: proxyBaseUrl + '/langsmith',
763
+ getAuthHeaders: async () => await manager.getAuthHeaders(),
764
+ };
765
+ }
766
+ const context = this.adapterService.createContext(user, {
767
+ searchProxyConfig,
768
+ pushRef,
769
+ threadId,
770
+ });
771
+ if (!localGatewayDisabled && userGateway?.isConnected) {
772
+ context.localMcpServer = userGateway;
773
+ }
774
+ context.permissions = this.settingsService.getPermissions();
775
+ if (this.sourceControlPreferencesService.getPreferences().branchReadOnly) {
776
+ context.permissions = (0, api_types_1.applyBranchReadOnlyOverrides)(context.permissions);
777
+ context.branchReadOnly = true;
778
+ }
779
+ let domainTracker = this.domainAccessTrackersByThread.get(threadId);
780
+ if (!domainTracker) {
781
+ domainTracker = (0, instance_ai_1.createDomainAccessTracker)();
782
+ this.domainAccessTrackersByThread.set(threadId, domainTracker);
783
+ }
784
+ context.domainAccessTracker = domainTracker;
785
+ context.runId = runId;
786
+ if (localGatewayDisabled) {
787
+ context.localGatewayStatus = { status: 'disabled' };
788
+ }
789
+ else if (userGateway?.isConnected) {
790
+ context.localGatewayStatus = { status: 'connected' };
791
+ }
792
+ else {
793
+ context.localGatewayStatus = {
794
+ status: 'disconnected',
795
+ capabilities: ['filesystem', 'browser'],
796
+ };
797
+ }
798
+ const modelId = proxyBaseUrl && tokenManager
799
+ ? await this.resolveProxyModel(user, proxyBaseUrl, tokenManager)
800
+ : await this.settingsService.resolveModelConfig(user);
801
+ const memory = (0, instance_ai_1.createMemory)(this.createMemoryConfig());
802
+ await this.ensureThreadExists(memory, threadId, user.id);
803
+ const taskStorage = new instance_ai_1.MastraTaskStorage(memory);
804
+ const iterationLog = this.dbIterationLogStorage;
805
+ const snapshotStorage = this.dbSnapshotStorage;
806
+ const workflowLoopStorage = new instance_ai_1.WorkflowLoopStorage(memory);
807
+ const workflowTasks = new instance_ai_1.WorkflowTaskCoordinator(threadId, workflowLoopStorage);
808
+ const plannedTaskStorage = new instance_ai_1.PlannedTaskStorage(memory);
809
+ const plannedTaskService = new instance_ai_1.PlannedTaskCoordinator(plannedTaskStorage);
810
+ const nodeDefDirs = this.adapterService.getNodeDefinitionDirs();
811
+ if (nodeDefDirs.length > 0) {
812
+ (0, workflow_sdk_1.setSchemaBaseDirs)(nodeDefDirs);
813
+ }
814
+ const domainTools = (0, instance_ai_1.createAllTools)(context);
815
+ const sandboxEntry = await this.getOrCreateWorkspace(threadId, user);
816
+ const orchestrationContext = {
817
+ threadId,
818
+ runId,
819
+ messageGroupId,
820
+ userId: user.id,
821
+ orchestratorAgentId: ORCHESTRATOR_AGENT_ID,
822
+ modelId,
823
+ storage: this.compositeStore,
824
+ subAgentMaxSteps: this.instanceAiConfig.subAgentMaxSteps,
825
+ eventBus: this.eventBus,
826
+ logger: this.logger,
827
+ domainTools,
828
+ abortSignal,
829
+ taskStorage,
830
+ researchMode,
831
+ browserMcpConfig: this.instanceAiConfig.browserMcp
832
+ ? { name: 'chrome-devtools', command: 'npx', args: ['-y', 'chrome-devtools-mcp@latest'] }
833
+ : undefined,
834
+ localMcpServer: context.localMcpServer,
835
+ oauth2CallbackUrl: this.oauth2CallbackUrl,
836
+ webhookBaseUrl: this.webhookBaseUrl,
837
+ waitForConfirmation: async (requestId) => {
838
+ return await new Promise((resolve) => {
839
+ this.runState.registerPendingConfirmation(requestId, {
840
+ resolve,
841
+ threadId,
842
+ userId: user.id,
843
+ createdAt: Date.now(),
844
+ });
845
+ queueMicrotask(() => {
846
+ void this.saveAgentTreeSnapshot(threadId, runId, snapshotStorage);
847
+ });
848
+ });
849
+ },
850
+ cancelBackgroundTask: async (taskId) => this.cancelBackgroundTask(threadId, taskId),
851
+ spawnBackgroundTask: (opts) => this.spawnBackgroundTask(runId, opts, snapshotStorage, messageGroupId),
852
+ plannedTaskService,
853
+ schedulePlannedTasks: async () => await this.schedulePlannedTasks(user, threadId),
854
+ iterationLog,
855
+ sendCorrectionToTask: (taskId, correction) => this.sendCorrectionToTask(threadId, taskId, correction),
856
+ workflowTaskService: workflowTasks,
857
+ workspace: sandboxEntry?.workspace,
858
+ builderSandboxFactory: await this.createBuilderFactory(user),
859
+ nodeDefinitionDirs: nodeDefDirs.length > 0 ? nodeDefDirs : undefined,
860
+ domainContext: context,
861
+ tracingProxyConfig,
862
+ memory,
863
+ };
864
+ return {
865
+ context,
866
+ memory,
867
+ taskStorage,
868
+ iterationLog,
869
+ snapshotStorage,
870
+ workflowTasks,
871
+ plannedTaskService,
872
+ modelId,
873
+ orchestrationContext,
874
+ sandboxEntry,
875
+ };
876
+ }
877
+ async dispatchPlannedTask(task, context) {
878
+ const taskContext = this.createPlannedTaskContext(task.kind, context);
879
+ let started = null;
880
+ switch (task.kind) {
881
+ case 'build-workflow':
882
+ started = await (0, instance_ai_1.startBuildWorkflowAgentTask)(taskContext, {
883
+ task: task.spec,
884
+ workflowId: task.workflowId,
885
+ plannedTaskId: task.id,
886
+ });
887
+ break;
888
+ case 'manage-data-tables':
889
+ started = await (0, instance_ai_1.startDataTableAgentTask)(taskContext, {
890
+ task: task.spec,
891
+ plannedTaskId: task.id,
892
+ });
893
+ break;
894
+ case 'research':
895
+ started = await (0, instance_ai_1.startResearchAgentTask)(taskContext, {
896
+ goal: task.title,
897
+ constraints: task.spec,
898
+ plannedTaskId: task.id,
899
+ });
900
+ break;
901
+ case 'delegate':
902
+ started = await (0, instance_ai_1.startDetachedDelegateTask)(taskContext, {
903
+ title: task.title,
904
+ spec: task.spec,
905
+ tools: task.tools ?? [],
906
+ plannedTaskId: task.id,
907
+ });
908
+ break;
909
+ }
910
+ if (!started?.taskId) {
911
+ await context.plannedTaskService?.markFailed(context.threadId, task.id, {
912
+ error: started?.result || `Failed to start planned task "${task.title}"`,
913
+ });
914
+ return;
915
+ }
916
+ await context.plannedTaskService?.markRunning(context.threadId, task.id, {
917
+ agentId: started.agentId,
918
+ backgroundTaskId: started.taskId,
919
+ });
920
+ const nextGraph = await context.plannedTaskService?.getGraph(context.threadId);
921
+ if (nextGraph) {
922
+ await this.syncPlannedTasksToUi(context.threadId, nextGraph);
923
+ }
924
+ }
925
+ createPlannedTaskContext(kind, context) {
926
+ if (!context.domainContext)
927
+ return context;
928
+ const taskDomainContext = (0, instance_ai_1.applyPlannedTaskPermissions)(context.domainContext, kind);
929
+ if (taskDomainContext === context.domainContext)
930
+ return context;
931
+ return {
932
+ ...context,
933
+ domainContext: taskDomainContext,
934
+ domainTools: (0, instance_ai_1.createAllTools)(taskDomainContext),
935
+ };
936
+ }
937
+ async handlePlannedTaskSettlement(user, task, status) {
938
+ if (!task.plannedTaskId)
939
+ return;
940
+ const { plannedTaskService } = await this.createPlannedTaskState();
941
+ let graph = null;
942
+ if (status === 'succeeded') {
943
+ graph = await plannedTaskService.markSucceeded(task.threadId, task.plannedTaskId, {
944
+ result: task.result,
945
+ outcome: task.outcome,
946
+ });
947
+ }
948
+ else if (status === 'failed') {
949
+ graph = await plannedTaskService.markFailed(task.threadId, task.plannedTaskId, {
950
+ error: task.error,
951
+ });
952
+ }
953
+ else {
954
+ graph = await plannedTaskService.markCancelled(task.threadId, task.plannedTaskId, {
955
+ error: task.error,
956
+ });
957
+ }
958
+ if (graph) {
959
+ await this.syncPlannedTasksToUi(task.threadId, graph);
960
+ }
961
+ await this.schedulePlannedTasks(user, task.threadId);
962
+ }
963
+ async startInternalFollowUpRun(user, threadId, message, researchMode, messageGroupId) {
964
+ if (this.runState.hasLiveRun(threadId)) {
965
+ this.logger.warn('Skipping internal follow-up: active run exists', { threadId });
966
+ return '';
967
+ }
968
+ const { runId, abortController } = this.runState.startRun({
969
+ threadId,
970
+ user,
971
+ researchMode,
972
+ messageGroupId,
973
+ });
974
+ void this.executeRun(user, threadId, runId, message, abortController, researchMode, undefined, messageGroupId);
975
+ return runId;
976
+ }
977
+ async schedulePlannedTasks(user, threadId) {
978
+ const prev = this.schedulerLocks.get(threadId) ?? Promise.resolve();
979
+ const current = prev.then(() => this.doSchedulePlannedTasks(user, threadId)).catch(() => { });
980
+ this.schedulerLocks.set(threadId, current);
981
+ await current;
982
+ }
983
+ async doSchedulePlannedTasks(user, threadId) {
984
+ const { plannedTaskService } = await this.createPlannedTaskState();
985
+ const graph = await plannedTaskService.getGraph(threadId);
986
+ if (!graph)
987
+ return;
988
+ await this.syncPlannedTasksToUi(threadId, graph);
989
+ const availableSlots = Math.max(0, MAX_CONCURRENT_BACKGROUND_TASKS_PER_THREAD -
990
+ this.backgroundTasks.getRunningTasks(threadId).length);
991
+ const action = await plannedTaskService.tick(threadId, { availableSlots });
992
+ if (action.type === 'none')
993
+ return;
994
+ if (action.type === 'replan') {
995
+ await this.syncPlannedTasksToUi(threadId, action.graph);
996
+ await this.startInternalFollowUpRun(user, threadId, this.buildPlannedTaskFollowUpMessage('replan', action.graph, action.failedTask), this.runState.getThreadResearchMode(threadId), action.graph.messageGroupId);
997
+ return;
998
+ }
999
+ if (action.type === 'synthesize') {
1000
+ await this.syncPlannedTasksToUi(threadId, action.graph);
1001
+ await this.startInternalFollowUpRun(user, threadId, this.buildPlannedTaskFollowUpMessage('synthesize', action.graph), this.runState.getThreadResearchMode(threadId), action.graph.messageGroupId);
1002
+ return;
1003
+ }
1004
+ const environment = await this.createExecutionEnvironment(user, threadId, action.graph.planRunId, createInertAbortSignal(), this.runState.getThreadResearchMode(threadId), action.graph.messageGroupId);
1005
+ environment.orchestrationContext.tracing = this.getTraceContext(action.graph.planRunId);
1006
+ for (const task of action.tasks) {
1007
+ await this.dispatchPlannedTask(task, environment.orchestrationContext);
1008
+ }
1009
+ await this.doSchedulePlannedTasks(user, threadId);
1010
+ }
1011
+ async executeRun(user, threadId, runId, message, abortController, researchMode, attachments, messageGroupId, timeZone) {
1012
+ const signal = abortController.signal;
1013
+ let mastraRunId = '';
1014
+ let tracing;
1015
+ let messageTraceFinalization;
1016
+ try {
1017
+ const messageId = (0, nanoid_1.nanoid)();
1018
+ this.eventBus.publish(threadId, {
1019
+ type: 'run-start',
1020
+ runId,
1021
+ agentId: ORCHESTRATOR_AGENT_ID,
1022
+ userId: user.id,
1023
+ payload: { messageId, messageGroupId },
1024
+ });
1025
+ if (signal.aborted) {
1026
+ this.eventBus.publish(threadId, {
1027
+ type: 'run-finish',
1028
+ runId,
1029
+ agentId: ORCHESTRATOR_AGENT_ID,
1030
+ payload: { status: 'cancelled', reason: 'user_cancelled' },
1031
+ });
1032
+ return;
1033
+ }
1034
+ const mcpServers = this.parseMcpServers(this.instanceAiConfig.mcpServers);
1035
+ const executionPushRef = this.threadPushRef.get(threadId);
1036
+ const { context, memory, taskStorage, snapshotStorage, modelId, orchestrationContext } = await this.createExecutionEnvironment(user, threadId, runId, signal, researchMode, messageGroupId, executionPushRef);
1037
+ orchestrationContext.currentUserMessage = message;
1038
+ if (attachments && attachments.length > 0) {
1039
+ context.currentUserAttachments = attachments;
1040
+ }
1041
+ const memoryConfig = this.createMemoryConfig();
1042
+ const traceInput = {
1043
+ message,
1044
+ ...(attachments?.length
1045
+ ? {
1046
+ attachments: attachments.map((attachment) => ({
1047
+ mimeType: attachment.mimeType,
1048
+ size: attachment.data.length,
1049
+ })),
1050
+ }
1051
+ : {}),
1052
+ ...(researchMode !== undefined ? { researchMode } : {}),
1053
+ ...(messageGroupId ? { messageGroupId } : {}),
1054
+ };
1055
+ tracing = await (0, instance_ai_1.createInstanceAiTraceContext)({
1056
+ threadId,
1057
+ messageId,
1058
+ messageGroupId,
1059
+ runId,
1060
+ userId: user.id,
1061
+ modelId,
1062
+ input: traceInput,
1063
+ proxyConfig: orchestrationContext.tracingProxyConfig,
1064
+ });
1065
+ if (tracing) {
1066
+ orchestrationContext.tracing = tracing;
1067
+ this.runState.attachTracing(threadId, tracing);
1068
+ this.storeTraceContext(runId, threadId, tracing, messageGroupId);
1069
+ }
1070
+ const thread = await memory.getThreadById({ threadId });
1071
+ if (thread && !thread.title) {
1072
+ await (0, instance_ai_1.patchThread)(memory, {
1073
+ threadId,
1074
+ update: () => ({ title: (0, instance_ai_1.truncateToTitle)(message) }),
1075
+ });
1076
+ }
1077
+ const existingTasks = await taskStorage.get(threadId);
1078
+ if (existingTasks) {
1079
+ this.eventBus.publish(threadId, {
1080
+ type: 'tasks-update',
1081
+ runId,
1082
+ agentId: ORCHESTRATOR_AGENT_ID,
1083
+ payload: { tasks: existingTasks },
1084
+ });
1085
+ }
1086
+ const agent = await (0, instance_ai_1.createInstanceAgent)({
1087
+ modelId,
1088
+ context,
1089
+ orchestrationContext,
1090
+ mcpServers,
1091
+ memoryConfig,
1092
+ memory,
1093
+ workspace: orchestrationContext.workspace,
1094
+ disableDeferredTools: true,
1095
+ timeZone: timeZone ?? this.defaultTimeZone,
1096
+ });
1097
+ this.eventBus.publish(threadId, {
1098
+ type: 'status',
1099
+ runId,
1100
+ agentId: ORCHESTRATOR_AGENT_ID,
1101
+ payload: { message: 'Recalling conversation...' },
1102
+ });
1103
+ const contextCompactionRun = tracing
1104
+ ? await tracing.startChildRun(tracing.actorRun, {
1105
+ name: 'context_compaction',
1106
+ tags: ['context'],
1107
+ metadata: { agent_role: 'context_compaction' },
1108
+ inputs: {
1109
+ threadId,
1110
+ lastMessages: this.instanceAiConfig.lastMessages ?? 20,
1111
+ },
1112
+ })
1113
+ : undefined;
1114
+ let conversationSummary;
1115
+ try {
1116
+ conversationSummary = await this.compactionService.prepareCompactedContext(threadId, memory, modelId, this.instanceAiConfig.lastMessages ?? 20);
1117
+ if (contextCompactionRun && tracing) {
1118
+ await tracing.finishRun(contextCompactionRun, {
1119
+ outputs: {
1120
+ summarized: Boolean(conversationSummary),
1121
+ summary: conversationSummary ?? '',
1122
+ },
1123
+ metadata: { final_status: 'completed' },
1124
+ });
1125
+ }
1126
+ }
1127
+ catch (error) {
1128
+ if (contextCompactionRun && tracing) {
1129
+ await tracing.failRun(contextCompactionRun, error, {
1130
+ final_status: 'error',
1131
+ });
1132
+ }
1133
+ throw error;
1134
+ }
1135
+ this.eventBus.publish(threadId, {
1136
+ type: 'status',
1137
+ runId,
1138
+ agentId: ORCHESTRATOR_AGENT_ID,
1139
+ payload: { message: '' },
1140
+ });
1141
+ const promptBuildRun = tracing
1142
+ ? await tracing.startChildRun(tracing.actorRun, {
1143
+ name: 'prompt_build',
1144
+ tags: ['prompt'],
1145
+ metadata: { agent_role: 'prompt_build' },
1146
+ inputs: {
1147
+ message,
1148
+ hasConversationSummary: Boolean(conversationSummary),
1149
+ attachmentCount: attachments?.length ?? 0,
1150
+ },
1151
+ })
1152
+ : undefined;
1153
+ let streamInput;
1154
+ try {
1155
+ const enrichedMessage = await this.buildMessageWithRunningTasks(threadId, message);
1156
+ let fullMessage = conversationSummary
1157
+ ? `${conversationSummary}\n\n${enrichedMessage}`
1158
+ : enrichedMessage;
1159
+ if (attachments && attachments.length > 0) {
1160
+ const classified = (0, instance_ai_1.classifyAttachments)(attachments);
1161
+ const nonStructured = attachments.filter((a) => !(0, instance_ai_1.isStructuredAttachment)(a));
1162
+ const hasParseable = classified.some((c) => c.parseable);
1163
+ const manifest = (0, instance_ai_1.buildAttachmentManifest)(classified);
1164
+ if (!message && hasParseable) {
1165
+ fullMessage = conversationSummary
1166
+ ? `${conversationSummary}\n\nThe user attached file(s) without a message. Inspect the first parseable attachment with parse-file and provide a concise summary.\n\n${manifest}`
1167
+ : `The user attached file(s) without a message. Inspect the first parseable attachment with parse-file and provide a concise summary.\n\n${manifest}`;
1168
+ }
1169
+ else {
1170
+ fullMessage = `${fullMessage}\n\n${manifest}`;
1171
+ }
1172
+ if (nonStructured.length > 0) {
1173
+ streamInput = [
1174
+ {
1175
+ role: 'user',
1176
+ content: [
1177
+ { type: 'text', text: fullMessage },
1178
+ ...nonStructured.map((a) => ({
1179
+ type: 'file',
1180
+ data: a.data,
1181
+ mimeType: a.mimeType,
1182
+ })),
1183
+ ],
1184
+ },
1185
+ ];
1186
+ }
1187
+ else {
1188
+ streamInput = fullMessage;
1189
+ }
1190
+ }
1191
+ else {
1192
+ streamInput = fullMessage;
1193
+ }
1194
+ if (promptBuildRun && tracing) {
1195
+ const traceOutput = typeof streamInput === 'string'
1196
+ ? { fullMessage: streamInput }
1197
+ : {
1198
+ fullMessage,
1199
+ attachmentCount: attachments?.length ?? 0,
1200
+ nonStructuredAttachmentCount: attachments?.filter((a) => !(0, instance_ai_1.isStructuredAttachment)(a)).length ?? 0,
1201
+ };
1202
+ await tracing.finishRun(promptBuildRun, {
1203
+ outputs: traceOutput,
1204
+ metadata: { final_status: 'completed' },
1205
+ });
1206
+ }
1207
+ }
1208
+ catch (error) {
1209
+ if (promptBuildRun && tracing) {
1210
+ await tracing.failRun(promptBuildRun, error, {
1211
+ final_status: 'error',
1212
+ });
1213
+ }
1214
+ throw error;
1215
+ }
1216
+ const result = tracing
1217
+ ? await tracing.withRunTree(tracing.actorRun, async () => {
1218
+ return await (0, instance_ai_1.streamAgentRun)(agent, streamInput, {
1219
+ abortSignal: signal,
1220
+ memory: {
1221
+ resource: user.id,
1222
+ thread: threadId,
1223
+ },
1224
+ providerOptions: {
1225
+ anthropic: { cacheControl: { type: 'ephemeral' } },
1226
+ },
1227
+ }, {
1228
+ threadId,
1229
+ runId,
1230
+ agentId: ORCHESTRATOR_AGENT_ID,
1231
+ signal,
1232
+ eventBus: this.eventBus,
1233
+ logger: this.logger,
1234
+ });
1235
+ })
1236
+ : await (0, instance_ai_1.streamAgentRun)(agent, streamInput, {
1237
+ abortSignal: signal,
1238
+ memory: {
1239
+ resource: user.id,
1240
+ thread: threadId,
1241
+ },
1242
+ providerOptions: {
1243
+ anthropic: { cacheControl: { type: 'ephemeral' } },
1244
+ },
1245
+ }, {
1246
+ threadId,
1247
+ runId,
1248
+ agentId: ORCHESTRATOR_AGENT_ID,
1249
+ signal,
1250
+ eventBus: this.eventBus,
1251
+ logger: this.logger,
1252
+ });
1253
+ mastraRunId = result.mastraRunId;
1254
+ if (result.status === 'suspended') {
1255
+ if (result.suspension) {
1256
+ this.runState.suspendRun(threadId, {
1257
+ runId,
1258
+ mastraRunId: result.mastraRunId,
1259
+ agent,
1260
+ threadId,
1261
+ user,
1262
+ toolCallId: result.suspension.toolCallId,
1263
+ requestId: result.suspension.requestId,
1264
+ abortController,
1265
+ messageGroupId,
1266
+ createdAt: Date.now(),
1267
+ tracing,
1268
+ });
1269
+ }
1270
+ const intermediateText = await (result.text ?? Promise.resolve(''));
1271
+ if (intermediateText) {
1272
+ this.telemetry.track('Builder sent message', {
1273
+ thread_id: threadId,
1274
+ message: intermediateText,
1275
+ is_intermediate: true,
1276
+ });
1277
+ }
1278
+ if (result.confirmationEvent) {
1279
+ this.trackConfirmationRequest(threadId, result.confirmationEvent);
1280
+ this.eventBus.publish(threadId, result.confirmationEvent);
1281
+ }
1282
+ await this.saveAgentTreeSnapshot(threadId, runId, snapshotStorage);
1283
+ return;
1284
+ }
1285
+ const outputText = await (result.text ?? Promise.resolve(''));
1286
+ const finalStatus = result.status === 'errored' ? 'error' : result.status;
1287
+ await this.finalizeRunTracing(runId, tracing, {
1288
+ status: finalStatus,
1289
+ outputText,
1290
+ modelId,
1291
+ });
1292
+ messageTraceFinalization = {
1293
+ status: finalStatus,
1294
+ outputText,
1295
+ modelId,
1296
+ metadata: { completion_source: 'orchestrator' },
1297
+ };
1298
+ await this.finalizeRun(threadId, runId, result.status, snapshotStorage, {
1299
+ userId: user.id,
1300
+ modelId,
1301
+ });
1302
+ if (result.status === 'completed') {
1303
+ await this.countCreditsIfFirst(user, threadId, runId);
1304
+ this.telemetry.track('Builder sent message', {
1305
+ thread_id: threadId,
1306
+ message: outputText,
1307
+ });
1308
+ this.telemetry.track('Builder satisfied user intent', {
1309
+ thread_id: threadId,
1310
+ });
1311
+ }
1312
+ }
1313
+ catch (error) {
1314
+ if (signal.aborted) {
1315
+ await this.finalizeRunTracing(runId, tracing, {
1316
+ status: 'cancelled',
1317
+ reason: 'user_cancelled',
1318
+ });
1319
+ messageTraceFinalization = {
1320
+ status: 'cancelled',
1321
+ reason: 'user_cancelled',
1322
+ metadata: { completion_source: 'orchestrator' },
1323
+ };
1324
+ this.publishRunFinish(threadId, runId, 'cancelled', 'user_cancelled');
1325
+ return;
1326
+ }
1327
+ const errorMessage = getErrorMessage(error);
1328
+ this.logger.error('Instance AI run error', {
1329
+ error: errorMessage,
1330
+ threadId,
1331
+ runId,
1332
+ });
1333
+ await this.finalizeRunTracing(runId, tracing, {
1334
+ status: 'error',
1335
+ reason: errorMessage,
1336
+ });
1337
+ messageTraceFinalization = {
1338
+ status: 'error',
1339
+ reason: errorMessage,
1340
+ metadata: { completion_source: 'orchestrator' },
1341
+ };
1342
+ this.eventBus.publish(threadId, {
1343
+ type: 'run-finish',
1344
+ runId,
1345
+ agentId: ORCHESTRATOR_AGENT_ID,
1346
+ payload: {
1347
+ status: 'error',
1348
+ reason: errorMessage,
1349
+ },
1350
+ });
1351
+ }
1352
+ finally {
1353
+ this.runState.clearActiveRun(threadId);
1354
+ this.threadPushRef.delete(threadId);
1355
+ this.domainAccessTrackersByThread.get(threadId)?.clearRun(runId);
1356
+ if (messageTraceFinalization) {
1357
+ await this.maybeFinalizeRunTraceRoot(runId, messageTraceFinalization);
1358
+ }
1359
+ if (!this.runState.hasSuspendedRun(threadId) && mastraRunId) {
1360
+ void this.cleanupMastraSnapshots(mastraRunId);
1361
+ }
1362
+ }
1363
+ }
1364
+ async resolveConfirmation(requestingUserId, requestId, data) {
1365
+ if (this.runState.resolvePendingConfirmation(requestingUserId, requestId, data)) {
1366
+ this.logger.debug('Resolved pending confirmation (sub-agent HITL)', {
1367
+ requestId,
1368
+ approved: data.approved,
1369
+ });
1370
+ return true;
1371
+ }
1372
+ this.logger.debug('Pending confirmation not found, trying suspended run resume', {
1373
+ requestId,
1374
+ approved: data.approved,
1375
+ });
1376
+ return await this.resumeSuspendedRun(requestingUserId, requestId, data);
1377
+ }
1378
+ async resumeSuspendedRun(requestingUserId, requestId, data) {
1379
+ const suspended = this.runState.findSuspendedByRequestId(requestId);
1380
+ if (!suspended) {
1381
+ this.logger.warn('Confirmation target not found: no pending confirmation or suspended run', {
1382
+ requestId,
1383
+ approved: data.approved,
1384
+ });
1385
+ return false;
1386
+ }
1387
+ const { agent, runId, mastraRunId, threadId, user, toolCallId, abortController, tracing } = suspended;
1388
+ if (user.id !== requestingUserId)
1389
+ return false;
1390
+ this.runState.activateSuspendedRun(threadId);
1391
+ const credentialsPayload = data.nodeCredentials ?? data.credentials;
1392
+ const resumeData = {
1393
+ approved: data.approved,
1394
+ ...(data.credentialId ? { credentialId: data.credentialId } : {}),
1395
+ ...(credentialsPayload ? { credentials: credentialsPayload } : {}),
1396
+ ...(data.autoSetup ? { autoSetup: data.autoSetup } : {}),
1397
+ ...(data.userInput !== undefined ? { userInput: data.userInput } : {}),
1398
+ ...(data.domainAccessAction ? { domainAccessAction: data.domainAccessAction } : {}),
1399
+ ...(data.action ? { action: data.action } : {}),
1400
+ ...(data.nodeParameters ? { nodeParameters: data.nodeParameters } : {}),
1401
+ ...(data.testTriggerNode ? { testTriggerNode: data.testTriggerNode } : {}),
1402
+ ...(data.answers ? { answers: data.answers } : {}),
1403
+ ...(data.resourceDecision ? { resourceDecision: data.resourceDecision } : {}),
1404
+ };
1405
+ void this.processResumedStream(agent, resumeData, {
1406
+ runId,
1407
+ mastraRunId,
1408
+ threadId,
1409
+ user,
1410
+ toolCallId,
1411
+ signal: abortController.signal,
1412
+ abortController,
1413
+ snapshotStorage: this.dbSnapshotStorage,
1414
+ tracing,
1415
+ });
1416
+ return true;
1417
+ }
1418
+ async processResumedStream(agent, resumeData, opts) {
1419
+ let messageTraceFinalization;
1420
+ try {
1421
+ const result = opts.tracing
1422
+ ? await opts.tracing.withRunTree(opts.tracing.actorRun, async () => {
1423
+ return await (0, instance_ai_1.resumeAgentRun)(agent, resumeData, {
1424
+ runId: opts.mastraRunId,
1425
+ toolCallId: opts.toolCallId,
1426
+ memory: { resource: opts.user.id, thread: opts.threadId },
1427
+ }, {
1428
+ threadId: opts.threadId,
1429
+ runId: opts.runId,
1430
+ agentId: ORCHESTRATOR_AGENT_ID,
1431
+ signal: opts.signal,
1432
+ eventBus: this.eventBus,
1433
+ logger: this.logger,
1434
+ mastraRunId: opts.mastraRunId,
1435
+ });
1436
+ })
1437
+ : await (0, instance_ai_1.resumeAgentRun)(agent, resumeData, {
1438
+ runId: opts.mastraRunId,
1439
+ toolCallId: opts.toolCallId,
1440
+ memory: { resource: opts.user.id, thread: opts.threadId },
1441
+ }, {
1442
+ threadId: opts.threadId,
1443
+ runId: opts.runId,
1444
+ agentId: ORCHESTRATOR_AGENT_ID,
1445
+ signal: opts.signal,
1446
+ eventBus: this.eventBus,
1447
+ logger: this.logger,
1448
+ mastraRunId: opts.mastraRunId,
1449
+ });
1450
+ if (result.status === 'suspended') {
1451
+ if (result.suspension) {
1452
+ this.runState.suspendRun(opts.threadId, {
1453
+ runId: opts.runId,
1454
+ mastraRunId: result.mastraRunId,
1455
+ agent,
1456
+ threadId: opts.threadId,
1457
+ user: opts.user,
1458
+ toolCallId: result.suspension.toolCallId,
1459
+ requestId: result.suspension.requestId,
1460
+ abortController: opts.abortController,
1461
+ messageGroupId: this.traceContextsByRunId.get(opts.runId)?.messageGroupId,
1462
+ createdAt: Date.now(),
1463
+ tracing: opts.tracing,
1464
+ });
1465
+ }
1466
+ const intermediateText = await (result.text ?? Promise.resolve(''));
1467
+ if (intermediateText) {
1468
+ this.telemetry.track('Builder sent message', {
1469
+ thread_id: opts.threadId,
1470
+ message: intermediateText,
1471
+ is_intermediate: true,
1472
+ });
1473
+ }
1474
+ if (result.confirmationEvent) {
1475
+ this.trackConfirmationRequest(opts.threadId, result.confirmationEvent);
1476
+ this.eventBus.publish(opts.threadId, result.confirmationEvent);
1477
+ }
1478
+ await this.saveAgentTreeSnapshot(opts.threadId, opts.runId, opts.snapshotStorage);
1479
+ return;
1480
+ }
1481
+ const outputText = await (result.text ?? Promise.resolve(''));
1482
+ const finalStatus = result.status === 'errored' ? 'error' : result.status;
1483
+ await this.finalizeRunTracing(opts.runId, opts.tracing, {
1484
+ status: finalStatus,
1485
+ outputText,
1486
+ });
1487
+ messageTraceFinalization = {
1488
+ status: finalStatus,
1489
+ outputText,
1490
+ metadata: { completion_source: 'orchestrator' },
1491
+ };
1492
+ await this.finalizeRun(opts.threadId, opts.runId, result.status, opts.snapshotStorage);
1493
+ if (result.status === 'completed') {
1494
+ this.telemetry.track('Builder sent message', {
1495
+ thread_id: opts.threadId,
1496
+ message: outputText,
1497
+ });
1498
+ this.telemetry.track('Builder satisfied user intent', {
1499
+ thread_id: opts.threadId,
1500
+ });
1501
+ }
1502
+ }
1503
+ catch (error) {
1504
+ if (opts.signal.aborted) {
1505
+ await this.finalizeRunTracing(opts.runId, opts.tracing, {
1506
+ status: 'cancelled',
1507
+ reason: 'user_cancelled',
1508
+ });
1509
+ messageTraceFinalization = {
1510
+ status: 'cancelled',
1511
+ reason: 'user_cancelled',
1512
+ metadata: { completion_source: 'orchestrator' },
1513
+ };
1514
+ this.publishRunFinish(opts.threadId, opts.runId, 'cancelled', 'user_cancelled');
1515
+ return;
1516
+ }
1517
+ const errorMessage = getErrorMessage(error);
1518
+ this.logger.error('Instance AI resumed run error', {
1519
+ error: errorMessage,
1520
+ threadId: opts.threadId,
1521
+ runId: opts.runId,
1522
+ });
1523
+ await this.finalizeRunTracing(opts.runId, opts.tracing, {
1524
+ status: 'error',
1525
+ reason: errorMessage,
1526
+ });
1527
+ messageTraceFinalization = {
1528
+ status: 'error',
1529
+ reason: errorMessage,
1530
+ metadata: { completion_source: 'orchestrator' },
1531
+ };
1532
+ this.eventBus.publish(opts.threadId, {
1533
+ type: 'run-finish',
1534
+ runId: opts.runId,
1535
+ agentId: ORCHESTRATOR_AGENT_ID,
1536
+ payload: {
1537
+ status: 'error',
1538
+ reason: errorMessage,
1539
+ },
1540
+ });
1541
+ }
1542
+ finally {
1543
+ this.runState.clearActiveRun(opts.threadId);
1544
+ this.threadPushRef.delete(opts.threadId);
1545
+ if (messageTraceFinalization) {
1546
+ await this.maybeFinalizeRunTraceRoot(opts.runId, messageTraceFinalization);
1547
+ }
1548
+ }
1549
+ }
1550
+ spawnBackgroundTask(runId, opts, snapshotStorage, messageGroupIdOverride) {
1551
+ this.backgroundTasks.spawn({
1552
+ taskId: opts.taskId,
1553
+ threadId: opts.threadId,
1554
+ runId,
1555
+ role: opts.role,
1556
+ agentId: opts.agentId,
1557
+ messageGroupId: messageGroupIdOverride ?? this.runState.getMessageGroupId(opts.threadId),
1558
+ plannedTaskId: opts.plannedTaskId,
1559
+ workItemId: opts.workItemId,
1560
+ traceContext: opts.traceContext,
1561
+ run: opts.run,
1562
+ onLimitReached: async (errorMessage) => {
1563
+ await this.finalizeDetachedTraceRun(opts.taskId, opts.traceContext, {
1564
+ status: 'failed',
1565
+ outputs: {
1566
+ taskId: opts.taskId,
1567
+ agentId: opts.agentId,
1568
+ role: opts.role,
1569
+ },
1570
+ error: errorMessage,
1571
+ metadata: {
1572
+ ...(opts.plannedTaskId ? { planned_task_id: opts.plannedTaskId } : {}),
1573
+ ...(opts.workItemId ? { work_item_id: opts.workItemId } : {}),
1574
+ },
1575
+ });
1576
+ this.eventBus.publish(opts.threadId, {
1577
+ type: 'agent-completed',
1578
+ runId,
1579
+ agentId: opts.agentId,
1580
+ payload: {
1581
+ role: opts.role,
1582
+ result: '',
1583
+ error: errorMessage,
1584
+ },
1585
+ });
1586
+ },
1587
+ onCompleted: async (task) => {
1588
+ await this.finalizeBackgroundTaskTracing(task, 'completed');
1589
+ this.eventBus.publish(opts.threadId, {
1590
+ type: 'agent-completed',
1591
+ runId,
1592
+ agentId: opts.agentId,
1593
+ payload: { role: opts.role, result: task.result ?? '' },
1594
+ });
1595
+ const user = this.runState.getThreadUser(opts.threadId);
1596
+ if (user) {
1597
+ await this.handlePlannedTaskSettlement(user, task, 'succeeded');
1598
+ }
1599
+ },
1600
+ onFailed: async (task) => {
1601
+ await this.finalizeBackgroundTaskTracing(task, 'failed');
1602
+ this.eventBus.publish(opts.threadId, {
1603
+ type: 'agent-completed',
1604
+ runId,
1605
+ agentId: opts.agentId,
1606
+ payload: { role: opts.role, result: '', error: task.error ?? 'Unknown error' },
1607
+ });
1608
+ const user = this.runState.getThreadUser(opts.threadId);
1609
+ if (user) {
1610
+ await this.handlePlannedTaskSettlement(user, task, 'failed');
1611
+ }
1612
+ },
1613
+ onSettled: async (task) => {
1614
+ await this.saveAgentTreeSnapshot(opts.threadId, runId, snapshotStorage, true, task.messageGroupId);
1615
+ if (!task.plannedTaskId) {
1616
+ const remaining = this.backgroundTasks.getRunningTasks(opts.threadId);
1617
+ const hasActiveRun = !!this.runState.getActiveRunId(opts.threadId);
1618
+ const hasSuspendedRun = this.runState.hasSuspendedRun(opts.threadId);
1619
+ if (remaining.length === 0 && !hasActiveRun && !hasSuspendedRun) {
1620
+ const user = this.runState.getThreadUser(opts.threadId);
1621
+ if (user) {
1622
+ const payload = JSON.stringify({
1623
+ role: opts.role,
1624
+ status: task.result ? 'completed' : task.error ? 'failed' : 'finished',
1625
+ result: task.result ?? undefined,
1626
+ error: task.error ?? undefined,
1627
+ }, null, 2);
1628
+ await this.startInternalFollowUpRun(user, opts.threadId, `<background-task-completed>\n${payload}\n</background-task-completed>\n\n${internal_messages_1.AUTO_FOLLOW_UP_MESSAGE}`, this.runState.getThreadResearchMode(opts.threadId), task.messageGroupId);
1629
+ }
1630
+ }
1631
+ }
1632
+ },
1633
+ });
1634
+ }
1635
+ async buildMessageWithRunningTasks(threadId, message) {
1636
+ return await (0, instance_ai_1.enrichMessageWithBackgroundTasks)(message, this.backgroundTasks.getRunningTasks(threadId), {
1637
+ formatTask: async (task) => `[Running task — ${task.role}]: taskId=${task.taskId}`,
1638
+ });
1639
+ }
1640
+ trackConfirmationRequest(threadId, confirmationEvent) {
1641
+ const payload = confirmationEvent.payload;
1642
+ const inputThreadId = (0, nanoid_1.nanoid)();
1643
+ payload.inputThreadId = inputThreadId;
1644
+ const inputType = payload.inputType;
1645
+ let type;
1646
+ if (inputType) {
1647
+ type = inputType;
1648
+ }
1649
+ else if (Array.isArray(payload.setupRequests) && payload.setupRequests.length > 0) {
1650
+ type = 'setup';
1651
+ }
1652
+ else if (Array.isArray(payload.credentialRequests) && payload.credentialRequests.length > 0) {
1653
+ type = 'credential-setup';
1654
+ }
1655
+ else {
1656
+ type = 'approval';
1657
+ }
1658
+ let numSteps = 1;
1659
+ if (Array.isArray(payload.questions)) {
1660
+ numSteps = payload.questions.length;
1661
+ }
1662
+ else if (Array.isArray(payload.setupRequests)) {
1663
+ numSteps = payload.setupRequests.length;
1664
+ }
1665
+ else if (Array.isArray(payload.credentialRequests)) {
1666
+ numSteps = payload.credentialRequests.length;
1667
+ }
1668
+ this.telemetry.track('Builder asked for input', {
1669
+ thread_id: threadId,
1670
+ input_thread_id: inputThreadId,
1671
+ type,
1672
+ num_steps: numSteps,
1673
+ });
1674
+ }
1675
+ publishRunFinish(threadId, runId, status, reason) {
1676
+ const effectiveStatus = status === 'errored' ? 'error' : status;
1677
+ this.eventBus.publish(threadId, {
1678
+ type: 'run-finish',
1679
+ runId,
1680
+ agentId: ORCHESTRATOR_AGENT_ID,
1681
+ payload: status === 'cancelled'
1682
+ ? { status: effectiveStatus, reason: reason ?? 'user_cancelled' }
1683
+ : { status: effectiveStatus },
1684
+ });
1685
+ }
1686
+ async finalizeRun(threadId, runId, status, snapshotStorage, options) {
1687
+ this.publishRunFinish(threadId, runId, status);
1688
+ if (status === 'completed') {
1689
+ await this.saveAgentTreeSnapshot(threadId, runId, snapshotStorage);
1690
+ if (options?.userId && options?.modelId) {
1691
+ void this.refineTitleIfNeeded(threadId, options.userId, options.modelId);
1692
+ }
1693
+ }
1694
+ }
1695
+ async refineTitleIfNeeded(threadId, userId, modelId) {
1696
+ try {
1697
+ const memory = (0, instance_ai_1.createMemory)(this.createMemoryConfig());
1698
+ const thread = await memory.getThreadById({ threadId });
1699
+ if (!thread?.title)
1700
+ return;
1701
+ if (thread.metadata?.titleRefined)
1702
+ return;
1703
+ const result = await memory.recall({ threadId, resourceId: userId, perPage: 5 });
1704
+ const firstUserMsg = result.messages.find((m) => m.role === 'user');
1705
+ if (!firstUserMsg)
1706
+ return;
1707
+ const userText = typeof firstUserMsg.content === 'string'
1708
+ ? firstUserMsg.content
1709
+ : JSON.stringify(firstUserMsg.content);
1710
+ const llmTitle = await (0, instance_ai_1.generateThreadTitle)(modelId, userText);
1711
+ if (!llmTitle)
1712
+ return;
1713
+ await (0, instance_ai_1.patchThread)(memory, {
1714
+ threadId,
1715
+ update: ({ metadata }) => ({
1716
+ title: llmTitle,
1717
+ metadata: { ...metadata, titleRefined: true },
1718
+ }),
1719
+ });
1720
+ this.eventBus.publish(threadId, {
1721
+ type: 'thread-title-updated',
1722
+ runId: '',
1723
+ agentId: ORCHESTRATOR_AGENT_ID,
1724
+ payload: { title: llmTitle },
1725
+ });
1726
+ }
1727
+ catch (error) {
1728
+ this.logger.warn('Failed to refine thread title', {
1729
+ threadId,
1730
+ error: getErrorMessage(error),
1731
+ });
1732
+ }
1733
+ }
1734
+ async cleanupMastraSnapshots(mastraRunId) {
1735
+ try {
1736
+ const workflowsStorage = this.compositeStore.stores.workflows;
1737
+ await workflowsStorage.deleteAllByRunId(mastraRunId);
1738
+ }
1739
+ catch (error) {
1740
+ this.logger.warn('Failed to clean up Mastra workflow snapshots', {
1741
+ mastraRunId,
1742
+ error: getErrorMessage(error),
1743
+ });
1744
+ }
1745
+ }
1746
+ async saveAgentTreeSnapshot(threadId, runId, snapshotStorage, isUpdate = false, overrideMessageGroupId) {
1747
+ try {
1748
+ const messageGroupId = overrideMessageGroupId ?? this.runState.getMessageGroupId(threadId);
1749
+ let events;
1750
+ let groupRunIds;
1751
+ if (messageGroupId) {
1752
+ groupRunIds = this.getRunIdsForMessageGroup(messageGroupId);
1753
+ events = this.eventBus.getEventsForRuns(threadId, groupRunIds);
1754
+ }
1755
+ else {
1756
+ events = this.eventBus.getEventsForRun(threadId, runId);
1757
+ }
1758
+ const agentTree = (0, instance_ai_1.buildAgentTreeFromEvents)(events);
1759
+ if (isUpdate) {
1760
+ await snapshotStorage.updateLast(threadId, agentTree, runId, messageGroupId, groupRunIds);
1761
+ }
1762
+ else {
1763
+ await snapshotStorage.save(threadId, agentTree, runId, messageGroupId, groupRunIds);
1764
+ }
1765
+ }
1766
+ catch (error) {
1767
+ this.logger.warn('Failed to save agent tree snapshot', {
1768
+ threadId,
1769
+ runId,
1770
+ error: error instanceof Error ? error.message : String(error),
1771
+ });
1772
+ }
1773
+ }
1774
+ parseMcpServers(raw) {
1775
+ if (!raw.trim())
1776
+ return [];
1777
+ return raw.split(',').map((entry) => {
1778
+ const [name, url] = entry.trim().split('=');
1779
+ return { name: name.trim(), url: url?.trim() };
1780
+ });
1781
+ }
1782
+ };
1783
+ exports.InstanceAiService = InstanceAiService;
1784
+ exports.InstanceAiService = InstanceAiService = __decorate([
1785
+ (0, di_1.Service)(),
1786
+ __metadata("design:paramtypes", [backend_common_1.Logger,
1787
+ config_1.GlobalConfig,
1788
+ instance_ai_adapter_service_1.InstanceAiAdapterService,
1789
+ in_process_event_bus_1.InProcessEventBus,
1790
+ instance_ai_settings_service_1.InstanceAiSettingsService,
1791
+ typeorm_composite_store_1.TypeORMCompositeStore,
1792
+ compaction_service_1.InstanceAiCompactionService,
1793
+ ai_service_1.AiService,
1794
+ push_1.Push,
1795
+ instance_ai_thread_repository_1.InstanceAiThreadRepository,
1796
+ url_service_1.UrlService,
1797
+ db_snapshot_storage_1.DbSnapshotStorage,
1798
+ db_iteration_log_storage_1.DbIterationLogStorage,
1799
+ source_control_preferences_service_ee_1.SourceControlPreferencesService,
1800
+ telemetry_1.Telemetry])
1801
+ ], InstanceAiService);
1802
+ //# sourceMappingURL=instance-ai.service.js.map