@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,4 +1,41 @@
1
1
  import { createRequire as __cr } from 'node:module'; import { fileURLToPath as __f } from 'node:url'; import { dirname as __d } from 'node:path'; const require = __cr(import.meta.url); const __filename = __f(import.meta.url); const __dirname = __d(__filename);
2
+ import {
3
+ BUILT_IN_DEFAULTS,
4
+ GLOBAL_CONFIG_FILE,
5
+ STATE_DIR,
6
+ hashProjectPath,
7
+ loadEffectiveConfig,
8
+ parseUserConfig,
9
+ projectDirSegment,
10
+ require_dist,
11
+ sanitizeMnemonic,
12
+ setConfigValue
13
+ } from "./chunk-A5Y7LJMU.js";
14
+ import {
15
+ index,
16
+ integer as integer2,
17
+ sqliteTable,
18
+ text as text2
19
+ } from "./chunk-6AVSKCZJ.js";
20
+ import {
21
+ and,
22
+ asc,
23
+ bigint,
24
+ boolean,
25
+ desc,
26
+ eq,
27
+ gt,
28
+ inArray,
29
+ integer,
30
+ isNotNull,
31
+ jsonb,
32
+ lt,
33
+ lte,
34
+ or,
35
+ pgTable,
36
+ text,
37
+ timestamp
38
+ } from "./chunk-F2JI4GMX.js";
2
39
  import {
3
40
  AmbiguousBoxError,
4
41
  BOX_HOME,
@@ -12,10 +49,11 @@ import {
12
49
  MINIMAL_TRUSTED_CODEX_CONFIG,
13
50
  OPENCODE_PULL_CONFIG_ITEMS,
14
51
  OPENCODE_PULL_DATA_ITEMS,
15
- STATE_DIR,
52
+ STATE_DIR as STATE_DIR2,
16
53
  STATE_FILE,
17
54
  SYNC_DRYRUN_ENV,
18
55
  addProjectAlias,
56
+ boxSshDirForProvider,
19
57
  claudeInstallFingerprint,
20
58
  claudeInventoryScript,
21
59
  computeClaudePullPlan,
@@ -78,45 +116,34 @@ import {
78
116
  upstreamRef,
79
117
  writeClaudeMergedRegistries,
80
118
  writeCredentialBackup
81
- } from "./chunk-RXYOWSSN.js";
119
+ } from "./chunk-RMEUA6PA.js";
82
120
  import {
83
121
  execa
84
122
  } from "./chunk-UDZ3VXRF.js";
85
- import {
86
- BUILT_IN_DEFAULTS,
87
- GLOBAL_CONFIG_FILE,
88
- hashProjectPath,
89
- loadEffectiveConfig,
90
- parseUserConfig,
91
- projectDirSegment,
92
- require_dist,
93
- sanitizeMnemonic,
94
- setConfigValue
95
- } from "./chunk-QSMPSV5Z.js";
96
123
  import {
97
124
  __toESM
98
125
  } from "./chunk-OG4KH2FZ.js";
99
126
 
100
127
  // ../../packages/sandbox-docker/dist/index.js
101
128
  import { spawnSync } from "child_process";
102
- import { mkdtemp as mkdtemp2, readdir as readdir2, readFile as readFile23, rm as rm22, stat as stat2, writeFile as writeFile3 } from "fs/promises";
129
+ import { mkdtemp as mkdtemp2, readdir as readdir22, readFile as readFile23, rm as rm22, stat as stat2, writeFile as writeFile4 } from "fs/promises";
103
130
  import { homedir as homedir2, tmpdir as tmpdir2 } from "os";
104
- import { join as join3 } from "path";
131
+ import { join as join32 } from "path";
105
132
  import { setTimeout as delay } from "timers/promises";
106
- import { mkdir as mkdir3, readFile as readFile4, readdir as readdir3, stat } from "fs/promises";
107
- import { createHash as createHash2 } from "crypto";
133
+ import { mkdir as mkdir4, readFile as readFile4, readdir as readdir3, stat as stat3 } from "fs/promises";
134
+ import { createHash as createHash3 } from "crypto";
108
135
  import { homedir as homedir3 } from "os";
109
- import { dirname as dirname2, join as join23 } from "path";
110
- import { existsSync as existsSync2, mkdirSync, renameSync, statSync } from "fs";
111
- import { basename, dirname, posix, resolve } from "path";
136
+ import { dirname as dirname22, join as join24 } from "path";
137
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, renameSync, statSync } from "fs";
138
+ import { basename, dirname as dirname3, posix, resolve } from "path";
112
139
  import { createReadStream } from "fs";
113
- import { mkdtemp as mkdtemp3, rm as rm3 } from "fs/promises";
140
+ import { mkdtemp as mkdtemp3, rm as rm4 } from "fs/promises";
114
141
  import { tmpdir as tmpdir3 } from "os";
115
142
  import { join as join4 } from "path";
116
- import { chmod, mkdir as mkdir22 } from "fs/promises";
143
+ import { chmod as chmod2, mkdir as mkdir22 } from "fs/promises";
117
144
  import { basename as basename2, join as join42 } from "path";
118
145
  import { spawnSync as spawnSync2 } from "child_process";
119
- import { readFile as readFile32, stat as stat3 } from "fs/promises";
146
+ import { readFile as readFile33, stat as stat32 } from "fs/promises";
120
147
  import { homedir as homedir32 } from "os";
121
148
  import { join as join5 } from "path";
122
149
  import { homedir as homedir4 } from "os";
@@ -632,11 +659,11 @@ function validateUnitGraph(tasks, services) {
632
659
  if (color.get(name) === WHITE) visit(name);
633
660
  }
634
661
  }
635
- function parseConfig(text) {
662
+ function parseConfig(text3) {
636
663
  unknownKeyWarnings = [];
637
664
  let doc;
638
665
  try {
639
- doc = (0, import_yaml.parse)(text);
666
+ doc = (0, import_yaml.parse)(text3);
640
667
  } catch (err) {
641
668
  throw new ConfigError(`yaml parse error: ${err instanceof Error ? err.message : String(err)}`);
642
669
  }
@@ -695,16 +722,16 @@ function parseConfig(text) {
695
722
  return { services, tasks, replacements, warnings: unknownKeyWarnings };
696
723
  }
697
724
  async function loadConfig(path) {
698
- let text;
725
+ let text3;
699
726
  try {
700
- text = await readFile2(path, "utf8");
727
+ text3 = await readFile2(path, "utf8");
701
728
  } catch (err) {
702
729
  if (err.code === "ENOENT") {
703
730
  return { services: [], tasks: [], replacements: {}, warnings: [] };
704
731
  }
705
732
  throw err;
706
733
  }
707
- return parseConfig(text);
734
+ return parseConfig(text3);
708
735
  }
709
736
 
710
737
  // ../../packages/sandbox-docker/dist/index.js
@@ -713,30 +740,37 @@ import { existsSync as existsSync22 } from "fs";
713
740
  import { readFile as readFile42 } from "fs/promises";
714
741
  import { homedir as homedir6 } from "os";
715
742
  import { join as join8 } from "path";
743
+ import { connect } from "net";
716
744
  import { mkdir as mkdir32, readdir as readdir32, rm as rm32, stat as stat5 } from "fs/promises";
717
745
  import { homedir as homedir7, platform } from "os";
718
746
  import { join as join9, resolve as resolve2 } from "path";
719
- import { mkdir as mkdir4, mkdtemp as mkdtemp32, readFile as readFile5, readdir as readdir4, rm as rm4, writeFile as writeFile22 } from "fs/promises";
747
+ import { mkdir as mkdir42, mkdtemp as mkdtemp32, readFile as readFile5, readdir as readdir4, rm as rm42, writeFile as writeFile22 } from "fs/promises";
720
748
  import { homedir as homedir8, tmpdir as tmpdir32 } from "os";
721
749
  import { basename as basename3, join as join10 } from "path";
722
750
  import { stat as stat6 } from "fs/promises";
723
751
  import { spawn as spawn6 } from "child_process";
724
- import { randomBytes as randomBytes22 } from "crypto";
725
- import { existsSync as existsSync3, openSync as openSync2 } from "fs";
726
- import { cp, mkdir as mkdir5, readFile as readFile6, readdir as readdir5, rename as rename3, rm as rm5, unlink as unlink2, writeFile as writeFile32 } from "fs/promises";
752
+ import { randomBytes as randomBytes23 } from "crypto";
753
+ import { existsSync as existsSync32, openSync as openSync2 } from "fs";
754
+ import { cp, mkdir as mkdir5, readFile as readFile6, readdir as readdir5, rename as rename4, rm as rm5, unlink as unlink2, writeFile as writeFile32 } from "fs/promises";
727
755
  import { request as httpRequest } from "http";
728
- import { createRequire } from "module";
756
+ import { createRequire as createRequire2 } from "module";
729
757
  import { homedir as homedir9 } from "os";
730
- import { dirname as dirname3, join as join11, resolve as resolve3, sep } from "path";
758
+ import { dirname as dirname32, join as join11, resolve as resolve3, sep as sep2 } from "path";
731
759
  import { setTimeout as delay2 } from "timers/promises";
732
760
  import { fileURLToPath } from "url";
733
761
 
734
- // ../../packages/relay/dist/chunk-KNZCE7J6.js
762
+ // ../../packages/relay/dist/chunk-WVMWNSZY.js
735
763
  import { mkdir, rename, rm, writeFile } from "fs/promises";
736
764
  import { homedir } from "os";
737
765
  import { join } from "path";
738
766
  import { randomUUID } from "crypto";
739
767
  import { randomUUID as randomUUID2 } from "crypto";
768
+ import { existsSync } from "fs";
769
+ import { timingSafeEqual } from "crypto";
770
+ import { createHash } from "crypto";
771
+ import { timingSafeEqual as timingSafeEqual2 } from "crypto";
772
+ import { randomUUID as randomUUID3 } from "crypto";
773
+ import { timingSafeEqual as timingSafeEqual3 } from "crypto";
740
774
  import { createSign } from "crypto";
741
775
  var DEFAULT_RELAY_PORT = 8787;
742
776
  var DEFAULT_BOX_RELAY_PORT = 8788;
@@ -849,6 +883,10 @@ var BoxStatusStore = class {
849
883
  delete(boxId) {
850
884
  this.map.delete(boxId);
851
885
  }
886
+ /** Every box's latest snapshot in one pass (backs `Store.listStatuses`). */
887
+ list() {
888
+ return [...this.map.entries()].map(([boxId, status]) => ({ boxId, status }));
889
+ }
852
890
  };
853
891
  var MemoryStore = class {
854
892
  registry;
@@ -899,6 +937,9 @@ var MemoryStore = class {
899
937
  this.statusStore.delete(boxId);
900
938
  return Promise.resolve();
901
939
  }
940
+ listStatuses() {
941
+ return Promise.resolve(this.statusStore.list());
942
+ }
902
943
  createPrompt(row) {
903
944
  this.prompts.set(row.id, { ...row });
904
945
  return Promise.resolve();
@@ -935,6 +976,11 @@ var MemoryStore = class {
935
976
  const job = this.createJobs.get(id);
936
977
  return Promise.resolve(job ? { ...job } : null);
937
978
  }
979
+ listCreateJobs(opts) {
980
+ const wanted = opts?.status;
981
+ const rows = [...this.createJobs.values()].filter((j) => !wanted || wanted.includes(j.status)).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).map((j) => ({ ...j }));
982
+ return Promise.resolve(opts?.limit ? rows.slice(0, opts.limit) : rows);
983
+ }
938
984
  claimNextCreateJob(workerId) {
939
985
  const queued = [...this.createJobs.values()].filter((j) => j.status === "queued").sort((a, b) => a.createdAt.localeCompare(b.createdAt));
940
986
  const job = queued[0];
@@ -1161,6 +1207,10 @@ function resolveWorktree(reg, containerPath) {
1161
1207
  ).sort((a, b) => b.containerPath.length - a.containerPath.length);
1162
1208
  return prefixMatches[0] ?? trees.find((w) => w.containerPath === "/workspace") ?? null;
1163
1209
  }
1210
+ function hostRepoUnavailableReason(worktree, boxId, op) {
1211
+ if (worktree.hostMainRepo.length > 0 && existsSync(worktree.hostMainRepo)) return null;
1212
+ return `host-side ${op} is unavailable for box ${boxId}: its host repo (${worktree.hostMainRepo || "<unset>"}) does not exist on this host. Boxes created by the control-box worker have no host working copy \u2014 push from inside the box (leased) or adopt the box on this host first.`;
1213
+ }
1164
1214
  function parseGitRemote(origin) {
1165
1215
  const trimmed = origin.trim();
1166
1216
  if (trimmed.length === 0) throw new Error("empty git remote URL");
@@ -1244,6 +1294,481 @@ async function leaseTokenResult(leaser, reg) {
1244
1294
  };
1245
1295
  }
1246
1296
  }
1297
+ function isStoreRpcMethod(method) {
1298
+ return STORE_RPC_METHODS.has(method);
1299
+ }
1300
+ var STORE_RPC_METHODS = /* @__PURE__ */ new Set([
1301
+ "registerBox",
1302
+ "getBox",
1303
+ "authenticateBox",
1304
+ "listBoxes",
1305
+ "forgetBox",
1306
+ "countBoxes",
1307
+ "appendEvent",
1308
+ "listEvents",
1309
+ "countEvents",
1310
+ "setStatus",
1311
+ "getStatus",
1312
+ "deleteStatus",
1313
+ "listStatuses",
1314
+ "createPrompt",
1315
+ "getPrompt",
1316
+ "answerPrompt",
1317
+ "listPendingPrompts",
1318
+ "setPromptResult"
1319
+ ]);
1320
+ function applyStoreOp(store, method, args) {
1321
+ switch (method) {
1322
+ case "registerBox":
1323
+ return store.registerBox(args[0]);
1324
+ case "getBox":
1325
+ return store.getBox(args[0]);
1326
+ case "authenticateBox":
1327
+ return store.authenticateBox(args[0]);
1328
+ case "listBoxes":
1329
+ return store.listBoxes();
1330
+ case "forgetBox":
1331
+ return store.forgetBox(args[0]);
1332
+ case "countBoxes":
1333
+ return store.countBoxes();
1334
+ case "appendEvent":
1335
+ return store.appendEvent(args[0]);
1336
+ case "listEvents":
1337
+ return store.listEvents(args[0], args[1]);
1338
+ case "countEvents":
1339
+ return store.countEvents();
1340
+ case "setStatus":
1341
+ return store.setStatus(
1342
+ args[0],
1343
+ args[1],
1344
+ args[2],
1345
+ args[3]
1346
+ );
1347
+ case "getStatus":
1348
+ return store.getStatus(args[0]);
1349
+ case "deleteStatus":
1350
+ return store.deleteStatus(args[0]);
1351
+ case "listStatuses":
1352
+ return store.listStatuses();
1353
+ case "createPrompt":
1354
+ return store.createPrompt(args[0]);
1355
+ case "getPrompt":
1356
+ return store.getPrompt(args[0]);
1357
+ case "answerPrompt":
1358
+ return store.answerPrompt(
1359
+ args[0],
1360
+ args[1],
1361
+ args[2]
1362
+ );
1363
+ case "listPendingPrompts":
1364
+ return store.listPendingPrompts(args[0]);
1365
+ case "setPromptResult":
1366
+ return store.setPromptResult(args[0], args[1]);
1367
+ default:
1368
+ throw new Error(`unknown store op: ${method}`);
1369
+ }
1370
+ }
1371
+ var STORE_RPC_PATH = "/admin/store";
1372
+ function isStoreRpcPath(path) {
1373
+ return path === STORE_RPC_PATH;
1374
+ }
1375
+ function timingSafeEqualStr(a, b) {
1376
+ const ab = Buffer.from(a, "utf8");
1377
+ const bb = Buffer.from(b, "utf8");
1378
+ if (ab.length !== bb.length) return false;
1379
+ return timingSafeEqual(ab, bb);
1380
+ }
1381
+ function parseJson(text3) {
1382
+ if (text3.length === 0) return null;
1383
+ try {
1384
+ return JSON.parse(text3);
1385
+ } catch {
1386
+ return null;
1387
+ }
1388
+ }
1389
+ async function handleStoreRpcRequest(req, deps) {
1390
+ if (!isStoreRpcPath(req.path)) return null;
1391
+ const adminToken = deps.adminToken ?? "";
1392
+ if (adminToken.length === 0) {
1393
+ return { status: 503, body: { error: "control plane not configured: admin token unset" } };
1394
+ }
1395
+ if (!timingSafeEqualStr(req.bearer, adminToken)) {
1396
+ return { status: 401, body: { error: "invalid admin token" } };
1397
+ }
1398
+ if (req.method !== "POST") {
1399
+ return { status: 405, body: { error: "method not allowed" } };
1400
+ }
1401
+ const body = parseJson(req.bodyText);
1402
+ if (!body || typeof body.method !== "string" || !Array.isArray(body.args)) {
1403
+ return { status: 400, body: { error: "expected {method, args}" } };
1404
+ }
1405
+ if (!isStoreRpcMethod(body.method)) {
1406
+ return { status: 400, body: { error: `unknown store op: ${body.method}` } };
1407
+ }
1408
+ const result = await applyStoreOp(deps.store, body.method, body.args);
1409
+ return { status: 200, body: { result: result ?? null } };
1410
+ }
1411
+ var CUSTODY_SCOPES = ["agents", "projects", "boxes", "prepared"];
1412
+ var AGENT_IDS = ["claude", "codex", "opencode"];
1413
+ var CustodyPathError = class extends Error {
1414
+ constructor(message) {
1415
+ super(message);
1416
+ this.name = "CustodyPathError";
1417
+ }
1418
+ };
1419
+ var SEGMENT_RE = /^[A-Za-z0-9._-]+$/;
1420
+ var MAX_SEGMENTS = 6;
1421
+ var MAX_PATH_LENGTH = 256;
1422
+ function custodyDigest(data) {
1423
+ return createHash("sha256").update(data).digest("hex");
1424
+ }
1425
+ function normalizeCustodyPath(raw) {
1426
+ const trimmed = raw.replace(/^\/+/, "").replace(/\/+$/, "");
1427
+ if (trimmed.length === 0) throw new CustodyPathError("empty custody path");
1428
+ if (trimmed.length > MAX_PATH_LENGTH) {
1429
+ throw new CustodyPathError(`custody path too long (max ${String(MAX_PATH_LENGTH)} chars)`);
1430
+ }
1431
+ const segments = trimmed.split("/");
1432
+ if (segments.length < 2) {
1433
+ throw new CustodyPathError(`custody path needs a scope and a name: '${raw}'`);
1434
+ }
1435
+ if (segments.length > MAX_SEGMENTS) {
1436
+ throw new CustodyPathError(`custody path too deep (max ${String(MAX_SEGMENTS)} segments)`);
1437
+ }
1438
+ for (const seg of segments) {
1439
+ if (seg === "." || seg === ".." || !SEGMENT_RE.test(seg)) {
1440
+ throw new CustodyPathError(`illegal custody path segment: '${seg}'`);
1441
+ }
1442
+ }
1443
+ const scope = segments[0];
1444
+ if (!CUSTODY_SCOPES.includes(scope)) {
1445
+ throw new CustodyPathError(
1446
+ `unknown custody scope '${scope}' (expected ${CUSTODY_SCOPES.join(" | ")})`
1447
+ );
1448
+ }
1449
+ if (scope === "agents" && !AGENT_IDS.includes(segments[1])) {
1450
+ throw new CustodyPathError(
1451
+ `unknown agent '${segments[1]}' (expected ${AGENT_IDS.join(" | ")})`
1452
+ );
1453
+ }
1454
+ return segments.join("/");
1455
+ }
1456
+ function normalizeCustodyPrefix(raw) {
1457
+ const trimmed = raw.replace(/^\/+/, "").replace(/\/+$/, "");
1458
+ if (trimmed.length === 0) return "";
1459
+ if (trimmed.length > MAX_PATH_LENGTH) {
1460
+ throw new CustodyPathError(`custody prefix too long (max ${String(MAX_PATH_LENGTH)} chars)`);
1461
+ }
1462
+ const segments = trimmed.split("/");
1463
+ if (segments.length > MAX_SEGMENTS) {
1464
+ throw new CustodyPathError(`custody prefix too deep (max ${String(MAX_SEGMENTS)} segments)`);
1465
+ }
1466
+ for (const seg of segments) {
1467
+ if (seg === "." || seg === ".." || !SEGMENT_RE.test(seg)) {
1468
+ throw new CustodyPathError(`illegal custody prefix segment: '${seg}'`);
1469
+ }
1470
+ }
1471
+ if (!CUSTODY_SCOPES.includes(segments[0])) {
1472
+ throw new CustodyPathError(
1473
+ `unknown custody scope '${segments[0]}' (expected ${CUSTODY_SCOPES.join(" | ")})`
1474
+ );
1475
+ }
1476
+ return segments.join("/");
1477
+ }
1478
+ var CUSTODY_PATH_PREFIX = "/admin/custody";
1479
+ function isCustodyPath(path) {
1480
+ return path === CUSTODY_PATH_PREFIX || path.startsWith(`${CUSTODY_PATH_PREFIX}/`);
1481
+ }
1482
+ function timingSafeEqualStr2(a, b) {
1483
+ const ab = Buffer.from(a, "utf8");
1484
+ const bb = Buffer.from(b, "utf8");
1485
+ if (ab.length !== bb.length) return false;
1486
+ return timingSafeEqual2(ab, bb);
1487
+ }
1488
+ async function handleCustodyRequest(req, deps) {
1489
+ if (!isCustodyPath(req.path)) return null;
1490
+ const log = deps.log ?? (() => {
1491
+ });
1492
+ const adminToken = deps.adminToken ?? "";
1493
+ if (adminToken.length === 0) {
1494
+ return { status: 503, body: { error: "custody not configured: admin token unset" } };
1495
+ }
1496
+ if (!timingSafeEqualStr2(req.bearer, adminToken)) {
1497
+ return { status: 401, body: { error: "invalid admin token" } };
1498
+ }
1499
+ const store = deps.custody;
1500
+ if (!store) {
1501
+ return { status: 503, body: { error: "custody store not enabled on this relay" } };
1502
+ }
1503
+ try {
1504
+ if (req.path === CUSTODY_PATH_PREFIX) {
1505
+ if (req.method !== "GET") return { status: 405, body: { error: "method not allowed" } };
1506
+ const rawPrefix = req.query.get("prefix");
1507
+ const prefix = rawPrefix ? normalizeCustodyPrefix(rawPrefix) : void 0;
1508
+ const entries = await store.list(prefix);
1509
+ return { status: 200, body: { entries } };
1510
+ }
1511
+ const path = normalizeCustodyPath(
1512
+ decodeURIComponent(req.path.slice(`${CUSTODY_PATH_PREFIX}/`.length))
1513
+ );
1514
+ if (req.method === "PUT") {
1515
+ let parsed;
1516
+ try {
1517
+ parsed = JSON.parse(req.bodyText.length === 0 ? "{}" : req.bodyText);
1518
+ } catch {
1519
+ return { status: 400, body: { error: "expected JSON {data: <base64>}" } };
1520
+ }
1521
+ if (typeof parsed.data !== "string") {
1522
+ return { status: 400, body: { error: "expected {data: <base64>}" } };
1523
+ }
1524
+ const buf = Buffer.from(parsed.data, "base64");
1525
+ if (buf.toString("base64") !== parsed.data.replace(/\s+/g, "")) {
1526
+ return { status: 400, body: { error: "data is not valid base64" } };
1527
+ }
1528
+ const result = await store.put(path, buf);
1529
+ log(
1530
+ `custody put ${path} (${String(result.size)} bytes, ${result.changed ? "changed" : "unchanged"})`
1531
+ );
1532
+ return { status: 200, body: result };
1533
+ }
1534
+ if (req.method === "GET") {
1535
+ const found = await store.get(path);
1536
+ if (!found) return { status: 404, body: { error: "no such custody entry" } };
1537
+ log(`custody get ${path} (${String(found.entry.size)} bytes)`);
1538
+ return { status: 200, body: { ...found.entry, data: found.data.toString("base64") } };
1539
+ }
1540
+ if (req.method === "DELETE") {
1541
+ const hit = await store.delete(path);
1542
+ if (!hit) return { status: 404, body: { error: "no such custody entry" } };
1543
+ log(`custody delete ${path}`);
1544
+ return { status: 204 };
1545
+ }
1546
+ return { status: 405, body: { error: "method not allowed" } };
1547
+ } catch (err) {
1548
+ if (err instanceof CustodyPathError) return { status: 400, body: { error: err.message } };
1549
+ const msg = err instanceof Error ? err.message : String(err);
1550
+ log(`custody error: ${msg}`);
1551
+ return { status: 500, body: { error: `custody: ${msg}` } };
1552
+ }
1553
+ }
1554
+ var REMOTE_BOXES_PREFIX = "/remote/boxes";
1555
+ function isRemoteBoxesPath(path) {
1556
+ return path === REMOTE_BOXES_PREFIX || path.startsWith(`${REMOTE_BOXES_PREFIX}/`);
1557
+ }
1558
+ function timingSafeEqualStr3(a, b) {
1559
+ const ab = Buffer.from(a, "utf8");
1560
+ const bb = Buffer.from(b, "utf8");
1561
+ if (ab.length !== bb.length) return false;
1562
+ return timingSafeEqual3(ab, bb);
1563
+ }
1564
+ function parseJson2(text3) {
1565
+ if (text3.length === 0) return {};
1566
+ try {
1567
+ return JSON.parse(text3);
1568
+ } catch {
1569
+ return null;
1570
+ }
1571
+ }
1572
+ async function handleRemoteBoxesRequest(req, deps) {
1573
+ if (!isRemoteBoxesPath(req.path)) return null;
1574
+ const log = deps.log ?? (() => {
1575
+ });
1576
+ const { store } = deps;
1577
+ const adminToken = deps.adminToken ?? "";
1578
+ if (adminToken.length === 0) {
1579
+ return { status: 503, body: { error: "control plane not configured: admin token unset" } };
1580
+ }
1581
+ if (!timingSafeEqualStr3(req.bearer, adminToken)) {
1582
+ return { status: 401, body: { error: "invalid admin token" } };
1583
+ }
1584
+ if (req.method === "POST" && req.path === REMOTE_BOXES_PREFIX) {
1585
+ if (!store.enqueueCreateJob) {
1586
+ return { status: 501, body: { error: "create-job queue not available on this store" } };
1587
+ }
1588
+ const body = parseJson2(req.bodyText);
1589
+ if (!body || typeof body.repoUrl !== "string" || typeof body.provider !== "string") {
1590
+ return { status: 400, body: { error: "expected {repoUrl, provider, branch?, name?, agent?, prompt?}" } };
1591
+ }
1592
+ const allowed = deps.createProviders;
1593
+ if (allowed && allowed.length > 0 && !allowed.includes(body.provider)) {
1594
+ return {
1595
+ status: 400,
1596
+ body: {
1597
+ error: `provider '${body.provider}' is not supported by this control plane (allowed: ${allowed.join(", ")})`
1598
+ }
1599
+ };
1600
+ }
1601
+ const id = randomUUID3();
1602
+ await store.enqueueCreateJob({
1603
+ id,
1604
+ status: "queued",
1605
+ request: {
1606
+ repoUrl: body.repoUrl,
1607
+ provider: body.provider,
1608
+ branch: body.branch,
1609
+ name: body.name,
1610
+ agent: body.agent,
1611
+ prompt: body.prompt
1612
+ },
1613
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1614
+ });
1615
+ log(`enqueued create job ${id} (${body.provider} ${body.repoUrl})`);
1616
+ return { status: 202, body: { jobId: id } };
1617
+ }
1618
+ if (req.method === "GET" && req.path === REMOTE_BOXES_PREFIX) {
1619
+ if (!store.listCreateJobs) {
1620
+ return { status: 501, body: { error: "create-job queue not available on this store" } };
1621
+ }
1622
+ const jobs = await store.listCreateJobs({ limit: 100 });
1623
+ return { status: 200, body: { jobs } };
1624
+ }
1625
+ if (req.method === "GET" && req.path.startsWith(`${REMOTE_BOXES_PREFIX}/`)) {
1626
+ if (!store.getCreateJob) {
1627
+ return { status: 501, body: { error: "create-job queue not available on this store" } };
1628
+ }
1629
+ const id = decodeURIComponent(req.path.slice(`${REMOTE_BOXES_PREFIX}/`.length));
1630
+ const job = await store.getCreateJob(id);
1631
+ return job ? { status: 200, body: job } : { status: 404, body: { error: "no such job" } };
1632
+ }
1633
+ if (req.method === "DELETE" && req.path.startsWith(`${REMOTE_BOXES_PREFIX}/`)) {
1634
+ const boxId = decodeURIComponent(req.path.slice(`${REMOTE_BOXES_PREFIX}/`.length));
1635
+ if (boxId.length === 0) return { status: 404, body: { error: "no such box" } };
1636
+ const reg = await store.getBox(boxId);
1637
+ const existed = await store.forgetBox(boxId);
1638
+ await store.deleteStatus(boxId);
1639
+ let custodyRemoved = 0;
1640
+ if (deps.custody) {
1641
+ const key = reg?.sandboxId ?? boxId;
1642
+ const entries = await deps.custody.list(`boxes/${key}`).catch(() => []);
1643
+ for (const e of entries) {
1644
+ if (await deps.custody.delete(e.path).catch(() => false)) custodyRemoved += 1;
1645
+ }
1646
+ }
1647
+ if (!existed && !reg && custodyRemoved === 0) {
1648
+ return { status: 404, body: { error: "no such box" } };
1649
+ }
1650
+ log(`reaped box ${boxId} (registration=${String(existed)}, custody=${String(custodyRemoved)})`);
1651
+ return { status: 200, body: { boxId, removed: existed, custodyRemoved } };
1652
+ }
1653
+ return { status: 405, body: { error: "method not allowed" } };
1654
+ }
1655
+ var WriteThroughStore = class {
1656
+ inner;
1657
+ registry;
1658
+ events;
1659
+ statusStore;
1660
+ constructor(inner, parts) {
1661
+ this.inner = inner;
1662
+ this.registry = parts.registry;
1663
+ this.events = parts.events;
1664
+ this.statusStore = parts.statusStore;
1665
+ }
1666
+ /**
1667
+ * Load the durable store's boxes + statuses into the in-memory instances, once
1668
+ * at boot, so the loops start against a populated registry after a restart.
1669
+ * Events are a ring buffer (ephemeral) and are not hydrated.
1670
+ */
1671
+ async hydrate() {
1672
+ for (const reg of await this.inner.listBoxes()) this.registry.register(reg);
1673
+ for (const { boxId, status } of await this.inner.listStatuses()) {
1674
+ const reg = this.registry.get(boxId);
1675
+ await this.statusStore.set(boxId, reg?.name ?? boxId, reg?.projectIndex, status);
1676
+ }
1677
+ }
1678
+ migrate() {
1679
+ return this.inner.migrate?.() ?? Promise.resolve();
1680
+ }
1681
+ // --- boxes ---
1682
+ async registerBox(reg) {
1683
+ await this.inner.registerBox(reg);
1684
+ this.registry.register(reg);
1685
+ }
1686
+ getBox(boxId) {
1687
+ return this.inner.getBox(boxId);
1688
+ }
1689
+ authenticateBox(token) {
1690
+ return this.inner.authenticateBox(token);
1691
+ }
1692
+ listBoxes() {
1693
+ return this.inner.listBoxes();
1694
+ }
1695
+ async forgetBox(boxId) {
1696
+ const existed = await this.inner.forgetBox(boxId);
1697
+ this.registry.forget(boxId);
1698
+ return existed;
1699
+ }
1700
+ countBoxes() {
1701
+ return this.inner.countBoxes();
1702
+ }
1703
+ // --- events ---
1704
+ async appendEvent(input) {
1705
+ const ev = await this.inner.appendEvent(input);
1706
+ this.events.append(input);
1707
+ return ev;
1708
+ }
1709
+ listEvents(since, boxId) {
1710
+ return this.inner.listEvents(since, boxId);
1711
+ }
1712
+ countEvents() {
1713
+ return this.inner.countEvents();
1714
+ }
1715
+ // --- status ---
1716
+ async setStatus(boxId, name, projectIndex, status) {
1717
+ await this.inner.setStatus(boxId, name, projectIndex, status);
1718
+ await this.statusStore.set(boxId, name, projectIndex, status);
1719
+ }
1720
+ getStatus(boxId) {
1721
+ return this.inner.getStatus(boxId);
1722
+ }
1723
+ async deleteStatus(boxId) {
1724
+ await this.inner.deleteStatus(boxId);
1725
+ this.statusStore.delete(boxId);
1726
+ }
1727
+ listStatuses() {
1728
+ return this.inner.listStatuses();
1729
+ }
1730
+ // --- prompt mailbox (pure delegation; no in-memory mirror the loops read) ---
1731
+ createPrompt(row) {
1732
+ return this.inner.createPrompt(row);
1733
+ }
1734
+ getPrompt(promptId) {
1735
+ return this.inner.getPrompt(promptId);
1736
+ }
1737
+ answerPrompt(promptId, answer, cancelled) {
1738
+ return this.inner.answerPrompt(promptId, answer, cancelled);
1739
+ }
1740
+ listPendingPrompts(boxId) {
1741
+ return this.inner.listPendingPrompts(boxId);
1742
+ }
1743
+ setPromptResult(promptId, result) {
1744
+ return this.inner.setPromptResult(promptId, result);
1745
+ }
1746
+ // --- box-create job queue (pure delegation) ---
1747
+ enqueueCreateJob(job) {
1748
+ if (!this.inner.enqueueCreateJob) return Promise.resolve();
1749
+ return this.inner.enqueueCreateJob(job);
1750
+ }
1751
+ getCreateJob(id) {
1752
+ return this.inner.getCreateJob?.(id) ?? Promise.resolve(null);
1753
+ }
1754
+ listCreateJobs(opts) {
1755
+ return this.inner.listCreateJobs?.(opts) ?? Promise.resolve([]);
1756
+ }
1757
+ claimNextCreateJob(workerId) {
1758
+ return this.inner.claimNextCreateJob?.(workerId) ?? Promise.resolve(null);
1759
+ }
1760
+ completeCreateJob(id, status, result) {
1761
+ if (!this.inner.completeCreateJob) return Promise.resolve();
1762
+ return this.inner.completeCreateJob(id, status, result);
1763
+ }
1764
+ // --- retention (forwarded; blocker B) ---
1765
+ prunePrompts(beforeIso) {
1766
+ return this.inner.prunePrompts?.(beforeIso) ?? Promise.resolve(0);
1767
+ }
1768
+ pruneCreateJobs(beforeIso) {
1769
+ return this.inner.pruneCreateJobs?.(beforeIso) ?? Promise.resolve(0);
1770
+ }
1771
+ };
1247
1772
  function loadGitHubAppConfig() {
1248
1773
  const appId = process.env.GITHUB_APP_ID;
1249
1774
  let key = process.env.GITHUB_APP_PRIVATE_KEY;
@@ -1355,15 +1880,999 @@ var GitHubAppLeaser = class {
1355
1880
  }
1356
1881
  };
1357
1882
 
1358
- // ../../packages/relay/dist/chunk-GEIE6TWJ.js
1883
+ // ../../packages/relay/dist/chunk-ATOI6ZPE.js
1884
+ import { mkdirSync } from "fs";
1885
+ import { createRequire } from "module";
1886
+ import { dirname, join as join2 } from "path";
1887
+ import { chmod, mkdir as mkdir2, readFile, readdir, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "fs/promises";
1888
+ import { dirname as dirname2, join as join22, relative, sep } from "path";
1889
+ import { randomBytes } from "crypto";
1890
+ function lfsEndpointFor(cloneUrl) {
1891
+ return `${cloneUrl.replace(/\.git$/, "")}.git/info/lfs`;
1892
+ }
1893
+ async function cloneRepoWithLfs(runGit, authedUrl, repoUrl, dest, branch, log = () => {
1894
+ }) {
1895
+ await runGit(branch ? ["clone", "--branch", branch, authedUrl, dest] : ["clone", authedUrl, dest], {
1896
+ GIT_LFS_SKIP_SMUDGE: "1"
1897
+ });
1898
+ try {
1899
+ await runGit(
1900
+ ["-C", dest, "-c", `lfs.url=${lfsEndpointFor(authedUrl)}`, "lfs", "pull"],
1901
+ { GIT_TERMINAL_PROMPT: "0", GIT_SSH_COMMAND: "ssh -o BatchMode=yes -o StrictHostKeyChecking=no" },
1902
+ 12e4
1903
+ );
1904
+ } catch (err2) {
1905
+ log(`git-lfs objects left as pointers (fetch failed): ${err2 instanceof Error ? err2.message : String(err2)}`);
1906
+ }
1907
+ await runGit(["-C", dest, "remote", "set-url", "origin", repoUrl]);
1908
+ }
1909
+ function makeControlPlaneCreateBox(deps) {
1910
+ return async (request, jobId) => {
1911
+ const log = deps.log ?? (() => {
1912
+ });
1913
+ const dir = deps.tmpDir(jobId);
1914
+ try {
1915
+ log(`leasing a push token for ${request.repoUrl}`);
1916
+ const authedUrl = await deps.leaseRemoteUrl(request.repoUrl);
1917
+ log(`cloning ${request.repoUrl}${request.branch ? `@${request.branch}` : ""} into ${dir}`);
1918
+ await deps.cloneRepo(authedUrl, request.repoUrl, dir, request.branch);
1919
+ if (deps.fetchSeedMaterial) {
1920
+ try {
1921
+ const seed = await deps.fetchSeedMaterial(request.repoUrl, dir);
1922
+ if (seed && seed.files > 0) {
1923
+ const from = [
1924
+ seed.repoHeadSha ? `at ${seed.repoHeadSha.slice(0, 8)}` : null,
1925
+ seed.capturedAt ? `captured ${seed.capturedAt}` : null
1926
+ ].filter(Boolean).join(", ");
1927
+ log(`applied ${String(seed.files)} seed file(s) from custody${from ? ` (${from})` : ""}`);
1928
+ }
1929
+ } catch (err2) {
1930
+ log(
1931
+ `seed material unavailable (continuing with a bare clone): ${err2 instanceof Error ? err2.message : String(err2)}`
1932
+ );
1933
+ }
1934
+ }
1935
+ log(`provisioning ${request.provider} box from the clone`);
1936
+ const box = await deps.createBox({
1937
+ workspacePath: dir,
1938
+ name: request.name,
1939
+ provider: request.provider,
1940
+ // Carry the job's agent through to the box record + its plane
1941
+ // registration, so an adopting PC relaunches the right agent instead of
1942
+ // guessing. Without this a hub-created box adopts with no `lastAgent`.
1943
+ agent: request.agent,
1944
+ // A background `-i` run seeds a prompt: the worker starts the agent
1945
+ // in-box with these. Absent ⇒ a "cold" create (create --via-hub /
1946
+ // foreground) that the PC attaches later.
1947
+ prompt: request.prompt,
1948
+ agentArgs: request.agentArgs,
1949
+ onLog: deps.log
1950
+ });
1951
+ log(`created box ${box.id}`);
1952
+ return { boxId: box.id, agentStartError: box.agentStartError };
1953
+ } finally {
1954
+ await deps.cleanup(dir);
1955
+ }
1956
+ };
1957
+ }
1958
+ async function drainOneCreateJob(store, createBox2, workerId) {
1959
+ if (!store.claimNextCreateJob || !store.completeCreateJob) return null;
1960
+ const job = await store.claimNextCreateJob(workerId);
1961
+ if (!job) return null;
1962
+ try {
1963
+ const { boxId, agentStartError } = await createBox2(job.request, job.id);
1964
+ if (agentStartError) {
1965
+ await store.completeCreateJob(job.id, "failed", { boxId, error: agentStartError });
1966
+ } else {
1967
+ await store.completeCreateJob(job.id, "done", { boxId });
1968
+ }
1969
+ } catch (err2) {
1970
+ await store.completeCreateJob(job.id, "failed", {
1971
+ error: err2 instanceof Error ? err2.message : String(err2)
1972
+ });
1973
+ }
1974
+ return job.id;
1975
+ }
1976
+ async function drainCreateJobs(store, createBox2, workerId, max = 10) {
1977
+ let processed = 0;
1978
+ while (processed < max) {
1979
+ const id = await drainOneCreateJob(store, createBox2, workerId);
1980
+ if (!id) break;
1981
+ processed++;
1982
+ }
1983
+ return processed;
1984
+ }
1985
+ var pgBoxes = pgTable("boxes", {
1986
+ boxId: text("box_id").primaryKey(),
1987
+ token: text("token").notNull(),
1988
+ originUrl: text("origin_url"),
1989
+ data: jsonb("data").$type().notNull(),
1990
+ registeredAt: timestamp("registered_at", { withTimezone: true }).notNull()
1991
+ });
1992
+ var pgEvents = pgTable("events", {
1993
+ id: bigint("id", { mode: "number" }).generatedAlwaysAsIdentity().primaryKey(),
1994
+ boxId: text("box_id").notNull(),
1995
+ type: text("type").notNull(),
1996
+ ts: text("ts"),
1997
+ payload: jsonb("payload"),
1998
+ receivedAt: timestamp("received_at", { withTimezone: true }).notNull()
1999
+ });
2000
+ var pgBoxStatus = pgTable("box_status", {
2001
+ boxId: text("box_id").primaryKey(),
2002
+ name: text("name"),
2003
+ projectIndex: integer("project_index"),
2004
+ status: jsonb("status").$type().notNull(),
2005
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull()
2006
+ });
2007
+ var pgPrompts = pgTable("prompts", {
2008
+ id: text("id").primaryKey(),
2009
+ boxId: text("box_id").notNull(),
2010
+ ev: jsonb("ev").$type().notNull(),
2011
+ method: text("method").notNull(),
2012
+ params: jsonb("params"),
2013
+ status: text("status").$type().notNull(),
2014
+ answer: text("answer").$type(),
2015
+ cancelled: boolean("cancelled"),
2016
+ result: jsonb("result").$type(),
2017
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
2018
+ expiresAt: timestamp("expires_at", { withTimezone: true })
2019
+ });
2020
+ var pgCreateJobs = pgTable("create_jobs", {
2021
+ id: text("id").primaryKey(),
2022
+ status: text("status").$type().notNull(),
2023
+ request: jsonb("request").$type().notNull(),
2024
+ result: jsonb("result").$type(),
2025
+ claimedBy: text("claimed_by"),
2026
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
2027
+ startedAt: timestamp("started_at", { withTimezone: true }),
2028
+ finishedAt: timestamp("finished_at", { withTimezone: true })
2029
+ });
2030
+ var PG_SCHEMA_SQL = `
2031
+ CREATE TABLE IF NOT EXISTS boxes (
2032
+ box_id text PRIMARY KEY,
2033
+ token text NOT NULL,
2034
+ origin_url text,
2035
+ data jsonb NOT NULL,
2036
+ registered_at timestamptz NOT NULL DEFAULT now()
2037
+ );
2038
+ CREATE INDEX IF NOT EXISTS boxes_token_idx ON boxes (token);
2039
+
2040
+ CREATE TABLE IF NOT EXISTS events (
2041
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
2042
+ box_id text NOT NULL,
2043
+ type text NOT NULL,
2044
+ ts text,
2045
+ payload jsonb,
2046
+ received_at timestamptz NOT NULL DEFAULT now()
2047
+ );
2048
+ CREATE INDEX IF NOT EXISTS events_box_idx ON events (box_id, id);
2049
+
2050
+ CREATE TABLE IF NOT EXISTS box_status (
2051
+ box_id text PRIMARY KEY,
2052
+ name text,
2053
+ project_index int,
2054
+ status jsonb NOT NULL,
2055
+ updated_at timestamptz NOT NULL DEFAULT now()
2056
+ );
2057
+
2058
+ CREATE TABLE IF NOT EXISTS prompts (
2059
+ id text PRIMARY KEY,
2060
+ box_id text NOT NULL,
2061
+ ev jsonb NOT NULL,
2062
+ method text NOT NULL,
2063
+ params jsonb,
2064
+ status text NOT NULL DEFAULT 'pending',
2065
+ answer text,
2066
+ cancelled boolean,
2067
+ result jsonb,
2068
+ created_at timestamptz NOT NULL DEFAULT now(),
2069
+ expires_at timestamptz
2070
+ );
2071
+ CREATE INDEX IF NOT EXISTS prompts_box_pending_idx ON prompts (box_id) WHERE status = 'pending';
2072
+
2073
+ CREATE TABLE IF NOT EXISTS create_jobs (
2074
+ id text PRIMARY KEY,
2075
+ status text NOT NULL DEFAULT 'queued',
2076
+ request jsonb NOT NULL,
2077
+ result jsonb,
2078
+ claimed_by text,
2079
+ created_at timestamptz NOT NULL DEFAULT now(),
2080
+ started_at timestamptz,
2081
+ finished_at timestamptz
2082
+ );
2083
+ CREATE INDEX IF NOT EXISTS create_jobs_queued_idx ON create_jobs (created_at) WHERE status = 'queued';
2084
+ `;
2085
+ var sqliteBoxes = sqliteTable(
2086
+ "boxes",
2087
+ {
2088
+ boxId: text2("box_id").primaryKey(),
2089
+ token: text2("token").notNull(),
2090
+ originUrl: text2("origin_url"),
2091
+ data: text2("data", { mode: "json" }).$type().notNull(),
2092
+ registeredAt: text2("registered_at").notNull()
2093
+ },
2094
+ (t) => [index("boxes_token_idx").on(t.token)]
2095
+ );
2096
+ var sqliteEvents = sqliteTable(
2097
+ "events",
2098
+ {
2099
+ id: integer2("id").primaryKey({ autoIncrement: true }),
2100
+ boxId: text2("box_id").notNull(),
2101
+ type: text2("type").notNull(),
2102
+ ts: text2("ts"),
2103
+ payload: text2("payload", { mode: "json" }),
2104
+ receivedAt: text2("received_at").notNull()
2105
+ },
2106
+ (t) => [index("events_box_idx").on(t.boxId, t.id)]
2107
+ );
2108
+ var sqliteBoxStatus = sqliteTable("box_status", {
2109
+ boxId: text2("box_id").primaryKey(),
2110
+ name: text2("name"),
2111
+ projectIndex: integer2("project_index"),
2112
+ status: text2("status", { mode: "json" }).$type().notNull(),
2113
+ updatedAt: text2("updated_at").notNull()
2114
+ });
2115
+ var sqlitePrompts = sqliteTable(
2116
+ "prompts",
2117
+ {
2118
+ id: text2("id").primaryKey(),
2119
+ boxId: text2("box_id").notNull(),
2120
+ ev: text2("ev", { mode: "json" }).$type().notNull(),
2121
+ method: text2("method").notNull(),
2122
+ params: text2("params", { mode: "json" }),
2123
+ status: text2("status").$type().notNull(),
2124
+ answer: text2("answer").$type(),
2125
+ cancelled: integer2("cancelled", { mode: "boolean" }),
2126
+ result: text2("result", { mode: "json" }).$type(),
2127
+ createdAt: text2("created_at").notNull(),
2128
+ expiresAt: text2("expires_at")
2129
+ },
2130
+ (t) => [index("prompts_box_status_idx").on(t.boxId, t.status)]
2131
+ );
2132
+ var sqliteCreateJobs = sqliteTable(
2133
+ "create_jobs",
2134
+ {
2135
+ id: text2("id").primaryKey(),
2136
+ status: text2("status").$type().notNull(),
2137
+ request: text2("request", { mode: "json" }).$type().notNull(),
2138
+ result: text2("result", { mode: "json" }).$type(),
2139
+ claimedBy: text2("claimed_by"),
2140
+ createdAt: text2("created_at").notNull(),
2141
+ startedAt: text2("started_at"),
2142
+ finishedAt: text2("finished_at")
2143
+ },
2144
+ (t) => [index("create_jobs_status_idx").on(t.status, t.createdAt)]
2145
+ );
2146
+ var SQLITE_SCHEMA_SQL = `
2147
+ CREATE TABLE IF NOT EXISTS boxes (
2148
+ box_id text PRIMARY KEY,
2149
+ token text NOT NULL,
2150
+ origin_url text,
2151
+ data text NOT NULL,
2152
+ registered_at text NOT NULL
2153
+ );
2154
+ CREATE INDEX IF NOT EXISTS boxes_token_idx ON boxes (token);
2155
+
2156
+ CREATE TABLE IF NOT EXISTS events (
2157
+ id integer PRIMARY KEY AUTOINCREMENT,
2158
+ box_id text NOT NULL,
2159
+ type text NOT NULL,
2160
+ ts text,
2161
+ payload text,
2162
+ received_at text NOT NULL
2163
+ );
2164
+ CREATE INDEX IF NOT EXISTS events_box_idx ON events (box_id, id);
2165
+
2166
+ CREATE TABLE IF NOT EXISTS box_status (
2167
+ box_id text PRIMARY KEY,
2168
+ name text,
2169
+ project_index integer,
2170
+ status text NOT NULL,
2171
+ updated_at text NOT NULL
2172
+ );
2173
+
2174
+ CREATE TABLE IF NOT EXISTS prompts (
2175
+ id text PRIMARY KEY,
2176
+ box_id text NOT NULL,
2177
+ ev text NOT NULL,
2178
+ method text NOT NULL,
2179
+ params text,
2180
+ status text NOT NULL DEFAULT 'pending',
2181
+ answer text,
2182
+ cancelled integer,
2183
+ result text,
2184
+ created_at text NOT NULL,
2185
+ expires_at text
2186
+ );
2187
+ CREATE INDEX IF NOT EXISTS prompts_box_status_idx ON prompts (box_id, status);
2188
+
2189
+ CREATE TABLE IF NOT EXISTS create_jobs (
2190
+ id text PRIMARY KEY,
2191
+ status text NOT NULL DEFAULT 'queued',
2192
+ request text NOT NULL,
2193
+ result text,
2194
+ claimed_by text,
2195
+ created_at text NOT NULL,
2196
+ started_at text,
2197
+ finished_at text
2198
+ );
2199
+ CREATE INDEX IF NOT EXISTS create_jobs_status_idx ON create_jobs (status, created_at);
2200
+ `;
2201
+ function toIso(value) {
2202
+ return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
2203
+ }
2204
+ function toIsoOrUndefined(value) {
2205
+ return value === null ? void 0 : toIso(value);
2206
+ }
2207
+ function rowToEvent(r) {
2208
+ return {
2209
+ id: Number(r.id),
2210
+ boxId: r.boxId,
2211
+ type: r.type,
2212
+ ts: r.ts ?? void 0,
2213
+ payload: r.payload ?? void 0,
2214
+ receivedAt: toIso(r.receivedAt)
2215
+ };
2216
+ }
2217
+ function rowToPrompt(r) {
2218
+ return {
2219
+ id: r.id,
2220
+ boxId: r.boxId,
2221
+ ev: r.ev,
2222
+ method: r.method,
2223
+ params: r.params ?? void 0,
2224
+ status: r.status,
2225
+ answer: r.answer ?? void 0,
2226
+ cancelled: r.cancelled ?? void 0,
2227
+ result: r.result ?? void 0,
2228
+ createdAt: toIso(r.createdAt),
2229
+ expiresAt: toIsoOrUndefined(r.expiresAt)
2230
+ };
2231
+ }
2232
+ function rowToJob(r) {
2233
+ return {
2234
+ id: r.id,
2235
+ status: r.status,
2236
+ request: r.request,
2237
+ result: r.result ?? void 0,
2238
+ claimedBy: r.claimedBy ?? void 0,
2239
+ createdAt: toIso(r.createdAt),
2240
+ startedAt: toIsoOrUndefined(r.startedAt),
2241
+ finishedAt: toIsoOrUndefined(r.finishedAt)
2242
+ };
2243
+ }
2244
+ var DEFAULT_EVENT_CAP = RELAY_EVENT_RING_SIZE;
2245
+ var PostgresStore = class {
2246
+ eventCap;
2247
+ connectionString;
2248
+ injectedPool;
2249
+ poolPromise = null;
2250
+ dbPromise = null;
2251
+ constructor(opts = {}) {
2252
+ this.connectionString = opts.connectionString;
2253
+ this.injectedPool = opts.pool;
2254
+ this.eventCap = opts.eventCap ?? DEFAULT_EVENT_CAP;
2255
+ }
2256
+ /** Lazily build (or reuse) the pg Pool. `pg` is imported on first use only. */
2257
+ pool() {
2258
+ if (this.injectedPool) return Promise.resolve(this.injectedPool);
2259
+ this.poolPromise ??= import("pg").then(
2260
+ ({ default: pg2 }) => new pg2.Pool({ connectionString: this.connectionString })
2261
+ );
2262
+ return this.poolPromise;
2263
+ }
2264
+ db() {
2265
+ this.dbPromise ??= (async () => {
2266
+ const pool = await this.pool();
2267
+ const { drizzle } = await import("./node-postgres-DIU2H5VP.js");
2268
+ return drizzle(pool);
2269
+ })();
2270
+ return this.dbPromise;
2271
+ }
2272
+ /** Create the tables if absent. Call once on boot (idempotent). */
2273
+ async migrate() {
2274
+ const pool = await this.pool();
2275
+ await pool.query(PG_SCHEMA_SQL);
2276
+ }
2277
+ /** Release the pool (tests / graceful shutdown). No-op for an injected pool. */
2278
+ async close() {
2279
+ if (this.injectedPool) return;
2280
+ if (this.poolPromise) {
2281
+ const pool = await this.poolPromise;
2282
+ await pool.end();
2283
+ this.poolPromise = null;
2284
+ this.dbPromise = null;
2285
+ }
2286
+ }
2287
+ // --- boxes ---
2288
+ async registerBox(reg) {
2289
+ const db = await this.db();
2290
+ await db.insert(pgBoxes).values({
2291
+ boxId: reg.boxId,
2292
+ token: reg.token,
2293
+ originUrl: reg.originUrl ?? null,
2294
+ data: reg,
2295
+ registeredAt: new Date(reg.registeredAt)
2296
+ }).onConflictDoUpdate({
2297
+ target: pgBoxes.boxId,
2298
+ set: { token: reg.token, originUrl: reg.originUrl ?? null, data: reg }
2299
+ });
2300
+ }
2301
+ async getBox(boxId) {
2302
+ const db = await this.db();
2303
+ const rows = await db.select({ data: pgBoxes.data }).from(pgBoxes).where(eq(pgBoxes.boxId, boxId));
2304
+ return rows[0]?.data;
2305
+ }
2306
+ async authenticateBox(token) {
2307
+ if (token.length === 0) return null;
2308
+ const db = await this.db();
2309
+ const rows = await db.select({ data: pgBoxes.data }).from(pgBoxes).where(eq(pgBoxes.token, token)).limit(1);
2310
+ return rows[0]?.data ?? null;
2311
+ }
2312
+ async listBoxes() {
2313
+ const db = await this.db();
2314
+ const rows = await db.select({ data: pgBoxes.data }).from(pgBoxes).orderBy(asc(pgBoxes.registeredAt));
2315
+ return rows.map((r) => r.data);
2316
+ }
2317
+ async forgetBox(boxId) {
2318
+ const db = await this.db();
2319
+ const rows = await db.delete(pgBoxes).where(eq(pgBoxes.boxId, boxId)).returning({ boxId: pgBoxes.boxId });
2320
+ return rows.length > 0;
2321
+ }
2322
+ async countBoxes() {
2323
+ const db = await this.db();
2324
+ return db.$count(pgBoxes);
2325
+ }
2326
+ // --- events ---
2327
+ async appendEvent(input) {
2328
+ const db = await this.db();
2329
+ const rows = await db.insert(pgEvents).values({
2330
+ boxId: input.boxId,
2331
+ type: input.type,
2332
+ ts: input.ts ?? null,
2333
+ payload: input.payload ?? null,
2334
+ receivedAt: /* @__PURE__ */ new Date()
2335
+ }).returning({ id: pgEvents.id, receivedAt: pgEvents.receivedAt });
2336
+ const row = rows[0];
2337
+ if (this.eventCap > 0) {
2338
+ await db.delete(pgEvents).where(lte(pgEvents.id, row.id - this.eventCap));
2339
+ }
2340
+ return {
2341
+ id: row.id,
2342
+ boxId: input.boxId,
2343
+ type: input.type,
2344
+ ts: input.ts,
2345
+ payload: input.payload,
2346
+ receivedAt: row.receivedAt.toISOString()
2347
+ };
2348
+ }
2349
+ async listEvents(since, boxId) {
2350
+ const db = await this.db();
2351
+ const where = boxId === void 0 ? gt(pgEvents.id, since) : and(gt(pgEvents.id, since), eq(pgEvents.boxId, boxId));
2352
+ const rows = await db.select().from(pgEvents).where(where).orderBy(asc(pgEvents.id));
2353
+ return rows.map(rowToEvent);
2354
+ }
2355
+ async countEvents() {
2356
+ const db = await this.db();
2357
+ return db.$count(pgEvents);
2358
+ }
2359
+ // --- status ---
2360
+ async setStatus(boxId, name, projectIndex, status) {
2361
+ const db = await this.db();
2362
+ const updatedAt = /* @__PURE__ */ new Date();
2363
+ await db.insert(pgBoxStatus).values({ boxId, name, projectIndex: projectIndex ?? null, status, updatedAt }).onConflictDoUpdate({
2364
+ target: pgBoxStatus.boxId,
2365
+ set: { name, projectIndex: projectIndex ?? null, status, updatedAt }
2366
+ });
2367
+ }
2368
+ async getStatus(boxId) {
2369
+ const db = await this.db();
2370
+ const rows = await db.select({ status: pgBoxStatus.status }).from(pgBoxStatus).where(eq(pgBoxStatus.boxId, boxId));
2371
+ return rows[0]?.status;
2372
+ }
2373
+ async deleteStatus(boxId) {
2374
+ const db = await this.db();
2375
+ await db.delete(pgBoxStatus).where(eq(pgBoxStatus.boxId, boxId));
2376
+ }
2377
+ /**
2378
+ * All box status snapshots in one query (avoids N+1 over listBoxes +
2379
+ * per-box getStatus). Used by the hosted hub UI to render every box's live
2380
+ * status. Not on the Store interface — only the hosted stores need it.
2381
+ */
2382
+ async listStatuses() {
2383
+ const db = await this.db();
2384
+ return db.select({ boxId: pgBoxStatus.boxId, status: pgBoxStatus.status }).from(pgBoxStatus);
2385
+ }
2386
+ // --- prompt mailbox ---
2387
+ async createPrompt(row) {
2388
+ const db = await this.db();
2389
+ await db.insert(pgPrompts).values({
2390
+ id: row.id,
2391
+ boxId: row.boxId,
2392
+ ev: row.ev,
2393
+ method: row.method,
2394
+ params: row.params ?? null,
2395
+ status: row.status,
2396
+ answer: row.answer ?? null,
2397
+ cancelled: row.cancelled ?? null,
2398
+ result: row.result ?? null,
2399
+ createdAt: new Date(row.createdAt),
2400
+ expiresAt: row.expiresAt ? new Date(row.expiresAt) : null
2401
+ }).onConflictDoNothing({ target: pgPrompts.id });
2402
+ }
2403
+ async getPrompt(promptId) {
2404
+ const db = await this.db();
2405
+ const rows = await db.select().from(pgPrompts).where(eq(pgPrompts.id, promptId));
2406
+ return rows[0] ? rowToPrompt(rows[0]) : null;
2407
+ }
2408
+ async answerPrompt(promptId, answer, cancelled) {
2409
+ const db = await this.db();
2410
+ const rows = await db.update(pgPrompts).set({ status: "answered", answer, cancelled: cancelled ?? null }).where(and(eq(pgPrompts.id, promptId), eq(pgPrompts.status, "pending"))).returning({ id: pgPrompts.id });
2411
+ return rows.length > 0;
2412
+ }
2413
+ async listPendingPrompts(boxId) {
2414
+ const db = await this.db();
2415
+ const rows = await db.select().from(pgPrompts).where(and(eq(pgPrompts.boxId, boxId), eq(pgPrompts.status, "pending"))).orderBy(asc(pgPrompts.createdAt));
2416
+ return rows.map(rowToPrompt);
2417
+ }
2418
+ async setPromptResult(promptId, result) {
2419
+ const db = await this.db();
2420
+ await db.update(pgPrompts).set({ result }).where(eq(pgPrompts.id, promptId));
2421
+ }
2422
+ // --- box-create job queue ---
2423
+ async enqueueCreateJob(job) {
2424
+ const db = await this.db();
2425
+ await db.insert(pgCreateJobs).values({
2426
+ id: job.id,
2427
+ status: job.status,
2428
+ request: job.request,
2429
+ result: job.result ?? null,
2430
+ claimedBy: job.claimedBy ?? null,
2431
+ createdAt: new Date(job.createdAt),
2432
+ startedAt: job.startedAt ? new Date(job.startedAt) : null,
2433
+ finishedAt: job.finishedAt ? new Date(job.finishedAt) : null
2434
+ }).onConflictDoNothing({ target: pgCreateJobs.id });
2435
+ }
2436
+ async getCreateJob(id) {
2437
+ const db = await this.db();
2438
+ const rows = await db.select().from(pgCreateJobs).where(eq(pgCreateJobs.id, id));
2439
+ return rows[0] ? rowToJob(rows[0]) : null;
2440
+ }
2441
+ async listCreateJobs(opts) {
2442
+ const db = await this.db();
2443
+ const base = db.select().from(pgCreateJobs);
2444
+ const filtered = opts?.status?.length ? base.where(inArray(pgCreateJobs.status, opts.status)) : base;
2445
+ const rows = await filtered.orderBy(desc(pgCreateJobs.createdAt)).limit(opts?.limit ?? 100);
2446
+ return rows.map(rowToJob);
2447
+ }
2448
+ async claimNextCreateJob(workerId) {
2449
+ const db = await this.db();
2450
+ const oldestQueued = db.select({ id: pgCreateJobs.id }).from(pgCreateJobs).where(eq(pgCreateJobs.status, "queued")).orderBy(asc(pgCreateJobs.createdAt)).limit(1).for("update", { skipLocked: true });
2451
+ const rows = await db.update(pgCreateJobs).set({ status: "running", claimedBy: workerId, startedAt: /* @__PURE__ */ new Date() }).where(inArray(pgCreateJobs.id, oldestQueued)).returning();
2452
+ return rows[0] ? rowToJob(rows[0]) : null;
2453
+ }
2454
+ async completeCreateJob(id, status, result) {
2455
+ const db = await this.db();
2456
+ await db.update(pgCreateJobs).set({ status, result, finishedAt: /* @__PURE__ */ new Date() }).where(eq(pgCreateJobs.id, id));
2457
+ }
2458
+ // --- retention (timestamptz columns compare against a Date) ---
2459
+ async prunePrompts(beforeIso) {
2460
+ const db = await this.db();
2461
+ const before = new Date(beforeIso);
2462
+ const rows = await db.delete(pgPrompts).where(
2463
+ or(
2464
+ and(eq(pgPrompts.status, "answered"), lt(pgPrompts.createdAt, before)),
2465
+ and(isNotNull(pgPrompts.expiresAt), lt(pgPrompts.expiresAt, before))
2466
+ )
2467
+ ).returning({ id: pgPrompts.id });
2468
+ return rows.length;
2469
+ }
2470
+ async pruneCreateJobs(beforeIso) {
2471
+ const db = await this.db();
2472
+ const before = new Date(beforeIso);
2473
+ const rows = await db.delete(pgCreateJobs).where(
2474
+ and(
2475
+ inArray(pgCreateJobs.status, ["done", "failed"]),
2476
+ isNotNull(pgCreateJobs.finishedAt),
2477
+ lt(pgCreateJobs.finishedAt, before)
2478
+ )
2479
+ ).returning({ id: pgCreateJobs.id });
2480
+ return rows.length;
2481
+ }
2482
+ };
2483
+ var DEFAULT_EVENT_CAP2 = RELAY_EVENT_RING_SIZE;
2484
+ var DEFAULT_SQLITE_STORE_PATH = join2(STATE_DIR, "hub", "store.db");
2485
+ var MIN_NODE_SQLITE = [22, 5];
2486
+ function loadNodeSqlite() {
2487
+ const require2 = createRequire(import.meta.url);
2488
+ return require2("node:sqlite");
2489
+ }
2490
+ function assertNodeSupportsSqlite() {
2491
+ const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
2492
+ const ok2 = major > MIN_NODE_SQLITE[0] || major === MIN_NODE_SQLITE[0] && minor >= MIN_NODE_SQLITE[1];
2493
+ if (!ok2) {
2494
+ throw new Error(
2495
+ `the SQLite store needs Node >= ${MIN_NODE_SQLITE[0]}.${MIN_NODE_SQLITE[1]} for node:sqlite (running ${process.versions.node}). Upgrade Node, or point the hub at a Postgres store (POSTGRES_URL).`
2496
+ );
2497
+ }
2498
+ }
2499
+ var SqliteStore = class {
2500
+ path;
2501
+ eventCap;
2502
+ raw = null;
2503
+ dbPromise = null;
2504
+ constructor(opts = {}) {
2505
+ this.path = opts.path ?? DEFAULT_SQLITE_STORE_PATH;
2506
+ this.eventCap = opts.eventCap ?? DEFAULT_EVENT_CAP2;
2507
+ }
2508
+ /**
2509
+ * Open the DB (creating the file + tables if absent) and wrap it in drizzle.
2510
+ * Lazy + memoized: the schema is always applied before the first query, so
2511
+ * callers never have to sequence `migrate()` themselves.
2512
+ */
2513
+ db() {
2514
+ this.dbPromise ??= (async () => {
2515
+ assertNodeSupportsSqlite();
2516
+ const { DatabaseSync } = loadNodeSqlite();
2517
+ const { drizzle } = await import("./sqlite-proxy-VJS3HIOV.js");
2518
+ if (this.path !== ":memory:") mkdirSync(dirname(this.path), { recursive: true });
2519
+ const raw = new DatabaseSync(this.path);
2520
+ raw.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;");
2521
+ raw.exec(SQLITE_SCHEMA_SQL);
2522
+ this.raw = raw;
2523
+ return drizzle(async (sql, params, method) => {
2524
+ const stmt = raw.prepare(sql);
2525
+ if (method === "run") {
2526
+ stmt.run(...params);
2527
+ return { rows: [] };
2528
+ }
2529
+ let rows;
2530
+ if (typeof stmt.setReturnArrays === "function") {
2531
+ stmt.setReturnArrays(true);
2532
+ rows = stmt.all(...params);
2533
+ } else {
2534
+ rows = stmt.all(...params).map((r) => Object.values(r));
2535
+ }
2536
+ return method === "get" ? { rows: rows[0] ?? [] } : { rows };
2537
+ });
2538
+ })();
2539
+ return this.dbPromise;
2540
+ }
2541
+ /** Open + apply the schema. Idempotent; `db()` does it lazily anyway. */
2542
+ async migrate() {
2543
+ await this.db();
2544
+ }
2545
+ /** Close the underlying handle (tests / graceful shutdown). */
2546
+ async close() {
2547
+ if (this.dbPromise) await this.dbPromise.catch(() => void 0);
2548
+ this.raw?.close();
2549
+ this.raw = null;
2550
+ this.dbPromise = null;
2551
+ }
2552
+ // --- boxes ---
2553
+ async registerBox(reg) {
2554
+ const db = await this.db();
2555
+ await db.insert(sqliteBoxes).values({
2556
+ boxId: reg.boxId,
2557
+ token: reg.token,
2558
+ originUrl: reg.originUrl ?? null,
2559
+ data: reg,
2560
+ registeredAt: reg.registeredAt
2561
+ }).onConflictDoUpdate({
2562
+ target: sqliteBoxes.boxId,
2563
+ set: { token: reg.token, originUrl: reg.originUrl ?? null, data: reg }
2564
+ });
2565
+ }
2566
+ async getBox(boxId) {
2567
+ const db = await this.db();
2568
+ const rows = await db.select({ data: sqliteBoxes.data }).from(sqliteBoxes).where(eq(sqliteBoxes.boxId, boxId));
2569
+ return rows[0]?.data;
2570
+ }
2571
+ async authenticateBox(token) {
2572
+ if (token.length === 0) return null;
2573
+ const db = await this.db();
2574
+ const rows = await db.select({ data: sqliteBoxes.data }).from(sqliteBoxes).where(eq(sqliteBoxes.token, token)).limit(1);
2575
+ return rows[0]?.data ?? null;
2576
+ }
2577
+ async listBoxes() {
2578
+ const db = await this.db();
2579
+ const rows = await db.select({ data: sqliteBoxes.data }).from(sqliteBoxes).orderBy(asc(sqliteBoxes.registeredAt));
2580
+ return rows.map((r) => r.data);
2581
+ }
2582
+ async forgetBox(boxId) {
2583
+ const db = await this.db();
2584
+ const rows = await db.delete(sqliteBoxes).where(eq(sqliteBoxes.boxId, boxId)).returning({ boxId: sqliteBoxes.boxId });
2585
+ return rows.length > 0;
2586
+ }
2587
+ async countBoxes() {
2588
+ const db = await this.db();
2589
+ return db.$count(sqliteBoxes);
2590
+ }
2591
+ // --- events ---
2592
+ async appendEvent(input) {
2593
+ const db = await this.db();
2594
+ const receivedAt = (/* @__PURE__ */ new Date()).toISOString();
2595
+ const rows = await db.insert(sqliteEvents).values({
2596
+ boxId: input.boxId,
2597
+ type: input.type,
2598
+ ts: input.ts ?? null,
2599
+ payload: input.payload ?? null,
2600
+ receivedAt
2601
+ }).returning({ id: sqliteEvents.id });
2602
+ const id = rows[0].id;
2603
+ if (this.eventCap > 0) {
2604
+ await db.delete(sqliteEvents).where(lte(sqliteEvents.id, id - this.eventCap));
2605
+ }
2606
+ return {
2607
+ id,
2608
+ boxId: input.boxId,
2609
+ type: input.type,
2610
+ ts: input.ts,
2611
+ payload: input.payload,
2612
+ receivedAt
2613
+ };
2614
+ }
2615
+ async listEvents(since, boxId) {
2616
+ const db = await this.db();
2617
+ const where = boxId === void 0 ? gt(sqliteEvents.id, since) : and(gt(sqliteEvents.id, since), eq(sqliteEvents.boxId, boxId));
2618
+ const rows = await db.select().from(sqliteEvents).where(where).orderBy(asc(sqliteEvents.id));
2619
+ return rows.map(rowToEvent);
2620
+ }
2621
+ async countEvents() {
2622
+ const db = await this.db();
2623
+ return db.$count(sqliteEvents);
2624
+ }
2625
+ // --- status ---
2626
+ async setStatus(boxId, name, projectIndex, status) {
2627
+ const db = await this.db();
2628
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2629
+ await db.insert(sqliteBoxStatus).values({ boxId, name, projectIndex: projectIndex ?? null, status, updatedAt }).onConflictDoUpdate({
2630
+ target: sqliteBoxStatus.boxId,
2631
+ set: { name, projectIndex: projectIndex ?? null, status, updatedAt }
2632
+ });
2633
+ }
2634
+ async getStatus(boxId) {
2635
+ const db = await this.db();
2636
+ const rows = await db.select({ status: sqliteBoxStatus.status }).from(sqliteBoxStatus).where(eq(sqliteBoxStatus.boxId, boxId));
2637
+ return rows[0]?.status;
2638
+ }
2639
+ async deleteStatus(boxId) {
2640
+ const db = await this.db();
2641
+ await db.delete(sqliteBoxStatus).where(eq(sqliteBoxStatus.boxId, boxId));
2642
+ }
2643
+ /** All box status snapshots in one query (see PostgresStore.listStatuses). */
2644
+ async listStatuses() {
2645
+ const db = await this.db();
2646
+ return db.select({ boxId: sqliteBoxStatus.boxId, status: sqliteBoxStatus.status }).from(sqliteBoxStatus);
2647
+ }
2648
+ // --- prompt mailbox ---
2649
+ async createPrompt(row) {
2650
+ const db = await this.db();
2651
+ await db.insert(sqlitePrompts).values({
2652
+ id: row.id,
2653
+ boxId: row.boxId,
2654
+ ev: row.ev,
2655
+ method: row.method,
2656
+ params: row.params ?? null,
2657
+ status: row.status,
2658
+ answer: row.answer ?? null,
2659
+ cancelled: row.cancelled ?? null,
2660
+ result: row.result ?? null,
2661
+ createdAt: row.createdAt,
2662
+ expiresAt: row.expiresAt ?? null
2663
+ }).onConflictDoNothing({ target: sqlitePrompts.id });
2664
+ }
2665
+ async getPrompt(promptId) {
2666
+ const db = await this.db();
2667
+ const rows = await db.select().from(sqlitePrompts).where(eq(sqlitePrompts.id, promptId));
2668
+ return rows[0] ? rowToPrompt(rows[0]) : null;
2669
+ }
2670
+ async answerPrompt(promptId, answer, cancelled) {
2671
+ const db = await this.db();
2672
+ const rows = await db.update(sqlitePrompts).set({ status: "answered", answer, cancelled: cancelled ?? null }).where(and(eq(sqlitePrompts.id, promptId), eq(sqlitePrompts.status, "pending"))).returning({ id: sqlitePrompts.id });
2673
+ return rows.length > 0;
2674
+ }
2675
+ async listPendingPrompts(boxId) {
2676
+ const db = await this.db();
2677
+ const rows = await db.select().from(sqlitePrompts).where(and(eq(sqlitePrompts.boxId, boxId), eq(sqlitePrompts.status, "pending"))).orderBy(asc(sqlitePrompts.createdAt));
2678
+ return rows.map(rowToPrompt);
2679
+ }
2680
+ async setPromptResult(promptId, result) {
2681
+ const db = await this.db();
2682
+ await db.update(sqlitePrompts).set({ result }).where(eq(sqlitePrompts.id, promptId));
2683
+ }
2684
+ // --- box-create job queue ---
2685
+ async enqueueCreateJob(job) {
2686
+ const db = await this.db();
2687
+ await db.insert(sqliteCreateJobs).values({
2688
+ id: job.id,
2689
+ status: job.status,
2690
+ request: job.request,
2691
+ result: job.result ?? null,
2692
+ claimedBy: job.claimedBy ?? null,
2693
+ createdAt: job.createdAt,
2694
+ startedAt: job.startedAt ?? null,
2695
+ finishedAt: job.finishedAt ?? null
2696
+ }).onConflictDoNothing({ target: sqliteCreateJobs.id });
2697
+ }
2698
+ async getCreateJob(id) {
2699
+ const db = await this.db();
2700
+ const rows = await db.select().from(sqliteCreateJobs).where(eq(sqliteCreateJobs.id, id));
2701
+ return rows[0] ? rowToJob(rows[0]) : null;
2702
+ }
2703
+ async listCreateJobs(opts) {
2704
+ const db = await this.db();
2705
+ const base = db.select().from(sqliteCreateJobs);
2706
+ const filtered = opts?.status?.length ? base.where(inArray(sqliteCreateJobs.status, opts.status)) : base;
2707
+ const rows = await filtered.orderBy(desc(sqliteCreateJobs.createdAt)).limit(opts?.limit ?? 100);
2708
+ return rows.map(rowToJob);
2709
+ }
2710
+ async claimNextCreateJob(workerId) {
2711
+ const db = await this.db();
2712
+ const oldestQueued = db.select({ id: sqliteCreateJobs.id }).from(sqliteCreateJobs).where(eq(sqliteCreateJobs.status, "queued")).orderBy(asc(sqliteCreateJobs.createdAt)).limit(1);
2713
+ const rows = await db.update(sqliteCreateJobs).set({ status: "running", claimedBy: workerId, startedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(
2714
+ and(inArray(sqliteCreateJobs.id, oldestQueued), eq(sqliteCreateJobs.status, "queued"))
2715
+ ).returning();
2716
+ return rows[0] ? rowToJob(rows[0]) : null;
2717
+ }
2718
+ async completeCreateJob(id, status, result) {
2719
+ const db = await this.db();
2720
+ await db.update(sqliteCreateJobs).set({ status, result, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq(sqliteCreateJobs.id, id));
2721
+ }
2722
+ // --- retention (ISO strings compare lexicographically, matching the columns) ---
2723
+ async prunePrompts(beforeIso) {
2724
+ const db = await this.db();
2725
+ const rows = await db.delete(sqlitePrompts).where(
2726
+ or(
2727
+ and(eq(sqlitePrompts.status, "answered"), lt(sqlitePrompts.createdAt, beforeIso)),
2728
+ and(isNotNull(sqlitePrompts.expiresAt), lt(sqlitePrompts.expiresAt, beforeIso))
2729
+ )
2730
+ ).returning({ id: sqlitePrompts.id });
2731
+ return rows.length;
2732
+ }
2733
+ async pruneCreateJobs(beforeIso) {
2734
+ const db = await this.db();
2735
+ const rows = await db.delete(sqliteCreateJobs).where(
2736
+ and(
2737
+ inArray(sqliteCreateJobs.status, ["done", "failed"]),
2738
+ isNotNull(sqliteCreateJobs.finishedAt),
2739
+ lt(sqliteCreateJobs.finishedAt, beforeIso)
2740
+ )
2741
+ ).returning({ id: sqliteCreateJobs.id });
2742
+ return rows.length;
2743
+ }
2744
+ };
2745
+ function makeStore(spec) {
2746
+ if (!spec || spec === "memory") return new MemoryStore();
2747
+ if (spec.startsWith("postgres://") || spec.startsWith("postgresql://")) {
2748
+ return new PostgresStore({ connectionString: spec });
2749
+ }
2750
+ if (spec.startsWith("sqlite:")) {
2751
+ const path = spec.slice("sqlite:".length).replace(/^\/\//, "");
2752
+ if (!path) throw new Error(`store spec has no path: ${spec}`);
2753
+ return new SqliteStore({ path });
2754
+ }
2755
+ if (spec === ":memory:" || spec.startsWith("/") || spec.startsWith(".") || spec.endsWith(".db")) {
2756
+ return new SqliteStore({ path: spec });
2757
+ }
2758
+ throw new Error(`unknown store spec: ${spec}`);
2759
+ }
2760
+ var DEFAULT_CUSTODY_DIR = join22(STATE_DIR, "hub", "custody");
2761
+ var DIR_MODE = 448;
2762
+ var FILE_MODE = 384;
2763
+ var FsCustodyStore = class {
2764
+ root;
2765
+ constructor(opts = {}) {
2766
+ this.root = opts.root ?? DEFAULT_CUSTODY_DIR;
2767
+ }
2768
+ async put(path, data) {
2769
+ const rel = normalizeCustodyPath(path);
2770
+ const abs = join22(this.root, rel);
2771
+ const sha256 = custodyDigest(data);
2772
+ const existing = await this.readEntry(rel);
2773
+ if (existing && existing.entry.sha256 === sha256) {
2774
+ return { ...existing.entry, changed: false };
2775
+ }
2776
+ await mkdir2(dirname2(abs), { recursive: true, mode: DIR_MODE });
2777
+ const tmp = `${abs}.${randomBytes(6).toString("hex")}.tmp`;
2778
+ try {
2779
+ await writeFile2(tmp, data, { mode: FILE_MODE });
2780
+ await chmod(tmp, FILE_MODE);
2781
+ await rename2(tmp, abs);
2782
+ } catch (err2) {
2783
+ await rm2(tmp, { force: true });
2784
+ throw err2;
2785
+ }
2786
+ const st = await stat(abs);
2787
+ return {
2788
+ path: rel,
2789
+ size: data.length,
2790
+ sha256,
2791
+ mode: st.mode & 511,
2792
+ updatedAt: st.mtime.toISOString(),
2793
+ changed: true
2794
+ };
2795
+ }
2796
+ async get(path) {
2797
+ return this.readEntry(normalizeCustodyPath(path));
2798
+ }
2799
+ async stat(path) {
2800
+ const found = await this.readEntry(normalizeCustodyPath(path));
2801
+ return found ? found.entry : null;
2802
+ }
2803
+ async list(prefix) {
2804
+ const rel = prefix === void 0 ? "" : normalizeCustodyPrefix(prefix);
2805
+ const entries = [];
2806
+ for (const found of await this.walk(this.root)) {
2807
+ if (rel.length > 0 && found !== rel && !found.startsWith(`${rel}/`)) continue;
2808
+ const e = await this.readEntry(found);
2809
+ if (e) entries.push(e.entry);
2810
+ }
2811
+ entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
2812
+ return entries;
2813
+ }
2814
+ async delete(path) {
2815
+ const rel = normalizeCustodyPath(path);
2816
+ const abs = join22(this.root, rel);
2817
+ try {
2818
+ await rm2(abs);
2819
+ return true;
2820
+ } catch (err2) {
2821
+ if (err2.code === "ENOENT") return false;
2822
+ throw err2;
2823
+ }
2824
+ }
2825
+ async readEntry(rel) {
2826
+ const abs = join22(this.root, rel);
2827
+ try {
2828
+ const [data, st] = await Promise.all([readFile(abs), stat(abs)]);
2829
+ return {
2830
+ entry: {
2831
+ path: rel,
2832
+ size: data.length,
2833
+ sha256: custodyDigest(data),
2834
+ mode: st.mode & 511,
2835
+ updatedAt: st.mtime.toISOString()
2836
+ },
2837
+ data
2838
+ };
2839
+ } catch (err2) {
2840
+ const code = err2.code;
2841
+ if (code === "ENOENT" || code === "EISDIR") return null;
2842
+ throw err2;
2843
+ }
2844
+ }
2845
+ /** Custody-relative paths of every regular file under `dir` (tmp files skipped). */
2846
+ async walk(dir) {
2847
+ let dirents;
2848
+ try {
2849
+ dirents = await readdir(dir, { withFileTypes: true });
2850
+ } catch (err2) {
2851
+ if (err2.code === "ENOENT") return [];
2852
+ throw err2;
2853
+ }
2854
+ const out = [];
2855
+ for (const d of dirents) {
2856
+ const abs = join22(dir, d.name);
2857
+ if (d.isDirectory()) {
2858
+ out.push(...await this.walk(abs));
2859
+ } else if (d.isFile() && !d.name.endsWith(".tmp")) {
2860
+ out.push(relative(this.root, abs).split(sep).join("/"));
2861
+ }
2862
+ }
2863
+ return out;
2864
+ }
2865
+ };
2866
+
2867
+ // ../../packages/relay/dist/chunk-4ZINSJOP.js
1359
2868
  import { spawn as spawn3 } from "child_process";
1360
2869
  import { createServer } from "http";
1361
- import { mkdtemp, rm as rm2 } from "fs/promises";
2870
+ import { mkdtemp, rm as rm3 } from "fs/promises";
1362
2871
  import { tmpdir } from "os";
1363
- import { join as join2 } from "path";
2872
+ import { join as join3 } from "path";
1364
2873
  import { pathToFileURL } from "url";
1365
2874
  import { spawn } from "child_process";
1366
- import { createHash, randomBytes } from "crypto";
2875
+ import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
1367
2876
  import { spawn as spawn2 } from "child_process";
1368
2877
 
1369
2878
  // ../../packages/integrations/dist/index.js
@@ -1642,24 +3151,25 @@ function getConnector(service) {
1642
3151
  return null;
1643
3152
  }
1644
3153
 
1645
- // ../../packages/relay/dist/chunk-GEIE6TWJ.js
1646
- import { randomUUID as randomUUID3 } from "crypto";
3154
+ // ../../packages/relay/dist/chunk-4ZINSJOP.js
3155
+ import { randomUUID as randomUUID4 } from "crypto";
1647
3156
  import { randomUUID as randomUUID22 } from "crypto";
3157
+ import { timingSafeEqual as timingSafeEqual4 } from "crypto";
1648
3158
  import { spawn as spawn5 } from "child_process";
1649
3159
  import { readFile as readFile22 } from "fs/promises";
1650
3160
  import { spawn as spawn4 } from "child_process";
1651
- import { randomBytes as randomBytes2 } from "crypto";
3161
+ import { randomBytes as randomBytes22 } from "crypto";
1652
3162
  import {
1653
- mkdir as mkdir2,
1654
- readdir,
1655
- readFile,
1656
- rename as rename2,
3163
+ mkdir as mkdir3,
3164
+ readdir as readdir2,
3165
+ readFile as readFile3,
3166
+ rename as rename3,
1657
3167
  unlink,
1658
- writeFile as writeFile2
3168
+ writeFile as writeFile3
1659
3169
  } from "fs/promises";
1660
- import { closeSync, existsSync, openSync } from "fs";
1661
- import { join as join22 } from "path";
1662
- import { readFile as readFile3 } from "fs/promises";
3170
+ import { closeSync, existsSync as existsSync2, openSync } from "fs";
3171
+ import { join as join23 } from "path";
3172
+ import { readFile as readFile32 } from "fs/promises";
1663
3173
  var GH_PR_OPS = [
1664
3174
  "create",
1665
3175
  "view",
@@ -1932,7 +3442,7 @@ function refuseCheckoutByDefault(op) {
1932
3442
  }
1933
3443
  var DEFAULT_TTL_MS = 12e4;
1934
3444
  function hashRpcParams(params) {
1935
- return createHash("sha256").update(canonicalJson(params)).digest("hex");
3445
+ return createHash2("sha256").update(canonicalJson(params)).digest("hex");
1936
3446
  }
1937
3447
  function canonicalJson(v) {
1938
3448
  if (v === null) return "null";
@@ -1956,7 +3466,7 @@ var HostInitiatedTokens = class {
1956
3466
  * params (no current call sites use this).
1957
3467
  */
1958
3468
  mint(boxId, method, paramsHash, ttlMs = DEFAULT_TTL_MS) {
1959
- const token = randomBytes(32).toString("hex");
3469
+ const token = randomBytes2(32).toString("hex");
1960
3470
  this.store.set(token, { boxId, method, paramsHash, expiresAt: Date.now() + ttlMs });
1961
3471
  return token;
1962
3472
  }
@@ -2858,8 +4368,8 @@ async function runGitRpc(action, deps) {
2858
4368
  }
2859
4369
  if (params.hostOnly) {
2860
4370
  const dest = resolveLandDest(branch, params.as);
2861
- const stageSave = await mkdtemp(join2(tmpdir(), "agentbox-git-save-"));
2862
- const hostBundleSave = join2(stageSave, "op.bundle");
4371
+ const stageSave = await mkdtemp(join3(tmpdir(), "agentbox-git-save-"));
4372
+ const hostBundleSave = join3(stageSave, "op.bundle");
2863
4373
  const remoteBundleSave = "/tmp/agentbox-rpc-save.bundle";
2864
4374
  try {
2865
4375
  const make = await backend.exec(
@@ -2890,7 +4400,7 @@ ${landed.stdout ?? ""}`,
2890
4400
  stderr: landed.stderr ?? ""
2891
4401
  };
2892
4402
  } finally {
2893
- await rm2(stageSave, { recursive: true, force: true });
4403
+ await rm3(stageSave, { recursive: true, force: true });
2894
4404
  await backend.exec(handle, `rm -f ${shellQuote(remoteBundleSave)}`).catch(() => {
2895
4405
  });
2896
4406
  }
@@ -2969,8 +4479,8 @@ ${landed.stdout ?? ""}`,
2969
4479
  }
2970
4480
  }
2971
4481
  }
2972
- const stage = await mkdtemp(join2(tmpdir(), "agentbox-git-rpc-"));
2973
- const hostBundle = join2(stage, "op.bundle");
4482
+ const stage = await mkdtemp(join3(tmpdir(), "agentbox-git-rpc-"));
4483
+ const hostBundle = join3(stage, "op.bundle");
2974
4484
  const remoteBundle = "/tmp/agentbox-rpc.bundle";
2975
4485
  try {
2976
4486
  if (action.method === "git.push") {
@@ -3071,7 +4581,7 @@ relay: post-push in-box origin/upstream sync threw: ${err instanceof Error ? err
3071
4581
  stderr: sandboxFetch.stderr
3072
4582
  };
3073
4583
  } finally {
3074
- await rm2(stage, { recursive: true, force: true });
4584
+ await rm3(stage, { recursive: true, force: true });
3075
4585
  await backend.exec(handle, `rm -f ${shellQuote(remoteBundle)}`).catch(() => {
3076
4586
  });
3077
4587
  }
@@ -3098,7 +4608,7 @@ var HostActionQueue = class {
3098
4608
  * is open" semantics).
3099
4609
  */
3100
4610
  enqueue(boxId, method, params) {
3101
- const id = randomUUID3();
4611
+ const id = randomUUID4();
3102
4612
  const action = {
3103
4613
  id,
3104
4614
  boxId,
@@ -3237,6 +4747,17 @@ var BoxNotices = class {
3237
4747
  return this.entries.size;
3238
4748
  }
3239
4749
  };
4750
+ function timingSafeEqualStr4(a, b) {
4751
+ const ab = Buffer.from(a, "utf8");
4752
+ const bb = Buffer.from(b, "utf8");
4753
+ if (ab.length !== bb.length) return false;
4754
+ return timingSafeEqual4(ab, bb);
4755
+ }
4756
+ function adminGateAllows(isLoopback, bearer, adminToken) {
4757
+ if (isLoopback) return true;
4758
+ if (adminToken.length === 0) return false;
4759
+ return Boolean(bearer) && timingSafeEqualStr4(bearer ?? "", adminToken);
4760
+ }
3240
4761
  var CREDENTIALS_UPDATED_EVENT = "credentials-updated";
3241
4762
  var CredentialsFanout = class {
3242
4763
  log;
@@ -3315,6 +4836,7 @@ async function defaultRunPropagate(agent, sourceBoxId) {
3315
4836
  }
3316
4837
  var BOX_STATUS_EVENT = "box-status";
3317
4838
  var MAX_BODY_BYTES = 1024 * 1024;
4839
+ var DEFAULT_CUSTODY_MAX_BODY_BYTES = 32 * 1024 * 1024;
3318
4840
  var GIT_RPC_TIMEOUT_MS = 12e4;
3319
4841
  var CHECKPOINT_RPC_TIMEOUT_MS = 6e5;
3320
4842
  var DOWNLOAD_RPC_TIMEOUT_MS = 6e5;
@@ -3323,12 +4845,12 @@ var BROWSER_OPEN_RPC_TIMEOUT_MS = 15e3;
3323
4845
  var BROWSER_OPEN_PROMPT_TTL_MS = 25e3;
3324
4846
  var SSE_HEARTBEAT_MS = 15e3;
3325
4847
  function send(res, status, body, contentType = "application/json") {
3326
- const text = body == null ? "" : typeof body === "string" ? body : JSON.stringify(body);
4848
+ const text3 = body == null ? "" : typeof body === "string" ? body : JSON.stringify(body);
3327
4849
  res.statusCode = status;
3328
- if (text.length > 0) {
4850
+ if (text3.length > 0) {
3329
4851
  res.setHeader("Content-Type", contentType);
3330
- res.setHeader("Content-Length", Buffer.byteLength(text).toString());
3331
- res.end(text);
4852
+ res.setHeader("Content-Length", Buffer.byteLength(text3).toString());
4853
+ res.end(text3);
3332
4854
  } else {
3333
4855
  res.end();
3334
4856
  }
@@ -3347,13 +4869,13 @@ async function readJsonBody(req) {
3347
4869
  chunks.push(chunk);
3348
4870
  });
3349
4871
  req.on("end", () => {
3350
- const text = Buffer.concat(chunks).toString("utf8");
3351
- if (text.length === 0) {
4872
+ const text3 = Buffer.concat(chunks).toString("utf8");
4873
+ if (text3.length === 0) {
3352
4874
  resolve6({});
3353
4875
  return;
3354
4876
  }
3355
4877
  try {
3356
- resolve6(JSON.parse(text));
4878
+ resolve6(JSON.parse(text3));
3357
4879
  } catch (err) {
3358
4880
  reject(err instanceof Error ? err : new Error(String(err)));
3359
4881
  }
@@ -3361,6 +4883,23 @@ async function readJsonBody(req) {
3361
4883
  req.on("error", reject);
3362
4884
  });
3363
4885
  }
4886
+ async function readRawBody(req, maxBytes = MAX_BODY_BYTES) {
4887
+ return new Promise((resolve6, reject) => {
4888
+ let total = 0;
4889
+ const chunks = [];
4890
+ req.on("data", (chunk) => {
4891
+ total += chunk.length;
4892
+ if (total > maxBytes) {
4893
+ reject(new Error("request body too large"));
4894
+ req.destroy();
4895
+ return;
4896
+ }
4897
+ chunks.push(chunk);
4898
+ });
4899
+ req.on("end", () => resolve6(Buffer.concat(chunks).toString("utf8")));
4900
+ req.on("error", reject);
4901
+ });
4902
+ }
3364
4903
  function bearerToken(req) {
3365
4904
  const raw = req.headers.authorization;
3366
4905
  if (typeof raw !== "string") return "";
@@ -3382,7 +4921,7 @@ function createRelayServer(opts) {
3382
4921
  const notices = new BoxNotices(subscribers);
3383
4922
  const hubNotifier = new HubNotifier();
3384
4923
  prompts.setOnChange(() => hubNotifier.notify());
3385
- const store = opts.store ?? new MemoryStore({ registry, events, statusStore });
4924
+ const store = opts.store ? new WriteThroughStore(opts.store, { registry, events, statusStore }) : new MemoryStore({ registry, events, statusStore });
3386
4925
  prompts.setAutoApprovePolicy({
3387
4926
  shouldAutoApprove: (boxId) => registry.get(boxId)?.autoApproveHostActions === true,
3388
4927
  audit: (boxId, params, reason) => {
@@ -3415,6 +4954,9 @@ function createRelayServer(opts) {
3415
4954
  const gateDeps = { mode: promptMode, store, prompts, subscribers };
3416
4955
  const githubAppConfig = opts.githubApp === void 0 ? loadGitHubAppConfig() : opts.githubApp;
3417
4956
  const leaser = githubAppConfig ? new GitHubAppLeaser(githubAppConfig) : null;
4957
+ const custody = opts.custody ?? null;
4958
+ const custodyAdminToken = opts.adminToken ?? "";
4959
+ const custodyMaxBodyBytes = typeof opts.custodyMaxBodyBytes === "number" && opts.custodyMaxBodyBytes > 0 ? opts.custodyMaxBodyBytes : DEFAULT_CUSTODY_MAX_BODY_BYTES;
3418
4960
  const uiHandler = opts.uiHandler;
3419
4961
  let pollers = null;
3420
4962
  async function getPollers() {
@@ -3504,12 +5046,62 @@ function createRelayServer(opts) {
3504
5046
  send(res, 404, { error: "not found", route });
3505
5047
  return;
3506
5048
  }
5049
+ if (url.pathname === "/admin/custody" || url.pathname.startsWith("/admin/custody/")) {
5050
+ const bodyText = req.method === "PUT" || req.method === "POST" ? await readRawBody(req, custodyMaxBodyBytes) : "";
5051
+ const custodyRes = await handleCustodyRequest(
5052
+ {
5053
+ method: req.method ?? "GET",
5054
+ path: url.pathname,
5055
+ query: url.searchParams,
5056
+ bearer: bearerToken(req),
5057
+ bodyText
5058
+ },
5059
+ { custody, adminToken: custodyAdminToken, log }
5060
+ );
5061
+ if (custodyRes) {
5062
+ send(res, custodyRes.status, custodyRes.body ?? null);
5063
+ return;
5064
+ }
5065
+ }
5066
+ if (isRemoteBoxesPath(url.pathname)) {
5067
+ const bodyText = req.method === "POST" ? await readRawBody(req) : "";
5068
+ const remoteRes = await handleRemoteBoxesRequest(
5069
+ {
5070
+ method: req.method ?? "GET",
5071
+ path: url.pathname,
5072
+ bearer: bearerToken(req),
5073
+ bodyText
5074
+ },
5075
+ { store, adminToken: custodyAdminToken, custody, log }
5076
+ );
5077
+ if (remoteRes) {
5078
+ send(res, remoteRes.status, remoteRes.body ?? null);
5079
+ return;
5080
+ }
5081
+ }
5082
+ if (isStoreRpcPath(url.pathname)) {
5083
+ const bodyText = req.method === "POST" ? await readRawBody(req) : "";
5084
+ const storeRpcRes = await handleStoreRpcRequest(
5085
+ {
5086
+ method: req.method ?? "GET",
5087
+ path: url.pathname,
5088
+ bearer: bearerToken(req),
5089
+ bodyText
5090
+ },
5091
+ { store, adminToken: custodyAdminToken, log }
5092
+ );
5093
+ if (storeRpcRes) {
5094
+ send(res, storeRpcRes.status, storeRpcRes.body ?? null);
5095
+ return;
5096
+ }
5097
+ }
3507
5098
  if (url.pathname.startsWith("/admin/") || url.pathname.startsWith("/remote/")) {
3508
5099
  if (url.pathname.startsWith("/remote/")) {
3509
5100
  send(res, 404, { error: "not found", route });
3510
5101
  return;
3511
5102
  }
3512
- if (!isLoopbackAddress(req.socket.remoteAddress)) {
5103
+ const loopback = isLoopbackAddress(req.socket.remoteAddress);
5104
+ if (!adminGateAllows(loopback, bearerToken(req), custodyAdminToken)) {
3513
5105
  send(res, 403, { error: "admin endpoints are loopback-only" });
3514
5106
  return;
3515
5107
  }
@@ -3946,6 +5538,7 @@ function createRelayServer(opts) {
3946
5538
  name: body.name,
3947
5539
  kind,
3948
5540
  backend: typeof body.backend === "string" && body.backend.length > 0 ? body.backend : void 0,
5541
+ sandboxId: typeof body.sandboxId === "string" && body.sandboxId.length > 0 ? body.sandboxId : void 0,
3949
5542
  registeredAt: (/* @__PURE__ */ new Date()).toISOString(),
3950
5543
  containerName: typeof body.containerName === "string" && body.containerName.length > 0 ? body.containerName : void 0,
3951
5544
  createdAt: typeof body.createdAt === "string" && body.createdAt.length > 0 ? body.createdAt : void 0,
@@ -3958,7 +5551,12 @@ function createRelayServer(opts) {
3958
5551
  // Default on: only an explicit `false` disables the safe subset, so an
3959
5552
  // older wire body without the field stays relaxed.
3960
5553
  autoApproveSafeHostActions: body.autoApproveSafeHostActions !== false,
3961
- originUrl: typeof body.originUrl === "string" && body.originUrl.length > 0 ? body.originUrl : void 0
5554
+ originUrl: typeof body.originUrl === "string" && body.originUrl.length > 0 ? body.originUrl : void 0,
5555
+ publicHost: typeof body.publicHost === "string" && body.publicHost.length > 0 ? body.publicHost : void 0,
5556
+ image: typeof body.image === "string" && body.image.length > 0 ? body.image : void 0,
5557
+ webPort: typeof body.webPort === "number" && Number.isFinite(body.webPort) && body.webPort > 0 ? Math.trunc(body.webPort) : void 0,
5558
+ agent: typeof body.agent === "string" && body.agent.length > 0 ? body.agent : void 0,
5559
+ projectSlug: typeof body.projectSlug === "string" && body.projectSlug.length > 0 ? body.projectSlug : void 0
3962
5560
  };
3963
5561
  await store.registerBox(reg);
3964
5562
  log(
@@ -4258,6 +5856,7 @@ data: {"ts":"${(/* @__PURE__ */ new Date()).toISOString()}"}
4258
5856
  subscribers,
4259
5857
  notices,
4260
5858
  hubNotifier,
5859
+ custody,
4261
5860
  hostActions: hostActions ?? void 0,
4262
5861
  url: `http://${host}:${String(opts.port)}`,
4263
5862
  setQueuePoke: (fn) => {
@@ -4341,6 +5940,10 @@ async function handleGitRpc(reg, method, params) {
4341
5940
  stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`
4342
5941
  };
4343
5942
  }
5943
+ const unavailable = hostRepoUnavailableReason(worktree, reg.boxId, method);
5944
+ if (unavailable) {
5945
+ return { exitCode: 64, stdout: "", stderr: unavailable };
5946
+ }
4344
5947
  const op = method === "git.push" ? "push" : "fetch";
4345
5948
  const remote = resolveRemote(params?.remote);
4346
5949
  const pushBranch = worktree.sanctionedBranch ?? worktree.branch;
@@ -4683,6 +6286,7 @@ relay: command timed out after ${String(timeoutMs)}ms
4683
6286
  }
4684
6287
  async function startRelayServer(opts) {
4685
6288
  const handle = createRelayServer(opts);
6289
+ if (handle.store instanceof WriteThroughStore) await handle.store.hydrate();
4686
6290
  await new Promise((resolve6, reject) => {
4687
6291
  handle.server.once("error", reject);
4688
6292
  handle.server.listen(opts.port, opts.host ?? "0.0.0.0", () => {
@@ -4692,13 +6296,13 @@ async function startRelayServer(opts) {
4692
6296
  });
4693
6297
  return handle;
4694
6298
  }
4695
- var QUEUE_DIR = join22(STATE_DIR, "queue");
6299
+ var QUEUE_DIR = join23(STATE_DIR2, "queue");
4696
6300
  var PREPARE_MAX_CONCURRENT = 1;
4697
6301
  async function loadQueueConfig() {
4698
6302
  const d = BUILT_IN_DEFAULTS.queue;
4699
6303
  let global = {};
4700
6304
  try {
4701
- global = parseUserConfig(await readFile(GLOBAL_CONFIG_FILE, "utf8"), GLOBAL_CONFIG_FILE);
6305
+ global = parseUserConfig(await readFile3(GLOBAL_CONFIG_FILE, "utf8"), GLOBAL_CONFIG_FILE);
4702
6306
  } catch {
4703
6307
  }
4704
6308
  const q = global.queue ?? {};
@@ -4710,17 +6314,17 @@ async function loadQueueConfig() {
4710
6314
  };
4711
6315
  }
4712
6316
  async function writeJob(job) {
4713
- await mkdir2(QUEUE_DIR, { recursive: true });
4714
- const final = join22(QUEUE_DIR, `${job.id}.json`);
6317
+ await mkdir3(QUEUE_DIR, { recursive: true });
6318
+ const final = join23(QUEUE_DIR, `${job.id}.json`);
4715
6319
  const tmp = `${final}.tmp.${String(process.pid)}.${String(Date.now())}`;
4716
- await writeFile2(tmp, JSON.stringify(job, null, 2) + "\n", "utf8");
4717
- await rename2(tmp, final);
6320
+ await writeFile3(tmp, JSON.stringify(job, null, 2) + "\n", "utf8");
6321
+ await rename3(tmp, final);
4718
6322
  }
4719
6323
  async function enqueueQueueJob(input) {
4720
6324
  const cfg = await loadQueueConfig();
4721
6325
  const ceiling = typeof input.maxRunningOverride === "number" && input.maxRunningOverride > 0 ? input.maxRunningOverride : cfg.maxConcurrent;
4722
6326
  const maxWorking = typeof input.maxWorkingOverride === "number" && input.maxWorkingOverride > 0 ? input.maxWorkingOverride : void 0;
4723
- const id = randomBytes2(9).toString("hex");
6327
+ const id = randomBytes22(9).toString("hex");
4724
6328
  const job = {
4725
6329
  id,
4726
6330
  agent: input.agent,
@@ -4748,7 +6352,7 @@ async function enqueueQueueJob(input) {
4748
6352
  return { job, runningCount, maxConcurrent: ceiling };
4749
6353
  }
4750
6354
  async function enqueuePrepareJob(input) {
4751
- const id = randomBytes2(9).toString("hex");
6355
+ const id = randomBytes22(9).toString("hex");
4752
6356
  const prepare = {
4753
6357
  ...input.force ? { force: true } : {},
4754
6358
  ...input.claudeInstall ? { claudeInstall: input.claudeInstall } : {}
@@ -4774,7 +6378,7 @@ async function enqueuePrepareJob(input) {
4774
6378
  }
4775
6379
  async function readJob(id) {
4776
6380
  try {
4777
- const raw = await readFile(join22(QUEUE_DIR, `${id}.json`), "utf8");
6381
+ const raw = await readFile3(join23(QUEUE_DIR, `${id}.json`), "utf8");
4778
6382
  return JSON.parse(raw);
4779
6383
  } catch (err) {
4780
6384
  if (err.code === "ENOENT") return null;
@@ -4783,7 +6387,7 @@ async function readJob(id) {
4783
6387
  }
4784
6388
  async function deleteJob(id) {
4785
6389
  try {
4786
- await unlink(join22(QUEUE_DIR, `${id}.json`));
6390
+ await unlink(join23(QUEUE_DIR, `${id}.json`));
4787
6391
  } catch (err) {
4788
6392
  if (err.code !== "ENOENT") throw err;
4789
6393
  }
@@ -4791,7 +6395,7 @@ async function deleteJob(id) {
4791
6395
  async function loadQueue() {
4792
6396
  let entries;
4793
6397
  try {
4794
- entries = await readdir(QUEUE_DIR);
6398
+ entries = await readdir2(QUEUE_DIR);
4795
6399
  } catch (err) {
4796
6400
  if (err.code === "ENOENT") return [];
4797
6401
  throw err;
@@ -4800,7 +6404,7 @@ async function loadQueue() {
4800
6404
  for (const name of entries) {
4801
6405
  if (!name.endsWith(".json")) continue;
4802
6406
  try {
4803
- const raw = await readFile(join22(QUEUE_DIR, name), "utf8");
6407
+ const raw = await readFile3(join23(QUEUE_DIR, name), "utf8");
4804
6408
  out.push(JSON.parse(raw));
4805
6409
  } catch {
4806
6410
  }
@@ -5206,19 +6810,19 @@ function inspectDockerState(containerName) {
5206
6810
  }
5207
6811
  async function defaultSpawnWorker(job) {
5208
6812
  const entry = process.env.AGENTBOX_CLI_ENTRY;
5209
- if (!entry || !existsSync(entry)) {
6813
+ if (!entry || !existsSync2(entry)) {
5210
6814
  throw new Error(
5211
6815
  `AGENTBOX_CLI_ENTRY not set or missing (${String(entry)}); cannot spawn queue worker`
5212
6816
  );
5213
6817
  }
5214
- await mkdir2(join22(STATE_DIR, "logs"), { recursive: true });
6818
+ await mkdir3(join23(STATE_DIR2, "logs"), { recursive: true });
5215
6819
  const fd = openSync(job.logPath, "a");
5216
6820
  const command = job.kind === "prepare" ? "_run-queued-prepare" : "_run-queued-job";
5217
6821
  const child = spawn4(process.execPath, [entry, command, job.id], {
5218
6822
  detached: true,
5219
6823
  stdio: ["ignore", fd, fd],
5220
6824
  env: process.env,
5221
- cwd: STATE_DIR
6825
+ cwd: STATE_DIR2
5222
6826
  });
5223
6827
  child.unref();
5224
6828
  try {
@@ -5227,19 +6831,19 @@ async function defaultSpawnWorker(job) {
5227
6831
  }
5228
6832
  return typeof child.pid === "number" ? child.pid : null;
5229
6833
  }
5230
- var QUEUE_LOGS_DIR = join22(STATE_DIR, "logs");
6834
+ var QUEUE_LOGS_DIR = join23(STATE_DIR2, "logs");
5231
6835
  function queueLogPath(id) {
5232
- return join22(QUEUE_LOGS_DIR, `queue-${id}.log`);
6836
+ return join23(QUEUE_LOGS_DIR, `queue-${id}.log`);
5233
6837
  }
5234
6838
  function queueLoginCodePath(id) {
5235
- return join22(QUEUE_DIR, `${id}.login-code`);
6839
+ return join23(QUEUE_DIR, `${id}.login-code`);
5236
6840
  }
5237
6841
  async function writeQueueLoginCode(id, code) {
5238
- await mkdir2(QUEUE_DIR, { recursive: true });
6842
+ await mkdir3(QUEUE_DIR, { recursive: true });
5239
6843
  const final = queueLoginCodePath(id);
5240
6844
  const tmp = `${final}.tmp.${String(process.pid)}.${String(Date.now())}`;
5241
- await writeFile2(tmp, code.trim(), { mode: 384 });
5242
- await rename2(tmp, final);
6845
+ await writeFile3(tmp, code.trim(), { mode: 384 });
6846
+ await rename3(tmp, final);
5243
6847
  }
5244
6848
  function selectBoxesToPause(entries, cfg) {
5245
6849
  if (!cfg.enabled) return [];
@@ -5648,7 +7252,7 @@ async function defaultFallbackCreateTimeoutMs(backend) {
5648
7252
  const fallback = BUILT_IN_DEFAULTS.box.vercelTimeoutMs;
5649
7253
  try {
5650
7254
  const global = parseUserConfig(
5651
- await readFile3(GLOBAL_CONFIG_FILE, "utf8"),
7255
+ await readFile32(GLOBAL_CONFIG_FILE, "utf8"),
5652
7256
  GLOBAL_CONFIG_FILE
5653
7257
  );
5654
7258
  const v = global.box?.vercelTimeoutMs;
@@ -5657,6 +7261,49 @@ async function defaultFallbackCreateTimeoutMs(backend) {
5657
7261
  return fallback;
5658
7262
  }
5659
7263
  }
7264
+ var DEFAULT_RETENTION_MS = 24 * 60 * 6e4;
7265
+ var DEFAULT_INTERVAL_MS4 = 60 * 6e4;
7266
+ function startRetentionLoop(deps) {
7267
+ const { store, log } = deps;
7268
+ const retentionMs = deps.retentionMs ?? DEFAULT_RETENTION_MS;
7269
+ const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS4;
7270
+ const nowFn = deps.now ?? Date.now;
7271
+ if (!store.prunePrompts && !store.pruneCreateJobs) {
7272
+ return { stop: () => Promise.resolve() };
7273
+ }
7274
+ let ticking = false;
7275
+ let stopped = false;
7276
+ let inFlight = Promise.resolve();
7277
+ async function tick() {
7278
+ if (ticking) return;
7279
+ ticking = true;
7280
+ try {
7281
+ const before = new Date(nowFn() - retentionMs).toISOString();
7282
+ const prompts = await store.prunePrompts?.(before) ?? 0;
7283
+ const jobs = await store.pruneCreateJobs?.(before) ?? 0;
7284
+ if (prompts > 0 || jobs > 0) {
7285
+ log(`retention: pruned ${String(prompts)} prompt(s), ${String(jobs)} create job(s)`);
7286
+ }
7287
+ } catch (err) {
7288
+ log(`retention: tick error: ${err instanceof Error ? err.message : String(err)}`);
7289
+ } finally {
7290
+ ticking = false;
7291
+ }
7292
+ }
7293
+ const timer = setInterval(() => {
7294
+ if (stopped) return;
7295
+ inFlight = tick();
7296
+ }, intervalMs);
7297
+ timer.unref();
7298
+ return {
7299
+ stop: async () => {
7300
+ stopped = true;
7301
+ clearInterval(timer);
7302
+ await inFlight.catch(() => {
7303
+ });
7304
+ }
7305
+ };
7306
+ }
5660
7307
  async function startRelayDaemon(opts) {
5661
7308
  const handle = await startRelayServer(opts);
5662
7309
  const log = opts.logger ?? (() => {
@@ -5681,18 +7328,94 @@ async function startRelayDaemon(opts) {
5681
7328
  // then transitions creating → running without waiting for the 15s SSE ping.
5682
7329
  onStatusChange: () => handle.hubNotifier.notify()
5683
7330
  });
7331
+ const retention = startRetentionLoop({ store: handle.store, log });
5684
7332
  handle.setQueuePoke(() => {
5685
7333
  queue.poke?.();
5686
7334
  });
5687
7335
  return {
5688
7336
  handle,
5689
7337
  stop: async () => {
5690
- await Promise.allSettled([autopause.stop(), cloudKeepalive.stop(), queue.stop()]);
7338
+ await Promise.allSettled([
7339
+ autopause.stop(),
7340
+ cloudKeepalive.stop(),
7341
+ queue.stop(),
7342
+ retention.stop()
7343
+ ]);
5691
7344
  await handle.close();
5692
7345
  }
5693
7346
  };
5694
7347
  }
5695
7348
 
7349
+ // ../../packages/relay/dist/index.js
7350
+ var BOX_SSH_USER = "vscode";
7351
+ function normalizeRegistrationAgent(agent) {
7352
+ return agent === "claude" || agent === "codex" || agent === "opencode" ? agent : void 0;
7353
+ }
7354
+ function buildSshTarget(provider, sandboxId, publicHost) {
7355
+ if (!publicHost) return void 0;
7356
+ const dir = boxSshDirForProvider(provider, sandboxId);
7357
+ return {
7358
+ host: publicHost,
7359
+ user: BOX_SSH_USER,
7360
+ ...dir ? { identityFile: `${dir}/id_ed25519` } : {}
7361
+ };
7362
+ }
7363
+ function registrationToBoxRecord(reg, opts) {
7364
+ const provider = reg.backend ?? "docker";
7365
+ const sandboxId = reg.sandboxId ?? reg.boxId;
7366
+ const { existing, projectRoot, projectIndex, controlPlaneUrl, freshToken } = opts;
7367
+ const branch = reg.worktrees?.[0]?.branch ?? `agentbox/${reg.name}`;
7368
+ const sanctionedBranch = reg.worktrees?.[0]?.sanctionedBranch ?? branch;
7369
+ const gitWorktrees = projectRoot ? [
7370
+ {
7371
+ kind: "root",
7372
+ branch,
7373
+ sanctionedBranch,
7374
+ containerPath: "/workspace",
7375
+ hostMainRepo: projectRoot,
7376
+ gitWorktreePath: "",
7377
+ relPathFromWorkspace: ""
7378
+ }
7379
+ ] : void 0;
7380
+ return {
7381
+ id: existing?.id ?? reg.boxId,
7382
+ name: reg.name,
7383
+ displayName: existing?.displayName,
7384
+ provider,
7385
+ container: `cloud:${sandboxId}`,
7386
+ image: reg.image ?? existing?.image ?? "",
7387
+ workspacePath: projectRoot ?? existing?.workspacePath ?? "/workspace",
7388
+ projectRoot,
7389
+ projectIndex,
7390
+ // Tokens are regenerated only for a fresh adoption; a re-adopt keeps the
7391
+ // box's live tokens (already injected in the running box).
7392
+ relayToken: existing?.relayToken ?? reg.token ?? freshToken(),
7393
+ lastAgent: normalizeRegistrationAgent(reg.agent) ?? existing?.lastAgent,
7394
+ gitWorktrees,
7395
+ createdAt: reg.createdAt ?? existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
7396
+ ssh: buildSshTarget(provider, sandboxId, reg.publicHost) ?? existing?.ssh,
7397
+ cloud: {
7398
+ ...existing?.cloud,
7399
+ backend: provider,
7400
+ sandboxId,
7401
+ image: reg.image ?? existing?.cloud?.image,
7402
+ webPort: reg.webPort ?? existing?.cloud?.webPort,
7403
+ publicHost: reg.publicHost ?? existing?.cloud?.publicHost,
7404
+ bridgeToken: reg.bridgeToken ?? existing?.cloud?.bridgeToken ?? freshToken(),
7405
+ relayPreviewUrl: reg.previewUrl ?? existing?.cloud?.relayPreviewUrl,
7406
+ relayPreviewToken: reg.previewToken ?? existing?.cloud?.relayPreviewToken,
7407
+ workspaceBranch: branch,
7408
+ sanctionedBranch,
7409
+ lastState: existing?.cloud?.lastState ?? "running",
7410
+ topology: "control-plane",
7411
+ controlPlaneUrl,
7412
+ // A hub-created box clones in-box from a leased URL — it shares no fork
7413
+ // base with a PC, so the session-start live resync must skip it.
7414
+ hostSeeded: void 0
7415
+ }
7416
+ };
7417
+ }
7418
+
5696
7419
  // ../../packages/sandbox-docker/dist/index.js
5697
7420
  import { readdir as readdir6, rm as rm6, stat as stat8 } from "fs/promises";
5698
7421
  import { join as join14 } from "path";
@@ -5703,7 +7426,7 @@ import { mkdir as mkdir7 } from "fs/promises";
5703
7426
  import { dirname as dirname4, join as join16 } from "path";
5704
7427
  import { spawn as spawn22 } from "child_process";
5705
7428
  import { existsSync as existsSync4, openSync as openSync22 } from "fs";
5706
- import { mkdir as mkdir8, readFile as readFile7, unlink as unlink22, writeFile as writeFile4 } from "fs/promises";
7429
+ import { mkdir as mkdir8, readFile as readFile7, unlink as unlink22, writeFile as writeFile42 } from "fs/promises";
5707
7430
  import { homedir as homedir12 } from "os";
5708
7431
  import { dirname as dirname5, join as join17, resolve as resolve5 } from "path";
5709
7432
  import { setTimeout as delay3 } from "timers/promises";
@@ -5948,9 +7671,9 @@ async function streamTarPipe(producerFile, producerArgs, consumerFile, consumerA
5948
7671
  }
5949
7672
  async function uploadOneToBox(box, hostSrc, boxDst, exclude) {
5950
7673
  const srcAbs = resolve(hostSrc);
5951
- if (!existsSync2(srcAbs)) throw new Error(`source not found: ${hostSrc}`);
7674
+ if (!existsSync3(srcAbs)) throw new Error(`source not found: ${hostSrc}`);
5952
7675
  const srcBasename = basename(srcAbs);
5953
- const srcParent = dirname(srcAbs);
7676
+ const srcParent = dirname3(srcAbs);
5954
7677
  let boxParent;
5955
7678
  let finalName;
5956
7679
  if (boxDst.endsWith("/")) {
@@ -6048,15 +7771,15 @@ async function downloadOneFromBox(box, boxSrc, hostDst, exclude) {
6048
7771
  const dstAbs = resolve(hostDst);
6049
7772
  let hostParent;
6050
7773
  let finalName;
6051
- const dstExists = existsSync2(dstAbs);
7774
+ const dstExists = existsSync3(dstAbs);
6052
7775
  if (hostDst.endsWith("/") || dstExists && statSync(dstAbs).isDirectory()) {
6053
7776
  hostParent = dstAbs;
6054
7777
  finalName = srcBasename;
6055
7778
  } else {
6056
- hostParent = dirname(dstAbs);
7779
+ hostParent = dirname3(dstAbs);
6057
7780
  finalName = basename(dstAbs);
6058
7781
  }
6059
- mkdirSync(hostParent, { recursive: true });
7782
+ mkdirSync2(hostParent, { recursive: true });
6060
7783
  const finalPath = posix.join(hostParent, finalName);
6061
7784
  const [packed, extracted] = await streamTarPipe(
6062
7785
  "docker",
@@ -6100,7 +7823,7 @@ async function uploadToBox(box, hostSrcs, boxDst, exclude) {
6100
7823
  if (hostSrcs.length === 1) return uploadOneToBox(box, hostSrcs[0], boxDst, exclude);
6101
7824
  const absSrcs = hostSrcs.map((s) => {
6102
7825
  const a = resolve(s);
6103
- if (!existsSync2(a)) throw new Error(`source not found: ${s}`);
7826
+ if (!existsSync3(a)) throw new Error(`source not found: ${s}`);
6104
7827
  return a;
6105
7828
  });
6106
7829
  const boxDir = await resolveBoxDestDir(box, boxDst);
@@ -6112,7 +7835,7 @@ async function uploadToBox(box, hostSrcs, boxDst, exclude) {
6112
7835
  if (mk.exitCode !== 0) {
6113
7836
  throw new Error(`mkdir -p ${boxDir} in box failed: ${asText(mk.stderr).slice(0, 300)}`);
6114
7837
  }
6115
- for (const [parent, basenames] of groupByParent(absSrcs, dirname, basename)) {
7838
+ for (const [parent, basenames] of groupByParent(absSrcs, dirname3, basename)) {
6116
7839
  const [packed, extracted] = await streamTarPipe(
6117
7840
  "tar",
6118
7841
  ["-C", parent, "-cf", "-", ...tarExcludeArgs(exclude), ...basenames],
@@ -6165,13 +7888,13 @@ async function uploadToBox(box, hostSrcs, boxDst, exclude) {
6165
7888
  async function downloadFromBox(box, boxSrcs, hostDst, exclude) {
6166
7889
  if (boxSrcs.length === 1) return downloadOneFromBox(box, boxSrcs[0], hostDst, exclude);
6167
7890
  const dstAbs = resolve(hostDst);
6168
- const dstExists = existsSync2(dstAbs);
7891
+ const dstExists = existsSync3(dstAbs);
6169
7892
  if (!hostDst.endsWith("/") && !(dstExists && statSync(dstAbs).isDirectory())) {
6170
7893
  throw new Error(
6171
7894
  `cannot copy multiple sources to '${hostDst}': destination is not a directory (add a trailing slash, e.g. ${hostDst}/)`
6172
7895
  );
6173
7896
  }
6174
- mkdirSync(dstAbs, { recursive: true });
7897
+ mkdirSync2(dstAbs, { recursive: true });
6175
7898
  for (const [parent, basenames] of groupByParent(boxSrcs, posixDirname, posix.basename)) {
6176
7899
  const [packed, extracted] = await streamTarPipe(
6177
7900
  "docker",
@@ -6237,7 +7960,7 @@ function createDockerSyncTransport(init) {
6237
7960
  }
6238
7961
  await transport.applyTarball(localTar, boxDestDir, opts);
6239
7962
  } finally {
6240
- await rm3(stage, { recursive: true, force: true });
7963
+ await rm4(stage, { recursive: true, force: true });
6241
7964
  }
6242
7965
  },
6243
7966
  async pushFile(hostSrcPath, boxDestPath, opts) {
@@ -6331,7 +8054,7 @@ async function getDockerContext() {
6331
8054
  const ctx = (result.stdout ?? "").trim();
6332
8055
  return ctx.length > 0 ? ctx : void 0;
6333
8056
  }
6334
- var BOXES_ROOT = join23(homedir3(), ".agentbox", "boxes");
8057
+ var BOXES_ROOT = join24(homedir3(), ".agentbox", "boxes");
6335
8058
  function boxDirSegment(box) {
6336
8059
  const mnemonic = sanitizeMnemonic(box.name);
6337
8060
  const n = box.projectIndex;
@@ -6341,10 +8064,10 @@ function boxDirSegment(box) {
6341
8064
  return `${box.id}-${mnemonic}`;
6342
8065
  }
6343
8066
  function boxRunDirFor2(box) {
6344
- return join23(BOXES_ROOT, boxDirSegment(box));
8067
+ return join24(BOXES_ROOT, boxDirSegment(box));
6345
8068
  }
6346
8069
  function boxStatusPathFor2(box) {
6347
- return join23(boxRunDirFor2(box), "status.json");
8070
+ return join24(boxRunDirFor2(box), "status.json");
6348
8071
  }
6349
8072
  async function readBoxStatus(box) {
6350
8073
  try {
@@ -6357,13 +8080,13 @@ async function readBoxStatus(box) {
6357
8080
  }
6358
8081
  }
6359
8082
  function orbstackVolumePath(volume, ...sub) {
6360
- return join23(homedir3(), "OrbStack", "docker", "volumes", volume, ...sub);
8083
+ return join24(homedir3(), "OrbStack", "docker", "volumes", volume, ...sub);
6361
8084
  }
6362
8085
  async function getHostPaths(record) {
6363
8086
  const boxDir = boxRunDirFor2(record);
6364
8087
  return {
6365
8088
  boxDir,
6366
- mergedExport: join23(boxDir, "workspace")
8089
+ mergedExport: join24(boxDir, "workspace")
6367
8090
  };
6368
8091
  }
6369
8092
  async function hasContainerPath(container, path) {
@@ -6373,7 +8096,7 @@ async function hasContainerPath(container, path) {
6373
8096
  async function refreshExport(record, opts = {}) {
6374
8097
  const paths = await getHostPaths(record);
6375
8098
  const excludeNodeModules = !opts.includeNodeModules;
6376
- await mkdir3(paths.mergedExport, { recursive: true });
8099
+ await mkdir4(paths.mergedExport, { recursive: true });
6377
8100
  const bindAvailable = await hasContainerPath(record.container, CONTAINER_EXPORT_MERGED);
6378
8101
  if (bindAvailable) {
6379
8102
  const args = ["rsync", "-a", "--delete"];
@@ -6487,7 +8210,7 @@ async function pullToHost(record, opts = {}) {
6487
8210
  let scratchDir;
6488
8211
  if (opts.noRefresh) {
6489
8212
  scratchDir = paths.mergedExport;
6490
- await mkdir3(scratchDir, { recursive: true });
8213
+ await mkdir4(scratchDir, { recursive: true });
6491
8214
  } else {
6492
8215
  const refreshed = await refreshExport(record, {
6493
8216
  includeNodeModules: opts.includeNodeModules
@@ -6566,7 +8289,7 @@ async function openInFinder(record, opts) {
6566
8289
  if (opts.noRefresh) {
6567
8290
  const paths = await getHostPaths(record);
6568
8291
  hostPath = paths.mergedExport;
6569
- await mkdir3(hostPath, { recursive: true });
8292
+ await mkdir4(hostPath, { recursive: true });
6570
8293
  } else {
6571
8294
  const refreshed = await refreshExport(record, opts);
6572
8295
  hostPath = refreshed.hostPath;
@@ -6595,17 +8318,17 @@ async function carrySourceHash(entry) {
6595
8318
  if (entry.kind === "missing") return void 0;
6596
8319
  try {
6597
8320
  if (entry.kind === "file") {
6598
- return createHash2("sha256").update(await readFile4(entry.absSrc)).digest("hex");
8321
+ return createHash3("sha256").update(await readFile4(entry.absSrc)).digest("hex");
6599
8322
  }
6600
8323
  const exclude = entry.exclude ?? [];
6601
- const h = createHash2("sha256");
8324
+ const h = createHash3("sha256");
6602
8325
  const walk = async (dir, rel) => {
6603
8326
  const names = (await readdir3(dir)).sort();
6604
8327
  for (const name of names) {
6605
8328
  const relPath = rel ? `${rel}/${name}` : name;
6606
8329
  if (carryRelExcluded(relPath, exclude)) continue;
6607
- const abs = join23(dir, name);
6608
- const st = await stat(abs);
8330
+ const abs = join24(dir, name);
8331
+ const st = await stat3(abs);
6609
8332
  if (st.isDirectory()) {
6610
8333
  h.update(`d\0${relPath}
6611
8334
  `);
@@ -6683,7 +8406,7 @@ async function copyOneEntry(container, entry) {
6683
8406
  throw new Error(`mkdir -p ${parentDir} failed: ${String(mkdir9.stderr).slice(0, 300)}`);
6684
8407
  }
6685
8408
  if (!plan.isDir) {
6686
- const srcDir = dirname2(entry.absSrc);
8409
+ const srcDir = dirname22(entry.absSrc);
6687
8410
  const [packed, extract] = await streamTarPipe(
6688
8411
  "tar",
6689
8412
  ["-C", srcDir, "-cf", "-", fileBase],
@@ -6754,13 +8477,13 @@ async function copyOneEntry(container, entry) {
6754
8477
  }
6755
8478
  }
6756
8479
  if (mode) {
6757
- const chmod2 = await execa(
8480
+ const chmod22 = await execa(
6758
8481
  "docker",
6759
8482
  ["exec", "--user", "0:0", container, "chmod", "-R", mode, boxDest],
6760
8483
  { reject: false }
6761
8484
  );
6762
- if (chmod2.exitCode !== 0) {
6763
- throw new Error(`chmod failed: ${String(chmod2.stderr).slice(0, 300)}`);
8485
+ if (chmod22.exitCode !== 0) {
8486
+ throw new Error(`chmod failed: ${String(chmod22.stderr).slice(0, 300)}`);
6764
8487
  }
6765
8488
  }
6766
8489
  const chown = await execa(
@@ -6818,13 +8541,13 @@ async function ensureClaudeVolume(spec, opts) {
6818
8541
  await ensureVolume(spec.volume);
6819
8542
  const created = !existed;
6820
8543
  if (!opts.syncFromHost) return { created, synced: false };
6821
- const hostClaude = join3(homedir2(), ".claude");
8544
+ const hostClaude = join32(homedir2(), ".claude");
6822
8545
  if (!await pathExists(hostClaude)) return { created, synced: false };
6823
- const hostClaudeJson = join3(homedir2(), ".claude.json");
8546
+ const hostClaudeJson = join32(homedir2(), ".claude.json");
6824
8547
  const hasJson = await pathExists(hostClaudeJson);
6825
8548
  const seedClaudeJson = !await volumeHasClaudeJson(spec.volume, opts.image);
6826
8549
  const hostHome = homedir2();
6827
- const hostAgents = join3(homedir2(), ".agents");
8550
+ const hostAgents = join32(homedir2(), ".agents");
6828
8551
  const hasAgents = await pathExists(hostAgents);
6829
8552
  const args = [
6830
8553
  "run",
@@ -6842,15 +8565,15 @@ async function ensureClaudeVolume(spec, opts) {
6842
8565
  ];
6843
8566
  if (hasJson && seedClaudeJson) args.push("-v", `${hostClaudeJson}:/src-claude-json:ro`);
6844
8567
  if (hasAgents) args.push("-v", `${hostAgents}:/.agents:ro`);
6845
- const filterDir = await mkdtemp2(join3(tmpdir2(), "agentbox-claude-filter-"));
8568
+ const filterDir = await mkdtemp2(join32(tmpdir2(), "agentbox-claude-filter-"));
6846
8569
  let filteredHookCount = 0;
6847
8570
  let installMethodFixed = false;
6848
8571
  let aliasedProjectKey = false;
6849
8572
  let workspaceTrusted = false;
6850
8573
  try {
6851
8574
  const settingsResult = await maybeFilterTo(
6852
- join3(hostClaude, "settings.json"),
6853
- join3(filterDir, "settings.json"),
8575
+ join32(hostClaude, "settings.json"),
8576
+ join32(filterDir, "settings.json"),
6854
8577
  hostHome
6855
8578
  );
6856
8579
  filteredHookCount += settingsResult.removedHooks;
@@ -6858,7 +8581,7 @@ async function ensureClaudeVolume(spec, opts) {
6858
8581
  } else if (hasJson) {
6859
8582
  const jsonResult = await maybeFilterTo(
6860
8583
  hostClaudeJson,
6861
- join3(filterDir, "_claude.json"),
8584
+ join32(filterDir, "_claude.json"),
6862
8585
  hostHome,
6863
8586
  {
6864
8587
  setInstallMethodNative: true,
@@ -6871,8 +8594,8 @@ async function ensureClaudeVolume(spec, opts) {
6871
8594
  aliasedProjectKey = jsonResult.aliasedProjectKey;
6872
8595
  workspaceTrusted = jsonResult.workspaceTrusted;
6873
8596
  } else {
6874
- await writeFile3(
6875
- join3(filterDir, "_claude.json"),
8597
+ await writeFile4(
8598
+ join32(filterDir, "_claude.json"),
6876
8599
  JSON.stringify(
6877
8600
  {
6878
8601
  installMethod: "native",
@@ -7004,7 +8727,7 @@ async function maybeFilterTo(src, dest, hostHome, opts = {}) {
7004
8727
  if (filtered.removedCommands.length === 0 && !installFixed && !aliased && !trusted) {
7005
8728
  return zero;
7006
8729
  }
7007
- await writeFile3(dest, JSON.stringify(working, null, 2));
8730
+ await writeFile4(dest, JSON.stringify(working, null, 2));
7008
8731
  return {
7009
8732
  removedHooks: filtered.removedCommands.length,
7010
8733
  installMethodFixed: installFixed,
@@ -7068,39 +8791,39 @@ async function readReferencedPluginKeys(installedPluginsJsonPath) {
7068
8791
  }
7069
8792
  async function scanPluginCacheForRebuild(cacheRoot) {
7070
8793
  const referenced = await readReferencedPluginKeys(
7071
- join3(cacheRoot, "..", "installed_plugins.json")
8794
+ join32(cacheRoot, "..", "installed_plugins.json")
7072
8795
  );
7073
8796
  let marketplaces;
7074
8797
  try {
7075
- marketplaces = await readdir2(cacheRoot, { withFileTypes: true });
8798
+ marketplaces = await readdir22(cacheRoot, { withFileTypes: true });
7076
8799
  } catch {
7077
8800
  return false;
7078
8801
  }
7079
8802
  for (const m of marketplaces) {
7080
8803
  if (!m.isDirectory()) continue;
7081
- const mPath = join3(cacheRoot, m.name);
8804
+ const mPath = join32(cacheRoot, m.name);
7082
8805
  let plugins;
7083
8806
  try {
7084
- plugins = await readdir2(mPath, { withFileTypes: true });
8807
+ plugins = await readdir22(mPath, { withFileTypes: true });
7085
8808
  } catch {
7086
8809
  continue;
7087
8810
  }
7088
8811
  for (const p of plugins) {
7089
8812
  if (!p.isDirectory()) continue;
7090
- const pPath = join3(mPath, p.name);
8813
+ const pPath = join32(mPath, p.name);
7091
8814
  let versions;
7092
8815
  try {
7093
- versions = await readdir2(pPath, { withFileTypes: true });
8816
+ versions = await readdir22(pPath, { withFileTypes: true });
7094
8817
  } catch {
7095
8818
  continue;
7096
8819
  }
7097
8820
  for (const v of versions) {
7098
8821
  if (!v.isDirectory()) continue;
7099
8822
  if (referenced.size > 0 && !referenced.has(`${m.name}/${p.name}/${v.name}`)) continue;
7100
- const vPath = join3(pPath, v.name);
7101
- if (!await isFile(join3(vPath, "package.json"))) continue;
7102
- if (await isFile(join3(vPath, PLUGIN_INSTALLED_MARKER))) continue;
7103
- if (await isRecentFailMarker(join3(vPath, PLUGIN_FAILED_MARKER))) continue;
8823
+ const vPath = join32(pPath, v.name);
8824
+ if (!await isFile(join32(vPath, "package.json"))) continue;
8825
+ if (await isFile(join32(vPath, PLUGIN_INSTALLED_MARKER))) continue;
8826
+ if (await isRecentFailMarker(join32(vPath, PLUGIN_FAILED_MARKER))) continue;
7104
8827
  return true;
7105
8828
  }
7106
8829
  }
@@ -7512,7 +9235,7 @@ async function claudeSessionInfo(container, sessionName) {
7512
9235
  return { running: true, sessionName: name, startedAt };
7513
9236
  }
7514
9237
  async function pullClaudeExtras(spec, opts) {
7515
- const hostClaude = join3(homedir2(), ".claude");
9238
+ const hostClaude = join32(homedir2(), ".claude");
7516
9239
  const inv = await execa(
7517
9240
  "docker",
7518
9241
  ["run", "--rm", "--user", "0", "-v", `${spec.volume}:/src:ro`, opts.image, "sh", "-c", claudeInventoryScript("/src")],
@@ -7563,15 +9286,15 @@ async function pullClaudeExtras(spec, opts) {
7563
9286
  await writeClaudeMergedRegistries(plan);
7564
9287
  return { newItems, mergedRegistries, sourceRegistries };
7565
9288
  }
7566
- var CREDENTIALS_BACKUP_FILE = join42(STATE_DIR, "claude-credentials.json");
7567
- var CODEX_CREDENTIALS_BACKUP_FILE = join42(STATE_DIR, "codex-credentials.json");
7568
- var OPENCODE_CREDENTIALS_BACKUP_FILE = join42(STATE_DIR, "opencode-credentials.json");
9289
+ var CREDENTIALS_BACKUP_FILE = join42(STATE_DIR2, "claude-credentials.json");
9290
+ var CODEX_CREDENTIALS_BACKUP_FILE = join42(STATE_DIR2, "codex-credentials.json");
9291
+ var OPENCODE_CREDENTIALS_BACKUP_FILE = join42(STATE_DIR2, "opencode-credentials.json");
7569
9292
  function parseExtractResult(stdout) {
7570
9293
  return { copied: /\bCOPIED=yes\b/.test(stdout) };
7571
9294
  }
7572
9295
  async function extractVolumeAuthToBackup(opts) {
7573
9296
  try {
7574
- await mkdir22(STATE_DIR, { recursive: true });
9297
+ await mkdir22(STATE_DIR2, { recursive: true });
7575
9298
  const script = 'COPIED=no; if [ -s /dst/auth.json ]; then cp -a /dst/auth.json "/host-state/$DEST" && COPIED=yes; fi; echo "COPIED=$COPIED"';
7576
9299
  const { stdout } = await execa("docker", [
7577
9300
  "run",
@@ -7581,7 +9304,7 @@ async function extractVolumeAuthToBackup(opts) {
7581
9304
  "-v",
7582
9305
  `${opts.volume}:/dst`,
7583
9306
  "-v",
7584
- `${STATE_DIR}:/host-state`,
9307
+ `${STATE_DIR2}:/host-state`,
7585
9308
  "-e",
7586
9309
  // Pass the destination filename via env so the path isn't interpolated
7587
9310
  // into the script string (keeps the docker arg list static + injection-safe).
@@ -7592,7 +9315,7 @@ async function extractVolumeAuthToBackup(opts) {
7592
9315
  script
7593
9316
  ]);
7594
9317
  const result = parseExtractResult(stdout);
7595
- if (result.copied) await chmod(opts.backupFile, 384).catch(() => {
9318
+ if (result.copied) await chmod2(opts.backupFile, 384).catch(() => {
7596
9319
  });
7597
9320
  return result;
7598
9321
  } catch {
@@ -7662,7 +9385,7 @@ echo "EXTRACTED=$EXTRACTED SEEDED=$SEEDED VOLREAL=$VOL_REAL"
7662
9385
  `;
7663
9386
  async function syncClaudeCredentials(spec, opts) {
7664
9387
  try {
7665
- await mkdir22(STATE_DIR, { recursive: true });
9388
+ await mkdir22(STATE_DIR2, { recursive: true });
7666
9389
  const { stdout } = await execa("docker", [
7667
9390
  "run",
7668
9391
  "--rm",
@@ -7671,7 +9394,7 @@ async function syncClaudeCredentials(spec, opts) {
7671
9394
  "-v",
7672
9395
  `${spec.volume}:/dst`,
7673
9396
  "-v",
7674
- `${STATE_DIR}:/host-state`,
9397
+ `${STATE_DIR2}:/host-state`,
7675
9398
  "-e",
7676
9399
  `ISOLATE=${opts.isolate ? "yes" : "no"}`,
7677
9400
  opts.image,
@@ -7681,7 +9404,7 @@ async function syncClaudeCredentials(spec, opts) {
7681
9404
  ]);
7682
9405
  const result = parseSyncResult(stdout);
7683
9406
  if (result.direction === "extracted") {
7684
- await chmod(CREDENTIALS_BACKUP_FILE, 384).catch(() => {
9407
+ await chmod2(CREDENTIALS_BACKUP_FILE, 384).catch(() => {
7685
9408
  });
7686
9409
  }
7687
9410
  return result;
@@ -7735,7 +9458,7 @@ function resolveCodexVolume(opts) {
7735
9458
  }
7736
9459
  async function pathExists2(p) {
7737
9460
  try {
7738
- await stat3(p);
9461
+ await stat32(p);
7739
9462
  return true;
7740
9463
  } catch {
7741
9464
  return false;
@@ -7879,7 +9602,7 @@ async function reconcileVolumeCodexConfig(volume, image) {
7879
9602
  if (!await pathExists2(hostConfig)) {
7880
9603
  base = MINIMAL_TRUSTED_CODEX_CONFIG;
7881
9604
  } else {
7882
- const hostText = await readFile32(hostConfig, "utf8");
9605
+ const hostText = await readFile33(hostConfig, "utf8");
7883
9606
  try {
7884
9607
  base = sanitizeCodexConfigForBox(hostText).text;
7885
9608
  } catch {
@@ -7895,7 +9618,7 @@ async function reconcileVolumeCodexConfig(volume, image) {
7895
9618
  return { reconciled: false };
7896
9619
  }
7897
9620
  }
7898
- async function writeVolumeCodexConfig(volume, image, text, keptMarketplaces) {
9621
+ async function writeVolumeCodexConfig(volume, image, text3, keptMarketplaces) {
7899
9622
  const purge = keptMarketplaces === null ? "" : ` && ${buildCodexOrphanPurgeScript(keptMarketplaces)}`;
7900
9623
  await execa(
7901
9624
  "docker",
@@ -7912,7 +9635,7 @@ async function writeVolumeCodexConfig(volume, image, text, keptMarketplaces) {
7912
9635
  "-c",
7913
9636
  "cat > /dst/config.toml.tmp && chown 1000:1000 /dst/config.toml.tmp && mv /dst/config.toml.tmp /dst/config.toml" + purge
7914
9637
  ],
7915
- { input: text }
9638
+ { input: text3 }
7916
9639
  );
7917
9640
  }
7918
9641
  var CODEX_FORWARDED_ENV_KEYS = ["OPENAI_API_KEY"];
@@ -9144,6 +10867,11 @@ var SUB_VERSION = ["--version"];
9144
10867
  var SUB_ALIAS = "alias";
9145
10868
  var SUB_ALIAS_REMOVE = "--remove";
9146
10869
  var SUB_GET = "get";
10870
+ var SUB_SERVICE_INSTALL = ["service", "install"];
10871
+ var SUB_SERVICE_STATUS = ["service", "status"];
10872
+ var SUB_SERVICE_UNINSTALL = ["service", "uninstall"];
10873
+ var PORTLESS_PROBE_NAME = "agentbox-probe";
10874
+ var PORTLESS_LAUNCHD_PLIST = "/Library/LaunchDaemons/sh.portless.proxy.plist";
9147
10875
  var PORTLESS_PROXY_PORT = 1355;
9148
10876
  var cached = null;
9149
10877
  async function detectPortless() {
@@ -9183,15 +10911,24 @@ async function portlessUnalias(name) {
9183
10911
  return false;
9184
10912
  }
9185
10913
  }
10914
+ function composePortlessUrl(name, mode) {
10915
+ const scheme = mode.tls ? "https" : "http";
10916
+ const isDefaultPort = mode.tls ? mode.port === 443 : mode.port === 80;
10917
+ return `${scheme}://${name}.localhost${isDefaultPort ? "" : `:${String(mode.port)}`}`;
10918
+ }
9186
10919
  async function portlessGetUrl(name) {
9187
- const fallback = `https://${name}.localhost`;
10920
+ const expectedHost = `${name}.localhost`;
9188
10921
  try {
9189
10922
  const r = await execa(PORTLESS_BIN, [SUB_GET, name], { reject: false });
9190
10923
  const out = (r.stdout ?? "").trim();
9191
- if (r.exitCode === 0 && /^https?:\/\//.test(out)) return out;
10924
+ if (r.exitCode === 0 && /^https?:\/\//.test(out)) {
10925
+ const host = new URL(out).hostname;
10926
+ if (host === expectedHost) return out;
10927
+ }
9192
10928
  } catch {
9193
10929
  }
9194
- return fallback;
10930
+ const mode = await portlessConfiguredMode();
10931
+ return mode === null ? `https://${expectedHost}` : composePortlessUrl(name, mode);
9195
10932
  }
9196
10933
  function portlessInstallHint() {
9197
10934
  return "npm install -g portless";
@@ -9199,7 +10936,10 @@ function portlessInstallHint() {
9199
10936
  function portlessStartHint() {
9200
10937
  return "portless proxy start";
9201
10938
  }
9202
- function portlessDoctorRow(state) {
10939
+ function portlessServiceHint() {
10940
+ return "agentbox install portless";
10941
+ }
10942
+ function portlessDoctorRow(state, service) {
9203
10943
  if (!state.installed) {
9204
10944
  return {
9205
10945
  label: "portless",
@@ -9213,14 +10953,23 @@ function portlessDoctorRow(state) {
9213
10953
  label: "portless",
9214
10954
  status: "warn",
9215
10955
  detail: "installed, proxy not running",
9216
- hint: `start it: \`${portlessStartHint()}\``
10956
+ // The OS service is the hint that actually sticks: `proxy start` has to be
10957
+ // re-run after every reboot, which is how a host ends up here in the first
10958
+ // place. AgentBox also starts a proxy on demand, so this is a nudge, not a
10959
+ // blocker.
10960
+ hint: `make it permanent: \`${portlessServiceHint()}\` (or one-shot: \`${portlessStartHint()}\`)`
9217
10961
  };
9218
10962
  }
9219
- return {
9220
- label: "portless",
9221
- status: "ok",
9222
- detail: state.version ? `running \xB7 v${state.version}` : "running"
9223
- };
10963
+ const running = state.version ? `running \xB7 v${state.version}` : "running";
10964
+ if (service?.installed === false) {
10965
+ return {
10966
+ label: "portless",
10967
+ status: "ok",
10968
+ detail: `${running} \xB7 no OS service (won't survive a reboot)`,
10969
+ hint: `optional: \`${portlessServiceHint()}\` to start it at boot`
10970
+ };
10971
+ }
10972
+ return { label: "portless", status: "ok", detail: running };
9224
10973
  }
9225
10974
  function portlessBrowserEnv(boxName, opts) {
9226
10975
  return {
@@ -9236,13 +10985,11 @@ async function installPortless() {
9236
10985
  return false;
9237
10986
  }
9238
10987
  }
9239
- async function startPortlessProxy() {
10988
+ async function startPortlessProxy(port = PORTLESS_PROXY_PORT) {
9240
10989
  try {
9241
- const r = await execa(
9242
- PORTLESS_BIN,
9243
- ["proxy", "start", "--no-tls", "-p", String(PORTLESS_PROXY_PORT)],
9244
- { reject: false }
9245
- );
10990
+ const r = await execa(PORTLESS_BIN, ["proxy", "start", "--no-tls", "-p", String(port)], {
10991
+ reject: false
10992
+ });
9246
10993
  return r.exitCode === 0;
9247
10994
  } catch {
9248
10995
  return false;
@@ -9283,6 +11030,85 @@ async function startPortlessProxyRoot() {
9283
11030
  return "failed";
9284
11031
  }
9285
11032
  }
11033
+ async function portlessServiceStatus() {
11034
+ try {
11035
+ const r = await execa(PORTLESS_BIN, SUB_SERVICE_STATUS, { reject: false });
11036
+ const m = /^\s*Installed:\s*(yes|no)\s*$/im.exec(r.stdout ?? "");
11037
+ if (m) return { installed: m[1]?.toLowerCase() === "yes" };
11038
+ } catch {
11039
+ }
11040
+ if (process.platform === "darwin") return { installed: existsSync22(PORTLESS_LAUNCHD_PLIST) };
11041
+ return { installed: false };
11042
+ }
11043
+ async function installPortlessService() {
11044
+ const bin = await resolvePortlessBin();
11045
+ try {
11046
+ if (process.platform === "darwin") {
11047
+ const q = shellSingleQuote(bin);
11048
+ const shellCmd = `${q} ${SUB_SERVICE_INSTALL.join(" ")} && ${q} trust`;
11049
+ const script = `do shell script "${escapeForAppleScript(shellCmd)}" with administrator privileges with prompt "AgentBox wants to start the Portless proxy at login."`;
11050
+ const r2 = await execa("osascript", ["-e", script], { reject: false });
11051
+ if (r2.exitCode === 0) return "started";
11052
+ if (/User canceled|-128/i.test(r2.stderr ?? "")) return "cancelled";
11053
+ return "failed";
11054
+ }
11055
+ const r = await execa(bin, SUB_SERVICE_INSTALL, { reject: false, stdio: "inherit" });
11056
+ if (r.exitCode !== 0) return "failed";
11057
+ await execa(bin, ["trust"], { reject: false, stdio: "inherit" });
11058
+ return "started";
11059
+ } catch {
11060
+ return "failed";
11061
+ }
11062
+ }
11063
+ async function uninstallPortlessService() {
11064
+ const bin = await resolvePortlessBin();
11065
+ try {
11066
+ if (process.platform === "darwin") {
11067
+ const shellCmd = `${shellSingleQuote(bin)} ${SUB_SERVICE_UNINSTALL.join(" ")}`;
11068
+ const script = `do shell script "${escapeForAppleScript(shellCmd)}" with administrator privileges with prompt "AgentBox wants to remove the Portless startup service."`;
11069
+ const r2 = await execa("osascript", ["-e", script], { reject: false });
11070
+ return r2.exitCode === 0;
11071
+ }
11072
+ const r = await execa(bin, SUB_SERVICE_UNINSTALL, { reject: false, stdio: "inherit" });
11073
+ return r.exitCode === 0;
11074
+ } catch {
11075
+ return false;
11076
+ }
11077
+ }
11078
+ async function portlessConfiguredMode() {
11079
+ try {
11080
+ const r = await execa(PORTLESS_BIN, [SUB_GET, PORTLESS_PROBE_NAME], { reject: false });
11081
+ const out = (r.stdout ?? "").trim();
11082
+ if (r.exitCode !== 0 || !/^https?:\/\//.test(out)) return null;
11083
+ const u = new URL(out);
11084
+ const tls = u.protocol === "https:";
11085
+ const port = u.port ? Number.parseInt(u.port, 10) : tls ? 443 : 80;
11086
+ return Number.isFinite(port) ? { port, tls } : null;
11087
+ } catch {
11088
+ return null;
11089
+ }
11090
+ }
11091
+ function needsRoot(port) {
11092
+ return port < 1024;
11093
+ }
11094
+ async function ensurePortlessProxy(opts = {}) {
11095
+ let state = await detectPortless();
11096
+ if (!state.installed || state.proxyRunning) return state;
11097
+ const mode = await portlessConfiguredMode();
11098
+ const wantsRoot = mode === null || needsRoot(mode.port);
11099
+ if (wantsRoot) {
11100
+ if (opts.allowRootPrompt !== true) return state;
11101
+ await startPortlessProxyRoot();
11102
+ resetPortlessCache();
11103
+ state = await detectPortless();
11104
+ if (state.proxyRunning) return state;
11105
+ }
11106
+ await startPortlessProxy(
11107
+ mode !== null && !needsRoot(mode.port) ? mode.port : PORTLESS_PROXY_PORT
11108
+ );
11109
+ resetPortlessCache();
11110
+ return detectPortless();
11111
+ }
9286
11112
  function portlessStateDirCandidates() {
9287
11113
  const env = process.env["PORTLESS_STATE_DIR"];
9288
11114
  if (env && env.trim().length > 0) return [env.trim()];
@@ -9324,14 +11150,30 @@ async function resolvePortlessHostStateDir(override) {
9324
11150
  if (existsSync22("/tmp/portless")) return "/tmp/portless";
9325
11151
  return home;
9326
11152
  }
11153
+ async function tcpAccepts(port, timeoutMs = 400) {
11154
+ return new Promise((resolve6) => {
11155
+ const socket = connect({ host: "127.0.0.1", port });
11156
+ const done = (result) => {
11157
+ socket.destroy();
11158
+ resolve6(result);
11159
+ };
11160
+ socket.setTimeout(timeoutMs);
11161
+ socket.once("connect", () => {
11162
+ done(true);
11163
+ });
11164
+ socket.once("timeout", () => {
11165
+ done(false);
11166
+ });
11167
+ socket.once("error", () => {
11168
+ done(false);
11169
+ });
11170
+ });
11171
+ }
9327
11172
  async function isProxyRunning() {
9328
11173
  if (await findLivePortlessStateDir() !== null) return true;
9329
- try {
9330
- const r = await execa("pgrep", ["-f", "portless proxy"], { reject: false });
9331
- return r.exitCode === 0 && (r.stdout ?? "").trim().length > 0;
9332
- } catch {
9333
- return false;
9334
- }
11174
+ const mode = await portlessConfiguredMode();
11175
+ if (mode === null) return false;
11176
+ return tcpAccepts(mode.port);
9335
11177
  }
9336
11178
  var EXCLUDE_DIRS = /* @__PURE__ */ new Set([
9337
11179
  "node_modules",
@@ -9476,7 +11318,7 @@ async function removeCheckpoint(projectRoot, ref) {
9476
11318
  const dir = checkpointDir(projectRoot, ref);
9477
11319
  const manifest = await readManifest(dir);
9478
11320
  if (!manifest) return false;
9479
- await rm4(dir, { recursive: true, force: true });
11321
+ await rm42(dir, { recursive: true, force: true });
9480
11322
  await removeImage(manifest.image, { force: true });
9481
11323
  return true;
9482
11324
  }
@@ -9536,11 +11378,11 @@ var RUNTIME_ENV_BLOCKLIST = /* @__PURE__ */ new Set([
9536
11378
  function renderConfigDirectives(cfg) {
9537
11379
  const lines = [];
9538
11380
  for (const kv of cfg.Env ?? []) {
9539
- const eq = kv.indexOf("=");
9540
- if (eq <= 0) continue;
9541
- const k = kv.slice(0, eq);
11381
+ const eq2 = kv.indexOf("=");
11382
+ if (eq2 <= 0) continue;
11383
+ const k = kv.slice(0, eq2);
9542
11384
  if (RUNTIME_ENV_BLOCKLIST.has(k)) continue;
9543
- const v = kv.slice(eq + 1);
11385
+ const v = kv.slice(eq2 + 1);
9544
11386
  lines.push(`ENV ${k}=${dockerfileQuote(v)}`);
9545
11387
  }
9546
11388
  if (cfg.WorkingDir) lines.push(`WORKDIR ${cfg.WorkingDir}`);
@@ -9579,7 +11421,7 @@ async function createCheckpoint(opts) {
9579
11421
  }
9580
11422
  }
9581
11423
  const tag = checkpointImageTag(opts.projectRoot, name);
9582
- await mkdir4(dir, { recursive: true });
11424
+ await mkdir42(dir, { recursive: true });
9583
11425
  log(`running pre-commit cleanup in ${box.container}`);
9584
11426
  await runCleanup(box.container, log);
9585
11427
  if (type === "layered") {
@@ -9671,7 +11513,7 @@ async function flattenImage(sourceTag, destTag, log) {
9671
11513
  }
9672
11514
  } finally {
9673
11515
  await execa("docker", ["rm", "-f", tmpName], { reject: false });
9674
- await rm4(scratch, { recursive: true, force: true });
11516
+ await rm42(scratch, { recursive: true, force: true });
9675
11517
  }
9676
11518
  }
9677
11519
  var CheckpointError = class extends Error {
@@ -9755,10 +11597,10 @@ async function ensureHomeOwnedByVscode(container) {
9755
11597
  { reject: false }
9756
11598
  );
9757
11599
  }
9758
- var STATE_DIR2 = join11(homedir9(), ".agentbox");
9759
- var PID_FILE = join11(STATE_DIR2, "relay.pid");
9760
- var LOG_FILE = join11(STATE_DIR2, "relay.log");
9761
- var RELAY_HOME_DIR = join11(STATE_DIR2, "relay");
11600
+ var STATE_DIR22 = join11(homedir9(), ".agentbox");
11601
+ var PID_FILE = join11(STATE_DIR22, "relay.pid");
11602
+ var LOG_FILE = join11(STATE_DIR22, "relay.log");
11603
+ var RELAY_HOME_DIR = join11(STATE_DIR22, "relay");
9762
11604
  var PORT = DEFAULT_RELAY_PORT;
9763
11605
  var ENDPOINT = {
9764
11606
  // host.docker.internal is the Docker Desktop / OrbStack-supplied alias for
@@ -9779,7 +11621,7 @@ function shouldReclaimForVersion(health, currentVersion) {
9779
11621
  async function ensureRelay(opts = {}) {
9780
11622
  const log = opts.onLog ?? (() => {
9781
11623
  });
9782
- await mkdir5(STATE_DIR2, { recursive: true });
11624
+ await mkdir5(STATE_DIR22, { recursive: true });
9783
11625
  if (await containerExists(RELAY_CONTAINER_NAME)) {
9784
11626
  await removeContainer(RELAY_CONTAINER_NAME);
9785
11627
  log(`removed legacy relay container ${RELAY_CONTAINER_NAME}`);
@@ -9888,8 +11730,8 @@ async function spawnRelay(relayBin, cliEntry, log) {
9888
11730
  }
9889
11731
  function resolveRelayBin() {
9890
11732
  const override = process.env.AGENTBOX_RELAY_BIN;
9891
- if (override && existsSync3(override)) return override;
9892
- const here = dirname3(fileURLToPath(import.meta.url));
11733
+ if (override && existsSync32(override)) return override;
11734
+ const here = dirname32(fileURLToPath(import.meta.url));
9893
11735
  const candidates = [
9894
11736
  resolve3(here, "..", "runtime", "relay", "bin.cjs"),
9895
11737
  resolve3(here, "..", "..", "relay", "dist", "bin.cjs"),
@@ -9897,7 +11739,7 @@ function resolveRelayBin() {
9897
11739
  resolve3(here, "..", "..", "node_modules", "@agentbox", "relay", "dist", "bin.cjs")
9898
11740
  ];
9899
11741
  for (const c of candidates) {
9900
- if (existsSync3(c)) return c;
11742
+ if (existsSync32(c)) return c;
9901
11743
  }
9902
11744
  throw new Error(
9903
11745
  `could not locate @agentbox/relay bin; tried:
@@ -9906,8 +11748,8 @@ function resolveRelayBin() {
9906
11748
  }
9907
11749
  function resolveCliEntry() {
9908
11750
  const override = process.env.AGENTBOX_CLI_ENTRY;
9909
- if (override && existsSync3(override)) return override;
9910
- const here = dirname3(fileURLToPath(import.meta.url));
11751
+ if (override && existsSync32(override)) return override;
11752
+ const here = dirname32(fileURLToPath(import.meta.url));
9911
11753
  const candidates = [
9912
11754
  // Bundled CLI (dev + published): this module IS bundled into the CLI
9913
11755
  // entry, so the entry is index.js next to this file.
@@ -9916,19 +11758,19 @@ function resolveCliEntry() {
9916
11758
  resolve3(here, "..", "..", "..", "..", "dist", "index.js")
9917
11759
  ];
9918
11760
  for (const c of candidates) {
9919
- if (existsSync3(c)) return c;
11761
+ if (existsSync32(c)) return c;
9920
11762
  }
9921
11763
  return null;
9922
11764
  }
9923
11765
  async function stageRelayHome(version, log) {
9924
11766
  if (!version || version === "0.0.0-dev") return null;
9925
11767
  if (process.env.AGENTBOX_RELAY_BIN || process.env.AGENTBOX_CLI_ENTRY) return null;
9926
- const cliRoot = findCliRoot(dirname3(fileURLToPath(import.meta.url)));
11768
+ const cliRoot = findCliRoot(dirname32(fileURLToPath(import.meta.url)));
9927
11769
  if (cliRoot === null) return null;
9928
11770
  const homeDir = join11(RELAY_HOME_DIR, version);
9929
11771
  const stagedEntry = join11(homeDir, "dist", "index.js");
9930
11772
  const stagedBin = join11(homeDir, "runtime", "relay", "bin.cjs");
9931
- if (existsSync3(stagedEntry) && existsSync3(stagedBin)) {
11773
+ if (existsSync32(stagedEntry) && existsSync32(stagedBin)) {
9932
11774
  return { relayBin: stagedBin, cliEntry: stagedEntry };
9933
11775
  }
9934
11776
  const nodeModules = resolveDepRoot(join11(cliRoot, "dist", "index.js"));
@@ -9940,15 +11782,15 @@ async function stageRelayHome(version, log) {
9940
11782
  await mkdir5(tmpDir, { recursive: true });
9941
11783
  for (const sub of ["dist", "runtime", "share"]) {
9942
11784
  const src = join11(cliRoot, sub);
9943
- if (existsSync3(src)) await cp(src, join11(tmpDir, sub), { recursive: true });
11785
+ if (existsSync32(src)) await cp(src, join11(tmpDir, sub), { recursive: true });
9944
11786
  }
9945
11787
  await cp(nodeModules, join11(tmpDir, "node_modules"), { recursive: true, dereference: true });
9946
11788
  await rm5(homeDir, { recursive: true, force: true });
9947
- await rename3(tmpDir, homeDir);
11789
+ await rename4(tmpDir, homeDir);
9948
11790
  } catch (err) {
9949
11791
  await rm5(tmpDir, { recursive: true, force: true }).catch(() => {
9950
11792
  });
9951
- if (existsSync3(stagedEntry) && existsSync3(stagedBin)) {
11793
+ if (existsSync32(stagedEntry) && existsSync32(stagedBin)) {
9952
11794
  return { relayBin: stagedBin, cliEntry: stagedEntry };
9953
11795
  }
9954
11796
  log(`relay home staging failed (${err instanceof Error ? err.message : String(err)}); using bundle paths`);
@@ -9961,7 +11803,7 @@ async function stageRelayHome(version, log) {
9961
11803
  }
9962
11804
  function findCliRoot(moduleDir) {
9963
11805
  for (const root of [resolve3(moduleDir, ".."), resolve3(moduleDir, "..", "..")]) {
9964
- if (existsSync3(join11(root, "dist", "index.js")) && existsSync3(join11(root, "runtime", "relay", "bin.cjs"))) {
11806
+ if (existsSync32(join11(root, "dist", "index.js")) && existsSync32(join11(root, "runtime", "relay", "bin.cjs"))) {
9965
11807
  return root;
9966
11808
  }
9967
11809
  }
@@ -9969,14 +11811,14 @@ function findCliRoot(moduleDir) {
9969
11811
  }
9970
11812
  function resolveDepRoot(fromFile) {
9971
11813
  try {
9972
- const req = createRequire(fromFile);
11814
+ const req = createRequire2(fromFile);
9973
11815
  const main = req.resolve("commander");
9974
- if (main.includes(`${sep}.pnpm${sep}`)) return null;
9975
- const marker = `${sep}node_modules${sep}`;
11816
+ if (main.includes(`${sep2}.pnpm${sep2}`)) return null;
11817
+ const marker = `${sep2}node_modules${sep2}`;
9976
11818
  const idx = main.lastIndexOf(marker);
9977
11819
  if (idx === -1) return null;
9978
11820
  const nm = main.slice(0, idx + marker.length - 1);
9979
- return existsSync3(join11(nm, "commander")) ? nm : null;
11821
+ return existsSync32(join11(nm, "commander")) ? nm : null;
9980
11822
  } catch {
9981
11823
  return null;
9982
11824
  }
@@ -10102,8 +11944,8 @@ function fetchHealthz(timeoutMs) {
10102
11944
  }
10103
11945
  async function readPidFile() {
10104
11946
  try {
10105
- const text = await readFile6(PID_FILE, "utf8");
10106
- const pid = Number.parseInt(text.trim(), 10);
11947
+ const text3 = await readFile6(PID_FILE, "utf8");
11948
+ const pid = Number.parseInt(text3.trim(), 10);
10107
11949
  return Number.isFinite(pid) && pid > 0 ? pid : null;
10108
11950
  } catch {
10109
11951
  return null;
@@ -10118,7 +11960,7 @@ async function processAlive2(pid) {
10118
11960
  }
10119
11961
  }
10120
11962
  function generateRelayToken() {
10121
- return randomBytes22(32).toString("hex");
11963
+ return randomBytes23(32).toString("hex");
10122
11964
  }
10123
11965
  async function registerBoxWithRelay(args) {
10124
11966
  const worktrees = (args.worktrees ?? []).map((w) => ({
@@ -10208,8 +12050,8 @@ async function adminPost(path, body) {
10208
12050
  if (status >= 200 && status < 300) {
10209
12051
  resolveP();
10210
12052
  } else {
10211
- const text = Buffer.concat(chunks).toString("utf8");
10212
- rejectP(new Error(`relay ${path} \u2192 ${String(status)}: ${text}`));
12053
+ const text3 = Buffer.concat(chunks).toString("utf8");
12054
+ rejectP(new Error(`relay ${path} \u2192 ${String(status)}: ${text3}`));
10213
12055
  }
10214
12056
  });
10215
12057
  }
@@ -10247,9 +12089,9 @@ async function adminPostForJson(path, body) {
10247
12089
  rejectP(new Error(`relay ${path} \u2192 ${String(status)}`));
10248
12090
  return;
10249
12091
  }
10250
- const text = Buffer.concat(chunks).toString("utf8");
12092
+ const text3 = Buffer.concat(chunks).toString("utf8");
10251
12093
  try {
10252
- resolveP(text.length > 0 ? JSON.parse(text) : {});
12094
+ resolveP(text3.length > 0 ? JSON.parse(text3) : {});
10253
12095
  } catch (err) {
10254
12096
  rejectP(err instanceof Error ? err : new Error(String(err)));
10255
12097
  }
@@ -11697,8 +13539,9 @@ async function pruneBoxes(opts = {}) {
11697
13539
  const dryRun = opts.dryRun ?? false;
11698
13540
  const all = opts.all ?? false;
11699
13541
  const { boxes } = await readState();
13542
+ const dockerBoxes = boxes.filter((b) => (b.provider ?? "docker") === "docker");
11700
13543
  const stateChecks = await Promise.all(
11701
- boxes.map(async (b) => ({ box: b, status: await inspectContainerStatus(b.container) }))
13544
+ dockerBoxes.map(async (b) => ({ box: b, status: await inspectContainerStatus(b.container) }))
11702
13545
  );
11703
13546
  const missingRecords = stateChecks.filter((c) => c.status === "missing").map((c) => c.box);
11704
13547
  let orphanContainers = [];
@@ -12254,7 +14097,7 @@ async function dockerChecks() {
12254
14097
  (async () => {
12255
14098
  const engine = await detectEngine().catch(() => "other");
12256
14099
  if (engine === "orbstack") return null;
12257
- return portlessDoctorRow(await detectPortless());
14100
+ return portlessDoctorRow(await detectPortless(), await portlessServiceStatus());
12258
14101
  })()
12259
14102
  ]);
12260
14103
  if (info.exitCode !== 0) {
@@ -12362,7 +14205,7 @@ function volumeSettingsTarget(volume, image, label) {
12362
14205
  },
12363
14206
  async writeText(rel, content, opts) {
12364
14207
  const parent = posixDirname2(rel);
12365
- const chmod2 = opts?.mode !== void 0 ? ` && chmod ${opts.mode.toString(8)} '/dst/${rel}'` : "";
14208
+ const chmod22 = opts?.mode !== void 0 ? ` && chmod ${opts.mode.toString(8)} '/dst/${rel}'` : "";
12366
14209
  const r = await run(
12367
14210
  [
12368
14211
  "run",
@@ -12375,7 +14218,7 @@ function volumeSettingsTarget(volume, image, label) {
12375
14218
  image,
12376
14219
  "sh",
12377
14220
  "-c",
12378
- `${parent ? `mkdir -p '/dst/${parent}' && ` : ""}cat > '/dst/${rel}' && chown 1000:1000 '/dst/${rel}'${chmod2}`
14221
+ `${parent ? `mkdir -p '/dst/${parent}' && ` : ""}cat > '/dst/${rel}' && chown 1000:1000 '/dst/${rel}'${chmod22}`
12379
14222
  ],
12380
14223
  content
12381
14224
  );
@@ -12469,6 +14312,16 @@ async function readHubPortlessUrl() {
12469
14312
  return null;
12470
14313
  }
12471
14314
  }
14315
+ async function currentHubPortlessUrl() {
14316
+ const cached2 = await readHubPortlessUrl();
14317
+ if (cached2 === null) return null;
14318
+ const portless = await detectPortless();
14319
+ if (!portless.proxyRunning) return null;
14320
+ const url = await portlessGetUrl(HUB_PORTLESS_ALIAS);
14321
+ if (url !== cached2) await writeFile42(HUB_PORTLESS_FILE, url, "utf8").catch(() => {
14322
+ });
14323
+ return url;
14324
+ }
12472
14325
  async function syncHubPortless(enabled) {
12473
14326
  const teardown = async () => {
12474
14327
  await portlessUnalias(HUB_PORTLESS_ALIAS).catch(() => {
@@ -12485,8 +14338,8 @@ async function syncHubPortless(enabled) {
12485
14338
  await portlessAlias(HUB_PORTLESS_ALIAS, PORT2);
12486
14339
  const url = await portlessGetUrl(HUB_PORTLESS_ALIAS);
12487
14340
  await mkdir8(dirname5(HUB_PORTLESS_FILE), { recursive: true });
12488
- await writeFile4(HUB_PORTLESS_FILE, url, "utf8");
12489
- return url;
14341
+ await writeFile42(HUB_PORTLESS_FILE, url, "utf8");
14342
+ return portless.proxyRunning ? url : void 0;
12490
14343
  } catch {
12491
14344
  return void 0;
12492
14345
  }
@@ -12591,7 +14444,7 @@ async function spawnHub(hubServer, cliEntry, log, portlessEnabled) {
12591
14444
  exit = { code, signal };
12592
14445
  });
12593
14446
  if (typeof child.pid === "number") {
12594
- await writeFile4(HUB_PID_FILE, String(child.pid), "utf8");
14447
+ await writeFile42(HUB_PID_FILE, String(child.pid), "utf8");
12595
14448
  log(`spawned hub process (pid ${String(child.pid)}, port ${String(PORT2)})`);
12596
14449
  }
12597
14450
  for (let i = 0; i < 50; i++) {
@@ -12605,11 +14458,17 @@ async function spawnHub(hubServer, cliEntry, log, portlessEnabled) {
12605
14458
  await unlink22(HUB_PID_FILE).catch(() => {
12606
14459
  });
12607
14460
  await delay3(150);
12608
- throw new Error(await hubStartupError(`hub process exited (${describeExit(exit)}) during startup`));
14461
+ throw new Error(
14462
+ await hubStartupError(`hub process exited (${describeExit(exit)}) during startup`)
14463
+ );
12609
14464
  }
12610
14465
  await delay3(200);
12611
14466
  }
12612
- throw new Error(await hubStartupError(`hub did not become reachable on http://${HOST}:${String(PORT2)} within ~25s`));
14467
+ throw new Error(
14468
+ await hubStartupError(
14469
+ `hub did not become reachable on http://${HOST}:${String(PORT2)} within ~25s`
14470
+ )
14471
+ );
12613
14472
  }
12614
14473
  function describeExit(exit) {
12615
14474
  if (exit.signal !== null) return `killed by ${exit.signal}`;
@@ -12658,7 +14517,7 @@ async function getHubStatus() {
12658
14517
  const pid = await readPid(HUB_PID_FILE);
12659
14518
  const pidAlive2 = pid !== null && await processAlive2(pid);
12660
14519
  const health = await fetchHealthz(300);
12661
- const ep = await endpointFor(await readHubPortlessUrl() ?? void 0);
14520
+ const ep = await endpointFor(await currentHubPortlessUrl() ?? void 0);
12662
14521
  return {
12663
14522
  running: health !== null,
12664
14523
  ui: health?.ui === true,
@@ -12707,6 +14566,15 @@ export {
12707
14566
  RELAY_NETWORK_NAME,
12708
14567
  RELAY_IMAGE_REF,
12709
14568
  isValidBoxStatus,
14569
+ parseGitRemote,
14570
+ toAuthedHttpsUrl,
14571
+ loadGitHubAppConfig,
14572
+ GitHubAppLeaser,
14573
+ cloneRepoWithLfs,
14574
+ makeControlPlaneCreateBox,
14575
+ drainCreateJobs,
14576
+ makeStore,
14577
+ FsCustodyStore,
12710
14578
  hashRpcParams,
12711
14579
  enqueueQueueJob,
12712
14580
  enqueuePrepareJob,
@@ -12715,6 +14583,7 @@ export {
12715
14583
  loadQueue,
12716
14584
  writeQueueLoginCode,
12717
14585
  startRelayDaemon,
14586
+ registrationToBoxRecord,
12718
14587
  execInBox,
12719
14588
  removeImage,
12720
14589
  volumeExists,
@@ -12843,11 +14712,16 @@ export {
12843
14712
  portlessGetUrl,
12844
14713
  portlessInstallHint,
12845
14714
  portlessStartHint,
14715
+ portlessServiceHint,
12846
14716
  portlessDoctorRow,
12847
14717
  portlessBrowserEnv,
12848
14718
  installPortless,
12849
14719
  startPortlessProxy,
12850
14720
  startPortlessProxyRoot,
14721
+ portlessServiceStatus,
14722
+ installPortlessService,
14723
+ uninstallPortlessService,
14724
+ ensurePortlessProxy,
12851
14725
  resolvePortlessHostStateDir,
12852
14726
  EXCLUDE_DIRS,
12853
14727
  SNAPSHOTS_ROOT,