@madarco/agentbox 0.27.1 → 0.28.0-nightly.202607251721

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 (364) hide show
  1. package/CHANGELOG.md +87 -4
  2. package/README.md +7 -3
  3. package/dist/_cloud-attach-XZYF324R.js +26 -0
  4. package/dist/admin-client-NOZ5CCAH.js +15 -0
  5. package/dist/chunk-2VW37PW4.js +1694 -0
  6. package/dist/chunk-2VW37PW4.js.map +1 -0
  7. package/dist/{chunk-HR7NHH5J.js → chunk-3UMM4VJH.js} +808 -57
  8. package/dist/chunk-3UMM4VJH.js.map +1 -0
  9. package/dist/chunk-5U5QOFL5.js +20 -0
  10. package/dist/chunk-5U5QOFL5.js.map +1 -0
  11. package/dist/chunk-6P6D77QP.js +285 -0
  12. package/dist/chunk-6P6D77QP.js.map +1 -0
  13. package/dist/chunk-6V366IZC.js +2892 -0
  14. package/dist/chunk-6V366IZC.js.map +1 -0
  15. package/dist/{chunk-KWOEUFVA.js → chunk-7J6G526Q.js} +6 -14
  16. package/dist/{chunk-KWOEUFVA.js.map → chunk-7J6G526Q.js.map} +1 -1
  17. package/dist/{chunk-IDH5A4RR.js → chunk-AYPAYY5R.js} +17 -4
  18. package/dist/chunk-AYPAYY5R.js.map +1 -0
  19. package/dist/{chunk-JGZSA5ZI.js → chunk-BHJCMTHP.js} +58 -15
  20. package/dist/chunk-BHJCMTHP.js.map +1 -0
  21. package/dist/{chunk-26IKZRTT.js → chunk-BLWAWGFX.js} +297 -1217
  22. package/dist/chunk-BLWAWGFX.js.map +1 -0
  23. package/dist/chunk-CGPUFXET.js +95 -0
  24. package/dist/chunk-CGPUFXET.js.map +1 -0
  25. package/dist/{chunk-SJ75AIA2.js → chunk-D6AODRNA.js} +12 -9
  26. package/dist/{chunk-SJ75AIA2.js.map → chunk-D6AODRNA.js.map} +1 -1
  27. package/dist/chunk-DPJMEG7U.js +11 -0
  28. package/dist/chunk-DPJMEG7U.js.map +1 -0
  29. package/dist/chunk-E2ITEZAQ.js +148 -0
  30. package/dist/chunk-E2ITEZAQ.js.map +1 -0
  31. package/dist/{chunk-JE6UI5YR.js → chunk-NKVCIH6N.js} +89 -223
  32. package/dist/chunk-NKVCIH6N.js.map +1 -0
  33. package/dist/chunk-OEYAVBA6.js +120 -0
  34. package/dist/chunk-OEYAVBA6.js.map +1 -0
  35. package/dist/{chunk-UJEH2NJT.js → chunk-PXYPQ5BO.js} +64 -264
  36. package/dist/chunk-PXYPQ5BO.js.map +1 -0
  37. package/dist/chunk-QESXSSO6.js +670 -0
  38. package/dist/chunk-QESXSSO6.js.map +1 -0
  39. package/dist/{chunk-NEF6MDJO.js → chunk-QJCK2AFX.js} +128 -26
  40. package/dist/chunk-QJCK2AFX.js.map +1 -0
  41. package/dist/chunk-RUJJY23M.js +84 -0
  42. package/dist/chunk-RUJJY23M.js.map +1 -0
  43. package/dist/{chunk-LL7NCMUU.js → chunk-SKNJRYM5.js} +7 -13
  44. package/dist/chunk-SKNJRYM5.js.map +1 -0
  45. package/dist/chunk-WFGAMJ5Q.js +689 -0
  46. package/dist/chunk-WFGAMJ5Q.js.map +1 -0
  47. package/dist/chunk-ZJL56TJD.js +1444 -0
  48. package/dist/chunk-ZJL56TJD.js.map +1 -0
  49. package/dist/{chunk-V5XXJH63.js → chunk-ZXOP4LBG.js} +5 -8
  50. package/dist/chunk-ZXOP4LBG.js.map +1 -0
  51. package/dist/control-plane-2VEM2KCL.js +31 -0
  52. package/dist/custody-client-P6XIXHRG.js +16 -0
  53. package/dist/{dist-TSFVB7AI.js → dist-2SYQI5S2.js} +11 -7
  54. package/dist/dist-2SYQI5S2.js.map +1 -0
  55. package/dist/{dist-KQTMCVME.js → dist-6QZMZEL7.js} +18 -11
  56. package/dist/dist-6QZMZEL7.js.map +1 -0
  57. package/dist/{dist-FTKS2GI4.js → dist-JHMILJUT.js} +10 -6
  58. package/dist/{dist-OO52HARR.js → dist-JOFZOZCY.js} +41 -25
  59. package/dist/{dist-O3LKOIE7.js → dist-KZ2GEEEX.js} +11 -7
  60. package/dist/dist-KZ2GEEEX.js.map +1 -0
  61. package/dist/{dist-Z6L5MM5D.js → dist-Q5NY4CF6.js} +10 -6
  62. package/dist/{dist-U2SVLJUQ.js → dist-SKMNEDVW.js} +8 -2
  63. package/dist/dist-SKMNEDVW.js.map +1 -0
  64. package/dist/dist-SRCKO7ZV.js +197 -0
  65. package/dist/dist-SRCKO7ZV.js.map +1 -0
  66. package/dist/{dist-WVYAURMF.js → dist-UXZQWKY6.js} +10 -6
  67. package/dist/dist-UXZQWKY6.js.map +1 -0
  68. package/dist/env-file-UDUDQMP4.js +11 -0
  69. package/dist/env-file-UDUDQMP4.js.map +1 -0
  70. package/dist/hub-adopt-ZS5CREYF.js +21 -0
  71. package/dist/hub-adopt-ZS5CREYF.js.map +1 -0
  72. package/dist/index.js +2461 -1905
  73. package/dist/index.js.map +1 -1
  74. package/dist/node-postgres-6JUOVUN5.js +3584 -0
  75. package/dist/node-postgres-6JUOVUN5.js.map +1 -0
  76. package/dist/{prepared-state-75DIZ55S-TNJXWMXV.js → prepared-state-75DIZ55S-P6LE4N64.js} +3 -2
  77. package/dist/prepared-state-75DIZ55S-P6LE4N64.js.map +1 -0
  78. package/dist/remote-hub-SJ4XWBA5.js +9 -0
  79. package/dist/remote-hub-SJ4XWBA5.js.map +1 -0
  80. package/dist/sqlite-proxy-53E5D2VM.js +2882 -0
  81. package/dist/sqlite-proxy-53E5D2VM.js.map +1 -0
  82. package/package.json +1 -1
  83. package/runtime/_shared/ctl.cjs +29199 -16813
  84. package/runtime/digitalocean/ctl.cjs +29199 -16813
  85. package/runtime/docker/packages/ctl/dist/bin.cjs +29199 -16813
  86. package/runtime/e2b/ctl.cjs +29199 -16813
  87. package/runtime/hetzner/ctl.cjs +29199 -16813
  88. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  89. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  90. package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js +5 -5
  91. package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js.nft.json +1 -1
  92. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js +2 -2
  93. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js.nft.json +1 -1
  94. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js +2 -2
  95. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js.nft.json +1 -1
  96. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js +2 -2
  97. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js.nft.json +1 -1
  98. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js +2 -2
  99. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js.nft.json +1 -1
  100. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js +2 -2
  101. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js.nft.json +1 -1
  102. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js +2 -2
  103. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js.nft.json +1 -1
  104. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js +2 -2
  105. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js.nft.json +1 -1
  106. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js +2 -2
  107. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js.nft.json +1 -1
  108. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js +2 -2
  109. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js.nft.json +1 -1
  110. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js +2 -2
  111. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js.nft.json +1 -1
  112. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js +4 -4
  113. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js.nft.json +1 -1
  114. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js +2 -2
  115. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js.nft.json +1 -1
  116. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js +2 -2
  117. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js.nft.json +1 -1
  118. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js +2 -2
  119. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.nft.json +1 -1
  120. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js +2 -2
  121. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.nft.json +1 -1
  122. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js +2 -2
  123. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.nft.json +1 -1
  124. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js +2 -2
  125. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js.nft.json +1 -1
  126. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js +2 -2
  127. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js.nft.json +1 -1
  128. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js +2 -2
  129. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js.nft.json +1 -1
  130. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js +2 -2
  131. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js.nft.json +1 -1
  132. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js +2 -2
  133. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js.nft.json +1 -1
  134. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js +2 -2
  135. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js.nft.json +1 -1
  136. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js +2 -2
  137. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js.nft.json +1 -1
  138. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js +2 -2
  139. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js.nft.json +1 -1
  140. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js +2 -2
  141. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js.nft.json +1 -1
  142. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js +2 -2
  143. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js.nft.json +1 -1
  144. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js +2 -2
  145. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
  146. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
  147. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js +2 -2
  148. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.nft.json +1 -1
  149. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +1 -1
  150. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js +2 -2
  151. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -1
  152. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
  153. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js +2 -2
  154. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.nft.json +1 -1
  155. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page_client-reference-manifest.js +1 -1
  156. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js +2 -2
  157. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
  158. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  159. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js +4 -2
  160. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js.nft.json +1 -1
  161. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  162. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  163. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  164. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  165. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  166. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  167. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  168. package/runtime/hub/apps/hub/.next/server/chunks/0-fj_better-auth_dist_adapters_kysely-adapter_index_mjs_0btft52._.js +3 -0
  169. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_0gvv4ct._.js +4 -0
  170. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_0pn9b49._.js +4 -0
  171. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_145bz8z._.js +9 -0
  172. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_14y990b._.js +3 -0
  173. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_1nl4l3q._.js +3 -0
  174. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_sqlite-proxy_index_05v_j5r.js +15 -0
  175. package/runtime/hub/apps/hub/.next/server/chunks/{[externals]__12m3qoa._.js → [externals]__0f3aqcx._.js} +2 -2
  176. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-9g1s8._.js +3 -0
  177. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-pvfxg._.js +3 -0
  178. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__01amzh6._.js +3 -0
  179. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__02q799_._.js +3 -0
  180. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__03k22rl._.js +3 -0
  181. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04tqk-j._.js +3 -0
  182. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05ovf1y._.js +3 -0
  183. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05s-_x7._.js +3 -0
  184. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07dnyfi._.js +3 -0
  185. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07zk6qo._.js +3 -0
  186. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0_59yi6._.js +3 -0
  187. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ajlo3d._.js +3 -0
  188. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0b5s54n._.js +3 -0
  189. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c4fiez._.js +3 -0
  190. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c9iff1._.js +3 -0
  191. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d1lmiq._.js +5 -5
  192. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dh6lzr._.js +3 -0
  193. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ey83ai._.js +3 -0
  194. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0h6vdvr._.js +3 -0
  195. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lup7p4._.js +3 -0
  196. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0luxuu4._.js +3 -0
  197. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nl2u6u._.js +3 -0
  198. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nonp-6._.js +3 -0
  199. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0oplozy._.js +3 -0
  200. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0p-6wgd._.js +3 -0
  201. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0rcnwbw._.js +3 -0
  202. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0tuz1am._.js +3 -0
  203. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-9g0ae._.js +1 -1
  204. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10ry4ss._.js +3 -0
  205. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11hv164._.js +3 -0
  206. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__154_i13._.js +3 -0
  207. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__17676rc._.js +3 -0
  208. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bg1alc._.js +3 -0
  209. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1cvqb1d._.js +3 -0
  210. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d60gbz._.js +3 -0
  211. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dm0jmw._.js +6 -0
  212. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dv_b1t._.js +3 -0
  213. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1fzxip4._.js +3 -0
  214. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4oj-e._.js +3 -0
  215. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1i4gq_2._.js +3 -0
  216. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v1p7in._.js +3 -0
  217. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v9_her._.js +4 -0
  218. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1x1jkpb._.js +3 -0
  219. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1yd8n5l._.js +3 -0
  220. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20t_rs8._.js +3 -0
  221. package/runtime/hub/apps/hub/.next/server/chunks/_033w048._.js +1 -1
  222. package/runtime/hub/apps/hub/.next/server/chunks/_06f2faq._.js +1 -1
  223. package/runtime/hub/apps/hub/.next/server/chunks/{_0760z6y._.js → _0907rw0._.js} +15 -15
  224. package/runtime/hub/apps/hub/.next/server/chunks/_0f3molr._.js +1 -1
  225. package/runtime/hub/apps/hub/.next/server/chunks/_0lgs9kd._.js +1 -1
  226. package/runtime/hub/apps/hub/.next/server/chunks/_0pyhcqe._.js +1 -1
  227. package/runtime/hub/apps/hub/.next/server/chunks/_1-42ili._.js +1 -1
  228. package/runtime/hub/apps/hub/.next/server/chunks/_11__3wi._.js +1 -1
  229. package/runtime/hub/apps/hub/.next/server/chunks/_12flzuh._.js +1 -1
  230. package/runtime/hub/apps/hub/.next/server/chunks/_1bng7w9._.js +1 -1
  231. package/runtime/hub/apps/hub/.next/server/chunks/_1rpkqst._.js +1 -1
  232. package/runtime/hub/apps/hub/.next/server/chunks/_1wt72m1._.js +1 -1
  233. package/runtime/hub/apps/hub/.next/server/chunks/_1x3l5t8._.js +1 -1
  234. package/runtime/hub/apps/hub/.next/server/chunks/packages_relay_dist_control-plane_03a-9aj.js +62 -31
  235. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_0xy-j7z._.js +1 -1
  236. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_1uccfbf._.js +1 -1
  237. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_010858m.js +1 -1
  238. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_04zwxnx.js +1 -1
  239. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_06exuc7.js +1 -1
  240. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2ldrt.js +1 -1
  241. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2tzep.js +1 -1
  242. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_116nh32.js +1 -1
  243. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_11dyjcb.js +1 -1
  244. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_1_4knli.js +1 -1
  245. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0ebuy19._.js +3 -0
  246. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0wxhi0-._.js +3 -0
  247. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0xe4ick._.js +9 -0
  248. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_14oaveu._.js +4 -0
  249. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_sqlite-proxy_index_1a6wfdg.js +15 -0
  250. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0-pm2yl._.js +3 -0
  251. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__08-1wwu._.js +1 -1
  252. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0c9mbcn._.js +1 -1
  253. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0gdfxj4._.js +1 -1
  254. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0kc-hwp._.js +1 -1
  255. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0lu73p6._.js +1 -1
  256. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0m1yf2b._.js +4 -0
  257. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0wv-3zo._.js +3 -0
  258. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__10bfmwi._.js +1 -1
  259. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__18qvdzb._.js +2 -2
  260. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1l2urlw._.js +1 -1
  261. package/runtime/hub/apps/hub/.next/server/chunks/ssr/{_0ro6vh6._.js → _0r2xlss._.js} +3 -3
  262. package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_components_1z1p98f._.js +1 -1
  263. package/runtime/hub/apps/hub/.next/server/chunks/ssr/packages_relay_dist_control-plane_0ve-wz4.js +2 -25
  264. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  265. package/runtime/hub/apps/hub/.next/server/middleware.js +1 -1
  266. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  267. package/runtime/hub/apps/hub/.next/static/chunks/{2xc1sm79a6tsb.js → 2gsrna76i1d80.js} +1 -1
  268. package/runtime/hub/apps/hub/attach-helper.cjs +191 -0
  269. package/runtime/hub/apps/hub/{auth-DC44GQZY.js → auth-IRNNO3IK.js} +2 -2
  270. package/runtime/hub/apps/hub/{auth-config-LALRDYDO.js → auth-config-WJHIMGUE.js} +4 -2
  271. package/runtime/hub/apps/hub/{chunk-YJ5MJOXK.js → chunk-4LYVBRBC.js} +2094 -220
  272. package/runtime/hub/apps/hub/chunk-6AVSKCZJ.js +669 -0
  273. package/runtime/hub/apps/hub/{chunk-QSMPSV5Z.js → chunk-A5Y7LJMU.js} +57 -14
  274. package/runtime/hub/apps/hub/chunk-EDRFXO2M.js +35 -0
  275. package/runtime/hub/apps/hub/chunk-F2JI4GMX.js +2891 -0
  276. package/runtime/hub/apps/hub/{chunk-EHBJKZCL.js → chunk-O3K3ZGFF.js} +500 -35
  277. package/runtime/hub/apps/hub/chunk-RII6IKNJ.js +688 -0
  278. package/runtime/hub/apps/hub/{chunk-RXYOWSSN.js → chunk-RMEUA6PA.js} +120 -14
  279. package/runtime/hub/apps/hub/{chunk-3FJNKSNZ.js → chunk-SCHQR5KR.js} +3 -1
  280. package/runtime/hub/apps/hub/{dist-6FPPUSWZ.js → dist-2GEAA7QA.js} +15 -3
  281. package/runtime/hub/apps/hub/{dist-JG45OFT2.js → dist-36O6F6M3.js} +39 -24
  282. package/runtime/hub/apps/hub/{dist-3I7KUI6W.js → dist-IWLEL2TO.js} +21 -24
  283. package/runtime/hub/apps/hub/{dist-G6TXUSPZ.js → dist-NYKIT5W5.js} +10 -11
  284. package/runtime/hub/apps/hub/{dist-EQV4L7KP.js → dist-QB2IJ7OD.js} +7 -1
  285. package/runtime/hub/apps/hub/{dist-LYDHYTP2.js → dist-RBBXXGLI.js} +129 -26
  286. package/runtime/hub/apps/hub/{dist-GTVVXCBP.js → dist-RRJN2U5P.js} +10 -14
  287. package/runtime/hub/apps/hub/{dist-DX6IYMAH.js → dist-UWXGDCK4.js} +14 -11
  288. package/runtime/hub/apps/hub/{hub-token-COBZGSLS.js → hub-token-6USIMBPQ.js} +2 -2
  289. package/runtime/hub/apps/hub/hub-worker-SOFWVTWU.js +215 -0
  290. package/runtime/hub/apps/hub/node-postgres-DIU2H5VP.js +3583 -0
  291. package/runtime/hub/apps/hub/package.json +5 -2
  292. package/runtime/hub/apps/hub/{prepared-state-75DIZ55S-2IFNUHHM.js → prepared-state-75DIZ55S-P5FHEORG.js} +1 -1
  293. package/runtime/hub/apps/hub/server.js +247 -66
  294. package/runtime/hub/apps/hub/sqlite-proxy-VJS3HIOV.js +2881 -0
  295. package/runtime/relay/bin.cjs +694 -13
  296. package/runtime/vercel/ctl.cjs +29199 -16813
  297. package/dist/_cloud-attach-WDGM6FL5.js +0 -19
  298. package/dist/chunk-26IKZRTT.js.map +0 -1
  299. package/dist/chunk-HR7NHH5J.js.map +0 -1
  300. package/dist/chunk-IDH5A4RR.js.map +0 -1
  301. package/dist/chunk-JE6UI5YR.js.map +0 -1
  302. package/dist/chunk-JGZSA5ZI.js.map +0 -1
  303. package/dist/chunk-LL7NCMUU.js.map +0 -1
  304. package/dist/chunk-NEF6MDJO.js.map +0 -1
  305. package/dist/chunk-UJEH2NJT.js.map +0 -1
  306. package/dist/chunk-V5XXJH63.js.map +0 -1
  307. package/dist/dist-KQTMCVME.js.map +0 -1
  308. package/dist/dist-O3LKOIE7.js.map +0 -1
  309. package/dist/dist-TSFVB7AI.js.map +0 -1
  310. package/runtime/hub/apps/hub/.next/server/chunks/0zhp_better-auth_dist_adapters_kysely-adapter_index_mjs_1rl4qnh._.js +0 -3
  311. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04h15ml._.js +0 -3
  312. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04jgk9x._.js +0 -3
  313. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07ednlo._.js +0 -3
  314. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a7djvw._.js +0 -3
  315. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ig1bot._.js +0 -3
  316. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +0 -3
  317. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ql4fjo._.js +0 -3
  318. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0szd4sh._.js +0 -3
  319. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0t7o5ed._.js +0 -3
  320. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0vs8fma._.js +0 -3
  321. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0w9ud8u._.js +0 -3
  322. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xh14bo._.js +0 -3
  323. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yhb0gc._.js +0 -3
  324. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-0flwc._.js +0 -3
  325. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13ioh5z._.js +0 -3
  326. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13jwk_k._.js +0 -3
  327. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16_uteg._.js +0 -3
  328. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16p2m-g._.js +0 -3
  329. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19pc87s._.js +0 -3
  330. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_gu2yk._.js +0 -3
  331. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1a50b07._.js +0 -3
  332. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ai-945._.js +0 -3
  333. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bu2zio._.js +0 -3
  334. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ctczev._.js +0 -3
  335. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d6mtlk._.js +0 -3
  336. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dn_3i1._.js +0 -3
  337. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1e4z_-v._.js +0 -3
  338. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1f2sueq._.js +0 -3
  339. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1f9zctr._.js +0 -3
  340. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4xycg._.js +0 -3
  341. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hqla7-._.js +0 -3
  342. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1js2jdv._.js +0 -3
  343. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1md9kdw._.js +0 -3
  344. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mttufy._.js +0 -3
  345. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1nepkp-._.js +0 -6
  346. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1pp5oib._.js +0 -3
  347. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1q5bqse._.js +0 -3
  348. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qwhzmi._.js +0 -3
  349. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1thipug._.js +0 -3
  350. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v9om6g._.js +0 -3
  351. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1xeczo7._.js +0 -3
  352. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20503l7._.js +0 -3
  353. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[externals]_pg_20c820g._.js +0 -3
  354. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0j0tjwn._.js +0 -3
  355. /package/dist/{_cloud-attach-WDGM6FL5.js.map → _cloud-attach-XZYF324R.js.map} +0 -0
  356. /package/dist/{dist-FTKS2GI4.js.map → admin-client-NOZ5CCAH.js.map} +0 -0
  357. /package/dist/{dist-OO52HARR.js.map → control-plane-2VEM2KCL.js.map} +0 -0
  358. /package/dist/{dist-U2SVLJUQ.js.map → custody-client-P6XIXHRG.js.map} +0 -0
  359. /package/dist/{dist-WVYAURMF.js.map → dist-JHMILJUT.js.map} +0 -0
  360. /package/dist/{dist-Z6L5MM5D.js.map → dist-JOFZOZCY.js.map} +0 -0
  361. /package/dist/{prepared-state-75DIZ55S-TNJXWMXV.js.map → dist-Q5NY4CF6.js.map} +0 -0
  362. /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_buildManifest.js +0 -0
  363. /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_clientMiddlewareManifest.js +0 -0
  364. /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_ssgManifest.js +0 -0
@@ -1,10 +1,10 @@
1
- module.exports=[7876,73835,13272,t=>{"use strict";var e=t.i(24868),r=t.i(46786),s=t.i(14747),n=t.i(54799),a=class{map=new Map;register(t){this.map.set(t.boxId,t)}forget(t){return this.map.delete(t)}authenticate(t){if(0===t.length)return null;for(let e of this.map.values())if(e.token===t)return e;return null}get(t){return this.map.get(t)}list(){return[...this.map.values()]}size(){return this.map.size}},o=class{constructor(t=1e3){this.capacity=t}capacity;buf=[];nextId=1;append(t){let e={id:this.nextId++,receivedAt:new Date().toISOString(),...t};return this.buf.push(e),this.buf.length>this.capacity&&this.buf.shift(),e}since(t,e){let r=[];for(let s of this.buf)!(s.id<=t)&&(e&&s.boxId!==e||r.push(s));return r}all(){return this.buf.slice()}size(){return this.buf.length}};function i(t,e,n){let a=e.toLowerCase().replace(/-/g,"_").replace(/[^a-z0-9_]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"").slice(0,32)||"unnamed",o="number"==typeof n&&Number.isFinite(n)&&n>0?`${t}-${String(n)}-${a}`:`${t}-${a}`;return(0,s.join)((0,r.homedir)(),".agentbox","boxes",o)}function d(t){return"object"==typeof t&&null!==t&&1===t.schema&&"string"==typeof t.boxId&&t.boxId.length>0}var u=class{map=new Map;get(t){return this.map.get(t)}async set(t,r,n,a){this.map.set(t,a);let o=(0,s.join)(i(t,r,n),"status.json"),d=`${o}.${String(process.pid)}.tmp`;try{await (0,e.mkdir)(i(t,r,n),{recursive:!0}),await (0,e.writeFile)(d,JSON.stringify(a),"utf8"),await (0,e.rename)(d,o)}catch{await (0,e.rm)(d,{force:!0}).catch(()=>{})}}delete(t){this.map.delete(t)}},l=class{registry;events;statusStore;prompts=new Map;createJobs=new Map;constructor(t={}){this.registry=t.registry??new a,this.events=t.events??new o,this.statusStore=t.statusStore??new u}registerBox(t){return this.registry.register(t),Promise.resolve()}getBox(t){return Promise.resolve(this.registry.get(t))}authenticateBox(t){return Promise.resolve(this.registry.authenticate(t))}listBoxes(){return Promise.resolve(this.registry.list())}forgetBox(t){return Promise.resolve(this.registry.forget(t))}countBoxes(){return Promise.resolve(this.registry.size())}appendEvent(t){return Promise.resolve(this.events.append(t))}listEvents(t,e){return Promise.resolve(this.events.since(t,e))}countEvents(){return Promise.resolve(this.events.size())}setStatus(t,e,r,s){return this.statusStore.set(t,e,r,s)}getStatus(t){return Promise.resolve(this.statusStore.get(t))}deleteStatus(t){return this.statusStore.delete(t),Promise.resolve()}createPrompt(t){return this.prompts.set(t.id,{...t}),Promise.resolve()}getPrompt(t){let e=this.prompts.get(t);return Promise.resolve(e?{...e}:null)}answerPrompt(t,e,r){let s=this.prompts.get(t);return s&&"pending"===s.status?(s.status="answered",s.answer=e,s.cancelled=r,Promise.resolve(!0)):Promise.resolve(!1)}listPendingPrompts(t){let e=[];for(let r of this.prompts.values())r.boxId===t&&"pending"===r.status&&e.push({...r});return Promise.resolve(e)}setPromptResult(t,e){let r=this.prompts.get(t);return r&&(r.result=e),Promise.resolve()}enqueueCreateJob(t){return this.createJobs.set(t.id,{...t}),Promise.resolve()}getCreateJob(t){let e=this.createJobs.get(t);return Promise.resolve(e?{...e}:null)}claimNextCreateJob(t){let e=[...this.createJobs.values()].filter(t=>"queued"===t.status).sort((t,e)=>t.createdAt.localeCompare(e.createdAt))[0];return e?(e.status="running",e.claimedBy=t,e.startedAt=new Date().toISOString(),Promise.resolve({...e})):Promise.resolve(null)}completeCreateJob(t,e,r){let s=this.createJobs.get(t);return s&&(s.status=e,s.result=r,s.finishedAt=new Date().toISOString()),Promise.resolve()}};async function p(t,e,r,s,a){if("off"===process.env.AGENTBOX_PROMPT||t.consumeAutoApprove(r,s))return{answer:"y"};let o={id:(0,n.randomUUID)(),...s},i=t.add(r,o);if(e.broadcast(r,"prompt-ask",o),a?.ttlMs!==void 0&&a.ttlMs>0){let n=setTimeout(()=>{t.resolve(o.id,s.defaultAnswer??"n",!0)&&e.broadcast(r,"prompt-resolved",{id:o.id})},a.ttlMs);"function"==typeof n.unref&&n.unref(),i.then(()=>{clearTimeout(n)})}return i}async function c(t,e,r,s,a){if("block"===t.mode){if(!t.prompts||!t.subscribers)return{kind:"deny"};let r=await p(t.prompts,t.subscribers,e,a);return"y"!==r.answer||r.cancelled?{kind:"deny"}:{kind:"allow"}}if("off"===process.env.AGENTBOX_PROMPT)return{kind:"allow"};let o=await t.store.getBox(e);if(o?.autoApproveHostActions)return await t.store.appendEvent({boxId:e,type:"host-action-auto-approved",payload:{command:a.context?.command,argv:a.context?.argv,message:a.message}}),{kind:"allow"};let i=(0,n.randomUUID)(),d={id:i,...a};return await t.store.createPrompt({id:i,boxId:e,ev:d,method:r,params:s,status:"pending",createdAt:new Date().toISOString()}),t.subscribers?.broadcast(e,"prompt-ask",d),{kind:"pending",promptId:i}}function m(t,e){let r=t.worktrees??[];if(0===r.length)return null;let s=r.find(t=>t.containerPath===e);return s||(r.filter(t=>e===t.containerPath||e.startsWith(t.containerPath+"/")).sort((t,e)=>e.containerPath.length-t.containerPath.length)[0]??r.find(t=>"/workspace"===t.containerPath)??null)}function h(t){let e,r,s=t.trim();if(0===s.length)throw Error("empty git remote URL");let n=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(s),a=/^(?:[^@/]+@)?([^/:]+):(.+)$/.exec(s);if(n)e=n[1],r=n[2];else if(a&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(s))e=a[1],r=a[2];else throw Error(`unrecognized git remote URL: ${t}`);return{host:e,path:r.replace(/^\/+/,"")}}async function g(t,e){if(!t)return{exitCode:64,stdout:"",stderr:"git.lease-token: no GitHub App configured on this relay\n"};let r=e.originUrl;if(!r)return{exitCode:64,stdout:"",stderr:`git.lease-token: box ${e.boxId} has no registered origin URL
2
- `};let s="",n="",a="";try{let{path:t}=h(r),[e,o]=t.replace(/\.git$/,"").split("/");s=e??"",n=o??"",a=function(t){let{host:e,path:r}=h(t),s=r.replace(/\.git$/,"");return"github.com"===e.toLowerCase()?s:`${e}/${s}`}(r)}catch{return{exitCode:65,stdout:"",stderr:`git.lease-token: unrecognized origin ${r}
3
- `}}if(!s||!n)return{exitCode:65,stdout:"",stderr:`git.lease-token: cannot derive owner/repo from ${r}
4
- `};try{let e=await t.leaseRepoToken(s,n),o={token:e.token,expiresAt:e.expiresAt,remoteUrl:function(t,e){let{host:r,path:s}=h(t);return`https://x-access-token:${e}@${r}/${s}`}(r,e.token),repo:a};return{exitCode:0,stdout:JSON.stringify(o),stderr:""}}catch(t){return{exitCode:1,stdout:"",stderr:`git.lease-token: ${t instanceof Error?t.message:String(t)}
5
- `}}}function x(t){return Buffer.from(t).toString("base64url")}function b(t,e=Date.now()){let r=Math.floor(e/1e3),s=x(JSON.stringify({alg:"RS256",typ:"JWT"})),a=x(JSON.stringify({iat:r-60,exp:r+540,iss:t.appId})),o=`${s}.${a}`,i=(0,n.createSign)("RSA-SHA256").update(o).sign(t.privateKeyPem);return`${o}.${x(i)}`}var E=class{cfg;fetchImpl;now;apiBase;cache=new Map;installationIds=new Map;constructor(t,e={}){this.cfg=t,this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now,this.apiBase=(t.apiBaseUrl??"https://api.github.com").replace(/\/$/,"")}headers(t){return{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"agentbox-relay"}}async lookupInstallationId(t,e){let r=`${t}/${e}`,s=this.installationIds.get(r);if(void 0!==s)return s;let n=b(this.cfg,this.now()),a=await this.fetchImpl(`${this.apiBase}/repos/${t}/${e}/installation`,{headers:this.headers(n)});if(404===a.status)return null;if(!a.ok)throw Error(`GET installation for ${r} \u2192 ${String(a.status)}`);let o=await a.json();if("number"!=typeof o.id)throw Error("installation response missing id");return this.installationIds.set(r,o.id),o.id}async installationId(t,e){let r=await this.lookupInstallationId(t,e);if(null===r)throw Error(`GitHub App is not installed on ${t}/${e}`);return r}async isRepoInstalled(t,e){return await this.lookupInstallationId(t,e)!==null}async leaseRepoToken(t,e){let r=`${t}/${e}`,s=this.cache.get(r);if(s&&s.expiresAtMs-this.now()>3e5)return{token:s.token,expiresAt:s.expiresAt};let n=await this.installationId(t,e),a=b(this.cfg,this.now()),o=await this.fetchImpl(`${this.apiBase}/app/installations/${String(n)}/access_tokens`,{method:"POST",headers:{...this.headers(a),"Content-Type":"application/json"},body:JSON.stringify({repositories:[e],permissions:{contents:"write",pull_requests:"write"}})});if(!o.ok)throw Error(`failed to mint installation token for ${r} (\u2192 ${String(o.status)})`);let i=await o.json();if(!i.token||!i.expires_at)throw Error("access_tokens response missing token/expires_at");return this.cache.set(r,{token:i.token,expiresAt:i.expires_at,expiresAtMs:Date.parse(i.expires_at)}),{token:i.token,expiresAt:i.expires_at}}};async function f(t,e,r){if(!t.claimNextCreateJob||!t.completeCreateJob)return null;let s=await t.claimNextCreateJob(r);if(!s)return null;try{let{boxId:r}=await e(s.request,s.id);await t.completeCreateJob(s.id,"done",{boxId:r})}catch(e){await t.completeCreateJob(s.id,"failed",{error:e instanceof Error?e.message:String(e)})}return s.id}async function y(t,e,r,s=10){let n=0;for(;n<s&&await f(t,e,r);)n++;return n}t.s(["GitHubAppLeaser",0,E,"MemoryStore",0,l,"RELAY_EVENT_RING_SIZE",0,1e3,"gateApproval",0,c,"isValidBoxStatus",0,d,"leaseTokenResult",0,g,"loadGitHubAppConfig",0,function(){let t=process.env.GITHUB_APP_ID,e=process.env.GITHUB_APP_PRIVATE_KEY;if(!t||!e)return null;if(!e.includes("BEGIN"))try{e=Buffer.from(e,"base64").toString("utf8")}catch{return null}return{appId:t,privateKeyPem:e,apiBaseUrl:process.env.GITHUB_API_URL||void 0}},"resolveWorktree",0,m],73835);var w=new Set(["registerBox","getBox","authenticateBox","listBoxes","forgetBox","countBoxes","appendEvent","listEvents","countEvents","setStatus","getStatus","deleteStatus","createPrompt","getPrompt","answerPrompt","listPendingPrompts","setPromptResult"]);function v(t,e=200){return{status:e,body:t}}function S(t,e){return{status:t,body:{error:e}}}function T(t){if(0===t.length)return{};try{return JSON.parse(t)}catch{return null}}var I=new Set(["git.push","git.fetch","cp.toHost","cp.fromHost","download.workspace","download.env","download.config","download.claude","checkpoint.create"]);async function _(t,e){var r,s,a;let o,i,{store:u,leaser:l}=e,p=e.log??(()=>{});if(0===e.adminToken.length)return S(503,"control plane not configured: admin token unset");if("GET"===t.method&&"/healthz"===t.path)return v({ok:!0,boxes:await u.countBoxes(),events:await u.countEvents(),controlPlane:!0});if((t.path.startsWith("/admin/")||t.path.startsWith("/remote/"))&&(r=t.bearer,s=e.adminToken,o=Buffer.from(r,"utf8"),i=Buffer.from(s,"utf8"),!(o.length===i.length&&(0,n.timingSafeEqual)(o,i))))return S(401,"invalid admin token");if("POST"===t.method&&"/events"===t.path){let e=await u.authenticateBox(t.bearer);if(!e)return S(401,"unknown box token");let r=T(t.bodyText);return r&&"string"==typeof r.type&&0!==r.type.length?"box-status"===r.type?d(r.payload)?(await u.setStatus(e.boxId,e.name,e.projectIndex,r.payload),v({ok:!0},202)):S(400,"invalid box-status payload"):v({id:(await u.appendEvent({boxId:e.boxId,type:r.type,ts:"string"==typeof r.ts?r.ts:void 0,payload:r.payload})).id},202):S(400,'missing "type" string')}if("POST"===t.method&&"/rpc"===t.path){let r=await u.authenticateBox(t.bearer);if(!r)return S(401,"unknown box token");let s=T(t.bodyText);return s&&"string"==typeof s.method&&0!==s.method.length?(p(`rpc box=${r.boxId} method=${s.method}`),A(r,s.method,s.params,e)):S(400,'missing "method" string')}if("GET"===t.method&&t.path.startsWith("/rpc/status/")){let e=await u.authenticateBox(t.bearer);if(!e)return S(401,"unknown box token");let r=decodeURIComponent(t.path.slice(12)),s=await u.getPrompt(r);if(!s||s.boxId!==e.boxId)return S(404,"no such prompt");if("pending"===s.status)return v({status:"pending"});if("y"!==s.answer||s.cancelled)return v({status:"done",result:{exitCode:10,stdout:"",stderr:"denied by user\n"}});let n=s.result,a=n??await N(e,s.method,l);return n||await u.setPromptResult(r,a),v({status:"done",result:a})}if("POST"===t.method&&"/admin/register-box"===t.path){let e=T(t.bodyText);if(!e||!e.boxId||!e.token||"string"!=typeof e.name)return S(400,"expected {boxId, token, name}");let r={boxId:e.boxId,token:e.token,name:e.name,kind:"cloud"===e.kind?"cloud":"docker",backend:e.backend||void 0,registeredAt:new Date().toISOString(),containerName:e.containerName||void 0,createdAt:e.createdAt||void 0,projectIndex:"number"==typeof e.projectIndex&&e.projectIndex>0?Math.trunc(e.projectIndex):void 0,worktrees:Array.isArray(e.worktrees)?e.worktrees:void 0,previewUrl:e.previewUrl||void 0,previewToken:e.previewToken||void 0,bridgeToken:e.bridgeToken||void 0,autoApproveHostActions:!0===e.autoApproveHostActions,autoApproveSafeHostActions:!1!==e.autoApproveSafeHostActions,originUrl:e.originUrl||void 0};return await u.registerBox(r),p(`registered ${r.kind??"docker"} box ${r.boxId} (${r.name})`),v(null,204)}if("POST"===t.method&&"/admin/forget-box"===t.path){let e=T(t.bodyText);return e?.boxId?(await u.forgetBox(e.boxId),await u.deleteStatus(e.boxId),v(null,204)):S(400,"expected {boxId}")}if("GET"===t.method&&"/admin/box-status"===t.path){let e=t.query.get("box")??"",r=e?await u.getStatus(e):void 0;return r?v(r):S(404,"no status for box")}if("GET"===t.method&&"/admin/events"===t.path){let e=Number.parseInt(t.query.get("since")??"0",10)||0,r=t.query.get("box")??void 0;return v({events:await u.listEvents(e,r??void 0)})}if("GET"===t.method&&"/admin/app/repo-installed"===t.path){if(!l)return S(503,"no GitHub App configured on this control plane");let e=t.query.get("owner")??"",r=t.query.get("repo")??"";if(!e||!r)return S(400,"missing owner/repo query params");try{return v({installed:await l.isRepoInstalled(e,r)})}catch(t){return S(502,`installation check failed: ${t instanceof Error?t.message:String(t)}`)}}if("GET"===t.method&&"/admin/registry"===t.path)return v({boxes:(await u.listBoxes()).map(t=>({boxId:t.boxId,name:t.name,kind:t.kind,registeredAt:t.registeredAt,projectIndex:t.projectIndex,originUrl:t.originUrl}))});if("GET"===t.method&&"/admin/prompts"===t.path){let e=t.query.get("boxId")??"";return 0===e.length?S(400,"missing boxId query param"):v({prompts:(await u.listPendingPrompts(e)).map(t=>t.ev)})}if("POST"===t.method&&"/admin/prompts/answer"===t.path){let e=T(t.bodyText);return e?.id&&("y"===e.answer||"n"===e.answer)?await u.answerPrompt(e.id,e.answer,e.cancelled)?v(null,204):S(404,"no pending prompt with that id"):S(400,'expected {id, answer:"y"|"n", cancelled?}')}if("POST"===t.method&&"/admin/store"===t.path){let e=T(t.bodyText);return e&&"string"==typeof e.method&&Array.isArray(e.args)?(a=e.method,w.has(a))?v({result:await function(t,e,r){switch(e){case"registerBox":return t.registerBox(r[0]);case"getBox":return t.getBox(r[0]);case"authenticateBox":return t.authenticateBox(r[0]);case"listBoxes":return t.listBoxes();case"forgetBox":return t.forgetBox(r[0]);case"countBoxes":return t.countBoxes();case"appendEvent":return t.appendEvent(r[0]);case"listEvents":return t.listEvents(r[0],r[1]);case"countEvents":return t.countEvents();case"setStatus":return t.setStatus(r[0],r[1],r[2],r[3]);case"getStatus":return t.getStatus(r[0]);case"deleteStatus":return t.deleteStatus(r[0]);case"createPrompt":return t.createPrompt(r[0]);case"getPrompt":return t.getPrompt(r[0]);case"answerPrompt":return t.answerPrompt(r[0],r[1],r[2]);case"listPendingPrompts":return t.listPendingPrompts(r[0]);case"setPromptResult":return t.setPromptResult(r[0],r[1]);default:throw Error(`unknown store op: ${e}`)}}(u,e.method,e.args)??null}):S(400,`unknown store op: ${e.method}`):S(400,"expected {method, args}")}if("POST"===t.method&&"/remote/boxes"===t.path){if(!u.enqueueCreateJob)return S(501,"create-job queue not available on this store");let r=T(t.bodyText);if(!r||"string"!=typeof r.repoUrl||"string"!=typeof r.provider)return S(400,"expected {repoUrl, provider, branch?, name?, agent?, prompt?}");let s=e.createProviders;if(s&&s.length>0&&!s.includes(r.provider))return S(400,`provider '${r.provider}' is not supported by this control plane (allowed: ${s.join(", ")})`);let a=(0,n.randomUUID)();return await u.enqueueCreateJob({id:a,status:"queued",request:{repoUrl:r.repoUrl,provider:r.provider,branch:r.branch,name:r.name,agent:r.agent,prompt:r.prompt},createdAt:new Date().toISOString()}),p(`enqueued create job ${a} (${r.provider} ${r.repoUrl})`),v({jobId:a},202)}if("GET"===t.method&&t.path.startsWith("/remote/boxes/")){if(!u.getCreateJob)return S(501,"create-job queue not available on this store");let e=decodeURIComponent(t.path.slice(14)),r=await u.getCreateJob(e);return r?v(r):S(404,"no such job")}return S(404,"not found")}async function A(t,e,r,s){if("git.lease-token"===e){var n;let a=m(t,r?.path??"/workspace");if(!((n=a?.branch)&&n.startsWith("agentbox/"))){let n=await c({mode:"poll",store:s.store},t.boxId,e,r,{kind:"confirm",message:`Allow box ${t.name} to lease a push token for ${t.originUrl??"its repo"}?`,detail:`branch ${a?.branch??"(unregistered)"}`,defaultAnswer:"n",context:{command:"git lease-token",cwd:r?.path}});if("pending"===n.kind)return v({status:"pending",promptId:n.promptId},202);if("deny"===n.kind)return v({exitCode:10,stdout:"",stderr:"denied by user\n"},500)}let o=await g(s.leaser,t);return v(o,0===o.exitCode?200:500)}return"browser.open"===e?("string"==typeof r?.url&&await s.store.appendEvent({boxId:t.boxId,type:"browser-open",payload:{url:r.url}}),v({exitCode:0,stdout:"",stderr:""})):I.has(e)?v({exitCode:64,stdout:"",stderr:`${e}: not available on the hosted control plane (no host). Cloud boxes push via git.lease-token.
6
- `},501):v({error:"rpc method not implemented",method:e},501)}async function N(t,e,r){return"git.lease-token"===e?g(r,t):{exitCode:64,stdout:"",stderr:`relay: no approved-action executor for ${e}
7
- `}}var O=`
1
+ module.exports=[7876,99617,13806,t=>{"use strict";var e=t.i(24868),r=t.i(46786),a=t.i(14747),s=t.i(54799),n=t.i(22734),i=class{map=new Map;register(t){this.map.set(t.boxId,t)}forget(t){return this.map.delete(t)}authenticate(t){if(0===t.length)return null;for(let e of this.map.values())if(e.token===t)return e;return null}get(t){return this.map.get(t)}list(){return[...this.map.values()]}size(){return this.map.size}},o=class{constructor(t=1e3){this.capacity=t}capacity;buf=[];nextId=1;append(t){let e={id:this.nextId++,receivedAt:new Date().toISOString(),...t};return this.buf.push(e),this.buf.length>this.capacity&&this.buf.shift(),e}since(t,e){let r=[];for(let a of this.buf)!(a.id<=t)&&(e&&a.boxId!==e||r.push(a));return r}all(){return this.buf.slice()}size(){return this.buf.length}};function d(t,e,s){let n=e.toLowerCase().replace(/-/g,"_").replace(/[^a-z0-9_]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"").slice(0,32)||"unnamed",i="number"==typeof s&&Number.isFinite(s)&&s>0?`${t}-${String(s)}-${n}`:`${t}-${n}`;return(0,a.join)((0,r.homedir)(),".agentbox","boxes",i)}function l(t){return"object"==typeof t&&null!==t&&1===t.schema&&"string"==typeof t.boxId&&t.boxId.length>0}var u=class{map=new Map;get(t){return this.map.get(t)}async set(t,r,s,n){this.map.set(t,n);let i=(0,a.join)(d(t,r,s),"status.json"),o=`${i}.${String(process.pid)}.tmp`;try{await (0,e.mkdir)(d(t,r,s),{recursive:!0}),await (0,e.writeFile)(o,JSON.stringify(n),"utf8"),await (0,e.rename)(o,i)}catch{await (0,e.rm)(o,{force:!0}).catch(()=>{})}}delete(t){this.map.delete(t)}list(){return[...this.map.entries()].map(([t,e])=>({boxId:t,status:e}))}},c=class{registry;events;statusStore;prompts=new Map;createJobs=new Map;constructor(t={}){this.registry=t.registry??new i,this.events=t.events??new o,this.statusStore=t.statusStore??new u}registerBox(t){return this.registry.register(t),Promise.resolve()}getBox(t){return Promise.resolve(this.registry.get(t))}authenticateBox(t){return Promise.resolve(this.registry.authenticate(t))}listBoxes(){return Promise.resolve(this.registry.list())}forgetBox(t){return Promise.resolve(this.registry.forget(t))}countBoxes(){return Promise.resolve(this.registry.size())}appendEvent(t){return Promise.resolve(this.events.append(t))}listEvents(t,e){return Promise.resolve(this.events.since(t,e))}countEvents(){return Promise.resolve(this.events.size())}setStatus(t,e,r,a){return this.statusStore.set(t,e,r,a)}getStatus(t){return Promise.resolve(this.statusStore.get(t))}deleteStatus(t){return this.statusStore.delete(t),Promise.resolve()}listStatuses(){return Promise.resolve(this.statusStore.list())}createPrompt(t){return this.prompts.set(t.id,{...t}),Promise.resolve()}getPrompt(t){let e=this.prompts.get(t);return Promise.resolve(e?{...e}:null)}answerPrompt(t,e,r){let a=this.prompts.get(t);return a&&"pending"===a.status?(a.status="answered",a.answer=e,a.cancelled=r,Promise.resolve(!0)):Promise.resolve(!1)}listPendingPrompts(t){let e=[];for(let r of this.prompts.values())r.boxId===t&&"pending"===r.status&&e.push({...r});return Promise.resolve(e)}setPromptResult(t,e){let r=this.prompts.get(t);return r&&(r.result=e),Promise.resolve()}enqueueCreateJob(t){return this.createJobs.set(t.id,{...t}),Promise.resolve()}getCreateJob(t){let e=this.createJobs.get(t);return Promise.resolve(e?{...e}:null)}listCreateJobs(t){let e=t?.status,r=[...this.createJobs.values()].filter(t=>!e||e.includes(t.status)).sort((t,e)=>e.createdAt.localeCompare(t.createdAt)).map(t=>({...t}));return Promise.resolve(t?.limit?r.slice(0,t.limit):r)}claimNextCreateJob(t){let e=[...this.createJobs.values()].filter(t=>"queued"===t.status).sort((t,e)=>t.createdAt.localeCompare(e.createdAt))[0];return e?(e.status="running",e.claimedBy=t,e.startedAt=new Date().toISOString(),Promise.resolve({...e})):Promise.resolve(null)}completeCreateJob(t,e,r){let a=this.createJobs.get(t);return a&&(a.status=e,a.result=r,a.finishedAt=new Date().toISOString()),Promise.resolve()}};async function p(t,e,r,a,n){if("off"===process.env.AGENTBOX_PROMPT||t.consumeAutoApprove(r,a))return{answer:"y"};let i={id:(0,s.randomUUID)(),...a},o=t.add(r,i);if(e.broadcast(r,"prompt-ask",i),n?.ttlMs!==void 0&&n.ttlMs>0){let s=setTimeout(()=>{t.resolve(i.id,a.defaultAnswer??"n",!0)&&e.broadcast(r,"prompt-resolved",{id:i.id})},n.ttlMs);"function"==typeof s.unref&&s.unref(),o.then(()=>{clearTimeout(s)})}return o}async function h(t,e,r,a,n){if("block"===t.mode){if(!t.prompts||!t.subscribers)return{kind:"deny"};let r=await p(t.prompts,t.subscribers,e,n);return"y"!==r.answer||r.cancelled?{kind:"deny"}:{kind:"allow"}}if("off"===process.env.AGENTBOX_PROMPT)return{kind:"allow"};let i=await t.store.getBox(e);if(i?.autoApproveHostActions)return await t.store.appendEvent({boxId:e,type:"host-action-auto-approved",payload:{command:n.context?.command,argv:n.context?.argv,message:n.message}}),{kind:"allow"};let o=(0,s.randomUUID)(),d={id:o,...n};return await t.store.createPrompt({id:o,boxId:e,ev:d,method:r,params:a,status:"pending",createdAt:new Date().toISOString()}),t.subscribers?.broadcast(e,"prompt-ask",d),{kind:"pending",promptId:o}}function m(t,e){let r=t.worktrees??[];if(0===r.length)return null;let a=r.find(t=>t.containerPath===e);return a||(r.filter(t=>e===t.containerPath||e.startsWith(t.containerPath+"/")).sort((t,e)=>e.containerPath.length-t.containerPath.length)[0]??r.find(t=>"/workspace"===t.containerPath)??null)}function g(t){let e,r,a=t.trim();if(0===a.length)throw Error("empty git remote URL");let s=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(a),n=/^(?:[^@/]+@)?([^/:]+):(.+)$/.exec(a);if(s)e=s[1],r=s[2];else if(n&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(a))e=n[1],r=n[2];else throw Error(`unrecognized git remote URL: ${t}`);return{host:e,path:r.replace(/^\/+/,"")}}function b(t,e){let{host:r,path:a}=g(t);return`https://x-access-token:${e}@${r}/${a}`}function x(t){let{host:e,path:r}=g(t),a=r.replace(/\.git$/,"");return"github.com"===e.toLowerCase()?a:`${e}/${a}`}async function w(t,e){if(!t)return{exitCode:64,stdout:"",stderr:"git.lease-token: no GitHub App configured on this relay\n"};let r=e.originUrl;if(!r)return{exitCode:64,stdout:"",stderr:`git.lease-token: box ${e.boxId} has no registered origin URL
2
+ `};let a="",s="",n="";try{let{path:t}=g(r),[e,i]=t.replace(/\.git$/,"").split("/");a=e??"",s=i??"",n=x(r)}catch{return{exitCode:65,stdout:"",stderr:`git.lease-token: unrecognized origin ${r}
3
+ `}}if(!a||!s)return{exitCode:65,stdout:"",stderr:`git.lease-token: cannot derive owner/repo from ${r}
4
+ `};try{let e=await t.leaseRepoToken(a,s),i={token:e.token,expiresAt:e.expiresAt,remoteUrl:b(r,e.token),repo:n};return{exitCode:0,stdout:JSON.stringify(i),stderr:""}}catch(t){return{exitCode:1,stdout:"",stderr:`git.lease-token: ${t instanceof Error?t.message:String(t)}
5
+ `}}}var y=new Set(["registerBox","getBox","authenticateBox","listBoxes","forgetBox","countBoxes","appendEvent","listEvents","countEvents","setStatus","getStatus","deleteStatus","listStatuses","createPrompt","getPrompt","answerPrompt","listPendingPrompts","setPromptResult"]);async function f(t,e){var r,a;let n,i;if("/admin/store"!==t.path)return null;let o=e.adminToken??"";if(0===o.length)return{status:503,body:{error:"control plane not configured: admin token unset"}};if(r=t.bearer,n=Buffer.from(r,"utf8"),i=Buffer.from(o,"utf8"),!(n.length===i.length&&(0,s.timingSafeEqual)(n,i)))return{status:401,body:{error:"invalid admin token"}};if("POST"!==t.method)return{status:405,body:{error:"method not allowed"}};let d=function(t){if(0===t.length)return null;try{return JSON.parse(t)}catch{return null}}(t.bodyText);return d&&"string"==typeof d.method&&Array.isArray(d.args)?(a=d.method,y.has(a))?{status:200,body:{result:await function(t,e,r){switch(e){case"registerBox":return t.registerBox(r[0]);case"getBox":return t.getBox(r[0]);case"authenticateBox":return t.authenticateBox(r[0]);case"listBoxes":return t.listBoxes();case"forgetBox":return t.forgetBox(r[0]);case"countBoxes":return t.countBoxes();case"appendEvent":return t.appendEvent(r[0]);case"listEvents":return t.listEvents(r[0],r[1]);case"countEvents":return t.countEvents();case"setStatus":return t.setStatus(r[0],r[1],r[2],r[3]);case"getStatus":return t.getStatus(r[0]);case"deleteStatus":return t.deleteStatus(r[0]);case"listStatuses":return t.listStatuses();case"createPrompt":return t.createPrompt(r[0]);case"getPrompt":return t.getPrompt(r[0]);case"answerPrompt":return t.answerPrompt(r[0],r[1],r[2]);case"listPendingPrompts":return t.listPendingPrompts(r[0]);case"setPromptResult":return t.setPromptResult(r[0],r[1]);default:throw Error(`unknown store op: ${e}`)}}(e.store,d.method,d.args)??null}}:{status:400,body:{error:`unknown store op: ${d.method}`}}:{status:400,body:{error:"expected {method, args}"}}}var v=["agents","projects","boxes","prepared"],A=["claude","codex","opencode"],I=class extends Error{constructor(t){super(t),this.name="CustodyPathError"}},S=/^[A-Za-z0-9._-]+$/;function T(t){return(0,s.createHash)("sha256").update(t).digest("hex")}function E(t){let e=t.replace(/^\/+/,"").replace(/\/+$/,"");if(0===e.length)throw new I("empty custody path");if(e.length>256)throw new I(`custody path too long (max ${String(256)} chars)`);let r=e.split("/");if(r.length<2)throw new I(`custody path needs a scope and a name: '${t}'`);if(r.length>6)throw new I(`custody path too deep (max ${String(6)} segments)`);for(let t of r)if("."===t||".."===t||!S.test(t))throw new I(`illegal custody path segment: '${t}'`);let a=r[0];if(!v.includes(a))throw new I(`unknown custody scope '${a}' (expected ${v.join(" | ")})`);if("agents"===a&&!A.includes(r[1]))throw new I(`unknown agent '${r[1]}' (expected ${A.join(" | ")})`);return r.join("/")}function N(t){let e=t.replace(/^\/+/,"").replace(/\/+$/,"");if(0===e.length)return"";if(e.length>256)throw new I(`custody prefix too long (max ${String(256)} chars)`);let r=e.split("/");if(r.length>6)throw new I(`custody prefix too deep (max ${String(6)} segments)`);for(let t of r)if("."===t||".."===t||!S.test(t))throw new I(`illegal custody prefix segment: '${t}'`);if(!v.includes(r[0]))throw new I(`unknown custody scope '${r[0]}' (expected ${v.join(" | ")})`);return r.join("/")}var P="/admin/custody";async function _(t,e){var r,a;let n,i;if(!((r=t.path)===P||r.startsWith(`${P}/`)))return null;let o=e.log??(()=>{}),d=e.adminToken??"";if(0===d.length)return{status:503,body:{error:"custody not configured: admin token unset"}};if(a=t.bearer,n=Buffer.from(a,"utf8"),i=Buffer.from(d,"utf8"),!(n.length===i.length&&(0,s.timingSafeEqual)(n,i)))return{status:401,body:{error:"invalid admin token"}};let l=e.custody;if(!l)return{status:503,body:{error:"custody store not enabled on this relay"}};try{if(t.path===P){if("GET"!==t.method)return{status:405,body:{error:"method not allowed"}};let e=t.query.get("prefix"),r=e?N(e):void 0,a=await l.list(r);return{status:200,body:{entries:a}}}let e=E(decodeURIComponent(t.path.slice(`${P}/`.length)));if("PUT"===t.method){let r;try{r=JSON.parse(0===t.bodyText.length?"{}":t.bodyText)}catch{return{status:400,body:{error:"expected JSON {data: <base64>}"}}}if("string"!=typeof r.data)return{status:400,body:{error:"expected {data: <base64>}"}};let a=Buffer.from(r.data,"base64");if(a.toString("base64")!==r.data.replace(/\s+/g,""))return{status:400,body:{error:"data is not valid base64"}};let s=await l.put(e,a);return o(`custody put ${e} (${String(s.size)} bytes, ${s.changed?"changed":"unchanged"})`),{status:200,body:s}}if("GET"===t.method){let t=await l.get(e);if(!t)return{status:404,body:{error:"no such custody entry"}};return o(`custody get ${e} (${String(t.entry.size)} bytes)`),{status:200,body:{...t.entry,data:t.data.toString("base64")}}}if("DELETE"===t.method){if(!await l.delete(e))return{status:404,body:{error:"no such custody entry"}};return o(`custody delete ${e}`),{status:204}}return{status:405,body:{error:"method not allowed"}}}catch(e){if(e instanceof I)return{status:400,body:{error:e.message}};let t=e instanceof Error?e.message:String(e);return o(`custody error: ${t}`),{status:500,body:{error:`custody: ${t}`}}}}var k="/remote/boxes";async function $(t,e){var r,a;let n,i;if(!((r=t.path)===k||r.startsWith(`${k}/`)))return null;let o=e.log??(()=>{}),{store:d}=e,l=e.adminToken??"";if(0===l.length)return{status:503,body:{error:"control plane not configured: admin token unset"}};if(a=t.bearer,n=Buffer.from(a,"utf8"),i=Buffer.from(l,"utf8"),!(n.length===i.length&&(0,s.timingSafeEqual)(n,i)))return{status:401,body:{error:"invalid admin token"}};if("POST"===t.method&&t.path===k){if(!d.enqueueCreateJob)return{status:501,body:{error:"create-job queue not available on this store"}};let r=function(t){if(0===t.length)return{};try{return JSON.parse(t)}catch{return null}}(t.bodyText);if(!r||"string"!=typeof r.repoUrl||"string"!=typeof r.provider)return{status:400,body:{error:"expected {repoUrl, provider, branch?, name?, agent?, prompt?}"}};let a=e.createProviders;if(a&&a.length>0&&!a.includes(r.provider))return{status:400,body:{error:`provider '${r.provider}' is not supported by this control plane (allowed: ${a.join(", ")})`}};let n=(0,s.randomUUID)();return await d.enqueueCreateJob({id:n,status:"queued",request:{repoUrl:r.repoUrl,provider:r.provider,branch:r.branch,name:r.name,agent:r.agent,prompt:r.prompt},createdAt:new Date().toISOString()}),o(`enqueued create job ${n} (${r.provider} ${r.repoUrl})`),{status:202,body:{jobId:n}}}if("GET"===t.method&&t.path===k)return d.listCreateJobs?{status:200,body:{jobs:await d.listCreateJobs({limit:100})}}:{status:501,body:{error:"create-job queue not available on this store"}};if("GET"===t.method&&t.path.startsWith(`${k}/`)){if(!d.getCreateJob)return{status:501,body:{error:"create-job queue not available on this store"}};let e=decodeURIComponent(t.path.slice(`${k}/`.length)),r=await d.getCreateJob(e);return r?{status:200,body:r}:{status:404,body:{error:"no such job"}}}if("DELETE"===t.method&&t.path.startsWith(`${k}/`)){let r=decodeURIComponent(t.path.slice(`${k}/`.length));if(0===r.length)return{status:404,body:{error:"no such box"}};let a=await d.getBox(r),s=await d.forgetBox(r);await d.deleteStatus(r);let n=0;if(e.custody){let t=a?.sandboxId??r;for(let r of(await e.custody.list(`boxes/${t}`).catch(()=>[])))await e.custody.delete(r.path).catch(()=>!1)&&(n+=1)}return s||a||0!==n?(o(`reaped box ${r} (registration=${String(s)}, custody=${String(n)})`),{status:200,body:{boxId:r,removed:s,custodyRemoved:n}}):{status:404,body:{error:"no such box"}}}return{status:405,body:{error:"method not allowed"}}}var C=class{inner;registry;events;statusStore;constructor(t,e){this.inner=t,this.registry=e.registry,this.events=e.events,this.statusStore=e.statusStore}async hydrate(){for(let t of(await this.inner.listBoxes()))this.registry.register(t);for(let{boxId:t,status:e}of(await this.inner.listStatuses())){let r=this.registry.get(t);await this.statusStore.set(t,r?.name??t,r?.projectIndex,e)}}migrate(){return this.inner.migrate?.()??Promise.resolve()}async registerBox(t){await this.inner.registerBox(t),this.registry.register(t)}getBox(t){return this.inner.getBox(t)}authenticateBox(t){return this.inner.authenticateBox(t)}listBoxes(){return this.inner.listBoxes()}async forgetBox(t){let e=await this.inner.forgetBox(t);return this.registry.forget(t),e}countBoxes(){return this.inner.countBoxes()}async appendEvent(t){let e=await this.inner.appendEvent(t);return this.events.append(t),e}listEvents(t,e){return this.inner.listEvents(t,e)}countEvents(){return this.inner.countEvents()}async setStatus(t,e,r,a){await this.inner.setStatus(t,e,r,a),await this.statusStore.set(t,e,r,a)}getStatus(t){return this.inner.getStatus(t)}async deleteStatus(t){await this.inner.deleteStatus(t),this.statusStore.delete(t)}listStatuses(){return this.inner.listStatuses()}createPrompt(t){return this.inner.createPrompt(t)}getPrompt(t){return this.inner.getPrompt(t)}answerPrompt(t,e,r){return this.inner.answerPrompt(t,e,r)}listPendingPrompts(t){return this.inner.listPendingPrompts(t)}setPromptResult(t,e){return this.inner.setPromptResult(t,e)}enqueueCreateJob(t){return this.inner.enqueueCreateJob?this.inner.enqueueCreateJob(t):Promise.resolve()}getCreateJob(t){return this.inner.getCreateJob?.(t)??Promise.resolve(null)}listCreateJobs(t){return this.inner.listCreateJobs?.(t)??Promise.resolve([])}claimNextCreateJob(t){return this.inner.claimNextCreateJob?.(t)??Promise.resolve(null)}completeCreateJob(t,e,r){return this.inner.completeCreateJob?this.inner.completeCreateJob(t,e,r):Promise.resolve()}prunePrompts(t){return this.inner.prunePrompts?.(t)??Promise.resolve(0)}pruneCreateJobs(t){return this.inner.pruneCreateJobs?.(t)??Promise.resolve(0)}};function B(t){return Buffer.from(t).toString("base64url")}function O(t,e=Date.now()){let r=Math.floor(e/1e3),a=B(JSON.stringify({alg:"RS256",typ:"JWT"})),n=B(JSON.stringify({iat:r-60,exp:r+540,iss:t.appId})),i=`${a}.${n}`,o=(0,s.createSign)("RSA-SHA256").update(i).sign(t.privateKeyPem);return`${i}.${B(o)}`}var L=class{cfg;fetchImpl;now;apiBase;cache=new Map;installationIds=new Map;constructor(t,e={}){this.cfg=t,this.fetchImpl=e.fetchImpl??fetch,this.now=e.now??Date.now,this.apiBase=(t.apiBaseUrl??"https://api.github.com").replace(/\/$/,"")}headers(t){return{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"agentbox-relay"}}async lookupInstallationId(t,e){let r=`${t}/${e}`,a=this.installationIds.get(r);if(void 0!==a)return a;let s=O(this.cfg,this.now()),n=await this.fetchImpl(`${this.apiBase}/repos/${t}/${e}/installation`,{headers:this.headers(s)});if(404===n.status)return null;if(!n.ok)throw Error(`GET installation for ${r} \u2192 ${String(n.status)}`);let i=await n.json();if("number"!=typeof i.id)throw Error("installation response missing id");return this.installationIds.set(r,i.id),i.id}async installationId(t,e){let r=await this.lookupInstallationId(t,e);if(null===r)throw Error(`GitHub App is not installed on ${t}/${e}`);return r}async isRepoInstalled(t,e){return await this.lookupInstallationId(t,e)!==null}async leaseRepoToken(t,e){let r=`${t}/${e}`,a=this.cache.get(r);if(a&&a.expiresAtMs-this.now()>3e5)return{token:a.token,expiresAt:a.expiresAt};let s=await this.installationId(t,e),n=O(this.cfg,this.now()),i=await this.fetchImpl(`${this.apiBase}/app/installations/${String(s)}/access_tokens`,{method:"POST",headers:{...this.headers(n),"Content-Type":"application/json"},body:JSON.stringify({repositories:[e],permissions:{contents:"write",pull_requests:"write"}})});if(!i.ok)throw Error(`failed to mint installation token for ${r} (\u2192 ${String(i.status)})`);let o=await i.json();if(!o.token||!o.expires_at)throw Error("access_tokens response missing token/expires_at");return this.cache.set(r,{token:o.token,expiresAt:o.expires_at,expiresAtMs:Date.parse(o.expires_at)}),{token:o.token,expiresAt:o.expires_at}}};t.s(["CUSTODY_SCOPES",0,v,"GitHubAppLeaser",0,L,"MemoryStore",0,c,"RELAY_EVENT_RING_SIZE",0,1e3,"WriteThroughStore",0,C,"custodyDigest",0,T,"gateApproval",0,h,"handleCustodyRequest",0,_,"handleRemoteBoxesRequest",0,$,"handleStoreRpcRequest",0,f,"isValidBoxStatus",0,l,"leaseTokenResult",0,w,"loadGitHubAppConfig",0,function(){let t=process.env.GITHUB_APP_ID,e=process.env.GITHUB_APP_PRIVATE_KEY;if(!t||!e)return null;if(!e.includes("BEGIN"))try{e=Buffer.from(e,"base64").toString("utf8")}catch{return null}return{appId:t,privateKeyPem:e,apiBaseUrl:process.env.GITHUB_API_URL||void 0}},"normalizeCustodyPath",0,E,"normalizeCustodyPrefix",0,N,"parseGitRemote",0,g,"repoSlugFromRemote",0,x,"resolveWorktree",0,m,"toAuthedHttpsUrl",0,b],99617);var U=t.i(57743),q=t.i(11205),R=t.i(63080),j=t.i(56698),D=t.i(44946),J=t.i(64645),M=t.i(62160),F=t.i(8614),z=t.i(93540),G=t.i(21918),X=t.i(55171),H=t.i(42631),Y=t.i(48771),K=t.i(62562),W=t.i(46063);let Q={get url(){return`file://${t.P("packages/relay/dist/chunk-ATOI6ZPE.js")}`}};async function V(t,e,r,a,s,n=()=>{}){await t(s?["clone","--branch",s,e,a]:["clone",e,a],{GIT_LFS_SKIP_SMUDGE:"1"});try{await t(["-C",a,"-c",`lfs.url=${e.replace(/\.git$/,"")}.git/info/lfs`,"lfs","pull"],{GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:"ssh -o BatchMode=yes -o StrictHostKeyChecking=no"},12e4)}catch(t){n(`git-lfs objects left as pointers (fetch failed): ${t instanceof Error?t.message:String(t)}`)}await t(["-C",a,"remote","set-url","origin",r])}async function Z(t,e,r){if(!t.claimNextCreateJob||!t.completeCreateJob)return null;let a=await t.claimNextCreateJob(r);if(!a)return null;try{let{boxId:r,agentStartError:s}=await e(a.request,a.id);s?await t.completeCreateJob(a.id,"failed",{boxId:r,error:s}):await t.completeCreateJob(a.id,"done",{boxId:r})}catch(e){await t.completeCreateJob(a.id,"failed",{error:e instanceof Error?e.message:String(e)})}return a.id}async function tt(t,e,r,a=10){let s=0;for(;s<a&&await Z(t,e,r);)s++;return s}function te(t,e=200){return{status:e,body:t}}function tr(t,e){return{status:t,body:{error:e}}}function ta(t){if(0===t.length)return{};try{return JSON.parse(t)}catch{return null}}var ts=new Set(["git.push","git.fetch","cp.toHost","cp.fromHost","download.workspace","download.env","download.config","download.claude","checkpoint.create"]);async function tn(t,e){var r,a;let n,i,{store:o,leaser:d}=e,u=e.log??(()=>{});if(0===e.adminToken.length)return tr(503,"control plane not configured: admin token unset");if("GET"===t.method&&"/healthz"===t.path)return te({ok:!0,boxes:await o.countBoxes(),events:await o.countEvents(),controlPlane:!0});if((t.path.startsWith("/admin/")||t.path.startsWith("/remote/"))&&(r=t.bearer,a=e.adminToken,n=Buffer.from(r,"utf8"),i=Buffer.from(a,"utf8"),!(n.length===i.length&&(0,s.timingSafeEqual)(n,i))))return tr(401,"invalid admin token");let c={custody:e.custody,adminToken:e.adminToken,log:u},p=await _(t,c);if(p)return void 0===p.body?{status:p.status}:te(p.body,p.status);if("POST"===t.method&&"/events"===t.path){let e=await o.authenticateBox(t.bearer);if(!e)return tr(401,"unknown box token");let r=ta(t.bodyText);return r&&"string"==typeof r.type&&0!==r.type.length?"box-status"===r.type?l(r.payload)?(await o.setStatus(e.boxId,e.name,e.projectIndex,r.payload),te({ok:!0},202)):tr(400,"invalid box-status payload"):te({id:(await o.appendEvent({boxId:e.boxId,type:r.type,ts:"string"==typeof r.ts?r.ts:void 0,payload:r.payload})).id},202):tr(400,'missing "type" string')}if("POST"===t.method&&"/rpc"===t.path){let r=await o.authenticateBox(t.bearer);if(!r)return tr(401,"unknown box token");let a=ta(t.bodyText);return a&&"string"==typeof a.method&&0!==a.method.length?(u(`rpc box=${r.boxId} method=${a.method}`),ti(r,a.method,a.params,e)):tr(400,'missing "method" string')}if("GET"===t.method&&t.path.startsWith("/rpc/status/")){let e=await o.authenticateBox(t.bearer);if(!e)return tr(401,"unknown box token");let r=decodeURIComponent(t.path.slice(12)),a=await o.getPrompt(r);if(!a||a.boxId!==e.boxId)return tr(404,"no such prompt");if("pending"===a.status)return te({status:"pending"});if("y"!==a.answer||a.cancelled)return te({status:"done",result:{exitCode:10,stdout:"",stderr:"denied by user\n"}});let s=a.result,n=s??await to(e,a.method,d);return s||await o.setPromptResult(r,n),te({status:"done",result:n})}if("POST"===t.method&&"/admin/register-box"===t.path){let e=ta(t.bodyText);if(!e||!e.boxId||!e.token||"string"!=typeof e.name)return tr(400,"expected {boxId, token, name}");let r={boxId:e.boxId,token:e.token,name:e.name,kind:"cloud"===e.kind?"cloud":"docker",backend:e.backend||void 0,sandboxId:e.sandboxId||void 0,registeredAt:new Date().toISOString(),containerName:e.containerName||void 0,createdAt:e.createdAt||void 0,projectIndex:"number"==typeof e.projectIndex&&e.projectIndex>0?Math.trunc(e.projectIndex):void 0,worktrees:Array.isArray(e.worktrees)?e.worktrees:void 0,previewUrl:e.previewUrl||void 0,previewToken:e.previewToken||void 0,bridgeToken:e.bridgeToken||void 0,autoApproveHostActions:!0===e.autoApproveHostActions,autoApproveSafeHostActions:!1!==e.autoApproveSafeHostActions,originUrl:e.originUrl||void 0};return await o.registerBox(r),u(`registered ${r.kind??"docker"} box ${r.boxId} (${r.name})`),te(null,204)}if("POST"===t.method&&"/admin/forget-box"===t.path){let e=ta(t.bodyText);return e?.boxId?(await o.forgetBox(e.boxId),await o.deleteStatus(e.boxId),te(null,204)):tr(400,"expected {boxId}")}if("GET"===t.method&&"/admin/box-status"===t.path){let e=t.query.get("box")??"",r=e?await o.getStatus(e):void 0;return r?te(r):tr(404,"no status for box")}if("GET"===t.method&&"/admin/events"===t.path){let e=Number.parseInt(t.query.get("since")??"0",10)||0,r=t.query.get("box")??void 0;return te({events:await o.listEvents(e,r??void 0)})}if("GET"===t.method&&"/admin/app/repo-installed"===t.path){if(!d)return tr(503,"no GitHub App configured on this control plane");let e=t.query.get("owner")??"",r=t.query.get("repo")??"";if(!e||!r)return tr(400,"missing owner/repo query params");try{return te({installed:await d.isRepoInstalled(e,r)})}catch(t){return tr(502,`installation check failed: ${t instanceof Error?t.message:String(t)}`)}}if("GET"===t.method&&"/admin/registry"===t.path)return te({boxes:(await o.listBoxes()).map(t=>({boxId:t.boxId,name:t.name,kind:t.kind,registeredAt:t.registeredAt,projectIndex:t.projectIndex,originUrl:t.originUrl}))});if("GET"===t.method&&"/admin/prompts"===t.path){let e=t.query.get("boxId")??"";return 0===e.length?tr(400,"missing boxId query param"):te({prompts:(await o.listPendingPrompts(e)).map(t=>t.ev)})}if("POST"===t.method&&"/admin/prompts/answer"===t.path){let e=ta(t.bodyText);return e?.id&&("y"===e.answer||"n"===e.answer)?await o.answerPrompt(e.id,e.answer,e.cancelled)?te(null,204):tr(404,"no pending prompt with that id"):tr(400,'expected {id, answer:"y"|"n", cancelled?}')}let h=await f(t,{store:o,adminToken:e.adminToken,log:u});if(h)return void 0===h.body?{status:h.status}:te(h.body,h.status);let m=await $(t,{store:o,adminToken:e.adminToken,createProviders:e.createProviders,custody:e.custody,log:u});return m?void 0===m.body?{status:m.status}:te(m.body,m.status):tr(404,"not found")}async function ti(t,e,r,a){if("git.lease-token"===e){var s;let n=m(t,r?.path??"/workspace");if(!((s=n?.branch)&&s.startsWith("agentbox/"))){let s=await h({mode:"poll",store:a.store},t.boxId,e,r,{kind:"confirm",message:`Allow box ${t.name} to lease a push token for ${t.originUrl??"its repo"}?`,detail:`branch ${n?.branch??"(unregistered)"}`,defaultAnswer:"n",context:{command:"git lease-token",cwd:r?.path}});if("pending"===s.kind)return te({status:"pending",promptId:s.promptId},202);if("deny"===s.kind)return te({exitCode:10,stdout:"",stderr:"denied by user\n"},500)}let i=await w(a.leaser,t);return te(i,0===i.exitCode?200:500)}return"browser.open"===e?("string"==typeof r?.url&&await a.store.appendEvent({boxId:t.boxId,type:"browser-open",payload:{url:r.url}}),te({exitCode:0,stdout:"",stderr:""})):ts.has(e)?te({exitCode:64,stdout:"",stderr:`${e}: not available on the hosted control plane (no host). Cloud boxes push via git.lease-token.
6
+ `},501):te({error:"rpc method not implemented",method:e},501)}async function to(t,e,r){return"git.lease-token"===e?w(r,t):{exitCode:64,stdout:"",stderr:`relay: no approved-action executor for ${e}
7
+ `}}var td=U.pgTable("boxes",{boxId:q.text("box_id").primaryKey(),token:q.text("token").notNull(),originUrl:q.text("origin_url"),data:R.jsonb("data").$type().notNull(),registeredAt:j.timestamp("registered_at",{withTimezone:!0}).notNull()}),tl=U.pgTable("events",{id:D.bigint("id",{mode:"number"}).generatedAlwaysAsIdentity().primaryKey(),boxId:q.text("box_id").notNull(),type:q.text("type").notNull(),ts:q.text("ts"),payload:R.jsonb("payload"),receivedAt:j.timestamp("received_at",{withTimezone:!0}).notNull()}),tu=U.pgTable("box_status",{boxId:q.text("box_id").primaryKey(),name:q.text("name"),projectIndex:J.integer("project_index"),status:R.jsonb("status").$type().notNull(),updatedAt:j.timestamp("updated_at",{withTimezone:!0}).notNull()}),tc=U.pgTable("prompts",{id:q.text("id").primaryKey(),boxId:q.text("box_id").notNull(),ev:R.jsonb("ev").$type().notNull(),method:q.text("method").notNull(),params:R.jsonb("params"),status:q.text("status").$type().notNull(),answer:q.text("answer").$type(),cancelled:M.boolean("cancelled"),result:R.jsonb("result").$type(),createdAt:j.timestamp("created_at",{withTimezone:!0}).notNull(),expiresAt:j.timestamp("expires_at",{withTimezone:!0})}),tp=U.pgTable("create_jobs",{id:q.text("id").primaryKey(),status:q.text("status").$type().notNull(),request:R.jsonb("request").$type().notNull(),result:R.jsonb("result").$type(),claimedBy:q.text("claimed_by"),createdAt:j.timestamp("created_at",{withTimezone:!0}).notNull(),startedAt:j.timestamp("started_at",{withTimezone:!0}),finishedAt:j.timestamp("finished_at",{withTimezone:!0})}),th=`
8
8
  CREATE TABLE IF NOT EXISTS boxes (
9
9
  box_id text PRIMARY KEY,
10
10
  token text NOT NULL,
@@ -58,29 +58,60 @@ CREATE TABLE IF NOT EXISTS create_jobs (
58
58
  finished_at timestamptz
59
59
  );
60
60
  CREATE INDEX IF NOT EXISTS create_jobs_queued_idx ON create_jobs (created_at) WHERE status = 'queued';
61
- `,P=class{eventCap;connectionString;injectedPool;poolPromise=null;constructor(t={}){this.connectionString=t.connectionString,this.injectedPool=t.pool,this.eventCap=t.eventCap??1e3}pool(){return this.injectedPool?Promise.resolve(this.injectedPool):(this.poolPromise||(this.poolPromise=t.A(6194).then(({Pool:t})=>new t({connectionString:this.connectionString}))),this.poolPromise)}async query(t,e){let r=await this.pool();return(await r.query(t,e)).rows}async migrate(){let t=await this.pool();await t.query(O)}async close(){if(!this.injectedPool&&this.poolPromise){let t=await this.poolPromise;await t.end(),this.poolPromise=null}}async registerBox(t){let e=t.originUrl??null;await this.query(`INSERT INTO boxes (box_id, token, origin_url, data)
62
- VALUES ($1, $2, $3, $4)
63
- ON CONFLICT (box_id) DO UPDATE
64
- SET token = EXCLUDED.token, origin_url = EXCLUDED.origin_url, data = EXCLUDED.data`,[t.boxId,t.token,e,JSON.stringify(t)])}async getBox(t){let e=await this.query("SELECT data FROM boxes WHERE box_id = $1",[t]);return e[0]?.data}async authenticateBox(t){if(0===t.length)return null;let e=await this.query("SELECT data FROM boxes WHERE token = $1 LIMIT 1",[t]);return e[0]?.data??null}async listBoxes(){return(await this.query("SELECT data FROM boxes ORDER BY registered_at")).map(t=>t.data)}async forgetBox(t){return(await this.query("DELETE FROM boxes WHERE box_id = $1 RETURNING box_id",[t])).length>0}async countBoxes(){let t=await this.query("SELECT count(*)::text AS n FROM boxes");return Number.parseInt(t[0]?.n??"0",10)}async appendEvent(t){let e=await this.query(`INSERT INTO events (box_id, type, ts, payload)
65
- VALUES ($1, $2, $3, $4)
66
- RETURNING id, received_at`,[t.boxId,t.type,t.ts??null,void 0===t.payload?null:JSON.stringify(t.payload)]),r=Number(e[0].id);return this.eventCap>0&&await this.query("DELETE FROM events WHERE id <= $1",[r-this.eventCap]),{id:r,boxId:t.boxId,type:t.type,ts:t.ts,payload:t.payload,receivedAt:new Date(e[0].received_at).toISOString()}}async listEvents(t,e){return(void 0!==e?await this.query(`SELECT id, box_id, type, ts, payload, received_at FROM events
67
- WHERE id > $1 AND box_id = $2 ORDER BY id`,[t,e]):await this.query(`SELECT id, box_id, type, ts, payload, received_at FROM events
68
- WHERE id > $1 ORDER BY id`,[t])).map(k)}async countEvents(){let t=await this.query("SELECT count(*)::text AS n FROM events");return Number.parseInt(t[0]?.n??"0",10)}async setStatus(t,e,r,s){await this.query(`INSERT INTO box_status (box_id, name, project_index, status, updated_at)
69
- VALUES ($1, $2, $3, $4, now())
70
- ON CONFLICT (box_id) DO UPDATE
71
- SET name = EXCLUDED.name, project_index = EXCLUDED.project_index,
72
- status = EXCLUDED.status, updated_at = now()`,[t,e,r??null,JSON.stringify(s)])}async getStatus(t){let e=await this.query("SELECT status FROM box_status WHERE box_id = $1",[t]);return e[0]?.status}async deleteStatus(t){await this.query("DELETE FROM box_status WHERE box_id = $1",[t])}async listStatuses(){return(await this.query("SELECT box_id, status FROM box_status")).map(t=>({boxId:t.box_id,status:t.status}))}async createPrompt(t){await this.query(`INSERT INTO prompts (id, box_id, ev, method, params, status, answer, cancelled, result, created_at, expires_at)
73
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
74
- ON CONFLICT (id) DO NOTHING`,[t.id,t.boxId,JSON.stringify(t.ev),t.method,void 0===t.params?null:JSON.stringify(t.params),t.status,t.answer??null,t.cancelled??null,void 0===t.result?null:JSON.stringify(t.result),t.createdAt,t.expiresAt??null])}async getPrompt(t){let e=await this.query(`SELECT id, box_id, ev, method, params, status, answer, cancelled, result, created_at, expires_at
75
- FROM prompts WHERE id = $1`,[t]);return e[0]?R(e[0]):null}async answerPrompt(t,e,r){return(await this.query(`UPDATE prompts SET status = 'answered', answer = $2, cancelled = $3
76
- WHERE id = $1 AND status = 'pending' RETURNING id`,[t,e,r??null])).length>0}async listPendingPrompts(t){return(await this.query(`SELECT id, box_id, ev, method, params, status, answer, cancelled, result, created_at, expires_at
77
- FROM prompts WHERE box_id = $1 AND status = 'pending' ORDER BY created_at`,[t])).map(R)}async setPromptResult(t,e){await this.query("UPDATE prompts SET result = $2 WHERE id = $1",[t,JSON.stringify(e)])}async enqueueCreateJob(t){await this.query(`INSERT INTO create_jobs (id, status, request, result, claimed_by, created_at, started_at, finished_at)
78
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (id) DO NOTHING`,[t.id,t.status,JSON.stringify(t.request),t.result?JSON.stringify(t.result):null,t.claimedBy??null,t.createdAt,t.startedAt??null,t.finishedAt??null])}async getCreateJob(t){let e=await this.query(`SELECT id, status, request, result, claimed_by, created_at, started_at, finished_at
79
- FROM create_jobs WHERE id = $1`,[t]);return e[0]?$(e[0]):null}async claimNextCreateJob(t){let e=await this.query(`UPDATE create_jobs SET status = 'running', claimed_by = $1, started_at = now()
80
- WHERE id = (
81
- SELECT id FROM create_jobs WHERE status = 'queued'
82
- ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1
83
- )
84
- RETURNING id, status, request, result, claimed_by, created_at, started_at, finished_at`,[t]);return e[0]?$(e[0]):null}async completeCreateJob(t,e,r){await this.query("UPDATE create_jobs SET status = $2, result = $3, finished_at = now() WHERE id = $1",[t,e,JSON.stringify(r)])}};function $(t){return{id:t.id,status:t.status,request:t.request,result:t.result??void 0,claimedBy:t.claimed_by??void 0,createdAt:new Date(t.created_at).toISOString(),startedAt:t.started_at?new Date(t.started_at).toISOString():void 0,finishedAt:t.finished_at?new Date(t.finished_at).toISOString():void 0}}function R(t){return{id:t.id,boxId:t.box_id,ev:t.ev,method:t.method,params:t.params??void 0,status:t.status,answer:t.answer??void 0,cancelled:t.cancelled??void 0,result:t.result??void 0,createdAt:new Date(t.created_at).toISOString(),expiresAt:t.expires_at?new Date(t.expires_at).toISOString():void 0}}function k(t){return{id:Number(t.id),boxId:t.box_id,type:t.type,ts:t.ts??void 0,payload:t.payload??void 0,receivedAt:new Date(t.received_at).toISOString()}}t.s(["PostgresStore",0,P,"SCHEMA_SQL",0,O,"drainCreateJobs",0,y,"drainOneCreateJob",0,f,"handleRelayRequest",0,_],13272),t.s([],7876)}];
61
+ `,tm=F.sqliteTable("boxes",{boxId:z.text("box_id").primaryKey(),token:z.text("token").notNull(),originUrl:z.text("origin_url"),data:z.text("data",{mode:"json"}).$type().notNull(),registeredAt:z.text("registered_at").notNull()},t=>[G.index("boxes_token_idx").on(t.token)]),tg=F.sqliteTable("events",{id:X.integer("id").primaryKey({autoIncrement:!0}),boxId:z.text("box_id").notNull(),type:z.text("type").notNull(),ts:z.text("ts"),payload:z.text("payload",{mode:"json"}),receivedAt:z.text("received_at").notNull()},t=>[G.index("events_box_idx").on(t.boxId,t.id)]),tb=F.sqliteTable("box_status",{boxId:z.text("box_id").primaryKey(),name:z.text("name"),projectIndex:X.integer("project_index"),status:z.text("status",{mode:"json"}).$type().notNull(),updatedAt:z.text("updated_at").notNull()}),tx=F.sqliteTable("prompts",{id:z.text("id").primaryKey(),boxId:z.text("box_id").notNull(),ev:z.text("ev",{mode:"json"}).$type().notNull(),method:z.text("method").notNull(),params:z.text("params",{mode:"json"}),status:z.text("status").$type().notNull(),answer:z.text("answer").$type(),cancelled:X.integer("cancelled",{mode:"boolean"}),result:z.text("result",{mode:"json"}).$type(),createdAt:z.text("created_at").notNull(),expiresAt:z.text("expires_at")},t=>[G.index("prompts_box_status_idx").on(t.boxId,t.status)]),tw=F.sqliteTable("create_jobs",{id:z.text("id").primaryKey(),status:z.text("status").$type().notNull(),request:z.text("request",{mode:"json"}).$type().notNull(),result:z.text("result",{mode:"json"}).$type(),claimedBy:z.text("claimed_by"),createdAt:z.text("created_at").notNull(),startedAt:z.text("started_at"),finishedAt:z.text("finished_at")},t=>[G.index("create_jobs_status_idx").on(t.status,t.createdAt)]),ty=`
62
+ CREATE TABLE IF NOT EXISTS boxes (
63
+ box_id text PRIMARY KEY,
64
+ token text NOT NULL,
65
+ origin_url text,
66
+ data text NOT NULL,
67
+ registered_at text NOT NULL
68
+ );
69
+ CREATE INDEX IF NOT EXISTS boxes_token_idx ON boxes (token);
70
+
71
+ CREATE TABLE IF NOT EXISTS events (
72
+ id integer PRIMARY KEY AUTOINCREMENT,
73
+ box_id text NOT NULL,
74
+ type text NOT NULL,
75
+ ts text,
76
+ payload text,
77
+ received_at text NOT NULL
78
+ );
79
+ CREATE INDEX IF NOT EXISTS events_box_idx ON events (box_id, id);
80
+
81
+ CREATE TABLE IF NOT EXISTS box_status (
82
+ box_id text PRIMARY KEY,
83
+ name text,
84
+ project_index integer,
85
+ status text NOT NULL,
86
+ updated_at text NOT NULL
87
+ );
88
+
89
+ CREATE TABLE IF NOT EXISTS prompts (
90
+ id text PRIMARY KEY,
91
+ box_id text NOT NULL,
92
+ ev text NOT NULL,
93
+ method text NOT NULL,
94
+ params text,
95
+ status text NOT NULL DEFAULT 'pending',
96
+ answer text,
97
+ cancelled integer,
98
+ result text,
99
+ created_at text NOT NULL,
100
+ expires_at text
101
+ );
102
+ CREATE INDEX IF NOT EXISTS prompts_box_status_idx ON prompts (box_id, status);
103
+
104
+ CREATE TABLE IF NOT EXISTS create_jobs (
105
+ id text PRIMARY KEY,
106
+ status text NOT NULL DEFAULT 'queued',
107
+ request text NOT NULL,
108
+ result text,
109
+ claimed_by text,
110
+ created_at text NOT NULL,
111
+ started_at text,
112
+ finished_at text
113
+ );
114
+ CREATE INDEX IF NOT EXISTS create_jobs_status_idx ON create_jobs (status, created_at);
115
+ `;function tf(t){return t instanceof Date?t.toISOString():new Date(t).toISOString()}function tv(t){return null===t?void 0:tf(t)}function tA(t){return{id:Number(t.id),boxId:t.boxId,type:t.type,ts:t.ts??void 0,payload:t.payload??void 0,receivedAt:tf(t.receivedAt)}}function tI(t){return{id:t.id,boxId:t.boxId,ev:t.ev,method:t.method,params:t.params??void 0,status:t.status,answer:t.answer??void 0,cancelled:t.cancelled??void 0,result:t.result??void 0,createdAt:tf(t.createdAt),expiresAt:tv(t.expiresAt)}}function tS(t){return{id:t.id,status:t.status,request:t.request,result:t.result??void 0,claimedBy:t.claimedBy??void 0,createdAt:tf(t.createdAt),startedAt:tv(t.startedAt),finishedAt:tv(t.finishedAt)}}var tT=class{eventCap;connectionString;injectedPool;poolPromise=null;dbPromise=null;constructor(t={}){this.connectionString=t.connectionString,this.injectedPool=t.pool,this.eventCap=t.eventCap??1e3}pool(){return this.injectedPool?Promise.resolve(this.injectedPool):(this.poolPromise??=t.A(6194).then(({default:t})=>new t.Pool({connectionString:this.connectionString})),this.poolPromise)}db(){return this.dbPromise??=(async()=>{let e=await this.pool(),{drizzle:r}=await t.A(14788);return r(e)})(),this.dbPromise}async migrate(){let t=await this.pool();await t.query(th)}async close(){if(!this.injectedPool&&this.poolPromise){let t=await this.poolPromise;await t.end(),this.poolPromise=null,this.dbPromise=null}}async registerBox(t){let e=await this.db();await e.insert(td).values({boxId:t.boxId,token:t.token,originUrl:t.originUrl??null,data:t,registeredAt:new Date(t.registeredAt)}).onConflictDoUpdate({target:td.boxId,set:{token:t.token,originUrl:t.originUrl??null,data:t}})}async getBox(t){let e=await this.db(),r=await e.select({data:td.data}).from(td).where((0,H.eq)(td.boxId,t));return r[0]?.data}async authenticateBox(t){if(0===t.length)return null;let e=await this.db(),r=await e.select({data:td.data}).from(td).where((0,H.eq)(td.token,t)).limit(1);return r[0]?.data??null}async listBoxes(){let t=await this.db();return(await t.select({data:td.data}).from(td).orderBy((0,Y.asc)(td.registeredAt))).map(t=>t.data)}async forgetBox(t){let e=await this.db();return(await e.delete(td).where((0,H.eq)(td.boxId,t)).returning({boxId:td.boxId})).length>0}async countBoxes(){return(await this.db()).$count(td)}async appendEvent(t){let e=await this.db(),r=(await e.insert(tl).values({boxId:t.boxId,type:t.type,ts:t.ts??null,payload:t.payload??null,receivedAt:new Date}).returning({id:tl.id,receivedAt:tl.receivedAt}))[0];return this.eventCap>0&&await e.delete(tl).where((0,H.lte)(tl.id,r.id-this.eventCap)),{id:r.id,boxId:t.boxId,type:t.type,ts:t.ts,payload:t.payload,receivedAt:r.receivedAt.toISOString()}}async listEvents(t,e){let r=await this.db(),a=void 0===e?(0,H.gt)(tl.id,t):(0,H.and)((0,H.gt)(tl.id,t),(0,H.eq)(tl.boxId,e));return(await r.select().from(tl).where(a).orderBy((0,Y.asc)(tl.id))).map(tA)}async countEvents(){return(await this.db()).$count(tl)}async setStatus(t,e,r,a){let s=await this.db(),n=new Date;await s.insert(tu).values({boxId:t,name:e,projectIndex:r??null,status:a,updatedAt:n}).onConflictDoUpdate({target:tu.boxId,set:{name:e,projectIndex:r??null,status:a,updatedAt:n}})}async getStatus(t){let e=await this.db(),r=await e.select({status:tu.status}).from(tu).where((0,H.eq)(tu.boxId,t));return r[0]?.status}async deleteStatus(t){let e=await this.db();await e.delete(tu).where((0,H.eq)(tu.boxId,t))}async listStatuses(){return(await this.db()).select({boxId:tu.boxId,status:tu.status}).from(tu)}async createPrompt(t){let e=await this.db();await e.insert(tc).values({id:t.id,boxId:t.boxId,ev:t.ev,method:t.method,params:t.params??null,status:t.status,answer:t.answer??null,cancelled:t.cancelled??null,result:t.result??null,createdAt:new Date(t.createdAt),expiresAt:t.expiresAt?new Date(t.expiresAt):null}).onConflictDoNothing({target:tc.id})}async getPrompt(t){let e=await this.db(),r=await e.select().from(tc).where((0,H.eq)(tc.id,t));return r[0]?tI(r[0]):null}async answerPrompt(t,e,r){let a=await this.db();return(await a.update(tc).set({status:"answered",answer:e,cancelled:r??null}).where((0,H.and)((0,H.eq)(tc.id,t),(0,H.eq)(tc.status,"pending"))).returning({id:tc.id})).length>0}async listPendingPrompts(t){let e=await this.db();return(await e.select().from(tc).where((0,H.and)((0,H.eq)(tc.boxId,t),(0,H.eq)(tc.status,"pending"))).orderBy((0,Y.asc)(tc.createdAt))).map(tI)}async setPromptResult(t,e){let r=await this.db();await r.update(tc).set({result:e}).where((0,H.eq)(tc.id,t))}async enqueueCreateJob(t){let e=await this.db();await e.insert(tp).values({id:t.id,status:t.status,request:t.request,result:t.result??null,claimedBy:t.claimedBy??null,createdAt:new Date(t.createdAt),startedAt:t.startedAt?new Date(t.startedAt):null,finishedAt:t.finishedAt?new Date(t.finishedAt):null}).onConflictDoNothing({target:tp.id})}async getCreateJob(t){let e=await this.db(),r=await e.select().from(tp).where((0,H.eq)(tp.id,t));return r[0]?tS(r[0]):null}async listCreateJobs(t){let e=(await this.db()).select().from(tp),r=t?.status?.length?e.where((0,H.inArray)(tp.status,t.status)):e;return(await r.orderBy((0,Y.desc)(tp.createdAt)).limit(t?.limit??100)).map(tS)}async claimNextCreateJob(t){let e=await this.db(),r=e.select({id:tp.id}).from(tp).where((0,H.eq)(tp.status,"queued")).orderBy((0,Y.asc)(tp.createdAt)).limit(1).for("update",{skipLocked:!0}),a=await e.update(tp).set({status:"running",claimedBy:t,startedAt:new Date}).where((0,H.inArray)(tp.id,r)).returning();return a[0]?tS(a[0]):null}async completeCreateJob(t,e,r){let a=await this.db();await a.update(tp).set({status:e,result:r,finishedAt:new Date}).where((0,H.eq)(tp.id,t))}async prunePrompts(t){let e=await this.db(),r=new Date(t);return(await e.delete(tc).where((0,H.or)((0,H.and)((0,H.eq)(tc.status,"answered"),(0,H.lt)(tc.createdAt,r)),(0,H.and)((0,H.isNotNull)(tc.expiresAt),(0,H.lt)(tc.expiresAt,r)))).returning({id:tc.id})).length}async pruneCreateJobs(t){let e=await this.db(),r=new Date(t);return(await e.delete(tp).where((0,H.and)((0,H.inArray)(tp.status,["done","failed"]),(0,H.isNotNull)(tp.finishedAt),(0,H.lt)(tp.finishedAt,r))).returning({id:tp.id})).length}},tE=(0,a.join)(W.STATE_DIR,"hub","store.db"),tN=class{path;eventCap;raw=null;dbPromise=null;constructor(t={}){this.path=t.path??tE,this.eventCap=t.eventCap??1e3}db(){return this.dbPromise??=(async()=>{!function(){let[t=0,e=0]=process.versions.node.split(".").map(Number);if(!(t>22||22===t&&e>=5))throw Error(`the SQLite store needs Node >= 22.5 for node:sqlite (running ${process.versions.node}). Upgrade Node, or point the hub at a Postgres store (POSTGRES_URL).`)}();let{DatabaseSync:e}=function(){(0,K.createRequire)(Q.url);let t=Error("Cannot find module 'node:sqlite': Unsupported external type Url for commonjs reference");throw t.code="MODULE_NOT_FOUND",t}(),{drizzle:r}=await t.A(86115);":memory:"!==this.path&&(0,n.mkdirSync)((0,a.dirname)(this.path),{recursive:!0});let s=new e(this.path);return s.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;"),s.exec(ty),this.raw=s,r(async(t,e,r)=>{let a,n=s.prepare(t);return"run"===r?(n.run(...e),{rows:[]}):("function"==typeof n.setReturnArrays?(n.setReturnArrays(!0),a=n.all(...e)):a=n.all(...e).map(t=>Object.values(t)),"get"===r?{rows:a[0]??[]}:{rows:a})})})(),this.dbPromise}async migrate(){await this.db()}async close(){this.dbPromise&&await this.dbPromise.catch(()=>void 0),this.raw?.close(),this.raw=null,this.dbPromise=null}async registerBox(t){let e=await this.db();await e.insert(tm).values({boxId:t.boxId,token:t.token,originUrl:t.originUrl??null,data:t,registeredAt:t.registeredAt}).onConflictDoUpdate({target:tm.boxId,set:{token:t.token,originUrl:t.originUrl??null,data:t}})}async getBox(t){let e=await this.db(),r=await e.select({data:tm.data}).from(tm).where((0,H.eq)(tm.boxId,t));return r[0]?.data}async authenticateBox(t){if(0===t.length)return null;let e=await this.db(),r=await e.select({data:tm.data}).from(tm).where((0,H.eq)(tm.token,t)).limit(1);return r[0]?.data??null}async listBoxes(){let t=await this.db();return(await t.select({data:tm.data}).from(tm).orderBy((0,Y.asc)(tm.registeredAt))).map(t=>t.data)}async forgetBox(t){let e=await this.db();return(await e.delete(tm).where((0,H.eq)(tm.boxId,t)).returning({boxId:tm.boxId})).length>0}async countBoxes(){return(await this.db()).$count(tm)}async appendEvent(t){let e=await this.db(),r=new Date().toISOString(),a=(await e.insert(tg).values({boxId:t.boxId,type:t.type,ts:t.ts??null,payload:t.payload??null,receivedAt:r}).returning({id:tg.id}))[0].id;return this.eventCap>0&&await e.delete(tg).where((0,H.lte)(tg.id,a-this.eventCap)),{id:a,boxId:t.boxId,type:t.type,ts:t.ts,payload:t.payload,receivedAt:r}}async listEvents(t,e){let r=await this.db(),a=void 0===e?(0,H.gt)(tg.id,t):(0,H.and)((0,H.gt)(tg.id,t),(0,H.eq)(tg.boxId,e));return(await r.select().from(tg).where(a).orderBy((0,Y.asc)(tg.id))).map(tA)}async countEvents(){return(await this.db()).$count(tg)}async setStatus(t,e,r,a){let s=await this.db(),n=new Date().toISOString();await s.insert(tb).values({boxId:t,name:e,projectIndex:r??null,status:a,updatedAt:n}).onConflictDoUpdate({target:tb.boxId,set:{name:e,projectIndex:r??null,status:a,updatedAt:n}})}async getStatus(t){let e=await this.db(),r=await e.select({status:tb.status}).from(tb).where((0,H.eq)(tb.boxId,t));return r[0]?.status}async deleteStatus(t){let e=await this.db();await e.delete(tb).where((0,H.eq)(tb.boxId,t))}async listStatuses(){return(await this.db()).select({boxId:tb.boxId,status:tb.status}).from(tb)}async createPrompt(t){let e=await this.db();await e.insert(tx).values({id:t.id,boxId:t.boxId,ev:t.ev,method:t.method,params:t.params??null,status:t.status,answer:t.answer??null,cancelled:t.cancelled??null,result:t.result??null,createdAt:t.createdAt,expiresAt:t.expiresAt??null}).onConflictDoNothing({target:tx.id})}async getPrompt(t){let e=await this.db(),r=await e.select().from(tx).where((0,H.eq)(tx.id,t));return r[0]?tI(r[0]):null}async answerPrompt(t,e,r){let a=await this.db();return(await a.update(tx).set({status:"answered",answer:e,cancelled:r??null}).where((0,H.and)((0,H.eq)(tx.id,t),(0,H.eq)(tx.status,"pending"))).returning({id:tx.id})).length>0}async listPendingPrompts(t){let e=await this.db();return(await e.select().from(tx).where((0,H.and)((0,H.eq)(tx.boxId,t),(0,H.eq)(tx.status,"pending"))).orderBy((0,Y.asc)(tx.createdAt))).map(tI)}async setPromptResult(t,e){let r=await this.db();await r.update(tx).set({result:e}).where((0,H.eq)(tx.id,t))}async enqueueCreateJob(t){let e=await this.db();await e.insert(tw).values({id:t.id,status:t.status,request:t.request,result:t.result??null,claimedBy:t.claimedBy??null,createdAt:t.createdAt,startedAt:t.startedAt??null,finishedAt:t.finishedAt??null}).onConflictDoNothing({target:tw.id})}async getCreateJob(t){let e=await this.db(),r=await e.select().from(tw).where((0,H.eq)(tw.id,t));return r[0]?tS(r[0]):null}async listCreateJobs(t){let e=(await this.db()).select().from(tw),r=t?.status?.length?e.where((0,H.inArray)(tw.status,t.status)):e;return(await r.orderBy((0,Y.desc)(tw.createdAt)).limit(t?.limit??100)).map(tS)}async claimNextCreateJob(t){let e=await this.db(),r=e.select({id:tw.id}).from(tw).where((0,H.eq)(tw.status,"queued")).orderBy((0,Y.asc)(tw.createdAt)).limit(1),a=await e.update(tw).set({status:"running",claimedBy:t,startedAt:new Date().toISOString()}).where((0,H.and)((0,H.inArray)(tw.id,r),(0,H.eq)(tw.status,"queued"))).returning();return a[0]?tS(a[0]):null}async completeCreateJob(t,e,r){let a=await this.db();await a.update(tw).set({status:e,result:r,finishedAt:new Date().toISOString()}).where((0,H.eq)(tw.id,t))}async prunePrompts(t){let e=await this.db();return(await e.delete(tx).where((0,H.or)((0,H.and)((0,H.eq)(tx.status,"answered"),(0,H.lt)(tx.createdAt,t)),(0,H.and)((0,H.isNotNull)(tx.expiresAt),(0,H.lt)(tx.expiresAt,t)))).returning({id:tx.id})).length}async pruneCreateJobs(t){let e=await this.db();return(await e.delete(tw).where((0,H.and)((0,H.inArray)(tw.status,["done","failed"]),(0,H.isNotNull)(tw.finishedAt),(0,H.lt)(tw.finishedAt,t))).returning({id:tw.id})).length}},tP=(0,a.join)(W.STATE_DIR,"hub","custody"),t_=class{root;constructor(t={}){this.root=t.root??tP}async put(t,r){let n=E(t),i=(0,a.join)(this.root,n),o=T(r),d=await this.readEntry(n);if(d&&d.entry.sha256===o)return{...d.entry,changed:!1};await (0,e.mkdir)((0,a.dirname)(i),{recursive:!0,mode:448});let l=`${i}.${(0,s.randomBytes)(6).toString("hex")}.tmp`;try{await (0,e.writeFile)(l,r,{mode:384}),await (0,e.chmod)(l,384),await (0,e.rename)(l,i)}catch(t){throw await (0,e.rm)(l,{force:!0}),t}let u=await (0,e.stat)(i);return{path:n,size:r.length,sha256:o,mode:511&u.mode,updatedAt:u.mtime.toISOString(),changed:!0}}async get(t){return this.readEntry(E(t))}async stat(t){let e=await this.readEntry(E(t));return e?e.entry:null}async list(t){let e=void 0===t?"":N(t),r=[];for(let t of(await this.walk(this.root))){if(e.length>0&&t!==e&&!t.startsWith(`${e}/`))continue;let a=await this.readEntry(t);a&&r.push(a.entry)}return r.sort((t,e)=>t.path<e.path?-1:+(t.path>e.path)),r}async delete(t){let r=E(t),s=(0,a.join)(this.root,r);try{return await (0,e.rm)(s),!0}catch(t){if("ENOENT"===t.code)return!1;throw t}}async readEntry(t){let r=(0,a.join)(this.root,t);try{let[a,s]=await Promise.all([(0,e.readFile)(r),(0,e.stat)(r)]);return{entry:{path:t,size:a.length,sha256:T(a),mode:511&s.mode,updatedAt:s.mtime.toISOString()},data:a}}catch(e){let t=e.code;if("ENOENT"===t||"EISDIR"===t)return null;throw e}}async walk(t){let r;try{r=await (0,e.readdir)(t,{withFileTypes:!0})}catch(t){if("ENOENT"===t.code)return[];throw t}let s=[];for(let e of r){let r=(0,a.join)(t,e.name);e.isDirectory()?s.push(...await this.walk(r)):e.isFile()&&!e.name.endsWith(".tmp")&&s.push((0,a.relative)(this.root,r).split(a.sep).join("/"))}return s}};t.s(["DEFAULT_CUSTODY_DIR",0,tP,"DEFAULT_SQLITE_STORE_PATH",0,tE,"FsCustodyStore",0,t_,"PG_SCHEMA_SQL",0,th,"PostgresStore",0,tT,"SQLITE_SCHEMA_SQL",0,ty,"SqliteStore",0,tN,"cloneRepoWithLfs",0,V,"drainCreateJobs",0,tt,"drainOneCreateJob",0,Z,"handleRelayRequest",0,tn,"makeControlPlaneCreateBox",0,function(t){return async(e,r)=>{let a=t.log??(()=>{}),s=t.tmpDir(r);try{a(`leasing a push token for ${e.repoUrl}`);let r=await t.leaseRemoteUrl(e.repoUrl);if(a(`cloning ${e.repoUrl}${e.branch?`@${e.branch}`:""} into ${s}`),await t.cloneRepo(r,e.repoUrl,s,e.branch),t.fetchSeedMaterial)try{let r=await t.fetchSeedMaterial(e.repoUrl,s);if(r&&r.files>0){let t=[r.repoHeadSha?`at ${r.repoHeadSha.slice(0,8)}`:null,r.capturedAt?`captured ${r.capturedAt}`:null].filter(Boolean).join(", ");a(`applied ${String(r.files)} seed file(s) from custody${t?` (${t})`:""}`)}}catch(t){a(`seed material unavailable (continuing with a bare clone): ${t instanceof Error?t.message:String(t)}`)}a(`provisioning ${e.provider} box from the clone`);let n=await t.createBox({workspacePath:s,name:e.name,provider:e.provider,agent:e.agent,prompt:e.prompt,agentArgs:e.agentArgs,onLog:t.log});return a(`created box ${n.id}`),{boxId:n.id,agentStartError:n.agentStartError}}finally{await t.cleanup(s)}}},"makeStore",0,function(t){if(!t||"memory"===t)return new c;if(t.startsWith("postgres://")||t.startsWith("postgresql://"))return new tT({connectionString:t});if(t.startsWith("sqlite:")){let e=t.slice(7).replace(/^\/\//,"");if(!e)throw Error(`store spec has no path: ${t}`);return new tN({path:e})}if(":memory:"===t||t.startsWith("/")||t.startsWith(".")||t.endsWith(".db"))return new tN({path:t});throw Error(`unknown store spec: ${t}`)}],13806),t.s([],7876)}];
85
116
 
86
117
  //# sourceMappingURL=packages_relay_dist_control-plane_03a-9aj.js.map