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