@paperclipai_dld/server 2026.319.0-canary.3

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 (702) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/codex-models.d.ts +4 -0
  3. package/dist/adapters/codex-models.d.ts.map +1 -0
  4. package/dist/adapters/codex-models.js +98 -0
  5. package/dist/adapters/codex-models.js.map +1 -0
  6. package/dist/adapters/cursor-models.d.ts +13 -0
  7. package/dist/adapters/cursor-models.d.ts.map +1 -0
  8. package/dist/adapters/cursor-models.js +148 -0
  9. package/dist/adapters/cursor-models.js.map +1 -0
  10. package/dist/adapters/http/execute.d.ts +3 -0
  11. package/dist/adapters/http/execute.d.ts.map +1 -0
  12. package/dist/adapters/http/execute.js +39 -0
  13. package/dist/adapters/http/execute.js.map +1 -0
  14. package/dist/adapters/http/index.d.ts +3 -0
  15. package/dist/adapters/http/index.d.ts.map +1 -0
  16. package/dist/adapters/http/index.js +20 -0
  17. package/dist/adapters/http/index.js.map +1 -0
  18. package/dist/adapters/http/test.d.ts +3 -0
  19. package/dist/adapters/http/test.d.ts.map +1 -0
  20. package/dist/adapters/http/test.js +106 -0
  21. package/dist/adapters/http/test.js.map +1 -0
  22. package/dist/adapters/index.d.ts +4 -0
  23. package/dist/adapters/index.d.ts.map +1 -0
  24. package/dist/adapters/index.js +3 -0
  25. package/dist/adapters/index.js.map +1 -0
  26. package/dist/adapters/process/execute.d.ts +3 -0
  27. package/dist/adapters/process/execute.d.ts.map +1 -0
  28. package/dist/adapters/process/execute.js +63 -0
  29. package/dist/adapters/process/execute.js.map +1 -0
  30. package/dist/adapters/process/index.d.ts +3 -0
  31. package/dist/adapters/process/index.d.ts.map +1 -0
  32. package/dist/adapters/process/index.js +23 -0
  33. package/dist/adapters/process/index.js.map +1 -0
  34. package/dist/adapters/process/test.d.ts +3 -0
  35. package/dist/adapters/process/test.d.ts.map +1 -0
  36. package/dist/adapters/process/test.js +77 -0
  37. package/dist/adapters/process/test.js.map +1 -0
  38. package/dist/adapters/registry.d.ts +9 -0
  39. package/dist/adapters/registry.d.ts.map +1 -0
  40. package/dist/adapters/registry.js +142 -0
  41. package/dist/adapters/registry.js.map +1 -0
  42. package/dist/adapters/types.d.ts +2 -0
  43. package/dist/adapters/types.d.ts.map +1 -0
  44. package/dist/adapters/types.js +2 -0
  45. package/dist/adapters/types.js.map +1 -0
  46. package/dist/adapters/utils.d.ts +10 -0
  47. package/dist/adapters/utils.d.ts.map +1 -0
  48. package/dist/adapters/utils.js +14 -0
  49. package/dist/adapters/utils.js.map +1 -0
  50. package/dist/agent-auth-jwt.d.ts +14 -0
  51. package/dist/agent-auth-jwt.d.ts.map +1 -0
  52. package/dist/agent-auth-jwt.js +117 -0
  53. package/dist/agent-auth-jwt.js.map +1 -0
  54. package/dist/app.d.ts +25 -0
  55. package/dist/app.d.ts.map +1 -0
  56. package/dist/app.js +259 -0
  57. package/dist/app.js.map +1 -0
  58. package/dist/attachment-types.d.ts +33 -0
  59. package/dist/attachment-types.d.ts.map +1 -0
  60. package/dist/attachment-types.js +67 -0
  61. package/dist/attachment-types.js.map +1 -0
  62. package/dist/auth/better-auth.d.ts +24 -0
  63. package/dist/auth/better-auth.d.ts.map +1 -0
  64. package/dist/auth/better-auth.js +108 -0
  65. package/dist/auth/better-auth.js.map +1 -0
  66. package/dist/board-claim.d.ts +23 -0
  67. package/dist/board-claim.d.ts.map +1 -0
  68. package/dist/board-claim.js +115 -0
  69. package/dist/board-claim.js.map +1 -0
  70. package/dist/config-file.d.ts +3 -0
  71. package/dist/config-file.d.ts.map +1 -0
  72. package/dist/config-file.js +16 -0
  73. package/dist/config-file.js.map +1 -0
  74. package/dist/config.d.ts +38 -0
  75. package/dist/config.d.ts.map +1 -0
  76. package/dist/config.js +162 -0
  77. package/dist/config.js.map +1 -0
  78. package/dist/errors.d.ts +12 -0
  79. package/dist/errors.d.ts.map +1 -0
  80. package/dist/errors.js +28 -0
  81. package/dist/errors.js.map +1 -0
  82. package/dist/home-paths.d.ts +17 -0
  83. package/dist/home-paths.d.ts.map +1 -0
  84. package/dist/home-paths.js +75 -0
  85. package/dist/home-paths.js.map +1 -0
  86. package/dist/index.d.ts +10 -0
  87. package/dist/index.d.ts.map +1 -0
  88. package/dist/index.js +581 -0
  89. package/dist/index.js.map +1 -0
  90. package/dist/log-redaction.d.ts +10 -0
  91. package/dist/log-redaction.d.ts.map +1 -0
  92. package/dist/log-redaction.js +110 -0
  93. package/dist/log-redaction.js.map +1 -0
  94. package/dist/middleware/auth.d.ts +12 -0
  95. package/dist/middleware/auth.d.ts.map +1 -0
  96. package/dist/middleware/auth.js +124 -0
  97. package/dist/middleware/auth.js.map +1 -0
  98. package/dist/middleware/board-mutation-guard.d.ts +3 -0
  99. package/dist/middleware/board-mutation-guard.d.ts.map +1 -0
  100. package/dist/middleware/board-mutation-guard.js +60 -0
  101. package/dist/middleware/board-mutation-guard.js.map +1 -0
  102. package/dist/middleware/error-handler.d.ts +17 -0
  103. package/dist/middleware/error-handler.d.ts.map +1 -0
  104. package/dist/middleware/error-handler.js +37 -0
  105. package/dist/middleware/error-handler.js.map +1 -0
  106. package/dist/middleware/index.d.ts +4 -0
  107. package/dist/middleware/index.d.ts.map +1 -0
  108. package/dist/middleware/index.js +4 -0
  109. package/dist/middleware/index.js.map +1 -0
  110. package/dist/middleware/logger.d.ts +4 -0
  111. package/dist/middleware/logger.d.ts.map +1 -0
  112. package/dist/middleware/logger.js +87 -0
  113. package/dist/middleware/logger.js.map +1 -0
  114. package/dist/middleware/private-hostname-guard.d.ts +11 -0
  115. package/dist/middleware/private-hostname-guard.d.ts.map +1 -0
  116. package/dist/middleware/private-hostname-guard.js +78 -0
  117. package/dist/middleware/private-hostname-guard.js.map +1 -0
  118. package/dist/middleware/validate.d.ts +4 -0
  119. package/dist/middleware/validate.d.ts.map +1 -0
  120. package/dist/middleware/validate.js +7 -0
  121. package/dist/middleware/validate.js.map +1 -0
  122. package/dist/paths.d.ts +3 -0
  123. package/dist/paths.d.ts.map +1 -0
  124. package/dist/paths.js +31 -0
  125. package/dist/paths.js.map +1 -0
  126. package/dist/realtime/live-events-ws.d.ts +28 -0
  127. package/dist/realtime/live-events-ws.d.ts.map +1 -0
  128. package/dist/realtime/live-events-ws.js +187 -0
  129. package/dist/realtime/live-events-ws.js.map +1 -0
  130. package/dist/redaction.d.ts +4 -0
  131. package/dist/redaction.d.ts.map +1 -0
  132. package/dist/redaction.js +63 -0
  133. package/dist/redaction.js.map +1 -0
  134. package/dist/routes/access.d.ts +56 -0
  135. package/dist/routes/access.d.ts.map +1 -0
  136. package/dist/routes/access.js +2124 -0
  137. package/dist/routes/access.js.map +1 -0
  138. package/dist/routes/activity.d.ts +3 -0
  139. package/dist/routes/activity.d.ts.map +1 -0
  140. package/dist/routes/activity.js +78 -0
  141. package/dist/routes/activity.js.map +1 -0
  142. package/dist/routes/agents.d.ts +4 -0
  143. package/dist/routes/agents.d.ts.map +1 -0
  144. package/dist/routes/agents.js +1390 -0
  145. package/dist/routes/agents.js.map +1 -0
  146. package/dist/routes/approvals.d.ts +3 -0
  147. package/dist/routes/approvals.d.ts.map +1 -0
  148. package/dist/routes/approvals.js +275 -0
  149. package/dist/routes/approvals.js.map +1 -0
  150. package/dist/routes/assets.d.ts +4 -0
  151. package/dist/routes/assets.d.ts.map +1 -0
  152. package/dist/routes/assets.js +309 -0
  153. package/dist/routes/assets.js.map +1 -0
  154. package/dist/routes/authz.d.ts +15 -0
  155. package/dist/routes/authz.d.ts.map +1 -0
  156. package/dist/routes/authz.js +40 -0
  157. package/dist/routes/authz.js.map +1 -0
  158. package/dist/routes/companies.d.ts +3 -0
  159. package/dist/routes/companies.d.ts.map +1 -0
  160. package/dist/routes/companies.js +174 -0
  161. package/dist/routes/companies.js.map +1 -0
  162. package/dist/routes/costs.d.ts +3 -0
  163. package/dist/routes/costs.d.ts.map +1 -0
  164. package/dist/routes/costs.js +268 -0
  165. package/dist/routes/costs.js.map +1 -0
  166. package/dist/routes/dashboard.d.ts +3 -0
  167. package/dist/routes/dashboard.d.ts.map +1 -0
  168. package/dist/routes/dashboard.js +15 -0
  169. package/dist/routes/dashboard.js.map +1 -0
  170. package/dist/routes/execution-workspaces.d.ts +3 -0
  171. package/dist/routes/execution-workspaces.d.ts.map +1 -0
  172. package/dist/routes/execution-workspaces.js +165 -0
  173. package/dist/routes/execution-workspaces.js.map +1 -0
  174. package/dist/routes/goals.d.ts +3 -0
  175. package/dist/routes/goals.d.ts.map +1 -0
  176. package/dist/routes/goals.js +95 -0
  177. package/dist/routes/goals.js.map +1 -0
  178. package/dist/routes/health.d.ts +9 -0
  179. package/dist/routes/health.d.ts.map +1 -0
  180. package/dist/routes/health.js +51 -0
  181. package/dist/routes/health.js.map +1 -0
  182. package/dist/routes/index.d.ts +16 -0
  183. package/dist/routes/index.d.ts.map +1 -0
  184. package/dist/routes/index.js +16 -0
  185. package/dist/routes/index.js.map +1 -0
  186. package/dist/routes/instance-settings.d.ts +3 -0
  187. package/dist/routes/instance-settings.d.ts.map +1 -0
  188. package/dist/routes/instance-settings.js +46 -0
  189. package/dist/routes/instance-settings.js.map +1 -0
  190. package/dist/routes/issues-checkout-wakeup.d.ts +9 -0
  191. package/dist/routes/issues-checkout-wakeup.d.ts.map +1 -0
  192. package/dist/routes/issues-checkout-wakeup.js +12 -0
  193. package/dist/routes/issues-checkout-wakeup.js.map +1 -0
  194. package/dist/routes/issues.d.ts +4 -0
  195. package/dist/routes/issues.d.ts.map +1 -0
  196. package/dist/routes/issues.js +1431 -0
  197. package/dist/routes/issues.js.map +1 -0
  198. package/dist/routes/llms.d.ts +3 -0
  199. package/dist/routes/llms.d.ts.map +1 -0
  200. package/dist/routes/llms.js +78 -0
  201. package/dist/routes/llms.js.map +1 -0
  202. package/dist/routes/plugin-ui-static.d.ts +69 -0
  203. package/dist/routes/plugin-ui-static.d.ts.map +1 -0
  204. package/dist/routes/plugin-ui-static.js +411 -0
  205. package/dist/routes/plugin-ui-static.js.map +1 -0
  206. package/dist/routes/plugins.d.ts +120 -0
  207. package/dist/routes/plugins.d.ts.map +1 -0
  208. package/dist/routes/plugins.js +1784 -0
  209. package/dist/routes/plugins.js.map +1 -0
  210. package/dist/routes/projects.d.ts +3 -0
  211. package/dist/routes/projects.d.ts.map +1 -0
  212. package/dist/routes/projects.js +257 -0
  213. package/dist/routes/projects.js.map +1 -0
  214. package/dist/routes/secrets.d.ts +3 -0
  215. package/dist/routes/secrets.d.ts.map +1 -0
  216. package/dist/routes/secrets.js +128 -0
  217. package/dist/routes/secrets.js.map +1 -0
  218. package/dist/routes/sidebar-badges.d.ts +3 -0
  219. package/dist/routes/sidebar-badges.d.ts.map +1 -0
  220. package/dist/routes/sidebar-badges.js +45 -0
  221. package/dist/routes/sidebar-badges.js.map +1 -0
  222. package/dist/secrets/external-stub-providers.d.ts +5 -0
  223. package/dist/secrets/external-stub-providers.d.ts.map +1 -0
  224. package/dist/secrets/external-stub-providers.js +21 -0
  225. package/dist/secrets/external-stub-providers.js.map +1 -0
  226. package/dist/secrets/local-encrypted-provider.d.ts +3 -0
  227. package/dist/secrets/local-encrypted-provider.d.ts.map +1 -0
  228. package/dist/secrets/local-encrypted-provider.js +116 -0
  229. package/dist/secrets/local-encrypted-provider.js.map +1 -0
  230. package/dist/secrets/provider-registry.d.ts +5 -0
  231. package/dist/secrets/provider-registry.d.ts.map +1 -0
  232. package/dist/secrets/provider-registry.js +20 -0
  233. package/dist/secrets/provider-registry.js.map +1 -0
  234. package/dist/secrets/types.d.ts +21 -0
  235. package/dist/secrets/types.d.ts.map +1 -0
  236. package/dist/secrets/types.js +2 -0
  237. package/dist/secrets/types.js.map +1 -0
  238. package/dist/services/access.d.ts +81 -0
  239. package/dist/services/access.d.ts.map +1 -0
  240. package/dist/services/access.js +187 -0
  241. package/dist/services/access.js.map +1 -0
  242. package/dist/services/activity-log.d.ts +17 -0
  243. package/dist/services/activity-log.d.ts.map +1 -0
  244. package/dist/services/activity-log.js +68 -0
  245. package/dist/services/activity-log.js.map +1 -0
  246. package/dist/services/activity.d.ts +764 -0
  247. package/dist/services/activity.d.ts.map +1 -0
  248. package/dist/services/activity.js +105 -0
  249. package/dist/services/activity.js.map +1 -0
  250. package/dist/services/agent-permissions.d.ts +6 -0
  251. package/dist/services/agent-permissions.d.ts.map +1 -0
  252. package/dist/services/agent-permissions.js +18 -0
  253. package/dist/services/agent-permissions.js.map +1 -0
  254. package/dist/services/agents.d.ts +1530 -0
  255. package/dist/services/agents.d.ts.map +1 -0
  256. package/dist/services/agents.js +566 -0
  257. package/dist/services/agents.js.map +1 -0
  258. package/dist/services/approvals.d.ts +546 -0
  259. package/dist/services/approvals.d.ts.map +1 -0
  260. package/dist/services/approvals.js +206 -0
  261. package/dist/services/approvals.js.map +1 -0
  262. package/dist/services/assets.d.ts +33 -0
  263. package/dist/services/assets.d.ts.map +1 -0
  264. package/dist/services/assets.js +17 -0
  265. package/dist/services/assets.js.map +1 -0
  266. package/dist/services/budgets.d.ts +38 -0
  267. package/dist/services/budgets.d.ts.map +1 -0
  268. package/dist/services/budgets.js +784 -0
  269. package/dist/services/budgets.js.map +1 -0
  270. package/dist/services/companies.d.ts +124 -0
  271. package/dist/services/companies.d.ts.map +1 -0
  272. package/dist/services/companies.js +256 -0
  273. package/dist/services/companies.js.map +1 -0
  274. package/dist/services/company-portability.d.ts +8 -0
  275. package/dist/services/company-portability.d.ts.map +1 -0
  276. package/dist/services/company-portability.js +867 -0
  277. package/dist/services/company-portability.js.map +1 -0
  278. package/dist/services/costs.d.ts +114 -0
  279. package/dist/services/costs.d.ts.map +1 -0
  280. package/dist/services/costs.js +294 -0
  281. package/dist/services/costs.js.map +1 -0
  282. package/dist/services/cron.d.ts +80 -0
  283. package/dist/services/cron.d.ts.map +1 -0
  284. package/dist/services/cron.js +300 -0
  285. package/dist/services/cron.js.map +1 -0
  286. package/dist/services/dashboard.d.ts +26 -0
  287. package/dist/services/dashboard.d.ts.map +1 -0
  288. package/dist/services/dashboard.js +98 -0
  289. package/dist/services/dashboard.js.map +1 -0
  290. package/dist/services/documents.d.ts +164 -0
  291. package/dist/services/documents.d.ts.map +1 -0
  292. package/dist/services/documents.js +382 -0
  293. package/dist/services/documents.js.map +1 -0
  294. package/dist/services/execution-workspace-policy.d.ts +20 -0
  295. package/dist/services/execution-workspace-policy.d.ts.map +1 -0
  296. package/dist/services/execution-workspace-policy.js +165 -0
  297. package/dist/services/execution-workspace-policy.js.map +1 -0
  298. package/dist/services/execution-workspaces.d.ts +19 -0
  299. package/dist/services/execution-workspaces.d.ts.map +1 -0
  300. package/dist/services/execution-workspaces.js +87 -0
  301. package/dist/services/execution-workspaces.js.map +1 -0
  302. package/dist/services/finance.d.ts +93 -0
  303. package/dist/services/finance.d.ts.map +1 -0
  304. package/dist/services/finance.js +120 -0
  305. package/dist/services/finance.js.map +1 -0
  306. package/dist/services/goals.d.ts +433 -0
  307. package/dist/services/goals.d.ts.map +1 -0
  308. package/dist/services/goals.js +54 -0
  309. package/dist/services/goals.js.map +1 -0
  310. package/dist/services/heartbeat-run-summary.d.ts +2 -0
  311. package/dist/services/heartbeat-run-summary.d.ts.map +1 -0
  312. package/dist/services/heartbeat-run-summary.js +30 -0
  313. package/dist/services/heartbeat-run-summary.js.map +1 -0
  314. package/dist/services/heartbeat.d.ts +766 -0
  315. package/dist/services/heartbeat.d.ts.map +1 -0
  316. package/dist/services/heartbeat.js +3024 -0
  317. package/dist/services/heartbeat.js.map +1 -0
  318. package/dist/services/hire-hook.d.ts +14 -0
  319. package/dist/services/hire-hook.d.ts.map +1 -0
  320. package/dist/services/hire-hook.js +85 -0
  321. package/dist/services/hire-hook.js.map +1 -0
  322. package/dist/services/index.d.ts +29 -0
  323. package/dist/services/index.d.ts.map +1 -0
  324. package/dist/services/index.js +29 -0
  325. package/dist/services/index.js.map +1 -0
  326. package/dist/services/instance-settings.d.ts +9 -0
  327. package/dist/services/instance-settings.d.ts.map +1 -0
  328. package/dist/services/instance-settings.js +80 -0
  329. package/dist/services/instance-settings.js.map +1 -0
  330. package/dist/services/issue-approvals.d.ts +56 -0
  331. package/dist/services/issue-approvals.d.ts.map +1 -0
  332. package/dist/services/issue-approvals.js +153 -0
  333. package/dist/services/issue-approvals.js.map +1 -0
  334. package/dist/services/issue-goal-fallback.d.ts +15 -0
  335. package/dist/services/issue-goal-fallback.d.ts.map +1 -0
  336. package/dist/services/issue-goal-fallback.js +15 -0
  337. package/dist/services/issue-goal-fallback.js.map +1 -0
  338. package/dist/services/issues.d.ts +532 -0
  339. package/dist/services/issues.d.ts.map +1 -0
  340. package/dist/services/issues.js +1308 -0
  341. package/dist/services/issues.js.map +1 -0
  342. package/dist/services/live-events.d.ts +17 -0
  343. package/dist/services/live-events.d.ts.map +1 -0
  344. package/dist/services/live-events.js +33 -0
  345. package/dist/services/live-events.js.map +1 -0
  346. package/dist/services/plugin-capability-validator.d.ts +108 -0
  347. package/dist/services/plugin-capability-validator.d.ts.map +1 -0
  348. package/dist/services/plugin-capability-validator.js +268 -0
  349. package/dist/services/plugin-capability-validator.js.map +1 -0
  350. package/dist/services/plugin-config-validator.d.ts +26 -0
  351. package/dist/services/plugin-config-validator.d.ts.map +1 -0
  352. package/dist/services/plugin-config-validator.js +41 -0
  353. package/dist/services/plugin-config-validator.js.map +1 -0
  354. package/dist/services/plugin-dev-watcher.d.ts +30 -0
  355. package/dist/services/plugin-dev-watcher.d.ts.map +1 -0
  356. package/dist/services/plugin-dev-watcher.js +241 -0
  357. package/dist/services/plugin-dev-watcher.js.map +1 -0
  358. package/dist/services/plugin-event-bus.d.ts +149 -0
  359. package/dist/services/plugin-event-bus.d.ts.map +1 -0
  360. package/dist/services/plugin-event-bus.js +258 -0
  361. package/dist/services/plugin-event-bus.js.map +1 -0
  362. package/dist/services/plugin-host-service-cleanup.d.ts +14 -0
  363. package/dist/services/plugin-host-service-cleanup.d.ts.map +1 -0
  364. package/dist/services/plugin-host-service-cleanup.js +37 -0
  365. package/dist/services/plugin-host-service-cleanup.js.map +1 -0
  366. package/dist/services/plugin-host-services.d.ts +13 -0
  367. package/dist/services/plugin-host-services.d.ts.map +1 -0
  368. package/dist/services/plugin-host-services.js +969 -0
  369. package/dist/services/plugin-host-services.js.map +1 -0
  370. package/dist/services/plugin-job-coordinator.d.ts +81 -0
  371. package/dist/services/plugin-job-coordinator.d.ts.map +1 -0
  372. package/dist/services/plugin-job-coordinator.js +172 -0
  373. package/dist/services/plugin-job-coordinator.js.map +1 -0
  374. package/dist/services/plugin-job-scheduler.d.ts +163 -0
  375. package/dist/services/plugin-job-scheduler.d.ts.map +1 -0
  376. package/dist/services/plugin-job-scheduler.js +454 -0
  377. package/dist/services/plugin-job-scheduler.js.map +1 -0
  378. package/dist/services/plugin-job-store.d.ts +208 -0
  379. package/dist/services/plugin-job-store.d.ts.map +1 -0
  380. package/dist/services/plugin-job-store.js +350 -0
  381. package/dist/services/plugin-job-store.js.map +1 -0
  382. package/dist/services/plugin-lifecycle.d.ts +203 -0
  383. package/dist/services/plugin-lifecycle.d.ts.map +1 -0
  384. package/dist/services/plugin-lifecycle.js +476 -0
  385. package/dist/services/plugin-lifecycle.js.map +1 -0
  386. package/dist/services/plugin-loader.d.ts +441 -0
  387. package/dist/services/plugin-loader.d.ts.map +1 -0
  388. package/dist/services/plugin-loader.js +1192 -0
  389. package/dist/services/plugin-loader.js.map +1 -0
  390. package/dist/services/plugin-log-retention.d.ts +20 -0
  391. package/dist/services/plugin-log-retention.d.ts.map +1 -0
  392. package/dist/services/plugin-log-retention.js +63 -0
  393. package/dist/services/plugin-log-retention.js.map +1 -0
  394. package/dist/services/plugin-manifest-validator.d.ts +79 -0
  395. package/dist/services/plugin-manifest-validator.d.ts.map +1 -0
  396. package/dist/services/plugin-manifest-validator.js +84 -0
  397. package/dist/services/plugin-manifest-validator.js.map +1 -0
  398. package/dist/services/plugin-registry.d.ts +2542 -0
  399. package/dist/services/plugin-registry.d.ts.map +1 -0
  400. package/dist/services/plugin-registry.js +539 -0
  401. package/dist/services/plugin-registry.js.map +1 -0
  402. package/dist/services/plugin-runtime-sandbox.d.ts +40 -0
  403. package/dist/services/plugin-runtime-sandbox.d.ts.map +1 -0
  404. package/dist/services/plugin-runtime-sandbox.js +154 -0
  405. package/dist/services/plugin-runtime-sandbox.js.map +1 -0
  406. package/dist/services/plugin-secrets-handler.d.ts +81 -0
  407. package/dist/services/plugin-secrets-handler.d.ts.map +1 -0
  408. package/dist/services/plugin-secrets-handler.js +275 -0
  409. package/dist/services/plugin-secrets-handler.js.map +1 -0
  410. package/dist/services/plugin-state-store.d.ts +92 -0
  411. package/dist/services/plugin-state-store.d.ts.map +1 -0
  412. package/dist/services/plugin-state-store.js +190 -0
  413. package/dist/services/plugin-state-store.js.map +1 -0
  414. package/dist/services/plugin-stream-bus.d.ts +29 -0
  415. package/dist/services/plugin-stream-bus.d.ts.map +1 -0
  416. package/dist/services/plugin-stream-bus.js +48 -0
  417. package/dist/services/plugin-stream-bus.js.map +1 -0
  418. package/dist/services/plugin-tool-dispatcher.d.ts +180 -0
  419. package/dist/services/plugin-tool-dispatcher.d.ts.map +1 -0
  420. package/dist/services/plugin-tool-dispatcher.js +224 -0
  421. package/dist/services/plugin-tool-dispatcher.js.map +1 -0
  422. package/dist/services/plugin-tool-registry.d.ts +192 -0
  423. package/dist/services/plugin-tool-registry.d.ts.map +1 -0
  424. package/dist/services/plugin-tool-registry.js +224 -0
  425. package/dist/services/plugin-tool-registry.js.map +1 -0
  426. package/dist/services/plugin-worker-manager.d.ts +260 -0
  427. package/dist/services/plugin-worker-manager.d.ts.map +1 -0
  428. package/dist/services/plugin-worker-manager.js +835 -0
  429. package/dist/services/plugin-worker-manager.js.map +1 -0
  430. package/dist/services/projects.d.ts +87 -0
  431. package/dist/services/projects.d.ts.map +1 -0
  432. package/dist/services/projects.js +656 -0
  433. package/dist/services/projects.js.map +1 -0
  434. package/dist/services/quota-windows.d.ts +9 -0
  435. package/dist/services/quota-windows.d.ts.map +1 -0
  436. package/dist/services/quota-windows.js +56 -0
  437. package/dist/services/quota-windows.js.map +1 -0
  438. package/dist/services/run-log-store.d.ts +34 -0
  439. package/dist/services/run-log-store.d.ts.map +1 -0
  440. package/dist/services/run-log-store.js +109 -0
  441. package/dist/services/run-log-store.js.map +1 -0
  442. package/dist/services/secrets.d.ts +510 -0
  443. package/dist/services/secrets.d.ts.map +1 -0
  444. package/dist/services/secrets.js +288 -0
  445. package/dist/services/secrets.js.map +1 -0
  446. package/dist/services/sidebar-badges.d.ts +9 -0
  447. package/dist/services/sidebar-badges.d.ts.map +1 -0
  448. package/dist/services/sidebar-badges.js +33 -0
  449. package/dist/services/sidebar-badges.js.map +1 -0
  450. package/dist/services/work-products.d.ts +14 -0
  451. package/dist/services/work-products.d.ts.map +1 -0
  452. package/dist/services/work-products.js +100 -0
  453. package/dist/services/work-products.js.map +1 -0
  454. package/dist/services/workspace-operation-log-store.d.ts +33 -0
  455. package/dist/services/workspace-operation-log-store.d.ts.map +1 -0
  456. package/dist/services/workspace-operation-log-store.js +110 -0
  457. package/dist/services/workspace-operation-log-store.js.map +1 -0
  458. package/dist/services/workspace-operations.d.ts +44 -0
  459. package/dist/services/workspace-operations.d.ts.map +1 -0
  460. package/dist/services/workspace-operations.js +204 -0
  461. package/dist/services/workspace-operations.js.map +1 -0
  462. package/dist/services/workspace-runtime.d.ts +164 -0
  463. package/dist/services/workspace-runtime.d.ts.map +1 -0
  464. package/dist/services/workspace-runtime.js +1235 -0
  465. package/dist/services/workspace-runtime.js.map +1 -0
  466. package/dist/startup-banner.d.ts +31 -0
  467. package/dist/startup-banner.d.ts.map +1 -0
  468. package/dist/startup-banner.js +117 -0
  469. package/dist/startup-banner.js.map +1 -0
  470. package/dist/storage/index.d.ts +6 -0
  471. package/dist/storage/index.d.ts.map +1 -0
  472. package/dist/storage/index.js +29 -0
  473. package/dist/storage/index.js.map +1 -0
  474. package/dist/storage/local-disk-provider.d.ts +3 -0
  475. package/dist/storage/local-disk-provider.d.ts.map +1 -0
  476. package/dist/storage/local-disk-provider.js +79 -0
  477. package/dist/storage/local-disk-provider.js.map +1 -0
  478. package/dist/storage/provider-registry.d.ts +4 -0
  479. package/dist/storage/provider-registry.d.ts.map +1 -0
  480. package/dist/storage/provider-registry.js +15 -0
  481. package/dist/storage/provider-registry.js.map +1 -0
  482. package/dist/storage/s3-provider.d.ts +11 -0
  483. package/dist/storage/s3-provider.d.ts.map +1 -0
  484. package/dist/storage/s3-provider.js +123 -0
  485. package/dist/storage/s3-provider.js.map +1 -0
  486. package/dist/storage/service.d.ts +3 -0
  487. package/dist/storage/service.d.ts.map +1 -0
  488. package/dist/storage/service.js +120 -0
  489. package/dist/storage/service.js.map +1 -0
  490. package/dist/storage/types.d.ts +55 -0
  491. package/dist/storage/types.d.ts.map +1 -0
  492. package/dist/storage/types.js +2 -0
  493. package/dist/storage/types.js.map +1 -0
  494. package/dist/ui-branding.d.ts +13 -0
  495. package/dist/ui-branding.d.ts.map +1 -0
  496. package/dist/ui-branding.js +187 -0
  497. package/dist/ui-branding.js.map +1 -0
  498. package/dist/version.d.ts +2 -0
  499. package/dist/version.d.ts.map +1 -0
  500. package/dist/version.js +5 -0
  501. package/dist/version.js.map +1 -0
  502. package/dist/wallet/connie-wallet.d.ts +8 -0
  503. package/dist/wallet/connie-wallet.d.ts.map +1 -0
  504. package/dist/wallet/connie-wallet.js +28 -0
  505. package/dist/wallet/connie-wallet.js.map +1 -0
  506. package/dist/wallet/signer-service.d.ts +46 -0
  507. package/dist/wallet/signer-service.d.ts.map +1 -0
  508. package/dist/wallet/signer-service.js +51 -0
  509. package/dist/wallet/signer-service.js.map +1 -0
  510. package/package.json +89 -0
  511. package/skills/paperclip/SKILL.md +310 -0
  512. package/skills/paperclip/references/api-reference.md +561 -0
  513. package/skills/paperclip-create-agent/SKILL.md +139 -0
  514. package/skills/paperclip-create-agent/references/api-reference.md +95 -0
  515. package/skills/paperclip-create-plugin/SKILL.md +101 -0
  516. package/skills/para-memory-files/SKILL.md +104 -0
  517. package/skills/para-memory-files/references/schemas.md +35 -0
  518. package/ui-dist/android-chrome-192x192.png +0 -0
  519. package/ui-dist/android-chrome-512x512.png +0 -0
  520. package/ui-dist/apple-touch-icon.png +0 -0
  521. package/ui-dist/assets/_basePickBy-C3SapTV-.js +1 -0
  522. package/ui-dist/assets/_baseUniq-tAa_W7wz.js +1 -0
  523. package/ui-dist/assets/apl-B4CMkyY2.js +1 -0
  524. package/ui-dist/assets/arc-1aKL9N1m.js +1 -0
  525. package/ui-dist/assets/architectureDiagram-VXUJARFQ-C-BWMHir.js +36 -0
  526. package/ui-dist/assets/asciiarmor-Df11BRmG.js +1 -0
  527. package/ui-dist/assets/asn1-EdZsLKOL.js +1 -0
  528. package/ui-dist/assets/asterisk-B-8jnY81.js +1 -0
  529. package/ui-dist/assets/blockDiagram-VD42YOAC-DiZzNyCp.js +122 -0
  530. package/ui-dist/assets/brainfuck-C4LP7Hcl.js +1 -0
  531. package/ui-dist/assets/c4Diagram-YG6GDRKO-BxkN6K8Z.js +10 -0
  532. package/ui-dist/assets/channel-g6sWbOF_.js +1 -0
  533. package/ui-dist/assets/chunk-4BX2VUAB-dEQLWXMP.js +1 -0
  534. package/ui-dist/assets/chunk-55IACEB6-DOlf6bGB.js +1 -0
  535. package/ui-dist/assets/chunk-B4BG7PRW-D82iJIh4.js +165 -0
  536. package/ui-dist/assets/chunk-DI55MBZ5-Dvu2BjZt.js +220 -0
  537. package/ui-dist/assets/chunk-FMBD7UC4-zLtBDqIV.js +15 -0
  538. package/ui-dist/assets/chunk-QN33PNHL-BsDTCIez.js +1 -0
  539. package/ui-dist/assets/chunk-QZHKN3VN-CVk0cJt0.js +1 -0
  540. package/ui-dist/assets/chunk-TZMSLE5B-BkF4gaW2.js +1 -0
  541. package/ui-dist/assets/classDiagram-2ON5EDUG-D_SGf4i1.js +1 -0
  542. package/ui-dist/assets/classDiagram-v2-WZHVMYZB-D_SGf4i1.js +1 -0
  543. package/ui-dist/assets/clike-B9uivgTg.js +1 -0
  544. package/ui-dist/assets/clojure-BMjYHr_A.js +1 -0
  545. package/ui-dist/assets/clone-CvdGFEjL.js +1 -0
  546. package/ui-dist/assets/cmake-BQqOBYOt.js +1 -0
  547. package/ui-dist/assets/cobol-CWcv1MsR.js +1 -0
  548. package/ui-dist/assets/coffeescript-S37ZYGWr.js +1 -0
  549. package/ui-dist/assets/commonlisp-DBKNyK5s.js +1 -0
  550. package/ui-dist/assets/cose-bilkent-S5V4N54A-DhXJS1Wr.js +1 -0
  551. package/ui-dist/assets/crystal-SjHAIU92.js +1 -0
  552. package/ui-dist/assets/css-BnMrqG3P.js +1 -0
  553. package/ui-dist/assets/cypher-C_CwsFkJ.js +1 -0
  554. package/ui-dist/assets/cytoscape.esm-BQaXIfA_.js +331 -0
  555. package/ui-dist/assets/d-pRatUO7H.js +1 -0
  556. package/ui-dist/assets/dagre-6UL2VRFP-BgSr9M5y.js +4 -0
  557. package/ui-dist/assets/defaultLocale-DX6XiGOO.js +1 -0
  558. package/ui-dist/assets/diagram-PSM6KHXK-RVw3ElKR.js +24 -0
  559. package/ui-dist/assets/diagram-QEK2KX5R-C3K5KNnR.js +43 -0
  560. package/ui-dist/assets/diagram-S2PKOQOG-L2G5bc-i.js +24 -0
  561. package/ui-dist/assets/diff-DbItnlRl.js +1 -0
  562. package/ui-dist/assets/dockerfile-BKs6k2Af.js +1 -0
  563. package/ui-dist/assets/dtd-DF_7sFjM.js +1 -0
  564. package/ui-dist/assets/dylan-DwRh75JA.js +1 -0
  565. package/ui-dist/assets/ebnf-CDyGwa7X.js +1 -0
  566. package/ui-dist/assets/ecl-Cabwm37j.js +1 -0
  567. package/ui-dist/assets/eiffel-CnydiIhH.js +1 -0
  568. package/ui-dist/assets/elm-vLlmbW-K.js +1 -0
  569. package/ui-dist/assets/erDiagram-Q2GNP2WA-B-fEopEW.js +60 -0
  570. package/ui-dist/assets/erlang-BNw1qcRV.js +1 -0
  571. package/ui-dist/assets/factor-kuTfRLto.js +1 -0
  572. package/ui-dist/assets/fcl-Kvtd6kyn.js +1 -0
  573. package/ui-dist/assets/flowDiagram-NV44I4VS-B67TmiaU.js +162 -0
  574. package/ui-dist/assets/forth-Ffai-XNe.js +1 -0
  575. package/ui-dist/assets/fortran-DYz_wnZ1.js +1 -0
  576. package/ui-dist/assets/ganttDiagram-JELNMOA3-DyPUX6hg.js +267 -0
  577. package/ui-dist/assets/gas-Bneqetm1.js +1 -0
  578. package/ui-dist/assets/gherkin-heZmZLOM.js +1 -0
  579. package/ui-dist/assets/gitGraphDiagram-V2S2FVAM--OZSHgOs.js +65 -0
  580. package/ui-dist/assets/graph-BuZXpro8.js +1 -0
  581. package/ui-dist/assets/groovy-D9Dt4D0W.js +1 -0
  582. package/ui-dist/assets/haskell-Cw1EW3IL.js +1 -0
  583. package/ui-dist/assets/haxe-H-WmDvRZ.js +1 -0
  584. package/ui-dist/assets/http-DBlCnlav.js +1 -0
  585. package/ui-dist/assets/idl-BEugSyMb.js +1 -0
  586. package/ui-dist/assets/index-1BDMTcZo.css +1 -0
  587. package/ui-dist/assets/index-5qKrPxpA.js +1 -0
  588. package/ui-dist/assets/index-64g9Tgj8.js +1 -0
  589. package/ui-dist/assets/index-B2BWcxI3.js +1 -0
  590. package/ui-dist/assets/index-BBnLF7s9.js +1 -0
  591. package/ui-dist/assets/index-BcGr-t2T.js +3 -0
  592. package/ui-dist/assets/index-BvFjgW1S.js +1 -0
  593. package/ui-dist/assets/index-Bwu5E0tU.js +1120 -0
  594. package/ui-dist/assets/index-CWdVcwY-.js +7 -0
  595. package/ui-dist/assets/index-CcZ3jKyu.js +1 -0
  596. package/ui-dist/assets/index-CftQkMtr.js +1 -0
  597. package/ui-dist/assets/index-CiuvxTr1.js +13 -0
  598. package/ui-dist/assets/index-CvJFaRY-.js +1 -0
  599. package/ui-dist/assets/index-D2Vi4KQ1.js +1 -0
  600. package/ui-dist/assets/index-D9ei6U88.js +6 -0
  601. package/ui-dist/assets/index-DJHKsR5g.js +1 -0
  602. package/ui-dist/assets/index-DSGN-qDr.js +1 -0
  603. package/ui-dist/assets/index-DVPlvZkH.js +1 -0
  604. package/ui-dist/assets/index-DowQVAaY.js +1 -0
  605. package/ui-dist/assets/index-Dr_PpBCY.js +1 -0
  606. package/ui-dist/assets/index-Ivk3iEUq.js +2 -0
  607. package/ui-dist/assets/index-OVXAhlMW.js +1 -0
  608. package/ui-dist/assets/index-ff_wE0-y.js +1 -0
  609. package/ui-dist/assets/index-tIsOsmOg.js +1 -0
  610. package/ui-dist/assets/infoDiagram-HS3SLOUP-CorcfaW7.js +2 -0
  611. package/ui-dist/assets/init-Gi6I4Gst.js +1 -0
  612. package/ui-dist/assets/javascript-iXu5QeM3.js +1 -0
  613. package/ui-dist/assets/journeyDiagram-XKPGCS4Q-D3K55-qo.js +139 -0
  614. package/ui-dist/assets/julia-DuME0IfC.js +1 -0
  615. package/ui-dist/assets/kanban-definition-3W4ZIXB7-47soc494.js +89 -0
  616. package/ui-dist/assets/katex-O9d3_IXG.js +261 -0
  617. package/ui-dist/assets/layout-mxhxSLBl.js +1 -0
  618. package/ui-dist/assets/linear-D5Y7uAaH.js +1 -0
  619. package/ui-dist/assets/livescript-BwQOo05w.js +1 -0
  620. package/ui-dist/assets/lua-BgMRiT3U.js +1 -0
  621. package/ui-dist/assets/mathematica-DTrFuWx2.js +1 -0
  622. package/ui-dist/assets/mbox-CNhZ1qSd.js +1 -0
  623. package/ui-dist/assets/mermaid.core-7SNUCoBq.js +256 -0
  624. package/ui-dist/assets/mindmap-definition-VGOIOE7T-C37ba4sG.js +68 -0
  625. package/ui-dist/assets/mirc-CjQqDB4T.js +1 -0
  626. package/ui-dist/assets/mllike-CXdrOF99.js +1 -0
  627. package/ui-dist/assets/modelica-Dc1JOy9r.js +1 -0
  628. package/ui-dist/assets/mscgen-BA5vi2Kp.js +1 -0
  629. package/ui-dist/assets/mumps-BT43cFF4.js +1 -0
  630. package/ui-dist/assets/nginx-DdIZxoE0.js +1 -0
  631. package/ui-dist/assets/nsis-LdVXkNf5.js +1 -0
  632. package/ui-dist/assets/ntriples-BfvgReVJ.js +1 -0
  633. package/ui-dist/assets/octave-Ck1zUtKM.js +1 -0
  634. package/ui-dist/assets/ordinal-Cboi1Yqb.js +1 -0
  635. package/ui-dist/assets/oz-BzwKVEFT.js +1 -0
  636. package/ui-dist/assets/pascal--L3eBynH.js +1 -0
  637. package/ui-dist/assets/perl-CdXCOZ3F.js +1 -0
  638. package/ui-dist/assets/pieDiagram-ADFJNKIX-D78e-tVE.js +30 -0
  639. package/ui-dist/assets/pig-CevX1Tat.js +1 -0
  640. package/ui-dist/assets/powershell-CFHJl5sT.js +1 -0
  641. package/ui-dist/assets/properties-C78fOPTZ.js +1 -0
  642. package/ui-dist/assets/protobuf-ChK-085T.js +1 -0
  643. package/ui-dist/assets/pug-DeIclll2.js +1 -0
  644. package/ui-dist/assets/puppet-DMA9R1ak.js +1 -0
  645. package/ui-dist/assets/python-BuPzkPfP.js +1 -0
  646. package/ui-dist/assets/q-pXgVlZs6.js +1 -0
  647. package/ui-dist/assets/quadrantDiagram-AYHSOK5B-CGERMcfi.js +7 -0
  648. package/ui-dist/assets/r-B6wPVr8A.js +1 -0
  649. package/ui-dist/assets/requirementDiagram-UZGBJVZJ-vZWAyhU1.js +64 -0
  650. package/ui-dist/assets/rpm-CTu-6PCP.js +1 -0
  651. package/ui-dist/assets/ruby-B2Rjki9n.js +1 -0
  652. package/ui-dist/assets/sankeyDiagram-TZEHDZUN-C51wCQX7.js +10 -0
  653. package/ui-dist/assets/sas-B4kiWyti.js +1 -0
  654. package/ui-dist/assets/scheme-C41bIUwD.js +1 -0
  655. package/ui-dist/assets/sequenceDiagram-WL72ISMW-eCSbKUaE.js +145 -0
  656. package/ui-dist/assets/shell-CjFT_Tl9.js +1 -0
  657. package/ui-dist/assets/sieve-C3Gn_uJK.js +1 -0
  658. package/ui-dist/assets/simple-mode-GW_nhZxv.js +1 -0
  659. package/ui-dist/assets/smalltalk-CnHTOXQT.js +1 -0
  660. package/ui-dist/assets/solr-DehyRSwq.js +1 -0
  661. package/ui-dist/assets/sparql-DkYu6x3z.js +1 -0
  662. package/ui-dist/assets/spreadsheet-BCZA_wO0.js +1 -0
  663. package/ui-dist/assets/sql-D0XecflT.js +1 -0
  664. package/ui-dist/assets/stateDiagram-FKZM4ZOC-H3lI51qU.js +1 -0
  665. package/ui-dist/assets/stateDiagram-v2-4FDKWEC3--Q50auwn.js +1 -0
  666. package/ui-dist/assets/stex-C3f8Ysf7.js +1 -0
  667. package/ui-dist/assets/stylus-B533Al4x.js +1 -0
  668. package/ui-dist/assets/swift-BzpIVaGY.js +1 -0
  669. package/ui-dist/assets/tcl-DVfN8rqt.js +1 -0
  670. package/ui-dist/assets/textile-CnDTJFAw.js +1 -0
  671. package/ui-dist/assets/tiddlywiki-DO-Gjzrf.js +1 -0
  672. package/ui-dist/assets/tiki-DGYXhP31.js +1 -0
  673. package/ui-dist/assets/timeline-definition-IT6M3QCI-CP9CNQLU.js +61 -0
  674. package/ui-dist/assets/toml-Bm5Em-hy.js +1 -0
  675. package/ui-dist/assets/treemap-GDKQZRPO-BfRhErz4.js +162 -0
  676. package/ui-dist/assets/troff-wAsdV37c.js +1 -0
  677. package/ui-dist/assets/ttcn-CfJYG6tj.js +1 -0
  678. package/ui-dist/assets/ttcn-cfg-B9xdYoR4.js +1 -0
  679. package/ui-dist/assets/turtle-B1tBg_DP.js +1 -0
  680. package/ui-dist/assets/vb-CmGdzxic.js +1 -0
  681. package/ui-dist/assets/vbscript-BuJXcnF6.js +1 -0
  682. package/ui-dist/assets/velocity-D8B20fx6.js +1 -0
  683. package/ui-dist/assets/verilog-C6RDOZhf.js +1 -0
  684. package/ui-dist/assets/vhdl-lSbBsy5d.js +1 -0
  685. package/ui-dist/assets/webidl-ZXfAyPTL.js +1 -0
  686. package/ui-dist/assets/xquery-DzFWVndE.js +1 -0
  687. package/ui-dist/assets/xychartDiagram-PRI3JC2R-BSy7gZ_Q.js +7 -0
  688. package/ui-dist/assets/yacas-BJ4BC0dw.js +1 -0
  689. package/ui-dist/assets/z80-Hz9HOZM7.js +1 -0
  690. package/ui-dist/brands/opencode-logo-dark-square.svg +18 -0
  691. package/ui-dist/brands/opencode-logo-light-square.svg +18 -0
  692. package/ui-dist/favicon-16x16.png +0 -0
  693. package/ui-dist/favicon-32x32.png +0 -0
  694. package/ui-dist/favicon.ico +0 -0
  695. package/ui-dist/favicon.svg +9 -0
  696. package/ui-dist/index.html +48 -0
  697. package/ui-dist/site.webmanifest +30 -0
  698. package/ui-dist/sw.js +42 -0
  699. package/ui-dist/worktree-favicon-16x16.png +0 -0
  700. package/ui-dist/worktree-favicon-32x32.png +0 -0
  701. package/ui-dist/worktree-favicon.ico +0 -0
  702. package/ui-dist/worktree-favicon.svg +9 -0
@@ -0,0 +1,3024 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { execFile as execFileCallback } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { and, asc, desc, eq, gt, inArray, sql } from "drizzle-orm";
6
+ import { agents, agentRuntimeState, agentTaskSessions, agentWakeupRequests, heartbeatRunEvents, heartbeatRuns, issues, projects, projectWorkspaces, } from "@paperclipai_dld/db";
7
+ import { conflict, notFound } from "../errors.js";
8
+ import { logger } from "../middleware/logger.js";
9
+ import { publishLiveEvent } from "./live-events.js";
10
+ import { getRunLogStore } from "./run-log-store.js";
11
+ import { getServerAdapter, runningProcesses, finishedWorkspacePaths, FINISHED_WORKSPACE_PATH_RETENTION_MS } from "../adapters/index.js";
12
+ import { createLocalAgentJwt } from "../agent-auth-jwt.js";
13
+ import { parseObject, asBoolean, asNumber, appendWithCap, MAX_EXCERPT_BYTES } from "../adapters/utils.js";
14
+ import { costService } from "./costs.js";
15
+ import { budgetService } from "./budgets.js";
16
+ import { secretService } from "./secrets.js";
17
+ import { resolveDefaultAgentWorkspaceDir, resolveManagedProjectWorkspaceDir } from "../home-paths.js";
18
+ import { summarizeHeartbeatRunResultJson } from "./heartbeat-run-summary.js";
19
+ import { buildWorkspaceReadyComment, cleanupExecutionWorkspaceArtifacts, ensureRuntimeServicesForRun, persistAdapterManagedRuntimeServices, realizeExecutionWorkspace, releaseRuntimeServicesForRun, sanitizeRuntimeServiceBaseEnv, } from "./workspace-runtime.js";
20
+ import { issueService } from "./issues.js";
21
+ import { executionWorkspaceService } from "./execution-workspaces.js";
22
+ import { workspaceOperationService } from "./workspace-operations.js";
23
+ import { buildExecutionWorkspaceAdapterConfig, gateProjectExecutionWorkspacePolicy, parseIssueExecutionWorkspaceSettings, parseProjectExecutionWorkspacePolicy, resolveExecutionWorkspaceMode, } from "./execution-workspace-policy.js";
24
+ import { instanceSettingsService } from "./instance-settings.js";
25
+ import { redactCurrentUserText, redactCurrentUserValue } from "../log-redaction.js";
26
+ import { hasSessionCompactionThresholds, resolveSessionCompactionPolicy, } from "@paperclipai_dld/adapter-utils";
27
+ const MAX_LIVE_LOG_CHUNK_BYTES = 8 * 1024;
28
+ const HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT = 1;
29
+ const HEARTBEAT_MAX_CONCURRENT_RUNS_MAX = 10;
30
+ const HEARTBEAT_MAX_QUEUED_RUNS_DEFAULT = 5;
31
+ const HEARTBEAT_MAX_QUEUED_RUNS_MAX = 50;
32
+ const DEFERRED_WAKE_CONTEXT_KEY = "_paperclipWakeContext";
33
+ const startLocksByAgent = new Map();
34
+ const REPO_ONLY_CWD_SENTINEL = "/__paperclip_repo_only__";
35
+ const MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS = 10 * 60 * 1000;
36
+ const execFile = promisify(execFileCallback);
37
+ const SESSIONED_LOCAL_ADAPTERS = new Set([
38
+ "claude_local",
39
+ "codex_local",
40
+ "cursor",
41
+ "gemini_local",
42
+ "opencode_local",
43
+ "pi_local",
44
+ ]);
45
+ function deriveRepoNameFromRepoUrl(repoUrl) {
46
+ const trimmed = repoUrl?.trim() ?? "";
47
+ if (!trimmed)
48
+ return null;
49
+ try {
50
+ const parsed = new URL(trimmed);
51
+ const cleanedPath = parsed.pathname.replace(/\/+$/, "");
52
+ const repoName = cleanedPath.split("/").filter(Boolean).pop()?.replace(/\.git$/i, "") ?? "";
53
+ return repoName || null;
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ async function ensureManagedProjectWorkspace(input) {
60
+ const cwd = resolveManagedProjectWorkspaceDir({
61
+ companyId: input.companyId,
62
+ projectId: input.projectId,
63
+ repoName: deriveRepoNameFromRepoUrl(input.repoUrl),
64
+ });
65
+ await fs.mkdir(path.dirname(cwd), { recursive: true });
66
+ const stats = await fs.stat(cwd).catch(() => null);
67
+ if (!input.repoUrl) {
68
+ if (!stats) {
69
+ await fs.mkdir(cwd, { recursive: true });
70
+ }
71
+ return { cwd, warning: null };
72
+ }
73
+ const gitDirExists = await fs
74
+ .stat(path.resolve(cwd, ".git"))
75
+ .then((entry) => entry.isDirectory())
76
+ .catch(() => false);
77
+ if (gitDirExists) {
78
+ return { cwd, warning: null };
79
+ }
80
+ if (stats) {
81
+ const entries = await fs.readdir(cwd).catch(() => []);
82
+ if (entries.length > 0) {
83
+ return {
84
+ cwd,
85
+ warning: `Managed workspace path "${cwd}" already exists but is not a git checkout. Using it as-is.`,
86
+ };
87
+ }
88
+ await fs.rm(cwd, { recursive: true, force: true });
89
+ }
90
+ try {
91
+ await execFile("git", ["clone", input.repoUrl, cwd], {
92
+ env: sanitizeRuntimeServiceBaseEnv(process.env),
93
+ timeout: MANAGED_WORKSPACE_GIT_CLONE_TIMEOUT_MS,
94
+ });
95
+ return { cwd, warning: null };
96
+ }
97
+ catch (error) {
98
+ const reason = error instanceof Error ? error.message : String(error);
99
+ throw new Error(`Failed to prepare managed checkout for "${input.repoUrl}" at "${cwd}": ${reason}`);
100
+ }
101
+ }
102
+ const heartbeatRunListColumns = {
103
+ id: heartbeatRuns.id,
104
+ companyId: heartbeatRuns.companyId,
105
+ agentId: heartbeatRuns.agentId,
106
+ invocationSource: heartbeatRuns.invocationSource,
107
+ triggerDetail: heartbeatRuns.triggerDetail,
108
+ status: heartbeatRuns.status,
109
+ startedAt: heartbeatRuns.startedAt,
110
+ finishedAt: heartbeatRuns.finishedAt,
111
+ error: heartbeatRuns.error,
112
+ wakeupRequestId: heartbeatRuns.wakeupRequestId,
113
+ exitCode: heartbeatRuns.exitCode,
114
+ signal: heartbeatRuns.signal,
115
+ usageJson: heartbeatRuns.usageJson,
116
+ resultJson: heartbeatRuns.resultJson,
117
+ sessionIdBefore: heartbeatRuns.sessionIdBefore,
118
+ sessionIdAfter: heartbeatRuns.sessionIdAfter,
119
+ logStore: heartbeatRuns.logStore,
120
+ logRef: heartbeatRuns.logRef,
121
+ logBytes: heartbeatRuns.logBytes,
122
+ logSha256: heartbeatRuns.logSha256,
123
+ logCompressed: heartbeatRuns.logCompressed,
124
+ stdoutExcerpt: sql `NULL`.as("stdoutExcerpt"),
125
+ stderrExcerpt: sql `NULL`.as("stderrExcerpt"),
126
+ errorCode: heartbeatRuns.errorCode,
127
+ externalRunId: heartbeatRuns.externalRunId,
128
+ contextSnapshot: heartbeatRuns.contextSnapshot,
129
+ createdAt: heartbeatRuns.createdAt,
130
+ updatedAt: heartbeatRuns.updatedAt,
131
+ };
132
+ function appendExcerpt(prev, chunk) {
133
+ return appendWithCap(prev, chunk, MAX_EXCERPT_BYTES);
134
+ }
135
+ function normalizeMaxConcurrentRuns(value) {
136
+ const parsed = Math.floor(asNumber(value, HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT));
137
+ if (!Number.isFinite(parsed))
138
+ return HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT;
139
+ return Math.max(HEARTBEAT_MAX_CONCURRENT_RUNS_DEFAULT, Math.min(HEARTBEAT_MAX_CONCURRENT_RUNS_MAX, parsed));
140
+ }
141
+ export function normalizeMaxQueuedRuns(value) {
142
+ const parsed = Math.floor(asNumber(value, HEARTBEAT_MAX_QUEUED_RUNS_DEFAULT));
143
+ if (!Number.isFinite(parsed))
144
+ return HEARTBEAT_MAX_QUEUED_RUNS_DEFAULT;
145
+ return Math.max(1, Math.min(HEARTBEAT_MAX_QUEUED_RUNS_MAX, parsed));
146
+ }
147
+ export function parseHeartbeatPolicy(agent) {
148
+ const runtimeConfig = parseObject(agent.runtimeConfig);
149
+ const heartbeat = parseObject(runtimeConfig.heartbeat);
150
+ return {
151
+ enabled: asBoolean(heartbeat.enabled, true),
152
+ intervalSec: Math.max(0, asNumber(heartbeat.intervalSec, 0)),
153
+ wakeOnDemand: asBoolean(heartbeat.wakeOnDemand ?? heartbeat.wakeOnAssignment ?? heartbeat.wakeOnOnDemand ?? heartbeat.wakeOnAutomation, true),
154
+ maxConcurrentRuns: normalizeMaxConcurrentRuns(heartbeat.maxConcurrentRuns),
155
+ maxQueuedRuns: normalizeMaxQueuedRuns(heartbeat.maxQueuedRuns),
156
+ skipTimerWhenNoAssignedOpenIssue: heartbeat.skipTimerWhenNoAssignedOpenIssue === true,
157
+ };
158
+ }
159
+ async function withAgentStartLock(agentId, fn) {
160
+ const previous = startLocksByAgent.get(agentId) ?? Promise.resolve();
161
+ const run = previous.then(fn);
162
+ const marker = run.then(() => undefined, () => undefined);
163
+ startLocksByAgent.set(agentId, marker);
164
+ try {
165
+ return await run;
166
+ }
167
+ finally {
168
+ if (startLocksByAgent.get(agentId) === marker) {
169
+ startLocksByAgent.delete(agentId);
170
+ }
171
+ }
172
+ }
173
+ export function prioritizeProjectWorkspaceCandidatesForRun(rows, preferredWorkspaceId) {
174
+ if (!preferredWorkspaceId)
175
+ return rows;
176
+ const preferredIndex = rows.findIndex((row) => row.id === preferredWorkspaceId);
177
+ if (preferredIndex <= 0)
178
+ return rows;
179
+ return [rows[preferredIndex], ...rows.slice(0, preferredIndex), ...rows.slice(preferredIndex + 1)];
180
+ }
181
+ function readNonEmptyString(value) {
182
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
183
+ }
184
+ function normalizeLedgerBillingType(value) {
185
+ const raw = readNonEmptyString(value);
186
+ switch (raw) {
187
+ case "api":
188
+ case "metered_api":
189
+ return "metered_api";
190
+ case "subscription":
191
+ case "subscription_included":
192
+ return "subscription_included";
193
+ case "subscription_overage":
194
+ return "subscription_overage";
195
+ case "credits":
196
+ return "credits";
197
+ case "fixed":
198
+ return "fixed";
199
+ default:
200
+ return "unknown";
201
+ }
202
+ }
203
+ function resolveLedgerBiller(result) {
204
+ return readNonEmptyString(result.biller) ?? readNonEmptyString(result.provider) ?? "unknown";
205
+ }
206
+ function normalizeBilledCostCents(costUsd, billingType) {
207
+ if (billingType === "subscription_included")
208
+ return 0;
209
+ if (typeof costUsd !== "number" || !Number.isFinite(costUsd))
210
+ return 0;
211
+ return Math.max(0, Math.round(costUsd * 100));
212
+ }
213
+ async function resolveLedgerScopeForRun(db, companyId, run) {
214
+ const context = parseObject(run.contextSnapshot);
215
+ const contextIssueId = readNonEmptyString(context.issueId);
216
+ const contextProjectId = readNonEmptyString(context.projectId);
217
+ if (!contextIssueId) {
218
+ return {
219
+ issueId: null,
220
+ projectId: contextProjectId,
221
+ };
222
+ }
223
+ const issue = await db
224
+ .select({
225
+ id: issues.id,
226
+ projectId: issues.projectId,
227
+ })
228
+ .from(issues)
229
+ .where(and(eq(issues.id, contextIssueId), eq(issues.companyId, companyId)))
230
+ .then((rows) => rows[0] ?? null);
231
+ return {
232
+ issueId: issue?.id ?? null,
233
+ projectId: issue?.projectId ?? contextProjectId,
234
+ };
235
+ }
236
+ function normalizeUsageTotals(usage) {
237
+ if (!usage)
238
+ return null;
239
+ return {
240
+ inputTokens: Math.max(0, Math.floor(asNumber(usage.inputTokens, 0))),
241
+ cachedInputTokens: Math.max(0, Math.floor(asNumber(usage.cachedInputTokens, 0))),
242
+ outputTokens: Math.max(0, Math.floor(asNumber(usage.outputTokens, 0))),
243
+ };
244
+ }
245
+ function readRawUsageTotals(usageJson) {
246
+ const parsed = parseObject(usageJson);
247
+ if (Object.keys(parsed).length === 0)
248
+ return null;
249
+ const inputTokens = Math.max(0, Math.floor(asNumber(parsed.rawInputTokens, asNumber(parsed.inputTokens, 0))));
250
+ const cachedInputTokens = Math.max(0, Math.floor(asNumber(parsed.rawCachedInputTokens, asNumber(parsed.cachedInputTokens, 0))));
251
+ const outputTokens = Math.max(0, Math.floor(asNumber(parsed.rawOutputTokens, asNumber(parsed.outputTokens, 0))));
252
+ if (inputTokens <= 0 && cachedInputTokens <= 0 && outputTokens <= 0) {
253
+ return null;
254
+ }
255
+ return {
256
+ inputTokens,
257
+ cachedInputTokens,
258
+ outputTokens,
259
+ };
260
+ }
261
+ function deriveNormalizedUsageDelta(current, previous) {
262
+ if (!current)
263
+ return null;
264
+ if (!previous)
265
+ return { ...current };
266
+ const inputTokens = current.inputTokens >= previous.inputTokens
267
+ ? current.inputTokens - previous.inputTokens
268
+ : current.inputTokens;
269
+ const cachedInputTokens = current.cachedInputTokens >= previous.cachedInputTokens
270
+ ? current.cachedInputTokens - previous.cachedInputTokens
271
+ : current.cachedInputTokens;
272
+ const outputTokens = current.outputTokens >= previous.outputTokens
273
+ ? current.outputTokens - previous.outputTokens
274
+ : current.outputTokens;
275
+ return {
276
+ inputTokens: Math.max(0, inputTokens),
277
+ cachedInputTokens: Math.max(0, cachedInputTokens),
278
+ outputTokens: Math.max(0, outputTokens),
279
+ };
280
+ }
281
+ function formatCount(value) {
282
+ if (typeof value !== "number" || !Number.isFinite(value))
283
+ return "0";
284
+ return value.toLocaleString("en-US");
285
+ }
286
+ export function parseSessionCompactionPolicy(agent) {
287
+ return resolveSessionCompactionPolicy(agent.adapterType, agent.runtimeConfig).policy;
288
+ }
289
+ export function resolveRuntimeSessionParamsForWorkspace(input) {
290
+ const { agentId, previousSessionParams, resolvedWorkspace } = input;
291
+ const previousSessionId = readNonEmptyString(previousSessionParams?.sessionId);
292
+ const previousCwd = readNonEmptyString(previousSessionParams?.cwd);
293
+ if (!previousSessionId || !previousCwd) {
294
+ return {
295
+ sessionParams: previousSessionParams,
296
+ warning: null,
297
+ };
298
+ }
299
+ if (resolvedWorkspace.source !== "project_primary") {
300
+ return {
301
+ sessionParams: previousSessionParams,
302
+ warning: null,
303
+ };
304
+ }
305
+ const projectCwd = readNonEmptyString(resolvedWorkspace.cwd);
306
+ if (!projectCwd) {
307
+ return {
308
+ sessionParams: previousSessionParams,
309
+ warning: null,
310
+ };
311
+ }
312
+ const fallbackAgentHomeCwd = resolveDefaultAgentWorkspaceDir(agentId);
313
+ if (path.resolve(previousCwd) !== path.resolve(fallbackAgentHomeCwd)) {
314
+ return {
315
+ sessionParams: previousSessionParams,
316
+ warning: null,
317
+ };
318
+ }
319
+ if (path.resolve(projectCwd) === path.resolve(previousCwd)) {
320
+ return {
321
+ sessionParams: previousSessionParams,
322
+ warning: null,
323
+ };
324
+ }
325
+ const previousWorkspaceId = readNonEmptyString(previousSessionParams?.workspaceId);
326
+ if (previousWorkspaceId &&
327
+ resolvedWorkspace.workspaceId &&
328
+ previousWorkspaceId !== resolvedWorkspace.workspaceId) {
329
+ return {
330
+ sessionParams: previousSessionParams,
331
+ warning: null,
332
+ };
333
+ }
334
+ const migratedSessionParams = {
335
+ ...(previousSessionParams ?? {}),
336
+ cwd: projectCwd,
337
+ };
338
+ if (resolvedWorkspace.workspaceId)
339
+ migratedSessionParams.workspaceId = resolvedWorkspace.workspaceId;
340
+ if (resolvedWorkspace.repoUrl)
341
+ migratedSessionParams.repoUrl = resolvedWorkspace.repoUrl;
342
+ if (resolvedWorkspace.repoRef)
343
+ migratedSessionParams.repoRef = resolvedWorkspace.repoRef;
344
+ return {
345
+ sessionParams: migratedSessionParams,
346
+ warning: `Project workspace "${projectCwd}" is now available. ` +
347
+ `Attempting to resume session "${previousSessionId}" that was previously saved in fallback workspace "${previousCwd}".`,
348
+ };
349
+ }
350
+ function parseIssueAssigneeAdapterOverrides(raw) {
351
+ const parsed = parseObject(raw);
352
+ const parsedAdapterConfig = parseObject(parsed.adapterConfig);
353
+ const adapterConfig = Object.keys(parsedAdapterConfig).length > 0 ? parsedAdapterConfig : null;
354
+ const useProjectWorkspace = typeof parsed.useProjectWorkspace === "boolean"
355
+ ? parsed.useProjectWorkspace
356
+ : null;
357
+ if (!adapterConfig && useProjectWorkspace === null)
358
+ return null;
359
+ return {
360
+ adapterConfig,
361
+ useProjectWorkspace,
362
+ };
363
+ }
364
+ function deriveTaskKey(contextSnapshot, payload) {
365
+ return (readNonEmptyString(contextSnapshot?.taskKey) ??
366
+ readNonEmptyString(contextSnapshot?.taskId) ??
367
+ readNonEmptyString(contextSnapshot?.issueId) ??
368
+ readNonEmptyString(payload?.taskKey) ??
369
+ readNonEmptyString(payload?.taskId) ??
370
+ readNonEmptyString(payload?.issueId) ??
371
+ null);
372
+ }
373
+ /**
374
+ * Returns true when the agent's runtimeConfig explicitly enables the timer-skip
375
+ * optimization. Intentionally strict: only a literal `true` boolean enables it,
376
+ * so absent or string-truthy values keep the default (disabled) behavior.
377
+ */
378
+ export function isTimerSkipEnabled(runtimeConfig) {
379
+ if (runtimeConfig === null || typeof runtimeConfig !== "object")
380
+ return false;
381
+ const heartbeat = runtimeConfig.heartbeat;
382
+ if (heartbeat === null || typeof heartbeat !== "object")
383
+ return false;
384
+ return heartbeat.skipTimerWhenNoAssignedOpenIssue === true;
385
+ }
386
+ /**
387
+ * Returns true when a timer wake should be skipped for an agent.
388
+ * The flag must be enabled AND the agent must have zero open assigned issues.
389
+ * Callers are responsible for querying the issue count.
390
+ */
391
+ export function shouldSkipTimerWake(runtimeConfig, openIssueCount) {
392
+ if (!isTimerSkipEnabled(runtimeConfig))
393
+ return false;
394
+ return openIssueCount === 0;
395
+ }
396
+ export function shouldResetTaskSessionForWake(contextSnapshot) {
397
+ if (contextSnapshot?.forceFreshSession === true)
398
+ return true;
399
+ const wakeReason = readNonEmptyString(contextSnapshot?.wakeReason);
400
+ if (wakeReason === "issue_assigned")
401
+ return true;
402
+ return false;
403
+ }
404
+ export function formatRuntimeWorkspaceWarningLog(warning) {
405
+ return {
406
+ stream: "stdout",
407
+ chunk: `[paperclip] ${warning}\n`,
408
+ };
409
+ }
410
+ function describeSessionResetReason(contextSnapshot) {
411
+ if (contextSnapshot?.forceFreshSession === true)
412
+ return "forceFreshSession was requested";
413
+ const wakeReason = readNonEmptyString(contextSnapshot?.wakeReason);
414
+ if (wakeReason === "issue_assigned")
415
+ return "wake reason is issue_assigned";
416
+ return null;
417
+ }
418
+ function deriveCommentId(contextSnapshot, payload) {
419
+ return (readNonEmptyString(contextSnapshot?.wakeCommentId) ??
420
+ readNonEmptyString(contextSnapshot?.commentId) ??
421
+ readNonEmptyString(payload?.commentId) ??
422
+ null);
423
+ }
424
+ function enrichWakeContextSnapshot(input) {
425
+ const { contextSnapshot, reason, source, triggerDetail, payload } = input;
426
+ const issueIdFromPayload = readNonEmptyString(payload?.["issueId"]);
427
+ const commentIdFromPayload = readNonEmptyString(payload?.["commentId"]);
428
+ const taskKey = deriveTaskKey(contextSnapshot, payload);
429
+ const wakeCommentId = deriveCommentId(contextSnapshot, payload);
430
+ if (!readNonEmptyString(contextSnapshot["wakeReason"]) && reason) {
431
+ contextSnapshot.wakeReason = reason;
432
+ }
433
+ if (!readNonEmptyString(contextSnapshot["issueId"]) && issueIdFromPayload) {
434
+ contextSnapshot.issueId = issueIdFromPayload;
435
+ }
436
+ if (!readNonEmptyString(contextSnapshot["taskId"]) && issueIdFromPayload) {
437
+ contextSnapshot.taskId = issueIdFromPayload;
438
+ }
439
+ if (!readNonEmptyString(contextSnapshot["taskKey"]) && taskKey) {
440
+ contextSnapshot.taskKey = taskKey;
441
+ }
442
+ if (!readNonEmptyString(contextSnapshot["commentId"]) && commentIdFromPayload) {
443
+ contextSnapshot.commentId = commentIdFromPayload;
444
+ }
445
+ if (!readNonEmptyString(contextSnapshot["wakeCommentId"]) && wakeCommentId) {
446
+ contextSnapshot.wakeCommentId = wakeCommentId;
447
+ }
448
+ if (!readNonEmptyString(contextSnapshot["wakeSource"]) && source) {
449
+ contextSnapshot.wakeSource = source;
450
+ }
451
+ if (!readNonEmptyString(contextSnapshot["wakeTriggerDetail"]) && triggerDetail) {
452
+ contextSnapshot.wakeTriggerDetail = triggerDetail;
453
+ }
454
+ return {
455
+ contextSnapshot,
456
+ issueIdFromPayload,
457
+ commentIdFromPayload,
458
+ taskKey,
459
+ wakeCommentId,
460
+ };
461
+ }
462
+ function mergeCoalescedContextSnapshot(existingRaw, incoming) {
463
+ const existing = parseObject(existingRaw);
464
+ const merged = {
465
+ ...existing,
466
+ ...incoming,
467
+ };
468
+ const commentId = deriveCommentId(incoming, null);
469
+ if (commentId) {
470
+ merged.commentId = commentId;
471
+ merged.wakeCommentId = commentId;
472
+ }
473
+ return merged;
474
+ }
475
+ function runTaskKey(run) {
476
+ return deriveTaskKey(run.contextSnapshot, null);
477
+ }
478
+ function isSameTaskScope(left, right) {
479
+ return (left ?? null) === (right ?? null);
480
+ }
481
+ function truncateDisplayId(value, max = 128) {
482
+ if (!value)
483
+ return null;
484
+ return value.length > max ? value.slice(0, max) : value;
485
+ }
486
+ function normalizeAgentNameKey(value) {
487
+ if (typeof value !== "string")
488
+ return null;
489
+ const normalized = value.trim().toLowerCase();
490
+ return normalized.length > 0 ? normalized : null;
491
+ }
492
+ const defaultSessionCodec = {
493
+ deserialize(raw) {
494
+ const asObj = parseObject(raw);
495
+ if (Object.keys(asObj).length > 0)
496
+ return asObj;
497
+ const sessionId = readNonEmptyString(raw?.sessionId);
498
+ if (sessionId)
499
+ return { sessionId };
500
+ return null;
501
+ },
502
+ serialize(params) {
503
+ if (!params || Object.keys(params).length === 0)
504
+ return null;
505
+ return params;
506
+ },
507
+ getDisplayId(params) {
508
+ return readNonEmptyString(params?.sessionId);
509
+ },
510
+ };
511
+ function getAdapterSessionCodec(adapterType) {
512
+ const adapter = getServerAdapter(adapterType);
513
+ return adapter.sessionCodec ?? defaultSessionCodec;
514
+ }
515
+ function normalizeSessionParams(params) {
516
+ if (!params)
517
+ return null;
518
+ return Object.keys(params).length > 0 ? params : null;
519
+ }
520
+ function resolveNextSessionState(input) {
521
+ const { codec, adapterResult, previousParams, previousDisplayId, previousLegacySessionId } = input;
522
+ if (adapterResult.clearSession) {
523
+ return {
524
+ params: null,
525
+ displayId: null,
526
+ legacySessionId: null,
527
+ };
528
+ }
529
+ const explicitParams = adapterResult.sessionParams;
530
+ const hasExplicitParams = adapterResult.sessionParams !== undefined;
531
+ const hasExplicitSessionId = adapterResult.sessionId !== undefined;
532
+ const explicitSessionId = readNonEmptyString(adapterResult.sessionId);
533
+ const hasExplicitDisplay = adapterResult.sessionDisplayId !== undefined;
534
+ const explicitDisplayId = readNonEmptyString(adapterResult.sessionDisplayId);
535
+ const shouldUsePrevious = !hasExplicitParams && !hasExplicitSessionId && !hasExplicitDisplay;
536
+ const candidateParams = hasExplicitParams
537
+ ? explicitParams
538
+ : hasExplicitSessionId
539
+ ? (explicitSessionId ? { sessionId: explicitSessionId } : null)
540
+ : previousParams;
541
+ const serialized = normalizeSessionParams(codec.serialize(normalizeSessionParams(candidateParams) ?? null));
542
+ const deserialized = normalizeSessionParams(codec.deserialize(serialized));
543
+ const displayId = truncateDisplayId(explicitDisplayId ??
544
+ (codec.getDisplayId ? codec.getDisplayId(deserialized) : null) ??
545
+ readNonEmptyString(deserialized?.sessionId) ??
546
+ (shouldUsePrevious ? previousDisplayId : null) ??
547
+ explicitSessionId ??
548
+ (shouldUsePrevious ? previousLegacySessionId : null));
549
+ const legacySessionId = explicitSessionId ??
550
+ readNonEmptyString(deserialized?.sessionId) ??
551
+ displayId ??
552
+ (shouldUsePrevious ? previousLegacySessionId : null);
553
+ return {
554
+ params: serialized,
555
+ displayId,
556
+ legacySessionId,
557
+ };
558
+ }
559
+ export function heartbeatService(db) {
560
+ const instanceSettings = instanceSettingsService(db);
561
+ const runLogStore = getRunLogStore();
562
+ const secretsSvc = secretService(db);
563
+ const issuesSvc = issueService(db);
564
+ const executionWorkspacesSvc = executionWorkspaceService(db);
565
+ const workspaceOperationsSvc = workspaceOperationService(db);
566
+ const activeRunExecutions = new Set();
567
+ const budgetHooks = {
568
+ cancelWorkForScope: cancelBudgetScopeWork,
569
+ };
570
+ const budgets = budgetService(db, budgetHooks);
571
+ async function getAgent(agentId) {
572
+ return db
573
+ .select()
574
+ .from(agents)
575
+ .where(eq(agents.id, agentId))
576
+ .then((rows) => rows[0] ?? null);
577
+ }
578
+ async function getRun(runId) {
579
+ return db
580
+ .select()
581
+ .from(heartbeatRuns)
582
+ .where(eq(heartbeatRuns.id, runId))
583
+ .then((rows) => rows[0] ?? null);
584
+ }
585
+ async function getRuntimeState(agentId) {
586
+ return db
587
+ .select()
588
+ .from(agentRuntimeState)
589
+ .where(eq(agentRuntimeState.agentId, agentId))
590
+ .then((rows) => rows[0] ?? null);
591
+ }
592
+ async function getTaskSession(companyId, agentId, adapterType, taskKey) {
593
+ return db
594
+ .select()
595
+ .from(agentTaskSessions)
596
+ .where(and(eq(agentTaskSessions.companyId, companyId), eq(agentTaskSessions.agentId, agentId), eq(agentTaskSessions.adapterType, adapterType), eq(agentTaskSessions.taskKey, taskKey)))
597
+ .then((rows) => rows[0] ?? null);
598
+ }
599
+ async function getLatestRunForSession(agentId, sessionId, opts) {
600
+ const conditions = [
601
+ eq(heartbeatRuns.agentId, agentId),
602
+ eq(heartbeatRuns.sessionIdAfter, sessionId),
603
+ ];
604
+ if (opts?.excludeRunId) {
605
+ conditions.push(sql `${heartbeatRuns.id} <> ${opts.excludeRunId}`);
606
+ }
607
+ return db
608
+ .select()
609
+ .from(heartbeatRuns)
610
+ .where(and(...conditions))
611
+ .orderBy(desc(heartbeatRuns.createdAt))
612
+ .limit(1)
613
+ .then((rows) => rows[0] ?? null);
614
+ }
615
+ async function getOldestRunForSession(agentId, sessionId) {
616
+ return db
617
+ .select({
618
+ id: heartbeatRuns.id,
619
+ createdAt: heartbeatRuns.createdAt,
620
+ })
621
+ .from(heartbeatRuns)
622
+ .where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.sessionIdAfter, sessionId)))
623
+ .orderBy(asc(heartbeatRuns.createdAt), asc(heartbeatRuns.id))
624
+ .limit(1)
625
+ .then((rows) => rows[0] ?? null);
626
+ }
627
+ async function resolveNormalizedUsageForSession(input) {
628
+ const { agentId, runId, sessionId, rawUsage } = input;
629
+ if (!sessionId || !rawUsage) {
630
+ return {
631
+ normalizedUsage: rawUsage,
632
+ previousRawUsage: null,
633
+ derivedFromSessionTotals: false,
634
+ };
635
+ }
636
+ const previousRun = await getLatestRunForSession(agentId, sessionId, { excludeRunId: runId });
637
+ const previousRawUsage = readRawUsageTotals(previousRun?.usageJson);
638
+ return {
639
+ normalizedUsage: deriveNormalizedUsageDelta(rawUsage, previousRawUsage),
640
+ previousRawUsage,
641
+ derivedFromSessionTotals: previousRawUsage !== null,
642
+ };
643
+ }
644
+ async function evaluateSessionCompaction(input) {
645
+ const { agent, sessionId, issueId } = input;
646
+ if (!sessionId) {
647
+ return {
648
+ rotate: false,
649
+ reason: null,
650
+ handoffMarkdown: null,
651
+ previousRunId: null,
652
+ };
653
+ }
654
+ const policy = parseSessionCompactionPolicy(agent);
655
+ if (!policy.enabled || !hasSessionCompactionThresholds(policy)) {
656
+ return {
657
+ rotate: false,
658
+ reason: null,
659
+ handoffMarkdown: null,
660
+ previousRunId: null,
661
+ };
662
+ }
663
+ const fetchLimit = Math.max(policy.maxSessionRuns > 0 ? policy.maxSessionRuns + 1 : 0, 4);
664
+ const runs = await db
665
+ .select({
666
+ id: heartbeatRuns.id,
667
+ createdAt: heartbeatRuns.createdAt,
668
+ usageJson: heartbeatRuns.usageJson,
669
+ resultJson: heartbeatRuns.resultJson,
670
+ error: heartbeatRuns.error,
671
+ })
672
+ .from(heartbeatRuns)
673
+ .where(and(eq(heartbeatRuns.agentId, agent.id), eq(heartbeatRuns.sessionIdAfter, sessionId)))
674
+ .orderBy(desc(heartbeatRuns.createdAt))
675
+ .limit(fetchLimit);
676
+ if (runs.length === 0) {
677
+ return {
678
+ rotate: false,
679
+ reason: null,
680
+ handoffMarkdown: null,
681
+ previousRunId: null,
682
+ };
683
+ }
684
+ const latestRun = runs[0] ?? null;
685
+ const oldestRun = policy.maxSessionAgeHours > 0
686
+ ? await getOldestRunForSession(agent.id, sessionId)
687
+ : runs[runs.length - 1] ?? latestRun;
688
+ const latestRawUsage = readRawUsageTotals(latestRun?.usageJson);
689
+ const sessionAgeHours = latestRun && oldestRun
690
+ ? Math.max(0, (new Date(latestRun.createdAt).getTime() - new Date(oldestRun.createdAt).getTime()) / (1000 * 60 * 60))
691
+ : 0;
692
+ let reason = null;
693
+ if (policy.maxSessionRuns > 0 && runs.length > policy.maxSessionRuns) {
694
+ reason = `session exceeded ${policy.maxSessionRuns} runs`;
695
+ }
696
+ else if (policy.maxRawInputTokens > 0 &&
697
+ latestRawUsage &&
698
+ latestRawUsage.inputTokens >= policy.maxRawInputTokens) {
699
+ reason =
700
+ `session raw input reached ${formatCount(latestRawUsage.inputTokens)} tokens ` +
701
+ `(threshold ${formatCount(policy.maxRawInputTokens)})`;
702
+ }
703
+ else if (policy.maxSessionAgeHours > 0 && sessionAgeHours >= policy.maxSessionAgeHours) {
704
+ reason = `session age reached ${Math.floor(sessionAgeHours)} hours`;
705
+ }
706
+ if (!reason || !latestRun) {
707
+ return {
708
+ rotate: false,
709
+ reason: null,
710
+ handoffMarkdown: null,
711
+ previousRunId: latestRun?.id ?? null,
712
+ };
713
+ }
714
+ const latestSummary = summarizeHeartbeatRunResultJson(latestRun.resultJson);
715
+ const latestTextSummary = readNonEmptyString(latestSummary?.summary) ??
716
+ readNonEmptyString(latestSummary?.result) ??
717
+ readNonEmptyString(latestSummary?.message) ??
718
+ readNonEmptyString(latestRun.error);
719
+ const handoffMarkdown = [
720
+ "Paperclip session handoff:",
721
+ `- Previous session: ${sessionId}`,
722
+ issueId ? `- Issue: ${issueId}` : "",
723
+ `- Rotation reason: ${reason}`,
724
+ latestTextSummary ? `- Last run summary: ${latestTextSummary}` : "",
725
+ "Continue from the current task state. Rebuild only the minimum context you need.",
726
+ ]
727
+ .filter(Boolean)
728
+ .join("\n");
729
+ return {
730
+ rotate: true,
731
+ reason,
732
+ handoffMarkdown,
733
+ previousRunId: latestRun.id,
734
+ };
735
+ }
736
+ async function resolveSessionBeforeForWakeup(agent, taskKey) {
737
+ if (taskKey) {
738
+ const codec = getAdapterSessionCodec(agent.adapterType);
739
+ const existingTaskSession = await getTaskSession(agent.companyId, agent.id, agent.adapterType, taskKey);
740
+ const parsedParams = normalizeSessionParams(codec.deserialize(existingTaskSession?.sessionParamsJson ?? null));
741
+ return truncateDisplayId(existingTaskSession?.sessionDisplayId ??
742
+ (codec.getDisplayId ? codec.getDisplayId(parsedParams) : null) ??
743
+ readNonEmptyString(parsedParams?.sessionId));
744
+ }
745
+ const runtimeForRun = await getRuntimeState(agent.id);
746
+ return runtimeForRun?.sessionId ?? null;
747
+ }
748
+ async function resolveWorkspaceForRun(agent, context, previousSessionParams, opts) {
749
+ const issueId = readNonEmptyString(context.issueId);
750
+ const contextProjectId = readNonEmptyString(context.projectId);
751
+ const contextProjectWorkspaceId = readNonEmptyString(context.projectWorkspaceId);
752
+ const issueProjectRef = issueId
753
+ ? await db
754
+ .select({
755
+ projectId: issues.projectId,
756
+ projectWorkspaceId: issues.projectWorkspaceId,
757
+ })
758
+ .from(issues)
759
+ .where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId)))
760
+ .then((rows) => rows[0] ?? null)
761
+ : null;
762
+ const issueProjectId = issueProjectRef?.projectId ?? null;
763
+ const preferredProjectWorkspaceId = issueProjectRef?.projectWorkspaceId ?? contextProjectWorkspaceId ?? null;
764
+ const resolvedProjectId = issueProjectId ?? contextProjectId;
765
+ const useProjectWorkspace = opts?.useProjectWorkspace !== false;
766
+ const workspaceProjectId = useProjectWorkspace ? resolvedProjectId : null;
767
+ const unorderedProjectWorkspaceRows = workspaceProjectId
768
+ ? await db
769
+ .select()
770
+ .from(projectWorkspaces)
771
+ .where(and(eq(projectWorkspaces.companyId, agent.companyId), eq(projectWorkspaces.projectId, workspaceProjectId)))
772
+ .orderBy(asc(projectWorkspaces.createdAt), asc(projectWorkspaces.id))
773
+ : [];
774
+ const projectWorkspaceRows = prioritizeProjectWorkspaceCandidatesForRun(unorderedProjectWorkspaceRows, preferredProjectWorkspaceId);
775
+ const workspaceHints = projectWorkspaceRows.map((workspace) => ({
776
+ workspaceId: workspace.id,
777
+ cwd: readNonEmptyString(workspace.cwd),
778
+ repoUrl: readNonEmptyString(workspace.repoUrl),
779
+ repoRef: readNonEmptyString(workspace.repoRef),
780
+ }));
781
+ if (projectWorkspaceRows.length > 0) {
782
+ const preferredWorkspace = preferredProjectWorkspaceId
783
+ ? projectWorkspaceRows.find((workspace) => workspace.id === preferredProjectWorkspaceId) ?? null
784
+ : null;
785
+ const missingProjectCwds = [];
786
+ let hasConfiguredProjectCwd = false;
787
+ let preferredWorkspaceWarning = null;
788
+ if (preferredProjectWorkspaceId && !preferredWorkspace) {
789
+ preferredWorkspaceWarning =
790
+ `Selected project workspace "${preferredProjectWorkspaceId}" is not available on this project.`;
791
+ }
792
+ for (const workspace of projectWorkspaceRows) {
793
+ let projectCwd = readNonEmptyString(workspace.cwd);
794
+ let managedWorkspaceWarning = null;
795
+ if (!projectCwd || projectCwd === REPO_ONLY_CWD_SENTINEL) {
796
+ try {
797
+ const managedWorkspace = await ensureManagedProjectWorkspace({
798
+ companyId: agent.companyId,
799
+ projectId: workspaceProjectId ?? resolvedProjectId ?? workspace.projectId,
800
+ repoUrl: readNonEmptyString(workspace.repoUrl),
801
+ });
802
+ projectCwd = managedWorkspace.cwd;
803
+ managedWorkspaceWarning = managedWorkspace.warning;
804
+ }
805
+ catch (error) {
806
+ if (preferredWorkspace?.id === workspace.id) {
807
+ preferredWorkspaceWarning = error instanceof Error ? error.message : String(error);
808
+ }
809
+ continue;
810
+ }
811
+ }
812
+ hasConfiguredProjectCwd = true;
813
+ const projectCwdExists = await fs
814
+ .stat(projectCwd)
815
+ .then((stats) => stats.isDirectory())
816
+ .catch(() => false);
817
+ if (projectCwdExists) {
818
+ return {
819
+ cwd: projectCwd,
820
+ source: "project_primary",
821
+ projectId: resolvedProjectId,
822
+ workspaceId: workspace.id,
823
+ repoUrl: workspace.repoUrl,
824
+ repoRef: workspace.repoRef,
825
+ workspaceHints,
826
+ warnings: [preferredWorkspaceWarning, managedWorkspaceWarning].filter((value) => Boolean(value)),
827
+ };
828
+ }
829
+ if (preferredWorkspace?.id === workspace.id) {
830
+ preferredWorkspaceWarning =
831
+ `Selected project workspace path "${projectCwd}" is not available yet.`;
832
+ }
833
+ missingProjectCwds.push(projectCwd);
834
+ }
835
+ const fallbackCwd = resolveDefaultAgentWorkspaceDir(agent.id);
836
+ await fs.mkdir(fallbackCwd, { recursive: true });
837
+ const warnings = [];
838
+ if (preferredWorkspaceWarning) {
839
+ warnings.push(preferredWorkspaceWarning);
840
+ }
841
+ if (missingProjectCwds.length > 0) {
842
+ const firstMissing = missingProjectCwds[0];
843
+ const extraMissingCount = Math.max(0, missingProjectCwds.length - 1);
844
+ warnings.push(extraMissingCount > 0
845
+ ? `Project workspace path "${firstMissing}" and ${extraMissingCount} other configured path(s) are not available yet. Using fallback workspace "${fallbackCwd}" for this run.`
846
+ : `Project workspace path "${firstMissing}" is not available yet. Using fallback workspace "${fallbackCwd}" for this run.`);
847
+ }
848
+ else if (!hasConfiguredProjectCwd) {
849
+ warnings.push(`Project workspace has no local cwd configured. Using fallback workspace "${fallbackCwd}" for this run.`);
850
+ }
851
+ return {
852
+ cwd: fallbackCwd,
853
+ source: "project_primary",
854
+ projectId: resolvedProjectId,
855
+ workspaceId: projectWorkspaceRows[0]?.id ?? null,
856
+ repoUrl: projectWorkspaceRows[0]?.repoUrl ?? null,
857
+ repoRef: projectWorkspaceRows[0]?.repoRef ?? null,
858
+ workspaceHints,
859
+ warnings,
860
+ };
861
+ }
862
+ if (workspaceProjectId) {
863
+ const managedWorkspace = await ensureManagedProjectWorkspace({
864
+ companyId: agent.companyId,
865
+ projectId: workspaceProjectId,
866
+ repoUrl: null,
867
+ });
868
+ return {
869
+ cwd: managedWorkspace.cwd,
870
+ source: "project_primary",
871
+ projectId: resolvedProjectId,
872
+ workspaceId: null,
873
+ repoUrl: null,
874
+ repoRef: null,
875
+ workspaceHints,
876
+ warnings: managedWorkspace.warning ? [managedWorkspace.warning] : [],
877
+ };
878
+ }
879
+ const sessionCwd = readNonEmptyString(previousSessionParams?.cwd);
880
+ if (sessionCwd) {
881
+ const sessionCwdExists = await fs
882
+ .stat(sessionCwd)
883
+ .then((stats) => stats.isDirectory())
884
+ .catch(() => false);
885
+ if (sessionCwdExists) {
886
+ return {
887
+ cwd: sessionCwd,
888
+ source: "task_session",
889
+ projectId: resolvedProjectId,
890
+ workspaceId: readNonEmptyString(previousSessionParams?.workspaceId),
891
+ repoUrl: readNonEmptyString(previousSessionParams?.repoUrl),
892
+ repoRef: readNonEmptyString(previousSessionParams?.repoRef),
893
+ workspaceHints,
894
+ warnings: [],
895
+ };
896
+ }
897
+ }
898
+ const cwd = resolveDefaultAgentWorkspaceDir(agent.id);
899
+ await fs.mkdir(cwd, { recursive: true });
900
+ const warnings = [];
901
+ if (sessionCwd) {
902
+ warnings.push(`Saved session workspace "${sessionCwd}" is not available. Using fallback workspace "${cwd}" for this run.`);
903
+ }
904
+ else if (resolvedProjectId) {
905
+ warnings.push(`No project workspace directory is currently available for this issue. Using fallback workspace "${cwd}" for this run.`);
906
+ }
907
+ else {
908
+ warnings.push(`No project or prior session workspace was available. Using fallback workspace "${cwd}" for this run.`);
909
+ }
910
+ return {
911
+ cwd,
912
+ source: "agent_home",
913
+ projectId: resolvedProjectId,
914
+ workspaceId: null,
915
+ repoUrl: null,
916
+ repoRef: null,
917
+ workspaceHints,
918
+ warnings,
919
+ };
920
+ }
921
+ async function upsertTaskSession(input) {
922
+ const existing = await getTaskSession(input.companyId, input.agentId, input.adapterType, input.taskKey);
923
+ if (existing) {
924
+ return db
925
+ .update(agentTaskSessions)
926
+ .set({
927
+ sessionParamsJson: input.sessionParamsJson,
928
+ sessionDisplayId: input.sessionDisplayId,
929
+ lastRunId: input.lastRunId,
930
+ lastError: input.lastError,
931
+ updatedAt: new Date(),
932
+ })
933
+ .where(eq(agentTaskSessions.id, existing.id))
934
+ .returning()
935
+ .then((rows) => rows[0] ?? null);
936
+ }
937
+ return db
938
+ .insert(agentTaskSessions)
939
+ .values({
940
+ companyId: input.companyId,
941
+ agentId: input.agentId,
942
+ adapterType: input.adapterType,
943
+ taskKey: input.taskKey,
944
+ sessionParamsJson: input.sessionParamsJson,
945
+ sessionDisplayId: input.sessionDisplayId,
946
+ lastRunId: input.lastRunId,
947
+ lastError: input.lastError,
948
+ })
949
+ .returning()
950
+ .then((rows) => rows[0] ?? null);
951
+ }
952
+ async function clearTaskSessions(companyId, agentId, opts) {
953
+ const conditions = [
954
+ eq(agentTaskSessions.companyId, companyId),
955
+ eq(agentTaskSessions.agentId, agentId),
956
+ ];
957
+ if (opts?.taskKey) {
958
+ conditions.push(eq(agentTaskSessions.taskKey, opts.taskKey));
959
+ }
960
+ if (opts?.adapterType) {
961
+ conditions.push(eq(agentTaskSessions.adapterType, opts.adapterType));
962
+ }
963
+ return db
964
+ .delete(agentTaskSessions)
965
+ .where(and(...conditions))
966
+ .returning()
967
+ .then((rows) => rows.length);
968
+ }
969
+ async function ensureRuntimeState(agent) {
970
+ const existing = await getRuntimeState(agent.id);
971
+ if (existing)
972
+ return existing;
973
+ return db
974
+ .insert(agentRuntimeState)
975
+ .values({
976
+ agentId: agent.id,
977
+ companyId: agent.companyId,
978
+ adapterType: agent.adapterType,
979
+ stateJson: {},
980
+ })
981
+ .returning()
982
+ .then((rows) => rows[0]);
983
+ }
984
+ async function setRunStatus(runId, status, patch) {
985
+ const updated = await db
986
+ .update(heartbeatRuns)
987
+ .set({ status, ...patch, updatedAt: new Date() })
988
+ .where(eq(heartbeatRuns.id, runId))
989
+ .returning()
990
+ .then((rows) => rows[0] ?? null);
991
+ if (updated) {
992
+ publishLiveEvent({
993
+ companyId: updated.companyId,
994
+ type: "heartbeat.run.status",
995
+ payload: {
996
+ runId: updated.id,
997
+ agentId: updated.agentId,
998
+ status: updated.status,
999
+ invocationSource: updated.invocationSource,
1000
+ triggerDetail: updated.triggerDetail,
1001
+ error: updated.error ?? null,
1002
+ errorCode: updated.errorCode ?? null,
1003
+ startedAt: updated.startedAt ? new Date(updated.startedAt).toISOString() : null,
1004
+ finishedAt: updated.finishedAt ? new Date(updated.finishedAt).toISOString() : null,
1005
+ },
1006
+ });
1007
+ }
1008
+ return updated;
1009
+ }
1010
+ async function setWakeupStatus(wakeupRequestId, status, patch) {
1011
+ if (!wakeupRequestId)
1012
+ return;
1013
+ await db
1014
+ .update(agentWakeupRequests)
1015
+ .set({ status, ...patch, updatedAt: new Date() })
1016
+ .where(eq(agentWakeupRequests.id, wakeupRequestId));
1017
+ }
1018
+ async function appendRunEvent(run, seq, event) {
1019
+ const sanitizedMessage = event.message ? redactCurrentUserText(event.message) : event.message;
1020
+ const sanitizedPayload = event.payload ? redactCurrentUserValue(event.payload) : event.payload;
1021
+ await db.insert(heartbeatRunEvents).values({
1022
+ companyId: run.companyId,
1023
+ runId: run.id,
1024
+ agentId: run.agentId,
1025
+ seq,
1026
+ eventType: event.eventType,
1027
+ stream: event.stream,
1028
+ level: event.level,
1029
+ color: event.color,
1030
+ message: sanitizedMessage,
1031
+ payload: sanitizedPayload,
1032
+ });
1033
+ publishLiveEvent({
1034
+ companyId: run.companyId,
1035
+ type: "heartbeat.run.event",
1036
+ payload: {
1037
+ runId: run.id,
1038
+ agentId: run.agentId,
1039
+ seq,
1040
+ eventType: event.eventType,
1041
+ stream: event.stream ?? null,
1042
+ level: event.level ?? null,
1043
+ color: event.color ?? null,
1044
+ message: sanitizedMessage ?? null,
1045
+ payload: sanitizedPayload ?? null,
1046
+ },
1047
+ });
1048
+ }
1049
+ async function countRunningRunsForAgent(agentId) {
1050
+ const [{ count }] = await db
1051
+ .select({ count: sql `count(*)` })
1052
+ .from(heartbeatRuns)
1053
+ .where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.status, "running")));
1054
+ return Number(count ?? 0);
1055
+ }
1056
+ async function canEnqueueRun(agent) {
1057
+ const policy = parseHeartbeatPolicy(agent);
1058
+ const [result] = await db
1059
+ .select({ count: sql `count(*)::int` })
1060
+ .from(heartbeatRuns)
1061
+ .where(and(eq(heartbeatRuns.agentId, agent.id), eq(heartbeatRuns.status, "queued")));
1062
+ const queuedCount = Number(result?.count ?? 0);
1063
+ return {
1064
+ policy,
1065
+ queuedCount,
1066
+ allowed: queuedCount < policy.maxQueuedRuns,
1067
+ };
1068
+ }
1069
+ async function claimQueuedRun(run) {
1070
+ if (run.status !== "queued")
1071
+ return run;
1072
+ const agent = await getAgent(run.agentId);
1073
+ if (!agent) {
1074
+ await cancelRunInternal(run.id, "Cancelled because the agent no longer exists");
1075
+ return null;
1076
+ }
1077
+ if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") {
1078
+ await cancelRunInternal(run.id, "Cancelled because the agent is not invokable");
1079
+ return null;
1080
+ }
1081
+ const context = parseObject(run.contextSnapshot);
1082
+ const budgetBlock = await budgets.getInvocationBlock(run.companyId, run.agentId, {
1083
+ issueId: readNonEmptyString(context.issueId),
1084
+ projectId: readNonEmptyString(context.projectId),
1085
+ });
1086
+ if (budgetBlock) {
1087
+ await cancelRunInternal(run.id, budgetBlock.reason);
1088
+ return null;
1089
+ }
1090
+ const claimedAt = new Date();
1091
+ const claimed = await db
1092
+ .update(heartbeatRuns)
1093
+ .set({
1094
+ status: "running",
1095
+ startedAt: run.startedAt ?? claimedAt,
1096
+ updatedAt: claimedAt,
1097
+ })
1098
+ .where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.status, "queued")))
1099
+ .returning()
1100
+ .then((rows) => rows[0] ?? null);
1101
+ if (!claimed)
1102
+ return null;
1103
+ publishLiveEvent({
1104
+ companyId: claimed.companyId,
1105
+ type: "heartbeat.run.status",
1106
+ payload: {
1107
+ runId: claimed.id,
1108
+ agentId: claimed.agentId,
1109
+ status: claimed.status,
1110
+ invocationSource: claimed.invocationSource,
1111
+ triggerDetail: claimed.triggerDetail,
1112
+ error: claimed.error ?? null,
1113
+ errorCode: claimed.errorCode ?? null,
1114
+ startedAt: claimed.startedAt ? new Date(claimed.startedAt).toISOString() : null,
1115
+ finishedAt: claimed.finishedAt ? new Date(claimed.finishedAt).toISOString() : null,
1116
+ },
1117
+ });
1118
+ await setWakeupStatus(claimed.wakeupRequestId, "claimed", { claimedAt });
1119
+ return claimed;
1120
+ }
1121
+ async function finalizeAgentStatus(agentId, outcome) {
1122
+ const existing = await getAgent(agentId);
1123
+ if (!existing)
1124
+ return;
1125
+ if (existing.status === "paused" || existing.status === "terminated") {
1126
+ return;
1127
+ }
1128
+ const runningCount = await countRunningRunsForAgent(agentId);
1129
+ const nextStatus = runningCount > 0
1130
+ ? "running"
1131
+ : outcome === "succeeded" || outcome === "cancelled"
1132
+ ? "idle"
1133
+ : "error";
1134
+ const updated = await db
1135
+ .update(agents)
1136
+ .set({
1137
+ status: nextStatus,
1138
+ lastHeartbeatAt: new Date(),
1139
+ updatedAt: new Date(),
1140
+ })
1141
+ .where(eq(agents.id, agentId))
1142
+ .returning()
1143
+ .then((rows) => rows[0] ?? null);
1144
+ if (updated) {
1145
+ publishLiveEvent({
1146
+ companyId: updated.companyId,
1147
+ type: "agent.status",
1148
+ payload: {
1149
+ agentId: updated.id,
1150
+ status: updated.status,
1151
+ lastHeartbeatAt: updated.lastHeartbeatAt
1152
+ ? new Date(updated.lastHeartbeatAt).toISOString()
1153
+ : null,
1154
+ outcome,
1155
+ },
1156
+ });
1157
+ }
1158
+ }
1159
+ async function reapOrphanedRuns(opts) {
1160
+ const staleThresholdMs = opts?.staleThresholdMs ?? 0;
1161
+ const now = new Date();
1162
+ // Find all runs stuck in "running" state (queued runs are legitimately waiting; resumeQueuedRuns handles them)
1163
+ const activeRuns = await db
1164
+ .select()
1165
+ .from(heartbeatRuns)
1166
+ .where(eq(heartbeatRuns.status, "running"));
1167
+ const reaped = [];
1168
+ for (const run of activeRuns) {
1169
+ if (runningProcesses.has(run.id) || activeRunExecutions.has(run.id))
1170
+ continue;
1171
+ // Apply staleness threshold to avoid false positives
1172
+ if (staleThresholdMs > 0) {
1173
+ const refTime = run.updatedAt ? new Date(run.updatedAt).getTime() : 0;
1174
+ if (now.getTime() - refTime < staleThresholdMs)
1175
+ continue;
1176
+ }
1177
+ await setRunStatus(run.id, "failed", {
1178
+ error: "Process lost -- server may have restarted",
1179
+ errorCode: "process_lost",
1180
+ finishedAt: now,
1181
+ });
1182
+ await setWakeupStatus(run.wakeupRequestId, "failed", {
1183
+ finishedAt: now,
1184
+ error: "Process lost -- server may have restarted",
1185
+ });
1186
+ const updatedRun = await getRun(run.id);
1187
+ if (updatedRun) {
1188
+ await appendRunEvent(updatedRun, 1, {
1189
+ eventType: "lifecycle",
1190
+ stream: "system",
1191
+ level: "error",
1192
+ message: "Process lost -- server may have restarted",
1193
+ });
1194
+ await releaseIssueExecutionAndPromote(updatedRun);
1195
+ }
1196
+ await finalizeAgentStatus(run.agentId, "failed");
1197
+ await startNextQueuedRunForAgent(run.agentId);
1198
+ runningProcesses.delete(run.id);
1199
+ reaped.push(run.id);
1200
+ }
1201
+ if (reaped.length > 0) {
1202
+ logger.warn({ reapedCount: reaped.length, runIds: reaped }, "reaped orphaned heartbeat runs");
1203
+ }
1204
+ return { reaped: reaped.length, runIds: reaped };
1205
+ }
1206
+ /**
1207
+ * Scan procfs on Linux for processes whose cmdline references a
1208
+ * workspace path belonging to a recently finished run and kill them.
1209
+ *
1210
+ * This catches grandchild processes (e.g. vitest workers, language servers)
1211
+ * that were reparented to PID 1 after cursor-agent exited naturally.
1212
+ * Guard: only active on Linux, no-op elsewhere.
1213
+ */
1214
+ async function reapOrphanedWorkspaceProcesses() {
1215
+ if (process.platform !== "linux")
1216
+ return { killed: 0 };
1217
+ const candidates = Array.from(finishedWorkspacePaths.entries()).filter(([, v]) => Date.now() - v.finishedAt.getTime() < FINISHED_WORKSPACE_PATH_RETENTION_MS);
1218
+ if (candidates.length === 0)
1219
+ return { killed: 0 };
1220
+ let killed = 0;
1221
+ let procEntries = [];
1222
+ try {
1223
+ procEntries = await fs.readdir("/proc");
1224
+ }
1225
+ catch {
1226
+ return { killed: 0 };
1227
+ }
1228
+ for (const entry of procEntries) {
1229
+ if (!/^\d+$/.test(entry))
1230
+ continue;
1231
+ const pid = Number(entry);
1232
+ let cmdline = "";
1233
+ try {
1234
+ const raw = await fs.readFile(`/proc/${entry}/cmdline`, "utf8");
1235
+ cmdline = raw.replace(/\0/g, " ").trim();
1236
+ }
1237
+ catch {
1238
+ continue;
1239
+ }
1240
+ for (const [runId, { workspacePath }] of candidates) {
1241
+ if (!cmdline.includes(workspacePath))
1242
+ continue;
1243
+ // Skip if this PID is still in runningProcesses (still active run)
1244
+ const isActiveRun = Array.from(runningProcesses.values()).some((rp) => rp.pid === pid);
1245
+ if (isActiveRun)
1246
+ continue;
1247
+ logger.warn({ pid, workspacePath, runId }, "killing orphaned workspace process");
1248
+ try {
1249
+ process.kill(pid, "SIGTERM");
1250
+ killed++;
1251
+ }
1252
+ catch {
1253
+ // ESRCH: process already gone
1254
+ }
1255
+ break;
1256
+ }
1257
+ }
1258
+ if (killed > 0) {
1259
+ logger.warn({ killed }, "reaped orphaned workspace processes");
1260
+ }
1261
+ return { killed };
1262
+ }
1263
+ /**
1264
+ * Release execution locks on issues whose associated run has already reached
1265
+ * a terminal state (succeeded / failed / cancelled / timed_out).
1266
+ *
1267
+ * This is a safety net for the gap between `setRunStatus` and
1268
+ * `releaseIssueExecutionAndPromote` — e.g. if the server crashed in that
1269
+ * window the issue would be permanently stuck with a stale lock.
1270
+ *
1271
+ * Safe to call repeatedly; it is idempotent because
1272
+ * `releaseIssueExecutionAndPromote` checks the current `executionRunId`
1273
+ * inside a transaction.
1274
+ */
1275
+ async function expireTerminatedRunLocks() {
1276
+ const terminalStatuses = ["succeeded", "failed", "cancelled", "timed_out"];
1277
+ const rows = await db
1278
+ .select({ run: heartbeatRuns })
1279
+ .from(issues)
1280
+ .innerJoin(heartbeatRuns, eq(issues.executionRunId, heartbeatRuns.id))
1281
+ .where(inArray(heartbeatRuns.status, terminalStatuses));
1282
+ const released = [];
1283
+ for (const { run } of rows) {
1284
+ try {
1285
+ await releaseIssueExecutionAndPromote(run);
1286
+ released.push(run.id);
1287
+ }
1288
+ catch (err) {
1289
+ logger.error({ err, runId: run.id }, "failed to release stale execution lock for terminated run");
1290
+ }
1291
+ }
1292
+ if (released.length > 0) {
1293
+ logger.warn({ releasedCount: released.length, runIds: released }, "expired stale execution locks held by terminated runs");
1294
+ }
1295
+ return { released: released.length, runIds: released };
1296
+ }
1297
+ async function resumeQueuedRuns() {
1298
+ const queuedRuns = await db
1299
+ .select({ agentId: heartbeatRuns.agentId })
1300
+ .from(heartbeatRuns)
1301
+ .where(eq(heartbeatRuns.status, "queued"));
1302
+ const agentIds = [...new Set(queuedRuns.map((r) => r.agentId))];
1303
+ for (const agentId of agentIds) {
1304
+ await startNextQueuedRunForAgent(agentId);
1305
+ }
1306
+ }
1307
+ async function updateRuntimeState(agent, run, result, session, normalizedUsage) {
1308
+ await ensureRuntimeState(agent);
1309
+ const usage = normalizedUsage ?? normalizeUsageTotals(result.usage);
1310
+ const inputTokens = usage?.inputTokens ?? 0;
1311
+ const outputTokens = usage?.outputTokens ?? 0;
1312
+ const cachedInputTokens = usage?.cachedInputTokens ?? 0;
1313
+ const billingType = normalizeLedgerBillingType(result.billingType);
1314
+ const additionalCostCents = normalizeBilledCostCents(result.costUsd, billingType);
1315
+ const hasTokenUsage = inputTokens > 0 || outputTokens > 0 || cachedInputTokens > 0;
1316
+ const provider = result.provider ?? "unknown";
1317
+ const biller = resolveLedgerBiller(result);
1318
+ const ledgerScope = await resolveLedgerScopeForRun(db, agent.companyId, run);
1319
+ await db
1320
+ .update(agentRuntimeState)
1321
+ .set({
1322
+ adapterType: agent.adapterType,
1323
+ sessionId: session.legacySessionId,
1324
+ lastRunId: run.id,
1325
+ lastRunStatus: run.status,
1326
+ lastError: result.errorMessage ?? null,
1327
+ totalInputTokens: sql `${agentRuntimeState.totalInputTokens} + ${inputTokens}`,
1328
+ totalOutputTokens: sql `${agentRuntimeState.totalOutputTokens} + ${outputTokens}`,
1329
+ totalCachedInputTokens: sql `${agentRuntimeState.totalCachedInputTokens} + ${cachedInputTokens}`,
1330
+ totalCostCents: sql `${agentRuntimeState.totalCostCents} + ${additionalCostCents}`,
1331
+ updatedAt: new Date(),
1332
+ })
1333
+ .where(eq(agentRuntimeState.agentId, agent.id));
1334
+ if (additionalCostCents > 0 || hasTokenUsage) {
1335
+ const costs = costService(db, budgetHooks);
1336
+ await costs.createEvent(agent.companyId, {
1337
+ heartbeatRunId: run.id,
1338
+ agentId: agent.id,
1339
+ issueId: ledgerScope.issueId,
1340
+ projectId: ledgerScope.projectId,
1341
+ provider,
1342
+ biller,
1343
+ billingType,
1344
+ model: result.model ?? "unknown",
1345
+ inputTokens,
1346
+ cachedInputTokens,
1347
+ outputTokens,
1348
+ costCents: additionalCostCents,
1349
+ occurredAt: new Date(),
1350
+ });
1351
+ }
1352
+ }
1353
+ async function startNextQueuedRunForAgent(agentId) {
1354
+ return withAgentStartLock(agentId, async () => {
1355
+ const agent = await getAgent(agentId);
1356
+ if (!agent)
1357
+ return [];
1358
+ if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") {
1359
+ return [];
1360
+ }
1361
+ const policy = parseHeartbeatPolicy(agent);
1362
+ const runningCount = await countRunningRunsForAgent(agentId);
1363
+ const availableSlots = Math.max(0, policy.maxConcurrentRuns - runningCount);
1364
+ if (availableSlots <= 0)
1365
+ return [];
1366
+ const queuedRuns = await db
1367
+ .select()
1368
+ .from(heartbeatRuns)
1369
+ .where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.status, "queued")))
1370
+ .orderBy(asc(heartbeatRuns.createdAt))
1371
+ .limit(availableSlots);
1372
+ if (queuedRuns.length === 0)
1373
+ return [];
1374
+ const claimedRuns = [];
1375
+ for (const queuedRun of queuedRuns) {
1376
+ const claimed = await claimQueuedRun(queuedRun);
1377
+ if (claimed)
1378
+ claimedRuns.push(claimed);
1379
+ }
1380
+ if (claimedRuns.length === 0)
1381
+ return [];
1382
+ for (const claimedRun of claimedRuns) {
1383
+ void executeRun(claimedRun.id).catch((err) => {
1384
+ logger.error({ err, runId: claimedRun.id }, "queued heartbeat execution failed");
1385
+ });
1386
+ }
1387
+ return claimedRuns;
1388
+ });
1389
+ }
1390
+ async function executeRun(runId) {
1391
+ let run = await getRun(runId);
1392
+ if (!run)
1393
+ return;
1394
+ if (run.status !== "queued" && run.status !== "running")
1395
+ return;
1396
+ if (run.status === "queued") {
1397
+ const claimed = await claimQueuedRun(run);
1398
+ if (!claimed) {
1399
+ // Another worker has already claimed or finalized this run.
1400
+ return;
1401
+ }
1402
+ run = claimed;
1403
+ }
1404
+ activeRunExecutions.add(run.id);
1405
+ try {
1406
+ const agent = await getAgent(run.agentId);
1407
+ if (!agent) {
1408
+ await setRunStatus(runId, "failed", {
1409
+ error: "Agent not found",
1410
+ errorCode: "agent_not_found",
1411
+ finishedAt: new Date(),
1412
+ });
1413
+ await setWakeupStatus(run.wakeupRequestId, "failed", {
1414
+ finishedAt: new Date(),
1415
+ error: "Agent not found",
1416
+ });
1417
+ const failedRun = await getRun(runId);
1418
+ if (failedRun)
1419
+ await releaseIssueExecutionAndPromote(failedRun);
1420
+ return;
1421
+ }
1422
+ const runtime = await ensureRuntimeState(agent);
1423
+ const context = parseObject(run.contextSnapshot);
1424
+ const taskKey = deriveTaskKey(context, null);
1425
+ const sessionCodec = getAdapterSessionCodec(agent.adapterType);
1426
+ const issueId = readNonEmptyString(context.issueId);
1427
+ const issueContext = issueId
1428
+ ? await db
1429
+ .select({
1430
+ id: issues.id,
1431
+ identifier: issues.identifier,
1432
+ title: issues.title,
1433
+ projectId: issues.projectId,
1434
+ projectWorkspaceId: issues.projectWorkspaceId,
1435
+ executionWorkspaceId: issues.executionWorkspaceId,
1436
+ executionWorkspacePreference: issues.executionWorkspacePreference,
1437
+ assigneeAgentId: issues.assigneeAgentId,
1438
+ assigneeAdapterOverrides: issues.assigneeAdapterOverrides,
1439
+ executionWorkspaceSettings: issues.executionWorkspaceSettings,
1440
+ })
1441
+ .from(issues)
1442
+ .where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId)))
1443
+ .then((rows) => rows[0] ?? null)
1444
+ : null;
1445
+ const issueAssigneeOverrides = issueContext && issueContext.assigneeAgentId === agent.id
1446
+ ? parseIssueAssigneeAdapterOverrides(issueContext.assigneeAdapterOverrides)
1447
+ : null;
1448
+ const isolatedWorkspacesEnabled = (await instanceSettings.getExperimental()).enableIsolatedWorkspaces;
1449
+ const issueExecutionWorkspaceSettings = isolatedWorkspacesEnabled
1450
+ ? parseIssueExecutionWorkspaceSettings(issueContext?.executionWorkspaceSettings)
1451
+ : null;
1452
+ const contextProjectId = readNonEmptyString(context.projectId);
1453
+ const executionProjectId = issueContext?.projectId ?? contextProjectId;
1454
+ const projectExecutionWorkspacePolicy = executionProjectId
1455
+ ? await db
1456
+ .select({ executionWorkspacePolicy: projects.executionWorkspacePolicy })
1457
+ .from(projects)
1458
+ .where(and(eq(projects.id, executionProjectId), eq(projects.companyId, agent.companyId)))
1459
+ .then((rows) => gateProjectExecutionWorkspacePolicy(parseProjectExecutionWorkspacePolicy(rows[0]?.executionWorkspacePolicy), isolatedWorkspacesEnabled))
1460
+ : null;
1461
+ const taskSession = taskKey
1462
+ ? await getTaskSession(agent.companyId, agent.id, agent.adapterType, taskKey)
1463
+ : null;
1464
+ const resetTaskSession = shouldResetTaskSessionForWake(context);
1465
+ const sessionResetReason = describeSessionResetReason(context);
1466
+ const taskSessionForRun = resetTaskSession ? null : taskSession;
1467
+ const previousSessionParams = normalizeSessionParams(sessionCodec.deserialize(taskSessionForRun?.sessionParamsJson ?? null));
1468
+ const config = parseObject(agent.adapterConfig);
1469
+ const executionWorkspaceMode = resolveExecutionWorkspaceMode({
1470
+ projectPolicy: projectExecutionWorkspacePolicy,
1471
+ issueSettings: issueExecutionWorkspaceSettings,
1472
+ legacyUseProjectWorkspace: issueAssigneeOverrides?.useProjectWorkspace ?? null,
1473
+ });
1474
+ const resolvedWorkspace = await resolveWorkspaceForRun(agent, context, previousSessionParams, { useProjectWorkspace: executionWorkspaceMode !== "agent_default" });
1475
+ const workspaceManagedConfig = buildExecutionWorkspaceAdapterConfig({
1476
+ agentConfig: config,
1477
+ projectPolicy: projectExecutionWorkspacePolicy,
1478
+ issueSettings: issueExecutionWorkspaceSettings,
1479
+ mode: executionWorkspaceMode,
1480
+ legacyUseProjectWorkspace: issueAssigneeOverrides?.useProjectWorkspace ?? null,
1481
+ });
1482
+ const mergedConfig = issueAssigneeOverrides?.adapterConfig
1483
+ ? { ...workspaceManagedConfig, ...issueAssigneeOverrides.adapterConfig }
1484
+ : workspaceManagedConfig;
1485
+ const { config: resolvedConfig, secretKeys } = await secretsSvc.resolveAdapterConfigForRuntime(agent.companyId, mergedConfig);
1486
+ const issueRef = issueContext
1487
+ ? {
1488
+ id: issueContext.id,
1489
+ identifier: issueContext.identifier,
1490
+ title: issueContext.title,
1491
+ projectId: issueContext.projectId,
1492
+ projectWorkspaceId: issueContext.projectWorkspaceId,
1493
+ executionWorkspaceId: issueContext.executionWorkspaceId,
1494
+ executionWorkspacePreference: issueContext.executionWorkspacePreference,
1495
+ }
1496
+ : null;
1497
+ const existingExecutionWorkspace = issueRef?.executionWorkspaceId ? await executionWorkspacesSvc.getById(issueRef.executionWorkspaceId) : null;
1498
+ const workspaceOperationRecorder = workspaceOperationsSvc.createRecorder({
1499
+ companyId: agent.companyId,
1500
+ heartbeatRunId: run.id,
1501
+ executionWorkspaceId: existingExecutionWorkspace?.id ?? null,
1502
+ });
1503
+ const executionWorkspace = await realizeExecutionWorkspace({
1504
+ base: {
1505
+ baseCwd: resolvedWorkspace.cwd,
1506
+ source: resolvedWorkspace.source,
1507
+ projectId: resolvedWorkspace.projectId,
1508
+ workspaceId: resolvedWorkspace.workspaceId,
1509
+ repoUrl: resolvedWorkspace.repoUrl,
1510
+ repoRef: resolvedWorkspace.repoRef,
1511
+ },
1512
+ config: resolvedConfig,
1513
+ issue: issueRef,
1514
+ agent: {
1515
+ id: agent.id,
1516
+ name: agent.name,
1517
+ companyId: agent.companyId,
1518
+ },
1519
+ recorder: workspaceOperationRecorder,
1520
+ });
1521
+ const resolvedProjectId = executionWorkspace.projectId ?? issueRef?.projectId ?? executionProjectId ?? null;
1522
+ const resolvedProjectWorkspaceId = issueRef?.projectWorkspaceId ?? resolvedWorkspace.workspaceId ?? null;
1523
+ const shouldReuseExisting = issueRef?.executionWorkspacePreference === "reuse_existing" &&
1524
+ existingExecutionWorkspace &&
1525
+ existingExecutionWorkspace.status !== "archived";
1526
+ let persistedExecutionWorkspace = null;
1527
+ try {
1528
+ persistedExecutionWorkspace = shouldReuseExisting && existingExecutionWorkspace
1529
+ ? await executionWorkspacesSvc.update(existingExecutionWorkspace.id, {
1530
+ cwd: executionWorkspace.cwd,
1531
+ repoUrl: executionWorkspace.repoUrl,
1532
+ baseRef: executionWorkspace.repoRef,
1533
+ branchName: executionWorkspace.branchName,
1534
+ providerType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "local_fs",
1535
+ providerRef: executionWorkspace.worktreePath,
1536
+ status: "active",
1537
+ lastUsedAt: new Date(),
1538
+ metadata: {
1539
+ ...(existingExecutionWorkspace.metadata ?? {}),
1540
+ source: executionWorkspace.source,
1541
+ createdByRuntime: executionWorkspace.created,
1542
+ },
1543
+ })
1544
+ : resolvedProjectId
1545
+ ? await executionWorkspacesSvc.create({
1546
+ companyId: agent.companyId,
1547
+ projectId: resolvedProjectId,
1548
+ projectWorkspaceId: resolvedProjectWorkspaceId,
1549
+ sourceIssueId: issueRef?.id ?? null,
1550
+ mode: executionWorkspaceMode === "isolated_workspace"
1551
+ ? "isolated_workspace"
1552
+ : executionWorkspaceMode === "operator_branch"
1553
+ ? "operator_branch"
1554
+ : executionWorkspaceMode === "agent_default"
1555
+ ? "adapter_managed"
1556
+ : "shared_workspace",
1557
+ strategyType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "project_primary",
1558
+ name: executionWorkspace.branchName ?? issueRef?.identifier ?? `workspace-${agent.id.slice(0, 8)}`,
1559
+ status: "active",
1560
+ cwd: executionWorkspace.cwd,
1561
+ repoUrl: executionWorkspace.repoUrl,
1562
+ baseRef: executionWorkspace.repoRef,
1563
+ branchName: executionWorkspace.branchName,
1564
+ providerType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "local_fs",
1565
+ providerRef: executionWorkspace.worktreePath,
1566
+ lastUsedAt: new Date(),
1567
+ openedAt: new Date(),
1568
+ metadata: {
1569
+ source: executionWorkspace.source,
1570
+ createdByRuntime: executionWorkspace.created,
1571
+ },
1572
+ })
1573
+ : null;
1574
+ }
1575
+ catch (error) {
1576
+ if (executionWorkspace.created) {
1577
+ try {
1578
+ await cleanupExecutionWorkspaceArtifacts({
1579
+ workspace: {
1580
+ id: existingExecutionWorkspace?.id ?? `transient-${run.id}`,
1581
+ cwd: executionWorkspace.cwd,
1582
+ providerType: executionWorkspace.strategy === "git_worktree" ? "git_worktree" : "local_fs",
1583
+ providerRef: executionWorkspace.worktreePath,
1584
+ branchName: executionWorkspace.branchName,
1585
+ repoUrl: executionWorkspace.repoUrl,
1586
+ baseRef: executionWorkspace.repoRef,
1587
+ projectId: resolvedProjectId,
1588
+ projectWorkspaceId: resolvedProjectWorkspaceId,
1589
+ sourceIssueId: issueRef?.id ?? null,
1590
+ metadata: {
1591
+ createdByRuntime: true,
1592
+ source: executionWorkspace.source,
1593
+ },
1594
+ },
1595
+ projectWorkspace: {
1596
+ cwd: resolvedWorkspace.cwd,
1597
+ cleanupCommand: null,
1598
+ },
1599
+ teardownCommand: projectExecutionWorkspacePolicy?.workspaceStrategy?.teardownCommand ?? null,
1600
+ recorder: workspaceOperationRecorder,
1601
+ });
1602
+ }
1603
+ catch (cleanupError) {
1604
+ logger.warn({
1605
+ runId: run.id,
1606
+ issueId,
1607
+ executionWorkspaceCwd: executionWorkspace.cwd,
1608
+ cleanupError: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
1609
+ }, "Failed to cleanup realized execution workspace after persistence failure");
1610
+ }
1611
+ }
1612
+ throw error;
1613
+ }
1614
+ await workspaceOperationRecorder.attachExecutionWorkspaceId(persistedExecutionWorkspace?.id ?? null);
1615
+ if (existingExecutionWorkspace &&
1616
+ persistedExecutionWorkspace &&
1617
+ existingExecutionWorkspace.id !== persistedExecutionWorkspace.id &&
1618
+ existingExecutionWorkspace.status === "active") {
1619
+ await executionWorkspacesSvc.update(existingExecutionWorkspace.id, {
1620
+ status: "idle",
1621
+ cleanupReason: null,
1622
+ });
1623
+ }
1624
+ if (issueId && persistedExecutionWorkspace && issueRef?.executionWorkspaceId !== persistedExecutionWorkspace.id) {
1625
+ await issuesSvc.update(issueId, {
1626
+ executionWorkspaceId: persistedExecutionWorkspace.id,
1627
+ ...(resolvedProjectWorkspaceId ? { projectWorkspaceId: resolvedProjectWorkspaceId } : {}),
1628
+ });
1629
+ }
1630
+ if (persistedExecutionWorkspace) {
1631
+ context.executionWorkspaceId = persistedExecutionWorkspace.id;
1632
+ await db
1633
+ .update(heartbeatRuns)
1634
+ .set({
1635
+ contextSnapshot: context,
1636
+ updatedAt: new Date(),
1637
+ })
1638
+ .where(eq(heartbeatRuns.id, run.id));
1639
+ }
1640
+ const runtimeSessionResolution = resolveRuntimeSessionParamsForWorkspace({
1641
+ agentId: agent.id,
1642
+ previousSessionParams,
1643
+ resolvedWorkspace: {
1644
+ ...resolvedWorkspace,
1645
+ cwd: executionWorkspace.cwd,
1646
+ },
1647
+ });
1648
+ const runtimeSessionParams = runtimeSessionResolution.sessionParams;
1649
+ const runtimeWorkspaceWarnings = [
1650
+ ...resolvedWorkspace.warnings,
1651
+ ...executionWorkspace.warnings,
1652
+ ...(runtimeSessionResolution.warning ? [runtimeSessionResolution.warning] : []),
1653
+ ...(resetTaskSession && sessionResetReason
1654
+ ? [
1655
+ taskKey
1656
+ ? `Skipping saved session resume for task "${taskKey}" because ${sessionResetReason}.`
1657
+ : `Skipping saved session resume because ${sessionResetReason}.`,
1658
+ ]
1659
+ : []),
1660
+ ];
1661
+ context.paperclipWorkspace = {
1662
+ cwd: executionWorkspace.cwd,
1663
+ source: executionWorkspace.source,
1664
+ mode: executionWorkspaceMode,
1665
+ strategy: executionWorkspace.strategy,
1666
+ projectId: executionWorkspace.projectId,
1667
+ workspaceId: executionWorkspace.workspaceId,
1668
+ repoUrl: executionWorkspace.repoUrl,
1669
+ repoRef: executionWorkspace.repoRef,
1670
+ branchName: executionWorkspace.branchName,
1671
+ worktreePath: executionWorkspace.worktreePath,
1672
+ agentHome: resolveDefaultAgentWorkspaceDir(agent.id),
1673
+ };
1674
+ context.paperclipWorkspaces = resolvedWorkspace.workspaceHints;
1675
+ const runtimeServiceIntents = (() => {
1676
+ const runtimeConfig = parseObject(resolvedConfig.workspaceRuntime);
1677
+ return Array.isArray(runtimeConfig.services)
1678
+ ? runtimeConfig.services.filter((value) => typeof value === "object" && value !== null)
1679
+ : [];
1680
+ })();
1681
+ if (runtimeServiceIntents.length > 0) {
1682
+ context.paperclipRuntimeServiceIntents = runtimeServiceIntents;
1683
+ }
1684
+ else {
1685
+ delete context.paperclipRuntimeServiceIntents;
1686
+ }
1687
+ if (executionWorkspace.projectId && !readNonEmptyString(context.projectId)) {
1688
+ context.projectId = executionWorkspace.projectId;
1689
+ }
1690
+ const runtimeSessionFallback = taskKey || resetTaskSession ? null : runtime.sessionId;
1691
+ let previousSessionDisplayId = truncateDisplayId(taskSessionForRun?.sessionDisplayId ??
1692
+ (sessionCodec.getDisplayId ? sessionCodec.getDisplayId(runtimeSessionParams) : null) ??
1693
+ readNonEmptyString(runtimeSessionParams?.sessionId) ??
1694
+ runtimeSessionFallback);
1695
+ let runtimeSessionIdForAdapter = readNonEmptyString(runtimeSessionParams?.sessionId) ?? runtimeSessionFallback;
1696
+ let runtimeSessionParamsForAdapter = runtimeSessionParams;
1697
+ const sessionCompaction = await evaluateSessionCompaction({
1698
+ agent,
1699
+ sessionId: previousSessionDisplayId ?? runtimeSessionIdForAdapter,
1700
+ issueId,
1701
+ });
1702
+ if (sessionCompaction.rotate) {
1703
+ context.paperclipSessionHandoffMarkdown = sessionCompaction.handoffMarkdown;
1704
+ context.paperclipSessionRotationReason = sessionCompaction.reason;
1705
+ context.paperclipPreviousSessionId = previousSessionDisplayId ?? runtimeSessionIdForAdapter;
1706
+ runtimeSessionIdForAdapter = null;
1707
+ runtimeSessionParamsForAdapter = null;
1708
+ previousSessionDisplayId = null;
1709
+ if (sessionCompaction.reason) {
1710
+ runtimeWorkspaceWarnings.push(`Starting a fresh session because ${sessionCompaction.reason}.`);
1711
+ }
1712
+ }
1713
+ else {
1714
+ delete context.paperclipSessionHandoffMarkdown;
1715
+ delete context.paperclipSessionRotationReason;
1716
+ delete context.paperclipPreviousSessionId;
1717
+ }
1718
+ const runtimeForAdapter = {
1719
+ sessionId: runtimeSessionIdForAdapter,
1720
+ sessionParams: runtimeSessionParamsForAdapter,
1721
+ sessionDisplayId: previousSessionDisplayId,
1722
+ taskKey,
1723
+ };
1724
+ let seq = 1;
1725
+ let handle = null;
1726
+ let stdoutExcerpt = "";
1727
+ let stderrExcerpt = "";
1728
+ try {
1729
+ const startedAt = run.startedAt ?? new Date();
1730
+ const runningWithSession = await db
1731
+ .update(heartbeatRuns)
1732
+ .set({
1733
+ startedAt,
1734
+ sessionIdBefore: runtimeForAdapter.sessionDisplayId ?? runtimeForAdapter.sessionId,
1735
+ contextSnapshot: context,
1736
+ updatedAt: new Date(),
1737
+ })
1738
+ .where(eq(heartbeatRuns.id, run.id))
1739
+ .returning()
1740
+ .then((rows) => rows[0] ?? null);
1741
+ if (runningWithSession)
1742
+ run = runningWithSession;
1743
+ const runningAgent = await db
1744
+ .update(agents)
1745
+ .set({ status: "running", updatedAt: new Date() })
1746
+ .where(eq(agents.id, agent.id))
1747
+ .returning()
1748
+ .then((rows) => rows[0] ?? null);
1749
+ if (runningAgent) {
1750
+ publishLiveEvent({
1751
+ companyId: runningAgent.companyId,
1752
+ type: "agent.status",
1753
+ payload: {
1754
+ agentId: runningAgent.id,
1755
+ status: runningAgent.status,
1756
+ outcome: "running",
1757
+ },
1758
+ });
1759
+ }
1760
+ const currentRun = run;
1761
+ await appendRunEvent(currentRun, seq++, {
1762
+ eventType: "lifecycle",
1763
+ stream: "system",
1764
+ level: "info",
1765
+ message: "run started",
1766
+ });
1767
+ handle = await runLogStore.begin({
1768
+ companyId: run.companyId,
1769
+ agentId: run.agentId,
1770
+ runId,
1771
+ });
1772
+ await db
1773
+ .update(heartbeatRuns)
1774
+ .set({
1775
+ logStore: handle.store,
1776
+ logRef: handle.logRef,
1777
+ updatedAt: new Date(),
1778
+ })
1779
+ .where(eq(heartbeatRuns.id, runId));
1780
+ const onLog = async (stream, chunk) => {
1781
+ const sanitizedChunk = redactCurrentUserText(chunk);
1782
+ if (stream === "stdout")
1783
+ stdoutExcerpt = appendExcerpt(stdoutExcerpt, sanitizedChunk);
1784
+ if (stream === "stderr")
1785
+ stderrExcerpt = appendExcerpt(stderrExcerpt, sanitizedChunk);
1786
+ const ts = new Date().toISOString();
1787
+ if (handle) {
1788
+ await runLogStore.append(handle, {
1789
+ stream,
1790
+ chunk: sanitizedChunk,
1791
+ ts,
1792
+ });
1793
+ }
1794
+ const payloadChunk = sanitizedChunk.length > MAX_LIVE_LOG_CHUNK_BYTES
1795
+ ? sanitizedChunk.slice(sanitizedChunk.length - MAX_LIVE_LOG_CHUNK_BYTES)
1796
+ : sanitizedChunk;
1797
+ publishLiveEvent({
1798
+ companyId: run.companyId,
1799
+ type: "heartbeat.run.log",
1800
+ payload: {
1801
+ runId: run.id,
1802
+ agentId: run.agentId,
1803
+ ts,
1804
+ stream,
1805
+ chunk: payloadChunk,
1806
+ truncated: payloadChunk.length !== sanitizedChunk.length,
1807
+ },
1808
+ });
1809
+ };
1810
+ for (const warning of runtimeWorkspaceWarnings) {
1811
+ const logEntry = formatRuntimeWorkspaceWarningLog(warning);
1812
+ await onLog(logEntry.stream, logEntry.chunk);
1813
+ }
1814
+ const adapterEnv = Object.fromEntries(Object.entries(parseObject(resolvedConfig.env)).filter((entry) => typeof entry[0] === "string" && typeof entry[1] === "string"));
1815
+ const runtimeServices = await ensureRuntimeServicesForRun({
1816
+ db,
1817
+ runId: run.id,
1818
+ agent: {
1819
+ id: agent.id,
1820
+ name: agent.name,
1821
+ companyId: agent.companyId,
1822
+ },
1823
+ issue: issueRef,
1824
+ workspace: executionWorkspace,
1825
+ executionWorkspaceId: persistedExecutionWorkspace?.id ?? issueRef?.executionWorkspaceId ?? null,
1826
+ config: resolvedConfig,
1827
+ adapterEnv,
1828
+ onLog,
1829
+ });
1830
+ if (runtimeServices.length > 0) {
1831
+ context.paperclipRuntimeServices = runtimeServices;
1832
+ context.paperclipRuntimePrimaryUrl =
1833
+ runtimeServices.find((service) => readNonEmptyString(service.url))?.url ?? null;
1834
+ await db
1835
+ .update(heartbeatRuns)
1836
+ .set({
1837
+ contextSnapshot: context,
1838
+ updatedAt: new Date(),
1839
+ })
1840
+ .where(eq(heartbeatRuns.id, run.id));
1841
+ }
1842
+ if (issueId && (executionWorkspace.created || runtimeServices.some((service) => !service.reused))) {
1843
+ try {
1844
+ await issuesSvc.addComment(issueId, buildWorkspaceReadyComment({
1845
+ workspace: executionWorkspace,
1846
+ runtimeServices,
1847
+ }), { agentId: agent.id });
1848
+ }
1849
+ catch (err) {
1850
+ await onLog("stderr", `[paperclip] Failed to post workspace-ready comment: ${err instanceof Error ? err.message : String(err)}\n`);
1851
+ }
1852
+ }
1853
+ const onAdapterMeta = async (meta) => {
1854
+ if (meta.env && secretKeys.size > 0) {
1855
+ for (const key of secretKeys) {
1856
+ if (key in meta.env)
1857
+ meta.env[key] = "***REDACTED***";
1858
+ }
1859
+ }
1860
+ await appendRunEvent(currentRun, seq++, {
1861
+ eventType: "adapter.invoke",
1862
+ stream: "system",
1863
+ level: "info",
1864
+ message: "adapter invocation",
1865
+ payload: meta,
1866
+ });
1867
+ };
1868
+ const adapter = getServerAdapter(agent.adapterType);
1869
+ const authToken = adapter.supportsLocalAgentJwt
1870
+ ? createLocalAgentJwt(agent.id, agent.companyId, agent.adapterType, run.id)
1871
+ : null;
1872
+ if (adapter.supportsLocalAgentJwt && !authToken) {
1873
+ logger.warn({
1874
+ companyId: agent.companyId,
1875
+ agentId: agent.id,
1876
+ runId: run.id,
1877
+ adapterType: agent.adapterType,
1878
+ }, "local agent jwt secret missing or invalid; running without injected PAPERCLIP_API_KEY");
1879
+ }
1880
+ const adapterResult = await adapter.execute({
1881
+ runId: run.id,
1882
+ agent,
1883
+ runtime: runtimeForAdapter,
1884
+ config: resolvedConfig,
1885
+ context,
1886
+ onLog,
1887
+ onMeta: onAdapterMeta,
1888
+ authToken: authToken ?? undefined,
1889
+ });
1890
+ const adapterManagedRuntimeServices = adapterResult.runtimeServices
1891
+ ? await persistAdapterManagedRuntimeServices({
1892
+ db,
1893
+ adapterType: agent.adapterType,
1894
+ runId: run.id,
1895
+ agent: {
1896
+ id: agent.id,
1897
+ name: agent.name,
1898
+ companyId: agent.companyId,
1899
+ },
1900
+ issue: issueRef,
1901
+ workspace: executionWorkspace,
1902
+ reports: adapterResult.runtimeServices,
1903
+ })
1904
+ : [];
1905
+ if (adapterManagedRuntimeServices.length > 0) {
1906
+ const combinedRuntimeServices = [
1907
+ ...runtimeServices,
1908
+ ...adapterManagedRuntimeServices,
1909
+ ];
1910
+ context.paperclipRuntimeServices = combinedRuntimeServices;
1911
+ context.paperclipRuntimePrimaryUrl =
1912
+ combinedRuntimeServices.find((service) => readNonEmptyString(service.url))?.url ?? null;
1913
+ await db
1914
+ .update(heartbeatRuns)
1915
+ .set({
1916
+ contextSnapshot: context,
1917
+ updatedAt: new Date(),
1918
+ })
1919
+ .where(eq(heartbeatRuns.id, run.id));
1920
+ if (issueId) {
1921
+ try {
1922
+ await issuesSvc.addComment(issueId, buildWorkspaceReadyComment({
1923
+ workspace: executionWorkspace,
1924
+ runtimeServices: adapterManagedRuntimeServices,
1925
+ }), { agentId: agent.id });
1926
+ }
1927
+ catch (err) {
1928
+ await onLog("stderr", `[paperclip] Failed to post adapter-managed runtime comment: ${err instanceof Error ? err.message : String(err)}\n`);
1929
+ }
1930
+ }
1931
+ }
1932
+ const nextSessionState = resolveNextSessionState({
1933
+ codec: sessionCodec,
1934
+ adapterResult,
1935
+ previousParams: previousSessionParams,
1936
+ previousDisplayId: runtimeForAdapter.sessionDisplayId,
1937
+ previousLegacySessionId: runtimeForAdapter.sessionId,
1938
+ });
1939
+ const rawUsage = normalizeUsageTotals(adapterResult.usage);
1940
+ const sessionUsageResolution = await resolveNormalizedUsageForSession({
1941
+ agentId: agent.id,
1942
+ runId: run.id,
1943
+ sessionId: nextSessionState.displayId ?? nextSessionState.legacySessionId,
1944
+ rawUsage,
1945
+ });
1946
+ const normalizedUsage = sessionUsageResolution.normalizedUsage;
1947
+ let outcome;
1948
+ const latestRun = await getRun(run.id);
1949
+ if (latestRun?.status === "cancelled") {
1950
+ outcome = "cancelled";
1951
+ }
1952
+ else if (adapterResult.timedOut) {
1953
+ outcome = "timed_out";
1954
+ }
1955
+ else if ((adapterResult.exitCode ?? 0) === 0 && !adapterResult.errorMessage) {
1956
+ outcome = "succeeded";
1957
+ }
1958
+ else {
1959
+ outcome = "failed";
1960
+ }
1961
+ let logSummary = null;
1962
+ if (handle) {
1963
+ logSummary = await runLogStore.finalize(handle);
1964
+ }
1965
+ const status = outcome === "succeeded"
1966
+ ? "succeeded"
1967
+ : outcome === "cancelled"
1968
+ ? "cancelled"
1969
+ : outcome === "timed_out"
1970
+ ? "timed_out"
1971
+ : "failed";
1972
+ const usageJson = normalizedUsage || adapterResult.costUsd != null
1973
+ ? {
1974
+ ...(normalizedUsage ?? {}),
1975
+ ...(rawUsage ? {
1976
+ rawInputTokens: rawUsage.inputTokens,
1977
+ rawCachedInputTokens: rawUsage.cachedInputTokens,
1978
+ rawOutputTokens: rawUsage.outputTokens,
1979
+ } : {}),
1980
+ ...(sessionUsageResolution.derivedFromSessionTotals ? { usageSource: "session_delta" } : {}),
1981
+ ...((nextSessionState.displayId ?? nextSessionState.legacySessionId)
1982
+ ? { persistedSessionId: nextSessionState.displayId ?? nextSessionState.legacySessionId }
1983
+ : {}),
1984
+ sessionReused: runtimeForAdapter.sessionId != null || runtimeForAdapter.sessionDisplayId != null,
1985
+ taskSessionReused: taskSessionForRun != null,
1986
+ freshSession: runtimeForAdapter.sessionId == null && runtimeForAdapter.sessionDisplayId == null,
1987
+ sessionRotated: sessionCompaction.rotate,
1988
+ sessionRotationReason: sessionCompaction.reason,
1989
+ provider: readNonEmptyString(adapterResult.provider) ?? "unknown",
1990
+ biller: resolveLedgerBiller(adapterResult),
1991
+ model: readNonEmptyString(adapterResult.model) ?? "unknown",
1992
+ ...(adapterResult.costUsd != null ? { costUsd: adapterResult.costUsd } : {}),
1993
+ billingType: normalizeLedgerBillingType(adapterResult.billingType),
1994
+ }
1995
+ : null;
1996
+ await setRunStatus(run.id, status, {
1997
+ finishedAt: new Date(),
1998
+ error: outcome === "succeeded"
1999
+ ? null
2000
+ : redactCurrentUserText(adapterResult.errorMessage ?? (outcome === "timed_out" ? "Timed out" : "Adapter failed")),
2001
+ errorCode: outcome === "timed_out"
2002
+ ? "timeout"
2003
+ : outcome === "cancelled"
2004
+ ? "cancelled"
2005
+ : outcome === "failed"
2006
+ ? (adapterResult.errorCode ?? "adapter_failed")
2007
+ : null,
2008
+ exitCode: adapterResult.exitCode,
2009
+ signal: adapterResult.signal,
2010
+ usageJson,
2011
+ resultJson: adapterResult.resultJson ?? null,
2012
+ sessionIdAfter: nextSessionState.displayId ?? nextSessionState.legacySessionId,
2013
+ stdoutExcerpt,
2014
+ stderrExcerpt,
2015
+ logBytes: logSummary?.bytes,
2016
+ logSha256: logSummary?.sha256,
2017
+ logCompressed: logSummary?.compressed ?? false,
2018
+ });
2019
+ await setWakeupStatus(run.wakeupRequestId, outcome === "succeeded" ? "completed" : status, {
2020
+ finishedAt: new Date(),
2021
+ error: adapterResult.errorMessage ?? null,
2022
+ });
2023
+ const finalizedRun = await getRun(run.id);
2024
+ if (finalizedRun) {
2025
+ await appendRunEvent(finalizedRun, seq++, {
2026
+ eventType: "lifecycle",
2027
+ stream: "system",
2028
+ level: outcome === "succeeded" ? "info" : "error",
2029
+ message: `run ${outcome}`,
2030
+ payload: {
2031
+ status,
2032
+ exitCode: adapterResult.exitCode,
2033
+ },
2034
+ });
2035
+ await releaseIssueExecutionAndPromote(finalizedRun);
2036
+ }
2037
+ if (finalizedRun) {
2038
+ await updateRuntimeState(agent, finalizedRun, adapterResult, {
2039
+ legacySessionId: nextSessionState.legacySessionId,
2040
+ }, normalizedUsage);
2041
+ if (taskKey) {
2042
+ if (adapterResult.clearSession || (!nextSessionState.params && !nextSessionState.displayId)) {
2043
+ await clearTaskSessions(agent.companyId, agent.id, {
2044
+ taskKey,
2045
+ adapterType: agent.adapterType,
2046
+ });
2047
+ }
2048
+ else {
2049
+ await upsertTaskSession({
2050
+ companyId: agent.companyId,
2051
+ agentId: agent.id,
2052
+ adapterType: agent.adapterType,
2053
+ taskKey,
2054
+ sessionParamsJson: nextSessionState.params,
2055
+ sessionDisplayId: nextSessionState.displayId,
2056
+ lastRunId: finalizedRun.id,
2057
+ lastError: outcome === "succeeded" ? null : (adapterResult.errorMessage ?? "run_failed"),
2058
+ });
2059
+ }
2060
+ }
2061
+ }
2062
+ await finalizeAgentStatus(agent.id, outcome);
2063
+ }
2064
+ catch (err) {
2065
+ const message = redactCurrentUserText(err instanceof Error ? err.message : "Unknown adapter failure");
2066
+ logger.error({ err, runId }, "heartbeat execution failed");
2067
+ let logSummary = null;
2068
+ if (handle) {
2069
+ try {
2070
+ logSummary = await runLogStore.finalize(handle);
2071
+ }
2072
+ catch (finalizeErr) {
2073
+ logger.warn({ err: finalizeErr, runId }, "failed to finalize run log after error");
2074
+ }
2075
+ }
2076
+ const failedRun = await setRunStatus(run.id, "failed", {
2077
+ error: message,
2078
+ errorCode: "adapter_failed",
2079
+ finishedAt: new Date(),
2080
+ stdoutExcerpt,
2081
+ stderrExcerpt,
2082
+ logBytes: logSummary?.bytes,
2083
+ logSha256: logSummary?.sha256,
2084
+ logCompressed: logSummary?.compressed ?? false,
2085
+ });
2086
+ await setWakeupStatus(run.wakeupRequestId, "failed", {
2087
+ finishedAt: new Date(),
2088
+ error: message,
2089
+ });
2090
+ if (failedRun) {
2091
+ await appendRunEvent(failedRun, seq++, {
2092
+ eventType: "error",
2093
+ stream: "system",
2094
+ level: "error",
2095
+ message,
2096
+ });
2097
+ await releaseIssueExecutionAndPromote(failedRun);
2098
+ await updateRuntimeState(agent, failedRun, {
2099
+ exitCode: null,
2100
+ signal: null,
2101
+ timedOut: false,
2102
+ errorMessage: message,
2103
+ }, {
2104
+ legacySessionId: runtimeForAdapter.sessionId,
2105
+ });
2106
+ if (taskKey && (previousSessionParams || previousSessionDisplayId || taskSession)) {
2107
+ await upsertTaskSession({
2108
+ companyId: agent.companyId,
2109
+ agentId: agent.id,
2110
+ adapterType: agent.adapterType,
2111
+ taskKey,
2112
+ sessionParamsJson: previousSessionParams,
2113
+ sessionDisplayId: previousSessionDisplayId,
2114
+ lastRunId: failedRun.id,
2115
+ lastError: message,
2116
+ });
2117
+ }
2118
+ }
2119
+ await finalizeAgentStatus(agent.id, "failed");
2120
+ }
2121
+ }
2122
+ catch (outerErr) {
2123
+ // Setup code before adapter.execute threw (e.g. ensureRuntimeState, resolveWorkspaceForRun).
2124
+ // The inner catch did not fire, so we must record the failure here.
2125
+ const message = outerErr instanceof Error ? outerErr.message : "Unknown setup failure";
2126
+ logger.error({ err: outerErr, runId }, "heartbeat execution setup failed");
2127
+ await setRunStatus(runId, "failed", {
2128
+ error: message,
2129
+ errorCode: "adapter_failed",
2130
+ finishedAt: new Date(),
2131
+ }).catch(() => undefined);
2132
+ await setWakeupStatus(run.wakeupRequestId, "failed", {
2133
+ finishedAt: new Date(),
2134
+ error: message,
2135
+ }).catch(() => undefined);
2136
+ const failedRun = await getRun(runId).catch(() => null);
2137
+ if (failedRun) {
2138
+ // Emit a run-log event so the failure is visible in the run timeline,
2139
+ // consistent with what the inner catch block does for adapter failures.
2140
+ await appendRunEvent(failedRun, 1, {
2141
+ eventType: "error",
2142
+ stream: "system",
2143
+ level: "error",
2144
+ message,
2145
+ }).catch(() => undefined);
2146
+ await releaseIssueExecutionAndPromote(failedRun).catch(() => undefined);
2147
+ }
2148
+ // Ensure the agent is not left stuck in "running" if the inner catch handler's
2149
+ // DB calls threw (e.g. a transient DB error in finalizeAgentStatus).
2150
+ await finalizeAgentStatus(run.agentId, "failed").catch(() => undefined);
2151
+ }
2152
+ finally {
2153
+ await releaseRuntimeServicesForRun(run.id).catch(() => undefined);
2154
+ activeRunExecutions.delete(run.id);
2155
+ await startNextQueuedRunForAgent(run.agentId);
2156
+ }
2157
+ }
2158
+ async function releaseIssueExecutionAndPromote(run) {
2159
+ const promotedRun = await db.transaction(async (tx) => {
2160
+ await tx.execute(sql `select id from issues where company_id = ${run.companyId} and execution_run_id = ${run.id} for update`);
2161
+ const issue = await tx
2162
+ .select({
2163
+ id: issues.id,
2164
+ companyId: issues.companyId,
2165
+ })
2166
+ .from(issues)
2167
+ .where(and(eq(issues.companyId, run.companyId), eq(issues.executionRunId, run.id)))
2168
+ .then((rows) => rows[0] ?? null);
2169
+ if (!issue)
2170
+ return;
2171
+ await tx
2172
+ .update(issues)
2173
+ .set({
2174
+ executionRunId: null,
2175
+ executionAgentNameKey: null,
2176
+ executionLockedAt: null,
2177
+ updatedAt: new Date(),
2178
+ })
2179
+ .where(eq(issues.id, issue.id));
2180
+ while (true) {
2181
+ const deferred = await tx
2182
+ .select()
2183
+ .from(agentWakeupRequests)
2184
+ .where(and(eq(agentWakeupRequests.companyId, issue.companyId), eq(agentWakeupRequests.status, "deferred_issue_execution"), sql `${agentWakeupRequests.payload} ->> 'issueId' = ${issue.id}`))
2185
+ .orderBy(asc(agentWakeupRequests.requestedAt))
2186
+ .limit(1)
2187
+ .then((rows) => rows[0] ?? null);
2188
+ if (!deferred)
2189
+ return null;
2190
+ const deferredAgent = await tx
2191
+ .select()
2192
+ .from(agents)
2193
+ .where(eq(agents.id, deferred.agentId))
2194
+ .then((rows) => rows[0] ?? null);
2195
+ if (!deferredAgent ||
2196
+ deferredAgent.companyId !== issue.companyId ||
2197
+ deferredAgent.status === "paused" ||
2198
+ deferredAgent.status === "terminated" ||
2199
+ deferredAgent.status === "pending_approval") {
2200
+ await tx
2201
+ .update(agentWakeupRequests)
2202
+ .set({
2203
+ status: "failed",
2204
+ finishedAt: new Date(),
2205
+ error: "Deferred wake could not be promoted: agent is not invokable",
2206
+ updatedAt: new Date(),
2207
+ })
2208
+ .where(eq(agentWakeupRequests.id, deferred.id));
2209
+ continue;
2210
+ }
2211
+ const deferredPayload = parseObject(deferred.payload);
2212
+ const deferredContextSeed = parseObject(deferredPayload[DEFERRED_WAKE_CONTEXT_KEY]);
2213
+ const promotedContextSeed = { ...deferredContextSeed };
2214
+ const promotedReason = readNonEmptyString(deferred.reason) ?? "issue_execution_promoted";
2215
+ const promotedSource = readNonEmptyString(deferred.source) ?? "automation";
2216
+ const promotedTriggerDetail = readNonEmptyString(deferred.triggerDetail) ?? null;
2217
+ const promotedPayload = deferredPayload;
2218
+ delete promotedPayload[DEFERRED_WAKE_CONTEXT_KEY];
2219
+ const { contextSnapshot: promotedContextSnapshot, taskKey: promotedTaskKey, } = enrichWakeContextSnapshot({
2220
+ contextSnapshot: promotedContextSeed,
2221
+ reason: promotedReason,
2222
+ source: promotedSource,
2223
+ triggerDetail: promotedTriggerDetail,
2224
+ payload: promotedPayload,
2225
+ });
2226
+ const deferredPolicy = parseHeartbeatPolicy(deferredAgent);
2227
+ const [promotionQueueCountRow] = await tx
2228
+ .select({ count: sql `count(*)::int` })
2229
+ .from(heartbeatRuns)
2230
+ .where(and(eq(heartbeatRuns.agentId, deferredAgent.id), eq(heartbeatRuns.status, "queued")));
2231
+ const promotionQueuedCount = Number(promotionQueueCountRow?.count ?? 0);
2232
+ if (promotionQueuedCount >= deferredPolicy.maxQueuedRuns) {
2233
+ logger.info({ agentId: deferredAgent.id, wakeupId: deferred.id, promotionQueuedCount, maxQueuedRuns: deferredPolicy.maxQueuedRuns }, "deferred promotion suppressed by maxQueuedRuns cap; will retry on next issue release");
2234
+ return null;
2235
+ }
2236
+ const sessionBefore = await resolveSessionBeforeForWakeup(deferredAgent, promotedTaskKey);
2237
+ const now = new Date();
2238
+ const newRun = await tx
2239
+ .insert(heartbeatRuns)
2240
+ .values({
2241
+ companyId: deferredAgent.companyId,
2242
+ agentId: deferredAgent.id,
2243
+ invocationSource: promotedSource,
2244
+ triggerDetail: promotedTriggerDetail,
2245
+ status: "queued",
2246
+ wakeupRequestId: deferred.id,
2247
+ contextSnapshot: promotedContextSnapshot,
2248
+ sessionIdBefore: sessionBefore,
2249
+ })
2250
+ .returning()
2251
+ .then((rows) => rows[0]);
2252
+ await tx
2253
+ .update(agentWakeupRequests)
2254
+ .set({
2255
+ status: "queued",
2256
+ reason: "issue_execution_promoted",
2257
+ runId: newRun.id,
2258
+ claimedAt: null,
2259
+ finishedAt: null,
2260
+ error: null,
2261
+ updatedAt: now,
2262
+ })
2263
+ .where(eq(agentWakeupRequests.id, deferred.id));
2264
+ await tx
2265
+ .update(issues)
2266
+ .set({
2267
+ executionRunId: newRun.id,
2268
+ executionAgentNameKey: normalizeAgentNameKey(deferredAgent.name),
2269
+ executionLockedAt: now,
2270
+ updatedAt: now,
2271
+ })
2272
+ .where(eq(issues.id, issue.id));
2273
+ return newRun;
2274
+ }
2275
+ });
2276
+ if (!promotedRun)
2277
+ return;
2278
+ publishLiveEvent({
2279
+ companyId: promotedRun.companyId,
2280
+ type: "heartbeat.run.queued",
2281
+ payload: {
2282
+ runId: promotedRun.id,
2283
+ agentId: promotedRun.agentId,
2284
+ invocationSource: promotedRun.invocationSource,
2285
+ triggerDetail: promotedRun.triggerDetail,
2286
+ wakeupRequestId: promotedRun.wakeupRequestId,
2287
+ },
2288
+ });
2289
+ await startNextQueuedRunForAgent(promotedRun.agentId);
2290
+ }
2291
+ async function enqueueWakeup(agentId, opts = {}) {
2292
+ const source = opts.source ?? "on_demand";
2293
+ const triggerDetail = opts.triggerDetail ?? null;
2294
+ const contextSnapshot = { ...(opts.contextSnapshot ?? {}) };
2295
+ const reason = opts.reason ?? null;
2296
+ const payload = opts.payload ?? null;
2297
+ const { contextSnapshot: enrichedContextSnapshot, issueIdFromPayload, taskKey, wakeCommentId, } = enrichWakeContextSnapshot({
2298
+ contextSnapshot,
2299
+ reason,
2300
+ source,
2301
+ triggerDetail,
2302
+ payload,
2303
+ });
2304
+ const issueId = readNonEmptyString(enrichedContextSnapshot.issueId) ?? issueIdFromPayload;
2305
+ const agent = await getAgent(agentId);
2306
+ if (!agent)
2307
+ throw notFound("Agent not found");
2308
+ const writeSkippedRequest = async (skipReason) => {
2309
+ await db.insert(agentWakeupRequests).values({
2310
+ companyId: agent.companyId,
2311
+ agentId,
2312
+ source,
2313
+ triggerDetail,
2314
+ reason: skipReason,
2315
+ payload,
2316
+ status: "skipped",
2317
+ requestedByActorType: opts.requestedByActorType ?? null,
2318
+ requestedByActorId: opts.requestedByActorId ?? null,
2319
+ idempotencyKey: opts.idempotencyKey ?? null,
2320
+ finishedAt: new Date(),
2321
+ });
2322
+ };
2323
+ let projectId = readNonEmptyString(enrichedContextSnapshot.projectId);
2324
+ if (!projectId && issueId) {
2325
+ projectId = await db
2326
+ .select({ projectId: issues.projectId })
2327
+ .from(issues)
2328
+ .where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId)))
2329
+ .then((rows) => rows[0]?.projectId ?? null);
2330
+ }
2331
+ const budgetBlock = await budgets.getInvocationBlock(agent.companyId, agentId, {
2332
+ issueId,
2333
+ projectId,
2334
+ });
2335
+ if (budgetBlock) {
2336
+ await writeSkippedRequest("budget.blocked");
2337
+ throw conflict(budgetBlock.reason, {
2338
+ scopeType: budgetBlock.scopeType,
2339
+ scopeId: budgetBlock.scopeId,
2340
+ });
2341
+ }
2342
+ if (agent.status === "paused" ||
2343
+ agent.status === "terminated" ||
2344
+ agent.status === "pending_approval") {
2345
+ throw conflict("Agent is not invokable in its current state", { status: agent.status });
2346
+ }
2347
+ const policy = parseHeartbeatPolicy(agent);
2348
+ if (source === "timer" && !policy.enabled) {
2349
+ await writeSkippedRequest("heartbeat.disabled");
2350
+ return null;
2351
+ }
2352
+ if (source !== "timer" && !policy.wakeOnDemand) {
2353
+ await writeSkippedRequest("heartbeat.wakeOnDemand.disabled");
2354
+ return null;
2355
+ }
2356
+ const bypassIssueExecutionLock = reason === "issue_comment_mentioned" ||
2357
+ readNonEmptyString(enrichedContextSnapshot.wakeReason) === "issue_comment_mentioned";
2358
+ if (issueId && !bypassIssueExecutionLock) {
2359
+ const agentNameKey = normalizeAgentNameKey(agent.name);
2360
+ const sessionBefore = await resolveSessionBeforeForWakeup(agent, taskKey);
2361
+ const outcome = await db.transaction(async (tx) => {
2362
+ await tx.execute(sql `select id from issues where id = ${issueId} and company_id = ${agent.companyId} for update`);
2363
+ const issue = await tx
2364
+ .select({
2365
+ id: issues.id,
2366
+ companyId: issues.companyId,
2367
+ executionRunId: issues.executionRunId,
2368
+ executionAgentNameKey: issues.executionAgentNameKey,
2369
+ })
2370
+ .from(issues)
2371
+ .where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId)))
2372
+ .then((rows) => rows[0] ?? null);
2373
+ if (!issue) {
2374
+ await tx.insert(agentWakeupRequests).values({
2375
+ companyId: agent.companyId,
2376
+ agentId,
2377
+ source,
2378
+ triggerDetail,
2379
+ reason: "issue_execution_issue_not_found",
2380
+ payload,
2381
+ status: "skipped",
2382
+ requestedByActorType: opts.requestedByActorType ?? null,
2383
+ requestedByActorId: opts.requestedByActorId ?? null,
2384
+ idempotencyKey: opts.idempotencyKey ?? null,
2385
+ finishedAt: new Date(),
2386
+ });
2387
+ return { kind: "skipped" };
2388
+ }
2389
+ let activeExecutionRun = issue.executionRunId
2390
+ ? await tx
2391
+ .select()
2392
+ .from(heartbeatRuns)
2393
+ .where(eq(heartbeatRuns.id, issue.executionRunId))
2394
+ .then((rows) => rows[0] ?? null)
2395
+ : null;
2396
+ if (activeExecutionRun && activeExecutionRun.status !== "queued" && activeExecutionRun.status !== "running") {
2397
+ activeExecutionRun = null;
2398
+ }
2399
+ if (!activeExecutionRun && issue.executionRunId) {
2400
+ await tx
2401
+ .update(issues)
2402
+ .set({
2403
+ executionRunId: null,
2404
+ executionAgentNameKey: null,
2405
+ executionLockedAt: null,
2406
+ updatedAt: new Date(),
2407
+ })
2408
+ .where(eq(issues.id, issue.id));
2409
+ }
2410
+ if (!activeExecutionRun) {
2411
+ const legacyRun = await tx
2412
+ .select()
2413
+ .from(heartbeatRuns)
2414
+ .where(and(eq(heartbeatRuns.companyId, issue.companyId), inArray(heartbeatRuns.status, ["queued", "running"]), sql `${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issue.id}`))
2415
+ .orderBy(sql `case when ${heartbeatRuns.status} = 'running' then 0 else 1 end`, asc(heartbeatRuns.createdAt))
2416
+ .limit(1)
2417
+ .then((rows) => rows[0] ?? null);
2418
+ if (legacyRun) {
2419
+ activeExecutionRun = legacyRun;
2420
+ const legacyAgent = await tx
2421
+ .select({ name: agents.name })
2422
+ .from(agents)
2423
+ .where(eq(agents.id, legacyRun.agentId))
2424
+ .then((rows) => rows[0] ?? null);
2425
+ await tx
2426
+ .update(issues)
2427
+ .set({
2428
+ executionRunId: legacyRun.id,
2429
+ executionAgentNameKey: normalizeAgentNameKey(legacyAgent?.name),
2430
+ executionLockedAt: new Date(),
2431
+ updatedAt: new Date(),
2432
+ })
2433
+ .where(eq(issues.id, issue.id));
2434
+ }
2435
+ }
2436
+ if (activeExecutionRun) {
2437
+ const executionAgent = await tx
2438
+ .select({ name: agents.name })
2439
+ .from(agents)
2440
+ .where(eq(agents.id, activeExecutionRun.agentId))
2441
+ .then((rows) => rows[0] ?? null);
2442
+ const executionAgentNameKey = normalizeAgentNameKey(issue.executionAgentNameKey) ??
2443
+ normalizeAgentNameKey(executionAgent?.name);
2444
+ const isSameExecutionAgent = Boolean(executionAgentNameKey) && executionAgentNameKey === agentNameKey;
2445
+ const shouldQueueFollowupForCommentWake = Boolean(wakeCommentId) &&
2446
+ activeExecutionRun.status === "running" &&
2447
+ isSameExecutionAgent;
2448
+ if (isSameExecutionAgent && !shouldQueueFollowupForCommentWake) {
2449
+ const mergedContextSnapshot = mergeCoalescedContextSnapshot(activeExecutionRun.contextSnapshot, enrichedContextSnapshot);
2450
+ const mergedRun = await tx
2451
+ .update(heartbeatRuns)
2452
+ .set({
2453
+ contextSnapshot: mergedContextSnapshot,
2454
+ updatedAt: new Date(),
2455
+ })
2456
+ .where(eq(heartbeatRuns.id, activeExecutionRun.id))
2457
+ .returning()
2458
+ .then((rows) => rows[0] ?? activeExecutionRun);
2459
+ await tx.insert(agentWakeupRequests).values({
2460
+ companyId: agent.companyId,
2461
+ agentId,
2462
+ source,
2463
+ triggerDetail,
2464
+ reason: "issue_execution_same_name",
2465
+ payload,
2466
+ status: "coalesced",
2467
+ coalescedCount: 1,
2468
+ requestedByActorType: opts.requestedByActorType ?? null,
2469
+ requestedByActorId: opts.requestedByActorId ?? null,
2470
+ idempotencyKey: opts.idempotencyKey ?? null,
2471
+ runId: mergedRun.id,
2472
+ finishedAt: new Date(),
2473
+ });
2474
+ return { kind: "coalesced", run: mergedRun };
2475
+ }
2476
+ const deferredPayload = {
2477
+ ...(payload ?? {}),
2478
+ issueId,
2479
+ [DEFERRED_WAKE_CONTEXT_KEY]: enrichedContextSnapshot,
2480
+ };
2481
+ const existingDeferred = await tx
2482
+ .select()
2483
+ .from(agentWakeupRequests)
2484
+ .where(and(eq(agentWakeupRequests.companyId, agent.companyId), eq(agentWakeupRequests.agentId, agentId), eq(agentWakeupRequests.status, "deferred_issue_execution"), sql `${agentWakeupRequests.payload} ->> 'issueId' = ${issue.id}`))
2485
+ .orderBy(asc(agentWakeupRequests.requestedAt))
2486
+ .limit(1)
2487
+ .then((rows) => rows[0] ?? null);
2488
+ if (existingDeferred) {
2489
+ const existingDeferredPayload = parseObject(existingDeferred.payload);
2490
+ const existingDeferredContext = parseObject(existingDeferredPayload[DEFERRED_WAKE_CONTEXT_KEY]);
2491
+ const mergedDeferredContext = mergeCoalescedContextSnapshot(existingDeferredContext, enrichedContextSnapshot);
2492
+ const mergedDeferredPayload = {
2493
+ ...existingDeferredPayload,
2494
+ ...(payload ?? {}),
2495
+ issueId,
2496
+ [DEFERRED_WAKE_CONTEXT_KEY]: mergedDeferredContext,
2497
+ };
2498
+ await tx
2499
+ .update(agentWakeupRequests)
2500
+ .set({
2501
+ payload: mergedDeferredPayload,
2502
+ coalescedCount: (existingDeferred.coalescedCount ?? 0) + 1,
2503
+ updatedAt: new Date(),
2504
+ })
2505
+ .where(eq(agentWakeupRequests.id, existingDeferred.id));
2506
+ return { kind: "deferred" };
2507
+ }
2508
+ await tx.insert(agentWakeupRequests).values({
2509
+ companyId: agent.companyId,
2510
+ agentId,
2511
+ source,
2512
+ triggerDetail,
2513
+ reason: "issue_execution_deferred",
2514
+ payload: deferredPayload,
2515
+ status: "deferred_issue_execution",
2516
+ requestedByActorType: opts.requestedByActorType ?? null,
2517
+ requestedByActorId: opts.requestedByActorId ?? null,
2518
+ idempotencyKey: opts.idempotencyKey ?? null,
2519
+ });
2520
+ return { kind: "deferred" };
2521
+ }
2522
+ const [queueCountRow] = await tx
2523
+ .select({ count: sql `count(*)::int` })
2524
+ .from(heartbeatRuns)
2525
+ .where(and(eq(heartbeatRuns.agentId, agent.id), eq(heartbeatRuns.status, "queued")));
2526
+ const issueScopedQueuedCount = Number(queueCountRow?.count ?? 0);
2527
+ if (issueScopedQueuedCount >= policy.maxQueuedRuns) {
2528
+ await tx.insert(agentWakeupRequests).values({
2529
+ companyId: agent.companyId,
2530
+ agentId,
2531
+ source,
2532
+ triggerDetail,
2533
+ reason: "heartbeat.maxQueuedRuns.exceeded",
2534
+ payload,
2535
+ status: "skipped",
2536
+ requestedByActorType: opts.requestedByActorType ?? null,
2537
+ requestedByActorId: opts.requestedByActorId ?? null,
2538
+ idempotencyKey: opts.idempotencyKey ?? null,
2539
+ finishedAt: new Date(),
2540
+ });
2541
+ return { kind: "capped" };
2542
+ }
2543
+ const wakeupRequest = await tx
2544
+ .insert(agentWakeupRequests)
2545
+ .values({
2546
+ companyId: agent.companyId,
2547
+ agentId,
2548
+ source,
2549
+ triggerDetail,
2550
+ reason,
2551
+ payload,
2552
+ status: "queued",
2553
+ requestedByActorType: opts.requestedByActorType ?? null,
2554
+ requestedByActorId: opts.requestedByActorId ?? null,
2555
+ idempotencyKey: opts.idempotencyKey ?? null,
2556
+ })
2557
+ .returning()
2558
+ .then((rows) => rows[0]);
2559
+ const newRun = await tx
2560
+ .insert(heartbeatRuns)
2561
+ .values({
2562
+ companyId: agent.companyId,
2563
+ agentId,
2564
+ invocationSource: source,
2565
+ triggerDetail,
2566
+ status: "queued",
2567
+ wakeupRequestId: wakeupRequest.id,
2568
+ contextSnapshot: enrichedContextSnapshot,
2569
+ sessionIdBefore: sessionBefore,
2570
+ })
2571
+ .returning()
2572
+ .then((rows) => rows[0]);
2573
+ await tx
2574
+ .update(agentWakeupRequests)
2575
+ .set({
2576
+ runId: newRun.id,
2577
+ updatedAt: new Date(),
2578
+ })
2579
+ .where(eq(agentWakeupRequests.id, wakeupRequest.id));
2580
+ await tx
2581
+ .update(issues)
2582
+ .set({
2583
+ executionRunId: newRun.id,
2584
+ executionAgentNameKey: agentNameKey,
2585
+ executionLockedAt: new Date(),
2586
+ updatedAt: new Date(),
2587
+ })
2588
+ .where(eq(issues.id, issue.id));
2589
+ return { kind: "queued", run: newRun };
2590
+ });
2591
+ if (outcome.kind === "deferred" || outcome.kind === "skipped" || outcome.kind === "capped")
2592
+ return null;
2593
+ if (outcome.kind === "coalesced")
2594
+ return outcome.run;
2595
+ const newRun = outcome.run;
2596
+ publishLiveEvent({
2597
+ companyId: newRun.companyId,
2598
+ type: "heartbeat.run.queued",
2599
+ payload: {
2600
+ runId: newRun.id,
2601
+ agentId: newRun.agentId,
2602
+ invocationSource: newRun.invocationSource,
2603
+ triggerDetail: newRun.triggerDetail,
2604
+ wakeupRequestId: newRun.wakeupRequestId,
2605
+ },
2606
+ });
2607
+ await startNextQueuedRunForAgent(agent.id);
2608
+ return newRun;
2609
+ }
2610
+ const activeRuns = await db
2611
+ .select()
2612
+ .from(heartbeatRuns)
2613
+ .where(and(eq(heartbeatRuns.agentId, agentId), inArray(heartbeatRuns.status, ["queued", "running"])))
2614
+ .orderBy(desc(heartbeatRuns.createdAt));
2615
+ const sameScopeQueuedRun = activeRuns.find((candidate) => candidate.status === "queued" && isSameTaskScope(runTaskKey(candidate), taskKey));
2616
+ const sameScopeRunningRun = activeRuns.find((candidate) => candidate.status === "running" && isSameTaskScope(runTaskKey(candidate), taskKey));
2617
+ const shouldQueueFollowupForCommentWake = Boolean(wakeCommentId) && Boolean(sameScopeRunningRun) && !sameScopeQueuedRun;
2618
+ const coalescedTargetRun = sameScopeQueuedRun ??
2619
+ (shouldQueueFollowupForCommentWake ? null : sameScopeRunningRun ?? null);
2620
+ if (coalescedTargetRun) {
2621
+ const mergedContextSnapshot = mergeCoalescedContextSnapshot(coalescedTargetRun.contextSnapshot, contextSnapshot);
2622
+ const mergedRun = await db
2623
+ .update(heartbeatRuns)
2624
+ .set({
2625
+ contextSnapshot: mergedContextSnapshot,
2626
+ updatedAt: new Date(),
2627
+ })
2628
+ .where(eq(heartbeatRuns.id, coalescedTargetRun.id))
2629
+ .returning()
2630
+ .then((rows) => rows[0] ?? coalescedTargetRun);
2631
+ await db.insert(agentWakeupRequests).values({
2632
+ companyId: agent.companyId,
2633
+ agentId,
2634
+ source,
2635
+ triggerDetail,
2636
+ reason,
2637
+ payload,
2638
+ status: "coalesced",
2639
+ coalescedCount: 1,
2640
+ requestedByActorType: opts.requestedByActorType ?? null,
2641
+ requestedByActorId: opts.requestedByActorId ?? null,
2642
+ idempotencyKey: opts.idempotencyKey ?? null,
2643
+ runId: mergedRun.id,
2644
+ finishedAt: new Date(),
2645
+ });
2646
+ return mergedRun;
2647
+ }
2648
+ const admission = await canEnqueueRun(agent);
2649
+ if (!admission.allowed) {
2650
+ await writeSkippedRequest("heartbeat.maxQueuedRuns.exceeded");
2651
+ return null;
2652
+ }
2653
+ const wakeupRequest = await db
2654
+ .insert(agentWakeupRequests)
2655
+ .values({
2656
+ companyId: agent.companyId,
2657
+ agentId,
2658
+ source,
2659
+ triggerDetail,
2660
+ reason,
2661
+ payload,
2662
+ status: "queued",
2663
+ requestedByActorType: opts.requestedByActorType ?? null,
2664
+ requestedByActorId: opts.requestedByActorId ?? null,
2665
+ idempotencyKey: opts.idempotencyKey ?? null,
2666
+ })
2667
+ .returning()
2668
+ .then((rows) => rows[0]);
2669
+ const sessionBefore = await resolveSessionBeforeForWakeup(agent, taskKey);
2670
+ const newRun = await db
2671
+ .insert(heartbeatRuns)
2672
+ .values({
2673
+ companyId: agent.companyId,
2674
+ agentId,
2675
+ invocationSource: source,
2676
+ triggerDetail,
2677
+ status: "queued",
2678
+ wakeupRequestId: wakeupRequest.id,
2679
+ contextSnapshot: enrichedContextSnapshot,
2680
+ sessionIdBefore: sessionBefore,
2681
+ })
2682
+ .returning()
2683
+ .then((rows) => rows[0]);
2684
+ await db
2685
+ .update(agentWakeupRequests)
2686
+ .set({
2687
+ runId: newRun.id,
2688
+ updatedAt: new Date(),
2689
+ })
2690
+ .where(eq(agentWakeupRequests.id, wakeupRequest.id));
2691
+ publishLiveEvent({
2692
+ companyId: newRun.companyId,
2693
+ type: "heartbeat.run.queued",
2694
+ payload: {
2695
+ runId: newRun.id,
2696
+ agentId: newRun.agentId,
2697
+ invocationSource: newRun.invocationSource,
2698
+ triggerDetail: newRun.triggerDetail,
2699
+ wakeupRequestId: newRun.wakeupRequestId,
2700
+ },
2701
+ });
2702
+ await startNextQueuedRunForAgent(agent.id);
2703
+ return newRun;
2704
+ }
2705
+ async function listProjectScopedRunIds(companyId, projectId) {
2706
+ const runIssueId = sql `${heartbeatRuns.contextSnapshot} ->> 'issueId'`;
2707
+ const effectiveProjectId = sql `coalesce(${heartbeatRuns.contextSnapshot} ->> 'projectId', ${issues.projectId}::text)`;
2708
+ const rows = await db
2709
+ .selectDistinctOn([heartbeatRuns.id], { id: heartbeatRuns.id })
2710
+ .from(heartbeatRuns)
2711
+ .leftJoin(issues, and(eq(issues.companyId, companyId), sql `${issues.id}::text = ${runIssueId}`))
2712
+ .where(and(eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.status, ["queued", "running"]), sql `${effectiveProjectId} = ${projectId}`));
2713
+ return rows.map((row) => row.id);
2714
+ }
2715
+ async function listProjectScopedWakeupIds(companyId, projectId) {
2716
+ const wakeIssueId = sql `${agentWakeupRequests.payload} ->> 'issueId'`;
2717
+ const effectiveProjectId = sql `coalesce(${agentWakeupRequests.payload} ->> 'projectId', ${issues.projectId}::text)`;
2718
+ const rows = await db
2719
+ .selectDistinctOn([agentWakeupRequests.id], { id: agentWakeupRequests.id })
2720
+ .from(agentWakeupRequests)
2721
+ .leftJoin(issues, and(eq(issues.companyId, companyId), sql `${issues.id}::text = ${wakeIssueId}`))
2722
+ .where(and(eq(agentWakeupRequests.companyId, companyId), inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]), sql `${agentWakeupRequests.runId} is null`, sql `${effectiveProjectId} = ${projectId}`));
2723
+ return rows.map((row) => row.id);
2724
+ }
2725
+ async function cancelPendingWakeupsForBudgetScope(scope) {
2726
+ const now = new Date();
2727
+ let wakeupIds = [];
2728
+ if (scope.scopeType === "company") {
2729
+ wakeupIds = await db
2730
+ .select({ id: agentWakeupRequests.id })
2731
+ .from(agentWakeupRequests)
2732
+ .where(and(eq(agentWakeupRequests.companyId, scope.companyId), inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]), sql `${agentWakeupRequests.runId} is null`))
2733
+ .then((rows) => rows.map((row) => row.id));
2734
+ }
2735
+ else if (scope.scopeType === "agent") {
2736
+ wakeupIds = await db
2737
+ .select({ id: agentWakeupRequests.id })
2738
+ .from(agentWakeupRequests)
2739
+ .where(and(eq(agentWakeupRequests.companyId, scope.companyId), eq(agentWakeupRequests.agentId, scope.scopeId), inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]), sql `${agentWakeupRequests.runId} is null`))
2740
+ .then((rows) => rows.map((row) => row.id));
2741
+ }
2742
+ else {
2743
+ wakeupIds = await listProjectScopedWakeupIds(scope.companyId, scope.scopeId);
2744
+ }
2745
+ if (wakeupIds.length === 0)
2746
+ return 0;
2747
+ await db
2748
+ .update(agentWakeupRequests)
2749
+ .set({
2750
+ status: "cancelled",
2751
+ finishedAt: now,
2752
+ error: "Cancelled due to budget pause",
2753
+ updatedAt: now,
2754
+ })
2755
+ .where(inArray(agentWakeupRequests.id, wakeupIds));
2756
+ return wakeupIds.length;
2757
+ }
2758
+ async function cancelRunInternal(runId, reason = "Cancelled by control plane") {
2759
+ const run = await getRun(runId);
2760
+ if (!run)
2761
+ throw notFound("Heartbeat run not found");
2762
+ if (run.status !== "running" && run.status !== "queued")
2763
+ return run;
2764
+ const running = runningProcesses.get(run.id);
2765
+ if (running) {
2766
+ try {
2767
+ process.kill(-running.pid, "SIGTERM");
2768
+ }
2769
+ catch { /* process group already gone */ }
2770
+ const graceMs = Math.max(1, running.graceSec) * 1000;
2771
+ setTimeout(() => {
2772
+ try {
2773
+ process.kill(-running.pid, "SIGKILL");
2774
+ }
2775
+ catch { /* process group already gone */ }
2776
+ }, graceMs);
2777
+ }
2778
+ const cancelled = await setRunStatus(run.id, "cancelled", {
2779
+ finishedAt: new Date(),
2780
+ error: reason,
2781
+ errorCode: "cancelled",
2782
+ });
2783
+ await setWakeupStatus(run.wakeupRequestId, "cancelled", {
2784
+ finishedAt: new Date(),
2785
+ error: reason,
2786
+ });
2787
+ if (cancelled) {
2788
+ await appendRunEvent(cancelled, 1, {
2789
+ eventType: "lifecycle",
2790
+ stream: "system",
2791
+ level: "warn",
2792
+ message: "run cancelled",
2793
+ });
2794
+ await releaseIssueExecutionAndPromote(cancelled);
2795
+ }
2796
+ runningProcesses.delete(run.id);
2797
+ await finalizeAgentStatus(run.agentId, "cancelled");
2798
+ await startNextQueuedRunForAgent(run.agentId);
2799
+ return cancelled;
2800
+ }
2801
+ async function cancelActiveForAgentInternal(agentId, reason = "Cancelled due to agent pause") {
2802
+ const runs = await db
2803
+ .select()
2804
+ .from(heartbeatRuns)
2805
+ .where(and(eq(heartbeatRuns.agentId, agentId), inArray(heartbeatRuns.status, ["queued", "running"])));
2806
+ for (const run of runs) {
2807
+ await setRunStatus(run.id, "cancelled", {
2808
+ finishedAt: new Date(),
2809
+ error: reason,
2810
+ errorCode: "cancelled",
2811
+ });
2812
+ await setWakeupStatus(run.wakeupRequestId, "cancelled", {
2813
+ finishedAt: new Date(),
2814
+ error: reason,
2815
+ });
2816
+ const running = runningProcesses.get(run.id);
2817
+ if (running) {
2818
+ const { pid, graceSec } = running;
2819
+ try {
2820
+ process.kill(-pid, "SIGTERM");
2821
+ }
2822
+ catch { /* process group already gone */ }
2823
+ const graceMs = Math.max(1, graceSec) * 1000;
2824
+ setTimeout(() => {
2825
+ try {
2826
+ process.kill(-pid, "SIGKILL");
2827
+ }
2828
+ catch { /* process group already gone */ }
2829
+ }, graceMs);
2830
+ runningProcesses.delete(run.id);
2831
+ }
2832
+ await releaseIssueExecutionAndPromote(run);
2833
+ }
2834
+ return runs.length;
2835
+ }
2836
+ async function cancelBudgetScopeWork(scope) {
2837
+ if (scope.scopeType === "agent") {
2838
+ await cancelActiveForAgentInternal(scope.scopeId, "Cancelled due to budget pause");
2839
+ await cancelPendingWakeupsForBudgetScope(scope);
2840
+ return;
2841
+ }
2842
+ const runIds = scope.scopeType === "company"
2843
+ ? await db
2844
+ .select({ id: heartbeatRuns.id })
2845
+ .from(heartbeatRuns)
2846
+ .where(and(eq(heartbeatRuns.companyId, scope.companyId), inArray(heartbeatRuns.status, ["queued", "running"])))
2847
+ .then((rows) => rows.map((row) => row.id))
2848
+ : await listProjectScopedRunIds(scope.companyId, scope.scopeId);
2849
+ for (const runId of runIds) {
2850
+ await cancelRunInternal(runId, "Cancelled due to budget pause");
2851
+ }
2852
+ await cancelPendingWakeupsForBudgetScope(scope);
2853
+ }
2854
+ return {
2855
+ list: async (companyId, agentId, limit) => {
2856
+ const query = db
2857
+ .select(heartbeatRunListColumns)
2858
+ .from(heartbeatRuns)
2859
+ .where(agentId
2860
+ ? and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.agentId, agentId))
2861
+ : eq(heartbeatRuns.companyId, companyId))
2862
+ .orderBy(desc(heartbeatRuns.createdAt));
2863
+ const rows = limit ? await query.limit(limit) : await query;
2864
+ return rows.map((row) => ({
2865
+ ...row,
2866
+ resultJson: summarizeHeartbeatRunResultJson(row.resultJson),
2867
+ }));
2868
+ },
2869
+ getRun,
2870
+ getRuntimeState: async (agentId) => {
2871
+ const state = await getRuntimeState(agentId);
2872
+ const agent = await getAgent(agentId);
2873
+ if (!agent)
2874
+ return null;
2875
+ const ensured = state ?? (await ensureRuntimeState(agent));
2876
+ const latestTaskSession = await db
2877
+ .select()
2878
+ .from(agentTaskSessions)
2879
+ .where(and(eq(agentTaskSessions.companyId, agent.companyId), eq(agentTaskSessions.agentId, agent.id)))
2880
+ .orderBy(desc(agentTaskSessions.updatedAt))
2881
+ .limit(1)
2882
+ .then((rows) => rows[0] ?? null);
2883
+ return {
2884
+ ...ensured,
2885
+ sessionDisplayId: latestTaskSession?.sessionDisplayId ?? ensured.sessionId,
2886
+ sessionParamsJson: latestTaskSession?.sessionParamsJson ?? null,
2887
+ };
2888
+ },
2889
+ listTaskSessions: async (agentId) => {
2890
+ const agent = await getAgent(agentId);
2891
+ if (!agent)
2892
+ throw notFound("Agent not found");
2893
+ return db
2894
+ .select()
2895
+ .from(agentTaskSessions)
2896
+ .where(and(eq(agentTaskSessions.companyId, agent.companyId), eq(agentTaskSessions.agentId, agentId)))
2897
+ .orderBy(desc(agentTaskSessions.updatedAt), desc(agentTaskSessions.createdAt));
2898
+ },
2899
+ resetRuntimeSession: async (agentId, opts) => {
2900
+ const agent = await getAgent(agentId);
2901
+ if (!agent)
2902
+ throw notFound("Agent not found");
2903
+ await ensureRuntimeState(agent);
2904
+ const taskKey = readNonEmptyString(opts?.taskKey);
2905
+ const clearedTaskSessions = await clearTaskSessions(agent.companyId, agent.id, taskKey ? { taskKey, adapterType: agent.adapterType } : undefined);
2906
+ const runtimePatch = {
2907
+ sessionId: null,
2908
+ lastError: null,
2909
+ updatedAt: new Date(),
2910
+ };
2911
+ if (!taskKey) {
2912
+ runtimePatch.stateJson = {};
2913
+ }
2914
+ const updated = await db
2915
+ .update(agentRuntimeState)
2916
+ .set(runtimePatch)
2917
+ .where(eq(agentRuntimeState.agentId, agentId))
2918
+ .returning()
2919
+ .then((rows) => rows[0] ?? null);
2920
+ if (!updated)
2921
+ return null;
2922
+ return {
2923
+ ...updated,
2924
+ sessionDisplayId: null,
2925
+ sessionParamsJson: null,
2926
+ clearedTaskSessions,
2927
+ };
2928
+ },
2929
+ listEvents: (runId, afterSeq = 0, limit = 200) => db
2930
+ .select()
2931
+ .from(heartbeatRunEvents)
2932
+ .where(and(eq(heartbeatRunEvents.runId, runId), gt(heartbeatRunEvents.seq, afterSeq)))
2933
+ .orderBy(asc(heartbeatRunEvents.seq))
2934
+ .limit(Math.max(1, Math.min(limit, 1000))),
2935
+ readLog: async (runId, opts) => {
2936
+ const run = await getRun(runId);
2937
+ if (!run)
2938
+ throw notFound("Heartbeat run not found");
2939
+ if (!run.logStore || !run.logRef)
2940
+ throw notFound("Run log not found");
2941
+ const result = await runLogStore.read({
2942
+ store: run.logStore,
2943
+ logRef: run.logRef,
2944
+ }, opts);
2945
+ return {
2946
+ runId,
2947
+ store: run.logStore,
2948
+ logRef: run.logRef,
2949
+ ...result,
2950
+ content: redactCurrentUserText(result.content),
2951
+ };
2952
+ },
2953
+ invoke: async (agentId, source = "on_demand", contextSnapshot = {}, triggerDetail = "manual", actor) => enqueueWakeup(agentId, {
2954
+ source,
2955
+ triggerDetail,
2956
+ contextSnapshot,
2957
+ requestedByActorType: actor?.actorType,
2958
+ requestedByActorId: actor?.actorId ?? null,
2959
+ }),
2960
+ wakeup: enqueueWakeup,
2961
+ reapOrphanedRuns,
2962
+ reapOrphanedWorkspaceProcesses,
2963
+ expireTerminatedRunLocks,
2964
+ resumeQueuedRuns,
2965
+ tickTimers: async (now = new Date()) => {
2966
+ const allAgents = await db.select().from(agents);
2967
+ let checked = 0;
2968
+ let enqueued = 0;
2969
+ let skipped = 0;
2970
+ for (const agent of allAgents) {
2971
+ if (agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval")
2972
+ continue;
2973
+ const policy = parseHeartbeatPolicy(agent);
2974
+ if (!policy.enabled || policy.intervalSec <= 0)
2975
+ continue;
2976
+ checked += 1;
2977
+ const baseline = new Date(agent.lastHeartbeatAt ?? agent.createdAt).getTime();
2978
+ const elapsedMs = now.getTime() - baseline;
2979
+ if (elapsedMs < policy.intervalSec * 1000)
2980
+ continue;
2981
+ if (policy.skipTimerWhenNoAssignedOpenIssue) {
2982
+ const [{ count }] = await db
2983
+ .select({ count: sql `count(*)` })
2984
+ .from(issues)
2985
+ .where(and(eq(issues.companyId, agent.companyId), eq(issues.assigneeAgentId, agent.id), inArray(issues.status, ["todo", "in_progress", "blocked", "in_review"])));
2986
+ if (shouldSkipTimerWake(agent.runtimeConfig, Number(count ?? 0))) {
2987
+ skipped += 1;
2988
+ continue;
2989
+ }
2990
+ }
2991
+ const run = await enqueueWakeup(agent.id, {
2992
+ source: "timer",
2993
+ triggerDetail: "system",
2994
+ reason: "heartbeat_timer",
2995
+ requestedByActorType: "system",
2996
+ requestedByActorId: "heartbeat_scheduler",
2997
+ contextSnapshot: {
2998
+ source: "scheduler",
2999
+ reason: "interval_elapsed",
3000
+ now: now.toISOString(),
3001
+ },
3002
+ });
3003
+ if (run)
3004
+ enqueued += 1;
3005
+ else
3006
+ skipped += 1;
3007
+ }
3008
+ return { checked, enqueued, skipped };
3009
+ },
3010
+ cancelRun: (runId) => cancelRunInternal(runId),
3011
+ cancelActiveForAgent: (agentId) => cancelActiveForAgentInternal(agentId),
3012
+ cancelBudgetScopeWork,
3013
+ getActiveRunForAgent: async (agentId) => {
3014
+ const [run] = await db
3015
+ .select()
3016
+ .from(heartbeatRuns)
3017
+ .where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.status, "running")))
3018
+ .orderBy(desc(heartbeatRuns.startedAt))
3019
+ .limit(1);
3020
+ return run ?? null;
3021
+ },
3022
+ };
3023
+ }
3024
+ //# sourceMappingURL=heartbeat.js.map