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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/README.md +172 -89
  2. package/dist/boards/board-events.d.ts +89 -9
  3. package/dist/boards/board-events.d.ts.map +1 -1
  4. package/dist/boards/board-events.js +176 -13
  5. package/dist/boards/board-events.js.map +1 -1
  6. package/dist/boards/board-writes.d.ts.map +1 -1
  7. package/dist/boards/board-writes.js +14 -1
  8. package/dist/boards/board-writes.js.map +1 -1
  9. package/dist/boards/busy-card.d.ts +11 -0
  10. package/dist/boards/busy-card.d.ts.map +1 -0
  11. package/dist/boards/busy-card.js +15 -0
  12. package/dist/boards/busy-card.js.map +1 -0
  13. package/dist/boards/card-facts.d.ts.map +1 -1
  14. package/dist/boards/card-facts.js +18 -4
  15. package/dist/boards/card-facts.js.map +1 -1
  16. package/dist/boards/index.d.ts +2 -1
  17. package/dist/boards/index.d.ts.map +1 -1
  18. package/dist/boards/index.js +3 -2
  19. package/dist/boards/intake-dry-run.d.ts +109 -0
  20. package/dist/boards/intake-dry-run.d.ts.map +1 -0
  21. package/dist/boards/intake-dry-run.js +158 -0
  22. package/dist/boards/intake-dry-run.js.map +1 -0
  23. package/dist/boards/intake-lookup.d.ts +32 -0
  24. package/dist/boards/intake-lookup.d.ts.map +1 -0
  25. package/dist/boards/intake-lookup.js +12 -0
  26. package/dist/boards/intake-lookup.js.map +1 -0
  27. package/dist/boards/intake-order.d.ts +32 -0
  28. package/dist/boards/intake-order.d.ts.map +1 -0
  29. package/dist/boards/intake-order.js +60 -0
  30. package/dist/boards/intake-order.js.map +1 -0
  31. package/dist/boards/intake-routing.d.ts +246 -35
  32. package/dist/boards/intake-routing.d.ts.map +1 -1
  33. package/dist/boards/intake-routing.js +437 -52
  34. package/dist/boards/intake-routing.js.map +1 -1
  35. package/dist/boards/reroute.d.ts +7 -3
  36. package/dist/boards/reroute.d.ts.map +1 -1
  37. package/dist/boards/reroute.js +21 -4
  38. package/dist/boards/reroute.js.map +1 -1
  39. package/dist/boards/semantics.d.ts +8 -28
  40. package/dist/boards/semantics.d.ts.map +1 -1
  41. package/dist/boards/semantics.js +14 -40
  42. package/dist/boards/semantics.js.map +1 -1
  43. package/dist/boards/work-routes.d.ts +31 -11
  44. package/dist/boards/work-routes.d.ts.map +1 -1
  45. package/dist/boards/work-routes.js +104 -20
  46. package/dist/boards/work-routes.js.map +1 -1
  47. package/dist/factory.d.ts +37 -1
  48. package/dist/factory.d.ts.map +1 -1
  49. package/dist/factory.js +127 -48
  50. package/dist/factory.js.map +1 -1
  51. package/dist/integrations/base.d.ts +9 -0
  52. package/dist/integrations/base.d.ts.map +1 -1
  53. package/dist/integrations/dependabot/rules.js +1 -1
  54. package/dist/integrations/dependabot/rules.js.map +1 -1
  55. package/dist/integrations/github/default-rules.d.ts +22 -1
  56. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  57. package/dist/integrations/github/default-rules.js +23 -5
  58. package/dist/integrations/github/default-rules.js.map +1 -1
  59. package/dist/integrations/github/intake-lookup.d.ts +16 -0
  60. package/dist/integrations/github/intake-lookup.d.ts.map +1 -0
  61. package/dist/integrations/github/intake-lookup.js +76 -0
  62. package/dist/integrations/github/intake-lookup.js.map +1 -0
  63. package/dist/integrations/github/integration.d.ts +19 -5
  64. package/dist/integrations/github/integration.d.ts.map +1 -1
  65. package/dist/integrations/github/integration.js +21 -6
  66. package/dist/integrations/github/integration.js.map +1 -1
  67. package/dist/integrations/github/issue-intake.d.ts +15 -0
  68. package/dist/integrations/github/issue-intake.d.ts.map +1 -0
  69. package/dist/integrations/github/issue-intake.js +50 -0
  70. package/dist/integrations/github/issue-intake.js.map +1 -0
  71. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  72. package/dist/integrations/github/issue-reconciler.js +10 -1
  73. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  74. package/dist/integrations/github/review-status-reporter.js +1 -1
  75. package/dist/integrations/github/routes.d.ts.map +1 -1
  76. package/dist/integrations/github/routes.js +14 -2
  77. package/dist/integrations/github/routes.js.map +1 -1
  78. package/dist/integrations/github/rules.d.ts +14 -1
  79. package/dist/integrations/github/rules.d.ts.map +1 -1
  80. package/dist/integrations/github/rules.js +221 -30
  81. package/dist/integrations/github/rules.js.map +1 -1
  82. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  83. package/dist/integrations/github/sandbox.js +30 -4
  84. package/dist/integrations/github/sandbox.js.map +1 -1
  85. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  86. package/dist/integrations/gitlab/default-rules.js +19 -3
  87. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  88. package/dist/integrations/gitlab/intake-lookup.d.ts +17 -0
  89. package/dist/integrations/gitlab/intake-lookup.d.ts.map +1 -0
  90. package/dist/integrations/gitlab/intake-lookup.js +85 -0
  91. package/dist/integrations/gitlab/intake-lookup.js.map +1 -0
  92. package/dist/integrations/gitlab/integration.d.ts +5 -0
  93. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  94. package/dist/integrations/gitlab/integration.js +21 -1
  95. package/dist/integrations/gitlab/integration.js.map +1 -1
  96. package/dist/integrations/gitlab/rules.d.ts +20 -0
  97. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  98. package/dist/integrations/gitlab/rules.js +108 -12
  99. package/dist/integrations/gitlab/rules.js.map +1 -1
  100. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  101. package/dist/integrations/incidentio/rules.js +14 -4
  102. package/dist/integrations/incidentio/rules.js.map +1 -1
  103. package/dist/integrations/jira/rules.d.ts.map +1 -1
  104. package/dist/integrations/jira/rules.js +12 -2
  105. package/dist/integrations/jira/rules.js.map +1 -1
  106. package/dist/integrations/linear/rules.d.ts.map +1 -1
  107. package/dist/integrations/linear/rules.js +13 -2
  108. package/dist/integrations/linear/rules.js.map +1 -1
  109. package/dist/integrations/platform/connect/routes.d.ts +43 -1
  110. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  111. package/dist/integrations/platform/connect/routes.js +82 -7
  112. package/dist/integrations/platform/connect/routes.js.map +1 -1
  113. package/dist/integrations/platform/connect/session-tools.d.ts +12 -0
  114. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -1
  115. package/dist/integrations/platform/connect/session-tools.js +28 -10
  116. package/dist/integrations/platform/connect/session-tools.js.map +1 -1
  117. package/dist/integrations/platform/github/event-worker.js +9 -1
  118. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  119. package/dist/integrations/platform/github/integration.d.ts +6 -6
  120. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  121. package/dist/integrations/platform/github/integration.js +22 -3
  122. package/dist/integrations/platform/github/integration.js.map +1 -1
  123. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
  124. package/dist/integrations/platform/vanta/integration.js +3 -3
  125. package/dist/integrations/platform/vanta/integration.js.map +1 -1
  126. package/dist/integrations/pull-request-head.d.ts +1 -1
  127. package/dist/integrations/pull-request-head.d.ts.map +1 -1
  128. package/dist/integrations/pull-request-head.js +5 -0
  129. package/dist/integrations/pull-request-head.js.map +1 -1
  130. package/dist/integrations/vanta/rules.js +1 -1
  131. package/dist/integrations/vanta/rules.js.map +1 -1
  132. package/dist/integrations/vanta/sync.d.ts +9 -0
  133. package/dist/integrations/vanta/sync.d.ts.map +1 -1
  134. package/dist/integrations/vanta/sync.js +10 -1
  135. package/dist/integrations/vanta/sync.js.map +1 -1
  136. package/dist/routes/board-snapshot.d.ts +13 -6
  137. package/dist/routes/board-snapshot.d.ts.map +1 -1
  138. package/dist/routes/board-snapshot.js +42 -20
  139. package/dist/routes/board-snapshot.js.map +1 -1
  140. package/dist/routes/boards.js.map +1 -1
  141. package/dist/routes/config.d.ts +17 -2
  142. package/dist/routes/config.d.ts.map +1 -1
  143. package/dist/routes/config.js +247 -77
  144. package/dist/routes/config.js.map +1 -1
  145. package/dist/routes/contracts.d.ts +1294 -7
  146. package/dist/routes/contracts.d.ts.map +1 -1
  147. package/dist/routes/contracts.js +603 -20
  148. package/dist/routes/contracts.js.map +1 -1
  149. package/dist/routes/custom-endpoint-url.d.ts +8 -0
  150. package/dist/routes/custom-endpoint-url.d.ts.map +1 -0
  151. package/dist/routes/custom-endpoint-url.js +45 -0
  152. package/dist/routes/custom-endpoint-url.js.map +1 -0
  153. package/dist/routes/custom-provider-source.d.ts +24 -8
  154. package/dist/routes/custom-provider-source.d.ts.map +1 -1
  155. package/dist/routes/custom-provider-source.js +93 -43
  156. package/dist/routes/custom-provider-source.js.map +1 -1
  157. package/dist/routes/intake-check.d.ts +92 -0
  158. package/dist/routes/intake-check.d.ts.map +1 -0
  159. package/dist/routes/intake-check.js +322 -0
  160. package/dist/routes/intake-check.js.map +1 -0
  161. package/dist/routes/intake-routes.d.ts +10 -2
  162. package/dist/routes/intake-routes.d.ts.map +1 -1
  163. package/dist/routes/intake-routes.js +292 -11
  164. package/dist/routes/intake-routes.js.map +1 -1
  165. package/dist/routes/intake.d.ts +6 -0
  166. package/dist/routes/intake.d.ts.map +1 -1
  167. package/dist/routes/intake.js +20 -0
  168. package/dist/routes/intake.js.map +1 -1
  169. package/dist/routes/mastra-gateway.d.ts.map +1 -1
  170. package/dist/routes/mastra-gateway.js +3 -2
  171. package/dist/routes/mastra-gateway.js.map +1 -1
  172. package/dist/routes/project-sessions.d.ts +61 -0
  173. package/dist/routes/project-sessions.d.ts.map +1 -0
  174. package/dist/routes/project-sessions.js +135 -0
  175. package/dist/routes/project-sessions.js.map +1 -0
  176. package/dist/routes/projects.d.ts +6 -1
  177. package/dist/routes/projects.d.ts.map +1 -1
  178. package/dist/routes/projects.js +19 -3
  179. package/dist/routes/projects.js.map +1 -1
  180. package/dist/routes/provider-credentials.d.ts +10 -1
  181. package/dist/routes/provider-credentials.d.ts.map +1 -1
  182. package/dist/routes/provider-credentials.js +13 -16
  183. package/dist/routes/provider-credentials.js.map +1 -1
  184. package/dist/routes/run-queue.d.ts +6 -6
  185. package/dist/routes/run-queue.d.ts.map +1 -1
  186. package/dist/routes/run-queue.js +28 -8
  187. package/dist/routes/run-queue.js.map +1 -1
  188. package/dist/routes/session-rows.d.ts +30 -0
  189. package/dist/routes/session-rows.d.ts.map +1 -0
  190. package/dist/routes/session-rows.js +94 -0
  191. package/dist/routes/session-rows.js.map +1 -0
  192. package/dist/routes/source-control-sessions.d.ts +4 -5
  193. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  194. package/dist/routes/source-control-sessions.js +8 -87
  195. package/dist/routes/source-control-sessions.js.map +1 -1
  196. package/dist/routes/surface.d.ts +16 -1
  197. package/dist/routes/surface.d.ts.map +1 -1
  198. package/dist/routes/surface.js +41 -30
  199. package/dist/routes/surface.js.map +1 -1
  200. package/dist/routes/tenant-credentials.d.ts.map +1 -1
  201. package/dist/routes/tenant-credentials.js +4 -4
  202. package/dist/routes/tenant-credentials.js.map +1 -1
  203. package/dist/routes/work-item-starters.d.ts +1 -0
  204. package/dist/routes/work-item-starters.d.ts.map +1 -1
  205. package/dist/routes/work-item-starters.js +14 -2
  206. package/dist/routes/work-item-starters.js.map +1 -1
  207. package/dist/routes/work-items.d.ts +22 -3
  208. package/dist/routes/work-items.d.ts.map +1 -1
  209. package/dist/routes/work-items.js +124 -48
  210. package/dist/routes/work-items.js.map +1 -1
  211. package/dist/rules/binding-context.d.ts +5 -0
  212. package/dist/rules/binding-context.d.ts.map +1 -1
  213. package/dist/rules/binding-context.js +51 -5
  214. package/dist/rules/binding-context.js.map +1 -1
  215. package/dist/rules/dispatch-errors.js +1 -1
  216. package/dist/rules/dispatch-errors.js.map +1 -1
  217. package/dist/rules/dispatcher.d.ts +39 -7
  218. package/dist/rules/dispatcher.d.ts.map +1 -1
  219. package/dist/rules/dispatcher.js +363 -123
  220. package/dist/rules/dispatcher.js.map +1 -1
  221. package/dist/rules/event-rules.d.ts +69 -1
  222. package/dist/rules/event-rules.d.ts.map +1 -1
  223. package/dist/rules/event-rules.js +151 -5
  224. package/dist/rules/event-rules.js.map +1 -1
  225. package/dist/rules/review-source-tool.js +1 -1
  226. package/dist/rules/rule-group.d.ts +18 -1
  227. package/dist/rules/rule-group.d.ts.map +1 -1
  228. package/dist/rules/rule-group.js +52 -8
  229. package/dist/rules/rule-group.js.map +1 -1
  230. package/dist/rules/run-bearing.d.ts +8 -0
  231. package/dist/rules/run-bearing.d.ts.map +1 -0
  232. package/dist/rules/run-bearing.js +11 -0
  233. package/dist/rules/run-bearing.js.map +1 -0
  234. package/dist/rules/start-coordinator.d.ts +2 -3
  235. package/dist/rules/start-coordinator.d.ts.map +1 -1
  236. package/dist/rules/start-coordinator.js +25 -38
  237. package/dist/rules/start-coordinator.js.map +1 -1
  238. package/dist/rules/tools.js +2 -1
  239. package/dist/rules/tools.js.map +1 -1
  240. package/dist/rules/transition-service.d.ts +16 -0
  241. package/dist/rules/transition-service.d.ts.map +1 -1
  242. package/dist/rules/transition-service.js +34 -10
  243. package/dist/rules/transition-service.js.map +1 -1
  244. package/dist/rules/types.d.ts +18 -5
  245. package/dist/rules/types.d.ts.map +1 -1
  246. package/dist/rules/types.js +2 -1
  247. package/dist/rules/types.js.map +1 -1
  248. package/dist/rules/update-fold.d.ts +32 -0
  249. package/dist/rules/update-fold.d.ts.map +1 -0
  250. package/dist/rules/update-fold.js +60 -0
  251. package/dist/rules/update-fold.js.map +1 -0
  252. package/dist/rules/validation.d.ts.map +1 -1
  253. package/dist/rules/validation.js +54 -6
  254. package/dist/rules/validation.js.map +1 -1
  255. package/dist/sandbox/session-retirement.d.ts +6 -0
  256. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  257. package/dist/sandbox/session-retirement.js +17 -0
  258. package/dist/sandbox/session-retirement.js.map +1 -1
  259. package/dist/session/factory-session.d.ts.map +1 -1
  260. package/dist/session/factory-session.js +2 -1
  261. package/dist/session/factory-session.js.map +1 -1
  262. package/dist/session/live-sessions.d.ts +6 -1
  263. package/dist/session/live-sessions.d.ts.map +1 -1
  264. package/dist/session/live-sessions.js +4 -0
  265. package/dist/session/live-sessions.js.map +1 -1
  266. package/dist/session/resource-migration.d.ts.map +1 -1
  267. package/dist/session/resource-migration.js +2 -3
  268. package/dist/session/resource-migration.js.map +1 -1
  269. package/dist/session/run-audit.d.ts +10 -1
  270. package/dist/session/run-audit.d.ts.map +1 -1
  271. package/dist/session/run-audit.js +9 -1
  272. package/dist/session/run-audit.js.map +1 -1
  273. package/dist/session/self-review-gate.d.ts +26 -2
  274. package/dist/session/self-review-gate.d.ts.map +1 -1
  275. package/dist/session/self-review-gate.js +60 -10
  276. package/dist/session/self-review-gate.js.map +1 -1
  277. package/dist/session/session-row-query.d.ts +25 -0
  278. package/dist/session/session-row-query.d.ts.map +1 -0
  279. package/dist/session/session-row-query.js +47 -0
  280. package/dist/session/session-row-query.js.map +1 -0
  281. package/dist/session/session-row-status.d.ts +16 -0
  282. package/dist/session/session-row-status.d.ts.map +1 -0
  283. package/dist/session/session-row-status.js +14 -0
  284. package/dist/session/session-row-status.js.map +1 -0
  285. package/dist/session/session-row-view.d.ts +13 -0
  286. package/dist/session/session-row-view.d.ts.map +1 -0
  287. package/dist/session/session-row-view.js +118 -0
  288. package/dist/session/session-row-view.js.map +1 -0
  289. package/dist/session/session-rows.d.ts +60 -0
  290. package/dist/session/session-rows.d.ts.map +1 -0
  291. package/dist/session/session-rows.js +307 -0
  292. package/dist/session/session-rows.js.map +1 -0
  293. package/dist/session/session-threads.d.ts.map +1 -1
  294. package/dist/session/session-threads.js +1 -0
  295. package/dist/session/session-threads.js.map +1 -1
  296. package/dist/session/session-unloader.d.ts +101 -0
  297. package/dist/session/session-unloader.d.ts.map +1 -0
  298. package/dist/session/session-unloader.js +278 -0
  299. package/dist/session/session-unloader.js.map +1 -0
  300. package/dist/session/source-control-tools.d.ts +14 -7
  301. package/dist/session/source-control-tools.d.ts.map +1 -1
  302. package/dist/session/source-control-tools.js +10 -2
  303. package/dist/session/source-control-tools.js.map +1 -1
  304. package/dist/session/work-item-repository.d.ts +49 -1
  305. package/dist/session/work-item-repository.d.ts.map +1 -1
  306. package/dist/session/work-item-repository.js +118 -15
  307. package/dist/session/work-item-repository.js.map +1 -1
  308. package/dist/session/work-item-state-processor.d.ts.map +1 -1
  309. package/dist/session/work-item-state-processor.js +44 -8
  310. package/dist/session/work-item-state-processor.js.map +1 -1
  311. package/dist/session-list-changes.d.ts +9 -0
  312. package/dist/session-list-changes.d.ts.map +1 -0
  313. package/dist/session-list-changes.js +54 -0
  314. package/dist/session-list-changes.js.map +1 -0
  315. package/dist/storage/announced-lists.d.ts +14 -0
  316. package/dist/storage/announced-lists.d.ts.map +1 -0
  317. package/dist/storage/announced-lists.js +78 -0
  318. package/dist/storage/announced-lists.js.map +1 -0
  319. package/dist/storage/domains/audit/actions.d.ts +2 -1
  320. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  321. package/dist/storage/domains/audit/actions.js +3 -1
  322. package/dist/storage/domains/audit/actions.js.map +1 -1
  323. package/dist/storage/domains/boards/base.d.ts +163 -15
  324. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  325. package/dist/storage/domains/boards/base.js +440 -48
  326. package/dist/storage/domains/boards/base.js.map +1 -1
  327. package/dist/storage/domains/boards/schemas.d.ts +6 -0
  328. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  329. package/dist/storage/domains/boards/schemas.js +95 -1
  330. package/dist/storage/domains/boards/schemas.js.map +1 -1
  331. package/dist/storage/domains/custom-providers/base.d.ts +62 -19
  332. package/dist/storage/domains/custom-providers/base.d.ts.map +1 -1
  333. package/dist/storage/domains/custom-providers/base.js +131 -100
  334. package/dist/storage/domains/custom-providers/base.js.map +1 -1
  335. package/dist/storage/domains/intake/base.d.ts +25 -7
  336. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  337. package/dist/storage/domains/intake/base.js +83 -19
  338. package/dist/storage/domains/intake/base.js.map +1 -1
  339. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  340. package/dist/storage/domains/projects/base.js +19 -10
  341. package/dist/storage/domains/projects/base.js.map +1 -1
  342. package/dist/storage/domains/source-control/base.d.ts +8 -0
  343. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  344. package/dist/storage/domains/source-control/base.js +110 -61
  345. package/dist/storage/domains/source-control/base.js.map +1 -1
  346. package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
  347. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  348. package/dist/storage/domains/source-control/inmemory.js +8 -5
  349. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  350. package/dist/storage/domains/work-items/base.d.ts +57 -18
  351. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  352. package/dist/storage/domains/work-items/base.js +168 -83
  353. package/dist/storage/domains/work-items/base.js.map +1 -1
  354. package/dist/storage/domains/work-items/cards.d.ts +3 -2
  355. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  356. package/dist/storage/domains/work-items/cards.js +4 -2
  357. package/dist/storage/domains/work-items/cards.js.map +1 -1
  358. package/dist/tools/audit-events-tool.d.ts +2 -2
  359. package/dist/tools/read-tools.d.ts +9 -5
  360. package/dist/tools/read-tools.d.ts.map +1 -1
  361. package/dist/tools/read-tools.js +61 -54
  362. package/dist/tools/read-tools.js.map +1 -1
  363. package/dist/tools/session-tools.d.ts +0 -13
  364. package/dist/tools/session-tools.d.ts.map +1 -1
  365. package/dist/tools/session-tools.js +128 -341
  366. package/dist/tools/session-tools.js.map +1 -1
  367. package/dist/tools/work-item-tools.d.ts +3 -0
  368. package/dist/tools/work-item-tools.d.ts.map +1 -1
  369. package/dist/tools/work-item-tools.js +99 -27
  370. package/dist/tools/work-item-tools.js.map +1 -1
  371. package/dist/work-item-branch.d.ts +4 -0
  372. package/dist/work-item-branch.d.ts.map +1 -1
  373. package/dist/work-item-branch.js +7 -1
  374. package/dist/work-item-branch.js.map +1 -1
  375. package/dist/work-items/card-context-sessions.d.ts +50 -0
  376. package/dist/work-items/card-context-sessions.d.ts.map +1 -0
  377. package/dist/work-items/card-context-sessions.js +84 -0
  378. package/dist/work-items/card-context-sessions.js.map +1 -0
  379. package/dist/work-items/card-reference.d.ts +21 -0
  380. package/dist/work-items/card-reference.d.ts.map +1 -0
  381. package/dist/work-items/card-reference.js +58 -0
  382. package/dist/work-items/card-reference.js.map +1 -0
  383. package/dist/work-items/change-requests.d.ts +87 -0
  384. package/dist/work-items/change-requests.d.ts.map +1 -0
  385. package/dist/work-items/change-requests.js +134 -0
  386. package/dist/work-items/change-requests.js.map +1 -0
  387. package/dist/work-items/create-work-item.d.ts +7 -2
  388. package/dist/work-items/create-work-item.d.ts.map +1 -1
  389. package/dist/work-items/create-work-item.js +44 -13
  390. package/dist/work-items/create-work-item.js.map +1 -1
  391. package/dist/work-items/list-related-cards.d.ts.map +1 -1
  392. package/dist/work-items/list-related-cards.js +1 -1
  393. package/dist/work-items/list-related-cards.js.map +1 -1
  394. package/dist/work-items/providers/github.d.ts.map +1 -1
  395. package/dist/work-items/providers/github.js +1 -0
  396. package/dist/work-items/providers/github.js.map +1 -1
  397. package/factory-skills/factory-build/SKILL.md +1 -1
  398. package/factory-skills/factory-plan/SKILL.md +5 -3
  399. package/factory-skills/factory-self-review/SKILL.md +2 -0
  400. package/factory-skills/factory-triage/SKILL.md +1 -1
  401. package/package.json +10 -10
@@ -1 +1 @@
1
- {"version":3,"file":"session-tools.js","names":[],"sources":["../../src/tools/session-tools.ts"],"sourcesContent":["import { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport { boardForWorkItem } from '../boards/index.js';\nimport { workLaneForRole } from '../boards/legacy-plan-role.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factorySessionUrl, factoryWorkItemUrl } from '../links.js';\nimport { buildModelCatalog, listSessionScopedCredentials } from '../routes/config.js';\nimport { USER_SESSION_BRANCH_PREFIX } from '../routes/source-control-sessions.js';\nimport { primeTenantCredentialsForTenant } from '../routes/tenant-credentials.js';\nimport { FactoryStartTransitionError, WorkItemRepositoryError } from '../rules/start-coordinator.js';\nimport type { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { resolveFactoryModelPolicy } from '../session/credential-policy.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport {\n ensureFactorySourceSession,\n hydrateFactorySession,\n requireOrganizationModelKey,\n resolveFactorySessionModel,\n} from '../session/factory-session.js';\nimport { recordSessionRunStart } from '../session/run-audit.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope, factoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { workItemNumber } from '../work-items/card-number.js';\nimport { deliverFactorySessionNotification, resolveSessionThread } from './deliver.js';\nimport type { FactoryMessaging } from './messaging-tools.js';\nimport { findWorkItem, workItemNotFound, workItemRefSchema } from './read-tools.js';\nimport { heartbeatOpenRunUntilEnd } from './run-watch.js';\nimport type { FactoryToolScope } from './scope.js';\nimport { sessionModel } from './side-sessions.js';\n\nconst TITLE_LENGTH = 120;\n\n/** Who renews the open-run entries this process writes; one id per process, like the dispatcher's. */\nexport const FACTORY_TOOLS_OWNER_ID = `factory-tools:${globalThis.crypto.randomUUID()}`;\n\nexport interface FactorySessionToolDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId' | 'getSourceControlBySessionId'>;\n sessionModel: {\n projects: FactoryProjectsStorage;\n modelDefaults: ModelDefaultsStorage;\n /**\n * Tenant credential stores, present when auth is on. Model switches then\n * check the target session's credential scope, like the Settings picker;\n * without them the server's own keys decide.\n */\n tenantCatalog?: {\n credentials: Pick<ModelCredentialsStorage, 'listCredentials'>;\n customProviders?: Pick<CustomProvidersStorage, 'ensureReady' | 'list'>;\n deploymentProviders?: ReadonlySet<string>;\n };\n };\n /** Resolved lazily: the controller only exists once the mount is up. */\n messaging: () => Promise<FactoryMessaging | null>;\n workItems: Pick<\n WorkItemsStorage,\n | 'listShared'\n | 'getForProject'\n | 'listRunBindings'\n | 'findActiveRunBindingForSession'\n | 'findRunBindingByThread'\n | 'hasRunBindingForSession'\n | 'subscribeToWorkItem'\n | 'unsubscribeFromWorkItem'\n | 'listSessionSubscriptions'\n | 'listWorkItemSubscribers'\n >;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n auditRecorder: AuditRecorder;\n intake?: Pick<IntakeStorage, 'getConfig'>;\n /** The browser Start's coordinator; absent until the Factory runtime is ready. */\n startCoordinator: () => Pick<FactoryStartCoordinator, 'prepare'> | undefined;\n}\n\nconst LISTED_MODELS = 8;\n\nfunction ambiguousRepository(candidates: readonly string[]): string {\n return `This item has several repositories (${candidates.join(', ')}); v1 can't choose one.`;\n}\n\nfunction startErrorMessage(error: unknown): string | null {\n if (error instanceof WorkItemRepositoryError) {\n return error.code === 'repository_ambiguous' ? ambiguousRepository(error.candidates) : error.message;\n }\n if (error instanceof FactoryStartTransitionError) return `The start was refused: ${error.result.reason}`;\n return null;\n}\n\nfunction workItemLabel(item: Card): string {\n const number = workItemNumber(item);\n return number === null ? `\"${item.title}\"` : `#${number}`;\n}\n\nfunction titleFrom(prompt: string): string {\n const firstLine = prompt.split('\\n').find(line => line.trim()) ?? prompt;\n return firstLine.trim().slice(0, TITLE_LENGTH);\n}\n\n/** Tools that start sessions on the caller's behalf, or switch their models. User sessions only. */\nexport function createFactorySessionTools(\n scope: FactoryToolScope,\n deps: FactorySessionToolDependencies,\n): IntegrationTools {\n /** The models a session can switch to, resolved from the target session's owner and project policy. */\n async function sessionModelCatalog(\n controller: FactoryMessaging['controller'],\n sessionId: string,\n threadId: string,\n resourceId: string,\n ): Promise<{ usable: string[]; known: Set<string>; scopeLabel: string }> {\n const models = await controller.listAvailableModels();\n const known = new Set(models.flatMap(model => (typeof model.id === 'string' ? [model.id] : [])));\n const tenantCatalog = deps.sessionModel.tenantCatalog;\n if (!tenantCatalog) {\n const usable = (await buildModelCatalog({ controller })).map(model => model.id);\n return { usable, known, scopeLabel: 'server' };\n }\n const requestContext = new RequestContext();\n requestContext.set('user', { id: scope.userId, organizationId: scope.orgId });\n requestContext.set('controller', { sessionId, resourceId, threadId });\n const policy = await resolveFactoryModelPolicy(requestContext, {\n projects: deps.sessionModel.projects,\n sourceControl: deps.sessions,\n workItems: deps.workItems,\n });\n if (!policy) throw new Error('Session model policy is unavailable.');\n const modelScope = policy.tenant.credentialScope ?? 'user';\n const orgId = policy.tenant.orgId ?? scope.orgId;\n const customProviders = tenantCatalog.customProviders;\n const usable = (\n await buildModelCatalog({\n controller,\n tenantCredentials: await listSessionScopedCredentials({\n credentials: tenantCatalog.credentials,\n orgId,\n userId: policy.tenant.userId,\n modelScope,\n }),\n deploymentProviders: tenantCatalog.deploymentProviders,\n listCustomProviders: customProviders\n ? async () => {\n await customProviders.ensureReady();\n return customProviders.list({ orgId });\n }\n : undefined,\n })\n ).map(model => model.id);\n for (const id of usable) known.add(id);\n return { usable, known, scopeLabel: modelScope === 'factory' ? 'Factory' : 'session owner' };\n }\n\n function unrunnableModelError(\n modelId: string,\n catalog: { usable: string[]; known: Set<string>; scopeLabel: string },\n ) {\n const options = catalog.usable.length\n ? ` Models available to it: ${catalog.usable.slice(0, LISTED_MODELS).join(', ')}${catalog.usable.length > LISTED_MODELS ? ', …' : ''}.`\n : ' No models are available to it; connect a provider credential first.';\n return new Error(\n catalog.known.has(modelId)\n ? `Model ${modelId} exists, but this session's credential scope (${catalog.scopeLabel}) has no credential for its provider.${options}`\n : `Unknown model ${modelId}.${options}`,\n );\n }\n\n const switchModel = createTool({\n id: 'factory_switch_session_model',\n description:\n 'Look up or switch the model of a session you own in this Factory (side, work item, or review session). When someone describes a model by purpose, family, or preference rather than an exact ID, call with sessionId alone first to list models the target session can actually use. Interpret their intent against that list, then call with the chosen exact modelId to switch; do not use their words as a guessed model ID. A running session switches immediately; a stopped one uses the model on its next run. User-scoped sessions use their owner credentials; Factory-scoped sessions use Factory credentials. Use a session ID from the Factory session or work item tools.',\n inputSchema: z\n .object({\n sessionId: z.string().trim().min(1).max(200),\n modelId: z.string().trim().min(1).max(200).optional().describe('Omit to list usable models without switching.'),\n })\n .strict(),\n execute: async ({ sessionId, modelId }) => {\n const row = await deps.sessions.getBySessionId(sessionId);\n if (\n !row ||\n row.orgId !== scope.orgId ||\n row.factoryProjectId !== scope.factoryProjectId ||\n row.userId !== scope.userId\n ) {\n throw new Error('Session not found or not owned by you in this Factory.');\n }\n // A turn nobody signed in started reaches only this session and the side sessions it started.\n if (!scope.interactive && sessionId !== scope.sessionId && row.originSessionId !== scope.sessionId) {\n throw new Error(\n 'Without a person in this turn, only this session and the side sessions it started can switch models.',\n );\n }\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Session model switching is not available on this server.');\n const threadId = await resolveSessionThread({\n controller: messaging.controller,\n sessions: deps.sessions,\n workItems: deps.workItems,\n sessionId,\n });\n if (!threadId) throw new Error('Session has no conversation thread yet.');\n // The thread's resource, not the session id: sessions share their Factory's or owner's resource.\n const resourceId = (await messaging.controller.queryThreadById({ threadId }))?.resourceId ?? sessionId;\n const catalog = await sessionModelCatalog(messaging.controller, sessionId, threadId, resourceId);\n if (modelId === undefined) return { sessionId, models: catalog.usable };\n if (!catalog.usable.includes(modelId)) throw unrunnableModelError(modelId, catalog);\n const { live } = await messaging.controller.setThreadModel({ resourceId, threadId, modelId });\n return { sessionId, threadId, modelId, live };\n },\n });\n\n const start = createTool({\n id: 'factory_start_session',\n description: [\n 'Start a side session in this Factory with a prompt. It runs on its own sandbox and branch as you, and reports back to this session with `factory-session` notifications.',\n 'A side session uses this session’s model. Pass `model` to start it on another model the session credentials can run.',\n 'Use it for self-contained investigations; when the result should land as a pull request, file a work item instead.',\n 'With `workItem` and `role` it starts that role on the work item instead, without moving the card, and this session follows the item.',\n \"A role that already has a session on the item (current or past) can't be started again from here: message that session with factory_signal_session, or ask the person to start it from a signed-in chat.\",\n ].join(' '),\n inputSchema: z\n .object({\n prompt: z.string().trim().min(1).max(8000).describe('The first message the new session receives.'),\n title: z.string().trim().min(1).max(TITLE_LENGTH).optional(),\n model: z\n .string()\n .trim()\n .min(1)\n .max(200)\n .optional()\n .describe(\n 'Model id for a side session. Omit it to inherit this session’s model. The session credentials must be able to run it.',\n ),\n workItem: workItemRefSchema.optional(),\n role: z.string().trim().min(1).max(64).optional(),\n })\n .strict()\n .refine(input => input.role === undefined || input.workItem !== undefined, {\n message: 'Pass workItem together with role.',\n path: ['role'],\n }),\n execute: async ({ prompt, title, model, workItem, role }) => {\n if (workItem !== undefined) {\n // A role start records a run as the person, so it waits for a turn the person started.\n if (!scope.interactive) {\n throw new Error(\n 'Starting a role on a work item needs a person in this turn; start a side session, or ask the person to ask for it in a signed-in chat.',\n );\n }\n return startWorkItemRole({ prompt, title, workItem, role });\n }\n\n const parent = await deps.sessions.getBySessionId(scope.sessionId);\n const sourceControl = await deps.sessions.getSourceControlBySessionId(scope.sessionId);\n if (!parent || !sourceControl) throw new Error('This session has no Factory session row to start from.');\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Starting sessions is not available on this server.');\n\n // The child runs with the same credentials as this session, so validate against those.\n const parentThreadId = await resolveSessionThread({\n controller: messaging.controller,\n sessions: deps.sessions,\n workItems: deps.workItems,\n sessionId: scope.sessionId,\n });\n const parentResourceId = parentThreadId\n ? ((await messaging.controller.queryThreadById({ threadId: parentThreadId }))?.resourceId ?? scope.sessionId)\n : scope.sessionId;\n const catalog = await sessionModelCatalog(\n messaging.controller,\n scope.sessionId,\n parentThreadId ?? scope.threadId,\n parentResourceId,\n );\n const inherited = model\n ? null\n : await sessionModel(messaging.controller, deps.sessions, deps.workItems, scope.sessionId);\n const requestedModel = model ?? (inherited && catalog.usable.includes(inherited) ? inherited : undefined);\n if (requestedModel && !catalog.usable.includes(requestedModel))\n throw unrunnableModelError(requestedModel, catalog);\n\n const sessionId = globalThis.crypto.randomUUID();\n const ensured = await ensureFactorySourceSession({\n sourceControl,\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId,\n branch: `${USER_SESSION_BRANCH_PREFIX}${sessionId}`,\n // Bills the caller: the credential tenant follows the row's user.\n attributeToUserId: scope.userId,\n // Same repository as the session that started it.\n ...(parent.projectRepositoryId ? { projectRepositoryId: parent.projectRepositoryId } : {}),\n visibility: parent.visibility,\n origin: { sessionId: scope.sessionId, threadId: scope.threadId },\n });\n const resolvedModel = await resolveFactorySessionModel({\n ...deps.sessionModel,\n factoryProjectId: scope.factoryProjectId,\n orgId: scope.orgId,\n ownerUserId: scope.userId,\n // No work item, so an interactive session: a hybrid Factory bills it as one.\n context: 'session',\n });\n\n // Only the new row's owner as `user`. The tool call's context carries the\n // interactive marker and the parent's controller entry; neither may reach the child.\n const kickoffContext = new RequestContext();\n kickoffContext.set('user', { workosId: scope.userId, organizationId: scope.orgId });\n\n const tags = { factoryProjectId: scope.factoryProjectId, projectRepositoryId: ensured.projectRepositoryId };\n const session = await messaging.controller.createSession({\n id: ensured.sessionId,\n ownerId: scope.userId,\n // A side session works for the Factory, so it shares the Factory's memory\n // resource; a private one stays with its owner, like a Slack DM.\n resourceId: parent.visibility === 'private' ? scope.userId : scope.factoryProjectId,\n threadId: ensured.sessionId,\n requestContext: kickoffContext,\n tags,\n });\n await session.state.set(tags);\n await hydrateFactorySession(session, {\n orgId: scope.orgId,\n modelScope: resolvedModel.modelScope,\n ownerUserId: scope.userId,\n defaultModelId: requestedModel ?? resolvedModel.modelId,\n });\n\n const threadId = session.thread.requireId();\n const threadTitle = title ?? titleFrom(prompt);\n await session.thread.rename({ title: threadTitle, pin: false });\n // On the row too, so its run-end reports name it without waiting for the title mirror.\n await sourceControl.sessions.rename({ sessionId: ensured.sessionId, title: threadTitle });\n await session.thread.setSetting({ key: 'factorySessionId', value: ensured.sessionId });\n\n await primeTenantCredentialsForTenant({\n orgId: scope.orgId,\n userId: scope.userId,\n credentialScope: resolvedModel.modelScope,\n });\n // How its runs end reaches this session through the listener every Factory\n // session gets (`observeSessionRunReports`), which follows the row's origin.\n // `requireDelivery` makes `accepted` reject when the wake fails; the run itself is not awaited.\n await session.sendSignal(\n { id: globalThis.crypto.randomUUID(), type: 'user', tagName: 'user', contents: prompt },\n { requestContext: kickoffContext, requireDelivery: true },\n ).accepted;\n\n return {\n mode: 'side' as const,\n sessionId: ensured.sessionId,\n threadId,\n title: threadTitle,\n url:\n factorySessionUrl({ factoryProjectId: scope.factoryProjectId, sessionId: ensured.sessionId, threadId }) ??\n null,\n };\n },\n });\n\n async function startWorkItemRole({\n prompt,\n title,\n workItem,\n role,\n }: {\n prompt: string;\n title?: string;\n workItem: string;\n role?: string;\n }) {\n if (!role) throw new Error('Pass the role to start on the work item.');\n const coordinator = deps.startCoordinator();\n if (!coordinator) throw new Error(\"Factory sessions can't be started yet; try again shortly.\");\n const item = await findWorkItem(deps.workItems, scope, workItem);\n if (!item) throw workItemNotFound(workItem);\n const label = workItemLabel(item);\n const board = (await toBoardSource(deps.boards).load(scope)).get(boardForWorkItem(item));\n // Work's old `plan` role still names Planning, though no phase runs in a `plan` context any more.\n if (!workLaneForRole(board, role) && !board?.phaseForRole(role)) {\n throw new Error(`${label}'s board has no ${role} role.`);\n }\n const seated = item.sessions[role];\n if (seated) {\n throw new Error(\n `${label} already has a ${role} session ${seated.sessionId}; message it with factory_signal_session.`,\n );\n }\n\n const parent = await deps.sessions.getBySessionId(scope.sessionId);\n const sourceControl = await deps.sessions.getSourceControlBySessionId(scope.sessionId);\n if (!parent || !sourceControl) throw new Error('This session has no Factory session row to start from.');\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Starting sessions is not available on this server.');\n const project = await deps.sessionModel.projects.get({ orgId: scope.orgId, id: scope.factoryProjectId });\n if (!project) throw new Error('This Factory no longer exists.');\n // A work-item start is a run, so a hybrid Factory uses the Factory's scope (as the Start route does).\n const modelScope = effectiveModelScope(project.modelScope, 'run');\n // On the Factory's credentials the card's session is the Factory's own, as when the board starts it;\n // the person asking stays the one who started it, and follows it from this session.\n const ownerUserId = modelScope === 'factory' ? factoryPrincipalId(project.id) : scope.userId;\n if (modelScope === 'factory') {\n await requireOrganizationModelKey(\n {\n modelCredentials: deps.sessionModel.tenantCatalog?.credentials,\n customProviders: deps.sessionModel.tenantCatalog?.customProviders,\n deploymentModelProviders: deps.sessionModel.tenantCatalog?.deploymentProviders,\n },\n project,\n );\n }\n const projectRepositoryId = await resolveRepository(sourceControl, item);\n\n const sessionId = globalThis.crypto.randomUUID();\n const ensured = await ensureFactorySourceSession({\n sourceControl,\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId,\n branch: `${USER_SESSION_BRANCH_PREFIX}${sessionId}`,\n projectRepositoryId,\n attributeToUserId: ownerUserId,\n // A run works a shared card, so the org can open it and answer its approvals even when the session that\n // started it is private.\n visibility: 'org',\n });\n\n // Follow first, so a fast run's first report already has somewhere to go.\n const followScope = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n const alreadyFollowing = (\n await deps.workItems.listSessionSubscriptions({ ...followScope, sessionId: scope.sessionId })\n ).some(subscription => subscription.workItemId === item.id);\n await deps.workItems.subscribeToWorkItem({\n ...followScope,\n workItemId: item.id,\n sessionId: scope.sessionId,\n threadId: scope.threadId,\n resourceId: scope.resourceId,\n userId: scope.userId,\n reason: 'started',\n });\n\n const startedAt = new Date();\n let prepared;\n try {\n prepared = await coordinator.prepare({\n orgId: scope.orgId,\n userId: ownerUserId,\n startedBy: { type: 'human', id: scope.userId },\n factoryProjectId: scope.factoryProjectId,\n sessionId: ensured.sessionId,\n threadTitle: title ?? `${label} ${role}`,\n kickoffKey: globalThis.crypto.randomUUID(),\n modelScope,\n defaultModelId: modelScope === 'factory' ? (project.defaultModelId ?? undefined) : undefined,\n workItem: {\n id: item.id,\n role,\n input: {\n externalSource: item.externalSource,\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n stages: item.stages,\n sessions: item.sessions,\n metadata: item.metadata,\n },\n },\n });\n } catch (error) {\n if (!alreadyFollowing) {\n await deps.workItems.unsubscribeFromWorkItem({\n orgId: scope.orgId,\n workItemId: item.id,\n sessionId: scope.sessionId,\n });\n }\n const message = startErrorMessage(error);\n if (message) throw new Error(message);\n throw error;\n }\n\n const bindings = await deps.workItems.listRunBindings(scope.orgId, scope.factoryProjectId, item.id);\n const replaced = bindings.find(\n binding =>\n binding.role === role &&\n binding.id !== prepared.bindingId &&\n binding.revokedAt !== null &&\n binding.revokedAt >= startedAt,\n );\n\n const session = await messaging.controller.getSession(prepared.sessionId);\n if (!session) {\n throw new Error(\n `The ${role} session ${prepared.sessionId} was bound but is not running; message it with factory_signal_session to wake it.`,\n );\n }\n const kickoffId = globalThis.crypto.randomUUID();\n // Heartbeat from before the kickoff so a fast run's end is seen; the open-run\n // entry and audit follow the accepted kickoff, as the dispatcher records them.\n // The run's end reaches this item's followers through the session's listener.\n const heartbeat = heartbeatOpenRunUntilEnd(session, kickoffId);\n const kickoffContext = new RequestContext();\n kickoffContext.set('user', { workosId: ownerUserId, organizationId: scope.orgId });\n try {\n await session.sendSignal(\n { id: kickoffId, type: 'user', tagName: 'user', contents: prompt },\n { requestContext: kickoffContext, requireDelivery: true },\n ).accepted;\n } catch (error) {\n heartbeat.stop();\n throw error;\n }\n\n await recordSessionRunStart(session, {\n audit: deps.auditRecorder,\n actorType: 'human',\n observedEnd: heartbeat.endReason,\n run: {\n kickoffId,\n ownerId: FACTORY_TOOLS_OWNER_ID,\n heartbeatAt: Date.now(),\n bindingId: prepared.bindingId,\n role,\n startedBy: scope.userId,\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n workItemId: item.id,\n workItemName: item.title,\n sessionId: prepared.sessionId,\n threadId: prepared.threadId,\n branch: prepared.branch,\n },\n });\n\n const number = workItemNumber(item);\n return {\n mode: 'work-item' as const,\n workItem: {\n id: item.id,\n ...(number === null ? {} : { number }),\n url:\n factoryWorkItemUrl({\n factoryProjectId: scope.factoryProjectId,\n board: boardForWorkItem(item),\n workItemId: item.id,\n }) ?? null,\n },\n role,\n sessionId: prepared.sessionId,\n threadId: prepared.threadId,\n url:\n factorySessionUrl({\n factoryProjectId: scope.factoryProjectId,\n sessionId: prepared.sessionId,\n threadId: prepared.threadId,\n }) ?? null,\n bindingId: prepared.bindingId,\n ...(replaced ? { replacedSessionId: replaced.sessionId } : {}),\n };\n }\n\n async function resolveRepository(sourceControl: SourceControlStorageHandle, item: Card): Promise<string> {\n const intakeConfig = await deps.intake?.getConfig({ orgId: scope.orgId, integrationIds: ['linear'] });\n const repository = await resolveWorkItemRepository({\n sourceControl,\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n item,\n linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,\n });\n if (repository.status === 'ambiguous') {\n throw new Error(ambiguousRepository(repository.candidates));\n }\n if (repository.status === 'unlinked') throw new Error(repository.hint);\n return repository.projectRepositoryId;\n }\n\n return { factory_start_session: start, factory_switch_session_model: switchModel };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,eAAe;;AAGrB,MAAa,yBAAyB,iBAAiB,WAAW,OAAO,WAAW;AAyCpF,MAAM,gBAAgB;AAEtB,SAAS,oBAAoB,YAAuC;CAClE,OAAO,uCAAuC,WAAW,KAAK,IAAI,EAAE;AACtE;AAEA,SAAS,kBAAkB,OAA+B;CACxD,IAAI,iBAAiB,yBACnB,OAAO,MAAM,SAAS,y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xB;GACA,qBAAqB,cAAc,QAAQ;EAC7C,CAAC;EACD,IAAI,WAAW,WAAW,aACxB,MAAM,IAAI,MAAM,oBAAoB,WAAW,UAAU,CAAC;EAE5D,IAAI,WAAW,WAAW,YAAY,MAAM,IAAI,MAAM,WAAW,IAAI;EACrE,OAAO,WAAW;CACpB;CAEA,OAAO;EAAE,uBAAuB;EAAO,8BAA8B;CAAY;AACnF"}
1
+ {"version":3,"file":"session-tools.js","names":[],"sources":["../../src/tools/session-tools.ts"],"sourcesContent":["import { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factorySessionUrl } from '../links.js';\nimport { buildModelCatalog, listSessionScopedCredentials } from '../routes/config.js';\nimport { customEndpointUrlProblem } from '../routes/custom-endpoint-url.js';\nimport { customProviderOwner } from '../routes/custom-provider-source.js';\nimport { primeTenantCredentialsForTenant } from '../routes/tenant-credentials.js';\nimport { resolveFactoryModelPolicy } from '../session/credential-policy.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport {\n ensureFactorySourceSession,\n hydrateFactorySession,\n resolveFactorySessionModel,\n} from '../session/factory-session.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { USER_SESSION_BRANCH_PREFIX } from '../work-item-branch.js';\nimport { resolveSessionThread } from './deliver.js';\nimport type { FactoryMessaging } from './messaging-tools.js';\nimport type { FactoryToolScope } from './scope.js';\nimport { sessionModel } from './side-sessions.js';\n\nconst TITLE_LENGTH = 120;\n\nexport interface FactorySessionToolDependencies {\n sessions: Pick<SourceControlSessionLookup, 'getBySessionId' | 'getSourceControlBySessionId'>;\n sessionModel: {\n projects: FactoryProjectsStorage;\n modelDefaults: ModelDefaultsStorage;\n /**\n * Tenant credential stores, present when auth is on. Model switches then\n * check the target session's credential scope, like the Settings picker;\n * without them the server's own keys decide.\n */\n tenantCatalog?: {\n credentials: Pick<ModelCredentialsStorage, 'listCredentials'>;\n customProviders?: Pick<CustomProvidersStorage, 'ensureReady' | 'list'>;\n deploymentProviders?: ReadonlySet<string>;\n };\n };\n /** Resolved lazily: the controller only exists once the mount is up. */\n messaging: () => Promise<FactoryMessaging | null>;\n workItems: Pick<\n WorkItemsStorage,\n | 'listShared'\n | 'getForProject'\n | 'listRunBindings'\n | 'findActiveRunBindingForSession'\n | 'findRunBindingByThread'\n | 'hasRunBindingForSession'\n | 'subscribeToWorkItem'\n | 'unsubscribeFromWorkItem'\n | 'listSessionSubscriptions'\n | 'listWorkItemSubscribers'\n >;\n}\n\nconst LISTED_MODELS = 8;\n\nfunction titleFrom(prompt: string): string {\n const firstLine = prompt.split('\\n').find(line => line.trim()) ?? prompt;\n return firstLine.trim().slice(0, TITLE_LENGTH);\n}\n\n/** Tools that start sessions on the caller's behalf, or switch their models. User sessions only. */\nexport function createFactorySessionTools(\n scope: FactoryToolScope,\n deps: FactorySessionToolDependencies,\n): IntegrationTools {\n /** The models a session can switch to, resolved from the target session's owner and project policy. */\n async function sessionModelCatalog(\n controller: FactoryMessaging['controller'],\n sessionId: string,\n threadId: string,\n resourceId: string,\n ): Promise<{ usable: string[]; known: Set<string>; scopeLabel: string }> {\n const models = await controller.listAvailableModels();\n const known = new Set(models.flatMap(model => (typeof model.id === 'string' ? [model.id] : [])));\n const tenantCatalog = deps.sessionModel.tenantCatalog;\n if (!tenantCatalog) {\n const usable = (await buildModelCatalog({ controller })).map(model => model.id);\n return { usable, known, scopeLabel: 'server' };\n }\n const requestContext = new RequestContext();\n requestContext.set('user', { id: scope.userId, organizationId: scope.orgId });\n requestContext.set('controller', { sessionId, resourceId, threadId });\n const policy = await resolveFactoryModelPolicy(requestContext, {\n projects: deps.sessionModel.projects,\n sourceControl: deps.sessions,\n workItems: deps.workItems,\n });\n if (!policy) throw new Error('Session model policy is unavailable.');\n const modelScope = policy.tenant.credentialScope ?? 'user';\n const orgId = policy.tenant.orgId ?? scope.orgId;\n const customProviders = tenantCatalog.customProviders;\n // The list model resolution uses for this session, so the tool never\n // offers a custom model the session cannot run. A tenant catalog only\n // exists with sign-in on.\n const customProviderOwnerForSession = customProviderOwner(\n { orgId, userId: policy.tenant.userId, credentialScope: modelScope },\n /* authEnabled */ true,\n );\n const usable = (\n await buildModelCatalog({\n controller,\n tenantCredentials: await listSessionScopedCredentials({\n credentials: tenantCatalog.credentials,\n orgId,\n userId: policy.tenant.userId,\n modelScope,\n }),\n deploymentProviders: tenantCatalog.deploymentProviders,\n listCustomProviders:\n customProviders && customProviderOwnerForSession\n ? async () => {\n await customProviders.ensureReady();\n return (await customProviders.list(customProviderOwnerForSession)).filter(\n provider => !customEndpointUrlProblem(provider.url),\n );\n }\n : undefined,\n })\n ).map(model => model.id);\n for (const id of usable) known.add(id);\n return { usable, known, scopeLabel: modelScope === 'factory' ? 'Factory' : 'session owner' };\n }\n\n function unrunnableModelError(\n modelId: string,\n catalog: { usable: string[]; known: Set<string>; scopeLabel: string },\n ) {\n const options = catalog.usable.length\n ? ` Models available to it: ${catalog.usable.slice(0, LISTED_MODELS).join(', ')}${catalog.usable.length > LISTED_MODELS ? ', …' : ''}.`\n : ' No models are available to it; connect a provider credential first.';\n return new Error(\n catalog.known.has(modelId)\n ? `Model ${modelId} exists, but this session's credential scope (${catalog.scopeLabel}) has no credential for its provider.${options}`\n : `Unknown model ${modelId}.${options}`,\n );\n }\n\n const switchModel = createTool({\n id: 'factory_switch_session_model',\n description:\n 'Look up or switch the model of a session you own in this Factory (side, work item, or review session). When someone describes a model by purpose, family, or preference rather than an exact ID, call with sessionId alone first to list models the target session can actually use. Interpret their intent against that list, then call with the chosen exact modelId to switch; do not use their words as a guessed model ID. A running session switches immediately; a stopped one uses the model on its next run. User-scoped sessions use their owner credentials; Factory-scoped sessions use Factory credentials. Use a session ID from the Factory session or work item tools.',\n inputSchema: z\n .object({\n sessionId: z.string().trim().min(1).max(200),\n modelId: z.string().trim().min(1).max(200).optional().describe('Omit to list usable models without switching.'),\n })\n .strict(),\n execute: async ({ sessionId, modelId }) => {\n const row = await deps.sessions.getBySessionId(sessionId);\n if (\n !row ||\n row.orgId !== scope.orgId ||\n row.factoryProjectId !== scope.factoryProjectId ||\n row.userId !== scope.userId\n ) {\n throw new Error('Session not found or not owned by you in this Factory.');\n }\n // A turn nobody signed in started reaches only this session and the side sessions it started.\n if (!scope.interactive && sessionId !== scope.sessionId && row.originSessionId !== scope.sessionId) {\n throw new Error(\n 'Without a person in this turn, only this session and the side sessions it started can switch models.',\n );\n }\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Session model switching is not available on this server.');\n const threadId = await resolveSessionThread({\n controller: messaging.controller,\n sessions: deps.sessions,\n workItems: deps.workItems,\n sessionId,\n });\n if (!threadId) throw new Error('Session has no conversation thread yet.');\n // The thread's resource, not the session id: sessions share their Factory's or owner's resource.\n const resourceId = (await messaging.controller.queryThreadById({ threadId }))?.resourceId ?? sessionId;\n const catalog = await sessionModelCatalog(messaging.controller, sessionId, threadId, resourceId);\n if (modelId === undefined) return { sessionId, models: catalog.usable };\n if (!catalog.usable.includes(modelId)) throw unrunnableModelError(modelId, catalog);\n const { live } = await messaging.controller.setThreadModel({ resourceId, threadId, modelId });\n return { sessionId, threadId, modelId, live };\n },\n });\n\n const start = createTool({\n id: 'factory_start_session',\n description: [\n 'Start a side session in this Factory with a prompt. It runs on its own sandbox and branch as you, and reports back to this session with `factory-session` notifications.',\n 'A side session uses this session’s model. Pass `model` to start it on another model the session credentials can run.',\n 'Use it when the person asks for a side session, and for work no card stage does: investigations and research, experiments, pushing fixes to an existing pull request or taking one over, or work that should leave the board alone.',\n \"When someone asks for a card's own stage work without saying where, run it on the card instead, as the board's buttons do: \\\"review this pull request\\\" moves the pull request's card to its review stage or reruns it there, so the review is recorded on the card and posted on the pull request, and new work that should land as a pull request goes on its issue's card, or a card filed for it.\",\n 'Find cards with factory_list_work_items (a pasted link works) and move them, or rerun their stage, with factory_transition_work_item.',\n ].join(' '),\n inputSchema: z\n .object({\n prompt: z.string().trim().min(1).max(8000).describe('The first message the new session receives.'),\n title: z.string().trim().min(1).max(TITLE_LENGTH).optional(),\n model: z\n .string()\n .trim()\n .min(1)\n .max(200)\n .optional()\n .describe(\n 'Model id for a side session. Omit it to inherit this session’s model. The session credentials must be able to run it.',\n ),\n })\n .strict(),\n execute: async ({ prompt, title, model }) => {\n const parent = await deps.sessions.getBySessionId(scope.sessionId);\n const sourceControl = await deps.sessions.getSourceControlBySessionId(scope.sessionId);\n if (!parent || !sourceControl) throw new Error('This session has no Factory session row to start from.');\n const messaging = await deps.messaging();\n if (!messaging) throw new Error('Starting sessions is not available on this server.');\n\n // The child runs with the same credentials as this session, so validate against those.\n const parentThreadId = await resolveSessionThread({\n controller: messaging.controller,\n sessions: deps.sessions,\n workItems: deps.workItems,\n sessionId: scope.sessionId,\n });\n const parentResourceId = parentThreadId\n ? ((await messaging.controller.queryThreadById({ threadId: parentThreadId }))?.resourceId ?? scope.sessionId)\n : scope.sessionId;\n const catalog = await sessionModelCatalog(\n messaging.controller,\n scope.sessionId,\n parentThreadId ?? scope.threadId,\n parentResourceId,\n );\n const inherited = model\n ? null\n : await sessionModel(messaging.controller, deps.sessions, deps.workItems, scope.sessionId);\n const requestedModel = model ?? (inherited && catalog.usable.includes(inherited) ? inherited : undefined);\n if (requestedModel && !catalog.usable.includes(requestedModel))\n throw unrunnableModelError(requestedModel, catalog);\n\n const sessionId = globalThis.crypto.randomUUID();\n const ensured = await ensureFactorySourceSession({\n sourceControl,\n orgId: scope.orgId,\n factoryProjectId: scope.factoryProjectId,\n sessionId,\n branch: `${USER_SESSION_BRANCH_PREFIX}${sessionId}`,\n // Bills the caller: the credential tenant follows the row's user.\n attributeToUserId: scope.userId,\n // Same repository as the session that started it.\n ...(parent.projectRepositoryId ? { projectRepositoryId: parent.projectRepositoryId } : {}),\n visibility: parent.visibility,\n origin: { sessionId: scope.sessionId, threadId: scope.threadId },\n });\n const resolvedModel = await resolveFactorySessionModel({\n ...deps.sessionModel,\n factoryProjectId: scope.factoryProjectId,\n orgId: scope.orgId,\n ownerUserId: scope.userId,\n // No work item, so an interactive session: a hybrid Factory bills it as one.\n context: 'session',\n });\n\n // Only the new row's owner as `user`. The tool call's context carries the\n // interactive marker and the parent's controller entry; neither may reach the child.\n const kickoffContext = new RequestContext();\n kickoffContext.set('user', { workosId: scope.userId, organizationId: scope.orgId });\n\n const tags = { factoryProjectId: scope.factoryProjectId, projectRepositoryId: ensured.projectRepositoryId };\n const session = await messaging.controller.createSession({\n id: ensured.sessionId,\n ownerId: scope.userId,\n // A side session works for the Factory, so it shares the Factory's memory\n // resource; a private one stays with its owner, like a Slack DM.\n resourceId: parent.visibility === 'private' ? scope.userId : scope.factoryProjectId,\n threadId: ensured.sessionId,\n requestContext: kickoffContext,\n tags,\n });\n await session.state.set(tags);\n await hydrateFactorySession(session, {\n orgId: scope.orgId,\n modelScope: resolvedModel.modelScope,\n ownerUserId: scope.userId,\n defaultModelId: requestedModel ?? resolvedModel.modelId,\n });\n\n const threadId = session.thread.requireId();\n const threadTitle = title ?? titleFrom(prompt);\n await session.thread.rename({ title: threadTitle, pin: false });\n // On the row too, so its run-end reports name it without waiting for the title mirror.\n await sourceControl.sessions.rename({ sessionId: ensured.sessionId, title: threadTitle });\n await session.thread.setSetting({ key: 'factorySessionId', value: ensured.sessionId });\n\n await primeTenantCredentialsForTenant({\n orgId: scope.orgId,\n userId: scope.userId,\n credentialScope: resolvedModel.modelScope,\n });\n // How its runs end reaches this session through the listener every Factory\n // session gets (`observeSessionRunReports`), which follows the row's origin.\n // `requireDelivery` makes `accepted` reject when the wake fails; the run itself is not awaited.\n await session.sendSignal(\n { id: globalThis.crypto.randomUUID(), type: 'user', tagName: 'user', contents: prompt },\n { requestContext: kickoffContext, requireDelivery: true },\n ).accepted;\n\n return {\n mode: 'side' as const,\n sessionId: ensured.sessionId,\n threadId,\n title: threadTitle,\n url:\n factorySessionUrl({ factoryProjectId: scope.factoryProjectId, sessionId: ensured.sessionId, threadId }) ??\n null,\n };\n },\n });\n\n return { factory_start_session: start, factory_switch_session_model: switchModel };\n}\n"],"mappings":";;;;;;;;;;;;;;AA4BA,MAAM,eAAe;AAmCrB,MAAM,gBAAgB;AAEtB,SAAS,UAAU,QAAwB;CAEzC,QADkB,OAAO,MAAM,IAAI,CAAC,CAAC,MAAK,SAAQ,KAAK,KAAK,CAAC,KAAK,OAAA,CACjD,KAAK,CAAC,CAAC,MAAM,GAAG,YAAY;AAC/C;;AAGA,SAAgB,0BACd,OACA,MACkB;;CAElB,eAAe,oBACb,YACA,WACA,UACA,YACuE;EACvE,MAAM,SAAS,MAAM,WAAW,oBAAoB;EACpD,MAAM,QAAQ,IAAI,IAAI,OAAO,SAAQ,UAAU,OAAO,MAAM,OAAO,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,CAAE,CAAC;EAC/F,MAAM,gBAAgB,KAAK,aAAa;EACxC,IAAI,CAAC,eAEH,OAAO;GAAE,SADO,MAAM,kBAAkB,EAAE,WAAW,CAAC,EAAA,CAAG,KAAI,UAAS,MAAM,EAC9D;GAAG;GAAO,YAAY;EAAS;EAE/C,MAAM,iBAAiB,IAAI,eAAe;EAC1C,eAAe,IAAI,QAAQ;GAAE,IAAI,MAAM;GAAQ,gBAAgB,MAAM;EAAM,CAAC;EAC5E,eAAe,IAAI,cAAc;GAAE;GAAW;GAAY;EAAS,CAAC;EACpE,MAAM,SAAS,MAAM,0BAA0B,gBAAgB;GAC7D,UAAU,KAAK,aAAa;GAC5B,eAAe,KAAK;GACpB,WAAW,KAAK;EAClB,CAAC;EACD,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,sCAAsC;EACnE,MAAM,aAAa,OAAO,OAAO,mBAAmB;EAC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;KACpC,OAAO,MAAM;KACb,QAAQ,MAAM;KACd,iBAAiB,cAAc;IACjC,CAAC;IAID,MAAM,QAAQ,WACZ;KAAE,IAAI,WAAW,OAAO,WAAW;KAAG,MAAM;KAAQ,SAAS;KAAQ,UAAU;IAAO,GACtF;KAAE,gBAAgB;KAAgB,iBAAiB;IAAK,CAC1D,CAAC,CAAC;IAEF,OAAO;KACL,MAAM;KACN,WAAW,QAAQ;KACnB;KACA,OAAO;KACP,KACE,kBAAkB;MAAE,kBAAkB,MAAM;MAAkB,WAAW,QAAQ;MAAW;KAAS,CAAC,KACtG;IACJ;GACF;EACF,CAEoC;EAAG,8BAA8B;CAAY;AACnF"}
@@ -10,6 +10,7 @@ import type { IntegrationTools } from '../integrations/base.js';
10
10
  import type { FactoryTransitionService } from '../rules/transition-service.js';
11
11
  import type { SourceControlSessionLookup } from '../session/factory-session.js';
12
12
  import type { AuditRecorder } from '../storage/domains/audit/domain.js';
13
+ import type { IntakeEvaluator } from '../storage/domains/boards/base.js';
13
14
  import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
14
15
  import type { FactoryToolScope } from './scope.js';
15
16
  export interface FactoryWorkItemToolDependencies {
@@ -18,6 +19,8 @@ export interface FactoryWorkItemToolDependencies {
18
19
  boards: BoardRegistry | ProjectBoardSource;
19
20
  /** The project's intake routes, which place a filed card. */
20
21
  intakeRoutes?: IntakeRoutesReader;
22
+ /** Which evaluator places a filed card; the old `route-list` by default. */
23
+ intakeEvaluator?: IntakeEvaluator;
21
24
  /** Governed stage moves; filing and moving items refuse while it is unavailable. */
22
25
  transitionService: Pick<FactoryTransitionService, 'transition'> | undefined;
23
26
  /** Writes audit rows with an explicit actor; tool calls have no HTTP request to read one from. */
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-tools.d.ts","sourceRoot":"","sources":["../../src/tools/work-item-tools.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAOH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC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E,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAGhE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAE/E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAEhF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AACxE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AAEzE,OAAO,KAAK,EAA6B,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAYzG,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,MAAM,WAAW,+BAA+B;IAC9C,SAAS,EAAE,gBAAgB,CAAC;IAC5B,mDAAmD;IACnD,MAAM,EAAE,aAAa,GAAG,kBAAkB,CAAC;IAC3C,6DAA6D;IAC7D,YAAY,CAAC,EAAE,kBAAkB,CAAC;IAClC,4EAA4E;IAC5E,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,oFAAoF;IACpF,iBAAiB,EAAE,IAAI,CAAC,wBAAwB,EAAE,YAAY,CAAC,GAAG,SAAS,CAAC;IAC5E,kGAAkG;IAClG,aAAa,EAAE,aAAa,CAAC;IAC7B,qGAAqG;IACrG,QAAQ,EAAE,IAAI,CAAC,0BAA0B,EAAE,6BAA6B,CAAC,CAAC;CAC3E;AAsCD,8EAA8E;AAC9E,wBAAgB,0BAA0B,CACxC,KAAK,EAAE,gBAAgB,EACvB,IAAI,EAAE,+BAA+B,GACpC,gBAAgB,CAgalB"}
@@ -1,8 +1,9 @@
1
- import { boardForWorkItem } from "../boards/semantics.js";
2
1
  import "../boards/index.js";
2
+ import { boardForWorkItem } from "../boards/semantics.js";
3
3
  import { toBoardSource } from "../boards/project-boards.js";
4
4
  import { factoryWorkItemUrl } from "../links.js";
5
5
  import { transitionBodySchema } from "../routes/contracts.js";
6
+ import "../rules/validation.js";
6
7
  import { resolveWorkItemRepository } from "../session/work-item-repository.js";
7
8
  import { WorkItemRelationError } from "../storage/domains/work-items/base.js";
8
9
  import { workItemNumber } from "../work-items/card-number.js";
@@ -34,6 +35,10 @@ function briefItem(item) {
34
35
  }) ?? null
35
36
  };
36
37
  }
38
+ function workItemLabel(item) {
39
+ const number = workItemNumber(item);
40
+ return number === null ? `"${item.title}"` : `#${number}`;
41
+ }
37
42
  function settled(result) {
38
43
  if (!result.ok) throw new Error(result.message);
39
44
  const { decision } = result;
@@ -95,22 +100,54 @@ function createFactoryWorkItemTools(scope, deps) {
95
100
  userId: scope.userId,
96
101
  reason
97
102
  });
103
+ /**
104
+ * Approving or retrying a run starts it from this session, so this session follows its card as a
105
+ * move does: the run's report and anything it waits on reach this session, which can pass them on.
106
+ * Only approval acts as the person; a retry keeps the run's original approver. The run has
107
+ * started by now: a failed read or follow is reported with it, not instead of it.
108
+ */
109
+ const followStartedRun = async (result) => {
110
+ if (!result.workItemId) return result;
111
+ let url = null;
112
+ try {
113
+ const item = await deps.workItems.getForProject(scope.orgId, scope.factoryProjectId, result.workItemId);
114
+ if (!item) return result;
115
+ url = factoryWorkItemUrl({
116
+ factoryProjectId: item.factoryProjectId,
117
+ board: boardForWorkItem(item),
118
+ workItemId: item.id
119
+ }) ?? null;
120
+ await follow(item, "started");
121
+ return {
122
+ ...result,
123
+ url
124
+ };
125
+ } catch (error) {
126
+ return {
127
+ ...result,
128
+ url,
129
+ warnings: [`This session does not follow it yet: ${error instanceof Error ? error.message : String(error)}`]
130
+ };
131
+ }
132
+ };
98
133
  return {
99
134
  factory_create_work_item: createTool({
100
135
  id: "factory_create_work_item",
101
- description: "File a new work item on this Factory's Work board (or wherever the project's intake routes send it) for the person you are working with. It enters its board's first phase, or the phase an intake route names, and this session follows it. Check factory_list_work_items for an existing item first. Name the repository when the Factory links more than one; runs refuse to start on a card that doesn't say which.",
136
+ description: "File a new work item on this Factory for the person you are working with, on the board the project's intake rules pick (or the board named). It enters its board's first phase, or the phase an intake rule names, and this session follows it. Check factory_list_work_items for an existing item first. When no intake rule takes it, the call is refused: ask the person which board it belongs on and call again with that board. Name the repository when you know it; a run on a card that names none determines it from the card.",
102
137
  inputSchema: z.object({
103
138
  title: z.string().trim().min(1).max(512).describe("Short title, as it should read on the card."),
104
139
  description: z.string().trim().min(1).max(8e3).describe("What needs doing and why; becomes the card description its runs start from."),
105
- repository: repositorySchema.optional()
140
+ repository: repositorySchema.optional(),
141
+ board: z.string().trim().min(1).max(128).optional().describe("The board's key, when the person picked one; files it in that board's first phase.")
106
142
  }).strict(),
107
- execute: async ({ title, description, repository }) => {
143
+ execute: async ({ title, description, repository, board }) => {
108
144
  if (repository) await requireRepository(repository);
109
145
  const created = await createFactoryWorkItem({
110
146
  workItems: deps.workItems,
111
147
  boards: await toBoardSource(deps.boards).load(project),
112
148
  transitionService: deps.transitionService,
113
149
  intakeRoutes: deps.intakeRoutes,
150
+ intakeEvaluator: deps.intakeEvaluator,
114
151
  audit,
115
152
  ...project,
116
153
  userId: scope.userId,
@@ -118,6 +155,7 @@ function createFactoryWorkItemTools(scope, deps) {
118
155
  input: {
119
156
  title,
120
157
  description,
158
+ ...board ? { board } : {},
121
159
  ...repository ? { metadata: { repository } } : {}
122
160
  }
123
161
  });
@@ -138,20 +176,60 @@ function createFactoryWorkItemTools(scope, deps) {
138
176
  }),
139
177
  factory_transition_work_item: createTool({
140
178
  id: "factory_transition_work_item",
141
- description: "Move a work item to another stage of its board, as the person you are working with. The board's rules decide whether the move is allowed and what it starts.",
179
+ description: [
180
+ "Move a work item to another stage of its board, or with `rerun` run the stage it is already in again, as the person you are working with: the same requests the board's own move and Start buttons send.",
181
+ "The board's rules decide whether the move is allowed and what it starts. The run it starts counts as approved by that person, so it does not wait in the approval queue. The result has the card's `url`, to link it where you report the move.",
182
+ "Use it when someone asks for a card's own stage work, such as \"review this pull request\" on a pull request that has a card: the card's review is recorded on the card and posted on the pull request.",
183
+ "When the person asks for a side session, a review in this chat, or work the stage does not do (pushing fixes to a pull request, taking it over), do that instead."
184
+ ].join(" "),
142
185
  inputSchema: z.object({
143
186
  workItem: workItemRefSchema,
144
- stage: z.string().trim().min(1).max(64).describe("Destination stage, e.g. \"planning\" or \"done\".")
187
+ stage: z.string().trim().min(1).max(64).describe("Destination stage key, as factory_inspect_work_item lists it (e.g. \"planning\" or \"done\")."),
188
+ rerun: z.boolean().optional().describe("With the stage the card is already in: run it again, as the board's Start button does. Without it, a request for the card's own stage changes nothing and says what the stage is doing.")
145
189
  }).strict(),
146
- execute: async ({ workItem, stage }) => {
190
+ execute: async ({ workItem, stage, rerun: rerunRequested }) => {
147
191
  if (!deps.transitionService) throw new Error("Factory stage transitions are not available right now.");
148
192
  const item = await requireItem(workItem);
193
+ const followed = async (result) => {
194
+ try {
195
+ await follow(item, "moved");
196
+ return result;
197
+ } catch (error) {
198
+ return {
199
+ ...result,
200
+ warnings: [`This session does not follow it yet: ${error instanceof Error ? error.message : String(error)}`]
201
+ };
202
+ }
203
+ };
204
+ const url = factoryWorkItemUrl({
205
+ factoryProjectId: item.factoryProjectId,
206
+ board: boardForWorkItem(item),
207
+ workItemId: item.id
208
+ }) ?? null;
209
+ const sameStage = item.stages.length === 1 && item.stages[0] === stage;
210
+ if (sameStage && rerunRequested !== true) {
211
+ const held = (await deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, {
212
+ workItemId: item.id,
213
+ statuses: ["proposed"]
214
+ })).filter((decision) => decision.decision.type === "invokeSkill").length;
215
+ return followed({
216
+ workItemId: item.id,
217
+ url,
218
+ stage,
219
+ revision: item.revision,
220
+ unchanged: true,
221
+ message: `${workItemLabel(item)} is already in ${stage}` + (held > 0 ? ", and its run there is waiting for approval." : ".") + " Pass rerun: true to run the stage again, as the board's Start button does; factory_inspect_work_item shows its sessions and runs."
222
+ });
223
+ }
224
+ const rerun = sameStage;
225
+ if (rerun && !scope.interactive) throw new Error(`Running ${stage} again on ${workItemLabel(item)} needs a person in this turn: ask them to request it from a signed-in chat or the board.`);
149
226
  const parsed = transitionBodySchema.safeParse({
150
227
  board: boardForWorkItem(item),
151
228
  stage,
152
229
  expectedRevision: item.revision,
153
230
  requestId: randomUUID(),
154
- cause: "factory_tools"
231
+ cause: "factory_tools",
232
+ ...rerun ? { reenter: true } : {}
155
233
  });
156
234
  if (!parsed.success) throw new Error(`"${stage}" is not a valid stage name.`);
157
235
  const result = await deps.transitionService.transition({
@@ -181,25 +259,18 @@ function createFactoryWorkItemTools(scope, deps) {
181
259
  }
182
260
  });
183
261
  if (result.status === "rejected") throw new Error(`The move was refused (${result.code}): ${result.reason}`);
184
- const moved = {
262
+ return followed({
185
263
  workItemId: item.id,
264
+ url,
186
265
  stage: result.stage,
187
- revision: result.revision
188
- };
189
- try {
190
- await follow(item, "moved");
191
- } catch (error) {
192
- return {
193
- ...moved,
194
- warnings: [`This session does not follow it yet: ${error instanceof Error ? error.message : String(error)}`]
195
- };
196
- }
197
- return moved;
266
+ revision: result.revision,
267
+ ...rerun ? { reran: true } : {}
268
+ });
198
269
  }
199
270
  }),
200
271
  factory_update_work_item: createTool({
201
272
  id: "factory_update_work_item",
202
- description: "Edit a work item's fields as the person you are working with: its title, description, the repository its runs use, or its parent item. Move stages with factory_transition_work_item and start roles with factory_start_session.",
273
+ description: "Edit a work item's fields as the person you are working with: its title, description, the repository its runs use, or its parent item. Move stages, or rerun the stage a card is in, with factory_transition_work_item.",
203
274
  inputSchema: z.object({
204
275
  workItem: workItemRefSchema,
205
276
  title: z.string().trim().min(1).max(500).optional().describe("New card title."),
@@ -262,14 +333,14 @@ function createFactoryWorkItemTools(scope, deps) {
262
333
  }),
263
334
  factory_retry_decision: createTool({
264
335
  id: "factory_retry_decision",
265
- description: "Retry one failed Factory run once its cause is fixed. Refused when the failure cannot be fixed by retrying or the item has moved on.",
336
+ description: "Retry one failed Factory run once its cause is fixed. Refused when the failure cannot be fixed by retrying or the item has moved on. This session follows the run's card, so it hears how the run ends; the result has the card's `url`.",
266
337
  inputSchema: z.object({ decisionId }).strict(),
267
- execute: async ({ decisionId }) => settled(await retryFactoryDecision({
338
+ execute: async ({ decisionId }) => followStartedRun(settled(await retryFactoryDecision({
268
339
  workItems: deps.workItems,
269
340
  boards: await toBoardSource(deps.boards).load(project),
270
341
  ...project,
271
342
  decisionId
272
- }))
343
+ })))
273
344
  }),
274
345
  factory_dismiss_decision: createTool({
275
346
  id: "factory_dismiss_decision",
@@ -288,14 +359,14 @@ function createFactoryWorkItemTools(scope, deps) {
288
359
  }),
289
360
  factory_resolve_proposal: createTool({
290
361
  id: "factory_resolve_proposal",
291
- description: "Approve or dismiss one proposed Factory run. Approving starts the run and lets the item's later runs start without asking.",
362
+ description: "Approve or dismiss one proposed Factory run. Approving starts the run and lets the item's later runs start without asking, and this session follows the run's card, so it hears how the run ends; the result has the card's `url`.",
292
363
  inputSchema: z.object({
293
364
  decisionId,
294
365
  action: z.enum(["approve", "dismiss"])
295
366
  }).strict(),
296
367
  execute: async ({ decisionId, action }) => {
297
368
  requirePerson(scope, "approve or dismiss a proposed run");
298
- return settled(await resolveFactoryProposal({
369
+ const result = settled(await resolveFactoryProposal({
299
370
  workItems: deps.workItems,
300
371
  audit,
301
372
  ...project,
@@ -303,6 +374,7 @@ function createFactoryWorkItemTools(scope, deps) {
303
374
  decisionId,
304
375
  action
305
376
  }));
377
+ return action === "approve" ? followStartedRun(result) : result;
306
378
  }
307
379
  }),
308
380
  factory_subscribe_work_item: createTool({
@@ -326,7 +398,7 @@ function createFactoryWorkItemTools(scope, deps) {
326
398
  execute: async ({ workItem }) => {
327
399
  const item = await requireItem(workItem);
328
400
  const removed = await deps.workItems.unsubscribeFromWorkItem({
329
- orgId: scope.orgId,
401
+ ...project,
330
402
  workItemId: item.id,
331
403
  sessionId: scope.sessionId
332
404
  });
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-tools.js","names":[],"sources":["../../src/tools/work-item-tools.ts"],"sourcesContent":["/**\n * Factory tools that change work items: file one, move it, settle its\n * decisions, and follow it. They act as the session's person (a human actor),\n * through the same code the board's routes use.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport { boardForWorkItem } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport type { IntakeRoutesReader } from '../boards/intake-routing.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factoryWorkItemUrl } from '../links.js';\nimport { transitionBodySchema } from '../routes/contracts.js';\nimport type { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport { WorkItemRelationError } from '../storage/domains/work-items/base.js';\nimport type { UpdateWorkItemInput, Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { workItemNumber } from '../work-items/card-number.js';\nimport { createFactoryWorkItem } from '../work-items/create-work-item.js';\nimport type { FactoryAuditEmit } from '../work-items/create-work-item.js';\nimport {\n dismissFactoryDecision,\n resolveFactoryProposal,\n retryFactoryDecision,\n} from '../work-items/decision-actions.js';\nimport type { FactoryDecisionActionResult } from '../work-items/decision-actions.js';\nimport { MAX_TEXT, findWorkItem, workItemRefSchema, truncate, workItemNotFound, workItemStage } from './read-tools.js';\nimport { requirePerson } from './scope.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport interface FactoryWorkItemToolDependencies {\n workItems: WorkItemsStorage;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** The project's intake routes, which place a filed card. */\n intakeRoutes?: IntakeRoutesReader;\n /** Governed stage moves; filing and moving items refuse while it is unavailable. */\n transitionService: Pick<FactoryTransitionService, 'transition'> | undefined;\n /** Writes audit rows with an explicit actor; tool calls have no HTTP request to read one from. */\n auditRecorder: AuditRecorder;\n /** Finds the caller session's source-control provider, whose linked repositories a card can name. */\n sessions: Pick<SourceControlSessionLookup, 'getSourceControlBySessionId'>;\n}\n\nconst repositorySchema = z\n .string()\n .trim()\n .min(3)\n .max(200)\n .regex(/^[^/\\s]+\\/[^/\\s]+$/, 'Use the owner/name form, e.g. \"mastra-ai/mastra\".')\n .describe('A repository linked to this Factory, as owner/name.');\n\nconst decisionId = z.string().trim().uuid().describe('Decision id, from factory_list_attention or inspect.');\n\nfunction briefItem(item: Card) {\n return {\n id: item.id,\n number: workItemNumber(item),\n title: truncate(item.title, MAX_TEXT),\n stage: workItemStage(item),\n url:\n factoryWorkItemUrl({\n factoryProjectId: item.factoryProjectId,\n board: boardForWorkItem(item),\n workItemId: item.id,\n }) ?? null,\n };\n}\n\nfunction settled(result: FactoryDecisionActionResult) {\n if (!result.ok) throw new Error(result.message);\n const { decision } = result;\n return { decisionId: decision.id, status: decision.status, workItemId: decision.workItemId };\n}\n\n/** The work-item write and subscription tools for one user session's turn. */\nexport function createFactoryWorkItemTools(\n scope: FactoryToolScope,\n deps: FactoryWorkItemToolDependencies,\n): IntegrationTools {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n const audit: FactoryAuditEmit = async input => {\n await deps.auditRecorder.record({\n orgId: scope.orgId,\n // Turns nobody signed in started are recorded as this session's agent, as their moves are.\n actorId: scope.interactive ? scope.userId : `agent:session:${scope.sessionId}`,\n actorType: scope.interactive ? 'human' : 'agent',\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n ...input,\n });\n };\n const requireItem = async (ref: string) => {\n const item = await findWorkItem(deps.workItems, scope, ref);\n if (!item) throw workItemNotFound(ref);\n return item;\n };\n /**\n * Check `slug` is a repository linked to this Factory and that a card with\n * `metadata` would run in it (a card synced from an issue follows the\n * issue's repository, which a slug can't override).\n */\n const requireRepository = async (slug: string, item?: Pick<Card, 'metadata' | 'workItem'>) => {\n const sourceControl = await deps.sessions.getSourceControlBySessionId(scope.sessionId);\n if (!sourceControl) throw new Error('This session has no source-control provider to look repositories up in.');\n const resolve = (repository?: string) =>\n resolveWorkItemRepository({\n sourceControl,\n ...project,\n item: {\n metadata: repository ? { repository } : (item?.metadata ?? null),\n workItem: item?.workItem ?? { metadata: null },\n },\n });\n const resolution = await resolve(slug);\n if (resolution.status === 'resolved' && resolution.slug === slug) return;\n if (resolution.status === 'resolved') {\n throw new Error(`This card runs in ${resolution.slug}, which comes from its linked issue and can't be changed.`);\n }\n const linked = await resolve();\n const candidates =\n linked.status === 'ambiguous' ? linked.candidates : linked.status === 'resolved' ? [linked.slug] : [];\n throw new Error(\n candidates.length > 0\n ? `${slug} is not linked to this Factory. Linked repositories: ${candidates.join(', ')}.`\n : `${slug} is not linked to this Factory, and it has no linked repositories.`,\n );\n };\n const follow = (item: Card, reason: 'created' | 'moved' | 'subscribed') =>\n deps.workItems.subscribeToWorkItem({\n ...project,\n workItemId: item.id,\n sessionId: scope.sessionId,\n threadId: scope.threadId,\n resourceId: scope.resourceId,\n userId: scope.userId,\n reason,\n });\n\n return {\n factory_create_work_item: createTool({\n id: 'factory_create_work_item',\n description:\n \"File a new work item on this Factory's Work board (or wherever the project's intake routes send it) for the person you are working with. It enters its board's first phase, or the phase an intake route names, and this session follows it. Check factory_list_work_items for an existing item first. Name the repository when the Factory links more than one; runs refuse to start on a card that doesn't say which.\",\n inputSchema: z\n .object({\n title: z.string().trim().min(1).max(512).describe('Short title, as it should read on the card.'),\n description: z\n .string()\n .trim()\n .min(1)\n .max(8000)\n .describe('What needs doing and why; becomes the card description its runs start from.'),\n repository: repositorySchema.optional(),\n })\n .strict(),\n execute: async ({ title, description, repository }) => {\n if (repository) await requireRepository(repository);\n const created = await createFactoryWorkItem({\n workItems: deps.workItems,\n boards: await toBoardSource(deps.boards).load(project),\n transitionService: deps.transitionService,\n intakeRoutes: deps.intakeRoutes,\n audit,\n ...project,\n userId: scope.userId,\n ...(scope.actorProfile ? { origin: { actorProfile: scope.actorProfile } } : {}),\n input: { title, description, ...(repository ? { metadata: { repository } } : {}) },\n });\n if (created.status === 'refused') throw new Error(created.message);\n if (created.status === 'rejected') throw new Error(`The board refused the new item: ${created.reason}`);\n const { item } = created;\n // The card exists from here on: report follow-up failures alongside it\n // rather than failing the call, so the agent doesn't file it twice.\n const warnings: string[] = [];\n try {\n await follow(item, 'created');\n } catch (error) {\n warnings.push(\n `This session does not follow it yet: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return warnings.length ? { ...briefItem(item), warnings } : briefItem(item);\n },\n }),\n\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description:\n \"Move a work item to another stage of its board, as the person you are working with. The board's rules decide whether the move is allowed and what it starts.\",\n inputSchema: z\n .object({\n workItem: workItemRefSchema,\n stage: z.string().trim().min(1).max(64).describe('Destination stage, e.g. \"planning\" or \"done\".'),\n })\n .strict(),\n execute: async ({ workItem, stage }) => {\n if (!deps.transitionService) throw new Error('Factory stage transitions are not available right now.');\n const item = await requireItem(workItem);\n const parsed = transitionBodySchema.safeParse({\n board: boardForWorkItem(item),\n stage,\n expectedRevision: item.revision,\n requestId: randomUUID(),\n cause: 'factory_tools',\n });\n if (!parsed.success) throw new Error(`\"${stage}\" is not a valid stage name.`);\n const result = await deps.transitionService.transition({\n ...parsed.data,\n ...project,\n workItemId: item.id,\n ...(scope.interactive\n ? {\n actor: { type: 'human' as const, id: scope.userId },\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n ingress: { ...parsed.data.ingress, identity: `human:${scope.userId}:${parsed.data.ingress.identity}` },\n }\n : {\n // Nobody signed in started this turn: move as this session's agent, so the\n // plan gate and the agent's done gates apply and the move arms no runs.\n actor: { type: 'agent' as const, bindingId: `session:${scope.sessionId}`, role: 'session' },\n ingress: {\n type: 'agent' as const,\n identity: `session:${scope.sessionId}:${parsed.data.ingress.identity}`,\n },\n }),\n });\n if (result.status === 'rejected') throw new Error(`The move was refused (${result.code}): ${result.reason}`);\n // The move can start a phase session the Factory owns. Following the card is what lets\n // this session hear when that run waits on someone, and answer it from here.\n // The card has moved by now: a failed follow is reported with the move, not instead of it.\n const moved = { workItemId: item.id, stage: result.stage, revision: result.revision };\n try {\n await follow(item, 'moved');\n } catch (error) {\n return {\n ...moved,\n warnings: [\n `This session does not follow it yet: ${error instanceof Error ? error.message : String(error)}`,\n ],\n };\n }\n return moved;\n },\n }),\n\n factory_update_work_item: createTool({\n id: 'factory_update_work_item',\n description:\n \"Edit a work item's fields as the person you are working with: its title, description, the repository its runs use, or its parent item. Move stages with factory_transition_work_item and start roles with factory_start_session.\",\n inputSchema: z\n .object({\n workItem: workItemRefSchema,\n title: z.string().trim().min(1).max(500).optional().describe('New card title.'),\n description: z\n .string()\n .trim()\n .max(8000)\n .optional()\n .describe('New card description; an empty string clears it.'),\n repository: repositorySchema.optional(),\n parentWorkItem: workItemRefSchema\n .nullable()\n .optional()\n .describe('Parent work item (id or #number), or null to detach it from its parent.'),\n })\n .strict()\n .refine(input => Object.keys(input).some(key => key !== 'workItem'), 'Pass at least one field to change.'),\n execute: async ({ workItem, title, description, repository, parentWorkItem }) => {\n const item = await requireItem(workItem);\n if (repository) await requireRepository(repository, item);\n let parentWorkItemId: string | null | undefined;\n if (parentWorkItem === null) parentWorkItemId = null;\n else if (parentWorkItem !== undefined) parentWorkItemId = (await requireItem(parentWorkItem)).id;\n const patch: UpdateWorkItemInput = {\n ...(title !== undefined ? { title } : {}),\n ...(description !== undefined ? { description: description || null } : {}),\n ...(repository ? { metadata: { repository } } : {}),\n ...(parentWorkItemId !== undefined ? { parentWorkItemId } : {}),\n };\n let updated: Awaited<ReturnType<WorkItemsStorage['update']>>;\n try {\n updated = await deps.workItems.update({ orgId: scope.orgId, id: item.id, userId: scope.userId, patch });\n } catch (error) {\n if (error instanceof WorkItemRelationError) throw new Error(`The parent was refused: ${error.message}`);\n throw error;\n }\n if (!updated) throw workItemNotFound(workItem);\n const fields = [\n ...(title !== undefined ? ['title'] : []),\n ...(description !== undefined ? ['description'] : []),\n ...(repository ? ['metadata'] : []),\n ...(parentWorkItemId !== undefined ? ['parentWorkItemId'] : []),\n ];\n await audit({\n action: 'factory.work_item.updated',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'work_item', id: updated.item.id, name: updated.item.title }],\n metadata: { fields, cause: 'factory_tools' },\n });\n const metadata = updated.item.metadata ?? {};\n return {\n workItem: briefItem(updated.item),\n updated: fields.map(field => (field === 'metadata' ? 'repository' : field)),\n repository: typeof metadata.repository === 'string' ? metadata.repository : null,\n parentWorkItemId: updated.item.parentWorkItemId,\n };\n },\n }),\n\n factory_retry_decision: createTool({\n id: 'factory_retry_decision',\n description:\n 'Retry one failed Factory run once its cause is fixed. Refused when the failure cannot be fixed by retrying or the item has moved on.',\n inputSchema: z.object({ decisionId }).strict(),\n execute: async ({ decisionId }) =>\n settled(\n await retryFactoryDecision({\n workItems: deps.workItems,\n boards: await toBoardSource(deps.boards).load(project),\n ...project,\n decisionId,\n }),\n ),\n }),\n\n factory_dismiss_decision: createTool({\n id: 'factory_dismiss_decision',\n description: 'Dismiss one proposed Factory run that is no longer wanted.',\n inputSchema: z.object({ decisionId }).strict(),\n execute: async ({ decisionId }) => {\n requirePerson(scope, 'dismiss a proposed run');\n return settled(\n await dismissFactoryDecision({\n workItems: deps.workItems,\n audit,\n ...project,\n userId: scope.userId,\n decisionId,\n }),\n );\n },\n }),\n\n factory_resolve_proposal: createTool({\n id: 'factory_resolve_proposal',\n description:\n \"Approve or dismiss one proposed Factory run. Approving starts the run and lets the item's later runs start without asking.\",\n inputSchema: z.object({ decisionId, action: z.enum(['approve', 'dismiss']) }).strict(),\n execute: async ({ decisionId, action }) => {\n requirePerson(scope, 'approve or dismiss a proposed run');\n return settled(\n await resolveFactoryProposal({\n workItems: deps.workItems,\n audit,\n ...project,\n userId: scope.userId,\n decisionId,\n action,\n }),\n );\n },\n }),\n\n factory_subscribe_work_item: createTool({\n id: 'factory_subscribe_work_item',\n description:\n 'Follow a work item from this session, so you hear about its progress and its sessions report to you. Items you file or start are followed already.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await requireItem(workItem);\n const subscription = await follow(item, 'subscribed');\n return { workItem: briefItem(item), subscribed: true, reason: subscription.reason };\n },\n }),\n\n factory_unsubscribe_work_item: createTool({\n id: 'factory_unsubscribe_work_item',\n description: 'Stop following a work item from this session.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await requireItem(workItem);\n const removed = await deps.workItems.unsubscribeFromWorkItem({\n orgId: scope.orgId,\n workItemId: item.id,\n sessionId: scope.sessionId,\n });\n return { workItem: briefItem(item), subscribed: false, wasSubscribed: removed };\n },\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmDA,MAAM,mBAAmB,EACtB,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,CAAC,CAAC,CACN,IAAI,GAAG,CAAC,CACR,MAAM,sBAAsB,qDAAmD,CAAC,CAChF,SAAS,qDAAqD;AAEjE,MAAM,aAAa,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS,sDAAsD;AAE3G,SAAS,UAAU,MAAY;CAC7B,OAAO;EACL,IAAI,KAAK;EACT,QAAQ,eAAe,IAAI;EAC3B,OAAO,SAAS,KAAK,OAAA,GAAe;EACpC,OAAO,cAAc,IAAI;EACzB,KACE,mBAAmB;GACjB,kBAAkB,KAAK;GACvB,OAAO,iBAAiB,IAAI;GAC5B,YAAY,KAAK;EACnB,CAAC,KAAK;CACV;AACF;AAEA,SAAS,QAAQ,QAAqC;CACpD,IAAI,CAAC,OAAO,IAAI,MAAM,IAAI,MAAM,OAAO,OAAO;CAC9C,MAAM,EAAE,aAAa;CACrB,OAAO;EAAE,YAAY,SAAS;EAAI,QAAQ,SAAS;EAAQ,YAAY,SAAS;CAAW;AAC7F;;AAGA,SAAgB,2BACd,OACA,MACk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IACvC,MAAM,UAAU,MAAM,KAAK,UAAU,wBAAwB;KAC3D,OAAO,MAAM;KACb,YAAY,KAAK;KACjB,WAAW,MAAM;IACnB,CAAC;IACD,OAAO;KAAE,UAAU,UAAU,IAAI;KAAG,YAAY;KAAO,eAAe;IAAQ;GAChF;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"work-item-tools.js","names":[],"sources":["../../src/tools/work-item-tools.ts"],"sourcesContent":["/**\n * Factory tools that change work items: file one, move it, settle its\n * decisions, and follow it. They act as the session's person (a human actor),\n * through the same code the board's routes use.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\nimport { boardForWorkItem } from '../boards/index.js';\n\nimport type { BoardRegistry } from '../boards/index.js';\nimport type { IntakeRoutesReader } from '../boards/intake-routing.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factoryWorkItemUrl } from '../links.js';\nimport { transitionBodySchema } from '../routes/contracts.js';\nimport type { FactoryTransitionService } from '../rules/transition-service.js';\nimport { MAX_BOARD_IDENTIFIER_LENGTH } from '../rules/validation.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { IntakeEvaluator } from '../storage/domains/boards/base.js';\nimport { WorkItemRelationError } from '../storage/domains/work-items/base.js';\nimport type { UpdateWorkItemInput, Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { workItemNumber } from '../work-items/card-number.js';\nimport { createFactoryWorkItem } from '../work-items/create-work-item.js';\nimport type { FactoryAuditEmit } from '../work-items/create-work-item.js';\nimport {\n dismissFactoryDecision,\n resolveFactoryProposal,\n retryFactoryDecision,\n} from '../work-items/decision-actions.js';\nimport type { FactoryDecisionActionResult } from '../work-items/decision-actions.js';\nimport { MAX_TEXT, findWorkItem, workItemRefSchema, truncate, workItemNotFound, workItemStage } from './read-tools.js';\nimport { requirePerson } from './scope.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport interface FactoryWorkItemToolDependencies {\n workItems: WorkItemsStorage;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** The project's intake routes, which place a filed card. */\n intakeRoutes?: IntakeRoutesReader;\n /** Which evaluator places a filed card; the old `route-list` by default. */\n intakeEvaluator?: IntakeEvaluator;\n /** Governed stage moves; filing and moving items refuse while it is unavailable. */\n transitionService: Pick<FactoryTransitionService, 'transition'> | undefined;\n /** Writes audit rows with an explicit actor; tool calls have no HTTP request to read one from. */\n auditRecorder: AuditRecorder;\n /** Finds the caller session's source-control provider, whose linked repositories a card can name. */\n sessions: Pick<SourceControlSessionLookup, 'getSourceControlBySessionId'>;\n}\n\nconst repositorySchema = z\n .string()\n .trim()\n .min(3)\n .max(200)\n .regex(/^[^/\\s]+\\/[^/\\s]+$/, 'Use the owner/name form, e.g. \"mastra-ai/mastra\".')\n .describe('A repository linked to this Factory, as owner/name.');\n\nconst decisionId = z.string().trim().uuid().describe('Decision id, from factory_list_attention or inspect.');\n\nfunction briefItem(item: Card) {\n return {\n id: item.id,\n number: workItemNumber(item),\n title: truncate(item.title, MAX_TEXT),\n stage: workItemStage(item),\n url:\n factoryWorkItemUrl({\n factoryProjectId: item.factoryProjectId,\n board: boardForWorkItem(item),\n workItemId: item.id,\n }) ?? null,\n };\n}\n\nfunction workItemLabel(item: Card): string {\n const number = workItemNumber(item);\n return number === null ? `\"${item.title}\"` : `#${number}`;\n}\n\nfunction settled(result: FactoryDecisionActionResult) {\n if (!result.ok) throw new Error(result.message);\n const { decision } = result;\n return { decisionId: decision.id, status: decision.status, workItemId: decision.workItemId };\n}\n\n/** The work-item write and subscription tools for one user session's turn. */\nexport function createFactoryWorkItemTools(\n scope: FactoryToolScope,\n deps: FactoryWorkItemToolDependencies,\n): IntegrationTools {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n const audit: FactoryAuditEmit = async input => {\n await deps.auditRecorder.record({\n orgId: scope.orgId,\n // Turns nobody signed in started are recorded as this session's agent, as their moves are.\n actorId: scope.interactive ? scope.userId : `agent:session:${scope.sessionId}`,\n actorType: scope.interactive ? 'human' : 'agent',\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n ...input,\n });\n };\n const requireItem = async (ref: string) => {\n const item = await findWorkItem(deps.workItems, scope, ref);\n if (!item) throw workItemNotFound(ref);\n return item;\n };\n /**\n * Check `slug` is a repository linked to this Factory and that a card with\n * `metadata` would run in it (a card synced from an issue follows the\n * issue's repository, which a slug can't override).\n */\n const requireRepository = async (slug: string, item?: Pick<Card, 'metadata' | 'workItem'>) => {\n const sourceControl = await deps.sessions.getSourceControlBySessionId(scope.sessionId);\n if (!sourceControl) throw new Error('This session has no source-control provider to look repositories up in.');\n const resolve = (repository?: string) =>\n resolveWorkItemRepository({\n sourceControl,\n ...project,\n item: {\n metadata: repository ? { repository } : (item?.metadata ?? null),\n workItem: item?.workItem ?? { metadata: null },\n },\n });\n const resolution = await resolve(slug);\n if (resolution.status === 'resolved' && resolution.slug === slug) return;\n if (resolution.status === 'resolved') {\n throw new Error(`This card runs in ${resolution.slug}, which comes from its linked issue and can't be changed.`);\n }\n const linked = await resolve();\n const candidates =\n linked.status === 'ambiguous' ? linked.candidates : linked.status === 'resolved' ? [linked.slug] : [];\n throw new Error(\n candidates.length > 0\n ? `${slug} is not linked to this Factory. Linked repositories: ${candidates.join(', ')}.`\n : `${slug} is not linked to this Factory, and it has no linked repositories.`,\n );\n };\n const follow = (item: Card, reason: 'created' | 'moved' | 'started' | 'subscribed') =>\n deps.workItems.subscribeToWorkItem({\n ...project,\n workItemId: item.id,\n sessionId: scope.sessionId,\n threadId: scope.threadId,\n resourceId: scope.resourceId,\n userId: scope.userId,\n reason,\n });\n /**\n * Approving or retrying a run starts it from this session, so this session follows its card as a\n * move does: the run's report and anything it waits on reach this session, which can pass them on.\n * Only approval acts as the person; a retry keeps the run's original approver. The run has\n * started by now: a failed read or follow is reported with it, not instead of it.\n */\n const followStartedRun = async (result: ReturnType<typeof settled>) => {\n if (!result.workItemId) return result;\n let url: string | null = null;\n try {\n const item = await deps.workItems.getForProject(scope.orgId, scope.factoryProjectId, result.workItemId);\n if (!item) return result;\n url =\n factoryWorkItemUrl({\n factoryProjectId: item.factoryProjectId,\n board: boardForWorkItem(item),\n workItemId: item.id,\n }) ?? null;\n await follow(item, 'started');\n return { ...result, url };\n } catch (error) {\n return {\n ...result,\n url,\n warnings: [`This session does not follow it yet: ${error instanceof Error ? error.message : String(error)}`],\n };\n }\n };\n\n return {\n factory_create_work_item: createTool({\n id: 'factory_create_work_item',\n description:\n \"File a new work item on this Factory for the person you are working with, on the board the project's intake rules pick (or the board named). It enters its board's first phase, or the phase an intake rule names, and this session follows it. Check factory_list_work_items for an existing item first. When no intake rule takes it, the call is refused: ask the person which board it belongs on and call again with that board. Name the repository when you know it; a run on a card that names none determines it from the card.\",\n inputSchema: z\n .object({\n title: z.string().trim().min(1).max(512).describe('Short title, as it should read on the card.'),\n description: z\n .string()\n .trim()\n .min(1)\n .max(8000)\n .describe('What needs doing and why; becomes the card description its runs start from.'),\n repository: repositorySchema.optional(),\n board: z\n .string()\n .trim()\n .min(1)\n .max(MAX_BOARD_IDENTIFIER_LENGTH)\n .optional()\n .describe(\"The board's key, when the person picked one; files it in that board's first phase.\"),\n })\n .strict(),\n execute: async ({ title, description, repository, board }) => {\n if (repository) await requireRepository(repository);\n const created = await createFactoryWorkItem({\n workItems: deps.workItems,\n boards: await toBoardSource(deps.boards).load(project),\n transitionService: deps.transitionService,\n intakeRoutes: deps.intakeRoutes,\n intakeEvaluator: deps.intakeEvaluator,\n audit,\n ...project,\n userId: scope.userId,\n ...(scope.actorProfile ? { origin: { actorProfile: scope.actorProfile } } : {}),\n input: {\n title,\n description,\n ...(board ? { board } : {}),\n ...(repository ? { metadata: { repository } } : {}),\n },\n });\n if (created.status === 'refused') throw new Error(created.message);\n if (created.status === 'rejected') throw new Error(`The board refused the new item: ${created.reason}`);\n const { item } = created;\n // The card exists from here on: report follow-up failures alongside it\n // rather than failing the call, so the agent doesn't file it twice.\n const warnings: string[] = [];\n try {\n await follow(item, 'created');\n } catch (error) {\n warnings.push(\n `This session does not follow it yet: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return warnings.length ? { ...briefItem(item), warnings } : briefItem(item);\n },\n }),\n\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description: [\n \"Move a work item to another stage of its board, or with `rerun` run the stage it is already in again, as the person you are working with: the same requests the board's own move and Start buttons send.\",\n \"The board's rules decide whether the move is allowed and what it starts. The run it starts counts as approved by that person, so it does not wait in the approval queue. The result has the card's `url`, to link it where you report the move.\",\n 'Use it when someone asks for a card\\'s own stage work, such as \"review this pull request\" on a pull request that has a card: the card\\'s review is recorded on the card and posted on the pull request.',\n 'When the person asks for a side session, a review in this chat, or work the stage does not do (pushing fixes to a pull request, taking it over), do that instead.',\n ].join(' '),\n inputSchema: z\n .object({\n workItem: workItemRefSchema,\n stage: z\n .string()\n .trim()\n .min(1)\n .max(64)\n .describe('Destination stage key, as factory_inspect_work_item lists it (e.g. \"planning\" or \"done\").'),\n rerun: z\n .boolean()\n .optional()\n .describe(\n \"With the stage the card is already in: run it again, as the board's Start button does. Without it, a request for the card's own stage changes nothing and says what the stage is doing.\",\n ),\n })\n .strict(),\n execute: async ({ workItem, stage, rerun: rerunRequested }) => {\n if (!deps.transitionService) throw new Error('Factory stage transitions are not available right now.');\n const item = await requireItem(workItem);\n // Following the card is what lets this session hear when its run waits on someone, and\n // answer it from here. It comes after the request: a failed follow is reported with it.\n const followed = async <T extends object>(result: T) => {\n try {\n await follow(item, 'moved');\n return result;\n } catch (error) {\n return {\n ...result,\n warnings: [\n `This session does not follow it yet: ${error instanceof Error ? error.message : String(error)}`,\n ],\n };\n }\n };\n // The card's page, so a chat can link the card it moved; null without a public URL.\n const url =\n factoryWorkItemUrl({\n factoryProjectId: item.factoryProjectId,\n board: boardForWorkItem(item),\n workItemId: item.id,\n }) ?? null;\n const sameStage = item.stages.length === 1 && item.stages[0] === stage;\n // Already there: report the stage instead of starting it again without being asked, which\n // would rerun a finished review or plan on a \"move it to review\".\n if (sameStage && rerunRequested !== true) {\n const held = (\n await deps.workItems.listDeferredDecisions(scope.orgId, scope.factoryProjectId, {\n workItemId: item.id,\n statuses: ['proposed'],\n })\n ).filter(decision => decision.decision.type === 'invokeSkill').length;\n return followed({\n workItemId: item.id,\n url,\n stage,\n revision: item.revision,\n unchanged: true,\n message:\n `${workItemLabel(item)} is already in ${stage}` +\n (held > 0 ? ', and its run there is waiting for approval.' : '.') +\n \" Pass rerun: true to run the stage again, as the board's Start button does; factory_inspect_work_item shows its sessions and runs.\",\n });\n }\n // The board's Start button sends the card's own stage with `reenter`; the rules decide the rest.\n const rerun = sameStage;\n // Rerunning starts a run approved by whoever asks, so like the button it needs a person.\n if (rerun && !scope.interactive) {\n throw new Error(\n `Running ${stage} again on ${workItemLabel(item)} needs a person in this turn: ask them to request it from a signed-in chat or the board.`,\n );\n }\n const parsed = transitionBodySchema.safeParse({\n board: boardForWorkItem(item),\n stage,\n expectedRevision: item.revision,\n requestId: randomUUID(),\n cause: 'factory_tools',\n ...(rerun ? { reenter: true } : {}),\n });\n if (!parsed.success) throw new Error(`\"${stage}\" is not a valid stage name.`);\n const result = await deps.transitionService.transition({\n ...parsed.data,\n ...project,\n workItemId: item.id,\n ...(scope.interactive\n ? {\n actor: { type: 'human' as const, id: scope.userId },\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n ingress: { ...parsed.data.ingress, identity: `human:${scope.userId}:${parsed.data.ingress.identity}` },\n }\n : {\n // Nobody signed in started this turn: move as this session's agent, so the\n // plan gate and the agent's done gates apply and the move arms no runs.\n actor: { type: 'agent' as const, bindingId: `session:${scope.sessionId}`, role: 'session' },\n ingress: {\n type: 'agent' as const,\n identity: `session:${scope.sessionId}:${parsed.data.ingress.identity}`,\n },\n }),\n });\n if (result.status === 'rejected') throw new Error(`The move was refused (${result.code}): ${result.reason}`);\n // The move can start a phase session the Factory owns; the card has moved by now.\n return followed({\n workItemId: item.id,\n url,\n stage: result.stage,\n revision: result.revision,\n ...(rerun ? { reran: true } : {}),\n });\n },\n }),\n\n factory_update_work_item: createTool({\n id: 'factory_update_work_item',\n description:\n \"Edit a work item's fields as the person you are working with: its title, description, the repository its runs use, or its parent item. Move stages, or rerun the stage a card is in, with factory_transition_work_item.\",\n inputSchema: z\n .object({\n workItem: workItemRefSchema,\n title: z.string().trim().min(1).max(500).optional().describe('New card title.'),\n description: z\n .string()\n .trim()\n .max(8000)\n .optional()\n .describe('New card description; an empty string clears it.'),\n repository: repositorySchema.optional(),\n parentWorkItem: workItemRefSchema\n .nullable()\n .optional()\n .describe('Parent work item (id or #number), or null to detach it from its parent.'),\n })\n .strict()\n .refine(input => Object.keys(input).some(key => key !== 'workItem'), 'Pass at least one field to change.'),\n execute: async ({ workItem, title, description, repository, parentWorkItem }) => {\n const item = await requireItem(workItem);\n if (repository) await requireRepository(repository, item);\n let parentWorkItemId: string | null | undefined;\n if (parentWorkItem === null) parentWorkItemId = null;\n else if (parentWorkItem !== undefined) parentWorkItemId = (await requireItem(parentWorkItem)).id;\n const patch: UpdateWorkItemInput = {\n ...(title !== undefined ? { title } : {}),\n ...(description !== undefined ? { description: description || null } : {}),\n ...(repository ? { metadata: { repository } } : {}),\n ...(parentWorkItemId !== undefined ? { parentWorkItemId } : {}),\n };\n let updated: Awaited<ReturnType<WorkItemsStorage['update']>>;\n try {\n updated = await deps.workItems.update({ orgId: scope.orgId, id: item.id, userId: scope.userId, patch });\n } catch (error) {\n if (error instanceof WorkItemRelationError) throw new Error(`The parent was refused: ${error.message}`);\n throw error;\n }\n if (!updated) throw workItemNotFound(workItem);\n const fields = [\n ...(title !== undefined ? ['title'] : []),\n ...(description !== undefined ? ['description'] : []),\n ...(repository ? ['metadata'] : []),\n ...(parentWorkItemId !== undefined ? ['parentWorkItemId'] : []),\n ];\n await audit({\n action: 'factory.work_item.updated',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'work_item', id: updated.item.id, name: updated.item.title }],\n metadata: { fields, cause: 'factory_tools' },\n });\n const metadata = updated.item.metadata ?? {};\n return {\n workItem: briefItem(updated.item),\n updated: fields.map(field => (field === 'metadata' ? 'repository' : field)),\n repository: typeof metadata.repository === 'string' ? metadata.repository : null,\n parentWorkItemId: updated.item.parentWorkItemId,\n };\n },\n }),\n\n factory_retry_decision: createTool({\n id: 'factory_retry_decision',\n description:\n \"Retry one failed Factory run once its cause is fixed. Refused when the failure cannot be fixed by retrying or the item has moved on. This session follows the run's card, so it hears how the run ends; the result has the card's `url`.\",\n inputSchema: z.object({ decisionId }).strict(),\n execute: async ({ decisionId }) =>\n followStartedRun(\n settled(\n await retryFactoryDecision({\n workItems: deps.workItems,\n boards: await toBoardSource(deps.boards).load(project),\n ...project,\n decisionId,\n }),\n ),\n ),\n }),\n\n factory_dismiss_decision: createTool({\n id: 'factory_dismiss_decision',\n description: 'Dismiss one proposed Factory run that is no longer wanted.',\n inputSchema: z.object({ decisionId }).strict(),\n execute: async ({ decisionId }) => {\n requirePerson(scope, 'dismiss a proposed run');\n return settled(\n await dismissFactoryDecision({\n workItems: deps.workItems,\n audit,\n ...project,\n userId: scope.userId,\n decisionId,\n }),\n );\n },\n }),\n\n factory_resolve_proposal: createTool({\n id: 'factory_resolve_proposal',\n description:\n \"Approve or dismiss one proposed Factory run. Approving starts the run and lets the item's later runs start without asking, and this session follows the run's card, so it hears how the run ends; the result has the card's `url`.\",\n inputSchema: z.object({ decisionId, action: z.enum(['approve', 'dismiss']) }).strict(),\n execute: async ({ decisionId, action }) => {\n requirePerson(scope, 'approve or dismiss a proposed run');\n const result = settled(\n await resolveFactoryProposal({\n workItems: deps.workItems,\n audit,\n ...project,\n userId: scope.userId,\n decisionId,\n action,\n }),\n );\n return action === 'approve' ? followStartedRun(result) : result;\n },\n }),\n\n factory_subscribe_work_item: createTool({\n id: 'factory_subscribe_work_item',\n description:\n 'Follow a work item from this session, so you hear about its progress and its sessions report to you. Items you file or start are followed already.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await requireItem(workItem);\n const subscription = await follow(item, 'subscribed');\n return { workItem: briefItem(item), subscribed: true, reason: subscription.reason };\n },\n }),\n\n factory_unsubscribe_work_item: createTool({\n id: 'factory_unsubscribe_work_item',\n description: 'Stop following a work item from this session.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await requireItem(workItem);\n const removed = await deps.workItems.unsubscribeFromWorkItem({\n ...project,\n workItemId: item.id,\n sessionId: scope.sessionId,\n });\n return { workItem: briefItem(item), subscribed: false, wasSubscribed: removed };\n },\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,mBAAmB,EACtB,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,CAAC,CAAC,CACN,IAAI,GAAG,CAAC,CACR,MAAM,sBAAsB,qDAAmD,CAAC,CAChF,SAAS,qDAAqD;AAEjE,MAAM,aAAa,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS,sDAAsD;AAE3G,SAAS,UAAU,MAAY;CAC7B,OAAO;EACL,IAAI,KAAK;EACT,QAAQ,eAAe,IAAI;EAC3B,OAAO,SAAS,KAAK,OAAA,GAAe;EACpC,OAAO,cAAc,IAAI;EACzB,KACE,mBAAmB;GACjB,kBAAkB,KAAK;GACvB,OAAO,iBAAiB,IAAI;GAC5B,YAAY,KAAK;EACnB,CAAC,KAAK;CACV;AACF;AAEA,SAAS,cAAc,MAAoB;CACzC,MAAM,SAAS,eAAe,IAAI;CAClC,OAAO,WAAW,OAAO,IAAI,KAAK,MAAM,KAAK,IAAI;AACn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AE,YAAY,aAAa;IACzC,cAAc,OAAO,mCAAmC;IACxD,MAAM,SAAS,QACb,MAAM,uBAAuB;KAC3B,WAAW,KAAK;KAChB;KACA,GAAG;KACH,QAAQ,MAAM;KACd;KACA;IACF,CAAC,CACH;IACA,OAAO,WAAW,YAAY,iBAAiB,MAAM,IAAI;GAC3D;EACF,CAAC;EAED,6BAA6B,WAAW;GACtC,IAAI;GACJ,aACE;GACF,aAAa,EAAE,OAAO,EAAE,UAAU,kBAAkB,CAAC,CAAC,CAAC,OAAO;GAC9D,SAAS,OAAO,EAAE,eAAe;IAC/B,MAAM,OAAO,MAAM,YAAY,QAAQ;IACvC,MAAM,eAAe,MAAM,OAAO,MAAM,YAAY;IACpD,OAAO;KAAE,UAAU,UAAU,IAAI;KAAG,YAAY;KAAM,QAAQ,aAAa;IAAO;GACpF;EACF,CAAC;EAED,+BAA+B,WAAW;GACxC,IAAI;GACJ,aAAa;GACb,aAAa,EAAE,OAAO,EAAE,UAAU,kBAAkB,CAAC,CAAC,CAAC,OAAO;GAC9D,SAAS,OAAO,EAAE,eAAe;IAC/B,MAAM,OAAO,MAAM,YAAY,QAAQ;IACvC,MAAM,UAAU,MAAM,KAAK,UAAU,wBAAwB;KAC3D,GAAG;KACH,YAAY,KAAK;KACjB,WAAW,MAAM;IACnB,CAAC;IACD,OAAO;KAAE,UAAU,UAAU,IAAI;KAAG,YAAY;KAAO,eAAe;IAAQ;GAChF;EACF,CAAC;CACH;AACF"}
@@ -49,6 +49,10 @@ export declare function legacyGithubWorkItemBranch(branch: string): string | und
49
49
  export declare function pullRequestNumberFromBranch(branch: string): number | undefined;
50
50
  /** The GitLab MR IID encoded in Factory's collision-resistant review branch. */
51
51
  export declare function mergeRequestNumberFromBranch(branch: string): number | undefined;
52
+ export declare const USER_BRANCH_PREFIX = "user/";
53
+ export declare const USER_SESSION_BRANCH_PREFIX = "user/session-";
54
+ export declare const SLACK_SESSION_BRANCH_PREFIX = "slack/";
55
+ export declare function isPersonSessionBranch(branch: string): boolean;
52
56
  /** Whether a provider-reported branch name is safe to show an agent or pass to git. */
53
57
  export declare function isSafeBranchName(value: string): boolean;
54
58
  //# sourceMappingURL=work-item-branch.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-branch.d.ts","sourceRoot":"","sources":["../src/work-item-branch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAEnF;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAC5B,cAAc,GACd,WAAW,GACX,cAAc,GACd,WAAW,GACX,cAAc,GACd,YAAY,GACZ,sBAAsB,GACtB,yBAAyB,GACzB,qBAAqB,GACrB,gBAAgB,GAChB,cAAc,GACd,QAAQ,CAAC;AAEb,MAAM,WAAW,mBAAmB;IAClC,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,oBAAoB,CAAC;IAC7B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAC3C;AAED,qFAAqF;AACrF,wBAAgB,oBAAoB,CAAC,cAAc,EAAE,sBAAsB,GAAG,IAAI,GAAG,SAAS,GAAG,oBAAoB,CAepH;AAOD,mGAAmG;AACnG,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,mBAAmB,EAAE,QAAQ,GAAG,UAAU,CAAC,GAAG,MAAM,GAAG,SAAS,CAOzG;AAED,yHAAyH;AACzH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,IAAI,CAAC,mBAAmB,EAAE,QAAQ,GAAG,UAAU,CAAC,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GACzE,MAAM,CAKR;AAgBD;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,mBAAmB,GAAG,MAAM,CA+BhE;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;I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AgB,mBAAmB,CACjC,IAAI,EAAE,IAAI,CAAC,mBAAmB,EAAE,QAAQ,GAAG,UAAU,CAAC,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GACzE,MAAM,CAKR;AAgBD;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,mBAAmB,GAAG,MAAM,CA+BhE;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAM9G;AAED,+FAA+F;AAC/F,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAG7E;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAI9E;AAED,gFAAgF;AAChF,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAI/E;AAED,eAAO,MAAM,kBAAkB,UAAU,CAAC;AAC1C,eAAO,MAAM,0BAA0B,kBAAkC,CAAC;AAE1E,eAAO,MAAM,2BAA2B,WAAW,CAAC;AAEpD,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAE7D;AAED,uFAAuF;AACvF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAUvD"}
@@ -103,10 +103,16 @@ function mergeRequestNumberFromBranch(branch) {
103
103
  const number = match ? Number(match[1]) : void 0;
104
104
  return number !== void 0 && Number.isSafeInteger(number) ? number : void 0;
105
105
  }
106
+ const USER_BRANCH_PREFIX = "user/";
107
+ const USER_SESSION_BRANCH_PREFIX = `${USER_BRANCH_PREFIX}session-`;
108
+ const SLACK_SESSION_BRANCH_PREFIX = "slack/";
109
+ function isPersonSessionBranch(branch) {
110
+ return branch.startsWith("user/") || branch.startsWith("slack/");
111
+ }
106
112
  /** Whether a provider-reported branch name is safe to show an agent or pass to git. */
107
113
  function isSafeBranchName(value) {
108
114
  return /^[A-Za-z0-9][A-Za-z0-9._/@+-]*$/.test(value) && !value.includes("..") && !value.includes("//") && !value.includes("@{") && !value.endsWith(".") && !value.endsWith("/") && !value.endsWith(".lock");
109
115
  }
110
- export { isSafeBranchName, legacyGithubWorkItemBranch, mergeRequestNumberFromBranch, pullRequestBranch, pullRequestNumberFromBranch, workItemBranch, workItemBranchSource, workItemNumber, workItemThreadTitle };
116
+ export { SLACK_SESSION_BRANCH_PREFIX, USER_BRANCH_PREFIX, USER_SESSION_BRANCH_PREFIX, isPersonSessionBranch, isSafeBranchName, legacyGithubWorkItemBranch, mergeRequestNumberFromBranch, pullRequestBranch, pullRequestNumberFromBranch, workItemBranch, workItemBranchSource, workItemNumber, workItemThreadTitle };
111
117
 
112
118
  //# sourceMappingURL=work-item-branch.js.map