@vercel/factory 0.0.13 → 0.0.15

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 (458) hide show
  1. package/README.md +307 -1
  2. package/dist/agent-routes.d.mts +69 -0
  3. package/dist/agent-routes.mjs +64 -0
  4. package/dist/agent-routes.mjs.map +1 -0
  5. package/dist/api-contracts.d.mts +1749 -0
  6. package/dist/api-contracts.mjs +118 -0
  7. package/dist/api-contracts.mjs.map +1 -0
  8. package/dist/api-images.d.mts +30 -0
  9. package/dist/api-images.mjs +28 -0
  10. package/dist/api-images.mjs.map +1 -0
  11. package/dist/api-task-graph.mjs +57 -0
  12. package/dist/api-task-graph.mjs.map +1 -0
  13. package/dist/api.d.mts +77 -0
  14. package/dist/api.mjs +1087 -0
  15. package/dist/api.mjs.map +1 -0
  16. package/dist/approval-access.d.mts +39 -0
  17. package/dist/approval-access.mjs +62 -0
  18. package/dist/approval-access.mjs.map +1 -0
  19. package/dist/approval-contracts.d.mts +692 -0
  20. package/dist/approval-contracts.mjs +27 -0
  21. package/dist/approval-contracts.mjs.map +1 -0
  22. package/dist/approval.d.mts +49 -0
  23. package/dist/approval.mjs +39 -0
  24. package/dist/approval.mjs.map +1 -0
  25. package/dist/blob/artifacts.d.mts +37 -0
  26. package/dist/blob/artifacts.mjs +45 -0
  27. package/dist/blob/artifacts.mjs.map +1 -0
  28. package/dist/blob/index.d.mts +44 -8
  29. package/dist/blob/index.mjs +159 -35
  30. package/dist/blob/index.mjs.map +1 -1
  31. package/dist/budget.d.mts +108 -0
  32. package/dist/budget.mjs +141 -0
  33. package/dist/budget.mjs.map +1 -0
  34. package/dist/budgets.d.mts +4 -0
  35. package/dist/budgets.mjs +4 -0
  36. package/dist/build-factory.d.mts +6 -4
  37. package/dist/build-factory.mjs +2 -1
  38. package/dist/build-factory.mjs.map +1 -1
  39. package/dist/change-verification/brief.d.mts +9 -0
  40. package/dist/change-verification/brief.mjs +13 -0
  41. package/dist/change-verification/brief.mjs.map +1 -0
  42. package/dist/change-verification/dispatch.d.mts +24 -0
  43. package/dist/change-verification/dispatch.mjs +45 -0
  44. package/dist/change-verification/dispatch.mjs.map +1 -0
  45. package/dist/change-verification/eve-tool.d.mts +60 -0
  46. package/dist/change-verification/eve-tool.mjs +101 -0
  47. package/dist/change-verification/eve-tool.mjs.map +1 -0
  48. package/dist/changes/eve-record-change.d.mts +56 -0
  49. package/dist/changes/eve-record-change.mjs +97 -0
  50. package/dist/changes/eve-record-change.mjs.map +1 -0
  51. package/dist/changes/presentation.d.mts +14 -0
  52. package/dist/changes.d.mts +23 -0
  53. package/dist/changes.mjs +29 -0
  54. package/dist/changes.mjs.map +1 -0
  55. package/dist/client-events.d.mts +18 -0
  56. package/dist/client-events.mjs +41 -0
  57. package/dist/client-events.mjs.map +1 -0
  58. package/dist/client-stream.d.mts +28 -0
  59. package/dist/client-stream.mjs +204 -0
  60. package/dist/client-stream.mjs.map +1 -0
  61. package/dist/client-transcript.d.mts +41 -0
  62. package/dist/client-transcript.mjs +229 -0
  63. package/dist/client-transcript.mjs.map +1 -0
  64. package/dist/client.d.mts +234 -0
  65. package/dist/client.mjs +258 -0
  66. package/dist/client.mjs.map +1 -0
  67. package/dist/code-review/contracts.d.mts +26 -0
  68. package/dist/code-review/eve-post-review.d.mts +70 -0
  69. package/dist/code-review/eve-post-review.mjs +183 -0
  70. package/dist/code-review/eve-post-review.mjs.map +1 -0
  71. package/dist/code-review/eve-review-comments.d.mts +64 -0
  72. package/dist/code-review/eve-review-comments.mjs +159 -0
  73. package/dist/code-review/eve-review-comments.mjs.map +1 -0
  74. package/dist/code-review/github-contracts.d.mts +10 -0
  75. package/dist/code-review/github-reporter.d.mts +44 -0
  76. package/dist/code-review/github-reporter.mjs +260 -0
  77. package/dist/code-review/github-reporter.mjs.map +1 -0
  78. package/dist/code-review/preparation.d.mts +34 -0
  79. package/dist/code-review/preparation.mjs +23 -0
  80. package/dist/code-review/preparation.mjs.map +1 -0
  81. package/dist/code-review/stall.d.mts +17 -0
  82. package/dist/code-review/stall.mjs +30 -0
  83. package/dist/code-review/stall.mjs.map +1 -0
  84. package/dist/code-review.d.mts +6 -0
  85. package/dist/code-review.mjs +5 -0
  86. package/dist/communication.d.mts +9 -0
  87. package/dist/communication.mjs +9 -0
  88. package/dist/connectors/github.d.mts +26 -0
  89. package/dist/connectors/github.mjs +55 -0
  90. package/dist/connectors/github.mjs.map +1 -0
  91. package/dist/connectors/index.d.mts +35 -2
  92. package/dist/connectors/index.mjs +4 -26
  93. package/dist/connectors/index.mjs.map +1 -1
  94. package/dist/connectors/outbox.d.mts +34 -0
  95. package/dist/connectors/outbox.mjs +50 -0
  96. package/dist/connectors/outbox.mjs.map +1 -0
  97. package/dist/connectors/slack-approval-blocks.mjs +136 -0
  98. package/dist/connectors/slack-approval-blocks.mjs.map +1 -0
  99. package/dist/connectors/slack-approvals.d.mts +29 -0
  100. package/dist/connectors/slack-approvals.mjs +346 -0
  101. package/dist/connectors/slack-approvals.mjs.map +1 -0
  102. package/dist/connectors/slack.d.mts +35 -41
  103. package/dist/connectors/slack.mjs +13 -69
  104. package/dist/connectors/slack.mjs.map +1 -1
  105. package/dist/deepsec/eve-tool.d.mts +110 -0
  106. package/dist/deepsec/eve-tool.mjs +164 -0
  107. package/dist/deepsec/eve-tool.mjs.map +1 -0
  108. package/dist/deepsec/finding.d.mts +84 -0
  109. package/dist/deepsec/finding.mjs +56 -0
  110. package/dist/deepsec/finding.mjs.map +1 -0
  111. package/dist/deepsec.d.mts +3 -0
  112. package/dist/delivery-metrics/metrics.d.mts +93 -0
  113. package/dist/delivery-metrics/metrics.mjs +200 -0
  114. package/dist/delivery-metrics/metrics.mjs.map +1 -0
  115. package/dist/delivery-metrics.d.mts +2 -0
  116. package/dist/delivery-metrics.mjs +2 -0
  117. package/dist/dispatch.d.mts +81 -0
  118. package/dist/dispatch.mjs +140 -0
  119. package/dist/dispatch.mjs.map +1 -0
  120. package/dist/errors.d.mts +15 -0
  121. package/dist/errors.mjs +38 -0
  122. package/dist/errors.mjs.map +1 -0
  123. package/dist/eve/index.d.mts +143 -1561
  124. package/dist/eve/index.mjs +244 -1063
  125. package/dist/eve/index.mjs.map +1 -1
  126. package/dist/eve/invoke.d.mts +144 -0
  127. package/dist/eve/invoke.mjs +241 -0
  128. package/dist/eve/invoke.mjs.map +1 -0
  129. package/dist/eve/session-client.d.mts +68 -0
  130. package/dist/eve/session-client.mjs +131 -0
  131. package/dist/eve/session-client.mjs.map +1 -0
  132. package/dist/eve/task-execution.mjs +18 -0
  133. package/dist/eve/task-execution.mjs.map +1 -0
  134. package/dist/eve/task-session.d.mts +87 -0
  135. package/dist/eve/task-session.mjs +203 -0
  136. package/dist/eve/task-session.mjs.map +1 -0
  137. package/dist/eve/transcript.d.mts +37 -0
  138. package/dist/eve/transcript.mjs +65 -0
  139. package/dist/eve/transcript.mjs.map +1 -0
  140. package/dist/execution-public.d.mts +8 -0
  141. package/dist/execution-public.mjs +7 -0
  142. package/dist/execution.d.mts +75 -0
  143. package/dist/execution.mjs +153 -0
  144. package/dist/execution.mjs.map +1 -0
  145. package/dist/finding-remediation/admission.d.mts +51 -0
  146. package/dist/finding-remediation/admission.mjs +87 -0
  147. package/dist/finding-remediation/admission.mjs.map +1 -0
  148. package/dist/finding-remediation/brief.d.mts +14 -0
  149. package/dist/finding-remediation/brief.mjs +25 -0
  150. package/dist/finding-remediation/brief.mjs.map +1 -0
  151. package/dist/finding-remediation/eve-tool.d.mts +29 -0
  152. package/dist/finding-remediation/eve-tool.mjs +34 -0
  153. package/dist/finding-remediation/eve-tool.mjs.map +1 -0
  154. package/dist/findings/fingerprint.d.mts +14 -0
  155. package/dist/findings/fingerprint.mjs +28 -0
  156. package/dist/findings/fingerprint.mjs.map +1 -0
  157. package/dist/findings.d.mts +6 -0
  158. package/dist/findings.mjs +6 -0
  159. package/dist/github-app.d.mts +54 -0
  160. package/dist/github-app.mjs +121 -0
  161. package/dist/github-app.mjs.map +1 -0
  162. package/dist/github-publication.d.mts +198 -0
  163. package/dist/github-publication.mjs +429 -0
  164. package/dist/github-publication.mjs.map +1 -0
  165. package/dist/github-transfer.d.mts +72 -0
  166. package/dist/github-transfer.mjs +125 -0
  167. package/dist/github-transfer.mjs.map +1 -0
  168. package/dist/github.d.mts +406 -2
  169. package/dist/github.mjs +250 -37
  170. package/dist/github.mjs.map +1 -1
  171. package/dist/image-input.d.mts +51 -0
  172. package/dist/image-input.mjs +63 -0
  173. package/dist/image-input.mjs.map +1 -0
  174. package/dist/index.d.mts +14 -314
  175. package/dist/index.mjs +14 -1124
  176. package/dist/intake-contracts.d.mts +56 -0
  177. package/dist/intake-contracts.mjs +33 -0
  178. package/dist/intake-contracts.mjs.map +1 -0
  179. package/dist/integrations/deepsec.d.mts +4 -0
  180. package/dist/integrations/deepsec.mjs +3 -0
  181. package/dist/integrations/github.d.mts +11 -0
  182. package/dist/integrations/github.mjs +9 -0
  183. package/dist/integrations/slack.d.mts +3 -0
  184. package/dist/integrations/slack.mjs +3 -0
  185. package/dist/integrations/vercel.d.mts +3 -0
  186. package/dist/integrations/vercel.mjs +3 -0
  187. package/dist/merge-resolution/contracts.d.mts +17 -0
  188. package/dist/merge-resolution/contracts.mjs +19 -0
  189. package/dist/merge-resolution/contracts.mjs.map +1 -0
  190. package/dist/merge-resolution/eve-tools.d.mts +46 -0
  191. package/dist/merge-resolution/eve-tools.mjs +117 -0
  192. package/dist/merge-resolution/eve-tools.mjs.map +1 -0
  193. package/dist/multi-repository-changes/coordination.d.mts +49 -0
  194. package/dist/multi-repository-changes/coordination.mjs +115 -0
  195. package/dist/multi-repository-changes/coordination.mjs.map +1 -0
  196. package/dist/planning/cancellation.mjs +82 -0
  197. package/dist/planning/cancellation.mjs.map +1 -0
  198. package/dist/planning/configuration.d.mts +23 -0
  199. package/dist/planning/configuration.mjs +56 -0
  200. package/dist/planning/configuration.mjs.map +1 -0
  201. package/dist/planning/contracts.d.mts +136 -0
  202. package/dist/planning/contracts.mjs +42 -0
  203. package/dist/planning/contracts.mjs.map +1 -0
  204. package/dist/planning/dependencies.mjs +44 -0
  205. package/dist/planning/dependencies.mjs.map +1 -0
  206. package/dist/planning/effects.mjs +122 -0
  207. package/dist/planning/effects.mjs.map +1 -0
  208. package/dist/planning/reconcile.mjs +273 -0
  209. package/dist/planning/reconcile.mjs.map +1 -0
  210. package/dist/planning/runtime.d.mts +27 -0
  211. package/dist/planning/runtime.mjs +25 -0
  212. package/dist/planning/runtime.mjs.map +1 -0
  213. package/dist/planning/state.mjs +92 -0
  214. package/dist/planning/state.mjs.map +1 -0
  215. package/dist/planning/turns.mjs +262 -0
  216. package/dist/planning/turns.mjs.map +1 -0
  217. package/dist/planning/validation.mjs +106 -0
  218. package/dist/planning/validation.mjs.map +1 -0
  219. package/dist/postgres/index.d.mts +7 -1
  220. package/dist/postgres/index.mjs +7 -3
  221. package/dist/postgres/index.mjs.map +1 -1
  222. package/dist/presets/software-development/approval.d.mts +14 -0
  223. package/dist/presets/software-development/approval.mjs +21 -0
  224. package/dist/presets/software-development/approval.mjs.map +1 -0
  225. package/dist/presets/software-development/deepsec-brief.d.mts +8 -0
  226. package/dist/presets/software-development/deepsec-brief.mjs +14 -0
  227. package/dist/presets/software-development/deepsec-brief.mjs.map +1 -0
  228. package/dist/presets/software-development/dispatch.d.mts +53 -0
  229. package/dist/presets/software-development/dispatch.mjs +66 -0
  230. package/dist/presets/software-development/dispatch.mjs.map +1 -0
  231. package/dist/presets/software-development/eve-delegation-policy.d.mts +7 -0
  232. package/dist/presets/software-development/eve-delegation-policy.mjs +34 -0
  233. package/dist/presets/software-development/eve-delegation-policy.mjs.map +1 -0
  234. package/dist/presets/software-development/eve.d.mts +18 -0
  235. package/dist/presets/software-development/eve.mjs +19 -0
  236. package/dist/presets/software-development/eve.mjs.map +1 -0
  237. package/dist/presets/software-development/finish-task-policy.d.mts +7 -0
  238. package/dist/presets/software-development/finish-task-policy.mjs +9 -0
  239. package/dist/presets/software-development/finish-task-policy.mjs.map +1 -0
  240. package/dist/presets/software-development/recovery.d.mts +32 -0
  241. package/dist/presets/software-development/recovery.mjs +120 -0
  242. package/dist/presets/software-development/recovery.mjs.map +1 -0
  243. package/dist/presets/software-development/task-communication.d.mts +23 -0
  244. package/dist/presets/software-development/task-communication.mjs +120 -0
  245. package/dist/presets/software-development/task-communication.mjs.map +1 -0
  246. package/dist/presets/software-development.d.mts +9 -0
  247. package/dist/presets/software-development.mjs +9 -0
  248. package/dist/pull-requests/contracts.d.mts +72 -0
  249. package/dist/pull-requests/eve-fetch.d.mts +57 -0
  250. package/dist/pull-requests/eve-fetch.mjs +151 -0
  251. package/dist/pull-requests/eve-fetch.mjs.map +1 -0
  252. package/dist/pull-requests/github-label-manager.d.mts +27 -0
  253. package/dist/pull-requests/github-label-manager.mjs +40 -0
  254. package/dist/pull-requests/github-label-manager.mjs.map +1 -0
  255. package/dist/pull-requests/github-publisher.d.mts +53 -0
  256. package/dist/pull-requests/github-publisher.mjs +345 -0
  257. package/dist/pull-requests/github-publisher.mjs.map +1 -0
  258. package/dist/pull-requests.d.mts +5 -0
  259. package/dist/pull-requests.mjs +4 -0
  260. package/dist/receipts.d.mts +4 -0
  261. package/dist/receipts.mjs +3 -0
  262. package/dist/repositories.d.mts +18 -0
  263. package/dist/repositories.mjs +33 -0
  264. package/dist/repositories.mjs.map +1 -0
  265. package/dist/sandbox/command.d.mts +18 -0
  266. package/dist/sandbox/execution-abort.d.mts +16 -0
  267. package/dist/sandbox/execution-abort.mjs +49 -0
  268. package/dist/sandbox/execution-abort.mjs.map +1 -0
  269. package/dist/sandbox/execution-environment.d.mts +25 -0
  270. package/dist/sandbox/execution-run-ledger.d.mts +115 -0
  271. package/dist/sandbox/execution-run-ledger.mjs +209 -0
  272. package/dist/sandbox/execution-run-ledger.mjs.map +1 -0
  273. package/dist/sandbox/execution.d.mts +54 -0
  274. package/dist/sandbox/execution.mjs +228 -0
  275. package/dist/sandbox/execution.mjs.map +1 -0
  276. package/dist/sandbox/harness-runner.d.mts +79 -0
  277. package/dist/sandbox/harness-runner.mjs +162 -0
  278. package/dist/sandbox/harness-runner.mjs.map +1 -0
  279. package/dist/sandbox/index.d.mts +9 -0
  280. package/dist/sandbox/index.mjs +7 -0
  281. package/dist/sandbox/task-environment.d.mts +50 -0
  282. package/dist/sandbox/task-environment.mjs +140 -0
  283. package/dist/sandbox/task-environment.mjs.map +1 -0
  284. package/dist/sandbox/workspace.d.mts +29 -0
  285. package/dist/sandbox/workspace.mjs +28 -0
  286. package/dist/sandbox/workspace.mjs.map +1 -0
  287. package/dist/schema/agent-route.d.mts +22 -0
  288. package/dist/schema/agent-route.mjs +15 -0
  289. package/dist/schema/agent-route.mjs.map +1 -0
  290. package/dist/schema/answer.d.mts +23 -0
  291. package/dist/schema/answer.mjs +21 -0
  292. package/dist/schema/answer.mjs.map +1 -0
  293. package/dist/schema/budget.d.mts +38 -0
  294. package/dist/schema/budget.mjs +30 -0
  295. package/dist/schema/budget.mjs.map +1 -0
  296. package/dist/schema/catalog.mjs +72 -0
  297. package/dist/schema/catalog.mjs.map +1 -0
  298. package/dist/schema/change.d.mts +117 -0
  299. package/dist/schema/change.mjs +68 -0
  300. package/dist/schema/change.mjs.map +1 -0
  301. package/dist/schema/common.d.mts +33 -0
  302. package/dist/{id-DwCihQr4.mjs → schema/common.mjs} +7 -14
  303. package/dist/schema/common.mjs.map +1 -0
  304. package/dist/schema/communication.d.mts +52 -0
  305. package/dist/schema/communication.mjs +35 -0
  306. package/dist/schema/communication.mjs.map +1 -0
  307. package/dist/schema/execution.d.mts +101 -0
  308. package/dist/schema/execution.mjs +86 -0
  309. package/dist/schema/execution.mjs.map +1 -0
  310. package/dist/schema/factory-config.d.mts +95 -0
  311. package/dist/schema/factory-config.mjs +60 -0
  312. package/dist/schema/factory-config.mjs.map +1 -0
  313. package/dist/schema/finding.d.mts +125 -0
  314. package/dist/schema/finding.mjs +67 -0
  315. package/dist/schema/finding.mjs.map +1 -0
  316. package/dist/schema/id.d.mts +43 -0
  317. package/dist/schema/id.mjs +32 -0
  318. package/dist/schema/id.mjs.map +1 -0
  319. package/dist/schema/outbox.d.mts +240 -0
  320. package/dist/schema/outbox.mjs +53 -0
  321. package/dist/schema/outbox.mjs.map +1 -0
  322. package/dist/schema/question-route.mjs +16 -0
  323. package/dist/schema/question-route.mjs.map +1 -0
  324. package/dist/schema/receipt.d.mts +81 -0
  325. package/dist/schema/receipt.mjs +94 -0
  326. package/dist/schema/receipt.mjs.map +1 -0
  327. package/dist/schema/repository.d.mts +26 -0
  328. package/dist/schema/repository.mjs +25 -0
  329. package/dist/schema/repository.mjs.map +1 -0
  330. package/dist/schema/session.d.mts +135 -0
  331. package/dist/schema/session.mjs +53 -0
  332. package/dist/schema/session.mjs.map +1 -0
  333. package/dist/schema/signal.d.mts +105 -0
  334. package/dist/schema/signal.mjs +81 -0
  335. package/dist/schema/signal.mjs.map +1 -0
  336. package/dist/schema/stored-session.mjs +10 -0
  337. package/dist/schema/stored-session.mjs.map +1 -0
  338. package/dist/schema/stored-task.mjs +20 -0
  339. package/dist/schema/stored-task.mjs.map +1 -0
  340. package/dist/schema/task-effect.d.mts +39 -0
  341. package/dist/schema/task-effect.mjs +29 -0
  342. package/dist/schema/task-effect.mjs.map +1 -0
  343. package/dist/schema/task-graph.d.mts +3134 -0
  344. package/dist/schema/task-graph.mjs +97 -0
  345. package/dist/schema/task-graph.mjs.map +1 -0
  346. package/dist/schema/task-message.d.mts +254 -0
  347. package/dist/schema/task-message.mjs +189 -0
  348. package/dist/schema/task-message.mjs.map +1 -0
  349. package/dist/schema/task.d.mts +272 -0
  350. package/dist/schema/task.mjs +199 -0
  351. package/dist/schema/task.mjs.map +1 -0
  352. package/dist/schema/transcript.d.mts +170 -0
  353. package/dist/schema/transcript.mjs +86 -0
  354. package/dist/schema/transcript.mjs.map +1 -0
  355. package/dist/schema/transitions.d.mts +50 -0
  356. package/dist/schema/transitions.mjs +303 -0
  357. package/dist/schema/transitions.mjs.map +1 -0
  358. package/dist/schema/work.d.mts +101 -0
  359. package/dist/schema/work.mjs +102 -0
  360. package/dist/schema/work.mjs.map +1 -0
  361. package/dist/signal-triage.d.mts +20 -0
  362. package/dist/signal-triage.mjs +85 -0
  363. package/dist/signal-triage.mjs.map +1 -0
  364. package/dist/signals.d.mts +19 -0
  365. package/dist/signals.mjs +19 -0
  366. package/dist/signals.mjs.map +1 -0
  367. package/dist/stall.d.mts +38 -0
  368. package/dist/stall.mjs +79 -0
  369. package/dist/stall.mjs.map +1 -0
  370. package/dist/storage.d.mts +4 -0
  371. package/dist/storage.mjs +4 -0
  372. package/dist/store/driver.d.mts +65 -0
  373. package/dist/store/driver.mjs +42 -0
  374. package/dist/store/driver.mjs.map +1 -0
  375. package/dist/store/engine.d.mts +485 -0
  376. package/dist/store/engine.mjs +2175 -0
  377. package/dist/store/engine.mjs.map +1 -0
  378. package/dist/store/memory.d.mts +7 -0
  379. package/dist/store/memory.mjs +52 -0
  380. package/dist/store/memory.mjs.map +1 -0
  381. package/dist/store/task-effects.d.mts +38 -0
  382. package/dist/store/task-effects.mjs +118 -0
  383. package/dist/store/task-effects.mjs.map +1 -0
  384. package/dist/store/task-graphs.d.mts +60 -0
  385. package/dist/store/task-graphs.mjs +212 -0
  386. package/dist/store/task-graphs.mjs.map +1 -0
  387. package/dist/store/task-messages.d.mts +136 -0
  388. package/dist/store/task-messages.mjs +475 -0
  389. package/dist/store/task-messages.mjs.map +1 -0
  390. package/dist/store/task-work.d.mts +65 -0
  391. package/dist/store/task-work.mjs +134 -0
  392. package/dist/store/task-work.mjs.map +1 -0
  393. package/dist/store/work-notifications.d.mts +19 -0
  394. package/dist/store/work-notifications.mjs +48 -0
  395. package/dist/store/work-notifications.mjs.map +1 -0
  396. package/dist/sweep.d.mts +57 -0
  397. package/dist/sweep.mjs +143 -0
  398. package/dist/sweep.mjs.map +1 -0
  399. package/dist/task-communication.d.mts +35 -0
  400. package/dist/task-communication.mjs +47 -0
  401. package/dist/task-communication.mjs.map +1 -0
  402. package/dist/task-graph-view.d.mts +264 -0
  403. package/dist/task-graph-view.mjs +17 -0
  404. package/dist/task-graph-view.mjs.map +1 -0
  405. package/dist/task-message-processing.d.mts +60 -0
  406. package/dist/task-message-processing.mjs +200 -0
  407. package/dist/task-message-processing.mjs.map +1 -0
  408. package/dist/task-protocols.d.mts +80 -0
  409. package/dist/task-protocols.mjs +47 -0
  410. package/dist/task-protocols.mjs.map +1 -0
  411. package/dist/tasks.d.mts +17 -0
  412. package/dist/tasks.mjs +17 -0
  413. package/dist/vercel-git.d.mts +21 -0
  414. package/dist/vercel-git.mjs +112 -0
  415. package/dist/vercel-git.mjs.map +1 -0
  416. package/dist/vercel.d.mts +33 -2
  417. package/dist/vercel.mjs +48 -3
  418. package/dist/vercel.mjs.map +1 -1
  419. package/dist/work-triage/eve-tool.d.mts +29 -0
  420. package/dist/work-triage/eve-tool.mjs +32 -0
  421. package/dist/work-triage/eve-tool.mjs.map +1 -0
  422. package/dist/work-triage/find-existing-work.d.mts +32 -0
  423. package/dist/work-triage/find-existing-work.mjs +31 -0
  424. package/dist/work-triage/find-existing-work.mjs.map +1 -0
  425. package/dist/work-triage/github.d.mts +15 -0
  426. package/dist/work-triage/github.mjs +14 -0
  427. package/dist/work-triage/github.mjs.map +1 -0
  428. package/dist/work-triage.d.mts +3 -0
  429. package/dist/work-triage.mjs +3 -0
  430. package/dist/workflows.d.mts +48 -0
  431. package/dist/workflows.mjs +86 -0
  432. package/dist/workflows.mjs.map +1 -0
  433. package/dist/workspace-diff-assembly.d.mts +33 -0
  434. package/dist/workspace-diff-assembly.mjs +95 -0
  435. package/dist/workspace-diff-assembly.mjs.map +1 -0
  436. package/dist/workspace-diff.d.mts +90 -0
  437. package/dist/workspace-diff.mjs +61 -0
  438. package/dist/workspace-diff.mjs.map +1 -0
  439. package/dist/workspace-snapshot.d.mts +26 -0
  440. package/dist/workspace-snapshot.mjs +80 -0
  441. package/dist/workspace-snapshot.mjs.map +1 -0
  442. package/package.json +129 -40
  443. package/dist/approval-CwhTP1XB.mjs +0 -269
  444. package/dist/approval-CwhTP1XB.mjs.map +0 -1
  445. package/dist/change-CzEAoFVE.mjs +0 -620
  446. package/dist/change-CzEAoFVE.mjs.map +0 -1
  447. package/dist/dispatch-B77cuPxh.d.mts +0 -713
  448. package/dist/driver-BJutB0PE.d.mts +0 -34
  449. package/dist/driver-Bbd25rNM.mjs +0 -23
  450. package/dist/driver-Bbd25rNM.mjs.map +0 -1
  451. package/dist/factory-config-BJcjsPKl.mjs +0 -86
  452. package/dist/factory-config-BJcjsPKl.mjs.map +0 -1
  453. package/dist/factory-config-D2yU3G0c.d.mts +0 -58
  454. package/dist/github-DXsxboUL.d.mts +0 -271
  455. package/dist/id-DwCihQr4.mjs.map +0 -1
  456. package/dist/index-Cy4jfXh5.d.mts +0 -67
  457. package/dist/index.mjs.map +0 -1
  458. package/dist/signal-CHVEmzvI.d.mts +0 -59
@@ -1,922 +1,15 @@
1
- import { i as repositoryIdSchema, o as signalIdSchema, p as vocabularySchema, s as taskIdSchema, t as changeIdSchema } from "../id-DwCihQr4.mjs";
2
- import { b as taskQuestionSchema, c as findingSchema, i as requiresApproval, o as findingFingerprint, r as defaultApprovalPolicy } from "../approval-CwhTP1XB.mjs";
3
- import { b as createCoordination, c as dispatchTask, i as levelSchema, t as changeEvidenceSchema } from "../change-CzEAoFVE.mjs";
4
- import { answerReviewComment, readPullRequestHead, readReviewComment, submitPullRequestReview } from "../github.mjs";
1
+ import { changeIdSchema, repositoryIdsSchema, signalIdSchema, taskIdSchema } from "../schema/id.mjs";
2
+ import { taskWork } from "../schema/work.mjs";
3
+ import { taskQuestionSchema } from "../schema/task.mjs";
4
+ import { receiptKindSchema, receiptStateSchema } from "../schema/receipt.mjs";
5
+ import { conversationBinding, conversationBindingForSession, conversationHeaders, factoryReplyAddressAttribute, factoryReplyAddressHeader, factoryReplyChannelAttribute, factoryReplyChannelHeader, factoryRepositoryIdsAttribute, factoryRepositoryIdsHeader, factoryTaskAttemptAttribute, factoryTaskAttemptHeader, factoryTaskAttribute, factoryTaskHeader, hasFactoryTaskBinding, optionalTaskIdForSession, replyToForSession, repositoryIdsForSession, requireTaskIdForSession, taskBindingForSession, taskHeaders, taskSessionAuth, withFactoryTask, withOptionalFactoryTask } from "./task-session.mjs";
6
+ import { requireTaskExecution } from "./task-execution.mjs";
7
+ import { createEveTranscriptMaterializer } from "./transcript.mjs";
8
+ import { cancelEveSession, forwardEveSessionRequest, readCompletedEveTurn, startEveSession } from "./session-client.mjs";
9
+ import { createDelegateAgentTool, createInvokeAgentTool } from "./invoke.mjs";
5
10
  import { z } from "zod";
6
- import { createHash } from "node:crypto";
7
11
  import { defineHook } from "eve/hooks";
8
12
  import { defineTool } from "eve/tools";
9
- //#region src/eve/conflict.ts
10
- const gitShaSchema = z.string().regex(/^[0-9a-f]{40}$/);
11
- const gitBranchSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/).refine((value) => !value.includes(".."));
12
- const mergeConflictPayloadSchema = z.strictObject({
13
- repository: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/),
14
- prNumber: z.number().int().positive(),
15
- prUrl: z.url(),
16
- headBranch: gitBranchSchema.refine((value) => value.startsWith("factory/")),
17
- headSha: gitShaSchema,
18
- baseBranch: gitBranchSchema,
19
- baseSha: gitShaSchema
20
- });
21
- function mergeConflictTools(stores, options) {
22
- const repoPath = options.repoPath ?? "repo";
23
- async function context(taskId) {
24
- const task = await stores.tasks.get(taskId);
25
- if (task === null) throw new Error(`task ${taskId} does not exist`);
26
- if (task.kind !== "merge_conflict") throw new Error(`task ${taskId} is ${task.kind}, not merge_conflict`);
27
- if (task.state !== "running") throw new Error(`task ${taskId} is ${task.state}, not running`);
28
- if (task.origin.signalId === void 0) throw new Error(`task ${taskId} has no conflict signal`);
29
- const signal = await stores.signals.get(task.origin.signalId);
30
- if (signal === null || signal.source !== "github_merge_conflict") throw new Error(`task ${taskId} has no GitHub merge conflict signal`);
31
- return {
32
- task,
33
- conflict: mergeConflictPayloadSchema.parse(signal.payload)
34
- };
35
- }
36
- return {
37
- fetch_merge_conflict: defineTool({
38
- description: "Fetch the conflicted factory pull request and its current base, check out the PR head, and start the merge. Resolve every file returned in conflictedFiles, then test and commit the merge.",
39
- inputSchema: z.object({ taskId: taskIdSchema }),
40
- async execute({ taskId }, ctx) {
41
- const { conflict } = await context(taskId);
42
- const sandbox = await ctx.getSandbox();
43
- const git = `git -C ${repoPath}`;
44
- const headRef = `refs/remotes/origin/conflict-pr-${conflict.prNumber}`;
45
- const baseRef = `refs/remotes/origin/conflict-base-${conflict.prNumber}`;
46
- const fetch = await options.withCredential(sandbox, conflict.repository, `${git} fetch --depth 100 origin +refs/pull/${conflict.prNumber}/head:${headRef} +refs/heads/${conflict.baseBranch}:${baseRef}`);
47
- if (typeof fetch.exitCode === "number" && fetch.exitCode !== 0) throw new Error(`could not fetch pull request: ${(fetch.stderr ?? "").trim()}`);
48
- const [headSha, baseSha] = (await sandbox.run({ command: `${git} rev-parse ${headRef} && ${git} rev-parse ${baseRef}` })).stdout.trim().split("\n");
49
- if (headSha !== conflict.headSha || baseSha !== conflict.baseSha) throw new Error("pull request or base changed while conflict resolution was starting; retry from a new task");
50
- await sandbox.run({ command: `${git} checkout -B conflict-pr ${headRef}` });
51
- const merge = await sandbox.run({ command: `${git} merge --no-commit --no-ff ${baseRef}` });
52
- const conflictedFiles = (await sandbox.run({ command: `${git} diff --name-only --diff-filter=U` })).stdout.trim().split("\n").filter(Boolean);
53
- if (conflictedFiles.length === 0) throw new Error(typeof merge.exitCode === "number" && merge.exitCode !== 0 ? `merge failed without file conflicts: ${(merge.stderr ?? "").trim()}` : "pull request no longer has merge conflicts");
54
- return {
55
- ...conflict,
56
- conflictedFiles
57
- };
58
- }
59
- }),
60
- publish_merge_resolution: defineTool({
61
- description: "Publish a tested, committed conflict resolution to the existing pull request branch. Fails if the remote branch changed since this task started.",
62
- inputSchema: z.object({
63
- taskId: taskIdSchema,
64
- summary: z.string().min(1).max(2e3)
65
- }),
66
- async execute({ taskId, summary }, ctx) {
67
- const { conflict } = await context(taskId);
68
- const sandbox = await ctx.getSandbox();
69
- const git = `git -C ${repoPath}`;
70
- if ((await sandbox.run({ command: `${git} status --porcelain` })).stdout.trim() !== "") throw new Error("commit the conflict resolution before publishing");
71
- if ((await sandbox.run({ command: `${git} diff --name-only --diff-filter=U` })).stdout.trim() !== "") throw new Error("merge conflicts remain unresolved");
72
- const push = await options.withCredential(sandbox, conflict.repository, `${git} push --force-with-lease=refs/heads/${conflict.headBranch}:${conflict.headSha} origin HEAD:refs/heads/${conflict.headBranch}`);
73
- if (typeof push.exitCode === "number" && push.exitCode !== 0) throw new Error(`could not update pull request branch: ${(push.stderr ?? "").trim()}`);
74
- await stores.tasks.transition(taskId, "verifying", { reason: summary });
75
- await stores.tasks.transition(taskId, "succeeded", { reason: summary });
76
- return {
77
- updated: true,
78
- prNumber: conflict.prNumber,
79
- prUrl: conflict.prUrl
80
- };
81
- }
82
- })
83
- };
84
- }
85
- //#endregion
86
- //#region src/eve/finding.ts
87
- function isLostRaceError(error) {
88
- return error instanceof Error && (error.name === "VersionConflictError" || error.name === "InvalidTransitionError");
89
- }
90
- /**
91
- * Turn one finding into a signal and a fix task. The fingerprint is the
92
- * signal's delivery id, so the same problem reported twice is a no-op. The
93
- * signal is accepted on the reporter's own verification (a human gate follows
94
- * when the approval policy says so), and the task carries the approval
95
- * decision from the moment it exists. Shared by record_finding and scanner
96
- * tools that record on the agent's behalf.
97
- */
98
- async function recordFinding(stores, repositoryId, finding, options = {}) {
99
- const source = options.source ?? "security_scan";
100
- const policy = options.approval ?? defaultApprovalPolicy;
101
- if (await stores.repositories.get(repositoryId) === null) return {
102
- recorded: false,
103
- reason: `repository ${repositoryId} does not exist`
104
- };
105
- const fingerprint = findingFingerprint(repositoryId, finding);
106
- const signal = await stores.signals.create({
107
- repositoryId,
108
- source,
109
- deliveryId: fingerprint,
110
- replyTo: {
111
- channel: "finding",
112
- address: fingerprint
113
- },
114
- payload: finding
115
- });
116
- if (signal.outcome !== "pending") return {
117
- recorded: false,
118
- duplicate: true,
119
- signalId: signal.id,
120
- reason: `already recorded as ${signal.id}`
121
- };
122
- try {
123
- await stores.signals.decide(signal.id, "accepted", {
124
- detail: finding.priority,
125
- reason: `${finding.tool ?? "scanner"} reported it, ${finding.verification.level} by ${finding.verification.method}`
126
- });
127
- } catch (error) {
128
- if (isLostRaceError(error)) {
129
- const current = await stores.signals.get(signal.id);
130
- if (current !== null && current.outcome !== "pending") return {
131
- recorded: false,
132
- duplicate: true,
133
- signalId: signal.id,
134
- reason: `already recorded as ${signal.id}`
135
- };
136
- }
137
- throw error;
138
- }
139
- const approval = requiresApproval(policy, {
140
- source,
141
- kind: "code_change",
142
- priority: finding.priority
143
- });
144
- const task = await stores.tasks.create({
145
- repositoryIds: [repositoryId],
146
- kind: "code_change",
147
- origin: { signalId: signal.id },
148
- replyTo: signal.replyTo,
149
- ...approval ? { approval: "required" } : {}
150
- });
151
- return {
152
- recorded: true,
153
- signalId: signal.id,
154
- taskId: task.id,
155
- approval: approval ? "required" : "not_required"
156
- };
157
- }
158
- /**
159
- * The scanner's outcome tool: turns one finding into a signal and a fix task
160
- * in a single deterministic step. The finding's fingerprint is the signal's
161
- * delivery id, so reporting the same problem twice is a no-op. The signal is
162
- * accepted on the reporter's own verification (a human gate follows when the
163
- * approval policy says so), and the task carries the approval decision from
164
- * the moment it exists.
165
- */
166
- function recordFindingTool(stores, options = {}) {
167
- return defineTool({
168
- description: "Record one problem you found in the repository. Creates a fix task (which may wait for human approval) unless the same finding was already recorded. Report every finding separately; never batch.",
169
- inputSchema: z.object({
170
- repositoryId: repositoryIdSchema,
171
- finding: findingSchema
172
- }),
173
- execute({ repositoryId, finding }) {
174
- return recordFinding(stores, repositoryId, finding, options);
175
- }
176
- });
177
- }
178
- //#endregion
179
- //#region src/eve/deepsec.ts
180
- /** deepsec's exported finding shape, as far as we depend on it. */
181
- const deepsecFindingSchema = z.looseObject({
182
- title: z.string().min(1),
183
- description: z.string().min(1),
184
- severity: z.string().min(1),
185
- metadata: z.looseObject({
186
- filePath: z.string().min(1).optional(),
187
- lineNumbers: z.array(z.number().int().min(1)).optional(),
188
- vulnSlug: z.string().min(1).optional(),
189
- confidence: z.string().optional(),
190
- runId: z.string().optional()
191
- }).optional()
192
- });
193
- const deepsecExportSchema = z.union([z.array(deepsecFindingSchema), z.looseObject({ findings: z.array(deepsecFindingSchema) }).transform((value) => value.findings)]);
194
- const priorityBySeverity = {
195
- CRITICAL: "P0",
196
- HIGH: "P1",
197
- MEDIUM: "P2",
198
- HIGH_BUG: "P2",
199
- BUG: "P3",
200
- LOW: "P3"
201
- };
202
- /** Convert one deepsec finding into the factory's Finding. Pure; exported for tests. */
203
- function findingFromDeepsec(raw) {
204
- const meta = raw.metadata ?? {};
205
- const confidence = (meta.confidence ?? "").toLowerCase();
206
- const line = meta.lineNumbers?.[0];
207
- const endLine = meta.lineNumbers === void 0 ? void 0 : Math.max(...meta.lineNumbers);
208
- return findingSchema.parse({
209
- title: raw.title.replace(/^\[[A-Z_]+\]\s*/u, "").slice(0, 200),
210
- body: raw.description.slice(0, 8e3),
211
- ...meta.filePath === void 0 ? {} : { path: meta.filePath.slice(0, 500) },
212
- ...line === void 0 ? {} : { line },
213
- ...endLine === void 0 || endLine === line ? {} : { endLine },
214
- priority: priorityBySeverity[raw.severity.toUpperCase()] ?? "P3",
215
- category: "security",
216
- verification: {
217
- level: confidence === "high" ? "supported" : "unverified",
218
- method: "static_analysis",
219
- summary: `deepsec ${meta.vulnSlug ?? "finding"} with ${confidence || "unknown"} confidence${meta.runId === void 0 ? "" : ` (run ${meta.runId})`}.`,
220
- limitations: "AI-assisted static analysis of the checkout; not reproduced at runtime."
221
- },
222
- tool: "deepsec",
223
- ...meta.vulnSlug === void 0 ? {} : { ruleId: meta.vulnSlug }
224
- });
225
- }
226
- const findingsPath = "/tmp/deepsec-findings.json";
227
- /** Parse "N file(s) with candidates" out of deepsec scan output; null when absent. */
228
- function candidateCount(output) {
229
- const match = /(\d+)\s+file\(s\) with candidates/u.exec(output);
230
- return match?.[1] === void 0 ? null : Number(match[1]);
231
- }
232
- /** The last few meaningful lines of a command's output, ANSI stripped, for a receipt. */
233
- function tail(output, lines = 4) {
234
- return output.replaceAll(/\u001b\[[0-9;]*m/gu, "").split("\n").map((line) => line.trim()).filter((line) => line !== "").slice(-lines).join(" | ").slice(0, 600);
235
- }
236
- /**
237
- * Runs deepsec (vercel-labs/deepsec) against the sandbox checkout and records
238
- * what it finds through the same path as record_finding, so every deepsec
239
- * finding becomes a fix task subject to the approval policy. Trusted code
240
- * owns the command sequence and the credential; the agent chooses when to
241
- * scan and reports the outcome.
242
- */
243
- function deepsecScanTool(stores, options) {
244
- const repoPath = options.repoPath ?? "repo";
245
- const workspace = options.workspacePath ?? "deepsec";
246
- const version = options.version ?? "2.3.8";
247
- const agent = options.agent ?? "claude";
248
- const model = options.model ?? "claude-sonnet-4-6";
249
- const thinkingLevel = options.thinkingLevel ?? "medium";
250
- const concurrency = options.concurrency ?? 4;
251
- const prefix = options.commandPrefix === void 0 ? [] : [options.commandPrefix];
252
- const filesPerRun = options.filesPerRun ?? 40;
253
- return defineTool({
254
- description: "Run deepsec, the AI-powered vulnerability scanner, over the repository checkout and record every finding it reports as a fix task. Takes minutes. Call once per scan; then summarize the result.",
255
- inputSchema: z.object({
256
- repositoryId: repositoryIdSchema,
257
- limit: z.number().int().min(1).max(500).optional().describe("Candidate files to investigate this run (default 40; deepsec resumes where it left off next time).")
258
- }),
259
- async execute({ repositoryId, limit }, ctx) {
260
- const repository = await stores.repositories.get(repositoryId);
261
- if (repository === null) return {
262
- scanned: false,
263
- reason: `repository ${repositoryId} does not exist`
264
- };
265
- const sandbox = await ctx.getSandbox();
266
- const projectId = repository.slug.replace(/[^a-z0-9]+/gu, "-");
267
- const startedAt = Date.now();
268
- const phase = async (state, reason) => {
269
- await stores.receipts.append({
270
- repositoryIds: [repositoryId],
271
- kind: "deepsec",
272
- state,
273
- phase: "security_scan",
274
- reason: `${reason} (${Math.round((Date.now() - startedAt) / 1e3)}s in)`
275
- });
276
- };
277
- await phase("started", `deepsec ${version} on ${repository.slug}, ${agent}/${model}`);
278
- const prepare = await sandbox.run({ command: [
279
- ...prefix,
280
- "set -e",
281
- `if [ ! -f ${workspace}/deepsec.config.ts ]; then`,
282
- ` npx -y deepsec@${version} init ./${workspace} ./${repoPath} --id ${projectId} --scaffold-only --headless --yes --skip-install`,
283
- ` (cd ${workspace} && npm install --no-audit --no-fund --loglevel=error)`,
284
- "fi",
285
- `cd ${workspace}`,
286
- `./node_modules/.bin/deepsec scan --project-id ${projectId}`
287
- ].join("\n") });
288
- if (typeof prepare.exitCode === "number" && prepare.exitCode !== 0) {
289
- const detail = (prepare.stderr ?? prepare.stdout).trim().slice(-1500);
290
- await phase("failed", `scan phase failed: ${detail.slice(-300)}`);
291
- return {
292
- scanned: false,
293
- reason: `deepsec scan failed: ${detail}`
294
- };
295
- }
296
- const candidates = candidateCount(prepare.stdout);
297
- await phase("scanned", `${candidates === null ? "scan output" : `${candidates} files with candidates`}: ${tail(`${prepare.stdout}\n${prepare.stderr ?? ""}`)}`);
298
- const investigate = await options.withModelCredential(sandbox, [
299
- ...prefix,
300
- "set -e",
301
- `cd ${workspace}`,
302
- `./node_modules/.bin/deepsec process --project-id ${projectId} --agent ${agent} --model ${model} --thinking-level ${thinkingLevel} --concurrency ${concurrency} --limit ${limit ?? filesPerRun}`,
303
- `./node_modules/.bin/deepsec export --project-id ${projectId} --format json --out ${findingsPath}`
304
- ].join("\n"));
305
- if (typeof investigate.exitCode === "number" && investigate.exitCode !== 0) {
306
- const detail = (investigate.stderr ?? investigate.stdout).trim().slice(-1500);
307
- await phase("failed", `process phase failed: ${detail.slice(-300)}`);
308
- return {
309
- scanned: false,
310
- reason: `deepsec process failed: ${detail}`
311
- };
312
- }
313
- const exported = await sandbox.run({ command: `cat ${findingsPath}` });
314
- let parsed;
315
- try {
316
- parsed = JSON.parse(exported.stdout);
317
- } catch {
318
- return {
319
- scanned: false,
320
- reason: "deepsec export was not valid JSON"
321
- };
322
- }
323
- const raw = deepsecExportSchema.safeParse(parsed);
324
- if (!raw.success) return {
325
- scanned: false,
326
- reason: `deepsec export had an unexpected shape: ${raw.error.issues[0]?.message ?? "unknown"}`
327
- };
328
- const results = [];
329
- for (const entry of raw.data) {
330
- const finding = findingFromDeepsec(entry);
331
- results.push({
332
- finding,
333
- result: await recordFinding(stores, repositoryId, finding, options)
334
- });
335
- }
336
- const recorded = results.filter(({ result }) => result.recorded);
337
- await phase("completed", `${results.length} findings, ${recorded.length} new. process output: ${tail(`${investigate.stdout}\n${investigate.stderr ?? ""}`, 6)}`);
338
- return {
339
- scanned: true,
340
- tool: "deepsec",
341
- found: results.length,
342
- recorded: recorded.length,
343
- duplicates: results.length - recorded.length,
344
- awaitingApproval: recorded.filter(({ result }) => result.recorded && result.approval === "required").length,
345
- findings: results.map(({ finding, result }) => ({
346
- title: finding.title,
347
- priority: finding.priority,
348
- path: finding.path,
349
- line: finding.line,
350
- ...result.recorded ? {
351
- taskId: result.taskId,
352
- approval: result.approval
353
- } : { duplicate: true }
354
- }))
355
- };
356
- }
357
- });
358
- }
359
- //#endregion
360
- //#region src/eve/fetch.ts
361
- /**
362
- * The verifier's way in to the change under review. The sandbox has no
363
- * GitHub credential while the agent runs, so trusted code does the one fetch
364
- * the agent cannot: the pull request number and repository come from the
365
- * change record, never from the agent, and the credential is gone again
366
- * before control returns. Mirrors how publication reads commits out of the
367
- * sandbox instead of letting the agent push.
368
- */
369
- function fetchPullRequestTool(stores, options) {
370
- const repoPath = options.repoPath ?? "repo";
371
- const depth = options.depth ?? 50;
372
- return defineTool({
373
- description: "Fetch the pull request and the repository's current default branch, then check out the pull request as local branch `pr`. Call this after get_task, before inspecting or testing the change. Returns an exact diff command based on their merge base; use it instead of origin/HEAD.",
374
- inputSchema: z.object({ changeId: changeIdSchema.describe("The change under review, from your starting message.") }),
375
- async execute({ changeId }, ctx) {
376
- const change = await stores.changes.get(changeId);
377
- if (change === null) return {
378
- fetched: false,
379
- reason: `change ${changeId} does not exist`
380
- };
381
- if (change.state !== "verifying" && change.state !== "ready") return {
382
- fetched: false,
383
- reason: `change is ${change.state}, not open for review; nothing to fetch`
384
- };
385
- const repository = await stores.repositories.get(change.repositoryId);
386
- if (repository === null) return {
387
- fetched: false,
388
- reason: `repository ${change.repositoryId} does not exist`
389
- };
390
- const sandbox = await ctx.getSandbox();
391
- const tracking = `refs/remotes/origin/pr-${change.prNumber}`;
392
- const baseTracking = `refs/remotes/origin/${repository.defaultBranch}`;
393
- const git = `git -C ${repoPath}`;
394
- const result = await options.withCredential(sandbox, repository.slug, `${git} fetch --depth ${depth} origin +refs/heads/${repository.defaultBranch}:${baseTracking} +refs/pull/${change.prNumber}/head:${tracking} && ${git} checkout -B pr ${tracking}`);
395
- if (typeof result.exitCode === "number" && result.exitCode !== 0) return {
396
- fetched: false,
397
- reason: `git fetch of pull request ${change.prNumber} failed: ${(result.stderr ?? "").trim()}`
398
- };
399
- const head = await sandbox.run({ command: `${git} rev-parse HEAD` });
400
- const base = await sandbox.run({ command: `${git} rev-parse ${baseTracking}` });
401
- const mergeBase = await sandbox.run({ command: `${git} merge-base ${baseTracking} pr` });
402
- if (typeof mergeBase.exitCode === "number" && mergeBase.exitCode !== 0) return {
403
- fetched: false,
404
- reason: `could not determine the pull request merge base: ${(mergeBase.stderr ?? "").trim()}`
405
- };
406
- const mergeBaseSha = mergeBase.stdout.trim();
407
- return {
408
- fetched: true,
409
- prNumber: change.prNumber,
410
- prUrl: change.prUrl,
411
- branch: "pr",
412
- headSha: head.stdout.trim(),
413
- baseBranch: repository.defaultBranch,
414
- baseSha: base.stdout.trim(),
415
- mergeBaseSha,
416
- diffCommand: `${git} diff ${mergeBaseSha}..pr`
417
- };
418
- }
419
- });
420
- }
421
- //#endregion
422
- //#region src/eve/invoke.ts
423
- /**
424
- * A tool that lets one agent hand work to another, NMA-style: the caller
425
- * decides to invoke; trusted code owns the how. The handoff is recorded as a
426
- * factory task (single-winner dispatch, receipts), then a fresh session is
427
- * started on the target agent carrying only the task id — never the caller's
428
- * context. The session start is create-once on the task id, so a retried
429
- * tool call cannot start a second session.
430
- */
431
- function invokeAgentTool(stores, options) {
432
- const doFetch = options.fetch ?? fetch;
433
- return defineTool({
434
- description: `${options.description} Hands the work to a separate agent in a fresh session; you will not see its reasoning. Returns the handoff task id.`,
435
- inputSchema: z.object({
436
- repositoryIds: z.array(repositoryIdSchema).min(1),
437
- parentTaskId: taskIdSchema.optional().describe("Your own task, when this work continues it."),
438
- changeId: changeIdSchema.optional().describe("The change the target agent should work on."),
439
- channel: z.string().min(1).describe("Reply connector, e.g. github."),
440
- address: z.string().min(1).describe("Reply address, e.g. acme/web#41."),
441
- brief: z.string().min(1).max(4e3).describe("What the target agent needs to know. Facts and references only, not your reasoning.")
442
- }),
443
- async execute(input) {
444
- const task = await stores.tasks.create({
445
- repositoryIds: input.repositoryIds,
446
- kind: options.kind,
447
- origin: input.parentTaskId === void 0 ? { operator: "factory" } : { parentTaskId: input.parentTaskId },
448
- replyTo: {
449
- channel: input.channel,
450
- address: input.address
451
- }
452
- });
453
- const running = await dispatchTask(stores, task.id, {
454
- maxLaunchAttempts: 1,
455
- budget: options.budget?.(),
456
- launch: async (dispatched) => {
457
- const headers = {
458
- "content-type": "application/json",
459
- ...await options.headers?.(dispatched)
460
- };
461
- const token = await options.token?.();
462
- if (token !== void 0) headers.authorization = `Bearer ${token}`;
463
- const message = [
464
- `You are assigned factory task ${dispatched.id}.`,
465
- input.changeId === void 0 ? null : `Change under review: ${input.changeId}.`,
466
- `Reply address: ${input.channel} ${input.address}.`,
467
- "",
468
- input.brief,
469
- "",
470
- "Read the task with get_task first, do the work, and record the outcome with your factory tools."
471
- ].filter((line) => line !== null).join("\n");
472
- const response = await doFetch(`${options.targetUrl()}/eve/v1/session`, {
473
- method: "POST",
474
- headers,
475
- body: JSON.stringify({
476
- message,
477
- operationId: `factory-task:${dispatched.id}`
478
- })
479
- });
480
- if (!response.ok) throw new Error(`target agent refused the session: ${response.status}`);
481
- }
482
- });
483
- return {
484
- taskId: running.id,
485
- kind: running.kind,
486
- state: running.state
487
- };
488
- }
489
- });
490
- }
491
- /**
492
- * Give a conversational agent one bounded delegation surface backed by the
493
- * application's route registry. The caller selects a declared route; trusted
494
- * code owns task creation, budget enforcement, and the fresh target session.
495
- */
496
- function delegateAgentTool(stores, options) {
497
- const doFetch = options.fetch ?? fetch;
498
- const routeSummary = options.routes.routes.map((route) => `${route.id}: ${route.description}`).join("\n");
499
- return defineTool({
500
- description: "Delegate durable work to one registered specialist. Select only a listed route; the specialist runs independently and reports its result through Factory.\n" + routeSummary,
501
- inputSchema: z.object({
502
- routeId: z.string().min(1).describe("One route id listed in this tool's description."),
503
- repositoryIds: z.array(repositoryIdSchema).min(1),
504
- signalId: signalIdSchema.optional().describe("Pending external signal this delegation accepts."),
505
- parentTaskId: taskIdSchema.optional().describe("Existing task this work continues."),
506
- changeId: changeIdSchema.optional().describe("Existing change the specialist should inspect."),
507
- channel: z.string().min(1).describe("Originating conversation channel."),
508
- address: z.string().min(1).describe("Originating conversation reply address."),
509
- brief: z.string().min(1).max(4e3).describe("Facts and desired outcome, without hidden reasoning.")
510
- }),
511
- async execute(input, ctx) {
512
- const route = options.routes.get(input.routeId);
513
- if (route === void 0) throw new Error(`Unknown agent route ${input.routeId}.`);
514
- const replyTo = {
515
- channel: input.channel,
516
- address: input.address
517
- };
518
- const attributes = ctx.session.auth.initiator?.attributes;
519
- const repositoryAttribute = attributes?.factoryRepositoryIds;
520
- const boundRepositoryIds = typeof repositoryAttribute === "string" ? repositoryAttribute.split(",").filter(Boolean) : repositoryAttribute;
521
- if (boundRepositoryIds !== void 0 && (boundRepositoryIds.length !== input.repositoryIds.length || boundRepositoryIds.some((id) => !input.repositoryIds.includes(id)))) throw new Error("Delegation repositories do not match the connector-authenticated context.");
522
- if (attributes?.factoryReplyChannel !== void 0 && attributes.factoryReplyChannel !== replyTo.channel || attributes?.factoryReplyAddress !== void 0 && attributes.factoryReplyAddress !== replyTo.address) throw new Error("Delegation reply address does not match the authenticated conversation.");
523
- for (const repositoryId of input.repositoryIds) {
524
- const repository = await stores.repositories.get(repositoryId);
525
- if (repository === null || !repository.enabled) throw new Error(`Repository ${repositoryId} is not enabled in this factory.`);
526
- }
527
- if (input.signalId !== void 0) {
528
- const signal = await stores.signals.get(input.signalId);
529
- if (signal === null) throw new Error(`Signal ${input.signalId} does not exist.`);
530
- if (!input.repositoryIds.includes(signal.repositoryId) || signal.replyTo.channel !== replyTo.channel || signal.replyTo.address !== replyTo.address) throw new Error("Delegation does not match the signal's authenticated repository and reply address.");
531
- if (signal.outcome === "pending") await stores.signals.decide(signal.id, "accepted", { reason: `Foreman selected ${route.id}.` });
532
- else if (signal.outcome !== "accepted") throw new Error(`Signal ${signal.id} is already ${signal.outcome}.`);
533
- }
534
- const operator = ctx.session.auth.initiator?.principalId ?? "foreman";
535
- if (route.taskKind === "code_change" && input.repositoryIds.length > 1) {
536
- const [first, second, ...rest] = input.repositoryIds;
537
- if (first === void 0 || second === void 0) throw new Error("Coordination requires two repositories.");
538
- const coordination = await createCoordination(stores, {
539
- repositoryIds: [
540
- first,
541
- second,
542
- ...rest
543
- ],
544
- replyTo,
545
- ...input.signalId === void 0 ? {} : { dedupeKey: `route:${input.signalId}:${route.id}` },
546
- ...input.signalId === void 0 ? { operator } : { signalId: input.signalId }
547
- });
548
- await Promise.all(coordination.children.filter((child) => child.state === "queued").map((child) => dispatchRouteTask(stores, options, doFetch, route, child, input.changeId, input.brief)));
549
- return {
550
- taskId: coordination.parent.id,
551
- childTaskIds: coordination.children.map(({ id }) => id),
552
- routeId: route.id,
553
- agent: route.agent,
554
- state: coordination.parent.state
555
- };
556
- }
557
- const task = await stores.tasks.create({
558
- repositoryIds: input.repositoryIds,
559
- kind: route.taskKind,
560
- origin: input.signalId !== void 0 ? { signalId: input.signalId } : input.parentTaskId !== void 0 ? { parentTaskId: input.parentTaskId } : { operator },
561
- replyTo,
562
- changeId: input.changeId,
563
- ...input.signalId === void 0 ? {} : { dedupeKey: `route:${input.signalId}:${route.id}` }
564
- });
565
- const running = task.state === "queued" ? await dispatchRouteTask(stores, options, doFetch, route, task, input.changeId, input.brief) : task;
566
- return {
567
- taskId: running.id,
568
- routeId: route.id,
569
- agent: route.agent,
570
- state: running.state
571
- };
572
- }
573
- });
574
- }
575
- async function dispatchRouteTask(stores, options, doFetch, route, task, changeId, brief) {
576
- return dispatchTask(stores, task.id, {
577
- maxLaunchAttempts: 1,
578
- budget: options.budget?.(route),
579
- launch: async (dispatched) => {
580
- const headers = {
581
- "content-type": "application/json",
582
- ...await options.headers?.(dispatched, route)
583
- };
584
- const token = await options.token?.(route);
585
- if (token !== void 0) headers.authorization = `Bearer ${token}`;
586
- const message = [
587
- `You are assigned factory task ${dispatched.id} through route ${route.id}.`,
588
- changeId === void 0 ? null : `Change under review: ${changeId}.`,
589
- brief,
590
- "Read the task first and return exactly one bounded Factory outcome."
591
- ].filter((line) => line !== null).join("\n\n");
592
- const response = await doFetch(`${options.targetUrl(route)}/eve/v1/session`, {
593
- method: "POST",
594
- headers,
595
- body: JSON.stringify({
596
- message,
597
- operationId: `factory-task:${dispatched.id}`
598
- })
599
- });
600
- if (!response.ok) throw new Error(`${route.agent} refused the session: ${response.status}`);
601
- }
602
- });
603
- }
604
- //#endregion
605
- //#region src/eve/post-review.ts
606
- const reviewCommentSchema = z.strictObject({
607
- key: z.string().min(1).max(80).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).optional().describe("Stable kebab-case identity for this defect and cause; keep it unchanged across reruns."),
608
- title: z.string().min(1).max(200).optional().describe("Short finding title."),
609
- path: z.string().min(1).max(500).describe("Repository-relative file path."),
610
- line: z.number().int().min(1).describe("Line in the pull request's new version."),
611
- body: z.string().min(1).max(5e3).describe("Markdown explaining the finding and a concrete fix.")
612
- });
613
- const reviewCommentsSchema = z.array(reviewCommentSchema).max(50).default([]).superRefine((comments, context) => {
614
- const seen = /* @__PURE__ */ new Set();
615
- comments.forEach((comment, index) => {
616
- if (comment.key === void 0) return;
617
- if (seen.has(comment.key)) context.addIssue({
618
- code: "custom",
619
- message: `duplicate finding key: ${comment.key}`,
620
- path: [index, "key"]
621
- });
622
- seen.add(comment.key);
623
- });
624
- });
625
- /**
626
- * Publish an independent review of an existing pull request and finish the
627
- * review task without changing the pull request's factory lifecycle.
628
- */
629
- function postReviewTool(stores, options) {
630
- return defineTool({
631
- description: "Record a completed code review and finish your code_review task. Results may be reported through completion callbacks instead of a GitHub review; use request_changes only for blocking findings.",
632
- inputSchema: z.object({
633
- taskId: taskIdSchema.describe("Your code_review task."),
634
- changeId: changeIdSchema.describe("The pull request change from your starting message."),
635
- verdict: z.enum([
636
- "approve",
637
- "request_changes",
638
- "comment"
639
- ]),
640
- headSha: z.string().regex(/^[0-9a-f]{40}$/).describe("Commit returned by fetch_pull_request."),
641
- summary: z.string().min(1).max(5e3).describe("Markdown summary of what you reviewed and found."),
642
- comments: reviewCommentsSchema
643
- }),
644
- async execute({ taskId, changeId, verdict, headSha, summary, comments }) {
645
- const task = await stores.tasks.get(taskId);
646
- if (task === null || task.kind !== "code_review") return {
647
- recorded: false,
648
- reason: `${taskId} is not a code_review task`
649
- };
650
- if (task.state !== "running") return {
651
- recorded: false,
652
- reason: `task is ${task.state}, not running`
653
- };
654
- const change = await stores.changes.get(changeId);
655
- if (change === null) return {
656
- recorded: false,
657
- reason: `change ${changeId} does not exist`
658
- };
659
- if (change.state !== "verifying" && change.state !== "ready") return {
660
- recorded: false,
661
- reason: `change is ${change.state}, not open for review`
662
- };
663
- const repository = await stores.repositories.get(change.repositoryId);
664
- if (repository === null) return {
665
- recorded: false,
666
- reason: `repository ${change.repositoryId} does not exist`
667
- };
668
- const token = await options.tokenForRepository(repository.slug);
669
- const completedComments = comments.map((comment) => {
670
- const key = comment.key ?? legacyFindingKey(comment);
671
- return {
672
- ...comment,
673
- key,
674
- title: comment.title ?? "Review finding",
675
- fingerprint: createHash("sha256").update(`${repository.slug.toLowerCase()}#${change.prNumber}:${key}`).digest("hex")
676
- };
677
- });
678
- const completed = {
679
- taskId,
680
- changeId,
681
- repository: repository.slug,
682
- pullRequestNumber: change.prNumber,
683
- headSha,
684
- verdict,
685
- summary,
686
- comments: completedComments
687
- };
688
- const publish = options.publishReviews !== false;
689
- let review;
690
- if (publish) {
691
- review = await submitPullRequestReview({
692
- repository: repository.slug,
693
- token,
694
- fetch: options.fetch,
695
- pullRequestNumber: change.prNumber,
696
- commitId: headSha,
697
- event: verdict === "approve" ? "APPROVE" : verdict === "request_changes" ? "REQUEST_CHANGES" : "COMMENT",
698
- body: summary,
699
- comments: completedComments
700
- });
701
- await options.onPublished?.({
702
- ...completed,
703
- review
704
- });
705
- } else {
706
- const head = await readPullRequestHead({
707
- repository: repository.slug,
708
- token,
709
- fetch: options.fetch,
710
- pullRequestNumber: change.prNumber
711
- });
712
- if (head.sha !== headSha) throw new Error(`pull request changed after review: expected ${headSha}, found ${head.sha}`);
713
- }
714
- await options.onCompleted?.(completed);
715
- await stores.tasks.transition(taskId, "verifying", { reason: summary });
716
- const finished = await stores.tasks.transition(taskId, "succeeded");
717
- return {
718
- recorded: true,
719
- verdict,
720
- published: review !== void 0,
721
- ...review === void 0 ? {} : { review },
722
- taskState: finished.state
723
- };
724
- }
725
- });
726
- }
727
- function legacyFindingKey(comment) {
728
- return `legacy-${createHash("sha256").update(`${comment.path}:${comment.line}:${comment.body}`).digest("hex").slice(0, 24)}`;
729
- }
730
- //#endregion
731
- //#region src/eve/review.ts
732
- function reviewCommentTools(stores, options) {
733
- const repoPath = options.repoPath ?? "repo";
734
- const commentInputSchema = z.object({
735
- changeId: changeIdSchema.describe("The change under review, from your starting message."),
736
- commentId: z.number().int().positive().describe("The GitHub review comment id.")
737
- });
738
- return {
739
- read_review_comment: defineTool({
740
- description: "Read an inline review comment on a change under verification or ready for human review. By default this refuses to return comments from people without write access to the repository.",
741
- inputSchema: commentInputSchema,
742
- async execute({ changeId, commentId }) {
743
- const change = await stores.changes.get(changeId);
744
- if (change === null) throw new Error(`change ${changeId} does not exist`);
745
- if (change.state !== "verifying" && change.state !== "ready") throw new Error(`change is ${change.state}, not open for review`);
746
- const repository = await stores.repositories.get(change.repositoryId);
747
- if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);
748
- return readReviewComment({
749
- repository: repository.slug,
750
- token: await options.tokenForRepository(repository.slug),
751
- fetch: options.fetch,
752
- commentId
753
- });
754
- }
755
- }),
756
- answer_review_comment: defineTool({
757
- description: "Reply to an inline review comment on a change under verification or ready for human review. Use for findings and low-confidence responses, not for a concrete medium- or high-confidence fix.",
758
- inputSchema: commentInputSchema.extend({ body: z.string().min(1).max(5e3).describe("The Markdown reply to post.") }),
759
- async execute({ changeId, commentId, body }) {
760
- const change = await stores.changes.get(changeId);
761
- if (change === null) throw new Error(`change ${changeId} does not exist`);
762
- if (change.state !== "verifying" && change.state !== "ready") throw new Error(`change is ${change.state}, not open for review`);
763
- const repository = await stores.repositories.get(change.repositoryId);
764
- if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);
765
- return answerReviewComment({
766
- repository: repository.slug,
767
- token: await options.tokenForRepository(repository.slug),
768
- fetch: options.fetch,
769
- pullRequestNumber: change.prNumber,
770
- commentId,
771
- body
772
- });
773
- }
774
- }),
775
- suggest_review_fix: defineTool({
776
- description: "Post a concrete, apply-able GitHub suggested change for a medium-confidence fix. The replacement must cover exactly the lines attached to the inline review comment.",
777
- inputSchema: commentInputSchema.extend({
778
- confidence: z.literal("medium"),
779
- replacement: z.string().min(1).max(5e3).describe("Exact replacement text for the commented lines."),
780
- summary: z.string().min(1).max(1e3).describe("A brief explanation of the suggested fix.")
781
- }),
782
- async execute({ changeId, commentId, replacement, summary }) {
783
- const change = await stores.changes.get(changeId);
784
- if (change === null) throw new Error(`change ${changeId} does not exist`);
785
- if (change.state !== "verifying" && change.state !== "ready") throw new Error(`change is ${change.state}, not open for review`);
786
- const repository = await stores.repositories.get(change.repositoryId);
787
- if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);
788
- return answerReviewComment({
789
- repository: repository.slug,
790
- token: await options.tokenForRepository(repository.slug),
791
- fetch: options.fetch,
792
- pullRequestNumber: change.prNumber,
793
- commentId,
794
- body: `${summary}\n\n\`\`\`suggestion\n${replacement}\n\`\`\``
795
- });
796
- }
797
- }),
798
- apply_review_fix: defineTool({
799
- description: "Publish a tested, committed high-confidence fix to the existing same-repository pull request branch. Fails if the checkout is dirty, the PR changed, or the PR comes from a fork.",
800
- inputSchema: commentInputSchema.extend({
801
- confidence: z.literal("high"),
802
- summary: z.string().min(1).max(1e3).describe("What was fixed and verified.")
803
- }),
804
- async execute({ changeId, commentId, summary }, ctx) {
805
- const change = await stores.changes.get(changeId);
806
- if (change === null) throw new Error(`change ${changeId} does not exist`);
807
- if (change.state !== "verifying" && change.state !== "ready") throw new Error(`change is ${change.state}, not open for review`);
808
- const repository = await stores.repositories.get(change.repositoryId);
809
- if (repository === null) throw new Error(`repository ${change.repositoryId} does not exist`);
810
- if (options.withCredential === void 0) throw new Error("applying review fixes is not configured");
811
- const token = await options.tokenForRepository(repository.slug);
812
- await readReviewComment({
813
- repository: repository.slug,
814
- token,
815
- fetch: options.fetch,
816
- commentId
817
- });
818
- const head = await readPullRequestHead({
819
- repository: repository.slug,
820
- token,
821
- fetch: options.fetch,
822
- pullRequestNumber: change.prNumber
823
- });
824
- if (head.repository !== repository.slug.toLowerCase()) throw new Error("cannot apply a fix to a pull request from a fork");
825
- const sandbox = await ctx.getSandbox();
826
- const git = `git -C ${repoPath}`;
827
- if ((await sandbox.run({ command: `${git} status --porcelain` })).stdout.trim() !== "") throw new Error("commit the review fix before publishing");
828
- if ((await sandbox.run({ command: `${git} merge-base --is-ancestor ${head.sha} HEAD` })).exitCode !== 0) throw new Error("pull request changed after it was fetched; fetch it again before applying the fix");
829
- if ((await sandbox.run({ command: `${git} rev-parse HEAD` })).stdout.trim() === head.sha) throw new Error("no committed review fix to publish");
830
- const push = await options.withCredential(sandbox, repository.slug, `${git} push --force-with-lease=refs/heads/${head.branch}:${head.sha} origin HEAD:refs/heads/${head.branch}`);
831
- if (typeof push.exitCode === "number" && push.exitCode !== 0) throw new Error(`could not update pull request branch: ${(push.stderr ?? "").trim()}`);
832
- const reply = await answerReviewComment({
833
- repository: repository.slug,
834
- token,
835
- fetch: options.fetch,
836
- pullRequestNumber: change.prNumber,
837
- commentId,
838
- body: summary
839
- });
840
- return {
841
- updated: true,
842
- prNumber: change.prNumber,
843
- prUrl: change.prUrl,
844
- reply
845
- };
846
- }
847
- })
848
- };
849
- }
850
- //#endregion
851
- //#region src/eve/verification.ts
852
- /**
853
- * The verifier's outcome tool. Writes evidence onto the change and moves it
854
- * to ready only when the verdict is pass; a failed verdict leaves the change
855
- * verifying with the evidence recorded, and the verification task itself
856
- * ends with a receipt either way. The change's own code_change task follows
857
- * the verdict too: succeeded on pass, failed on fail with the verifier's
858
- * summary as the reason, so the ledger never shows a verified-and-rejected fix
859
- * as still in progress. Fail closed: the agent cannot mark a change ready
860
- * without supplying every evidence field.
861
- */
862
- function recordVerificationTool(stores, options = {}) {
863
- return defineTool({
864
- description: "Record the outcome of a verification task: the evidence you gathered and whether the change passed. Pass moves the change to ready for human review; fail keeps it out of review.",
865
- inputSchema: z.object({
866
- taskId: taskIdSchema.describe("Your verification task."),
867
- changeId: changeIdSchema.describe("The change you verified."),
868
- verdict: z.enum(["pass", "fail"]),
869
- evidence: changeEvidenceSchema,
870
- confidence: levelSchema.describe("How certain you are in the verdict."),
871
- summary: z.string().min(1).max(2e3).describe("What you checked and what you found.")
872
- }),
873
- async execute({ taskId, changeId, verdict, evidence, confidence, summary }) {
874
- const change = await stores.changes.get(changeId);
875
- if (change === null) return {
876
- recorded: false,
877
- reason: `change ${changeId} does not exist`
878
- };
879
- if (change.state !== "verifying") return {
880
- recorded: false,
881
- reason: `change is ${change.state}, not verifying; nothing to record`
882
- };
883
- const task = await stores.tasks.get(taskId);
884
- if (task === null || task.kind !== "verification") return {
885
- recorded: false,
886
- reason: `${taskId} is not a verification task`
887
- };
888
- let updatedChange = change;
889
- if (verdict === "pass") updatedChange = await stores.changes.transition(changeId, "ready", {
890
- patch: {
891
- evidence,
892
- confidence
893
- },
894
- reason: summary
895
- });
896
- let finished;
897
- if (verdict === "pass") {
898
- await stores.tasks.transition(taskId, "verifying", { reason: summary });
899
- finished = await stores.tasks.transition(taskId, "succeeded");
900
- } else finished = await stores.tasks.transition(taskId, "failed", { reason: summary });
901
- if (change.taskId !== void 0) {
902
- if ((await stores.tasks.get(change.taskId))?.state === "verifying") await stores.tasks.transition(change.taskId, verdict === "pass" ? "succeeded" : "failed", verdict === "pass" ? {} : { reason: `verification failed: ${summary}` }).catch(() => void 0);
903
- }
904
- await options.presentResult?.({
905
- taskId,
906
- changeId,
907
- verdict,
908
- summary
909
- });
910
- return {
911
- recorded: true,
912
- verdict,
913
- changeState: updatedChange.state,
914
- taskState: finished.state
915
- };
916
- }
917
- });
918
- }
919
- //#endregion
920
13
  //#region src/eve/index.ts
921
14
  const decidedOutcomeSchema = z.enum([
922
15
  "accepted",
@@ -925,43 +18,62 @@ const decidedOutcomeSchema = z.enum([
925
18
  "low_confidence",
926
19
  "ignored"
927
20
  ]);
928
- const recordChangeInputSchema = z.object({
929
- taskId: taskIdSchema,
930
- repositoryId: repositoryIdSchema,
931
- prNumber: z.number().int().min(1),
932
- prUrl: z.url(),
933
- risk: levelSchema.describe("Blast radius of the change if it is wrong."),
934
- confidence: levelSchema.describe("How certain you are the change is correct."),
935
- summary: z.string().min(1).describe("One-sentence description of the change.")
936
- });
937
21
  async function createAndPresentQuestion(stores, parent, question, presentQuestion) {
22
+ const needsHumanAction = question.text.trim();
23
+ if (needsHumanAction === "") throw new Error("A human question must contain non-blank text.");
938
24
  const task = await stores.tasks.create({
939
25
  repositoryIds: parent.repositoryIds,
940
26
  kind: "question",
941
- origin: { parentTaskId: parent.id },
27
+ work: taskWork({
28
+ title: needsHumanAction.slice(0, 256),
29
+ input: { question }
30
+ }),
31
+ parentTaskId: parent.id,
32
+ parentTaskAttempt: parent.attempt,
33
+ origin: {},
942
34
  replyTo: parent.replyTo,
943
35
  question
944
36
  });
945
- const waiting = await stores.tasks.transition(task.id, "needs_human");
946
37
  try {
947
- if (parent.state === "running") await stores.tasks.transition(parent.id, "needs_human", { reason: `waiting for answer to question ${waiting.id}` });
38
+ const waiting = await stores.tasks.transition(task.id, "needs_human", { needsHumanAction });
39
+ if (parent.state === "running") await stores.tasks.transition(parent.id, "needs_human", {
40
+ expectFrom: "running",
41
+ expectAttempt: parent.attempt,
42
+ reason: `waiting for answer to question ${waiting.id}`,
43
+ questionTaskId: waiting.id,
44
+ needsHumanAction
45
+ });
948
46
  await presentQuestion(waiting);
47
+ return waiting;
949
48
  } catch (error) {
950
- if ((await stores.tasks.get(parent.id))?.state === "needs_human") await stores.tasks.transition(parent.id, "queued", { reason: `delivery of question ${waiting.id} failed` });
951
- if ((await stores.tasks.get(waiting.id))?.state === "needs_human") await stores.tasks.transition(waiting.id, "cancelled", { reason: "question delivery failed" });
49
+ const currentParent = await stores.tasks.get(parent.id);
50
+ if (currentParent?.state === "needs_human" && currentParent.attempt === parent.attempt && currentParent.questionTaskId === task.id) try {
51
+ await stores.tasks.transition(parent.id, "queued", {
52
+ expectFrom: "needs_human",
53
+ expectAttempt: currentParent.attempt,
54
+ expectQuestionTaskId: task.id,
55
+ reason: `delivery of question ${task.id} failed`
56
+ });
57
+ } catch (cleanupError) {
58
+ const latest = await stores.tasks.get(parent.id);
59
+ if (latest?.state === "needs_human" && latest.attempt === currentParent.attempt && latest.questionTaskId === task.id) throw cleanupError;
60
+ }
61
+ const currentQuestion = await stores.tasks.get(task.id);
62
+ if (currentQuestion?.state === "needs_human" || currentQuestion?.state === "queued") await stores.tasks.transition(task.id, "cancelled", {
63
+ expectFrom: currentQuestion.state,
64
+ expectAttempt: currentQuestion.attempt,
65
+ reason: "question delivery failed"
66
+ });
952
67
  throw error;
953
68
  }
954
- return waiting;
955
69
  }
956
70
  /**
957
- * The factory's store operations wrapped as eve tools. Expose a tool to an
71
+ * The factory's provider-neutral store operations wrapped as Eve tools. Expose a tool to an
958
72
  * agent by re-exporting it from a file under agent/tools/, e.g.
959
- * `export default factoryTools(stores).get_task;`. Every write goes through
73
+ * `export default createTaskTools(stores).get_task;`. Every write goes through
960
74
  * the engine, so agents inherit transition legality and receipts.
961
75
  */
962
- function factoryTools(stores, options = {}) {
963
- const recordChangeGate = options.recordChangeGate;
964
- const verification = options.verification ?? "required";
76
+ function createTaskTools(stores, options = {}) {
965
77
  return {
966
78
  get_task: defineTool({
967
79
  description: "Read one factory task by id: its kind, state, repositories, origin, and results.",
@@ -982,105 +94,45 @@ function factoryTools(stores, options = {}) {
982
94
  detail: z.string().min(1).optional().describe("Severity if accepted, or the duplicate-of signal id.")
983
95
  }),
984
96
  execute({ signalId, outcome, reason, detail }) {
985
- return stores.signals.decide(signalId, outcome, {
97
+ return stores.signals.decide(signalId, {
98
+ outcome,
986
99
  reason,
987
100
  detail
988
101
  });
989
102
  }
990
103
  }),
991
- record_change: defineTool({
992
- description: verification === "required" ? "Record the pull request produced for a code_change task. Creates the change, links it to the task, and moves the task to verifying." : "Record the pull request produced for a code_change task. Creates the change and marks it ready for human review without independent verification.",
993
- inputSchema: recordChangeInputSchema,
994
- ...recordChangeGate === void 0 ? {} : { approval: async ({ toolInput }) => {
995
- const parsed = recordChangeInputSchema.safeParse(toolInput);
996
- if (!parsed.success) return {
997
- type: "denied",
998
- reason: "record_change input is malformed; fix the arguments and retry"
999
- };
1000
- const verdict = await recordChangeGate(parsed.data);
1001
- return verdict.ok ? "not-applicable" : {
1002
- type: "denied",
1003
- reason: verdict.reason
1004
- };
1005
- } },
1006
- async execute({ taskId, repositoryId, prNumber, prUrl, risk, confidence, summary }) {
1007
- const currentTask = await stores.tasks.get(taskId);
1008
- if (currentTask === null) throw new Error(`task ${taskId} does not exist`);
1009
- if (currentTask.state !== "running" && currentTask.state !== "verifying" && currentTask.state !== "succeeded") throw new Error(`task ${taskId} is ${currentTask.state}, not running`);
1010
- const linkedChange = currentTask.changeId === void 0 ? void 0 : await stores.changes.get(currentTask.changeId);
1011
- if (currentTask.changeId !== void 0 && linkedChange === null) throw new Error(`change ${currentTask.changeId} does not exist`);
1012
- let change = linkedChange ?? (await stores.changes.list()).find((candidate) => candidate.taskId === taskId);
1013
- if (change === void 0) {
1014
- if (currentTask.state !== "running") throw new Error(`task ${taskId} has no recorded change`);
1015
- change = await stores.changes.create({
1016
- repositoryId,
1017
- taskId,
1018
- prNumber,
1019
- prUrl,
1020
- author: "factory",
1021
- risk,
1022
- confidence,
1023
- evidence: {
1024
- reproVerified: false,
1025
- testsAdded: 0,
1026
- checksGreen: false,
1027
- attackPassed: false,
1028
- scopeMatches: false
1029
- }
1030
- });
1031
- }
1032
- if (currentTask.state === "running") await options.presentChange?.({
1033
- taskId,
1034
- changeId: change.id,
1035
- verification,
1036
- summary
1037
- });
1038
- let task = currentTask;
1039
- if (task.state === "running") task = await stores.tasks.transition(taskId, "verifying", {
1040
- patch: { changeId: change.id },
1041
- reason: summary
1042
- });
1043
- if (verification === "required") return {
1044
- change,
1045
- task
1046
- };
1047
- if (change.state === "verifying") change = await stores.changes.transition(change.id, "ready", { reason: "independent verification is not configured" });
1048
- if (task.state === "verifying") task = await stores.tasks.transition(taskId, "succeeded", { reason: "change recorded for human review without independent verification" });
1049
- return {
1050
- change,
1051
- task
1052
- };
1053
- }
1054
- }),
1055
104
  finish_task: defineTool({
1056
- description: "Mark your task finished with a summary, for task kinds that have no other outcome tool (for example a security_scan). Not for code_change or verification tasks: those end with record_change and record_verification.",
105
+ description: "Mark your running task finished with a summary. The configured workflow policy may require a more specific outcome tool.",
1057
106
  inputSchema: z.object({
1058
107
  taskId: taskIdSchema,
1059
108
  summary: z.string().min(1).max(4e3).describe("What you did and found, for the ledger.")
1060
109
  }),
1061
- async execute({ taskId, summary }) {
1062
- const task = await stores.tasks.get(taskId);
1063
- if (task === null) return {
1064
- finished: false,
1065
- reason: `${taskId} does not exist`
1066
- };
1067
- if (task.kind === "code_change" || task.kind === "verification") return {
110
+ async execute({ taskId, summary }, ctx) {
111
+ const task = await requireTaskExecution(stores, ctx, taskId);
112
+ const refusal = await options.finishTaskPolicy?.(task);
113
+ if (refusal !== void 0 && refusal !== null) return {
1068
114
  finished: false,
1069
- reason: `${task.kind} tasks end with their own outcome tool`
115
+ reason: refusal
1070
116
  };
1071
117
  if (task.state !== "running") return {
1072
118
  finished: false,
1073
119
  reason: `task is ${task.state}, not running`
1074
120
  };
1075
- await stores.tasks.transition(taskId, "verifying", { reason: summary });
121
+ await stores.tasks.transition(taskId, "succeeded", {
122
+ expectFrom: "running",
123
+ expectAttempt: task.attempt,
124
+ expectExecution: task.execution,
125
+ reason: summary,
126
+ output: { summary }
127
+ });
1076
128
  return {
1077
129
  finished: true,
1078
- taskState: (await stores.tasks.transition(taskId, "succeeded", { reason: summary })).state
130
+ taskState: "succeeded"
1079
131
  };
1080
132
  }
1081
133
  }),
1082
134
  request_human_input: defineTool({
1083
- description: "Request human input or action and pause your task until the human replies. The parent task determines the repositories and reply destination.",
135
+ description: "Request one human input or action and pause your currently running task until the human replies. A paused task cannot request another question; wait for the answer and replacement execution. The parent task determines the repositories and reply destination. Name any suggested reply in question.closingOptions when that exact answer means no further attempt can help (for example \"nothing to do, close it\"); Factory resolves the task instead of requeuing an identical retry when the human picks one.",
1084
136
  inputSchema: z.object({
1085
137
  parentTaskId: taskIdSchema.describe("Your running task, which the answer will unblock."),
1086
138
  question: taskQuestionSchema.omit({
@@ -1088,58 +140,40 @@ function factoryTools(stores, options = {}) {
1088
140
  answeredBy: true
1089
141
  })
1090
142
  }),
1091
- async execute({ parentTaskId, question }) {
143
+ async execute({ parentTaskId, question }, ctx) {
1092
144
  if (options.presentQuestion === void 0) throw new Error("request_human_input requires a configured question presenter.");
1093
- const parent = await stores.tasks.get(parentTaskId);
1094
- if (parent === null) throw new Error(`Parent task ${parentTaskId} does not exist.`);
1095
- if (parent.state !== "running" && parent.state !== "needs_human") throw new Error(`Parent task ${parentTaskId} is ${parent.state}, not running.`);
1096
- return createAndPresentQuestion(stores, parent, question, options.presentQuestion);
145
+ return createAndPresentQuestion(stores, await requireTaskExecution(stores, ctx, parentTaskId), question, options.presentQuestion);
1097
146
  }
1098
147
  }),
1099
148
  answer_question: defineTool({
1100
- description: "Record the authenticated user's answer to a waiting question and requeue the parent specialist task.",
149
+ description: "Record the authenticated user's answer to a waiting question and requeue the parent specialist task, unless the answer matches one of the question's closingOptions, which resolves the parent task instead. A blocked parent task id is also accepted and resolves its persisted QuestionTask id.",
1101
150
  inputSchema: z.object({
1102
151
  questionTaskId: taskIdSchema,
1103
152
  answer: z.string().min(1).max(4e3)
1104
153
  }),
1105
154
  async execute({ questionTaskId, answer }, ctx) {
1106
- const questionTask = await stores.tasks.get(questionTaskId);
1107
- if (questionTask === null || questionTask.kind !== "question" || questionTask.state !== "needs_human" || questionTask.question === void 0) throw new Error(`Question task ${questionTaskId} is not waiting for an answer.`);
1108
- const attributes = ctx.session.auth.initiator?.attributes;
1109
- if (attributes?.factoryReplyChannel !== questionTask.replyTo.channel || attributes.factoryReplyAddress !== questionTask.replyTo.address) throw new Error("Question reply does not match the authenticated conversation.");
1110
- const repositoryAttribute = attributes.factoryRepositoryIds;
1111
- const boundRepositoryIds = typeof repositoryAttribute === "string" ? repositoryAttribute.split(",").filter(Boolean) : repositoryAttribute;
1112
- if (boundRepositoryIds === void 0 || boundRepositoryIds.length !== questionTask.repositoryIds.length || boundRepositoryIds.some((id) => !questionTask.repositoryIds.includes(id))) throw new Error("Question repositories do not match the authenticated conversation.");
1113
- const answeredBy = ctx.session.auth.initiator?.principalId ?? "operator";
1114
- const answered = await stores.tasks.transition(questionTask.id, "succeeded", {
1115
- patch: { question: {
1116
- ...questionTask.question,
1117
- answer,
1118
- answeredBy
1119
- } },
1120
- reason: "question answered through Foreman"
155
+ const requestedTask = await stores.tasks.get(questionTaskId);
156
+ const resolvedQuestionTaskId = requestedTask?.kind === "question" ? requestedTask.id : requestedTask?.questionTaskId;
157
+ const questionTask = resolvedQuestionTaskId === void 0 ? null : await stores.tasks.get(resolvedQuestionTaskId);
158
+ if (questionTask === null || questionTask.kind !== "question" || questionTask.question === void 0) throw new Error(`Question task ${questionTaskId} does not exist.`);
159
+ const { initiator, current } = ctx.session.auth;
160
+ if (!initiator || !current || [initiator, current].some(({ attributes }) => attributes.factoryReplyChannel !== questionTask.replyTo.channel || attributes.factoryReplyAddress !== questionTask.replyTo.address)) throw new Error("Question reply does not match the authenticated conversation.");
161
+ const answeredBy = current.principalId;
162
+ return stores.tasks.answerQuestion({
163
+ questionTaskId: questionTask.id,
164
+ answer,
165
+ answeredBy
1121
166
  });
1122
- const parentTaskId = questionTask.origin.parentTaskId;
1123
- if (parentTaskId === void 0) return {
1124
- questionTask: answered,
1125
- parentTask: null
1126
- };
1127
- const parent = await stores.tasks.get(parentTaskId);
1128
- if (parent === null) throw new Error(`Parent task ${parentTaskId} does not exist.`);
1129
- return {
1130
- questionTask: answered,
1131
- parentTask: parent.state === "needs_human" ? await stores.tasks.transition(parent.id, "queued", { reason: `question ${questionTask.id} answered by ${answeredBy}` }) : parent
1132
- };
1133
167
  }
1134
168
  }),
1135
169
  append_receipt: defineTool({
1136
170
  description: "Append one immutable audit receipt for an event worth remembering. Receipts can never be edited or deleted.",
1137
171
  inputSchema: z.object({
1138
- repositoryIds: z.array(repositoryIdSchema).min(1),
172
+ repositoryIds: repositoryIdsSchema,
1139
173
  taskId: taskIdSchema.optional(),
1140
174
  changeId: changeIdSchema.optional(),
1141
- kind: vocabularySchema.describe("What the receipt is about, e.g. investigation."),
1142
- state: vocabularySchema.describe("What happened, e.g. flag_ramped."),
175
+ kind: receiptKindSchema.describe("What the receipt is about, e.g. investigation."),
176
+ state: receiptStateSchema.describe("What happened, e.g. flag_ramped."),
1143
177
  reason: z.string().min(1).max(2e3).optional(),
1144
178
  dedupeKey: z.string().min(1).optional().describe("Same key twice records one receipt instead of two.")
1145
179
  }),
@@ -1149,62 +183,209 @@ function factoryTools(stores, options = {}) {
1149
183
  })
1150
184
  };
1151
185
  }
186
+ function materializationInput(ctx) {
187
+ return {
188
+ agent: ctx.agent.name,
189
+ execution: {
190
+ provider: "eve",
191
+ sessionId: ctx.session.id
192
+ },
193
+ attributes: ctx.session.auth.initiator?.attributes ?? {}
194
+ };
195
+ }
196
+ /** Observe-only hook for agents that do not use the Factory task-lifecycle hook. */
197
+ function createTranscriptSnapshotHook(materialize) {
198
+ const snapshot = (_event, ctx) => materialize(materializationInput(ctx)).catch(() => void 0);
199
+ return defineHook({ events: {
200
+ "session.waiting": snapshot,
201
+ "session.completed": snapshot,
202
+ "session.failed": snapshot
203
+ } });
204
+ }
1152
205
  const terminalTaskStates = /* @__PURE__ */ new Set([
1153
206
  "succeeded",
1154
207
  "failed",
1155
208
  "cancelled"
1156
209
  ]);
1157
210
  /**
211
+ * The turn contract's escalation question: a specialist turn ended cleanly
212
+ * (eve durably recorded `turn.completed`) but the bound task is still
213
+ * `running`, so no transition was recorded. That is never a "worker died
214
+ * mid-turn" situation -- eve confirms the turn finished -- so retrying the
215
+ * identical brief cannot succeed any differently. Escalating straight to
216
+ * `needs_human` instead of waiting for the stall window (up to 45 minutes,
217
+ * times `maxAttempts`) surfaces the dead end immediately. "Close the task"
218
+ * is a declared closingOptions entry: answering with it resolves the task
219
+ * instead of requeuing an identical retry.
220
+ */
221
+ const UNRESOLVED_TURN_QUESTION = {
222
+ text: "The specialist ended its turn without recording a result for this task. Reply to retry it, or close it if the work no longer applies (for example, a newer attempt already superseded it).",
223
+ options: ["Retry the task", "Close the task"],
224
+ closingOptions: ["Close the task"]
225
+ };
226
+ /**
1158
227
  * Observe-only eve hooks that keep the ledger honest about session outcomes.
1159
228
  * Mount by re-exporting from agent/hooks/, e.g.
1160
- * `export default factoryHooks(stores, { presentQuestion }).factory;`.
229
+ * `export default createFactoryHooks(stores, { presentQuestion }).factory;`.
1161
230
  *
1162
231
  * step.completed: records the step's tokens and AI Gateway cost on the bound
1163
232
  * task. Delivery is at least once; recordUsage dedupes by (turnId, stepIndex).
1164
233
  *
234
+ * turn.failed/session.failed: immediately re-queues the current attempt, or
235
+ * fails it when its configured attempts are exhausted. turn.cancelled marks
236
+ * the current Task cancelled. Late events from prior attempts are ignored.
237
+ *
1165
238
  * turn.completed: settles the bound task's recorded usage if the task is
1166
- * already terminal (the sweep handles tasks that end later), then moves any
1167
- * still-running task at this session's reply address behind a surfaced human
1168
- * question, because the agent finished talking without recording an outcome.
239
+ * already terminal, and enforces the turn contract otherwise: a still-running
240
+ * bound task (or a still-running task at this session's reply address, for
241
+ * conversational continuations that never got their own bound session)
242
+ * escalates immediately to a surfaced human question instead of waiting out
243
+ * the stall window, because the agent finished without recording an outcome.
1169
244
  *
1170
245
  * Every store call is swallowed: a hook throw fails the turn.
246
+ * Transcript projection writes at session response boundaries are likewise
247
+ * best-effort; the API can rebuild a missing projection from durable events.
1171
248
  */
1172
- function factoryHooks(stores, options) {
249
+ function createFactoryHooks(stores, options) {
1173
250
  const taskIdAttribute = options.taskIdAttribute ?? "factoryTaskId";
251
+ const taskAttemptAttribute = options.taskAttemptAttribute ?? "factoryTaskAttempt";
252
+ const maxAttempts = z.number().int().min(1).parse(options.maxAttempts ?? 3);
1174
253
  function boundTaskId(ctx) {
1175
254
  const parsed = taskIdSchema.safeParse(ctx.session.auth.initiator?.attributes[taskIdAttribute]);
1176
255
  return parsed.success ? parsed.data : void 0;
1177
256
  }
257
+ function boundExecution(ctx) {
258
+ const attributes = ctx.session.auth.initiator?.attributes;
259
+ const taskId = boundTaskId(ctx);
260
+ const attempt = z.coerce.number().int().min(1).safeParse(attributes?.[taskAttemptAttribute]);
261
+ return taskId !== void 0 && attempt.success ? {
262
+ taskId,
263
+ attempt: attempt.data
264
+ } : void 0;
265
+ }
266
+ async function recoverFailedAttempt(binding, failure) {
267
+ const task = await stores.tasks.get(binding.taskId);
268
+ if (task?.state !== "running" || task.attempt !== binding.attempt) return;
269
+ const exhausted = task.attempt >= maxAttempts;
270
+ await stores.tasks.transition(task.id, exhausted ? "failed" : "queued", {
271
+ expectFrom: "running",
272
+ expectAttempt: binding.attempt,
273
+ phase: "retry",
274
+ reason: exhausted ? `${failure} on attempt ${task.attempt} of ${maxAttempts}; attempts exhausted` : `${failure} on attempt ${task.attempt} of ${maxAttempts}; replacement queued`
275
+ });
276
+ }
277
+ async function cancelAttempt(binding, reason) {
278
+ const task = await stores.tasks.get(binding.taskId);
279
+ if (task?.state !== "running" || task.attempt !== binding.attempt) return;
280
+ await stores.tasks.transition(task.id, "cancelled", {
281
+ expectFrom: "running",
282
+ expectAttempt: binding.attempt,
283
+ phase: "execution",
284
+ reason
285
+ });
286
+ }
287
+ async function isConversation(task) {
288
+ try {
289
+ return await options.isConversation?.(task) ?? false;
290
+ } catch {
291
+ return false;
292
+ }
293
+ }
1178
294
  async function settleIfTerminal(taskId) {
1179
295
  const task = await stores.tasks.get(taskId);
1180
296
  if (task?.usage === void 0 || task.settledUsd !== void 0 || !terminalTaskStates.has(task.state)) return;
1181
- await stores.tasks.settle(task.id, { totalUsd: task.usage.costUsd }, { reason: "measured usage settled at turn end" });
297
+ await stores.tasks.settle(task.id, {
298
+ cost: { totalUsd: task.usage.costUsd },
299
+ reason: "measured usage settled at turn end"
300
+ });
301
+ }
302
+ async function escalateUnresolvedTurn(task) {
303
+ await createAndPresentQuestion(stores, task, UNRESOLVED_TURN_QUESTION, options.presentQuestion).catch(() => void 0);
1182
304
  }
1183
305
  return { factory: defineHook({ events: {
1184
306
  async "step.completed"(event, ctx) {
1185
307
  const taskId = boundTaskId(ctx);
1186
308
  const usage = event.data.usage;
1187
309
  if (taskId === void 0 || usage === void 0) return;
1188
- await stores.tasks.recordUsage(taskId, {
310
+ const binding = boundExecution(ctx);
311
+ if (binding !== void 0) {
312
+ if ((await stores.tasks.get(taskId).catch(() => null))?.attempt !== binding.attempt) return;
313
+ }
314
+ await stores.tasks.recordUsage(taskId, { step: {
1189
315
  turnId: event.data.turnId,
1190
316
  stepIndex: event.data.stepIndex,
1191
317
  ...usage
1192
- }).catch(() => void 0);
318
+ } }).catch(() => void 0);
319
+ },
320
+ async "turn.failed"(event, ctx) {
321
+ const binding = boundExecution(ctx);
322
+ if (binding !== void 0) {
323
+ await recoverFailedAttempt(binding, `provider turn failed (${event.data.code}): ${event.data.message}`).catch(() => void 0);
324
+ return;
325
+ }
326
+ const taskId = boundTaskId(ctx);
327
+ const task = taskId ? await stores.tasks.get(taskId).catch(() => null) : null;
328
+ if (task?.state === "running" && await isConversation(task)) {
329
+ await stores.tasks.transition(task.id, "failed", {
330
+ expectFrom: "running",
331
+ reason: "Conversation turn failed"
332
+ }).catch(() => void 0);
333
+ await settleIfTerminal(task.id).catch(() => void 0);
334
+ }
335
+ },
336
+ async "session.failed"(event, ctx) {
337
+ const binding = boundExecution(ctx);
338
+ if (binding !== void 0) await recoverFailedAttempt(binding, `provider session failed (${event.data.code}): ${event.data.message}`).catch(() => void 0);
339
+ await options.materializeTranscript?.(materializationInput(ctx)).catch(() => void 0);
340
+ },
341
+ async "session.waiting"(_event, ctx) {
342
+ await options.materializeTranscript?.(materializationInput(ctx)).catch(() => void 0);
343
+ },
344
+ async "session.completed"(_event, ctx) {
345
+ await options.materializeTranscript?.(materializationInput(ctx)).catch(() => void 0);
346
+ },
347
+ async "turn.cancelled"(_event, ctx) {
348
+ const binding = boundExecution(ctx);
349
+ if (binding !== void 0) {
350
+ await cancelAttempt(binding, `provider turn cancelled on attempt ${binding.attempt}`).catch(() => void 0);
351
+ return;
352
+ }
353
+ const taskId = boundTaskId(ctx);
354
+ const task = taskId ? await stores.tasks.get(taskId).catch(() => null) : null;
355
+ if (task && await isConversation(task)) {
356
+ if (task.state === "running") await stores.tasks.transition(task.id, "cancelled", {
357
+ expectFrom: "running",
358
+ reason: "Conversation turn interrupted"
359
+ }).catch(() => void 0);
360
+ await settleIfTerminal(task.id).catch(() => void 0);
361
+ }
1193
362
  },
1194
363
  async "turn.completed"(_event, ctx) {
1195
364
  const taskId = boundTaskId(ctx);
1196
- if (taskId !== void 0) await settleIfTerminal(taskId).catch(() => void 0);
365
+ const binding = boundExecution(ctx);
366
+ if (taskId !== void 0) {
367
+ const task = await stores.tasks.get(taskId).catch(() => null);
368
+ if (binding !== void 0 && task?.attempt !== binding.attempt) return;
369
+ if (task?.state === "running" && !task.waitingForMessages) {
370
+ const completion = await options.completeConversation?.(task).catch(() => false);
371
+ if (completion) await stores.tasks.transition(taskId, "succeeded", {
372
+ expectFrom: "running",
373
+ expectAttempt: task.attempt,
374
+ reason: "Conversation turn completed",
375
+ output: completion.output
376
+ }).catch(() => void 0);
377
+ else await escalateUnresolvedTurn(task);
378
+ }
379
+ await settleIfTerminal(taskId).catch(() => void 0);
380
+ }
1197
381
  const address = ctx.channel.continuationToken;
1198
382
  if (address === void 0) return;
1199
- const abandoned = (await stores.tasks.list()).filter((task) => task.state === "running" && task.replyTo.address === address);
1200
- for (const task of abandoned) await createAndPresentQuestion(stores, task, {
1201
- text: "The worker stopped without recording an outcome. Please review the task and reply when Factory should retry it.",
1202
- options: ["Retry the task"]
1203
- }, options.presentQuestion).catch(() => void 0);
383
+ const abandoned = (await stores.tasks.list().catch(() => [])).filter((task) => task.id !== taskId && task.state === "running" && !task.waitingForMessages && task.replyTo.address === address);
384
+ for (const task of abandoned) await escalateUnresolvedTurn(task);
1204
385
  }
1205
386
  } }) };
1206
387
  }
1207
388
  //#endregion
1208
- export { deepsecScanTool, delegateAgentTool, factoryHooks, factoryTools, fetchPullRequestTool, findingFromDeepsec, invokeAgentTool, mergeConflictPayloadSchema, mergeConflictTools, postReviewTool, recordFinding, recordFindingTool, recordVerificationTool, reviewCommentTools };
389
+ export { cancelEveSession, conversationBinding, conversationBindingForSession, conversationHeaders, createDelegateAgentTool, createEveTranscriptMaterializer, createFactoryHooks, createInvokeAgentTool, createTaskTools, createTranscriptSnapshotHook, factoryReplyAddressAttribute, factoryReplyAddressHeader, factoryReplyChannelAttribute, factoryReplyChannelHeader, factoryRepositoryIdsAttribute, factoryRepositoryIdsHeader, factoryTaskAttemptAttribute, factoryTaskAttemptHeader, factoryTaskAttribute, factoryTaskHeader, forwardEveSessionRequest, hasFactoryTaskBinding, optionalTaskIdForSession, readCompletedEveTurn, replyToForSession, repositoryIdsForSession, requireTaskIdForSession, startEveSession, taskBindingForSession, taskHeaders, taskSessionAuth, withFactoryTask, withOptionalFactoryTask };
1209
390
 
1210
391
  //# sourceMappingURL=index.mjs.map