@mastra/factory 0.28.0-alpha.1 → 0.28.0-alpha.11

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 (662) hide show
  1. package/README.md +363 -162
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/auth.js +12 -6
  4. package/dist/auth.js.map +1 -1
  5. package/dist/boards/board-events.d.ts +23 -3
  6. package/dist/boards/board-events.d.ts.map +1 -1
  7. package/dist/boards/board-events.js +44 -7
  8. package/dist/boards/board-events.js.map +1 -1
  9. package/dist/boards/board-writes.d.ts +2 -2
  10. package/dist/boards/board-writes.d.ts.map +1 -1
  11. package/dist/boards/board-writes.js +23 -9
  12. package/dist/boards/board-writes.js.map +1 -1
  13. package/dist/boards/card-facts.d.ts +3 -1
  14. package/dist/boards/card-facts.d.ts.map +1 -1
  15. package/dist/boards/card-facts.js +30 -4
  16. package/dist/boards/card-facts.js.map +1 -1
  17. package/dist/boards/default-board.d.ts +7 -0
  18. package/dist/boards/default-board.d.ts.map +1 -0
  19. package/dist/boards/default-board.js +10 -0
  20. package/dist/boards/default-board.js.map +1 -0
  21. package/dist/boards/define-board.d.ts +40 -18
  22. package/dist/boards/define-board.d.ts.map +1 -1
  23. package/dist/boards/define-board.js +64 -42
  24. package/dist/boards/define-board.js.map +1 -1
  25. package/dist/boards/index.d.ts +6 -9
  26. package/dist/boards/index.d.ts.map +1 -1
  27. package/dist/boards/index.js +6 -20
  28. package/dist/boards/intake-routing.d.ts +29 -9
  29. package/dist/boards/intake-routing.d.ts.map +1 -1
  30. package/dist/boards/intake-routing.js +72 -20
  31. package/dist/boards/intake-routing.js.map +1 -1
  32. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  33. package/dist/boards/legacy-plan-role.js +7 -2
  34. package/dist/boards/legacy-plan-role.js.map +1 -1
  35. package/dist/boards/phase-automation.d.ts +7 -0
  36. package/dist/boards/phase-automation.d.ts.map +1 -1
  37. package/dist/boards/phase-automation.js +16 -5
  38. package/dist/boards/phase-automation.js.map +1 -1
  39. package/dist/boards/phase-runner.d.ts +18 -10
  40. package/dist/boards/phase-runner.d.ts.map +1 -1
  41. package/dist/boards/phase-runner.js +39 -34
  42. package/dist/boards/phase-runner.js.map +1 -1
  43. package/dist/boards/project-boards.d.ts +57 -11
  44. package/dist/boards/project-boards.d.ts.map +1 -1
  45. package/dist/boards/project-boards.js +161 -34
  46. package/dist/boards/project-boards.js.map +1 -1
  47. package/dist/boards/registry.d.ts +7 -1
  48. package/dist/boards/registry.d.ts.map +1 -1
  49. package/dist/boards/registry.js +19 -4
  50. package/dist/boards/registry.js.map +1 -1
  51. package/dist/boards/relocate.d.ts +1 -1
  52. package/dist/boards/relocate.d.ts.map +1 -1
  53. package/dist/boards/relocate.js +3 -2
  54. package/dist/boards/relocate.js.map +1 -1
  55. package/dist/boards/review.d.ts +5 -2
  56. package/dist/boards/review.d.ts.map +1 -1
  57. package/dist/boards/review.js +12 -11
  58. package/dist/boards/review.js.map +1 -1
  59. package/dist/boards/semantics.d.ts +160 -20
  60. package/dist/boards/semantics.d.ts.map +1 -1
  61. package/dist/boards/semantics.js +255 -23
  62. package/dist/boards/semantics.js.map +1 -1
  63. package/dist/boards/stored-board.d.ts +32 -18
  64. package/dist/boards/stored-board.d.ts.map +1 -1
  65. package/dist/boards/stored-board.js +31 -97
  66. package/dist/boards/stored-board.js.map +1 -1
  67. package/dist/boards/work-migrations.d.ts +43 -0
  68. package/dist/boards/work-migrations.d.ts.map +1 -0
  69. package/dist/boards/work-migrations.js +353 -0
  70. package/dist/boards/work-migrations.js.map +1 -0
  71. package/dist/boards/work-routes.d.ts +58 -0
  72. package/dist/boards/work-routes.d.ts.map +1 -0
  73. package/dist/boards/work-routes.js +270 -0
  74. package/dist/boards/work-routes.js.map +1 -0
  75. package/dist/boards/work-seeds.d.ts +9 -0
  76. package/dist/boards/work-seeds.d.ts.map +1 -0
  77. package/dist/boards/work-seeds.js +56 -0
  78. package/dist/boards/work-seeds.js.map +1 -0
  79. package/dist/boards/work.d.ts +8 -19
  80. package/dist/boards/work.d.ts.map +1 -1
  81. package/dist/boards/work.js +33 -281
  82. package/dist/boards/work.js.map +1 -1
  83. package/dist/capabilities/version-control.d.ts +6 -1
  84. package/dist/capabilities/version-control.d.ts.map +1 -1
  85. package/dist/environment/build-runner.d.ts.map +1 -1
  86. package/dist/environment/build-runner.js +2 -2
  87. package/dist/environment/build-runner.js.map +1 -1
  88. package/dist/environment/build-schedule.js +1 -1
  89. package/dist/environment/build-schedule.js.map +1 -1
  90. package/dist/environment/build-workflow.d.ts.map +1 -1
  91. package/dist/environment/build-workflow.js +6 -5
  92. package/dist/environment/build-workflow.js.map +1 -1
  93. package/dist/environment/build.d.ts +17 -4
  94. package/dist/environment/build.d.ts.map +1 -1
  95. package/dist/environment/build.js +35 -10
  96. package/dist/environment/build.js.map +1 -1
  97. package/dist/environment/heads.d.ts +1 -1
  98. package/dist/environment/heads.d.ts.map +1 -1
  99. package/dist/environment/heads.js +4 -1
  100. package/dist/environment/heads.js.map +1 -1
  101. package/dist/environment/repository-access.d.ts +13 -0
  102. package/dist/environment/repository-access.d.ts.map +1 -0
  103. package/dist/environment/repository-access.js +55 -0
  104. package/dist/environment/repository-access.js.map +1 -0
  105. package/dist/factory.d.ts +34 -7
  106. package/dist/factory.d.ts.map +1 -1
  107. package/dist/factory.js +161 -133
  108. package/dist/factory.js.map +1 -1
  109. package/dist/feed-events.d.ts +4 -4
  110. package/dist/feed-events.d.ts.map +1 -1
  111. package/dist/feed-events.js +6 -6
  112. package/dist/feed-events.js.map +1 -1
  113. package/dist/index.d.ts +7 -2
  114. package/dist/index.d.ts.map +1 -1
  115. package/dist/index.js +5 -3
  116. package/dist/integrations/base.d.ts +6 -13
  117. package/dist/integrations/base.d.ts.map +1 -1
  118. package/dist/integrations/closing-references.d.ts +15 -0
  119. package/dist/integrations/closing-references.d.ts.map +1 -0
  120. package/dist/integrations/closing-references.js +69 -0
  121. package/dist/integrations/closing-references.js.map +1 -0
  122. package/dist/integrations/github/default-rules.d.ts +15 -66
  123. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  124. package/dist/integrations/github/default-rules.js +129 -73
  125. package/dist/integrations/github/default-rules.js.map +1 -1
  126. package/dist/integrations/github/integration.d.ts.map +1 -1
  127. package/dist/integrations/github/integration.js +7 -3
  128. package/dist/integrations/github/integration.js.map +1 -1
  129. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  130. package/dist/integrations/github/issue-reconciler.js +5 -3
  131. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  132. package/dist/integrations/github/provenance.js +1 -1
  133. package/dist/integrations/github/provenance.js.map +1 -1
  134. package/dist/integrations/github/pull-request-source.d.ts +8 -0
  135. package/dist/integrations/github/pull-request-source.d.ts.map +1 -0
  136. package/dist/integrations/github/pull-request-source.js +17 -0
  137. package/dist/integrations/github/pull-request-source.js.map +1 -0
  138. package/dist/integrations/github/reconcile-worker.d.ts +5 -1
  139. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  140. package/dist/integrations/github/reconcile-worker.js +39 -6
  141. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  142. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -1
  143. package/dist/integrations/github/review-status-reporter.js +7 -3
  144. package/dist/integrations/github/review-status-reporter.js.map +1 -1
  145. package/dist/integrations/github/routes.d.ts +4 -3
  146. package/dist/integrations/github/routes.d.ts.map +1 -1
  147. package/dist/integrations/github/routes.js +10 -87
  148. package/dist/integrations/github/routes.js.map +1 -1
  149. package/dist/integrations/github/rules.d.ts +79 -7
  150. package/dist/integrations/github/rules.d.ts.map +1 -1
  151. package/dist/integrations/github/rules.js +426 -102
  152. package/dist/integrations/github/rules.js.map +1 -1
  153. package/dist/integrations/github/sandbox.d.ts +10 -2
  154. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  155. package/dist/integrations/github/sandbox.js +20 -4
  156. package/dist/integrations/github/sandbox.js.map +1 -1
  157. package/dist/integrations/github/session-subscriptions.js +2 -2
  158. package/dist/integrations/github/session-subscriptions.js.map +1 -1
  159. package/dist/integrations/github/token-refresh.d.ts +2 -1
  160. package/dist/integrations/github/token-refresh.d.ts.map +1 -1
  161. package/dist/integrations/github/token-refresh.js.map +1 -1
  162. package/dist/integrations/gitlab/agent-tools.js +1 -1
  163. package/dist/integrations/gitlab/default-rules.d.ts +73 -31
  164. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  165. package/dist/integrations/gitlab/default-rules.js +106 -43
  166. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  167. package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
  168. package/dist/integrations/gitlab/issue-reconciler.js +2 -1
  169. package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
  170. package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
  171. package/dist/integrations/gitlab/merge-request-reconciler.js +12 -5
  172. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  173. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  174. package/dist/integrations/gitlab/routes.js +1 -3
  175. package/dist/integrations/gitlab/routes.js.map +1 -1
  176. package/dist/integrations/gitlab/rules.d.ts +6 -1
  177. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  178. package/dist/integrations/gitlab/rules.js +119 -30
  179. package/dist/integrations/gitlab/rules.js.map +1 -1
  180. package/dist/integrations/gitlab/session-subscriptions.js +1 -1
  181. package/dist/integrations/incidentio/agent-tools.js +6 -6
  182. package/dist/integrations/incidentio/agent-tools.js.map +1 -1
  183. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
  184. package/dist/integrations/incidentio/default-rules.js +3 -3
  185. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  186. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  187. package/dist/integrations/incidentio/issue-reconciler.js +2 -1
  188. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  189. package/dist/integrations/incidentio/routes.d.ts +2 -2
  190. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  191. package/dist/integrations/incidentio/routes.js +10 -13
  192. package/dist/integrations/incidentio/routes.js.map +1 -1
  193. package/dist/integrations/incidentio/rules.d.ts +4 -4
  194. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  195. package/dist/integrations/incidentio/rules.js +18 -14
  196. package/dist/integrations/incidentio/rules.js.map +1 -1
  197. package/dist/integrations/issue-reconciler.js +1 -1
  198. package/dist/integrations/issue-reconciler.js.map +1 -1
  199. package/dist/integrations/jira/agent-tools.js +1 -1
  200. package/dist/integrations/jira/binding-scope.d.ts +5 -6
  201. package/dist/integrations/jira/binding-scope.d.ts.map +1 -1
  202. package/dist/integrations/jira/binding-scope.js +9 -11
  203. package/dist/integrations/jira/binding-scope.js.map +1 -1
  204. package/dist/integrations/jira/default-rules.d.ts.map +1 -1
  205. package/dist/integrations/jira/default-rules.js +3 -3
  206. package/dist/integrations/jira/default-rules.js.map +1 -1
  207. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  208. package/dist/integrations/jira/issue-reconciler.js +2 -1
  209. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  210. package/dist/integrations/jira/routes.d.ts.map +1 -1
  211. package/dist/integrations/jira/routes.js +3 -5
  212. package/dist/integrations/jira/routes.js.map +1 -1
  213. package/dist/integrations/jira/rules.d.ts +4 -4
  214. package/dist/integrations/jira/rules.d.ts.map +1 -1
  215. package/dist/integrations/jira/rules.js +18 -14
  216. package/dist/integrations/jira/rules.js.map +1 -1
  217. package/dist/integrations/linear/agent-tools.d.ts +9 -1
  218. package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
  219. package/dist/integrations/linear/agent-tools.js +81 -3
  220. package/dist/integrations/linear/agent-tools.js.map +1 -1
  221. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  222. package/dist/integrations/linear/default-rules.js +3 -3
  223. package/dist/integrations/linear/default-rules.js.map +1 -1
  224. package/dist/integrations/linear/integration.d.ts +4 -1
  225. package/dist/integrations/linear/integration.d.ts.map +1 -1
  226. package/dist/integrations/linear/integration.js +21 -1
  227. package/dist/integrations/linear/integration.js.map +1 -1
  228. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  229. package/dist/integrations/linear/issue-reconciler.js +2 -1
  230. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  231. package/dist/integrations/linear/routes.d.ts +2 -1
  232. package/dist/integrations/linear/routes.d.ts.map +1 -1
  233. package/dist/integrations/linear/routes.js +15 -17
  234. package/dist/integrations/linear/routes.js.map +1 -1
  235. package/dist/integrations/linear/rules.d.ts +4 -4
  236. package/dist/integrations/linear/rules.d.ts.map +1 -1
  237. package/dist/integrations/linear/rules.js +16 -15
  238. package/dist/integrations/linear/rules.js.map +1 -1
  239. package/dist/integrations/platform/connect/session-tools.d.ts +5 -0
  240. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -1
  241. package/dist/integrations/platform/connect/session-tools.js +5 -0
  242. package/dist/integrations/platform/connect/session-tools.js.map +1 -1
  243. package/dist/integrations/platform/github/event-worker.d.ts +4 -1
  244. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  245. package/dist/integrations/platform/github/event-worker.js +39 -3
  246. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  247. package/dist/integrations/platform/github/integration.d.ts +8 -0
  248. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  249. package/dist/integrations/platform/github/integration.js +143 -93
  250. package/dist/integrations/platform/github/integration.js.map +1 -1
  251. package/dist/integrations/platform/jira/agent-tools.js +1 -1
  252. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  253. package/dist/integrations/platform/jira/routes.js +3 -5
  254. package/dist/integrations/platform/jira/routes.js.map +1 -1
  255. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  256. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  257. package/dist/integrations/platform/linear/event-worker.js +1 -1
  258. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  259. package/dist/integrations/platform/linear/integration.d.ts +1 -1
  260. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  261. package/dist/integrations/platform/linear/integration.js +6 -5
  262. package/dist/integrations/platform/linear/integration.js.map +1 -1
  263. package/dist/integrations/slack/chat-tools.js +1 -1
  264. package/dist/integrations/slack/integration.d.ts +0 -2
  265. package/dist/integrations/slack/integration.d.ts.map +1 -1
  266. package/dist/integrations/slack/integration.js +7 -9
  267. package/dist/integrations/slack/integration.js.map +1 -1
  268. package/dist/integrations/slack/reply-tool.js +1 -1
  269. package/dist/integrations/slack/run-error-card.js +1 -0
  270. package/dist/integrations/slack/run-error-card.js.map +1 -1
  271. package/dist/integrations/slack/share-file-tool.js +1 -1
  272. package/dist/integrations/slack/slack.d.ts +13 -22
  273. package/dist/integrations/slack/slack.d.ts.map +1 -1
  274. package/dist/integrations/slack/slack.js +22 -83
  275. package/dist/integrations/slack/slack.js.map +1 -1
  276. package/dist/links.d.ts +1 -2
  277. package/dist/links.d.ts.map +1 -1
  278. package/dist/links.js +4 -4
  279. package/dist/links.js.map +1 -1
  280. package/dist/mcp/routes.js +3 -3
  281. package/dist/mcp/routes.js.map +1 -1
  282. package/dist/provider-display-name.d.ts.map +1 -1
  283. package/dist/provider-display-name.js +1 -0
  284. package/dist/provider-display-name.js.map +1 -1
  285. package/dist/routes/attention-parked.d.ts +1 -0
  286. package/dist/routes/attention-parked.d.ts.map +1 -1
  287. package/dist/routes/attention-parked.js +2 -2
  288. package/dist/routes/attention-parked.js.map +1 -1
  289. package/dist/routes/attention-providers.d.ts +0 -25
  290. package/dist/routes/attention-providers.d.ts.map +1 -1
  291. package/dist/routes/attention-providers.js +2 -150
  292. package/dist/routes/attention-providers.js.map +1 -1
  293. package/dist/routes/attention.d.ts +0 -2
  294. package/dist/routes/attention.d.ts.map +1 -1
  295. package/dist/routes/attention.js +2 -13
  296. package/dist/routes/attention.js.map +1 -1
  297. package/dist/routes/automation-runs.d.ts +5 -1
  298. package/dist/routes/automation-runs.d.ts.map +1 -1
  299. package/dist/routes/automation-runs.js +15 -0
  300. package/dist/routes/automation-runs.js.map +1 -1
  301. package/dist/routes/board-snapshot.d.ts +21 -0
  302. package/dist/routes/board-snapshot.d.ts.map +1 -0
  303. package/dist/routes/board-snapshot.js +58 -0
  304. package/dist/routes/board-snapshot.js.map +1 -0
  305. package/dist/routes/boards.d.ts +2 -2
  306. package/dist/routes/boards.d.ts.map +1 -1
  307. package/dist/routes/boards.js +1 -17
  308. package/dist/routes/boards.js.map +1 -1
  309. package/dist/routes/config.d.ts +11 -1
  310. package/dist/routes/config.d.ts.map +1 -1
  311. package/dist/routes/config.js +120 -22
  312. package/dist/routes/config.js.map +1 -1
  313. package/dist/routes/contracts.d.ts +257 -51
  314. package/dist/routes/contracts.d.ts.map +1 -1
  315. package/dist/routes/contracts.js +131 -40
  316. package/dist/routes/contracts.js.map +1 -1
  317. package/dist/routes/feed-events.d.ts +15 -0
  318. package/dist/routes/feed-events.d.ts.map +1 -0
  319. package/dist/routes/feed-events.js +68 -0
  320. package/dist/routes/feed-events.js.map +1 -0
  321. package/dist/routes/fs.d.ts +4 -0
  322. package/dist/routes/fs.d.ts.map +1 -1
  323. package/dist/routes/fs.js +8 -4
  324. package/dist/routes/fs.js.map +1 -1
  325. package/dist/routes/intake-routes.d.ts.map +1 -1
  326. package/dist/routes/intake-routes.js +6 -1
  327. package/dist/routes/intake-routes.js.map +1 -1
  328. package/dist/routes/intake.d.ts +0 -23
  329. package/dist/routes/intake.d.ts.map +1 -1
  330. package/dist/routes/intake.js +13 -309
  331. package/dist/routes/intake.js.map +1 -1
  332. package/dist/routes/knowledge.js +1 -1
  333. package/dist/routes/mastra-gateway.d.ts +19 -0
  334. package/dist/routes/mastra-gateway.d.ts.map +1 -0
  335. package/dist/routes/mastra-gateway.js +120 -0
  336. package/dist/routes/mastra-gateway.js.map +1 -0
  337. package/dist/routes/projects.d.ts +1 -1
  338. package/dist/routes/projects.d.ts.map +1 -1
  339. package/dist/routes/projects.js +74 -58
  340. package/dist/routes/projects.js.map +1 -1
  341. package/dist/routes/provider-credentials.d.ts +6 -1
  342. package/dist/routes/provider-credentials.d.ts.map +1 -1
  343. package/dist/routes/provider-credentials.js +42 -7
  344. package/dist/routes/provider-credentials.js.map +1 -1
  345. package/dist/routes/route.d.ts +6 -0
  346. package/dist/routes/route.d.ts.map +1 -1
  347. package/dist/routes/route.js.map +1 -1
  348. package/dist/routes/running-packages.d.ts +13 -0
  349. package/dist/routes/running-packages.d.ts.map +1 -0
  350. package/dist/routes/running-packages.js +45 -0
  351. package/dist/routes/running-packages.js.map +1 -0
  352. package/dist/routes/sandbox-envs.d.ts +26 -0
  353. package/dist/routes/sandbox-envs.d.ts.map +1 -0
  354. package/dist/routes/sandbox-envs.js +180 -0
  355. package/dist/routes/sandbox-envs.js.map +1 -0
  356. package/dist/routes/session-access.d.ts.map +1 -1
  357. package/dist/routes/session-access.js +12 -3
  358. package/dist/routes/session-access.js.map +1 -1
  359. package/dist/routes/surface.d.ts +10 -8
  360. package/dist/routes/surface.d.ts.map +1 -1
  361. package/dist/routes/surface.js +105 -42
  362. package/dist/routes/surface.js.map +1 -1
  363. package/dist/routes/tenant-credentials.d.ts.map +1 -1
  364. package/dist/routes/tenant-credentials.js +5 -1
  365. package/dist/routes/tenant-credentials.js.map +1 -1
  366. package/dist/routes/work-items.d.ts +0 -3
  367. package/dist/routes/work-items.d.ts.map +1 -1
  368. package/dist/routes/work-items.js +94 -12
  369. package/dist/routes/work-items.js.map +1 -1
  370. package/dist/rules/binding-context.d.ts.map +1 -1
  371. package/dist/rules/binding-context.js +1 -0
  372. package/dist/rules/binding-context.js.map +1 -1
  373. package/dist/rules/dispatcher.d.ts +0 -9
  374. package/dist/rules/dispatcher.d.ts.map +1 -1
  375. package/dist/rules/dispatcher.js +362 -69
  376. package/dist/rules/dispatcher.js.map +1 -1
  377. package/dist/rules/event-rules.d.ts +33 -2
  378. package/dist/rules/event-rules.d.ts.map +1 -1
  379. package/dist/rules/event-rules.js +46 -11
  380. package/dist/rules/event-rules.js.map +1 -1
  381. package/dist/rules/index.d.ts +2 -4
  382. package/dist/rules/index.d.ts.map +1 -1
  383. package/dist/rules/index.js +2 -3
  384. package/dist/rules/phase-goal.d.ts +54 -0
  385. package/dist/rules/phase-goal.d.ts.map +1 -0
  386. package/dist/rules/phase-goal.js +70 -0
  387. package/dist/rules/phase-goal.js.map +1 -0
  388. package/dist/rules/phase-tools.d.ts +11 -0
  389. package/dist/rules/phase-tools.d.ts.map +1 -0
  390. package/dist/rules/phase-tools.js +19 -0
  391. package/dist/rules/phase-tools.js.map +1 -0
  392. package/dist/rules/processor.d.ts.map +1 -1
  393. package/dist/rules/processor.js +116 -15
  394. package/dist/rules/processor.js.map +1 -1
  395. package/dist/rules/review-source-tool.d.ts +4 -1
  396. package/dist/rules/review-source-tool.d.ts.map +1 -1
  397. package/dist/rules/review-source-tool.js +24 -4
  398. package/dist/rules/review-source-tool.js.map +1 -1
  399. package/dist/rules/rule-group.d.ts +1 -1
  400. package/dist/rules/rule-group.d.ts.map +1 -1
  401. package/dist/rules/rule-group.js +15 -6
  402. package/dist/rules/rule-group.js.map +1 -1
  403. package/dist/rules/start-coordinator.d.ts +5 -1
  404. package/dist/rules/start-coordinator.d.ts.map +1 -1
  405. package/dist/rules/start-coordinator.js +9 -3
  406. package/dist/rules/start-coordinator.js.map +1 -1
  407. package/dist/rules/tools.d.ts.map +1 -1
  408. package/dist/rules/tools.js +39 -28
  409. package/dist/rules/tools.js.map +1 -1
  410. package/dist/rules/transition-service.d.ts +4 -10
  411. package/dist/rules/transition-service.d.ts.map +1 -1
  412. package/dist/rules/transition-service.js +61 -55
  413. package/dist/rules/transition-service.js.map +1 -1
  414. package/dist/rules/types.d.ts +86 -36
  415. package/dist/rules/types.d.ts.map +1 -1
  416. package/dist/rules/types.js +5 -41
  417. package/dist/rules/types.js.map +1 -1
  418. package/dist/rules/validation.d.ts.map +1 -1
  419. package/dist/rules/validation.js +32 -2
  420. package/dist/rules/validation.js.map +1 -1
  421. package/dist/run-error.d.ts +1 -1
  422. package/dist/run-error.d.ts.map +1 -1
  423. package/dist/run-error.js +38 -5
  424. package/dist/run-error.js.map +1 -1
  425. package/dist/sandbox/sandbox-env-cache.d.ts +33 -0
  426. package/dist/sandbox/sandbox-env-cache.d.ts.map +1 -0
  427. package/dist/sandbox/sandbox-env-cache.js +140 -0
  428. package/dist/sandbox/sandbox-env-cache.js.map +1 -0
  429. package/dist/sandbox/sandbox-env.d.ts +77 -0
  430. package/dist/sandbox/sandbox-env.d.ts.map +1 -0
  431. package/dist/sandbox/sandbox-env.js +130 -0
  432. package/dist/sandbox/sandbox-env.js.map +1 -0
  433. package/dist/secret-encryption.d.ts +21 -0
  434. package/dist/secret-encryption.d.ts.map +1 -1
  435. package/dist/secret-encryption.js +31 -4
  436. package/dist/secret-encryption.js.map +1 -1
  437. package/dist/session/live-sessions.d.ts +11 -4
  438. package/dist/session/live-sessions.d.ts.map +1 -1
  439. package/dist/session/live-sessions.js +41 -10
  440. package/dist/session/live-sessions.js.map +1 -1
  441. package/dist/session/self-review-gate.d.ts +6 -4
  442. package/dist/session/self-review-gate.d.ts.map +1 -1
  443. package/dist/session/self-review-gate.js +9 -12
  444. package/dist/session/self-review-gate.js.map +1 -1
  445. package/dist/session/session-threads.d.ts +2 -3
  446. package/dist/session/session-threads.d.ts.map +1 -1
  447. package/dist/session/session-threads.js.map +1 -1
  448. package/dist/session/source-control-tools.d.ts +39 -13
  449. package/dist/session/source-control-tools.d.ts.map +1 -1
  450. package/dist/session/source-control-tools.js +55 -61
  451. package/dist/session/source-control-tools.js.map +1 -1
  452. package/dist/session/work-item-state-processor.d.ts +24 -0
  453. package/dist/session/work-item-state-processor.d.ts.map +1 -0
  454. package/dist/session/work-item-state-processor.js +275 -0
  455. package/dist/session/work-item-state-processor.js.map +1 -0
  456. package/dist/storage/domains/audit/actions.d.ts +2 -1
  457. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  458. package/dist/storage/domains/audit/actions.js +5 -4
  459. package/dist/storage/domains/audit/actions.js.map +1 -1
  460. package/dist/storage/domains/boards/base.d.ts +85 -32
  461. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  462. package/dist/storage/domains/boards/base.js +120 -131
  463. package/dist/storage/domains/boards/base.js.map +1 -1
  464. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  465. package/dist/storage/domains/boards/schemas.js +12 -0
  466. package/dist/storage/domains/boards/schemas.js.map +1 -1
  467. package/dist/storage/domains/channel-identity/base.d.ts +0 -4
  468. package/dist/storage/domains/channel-identity/base.d.ts.map +1 -1
  469. package/dist/storage/domains/channel-identity/base.js +0 -7
  470. package/dist/storage/domains/channel-identity/base.js.map +1 -1
  471. package/dist/storage/domains/intake/base.d.ts +5 -45
  472. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  473. package/dist/storage/domains/intake/base.js +11 -89
  474. package/dist/storage/domains/intake/base.js.map +1 -1
  475. package/dist/storage/domains/projects/base.d.ts +17 -9
  476. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  477. package/dist/storage/domains/projects/base.js +15 -7
  478. package/dist/storage/domains/projects/base.js.map +1 -1
  479. package/dist/storage/domains/sandbox-envs/base.d.ts +70 -0
  480. package/dist/storage/domains/sandbox-envs/base.d.ts.map +1 -0
  481. package/dist/storage/domains/sandbox-envs/base.js +227 -0
  482. package/dist/storage/domains/sandbox-envs/base.js.map +1 -0
  483. package/dist/storage/domains/work-items/base.d.ts +62 -22
  484. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  485. package/dist/storage/domains/work-items/base.js +231 -146
  486. package/dist/storage/domains/work-items/base.js.map +1 -1
  487. package/dist/storage/domains/work-items/board-version.d.ts +6 -2
  488. package/dist/storage/domains/work-items/board-version.d.ts.map +1 -1
  489. package/dist/storage/domains/work-items/board-version.js +20 -9
  490. package/dist/storage/domains/work-items/board-version.js.map +1 -1
  491. package/dist/storage/domains/work-items/cards.d.ts +28 -5
  492. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  493. package/dist/storage/domains/work-items/cards.js +156 -23
  494. package/dist/storage/domains/work-items/cards.js.map +1 -1
  495. package/dist/storage/domains/work-items/legacy-review.d.ts +63 -0
  496. package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -0
  497. package/dist/storage/domains/work-items/legacy-review.js +109 -0
  498. package/dist/storage/domains/work-items/legacy-review.js.map +1 -0
  499. package/dist/storage/domains/work-items/metrics.d.ts +12 -4
  500. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -1
  501. package/dist/storage/domains/work-items/metrics.js +14 -32
  502. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  503. package/dist/storage/domains/work-items/work-item-schema.d.ts +4 -2
  504. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  505. package/dist/storage/domains/work-items/work-item-schema.js +59 -26
  506. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  507. package/dist/tools/approval-tools.d.ts.map +1 -1
  508. package/dist/tools/approval-tools.js +28 -9
  509. package/dist/tools/approval-tools.js.map +1 -1
  510. package/dist/tools/index.d.ts +1 -1
  511. package/dist/tools/index.js +1 -1
  512. package/dist/tools/index.js.map +1 -1
  513. package/dist/tools/messaging-tools.d.ts +3 -0
  514. package/dist/tools/messaging-tools.d.ts.map +1 -1
  515. package/dist/tools/messaging-tools.js +2 -1
  516. package/dist/tools/messaging-tools.js.map +1 -1
  517. package/dist/tools/read-tools.d.ts +8 -4
  518. package/dist/tools/read-tools.d.ts.map +1 -1
  519. package/dist/tools/read-tools.js +86 -37
  520. package/dist/tools/read-tools.js.map +1 -1
  521. package/dist/tools/reports.d.ts +1 -0
  522. package/dist/tools/reports.d.ts.map +1 -1
  523. package/dist/tools/reports.js +2 -1
  524. package/dist/tools/reports.js.map +1 -1
  525. package/dist/tools/run-watch.d.ts +1 -1
  526. package/dist/tools/run-watch.d.ts.map +1 -1
  527. package/dist/tools/run-watch.js +1 -0
  528. package/dist/tools/run-watch.js.map +1 -1
  529. package/dist/tools/sandbox-tools.js +1 -1
  530. package/dist/tools/session-tools.js +1 -1
  531. package/dist/tools/sessions-state-processor.d.ts +2 -0
  532. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  533. package/dist/tools/sessions-state-processor.js +4 -2
  534. package/dist/tools/sessions-state-processor.js.map +1 -1
  535. package/dist/tools/side-sessions.d.ts +2 -0
  536. package/dist/tools/side-sessions.d.ts.map +1 -1
  537. package/dist/tools/side-sessions.js +2 -1
  538. package/dist/tools/side-sessions.js.map +1 -1
  539. package/dist/tools/work-item-tools.d.ts +0 -3
  540. package/dist/tools/work-item-tools.d.ts.map +1 -1
  541. package/dist/tools/work-item-tools.js +10 -20
  542. package/dist/tools/work-item-tools.js.map +1 -1
  543. package/dist/work-item-branch.d.ts +13 -0
  544. package/dist/work-item-branch.d.ts.map +1 -1
  545. package/dist/work-item-branch.js +16 -1
  546. package/dist/work-item-branch.js.map +1 -1
  547. package/dist/work-items/create-work-item.d.ts +6 -0
  548. package/dist/work-items/create-work-item.d.ts.map +1 -1
  549. package/dist/work-items/create-work-item.js +28 -3
  550. package/dist/work-items/create-work-item.js.map +1 -1
  551. package/dist/work-items/description-context.d.ts +5 -0
  552. package/dist/work-items/description-context.d.ts.map +1 -0
  553. package/dist/work-items/description-context.js +17 -0
  554. package/dist/work-items/description-context.js.map +1 -0
  555. package/dist/work-items/providers/base.d.ts +4 -1
  556. package/dist/work-items/providers/base.d.ts.map +1 -1
  557. package/dist/work-items/providers/base.js +6 -1
  558. package/dist/work-items/providers/base.js.map +1 -1
  559. package/dist/work-items/providers/github.d.ts.map +1 -1
  560. package/dist/work-items/providers/github.js +2 -1
  561. package/dist/work-items/providers/github.js.map +1 -1
  562. package/dist/work-items/providers/gitlab.d.ts.map +1 -1
  563. package/dist/work-items/providers/gitlab.js +2 -1
  564. package/dist/work-items/providers/gitlab.js.map +1 -1
  565. package/dist/work-items/providers/jira.d.ts.map +1 -1
  566. package/dist/work-items/providers/jira.js +3 -2
  567. package/dist/work-items/providers/jira.js.map +1 -1
  568. package/dist/work-items/providers/linear.d.ts.map +1 -1
  569. package/dist/work-items/providers/linear.js +3 -2
  570. package/dist/work-items/providers/linear.js.map +1 -1
  571. package/dist/work-items/providers/types.d.ts +6 -0
  572. package/dist/work-items/providers/types.d.ts.map +1 -1
  573. package/dist/work-items/related-cards.d.ts +21 -0
  574. package/dist/work-items/related-cards.d.ts.map +1 -0
  575. package/dist/work-items/related-cards.js +45 -0
  576. package/dist/work-items/related-cards.js.map +1 -0
  577. package/dist/work-items/split-migration.d.ts.map +1 -1
  578. package/dist/work-items/split-migration.js +8 -8
  579. package/dist/work-items/split-migration.js.map +1 -1
  580. package/dist/workspace.d.ts +3 -1
  581. package/dist/workspace.d.ts.map +1 -1
  582. package/dist/workspace.js +122 -45
  583. package/dist/workspace.js.map +1 -1
  584. package/factory-skills/configure-factory-rules/SKILL.md +13 -11
  585. package/factory-skills/factory-build/SKILL.md +64 -0
  586. package/factory-skills/factory-gitlab-rereview/SKILL.md +4 -4
  587. package/factory-skills/factory-gitlab-review/SKILL.md +6 -6
  588. package/factory-skills/factory-plan/SKILL.md +8 -10
  589. package/factory-skills/factory-rereview/SKILL.md +74 -28
  590. package/factory-skills/factory-review/SKILL.md +85 -29
  591. package/factory-skills/factory-self-review/SKILL.md +32 -13
  592. package/factory-skills/factory-triage/SKILL.md +36 -32
  593. package/package.json +12 -12
  594. package/dist/boards/index.js.map +0 -1
  595. package/dist/boards/pull-request-review.d.ts +0 -14
  596. package/dist/boards/pull-request-review.d.ts.map +0 -1
  597. package/dist/boards/pull-request-review.js +0 -81
  598. package/dist/boards/pull-request-review.js.map +0 -1
  599. package/dist/boards/work-tool-rules.d.ts +0 -8
  600. package/dist/boards/work-tool-rules.d.ts.map +0 -1
  601. package/dist/boards/work-tool-rules.js +0 -19
  602. package/dist/boards/work-tool-rules.js.map +0 -1
  603. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts +0 -8
  604. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts.map +0 -1
  605. package/dist/integrations/slack/emoji-shortcodes.generated.js +0 -1984
  606. package/dist/integrations/slack/emoji-shortcodes.generated.js.map +0 -1
  607. package/dist/integrations/slack/emoji.d.ts +0 -3
  608. package/dist/integrations/slack/emoji.d.ts.map +0 -1
  609. package/dist/integrations/slack/emoji.js +0 -11
  610. package/dist/integrations/slack/emoji.js.map +0 -1
  611. package/dist/integrations/slack/feed-publisher.d.ts +0 -26
  612. package/dist/integrations/slack/feed-publisher.d.ts.map +0 -1
  613. package/dist/integrations/slack/feed-publisher.js +0 -43
  614. package/dist/integrations/slack/feed-publisher.js.map +0 -1
  615. package/dist/routes/attention-activity.d.ts +0 -23
  616. package/dist/routes/attention-activity.d.ts.map +0 -1
  617. package/dist/routes/attention-activity.js +0 -154
  618. package/dist/routes/attention-activity.js.map +0 -1
  619. package/dist/rules/resolve.d.ts +0 -15
  620. package/dist/rules/resolve.d.ts.map +0 -1
  621. package/dist/rules/resolve.js +0 -22
  622. package/dist/rules/resolve.js.map +0 -1
  623. package/dist/storage/domains/comments/activity.d.ts +0 -40
  624. package/dist/storage/domains/comments/activity.d.ts.map +0 -1
  625. package/dist/storage/domains/comments/activity.js +0 -93
  626. package/dist/storage/domains/comments/activity.js.map +0 -1
  627. package/dist/storage/domains/comments/actor.d.ts +0 -51
  628. package/dist/storage/domains/comments/actor.d.ts.map +0 -1
  629. package/dist/storage/domains/comments/actor.js +0 -37
  630. package/dist/storage/domains/comments/actor.js.map +0 -1
  631. package/dist/storage/domains/comments/base.d.ts +0 -245
  632. package/dist/storage/domains/comments/base.d.ts.map +0 -1
  633. package/dist/storage/domains/comments/base.js +0 -539
  634. package/dist/storage/domains/comments/base.js.map +0 -1
  635. package/dist/storage/domains/comments/domain.d.ts +0 -135
  636. package/dist/storage/domains/comments/domain.d.ts.map +0 -1
  637. package/dist/storage/domains/comments/domain.js +0 -284
  638. package/dist/storage/domains/comments/domain.js.map +0 -1
  639. package/dist/storage/domains/comments/feed-context.d.ts +0 -22
  640. package/dist/storage/domains/comments/feed-context.d.ts.map +0 -1
  641. package/dist/storage/domains/comments/feed-context.js +0 -88
  642. package/dist/storage/domains/comments/feed-context.js.map +0 -1
  643. package/dist/storage/domains/comments/feed-sync.d.ts +0 -21
  644. package/dist/storage/domains/comments/feed-sync.d.ts.map +0 -1
  645. package/dist/storage/domains/comments/feed-sync.js +0 -1
  646. package/dist/storage/domains/comments/parse.d.ts +0 -23
  647. package/dist/storage/domains/comments/parse.d.ts.map +0 -1
  648. package/dist/storage/domains/comments/parse.js +0 -89
  649. package/dist/storage/domains/comments/parse.js.map +0 -1
  650. package/dist/storage/domains/comments/routes.d.ts +0 -24
  651. package/dist/storage/domains/comments/routes.d.ts.map +0 -1
  652. package/dist/storage/domains/comments/routes.js +0 -299
  653. package/dist/storage/domains/comments/routes.js.map +0 -1
  654. package/dist/storage/domains/comments/schema.d.ts +0 -5
  655. package/dist/storage/domains/comments/schema.d.ts.map +0 -1
  656. package/dist/storage/domains/comments/schema.js +0 -178
  657. package/dist/storage/domains/comments/schema.js.map +0 -1
  658. package/dist/storage/domains/comments/wire.d.ts +0 -40
  659. package/dist/storage/domains/comments/wire.d.ts.map +0 -1
  660. package/dist/storage/domains/comments/wire.js +0 -36
  661. package/dist/storage/domains/comments/wire.js.map +0 -1
  662. package/factory-skills/factory-complete-issue/SKILL.md +0 -24
@@ -84,6 +84,13 @@ function boardEvent(value, label) {
84
84
  ...reason ? { reason } : {}
85
85
  };
86
86
  }
87
+ function linkedItemReference(value, field) {
88
+ if (value === void 0) return void 0;
89
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new FactoryRuleValidationError(`Factory linked work item ${field} must be an object.`);
90
+ assertExactKeys(value, ["workItemId"], `Factory linked work item ${field}`);
91
+ const { workItemId } = value;
92
+ return { workItemId: boundedString(workItemId, `Factory linked work item ${field}.workItemId`, 128) };
93
+ }
87
94
  function assertFactoryDecisionTarget(decision, boards, itemBoard) {
88
95
  if (decision.type !== "transition" && decision.type !== "upsertLinkedWorkItem") return;
89
96
  const board = boards.get(decision.board);
@@ -91,6 +98,20 @@ function assertFactoryDecisionTarget(decision, boards, itemBoard) {
91
98
  if (!Object.hasOwn(board.phases, decision.stage)) throw new FactoryRuleValidationError("Factory decision target phase is not defined on its board.");
92
99
  if (decision.type === "transition" && itemBoard !== void 0 && itemBoard !== decision.board) throw new FactoryRuleValidationError("Factory transition cannot change the item board.");
93
100
  }
101
+ const MAX_GOAL_OBJECTIVE_LENGTH = 2e3;
102
+ const MAX_GOAL_RUNS = 50;
103
+ function invokeSkillGoal(value) {
104
+ if (value === void 0) return void 0;
105
+ if (!isPlainObject(value)) throw new FactoryRuleValidationError("Factory skill goal must be an object.");
106
+ assertExactKeys(value, ["objective", "maxRuns"], "Factory skill goal");
107
+ const objective = boundedString(value.objective, "Factory skill goal objective", MAX_GOAL_OBJECTIVE_LENGTH);
108
+ const { maxRuns } = value;
109
+ if (maxRuns !== void 0 && (typeof maxRuns !== "number" || !Number.isInteger(maxRuns) || maxRuns < 1 || maxRuns > MAX_GOAL_RUNS)) throw new FactoryRuleValidationError("Factory skill goal maxRuns is invalid.");
110
+ return {
111
+ objective,
112
+ ...maxRuns !== void 0 ? { maxRuns } : {}
113
+ };
114
+ }
94
115
  function optionalBoundedString(value, label, max) {
95
116
  if (value === void 0) return void 0;
96
117
  return boundedString(value, label, max);
@@ -238,12 +259,16 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
238
259
  "url",
239
260
  "stage",
240
261
  "skipRules",
262
+ "attachTo",
263
+ "closesIssue",
241
264
  "metadata"
242
265
  ], "Factory linked work item decision");
243
266
  if (value.skipRules !== void 0 && typeof value.skipRules !== "boolean") throw new FactoryRuleValidationError("Factory linked work item skipRules must be a boolean.");
244
267
  const url = value.url;
245
268
  if (url !== null && (typeof url !== "string" || url.length > MAX_URL_LENGTH || !/^https?:\/\//.test(url))) throw new FactoryRuleValidationError("Factory linked work item URL is invalid.");
246
269
  const metadata = sanitizeMetadata(value.metadata);
270
+ const attachTo = linkedItemReference(value.attachTo, "attachTo");
271
+ const closesIssue = linkedItemReference(value.closesIssue, "closesIssue");
247
272
  return {
248
273
  type,
249
274
  ...commonCommitFields(value),
@@ -254,6 +279,8 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
254
279
  url,
255
280
  stage: boardIdentifier(value.stage, "Factory linked work item stage"),
256
281
  ...value.skipRules === true ? { skipRules: true } : {},
282
+ ...attachTo ? { attachTo } : {},
283
+ ...closesIssue ? { closesIssue } : {},
257
284
  ...metadata ? { metadata } : {}
258
285
  };
259
286
  }
@@ -268,7 +295,8 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
268
295
  "precedingMessage",
269
296
  "cancelInFlight",
270
297
  "startsAfterOwnMove",
271
- "resume"
298
+ "resume",
299
+ "goal"
272
300
  ], "Factory invoke skill decision");
273
301
  if (value.skillName === void 0 === (value.prompt === void 0)) throw new FactoryRuleValidationError("Factory skill invocation needs exactly one of skillName or prompt.");
274
302
  const args = optionalBoundedString(value.arguments, "Factory skill arguments", MAX_ARGUMENTS_LENGTH);
@@ -277,6 +305,7 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
277
305
  if (value.startsAfterOwnMove !== void 0 && typeof value.startsAfterOwnMove !== "boolean") throw new FactoryRuleValidationError("Factory skill startsAfterOwnMove must be a boolean.");
278
306
  if (value.resume !== void 0 && typeof value.resume !== "boolean") throw new FactoryRuleValidationError("Factory skill resume must be a boolean.");
279
307
  if (value.resume === true && value.skillName === void 0) throw new FactoryRuleValidationError("Factory skill resume requires skillName.");
308
+ const goal = invokeSkillGoal(value.goal);
280
309
  return {
281
310
  type,
282
311
  ...commonCommitFields(value),
@@ -288,7 +317,8 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
288
317
  ...args ? { arguments: args } : {},
289
318
  ...precedingMessage ? { precedingMessage } : {},
290
319
  ...value.cancelInFlight === true ? { cancelInFlight: true } : {},
291
- ...value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {}
320
+ ...value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {},
321
+ ...goal ? { goal } : {}
292
322
  };
293
323
  }
294
324
  case "sendMessage": {
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","names":[],"sources":["../../src/rules/validation.ts"],"sourcesContent":["import { ACTIVITY_EVENTS, CLOSE_REASONS, STATUS_EVENTS } from '../boards/board-events.js';\nimport type { BoardEventFacts } from '../boards/board-events.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleRejectionCode,\n FactoryRouteEventDecision,\n FactoryTransitionDecision,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nexport const MAX_ROLE_LENGTH = 32;\nexport const MAX_TOOL_NAME_LENGTH = 128;\nexport const MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nexport const MAX_BOARD_IDENTIFIER_LENGTH = 128;\n/** A source reference such as `acme/app#12` or `group/sub/project#3`. */\nconst SOURCE_REFERENCE_RE = /^[a-z0-9_][a-z0-9_.\\/-]*#\\d+$/i;\n/** A provider login such as `octocat`, `dependabot[bot]`, `jane.doe` or GitLab's `_jane`. */\nconst LOGIN_RE = /^[a-z0-9_][a-z0-9_.-]*(\\[bot\\])?$/i;\nconst MAX_LOGIN_LENGTH = 100;\nexport const IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nexport const BOARD_IDENTIFIER_RE = IDENTIFIER_RE;\nexport const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = [\n 'github-issue',\n 'github-pr',\n 'gitlab-issue',\n 'gitlab-pr',\n 'linear-issue',\n 'jira-issue',\n 'incidentio-follow-up',\n 'manual',\n];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nexport function isBoardIdentifier(value: unknown): value is string {\n return typeof value === 'string' && value.length <= MAX_BOARD_IDENTIFIER_LENGTH && BOARD_IDENTIFIER_RE.test(value);\n}\n\nfunction boardIdentifier(value: unknown, label: string): string {\n if (!isBoardIdentifier(value)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value;\n}\n\nfunction boardEvent(value: unknown, label: string): BoardEventFacts {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event must be an object.`);\n assertExactKeys(value, ['type', 'reason'], `${label} event`);\n const type = enumValue(value.type, STATUS_EVENTS, `${label} event type`);\n const reason =\n value.reason === undefined ? undefined : enumValue(value.reason, CLOSE_REASONS, `${label} event reason`);\n return { type, ...(reason ? { reason } : {}) };\n}\n\nexport function assertFactoryDecisionTarget(\n decision: FactoryRuleDecision,\n boards: BoardRegistry,\n itemBoard?: string | null,\n): void {\n if (decision.type !== 'transition' && decision.type !== 'upsertLinkedWorkItem') return;\n const board = boards.get(decision.board);\n if (!board) throw new FactoryRuleValidationError('Factory decision target board is not installed.');\n if (!Object.hasOwn(board.phases, decision.stage)) {\n throw new FactoryRuleValidationError('Factory decision target phase is not defined on its board.');\n }\n if (decision.type === 'transition' && itemBoard !== undefined && itemBoard !== decision.board) {\n throw new FactoryRuleValidationError('Factory transition cannot change the item board.');\n }\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nexport const DEFAULT_FACTORY_CONFIG_VERSION = 'factory-config-v1';\n\n/** Operator-maintained provenance label stamped on transition audit and deferred-decision rows. */\nexport function assertFactoryConfigVersion(value: unknown): string {\n return boundedString(value, 'Factory configVersion', MAX_VERSION_LENGTH);\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'stage', 'message', 'reenter', 'event'],\n 'Factory transition decision',\n );\n if (value.reenter !== undefined && typeof value.reenter !== 'boolean') {\n throw new FactoryRuleValidationError('Factory transition reenter must be a boolean.');\n }\n let message: { text: string; role?: string } | undefined;\n if (value.message !== undefined) {\n if (!isPlainObject(value.message)) {\n throw new FactoryRuleValidationError('Factory transition message must be an object.');\n }\n assertExactKeys(value.message, ['text', 'role'], 'Factory transition message');\n const role =\n value.message.role === undefined\n ? undefined\n : boundedString(value.message.role, 'Factory transition message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n message = {\n text: boundedString(value.message.text, 'Factory transition message text', MAX_MESSAGE_LENGTH),\n ...(role ? { role } : {}),\n };\n }\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory transition board'),\n stage: boardIdentifier(value.stage, 'Factory transition stage'),\n ...(message ? { message } : {}),\n ...(value.reenter === true ? { reenter: true } : {}),\n ...(value.event !== undefined ? { event: boardEvent(value.event, 'Factory transition') } : {}),\n };\n }\n case 'routeEvent': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'event'], 'Factory routeEvent decision');\n return { type, ...commonCommitFields(value), event: boardEvent(value.event, 'Factory routeEvent') };\n }\n case 'signalActivity': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'event', 'reference', 'url', 'author', 'authorTrusted', 'idleBehavior'],\n 'Factory signalActivity decision',\n );\n const url = value.url;\n if (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\/\\S+$/.test(url)) {\n throw new FactoryRuleValidationError('Factory signalActivity url must be an http(s) URL.');\n }\n if (typeof value.authorTrusted !== 'boolean') {\n throw new FactoryRuleValidationError('Factory signalActivity authorTrusted must be a boolean.');\n }\n const author =\n value.author === undefined\n ? undefined\n : boundedString(value.author, 'Factory signalActivity author', MAX_LOGIN_LENGTH, LOGIN_RE);\n return {\n type,\n ...commonCommitFields(value),\n event: enumValue(value.event, ACTIVITY_EVENTS, 'Factory signalActivity event'),\n reference: boundedString(\n value.reference,\n 'Factory signalActivity reference',\n MAX_SOURCE_KEY_LENGTH,\n SOURCE_REFERENCE_RE,\n ),\n url,\n ...(author ? { author } : {}),\n authorTrusted: value.authorTrusted,\n ...(value.idleBehavior === undefined\n ? {}\n : {\n idleBehavior: enumValue(\n value.idleBehavior,\n ['wake', 'persist'] as const,\n 'Factory signalActivity idleBehavior',\n ),\n }),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'board',\n 'source',\n 'sourceKey',\n // Decisions saved before claims were dropped still carry it; it is ignored.\n 'claimKey',\n 'title',\n 'url',\n 'stage',\n 'skipRules',\n 'metadata',\n ],\n 'Factory linked work item decision',\n );\n if (value.skipRules !== undefined && typeof value.skipRules !== 'boolean') {\n throw new FactoryRuleValidationError('Factory linked work item skipRules must be a boolean.');\n }\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n url,\n stage: boardIdentifier(value.stage, 'Factory linked work item stage'),\n ...(value.skipRules === true ? { skipRules: true } : {}),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'role',\n 'skillName',\n 'prompt',\n 'arguments',\n 'precedingMessage',\n 'cancelInFlight',\n 'startsAfterOwnMove',\n 'resume',\n ],\n 'Factory invoke skill decision',\n );\n // A run activates a skill or carries a prompt, never both: they are two\n // ways to author the same kickoff message, so accepting both would leave\n // the dispatcher picking a winner.\n if ((value.skillName === undefined) === (value.prompt === undefined)) {\n throw new FactoryRuleValidationError('Factory skill invocation needs exactly one of skillName or prompt.');\n }\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n if (value.cancelInFlight !== undefined && typeof value.cancelInFlight !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill cancelInFlight must be a boolean.');\n }\n if (value.startsAfterOwnMove !== undefined && typeof value.startsAfterOwnMove !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill startsAfterOwnMove must be a boolean.');\n }\n if (value.resume !== undefined && typeof value.resume !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill resume must be a boolean.');\n }\n // Resume continues an already-active skill by name; a plain prompt run has no\n // skill to resume, so the dispatcher would silently ignore the flag.\n if (value.resume === true && value.skillName === undefined) {\n throw new FactoryRuleValidationError('Factory skill resume requires skillName.');\n }\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n ...(value.skillName === undefined\n ? { prompt: boundedString(value.prompt, 'Factory skill prompt', MAX_MESSAGE_LENGTH) }\n : {\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(value.resume === true ? { resume: true } : {}),\n }),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n ...(value.cancelInFlight === true ? { cancelInFlight: true } : {}),\n ...(value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'message', 'priority', 'idleBehavior', 'prepareBinding'],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n if (value.prepareBinding === true && value.role === undefined) {\n throw new FactoryRuleValidationError('Factory message prepareBinding requires a role.');\n }\n const role =\n value.role === undefined\n ? undefined\n : boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n return {\n type,\n ...commonCommitFields(value),\n ...(role ? { role } : {}),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n case 'dismissStaleReviews': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'installationId',\n 'repository',\n 'pullRequestNumber',\n 'approvingReviewId',\n 'approvingAuthor',\n ],\n 'Factory dismiss stale reviews decision',\n );\n for (const key of ['installationId', 'pullRequestNumber'] as const) {\n if (!Number.isSafeInteger(value[key]) || (value[key] as number) <= 0) {\n throw new FactoryRuleValidationError(`Factory dismiss stale reviews ${key} must be a positive integer.`);\n }\n }\n return {\n type,\n ...commonCommitFields(value),\n installationId: value.installationId as number,\n repository: boundedString(value.repository, 'Factory dismiss stale reviews repository', MAX_TITLE_LENGTH),\n pullRequestNumber: value.pullRequestNumber as number,\n approvingReviewId: boundedString(value.approvingReviewId, 'Factory approving review id', MAX_TITLE_LENGTH),\n approvingAuthor: boundedString(value.approvingAuthor, 'Factory approving review author', MAX_TITLE_LENGTH),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n"],"mappings":";;AAaA,MAAa,gCAAgC;AAE7C,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AACnC,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAC7B,MAAa,kBAAkB;AAC/B,MAAa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jE,MAAM,IAAI,2BAA2B,iCAAiC,IAAI,6BAA6B;GAG3G,OAAO;IACL;IACA,GAAG,mBAAmB,KAAK;IAC3B,gBAAgB,MAAM;IACtB,YAAY,cAAc,MAAM,YAAY,4CAA4C,gBAAgB;IACxG,mBAAmB,MAAM;IACzB,mBAAmB,cAAc,MAAM,mBAAmB,+BAA+B,gBAAgB;IACzG,iBAAiB,cAAc,MAAM,iBAAiB,mCAAmC,gBAAgB;GAC3G;EAEF,SACE,MAAM,IAAI,2BAA2B,4CAA4C;CACrF;AACF;AAEA,SAAgB,6BAA6B,QAA4B,cAAc,GAA4B;CACjH,IAAI,OAAO,SAAS,0BAClB,MAAM,IAAI,2BAA2B,2CAA2C;CAElF,MAAM,YAAqC,CAAC;CAC5C,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,4BAA4B,OAAO,WAAW;EAC/D,IAAI,SAAS,SAAS,UACpB,MAAM,IAAI,2BAA2B,wDAAwD;EAE/F,UAAU,KAAK,QAAQ;CACzB;CACA,MAAM,OAAO,UAAU,KAAI,aAAY,SAAS,cAAc;CAC9D,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,SAAS,KAAK,QAC9B,MAAM,IAAI,2BAA2B,oDAAoD;CAE3F,OAAO;AACT"}
1
+ {"version":3,"file":"validation.js","names":[],"sources":["../../src/rules/validation.ts"],"sourcesContent":["import { ACTIVITY_EVENTS, CLOSE_REASONS, STATUS_EVENTS } from '../boards/board-events.js';\nimport type { BoardEventFacts } from '../boards/board-events.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleRejectionCode,\n FactoryRouteEventDecision,\n FactoryTransitionDecision,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nexport const MAX_ROLE_LENGTH = 32;\nexport const MAX_TOOL_NAME_LENGTH = 128;\nexport const MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nexport const MAX_BOARD_IDENTIFIER_LENGTH = 128;\n/** A source reference such as `acme/app#12` or `group/sub/project#3`. */\nconst SOURCE_REFERENCE_RE = /^[a-z0-9_][a-z0-9_.\\/-]*#\\d+$/i;\n/** A provider login such as `octocat`, `dependabot[bot]`, `jane.doe` or GitLab's `_jane`. */\nconst LOGIN_RE = /^[a-z0-9_][a-z0-9_.-]*(\\[bot\\])?$/i;\nconst MAX_LOGIN_LENGTH = 100;\nexport const IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nexport const BOARD_IDENTIFIER_RE = IDENTIFIER_RE;\nexport const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = [\n 'github-issue',\n 'github-pr',\n 'gitlab-issue',\n 'gitlab-pr',\n 'linear-issue',\n 'jira-issue',\n 'incidentio-follow-up',\n 'manual',\n];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nexport function isBoardIdentifier(value: unknown): value is string {\n return typeof value === 'string' && value.length <= MAX_BOARD_IDENTIFIER_LENGTH && BOARD_IDENTIFIER_RE.test(value);\n}\n\nfunction boardIdentifier(value: unknown, label: string): string {\n if (!isBoardIdentifier(value)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value;\n}\n\nfunction boardEvent(value: unknown, label: string): BoardEventFacts {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event must be an object.`);\n assertExactKeys(value, ['type', 'reason'], `${label} event`);\n const type = enumValue(value.type, STATUS_EVENTS, `${label} event type`);\n const reason =\n value.reason === undefined ? undefined : enumValue(value.reason, CLOSE_REASONS, `${label} event reason`);\n return { type, ...(reason ? { reason } : {}) };\n}\n\nfunction linkedItemReference(value: unknown, field: 'attachTo' | 'closesIssue'): { workItemId: string } | undefined {\n if (value === undefined) return undefined;\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new FactoryRuleValidationError(`Factory linked work item ${field} must be an object.`);\n }\n assertExactKeys(value as Record<string, unknown>, ['workItemId'], `Factory linked work item ${field}`);\n const { workItemId } = value as Record<string, unknown>;\n return { workItemId: boundedString(workItemId, `Factory linked work item ${field}.workItemId`, 128) };\n}\n\nexport function assertFactoryDecisionTarget(\n decision: FactoryRuleDecision,\n boards: BoardRegistry,\n itemBoard?: string | null,\n): void {\n if (decision.type !== 'transition' && decision.type !== 'upsertLinkedWorkItem') return;\n const board = boards.get(decision.board);\n if (!board) throw new FactoryRuleValidationError('Factory decision target board is not installed.');\n if (!Object.hasOwn(board.phases, decision.stage)) {\n throw new FactoryRuleValidationError('Factory decision target phase is not defined on its board.');\n }\n if (decision.type === 'transition' && itemBoard !== undefined && itemBoard !== decision.board) {\n throw new FactoryRuleValidationError('Factory transition cannot change the item board.');\n }\n}\n\nconst MAX_GOAL_OBJECTIVE_LENGTH = 2_000;\nconst MAX_GOAL_RUNS = 50;\n\nfunction invokeSkillGoal(value: unknown): { objective: string; maxRuns?: number } | undefined {\n if (value === undefined) return undefined;\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory skill goal must be an object.');\n assertExactKeys(value, ['objective', 'maxRuns'], 'Factory skill goal');\n const objective = boundedString(value.objective, 'Factory skill goal objective', MAX_GOAL_OBJECTIVE_LENGTH);\n const { maxRuns } = value;\n if (\n maxRuns !== undefined &&\n (typeof maxRuns !== 'number' || !Number.isInteger(maxRuns) || maxRuns < 1 || maxRuns > MAX_GOAL_RUNS)\n ) {\n throw new FactoryRuleValidationError('Factory skill goal maxRuns is invalid.');\n }\n return { objective, ...(maxRuns !== undefined ? { maxRuns } : {}) };\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nexport const DEFAULT_FACTORY_CONFIG_VERSION = 'factory-config-v1';\n\n/** Operator-maintained provenance label stamped on transition audit and deferred-decision rows. */\nexport function assertFactoryConfigVersion(value: unknown): string {\n return boundedString(value, 'Factory configVersion', MAX_VERSION_LENGTH);\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'stage', 'message', 'reenter', 'event'],\n 'Factory transition decision',\n );\n if (value.reenter !== undefined && typeof value.reenter !== 'boolean') {\n throw new FactoryRuleValidationError('Factory transition reenter must be a boolean.');\n }\n let message: { text: string; role?: string } | undefined;\n if (value.message !== undefined) {\n if (!isPlainObject(value.message)) {\n throw new FactoryRuleValidationError('Factory transition message must be an object.');\n }\n assertExactKeys(value.message, ['text', 'role'], 'Factory transition message');\n const role =\n value.message.role === undefined\n ? undefined\n : boundedString(value.message.role, 'Factory transition message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n message = {\n text: boundedString(value.message.text, 'Factory transition message text', MAX_MESSAGE_LENGTH),\n ...(role ? { role } : {}),\n };\n }\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory transition board'),\n stage: boardIdentifier(value.stage, 'Factory transition stage'),\n ...(message ? { message } : {}),\n ...(value.reenter === true ? { reenter: true } : {}),\n ...(value.event !== undefined ? { event: boardEvent(value.event, 'Factory transition') } : {}),\n };\n }\n case 'routeEvent': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'event'], 'Factory routeEvent decision');\n return { type, ...commonCommitFields(value), event: boardEvent(value.event, 'Factory routeEvent') };\n }\n case 'signalActivity': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'event', 'reference', 'url', 'author', 'authorTrusted', 'idleBehavior'],\n 'Factory signalActivity decision',\n );\n const url = value.url;\n if (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\/\\S+$/.test(url)) {\n throw new FactoryRuleValidationError('Factory signalActivity url must be an http(s) URL.');\n }\n if (typeof value.authorTrusted !== 'boolean') {\n throw new FactoryRuleValidationError('Factory signalActivity authorTrusted must be a boolean.');\n }\n const author =\n value.author === undefined\n ? undefined\n : boundedString(value.author, 'Factory signalActivity author', MAX_LOGIN_LENGTH, LOGIN_RE);\n return {\n type,\n ...commonCommitFields(value),\n event: enumValue(value.event, ACTIVITY_EVENTS, 'Factory signalActivity event'),\n reference: boundedString(\n value.reference,\n 'Factory signalActivity reference',\n MAX_SOURCE_KEY_LENGTH,\n SOURCE_REFERENCE_RE,\n ),\n url,\n ...(author ? { author } : {}),\n authorTrusted: value.authorTrusted,\n ...(value.idleBehavior === undefined\n ? {}\n : {\n idleBehavior: enumValue(\n value.idleBehavior,\n ['wake', 'persist'] as const,\n 'Factory signalActivity idleBehavior',\n ),\n }),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'board',\n 'source',\n 'sourceKey',\n // Decisions saved before claims were dropped still carry it; it is ignored.\n 'claimKey',\n 'title',\n 'url',\n 'stage',\n 'skipRules',\n 'attachTo',\n 'closesIssue',\n 'metadata',\n ],\n 'Factory linked work item decision',\n );\n if (value.skipRules !== undefined && typeof value.skipRules !== 'boolean') {\n throw new FactoryRuleValidationError('Factory linked work item skipRules must be a boolean.');\n }\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n const attachTo = linkedItemReference(value.attachTo, 'attachTo');\n const closesIssue = linkedItemReference(value.closesIssue, 'closesIssue');\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n url,\n stage: boardIdentifier(value.stage, 'Factory linked work item stage'),\n ...(value.skipRules === true ? { skipRules: true } : {}),\n ...(attachTo ? { attachTo } : {}),\n ...(closesIssue ? { closesIssue } : {}),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'role',\n 'skillName',\n 'prompt',\n 'arguments',\n 'precedingMessage',\n 'cancelInFlight',\n 'startsAfterOwnMove',\n 'resume',\n 'goal',\n ],\n 'Factory invoke skill decision',\n );\n // A run activates a skill or carries a prompt, never both: they are two\n // ways to author the same kickoff message, so accepting both would leave\n // the dispatcher picking a winner.\n if ((value.skillName === undefined) === (value.prompt === undefined)) {\n throw new FactoryRuleValidationError('Factory skill invocation needs exactly one of skillName or prompt.');\n }\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n if (value.cancelInFlight !== undefined && typeof value.cancelInFlight !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill cancelInFlight must be a boolean.');\n }\n if (value.startsAfterOwnMove !== undefined && typeof value.startsAfterOwnMove !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill startsAfterOwnMove must be a boolean.');\n }\n if (value.resume !== undefined && typeof value.resume !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill resume must be a boolean.');\n }\n // Resume continues an already-active skill by name; a plain prompt run has no\n // skill to resume, so the dispatcher would silently ignore the flag.\n if (value.resume === true && value.skillName === undefined) {\n throw new FactoryRuleValidationError('Factory skill resume requires skillName.');\n }\n const goal = invokeSkillGoal(value.goal);\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n ...(value.skillName === undefined\n ? { prompt: boundedString(value.prompt, 'Factory skill prompt', MAX_MESSAGE_LENGTH) }\n : {\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(value.resume === true ? { resume: true } : {}),\n }),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n ...(value.cancelInFlight === true ? { cancelInFlight: true } : {}),\n ...(value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {}),\n ...(goal ? { goal } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'message', 'priority', 'idleBehavior', 'prepareBinding'],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n if (value.prepareBinding === true && value.role === undefined) {\n throw new FactoryRuleValidationError('Factory message prepareBinding requires a role.');\n }\n const role =\n value.role === undefined\n ? undefined\n : boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n return {\n type,\n ...commonCommitFields(value),\n ...(role ? { role } : {}),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n case 'dismissStaleReviews': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'installationId',\n 'repository',\n 'pullRequestNumber',\n 'approvingReviewId',\n 'approvingAuthor',\n ],\n 'Factory dismiss stale reviews decision',\n );\n for (const key of ['installationId', 'pullRequestNumber'] as const) {\n if (!Number.isSafeInteger(value[key]) || (value[key] as number) <= 0) {\n throw new FactoryRuleValidationError(`Factory dismiss stale reviews ${key} must be a positive integer.`);\n }\n }\n return {\n type,\n ...commonCommitFields(value),\n installationId: value.installationId as number,\n repository: boundedString(value.repository, 'Factory dismiss stale reviews repository', MAX_TITLE_LENGTH),\n pullRequestNumber: value.pullRequestNumber as number,\n approvingReviewId: boundedString(value.approvingReviewId, 'Factory approving review id', MAX_TITLE_LENGTH),\n approvingAuthor: boundedString(value.approvingAuthor, 'Factory approving review author', MAX_TITLE_LENGTH),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n"],"mappings":";;AAaA,MAAa,gCAAgC;AAE7C,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AACnC,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAC7B,MAAa,kBAAkB;AAC/B,MAAa,uBAAuB;AACpC,MAAa,wBAAwB;AACrC,MAAM,wBAAwB;AAC9B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AACjC,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AAEjC,MAAa,8BAA8B;;AAE3C,MAAM,sBAAsB;;AAE5B,MAAM,WAAW;AACjB,MAAM,mBAAmB;AACzB,MAAa,gBAAgB;AAC7B,MAAa,sBAAsB;AACnC,MAAa,gBAAgB;AAC7B,MAAM,mBAAmB;AACzB,MAAM,oBAA+C;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,kBAAuD;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAa,6BAAb,cAAgD,MAAM;CACpD,OAAgB;CAEhB,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,gBAAgB,OAAgC,MAAyB,OAAqB;CACrG,MAAM,UAAU,IAAI,IAAI,IAAI;CAC5B,IAAI,OAAO,KAAK,KAAK,CAAC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,8BAA8B,gBAAgB;IAChF,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;IACvB,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;GAC3B;EACF;EACA,KAAK;GACH,gBACE,OACA;IACE;IACA;IACA;IACA;IACA;IACA;IACA;GACF,GACA,wCACF;GACA,KAAK,MAAM,OAAO,CAAC,kBAAkB,mBAAmB,GACtD,IAAI,CAAC,OAAO,cAAc,MAAM,IAAI,KAAM,MAAM,QAAmB,GACjE,MAAM,IAAI,2BAA2B,iCAAiC,IAAI,6BAA6B;GAG3G,OAAO;IACL;IACA,GAAG,mBAAmB,KAAK;IAC3B,gBAAgB,MAAM;IACtB,YAAY,cAAc,MAAM,YAAY,4CAA4C,gBAAgB;IACxG,mBAAmB,MAAM;IACzB,mBAAmB,cAAc,MAAM,mBAAmB,+BAA+B,gBAAgB;IACzG,iBAAiB,cAAc,MAAM,iBAAiB,mCAAmC,gBAAgB;GAC3G;EAEF,SACE,MAAM,IAAI,2BAA2B,4CAA4C;CACrF;AACF;AAEA,SAAgB,6BAA6B,QAA4B,cAAc,GAA4B;CACjH,IAAI,OAAO,SAAS,0BAClB,MAAM,IAAI,2BAA2B,2CAA2C;CAElF,MAAM,YAAqC,CAAC;CAC5C,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,4BAA4B,OAAO,WAAW;EAC/D,IAAI,SAAS,SAAS,UACpB,MAAM,IAAI,2BAA2B,wDAAwD;EAE/F,UAAU,KAAK,QAAQ;CACzB;CACA,MAAM,OAAO,UAAU,KAAI,aAAY,SAAS,cAAc;CAC9D,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,SAAS,KAAK,QAC9B,MAAM,IAAI,2BAA2B,oDAAoD;CAE3F,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- export type RunErrorRecovery = 'continue' | 'credentials' | 'model' | 'new_session';
1
+ export type RunErrorRecovery = 'continue' | 'credentials' | 'credits' | 'model' | 'new_session';
2
2
  export interface RunErrorDescription {
3
3
  title: string;
4
4
  message: string;
@@ -1 +1 @@
1
- {"version":3,"file":"run-error.d.ts","sourceRoot":"","sources":["../src/run-error.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG,aAAa,GAAG,OAAO,GAAG,aAAa,CAAC;AAEpF,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,gBAAgB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAMD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,mBAAmB,CAE7E"}
1
+ {"version":3,"file":"run-error.d.ts","sourceRoot":"","sources":["../src/run-error.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG,aAAa,GAAG,SAAS,GAAG,OAAO,GAAG,aAAa,CAAC;AAEhG,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,gBAAgB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AAMD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,mBAAmB,CAE7E"}
package/dist/run-error.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { MASTRA_GATEWAY_PREFIX } from "@mastra/code-sdk/providers/model-ids";
1
2
  import { PROVIDER_CALL_ERROR_NAME, classifyProviderError, providerErrorReason, providerModelId } from "@mastra/core/error";
2
3
  import { PROVIDER_AUTH_REQUIRED_ERROR } from "@mastra/code-sdk/auth/provider-auth-error";
3
4
  // src/run-error.ts
@@ -16,11 +17,21 @@ function explainRunError(error) {
16
17
  recoveries: ["credentials", "model"]
17
18
  };
18
19
  switch (classifyProviderError(error)) {
19
- case "quota": return {
20
- title: "Provider quota exhausted",
21
- message: afterProviderReason(error, "Check the provider account’s billing or usage allowance, or use another credential or model."),
22
- recoveries: ["credentials", "model"]
23
- };
20
+ case "quota":
21
+ if (isMastraGatewayError(error)) return {
22
+ title: "Out of Mastra Gateway credits",
23
+ message: "Your organization has no gateway credits left. Add credits, then continue the run, or choose another model.",
24
+ recoveries: [
25
+ "credits",
26
+ "continue",
27
+ "model"
28
+ ]
29
+ };
30
+ return {
31
+ title: "Provider quota exhausted",
32
+ message: afterProviderReason(error, "Check the provider account’s billing or usage allowance, or use another credential or model."),
33
+ recoveries: ["credentials", "model"]
34
+ };
24
35
  case "auth": return {
25
36
  title: "Provider access failed",
26
37
  message: afterProviderReason(error, "Review the credentials and model access configured for this session."),
@@ -68,6 +79,28 @@ function explainRunError(error) {
68
79
  case "unknown": return describeUnclassifiedError(error);
69
80
  }
70
81
  }
82
+ const MASTRA_GATEWAY_HOST = /(?:^|\.)gateway(?:-api)?\.mastra\.ai$/;
83
+ /**
84
+ * The Mastra Gateway answered: a `mastra/…` model, a request sent to its host, or its billing reply
85
+ * (which links to `gateway.mastra.ai`). The request reaches the gateway without the `mastra/` prefix.
86
+ */
87
+ function isMastraGatewayError(error) {
88
+ return providerModelId(error)?.startsWith(MASTRA_GATEWAY_PREFIX) === true || calledMastraGateway(error) || /gateway\.mastra\.ai/.test(providerErrorReason(error) ?? error.message);
89
+ }
90
+ /** Whether the request, or a provider error it wraps, went to the gateway's host. */
91
+ function calledMastraGateway(error, depth = 0) {
92
+ if (depth > 4 || typeof error !== "object" || error === null) return false;
93
+ const url = "url" in error ? error.url : void 0;
94
+ const cause = "cause" in error ? error.cause : void 0;
95
+ return typeof url === "string" && MASTRA_GATEWAY_HOST.test(hostOf(url)) || calledMastraGateway(cause, depth + 1);
96
+ }
97
+ function hostOf(url) {
98
+ try {
99
+ return new URL(url).hostname;
100
+ } catch {
101
+ return "";
102
+ }
103
+ }
71
104
  function afterProviderReason(error, next, fallback) {
72
105
  const reason = providerErrorReason(error) ?? fallback;
73
106
  return reason ? `${reason.replace(/\.?$/, ".")} ${next}` : next;
@@ -1 +1 @@
1
- {"version":3,"file":"run-error.js","names":[],"sources":["../src/run-error.ts"],"sourcesContent":["import { PROVIDER_AUTH_REQUIRED_ERROR } from '@mastra/code-sdk/auth/provider-auth-error';\nimport {\n classifyProviderError,\n PROVIDER_CALL_ERROR_NAME,\n providerErrorReason,\n providerModelId,\n} from '@mastra/core/error';\n\nexport type RunErrorRecovery = 'continue' | 'credentials' | 'model' | 'new_session';\n\nexport interface RunErrorDescription {\n title: string;\n message: string;\n recoveries: RunErrorRecovery[];\n model?: string;\n}\n\nexport interface RunErrorIdentity {\n name: string;\n message: string;\n}\n\nconst UNEXPECTED_ERROR = 'An unexpected error stopped the run. Copy the error details to investigate.';\nconst NO_REASON_AVAILABLE =\n 'The provider rejected the request. A specific reason isn’t available here. Copy the error details and check the server logs.';\n\nexport function describeRunError(error: RunErrorIdentity): RunErrorDescription {\n return { ...explainRunError(error), model: providerModelId(error) };\n}\n\nfunction explainRunError(error: RunErrorIdentity): Omit<RunErrorDescription, 'model'> {\n if (error.name === PROVIDER_AUTH_REQUIRED_ERROR) {\n return { title: 'Provider sign-in required', message: error.message, recoveries: ['credentials', 'model'] };\n }\n switch (classifyProviderError(error)) {\n case 'quota':\n return {\n title: 'Provider quota exhausted',\n message: afterProviderReason(\n error,\n 'Check the provider account’s billing or usage allowance, or use another credential or model.',\n ),\n recoveries: ['credentials', 'model'],\n };\n case 'auth':\n return {\n title: 'Provider access failed',\n message: afterProviderReason(error, 'Review the credentials and model access configured for this session.'),\n recoveries: ['credentials', 'model'],\n };\n case 'context_overflow':\n return {\n title: 'Conversation exceeds the model’s limit',\n message: 'Choose a model with a larger context window or start a new session with a shorter prompt.',\n recoveries: ['model', 'new_session'],\n };\n case 'model_rejected':\n return {\n title: 'Model not available',\n message: afterProviderReason(\n error,\n 'Choose another model for this session.',\n 'The provider rejected this model.',\n ),\n recoveries: ['model'],\n };\n case 'tool_history_rejected':\n return {\n title: 'Conversation history rejected',\n message:\n 'The provider could not match a tool call with its result. Start a new session to keep working, and copy the error details so this session can be investigated.',\n recoveries: ['new_session'],\n };\n case 'invalid_request':\n return {\n title: 'Model request rejected',\n message: providerErrorReason(error) ?? NO_REASON_AVAILABLE,\n recoveries: ['model'],\n };\n case 'timeout':\n return {\n title: 'Request timed out',\n message: 'The request took too long to complete. Send a message to continue the run.',\n recoveries: ['continue'],\n };\n case 'rate_limited':\n return {\n title: 'Provider rate limit reached',\n message:\n 'The provider account behind this session’s credential hit a rate or usage limit. Continue once it resets, or use another credential or model.',\n recoveries: ['continue', 'credentials', 'model'],\n };\n case 'unavailable':\n return {\n title: 'Model provider temporarily unavailable',\n message:\n 'The provider could not complete the request. Send a message to continue the run, or choose another model.',\n recoveries: ['continue', 'model'],\n };\n case 'unknown':\n return describeUnclassifiedError(error);\n }\n}\n\nfunction afterProviderReason(error: RunErrorIdentity, next: string, fallback?: string): string {\n const reason = providerErrorReason(error) ?? fallback;\n return reason ? `${reason.replace(/\\.?$/, '.')} ${next}` : next;\n}\n\nfunction describeUnclassifiedError(error: RunErrorIdentity): Omit<RunErrorDescription, 'model'> {\n const message = providerErrorReason(error) ?? (error.message || UNEXPECTED_ERROR);\n const providerCall = PROVIDER_CALL_ERROR_NAME.test(error.name);\n return {\n title: providerCall ? 'Model request failed' : 'Run stopped',\n message,\n recoveries: providerCall ? ['model'] : [],\n };\n}\n"],"mappings":";;;AAsBA,MAAM,mBAAmB;AACzB,MAAM,sBACJ;AAEF,SAAgB,iBAAiB,OAA8C;CAC7E,OAAO;EAAE,GAAG,gBAAgB,KAAK;EAAG,OAAO,gBAAgB,KAAK;CAAE;AACpE;AAEA,SAAS,gBAAgB,OA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,KAAK,MAAM,IAAI;CAC7D,OAAO;EACL,OAAO,eAAe,yBAAyB;EAC/C;EACA,YAAY,eAAe,CAAC,OAAO,IAAI,CAAC;CAC1C;AACF"}
1
+ {"version":3,"file":"run-error.js","names":[],"sources":["../src/run-error.ts"],"sourcesContent":["import { PROVIDER_AUTH_REQUIRED_ERROR } from '@mastra/code-sdk/auth/provider-auth-error';\nimport { MASTRA_GATEWAY_PREFIX } from '@mastra/code-sdk/providers/model-ids';\nimport {\n classifyProviderError,\n PROVIDER_CALL_ERROR_NAME,\n providerErrorReason,\n providerModelId,\n} from '@mastra/core/error';\n\nexport type RunErrorRecovery = 'continue' | 'credentials' | 'credits' | 'model' | 'new_session';\n\nexport interface RunErrorDescription {\n title: string;\n message: string;\n recoveries: RunErrorRecovery[];\n model?: string;\n}\n\nexport interface RunErrorIdentity {\n name: string;\n message: string;\n}\n\nconst UNEXPECTED_ERROR = 'An unexpected error stopped the run. Copy the error details to investigate.';\nconst NO_REASON_AVAILABLE =\n 'The provider rejected the request. A specific reason isn’t available here. Copy the error details and check the server logs.';\n\nexport function describeRunError(error: RunErrorIdentity): RunErrorDescription {\n return { ...explainRunError(error), model: providerModelId(error) };\n}\n\nfunction explainRunError(error: RunErrorIdentity): Omit<RunErrorDescription, 'model'> {\n if (error.name === PROVIDER_AUTH_REQUIRED_ERROR) {\n return { title: 'Provider sign-in required', message: error.message, recoveries: ['credentials', 'model'] };\n }\n switch (classifyProviderError(error)) {\n case 'quota':\n if (isMastraGatewayError(error)) {\n return {\n title: 'Out of Mastra Gateway credits',\n message:\n 'Your organization has no gateway credits left. Add credits, then continue the run, or choose another model.',\n recoveries: ['credits', 'continue', 'model'],\n };\n }\n return {\n title: 'Provider quota exhausted',\n message: afterProviderReason(\n error,\n 'Check the provider account’s billing or usage allowance, or use another credential or model.',\n ),\n recoveries: ['credentials', 'model'],\n };\n case 'auth':\n return {\n title: 'Provider access failed',\n message: afterProviderReason(error, 'Review the credentials and model access configured for this session.'),\n recoveries: ['credentials', 'model'],\n };\n case 'context_overflow':\n return {\n title: 'Conversation exceeds the model’s limit',\n message: 'Choose a model with a larger context window or start a new session with a shorter prompt.',\n recoveries: ['model', 'new_session'],\n };\n case 'model_rejected':\n return {\n title: 'Model not available',\n message: afterProviderReason(\n error,\n 'Choose another model for this session.',\n 'The provider rejected this model.',\n ),\n recoveries: ['model'],\n };\n case 'tool_history_rejected':\n return {\n title: 'Conversation history rejected',\n message:\n 'The provider could not match a tool call with its result. Start a new session to keep working, and copy the error details so this session can be investigated.',\n recoveries: ['new_session'],\n };\n case 'invalid_request':\n return {\n title: 'Model request rejected',\n message: providerErrorReason(error) ?? NO_REASON_AVAILABLE,\n recoveries: ['model'],\n };\n case 'timeout':\n return {\n title: 'Request timed out',\n message: 'The request took too long to complete. Send a message to continue the run.',\n recoveries: ['continue'],\n };\n case 'rate_limited':\n return {\n title: 'Provider rate limit reached',\n message:\n 'The provider account behind this session’s credential hit a rate or usage limit. Continue once it resets, or use another credential or model.',\n recoveries: ['continue', 'credentials', 'model'],\n };\n case 'unavailable':\n return {\n title: 'Model provider temporarily unavailable',\n message:\n 'The provider could not complete the request. Send a message to continue the run, or choose another model.',\n recoveries: ['continue', 'model'],\n };\n case 'unknown':\n return describeUnclassifiedError(error);\n }\n}\n\nconst MASTRA_GATEWAY_HOST = /(?:^|\\.)gateway(?:-api)?\\.mastra\\.ai$/;\n\n/**\n * The Mastra Gateway answered: a `mastra/…` model, a request sent to its host, or its billing reply\n * (which links to `gateway.mastra.ai`). The request reaches the gateway without the `mastra/` prefix.\n */\nfunction isMastraGatewayError(error: RunErrorIdentity): boolean {\n return (\n providerModelId(error)?.startsWith(MASTRA_GATEWAY_PREFIX) === true ||\n calledMastraGateway(error) ||\n /gateway\\.mastra\\.ai/.test(providerErrorReason(error) ?? error.message)\n );\n}\n\n/** Whether the request, or a provider error it wraps, went to the gateway's host. */\nfunction calledMastraGateway(error: unknown, depth = 0): boolean {\n if (depth > 4 || typeof error !== 'object' || error === null) return false;\n const url = 'url' in error ? error.url : undefined;\n const cause = 'cause' in error ? error.cause : undefined;\n return (typeof url === 'string' && MASTRA_GATEWAY_HOST.test(hostOf(url))) || calledMastraGateway(cause, depth + 1);\n}\n\nfunction hostOf(url: string): string {\n try {\n return new URL(url).hostname;\n } catch {\n return '';\n }\n}\n\nfunction afterProviderReason(error: RunErrorIdentity, next: string, fallback?: string): string {\n const reason = providerErrorReason(error) ?? fallback;\n return reason ? `${reason.replace(/\\.?$/, '.')} ${next}` : next;\n}\n\nfunction describeUnclassifiedError(error: RunErrorIdentity): Omit<RunErrorDescription, 'model'> {\n const message = providerErrorReason(error) ?? (error.message || UNEXPECTED_ERROR);\n const providerCall = PROVIDER_CALL_ERROR_NAME.test(error.name);\n return {\n title: providerCall ? 'Model request failed' : 'Run stopped',\n message,\n recoveries: providerCall ? ['model'] : [],\n };\n}\n"],"mappings":";;;;AAuBA,MAAM,mBAAmB;AACzB,MAAM,sBACJ;AAEF,SAAgB,iBAAiB,OAA8C;CAC7E,OAAO;EAAE,GAAG,gBAAgB,KAAK;EAAG,OAAO,gBAAgB,KAAK;CAAE;AACpE;AAEA,SAAS,gBAAgB,OAA6D;CACpF,IAAI,MAAM,SAAS,8BACjB,OAAO;EAAE,OAAO;EAA6B,SAAS,MAAM;EAAS,YAAY,CAAC,eAAe,OAAO;CAAE;CAE5G,QAAQ,sBAAsB,KAAK,GAAnC;EACE,KAAK;GACH,IAAI,qBAAqB,KAAK,GAC5B,OAAO;IACL,OAAO;IACP,SACE;IACF,YAAY;KAAC;KAAW;KAAY;IAAO;GAC7C;GAEF,OAAO;IACL,OAAO;IACP,SAAS,oBACP,OACA,8FACF;IACA,YAAY,CAAC,eAAe,OAAO;GACrC;EACF,KAAK,QACH,OAAO;GACL,OAAO;GACP,SAAS,oBAAoB,OAAO,sEAAsE;GAC1G,YAAY,CAAC,eAAe,OAAO;EACrC;EACF,KAAK,oBACH,OAAO;GACL,OAAO;GACP,SAAS;GACT,YAAY,CAAC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MAAM,SAAS,oBAAoB,KAAK,KAAK;CAC7C,OAAO,SAAS,GAAG,OAAO,QAAQ,QAAQ,GAAG,EAAE,GAAG,SAAS;AAC7D;AAEA,SAAS,0BAA0B,OAA6D;CAC9F,MAAM,UAAU,oBAAoB,KAAK,MAAM,MAAM,WAAW;CAChE,MAAM,eAAe,yBAAyB,KAAK,MAAM,IAAI;CAC7D,OAAO;EACL,OAAO,eAAe,yBAAyB;EAC/C;EACA,YAAY,eAAe,CAAC,OAAO,IAAI,CAAC;CAC1C;AACF"}
@@ -0,0 +1,33 @@
1
+ import type { PubSub } from '@mastra/core/events';
2
+ import type { ResolvedSandboxEnvs, SandboxEnvAppliesTo, SandboxEnvMetadata, SandboxEnvRevisions, SandboxEnvStore, SetSandboxEnvInput } from '../storage/domains/sandbox-envs/base.js';
3
+ /** One topic for every Factory: a replica drops its cached entry for the Factory named in the event. */
4
+ export declare const SANDBOX_ENV_CHANGED_TOPIC = "factory.sandbox-env";
5
+ /**
6
+ * The sandbox-envs store with reads served from memory. The revision is
7
+ * re-read only when a write is announced (by this replica or another one
8
+ * through the event bus) or the read gets old, and values are decrypted again
9
+ * only when the revision changed. Commands and workspace resolves then cost
10
+ * no storage reads while nobody edits a variable.
11
+ *
12
+ * Writes go through to the store, drop this replica's entry and announce the
13
+ * change, so the next command anywhere sees it.
14
+ */
15
+ export declare class CachedSandboxEnvs implements SandboxEnvStore {
16
+ #private;
17
+ private readonly store;
18
+ private readonly options;
19
+ constructor(store: SandboxEnvStore, options?: {
20
+ pubsub?: PubSub;
21
+ crossProcess?: boolean;
22
+ now?: () => number;
23
+ });
24
+ /** Listen for other replicas' writes; resolves to the unsubscribe. */
25
+ subscribe(): Promise<() => Promise<void>>;
26
+ list(orgId: string, projectId: string): Promise<SandboxEnvMetadata[]>;
27
+ set(orgId: string, projectId: string, input: SetSandboxEnvInput, actorId: string): Promise<SandboxEnvMetadata>;
28
+ updateAppliesTo(orgId: string, projectId: string, name: string, appliesTo: SandboxEnvAppliesTo, actorId: string): Promise<SandboxEnvMetadata | null>;
29
+ delete(orgId: string, projectId: string, name: string): Promise<boolean>;
30
+ revisions(orgId: string, projectId: string): Promise<SandboxEnvRevisions | null>;
31
+ resolve(orgId: string, projectId: string): Promise<ResolvedSandboxEnvs>;
32
+ }
33
+ //# sourceMappingURL=sandbox-env-cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox-env-cache.d.ts","sourceRoot":"","sources":["../../src/sandbox/sandbox-env-cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGjE,OAAO,KAAK,EACV,mBAAmB,EACnB,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,kBAAkB,EACnB,MAAM,yCAAyC,CAAC;AAEjD,wGAAwG;AACxG,eAAO,MAAM,yBAAyB,wBAAwB,CAAC;AAoB/D;;;;;;;;;GASG;AACH,qBAAa,iBAAkB,YAAW,eAAe;;IAWrD,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAF1B,YACmB,KAAK,EAAE,eAAe,EACtB,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,OAAO,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAA;KAAO,EAG/F;IAED,sEAAsE;IAChE,SAAS,IAAI,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAM9C;IAED,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAEpE;IAEK,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,+BAIrF;IAEK,eAAe,CACnB,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,mBAAmB,EAC9B,OAAO,EAAE,MAAM,sCAKhB;IAEK,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,oBAI1D;IAED,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,GAAG,IAAI,CAAC,CAE/E;IAEK,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAoB5E;CAgCF"}
@@ -0,0 +1,140 @@
1
+ import { withAck } from "@mastra/core/events";
2
+ // src/sandbox/sandbox-env-cache.ts
3
+ /** One topic for every Factory: a replica drops its cached entry for the Factory named in the event. */
4
+ const SANDBOX_ENV_CHANGED_TOPIC = "factory.sandbox-env";
5
+ /**
6
+ * How long a revision read is trusted without hearing of a change. With a
7
+ * cross-process event bus, other replicas announce their writes, so this is
8
+ * only a safety net for a missed event. Without one, a write on another
9
+ * replica is only seen when the read expires.
10
+ */
11
+ const TRUST_WITH_EVENTS_MS = 6e4;
12
+ const TRUST_WITHOUT_EVENTS_MS = 1e3;
13
+ /**
14
+ * The sandbox-envs store with reads served from memory. The revision is
15
+ * re-read only when a write is announced (by this replica or another one
16
+ * through the event bus) or the read gets old, and values are decrypted again
17
+ * only when the revision changed. Commands and workspace resolves then cost
18
+ * no storage reads while nobody edits a variable.
19
+ *
20
+ * Writes go through to the store, drop this replica's entry and announce the
21
+ * change, so the next command anywhere sees it.
22
+ */
23
+ var CachedSandboxEnvs = class {
24
+ store;
25
+ options;
26
+ #entries = /* @__PURE__ */ new Map();
27
+ #origin = globalThis.crypto.randomUUID();
28
+ #trustMs;
29
+ #onEvent = withAck(async (event) => {
30
+ if (event.runId === this.#origin) return;
31
+ const { orgId, projectId } = event.data ?? {};
32
+ if (typeof orgId === "string" && typeof projectId === "string") this.#forget({
33
+ orgId,
34
+ projectId
35
+ });
36
+ });
37
+ constructor(store, options = {}) {
38
+ this.store = store;
39
+ this.options = options;
40
+ this.#trustMs = options.crossProcess ? TRUST_WITH_EVENTS_MS : TRUST_WITHOUT_EVENTS_MS;
41
+ }
42
+ /** Listen for other replicas' writes; resolves to the unsubscribe. */
43
+ async subscribe() {
44
+ const pubsub = this.options.pubsub;
45
+ if (!pubsub) return async () => {};
46
+ await pubsub.subscribe(SANDBOX_ENV_CHANGED_TOPIC, this.#onEvent, { startFrom: "latest" });
47
+ return () => pubsub.unsubscribe(SANDBOX_ENV_CHANGED_TOPIC, this.#onEvent);
48
+ }
49
+ list(orgId, projectId) {
50
+ return this.store.list(orgId, projectId);
51
+ }
52
+ async set(orgId, projectId, input, actorId) {
53
+ const env = await this.store.set(orgId, projectId, input, actorId);
54
+ this.#changed({
55
+ orgId,
56
+ projectId
57
+ });
58
+ return env;
59
+ }
60
+ async updateAppliesTo(orgId, projectId, name, appliesTo, actorId) {
61
+ const env = await this.store.updateAppliesTo(orgId, projectId, name, appliesTo, actorId);
62
+ if (env) this.#changed({
63
+ orgId,
64
+ projectId
65
+ });
66
+ return env;
67
+ }
68
+ async delete(orgId, projectId, name) {
69
+ const deleted = await this.store.delete(orgId, projectId, name);
70
+ if (deleted) this.#changed({
71
+ orgId,
72
+ projectId
73
+ });
74
+ return deleted;
75
+ }
76
+ revisions(orgId, projectId) {
77
+ return this.#entry({
78
+ orgId,
79
+ projectId
80
+ }).revisions;
81
+ }
82
+ async resolve(orgId, projectId) {
83
+ const entry = this.#entry({
84
+ orgId,
85
+ projectId
86
+ });
87
+ const current = (await entry.revisions)?.revision ?? "";
88
+ if (entry.resolved) {
89
+ const cached = await entry.resolved.catch(() => void 0);
90
+ if (cached?.revision === current) return cached;
91
+ }
92
+ const resolved = this.store.resolve(orgId, projectId);
93
+ entry.resolved = resolved;
94
+ resolved.then(({ revision, buildRevision }) => {
95
+ if (revision !== current) entry.revisions = Promise.resolve({
96
+ revision,
97
+ buildRevision
98
+ });
99
+ }, () => {
100
+ if (entry.resolved === resolved) entry.resolved = void 0;
101
+ });
102
+ return resolved;
103
+ }
104
+ #entry(scope) {
105
+ const key = keyOf(scope);
106
+ const now = (this.options.now ?? Date.now)();
107
+ const existing = this.#entries.get(key);
108
+ if (existing && now - existing.at < this.#trustMs) return existing;
109
+ const revisions = this.store.revisions(scope.orgId, scope.projectId);
110
+ const entry = {
111
+ at: now,
112
+ revisions,
113
+ ...existing?.resolved ? { resolved: existing.resolved } : {}
114
+ };
115
+ this.#entries.set(key, entry);
116
+ revisions.catch(() => {
117
+ if (this.#entries.get(key) === entry) this.#entries.delete(key);
118
+ });
119
+ return entry;
120
+ }
121
+ #forget(scope) {
122
+ this.#entries.delete(keyOf(scope));
123
+ }
124
+ #changed(scope) {
125
+ this.#forget(scope);
126
+ this.options.pubsub?.publish(SANDBOX_ENV_CHANGED_TOPIC, {
127
+ type: "factory.sandbox-env.changed",
128
+ runId: this.#origin,
129
+ data: scope
130
+ }).catch((error) => {
131
+ console.warn("[Factory] Failed to announce a sandbox environment variable change", { error: error instanceof Error ? error.message : String(error) });
132
+ });
133
+ }
134
+ };
135
+ function keyOf(scope) {
136
+ return `${scope.orgId}\u0000${scope.projectId}`;
137
+ }
138
+ export { CachedSandboxEnvs, SANDBOX_ENV_CHANGED_TOPIC };
139
+
140
+ //# sourceMappingURL=sandbox-env-cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox-env-cache.js","names":[],"sources":["../../src/sandbox/sandbox-env-cache.ts"],"sourcesContent":["import type { EventCallback, PubSub } from '@mastra/core/events';\nimport { withAck } from '@mastra/core/events';\n\nimport type {\n ResolvedSandboxEnvs,\n SandboxEnvAppliesTo,\n SandboxEnvMetadata,\n SandboxEnvRevisions,\n SandboxEnvStore,\n SetSandboxEnvInput,\n} from '../storage/domains/sandbox-envs/base.js';\n\n/** One topic for every Factory: a replica drops its cached entry for the Factory named in the event. */\nexport const SANDBOX_ENV_CHANGED_TOPIC = 'factory.sandbox-env';\n\n/**\n * How long a revision read is trusted without hearing of a change. With a\n * cross-process event bus, other replicas announce their writes, so this is\n * only a safety net for a missed event. Without one, a write on another\n * replica is only seen when the read expires.\n */\nconst TRUST_WITH_EVENTS_MS = 60_000;\nconst TRUST_WITHOUT_EVENTS_MS = 1_000;\n\ntype Scope = { orgId: string; projectId: string };\n\ninterface Entry {\n at: number;\n revisions: Promise<SandboxEnvRevisions | null>;\n /** Decrypted values, reused while the revision they were read at is current. */\n resolved?: Promise<ResolvedSandboxEnvs>;\n}\n\n/**\n * The sandbox-envs store with reads served from memory. The revision is\n * re-read only when a write is announced (by this replica or another one\n * through the event bus) or the read gets old, and values are decrypted again\n * only when the revision changed. Commands and workspace resolves then cost\n * no storage reads while nobody edits a variable.\n *\n * Writes go through to the store, drop this replica's entry and announce the\n * change, so the next command anywhere sees it.\n */\nexport class CachedSandboxEnvs implements SandboxEnvStore {\n readonly #entries = new Map<string, Entry>();\n readonly #origin = globalThis.crypto.randomUUID();\n readonly #trustMs: number;\n readonly #onEvent: EventCallback = withAck(async event => {\n if (event.runId === this.#origin) return;\n const { orgId, projectId } = (event.data ?? {}) as Partial<Scope>;\n if (typeof orgId === 'string' && typeof projectId === 'string') this.#forget({ orgId, projectId });\n });\n\n constructor(\n private readonly store: SandboxEnvStore,\n private readonly options: { pubsub?: PubSub; crossProcess?: boolean; now?: () => number } = {},\n ) {\n this.#trustMs = options.crossProcess ? TRUST_WITH_EVENTS_MS : TRUST_WITHOUT_EVENTS_MS;\n }\n\n /** Listen for other replicas' writes; resolves to the unsubscribe. */\n async subscribe(): Promise<() => Promise<void>> {\n const pubsub = this.options.pubsub;\n if (!pubsub) return async () => {};\n // Without `latest`, a retaining broker replays old changes on boot.\n await pubsub.subscribe(SANDBOX_ENV_CHANGED_TOPIC, this.#onEvent, { startFrom: 'latest' });\n return () => pubsub.unsubscribe(SANDBOX_ENV_CHANGED_TOPIC, this.#onEvent);\n }\n\n list(orgId: string, projectId: string): Promise<SandboxEnvMetadata[]> {\n return this.store.list(orgId, projectId);\n }\n\n async set(orgId: string, projectId: string, input: SetSandboxEnvInput, actorId: string) {\n const env = await this.store.set(orgId, projectId, input, actorId);\n this.#changed({ orgId, projectId });\n return env;\n }\n\n async updateAppliesTo(\n orgId: string,\n projectId: string,\n name: string,\n appliesTo: SandboxEnvAppliesTo,\n actorId: string,\n ) {\n const env = await this.store.updateAppliesTo(orgId, projectId, name, appliesTo, actorId);\n if (env) this.#changed({ orgId, projectId });\n return env;\n }\n\n async delete(orgId: string, projectId: string, name: string) {\n const deleted = await this.store.delete(orgId, projectId, name);\n if (deleted) this.#changed({ orgId, projectId });\n return deleted;\n }\n\n revisions(orgId: string, projectId: string): Promise<SandboxEnvRevisions | null> {\n return this.#entry({ orgId, projectId }).revisions;\n }\n\n async resolve(orgId: string, projectId: string): Promise<ResolvedSandboxEnvs> {\n const entry = this.#entry({ orgId, projectId });\n const current = (await entry.revisions)?.revision ?? '';\n if (entry.resolved) {\n const cached = await entry.resolved.catch(() => undefined);\n if (cached?.revision === current) return cached;\n }\n const resolved = this.store.resolve(orgId, projectId);\n entry.resolved = resolved;\n resolved.then(\n // The values carry their own revision; adopt it so the next call matches instead of decrypting again.\n ({ revision, buildRevision }) => {\n if (revision !== current) entry.revisions = Promise.resolve({ revision, buildRevision });\n },\n // Keep only a read that succeeded.\n () => {\n if (entry.resolved === resolved) entry.resolved = undefined;\n },\n );\n return resolved;\n }\n\n #entry(scope: Scope): Entry {\n const key = keyOf(scope);\n const now = (this.options.now ?? Date.now)();\n const existing = this.#entries.get(key);\n if (existing && now - existing.at < this.#trustMs) return existing;\n const revisions = this.store.revisions(scope.orgId, scope.projectId);\n // The decrypted values survive a re-read: `resolve` reuses them if the revision didn't move.\n const entry: Entry = { at: now, revisions, ...(existing?.resolved ? { resolved: existing.resolved } : {}) };\n this.#entries.set(key, entry);\n // A failed read is never served from memory.\n revisions.catch(() => {\n if (this.#entries.get(key) === entry) this.#entries.delete(key);\n });\n return entry;\n }\n\n #forget(scope: Scope): void {\n this.#entries.delete(keyOf(scope));\n }\n\n #changed(scope: Scope): void {\n this.#forget(scope);\n this.options.pubsub\n ?.publish(SANDBOX_ENV_CHANGED_TOPIC, { type: 'factory.sandbox-env.changed', runId: this.#origin, data: scope })\n .catch((error: unknown) => {\n console.warn('[Factory] Failed to announce a sandbox environment variable change', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }\n}\n\nfunction keyOf(scope: Scope): string {\n return `${scope.orgId}\\u0000${scope.projectId}`;\n}\n"],"mappings":";;;AAaA,MAAa,4BAA4B;;;;;;;AAQzC,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;;;;;;;;;;;AAqBhC,IAAa,oBAAb,MAA0D;CAWrC;CACA;CAXnB,2BAAoB,IAAI,IAAmB;CAC3C,UAAmB,WAAW,OAAO,WAAW;CAChD;CACA,WAAmC,QAAQ,OAAM,UAAS;EACxD,IAAI,MAAM,UAAU,KAAK,SAAS;EAClC,MAAM,EAAE,OAAO,cAAe,MAAM,QAAQ,CAAC;EAC7C,IAAI,OAAO,UAAU,YAAY,OAAO,cAAc,UAAU,KAAK,QAAQ;GAAE;GAAO;EAAU,CAAC;CACnG,CAAC;CAED,YACE,OACA,UAA4F,CAAC,GAC7F;EAFiB,KAAA,QAAA;EACA,KAAA,UAAA;EAEjB,KAAK,WAAW,QAAQ,eAAe,uBAAuB;CAChE;;CAGA,MAAM,YAA0C;EAC9C,MAAM,SAAS,KAAK,QAAQ;EAC5B,IAAI,CAAC,QAAQ,OAAO,YAAY,CAAC;EAEjC,MAAM,OAAO,UAAU,2BAA2B,KAAK,UAAU,EAAE,WAAW,SAAS,CAAC;EACxF,aAAa,OAAO,YAAY,2BAA2B,KAAK,QAAQ;CAC1E;CAEA,KAAK,OAAe,WAAkD;EACpE,OAAO,KAAK,MAAM,KAAK,OAAO,SAAS;CACzC;CAEA,MAAM,IAAI,OAAe,WAAmB,OAA2B,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