@mastra/factory 0.28.0-alpha.0 → 0.28.0-alpha.2

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 (335) hide show
  1. package/README.md +210 -42
  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/intake-routing.d.ts +30 -6
  15. package/dist/boards/intake-routing.d.ts.map +1 -1
  16. package/dist/boards/intake-routing.js +43 -5
  17. package/dist/boards/intake-routing.js.map +1 -1
  18. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  19. package/dist/boards/legacy-plan-role.js +8 -4
  20. package/dist/boards/legacy-plan-role.js.map +1 -1
  21. package/dist/boards/phase-automation.d.ts.map +1 -1
  22. package/dist/boards/phase-automation.js +7 -2
  23. package/dist/boards/phase-automation.js.map +1 -1
  24. package/dist/boards/project-boards.d.ts +18 -7
  25. package/dist/boards/project-boards.d.ts.map +1 -1
  26. package/dist/boards/project-boards.js +78 -14
  27. package/dist/boards/project-boards.js.map +1 -1
  28. package/dist/boards/stored-board.d.ts +59 -1
  29. package/dist/boards/stored-board.d.ts.map +1 -1
  30. package/dist/boards/stored-board.js +219 -7
  31. package/dist/boards/stored-board.js.map +1 -1
  32. package/dist/factory.d.ts +63 -9
  33. package/dist/factory.d.ts.map +1 -1
  34. package/dist/factory.js +187 -22
  35. package/dist/factory.js.map +1 -1
  36. package/dist/index.d.ts +3 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +4 -3
  39. package/dist/integrations/base.d.ts +6 -0
  40. package/dist/integrations/base.d.ts.map +1 -1
  41. package/dist/integrations/github/acceptance-labels.d.ts +4 -0
  42. package/dist/integrations/github/acceptance-labels.d.ts.map +1 -1
  43. package/dist/integrations/github/acceptance-labels.js +1 -1
  44. package/dist/integrations/github/acceptance-labels.js.map +1 -1
  45. package/dist/integrations/github/default-rules.d.ts +2 -9
  46. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  47. package/dist/integrations/github/default-rules.js +7 -6
  48. package/dist/integrations/github/default-rules.js.map +1 -1
  49. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  50. package/dist/integrations/github/issue-reconciler.js +17 -1
  51. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  52. package/dist/integrations/github/review-status-comment.d.ts +61 -0
  53. package/dist/integrations/github/review-status-comment.d.ts.map +1 -0
  54. package/dist/integrations/github/review-status-comment.js +217 -0
  55. package/dist/integrations/github/review-status-comment.js.map +1 -0
  56. package/dist/integrations/github/review-status-reporter.d.ts +42 -0
  57. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -0
  58. package/dist/integrations/github/review-status-reporter.js +100 -0
  59. package/dist/integrations/github/review-status-reporter.js.map +1 -0
  60. package/dist/integrations/github/review-status.d.ts +28 -0
  61. package/dist/integrations/github/review-status.d.ts.map +1 -0
  62. package/dist/integrations/github/review-status.js +95 -0
  63. package/dist/integrations/github/review-status.js.map +1 -0
  64. package/dist/integrations/github/routes.d.ts.map +1 -1
  65. package/dist/integrations/github/routes.js +2 -5
  66. package/dist/integrations/github/routes.js.map +1 -1
  67. package/dist/integrations/github/rules.d.ts +13 -1
  68. package/dist/integrations/github/rules.d.ts.map +1 -1
  69. package/dist/integrations/github/rules.js +77 -6
  70. package/dist/integrations/github/rules.js.map +1 -1
  71. package/dist/integrations/gitlab/default-rules.d.ts +24 -9
  72. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  73. package/dist/integrations/gitlab/default-rules.js +4 -4
  74. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  75. package/dist/integrations/gitlab/merge-request-reconciler.js +1 -1
  76. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  77. package/dist/integrations/gitlab/routes.js +1 -3
  78. package/dist/integrations/gitlab/routes.js.map +1 -1
  79. package/dist/integrations/gitlab/rules.d.ts +16 -0
  80. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  81. package/dist/integrations/gitlab/rules.js +69 -4
  82. package/dist/integrations/gitlab/rules.js.map +1 -1
  83. package/dist/integrations/incidentio/default-rules.d.ts +1 -9
  84. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
  85. package/dist/integrations/incidentio/default-rules.js +3 -4
  86. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  87. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  88. package/dist/integrations/incidentio/routes.js +1 -4
  89. package/dist/integrations/incidentio/routes.js.map +1 -1
  90. package/dist/integrations/incidentio/rules.d.ts +7 -0
  91. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  92. package/dist/integrations/incidentio/rules.js +35 -3
  93. package/dist/integrations/incidentio/rules.js.map +1 -1
  94. package/dist/integrations/jira/default-rules.d.ts +1 -9
  95. package/dist/integrations/jira/default-rules.d.ts.map +1 -1
  96. package/dist/integrations/jira/default-rules.js +3 -4
  97. package/dist/integrations/jira/default-rules.js.map +1 -1
  98. package/dist/integrations/jira/routes.d.ts.map +1 -1
  99. package/dist/integrations/jira/routes.js +1 -4
  100. package/dist/integrations/jira/routes.js.map +1 -1
  101. package/dist/integrations/jira/rules.d.ts +7 -0
  102. package/dist/integrations/jira/rules.d.ts.map +1 -1
  103. package/dist/integrations/jira/rules.js +35 -3
  104. package/dist/integrations/jira/rules.js.map +1 -1
  105. package/dist/integrations/linear/default-rules.d.ts +1 -9
  106. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  107. package/dist/integrations/linear/default-rules.js +3 -4
  108. package/dist/integrations/linear/default-rules.js.map +1 -1
  109. package/dist/integrations/linear/routes.d.ts.map +1 -1
  110. package/dist/integrations/linear/routes.js +1 -4
  111. package/dist/integrations/linear/routes.js.map +1 -1
  112. package/dist/integrations/linear/rules.d.ts +7 -0
  113. package/dist/integrations/linear/rules.d.ts.map +1 -1
  114. package/dist/integrations/linear/rules.js +35 -3
  115. package/dist/integrations/linear/rules.js.map +1 -1
  116. package/dist/integrations/platform/connect/routes.d.ts +7 -1
  117. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  118. package/dist/integrations/platform/connect/routes.js +42 -5
  119. package/dist/integrations/platform/connect/routes.js.map +1 -1
  120. package/dist/integrations/platform/connect/session-tools.d.ts +7 -0
  121. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -0
  122. package/dist/integrations/platform/connect/session-tools.js +30 -0
  123. package/dist/integrations/platform/connect/session-tools.js.map +1 -0
  124. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  125. package/dist/integrations/platform/github/integration.js +1 -3
  126. package/dist/integrations/platform/github/integration.js.map +1 -1
  127. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  128. package/dist/integrations/platform/jira/routes.js +1 -4
  129. package/dist/integrations/platform/jira/routes.js.map +1 -1
  130. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  131. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  132. package/dist/integrations/platform/linear/event-worker.js +9 -0
  133. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  134. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  135. package/dist/integrations/platform/linear/integration.js +1 -3
  136. package/dist/integrations/platform/linear/integration.js.map +1 -1
  137. package/dist/integrations/slack/channel-reply-processor.d.ts +2 -0
  138. package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
  139. package/dist/integrations/slack/channel-reply-processor.js +6 -1
  140. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  141. package/dist/integrations/slack/connect-route.d.ts.map +1 -1
  142. package/dist/integrations/slack/connect-route.js +1 -1
  143. package/dist/integrations/slack/connect-route.js.map +1 -1
  144. package/dist/integrations/slack/integration.d.ts.map +1 -1
  145. package/dist/integrations/slack/integration.js +2 -0
  146. package/dist/integrations/slack/integration.js.map +1 -1
  147. package/dist/integrations/slack/slack.d.ts +12 -10
  148. package/dist/integrations/slack/slack.d.ts.map +1 -1
  149. package/dist/integrations/slack/slack.js +110 -43
  150. package/dist/integrations/slack/slack.js.map +1 -1
  151. package/dist/integrations/slack/voice-clips.d.ts +32 -0
  152. package/dist/integrations/slack/voice-clips.d.ts.map +1 -0
  153. package/dist/integrations/slack/voice-clips.js +201 -0
  154. package/dist/integrations/slack/voice-clips.js.map +1 -0
  155. package/dist/integrations/workos/integration.d.ts.map +1 -1
  156. package/dist/integrations/workos/integration.js +1 -3
  157. package/dist/integrations/workos/integration.js.map +1 -1
  158. package/dist/mcp/routes.js +1 -1
  159. package/dist/packages/_internals/workspace/dist/index.js +1 -1
  160. package/dist/routes/attention-activity.js +1 -1
  161. package/dist/routes/attention-providers.js +1 -1
  162. package/dist/routes/automation-runs.d.ts.map +1 -1
  163. package/dist/routes/automation-runs.js +1 -4
  164. package/dist/routes/automation-runs.js.map +1 -1
  165. package/dist/routes/boards.d.ts +8 -6
  166. package/dist/routes/boards.d.ts.map +1 -1
  167. package/dist/routes/boards.js +73 -143
  168. package/dist/routes/boards.js.map +1 -1
  169. package/dist/routes/config.d.ts.map +1 -1
  170. package/dist/routes/config.js +3 -8
  171. package/dist/routes/config.js.map +1 -1
  172. package/dist/routes/contracts.d.ts +132 -0
  173. package/dist/routes/contracts.d.ts.map +1 -1
  174. package/dist/routes/contracts.js +77 -29
  175. package/dist/routes/contracts.js.map +1 -1
  176. package/dist/routes/fs.d.ts.map +1 -1
  177. package/dist/routes/fs.js +1 -4
  178. package/dist/routes/fs.js.map +1 -1
  179. package/dist/routes/intake-routes.d.ts.map +1 -1
  180. package/dist/routes/intake-routes.js +19 -12
  181. package/dist/routes/intake-routes.js.map +1 -1
  182. package/dist/routes/intake.d.ts.map +1 -1
  183. package/dist/routes/intake.js +3 -5
  184. package/dist/routes/intake.js.map +1 -1
  185. package/dist/routes/knowledge.d.ts.map +1 -1
  186. package/dist/routes/knowledge.js +1 -4
  187. package/dist/routes/knowledge.js.map +1 -1
  188. package/dist/routes/oauth.d.ts.map +1 -1
  189. package/dist/routes/oauth.js +1 -4
  190. package/dist/routes/oauth.js.map +1 -1
  191. package/dist/routes/projects.d.ts +3 -0
  192. package/dist/routes/projects.d.ts.map +1 -1
  193. package/dist/routes/projects.js +7 -4
  194. package/dist/routes/projects.js.map +1 -1
  195. package/dist/routes/provider-credentials.d.ts.map +1 -1
  196. package/dist/routes/provider-credentials.js +6 -0
  197. package/dist/routes/provider-credentials.js.map +1 -1
  198. package/dist/routes/route.d.ts +2 -0
  199. package/dist/routes/route.d.ts.map +1 -1
  200. package/dist/routes/route.js +5 -1
  201. package/dist/routes/route.js.map +1 -1
  202. package/dist/routes/skills.d.ts.map +1 -1
  203. package/dist/routes/skills.js +1 -4
  204. package/dist/routes/skills.js.map +1 -1
  205. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  206. package/dist/routes/source-control-sessions.js +1 -3
  207. package/dist/routes/source-control-sessions.js.map +1 -1
  208. package/dist/routes/source-control-settings.d.ts.map +1 -1
  209. package/dist/routes/source-control-settings.js +3 -2
  210. package/dist/routes/source-control-settings.js.map +1 -1
  211. package/dist/routes/surface.d.ts +3 -1
  212. package/dist/routes/surface.d.ts.map +1 -1
  213. package/dist/routes/surface.js +11 -1
  214. package/dist/routes/surface.js.map +1 -1
  215. package/dist/routes/voice.d.ts +48 -0
  216. package/dist/routes/voice.d.ts.map +1 -0
  217. package/dist/routes/voice.js +248 -0
  218. package/dist/routes/voice.js.map +1 -0
  219. package/dist/routes/work-items.d.ts.map +1 -1
  220. package/dist/routes/work-items.js +1 -4
  221. package/dist/routes/work-items.js.map +1 -1
  222. package/dist/rules/decision-applicability.js +1 -1
  223. package/dist/rules/dispatcher.d.ts +28 -0
  224. package/dist/rules/dispatcher.d.ts.map +1 -1
  225. package/dist/rules/dispatcher.js +391 -93
  226. package/dist/rules/dispatcher.js.map +1 -1
  227. package/dist/rules/event-rules.d.ts +40 -1
  228. package/dist/rules/event-rules.d.ts.map +1 -1
  229. package/dist/rules/event-rules.js +59 -1
  230. package/dist/rules/event-rules.js.map +1 -1
  231. package/dist/rules/processor.js +1 -1
  232. package/dist/rules/processor.js.map +1 -1
  233. package/dist/rules/transition-service.d.ts +9 -0
  234. package/dist/rules/transition-service.d.ts.map +1 -1
  235. package/dist/rules/transition-service.js +4 -2
  236. package/dist/rules/transition-service.js.map +1 -1
  237. package/dist/rules/types.d.ts +54 -3
  238. package/dist/rules/types.d.ts.map +1 -1
  239. package/dist/rules/types.js +2 -0
  240. package/dist/rules/types.js.map +1 -1
  241. package/dist/rules/validation.d.ts.map +1 -1
  242. package/dist/rules/validation.js +57 -2
  243. package/dist/rules/validation.js.map +1 -1
  244. package/dist/session/credential-policy.d.ts +2 -2
  245. package/dist/session/credential-policy.d.ts.map +1 -1
  246. package/dist/session/credential-policy.js +3 -3
  247. package/dist/session/credential-policy.js.map +1 -1
  248. package/dist/session/default-model-hydration.d.ts +2 -2
  249. package/dist/session/default-model-hydration.d.ts.map +1 -1
  250. package/dist/session/default-model-hydration.js +4 -4
  251. package/dist/session/default-model-hydration.js.map +1 -1
  252. package/dist/session/session-threads.d.ts +8 -0
  253. package/dist/session/session-threads.d.ts.map +1 -1
  254. package/dist/session/session-threads.js +11 -1
  255. package/dist/session/session-threads.js.map +1 -1
  256. package/dist/skills/catalog.js +1 -1
  257. package/dist/storage/domains/audit/actions.d.ts +1 -1
  258. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  259. package/dist/storage/domains/audit/actions.js +2 -1
  260. package/dist/storage/domains/audit/actions.js.map +1 -1
  261. package/dist/storage/domains/audit/domain.d.ts.map +1 -1
  262. package/dist/storage/domains/audit/domain.js +1 -3
  263. package/dist/storage/domains/audit/domain.js.map +1 -1
  264. package/dist/storage/domains/boards/base.d.ts +32 -1
  265. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  266. package/dist/storage/domains/boards/base.js +155 -8
  267. package/dist/storage/domains/boards/base.js.map +1 -1
  268. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  269. package/dist/storage/domains/boards/schemas.js +13 -1
  270. package/dist/storage/domains/boards/schemas.js.map +1 -1
  271. package/dist/storage/domains/comments/routes.d.ts.map +1 -1
  272. package/dist/storage/domains/comments/routes.js +1 -3
  273. package/dist/storage/domains/comments/routes.js.map +1 -1
  274. package/dist/storage/domains/memory-settings/base.d.ts +0 -8
  275. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -1
  276. package/dist/storage/domains/memory-settings/base.js +1 -11
  277. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  278. package/dist/storage/domains/projects/base.d.ts +6 -0
  279. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  280. package/dist/storage/domains/projects/base.js +9 -1
  281. package/dist/storage/domains/projects/base.js.map +1 -1
  282. package/dist/storage/domains/voice-settings/base.d.ts +31 -0
  283. package/dist/storage/domains/voice-settings/base.d.ts.map +1 -0
  284. package/dist/storage/domains/voice-settings/base.js +81 -0
  285. package/dist/storage/domains/voice-settings/base.js.map +1 -0
  286. package/dist/storage/domains/work-items/base.d.ts +31 -2
  287. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  288. package/dist/storage/domains/work-items/base.js +197 -44
  289. package/dist/storage/domains/work-items/base.js.map +1 -1
  290. package/dist/storage/domains/work-items/cards.d.ts +6 -1
  291. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  292. package/dist/storage/domains/work-items/cards.js +54 -4
  293. package/dist/storage/domains/work-items/cards.js.map +1 -1
  294. package/dist/storage/domains/work-items/work-item-schema.d.ts +2 -0
  295. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  296. package/dist/storage/domains/work-items/work-item-schema.js +24 -1
  297. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  298. package/dist/timing.d.ts +1 -0
  299. package/dist/timing.d.ts.map +1 -1
  300. package/dist/timing.js +1 -1
  301. package/dist/timing.js.map +1 -1
  302. package/dist/tools/read-tools.d.ts +2 -2
  303. package/dist/tools/read-tools.d.ts.map +1 -1
  304. package/dist/tools/read-tools.js +7 -6
  305. package/dist/tools/read-tools.js.map +1 -1
  306. package/dist/tools/session-tools.d.ts +1 -1
  307. package/dist/tools/session-tools.d.ts.map +1 -1
  308. package/dist/tools/session-tools.js.map +1 -1
  309. package/dist/tools/sessions-state-processor.d.ts +1 -1
  310. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  311. package/dist/tools/sessions-state-processor.js +9 -2
  312. package/dist/tools/sessions-state-processor.js.map +1 -1
  313. package/dist/tools/work-item-tools.js +2 -2
  314. package/dist/voice/rate-limit.d.ts +13 -0
  315. package/dist/voice/rate-limit.d.ts.map +1 -0
  316. package/dist/voice/rate-limit.js +36 -0
  317. package/dist/voice/rate-limit.js.map +1 -0
  318. package/dist/voice/realtime.d.ts +13 -0
  319. package/dist/voice/realtime.d.ts.map +1 -0
  320. package/dist/voice/realtime.js +56 -0
  321. package/dist/voice/realtime.js.map +1 -0
  322. package/dist/voice/transcription.d.ts +51 -0
  323. package/dist/voice/transcription.d.ts.map +1 -0
  324. package/dist/voice/transcription.js +112 -0
  325. package/dist/voice/transcription.js.map +1 -0
  326. package/dist/work-items/split-backfill.d.ts +13 -0
  327. package/dist/work-items/split-backfill.d.ts.map +1 -0
  328. package/dist/work-items/split-backfill.js +32 -0
  329. package/dist/work-items/split-backfill.js.map +1 -0
  330. package/dist/work-items/split-migration.d.ts +39 -2
  331. package/dist/work-items/split-migration.d.ts.map +1 -1
  332. package/dist/work-items/split-migration.js +170 -62
  333. package/dist/work-items/split-migration.js.map +1 -1
  334. package/dist/workspace.js +2 -2
  335. package/package.json +12 -11
@@ -1 +1 @@
1
- {"version":3,"file":"integration.js","names":[],"sources":["../../../../src/integrations/platform/linear/integration.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\nimport type { Context } from 'hono';\n\nimport type { IntegrationConnection } from '../../../capabilities/connection.js';\nimport type { Intake, IntakeIssue, IntakeIssueDetail, UpdateIntakeIssueInput } from '../../../capabilities/intake.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { FactoryProjectsStorage } from '../../../storage/domains/projects/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../../base.js';\nimport { buildLinearAgentTools } from '../../linear/agent-tools.js';\nimport type { LinearEventRules, LinearRuleOverrides } from '../../linear/default-rules.js';\nimport { resolveLinearRules } from '../../linear/default-rules.js';\nimport type {\n LinearConnectionCheck,\n LinearIntegration,\n LinearIssueDetail as LinearRouteIssueDetail,\n} from '../../linear/integration.js';\nimport { attachLinearIssueReconciler } from '../../linear/issue-reconciler.js';\nimport {\n linearIssueReconciliationEnabled,\n linearIssueReconciliationInterval,\n} from '../../linear/reconciliation-config.js';\nimport { buildLinearRoutes } from '../../linear/routes.js';\nimport type { LinearWorkspaceListingError } from '../../linear/routes.js';\nimport { attachLinearRules } from '../../linear/rules.js';\nimport type { LinearConnectionData, LinearConnectionRow, LinearStorageHandle } from '../../linear/storage.js';\nimport {\n logPlatformInfo,\n logPlatformWarn,\n PlatformApiClient,\n PlatformApiError,\n platformApiClientConfigFromEnv,\n} from '../api-client.js';\nimport { PlatformLinearEventWorker } from './event-worker.js';\nimport type { PlatformLinearEventStorage } from './event-worker.js';\n\ntype PageInfo = { hasNextPage: boolean; endCursor: string | null };\ntype LinearUser = {\n id: string;\n name: string;\n displayName: string;\n email: string | null;\n avatarUrl: string | null;\n};\ntype LinearIssue = {\n id: string;\n identifier: string;\n number: number;\n title: string;\n description: string | null;\n url: string;\n priority: number;\n priorityLabel: string;\n labels: Array<{ id: string; name: string }>;\n state: { id: string; name: string; type: string };\n team: { id: string; key: string; name: string };\n project: { id: string } | null;\n assignee: LinearUser | null;\n creator: LinearUser | null;\n createdAt: string;\n updatedAt: string;\n archivedAt: string | null;\n};\ntype LinearComment = {\n id: string;\n body: string;\n url: string;\n issue: { id: string; identifier: string };\n user: LinearUser | null;\n parent: { id: string } | null;\n createdAt: string;\n updatedAt: string;\n};\ntype LinearWorkspace = {\n linearWorkspaceId: string;\n linearWorkspaceName: string;\n urlKey: string | null;\n connected: boolean;\n};\ntype LinearProject = {\n id: string;\n name: string;\n state: string;\n teams: Array<{ id: string; key: string; name: string }>;\n};\ntype LinearTeam = { id: string; key: string; name: string };\ntype ProjectSource = { workspace: LinearWorkspace; project: LinearProject };\ntype TeamSource = { workspace: LinearWorkspace; team: LinearTeam };\ntype LinearWorkflowState = {\n id: string;\n name: string;\n type: string;\n position: number;\n teamId: string;\n};\n\nconst API_PREFIX = '/v1/server/linear';\nconst PAGE_SIZE = 30;\nconst MAX_REFERENCE_PAGES = 20;\nconst MAX_COMMENT_PAGES = 20;\nconst PLATFORM_MANAGED_CONNECTION_TOKEN = 'platform-managed';\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\nfunction routeBaseUrl(ctx: IntegrationContext, requestUrl: string): string {\n return (ctx.baseUrl || new URL(requestUrl).origin).replace(/\\/+$/, '');\n}\n\nexport class PlatformLinearIntegration implements FactoryIntegration {\n readonly id = 'linear';\n readonly #client: PlatformApiClient;\n readonly #endpointHost: string;\n #projects: FactoryProjectsStorage | undefined;\n #auth: RouteAuth | undefined;\n /**\n * Per-instance workflow-state cache keyed by `${workspaceId}:${teamId}`. Scoped to the process\n * lifetime; not shared across requests intentionally to keep failure modes simple (stale states\n * clear on process restart). Populated lazily on first `updateIssue` per team.\n */\n readonly #workflowStatesByTeam = new Map<string, LinearWorkflowState[]>();\n\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: async () => {\n const [projectSources, teamSources] = await Promise.all([this.#listProjectSources(), this.#listTeamSources()]);\n const projects = projectSources.map(({ workspace, project }) => ({\n id: encodeSourceId(workspace.linearWorkspaceId, project.id),\n name: project.name,\n type: 'project' as const,\n metadata: {\n workspaceId: workspace.linearWorkspaceId,\n workspaceName: workspace.linearWorkspaceName,\n workspaceUrlKey: workspace.urlKey,\n state: project.state,\n teams: project.teams,\n },\n }));\n const teams = teamSources.map(({ workspace, team }) => ({\n id: encodeTeamSourceId(workspace.linearWorkspaceId, team.id),\n name: team.name,\n type: 'team' as const,\n metadata: {\n workspaceId: workspace.linearWorkspaceId,\n workspaceName: workspace.linearWorkspaceName,\n workspaceUrlKey: workspace.urlKey,\n teamKey: team.key,\n },\n }));\n return [...projects, ...teams];\n },\n listItems: async ({ sourceIds, attributionSourceIds, cursor }) => {\n const result = await this.#listIssues(sourceIds, cursor, undefined, attributionSourceIds);\n return {\n items: result.issues.map(({ issue, sourceId, workspace }) => ({\n source: { type: 'issue', externalId: issue.id, url: issue.url },\n sourceId,\n title: issue.title,\n status: issue.state.name,\n labels: issue.labels.map(label => label.name),\n assignee: issue.assignee?.displayName ?? issue.assignee?.name ?? null,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: {\n identifier: issue.identifier,\n workspaceId: workspace.linearWorkspaceId,\n workspaceName: workspace.linearWorkspaceName,\n projectId: issue.project?.id ?? null,\n team: issue.team.key,\n priority: issue.priorityLabel,\n },\n })),\n nextCursor: result.nextCursor,\n };\n },\n listIssues: async ({ connection, sourceIds, attributionSourceIds, labels, cursor }) => {\n requireLinearConnection(connection);\n const result = await this.#listIssues(sourceIds, cursor, labels, attributionSourceIds);\n return {\n issues: result.issues.map(({ issue, sourceId, workspace }) => ({\n ...parseIssue(issue, workspace.linearWorkspaceId),\n sourceId,\n })),\n nextCursor: result.nextCursor,\n };\n },\n getIssue: async ({ connection, sourceId, issueId }) => {\n requireLinearConnection(connection);\n const located = await this.#findIssue(sourceId, issueId);\n if (!located) return null;\n const comments = await this.#loadComments(located.workspaceId, issueId, located.issue.comments);\n return parseIssueDetail(located.issue, comments, located.workspaceId);\n },\n createComment: async ({ connection, sourceId, issueId, body }) => {\n requireLinearConnection(connection);\n const workspaceId = await this.#resolveWorkspaceForIssue(sourceId, issueId);\n if (!workspaceId) return null;\n try {\n const comment = await this.#client.request<LinearComment>(\n 'POST',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/issues/${encodeURIComponent(issueId)}/comments`,\n { body },\n );\n return { id: comment.id, url: comment.url };\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n },\n updateIssue: async (input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> => {\n requireLinearConnection(input.connection);\n const located = await this.#findIssue(input.sourceId, input.issueId);\n if (!located) return null;\n const { workspaceId, issue } = located;\n\n const target = input.state;\n // Idempotency: skip the write entirely if the issue is already at the target state.\n if (target.kind === 'byType' && issue.state.type === target.stateType) {\n return parseIssue(issue, workspaceId);\n }\n if (target.kind === 'byName' && issue.state.name.toLowerCase() === target.name.toLowerCase()) {\n return parseIssue(issue, workspaceId);\n }\n\n let states: LinearWorkflowState[];\n try {\n states = await this.#listWorkflowStates(workspaceId, issue.team.id);\n } catch (error) {\n if (isNotFound(error)) {\n // Platform companion endpoint not deployed yet — degrade to policy skip so PR 1\n // is standalone-mergeable ahead of the platform-side workflow-states route landing.\n logPlatformWarn('Platform Linear: workflow-states endpoint not available; skipping updateIssue.', {\n workspaceId,\n teamId: issue.team.id,\n });\n return null;\n }\n throw error;\n }\n let matched: LinearWorkflowState | undefined;\n if (target.kind === 'byType') {\n matched = states\n .slice()\n .sort((a, b) => a.position - b.position)\n .find(s => s.type === target.stateType);\n } else {\n const wanted = target.name.toLowerCase();\n matched = states.find(s => s.name.toLowerCase() === wanted);\n }\n if (!matched) {\n logPlatformWarn('Platform Linear: no workflow state matched target; skipping updateIssue.', {\n workspaceId,\n teamId: issue.team.id,\n target,\n });\n return null;\n }\n\n try {\n await this.#client.request<LinearIssue>(\n 'PATCH',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/issues/${encodeURIComponent(input.issueId)}`,\n { stateId: matched.id },\n );\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n\n const refreshed = await this.#findIssue(input.sourceId, input.issueId);\n return refreshed ? parseIssue(refreshed.issue, refreshed.workspaceId) : null;\n },\n };\n\n readonly #rules: LinearEventRules;\n\n get rules(): LinearEventRules {\n return this.#rules;\n }\n\n constructor({ rules }: { rules?: LinearRuleOverrides } = {}) {\n this.#rules = resolveLinearRules(rules);\n const config = platformApiClientConfigFromEnv();\n this.#client = new PlatformApiClient(config);\n this.#endpointHost = new URL(config.baseUrl).host;\n }\n\n get storage(): LinearStorageHandle {\n const now = new Date();\n return {\n integrationId: this.id,\n connections: {\n get: async (orgId: string) => ({\n id: `platform-linear:${orgId}`,\n orgId,\n userId: null,\n data: {\n accessToken: PLATFORM_MANAGED_CONNECTION_TOKEN,\n refreshToken: null,\n expiresAtMs: null,\n scope: 'read,comments:create',\n workspaceName: null,\n workspaceUrlKey: null,\n } satisfies LinearConnectionData,\n metadata: {},\n createdAt: now,\n updatedAt: now,\n }),\n },\n } as unknown as LinearStorageHandle;\n }\n\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) throw new Error('PlatformLinearIntegration projects storage has not been initialized.');\n return this.#projects;\n }\n\n initialize({ projects, auth }: { projects: FactoryProjectsStorage; auth?: RouteAuth }): void {\n this.#projects = projects;\n this.#auth = auth;\n logPlatformInfo('Platform Linear integration initialized', { endpointHost: this.#endpointHost });\n }\n\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n async resolveOrgId(resourceId: string): Promise<string | null> {\n try {\n const project = await this.projects.getById({ id: resourceId });\n return project?.orgId ?? null;\n } catch {\n return null;\n }\n }\n\n async loadConnection(orgId: string): Promise<LinearConnectionRow | null> {\n const workspace = (await this.#listWorkspaces())[0];\n if (!workspace) return null;\n const now = new Date();\n return {\n id: `platform-linear:${orgId}`,\n orgId,\n userId: null,\n accessToken: PLATFORM_MANAGED_CONNECTION_TOKEN,\n scope: 'read,comments:create',\n refreshToken: null,\n expiresAt: null,\n workspaceName: workspace.linearWorkspaceName,\n workspaceUrlKey: workspace.urlKey,\n createdAt: now,\n updatedAt: now,\n };\n }\n\n async getFreshAccessToken(_connection: LinearConnectionRow): Promise<string> {\n return PLATFORM_MANAGED_CONNECTION_TOKEN;\n }\n\n /**\n * Background-dispatch context: platform-managed connection token when the\n * org has a connected workspace. Linear work items store the issue UUID\n * directly as `externalId`.\n */\n async #resolveIntakeDispatch({\n orgId,\n externalSource,\n }: {\n orgId: string;\n externalSource: { type: string; externalId: string };\n }): Promise<{ connection: IntegrationConnection; issueId: string } | null> {\n if (externalSource.type !== 'issue') return null;\n const connection = await this.loadConnection(orgId);\n if (!connection) return null;\n return {\n connection: { type: 'oauth', accessToken: PLATFORM_MANAGED_CONNECTION_TOKEN },\n issueId: externalSource.externalId,\n };\n }\n\n canPostComments(connection: LinearConnectionRow): boolean {\n const scopes = (connection.scope ?? '').split(/[\\s,]+/).filter(Boolean);\n return scopes.some(scope => scope === 'comments:create' || scope === 'write' || scope === 'admin');\n }\n\n async checkConnection(orgId: string): Promise<LinearConnectionCheck> {\n const connection = await this.loadConnection(orgId);\n return {\n connected: connection !== null,\n canComment: connection !== null && this.canPostComments(connection),\n workspaceUrlKey: connection?.workspaceUrlKey ?? null,\n checkedAt: Date.now(),\n };\n }\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n const pollingEnabled = process.env.MASTRACODE_PLATFORM_LINEAR_POLLING_ENABLED?.trim().toLowerCase() !== 'false';\n const reconcileEnabled = linearIssueReconciliationEnabled();\n if (!pollingEnabled && !reconcileEnabled) return [];\n\n const ingest = attachLinearRules(this, ctx);\n const reconcile = reconcileEnabled ? attachLinearIssueReconciler(this, ctx) : undefined;\n const workItems = ctx.runtime?.workItems;\n if (!workItems) return [];\n if (!ingest && !reconcile) return [];\n\n const pollIntervalMs = optionalPositiveIntegerEnv('MASTRACODE_PLATFORM_LINEAR_POLLING_INTERVAL_MS');\n const reconcileIntervalMs = linearIssueReconciliationInterval();\n\n return [\n new PlatformLinearEventWorker({\n client: this.#client,\n linear: { listWorkspaces: () => this.listWorkspaces() },\n storage: ctx.storage.generic as unknown as PlatformLinearEventStorage,\n projects: ctx.storage.projects,\n workItems,\n ...(ingest ? { ingestFactoryIssue: ingest } : {}),\n ...(reconcile ? { reconcileFactoryState: reconcile } : {}),\n pollEventsEnabled: pollingEnabled,\n ...(pollIntervalMs !== undefined ? { intervalMs: pollIntervalMs } : {}),\n ...(reconcileIntervalMs !== undefined ? { reconcileIntervalMs } : {}),\n }),\n ];\n }\n\n routes(ctx: IntegrationContext): ApiRoute[] {\n return [\n this.#connectRoute(ctx),\n this.#reconnectReturnRoute(ctx),\n ...buildLinearRoutes({\n auth: ctx.auth,\n linear: this as unknown as LinearIntegration,\n listConnectionWorkspaces: async () =>\n (await this.#listAllWorkspaces()).map(workspace => ({\n id: workspace.linearWorkspaceId,\n name: workspace.linearWorkspaceName,\n urlKey: workspace.urlKey,\n connected: workspace.connected,\n })),\n listProjectsWithStatus: async () => {\n const workspaceErrors: LinearWorkspaceListingError[] = [];\n return { projects: await this.#listProjects(workspaceErrors), workspaceErrors };\n },\n listTeamsWithStatus: async () => {\n const workspaceErrors: LinearWorkspaceListingError[] = [];\n return { teams: await this.#listTeams(workspaceErrors), workspaceErrors };\n },\n stateSigner: ctx.stateSigner,\n baseUrl: ctx.baseUrl,\n intake: ctx.storage.intake,\n projects: ctx.storage.projects,\n ingestFactoryIssues: attachLinearRules(this, ctx),\n workItems: ctx.runtime?.workItems,\n boards: ctx.runtime?.boards,\n }).filter(route => !route.path.startsWith('/auth/linear/')),\n ];\n }\n\n #connectRoute(ctx: IntegrationContext): ApiRoute {\n return registerApiRoute('/auth/linear/connect', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await ctx.auth.ensureUser(loose(c));\n const tenant = ctx.auth.tenant(loose(c));\n if (!tenant?.orgId) return c.json({ error: 'unauthorized' }, 401);\n\n const returnUrl = localReturnUrl(c.req.query('return_to'));\n const returnTo = localPath(returnUrl);\n const originator = routeBaseUrl(ctx, c.req.url);\n const workspaceId = c.req.query('workspace_id');\n let authorizationReturnTo = returnTo;\n if (workspaceId) {\n const workspaces = await this.#listAllWorkspaces().catch(() => null);\n if (!workspaces) {\n returnUrl.searchParams.set('linear_reconnect', 'unavailable');\n returnUrl.searchParams.set('linear_workspace_id', workspaceId);\n return c.redirect(localPath(returnUrl));\n }\n if (!workspaces.some(workspace => workspace.linearWorkspaceId === workspaceId)) {\n return c.json({ error: 'linear_workspace_not_found' }, 404);\n }\n // Platform owns OAuth. Verify the intended workspace after it returns;\n // authorizing a different workspace must not claim to repair this one.\n authorizationReturnTo = `/auth/linear/reconnect-return?${new URLSearchParams({ workspace_id: workspaceId, return_to: returnTo })}`;\n }\n logPlatformInfo('Starting Platform Linear connect flow', {\n orgId: tenant.orgId,\n returnTo,\n originator,\n });\n const query = new URLSearchParams({ return_to: authorizationReturnTo, originator });\n const location = await this.#client.requestRedirect('GET', `${API_PREFIX}/authorize?${query}`);\n return c.redirect(location);\n },\n });\n }\n\n #reconnectReturnRoute(ctx: IntegrationContext): ApiRoute {\n return registerApiRoute('/auth/linear/reconnect-return', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await ctx.auth.ensureUser(loose(c));\n if (!ctx.auth.tenant(loose(c))?.orgId) return c.json({ error: 'unauthorized' }, 401);\n const destination = localReturnUrl(c.req.query('return_to'));\n const workspaceId = c.req.query('workspace_id');\n try {\n const workspaces = await this.#listWorkspaces();\n const restored = workspaces.some(workspace => workspace.linearWorkspaceId === workspaceId);\n destination.searchParams.set('linear_reconnect', restored ? 'connected' : 'not_connected');\n } catch {\n destination.searchParams.set('linear_reconnect', 'unavailable');\n }\n if (workspaceId) destination.searchParams.set('linear_workspace_id', workspaceId);\n return c.redirect(localPath(destination));\n },\n });\n }\n\n async agentTools({ requestContext }: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildLinearAgentTools({ requestContext, linear: this as unknown as LinearIntegration });\n }\n\n diagnostics(): Record<string, unknown> {\n return { mode: 'platform', endpointHost: this.#endpointHost };\n }\n\n async listProjects(): Promise<Array<LinearProject & { workspaceId: string }>> {\n return this.#listProjects();\n }\n\n async listTeams(_accessToken: string): Promise<Array<LinearTeam & { workspaceId: string; sourceId: string }>> {\n return this.#listTeams();\n }\n\n async #listProjects(errors?: LinearWorkspaceListingError[]): Promise<Array<LinearProject & { workspaceId: string }>> {\n return (await this.#listProjectSources(undefined, errors)).map(({ workspace, project }) => ({\n ...project,\n id: encodeSourceId(workspace.linearWorkspaceId, project.id),\n workspaceId: workspace.linearWorkspaceId,\n }));\n }\n\n async #listTeams(\n errors?: LinearWorkspaceListingError[],\n ): Promise<Array<LinearTeam & { workspaceId: string; sourceId: string }>> {\n return (await this.#listTeamSources(undefined, errors)).map(({ workspace, team }) => ({\n ...team,\n workspaceId: workspace.linearWorkspaceId,\n sourceId: encodeTeamSourceId(workspace.linearWorkspaceId, team.id),\n }));\n }\n\n async fetchIssueDetail(\n _accessToken: string,\n idOrIdentifier: string,\n sourceIds?: string[],\n routedSourceIds?: string[],\n ): Promise<LinearRouteIssueDetail | null> {\n const located = await this.#findIssue(undefined, idOrIdentifier, sourceIds, routedSourceIds);\n if (!located) return null;\n const comments = await this.#loadComments(located.workspaceId, located.issue.id, located.issue.comments);\n const issue = located.issue;\n return {\n id: issue.id,\n projectId: issue.project?.id ?? null,\n workspaceId: located.workspaceId,\n teamId: issue.team.id,\n identifier: issue.identifier,\n title: issue.title,\n description: issue.description?.trim() ? issue.description : null,\n url: issue.url,\n state: issue.state.name,\n stateType: issue.state.type,\n priorityLabel: issue.priorityLabel,\n assignee: issue.assignee?.displayName ?? issue.assignee?.name ?? null,\n creator: issue.creator?.displayName ?? issue.creator?.name ?? null,\n team: issue.team.key,\n labels: issue.labels.map(label => label.name),\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n comments: comments.map(comment => ({\n author: comment.user?.displayName ?? comment.user?.name ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n })),\n };\n }\n\n sourceMatchesIssue(\n sourceId: string,\n issue: Pick<LinearRouteIssueDetail, 'workspaceId' | 'projectId' | 'teamId'>,\n ): boolean {\n const source = parseSourceId(sourceId);\n if (issue.workspaceId !== source.workspaceId) return false;\n return source.kind === 'team' ? issue.teamId === source.teamId : issue.projectId === source.projectId;\n }\n\n async #listProjectSources(\n workspaceIds?: ReadonlySet<string>,\n errors?: LinearWorkspaceListingError[],\n ): Promise<ProjectSource[]> {\n const workspaces = await this.#listWorkspaces();\n const scopedWorkspaces = workspaceIds\n ? workspaces.filter(workspace => workspaceIds.has(workspace.linearWorkspaceId))\n : workspaces;\n const projectGroups = await Promise.allSettled(\n scopedWorkspaces.map(async workspace => {\n const projects: LinearProject[] = [];\n let after: string | undefined;\n for (let page = 0; page < MAX_REFERENCE_PAGES; page += 1) {\n const query = new URLSearchParams({ first: '200' });\n if (after) query.set('after', after);\n const result = await this.#client.request<{ projects: LinearProject[]; pageInfo: PageInfo }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspace.linearWorkspaceId)}/projects?${query}`,\n );\n projects.push(...result.projects);\n if (!result.pageInfo.hasNextPage || !result.pageInfo.endCursor) break;\n // A page that hands back the cursor it was asked for would replay forever.\n if (result.pageInfo.endCursor === after) throw invalidLinearCursor();\n after = result.pageInfo.endCursor;\n }\n return projects.map(project => ({ workspace, project }));\n }),\n );\n return collectWorkspaceListings(scopedWorkspaces, projectGroups, errors);\n }\n\n async #listTeamSources(\n workspaceIds?: ReadonlySet<string>,\n errors?: LinearWorkspaceListingError[],\n ): Promise<TeamSource[]> {\n const workspaces = await this.#listWorkspaces();\n const scopedWorkspaces = workspaceIds\n ? workspaces.filter(workspace => workspaceIds.has(workspace.linearWorkspaceId))\n : workspaces;\n const teamGroups = await Promise.allSettled(\n scopedWorkspaces.map(async workspace => {\n const teams: LinearTeam[] = [];\n let after: string | undefined;\n for (let page = 0; page < MAX_REFERENCE_PAGES; page += 1) {\n const query = new URLSearchParams({ first: '200' });\n if (after) query.set('after', after);\n const result = await this.#client.request<{ teams: LinearTeam[]; pageInfo: PageInfo }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspace.linearWorkspaceId)}/teams?${query}`,\n );\n teams.push(...result.teams);\n if (!result.pageInfo.hasNextPage || !result.pageInfo.endCursor) break;\n // A page that hands back the cursor it was asked for would replay forever.\n if (result.pageInfo.endCursor === after) throw invalidLinearCursor();\n after = result.pageInfo.endCursor;\n }\n return teams.map(team => ({ workspace, team }));\n }),\n );\n return collectWorkspaceListings(scopedWorkspaces, teamGroups, errors);\n }\n\n async listWorkspaces(): Promise<LinearWorkspace[]> {\n return this.#listWorkspaces();\n }\n\n async #listWorkspaces(): Promise<LinearWorkspace[]> {\n return (await this.#listAllWorkspaces()).filter(workspace => workspace.connected);\n }\n\n /** Includes workspaces whose connection stopped working. */\n async #listAllWorkspaces(): Promise<LinearWorkspace[]> {\n const result = await this.#client.request<{ workspaces: LinearWorkspace[] }>('GET', `${API_PREFIX}/workspaces`);\n return result.workspaces;\n }\n\n async #listIssues(sourceIds: string[], cursor?: string, labels?: string[], attributionSourceIds = sourceIds) {\n type ListedIssue = { issue: LinearIssue; sourceId: string; workspace: LinearWorkspace };\n if (sourceIds.length === 0) return { issues: [] as ListedIssue[], nextCursor: null };\n\n // Resolve every selected source to a concrete listing descriptor. Project\n // and team sources are listed separately: a project source filters by\n // `projectIds`, a team source filters by `teamId` (and returns projectless\n // issues too). Filters are never combined on one request.\n const parsedSources = sourceIds.map(sourceId => parseSourceId(sourceId));\n const projectWorkspaceIds = new Set(\n parsedSources.flatMap(source => (source.kind === 'project' ? [source.workspaceId] : [])),\n );\n const teamWorkspaceIds = new Set(\n parsedSources.flatMap(source => (source.kind === 'team' ? [source.workspaceId] : [])),\n );\n const [projectsResult, teamsResult] = await Promise.allSettled([\n projectWorkspaceIds.size > 0\n ? this.#listProjectSources(projectWorkspaceIds)\n : Promise.resolve([] as ProjectSource[]),\n teamWorkspaceIds.size > 0 ? this.#listTeamSources(teamWorkspaceIds) : Promise.resolve([] as TeamSource[]),\n ]);\n if (projectsResult.status === 'rejected' && (teamWorkspaceIds.size === 0 || teamsResult.status === 'rejected')) {\n throw projectsResult.reason;\n }\n if (teamsResult.status === 'rejected' && projectWorkspaceIds.size === 0) throw teamsResult.reason;\n const projectSources = projectsResult.status === 'fulfilled' ? projectsResult.value : [];\n const teamSources = teamsResult.status === 'fulfilled' ? teamsResult.value : [];\n const projectMap = new Map(\n projectSources.map(source => [encodeSourceId(source.workspace.linearWorkspaceId, source.project.id), source]),\n );\n const teamMap = new Map(\n teamSources.map(source => [encodeTeamSourceId(source.workspace.linearWorkspaceId, source.team.id), source]),\n );\n\n type Descriptor = {\n kind: 'project' | 'team';\n sourceId: string;\n workspace: LinearWorkspace;\n query: URLSearchParams;\n };\n const descriptors: Descriptor[] = [];\n const selectedProjectIdsByWorkspace = new Map<string, Set<string>>();\n for (const attributionSourceId of attributionSourceIds) {\n const source = parseSourceId(attributionSourceId);\n if (source.kind !== 'project') continue;\n const selectedProjectIds = selectedProjectIdsByWorkspace.get(source.workspaceId) ?? new Set<string>();\n selectedProjectIds.add(source.projectId);\n selectedProjectIdsByWorkspace.set(source.workspaceId, selectedProjectIds);\n }\n for (const sourceId of sourceIds) {\n const projectSource = projectMap.get(sourceId);\n if (projectSource) {\n const query = new URLSearchParams({\n first: String(PAGE_SIZE),\n projectIds: projectSource.project.id,\n stateType: 'triage,backlog,unstarted,started',\n orderBy: 'updatedAt',\n });\n const workspaceId = projectSource.workspace.linearWorkspaceId;\n const selectedProjectIds = selectedProjectIdsByWorkspace.get(workspaceId) ?? new Set<string>();\n selectedProjectIds.add(projectSource.project.id);\n selectedProjectIdsByWorkspace.set(workspaceId, selectedProjectIds);\n descriptors.push({ kind: 'project', sourceId, workspace: projectSource.workspace, query });\n continue;\n }\n const teamSource = teamMap.get(sourceId);\n if (teamSource) {\n const query = new URLSearchParams({\n first: String(PAGE_SIZE),\n teamId: teamSource.team.id,\n stateType: 'triage,backlog,unstarted,started',\n orderBy: 'updatedAt',\n });\n descriptors.push({ kind: 'team', sourceId, workspace: teamSource.workspace, query });\n }\n }\n\n const cursors = await decodeCursor(cursor, sourceIds, attributionSourceIds);\n const unfinished = descriptors.filter(({ sourceId }) => cursors[sourceId] !== null);\n const normalizedLabels = normalizeLabels(labels);\n const nextState: Record<string, string | null> = {};\n let hasNextPage = false;\n const pages = await Promise.allSettled(\n unfinished.map(async ({ kind, sourceId, workspace, query }) => {\n const after = cursors[sourceId];\n if (after) query.set('after', after);\n const result = await this.#client.request<{ issues: LinearIssue[]; pageInfo: PageInfo }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspace.linearWorkspaceId)}/issues?${query}`,\n );\n const next = result.pageInfo.hasNextPage ? result.pageInfo.endCursor : null;\n // A page that hands back the cursor it was asked for would replay forever.\n if (next !== null && next === after) throw invalidLinearCursor();\n nextState[sourceId] = next;\n hasNextPage ||= next !== null;\n return result.issues\n .filter(\n issue => normalizedLabels.length === 0 || issue.labels.some(label => normalizedLabels.includes(label.name)),\n )\n .filter(\n issue =>\n kind === 'project' ||\n issue.project === null ||\n !selectedProjectIdsByWorkspace.get(workspace.linearWorkspaceId)?.has(issue.project.id),\n )\n .map(issue => ({ issue, sourceId, workspace }));\n }),\n );\n return {\n // A failed workspace is retried from the start on the next intake poll;\n // successful workspaces can finish their own pagination in this cycle.\n issues: dedupeIssuesBySource(\n collectWorkspaceListings(\n unfinished.map(source => source.workspace),\n pages,\n ),\n sourceIds,\n ),\n nextCursor: hasNextPage ? await encodeCursor(nextState, sourceIds, attributionSourceIds) : null,\n };\n }\n\n async #findIssue(\n sourceId: string | undefined,\n issueId: string,\n sourceIds?: string[],\n routedSourceIds?: string[],\n ): Promise<{\n workspaceId: string;\n issue: LinearIssue & { comments?: { nodes: LinearComment[]; pageInfo: PageInfo } };\n } | null> {\n const scopedSourceIds = sourceIds ?? (sourceId ? [sourceId] : undefined);\n const scopedSources = scopedSourceIds?.map(sourceKey => ({\n sourceKey,\n source: parseSourceId(sourceKey),\n }));\n const routedSourceSet = routedSourceIds ? new Set(routedSourceIds) : undefined;\n const workspaceIds = routedSourceIds\n ? [...new Set(routedSourceIds.map(sourceKey => parseSourceId(sourceKey).workspaceId))]\n : scopedSources\n ? [...new Set(scopedSources.map(({ source }) => source.workspaceId))]\n : await this.#candidateWorkspaceIds(undefined);\n for (const workspaceId of workspaceIds) {\n try {\n const issue = await this.#client.request<\n LinearIssue & { comments?: { nodes: LinearComment[]; pageInfo: PageInfo } }\n >(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/issues/${encodeURIComponent(issueId)}?include=comments`,\n );\n if (scopedSources) {\n const matching = scopedSources.filter(\n ({ source }) =>\n source.workspaceId === workspaceId &&\n (source.kind === 'team' ? issue.team.id === source.teamId : issue.project?.id === source.projectId),\n );\n const winner = matching.find(({ source }) => source.kind === 'project') ?? matching[0];\n if (!winner || (routedSourceSet && !routedSourceSet.has(winner.sourceKey))) continue;\n }\n return { workspaceId, issue };\n } catch (error) {\n if (!isNotFound(error)) throw error;\n }\n }\n return null;\n }\n\n async #resolveWorkspaceForIssue(sourceId: string | undefined, issueId: string): Promise<string | null> {\n const workspaceIds = await this.#candidateWorkspaceIds(sourceId);\n if (workspaceIds.length === 1) return workspaceIds[0]!;\n for (const workspaceId of workspaceIds) {\n try {\n await this.#client.request<LinearIssue>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/issues/${encodeURIComponent(issueId)}`,\n );\n return workspaceId;\n } catch (error) {\n if (!isNotFound(error)) throw error;\n }\n }\n return null;\n }\n\n async #listWorkflowStates(workspaceId: string, teamId: string): Promise<LinearWorkflowState[]> {\n const cacheKey = `${workspaceId}:${teamId}`;\n const cached = this.#workflowStatesByTeam.get(cacheKey);\n if (cached) return cached;\n const result = await this.#client.request<{ workflowStates: LinearWorkflowState[]; pageInfo: PageInfo }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/workflow-states?teamId=${encodeURIComponent(teamId)}&first=100`,\n );\n this.#workflowStatesByTeam.set(cacheKey, result.workflowStates);\n return result.workflowStates;\n }\n\n async #candidateWorkspaceIds(sourceId: string | undefined): Promise<string[]> {\n if (sourceId) return [parseSourceId(sourceId).workspaceId];\n return (await this.#listWorkspaces()).map(workspace => workspace.linearWorkspaceId);\n }\n\n async #loadComments(\n workspaceId: string,\n issueId: string,\n embedded: { nodes: LinearComment[]; pageInfo: PageInfo } | undefined,\n ): Promise<LinearComment[]> {\n const comments = [...(embedded?.nodes ?? [])];\n let pageInfo = embedded?.pageInfo;\n let page = 0;\n while (pageInfo?.hasNextPage && pageInfo.endCursor && page < MAX_COMMENT_PAGES) {\n const result = await this.#client.request<{ comments: LinearComment[]; pageInfo: PageInfo }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/issues/${encodeURIComponent(issueId)}/comments?first=200&after=${encodeURIComponent(pageInfo.endCursor)}`,\n );\n comments.push(...result.comments);\n if (result.pageInfo.hasNextPage && result.pageInfo.endCursor === pageInfo.endCursor) throw invalidLinearCursor();\n pageInfo = result.pageInfo;\n page += 1;\n }\n return comments;\n }\n}\n\nfunction parseIssue(issue: LinearIssue, workspaceId: string): IntakeIssue {\n return {\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.creator?.displayName ?? issue.creator?.name ?? null,\n state: issue.state.name,\n stateType: issue.state.type,\n priority: issue.priorityLabel,\n assignee: issue.assignee?.displayName ?? issue.assignee?.name ?? null,\n source: issue.team.key,\n // Use the same workspace-scoped identity as listProjects and intake bindings.\n // The source may be a team, so it cannot stand in for the issue's project.\n projectId: issue.project ? encodeSourceId(workspaceId, issue.project.id) : null,\n labels: issue.labels.map(label => label.name),\n commentCount: null,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\nfunction parseIssueDetail(issue: LinearIssue, comments: LinearComment[], workspaceId: string): IntakeIssueDetail {\n return {\n ...parseIssue(issue, workspaceId),\n commentCount: comments.length,\n description: issue.description?.trim() ? issue.description : null,\n comments: comments.map(comment => ({\n author: comment.user?.displayName ?? comment.user?.name ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n })),\n };\n}\n\n/**\n * Deduplicate issues that surfaced from more than one selected source (a team\n * source and one of its projects both select the same issue). Keeps one entry\n * per Linear issue UUID.\n *\n * Tie-breaker — MOST-SPECIFIC-WINS: a project source beats a team source, so an\n * issue that belongs to a selected project is attributed to that project's\n * source (and therefore routes to the project's board). The team source covers\n * only the remainder — projectless issues and issues in projects that were not\n * separately selected. `selectionOrder` breaks a same-kind tie deterministically\n * by the order the sources were selected.\n *\n * This function is the single precedence point; change the comparison here to\n * change the routing policy.\n */\nfunction dedupeIssuesBySource<T extends { issue: { id: string }; sourceId: string }>(\n entries: T[],\n selectionOrder: string[],\n): T[] {\n const rank = new Map(selectionOrder.map((id, index) => [id, index]));\n const specificity = (sourceId: string): number => (parseSourceId(sourceId).kind === 'project' ? 0 : 1);\n const winners = new Map<string, T>();\n for (const entry of entries) {\n const existing = winners.get(entry.issue.id);\n if (!existing) {\n winners.set(entry.issue.id, entry);\n continue;\n }\n const bySpecificity = specificity(entry.sourceId) - specificity(existing.sourceId);\n const better =\n bySpecificity < 0 ||\n (bySpecificity === 0 &&\n (rank.get(entry.sourceId) ?? Number.MAX_SAFE_INTEGER) <\n (rank.get(existing.sourceId) ?? Number.MAX_SAFE_INTEGER));\n if (better) winners.set(entry.issue.id, entry);\n }\n // Preserve first-seen order of the surviving issues.\n const seen = new Set<string>();\n const ordered: T[] = [];\n for (const entry of entries) {\n if (seen.has(entry.issue.id)) continue;\n seen.add(entry.issue.id);\n ordered.push(winners.get(entry.issue.id)!);\n }\n return ordered;\n}\n\nexport function encodeSourceId(workspaceId: string, projectId: string): string {\n return `linear-project:${Buffer.from(JSON.stringify({ workspaceId, projectId })).toString('base64url')}`;\n}\n\nfunction decodeSourceId(sourceId: string): { workspaceId: string; projectId: string } {\n if (!sourceId.startsWith('linear-project:')) throw new Error('Linear project source id is invalid.');\n try {\n const parsed = JSON.parse(Buffer.from(sourceId.slice('linear-project:'.length), 'base64url').toString('utf8')) as {\n workspaceId?: unknown;\n projectId?: unknown;\n };\n if (typeof parsed.workspaceId !== 'string' || !parsed.workspaceId) throw new Error();\n if (typeof parsed.projectId !== 'string' || !parsed.projectId) throw new Error();\n return { workspaceId: parsed.workspaceId, projectId: parsed.projectId };\n } catch {\n throw new Error('Linear project source id is invalid.');\n }\n}\n\nconst TEAM_SOURCE_PREFIX = 'linear-team:';\n\nexport function encodeTeamSourceId(workspaceId: string, teamId: string): string {\n return `${TEAM_SOURCE_PREFIX}${Buffer.from(JSON.stringify({ workspaceId, teamId })).toString('base64url')}`;\n}\n\nexport function decodeTeamSourceId(sourceId: string): { workspaceId: string; teamId: string } {\n if (!sourceId.startsWith(TEAM_SOURCE_PREFIX)) throw new Error('Linear team source id is invalid.');\n try {\n const parsed = JSON.parse(Buffer.from(sourceId.slice(TEAM_SOURCE_PREFIX.length), 'base64url').toString('utf8')) as {\n workspaceId?: unknown;\n teamId?: unknown;\n };\n if (typeof parsed.workspaceId !== 'string' || !parsed.workspaceId) throw new Error();\n if (typeof parsed.teamId !== 'string' || !parsed.teamId) throw new Error();\n return { workspaceId: parsed.workspaceId, teamId: parsed.teamId };\n } catch {\n throw new Error('Linear team source id is invalid.');\n }\n}\n\n/**\n * A decoded intake source: either a Linear project or a whole Linear team.\n * Downstream code discriminates on `kind` to build the right issue-listing\n * filter and to apply most-specific-wins routing (project beats team).\n */\nexport type DecodedSource =\n { kind: 'project'; workspaceId: string; projectId: string } | { kind: 'team'; workspaceId: string; teamId: string };\n\n/** Discriminate any Linear source id by its prefix and decode it. */\nexport function parseSourceId(sourceId: string): DecodedSource {\n if (sourceId.startsWith(TEAM_SOURCE_PREFIX)) {\n return { kind: 'team', ...decodeTeamSourceId(sourceId) };\n }\n return { kind: 'project', ...decodeSourceId(sourceId) };\n}\n\nfunction normalizeLabels(labels: string[] | undefined): string[] {\n return [...new Set((labels ?? []).map(label => label.trim()).filter(Boolean))];\n}\n\ntype PlatformListCursor = { v: 1; sourceSet: string; cursors: Array<string | null> };\n\nfunction canonicalSourceIds(sourceIds: string[]): string[] {\n return [...new Set(sourceIds)].sort();\n}\n\nasync function linearSourceSetFingerprint(sourceIds: string[], attributionSourceIds: string[]): Promise<string> {\n const scope = {\n sourceIds: canonicalSourceIds(sourceIds),\n attributionSourceIds: canonicalSourceIds(attributionSourceIds),\n };\n const bytes = new TextEncoder().encode(JSON.stringify(scope));\n return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', bytes)).toString('base64url');\n}\n\nfunction invalidLinearCursor(): Error {\n return Object.assign(new Error('Linear cursor is invalid or stale.'), { code: 'invalid_cursor' as const });\n}\n\nasync function decodeCursor(\n cursor: string | undefined,\n sourceIds: string[],\n attributionSourceIds: string[],\n): Promise<Record<string, string | null | undefined>> {\n if (!cursor) return {};\n try {\n const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as Partial<PlatformListCursor>;\n const canonical = canonicalSourceIds(sourceIds);\n if (\n parsed.v !== 1 ||\n parsed.sourceSet !== (await linearSourceSetFingerprint(sourceIds, attributionSourceIds)) ||\n !Array.isArray(parsed.cursors) ||\n parsed.cursors.length !== canonical.length ||\n !parsed.cursors.every(value => value === null || typeof value === 'string')\n ) {\n throw invalidLinearCursor();\n }\n return Object.fromEntries(canonical.map((sourceId, index) => [sourceId, parsed.cursors![index]]));\n } catch {\n throw invalidLinearCursor();\n }\n}\n\nasync function encodeCursor(\n state: Record<string, string | null>,\n sourceIds: string[],\n attributionSourceIds: string[],\n): Promise<string> {\n const canonical = canonicalSourceIds(sourceIds);\n const cursor: PlatformListCursor = {\n v: 1,\n sourceSet: await linearSourceSetFingerprint(sourceIds, attributionSourceIds),\n cursors: canonical.map(sourceId => state[sourceId] ?? null),\n };\n return Buffer.from(JSON.stringify(cursor)).toString('base64url');\n}\n\nfunction requireLinearConnection(connection: IntegrationConnection): void {\n if (connection.type !== 'oauth') {\n throw new Error('Linear capabilities require an OAuth connection.');\n }\n}\n\nfunction isNotFound(error: unknown): boolean {\n return error instanceof PlatformApiError && error.status === 404;\n}\n\n/** A provider outage in one workspace must not hide sources from the others. */\nfunction collectWorkspaceListings<T>(\n workspaces: LinearWorkspace[],\n results: PromiseSettledResult<T[]>[],\n errors?: LinearWorkspaceListingError[],\n): T[] {\n const items: T[] = [];\n let firstFailure: unknown;\n let succeeded = false;\n for (const [index, result] of results.entries()) {\n if (result.status === 'fulfilled') {\n succeeded = true;\n items.push(...result.value);\n continue;\n }\n const workspace = workspaces[index]!;\n firstFailure ??= result.reason;\n errors?.push({ workspaceId: workspace.linearWorkspaceId, name: workspace.linearWorkspaceName });\n logPlatformWarn('Platform Linear workspace sources could not be loaded; intake will retry.', {\n workspaceId: workspace.linearWorkspaceId,\n });\n }\n if (!succeeded && firstFailure) throw firstFailure;\n return items;\n}\n\nconst LOCAL_RETURN_ORIGIN = 'https://factory.invalid';\n\nfunction localPath(url: URL): string {\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\n/** OAuth may only return to a path on this Factory host. */\nfunction localReturnUrl(value: string | undefined): URL {\n const url = value?.startsWith('/') ? URL.parse(value, LOCAL_RETURN_ORIGIN) : null;\n // Dot segments can normalize `/.//host` into a protocol-relative `//host`.\n if (url?.origin === LOCAL_RETURN_ORIGIN && !url.pathname.startsWith('//')) return url;\n return new URL('/', LOCAL_RETURN_ORIGIN);\n}\n\nfunction optionalPositiveIntegerEnv(name: string): number | undefined {\n const value = process.env[name]?.trim();\n if (!value) return undefined;\n const parsed = Number(value);\n if (!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SACtB,MAAM,IAAI,MAAM,kDAAkD;AAEtE;AAEA,SAAS,WAAW,OAAyB;CAC3C,OAAO,iBAAiB,oBAAoB,MAAM,WAAW;AAC/D;;AAGA,SAAS,yBACP,YACA,SACA,QACK;CACL,MAAM,QAAa,CAAC;CACpB,IAAI;CACJ,IAAI,YAAY;CAChB,KAAK,MAAM,CAAC,OAAO,WAAW,QAAQ,QAAQ,GAAG;EAC/C,IAAI,OAAO,WAAW,aAAa;GACjC,YAAY;GACZ,MAAM,KAAK,GAAG,OAAO,KAAK;GAC1B;EACF;EACA,MAAM,YAAY,WAAW;EAC7B,iBAAiB,OAAO;EACxB,QAAQ,KAAK;GAAE,aAAa,UAAU;GAAmB,MAAM,UAAU;EAAoB,CAAC;EAC9F,gBAAgB,6EAA6E,EAC3F,aAAa,UAAU,kBACzB,CAAC;CACH;CACA,IAAI,CAAC,aAAa,cAAc,MAAM;CACtC,OAAO;AACT;AAEA,MAAM,sBAAsB;AAE5B,SAAS,UAAU,KAAkB;CACnC,OAAO,GAAG,IAAI,WAAW,IAAI,SAAS,IAAI;AAC5C;;AAGA,SAAS,eAAe,OAAgC;CACtD,MAAM,MAAM,OAAO,WAAW,GAAG,IAAI,IAAI,MAAM,OAAO,mBAAmB,IAAI;CAE7E,IAAI,KAAK,WAAW,uBAAuB,CAAC,IAAI,SAAS,WAAW,IAAI,GAAG,OAAO;CAClF,OAAO,IAAI,IAAI,KAAK,mBAAmB;AACzC;AAEA,SAAS,2BAA2B,MAAkC;CACpE,MAAM,QAAQ,QAAQ,IAAI,KAAK,EAAE,KAAK;CACtC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,SAAS,OAAO,KAAK;CAC3B,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,UAAU,GAC7C,MAAM,IAAI,MAAM,GAAG,KAAK,6BAA6B;CAEvD,OAAO;AACT"}
1
+ {"version":3,"file":"integration.js","names":[],"sources":["../../../../src/integrations/platform/linear/integration.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\n\nimport type { IntegrationConnection } from '../../../capabilities/connection.js';\nimport type { Intake, IntakeIssue, IntakeIssueDetail, UpdateIntakeIssueInput } from '../../../capabilities/intake.js';\nimport { loose } from '../../../routes/route.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { FactoryProjectsStorage } from '../../../storage/domains/projects/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../../base.js';\nimport { buildLinearAgentTools } from '../../linear/agent-tools.js';\nimport type { LinearEventRules, LinearRuleOverrides } from '../../linear/default-rules.js';\nimport { resolveLinearRules } from '../../linear/default-rules.js';\nimport type {\n LinearConnectionCheck,\n LinearIntegration,\n LinearIssueDetail as LinearRouteIssueDetail,\n} from '../../linear/integration.js';\nimport { attachLinearIssueReconciler } from '../../linear/issue-reconciler.js';\nimport {\n linearIssueReconciliationEnabled,\n linearIssueReconciliationInterval,\n} from '../../linear/reconciliation-config.js';\nimport { buildLinearRoutes } from '../../linear/routes.js';\nimport type { LinearWorkspaceListingError } from '../../linear/routes.js';\nimport { attachLinearRules } from '../../linear/rules.js';\nimport type { LinearConnectionData, LinearConnectionRow, LinearStorageHandle } from '../../linear/storage.js';\nimport {\n logPlatformInfo,\n logPlatformWarn,\n PlatformApiClient,\n PlatformApiError,\n platformApiClientConfigFromEnv,\n} from '../api-client.js';\nimport { PlatformLinearEventWorker } from './event-worker.js';\nimport type { PlatformLinearEventStorage } from './event-worker.js';\n\ntype PageInfo = { hasNextPage: boolean; endCursor: string | null };\ntype LinearUser = {\n id: string;\n name: string;\n displayName: string;\n email: string | null;\n avatarUrl: string | null;\n};\ntype LinearIssue = {\n id: string;\n identifier: string;\n number: number;\n title: string;\n description: string | null;\n url: string;\n priority: number;\n priorityLabel: string;\n labels: Array<{ id: string; name: string }>;\n state: { id: string; name: string; type: string };\n team: { id: string; key: string; name: string };\n project: { id: string } | null;\n assignee: LinearUser | null;\n creator: LinearUser | null;\n createdAt: string;\n updatedAt: string;\n archivedAt: string | null;\n};\ntype LinearComment = {\n id: string;\n body: string;\n url: string;\n issue: { id: string; identifier: string };\n user: LinearUser | null;\n parent: { id: string } | null;\n createdAt: string;\n updatedAt: string;\n};\ntype LinearWorkspace = {\n linearWorkspaceId: string;\n linearWorkspaceName: string;\n urlKey: string | null;\n connected: boolean;\n};\ntype LinearProject = {\n id: string;\n name: string;\n state: string;\n teams: Array<{ id: string; key: string; name: string }>;\n};\ntype LinearTeam = { id: string; key: string; name: string };\ntype ProjectSource = { workspace: LinearWorkspace; project: LinearProject };\ntype TeamSource = { workspace: LinearWorkspace; team: LinearTeam };\ntype LinearWorkflowState = {\n id: string;\n name: string;\n type: string;\n position: number;\n teamId: string;\n};\n\nconst API_PREFIX = '/v1/server/linear';\nconst PAGE_SIZE = 30;\nconst MAX_REFERENCE_PAGES = 20;\nconst MAX_COMMENT_PAGES = 20;\nconst PLATFORM_MANAGED_CONNECTION_TOKEN = 'platform-managed';\n\nfunction routeBaseUrl(ctx: IntegrationContext, requestUrl: string): string {\n return (ctx.baseUrl || new URL(requestUrl).origin).replace(/\\/+$/, '');\n}\n\nexport class PlatformLinearIntegration implements FactoryIntegration {\n readonly id = 'linear';\n readonly #client: PlatformApiClient;\n readonly #endpointHost: string;\n #projects: FactoryProjectsStorage | undefined;\n #auth: RouteAuth | undefined;\n /**\n * Per-instance workflow-state cache keyed by `${workspaceId}:${teamId}`. Scoped to the process\n * lifetime; not shared across requests intentionally to keep failure modes simple (stale states\n * clear on process restart). Populated lazily on first `updateIssue` per team.\n */\n readonly #workflowStatesByTeam = new Map<string, LinearWorkflowState[]>();\n\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: async () => {\n const [projectSources, teamSources] = await Promise.all([this.#listProjectSources(), this.#listTeamSources()]);\n const projects = projectSources.map(({ workspace, project }) => ({\n id: encodeSourceId(workspace.linearWorkspaceId, project.id),\n name: project.name,\n type: 'project' as const,\n metadata: {\n workspaceId: workspace.linearWorkspaceId,\n workspaceName: workspace.linearWorkspaceName,\n workspaceUrlKey: workspace.urlKey,\n state: project.state,\n teams: project.teams,\n },\n }));\n const teams = teamSources.map(({ workspace, team }) => ({\n id: encodeTeamSourceId(workspace.linearWorkspaceId, team.id),\n name: team.name,\n type: 'team' as const,\n metadata: {\n workspaceId: workspace.linearWorkspaceId,\n workspaceName: workspace.linearWorkspaceName,\n workspaceUrlKey: workspace.urlKey,\n teamKey: team.key,\n },\n }));\n return [...projects, ...teams];\n },\n listItems: async ({ sourceIds, attributionSourceIds, cursor }) => {\n const result = await this.#listIssues(sourceIds, cursor, undefined, attributionSourceIds);\n return {\n items: result.issues.map(({ issue, sourceId, workspace }) => ({\n source: { type: 'issue', externalId: issue.id, url: issue.url },\n sourceId,\n title: issue.title,\n status: issue.state.name,\n labels: issue.labels.map(label => label.name),\n assignee: issue.assignee?.displayName ?? issue.assignee?.name ?? null,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: {\n identifier: issue.identifier,\n workspaceId: workspace.linearWorkspaceId,\n workspaceName: workspace.linearWorkspaceName,\n projectId: issue.project?.id ?? null,\n team: issue.team.key,\n priority: issue.priorityLabel,\n },\n })),\n nextCursor: result.nextCursor,\n };\n },\n listIssues: async ({ connection, sourceIds, attributionSourceIds, labels, cursor }) => {\n requireLinearConnection(connection);\n const result = await this.#listIssues(sourceIds, cursor, labels, attributionSourceIds);\n return {\n issues: result.issues.map(({ issue, sourceId, workspace }) => ({\n ...parseIssue(issue, workspace.linearWorkspaceId),\n sourceId,\n })),\n nextCursor: result.nextCursor,\n };\n },\n getIssue: async ({ connection, sourceId, issueId }) => {\n requireLinearConnection(connection);\n const located = await this.#findIssue(sourceId, issueId);\n if (!located) return null;\n const comments = await this.#loadComments(located.workspaceId, issueId, located.issue.comments);\n return parseIssueDetail(located.issue, comments, located.workspaceId);\n },\n createComment: async ({ connection, sourceId, issueId, body }) => {\n requireLinearConnection(connection);\n const workspaceId = await this.#resolveWorkspaceForIssue(sourceId, issueId);\n if (!workspaceId) return null;\n try {\n const comment = await this.#client.request<LinearComment>(\n 'POST',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/issues/${encodeURIComponent(issueId)}/comments`,\n { body },\n );\n return { id: comment.id, url: comment.url };\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n },\n updateIssue: async (input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> => {\n requireLinearConnection(input.connection);\n const located = await this.#findIssue(input.sourceId, input.issueId);\n if (!located) return null;\n const { workspaceId, issue } = located;\n\n const target = input.state;\n // Idempotency: skip the write entirely if the issue is already at the target state.\n if (target.kind === 'byType' && issue.state.type === target.stateType) {\n return parseIssue(issue, workspaceId);\n }\n if (target.kind === 'byName' && issue.state.name.toLowerCase() === target.name.toLowerCase()) {\n return parseIssue(issue, workspaceId);\n }\n\n let states: LinearWorkflowState[];\n try {\n states = await this.#listWorkflowStates(workspaceId, issue.team.id);\n } catch (error) {\n if (isNotFound(error)) {\n // Platform companion endpoint not deployed yet — degrade to policy skip so PR 1\n // is standalone-mergeable ahead of the platform-side workflow-states route landing.\n logPlatformWarn('Platform Linear: workflow-states endpoint not available; skipping updateIssue.', {\n workspaceId,\n teamId: issue.team.id,\n });\n return null;\n }\n throw error;\n }\n let matched: LinearWorkflowState | undefined;\n if (target.kind === 'byType') {\n matched = states\n .slice()\n .sort((a, b) => a.position - b.position)\n .find(s => s.type === target.stateType);\n } else {\n const wanted = target.name.toLowerCase();\n matched = states.find(s => s.name.toLowerCase() === wanted);\n }\n if (!matched) {\n logPlatformWarn('Platform Linear: no workflow state matched target; skipping updateIssue.', {\n workspaceId,\n teamId: issue.team.id,\n target,\n });\n return null;\n }\n\n try {\n await this.#client.request<LinearIssue>(\n 'PATCH',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/issues/${encodeURIComponent(input.issueId)}`,\n { stateId: matched.id },\n );\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n\n const refreshed = await this.#findIssue(input.sourceId, input.issueId);\n return refreshed ? parseIssue(refreshed.issue, refreshed.workspaceId) : null;\n },\n };\n\n readonly #rules: LinearEventRules;\n\n get rules(): LinearEventRules {\n return this.#rules;\n }\n\n constructor({ rules }: { rules?: LinearRuleOverrides } = {}) {\n this.#rules = resolveLinearRules(rules);\n const config = platformApiClientConfigFromEnv();\n this.#client = new PlatformApiClient(config);\n this.#endpointHost = new URL(config.baseUrl).host;\n }\n\n get storage(): LinearStorageHandle {\n const now = new Date();\n return {\n integrationId: this.id,\n connections: {\n get: async (orgId: string) => ({\n id: `platform-linear:${orgId}`,\n orgId,\n userId: null,\n data: {\n accessToken: PLATFORM_MANAGED_CONNECTION_TOKEN,\n refreshToken: null,\n expiresAtMs: null,\n scope: 'read,comments:create',\n workspaceName: null,\n workspaceUrlKey: null,\n } satisfies LinearConnectionData,\n metadata: {},\n createdAt: now,\n updatedAt: now,\n }),\n },\n } as unknown as LinearStorageHandle;\n }\n\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) throw new Error('PlatformLinearIntegration projects storage has not been initialized.');\n return this.#projects;\n }\n\n initialize({ projects, auth }: { projects: FactoryProjectsStorage; auth?: RouteAuth }): void {\n this.#projects = projects;\n this.#auth = auth;\n logPlatformInfo('Platform Linear integration initialized', { endpointHost: this.#endpointHost });\n }\n\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n async resolveOrgId(resourceId: string): Promise<string | null> {\n try {\n const project = await this.projects.getById({ id: resourceId });\n return project?.orgId ?? null;\n } catch {\n return null;\n }\n }\n\n async loadConnection(orgId: string): Promise<LinearConnectionRow | null> {\n const workspace = (await this.#listWorkspaces())[0];\n if (!workspace) return null;\n const now = new Date();\n return {\n id: `platform-linear:${orgId}`,\n orgId,\n userId: null,\n accessToken: PLATFORM_MANAGED_CONNECTION_TOKEN,\n scope: 'read,comments:create',\n refreshToken: null,\n expiresAt: null,\n workspaceName: workspace.linearWorkspaceName,\n workspaceUrlKey: workspace.urlKey,\n createdAt: now,\n updatedAt: now,\n };\n }\n\n async getFreshAccessToken(_connection: LinearConnectionRow): Promise<string> {\n return PLATFORM_MANAGED_CONNECTION_TOKEN;\n }\n\n /**\n * Background-dispatch context: platform-managed connection token when the\n * org has a connected workspace. Linear work items store the issue UUID\n * directly as `externalId`.\n */\n async #resolveIntakeDispatch({\n orgId,\n externalSource,\n }: {\n orgId: string;\n externalSource: { type: string; externalId: string };\n }): Promise<{ connection: IntegrationConnection; issueId: string } | null> {\n if (externalSource.type !== 'issue') return null;\n const connection = await this.loadConnection(orgId);\n if (!connection) return null;\n return {\n connection: { type: 'oauth', accessToken: PLATFORM_MANAGED_CONNECTION_TOKEN },\n issueId: externalSource.externalId,\n };\n }\n\n canPostComments(connection: LinearConnectionRow): boolean {\n const scopes = (connection.scope ?? '').split(/[\\s,]+/).filter(Boolean);\n return scopes.some(scope => scope === 'comments:create' || scope === 'write' || scope === 'admin');\n }\n\n async checkConnection(orgId: string): Promise<LinearConnectionCheck> {\n const connection = await this.loadConnection(orgId);\n return {\n connected: connection !== null,\n canComment: connection !== null && this.canPostComments(connection),\n workspaceUrlKey: connection?.workspaceUrlKey ?? null,\n checkedAt: Date.now(),\n };\n }\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n const pollingEnabled = process.env.MASTRACODE_PLATFORM_LINEAR_POLLING_ENABLED?.trim().toLowerCase() !== 'false';\n const reconcileEnabled = linearIssueReconciliationEnabled();\n if (!pollingEnabled && !reconcileEnabled) return [];\n\n const ingest = attachLinearRules(this, ctx);\n const reconcile = reconcileEnabled ? attachLinearIssueReconciler(this, ctx) : undefined;\n const workItems = ctx.runtime?.workItems;\n if (!workItems) return [];\n if (!ingest && !reconcile) return [];\n\n const pollIntervalMs = optionalPositiveIntegerEnv('MASTRACODE_PLATFORM_LINEAR_POLLING_INTERVAL_MS');\n const reconcileIntervalMs = linearIssueReconciliationInterval();\n\n return [\n new PlatformLinearEventWorker({\n client: this.#client,\n linear: { listWorkspaces: () => this.listWorkspaces() },\n storage: ctx.storage.generic as unknown as PlatformLinearEventStorage,\n projects: ctx.storage.projects,\n workItems,\n ...(ingest ? { ingestFactoryIssue: ingest } : {}),\n ...(reconcile ? { reconcileFactoryState: reconcile } : {}),\n pollEventsEnabled: pollingEnabled,\n ...(pollIntervalMs !== undefined ? { intervalMs: pollIntervalMs } : {}),\n ...(reconcileIntervalMs !== undefined ? { reconcileIntervalMs } : {}),\n }),\n ];\n }\n\n routes(ctx: IntegrationContext): ApiRoute[] {\n return [\n this.#connectRoute(ctx),\n this.#reconnectReturnRoute(ctx),\n ...buildLinearRoutes({\n auth: ctx.auth,\n linear: this as unknown as LinearIntegration,\n listConnectionWorkspaces: async () =>\n (await this.#listAllWorkspaces()).map(workspace => ({\n id: workspace.linearWorkspaceId,\n name: workspace.linearWorkspaceName,\n urlKey: workspace.urlKey,\n connected: workspace.connected,\n })),\n listProjectsWithStatus: async () => {\n const workspaceErrors: LinearWorkspaceListingError[] = [];\n return { projects: await this.#listProjects(workspaceErrors), workspaceErrors };\n },\n listTeamsWithStatus: async () => {\n const workspaceErrors: LinearWorkspaceListingError[] = [];\n return { teams: await this.#listTeams(workspaceErrors), workspaceErrors };\n },\n stateSigner: ctx.stateSigner,\n baseUrl: ctx.baseUrl,\n intake: ctx.storage.intake,\n projects: ctx.storage.projects,\n ingestFactoryIssues: attachLinearRules(this, ctx),\n workItems: ctx.runtime?.workItems,\n boards: ctx.runtime?.boards,\n }).filter(route => !route.path.startsWith('/auth/linear/')),\n ];\n }\n\n #connectRoute(ctx: IntegrationContext): ApiRoute {\n return registerApiRoute('/auth/linear/connect', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await ctx.auth.ensureUser(loose(c));\n const tenant = ctx.auth.tenant(loose(c));\n if (!tenant?.orgId) return c.json({ error: 'unauthorized' }, 401);\n\n const returnUrl = localReturnUrl(c.req.query('return_to'));\n const returnTo = localPath(returnUrl);\n const originator = routeBaseUrl(ctx, c.req.url);\n const workspaceId = c.req.query('workspace_id');\n let authorizationReturnTo = returnTo;\n if (workspaceId) {\n const workspaces = await this.#listAllWorkspaces().catch(() => null);\n if (!workspaces) {\n returnUrl.searchParams.set('linear_reconnect', 'unavailable');\n returnUrl.searchParams.set('linear_workspace_id', workspaceId);\n return c.redirect(localPath(returnUrl));\n }\n if (!workspaces.some(workspace => workspace.linearWorkspaceId === workspaceId)) {\n return c.json({ error: 'linear_workspace_not_found' }, 404);\n }\n // Platform owns OAuth. Verify the intended workspace after it returns;\n // authorizing a different workspace must not claim to repair this one.\n authorizationReturnTo = `/auth/linear/reconnect-return?${new URLSearchParams({ workspace_id: workspaceId, return_to: returnTo })}`;\n }\n logPlatformInfo('Starting Platform Linear connect flow', {\n orgId: tenant.orgId,\n returnTo,\n originator,\n });\n const query = new URLSearchParams({ return_to: authorizationReturnTo, originator });\n const location = await this.#client.requestRedirect('GET', `${API_PREFIX}/authorize?${query}`);\n return c.redirect(location);\n },\n });\n }\n\n #reconnectReturnRoute(ctx: IntegrationContext): ApiRoute {\n return registerApiRoute('/auth/linear/reconnect-return', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await ctx.auth.ensureUser(loose(c));\n if (!ctx.auth.tenant(loose(c))?.orgId) return c.json({ error: 'unauthorized' }, 401);\n const destination = localReturnUrl(c.req.query('return_to'));\n const workspaceId = c.req.query('workspace_id');\n try {\n const workspaces = await this.#listWorkspaces();\n const restored = workspaces.some(workspace => workspace.linearWorkspaceId === workspaceId);\n destination.searchParams.set('linear_reconnect', restored ? 'connected' : 'not_connected');\n } catch {\n destination.searchParams.set('linear_reconnect', 'unavailable');\n }\n if (workspaceId) destination.searchParams.set('linear_workspace_id', workspaceId);\n return c.redirect(localPath(destination));\n },\n });\n }\n\n async agentTools({ requestContext }: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildLinearAgentTools({ requestContext, linear: this as unknown as LinearIntegration });\n }\n\n diagnostics(): Record<string, unknown> {\n return { mode: 'platform', endpointHost: this.#endpointHost };\n }\n\n async listProjects(): Promise<Array<LinearProject & { workspaceId: string }>> {\n return this.#listProjects();\n }\n\n async listTeams(_accessToken: string): Promise<Array<LinearTeam & { workspaceId: string; sourceId: string }>> {\n return this.#listTeams();\n }\n\n async #listProjects(errors?: LinearWorkspaceListingError[]): Promise<Array<LinearProject & { workspaceId: string }>> {\n return (await this.#listProjectSources(undefined, errors)).map(({ workspace, project }) => ({\n ...project,\n id: encodeSourceId(workspace.linearWorkspaceId, project.id),\n workspaceId: workspace.linearWorkspaceId,\n }));\n }\n\n async #listTeams(\n errors?: LinearWorkspaceListingError[],\n ): Promise<Array<LinearTeam & { workspaceId: string; sourceId: string }>> {\n return (await this.#listTeamSources(undefined, errors)).map(({ workspace, team }) => ({\n ...team,\n workspaceId: workspace.linearWorkspaceId,\n sourceId: encodeTeamSourceId(workspace.linearWorkspaceId, team.id),\n }));\n }\n\n async fetchIssueDetail(\n _accessToken: string,\n idOrIdentifier: string,\n sourceIds?: string[],\n routedSourceIds?: string[],\n ): Promise<LinearRouteIssueDetail | null> {\n const located = await this.#findIssue(undefined, idOrIdentifier, sourceIds, routedSourceIds);\n if (!located) return null;\n const comments = await this.#loadComments(located.workspaceId, located.issue.id, located.issue.comments);\n const issue = located.issue;\n return {\n id: issue.id,\n projectId: issue.project?.id ?? null,\n workspaceId: located.workspaceId,\n teamId: issue.team.id,\n identifier: issue.identifier,\n title: issue.title,\n description: issue.description?.trim() ? issue.description : null,\n url: issue.url,\n state: issue.state.name,\n stateType: issue.state.type,\n priorityLabel: issue.priorityLabel,\n assignee: issue.assignee?.displayName ?? issue.assignee?.name ?? null,\n creator: issue.creator?.displayName ?? issue.creator?.name ?? null,\n team: issue.team.key,\n labels: issue.labels.map(label => label.name),\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n comments: comments.map(comment => ({\n author: comment.user?.displayName ?? comment.user?.name ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n })),\n };\n }\n\n sourceMatchesIssue(\n sourceId: string,\n issue: Pick<LinearRouteIssueDetail, 'workspaceId' | 'projectId' | 'teamId'>,\n ): boolean {\n const source = parseSourceId(sourceId);\n if (issue.workspaceId !== source.workspaceId) return false;\n return source.kind === 'team' ? issue.teamId === source.teamId : issue.projectId === source.projectId;\n }\n\n async #listProjectSources(\n workspaceIds?: ReadonlySet<string>,\n errors?: LinearWorkspaceListingError[],\n ): Promise<ProjectSource[]> {\n const workspaces = await this.#listWorkspaces();\n const scopedWorkspaces = workspaceIds\n ? workspaces.filter(workspace => workspaceIds.has(workspace.linearWorkspaceId))\n : workspaces;\n const projectGroups = await Promise.allSettled(\n scopedWorkspaces.map(async workspace => {\n const projects: LinearProject[] = [];\n let after: string | undefined;\n for (let page = 0; page < MAX_REFERENCE_PAGES; page += 1) {\n const query = new URLSearchParams({ first: '200' });\n if (after) query.set('after', after);\n const result = await this.#client.request<{ projects: LinearProject[]; pageInfo: PageInfo }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspace.linearWorkspaceId)}/projects?${query}`,\n );\n projects.push(...result.projects);\n if (!result.pageInfo.hasNextPage || !result.pageInfo.endCursor) break;\n // A page that hands back the cursor it was asked for would replay forever.\n if (result.pageInfo.endCursor === after) throw invalidLinearCursor();\n after = result.pageInfo.endCursor;\n }\n return projects.map(project => ({ workspace, project }));\n }),\n );\n return collectWorkspaceListings(scopedWorkspaces, projectGroups, errors);\n }\n\n async #listTeamSources(\n workspaceIds?: ReadonlySet<string>,\n errors?: LinearWorkspaceListingError[],\n ): Promise<TeamSource[]> {\n const workspaces = await this.#listWorkspaces();\n const scopedWorkspaces = workspaceIds\n ? workspaces.filter(workspace => workspaceIds.has(workspace.linearWorkspaceId))\n : workspaces;\n const teamGroups = await Promise.allSettled(\n scopedWorkspaces.map(async workspace => {\n const teams: LinearTeam[] = [];\n let after: string | undefined;\n for (let page = 0; page < MAX_REFERENCE_PAGES; page += 1) {\n const query = new URLSearchParams({ first: '200' });\n if (after) query.set('after', after);\n const result = await this.#client.request<{ teams: LinearTeam[]; pageInfo: PageInfo }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspace.linearWorkspaceId)}/teams?${query}`,\n );\n teams.push(...result.teams);\n if (!result.pageInfo.hasNextPage || !result.pageInfo.endCursor) break;\n // A page that hands back the cursor it was asked for would replay forever.\n if (result.pageInfo.endCursor === after) throw invalidLinearCursor();\n after = result.pageInfo.endCursor;\n }\n return teams.map(team => ({ workspace, team }));\n }),\n );\n return collectWorkspaceListings(scopedWorkspaces, teamGroups, errors);\n }\n\n async listWorkspaces(): Promise<LinearWorkspace[]> {\n return this.#listWorkspaces();\n }\n\n async #listWorkspaces(): Promise<LinearWorkspace[]> {\n return (await this.#listAllWorkspaces()).filter(workspace => workspace.connected);\n }\n\n /** Includes workspaces whose connection stopped working. */\n async #listAllWorkspaces(): Promise<LinearWorkspace[]> {\n const result = await this.#client.request<{ workspaces: LinearWorkspace[] }>('GET', `${API_PREFIX}/workspaces`);\n return result.workspaces;\n }\n\n async #listIssues(sourceIds: string[], cursor?: string, labels?: string[], attributionSourceIds = sourceIds) {\n type ListedIssue = { issue: LinearIssue; sourceId: string; workspace: LinearWorkspace };\n if (sourceIds.length === 0) return { issues: [] as ListedIssue[], nextCursor: null };\n\n // Resolve every selected source to a concrete listing descriptor. Project\n // and team sources are listed separately: a project source filters by\n // `projectIds`, a team source filters by `teamId` (and returns projectless\n // issues too). Filters are never combined on one request.\n const parsedSources = sourceIds.map(sourceId => parseSourceId(sourceId));\n const projectWorkspaceIds = new Set(\n parsedSources.flatMap(source => (source.kind === 'project' ? [source.workspaceId] : [])),\n );\n const teamWorkspaceIds = new Set(\n parsedSources.flatMap(source => (source.kind === 'team' ? [source.workspaceId] : [])),\n );\n const [projectsResult, teamsResult] = await Promise.allSettled([\n projectWorkspaceIds.size > 0\n ? this.#listProjectSources(projectWorkspaceIds)\n : Promise.resolve([] as ProjectSource[]),\n teamWorkspaceIds.size > 0 ? this.#listTeamSources(teamWorkspaceIds) : Promise.resolve([] as TeamSource[]),\n ]);\n if (projectsResult.status === 'rejected' && (teamWorkspaceIds.size === 0 || teamsResult.status === 'rejected')) {\n throw projectsResult.reason;\n }\n if (teamsResult.status === 'rejected' && projectWorkspaceIds.size === 0) throw teamsResult.reason;\n const projectSources = projectsResult.status === 'fulfilled' ? projectsResult.value : [];\n const teamSources = teamsResult.status === 'fulfilled' ? teamsResult.value : [];\n const projectMap = new Map(\n projectSources.map(source => [encodeSourceId(source.workspace.linearWorkspaceId, source.project.id), source]),\n );\n const teamMap = new Map(\n teamSources.map(source => [encodeTeamSourceId(source.workspace.linearWorkspaceId, source.team.id), source]),\n );\n\n type Descriptor = {\n kind: 'project' | 'team';\n sourceId: string;\n workspace: LinearWorkspace;\n query: URLSearchParams;\n };\n const descriptors: Descriptor[] = [];\n const selectedProjectIdsByWorkspace = new Map<string, Set<string>>();\n for (const attributionSourceId of attributionSourceIds) {\n const source = parseSourceId(attributionSourceId);\n if (source.kind !== 'project') continue;\n const selectedProjectIds = selectedProjectIdsByWorkspace.get(source.workspaceId) ?? new Set<string>();\n selectedProjectIds.add(source.projectId);\n selectedProjectIdsByWorkspace.set(source.workspaceId, selectedProjectIds);\n }\n for (const sourceId of sourceIds) {\n const projectSource = projectMap.get(sourceId);\n if (projectSource) {\n const query = new URLSearchParams({\n first: String(PAGE_SIZE),\n projectIds: projectSource.project.id,\n stateType: 'triage,backlog,unstarted,started',\n orderBy: 'updatedAt',\n });\n const workspaceId = projectSource.workspace.linearWorkspaceId;\n const selectedProjectIds = selectedProjectIdsByWorkspace.get(workspaceId) ?? new Set<string>();\n selectedProjectIds.add(projectSource.project.id);\n selectedProjectIdsByWorkspace.set(workspaceId, selectedProjectIds);\n descriptors.push({ kind: 'project', sourceId, workspace: projectSource.workspace, query });\n continue;\n }\n const teamSource = teamMap.get(sourceId);\n if (teamSource) {\n const query = new URLSearchParams({\n first: String(PAGE_SIZE),\n teamId: teamSource.team.id,\n stateType: 'triage,backlog,unstarted,started',\n orderBy: 'updatedAt',\n });\n descriptors.push({ kind: 'team', sourceId, workspace: teamSource.workspace, query });\n }\n }\n\n const cursors = await decodeCursor(cursor, sourceIds, attributionSourceIds);\n const unfinished = descriptors.filter(({ sourceId }) => cursors[sourceId] !== null);\n const normalizedLabels = normalizeLabels(labels);\n const nextState: Record<string, string | null> = {};\n let hasNextPage = false;\n const pages = await Promise.allSettled(\n unfinished.map(async ({ kind, sourceId, workspace, query }) => {\n const after = cursors[sourceId];\n if (after) query.set('after', after);\n const result = await this.#client.request<{ issues: LinearIssue[]; pageInfo: PageInfo }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspace.linearWorkspaceId)}/issues?${query}`,\n );\n const next = result.pageInfo.hasNextPage ? result.pageInfo.endCursor : null;\n // A page that hands back the cursor it was asked for would replay forever.\n if (next !== null && next === after) throw invalidLinearCursor();\n nextState[sourceId] = next;\n hasNextPage ||= next !== null;\n return result.issues\n .filter(\n issue => normalizedLabels.length === 0 || issue.labels.some(label => normalizedLabels.includes(label.name)),\n )\n .filter(\n issue =>\n kind === 'project' ||\n issue.project === null ||\n !selectedProjectIdsByWorkspace.get(workspace.linearWorkspaceId)?.has(issue.project.id),\n )\n .map(issue => ({ issue, sourceId, workspace }));\n }),\n );\n return {\n // A failed workspace is retried from the start on the next intake poll;\n // successful workspaces can finish their own pagination in this cycle.\n issues: dedupeIssuesBySource(\n collectWorkspaceListings(\n unfinished.map(source => source.workspace),\n pages,\n ),\n sourceIds,\n ),\n nextCursor: hasNextPage ? await encodeCursor(nextState, sourceIds, attributionSourceIds) : null,\n };\n }\n\n async #findIssue(\n sourceId: string | undefined,\n issueId: string,\n sourceIds?: string[],\n routedSourceIds?: string[],\n ): Promise<{\n workspaceId: string;\n issue: LinearIssue & { comments?: { nodes: LinearComment[]; pageInfo: PageInfo } };\n } | null> {\n const scopedSourceIds = sourceIds ?? (sourceId ? [sourceId] : undefined);\n const scopedSources = scopedSourceIds?.map(sourceKey => ({\n sourceKey,\n source: parseSourceId(sourceKey),\n }));\n const routedSourceSet = routedSourceIds ? new Set(routedSourceIds) : undefined;\n const workspaceIds = routedSourceIds\n ? [...new Set(routedSourceIds.map(sourceKey => parseSourceId(sourceKey).workspaceId))]\n : scopedSources\n ? [...new Set(scopedSources.map(({ source }) => source.workspaceId))]\n : await this.#candidateWorkspaceIds(undefined);\n for (const workspaceId of workspaceIds) {\n try {\n const issue = await this.#client.request<\n LinearIssue & { comments?: { nodes: LinearComment[]; pageInfo: PageInfo } }\n >(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/issues/${encodeURIComponent(issueId)}?include=comments`,\n );\n if (scopedSources) {\n const matching = scopedSources.filter(\n ({ source }) =>\n source.workspaceId === workspaceId &&\n (source.kind === 'team' ? issue.team.id === source.teamId : issue.project?.id === source.projectId),\n );\n const winner = matching.find(({ source }) => source.kind === 'project') ?? matching[0];\n if (!winner || (routedSourceSet && !routedSourceSet.has(winner.sourceKey))) continue;\n }\n return { workspaceId, issue };\n } catch (error) {\n if (!isNotFound(error)) throw error;\n }\n }\n return null;\n }\n\n async #resolveWorkspaceForIssue(sourceId: string | undefined, issueId: string): Promise<string | null> {\n const workspaceIds = await this.#candidateWorkspaceIds(sourceId);\n if (workspaceIds.length === 1) return workspaceIds[0]!;\n for (const workspaceId of workspaceIds) {\n try {\n await this.#client.request<LinearIssue>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/issues/${encodeURIComponent(issueId)}`,\n );\n return workspaceId;\n } catch (error) {\n if (!isNotFound(error)) throw error;\n }\n }\n return null;\n }\n\n async #listWorkflowStates(workspaceId: string, teamId: string): Promise<LinearWorkflowState[]> {\n const cacheKey = `${workspaceId}:${teamId}`;\n const cached = this.#workflowStatesByTeam.get(cacheKey);\n if (cached) return cached;\n const result = await this.#client.request<{ workflowStates: LinearWorkflowState[]; pageInfo: PageInfo }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/workflow-states?teamId=${encodeURIComponent(teamId)}&first=100`,\n );\n this.#workflowStatesByTeam.set(cacheKey, result.workflowStates);\n return result.workflowStates;\n }\n\n async #candidateWorkspaceIds(sourceId: string | undefined): Promise<string[]> {\n if (sourceId) return [parseSourceId(sourceId).workspaceId];\n return (await this.#listWorkspaces()).map(workspace => workspace.linearWorkspaceId);\n }\n\n async #loadComments(\n workspaceId: string,\n issueId: string,\n embedded: { nodes: LinearComment[]; pageInfo: PageInfo } | undefined,\n ): Promise<LinearComment[]> {\n const comments = [...(embedded?.nodes ?? [])];\n let pageInfo = embedded?.pageInfo;\n let page = 0;\n while (pageInfo?.hasNextPage && pageInfo.endCursor && page < MAX_COMMENT_PAGES) {\n const result = await this.#client.request<{ comments: LinearComment[]; pageInfo: PageInfo }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(workspaceId)}/issues/${encodeURIComponent(issueId)}/comments?first=200&after=${encodeURIComponent(pageInfo.endCursor)}`,\n );\n comments.push(...result.comments);\n if (result.pageInfo.hasNextPage && result.pageInfo.endCursor === pageInfo.endCursor) throw invalidLinearCursor();\n pageInfo = result.pageInfo;\n page += 1;\n }\n return comments;\n }\n}\n\nfunction parseIssue(issue: LinearIssue, workspaceId: string): IntakeIssue {\n return {\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.creator?.displayName ?? issue.creator?.name ?? null,\n state: issue.state.name,\n stateType: issue.state.type,\n priority: issue.priorityLabel,\n assignee: issue.assignee?.displayName ?? issue.assignee?.name ?? null,\n source: issue.team.key,\n // Use the same workspace-scoped identity as listProjects and intake bindings.\n // The source may be a team, so it cannot stand in for the issue's project.\n projectId: issue.project ? encodeSourceId(workspaceId, issue.project.id) : null,\n labels: issue.labels.map(label => label.name),\n commentCount: null,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\nfunction parseIssueDetail(issue: LinearIssue, comments: LinearComment[], workspaceId: string): IntakeIssueDetail {\n return {\n ...parseIssue(issue, workspaceId),\n commentCount: comments.length,\n description: issue.description?.trim() ? issue.description : null,\n comments: comments.map(comment => ({\n author: comment.user?.displayName ?? comment.user?.name ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n })),\n };\n}\n\n/**\n * Deduplicate issues that surfaced from more than one selected source (a team\n * source and one of its projects both select the same issue). Keeps one entry\n * per Linear issue UUID.\n *\n * Tie-breaker — MOST-SPECIFIC-WINS: a project source beats a team source, so an\n * issue that belongs to a selected project is attributed to that project's\n * source (and therefore routes to the project's board). The team source covers\n * only the remainder — projectless issues and issues in projects that were not\n * separately selected. `selectionOrder` breaks a same-kind tie deterministically\n * by the order the sources were selected.\n *\n * This function is the single precedence point; change the comparison here to\n * change the routing policy.\n */\nfunction dedupeIssuesBySource<T extends { issue: { id: string }; sourceId: string }>(\n entries: T[],\n selectionOrder: string[],\n): T[] {\n const rank = new Map(selectionOrder.map((id, index) => [id, index]));\n const specificity = (sourceId: string): number => (parseSourceId(sourceId).kind === 'project' ? 0 : 1);\n const winners = new Map<string, T>();\n for (const entry of entries) {\n const existing = winners.get(entry.issue.id);\n if (!existing) {\n winners.set(entry.issue.id, entry);\n continue;\n }\n const bySpecificity = specificity(entry.sourceId) - specificity(existing.sourceId);\n const better =\n bySpecificity < 0 ||\n (bySpecificity === 0 &&\n (rank.get(entry.sourceId) ?? Number.MAX_SAFE_INTEGER) <\n (rank.get(existing.sourceId) ?? Number.MAX_SAFE_INTEGER));\n if (better) winners.set(entry.issue.id, entry);\n }\n // Preserve first-seen order of the surviving issues.\n const seen = new Set<string>();\n const ordered: T[] = [];\n for (const entry of entries) {\n if (seen.has(entry.issue.id)) continue;\n seen.add(entry.issue.id);\n ordered.push(winners.get(entry.issue.id)!);\n }\n return ordered;\n}\n\nexport function encodeSourceId(workspaceId: string, projectId: string): string {\n return `linear-project:${Buffer.from(JSON.stringify({ workspaceId, projectId })).toString('base64url')}`;\n}\n\nfunction decodeSourceId(sourceId: string): { workspaceId: string; projectId: string } {\n if (!sourceId.startsWith('linear-project:')) throw new Error('Linear project source id is invalid.');\n try {\n const parsed = JSON.parse(Buffer.from(sourceId.slice('linear-project:'.length), 'base64url').toString('utf8')) as {\n workspaceId?: unknown;\n projectId?: unknown;\n };\n if (typeof parsed.workspaceId !== 'string' || !parsed.workspaceId) throw new Error();\n if (typeof parsed.projectId !== 'string' || !parsed.projectId) throw new Error();\n return { workspaceId: parsed.workspaceId, projectId: parsed.projectId };\n } catch {\n throw new Error('Linear project source id is invalid.');\n }\n}\n\nconst TEAM_SOURCE_PREFIX = 'linear-team:';\n\nexport function encodeTeamSourceId(workspaceId: string, teamId: string): string {\n return `${TEAM_SOURCE_PREFIX}${Buffer.from(JSON.stringify({ workspaceId, teamId })).toString('base64url')}`;\n}\n\nexport function decodeTeamSourceId(sourceId: string): { workspaceId: string; teamId: string } {\n if (!sourceId.startsWith(TEAM_SOURCE_PREFIX)) throw new Error('Linear team source id is invalid.');\n try {\n const parsed = JSON.parse(Buffer.from(sourceId.slice(TEAM_SOURCE_PREFIX.length), 'base64url').toString('utf8')) as {\n workspaceId?: unknown;\n teamId?: unknown;\n };\n if (typeof parsed.workspaceId !== 'string' || !parsed.workspaceId) throw new Error();\n if (typeof parsed.teamId !== 'string' || !parsed.teamId) throw new Error();\n return { workspaceId: parsed.workspaceId, teamId: parsed.teamId };\n } catch {\n throw new Error('Linear team source id is invalid.');\n }\n}\n\n/**\n * A decoded intake source: either a Linear project or a whole Linear team.\n * Downstream code discriminates on `kind` to build the right issue-listing\n * filter and to apply most-specific-wins routing (project beats team).\n */\nexport type DecodedSource =\n { kind: 'project'; workspaceId: string; projectId: string } | { kind: 'team'; workspaceId: string; teamId: string };\n\n/** Discriminate any Linear source id by its prefix and decode it. */\nexport function parseSourceId(sourceId: string): DecodedSource {\n if (sourceId.startsWith(TEAM_SOURCE_PREFIX)) {\n return { kind: 'team', ...decodeTeamSourceId(sourceId) };\n }\n return { kind: 'project', ...decodeSourceId(sourceId) };\n}\n\nfunction normalizeLabels(labels: string[] | undefined): string[] {\n return [...new Set((labels ?? []).map(label => label.trim()).filter(Boolean))];\n}\n\ntype PlatformListCursor = { v: 1; sourceSet: string; cursors: Array<string | null> };\n\nfunction canonicalSourceIds(sourceIds: string[]): string[] {\n return [...new Set(sourceIds)].sort();\n}\n\nasync function linearSourceSetFingerprint(sourceIds: string[], attributionSourceIds: string[]): Promise<string> {\n const scope = {\n sourceIds: canonicalSourceIds(sourceIds),\n attributionSourceIds: canonicalSourceIds(attributionSourceIds),\n };\n const bytes = new TextEncoder().encode(JSON.stringify(scope));\n return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', bytes)).toString('base64url');\n}\n\nfunction invalidLinearCursor(): Error {\n return Object.assign(new Error('Linear cursor is invalid or stale.'), { code: 'invalid_cursor' as const });\n}\n\nasync function decodeCursor(\n cursor: string | undefined,\n sourceIds: string[],\n attributionSourceIds: string[],\n): Promise<Record<string, string | null | undefined>> {\n if (!cursor) return {};\n try {\n const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as Partial<PlatformListCursor>;\n const canonical = canonicalSourceIds(sourceIds);\n if (\n parsed.v !== 1 ||\n parsed.sourceSet !== (await linearSourceSetFingerprint(sourceIds, attributionSourceIds)) ||\n !Array.isArray(parsed.cursors) ||\n parsed.cursors.length !== canonical.length ||\n !parsed.cursors.every(value => value === null || typeof value === 'string')\n ) {\n throw invalidLinearCursor();\n }\n return Object.fromEntries(canonical.map((sourceId, index) => [sourceId, parsed.cursors![index]]));\n } catch {\n throw invalidLinearCursor();\n }\n}\n\nasync function encodeCursor(\n state: Record<string, string | null>,\n sourceIds: string[],\n attributionSourceIds: string[],\n): Promise<string> {\n const canonical = canonicalSourceIds(sourceIds);\n const cursor: PlatformListCursor = {\n v: 1,\n sourceSet: await linearSourceSetFingerprint(sourceIds, attributionSourceIds),\n cursors: canonical.map(sourceId => state[sourceId] ?? null),\n };\n return Buffer.from(JSON.stringify(cursor)).toString('base64url');\n}\n\nfunction requireLinearConnection(connection: IntegrationConnection): void {\n if (connection.type !== 'oauth') {\n throw new Error('Linear capabilities require an OAuth connection.');\n }\n}\n\nfunction isNotFound(error: unknown): boolean {\n return error instanceof PlatformApiError && error.status === 404;\n}\n\n/** A provider outage in one workspace must not hide sources from the others. */\nfunction collectWorkspaceListings<T>(\n workspaces: LinearWorkspace[],\n results: PromiseSettledResult<T[]>[],\n errors?: LinearWorkspaceListingError[],\n): T[] {\n const items: T[] = [];\n let firstFailure: unknown;\n let succeeded = false;\n for (const [index, result] of results.entries()) {\n if (result.status === 'fulfilled') {\n succeeded = true;\n items.push(...result.value);\n continue;\n }\n const workspace = workspaces[index]!;\n firstFailure ??= result.reason;\n errors?.push({ workspaceId: workspace.linearWorkspaceId, name: workspace.linearWorkspaceName });\n logPlatformWarn('Platform Linear workspace sources could not be loaded; intake will retry.', {\n workspaceId: workspace.linearWorkspaceId,\n });\n }\n if (!succeeded && firstFailure) throw firstFailure;\n return items;\n}\n\nconst LOCAL_RETURN_ORIGIN = 'https://factory.invalid';\n\nfunction localPath(url: URL): string {\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\n/** OAuth may only return to a path on this Factory host. */\nfunction localReturnUrl(value: string | undefined): URL {\n const url = value?.startsWith('/') ? URL.parse(value, LOCAL_RETURN_ORIGIN) : null;\n // Dot segments can normalize `/.//host` into a protocol-relative `//host`.\n if (url?.origin === LOCAL_RETURN_ORIGIN && !url.pathname.startsWith('//')) return url;\n return new URL('/', LOCAL_RETURN_ORIGIN);\n}\n\nfunction optionalPositiveIntegerEnv(name: string): number | undefined {\n const value = process.env[name]?.trim();\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new Error(`${name} must be a positive integer.`);\n }\n return parsed;\n}\n"],"mappings":";;;;;;;;;;;AA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SACA,QACK;CACL,MAAM,QAAa,CAAC;CACpB,IAAI;CACJ,IAAI,YAAY;CAChB,KAAK,MAAM,CAAC,OAAO,WAAW,QAAQ,QAAQ,GAAG;EAC/C,IAAI,OAAO,WAAW,aAAa;GACjC,YAAY;GACZ,MAAM,KAAK,GAAG,OAAO,KAAK;GAC1B;EACF;EACA,MAAM,YAAY,WAAW;EAC7B,iBAAiB,OAAO;EACxB,QAAQ,KAAK;GAAE,aAAa,UAAU;GAAmB,MAAM,UAAU;EAAoB,CAAC;EAC9F,gBAAgB,6EAA6E,EAC3F,aAAa,UAAU,kBACzB,CAAC;CACH;CACA,IAAI,CAAC,aAAa,cAAc,MAAM;CACtC,OAAO;AACT;AAEA,MAAM,sBAAsB;AAE5B,SAAS,UAAU,KAAkB;CACnC,OAAO,GAAG,IAAI,WAAW,IAAI,SAAS,IAAI;AAC5C;;AAGA,SAAS,eAAe,OAAgC;CACtD,MAAM,MAAM,OAAO,WAAW,GAAG,IAAI,IAAI,MAAM,OAAO,mBAAmB,IAAI;CAE7E,IAAI,KAAK,WAAW,uBAAuB,CAAC,IAAI,SAAS,WAAW,IAAI,GAAG,OAAO;CAClF,OAAO,IAAI,IAAI,KAAK,mBAAmB;AACzC;AAEA,SAAS,2BAA2B,MAAkC;CACpE,MAAM,QAAQ,QAAQ,IAAI,KAAK,EAAE,KAAK;CACtC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,SAAS,OAAO,KAAK;CAC3B,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,UAAU,GAC7C,MAAM,IAAI,MAAM,GAAG,KAAK,6BAA6B;CAEvD,OAAO;AACT"}
@@ -35,4 +35,6 @@ export interface SessionLinkTarget {
35
35
  */
36
36
  export declare function sessionLink({ threadId, sessionId, resourceId, factoryProjectId, }: SessionLinkTarget): string | undefined;
37
37
  export declare function modelSettingsLink(factoryProjectId: string): string | undefined;
38
+ /** `VOICE_INPUT_ANCHOR` in factory-ui's `settingsSections.ts`; the voice section scrolls itself into view on this hash. */
39
+ export declare function voiceSettingsLink(factoryProjectId: string): string | undefined;
38
40
  //# sourceMappingURL=channel-reply-processor.d.ts.map
@@ -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"}
@@ -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,E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A2E;IAC3E,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AA0BD;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE;IAC7C,IAAI,EAAE,SAAS,CAAC;IAChB,YAAY,EAAE,sBAAsB,CAAC;IACrC,+EAA+E;IAC/E,iBAAiB,CAAC,EAAE,WAAW,CAAC;IAChC,IAAI,CAAC,EAAE,eAAe,CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,EAAE,sBAAsB,CAAC;CACnC,GAAG,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,I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,yCAAyC;GACxD,QAAQ;GACR,cAAc;GACd,SAAS,OAAM,MAAK;IAClB,MAAM,KAAK,WAAW,MAAM,CAAC,CAAC;IAC9B,MAAM,SAAS,KAAK,OAAO,MAAM,CAAC,CAAC;IACnC,IAAI,CAAC,QAAQ,OAAO,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG;IAEzD,MAAM,OAAQ,MAAM,EAAE,IAAI,KAAK,CAAC,CAAC,YAAY,IAAI;IAMjD,IAAI,CAAC,MAAM,YAAY,CAAC,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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UlG;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"}
@@ -168,6 +168,8 @@ var SlackIntegration = class {
168
168
  projects: ctx.storage.projects,
169
169
  sourceControls,
170
170
  modelDefaults: ctx.storage.modelDefaults,
171
+ modelCredentials: ctx.storage.modelCredentials,
172
+ voiceSettings: ctx.storage.voiceSettings,
171
173
  workItems: ctx.runtime?.workItems,
172
174
  feed: ctx.feed,
173
175
  adapterOptions: this.#adapterOptions