@mastra/factory 0.29.0-alpha.4 → 0.29.0-alpha.6

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 (401) hide show
  1. package/README.md +172 -89
  2. package/dist/boards/board-events.d.ts +89 -9
  3. package/dist/boards/board-events.d.ts.map +1 -1
  4. package/dist/boards/board-events.js +176 -13
  5. package/dist/boards/board-events.js.map +1 -1
  6. package/dist/boards/board-writes.d.ts.map +1 -1
  7. package/dist/boards/board-writes.js +14 -1
  8. package/dist/boards/board-writes.js.map +1 -1
  9. package/dist/boards/busy-card.d.ts +11 -0
  10. package/dist/boards/busy-card.d.ts.map +1 -0
  11. package/dist/boards/busy-card.js +15 -0
  12. package/dist/boards/busy-card.js.map +1 -0
  13. package/dist/boards/card-facts.d.ts.map +1 -1
  14. package/dist/boards/card-facts.js +18 -4
  15. package/dist/boards/card-facts.js.map +1 -1
  16. package/dist/boards/index.d.ts +2 -1
  17. package/dist/boards/index.d.ts.map +1 -1
  18. package/dist/boards/index.js +3 -2
  19. package/dist/boards/intake-dry-run.d.ts +109 -0
  20. package/dist/boards/intake-dry-run.d.ts.map +1 -0
  21. package/dist/boards/intake-dry-run.js +158 -0
  22. package/dist/boards/intake-dry-run.js.map +1 -0
  23. package/dist/boards/intake-lookup.d.ts +32 -0
  24. package/dist/boards/intake-lookup.d.ts.map +1 -0
  25. package/dist/boards/intake-lookup.js +12 -0
  26. package/dist/boards/intake-lookup.js.map +1 -0
  27. package/dist/boards/intake-order.d.ts +32 -0
  28. package/dist/boards/intake-order.d.ts.map +1 -0
  29. package/dist/boards/intake-order.js +60 -0
  30. package/dist/boards/intake-order.js.map +1 -0
  31. package/dist/boards/intake-routing.d.ts +246 -35
  32. package/dist/boards/intake-routing.d.ts.map +1 -1
  33. package/dist/boards/intake-routing.js +437 -52
  34. package/dist/boards/intake-routing.js.map +1 -1
  35. package/dist/boards/reroute.d.ts +7 -3
  36. package/dist/boards/reroute.d.ts.map +1 -1
  37. package/dist/boards/reroute.js +21 -4
  38. package/dist/boards/reroute.js.map +1 -1
  39. package/dist/boards/semantics.d.ts +8 -28
  40. package/dist/boards/semantics.d.ts.map +1 -1
  41. package/dist/boards/semantics.js +14 -40
  42. package/dist/boards/semantics.js.map +1 -1
  43. package/dist/boards/work-routes.d.ts +31 -11
  44. package/dist/boards/work-routes.d.ts.map +1 -1
  45. package/dist/boards/work-routes.js +104 -20
  46. package/dist/boards/work-routes.js.map +1 -1
  47. package/dist/factory.d.ts +37 -1
  48. package/dist/factory.d.ts.map +1 -1
  49. package/dist/factory.js +127 -48
  50. package/dist/factory.js.map +1 -1
  51. package/dist/integrations/base.d.ts +9 -0
  52. package/dist/integrations/base.d.ts.map +1 -1
  53. package/dist/integrations/dependabot/rules.js +1 -1
  54. package/dist/integrations/dependabot/rules.js.map +1 -1
  55. package/dist/integrations/github/default-rules.d.ts +22 -1
  56. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  57. package/dist/integrations/github/default-rules.js +23 -5
  58. package/dist/integrations/github/default-rules.js.map +1 -1
  59. package/dist/integrations/github/intake-lookup.d.ts +16 -0
  60. package/dist/integrations/github/intake-lookup.d.ts.map +1 -0
  61. package/dist/integrations/github/intake-lookup.js +76 -0
  62. package/dist/integrations/github/intake-lookup.js.map +1 -0
  63. package/dist/integrations/github/integration.d.ts +19 -5
  64. package/dist/integrations/github/integration.d.ts.map +1 -1
  65. package/dist/integrations/github/integration.js +21 -6
  66. package/dist/integrations/github/integration.js.map +1 -1
  67. package/dist/integrations/github/issue-intake.d.ts +15 -0
  68. package/dist/integrations/github/issue-intake.d.ts.map +1 -0
  69. package/dist/integrations/github/issue-intake.js +50 -0
  70. package/dist/integrations/github/issue-intake.js.map +1 -0
  71. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  72. package/dist/integrations/github/issue-reconciler.js +10 -1
  73. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  74. package/dist/integrations/github/review-status-reporter.js +1 -1
  75. package/dist/integrations/github/routes.d.ts.map +1 -1
  76. package/dist/integrations/github/routes.js +14 -2
  77. package/dist/integrations/github/routes.js.map +1 -1
  78. package/dist/integrations/github/rules.d.ts +14 -1
  79. package/dist/integrations/github/rules.d.ts.map +1 -1
  80. package/dist/integrations/github/rules.js +221 -30
  81. package/dist/integrations/github/rules.js.map +1 -1
  82. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  83. package/dist/integrations/github/sandbox.js +30 -4
  84. package/dist/integrations/github/sandbox.js.map +1 -1
  85. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  86. package/dist/integrations/gitlab/default-rules.js +19 -3
  87. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  88. package/dist/integrations/gitlab/intake-lookup.d.ts +17 -0
  89. package/dist/integrations/gitlab/intake-lookup.d.ts.map +1 -0
  90. package/dist/integrations/gitlab/intake-lookup.js +85 -0
  91. package/dist/integrations/gitlab/intake-lookup.js.map +1 -0
  92. package/dist/integrations/gitlab/integration.d.ts +5 -0
  93. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  94. package/dist/integrations/gitlab/integration.js +21 -1
  95. package/dist/integrations/gitlab/integration.js.map +1 -1
  96. package/dist/integrations/gitlab/rules.d.ts +20 -0
  97. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  98. package/dist/integrations/gitlab/rules.js +108 -12
  99. package/dist/integrations/gitlab/rules.js.map +1 -1
  100. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  101. package/dist/integrations/incidentio/rules.js +14 -4
  102. package/dist/integrations/incidentio/rules.js.map +1 -1
  103. package/dist/integrations/jira/rules.d.ts.map +1 -1
  104. package/dist/integrations/jira/rules.js +12 -2
  105. package/dist/integrations/jira/rules.js.map +1 -1
  106. package/dist/integrations/linear/rules.d.ts.map +1 -1
  107. package/dist/integrations/linear/rules.js +13 -2
  108. package/dist/integrations/linear/rules.js.map +1 -1
  109. package/dist/integrations/platform/connect/routes.d.ts +43 -1
  110. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  111. package/dist/integrations/platform/connect/routes.js +82 -7
  112. package/dist/integrations/platform/connect/routes.js.map +1 -1
  113. package/dist/integrations/platform/connect/session-tools.d.ts +12 -0
  114. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -1
  115. package/dist/integrations/platform/connect/session-tools.js +28 -10
  116. package/dist/integrations/platform/connect/session-tools.js.map +1 -1
  117. package/dist/integrations/platform/github/event-worker.js +9 -1
  118. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  119. package/dist/integrations/platform/github/integration.d.ts +6 -6
  120. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  121. package/dist/integrations/platform/github/integration.js +22 -3
  122. package/dist/integrations/platform/github/integration.js.map +1 -1
  123. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
  124. package/dist/integrations/platform/vanta/integration.js +3 -3
  125. package/dist/integrations/platform/vanta/integration.js.map +1 -1
  126. package/dist/integrations/pull-request-head.d.ts +1 -1
  127. package/dist/integrations/pull-request-head.d.ts.map +1 -1
  128. package/dist/integrations/pull-request-head.js +5 -0
  129. package/dist/integrations/pull-request-head.js.map +1 -1
  130. package/dist/integrations/vanta/rules.js +1 -1
  131. package/dist/integrations/vanta/rules.js.map +1 -1
  132. package/dist/integrations/vanta/sync.d.ts +9 -0
  133. package/dist/integrations/vanta/sync.d.ts.map +1 -1
  134. package/dist/integrations/vanta/sync.js +10 -1
  135. package/dist/integrations/vanta/sync.js.map +1 -1
  136. package/dist/routes/board-snapshot.d.ts +13 -6
  137. package/dist/routes/board-snapshot.d.ts.map +1 -1
  138. package/dist/routes/board-snapshot.js +42 -20
  139. package/dist/routes/board-snapshot.js.map +1 -1
  140. package/dist/routes/boards.js.map +1 -1
  141. package/dist/routes/config.d.ts +17 -2
  142. package/dist/routes/config.d.ts.map +1 -1
  143. package/dist/routes/config.js +247 -77
  144. package/dist/routes/config.js.map +1 -1
  145. package/dist/routes/contracts.d.ts +1294 -7
  146. package/dist/routes/contracts.d.ts.map +1 -1
  147. package/dist/routes/contracts.js +603 -20
  148. package/dist/routes/contracts.js.map +1 -1
  149. package/dist/routes/custom-endpoint-url.d.ts +8 -0
  150. package/dist/routes/custom-endpoint-url.d.ts.map +1 -0
  151. package/dist/routes/custom-endpoint-url.js +45 -0
  152. package/dist/routes/custom-endpoint-url.js.map +1 -0
  153. package/dist/routes/custom-provider-source.d.ts +24 -8
  154. package/dist/routes/custom-provider-source.d.ts.map +1 -1
  155. package/dist/routes/custom-provider-source.js +93 -43
  156. package/dist/routes/custom-provider-source.js.map +1 -1
  157. package/dist/routes/intake-check.d.ts +92 -0
  158. package/dist/routes/intake-check.d.ts.map +1 -0
  159. package/dist/routes/intake-check.js +322 -0
  160. package/dist/routes/intake-check.js.map +1 -0
  161. package/dist/routes/intake-routes.d.ts +10 -2
  162. package/dist/routes/intake-routes.d.ts.map +1 -1
  163. package/dist/routes/intake-routes.js +292 -11
  164. package/dist/routes/intake-routes.js.map +1 -1
  165. package/dist/routes/intake.d.ts +6 -0
  166. package/dist/routes/intake.d.ts.map +1 -1
  167. package/dist/routes/intake.js +20 -0
  168. package/dist/routes/intake.js.map +1 -1
  169. package/dist/routes/mastra-gateway.d.ts.map +1 -1
  170. package/dist/routes/mastra-gateway.js +3 -2
  171. package/dist/routes/mastra-gateway.js.map +1 -1
  172. package/dist/routes/project-sessions.d.ts +61 -0
  173. package/dist/routes/project-sessions.d.ts.map +1 -0
  174. package/dist/routes/project-sessions.js +135 -0
  175. package/dist/routes/project-sessions.js.map +1 -0
  176. package/dist/routes/projects.d.ts +6 -1
  177. package/dist/routes/projects.d.ts.map +1 -1
  178. package/dist/routes/projects.js +19 -3
  179. package/dist/routes/projects.js.map +1 -1
  180. package/dist/routes/provider-credentials.d.ts +10 -1
  181. package/dist/routes/provider-credentials.d.ts.map +1 -1
  182. package/dist/routes/provider-credentials.js +13 -16
  183. package/dist/routes/provider-credentials.js.map +1 -1
  184. package/dist/routes/run-queue.d.ts +6 -6
  185. package/dist/routes/run-queue.d.ts.map +1 -1
  186. package/dist/routes/run-queue.js +28 -8
  187. package/dist/routes/run-queue.js.map +1 -1
  188. package/dist/routes/session-rows.d.ts +30 -0
  189. package/dist/routes/session-rows.d.ts.map +1 -0
  190. package/dist/routes/session-rows.js +94 -0
  191. package/dist/routes/session-rows.js.map +1 -0
  192. package/dist/routes/source-control-sessions.d.ts +4 -5
  193. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  194. package/dist/routes/source-control-sessions.js +8 -87
  195. package/dist/routes/source-control-sessions.js.map +1 -1
  196. package/dist/routes/surface.d.ts +16 -1
  197. package/dist/routes/surface.d.ts.map +1 -1
  198. package/dist/routes/surface.js +41 -30
  199. package/dist/routes/surface.js.map +1 -1
  200. package/dist/routes/tenant-credentials.d.ts.map +1 -1
  201. package/dist/routes/tenant-credentials.js +4 -4
  202. package/dist/routes/tenant-credentials.js.map +1 -1
  203. package/dist/routes/work-item-starters.d.ts +1 -0
  204. package/dist/routes/work-item-starters.d.ts.map +1 -1
  205. package/dist/routes/work-item-starters.js +14 -2
  206. package/dist/routes/work-item-starters.js.map +1 -1
  207. package/dist/routes/work-items.d.ts +22 -3
  208. package/dist/routes/work-items.d.ts.map +1 -1
  209. package/dist/routes/work-items.js +124 -48
  210. package/dist/routes/work-items.js.map +1 -1
  211. package/dist/rules/binding-context.d.ts +5 -0
  212. package/dist/rules/binding-context.d.ts.map +1 -1
  213. package/dist/rules/binding-context.js +51 -5
  214. package/dist/rules/binding-context.js.map +1 -1
  215. package/dist/rules/dispatch-errors.js +1 -1
  216. package/dist/rules/dispatch-errors.js.map +1 -1
  217. package/dist/rules/dispatcher.d.ts +39 -7
  218. package/dist/rules/dispatcher.d.ts.map +1 -1
  219. package/dist/rules/dispatcher.js +363 -123
  220. package/dist/rules/dispatcher.js.map +1 -1
  221. package/dist/rules/event-rules.d.ts +69 -1
  222. package/dist/rules/event-rules.d.ts.map +1 -1
  223. package/dist/rules/event-rules.js +151 -5
  224. package/dist/rules/event-rules.js.map +1 -1
  225. package/dist/rules/review-source-tool.js +1 -1
  226. package/dist/rules/rule-group.d.ts +18 -1
  227. package/dist/rules/rule-group.d.ts.map +1 -1
  228. package/dist/rules/rule-group.js +52 -8
  229. package/dist/rules/rule-group.js.map +1 -1
  230. package/dist/rules/run-bearing.d.ts +8 -0
  231. package/dist/rules/run-bearing.d.ts.map +1 -0
  232. package/dist/rules/run-bearing.js +11 -0
  233. package/dist/rules/run-bearing.js.map +1 -0
  234. package/dist/rules/start-coordinator.d.ts +2 -3
  235. package/dist/rules/start-coordinator.d.ts.map +1 -1
  236. package/dist/rules/start-coordinator.js +25 -38
  237. package/dist/rules/start-coordinator.js.map +1 -1
  238. package/dist/rules/tools.js +2 -1
  239. package/dist/rules/tools.js.map +1 -1
  240. package/dist/rules/transition-service.d.ts +16 -0
  241. package/dist/rules/transition-service.d.ts.map +1 -1
  242. package/dist/rules/transition-service.js +34 -10
  243. package/dist/rules/transition-service.js.map +1 -1
  244. package/dist/rules/types.d.ts +18 -5
  245. package/dist/rules/types.d.ts.map +1 -1
  246. package/dist/rules/types.js +2 -1
  247. package/dist/rules/types.js.map +1 -1
  248. package/dist/rules/update-fold.d.ts +32 -0
  249. package/dist/rules/update-fold.d.ts.map +1 -0
  250. package/dist/rules/update-fold.js +60 -0
  251. package/dist/rules/update-fold.js.map +1 -0
  252. package/dist/rules/validation.d.ts.map +1 -1
  253. package/dist/rules/validation.js +54 -6
  254. package/dist/rules/validation.js.map +1 -1
  255. package/dist/sandbox/session-retirement.d.ts +6 -0
  256. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  257. package/dist/sandbox/session-retirement.js +17 -0
  258. package/dist/sandbox/session-retirement.js.map +1 -1
  259. package/dist/session/factory-session.d.ts.map +1 -1
  260. package/dist/session/factory-session.js +2 -1
  261. package/dist/session/factory-session.js.map +1 -1
  262. package/dist/session/live-sessions.d.ts +6 -1
  263. package/dist/session/live-sessions.d.ts.map +1 -1
  264. package/dist/session/live-sessions.js +4 -0
  265. package/dist/session/live-sessions.js.map +1 -1
  266. package/dist/session/resource-migration.d.ts.map +1 -1
  267. package/dist/session/resource-migration.js +2 -3
  268. package/dist/session/resource-migration.js.map +1 -1
  269. package/dist/session/run-audit.d.ts +10 -1
  270. package/dist/session/run-audit.d.ts.map +1 -1
  271. package/dist/session/run-audit.js +9 -1
  272. package/dist/session/run-audit.js.map +1 -1
  273. package/dist/session/self-review-gate.d.ts +26 -2
  274. package/dist/session/self-review-gate.d.ts.map +1 -1
  275. package/dist/session/self-review-gate.js +60 -10
  276. package/dist/session/self-review-gate.js.map +1 -1
  277. package/dist/session/session-row-query.d.ts +25 -0
  278. package/dist/session/session-row-query.d.ts.map +1 -0
  279. package/dist/session/session-row-query.js +47 -0
  280. package/dist/session/session-row-query.js.map +1 -0
  281. package/dist/session/session-row-status.d.ts +16 -0
  282. package/dist/session/session-row-status.d.ts.map +1 -0
  283. package/dist/session/session-row-status.js +14 -0
  284. package/dist/session/session-row-status.js.map +1 -0
  285. package/dist/session/session-row-view.d.ts +13 -0
  286. package/dist/session/session-row-view.d.ts.map +1 -0
  287. package/dist/session/session-row-view.js +118 -0
  288. package/dist/session/session-row-view.js.map +1 -0
  289. package/dist/session/session-rows.d.ts +60 -0
  290. package/dist/session/session-rows.d.ts.map +1 -0
  291. package/dist/session/session-rows.js +307 -0
  292. package/dist/session/session-rows.js.map +1 -0
  293. package/dist/session/session-threads.d.ts.map +1 -1
  294. package/dist/session/session-threads.js +1 -0
  295. package/dist/session/session-threads.js.map +1 -1
  296. package/dist/session/session-unloader.d.ts +101 -0
  297. package/dist/session/session-unloader.d.ts.map +1 -0
  298. package/dist/session/session-unloader.js +278 -0
  299. package/dist/session/session-unloader.js.map +1 -0
  300. package/dist/session/source-control-tools.d.ts +14 -7
  301. package/dist/session/source-control-tools.d.ts.map +1 -1
  302. package/dist/session/source-control-tools.js +10 -2
  303. package/dist/session/source-control-tools.js.map +1 -1
  304. package/dist/session/work-item-repository.d.ts +49 -1
  305. package/dist/session/work-item-repository.d.ts.map +1 -1
  306. package/dist/session/work-item-repository.js +118 -15
  307. package/dist/session/work-item-repository.js.map +1 -1
  308. package/dist/session/work-item-state-processor.d.ts.map +1 -1
  309. package/dist/session/work-item-state-processor.js +44 -8
  310. package/dist/session/work-item-state-processor.js.map +1 -1
  311. package/dist/session-list-changes.d.ts +9 -0
  312. package/dist/session-list-changes.d.ts.map +1 -0
  313. package/dist/session-list-changes.js +54 -0
  314. package/dist/session-list-changes.js.map +1 -0
  315. package/dist/storage/announced-lists.d.ts +14 -0
  316. package/dist/storage/announced-lists.d.ts.map +1 -0
  317. package/dist/storage/announced-lists.js +78 -0
  318. package/dist/storage/announced-lists.js.map +1 -0
  319. package/dist/storage/domains/audit/actions.d.ts +2 -1
  320. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  321. package/dist/storage/domains/audit/actions.js +3 -1
  322. package/dist/storage/domains/audit/actions.js.map +1 -1
  323. package/dist/storage/domains/boards/base.d.ts +163 -15
  324. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  325. package/dist/storage/domains/boards/base.js +440 -48
  326. package/dist/storage/domains/boards/base.js.map +1 -1
  327. package/dist/storage/domains/boards/schemas.d.ts +6 -0
  328. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  329. package/dist/storage/domains/boards/schemas.js +95 -1
  330. package/dist/storage/domains/boards/schemas.js.map +1 -1
  331. package/dist/storage/domains/custom-providers/base.d.ts +62 -19
  332. package/dist/storage/domains/custom-providers/base.d.ts.map +1 -1
  333. package/dist/storage/domains/custom-providers/base.js +131 -100
  334. package/dist/storage/domains/custom-providers/base.js.map +1 -1
  335. package/dist/storage/domains/intake/base.d.ts +25 -7
  336. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  337. package/dist/storage/domains/intake/base.js +83 -19
  338. package/dist/storage/domains/intake/base.js.map +1 -1
  339. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  340. package/dist/storage/domains/projects/base.js +19 -10
  341. package/dist/storage/domains/projects/base.js.map +1 -1
  342. package/dist/storage/domains/source-control/base.d.ts +8 -0
  343. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  344. package/dist/storage/domains/source-control/base.js +110 -61
  345. package/dist/storage/domains/source-control/base.js.map +1 -1
  346. package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
  347. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  348. package/dist/storage/domains/source-control/inmemory.js +8 -5
  349. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  350. package/dist/storage/domains/work-items/base.d.ts +57 -18
  351. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  352. package/dist/storage/domains/work-items/base.js +168 -83
  353. package/dist/storage/domains/work-items/base.js.map +1 -1
  354. package/dist/storage/domains/work-items/cards.d.ts +3 -2
  355. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  356. package/dist/storage/domains/work-items/cards.js +4 -2
  357. package/dist/storage/domains/work-items/cards.js.map +1 -1
  358. package/dist/tools/audit-events-tool.d.ts +2 -2
  359. package/dist/tools/read-tools.d.ts +9 -5
  360. package/dist/tools/read-tools.d.ts.map +1 -1
  361. package/dist/tools/read-tools.js +61 -54
  362. package/dist/tools/read-tools.js.map +1 -1
  363. package/dist/tools/session-tools.d.ts +0 -13
  364. package/dist/tools/session-tools.d.ts.map +1 -1
  365. package/dist/tools/session-tools.js +128 -341
  366. package/dist/tools/session-tools.js.map +1 -1
  367. package/dist/tools/work-item-tools.d.ts +3 -0
  368. package/dist/tools/work-item-tools.d.ts.map +1 -1
  369. package/dist/tools/work-item-tools.js +99 -27
  370. package/dist/tools/work-item-tools.js.map +1 -1
  371. package/dist/work-item-branch.d.ts +4 -0
  372. package/dist/work-item-branch.d.ts.map +1 -1
  373. package/dist/work-item-branch.js +7 -1
  374. package/dist/work-item-branch.js.map +1 -1
  375. package/dist/work-items/card-context-sessions.d.ts +50 -0
  376. package/dist/work-items/card-context-sessions.d.ts.map +1 -0
  377. package/dist/work-items/card-context-sessions.js +84 -0
  378. package/dist/work-items/card-context-sessions.js.map +1 -0
  379. package/dist/work-items/card-reference.d.ts +21 -0
  380. package/dist/work-items/card-reference.d.ts.map +1 -0
  381. package/dist/work-items/card-reference.js +58 -0
  382. package/dist/work-items/card-reference.js.map +1 -0
  383. package/dist/work-items/change-requests.d.ts +87 -0
  384. package/dist/work-items/change-requests.d.ts.map +1 -0
  385. package/dist/work-items/change-requests.js +134 -0
  386. package/dist/work-items/change-requests.js.map +1 -0
  387. package/dist/work-items/create-work-item.d.ts +7 -2
  388. package/dist/work-items/create-work-item.d.ts.map +1 -1
  389. package/dist/work-items/create-work-item.js +44 -13
  390. package/dist/work-items/create-work-item.js.map +1 -1
  391. package/dist/work-items/list-related-cards.d.ts.map +1 -1
  392. package/dist/work-items/list-related-cards.js +1 -1
  393. package/dist/work-items/list-related-cards.js.map +1 -1
  394. package/dist/work-items/providers/github.d.ts.map +1 -1
  395. package/dist/work-items/providers/github.js +1 -0
  396. package/dist/work-items/providers/github.js.map +1 -1
  397. package/factory-skills/factory-build/SKILL.md +1 -1
  398. package/factory-skills/factory-plan/SKILL.md +5 -3
  399. package/factory-skills/factory-self-review/SKILL.md +2 -0
  400. package/factory-skills/factory-triage/SKILL.md +1 -1
  401. package/package.json +10 -10
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/jira/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryJiraRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { JiraEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface JiraIssueIngress {\n /** Stable issue reference — direct Jira id or the Platform-encoded issue reference. */\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Jira reporter, when available. */\n author: string | null;\n /** Jira project key the issue belongs to, when available. */\n project: string | null;\n /** Jira site host the issue was read from, when available. */\n site: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Jira source the issue was read from. */\n sourceId?: string | null;\n}\n\nexport interface JiraRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n jiraRules: JiraEventRules;\n}\n\nexport interface JiraRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: JiraIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Jira sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryJiraRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nexport class JiraRules {\n constructor(private readonly options: JiraRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: JiraRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'jira', type: 'issue', externalId: issue.id })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n // A card filed by hand from Settings › Intake holds the issue key, while the\n // sweep names the issue by its id. Its browse URL names both the site and the key.\n const itemsByUrl = new Map(\n items.flatMap(item => (item.externalSource?.url ? [[item.externalSource.url, item] as const] : [])),\n );\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per Jira issue per project; other projects may file their own.\n const relatedItem = itemsBySourceKey.get(issue.id) ?? itemsByUrl.get(issue.url);\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: JiraRulesIngress,\n issue: JiraIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `jira:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'issueClosed' : 'issueObserved';\n const context: FactoryJiraRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'jira', id: ingressId },\n cause: `jira.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'jira-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Jira rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId },\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Jira rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF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AS,MAAM,mBAAmB,SAAS,KAAK,QAAQ,SAAS;IACrE,OAAO,MAAM;IACb,kBAAkB,MAAM;GAC1B,CAAC;GACD,IAAI,QAAQ,YAAY,CAAC,EAAE,GAAG,OAAO,CAAC;EACxC;EAEA,MAAM,YAAY,MAAM,KAAK,QAAQ,QAAQ,qBAAqB;GAChE,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,YAAY,aAAa,MAAM;GAC/B,SAAS,EAAE,UAAU,UAAU;GAC/B,kBAAkB,aAAa,YAAY;GAC3C;GACA;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC;EACD,IAAI,UAAU,WAAW,SAAS;GAEhC,IAAI,WAAW,yBACb,MAAM,IAAI,MAAM,oCAAoC,UAAU,6BAA6B;GAE7F,MAAM,QAAQ,cAAc,MAAM,KAAK,QAAQ,QAAQ,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,YAAY;GAAG,CAAC,IAAI;GACzG,IAAI,eAAe,CAAC,OAAO,OAAO;GAClC,OAAO,KAAK,aAAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF"}
1
+ {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/jira/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { commitObservedChange, deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryJiraRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { JiraEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface JiraIssueIngress {\n /** Stable issue reference — direct Jira id or the Platform-encoded issue reference. */\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Jira reporter, when available. */\n author: string | null;\n /** Jira project key the issue belongs to, when available. */\n project: string | null;\n /** Jira site host the issue was read from, when available. */\n site: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Jira source the issue was read from. */\n sourceId?: string | null;\n}\n\nexport interface JiraRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n jiraRules: JiraEventRules;\n}\n\nexport interface JiraRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: JiraIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Jira sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryJiraRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.opened' };\n}\n\nexport class JiraRules {\n constructor(private readonly options: JiraRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: JiraRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'jira', type: 'issue', externalId: issue.id })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n // A card filed by hand from Settings › Intake holds the issue key, while the\n // sweep names the issue by its id. Its browse URL names both the site and the key.\n const itemsByUrl = new Map(\n items.flatMap(item => (item.externalSource?.url ? [[item.externalSource.url, item] as const] : [])),\n );\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per Jira issue per project; other projects may file their own.\n const relatedItem = itemsBySourceKey.get(issue.id) ?? itemsByUrl.get(issue.url);\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: JiraRulesIngress,\n issue: JiraIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `jira:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'issueClosed' : 'issueObserved';\n const context: FactoryJiraRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'jira', id: ingressId },\n cause: `jira.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'jira-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Jira rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId },\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Jira rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n if (relatedItem && event === 'issueObserved' && outcome.status === 'accepted' && !ownedByDeployment) {\n await commitObservedChange(this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n item: relatedItem,\n ingressId,\n actor,\n labels: issue.labels,\n assignee: issue.assignee,\n observedAt: issue.updatedAt,\n });\n }\n return committed.status;\n }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;E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AW,GAAG,UAAU,GAAG,SAAS,CAAC;AAE1D;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,IAAI,CAAC,wBAAwB,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC,GAAG,eAAe,GAAG,SAAS,CAK9H;AAED,qBAAa,WAAW;;IACV,OAAO,CAAC,QAAQ,CAAC,OAAO;IAApC,YAA6B,OAAO,EAAE,kBAAkB,EAAI;IAOtD,MAAM,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,aAAa,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAS5F;CAwKF;AAED,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE;IAAE,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAA;CAAE,EAC5C,OAAO,EAAE,kBAAkB,GAC1B,CAAC,CAAC,KAAK,EAAE,kBAAkB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAU/D"}
@@ -3,7 +3,7 @@ import "../../boards/index.js";
3
3
  import { boardEventHandlers, boardForWorkItem, eventBoardId, isTerminalWorkItem, rulePhaseField, withBoardClosure, withIntakeTarget } from "../../boards/semantics.js";
4
4
  import { toBoardSource } from "../../boards/project-boards.js";
5
5
  import { recordIntakeEvent } from "../../metrics/intake.js";
6
- import { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from "../../rules/event-rules.js";
6
+ import { commitObservedChange, deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from "../../rules/event-rules.js";
7
7
  import { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from "../../rules/validation.js";
8
8
  // src/integrations/linear/rules.ts
9
9
  const RULE_TIMEOUT_MS = 5e3;
@@ -27,7 +27,7 @@ function boardEventFor(context) {
27
27
  type: "work_item.closed",
28
28
  reason: closeReason(context.issue.stateType === "canceled")
29
29
  };
30
- return context.item ? void 0 : { type: "work_item.created" };
30
+ return context.item ? void 0 : { type: "work_item.opened" };
31
31
  }
32
32
  var LinearRules = class {
33
33
  options;
@@ -189,6 +189,17 @@ var LinearRules = class {
189
189
  if (relatedItem && !fresh) return "missing";
190
190
  return this.#ingestIssue(input, issue, fresh ?? void 0, attempt + 1);
191
191
  }
192
+ if (relatedItem && event === "issueObserved" && outcome.status === "accepted" && !ownedByDeployment) await commitObservedChange(this.options.storage, {
193
+ orgId: input.orgId,
194
+ factoryProjectId: input.factoryProjectId,
195
+ item: relatedItem,
196
+ ingressId,
197
+ actor,
198
+ labels: issue.labels,
199
+ assignee: issue.assignee,
200
+ observedAt: issue.updatedAt,
201
+ metadata: { linearAssignee: issue.assignee }
202
+ });
192
203
  return committed.status;
193
204
  }
194
205
  };
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/linear/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n isTerminalWorkItem,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { recordIntakeEvent } from '../../metrics/intake.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryLinearRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport type { LinearEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface LinearIssueIngress {\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Linear user who created the issue, when available. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Linear source the issue was read from (project or team). */\n sourceId?: string | null;\n projectId?: string | null;\n}\n\nexport interface LinearRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n linearRules: LinearEventRules;\n}\n\nexport interface LinearRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: LinearIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Linear sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryLinearRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nexport class LinearRules {\n constructor(private readonly options: LinearRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: LinearRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n try {\n const result = await this.#ingest(input);\n recordIntakeEvent('linear', result.status);\n return result;\n } catch (error) {\n recordIntakeEvent('linear', 'error');\n throw error;\n }\n }\n\n async #ingest(input: LinearRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'linear', type: 'issue', externalId: `linear:${issue.identifier}` })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per Linear issue per project; other projects may file their own.\n // The identifier finds the card filed under it; after Linear renamed the\n // identifier, the stable issue id finds it, preferring a live card over\n // finished ones, as the issue detail route does.\n const byIssueId = items.filter(item => item.workItem.metadata?.linearIssueId === issue.id);\n const relatedItem =\n itemsBySourceKey.get(`linear:${issue.identifier}`) ??\n byIssueId.find(item => !isTerminalWorkItem(this.#boards(input), item)) ??\n byIssueId[0];\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: LinearRulesIngress,\n issue: LinearIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `linear:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'issueClosed' : 'issueObserved';\n const context: FactoryLinearRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'linear', id: ingressId },\n cause: `linear.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'linear-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.linearRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'linear'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.linearRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'linear'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Linear rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId },\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Linear rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n\nexport function attachLinearRules(\n linear: { readonly rules: LinearEventRules },\n context: IntegrationContext,\n): ((input: LinearRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n linearRules: linear.rules,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;;;;AAwBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,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AAQ;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,aAAa,OAAO;CACtB,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
1
+ {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/linear/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n isTerminalWorkItem,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { recordIntakeEvent } from '../../metrics/intake.js';\nimport { commitObservedChange, deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryLinearRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport type { LinearEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface LinearIssueIngress {\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Linear user who created the issue, when available. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Linear source the issue was read from (project or team). */\n sourceId?: string | null;\n projectId?: string | null;\n}\n\nexport interface LinearRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n linearRules: LinearEventRules;\n}\n\nexport interface LinearRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: LinearIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Linear sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryLinearRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.opened' };\n}\n\nexport class LinearRules {\n constructor(private readonly options: LinearRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: LinearRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n try {\n const result = await this.#ingest(input);\n recordIntakeEvent('linear', result.status);\n return result;\n } catch (error) {\n recordIntakeEvent('linear', 'error');\n throw error;\n }\n }\n\n async #ingest(input: LinearRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'linear', type: 'issue', externalId: `linear:${issue.identifier}` })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per Linear issue per project; other projects may file their own.\n // The identifier finds the card filed under it; after Linear renamed the\n // identifier, the stable issue id finds it, preferring a live card over\n // finished ones, as the issue detail route does.\n const byIssueId = items.filter(item => item.workItem.metadata?.linearIssueId === issue.id);\n const relatedItem =\n itemsBySourceKey.get(`linear:${issue.identifier}`) ??\n byIssueId.find(item => !isTerminalWorkItem(this.#boards(input), item)) ??\n byIssueId[0];\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: LinearRulesIngress,\n issue: LinearIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `linear:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'issueClosed' : 'issueObserved';\n const context: FactoryLinearRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'linear', id: ingressId },\n cause: `linear.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'linear-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.linearRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'linear'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.linearRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'linear'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Linear rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId },\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Linear rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n if (relatedItem && event === 'issueObserved' && outcome.status === 'accepted' && !ownedByDeployment) {\n await commitObservedChange(this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n item: relatedItem,\n ingressId,\n actor,\n labels: issue.labels,\n assignee: issue.assignee,\n observedAt: issue.updatedAt,\n metadata: { linearAssignee: issue.assignee },\n });\n }\n return committed.status;\n }\n}\n\nexport function attachLinearRules(\n linear: { readonly rules: LinearEventRules },\n context: IntegrationContext,\n): ((input: LinearRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n linearRules: linear.rules,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;;;;AAwBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,I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S,OAAO,KAAA;CAC7B,MAAM,QAAQ,IAAI,YAAY;EAC5B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,aAAa,OAAO;CACtB,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
@@ -12,6 +12,7 @@
12
12
  * Platform's own rule for these providers: a signed-in organization member
13
13
  * (org:write parity with Linear), not an organization admin.
14
14
  */
15
+ import { RequestContext } from '@mastra/core/request-context';
15
16
  import type { ApiRoute } from '@mastra/core/server';
16
17
  import type { RouteAuth } from '../../../routes/route.js';
17
18
  import type { PlatformApiClient } from '../api-client.js';
@@ -35,8 +36,49 @@ export interface BuildPlatformConnectRoutesOptions {
35
36
  export interface ConnectToolsSource {
36
37
  client: PlatformApiClient;
37
38
  projectId: string;
39
+ /**
40
+ * `default`: sessions get Factory's own Connect tools for this project.
41
+ * `custom`: the Factory's `tools` option sets session tools, and may or may
42
+ * not include these connections.
43
+ */
44
+ toolsSource: 'default' | 'custom';
45
+ /**
46
+ * Resolves the tools a session started by this request would get from
47
+ * `toolsSource`: the project's Connect tools before Factory's filters for
48
+ * `default`, or what the `tools` option returns for `custom`. Rejects when
49
+ * they can't be resolved.
50
+ */
51
+ resolveTools: (args: {
52
+ requestContext: RequestContext;
53
+ }) => Promise<Record<string, unknown>>;
38
54
  }
39
- export declare function buildConnectToolsRoute(auth: RouteAuth, source: ConnectToolsSource | undefined): ApiRoute;
55
+ /** One tool as Settings › Tools lists it. */
56
+ export interface ListedConnectTool {
57
+ name: string;
58
+ description: string | null;
59
+ /** The tool pauses the run until someone approves each call. */
60
+ requiresApproval: boolean;
61
+ /** Factory leaves this default Connect tool out of sessions: its name says it deletes or archives. */
62
+ excluded?: 'destructive';
63
+ }
64
+ /** The one piece of setup the Factory lacks to list its project's connections. */
65
+ export type ConnectToolsSetupMissing = 'no_credentials' | 'no_project_id';
66
+ /**
67
+ * Lists the Platform project's connections for Settings › Tools whenever the
68
+ * Factory has Platform credentials and `MASTRA_PROJECT_ID`, whatever its
69
+ * `tools` option. `toolsSource` tells the panel whether sessions get these
70
+ * connections by default or only through the Factory's own `tools` code.
71
+ */
72
+ export declare function buildConnectToolsRoute(auth: RouteAuth, source: ConnectToolsSource | {
73
+ missing: ConnectToolsSetupMissing;
74
+ }): ApiRoute;
75
+ /**
76
+ * Lists the tools sessions get from the Connect tools source, as the signed-in
77
+ * caller's session would resolve them, for the tool lists in Settings › Tools.
78
+ */
79
+ export declare function buildConnectToolListRoute(auth: RouteAuth, source: ConnectToolsSource | {
80
+ missing: ConnectToolsSetupMissing;
81
+ }): ApiRoute;
40
82
  /**
41
83
  * Build the `/web/integrations/platform/*` routes. Callers only mount these
42
84
  * when Platform machine credentials are configured.
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/connect/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAKpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,iBAAiB,EAAC,MAAM,kBAAkB,CAAC;AAMzD,MAAM,WAAW,uBAAuB;IACtC,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,wEAAwE;IACxE,wBAAwB,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAED;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAK9E,CAAC;AAgCF,MAAM,WAAW,iCAAiC;IAChD,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,iBAAiB,CAAC;CAC3B;AAED,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,iBAAiB,CAAC;IAC1B,SAAS,EAAE,MAAM,CAAC;CAC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AAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,gEAAgE;IAChE,gBAAgB,EAAE,OAAO,CAAC;IAC1B,sGAAsG;IACtG,QAAQ,CAAC,EAAE,aAAa,CAAC;CAC1B;AAED,kFAAkF;AAClF,MAAM,MAAM,wBAAwB,GAAG,gBAAgB,GAAG,eAAe,CAAC;AAiD1E;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,SAAS,EACf,MAAM,EAAE,kBAAkB,GAAG;IAAE,OAAO,EAAE,wBAAwB,CAAA;CAAE,GACjE,QAAQ,CAoDV;AAkBD;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,SAAS,EACf,MAAM,EAAE,kBAAkB,GAAG;IAAE,OAAO,EAAE,wBAAwB,CAAA;CAAE,GACjE,QAAQ,CAmCV;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,iCAAiC,GAAG,QAAQ,EAAE,CAgFjG"}
@@ -1,9 +1,24 @@
1
1
  import { loose } from "../../../routes/route.js";
2
2
  import { PlatformApiError } from "../api-client.js";
3
- import { offersSessionTools } from "./session-tools.js";
3
+ import { connectToolExclusion, offersSessionTools } from "./session-tools.js";
4
+ import { RequestContext } from "@mastra/core/request-context";
4
5
  import { registerApiRoute } from "@mastra/core/server";
5
6
  // src/integrations/platform/connect/routes.ts
6
7
  /**
8
+ * Mastra `apiRoutes` that let the Factory SPA connect and reconnect
9
+ * Platform-managed provider accounts without leaving Factory, and list the
10
+ * Platform project connections whose Mastra Connect tools sessions get.
11
+ *
12
+ * The browser cannot talk to the integrations service itself — it has no
13
+ * Platform session — so these routes mint Nango connect/reconnect sessions
14
+ * server-side with the deploy's machine credentials
15
+ * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the
16
+ * short-lived session token back to the SPA, which drives the provider's
17
+ * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the
18
+ * Platform's own rule for these providers: a signed-in organization member
19
+ * (org:write parity with Linear), not an organization admin.
20
+ */
21
+ /**
7
22
  * Providers the Factory SPA may connect through these routes. Keys are the
8
23
  * SPA-facing provider slugs; `integrationId` is the Platform catalog id used
9
24
  * for new connect sessions. Provider-specific PRs extend this registry when
@@ -27,6 +42,10 @@ const PLATFORM_CONNECT_PROVIDERS = {
27
42
  connectionIntegrationIds: ["vanta"]
28
43
  }
29
44
  };
45
+ const MISSING_SETUP_MESSAGES = {
46
+ no_credentials: "This Factory has no Mastra Platform credentials. Set MASTRA_PLATFORM_SECRET_KEY or MASTRA_PLATFORM_ACCESS_TOKEN.",
47
+ no_project_id: "This Factory has Mastra Platform credentials but no MASTRA_PROJECT_ID."
48
+ };
30
49
  async function resolveOrgTenant(c, auth) {
31
50
  if (!auth.enabled()) return { response: c.json({
32
51
  error: "auth_disabled",
@@ -64,21 +83,28 @@ function platformError(c, err) {
64
83
  message: err instanceof Error ? err.message : String(err)
65
84
  }, 502);
66
85
  }
86
+ /**
87
+ * Lists the Platform project's connections for Settings › Tools whenever the
88
+ * Factory has Platform credentials and `MASTRA_PROJECT_ID`, whatever its
89
+ * `tools` option. `toolsSource` tells the panel whether sessions get these
90
+ * connections by default or only through the Factory's own `tools` code.
91
+ */
67
92
  function buildConnectToolsRoute(auth, source) {
68
93
  return registerApiRoute("/web/integrations/platform/connect-tools", {
69
94
  method: "GET",
70
95
  requiresAuth: false,
71
96
  handler: async (rawContext) => {
72
97
  const c = loose(rawContext);
73
- if (!source) return c.json({
74
- error: "connect_tools_off",
75
- message: "This Factory's sessions don't get Mastra Connect tools."
76
- }, 404);
77
98
  if (auth.enabled()) {
78
99
  await auth.ensureUser(c);
79
100
  if (!auth.tenant(c)) return c.json({ error: "unauthorized" }, 401);
80
101
  }
81
- const { client, projectId } = source;
102
+ if ("missing" in source) return c.json({
103
+ error: "connect_tools_off",
104
+ reason: source.missing,
105
+ message: MISSING_SETUP_MESSAGES[source.missing]
106
+ }, 404);
107
+ const { client, projectId, toolsSource } = source;
82
108
  try {
83
109
  const [listed, catalog] = await Promise.all([client.request("GET", `/v2/projects/${encodeURIComponent(projectId)}/connections`), client.request("GET", "/v2/integrations").catch((error) => {
84
110
  console.warn(`MastraFactory: listing connections without provider names; the Platform catalog failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -98,6 +124,7 @@ function buildConnectToolsRoute(auth, source) {
98
124
  }).sort((a, b) => a.providerName.localeCompare(b.providerName));
99
125
  return c.json({
100
126
  projectId,
127
+ toolsSource,
101
128
  connections
102
129
  });
103
130
  } catch (err) {
@@ -106,6 +133,54 @@ function buildConnectToolsRoute(auth, source) {
106
133
  }
107
134
  });
108
135
  }
136
+ function listedTool(name, tool, toolsSource) {
137
+ const exclusion = toolsSource === "default" ? connectToolExclusion(name) : void 0;
138
+ if (exclusion === "source_control") return [];
139
+ const { description, requireApproval } = tool ?? {};
140
+ return [{
141
+ name,
142
+ description: typeof description === "string" && description.trim() ? description.trim() : null,
143
+ requiresApproval: requireApproval === true,
144
+ ...exclusion ? { excluded: exclusion } : {}
145
+ }];
146
+ }
147
+ /**
148
+ * Lists the tools sessions get from the Connect tools source, as the signed-in
149
+ * caller's session would resolve them, for the tool lists in Settings › Tools.
150
+ */
151
+ function buildConnectToolListRoute(auth, source) {
152
+ return registerApiRoute("/web/integrations/platform/connect-tools/tools", {
153
+ method: "GET",
154
+ requiresAuth: false,
155
+ handler: async (rawContext) => {
156
+ const c = loose(rawContext);
157
+ if (auth.enabled()) {
158
+ await auth.ensureUser(c);
159
+ if (!auth.tenant(c)) return c.json({ error: "unauthorized" }, 401);
160
+ }
161
+ if ("missing" in source) return c.json({
162
+ error: "connect_tools_off",
163
+ reason: source.missing,
164
+ message: MISSING_SETUP_MESSAGES[source.missing]
165
+ }, 404);
166
+ const { toolsSource, resolveTools } = source;
167
+ const requestContext = c.get("requestContext") ?? new RequestContext();
168
+ try {
169
+ const resolved = await resolveTools({ requestContext });
170
+ const tools = Object.entries(resolved).flatMap(([name, tool]) => listedTool(name, tool, toolsSource)).sort((a, b) => a.name.localeCompare(b.name));
171
+ return c.json({
172
+ toolsSource,
173
+ tools
174
+ });
175
+ } catch (err) {
176
+ return c.json({
177
+ error: "tools_unavailable",
178
+ message: `Couldn't resolve the tools: ${err instanceof Error ? err.message : String(err)}`
179
+ }, 502);
180
+ }
181
+ }
182
+ });
183
+ }
109
184
  /**
110
185
  * Build the `/web/integrations/platform/*` routes. Callers only mount these
111
186
  * when Platform machine credentials are configured.
@@ -171,6 +246,6 @@ function buildPlatformConnectRoutes(options) {
171
246
  })
172
247
  ];
173
248
  }
174
- export { PLATFORM_CONNECT_PROVIDERS, buildConnectToolsRoute, buildPlatformConnectRoutes };
249
+ export { PLATFORM_CONNECT_PROVIDERS, buildConnectToolListRoute, buildConnectToolsRoute, buildPlatformConnectRoutes };
175
250
 
176
251
  //# sourceMappingURL=routes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/connect/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` that let the Factory SPA connect and reconnect\n * Platform-managed provider accounts without leaving Factory, and list the\n * Platform project connections whose Mastra Connect tools sessions get.\n *\n * The browser cannot talk to the integrations service itself — it has no\n * Platform session — so these routes mint Nango connect/reconnect sessions\n * server-side with the deploy's machine credentials\n * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the\n * short-lived session token back to the SPA, which drives the provider's\n * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the\n * Platform's own rule for these providers: a signed-in organization member\n * (org:write parity with Linear), not an organization admin.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { loose } from '../../../routes/route.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { PlatformApiClient} from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\nimport { offersSessionTools } from './session-tools.js';\n\ntype RouteContext = Context;\n\nexport interface PlatformConnectProvider {\n /** Platform integration id used to mint connect sessions. */\n integrationId: string;\n /** Connection `integrationId` variants that belong to this provider. */\n connectionIntegrationIds: readonly string[];\n}\n\n/**\n * Providers the Factory SPA may connect through these routes. Keys are the\n * SPA-facing provider slugs; `integrationId` is the Platform catalog id used\n * for new connect sessions. Provider-specific PRs extend this registry when\n * their Factory integrations are available.\n */\nexport const PLATFORM_CONNECT_PROVIDERS: Record<string, PlatformConnectProvider> = {\n jira: { integrationId: 'jira', connectionIntegrationIds: ['jira'] },\n 'incident-io': { integrationId: 'incident-io', connectionIntegrationIds: ['incident-io'] },\n gitlab: { integrationId: 'gitlab', connectionIntegrationIds: ['gitlab'] },\n vanta: { integrationId: 'vanta', connectionIntegrationIds: ['vanta'] },\n};\n\ninterface PlatformConnectionRow {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n displayName?: string | null;\n connectedAt?: string;\n}\n\ninterface PlatformSessionResponse {\n connectionId: string;\n integrationId: string;\n connectUrl: string;\n sessionToken: string;\n expiresAt: string;\n}\n\ninterface ProjectConnectionRow {\n id: string;\n integrationId: string;\n status: string;\n accountLabel?: string | null;\n}\n\ninterface CatalogEntry {\n id: string;\n displayName?: string | null;\n logoUrl?: string | null;\n}\n\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n client: PlatformApiClient;\n}\n\nexport interface ConnectToolsSource {\n client: PlatformApiClient;\n projectId: string;\n}\n\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n if (!auth.enabled()) {\n return { response: c.json({ error: 'auth_disabled', message: 'Factory auth is not enabled.' }, 403) };\n }\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Provider connections require an organization. Personal accounts cannot connect providers.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction providerFromParam(c: RouteContext): PlatformConnectProvider | null {\n const provider = c.req.param('provider');\n return provider ? (PLATFORM_CONNECT_PROVIDERS[provider] ?? null) : null;\n}\n\nfunction platformError(c: RouteContext, err: unknown) {\n if (err instanceof PlatformApiError) {\n if (err.status === 409) {\n return c.json({ error: 'session_pending', message: err.message }, 409);\n }\n if (err.status === 403) {\n return c.json({ error: 'platform_forbidden', message: err.message }, 403);\n }\n }\n return c.json({ error: 'platform_request_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\nexport function buildConnectToolsRoute(auth: RouteAuth, source: ConnectToolsSource | undefined): ApiRoute {\n return registerApiRoute('/web/integrations/platform/connect-tools', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n if (!source) {\n return c.json(\n { error: 'connect_tools_off', message: \"This Factory's sessions don't get Mastra Connect tools.\" },\n 404,\n );\n }\n if (auth.enabled()) {\n await auth.ensureUser(c);\n if (!auth.tenant(c)) return c.json({ error: 'unauthorized' }, 401);\n }\n const { client, projectId } = source;\n try {\n const [listed, catalog] = await Promise.all([\n client.request<{ connections: ProjectConnectionRow[] }>(\n 'GET',\n `/v2/projects/${encodeURIComponent(projectId)}/connections`,\n ),\n client.request<{ integrations: CatalogEntry[] }>('GET', '/v2/integrations').catch((error: unknown) => {\n console.warn(\n `MastraFactory: listing connections without provider names; the Platform catalog failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n return { integrations: [] };\n }),\n ]);\n const entries = new Map(catalog.integrations.map(entry => [entry.id, entry]));\n const connections = listed.connections\n .filter(connection => offersSessionTools(connection.integrationId))\n .map(connection => {\n const entry = entries.get(connection.integrationId);\n return {\n id: connection.id,\n integrationId: connection.integrationId,\n providerName: entry?.displayName ?? connection.integrationId,\n logoUrl: entry?.logoUrl ?? null,\n accountLabel: connection.accountLabel ?? null,\n status: connection.status,\n };\n })\n .sort((a, b) => a.providerName.localeCompare(b.providerName));\n return c.json({ projectId, connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n });\n}\n\n/**\n * Build the `/web/integrations/platform/*` routes. Callers only mount these\n * when Platform machine credentials are configured.\n */\nexport function buildPlatformConnectRoutes(options: BuildPlatformConnectRoutesOptions): ApiRoute[] {\n const { auth, client } = options;\n\n return [\n registerApiRoute('/web/integrations/platform/:provider/connections', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const result = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connections = result.connections.filter(connection =>\n provider.connectionIntegrationIds.includes(connection.integrationId),\n );\n return c.json({ connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/integrations/${encodeURIComponent(provider.integrationId)}/connect-sessions`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connections/:connectionId/reconnect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n const connectionId = c.req.param('connectionId');\n if (!connectionId) return c.json({ error: 'connection_required' }, 400);\n try {\n // Confirm the connection belongs to this provider before minting so\n // one provider's page cannot reconnect a different provider's\n // connection through this route family.\n const listed = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connection = listed.connections.find(\n candidate =>\n candidate.id === connectionId && provider.connectionIntegrationIds.includes(candidate.integrationId),\n );\n if (!connection) return c.json({ error: 'connection_not_found' }, 404);\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/connections/${encodeURIComponent(connectionId)}/reconnect-session`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;AAwCA,MAAa,6BAAsE;CACjF,MAAM;EAAE,eAAe;EAAQ,0BAA0B,CAAC,MAAM;CAAE;CAClE,eAAe;EAAE,eAAe;EAAe,0BAA0B,CAAC,aAAa;CAAE;CACzF,QAAQ;EAAE,eAAe;EAAU,0BAA0B,CAAC,QAAQ;CAAE;CACxE,OAAO;EAAE,eAAe;EAAS,0BAA0B,CAAC,OAAO;CAAE;AACvE;AA0CA,eAAe,iBACb,GACA,MACiF;CACjF,IAAI,CAAC,KAAK,QAAQ,GAChB,OAAO,EAAE,UAAU,EAAE,KAAK;EAAE,OAAO;EAAiB,SAAS;CAA+B,GAAG,GAAG,EAAE;CAEtG,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;CAEF,OAAO,EAAE,QAAQ;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,EAAE;AAClE;AAEA,SAAS,kBAAkB,GAAiD;CAC1E,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IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/connect/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` that let the Factory SPA connect and reconnect\n * Platform-managed provider accounts without leaving Factory, and list the\n * Platform project connections whose Mastra Connect tools sessions get.\n *\n * The browser cannot talk to the integrations service itself — it has no\n * Platform session — so these routes mint Nango connect/reconnect sessions\n * server-side with the deploy's machine credentials\n * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the\n * short-lived session token back to the SPA, which drives the provider's\n * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the\n * Platform's own rule for these providers: a signed-in organization member\n * (org:write parity with Linear), not an organization admin.\n */\n\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { loose } from '../../../routes/route.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { PlatformApiClient } from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\nimport { connectToolExclusion, offersSessionTools } from './session-tools.js';\n\ntype RouteContext = Context;\n\nexport interface PlatformConnectProvider {\n /** Platform integration id used to mint connect sessions. */\n integrationId: string;\n /** Connection `integrationId` variants that belong to this provider. */\n connectionIntegrationIds: readonly string[];\n}\n\n/**\n * Providers the Factory SPA may connect through these routes. Keys are the\n * SPA-facing provider slugs; `integrationId` is the Platform catalog id used\n * for new connect sessions. Provider-specific PRs extend this registry when\n * their Factory integrations are available.\n */\nexport const PLATFORM_CONNECT_PROVIDERS: Record<string, PlatformConnectProvider> = {\n jira: { integrationId: 'jira', connectionIntegrationIds: ['jira'] },\n 'incident-io': { integrationId: 'incident-io', connectionIntegrationIds: ['incident-io'] },\n gitlab: { integrationId: 'gitlab', connectionIntegrationIds: ['gitlab'] },\n vanta: { integrationId: 'vanta', connectionIntegrationIds: ['vanta'] },\n};\n\ninterface PlatformConnectionRow {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n displayName?: string | null;\n connectedAt?: string;\n}\n\ninterface PlatformSessionResponse {\n connectionId: string;\n integrationId: string;\n connectUrl: string;\n sessionToken: string;\n expiresAt: string;\n}\n\ninterface ProjectConnectionRow {\n id: string;\n integrationId: string;\n status: string;\n accountLabel?: string | null;\n}\n\ninterface CatalogEntry {\n id: string;\n displayName?: string | null;\n logoUrl?: string | null;\n}\n\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n client: PlatformApiClient;\n}\n\nexport interface ConnectToolsSource {\n client: PlatformApiClient;\n projectId: string;\n /**\n * `default`: sessions get Factory's own Connect tools for this project.\n * `custom`: the Factory's `tools` option sets session tools, and may or may\n * not include these connections.\n */\n toolsSource: 'default' | 'custom';\n /**\n * Resolves the tools a session started by this request would get from\n * `toolsSource`: the project's Connect tools before Factory's filters for\n * `default`, or what the `tools` option returns for `custom`. Rejects when\n * they can't be resolved.\n */\n resolveTools: (args: { requestContext: RequestContext }) => Promise<Record<string, unknown>>;\n}\n\n/** One tool as Settings › Tools lists it. */\nexport interface ListedConnectTool {\n name: string;\n description: string | null;\n /** The tool pauses the run until someone approves each call. */\n requiresApproval: boolean;\n /** Factory leaves this default Connect tool out of sessions: its name says it deletes or archives. */\n excluded?: 'destructive';\n}\n\n/** The one piece of setup the Factory lacks to list its project's connections. */\nexport type ConnectToolsSetupMissing = 'no_credentials' | 'no_project_id';\n\nconst MISSING_SETUP_MESSAGES: Record<ConnectToolsSetupMissing, string> = {\n no_credentials:\n 'This Factory has no Mastra Platform credentials. Set MASTRA_PLATFORM_SECRET_KEY or MASTRA_PLATFORM_ACCESS_TOKEN.',\n no_project_id: 'This Factory has Mastra Platform credentials but no MASTRA_PROJECT_ID.',\n};\n\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n if (!auth.enabled()) {\n return { response: c.json({ error: 'auth_disabled', message: 'Factory auth is not enabled.' }, 403) };\n }\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Provider connections require an organization. Personal accounts cannot connect providers.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction providerFromParam(c: RouteContext): PlatformConnectProvider | null {\n const provider = c.req.param('provider');\n return provider ? (PLATFORM_CONNECT_PROVIDERS[provider] ?? null) : null;\n}\n\nfunction platformError(c: RouteContext, err: unknown) {\n if (err instanceof PlatformApiError) {\n if (err.status === 409) {\n return c.json({ error: 'session_pending', message: err.message }, 409);\n }\n if (err.status === 403) {\n return c.json({ error: 'platform_forbidden', message: err.message }, 403);\n }\n }\n return c.json({ error: 'platform_request_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Lists the Platform project's connections for Settings › Tools whenever the\n * Factory has Platform credentials and `MASTRA_PROJECT_ID`, whatever its\n * `tools` option. `toolsSource` tells the panel whether sessions get these\n * connections by default or only through the Factory's own `tools` code.\n */\nexport function buildConnectToolsRoute(\n auth: RouteAuth,\n source: ConnectToolsSource | { missing: ConnectToolsSetupMissing },\n): ApiRoute {\n return registerApiRoute('/web/integrations/platform/connect-tools', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n if (auth.enabled()) {\n await auth.ensureUser(c);\n if (!auth.tenant(c)) return c.json({ error: 'unauthorized' }, 401);\n }\n if ('missing' in source) {\n // `connect_tools_off` stays the code so settings pages from older CLIs still read it.\n return c.json(\n { error: 'connect_tools_off', reason: source.missing, message: MISSING_SETUP_MESSAGES[source.missing] },\n 404,\n );\n }\n const { client, projectId, toolsSource } = source;\n try {\n const [listed, catalog] = await Promise.all([\n client.request<{ connections: ProjectConnectionRow[] }>(\n 'GET',\n `/v2/projects/${encodeURIComponent(projectId)}/connections`,\n ),\n client.request<{ integrations: CatalogEntry[] }>('GET', '/v2/integrations').catch((error: unknown) => {\n console.warn(\n `MastraFactory: listing connections without provider names; the Platform catalog failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n return { integrations: [] };\n }),\n ]);\n const entries = new Map(catalog.integrations.map(entry => [entry.id, entry]));\n const connections = listed.connections\n .filter(connection => offersSessionTools(connection.integrationId))\n .map(connection => {\n const entry = entries.get(connection.integrationId);\n return {\n id: connection.id,\n integrationId: connection.integrationId,\n providerName: entry?.displayName ?? connection.integrationId,\n logoUrl: entry?.logoUrl ?? null,\n accountLabel: connection.accountLabel ?? null,\n status: connection.status,\n };\n })\n .sort((a, b) => a.providerName.localeCompare(b.providerName));\n return c.json({ projectId, toolsSource, connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n });\n}\n\nfunction listedTool(name: string, tool: unknown, toolsSource: ConnectToolsSource['toolsSource']): ListedConnectTool[] {\n // Factory filters only its default Connect tools; a `tools` option reaches sessions as written.\n const exclusion = toolsSource === 'default' ? connectToolExclusion(name) : undefined;\n // GitHub and GitLab connections aren't listed, so neither are their tools.\n if (exclusion === 'source_control') return [];\n const { description, requireApproval } = (tool ?? {}) as { description?: unknown; requireApproval?: unknown };\n return [\n {\n name,\n description: typeof description === 'string' && description.trim() ? description.trim() : null,\n requiresApproval: requireApproval === true,\n ...(exclusion ? { excluded: exclusion } : {}),\n },\n ];\n}\n\n/**\n * Lists the tools sessions get from the Connect tools source, as the signed-in\n * caller's session would resolve them, for the tool lists in Settings › Tools.\n */\nexport function buildConnectToolListRoute(\n auth: RouteAuth,\n source: ConnectToolsSource | { missing: ConnectToolsSetupMissing },\n): ApiRoute {\n return registerApiRoute('/web/integrations/platform/connect-tools/tools', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n if (auth.enabled()) {\n await auth.ensureUser(c);\n if (!auth.tenant(c)) return c.json({ error: 'unauthorized' }, 401);\n }\n if ('missing' in source) {\n return c.json(\n { error: 'connect_tools_off', reason: source.missing, message: MISSING_SETUP_MESSAGES[source.missing] },\n 404,\n );\n }\n const { toolsSource, resolveTools } = source;\n const requestContext = (c.get('requestContext' as never) as RequestContext | undefined) ?? new RequestContext();\n try {\n const resolved = await resolveTools({ requestContext });\n const tools = Object.entries(resolved)\n .flatMap(([name, tool]) => listedTool(name, tool, toolsSource))\n .sort((a, b) => a.name.localeCompare(b.name));\n return c.json({ toolsSource, tools });\n } catch (err) {\n return c.json(\n {\n error: 'tools_unavailable',\n message: `Couldn't resolve the tools: ${err instanceof Error ? err.message : String(err)}`,\n },\n 502,\n );\n }\n },\n });\n}\n\n/**\n * Build the `/web/integrations/platform/*` routes. Callers only mount these\n * when Platform machine credentials are configured.\n */\nexport function buildPlatformConnectRoutes(options: BuildPlatformConnectRoutesOptions): ApiRoute[] {\n const { auth, client } = options;\n\n return [\n registerApiRoute('/web/integrations/platform/:provider/connections', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const result = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connections = result.connections.filter(connection =>\n provider.connectionIntegrationIds.includes(connection.integrationId),\n );\n return c.json({ connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/integrations/${encodeURIComponent(provider.integrationId)}/connect-sessions`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connections/:connectionId/reconnect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n const connectionId = c.req.param('connectionId');\n if (!connectionId) return c.json({ error: 'connection_required' }, 400);\n try {\n // Confirm the connection belongs to this provider before minting so\n // one provider's page cannot reconnect a different provider's\n // connection through this route family.\n const listed = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connection = listed.connections.find(\n candidate =>\n candidate.id === connectionId && provider.connectionIntegrationIds.includes(candidate.integrationId),\n );\n if (!connection) return c.json({ error: 'connection_not_found' }, 404);\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/connections/${encodeURIComponent(connectionId)}/reconnect-session`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,6BAAsE;CACjF,MAAM;EAAE,eAAe;EAAQ,0BAA0B,CAAC,MAAM;CAAE;CAClE,eAAe;EAAE,eAAe;EAAe,0BAA0B,CAAC,aAAa;CAAE;CACzF,QAAQ;EAAE,eAAe;EAAU,0BAA0B,CAAC,QAAQ;CAAE;CACxE,OAAO;EAAE,eAAe;EAAS,0BAA0B,CAAC,OAAO;CAAE;AACvE;AAoEA,MAAM,yBAAmE;CACvE,gBACE;CACF,eAAe;AACjB;AAEA,eAAe,iBACb,GACA,MACiF;CACjF,IAAI,CAAC,KAAK,QAAQ,GAChB,OAAO,EAAE,UAAU,EAAE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M,iBAAiB,GAAG,IAAI;IAC/C,IAAI,cAAc,UAAU,OAAO,SAAS;IAC5C,MAAM,eAAe,EAAE,IAAI,MAAM,cAAc;IAC/C,IAAI,CAAC,cAAc,OAAO,EAAE,KAAK,EAAE,OAAO,sBAAsB,GAAG,GAAG;IACtE,IAAI;KASF,IAAI,EAJe,MADE,OAAO,QAAkD,OAAO,iBAAiB,EAAA,CAC5E,YAAY,MACpC,cACE,UAAU,OAAO,gBAAgB,SAAS,yBAAyB,SAAS,UAAU,aAAa,CAEzF,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,uBAAuB,GAAG,GAAG;KACrE,MAAM,UAAU,MAAM,OAAO,QAC3B,QACA,mBAAmB,mBAAmB,YAAY,EAAE,qBACpD,CAAC,CACH;KACA,EAAE,OAAO,iBAAiB,UAAU;KACpC,OAAO,EAAE,KAAK,SAAS,GAAG;IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
@@ -1,6 +1,18 @@
1
1
  import type { RequestContext } from '@mastra/core/request-context';
2
2
  import type { IntegrationTools } from '../../base.js';
3
3
  export declare function offersSessionTools(integrationId: string): boolean;
4
+ /** Why Factory keeps a Connect tool from sessions by default, or `undefined` when sessions get it. */
5
+ export type ConnectToolExclusion = 'destructive' | 'source_control';
6
+ export declare function connectToolExclusion(name: string): ConnectToolExclusion | undefined;
7
+ /** Rejects when `tools` takes longer than a run waits for Connect tools. */
8
+ export declare function resolveToolsInTime<T>(tools: Promise<T>): Promise<T>;
9
+ /**
10
+ * Every Mastra Connect tool of the project's connections, before Factory's
11
+ * filters. Rejects when the Platform fails or doesn't answer in time.
12
+ */
13
+ export declare function projectConnectTools(projectId: string): (args: {
14
+ requestContext: RequestContext;
15
+ }) => Promise<IntegrationTools>;
4
16
  /**
5
17
  * The Mastra Connect tools Factory gives sessions by default, without delete,
6
18
  * archive, and GitHub/GitLab tools. Passing `tools` replaces that default; call
@@ -1 +1 @@
1
- {"version":3,"file":"session-tools.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/connect/session-tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAQtD,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAEjE;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,MAAM,GAChB,CAAC,IAAI,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAwBzE"}
1
+ {"version":3,"file":"session-tools.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/connect/session-tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAQtD,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAEjE;AAED,sGAAsG;AACtG,MAAM,MAAM,oBAAoB,GAAG,aAAa,GAAG,gBAAgB,CAAC;AAEpE,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,oBAAoB,GAAG,SAAS,CAInF;AAED,4EAA4E;AAC5E,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAazE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,MAAM,GAChB,CAAC,IAAI,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAGzE;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,MAAM,GAChB,CAAC,IAAI,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAazE"}
@@ -7,29 +7,47 @@ const RESOLVE_TIMEOUT_MS = 15e3;
7
7
  function offersSessionTools(integrationId) {
8
8
  return !SOURCE_CONTROL_PROVIDERS.includes(integrationId);
9
9
  }
10
+ function connectToolExclusion(name) {
11
+ if (SOURCE_CONTROL_TOOL.test(name)) return "source_control";
12
+ if (DESTRUCTIVE_TOOL.test(name)) return "destructive";
13
+ }
14
+ /** Rejects when `tools` takes longer than a run waits for Connect tools. */
15
+ async function resolveToolsInTime(tools) {
16
+ let timer;
17
+ const timeout = new Promise((_, reject) => {
18
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`the tools didn't resolve within ${RESOLVE_TIMEOUT_MS / 1e3}s`)), RESOLVE_TIMEOUT_MS);
19
+ });
20
+ try {
21
+ return await Promise.race([tools, timeout]);
22
+ } finally {
23
+ clearTimeout(timer);
24
+ }
25
+ }
26
+ /**
27
+ * Every Mastra Connect tool of the project's connections, before Factory's
28
+ * filters. Rejects when the Platform fails or doesn't answer in time.
29
+ */
30
+ function projectConnectTools(projectId) {
31
+ const resolve = tools({ projectId });
32
+ return ({ requestContext }) => resolveToolsInTime(resolve({ requestContext }));
33
+ }
10
34
  /**
11
35
  * The Mastra Connect tools Factory gives sessions by default, without delete,
12
36
  * archive, and GitHub/GitLab tools. Passing `tools` replaces that default; call
13
37
  * this to keep it alongside your own.
14
38
  */
15
39
  function platformConnectTools(projectId) {
16
- const resolve = tools({ projectId });
40
+ const resolve = projectConnectTools(projectId);
17
41
  return async ({ requestContext }) => {
18
- let timer;
19
- const timeout = new Promise((_, reject) => {
20
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`the Platform didn't answer within ${RESOLVE_TIMEOUT_MS / 1e3}s`)), RESOLVE_TIMEOUT_MS);
21
- });
22
42
  try {
23
- const tools = await Promise.race([resolve({ requestContext }), timeout]);
24
- return Object.fromEntries(Object.entries(tools).filter(([name]) => !DESTRUCTIVE_TOOL.test(name) && !SOURCE_CONTROL_TOOL.test(name)));
43
+ const tools = await resolve({ requestContext });
44
+ return Object.fromEntries(Object.entries(tools).filter(([name]) => !connectToolExclusion(name)));
25
45
  } catch (error) {
26
46
  console.warn(`MastraFactory: Mastra Connect tools are unavailable for this run: ${error instanceof Error ? error.message : String(error)}`);
27
47
  return {};
28
- } finally {
29
- clearTimeout(timer);
30
48
  }
31
49
  };
32
50
  }
33
- export { offersSessionTools, platformConnectTools };
51
+ export { connectToolExclusion, offersSessionTools, platformConnectTools, projectConnectTools, resolveToolsInTime };
34
52
 
35
53
  //# sourceMappingURL=session-tools.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-tools.js","names":["connectTools"],"sources":["../../../../src/integrations/platform/connect/session-tools.ts"],"sourcesContent":["import { tools as connectTools } from '@mastra/connect';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport type { IntegrationTools } from '../../base.js';\n\n// Factory's own source-control tools enforce repository scope and self-review; Connect's would bypass both.\nconst SOURCE_CONTROL_PROVIDERS = ['github', 'gitlab'];\nconst SOURCE_CONTROL_TOOL = new RegExp(`^(${SOURCE_CONTROL_PROVIDERS.join('|')})_`);\nconst DESTRUCTIVE_TOOL = /delete|archive/i;\nconst RESOLVE_TIMEOUT_MS = 15_000;\n\nexport function offersSessionTools(integrationId: string): boolean {\n return !SOURCE_CONTROL_PROVIDERS.includes(integrationId);\n}\n\n/**\n * The Mastra Connect tools Factory gives sessions by default, without delete,\n * archive, and GitHub/GitLab tools. Passing `tools` replaces that default; call\n * this to keep it alongside your own.\n */\nexport function platformConnectTools(\n projectId: string,\n): (args: { requestContext: RequestContext }) => Promise<IntegrationTools> {\n const resolve = connectTools({ projectId });\n return async ({ requestContext }) => {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`the Platform didn't answer within ${RESOLVE_TIMEOUT_MS / 1000}s`)),\n RESOLVE_TIMEOUT_MS,\n );\n });\n try {\n const tools = await Promise.race([resolve({ requestContext }), timeout]);\n return Object.fromEntries(\n Object.entries(tools).filter(([name]) => !DESTRUCTIVE_TOOL.test(name) && !SOURCE_CONTROL_TOOL.test(name)),\n );\n } catch (error) {\n console.warn(\n `MastraFactory: Mastra Connect tools are unavailable for this run: ${error instanceof Error ? error.message : String(error)}`,\n );\n return {};\n } finally {\n clearTimeout(timer);\n }\n };\n}\n"],"mappings":";;AAMA,MAAM,2BAA2B,CAAC,UAAU,QAAQ;AACpD,MAAM,sBAAsB,IAAI,OAAO,KAAK,yBAAyB,KAAK,GAAG,EAAE,GAAG;AAClF,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAE3B,SAAgB,mBAAmB,eAAgC;CACjE,OAAO,CAAC,yBAAyB,SAAS,aAAa;AACzD;;;;;;AAOA,SAAgB,qBACd,WACyE;CACzE,MAAM,UAAUA,MAAa,EAAE,UAAU,CAAC;CAC1C,OAAO,OAAO,EAAE,qBAAqB;EACnC,IAAI;EACJ,MAAM,UAAU,IAAI,SAAgB,GAAG,WAAW;GAChD,QAAQ,iBACA,uBAAO,IAAI,MAAM,qCAAqC,qBAAqB,IAAK,EAAE,CAAC,GACzF,kBACF;EACF,CAAC;EACD,IAAI;GACF,MAAM,QAAQ,MAAM,QAAQ,KAAK,CAAC,QAAQ,EAAE,eAAe,CAAC,GAAG,OAAO,CAAC;GACvE,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,iBAAiB,KAAK,IAAI,KAAK,CAAC,oBAAoB,KAAK,IAAI,CAAC,CAC1G;EACF,SAAS,OAAO;GACd,QAAQ,KACN,qEAAqE,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC5H;GACA,OAAO,CAAC;EACV,UAAU;GACR,aAAa,KAAK;EACpB;CACF;AACF"}
1
+ {"version":3,"file":"session-tools.js","names":["connectTools"],"sources":["../../../../src/integrations/platform/connect/session-tools.ts"],"sourcesContent":["import { tools as connectTools } from '@mastra/connect';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport type { IntegrationTools } from '../../base.js';\n\n// Factory's own source-control tools enforce repository scope and self-review; Connect's would bypass both.\nconst SOURCE_CONTROL_PROVIDERS = ['github', 'gitlab'];\nconst SOURCE_CONTROL_TOOL = new RegExp(`^(${SOURCE_CONTROL_PROVIDERS.join('|')})_`);\nconst DESTRUCTIVE_TOOL = /delete|archive/i;\nconst RESOLVE_TIMEOUT_MS = 15_000;\n\nexport function offersSessionTools(integrationId: string): boolean {\n return !SOURCE_CONTROL_PROVIDERS.includes(integrationId);\n}\n\n/** Why Factory keeps a Connect tool from sessions by default, or `undefined` when sessions get it. */\nexport type ConnectToolExclusion = 'destructive' | 'source_control';\n\nexport function connectToolExclusion(name: string): ConnectToolExclusion | undefined {\n if (SOURCE_CONTROL_TOOL.test(name)) return 'source_control';\n if (DESTRUCTIVE_TOOL.test(name)) return 'destructive';\n return undefined;\n}\n\n/** Rejects when `tools` takes longer than a run waits for Connect tools. */\nexport async function resolveToolsInTime<T>(tools: Promise<T>): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`the tools didn't resolve within ${RESOLVE_TIMEOUT_MS / 1000}s`)),\n RESOLVE_TIMEOUT_MS,\n );\n });\n try {\n return await Promise.race([tools, timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Every Mastra Connect tool of the project's connections, before Factory's\n * filters. Rejects when the Platform fails or doesn't answer in time.\n */\nexport function projectConnectTools(\n projectId: string,\n): (args: { requestContext: RequestContext }) => Promise<IntegrationTools> {\n const resolve = connectTools({ projectId });\n return ({ requestContext }) => resolveToolsInTime(resolve({ requestContext }));\n}\n\n/**\n * The Mastra Connect tools Factory gives sessions by default, without delete,\n * archive, and GitHub/GitLab tools. Passing `tools` replaces that default; call\n * this to keep it alongside your own.\n */\nexport function platformConnectTools(\n projectId: string,\n): (args: { requestContext: RequestContext }) => Promise<IntegrationTools> {\n const resolve = projectConnectTools(projectId);\n return async ({ requestContext }) => {\n try {\n const tools = await resolve({ requestContext });\n return Object.fromEntries(Object.entries(tools).filter(([name]) => !connectToolExclusion(name)));\n } catch (error) {\n console.warn(\n `MastraFactory: Mastra Connect tools are unavailable for this run: ${error instanceof Error ? error.message : String(error)}`,\n );\n return {};\n }\n };\n}\n"],"mappings":";;AAMA,MAAM,2BAA2B,CAAC,UAAU,QAAQ;AACpD,MAAM,sBAAsB,IAAI,OAAO,KAAK,yBAAyB,KAAK,GAAG,EAAE,GAAG;AAClF,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAE3B,SAAgB,mBAAmB,eAAgC;CACjE,OAAO,CAAC,yBAAyB,SAAS,aAAa;AACzD;AAKA,SAAgB,qBAAqB,MAAgD;CACnF,IAAI,oBAAoB,KAAK,IAAI,GAAG,OAAO;CAC3C,IAAI,iBAAiB,KAAK,IAAI,GAAG,OAAO;AAE1C;;AAGA,eAAsB,mBAAsB,OAA+B;CACzE,IAAI;CACJ,MAAM,UAAU,IAAI,SAAgB,GAAG,WAAW;EAChD,QAAQ,iBACA,uBAAO,IAAI,MAAM,mCAAmC,qBAAqB,IAAK,EAAE,CAAC,GACvF,kBACF;CACF,CAAC;CACD,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CAAC,OAAO,OAAO,CAAC;CAC5C,UAAU;EACR,aAAa,KAAK;CACpB;AACF;;;;;AAMA,SAAgB,oBACd,WACyE;CACzE,MAAM,UAAUA,MAAa,EAAE,UAAU,CAAC;CAC1C,QAAQ,EAAE,qBAAqB,mBAAmB,QAAQ,EAAE,eAAe,CAAC,CAAC;AAC/E;;;;;;AAOA,SAAgB,qBACd,WACyE;CACzE,MAAM,UAAU,oBAAoB,SAAS;CAC7C,OAAO,OAAO,EAAE,qBAAqB;EACnC,IAAI;GACF,MAAM,QAAQ,MAAM,QAAQ,EAAE,eAAe,CAAC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