@mastra/factory 0.27.0 → 0.28.0-alpha.1

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 (426) hide show
  1. package/README.md +215 -41
  2. package/dist/boards/board-events.d.ts +34 -0
  3. package/dist/boards/board-events.d.ts.map +1 -0
  4. package/dist/boards/board-events.js +50 -0
  5. package/dist/boards/board-events.js.map +1 -0
  6. package/dist/boards/board-writes.d.ts +86 -0
  7. package/dist/boards/board-writes.d.ts.map +1 -0
  8. package/dist/boards/board-writes.js +252 -0
  9. package/dist/boards/board-writes.js.map +1 -0
  10. package/dist/boards/define-board.d.ts +16 -5
  11. package/dist/boards/define-board.d.ts.map +1 -1
  12. package/dist/boards/define-board.js +30 -8
  13. package/dist/boards/define-board.js.map +1 -1
  14. package/dist/boards/index.js +1 -1
  15. package/dist/boards/intake-routing.d.ts +30 -6
  16. package/dist/boards/intake-routing.d.ts.map +1 -1
  17. package/dist/boards/intake-routing.js +43 -5
  18. package/dist/boards/intake-routing.js.map +1 -1
  19. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  20. package/dist/boards/legacy-plan-role.js +8 -4
  21. package/dist/boards/legacy-plan-role.js.map +1 -1
  22. package/dist/boards/phase-automation.d.ts.map +1 -1
  23. package/dist/boards/phase-automation.js +7 -2
  24. package/dist/boards/phase-automation.js.map +1 -1
  25. package/dist/boards/project-boards.d.ts +18 -7
  26. package/dist/boards/project-boards.d.ts.map +1 -1
  27. package/dist/boards/project-boards.js +79 -15
  28. package/dist/boards/project-boards.js.map +1 -1
  29. package/dist/boards/stored-board.d.ts +59 -1
  30. package/dist/boards/stored-board.d.ts.map +1 -1
  31. package/dist/boards/stored-board.js +219 -7
  32. package/dist/boards/stored-board.js.map +1 -1
  33. package/dist/boards/work.js +1 -1
  34. package/dist/dispatch-wake.d.ts +13 -0
  35. package/dist/dispatch-wake.d.ts.map +1 -0
  36. package/dist/dispatch-wake.js +30 -0
  37. package/dist/dispatch-wake.js.map +1 -0
  38. package/dist/environment/build-runner.d.ts +1 -1
  39. package/dist/environment/build-runner.d.ts.map +1 -1
  40. package/dist/environment/build-runner.js +2 -2
  41. package/dist/environment/build-workflow.d.ts +1 -1
  42. package/dist/environment/build-workflow.d.ts.map +1 -1
  43. package/dist/environment/build-workflow.js +1 -1
  44. package/dist/environment/build.js +1 -1
  45. package/dist/factory.d.ts +63 -9
  46. package/dist/factory.d.ts.map +1 -1
  47. package/dist/factory.js +237 -59
  48. package/dist/factory.js.map +1 -1
  49. package/dist/index.d.ts +3 -1
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +10 -9
  52. package/dist/integrations/base.d.ts +6 -0
  53. package/dist/integrations/base.d.ts.map +1 -1
  54. package/dist/integrations/channel-thread-announcements.d.ts +5 -0
  55. package/dist/integrations/channel-thread-announcements.d.ts.map +1 -1
  56. package/dist/integrations/channel-thread-announcements.js +24 -2
  57. package/dist/integrations/channel-thread-announcements.js.map +1 -1
  58. package/dist/integrations/github/acceptance-labels.d.ts +4 -0
  59. package/dist/integrations/github/acceptance-labels.d.ts.map +1 -1
  60. package/dist/integrations/github/acceptance-labels.js +1 -1
  61. package/dist/integrations/github/acceptance-labels.js.map +1 -1
  62. package/dist/integrations/github/default-rules.d.ts +2 -9
  63. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  64. package/dist/integrations/github/default-rules.js +7 -6
  65. package/dist/integrations/github/default-rules.js.map +1 -1
  66. package/dist/integrations/github/integration.js +2 -2
  67. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  68. package/dist/integrations/github/issue-reconciler.js +17 -1
  69. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  70. package/dist/integrations/github/review-status-comment.d.ts +61 -0
  71. package/dist/integrations/github/review-status-comment.d.ts.map +1 -0
  72. package/dist/integrations/github/review-status-comment.js +217 -0
  73. package/dist/integrations/github/review-status-comment.js.map +1 -0
  74. package/dist/integrations/github/review-status-reporter.d.ts +42 -0
  75. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -0
  76. package/dist/integrations/github/review-status-reporter.js +100 -0
  77. package/dist/integrations/github/review-status-reporter.js.map +1 -0
  78. package/dist/integrations/github/review-status.d.ts +28 -0
  79. package/dist/integrations/github/review-status.d.ts.map +1 -0
  80. package/dist/integrations/github/review-status.js +95 -0
  81. package/dist/integrations/github/review-status.js.map +1 -0
  82. package/dist/integrations/github/routes.d.ts.map +1 -1
  83. package/dist/integrations/github/routes.js +19 -21
  84. package/dist/integrations/github/routes.js.map +1 -1
  85. package/dist/integrations/github/rules.d.ts +13 -1
  86. package/dist/integrations/github/rules.d.ts.map +1 -1
  87. package/dist/integrations/github/rules.js +80 -9
  88. package/dist/integrations/github/rules.js.map +1 -1
  89. package/dist/integrations/github/sandbox.js +1 -1
  90. package/dist/integrations/github/session-subscriptions.js +3 -3
  91. package/dist/integrations/github/webhook.js +2 -2
  92. package/dist/integrations/gitlab/default-rules.d.ts +24 -9
  93. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  94. package/dist/integrations/gitlab/default-rules.js +4 -4
  95. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  96. package/dist/integrations/gitlab/integration.js +2 -2
  97. package/dist/integrations/gitlab/issue-reconciler.js +1 -1
  98. package/dist/integrations/gitlab/merge-request-reconciler.js +2 -2
  99. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  100. package/dist/integrations/gitlab/routes.js +2 -4
  101. package/dist/integrations/gitlab/routes.js.map +1 -1
  102. package/dist/integrations/gitlab/rules.d.ts +16 -0
  103. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  104. package/dist/integrations/gitlab/rules.js +71 -6
  105. package/dist/integrations/gitlab/rules.js.map +1 -1
  106. package/dist/integrations/gitlab/session-subscriptions.js +1 -1
  107. package/dist/integrations/gitlab/webhook-dispatch.js +1 -1
  108. package/dist/integrations/incidentio/default-rules.d.ts +1 -9
  109. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
  110. package/dist/integrations/incidentio/default-rules.js +3 -4
  111. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  112. package/dist/integrations/incidentio/integration.js +3 -3
  113. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  114. package/dist/integrations/incidentio/routes.js +1 -4
  115. package/dist/integrations/incidentio/routes.js.map +1 -1
  116. package/dist/integrations/incidentio/rules.d.ts +7 -0
  117. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  118. package/dist/integrations/incidentio/rules.js +37 -5
  119. package/dist/integrations/incidentio/rules.js.map +1 -1
  120. package/dist/integrations/jira/default-rules.d.ts +1 -9
  121. package/dist/integrations/jira/default-rules.d.ts.map +1 -1
  122. package/dist/integrations/jira/default-rules.js +3 -4
  123. package/dist/integrations/jira/default-rules.js.map +1 -1
  124. package/dist/integrations/jira/integration.js +2 -2
  125. package/dist/integrations/jira/routes.d.ts.map +1 -1
  126. package/dist/integrations/jira/routes.js +2 -5
  127. package/dist/integrations/jira/routes.js.map +1 -1
  128. package/dist/integrations/jira/rules.d.ts +7 -0
  129. package/dist/integrations/jira/rules.d.ts.map +1 -1
  130. package/dist/integrations/jira/rules.js +37 -5
  131. package/dist/integrations/jira/rules.js.map +1 -1
  132. package/dist/integrations/linear/default-rules.d.ts +1 -9
  133. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  134. package/dist/integrations/linear/default-rules.js +3 -4
  135. package/dist/integrations/linear/default-rules.js.map +1 -1
  136. package/dist/integrations/linear/integration.js +2 -2
  137. package/dist/integrations/linear/routes.d.ts +21 -1
  138. package/dist/integrations/linear/routes.d.ts.map +1 -1
  139. package/dist/integrations/linear/routes.js +21 -6
  140. package/dist/integrations/linear/routes.js.map +1 -1
  141. package/dist/integrations/linear/rules.d.ts +7 -0
  142. package/dist/integrations/linear/rules.d.ts.map +1 -1
  143. package/dist/integrations/linear/rules.js +37 -5
  144. package/dist/integrations/linear/rules.js.map +1 -1
  145. package/dist/integrations/platform/connect/routes.d.ts +7 -1
  146. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  147. package/dist/integrations/platform/connect/routes.js +42 -5
  148. package/dist/integrations/platform/connect/routes.js.map +1 -1
  149. package/dist/integrations/platform/connect/session-tools.d.ts +7 -0
  150. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -0
  151. package/dist/integrations/platform/connect/session-tools.js +30 -0
  152. package/dist/integrations/platform/connect/session-tools.js.map +1 -0
  153. package/dist/integrations/platform/github/event-worker.js +1 -1
  154. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  155. package/dist/integrations/platform/github/integration.js +9 -8
  156. package/dist/integrations/platform/github/integration.js.map +1 -1
  157. package/dist/integrations/platform/gitlab/event-worker.js +1 -1
  158. package/dist/integrations/platform/gitlab/integration.js +2 -2
  159. package/dist/integrations/platform/incidentio/integration.js +5 -5
  160. package/dist/integrations/platform/jira/agent-tools.js +1 -1
  161. package/dist/integrations/platform/jira/integration.js +2 -2
  162. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  163. package/dist/integrations/platform/jira/routes.js +2 -5
  164. package/dist/integrations/platform/jira/routes.js.map +1 -1
  165. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  166. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  167. package/dist/integrations/platform/linear/event-worker.js +9 -0
  168. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  169. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  170. package/dist/integrations/platform/linear/integration.js +150 -48
  171. package/dist/integrations/platform/linear/integration.js.map +1 -1
  172. package/dist/integrations/slack/channel-reply-processor.d.ts +2 -0
  173. package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
  174. package/dist/integrations/slack/channel-reply-processor.js +6 -1
  175. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  176. package/dist/integrations/slack/chat-tools.d.ts +16 -0
  177. package/dist/integrations/slack/chat-tools.d.ts.map +1 -0
  178. package/dist/integrations/slack/chat-tools.js +215 -0
  179. package/dist/integrations/slack/chat-tools.js.map +1 -0
  180. package/dist/integrations/slack/connect-route.d.ts.map +1 -1
  181. package/dist/integrations/slack/connect-route.js +1 -1
  182. package/dist/integrations/slack/connect-route.js.map +1 -1
  183. package/dist/integrations/slack/integration.d.ts +19 -3
  184. package/dist/integrations/slack/integration.d.ts.map +1 -1
  185. package/dist/integrations/slack/integration.js +27 -8
  186. package/dist/integrations/slack/integration.js.map +1 -1
  187. package/dist/integrations/slack/run-error-card.js +1 -1
  188. package/dist/integrations/slack/share-file-tool.d.ts +8 -0
  189. package/dist/integrations/slack/share-file-tool.d.ts.map +1 -1
  190. package/dist/integrations/slack/share-file-tool.js +13 -4
  191. package/dist/integrations/slack/share-file-tool.js.map +1 -1
  192. package/dist/integrations/slack/slack.d.ts +12 -10
  193. package/dist/integrations/slack/slack.d.ts.map +1 -1
  194. package/dist/integrations/slack/slack.js +113 -46
  195. package/dist/integrations/slack/slack.js.map +1 -1
  196. package/dist/integrations/slack/tool-settings.d.ts +26 -0
  197. package/dist/integrations/slack/tool-settings.d.ts.map +1 -0
  198. package/dist/integrations/slack/tool-settings.js +35 -0
  199. package/dist/integrations/slack/tool-settings.js.map +1 -0
  200. package/dist/integrations/slack/voice-clips.d.ts +32 -0
  201. package/dist/integrations/slack/voice-clips.d.ts.map +1 -0
  202. package/dist/integrations/slack/voice-clips.js +201 -0
  203. package/dist/integrations/slack/voice-clips.js.map +1 -0
  204. package/dist/integrations/workos/integration.d.ts.map +1 -1
  205. package/dist/integrations/workos/integration.js +1 -3
  206. package/dist/integrations/workos/integration.js.map +1 -1
  207. package/dist/mcp/events.js +1 -1
  208. package/dist/mcp/routes.js +2 -2
  209. package/dist/packages/_internals/workspace/dist/index.js +1 -1
  210. package/dist/routes/attention-activity.js +1 -1
  211. package/dist/routes/attention-providers.js +2 -2
  212. package/dist/routes/attention.js +2 -2
  213. package/dist/routes/automation-runs.d.ts.map +1 -1
  214. package/dist/routes/automation-runs.js +2 -5
  215. package/dist/routes/automation-runs.js.map +1 -1
  216. package/dist/routes/boards.d.ts +8 -6
  217. package/dist/routes/boards.d.ts.map +1 -1
  218. package/dist/routes/boards.js +73 -143
  219. package/dist/routes/boards.js.map +1 -1
  220. package/dist/routes/config.d.ts.map +1 -1
  221. package/dist/routes/config.js +6 -11
  222. package/dist/routes/config.js.map +1 -1
  223. package/dist/routes/contracts.d.ts +162 -2
  224. package/dist/routes/contracts.d.ts.map +1 -1
  225. package/dist/routes/contracts.js +98 -33
  226. package/dist/routes/contracts.js.map +1 -1
  227. package/dist/routes/fs.d.ts.map +1 -1
  228. package/dist/routes/fs.js +2 -5
  229. package/dist/routes/fs.js.map +1 -1
  230. package/dist/routes/intake-routes.d.ts.map +1 -1
  231. package/dist/routes/intake-routes.js +19 -12
  232. package/dist/routes/intake-routes.js.map +1 -1
  233. package/dist/routes/intake.d.ts.map +1 -1
  234. package/dist/routes/intake.js +4 -6
  235. package/dist/routes/intake.js.map +1 -1
  236. package/dist/routes/knowledge.d.ts.map +1 -1
  237. package/dist/routes/knowledge.js +1 -4
  238. package/dist/routes/knowledge.js.map +1 -1
  239. package/dist/routes/oauth.d.ts.map +1 -1
  240. package/dist/routes/oauth.js +1 -4
  241. package/dist/routes/oauth.js.map +1 -1
  242. package/dist/routes/projects.d.ts +3 -0
  243. package/dist/routes/projects.d.ts.map +1 -1
  244. package/dist/routes/projects.js +42 -28
  245. package/dist/routes/projects.js.map +1 -1
  246. package/dist/routes/provider-credentials.d.ts.map +1 -1
  247. package/dist/routes/provider-credentials.js +6 -0
  248. package/dist/routes/provider-credentials.js.map +1 -1
  249. package/dist/routes/route.d.ts +2 -0
  250. package/dist/routes/route.d.ts.map +1 -1
  251. package/dist/routes/route.js +5 -1
  252. package/dist/routes/route.js.map +1 -1
  253. package/dist/routes/skills.d.ts.map +1 -1
  254. package/dist/routes/skills.js +2 -5
  255. package/dist/routes/skills.js.map +1 -1
  256. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  257. package/dist/routes/source-control-sessions.js +3 -5
  258. package/dist/routes/source-control-sessions.js.map +1 -1
  259. package/dist/routes/source-control-settings.d.ts.map +1 -1
  260. package/dist/routes/source-control-settings.js +3 -2
  261. package/dist/routes/source-control-settings.js.map +1 -1
  262. package/dist/routes/surface.d.ts +3 -1
  263. package/dist/routes/surface.d.ts.map +1 -1
  264. package/dist/routes/surface.js +27 -17
  265. package/dist/routes/surface.js.map +1 -1
  266. package/dist/routes/telemetry.js +1 -1
  267. package/dist/routes/voice.d.ts +48 -0
  268. package/dist/routes/voice.d.ts.map +1 -0
  269. package/dist/routes/voice.js +248 -0
  270. package/dist/routes/voice.js.map +1 -0
  271. package/dist/routes/work-items.d.ts.map +1 -1
  272. package/dist/routes/work-items.js +9 -12
  273. package/dist/routes/work-items.js.map +1 -1
  274. package/dist/rules/decision-applicability.js +1 -1
  275. package/dist/rules/dispatcher.d.ts +42 -0
  276. package/dist/rules/dispatcher.d.ts.map +1 -1
  277. package/dist/rules/dispatcher.js +522 -136
  278. package/dist/rules/dispatcher.js.map +1 -1
  279. package/dist/rules/event-rules.d.ts +40 -1
  280. package/dist/rules/event-rules.d.ts.map +1 -1
  281. package/dist/rules/event-rules.js +59 -1
  282. package/dist/rules/event-rules.js.map +1 -1
  283. package/dist/rules/index.js +1 -1
  284. package/dist/rules/processor.d.ts +2 -0
  285. package/dist/rules/processor.d.ts.map +1 -1
  286. package/dist/rules/processor.js +5 -4
  287. package/dist/rules/processor.js.map +1 -1
  288. package/dist/rules/start-coordinator.js +2 -2
  289. package/dist/rules/terminal-cleanup.js.map +1 -1
  290. package/dist/rules/tools.js +5 -5
  291. package/dist/rules/transition-service.d.ts +9 -0
  292. package/dist/rules/transition-service.d.ts.map +1 -1
  293. package/dist/rules/transition-service.js +9 -7
  294. package/dist/rules/transition-service.js.map +1 -1
  295. package/dist/rules/types.d.ts +54 -3
  296. package/dist/rules/types.d.ts.map +1 -1
  297. package/dist/rules/types.js +2 -0
  298. package/dist/rules/types.js.map +1 -1
  299. package/dist/rules/validation.d.ts.map +1 -1
  300. package/dist/rules/validation.js +57 -2
  301. package/dist/rules/validation.js.map +1 -1
  302. package/dist/sandbox/session-retirement.js +2 -2
  303. package/dist/sandbox/session-sandbox.js +1 -1
  304. package/dist/session/credential-policy.d.ts +2 -2
  305. package/dist/session/credential-policy.d.ts.map +1 -1
  306. package/dist/session/credential-policy.js +4 -4
  307. package/dist/session/credential-policy.js.map +1 -1
  308. package/dist/session/default-model-hydration.d.ts +2 -2
  309. package/dist/session/default-model-hydration.d.ts.map +1 -1
  310. package/dist/session/default-model-hydration.js +4 -4
  311. package/dist/session/default-model-hydration.js.map +1 -1
  312. package/dist/session/factory-session.js +3 -3
  313. package/dist/session/self-review-gate.js +1 -1
  314. package/dist/session/session-threads.d.ts +8 -0
  315. package/dist/session/session-threads.d.ts.map +1 -1
  316. package/dist/session/session-threads.js +11 -1
  317. package/dist/session/session-threads.js.map +1 -1
  318. package/dist/session/source-control-tools.js +3 -3
  319. package/dist/skills/catalog.js +1 -1
  320. package/dist/storage/domains/audit/actions.d.ts +1 -1
  321. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  322. package/dist/storage/domains/audit/actions.js +2 -1
  323. package/dist/storage/domains/audit/actions.js.map +1 -1
  324. package/dist/storage/domains/audit/domain.d.ts.map +1 -1
  325. package/dist/storage/domains/audit/domain.js +2 -4
  326. package/dist/storage/domains/audit/domain.js.map +1 -1
  327. package/dist/storage/domains/boards/base.d.ts +32 -1
  328. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  329. package/dist/storage/domains/boards/base.js +155 -8
  330. package/dist/storage/domains/boards/base.js.map +1 -1
  331. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  332. package/dist/storage/domains/boards/schemas.js +13 -1
  333. package/dist/storage/domains/boards/schemas.js.map +1 -1
  334. package/dist/storage/domains/comments/base.js +3 -3
  335. package/dist/storage/domains/comments/domain.js +3 -3
  336. package/dist/storage/domains/comments/routes.d.ts.map +1 -1
  337. package/dist/storage/domains/comments/routes.js +2 -4
  338. package/dist/storage/domains/comments/routes.js.map +1 -1
  339. package/dist/storage/domains/memory-settings/base.d.ts +0 -8
  340. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -1
  341. package/dist/storage/domains/memory-settings/base.js +1 -11
  342. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  343. package/dist/storage/domains/projects/base.d.ts +6 -0
  344. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  345. package/dist/storage/domains/projects/base.js +9 -1
  346. package/dist/storage/domains/projects/base.js.map +1 -1
  347. package/dist/storage/domains/source-control/base.d.ts +20 -0
  348. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  349. package/dist/storage/domains/source-control/base.js +42 -0
  350. package/dist/storage/domains/source-control/base.js.map +1 -1
  351. package/dist/storage/domains/source-control/inmemory.d.ts +5 -1
  352. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  353. package/dist/storage/domains/source-control/inmemory.js +23 -0
  354. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  355. package/dist/storage/domains/voice-settings/base.d.ts +31 -0
  356. package/dist/storage/domains/voice-settings/base.d.ts.map +1 -0
  357. package/dist/storage/domains/voice-settings/base.js +81 -0
  358. package/dist/storage/domains/voice-settings/base.js.map +1 -0
  359. package/dist/storage/domains/work-items/base.d.ts +47 -7
  360. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  361. package/dist/storage/domains/work-items/base.js +251 -115
  362. package/dist/storage/domains/work-items/base.js.map +1 -1
  363. package/dist/storage/domains/work-items/cards.d.ts +6 -1
  364. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  365. package/dist/storage/domains/work-items/cards.js +55 -5
  366. package/dist/storage/domains/work-items/cards.js.map +1 -1
  367. package/dist/storage/domains/work-items/claimable-work.d.ts +15 -0
  368. package/dist/storage/domains/work-items/claimable-work.d.ts.map +1 -0
  369. package/dist/storage/domains/work-items/claimable-work.js +51 -0
  370. package/dist/storage/domains/work-items/claimable-work.js.map +1 -0
  371. package/dist/storage/domains/work-items/work-item-schema.d.ts +2 -0
  372. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  373. package/dist/storage/domains/work-items/work-item-schema.js +24 -1
  374. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  375. package/dist/timing.d.ts +1 -0
  376. package/dist/timing.d.ts.map +1 -1
  377. package/dist/timing.js +1 -1
  378. package/dist/timing.js.map +1 -1
  379. package/dist/tools/index.js +2 -2
  380. package/dist/tools/messaging-tools.js +1 -1
  381. package/dist/tools/read-tools.d.ts +2 -2
  382. package/dist/tools/read-tools.d.ts.map +1 -1
  383. package/dist/tools/read-tools.js +10 -9
  384. package/dist/tools/read-tools.js.map +1 -1
  385. package/dist/tools/scope.js +1 -1
  386. package/dist/tools/session-tools.d.ts +1 -1
  387. package/dist/tools/session-tools.d.ts.map +1 -1
  388. package/dist/tools/session-tools.js +9 -9
  389. package/dist/tools/session-tools.js.map +1 -1
  390. package/dist/tools/sessions-state-processor.d.ts +1 -1
  391. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  392. package/dist/tools/sessions-state-processor.js +9 -2
  393. package/dist/tools/sessions-state-processor.js.map +1 -1
  394. package/dist/tools/work-item-tools.js +4 -4
  395. package/dist/voice/rate-limit.d.ts +13 -0
  396. package/dist/voice/rate-limit.d.ts.map +1 -0
  397. package/dist/voice/rate-limit.js +36 -0
  398. package/dist/voice/rate-limit.js.map +1 -0
  399. package/dist/voice/realtime.d.ts +13 -0
  400. package/dist/voice/realtime.d.ts.map +1 -0
  401. package/dist/voice/realtime.js +56 -0
  402. package/dist/voice/realtime.js.map +1 -0
  403. package/dist/voice/transcription.d.ts +51 -0
  404. package/dist/voice/transcription.d.ts.map +1 -0
  405. package/dist/voice/transcription.js +112 -0
  406. package/dist/voice/transcription.js.map +1 -0
  407. package/dist/work-items/create-work-item.js +2 -2
  408. package/dist/work-items/decision-actions.js +2 -2
  409. package/dist/work-items/providers/gitlab.js +1 -1
  410. package/dist/work-items/providers/incidentio.js +1 -1
  411. package/dist/work-items/providers/index.js +1 -1
  412. package/dist/work-items/providers/jira.js +1 -1
  413. package/dist/work-items/providers/linear.js +1 -1
  414. package/dist/work-items/split-backfill.d.ts +13 -0
  415. package/dist/work-items/split-backfill.d.ts.map +1 -0
  416. package/dist/work-items/split-backfill.js +32 -0
  417. package/dist/work-items/split-backfill.js.map +1 -0
  418. package/dist/work-items/split-migration.d.ts +39 -2
  419. package/dist/work-items/split-migration.d.ts.map +1 -1
  420. package/dist/work-items/split-migration.js +171 -63
  421. package/dist/work-items/split-migration.js.map +1 -1
  422. package/dist/workspace.d.ts +2 -0
  423. package/dist/workspace.d.ts.map +1 -1
  424. package/dist/workspace.js +12 -9
  425. package/dist/workspace.js.map +1 -1
  426. package/package.json +10 -9
@@ -1 +1 @@
1
- {"version":3,"file":"channel-reply-processor.d.ts","sourceRoot":"","sources":["../../../src/integrations/slack/channel-reply-processor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAQ/E,eAAO,MAAM,kBAAkB,wBAAmB,CAAC;AAanD;;;;;;;;;;;;GAYG;AACH,qBAAa,4BAA6B,YAAW,SAAS;IAC5D,QAAQ,CAAC,EAAE,2BAAM;IAEjB,gBAAgB,CAAC,EAAE,WAAW,EAAE,cAAc,EAAE,KAAK,EAAE,EAAE,oBAAoB;;kBA+B5E;CACF;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,EAC1B,QAAQ,EACR,SAAS,EACT,UAAU,EACV,gBAAgB,GACjB,EAAE,iBAAiB,GAAG,MAAM,GAAG,SAAS,CAQxC;AAED,wBAAgB,iBAAiB,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAE9E"}
1
+ {"version":3,"file":"channel-reply-processor.d.ts","sourceRoot":"","sources":["../../../src/integrations/slack/channel-reply-processor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAQ/E,eAAO,MAAM,kBAAkB,wBAAmB,CAAC;AAanD;;;;;;;;;;;;GAYG;AACH,qBAAa,4BAA6B,YAAW,SAAS;IAC5D,QAAQ,CAAC,EAAE,2BAAM;IAEjB,gBAAgB,CAAC,EAAE,WAAW,EAAE,cAAc,EAAE,KAAK,EAAE,EAAE,oBAAoB;;kBA+B5E;CACF;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,EAC1B,QAAQ,EACR,SAAS,EACT,UAAU,EACV,gBAAgB,GACjB,EAAE,iBAAiB,GAAG,MAAM,GAAG,SAAS,CAQxC;AAED,wBAAgB,iBAAiB,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAE9E;AAED,2HAA2H;AAC3H,wBAAgB,iBAAiB,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAG9E"}
@@ -70,6 +70,11 @@ function sessionLink({ threadId, sessionId, resourceId, factoryProjectId }) {
70
70
  function modelSettingsLink(factoryProjectId) {
71
71
  return factorySettingsUrl(factoryProjectId, "models");
72
72
  }
73
- export { FactoryChannelReplyProcessor, SESSION_LINK_LABEL, modelSettingsLink, sessionLink };
73
+ /** `VOICE_INPUT_ANCHOR` in factory-ui's `settingsSections.ts`; the voice section scrolls itself into view on this hash. */
74
+ function voiceSettingsLink(factoryProjectId) {
75
+ const models = modelSettingsLink(factoryProjectId);
76
+ return models && `${models}#voice-input`;
77
+ }
78
+ export { FactoryChannelReplyProcessor, SESSION_LINK_LABEL, modelSettingsLink, sessionLink, voiceSettingsLink };
74
79
 
75
80
  //# sourceMappingURL=channel-reply-processor.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"channel-reply-processor.js","names":[],"sources":["../../../src/integrations/slack/channel-reply-processor.ts"],"sourcesContent":["import type { ProcessInputStepArgs, Processor } from '@mastra/core/processors';\nimport { factorySettingsUrl, factoryUiOrigin } from '../../links.js';\n\n/** Mirrors `REPLY_TOOL_NAME` in `reply-tool.ts`, which imports this module. */\nconst REPLY_TOOL = 'reply_in_thread';\n\nconst ID = 'factory-channel-reply';\n\nexport const SESSION_LINK_LABEL = 'Open session ↗';\n\n/**\n * Chat surfaces show what the agent writes as-is, so a bare `#28467`,\n * `FACT-526` or `52db47cd` is a dead end for the reader. Every channel run\n * gets this, whether it speaks in reply text or through the reply tool.\n */\nconst LINK_REFERENCES = [\n 'Write every pull request, issue, commit, Linear ticket or other reference you mention in the thread as a markdown link to its page, with the ID as plain link text: [#28467](https://github.com/<owner>/<repo>/pull/28467), [52db47cd](https://github.com/<owner>/<repo>/commit/52db47cd), [FACT-526](<the ticket URL>). Never leave one as a bare ID or wrap it in code formatting.',\n \"Build GitHub and GitLab links from the repository the reference belongs to, from the repositories listed in your environment or a tool result; with more than one repository, don't assume which one a bare number belongs to. Build Linear links from the workspace URL pattern in the `linear_get_issue` tool description, or from a URL a tool returned. Don't guess a URL; leave a reference unlinked only when you can't work out its URL.\",\n 'Link Factory work items and sessions the same way, with the `url` the Factory tools return: [#123](<item url>). When something needs a person, ask them for it here and link the item; only send them to the web UI when the channel cannot do it, and then link the exact page.',\n].join('\\n');\n\n/**\n * Tells the agent how to open a reply when the run came in over a chat\n * channel (Slack, …): acknowledge a job in one line that names it — \"On it —\n * sleeping 30s, then running the echo\" — before starting, so the sender sees\n * a task-specific first message rather than a silent typing status until the\n * first tool finishes. The channel driver posts that opener on its own before\n * the tool widget, so the instruction and the rendering agree. The session\n * link is not the model's job: `FactoryChannelSessionLinkProcessor` appends it\n * to the first reply of a new session, so it is there whether or not the\n * model judged the request worth an opener. A run on a Slack-linked session\n * that didn't start from Slack gets a shorter note on when to post there; runs\n * with no channel at all (Studio, API, boards) get nothing.\n */\nexport class FactoryChannelReplyProcessor implements Processor {\n readonly id = ID;\n\n processInputStep({ messageList, requestContext, tools }: ProcessInputStepArgs) {\n if (!requestContext?.get('channel')) {\n // A run on a Slack-linked session that didn't start from a Slack message\n // (a web prompt, a woken run) still has the reply tool; core's channel\n // prompt says the thread is linked, this says how to use it.\n if (!tools || !(REPLY_TOOL in tools)) return undefined;\n messageList.addSystem(\n {\n role: 'system',\n content: `Post to that thread with \\`${REPLY_TOOL}\\`. This request came from outside it, so don't post an opener or progress there; post the outcome when the people in the thread asked for this work or are waiting on it, or when you're asked to. Don't write a note about what you posted. When you open a pull request, its link is posted to this thread for you, and again when it merges, so don't post the link yourself.\\n${LINK_REFERENCES}`,\n },\n ID,\n );\n return { messageList };\n }\n // With reply text hidden the thread only sees what the reply tool posts,\n // so the opener advice becomes advice about when to call it.\n const content =\n tools && REPLY_TOOL in tools\n ? [\n `Only messages you send with \\`${REPLY_TOOL}\\` reach this thread; your other text stays in the session. Don't write a note about what you posted. After a reply, either keep working or end your turn with an empty message; any text you write after posting is wasted.`,\n `When a request will take tools or more than a moment, post one short line first that says what you are about to do, then do the work and post the outcome when you finish — not a replay of the steps.`,\n `Post again in between only when you need an answer or have news the people in the thread would want. When a message needs nothing from you, don't call it.`,\n `When you open a pull request, its link is posted to this thread for you, and again when it merges, so don't post the link yourself.`,\n ]\n : [\n 'When a request will take tools or more than a moment to answer, reply first with one short line that says what you are about to do — \"On it — <the task in a few words>.\" — then do the work; the opener posts as its own message before any progress is shown. Give direct answers and trivial replies without an opener.',\n 'Finish with the outcome, not a replay of the steps.',\n ];\n messageList.addSystem({ role: 'system', content: [...content, LINK_REFERENCES].join('\\n') }, ID);\n return { messageList };\n }\n}\n\nexport interface SessionLinkTarget {\n threadId: string;\n sessionId: string;\n resourceId: string;\n factoryProjectId?: string;\n}\n\n/**\n * The web URL for a session, or undefined without a public origin. Same\n * routes the Factory UI navigates to: a repo-backed thread's Factory session\n * id is the workspace segment; chat-only threads keep the literal `channel`\n * segment and name their session in the query; a session with no factory\n * falls back to the factory-agnostic /threads/ redirect, which forwards the\n * query through.\n */\nexport function sessionLink({\n threadId,\n sessionId,\n resourceId,\n factoryProjectId,\n}: SessionLinkTarget): string | undefined {\n const origin = factoryUiOrigin();\n if (!origin) return undefined;\n const isChatOnly = resourceId.startsWith('channel:');\n const sessionParam = `?sessionId=${encodeURIComponent(sessionId)}`;\n if (!factoryProjectId) return `${origin}/threads/${encodeURIComponent(threadId)}${sessionParam}`;\n const workspaceSegment = isChatOnly ? 'channel' : encodeURIComponent(sessionId);\n return `${origin}/factories/${encodeURIComponent(factoryProjectId)}/workspaces/${workspaceSegment}/threads/${encodeURIComponent(threadId)}${isChatOnly ? sessionParam : ''}`;\n}\n\nexport function modelSettingsLink(factoryProjectId: string): string | undefined {\n return factorySettingsUrl(factoryProjectId, 'models');\n}\n"],"mappings":";;;AAIA,MAAM,aAAa;AAEnB,MAAM,KAAK;AAEX,MAAa,qBAAqB;;;;;;AAOlC,MAAM,kBAAkB;CACtB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;;;;;;;;;;;AAeX,IAAa,+BAAb,MAA+D;CAC7D,KAAc;CAEd,iBAAiB,EAAE,aAAa,gBAAgB,SAA+B;EAC7E,IAAI,CAAC,gBAAgB,IAAI,SAAS,GAAG;GAInC,IAAI,CAAC,SAAS,EAAE,cAAc,QAAQ,OAAO,KAAA;GAC7C,YAAY,UACV;IACE,MAAM;IACN,SAAS,8BAA8B,WAAW,qXAAqX;GACza,GACA,EACF;GACA,OAAO,EAAE,YAAY;EACvB;EAGA,MAAM,UACJ,SAAS,cAAc,QACnB;GACE,iCAAiC,WAAW;GAC5C;GACA;GACA;EACF,IACA,CACE,gUACA,qDACF;EACN,YAAY,UAAU;GAAE,MAAM;GAAU,SAAS,CAAC,GAAG,SAAS,eAAe,CAAC,CAAC,KAAK,IAAI;EAAE,GAAG,EAAE;EAC/F,OAAO,EAAE,YAAY;CACvB;AACF;;;;;;;;;AAiBA,SAAgB,YAAY,EAC1B,UACA,WACA,YACA,oBACwC;CACxC,MAAM,SAAS,gBAAgB;CAC/B,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,MAAM,aAAa,WAAW,WAAW,UAAU;CACnD,MAAM,eAAe,cAAc,mBAAmB,SAAS;CAC/D,IAAI,CAAC,kBAAkB,OAAO,GAAG,OAAO,WAAW,mBAAmB,QAAQ,IAAI;CAElF,OAAO,GAAG,OAAO,aAAa,mBAAmB,gBAAgB,EAAE,cAD1C,aAAa,YAAY,mBAAmB,SAAS,EACoB,WAAW,mBAAmB,QAAQ,IAAI,aAAa,eAAe;AAC1K;AAEA,SAAgB,kBAAkB,kBAA8C;CAC9E,OAAO,mBAAmB,kBAAkB,QAAQ;AACtD"}
1
+ {"version":3,"file":"channel-reply-processor.js","names":[],"sources":["../../../src/integrations/slack/channel-reply-processor.ts"],"sourcesContent":["import type { ProcessInputStepArgs, Processor } from '@mastra/core/processors';\nimport { factorySettingsUrl, factoryUiOrigin } from '../../links.js';\n\n/** Mirrors `REPLY_TOOL_NAME` in `reply-tool.ts`, which imports this module. */\nconst REPLY_TOOL = 'reply_in_thread';\n\nconst ID = 'factory-channel-reply';\n\nexport const SESSION_LINK_LABEL = 'Open session ↗';\n\n/**\n * Chat surfaces show what the agent writes as-is, so a bare `#28467`,\n * `FACT-526` or `52db47cd` is a dead end for the reader. Every channel run\n * gets this, whether it speaks in reply text or through the reply tool.\n */\nconst LINK_REFERENCES = [\n 'Write every pull request, issue, commit, Linear ticket or other reference you mention in the thread as a markdown link to its page, with the ID as plain link text: [#28467](https://github.com/<owner>/<repo>/pull/28467), [52db47cd](https://github.com/<owner>/<repo>/commit/52db47cd), [FACT-526](<the ticket URL>). Never leave one as a bare ID or wrap it in code formatting.',\n \"Build GitHub and GitLab links from the repository the reference belongs to, from the repositories listed in your environment or a tool result; with more than one repository, don't assume which one a bare number belongs to. Build Linear links from the workspace URL pattern in the `linear_get_issue` tool description, or from a URL a tool returned. Don't guess a URL; leave a reference unlinked only when you can't work out its URL.\",\n 'Link Factory work items and sessions the same way, with the `url` the Factory tools return: [#123](<item url>). When something needs a person, ask them for it here and link the item; only send them to the web UI when the channel cannot do it, and then link the exact page.',\n].join('\\n');\n\n/**\n * Tells the agent how to open a reply when the run came in over a chat\n * channel (Slack, …): acknowledge a job in one line that names it — \"On it —\n * sleeping 30s, then running the echo\" — before starting, so the sender sees\n * a task-specific first message rather than a silent typing status until the\n * first tool finishes. The channel driver posts that opener on its own before\n * the tool widget, so the instruction and the rendering agree. The session\n * link is not the model's job: `FactoryChannelSessionLinkProcessor` appends it\n * to the first reply of a new session, so it is there whether or not the\n * model judged the request worth an opener. A run on a Slack-linked session\n * that didn't start from Slack gets a shorter note on when to post there; runs\n * with no channel at all (Studio, API, boards) get nothing.\n */\nexport class FactoryChannelReplyProcessor implements Processor {\n readonly id = ID;\n\n processInputStep({ messageList, requestContext, tools }: ProcessInputStepArgs) {\n if (!requestContext?.get('channel')) {\n // A run on a Slack-linked session that didn't start from a Slack message\n // (a web prompt, a woken run) still has the reply tool; core's channel\n // prompt says the thread is linked, this says how to use it.\n if (!tools || !(REPLY_TOOL in tools)) return undefined;\n messageList.addSystem(\n {\n role: 'system',\n content: `Post to that thread with \\`${REPLY_TOOL}\\`. This request came from outside it, so don't post an opener or progress there; post the outcome when the people in the thread asked for this work or are waiting on it, or when you're asked to. Don't write a note about what you posted. When you open a pull request, its link is posted to this thread for you, and again when it merges, so don't post the link yourself.\\n${LINK_REFERENCES}`,\n },\n ID,\n );\n return { messageList };\n }\n // With reply text hidden the thread only sees what the reply tool posts,\n // so the opener advice becomes advice about when to call it.\n const content =\n tools && REPLY_TOOL in tools\n ? [\n `Only messages you send with \\`${REPLY_TOOL}\\` reach this thread; your other text stays in the session. Don't write a note about what you posted. After a reply, either keep working or end your turn with an empty message; any text you write after posting is wasted.`,\n `When a request will take tools or more than a moment, post one short line first that says what you are about to do, then do the work and post the outcome when you finish — not a replay of the steps.`,\n `Post again in between only when you need an answer or have news the people in the thread would want. When a message needs nothing from you, don't call it.`,\n `When you open a pull request, its link is posted to this thread for you, and again when it merges, so don't post the link yourself.`,\n ]\n : [\n 'When a request will take tools or more than a moment to answer, reply first with one short line that says what you are about to do — \"On it — <the task in a few words>.\" — then do the work; the opener posts as its own message before any progress is shown. Give direct answers and trivial replies without an opener.',\n 'Finish with the outcome, not a replay of the steps.',\n ];\n messageList.addSystem({ role: 'system', content: [...content, LINK_REFERENCES].join('\\n') }, ID);\n return { messageList };\n }\n}\n\nexport interface SessionLinkTarget {\n threadId: string;\n sessionId: string;\n resourceId: string;\n factoryProjectId?: string;\n}\n\n/**\n * The web URL for a session, or undefined without a public origin. Same\n * routes the Factory UI navigates to: a repo-backed thread's Factory session\n * id is the workspace segment; chat-only threads keep the literal `channel`\n * segment and name their session in the query; a session with no factory\n * falls back to the factory-agnostic /threads/ redirect, which forwards the\n * query through.\n */\nexport function sessionLink({\n threadId,\n sessionId,\n resourceId,\n factoryProjectId,\n}: SessionLinkTarget): string | undefined {\n const origin = factoryUiOrigin();\n if (!origin) return undefined;\n const isChatOnly = resourceId.startsWith('channel:');\n const sessionParam = `?sessionId=${encodeURIComponent(sessionId)}`;\n if (!factoryProjectId) return `${origin}/threads/${encodeURIComponent(threadId)}${sessionParam}`;\n const workspaceSegment = isChatOnly ? 'channel' : encodeURIComponent(sessionId);\n return `${origin}/factories/${encodeURIComponent(factoryProjectId)}/workspaces/${workspaceSegment}/threads/${encodeURIComponent(threadId)}${isChatOnly ? sessionParam : ''}`;\n}\n\nexport function modelSettingsLink(factoryProjectId: string): string | undefined {\n return factorySettingsUrl(factoryProjectId, 'models');\n}\n\n/** `VOICE_INPUT_ANCHOR` in factory-ui's `settingsSections.ts`; the voice section scrolls itself into view on this hash. */\nexport function voiceSettingsLink(factoryProjectId: string): string | undefined {\n const models = modelSettingsLink(factoryProjectId);\n return models && `${models}#voice-input`;\n}\n"],"mappings":";;;AAIA,MAAM,aAAa;AAEnB,MAAM,KAAK;AAEX,MAAa,qBAAqB;;;;;;AAOlC,MAAM,kBAAkB;CACtB;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;;;;;;;;;;;AAeX,IAAa,+BAAb,MAA+D;CAC7D,KAAc;CAEd,iBAAiB,EAAE,aAAa,gBAAgB,SAA+B;EAC7E,IAAI,CAAC,gBAAgB,IAAI,SAAS,GAAG;GAInC,IAAI,CAAC,SAAS,EAAE,cAAc,QAAQ,OAAO,KAAA;GAC7C,YAAY,UACV;IACE,MAAM;IACN,SAAS,8BAA8B,WAAW,qXAAqX;GACza,GACA,EACF;GACA,OAAO,EAAE,YAAY;EACvB;EAGA,MAAM,UACJ,SAAS,cAAc,QACnB;GACE,iCAAiC,WAAW;GAC5C;GACA;GACA;EACF,IACA,CACE,gUACA,qDACF;EACN,YAAY,UAAU;GAAE,MAAM;GAAU,SAAS,CAAC,GAAG,SAAS,eAAe,CAAC,CAAC,KAAK,IAAI;EAAE,GAAG,EAAE;EAC/F,OAAO,EAAE,YAAY;CACvB;AACF;;;;;;;;;AAiBA,SAAgB,YAAY,EAC1B,UACA,WACA,YACA,oBACwC;CACxC,MAAM,SAAS,gBAAgB;CAC/B,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,MAAM,aAAa,WAAW,WAAW,UAAU;CACnD,MAAM,eAAe,cAAc,mBAAmB,SAAS;CAC/D,IAAI,CAAC,kBAAkB,OAAO,GAAG,OAAO,WAAW,mBAAmB,QAAQ,IAAI;CAElF,OAAO,GAAG,OAAO,aAAa,mBAAmB,gBAAgB,EAAE,cAD1C,aAAa,YAAY,mBAAmB,SAAS,EACoB,WAAW,mBAAmB,QAAQ,IAAI,aAAa,eAAe;AAC1K;AAEA,SAAgB,kBAAkB,kBAA8C;CAC9E,OAAO,mBAAmB,kBAAkB,QAAQ;AACtD;;AAGA,SAAgB,kBAAkB,kBAA8C;CAC9E,MAAM,SAAS,kBAAkB,gBAAgB;CACjD,OAAO,UAAU,GAAG,OAAO;AAC7B"}
@@ -0,0 +1,16 @@
1
+ import type { Chat } from 'chat';
2
+ import type { IntegrationTools } from '../base.js';
3
+ import type { SlackToolSettings } from './tool-settings.js';
4
+ /**
5
+ * The Chat SDK's read and post tools, plus channel/person lookup, search and
6
+ * DMs, confined to the channels `settings` grant. They act as the app, so a
7
+ * session never reaches a channel the app isn't in, and posting needs no
8
+ * approval.
9
+ */
10
+ export declare function createSlackChatTools({ chat, sessionThreadId, settings, }: {
11
+ chat: Chat;
12
+ /** The session's own chat thread id, e.g. `slack:C123:1700000000.000100`. */
13
+ sessionThreadId: string;
14
+ settings: SlackToolSettings;
15
+ }): IntegrationTools;
16
+ //# sourceMappingURL=chat-tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat-tools.d.ts","sourceRoot":"","sources":["../../../src/integrations/slack/chat-tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAajC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AA0C5D;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,IAAI,EACJ,eAAe,EACf,QAAQ,GACT,EAAE;IACD,IAAI,EAAE,IAAI,CAAC;IACX,6EAA6E;IAC7E,eAAe,EAAE,MAAM,CAAC;IACxB,QAAQ,EAAE,iBAAiB,CAAC;CAC7B,GAAG,gBAAgB,CAsMnB"}
@@ -0,0 +1,215 @@
1
+ import { z } from "zod";
2
+ import { createTool } from "@mastra/core/tools";
3
+ import { fetchChannelMessages, fetchMessages, fetchThread, getChannelInfo, getThreadParticipants, listThreads, postChannelMessage, postMessage } from "chat/ai";
4
+ // src/integrations/slack/chat-tools.ts
5
+ /** Pages read per lookup, so one call can't walk a huge workspace. */
6
+ const MAX_LOOKUP_PAGES = 10;
7
+ /** Most messages searchMessages reads per channel. */
8
+ const MAX_SEARCH_SCAN = 1e3;
9
+ /** Treats a bare Slack id (`C0123`, `D0123`) as `slack:C0123`. */
10
+ function withPrefix(id) {
11
+ return id.startsWith("slack:") ? id : `slack:${id}`;
12
+ }
13
+ /** Same resolution the Chat SDK's own scope guard uses. */
14
+ function channelOf(chat, id) {
15
+ const prefix = id.split(":")[0];
16
+ return (prefix ? chat.getAdapter(prefix) : void 0)?.channelIdFromThreadId?.(id) ?? id.split(":").slice(0, 2).join(":");
17
+ }
18
+ const slackClient = (chat) => chat.getAdapter("slack").webClient;
19
+ /**
20
+ * Reads a paginated Slack list until it runs out of pages or hits the cap.
21
+ * `incomplete` is set when the cap stopped it, so a lookup that found nothing
22
+ * isn't mistaken for "doesn't exist".
23
+ */
24
+ async function listAll(fetchPage) {
25
+ const items = [];
26
+ let cursor;
27
+ for (let page = 0; page < MAX_LOOKUP_PAGES; page++) {
28
+ const result = await fetchPage(cursor);
29
+ items.push(...result.items ?? []);
30
+ cursor = result.response_metadata?.next_cursor || void 0;
31
+ if (!cursor) return { items };
32
+ }
33
+ return {
34
+ items,
35
+ incomplete: true
36
+ };
37
+ }
38
+ const normalize = (text) => text.toLowerCase().replace(/^[#@]/, "").trim();
39
+ /**
40
+ * The Chat SDK's read and post tools, plus channel/person lookup, search and
41
+ * DMs, confined to the channels `settings` grant. They act as the app, so a
42
+ * session never reaches a channel the app isn't in, and posting needs no
43
+ * approval.
44
+ */
45
+ function createSlackChatTools({ chat, sessionThreadId, settings }) {
46
+ const all = settings.channels === "all";
47
+ const allowed = /* @__PURE__ */ new Set([channelOf(chat, sessionThreadId), ...settings.channels === "selected" ? settings.channelIds.map((id) => `slack:${id}`) : []]);
48
+ const scope = all ? "any channel the app is a member of" : [...allowed].join(", ");
49
+ const ownChannel = channelOf(chat, sessionThreadId);
50
+ const guard = (id) => {
51
+ const channel = channelOf(chat, withPrefix(id));
52
+ if (channel.startsWith("slack:D") && channel !== ownChannel) throw new Error(`"${id}" is someone else's direct message with the app. Use sendDirectMessage to message a person.`);
53
+ if (all) return;
54
+ if (!allowed.has(channel)) throw new Error(`"${id}" is outside the channels this session can use: ${scope}.`);
55
+ };
56
+ const postGuard = settings.channelAccess === "read" ? (id) => {
57
+ if (channelOf(chat, id) !== ownChannel) throw new Error(`"${id}" is read only for this session: it can only post in its own channel, ${ownChannel}.`);
58
+ } : guard;
59
+ const note = (tool) => ({
60
+ ...tool,
61
+ description: `${String(tool.description)} Channels this session can use: ${scope}${settings.channelAccess === "read" ? " (read only: post only in this session's own channel)" : ""}. This session's thread is ${sessionThreadId}.`
62
+ });
63
+ return {
64
+ fetchMessages: note(fetchMessages(chat, guard)),
65
+ fetchChannelMessages: note(fetchChannelMessages(chat, guard)),
66
+ fetchThread: fetchThread(chat, guard),
67
+ listThreads: note(listThreads(chat, guard)),
68
+ getThreadParticipants: getThreadParticipants(chat, guard),
69
+ getChannelInfo: getChannelInfo(chat, guard),
70
+ postMessage: note(postMessage(chat, {
71
+ needsApproval: false,
72
+ guard: postGuard
73
+ })),
74
+ postChannelMessage: note(postChannelMessage(chat, {
75
+ needsApproval: false,
76
+ guard: (id) => {
77
+ if (id.split(":").length > 2) throw new Error(`"${id}" is a thread, not a channel. Use postMessage to reply in a thread.`);
78
+ postGuard(id);
79
+ }
80
+ })),
81
+ findChannel: createTool({
82
+ id: "findChannel",
83
+ description: "Find Slack channels by name, e.g. \"eng\" or \"#eng-proj-factories\". Returns full channel ids (slack:C…) to pass to the other Slack tools, and whether the app is a member. `incomplete: true` means the workspace was too large to check every channel.",
84
+ inputSchema: z.object({ name: z.string().min(1).describe("All or part of the channel name") }),
85
+ execute: async ({ name }) => {
86
+ const query = normalize(name);
87
+ const { items: found, incomplete } = await listAll(async (cursor) => {
88
+ const page = await slackClient(chat).conversations.list({
89
+ types: "public_channel,private_channel",
90
+ exclude_archived: true,
91
+ limit: 1e3,
92
+ cursor
93
+ });
94
+ return {
95
+ items: page.channels,
96
+ response_metadata: page.response_metadata
97
+ };
98
+ });
99
+ return {
100
+ channels: found.filter((c) => c.name?.toLowerCase().includes(query)).slice(0, 20).map((c) => ({
101
+ id: `slack:${c.id}`,
102
+ name: c.name,
103
+ isPrivate: Boolean(c.is_private),
104
+ isMember: Boolean(c.is_member)
105
+ })),
106
+ ...incomplete && { incomplete }
107
+ };
108
+ }
109
+ }),
110
+ searchMessages: createTool({
111
+ id: "searchMessages",
112
+ description: "Search recent top-level messages in Slack channels for words. Matches messages containing every word, ignoring case. Reads each channel's newest messages (not thread replies), so older messages are missed. Defaults to this session's channel; use findChannel to get other channel ids.",
113
+ inputSchema: z.object({
114
+ query: z.string().min(1).describe("Words to look for"),
115
+ channelIds: z.array(z.string().min(1)).max(10).optional().describe("Channels to search, as slack:C… ids. Defaults to the channel this session started in."),
116
+ scan: z.number().int().min(1).max(MAX_SEARCH_SCAN).default(200).describe("How many of the newest messages to read in each channel"),
117
+ limit: z.number().int().min(1).max(50).default(20).describe("Most matches to return")
118
+ }),
119
+ execute: async ({ query, channelIds, scan, limit }) => {
120
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
121
+ const channels = channelIds?.length ? channelIds : [channelOf(chat, sessionThreadId)];
122
+ const matches = [];
123
+ const errors = [];
124
+ let scanned = 0;
125
+ for (const channelId of channels) {
126
+ const id = withPrefix(channelId);
127
+ const channel = channelOf(chat, id).replace(/^slack:/, "");
128
+ let cursor;
129
+ let read = 0;
130
+ try {
131
+ guard(id);
132
+ while (read < scan) {
133
+ const page = await slackClient(chat).conversations.history({
134
+ channel,
135
+ limit: Math.min(200, scan - read),
136
+ cursor
137
+ });
138
+ for (const message of (page.messages ?? []).slice(0, scan - read)) {
139
+ read++;
140
+ scanned++;
141
+ const text = message.text ?? "";
142
+ if (words.every((word) => text.toLowerCase().includes(word))) matches.push({
143
+ channelId: `slack:${channel}`,
144
+ ts: message.ts ?? "",
145
+ userId: message.user,
146
+ text
147
+ });
148
+ }
149
+ cursor = page.response_metadata?.next_cursor || void 0;
150
+ if (!cursor || (page.messages?.length ?? 0) === 0) break;
151
+ }
152
+ } catch (error) {
153
+ errors.push({
154
+ channelId: `slack:${channel}`,
155
+ error: error.data?.error ?? String(error)
156
+ });
157
+ }
158
+ }
159
+ return {
160
+ matches: matches.slice(0, limit),
161
+ scanned,
162
+ ...errors.length ? { errors } : {}
163
+ };
164
+ }
165
+ }),
166
+ findUser: createTool({
167
+ id: "findUser",
168
+ description: "Find people in Slack by name, e.g. \"Caleb\" or \"@caleb\". Returns their user ids (U…), to mention them as <@U…> in a message or to DM them. `incomplete: true` means the workspace was too large to check everyone.",
169
+ inputSchema: z.object({ name: z.string().min(1).describe("All or part of their name or display name") }),
170
+ execute: async ({ name }) => {
171
+ const query = normalize(name);
172
+ const { items: people, incomplete } = await listAll(async (cursor) => {
173
+ const page = await slackClient(chat).users.list({
174
+ limit: 200,
175
+ cursor
176
+ });
177
+ return {
178
+ items: page.members,
179
+ response_metadata: page.response_metadata
180
+ };
181
+ });
182
+ return {
183
+ users: people.filter((p) => !p.deleted && !p.is_bot && p.id !== "USLACKBOT" && [
184
+ p.name,
185
+ p.profile?.real_name,
186
+ p.profile?.display_name
187
+ ].some((n) => n?.toLowerCase().includes(query))).slice(0, 20).map((p) => ({
188
+ id: p.id,
189
+ name: p.profile?.real_name || p.name,
190
+ displayName: p.profile?.display_name || void 0
191
+ })),
192
+ ...incomplete && { incomplete }
193
+ };
194
+ }
195
+ }),
196
+ ...settings.directMessages === "anyone" ? { sendDirectMessage: createTool({
197
+ id: "sendDirectMessage",
198
+ description: "Send a direct message to a person in Slack. Use findUser to get their user id (U…) from a name.",
199
+ inputSchema: z.object({
200
+ userId: z.string().min(1).describe("Slack user id, e.g. U123456"),
201
+ text: z.string().min(1).describe("The message, in markdown")
202
+ }),
203
+ execute: async ({ userId, text }) => {
204
+ const sent = await (await chat.openDM(userId)).post({ markdown: text });
205
+ return {
206
+ messageId: sent.id,
207
+ threadId: sent.threadId
208
+ };
209
+ }
210
+ }) } : {}
211
+ };
212
+ }
213
+ export { createSlackChatTools };
214
+
215
+ //# sourceMappingURL=chat-tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat-tools.js","names":[],"sources":["../../../src/integrations/slack/chat-tools.ts"],"sourcesContent":["import { createTool } from '@mastra/core/tools';\nimport type { SlackAdapter } from '@mastra/slack';\nimport type { Chat } from 'chat';\nimport {\n fetchChannelMessages,\n fetchMessages,\n fetchThread,\n getChannelInfo,\n getThreadParticipants,\n listThreads,\n postChannelMessage,\n postMessage,\n} from 'chat/ai';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../base.js';\nimport type { SlackToolSettings } from './tool-settings.js';\n\n/** Pages read per lookup, so one call can't walk a huge workspace. */\nconst MAX_LOOKUP_PAGES = 10;\n/** Most messages searchMessages reads per channel. */\nconst MAX_SEARCH_SCAN = 1000;\n\n/** Treats a bare Slack id (`C0123`, `D0123`) as `slack:C0123`. */\nfunction withPrefix(id: string): string {\n return id.startsWith('slack:') ? id : `slack:${id}`;\n}\n\n/** Same resolution the Chat SDK's own scope guard uses. */\nfunction channelOf(chat: Chat, id: string): string {\n const prefix = id.split(':')[0];\n const adapter = prefix ? chat.getAdapter(prefix) : undefined;\n return adapter?.channelIdFromThreadId?.(id) ?? id.split(':').slice(0, 2).join(':');\n}\n\nconst slackClient = (chat: Chat) => (chat.getAdapter('slack') as SlackAdapter).webClient;\n\n/**\n * Reads a paginated Slack list until it runs out of pages or hits the cap.\n * `incomplete` is set when the cap stopped it, so a lookup that found nothing\n * isn't mistaken for \"doesn't exist\".\n */\nasync function listAll<T>(\n fetchPage: (cursor: string | undefined) => Promise<{ items?: T[]; response_metadata?: { next_cursor?: string } }>,\n): Promise<{ items: T[]; incomplete?: true }> {\n const items: T[] = [];\n let cursor: string | undefined;\n for (let page = 0; page < MAX_LOOKUP_PAGES; page++) {\n const result = await fetchPage(cursor);\n items.push(...(result.items ?? []));\n cursor = result.response_metadata?.next_cursor || undefined;\n if (!cursor) return { items };\n }\n return { items, incomplete: true };\n}\n\nconst normalize = (text: string) => text.toLowerCase().replace(/^[#@]/, '').trim();\n\n/**\n * The Chat SDK's read and post tools, plus channel/person lookup, search and\n * DMs, confined to the channels `settings` grant. They act as the app, so a\n * session never reaches a channel the app isn't in, and posting needs no\n * approval.\n */\nexport function createSlackChatTools({\n chat,\n sessionThreadId,\n settings,\n}: {\n chat: Chat;\n /** The session's own chat thread id, e.g. `slack:C123:1700000000.000100`. */\n sessionThreadId: string;\n settings: SlackToolSettings;\n}): IntegrationTools {\n const all = settings.channels === 'all';\n const allowed = new Set([\n channelOf(chat, sessionThreadId),\n ...(settings.channels === 'selected' ? settings.channelIds.map(id => `slack:${id}`) : []),\n ]);\n const scope = all ? 'any channel the app is a member of' : [...allowed].join(', ');\n // Passing our own guard (a bare function for reads, `guard` for writes)\n // replaces the Chat SDK's, which would otherwise confine the tools to the\n // Slack conversation being handled.\n const ownChannel = channelOf(chat, sessionThreadId);\n const guard = (id: string) => {\n const channel = channelOf(chat, withPrefix(id));\n // Other people's DMs with the app are theirs, even when every channel is granted.\n if (channel.startsWith('slack:D') && channel !== ownChannel) {\n throw new Error(`\"${id}\" is someone else's direct message with the app. Use sendDirectMessage to message a person.`);\n }\n if (all) return;\n if (!allowed.has(channel)) {\n throw new Error(`\"${id}\" is outside the channels this session can use: ${scope}.`);\n }\n };\n const postGuard =\n settings.channelAccess === 'read'\n ? (id: string) => {\n if (channelOf(chat, id) !== ownChannel) {\n throw new Error(`\"${id}\" is read only for this session: it can only post in its own channel, ${ownChannel}.`);\n }\n }\n : guard;\n const note = <T extends { description?: unknown }>(tool: T): T => ({\n ...tool,\n description: `${String(tool.description)} Channels this session can use: ${scope}${\n settings.channelAccess === 'read' ? \" (read only: post only in this session's own channel)\" : ''\n }. This session's thread is ${sessionThreadId}.`,\n });\n\n return {\n fetchMessages: note(fetchMessages(chat, guard)),\n fetchChannelMessages: note(fetchChannelMessages(chat, guard)),\n fetchThread: fetchThread(chat, guard),\n listThreads: note(listThreads(chat, guard)),\n getThreadParticipants: getThreadParticipants(chat, guard),\n getChannelInfo: getChannelInfo(chat, guard),\n postMessage: note(postMessage(chat, { needsApproval: false, guard: postGuard })),\n // Given a thread id, Slack would silently post a new top-level message\n // instead of replying in that thread.\n postChannelMessage: note(\n postChannelMessage(chat, {\n needsApproval: false,\n guard: id => {\n if (id.split(':').length > 2) {\n throw new Error(`\"${id}\" is a thread, not a channel. Use postMessage to reply in a thread.`);\n }\n postGuard(id);\n },\n }),\n ),\n findChannel: createTool({\n id: 'findChannel',\n description:\n 'Find Slack channels by name, e.g. \"eng\" or \"#eng-proj-factories\". Returns full channel ids (slack:C…) to pass to the other Slack tools, and whether the app is a member. `incomplete: true` means the workspace was too large to check every channel.',\n inputSchema: z.object({ name: z.string().min(1).describe('All or part of the channel name') }),\n execute: async ({ name }) => {\n const query = normalize(name);\n const { items: found, incomplete } = await listAll(async cursor => {\n const page = await slackClient(chat).conversations.list({\n types: 'public_channel,private_channel',\n exclude_archived: true,\n limit: 1000,\n cursor,\n });\n return { items: page.channels, response_metadata: page.response_metadata };\n });\n const matches = found.filter(c => c.name?.toLowerCase().includes(query));\n return {\n channels: matches.slice(0, 20).map(c => ({\n id: `slack:${c.id}`,\n name: c.name,\n isPrivate: Boolean(c.is_private),\n isMember: Boolean(c.is_member),\n })),\n ...(incomplete && { incomplete }),\n };\n },\n }),\n searchMessages: createTool({\n id: 'searchMessages',\n description:\n \"Search recent top-level messages in Slack channels for words. Matches messages containing every word, ignoring case. Reads each channel's newest messages (not thread replies), so older messages are missed. Defaults to this session's channel; use findChannel to get other channel ids.\",\n inputSchema: z.object({\n query: z.string().min(1).describe('Words to look for'),\n channelIds: z\n .array(z.string().min(1))\n .max(10)\n .optional()\n .describe('Channels to search, as slack:C… ids. Defaults to the channel this session started in.'),\n scan: z\n .number()\n .int()\n .min(1)\n .max(MAX_SEARCH_SCAN)\n .default(200)\n .describe('How many of the newest messages to read in each channel'),\n limit: z.number().int().min(1).max(50).default(20).describe('Most matches to return'),\n }),\n execute: async ({ query, channelIds, scan, limit }) => {\n const words = query.toLowerCase().split(/\\s+/).filter(Boolean);\n const channels = channelIds?.length ? channelIds : [channelOf(chat, sessionThreadId)];\n const matches: Array<{ channelId: string; ts: string; userId?: string; text: string }> = [];\n const errors: Array<{ channelId: string; error: string }> = [];\n let scanned = 0;\n for (const channelId of channels) {\n // Read the channel the guard checked, not whatever string was passed.\n const id = withPrefix(channelId);\n const channel = channelOf(chat, id).replace(/^slack:/, '');\n let cursor: string | undefined;\n let read = 0;\n try {\n guard(id);\n while (read < scan) {\n const page = await slackClient(chat).conversations.history({\n channel,\n limit: Math.min(200, scan - read),\n cursor,\n });\n for (const message of (page.messages ?? []).slice(0, scan - read)) {\n read++;\n scanned++;\n const text = message.text ?? '';\n if (words.every(word => text.toLowerCase().includes(word))) {\n matches.push({ channelId: `slack:${channel}`, ts: message.ts ?? '', userId: message.user, text });\n }\n }\n cursor = page.response_metadata?.next_cursor || undefined;\n if (!cursor || (page.messages?.length ?? 0) === 0) break;\n }\n } catch (error) {\n errors.push({\n channelId: `slack:${channel}`,\n error: (error as { data?: { error?: string } }).data?.error ?? String(error),\n });\n }\n }\n return {\n matches: matches.slice(0, limit),\n scanned,\n ...(errors.length ? { errors } : {}),\n };\n },\n }),\n findUser: createTool({\n id: 'findUser',\n description:\n 'Find people in Slack by name, e.g. \"Caleb\" or \"@caleb\". Returns their user ids (U…), to mention them as <@U…> in a message or to DM them. `incomplete: true` means the workspace was too large to check everyone.',\n inputSchema: z.object({ name: z.string().min(1).describe('All or part of their name or display name') }),\n execute: async ({ name }) => {\n const query = normalize(name);\n const { items: people, incomplete } = await listAll(async cursor => {\n const page = await slackClient(chat).users.list({ limit: 200, cursor });\n return { items: page.members, response_metadata: page.response_metadata };\n });\n const matches = people.filter(\n p =>\n !p.deleted &&\n !p.is_bot &&\n p.id !== 'USLACKBOT' &&\n [p.name, p.profile?.real_name, p.profile?.display_name].some(n => n?.toLowerCase().includes(query)),\n );\n return {\n users: matches.slice(0, 20).map(p => ({\n id: p.id,\n name: p.profile?.real_name || p.name,\n displayName: p.profile?.display_name || undefined,\n })),\n ...(incomplete && { incomplete }),\n };\n },\n }),\n // The Chat SDK's own sendDirectMessage asks for approval; this one doesn't.\n ...(settings.directMessages === 'anyone'\n ? {\n sendDirectMessage: createTool({\n id: 'sendDirectMessage',\n description: 'Send a direct message to a person in Slack. Use findUser to get their user id (U…) from a name.',\n inputSchema: z.object({\n userId: z.string().min(1).describe('Slack user id, e.g. U123456'),\n text: z.string().min(1).describe('The message, in markdown'),\n }),\n execute: async ({ userId, text }) => {\n const dm = await chat.openDM(userId);\n const sent = await dm.post({ markdown: text });\n return { messageId: sent.id, threadId: sent.threadId };\n },\n }),\n }\n : {}),\n };\n}\n"],"mappings":";;;;;AAmBA,MAAM,mBAAmB;;AAEzB,MAAM,kBAAkB;;AAGxB,SAAS,WAAW,IAAoB;CACtC,OAAO,GAAG,WAAW,QAAQ,IAAI,KAAK,SAAS;AACjD;;AAGA,SAAS,UAAU,MAAY,IAAoB;CACjD,MAAM,SAAS,GAAG,MAAM,GAAG,CAAC,CAAC;CAE7B,QADgB,SAAS,KAAK,WAAW,MAAM,IAAI,KAAA,EAAA,EACnC,wBAAwB,EAAE,KAAK,GAAG,MAAM,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG;AACnF;AAEA,MAAM,eAAe,SAAgB,KAAK,WAAW,OAAO,CAAC,CAAkB;;;;;;AAO/E,eAAe,QACb,WAC4C;CAC5C,MAAM,QAAa,CAAC;CACpB,IAAI;CACJ,KAAK,IAAI,OAAO,GAAG,OAAO,kBAAkB,QAAQ;EAClD,MAAM,S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AAS,KAAK,CAAC,CAGvF,CAAC,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,KAAI,OAAM;MACpC,IAAI,EAAE;MACN,MAAM,EAAE,SAAS,aAAa,EAAE;MAChC,aAAa,EAAE,SAAS,gBAAgB,KAAA;KAC1C,EAAE;KACF,GAAI,cAAc,EAAE,WAAW;IACjC;GACF;EACF,CAAC;EAED,GAAI,SAAS,mBAAmB,WAC5B,EACE,mBAAmB,WAAW;GAC5B,IAAI;GACJ,aAAa;GACb,aAAa,EAAE,OAAO;IACpB,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,6BAA6B;IAChE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,0BAA0B;GAC7D,CAAC;GACD,SAAS,OAAO,EAAE,QAAQ,WAAW;IAEnC,MAAM,OAAO,OAAM,MADF,KAAK,OAAO,MAAM,EAAA,CACb,KAAK,EAAE,UAAU,KAAK,CAAC;IAC7C,OAAO;KAAE,WAAW,KAAK;KAAI,UAAU,KAAK;IAAS;GACvD;EACF,CAAC,EACH,IACA,CAAC;CACP;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"connect-route.d.ts","sourceRoot":"","sources":["../../../src/integrations/slack/connect-route.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gDAAgD,CAAC;AAC7F,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAkBrF;;;;;GAKG;AACH,UAAU,eAAe;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,eAAe,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AG,QAAQ,EAAE,CA6Ob"}
@@ -1,3 +1,4 @@
1
+ import { loose } from "../../routes/route.js";
1
2
  import { registerApiRoute } from "@mastra/core/server";
2
3
  // src/integrations/slack/connect-route.ts
3
4
  const SLACK_AUTHORIZE_URL = "https://slack.com/openid/connect/authorize";
@@ -43,7 +44,6 @@ function createSlackConnectRoutes(deps) {
43
44
  consumedNonces.set(nonce, now + STATE_REPLAY_WINDOW_MS);
44
45
  return true;
45
46
  };
46
- const loose = (c) => c;
47
47
  return [
48
48
  registerApiRoute("/connect/slack", {
49
49
  method: "GET",
@@ -1 +1 @@
1
- {"version":3,"file":"connect-route.js","names":[],"sources":["../../../src/integrations/slack/connect-route.ts"],"sourcesContent":["import { registerApiRoute } from '@mastra/core/server';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { StateSigner } from '../../state-signing.js';\nimport type { ChannelIdentityStorage } from '../../storage/domains/channel-identity/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\n\n/**\n * Payload shape for the Connections list: the platform sender key +\n * link time, without the tenant ids (the caller IS the tenant).\n */\ninterface ConnectedChannelAccountPayload {\n platform: string;\n externalTeamId: string;\n externalUserId: string;\n /** Display names captured at link time (OIDC profile claims); ids fall back. */\n externalTeamName?: string;\n externalUserName?: string;\n /** Which Factory project this link's channel runs route to (unset = not picked yet). */\n defaultFactoryProjectId?: string;\n linkedAt: string;\n}\n\n/**\n * Config for the web-initiated \"Sign in with Slack\" (OIDC) connect flow. All\n * values come from the env-supplied Slack app. Absent → the OIDC routes\n * respond with an error redirect and the list endpoint reports\n * `canConnect: false` so the UI hides its Connect button.\n */\ninterface SlackOidcConfig {\n clientId: string;\n clientSecret: string;\n /**\n * Public HTTPS origin the OIDC `redirect_uri` is built from (Slack rejects\n * plain-http redirect URLs, so locally this is the tunnel origin). Must also\n * be registered as a redirect URL on the Slack app.\n */\n redirectBaseUrl: string;\n /** Browser-facing origin post-connect redirects land on (the SPA host). */\n uiOrigin?: string;\n}\n\nconst SLACK_AUTHORIZE_URL = 'https://slack.com/openid/connect/authorize';\nconst SLACK_TOKEN_URL = 'https://slack.com/api/openid.connect.token';\nconst OIDC_CALLBACK_PATH = '/connect/slack/oidc/callback';\nconst SLACK_TOKEN_TIMEOUT_MS = 10_000;\n/** Matches the signer's own `state` lifetime — past it, `verify` rejects anyway. */\nconst STATE_REPLAY_WINDOW_MS = 10 * 60 * 1000;\n\n/**\n * Decode a JWT's payload WITHOUT signature verification. Safe here because the\n * `id_token` arrives directly from Slack's token endpoint over TLS in a\n * confidential-client code exchange — the transport authenticates the issuer,\n * which is the standard OIDC allowance for this flow. `iss`/`aud`/`exp` are\n * still checked by the caller.\n */\nfunction decodeJwtPayload(jwt: string): Record<string, unknown> | null {\n const payload = jwt.split('.')[1];\n if (!payload) return null;\n try {\n return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/**\n * Slack account-linking routes.\n *\n * A link is only ever written by the OIDC flow below, where Slack itself\n * asserts the `(team, user)` pair in the id_token — so the web user has to\n * actually control the Slack account they bind. `/connect/slack` is just the\n * Slack-side entry point: it carries no identity and writes nothing, it only\n * sends the visitor to Connections, where the flow starts.\n */\nexport function createSlackConnectRoutes(deps: {\n auth: RouteAuth;\n accountLinks: ChannelIdentityStorage;\n /** Signs the OIDC `state`, binding the round-trip to the initiating tenant. */\n tenantStateSigner?: StateSigner;\n oidc?: SlackOidcConfig;\n /**\n * Factory projects domain, for validating (and listing to) the per-link\n * default factory. Unset → the default-factory PATCH route rejects.\n */\n projects?: FactoryProjectsStorage;\n}): ApiRoute[] {\n const { auth, accountLinks, tenantStateSigner, oidc, projects } = deps;\n const oidcEnabled = Boolean(oidc && tenantStateSigner);\n const uiOrigin = oidc?.uiOrigin?.replace(/\\/$/, '') ?? '';\n\n // A signed `state` stays valid for its whole 10-minute window, so on its own\n // it authorizes the binding repeatedly: anyone who captures a callback URL\n // can re-run the exchange with their own fresh Slack `code` and bind their\n // Slack account to the tenant that started the flow. Burning the nonce makes\n // the state single-use. Scope note: this is per-process, so it does not stop\n // a replay routed to a different replica — narrowing that further needs\n // shared storage, which is out of proportion to a 10-minute window here.\n const consumedNonces = new Map<string, number>();\n const consumeNonce = (nonce: string): boolean => {\n const now = Date.now();\n for (const [seen, expiresAt] of consumedNonces) {\n if (expiresAt <= now) consumedNonces.delete(seen);\n }\n if (consumedNonces.has(nonce)) return false;\n consumedNonces.set(nonce, now + STATE_REPLAY_WINDOW_MS);\n return true;\n };\n\n // mc-web can resolve a different hono version than @mastra/factory, so the\n // registerApiRoute handler `Context` and the factory `RouteAuth` `Context`\n // are structurally incompatible (private `[GET_MATCH_RESULT]` symbol). Cast\n // through `unknown` at the seam — same `loose()` workaround the factory\n // routes use internally.\n type RouteAuthContext = Parameters<RouteAuth['ensureUser']>[0];\n const loose = (c: unknown): RouteAuthContext => c as RouteAuthContext;\n\n return [\n registerApiRoute('/connect/slack', {\n method: 'GET',\n // No auth: nothing here reads a tenant or writes a link. The SPA route\n // this lands on requires a session and bounces through login itself.\n requiresAuth: false,\n handler: async c => c.redirect(`${uiOrigin}/settings/connections`),\n }),\n // Web-initiated connect: \"Sign in with Slack\" (OIDC). The only route that\n // writes a link, because it is the only one that proves the signed-in web\n // user actually CONTROLS the Slack account: Slack itself asserts the\n // (team, user) pair in the id_token.\n registerApiRoute('/connect/slack/oidc/start', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!oidcEnabled) return c.redirect(`${uiOrigin}/?slack=error`);\n\n const factoryProjectId = c.req.query('factoryId')?.trim() || undefined;\n const startPath = factoryProjectId\n ? `/connect/slack/oidc/start?factoryId=${encodeURIComponent(factoryProjectId)}`\n : '/connect/slack/oidc/start';\n\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) {\n return c.redirect(`/auth/login?returnTo=${encodeURIComponent(startPath)}`);\n }\n\n const params = new URLSearchParams({\n response_type: 'code',\n // `profile` adds display-name claims (user name, team name) to the\n // id_token so Connections can show names instead of ids.\n scope: 'openid profile',\n client_id: oidc!.clientId,\n // Personal accounts have no org; the signer requires a string, so an\n // empty org round-trips and is mapped back to undefined on save.\n state: tenantStateSigner!.sign(tenant.orgId ?? '', tenant.userId, { factoryProjectId }),\n redirect_uri: `${oidc!.redirectBaseUrl.replace(/\\/$/, '')}${OIDC_CALLBACK_PATH}`,\n });\n return c.redirect(`${SLACK_AUTHORIZE_URL}?${params.toString()}`);\n },\n }),\n // OIDC callback. Authenticates via the signed `state` (which carries the\n // initiating tenant) rather than the session cookie — the callback may\n // arrive on a different origin (the public tunnel) where the SPA's\n // host-scoped cookie is not sent.\n registerApiRoute(OIDC_CALLBACK_PATH, {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!oidcEnabled) return c.redirect(`${uiOrigin}/?slack=error`);\n\n const tenant = tenantStateSigner!.verify(c.req.query('state'));\n const code = c.req.query('code');\n if (!tenant || !code) return c.redirect(`${uiOrigin}/?slack=error`);\n // Burn the state before spending the code, not after saving: a replay\n // must be refused even if the first attempt fails partway through.\n if (!consumeNonce(tenant.nonce)) return c.redirect(`${uiOrigin}/?slack=error`);\n\n // Bound the exchange: without a deadline a slow token endpoint parks the\n // request until the platform's own timeout, and this route is reachable\n // by anyone holding a signed state.\n const tokenRes = await fetch(SLACK_TOKEN_URL, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n client_id: oidc!.clientId,\n client_secret: oidc!.clientSecret,\n code,\n redirect_uri: `${oidc!.redirectBaseUrl.replace(/\\/$/, '')}${OIDC_CALLBACK_PATH}`,\n }),\n signal: AbortSignal.timeout(SLACK_TOKEN_TIMEOUT_MS),\n }).catch(() => null);\n const token = (await tokenRes?.json().catch(() => null)) as { ok?: boolean; id_token?: string } | null;\n if (!tokenRes?.ok || !token?.ok || typeof token.id_token !== 'string') {\n return c.redirect(`${uiOrigin}/?slack=error`);\n }\n\n const claims = decodeJwtPayload(token.id_token);\n const teamId = claims?.['https://slack.com/team_id'];\n const slackUserId = claims?.['https://slack.com/user_id'];\n // Display-only claims from the `profile` scope — absent claims just\n // mean the settings list falls back to ids.\n const teamName = claims?.['https://slack.com/team_name'];\n const userName = claims?.name;\n // `exp` is seconds since the epoch. A missing or past `exp` means the\n // assertion is not currently valid, so it cannot bind an account.\n const expiresAt = typeof claims?.exp === 'number' ? claims.exp * 1000 : null;\n if (\n !claims ||\n claims.iss !== 'https://slack.com' ||\n claims.aud !== oidc!.clientId ||\n expiresAt === null ||\n expiresAt <= Date.now() ||\n typeof teamId !== 'string' ||\n typeof slackUserId !== 'string'\n ) {\n return c.redirect(`${uiOrigin}/?slack=error`);\n }\n\n await accountLinks.saveAccountLink({\n platform: 'slack',\n externalTeamId: teamId,\n externalUserId: slackUserId,\n orgId: tenant.orgId || undefined,\n userId: tenant.userId,\n externalTeamName: typeof teamName === 'string' ? teamName : undefined,\n externalUserName: typeof userName === 'string' ? userName : undefined,\n });\n\n const successPath = tenant.factoryProjectId\n ? `/factories/${encodeURIComponent(tenant.factoryProjectId)}/settings/connections/slack`\n : '/settings/connections';\n return c.redirect(`${uiOrigin}${successPath}?slack=connected`);\n },\n }),\n // The caller's own linked channel accounts for Connections. Tenant-scoped:\n // you only ever see your own links.\n registerApiRoute('/web/channel-accounts', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized' }, 401);\n\n const links = await accountLinks.listAccountLinksForUser(tenant.userId);\n const accounts: ConnectedChannelAccountPayload[] = links.map(link => ({\n platform: link.platform,\n externalTeamId: link.externalTeamId,\n externalUserId: link.externalUserId,\n externalTeamName: link.externalTeamName,\n externalUserName: link.externalUserName,\n defaultFactoryProjectId: link.defaultFactoryProjectId,\n linkedAt: link.linkedAt.toISOString(),\n }));\n // `canConnect` tells the settings UI whether the web-initiated OIDC\n // connect flow is configured (vs. Slack-side Connect card only).\n return c.json({ accounts, canConnect: oidcEnabled });\n },\n }),\n // Self-service disconnect. The storage delete is guarded by the caller's\n // tenant userId, so a known sender key alone can never sever someone\n // else's link.\n registerApiRoute('/web/channel-accounts', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized' }, 401);\n\n const body = (await c.req.json().catch(() => null)) as {\n platform?: string;\n externalTeamId?: string;\n externalUserId?: string;\n } | null;\n if (!body?.platform || !body.externalTeamId || !body.externalUserId) {\n return c.json({ error: 'platform, externalTeamId and externalUserId are required' }, 400);\n }\n\n const deleted = await accountLinks.deleteAccountLinkForUser({\n userId: tenant.userId,\n platform: body.platform,\n externalTeamId: body.externalTeamId,\n externalUserId: body.externalUserId,\n });\n return c.json({ deleted });\n },\n }),\n // Set (or clear, with `factoryProjectId: null`) which Factory project a\n // link's channel runs route to. The storage write is guarded by the\n // caller's tenant userId — a known sender key alone can never repoint\n // someone else's link — and a non-null factory must exist in the caller's\n // org.\n registerApiRoute('/web/channel-accounts/default-factory', {\n method: 'PATCH',\n requiresAuth: false,\n handler: async c => {\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized' }, 401);\n\n const body = (await c.req.json().catch(() => null)) as {\n platform?: string;\n externalTeamId?: string;\n externalUserId?: string;\n factoryProjectId?: string | null;\n } | null;\n if (!body?.platform || !body.externalTeamId || !body.externalUserId || body.factoryProjectId === undefined) {\n return c.json(\n { error: 'platform, externalTeamId, externalUserId and factoryProjectId (nullable) are required' },\n 400,\n );\n }\n\n if (body.factoryProjectId !== null) {\n if (!projects) return c.json({ error: 'factory routing is not configured' }, 400);\n const factory = await projects.get({ orgId: tenant.orgId ?? '', id: body.factoryProjectId });\n if (!factory) return c.json({ error: 'unknown factory' }, 400);\n }\n\n const updated = await accountLinks.setDefaultFactory({\n userId: tenant.userId,\n platform: body.platform,\n externalTeamId: body.externalTeamId,\n externalUserId: body.externalUserId,\n factoryProjectId: body.factoryProjectId,\n });\n return c.json({ updated });\n },\n }),\n ];\n}\n"],"mappings":";;AA0CA,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,yBAAyB;;AAE/B,MAAM,yBAAyB;;;;;;;;AAS/B,SAAS,iBAAiB,KAA6C;CACrE,MAAM,UAAU,IAAI,MAAM,GAAG,CAAC,CAAC;CAC/B,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI;EACF,OAAO,KAAK,MAAM,OAAO,KAAK,SAAS,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACtE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;AAWA,SAAgB,yBAAyB,MAW1B;CACb,MAAM,EAAE,MAAM,cAAc,mBAAmB,MAAM,aAAa;CAClE,MAAM,cAAc,QAAQ,QAAQ,iBAAiB;CACrD,MAAM,WAAW,MAAM,UAAU,QAAQ,OAAO,EAAE,KAAK;CASvD,MAAM,iCAAiB,IAAI,IAAoB;CAC/C,MAAM,gBAAgB,UAA2B;EAC/C,MAAM,MAAM,KAAK,IAAI;EACrB,KAAK,MAAM,CAAC,MAAM,cAAc,gBAC9B,IAAI,aAAa,KAAK,eAAe,OAAO,IAAI;EAElD,IAAI,eAAe,IAAI,KAAK,GAAG,OAAO;EACtC,eAAe,IAAI,OAAO,MAAM,sBAAsB;EACtD,OAAO;CACT;CAQA,MAAM,SAAS,MAAiC;CAEhD,OAAO;EACL,iBAAiB,kBAAkB;GACjC,QAAQ;GAGR,cAAc;GACd,SAAS,OAAM,MAAK,EAAE,SAAS,GAAG,SAAS,sBAAsB;EACnE,CAAC;EAKD,iBAAiB,6BAA6B;GAC5C,QAAQ;GACR,cAAc;GACd,SAAS,OAAM,MAAK;IAClB,IAAI,CAAC,aAAa,OAAO,EAAE,SAAS,GAAG,SAAS,cAAc;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,KAAK,kBAAkB,CAAC,KAAK,kBAAkB,KAAK,qBAAqB,KAAA,GAC/F,OAAO,EAAE,KACP,EAAE,OAAO,wFAAwF,GACjG,GACF;IAGF,IAAI,KAAK,qBAAqB,MAAM;KAClC,IAAI,CAAC,UAAU,OAAO,EAAE,KAAK,EAAE,OAAO,oCAAoC,GAAG,GAAG;KAEhF,IAAI,CAAC,MADiB,SAAS,IAAI;MAAE,OAAO,OAAO,SAAS;MAAI,IAAI,KAAK;KAAiB,CAAC,GAC7E,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAC/D;IAEA,MAAM,UAAU,MAAM,aAAa,kBAAkB;KACnD,QAAQ,OAAO;KACf,UAAU,KAAK;KACf,gBAAgB,KAAK;KACrB,gBAAgB,KAAK;KACrB,kBAAkB,KAAK;IACzB,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC;GAC3B;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"connect-route.js","names":[],"sources":["../../../src/integrations/slack/connect-route.ts"],"sourcesContent":["import { registerApiRoute } from '@mastra/core/server';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { loose } from '../../routes/route.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { StateSigner } from '../../state-signing.js';\nimport type { ChannelIdentityStorage } from '../../storage/domains/channel-identity/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\n\n/**\n * Payload shape for the Connections list: the platform sender key +\n * link time, without the tenant ids (the caller IS the tenant).\n */\ninterface ConnectedChannelAccountPayload {\n platform: string;\n externalTeamId: string;\n externalUserId: string;\n /** Display names captured at link time (OIDC profile claims); ids fall back. */\n externalTeamName?: string;\n externalUserName?: string;\n /** Which Factory project this link's channel runs route to (unset = not picked yet). */\n defaultFactoryProjectId?: string;\n linkedAt: string;\n}\n\n/**\n * Config for the web-initiated \"Sign in with Slack\" (OIDC) connect flow. All\n * values come from the env-supplied Slack app. Absent → the OIDC routes\n * respond with an error redirect and the list endpoint reports\n * `canConnect: false` so the UI hides its Connect button.\n */\ninterface SlackOidcConfig {\n clientId: string;\n clientSecret: string;\n /**\n * Public HTTPS origin the OIDC `redirect_uri` is built from (Slack rejects\n * plain-http redirect URLs, so locally this is the tunnel origin). Must also\n * be registered as a redirect URL on the Slack app.\n */\n redirectBaseUrl: string;\n /** Browser-facing origin post-connect redirects land on (the SPA host). */\n uiOrigin?: string;\n}\n\nconst SLACK_AUTHORIZE_URL = 'https://slack.com/openid/connect/authorize';\nconst SLACK_TOKEN_URL = 'https://slack.com/api/openid.connect.token';\nconst OIDC_CALLBACK_PATH = '/connect/slack/oidc/callback';\nconst SLACK_TOKEN_TIMEOUT_MS = 10_000;\n/** Matches the signer's own `state` lifetime — past it, `verify` rejects anyway. */\nconst STATE_REPLAY_WINDOW_MS = 10 * 60 * 1000;\n\n/**\n * Decode a JWT's payload WITHOUT signature verification. Safe here because the\n * `id_token` arrives directly from Slack's token endpoint over TLS in a\n * confidential-client code exchange — the transport authenticates the issuer,\n * which is the standard OIDC allowance for this flow. `iss`/`aud`/`exp` are\n * still checked by the caller.\n */\nfunction decodeJwtPayload(jwt: string): Record<string, unknown> | null {\n const payload = jwt.split('.')[1];\n if (!payload) return null;\n try {\n return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as Record<string, unknown>;\n } catch {\n return null;\n }\n}\n\n/**\n * Slack account-linking routes.\n *\n * A link is only ever written by the OIDC flow below, where Slack itself\n * asserts the `(team, user)` pair in the id_token — so the web user has to\n * actually control the Slack account they bind. `/connect/slack` is just the\n * Slack-side entry point: it carries no identity and writes nothing, it only\n * sends the visitor to Connections, where the flow starts.\n */\nexport function createSlackConnectRoutes(deps: {\n auth: RouteAuth;\n accountLinks: ChannelIdentityStorage;\n /** Signs the OIDC `state`, binding the round-trip to the initiating tenant. */\n tenantStateSigner?: StateSigner;\n oidc?: SlackOidcConfig;\n /**\n * Factory projects domain, for validating (and listing to) the per-link\n * default factory. Unset → the default-factory PATCH route rejects.\n */\n projects?: FactoryProjectsStorage;\n}): ApiRoute[] {\n const { auth, accountLinks, tenantStateSigner, oidc, projects } = deps;\n const oidcEnabled = Boolean(oidc && tenantStateSigner);\n const uiOrigin = oidc?.uiOrigin?.replace(/\\/$/, '') ?? '';\n\n // A signed `state` stays valid for its whole 10-minute window, so on its own\n // it authorizes the binding repeatedly: anyone who captures a callback URL\n // can re-run the exchange with their own fresh Slack `code` and bind their\n // Slack account to the tenant that started the flow. Burning the nonce makes\n // the state single-use. Scope note: this is per-process, so it does not stop\n // a replay routed to a different replica — narrowing that further needs\n // shared storage, which is out of proportion to a 10-minute window here.\n const consumedNonces = new Map<string, number>();\n const consumeNonce = (nonce: string): boolean => {\n const now = Date.now();\n for (const [seen, expiresAt] of consumedNonces) {\n if (expiresAt <= now) consumedNonces.delete(seen);\n }\n if (consumedNonces.has(nonce)) return false;\n consumedNonces.set(nonce, now + STATE_REPLAY_WINDOW_MS);\n return true;\n };\n\n return [\n registerApiRoute('/connect/slack', {\n method: 'GET',\n // No auth: nothing here reads a tenant or writes a link. The SPA route\n // this lands on requires a session and bounces through login itself.\n requiresAuth: false,\n handler: async c => c.redirect(`${uiOrigin}/settings/connections`),\n }),\n // Web-initiated connect: \"Sign in with Slack\" (OIDC). The only route that\n // writes a link, because it is the only one that proves the signed-in web\n // user actually CONTROLS the Slack account: Slack itself asserts the\n // (team, user) pair in the id_token.\n registerApiRoute('/connect/slack/oidc/start', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!oidcEnabled) return c.redirect(`${uiOrigin}/?slack=error`);\n\n const factoryProjectId = c.req.query('factoryId')?.trim() || undefined;\n const startPath = factoryProjectId\n ? `/connect/slack/oidc/start?factoryId=${encodeURIComponent(factoryProjectId)}`\n : '/connect/slack/oidc/start';\n\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) {\n return c.redirect(`/auth/login?returnTo=${encodeURIComponent(startPath)}`);\n }\n\n const params = new URLSearchParams({\n response_type: 'code',\n // `profile` adds display-name claims (user name, team name) to the\n // id_token so Connections can show names instead of ids.\n scope: 'openid profile',\n client_id: oidc!.clientId,\n // Personal accounts have no org; the signer requires a string, so an\n // empty org round-trips and is mapped back to undefined on save.\n state: tenantStateSigner!.sign(tenant.orgId ?? '', tenant.userId, { factoryProjectId }),\n redirect_uri: `${oidc!.redirectBaseUrl.replace(/\\/$/, '')}${OIDC_CALLBACK_PATH}`,\n });\n return c.redirect(`${SLACK_AUTHORIZE_URL}?${params.toString()}`);\n },\n }),\n // OIDC callback. Authenticates via the signed `state` (which carries the\n // initiating tenant) rather than the session cookie — the callback may\n // arrive on a different origin (the public tunnel) where the SPA's\n // host-scoped cookie is not sent.\n registerApiRoute(OIDC_CALLBACK_PATH, {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!oidcEnabled) return c.redirect(`${uiOrigin}/?slack=error`);\n\n const tenant = tenantStateSigner!.verify(c.req.query('state'));\n const code = c.req.query('code');\n if (!tenant || !code) return c.redirect(`${uiOrigin}/?slack=error`);\n // Burn the state before spending the code, not after saving: a replay\n // must be refused even if the first attempt fails partway through.\n if (!consumeNonce(tenant.nonce)) return c.redirect(`${uiOrigin}/?slack=error`);\n\n // Bound the exchange: without a deadline a slow token endpoint parks the\n // request until the platform's own timeout, and this route is reachable\n // by anyone holding a signed state.\n const tokenRes = await fetch(SLACK_TOKEN_URL, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n client_id: oidc!.clientId,\n client_secret: oidc!.clientSecret,\n code,\n redirect_uri: `${oidc!.redirectBaseUrl.replace(/\\/$/, '')}${OIDC_CALLBACK_PATH}`,\n }),\n signal: AbortSignal.timeout(SLACK_TOKEN_TIMEOUT_MS),\n }).catch(() => null);\n const token = (await tokenRes?.json().catch(() => null)) as { ok?: boolean; id_token?: string } | null;\n if (!tokenRes?.ok || !token?.ok || typeof token.id_token !== 'string') {\n return c.redirect(`${uiOrigin}/?slack=error`);\n }\n\n const claims = decodeJwtPayload(token.id_token);\n const teamId = claims?.['https://slack.com/team_id'];\n const slackUserId = claims?.['https://slack.com/user_id'];\n // Display-only claims from the `profile` scope — absent claims just\n // mean the settings list falls back to ids.\n const teamName = claims?.['https://slack.com/team_name'];\n const userName = claims?.name;\n // `exp` is seconds since the epoch. A missing or past `exp` means the\n // assertion is not currently valid, so it cannot bind an account.\n const expiresAt = typeof claims?.exp === 'number' ? claims.exp * 1000 : null;\n if (\n !claims ||\n claims.iss !== 'https://slack.com' ||\n claims.aud !== oidc!.clientId ||\n expiresAt === null ||\n expiresAt <= Date.now() ||\n typeof teamId !== 'string' ||\n typeof slackUserId !== 'string'\n ) {\n return c.redirect(`${uiOrigin}/?slack=error`);\n }\n\n await accountLinks.saveAccountLink({\n platform: 'slack',\n externalTeamId: teamId,\n externalUserId: slackUserId,\n orgId: tenant.orgId || undefined,\n userId: tenant.userId,\n externalTeamName: typeof teamName === 'string' ? teamName : undefined,\n externalUserName: typeof userName === 'string' ? userName : undefined,\n });\n\n const successPath = tenant.factoryProjectId\n ? `/factories/${encodeURIComponent(tenant.factoryProjectId)}/settings/connections/slack`\n : '/settings/connections';\n return c.redirect(`${uiOrigin}${successPath}?slack=connected`);\n },\n }),\n // The caller's own linked channel accounts for Connections. Tenant-scoped:\n // you only ever see your own links.\n registerApiRoute('/web/channel-accounts', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized' }, 401);\n\n const links = await accountLinks.listAccountLinksForUser(tenant.userId);\n const accounts: ConnectedChannelAccountPayload[] = links.map(link => ({\n platform: link.platform,\n externalTeamId: link.externalTeamId,\n externalUserId: link.externalUserId,\n externalTeamName: link.externalTeamName,\n externalUserName: link.externalUserName,\n defaultFactoryProjectId: link.defaultFactoryProjectId,\n linkedAt: link.linkedAt.toISOString(),\n }));\n // `canConnect` tells the settings UI whether the web-initiated OIDC\n // connect flow is configured (vs. Slack-side Connect card only).\n return c.json({ accounts, canConnect: oidcEnabled });\n },\n }),\n // Self-service disconnect. The storage delete is guarded by the caller's\n // tenant userId, so a known sender key alone can never sever someone\n // else's link.\n registerApiRoute('/web/channel-accounts', {\n method: 'DELETE',\n requiresAuth: false,\n handler: async c => {\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized' }, 401);\n\n const body = (await c.req.json().catch(() => null)) as {\n platform?: string;\n externalTeamId?: string;\n externalUserId?: string;\n } | null;\n if (!body?.platform || !body.externalTeamId || !body.externalUserId) {\n return c.json({ error: 'platform, externalTeamId and externalUserId are required' }, 400);\n }\n\n const deleted = await accountLinks.deleteAccountLinkForUser({\n userId: tenant.userId,\n platform: body.platform,\n externalTeamId: body.externalTeamId,\n externalUserId: body.externalUserId,\n });\n return c.json({ deleted });\n },\n }),\n // Set (or clear, with `factoryProjectId: null`) which Factory project a\n // link's channel runs route to. The storage write is guarded by the\n // caller's tenant userId — a known sender key alone can never repoint\n // someone else's link — and a non-null factory must exist in the caller's\n // org.\n registerApiRoute('/web/channel-accounts/default-factory', {\n method: 'PATCH',\n requiresAuth: false,\n handler: async c => {\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized' }, 401);\n\n const body = (await c.req.json().catch(() => null)) as {\n platform?: string;\n externalTeamId?: string;\n externalUserId?: string;\n factoryProjectId?: string | null;\n } | null;\n if (!body?.platform || !body.externalTeamId || !body.externalUserId || body.factoryProjectId === undefined) {\n return c.json(\n { error: 'platform, externalTeamId, externalUserId and factoryProjectId (nullable) are required' },\n 400,\n );\n }\n\n if (body.factoryProjectId !== null) {\n if (!projects) return c.json({ error: 'factory routing is not configured' }, 400);\n const factory = await projects.get({ orgId: tenant.orgId ?? '', id: body.factoryProjectId });\n if (!factory) return c.json({ error: 'unknown factory' }, 400);\n }\n\n const updated = await accountLinks.setDefaultFactory({\n userId: tenant.userId,\n platform: body.platform,\n externalTeamId: body.externalTeamId,\n externalUserId: body.externalUserId,\n factoryProjectId: body.factoryProjectId,\n });\n return c.json({ updated });\n },\n }),\n ];\n}\n"],"mappings":";;;AA2CA,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,yBAAyB;;AAE/B,MAAM,yBAAyB;;;;;;;;AAS/B,SAAS,iBAAiB,KAA6C;CACrE,MAAM,UAAU,IAAI,MAAM,GAAG,CAAC,CAAC;CAC/B,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI;EACF,OAAO,KAAK,MAAM,OAAO,KAAK,SAAS,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACtE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;AAWA,SAAgB,yBAAyB,MAW1B;CACb,MAAM,EAAE,MAAM,cAAc,mBAAmB,MAAM,aAAa;CAClE,MAAM,cAAc,QAAQ,QAAQ,iBAAiB;CACrD,MAAM,WAAW,MAAM,UAAU,QAAQ,OAAO,EAAE,KAAK;CASvD,MAAM,iCAAiB,IAAI,IAAoB;CAC/C,MAAM,gBAAgB,UAA2B;EAC/C,MAAM,MAAM,KAAK,IAAI;EACrB,KAAK,MAAM,CAAC,MAAM,cAAc,gBAC9B,IAAI,aAAa,KAAK,eAAe,OAAO,IAAI;EAElD,IAAI,eAAe,IAAI,KAAK,GAAG,OAAO;EACtC,eAAe,IAAI,OAAO,MAAM,sBAAsB;EACtD,OAAO;CACT;CAEA,OAAO;EACL,iBAAiB,kBAAkB;GACjC,QAAQ;GAGR,cAAc;GACd,SAAS,OAAM,MAAK,EAAE,SAAS,GAAG,SAAS,sBAAsB;EACnE,CAAC;EAKD,iBAAiB,6BAA6B;GAC5C,QAAQ;GACR,cAAc;GACd,SAAS,OAAM,MAAK;IAClB,IAAI,CAAC,aAAa,OAAO,EAAE,SAAS,GAAG,SAAS,cAAc;IAE9D,MAAM,mBAA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AC,KAAK,kBAAkB,KAAK,qBAAqB,KAAA,GAC/F,OAAO,EAAE,KACP,EAAE,OAAO,wFAAwF,GACjG,GACF;IAGF,IAAI,KAAK,qBAAqB,MAAM;KAClC,IAAI,CAAC,UAAU,OAAO,EAAE,KAAK,EAAE,OAAO,oCAAoC,GAAG,GAAG;KAEhF,IAAI,CAAC,MADiB,SAAS,IAAI;MAAE,OAAO,OAAO,SAAS;MAAI,IAAI,KAAK;KAAiB,CAAC,GAC7E,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAC/D;IAEA,MAAM,UAAU,MAAM,aAAa,kBAAkB;KACnD,QAAQ,OAAO;KACf,UAAU,KAAK;KACf,gBAAgB,KAAK;KACrB,gBAAgB,KAAK;KACrB,kBAAkB,KAAK;IACzB,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC;GAC3B;EACF,CAAC;CACH;AACF"}
@@ -24,6 +24,7 @@ import type { ApiRoute } from '@mastra/core/server';
24
24
  import type { SlackAdapterChannelConfig } from '@mastra/slack';
25
25
  import type { WorkItemFeedPublisher } from '../../storage/domains/comments/feed-sync.js';
26
26
  import type { FactoryChannelsConfig, FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';
27
+ import type { SlackToolSettings } from './tool-settings.js';
27
28
  /** Slack app credentials, read from env ONCE by the deploy entry. */
28
29
  export interface SlackIntegrationConfig {
29
30
  /** Slack event transport. Defaults to webhook mode. */
@@ -63,6 +64,20 @@ export interface SlackIntegrationConfig {
63
64
  * ```
64
65
  */
65
66
  adapterOptions?: SlackAdapterChannelConfig;
67
+ /**
68
+ * What sessions started from Slack may do with the Slack tools. By default a
69
+ * session can read and post only in its own channel, and can't send DMs.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * new SlackIntegration({
74
+ * signingSecret,
75
+ * // Any channel the app is in, and DMs to anyone in the workspace.
76
+ * tools: { channels: 'all', directMessages: 'anyone' },
77
+ * });
78
+ * ```
79
+ */
80
+ tools?: Partial<SlackToolSettings>;
66
81
  }
67
82
  export declare class SlackIntegration implements FactoryIntegration {
68
83
  #private;
@@ -88,9 +103,10 @@ export declare class SlackIntegration implements FactoryIntegration {
88
103
  channels?: () => AgentChannels | null | undefined;
89
104
  }): void;
90
105
  /**
91
- * `attach_file`, and `reply_in_thread` when reply text is hidden, on runs
92
- * whose session is linked to a Slack thread. The tools find the thread to
93
- * post into when they are called.
106
+ * On runs whose session is linked to a Slack thread: `attach_file`,
107
+ * `reply_in_thread` when reply text is hidden, and the Slack read, post,
108
+ * search, lookup and DM tools. The tools find the thread to post into when
109
+ * they are called.
94
110
  */
95
111
  agentTools({ requestContext }: {
96
112
  requestContext: RequestContext;
@@ -1 +1 @@
1
- {"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../src/integrations/slack/integration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAkB,MAAM,uBAAuB,CAAC;AAC3E,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAE/D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,6CAA6C,CAAC;AAEzF,OAAO,KAAK,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAalH,qEAAqE;AACrE,MAAM,WAAW,sBAAsB;IACrC,uDAAuD;IACvD,IAAI,CAAC,EAAE,SAAS,GAAG,QAAQ,CAAC;IAC5B,2EAA2E;IAC3E,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,yEAAyE;IACzE,QAAQ,CAAC,EAAE,MAAM,CAAC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;;;;;;;;;OAYG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;CACpC;AAyED,qBAAa,gBAAiB,YAAW,kBAAkB;;IACzD,QAAQ,CAAC,EAAE,WAAW;IACtB;;;;OAIG;IACH,QAAQ,CAAC,yBAAyB,QAAQ;IAQ1C;;;;;OAKG;IACH,QAAQ,CAAC,UAAU,EAAE;QAAE,KAAK,EAAE,cAAc,EAAE,CAAC;QAAC,MAAM,EAAE,eAAe,EAAE,CAAA;KAAE,CAAC;IAQ5E,YAAY,MAAM,EAAE,sBAAsB,EA6BzC;IAMD,UAAU,CAAC,IAAI,EAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,aAAa,GAAG,IAAI,GAAG,SAAS,CAAA;KAAE,GAAG,IAAI,CAE5E;IAED;;;;;OAKG;IACG,UAAU,CAAC,EAAE,cAAc,EAAE,EAAE;QAAE,cAAc,EAAE,cAAc,CAAA;KAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAUlG;IAED;;;OAGG;IACG,gBAAgB,CAAC,EACrB,WAAW,EACX,cAAc,GACf,EAAE,UAAU,CAAC,WAAW,CAAC,kBAAkB,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAQpF;IAED,QAAQ,CAAC,GAAG,EAAE,kBAAkB,GAAG,qBAAqB,CA2BvD;IAED,aAAa,CAAC,GAAG,EAAE,kBAAkB,GAAG,qBAAqB,CAE5D;IAED,MAAM,CAAC,GAAG,EAAE,kBAAkB,GAAG,QAAQ,EAAE,CAY1C;IAED,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAQrC;CACF"}
@@ -1,13 +1,15 @@
1
- import { parseCreatedPullRequest } from "../github/session-subscriptions.js";
2
1
  import { announcePullRequest } from "../channel-thread-announcements.js";
2
+ import { parseCreatedPullRequest } from "../github/session-subscriptions.js";
3
3
  import { FactoryChannelReplyProcessor } from "./channel-reply-processor.js";
4
4
  import { FactoryChannelSessionLinkProcessor } from "./channel-session-link-processor.js";
5
+ import { createSlackChatTools } from "./chat-tools.js";
5
6
  import { createSlackConnectRoutes } from "./connect-route.js";
6
7
  import { SlackFeedPublisher } from "./feed-publisher.js";
7
- import { createShareFileTool, isSlackThread } from "./share-file-tool.js";
8
- import { FactoryReplyStreamProcessor, createReplyTool } from "./reply-tool.js";
9
8
  import { FactoryReplyReminderProcessor } from "./reply-reminder-processor.js";
9
+ import { FactoryReplyStreamProcessor, createReplyTool } from "./reply-tool.js";
10
+ import { createShareFileTool, isSlackThread, slackThreadOf } from "./share-file-tool.js";
10
11
  import { createSlackChannelsConfig } from "./slack.js";
12
+ import { DEFAULT_SLACK_TOOL_SETTINGS, slackToolSettingsSchema } from "./tool-settings.js";
11
13
  // src/integrations/slack/integration.ts
12
14
  /** Slack renders the status inline next to the app name; keep it to one short line. */
13
15
  const MAX_STATUS_LENGTH = 80;
@@ -74,6 +76,7 @@ var SlackIntegration = class {
74
76
  */
75
77
  requiresStableStateSigner = true;
76
78
  #config;
79
+ #toolSettings;
77
80
  #adapterOptions;
78
81
  /** Bound in `initialize()`; the controller mounts after integrations are built. */
79
82
  #channels;
@@ -97,6 +100,11 @@ var SlackIntegration = class {
97
100
  if (mode === "socket" && !config.appToken) throw new Error("SlackIntegration: 'appToken' is required in socket mode — Slack cannot open a Socket Mode connection without it.");
98
101
  if (mode === "socket" && !config.botToken) throw new Error("SlackIntegration: 'botToken' is required in socket mode — Factory cannot reply without it.");
99
102
  this.#config = config;
103
+ const granted = Object.fromEntries(Object.entries(config.tools ?? {}).filter(([, value]) => value !== void 0));
104
+ this.#toolSettings = slackToolSettingsSchema.parse({
105
+ ...DEFAULT_SLACK_TOOL_SETTINGS,
106
+ ...granted
107
+ });
100
108
  this.#adapterOptions = factoryAdapterOptions(adapterOverrides(config.adapterOptions));
101
109
  const textHidden = this.#textHidden;
102
110
  this.processors = {
@@ -111,15 +119,24 @@ var SlackIntegration = class {
111
119
  this.#channels = args.channels;
112
120
  }
113
121
  /**
114
- * `attach_file`, and `reply_in_thread` when reply text is hidden, on runs
115
- * whose session is linked to a Slack thread. The tools find the thread to
116
- * post into when they are called.
122
+ * On runs whose session is linked to a Slack thread: `attach_file`,
123
+ * `reply_in_thread` when reply text is hidden, and the Slack read, post,
124
+ * search, lookup and DM tools. The tools find the thread to post into when
125
+ * they are called.
117
126
  */
118
127
  async agentTools({ requestContext }) {
119
- if (!await isSlackThread(requestContext, this.#deps)) return {};
128
+ const slackThread = await slackThreadOf(requestContext, this.#deps);
129
+ if (!slackThread) return {};
130
+ const chat = this.#channels?.()?.sdk;
131
+ const sessionThreadId = slackThread.threadId;
120
132
  return {
121
133
  ...createShareFileTool(requestContext, this.#deps),
122
- ...this.#textHidden ? createReplyTool(requestContext, this.#deps) : {}
134
+ ...this.#textHidden ? createReplyTool(requestContext, this.#deps) : {},
135
+ ...chat && sessionThreadId ? createSlackChatTools({
136
+ chat,
137
+ sessionThreadId,
138
+ settings: this.#toolSettings
139
+ }) : {}
123
140
  };
124
141
  }
125
142
  /**
@@ -151,6 +168,8 @@ var SlackIntegration = class {
151
168
  projects: ctx.storage.projects,
152
169
  sourceControls,
153
170
  modelDefaults: ctx.storage.modelDefaults,
171
+ modelCredentials: ctx.storage.modelCredentials,
172
+ voiceSettings: ctx.storage.voiceSettings,
154
173
  workItems: ctx.runtime?.workItems,
155
174
  feed: ctx.feed,
156
175
  adapterOptions: this.#adapterOptions