tenjin-cli 0.1.0-alpha.31 → 0.1.0-alpha.33

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 (270) hide show
  1. package/README.md +45 -26
  2. package/dist/{_esm-MEXZI5DL.js → _esm-BIN7VY2L.js} +128 -132
  3. package/dist/{alive-J64H46HI.js → alive-GSOWKUOY.js} +13 -6
  4. package/dist/auto-update-Y24UL56V.js +24 -0
  5. package/dist/{ccip-7RMRLAGV.js → ccip-DHDFKTQV.js} +2 -2
  6. package/dist/{chunk-TTNESUPQ.js → chunk-2GP3HRYK.js} +2120 -193
  7. package/dist/chunk-2GP3HRYK.js.map +1 -0
  8. package/dist/chunk-2M2VPI2E.js +560 -0
  9. package/dist/chunk-2M2VPI2E.js.map +1 -0
  10. package/dist/{chunk-D65GNPS3.js → chunk-2RWB7RKE.js} +288 -108
  11. package/dist/chunk-2RWB7RKE.js.map +1 -0
  12. package/dist/{chunk-AGZ7PJKY.js → chunk-36RVGZNY.js} +22 -5
  13. package/dist/chunk-36RVGZNY.js.map +1 -0
  14. package/dist/chunk-3AIHRXKO.js +72 -0
  15. package/dist/chunk-3AIHRXKO.js.map +1 -0
  16. package/dist/{chunk-S4SAZ7OD.js → chunk-3FMZGI7I.js} +12 -2
  17. package/dist/{chunk-S4SAZ7OD.js.map → chunk-3FMZGI7I.js.map} +1 -1
  18. package/dist/chunk-3GNJXKIT.js +198 -0
  19. package/dist/chunk-3GNJXKIT.js.map +1 -0
  20. package/dist/{chunk-UQUOVWBG.js → chunk-4K7TQHNP.js} +7 -7
  21. package/dist/{chunk-A36LQPHV.js → chunk-4LMUQMBH.js} +1 -1
  22. package/dist/{chunk-A36LQPHV.js.map → chunk-4LMUQMBH.js.map} +1 -1
  23. package/dist/{chunk-KXQ4UIP7.js → chunk-4USCZ2NI.js} +2 -2
  24. package/dist/chunk-4YOZGGTZ.js +247 -0
  25. package/dist/chunk-4YOZGGTZ.js.map +1 -0
  26. package/dist/chunk-62KNUYWD.js +111 -0
  27. package/dist/chunk-62KNUYWD.js.map +1 -0
  28. package/dist/{chunk-POUWHWID.js → chunk-6CMM6YCB.js} +3 -3
  29. package/dist/{chunk-POUWHWID.js.map → chunk-6CMM6YCB.js.map} +1 -1
  30. package/dist/{chunk-5MARFNSB.js → chunk-A5GKIG5O.js} +49 -30
  31. package/dist/chunk-A5GKIG5O.js.map +1 -0
  32. package/dist/{chunk-YFPY4ONH.js → chunk-AGMVASXZ.js} +4 -4
  33. package/dist/chunk-BF4XHEQK.js +116 -0
  34. package/dist/chunk-BF4XHEQK.js.map +1 -0
  35. package/dist/chunk-BFDQ4WNW.js +119 -0
  36. package/dist/chunk-BFDQ4WNW.js.map +1 -0
  37. package/dist/{chunk-P4NH7OUK.js → chunk-C2Q76BVM.js} +49 -50
  38. package/dist/chunk-C2Q76BVM.js.map +1 -0
  39. package/dist/chunk-CEXSOI5R.js +808 -0
  40. package/dist/chunk-CEXSOI5R.js.map +1 -0
  41. package/dist/{chunk-QSCPK4F5.js → chunk-E7SW44LM.js} +4 -11
  42. package/dist/chunk-E7SW44LM.js.map +1 -0
  43. package/dist/chunk-EDJWHDDL.js +33 -0
  44. package/dist/chunk-EDJWHDDL.js.map +1 -0
  45. package/dist/chunk-F3ED5WTR.js +13 -0
  46. package/dist/chunk-F3ED5WTR.js.map +1 -0
  47. package/dist/{chunk-K72RURN3.js → chunk-FVIGCDSV.js} +2 -2
  48. package/dist/chunk-FVIGCDSV.js.map +1 -0
  49. package/dist/{chunk-5K5W4S66.js → chunk-GTTUCOPD.js} +2 -2
  50. package/dist/{chunk-4ZZO6ULA.js → chunk-HDPUXS3Z.js} +19 -48
  51. package/dist/chunk-HDPUXS3Z.js.map +1 -0
  52. package/dist/{chunk-LEFIX6RS.js → chunk-HGGWCP7W.js} +31 -11
  53. package/dist/chunk-HGGWCP7W.js.map +1 -0
  54. package/dist/{chunk-ORWL5BSN.js → chunk-HGZEPQUT.js} +2 -2
  55. package/dist/chunk-HMWYAUA6.js +478 -0
  56. package/dist/chunk-HMWYAUA6.js.map +1 -0
  57. package/dist/{chunk-7QKHZQKW.js → chunk-IADZOXKN.js} +39 -6
  58. package/dist/chunk-IADZOXKN.js.map +1 -0
  59. package/dist/{chunk-7Q5FDF65.js → chunk-IE7P2BZE.js} +3 -3
  60. package/dist/{chunk-77TCKDEC.js → chunk-ILNIZ5I2.js} +788 -508
  61. package/dist/chunk-ILNIZ5I2.js.map +1 -0
  62. package/dist/{hosts-FWZOV26H.js → chunk-INTFHMU4.js} +79 -24
  63. package/dist/chunk-INTFHMU4.js.map +1 -0
  64. package/dist/{chunk-6E5R45ZO.js → chunk-J57UC3DD.js} +4 -4
  65. package/dist/{chunk-6E5R45ZO.js.map → chunk-J57UC3DD.js.map} +1 -1
  66. package/dist/chunk-JNJWBTU2.js +3497 -0
  67. package/dist/chunk-JNJWBTU2.js.map +1 -0
  68. package/dist/{chunk-7WU4OPLP.js → chunk-KM7RY2ZS.js} +5 -3
  69. package/dist/{chunk-7WU4OPLP.js.map → chunk-KM7RY2ZS.js.map} +1 -1
  70. package/dist/chunk-L6JEXB3E.js +293 -0
  71. package/dist/chunk-L6JEXB3E.js.map +1 -0
  72. package/dist/chunk-LRW6S53P.js +450 -0
  73. package/dist/chunk-LRW6S53P.js.map +1 -0
  74. package/dist/{chunk-UKY4CHNC.js → chunk-LXAYUOXI.js} +24 -11
  75. package/dist/chunk-LXAYUOXI.js.map +1 -0
  76. package/dist/{chunk-WJXLQXJY.js → chunk-MPZUYCAP.js} +4 -1
  77. package/dist/{chunk-WJXLQXJY.js.map → chunk-MPZUYCAP.js.map} +1 -1
  78. package/dist/chunk-NDGZDTSJ.js +393 -0
  79. package/dist/chunk-NDGZDTSJ.js.map +1 -0
  80. package/dist/{chunk-SJLTEINJ.js → chunk-OJNTCYQQ.js} +17 -1
  81. package/dist/chunk-OJNTCYQQ.js.map +1 -0
  82. package/dist/{chunk-OHRR5OYM.js → chunk-P3LFTKE7.js} +5 -10
  83. package/dist/chunk-P3LFTKE7.js.map +1 -0
  84. package/dist/{chunk-XZKD7DIF.js → chunk-RL5UUDT4.js} +3 -3
  85. package/dist/{chunk-XZKD7DIF.js.map → chunk-RL5UUDT4.js.map} +1 -1
  86. package/dist/{chunk-5C32RLTA.js → chunk-RVPYTUP4.js} +20 -5
  87. package/dist/chunk-RVPYTUP4.js.map +1 -0
  88. package/dist/{chunk-YVFXE7RR.js → chunk-SNNSAGMT.js} +7279 -2627
  89. package/dist/chunk-SNNSAGMT.js.map +1 -0
  90. package/dist/{chunk-WK7F3B2E.js → chunk-SO3XRZPX.js} +3 -3
  91. package/dist/{chunk-R5LCN54M.js → chunk-TC2WZLSC.js} +13 -17
  92. package/dist/{chunk-R5LCN54M.js.map → chunk-TC2WZLSC.js.map} +1 -1
  93. package/dist/{chunk-B7HUUJOK.js → chunk-TKPF35W6.js} +3 -3
  94. package/dist/{chunk-KXVP2VKA.js → chunk-U3IKUGRP.js} +32 -33
  95. package/dist/chunk-U3IKUGRP.js.map +1 -0
  96. package/dist/{chunk-AKWGE6JQ.js → chunk-UUGOUOVT.js} +37 -2
  97. package/dist/chunk-UUGOUOVT.js.map +1 -0
  98. package/dist/{chunk-2XLC3AEX.js → chunk-UXZONNEQ.js} +536 -510
  99. package/dist/chunk-UXZONNEQ.js.map +1 -0
  100. package/dist/{chunk-7ZRL2LBQ.js → chunk-V2LQLN5H.js} +6 -6
  101. package/dist/{chunk-NEFNKLBE.js → chunk-WFSPCCVW.js} +1536 -423
  102. package/dist/chunk-WFSPCCVW.js.map +1 -0
  103. package/dist/{chunk-27EPWVOY.js → chunk-WXA2BWTE.js} +7 -3
  104. package/dist/chunk-WXA2BWTE.js.map +1 -0
  105. package/dist/chunk-WYXUQGOL.js +191 -0
  106. package/dist/chunk-WYXUQGOL.js.map +1 -0
  107. package/dist/chunk-X5ZBP3IY.js +97 -0
  108. package/dist/chunk-X5ZBP3IY.js.map +1 -0
  109. package/dist/{chunk-MNXS2U45.js → chunk-ZDZERB6L.js} +206 -297
  110. package/dist/chunk-ZDZERB6L.js.map +1 -0
  111. package/dist/chunk-ZNNXRNFD.js +113 -0
  112. package/dist/chunk-ZNNXRNFD.js.map +1 -0
  113. package/dist/{chunk-FW75G2W4.js → chunk-ZURZHELF.js} +5 -5
  114. package/dist/{cli-D5OE3URZ.js → cli-E36SPKBW.js} +145 -64
  115. package/dist/{cli-D5OE3URZ.js.map → cli-E36SPKBW.js.map} +1 -1
  116. package/dist/{codex-event-PPNVRRDH.js → codex-event-ZO2GEFE6.js} +2 -2
  117. package/dist/{codex-host-2RJOJW2B.js → codex-host-KECJVTA2.js} +7 -6
  118. package/dist/codex-install-HQZDGFXW.js +436 -0
  119. package/dist/codex-install-HQZDGFXW.js.map +1 -0
  120. package/dist/{config-ZD4OB2DO.js → config-HY2E4GGW.js} +21 -17
  121. package/dist/doctor-I6XQEKWD.js +1323 -0
  122. package/dist/doctor-I6XQEKWD.js.map +1 -0
  123. package/dist/{env-proxy-XL4P73MZ.js → env-proxy-R6ZMLQTT.js} +6 -2
  124. package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js → ethersCompat-Df4a6QIZ-X6YZWAML.js} +3 -3
  125. package/dist/{fund-5ITKQGYF.js → fund-2QRO7OJL.js} +43 -37
  126. package/dist/{fund-5ITKQGYF.js.map → fund-2QRO7OJL.js.map} +1 -1
  127. package/dist/hook-command-2UBCSZG6.js +43 -0
  128. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  129. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  130. package/dist/hosts/claude/tenjin/hooks/register.tsx +51 -11
  131. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +82 -0
  132. package/dist/hosts/claude/tenjin/types/index.d.ts +2 -1
  133. package/dist/hosts/codex/tenjin/.mcp.json +3 -0
  134. package/dist/hosts/codex/tenjin/hooks/hooks.json +51 -5
  135. package/dist/hosts-DVQJ32QC.js +38 -0
  136. package/dist/index.js +32 -11
  137. package/dist/index.js.map +1 -1
  138. package/dist/install-ILUX5C4A.js +107 -0
  139. package/dist/{install-identity-K7EJIQFP.js → install-identity-TZKGY6LQ.js} +11 -10
  140. package/dist/install-wallet-5M4OTYLX.js +281 -0
  141. package/dist/install-wallet-5M4OTYLX.js.map +1 -0
  142. package/dist/isows-native-Q2UDIVPT.js +9 -0
  143. package/dist/isows-native-Q2UDIVPT.js.map +1 -0
  144. package/dist/{mcp-3LIJSSJB.js → mcp-LE4DUS22.js} +785 -211
  145. package/dist/mcp-LE4DUS22.js.map +1 -0
  146. package/dist/{mine.wasm-6PIT3DK6.js → mine.wasm-QFAHIFPY.js} +2 -2
  147. package/dist/{mine.wasm-6PIT3DK6.js.map → mine.wasm-QFAHIFPY.js.map} +1 -1
  148. package/dist/{package-ZKQFDWLE.js → package-IJFGMWEV.js} +4 -2
  149. package/dist/passphrase-IFTDS3CU.js +44 -0
  150. package/dist/{paths-POPTXJO6.js → paths-XCSAKISU.js} +10 -2
  151. package/dist/{pay-WHBERZ3W.js → pay-WCG3IH4R.js} +29 -29
  152. package/dist/{payments-KVICEKD2.js → payments-HFPPWHTV.js} +15 -14
  153. package/dist/{payments-KVICEKD2.js.map → payments-HFPPWHTV.js.map} +1 -1
  154. package/dist/plugin-registration-PZFI5GZW.js +68 -0
  155. package/dist/{redact-6W23GGJC.js → redact-D7ASVWKL.js} +2 -2
  156. package/dist/runtime-UZOKSUZX.js +1321 -0
  157. package/dist/runtime-UZOKSUZX.js.map +1 -0
  158. package/dist/runtime-fetch-ZSSSK72Y.js +23 -0
  159. package/dist/runtime-layout-WIDILZ6K.js +25 -0
  160. package/dist/{send-7G7Y7DLN.js → send-GCVEAQKL.js} +24 -22
  161. package/dist/{send-7G7Y7DLN.js.map → send-GCVEAQKL.js.map} +1 -1
  162. package/dist/{status-OF7RH5HM.js → status-HCVAOCN7.js} +55 -25
  163. package/dist/status-HCVAOCN7.js.map +1 -0
  164. package/dist/{status-line-XOUE6MPL.js → status-line-OPCXDHL2.js} +10 -9
  165. package/dist/{status-line-XOUE6MPL.js.map → status-line-OPCXDHL2.js.map} +1 -1
  166. package/dist/uninstall-BAWRBXXQ.js +481 -0
  167. package/dist/uninstall-BAWRBXXQ.js.map +1 -0
  168. package/dist/update-CACXLQLR.js +56 -0
  169. package/dist/update-CACXLQLR.js.map +1 -0
  170. package/dist/{usdc-OGOGEHV2.js → usdc-VG4CIOUK.js} +6 -8
  171. package/dist/usdc-VG4CIOUK.js.map +1 -0
  172. package/dist/{viemAdapter-By13KInL-S3DA7DFW.js → viemAdapter-By13KInL-DOFTEIJV.js} +3 -3
  173. package/dist/viemAdapter-By13KInL-DOFTEIJV.js.map +1 -0
  174. package/dist/wallet-QL4UUXEZ.js +55 -0
  175. package/dist/wallet-QL4UUXEZ.js.map +1 -0
  176. package/dist/wallet-kdf-worker.mjs +8 -8
  177. package/docs/agent-permissions.md +50 -28
  178. package/docs/safety-model.md +1 -1
  179. package/docs/troubleshooting.md +72 -1
  180. package/package.json +17 -4
  181. package/scripts/installers/install.ps1 +67 -0
  182. package/scripts/installers/install.sh +68 -0
  183. package/dist/_esm-C5CRWCYU.js +0 -3737
  184. package/dist/_esm-C5CRWCYU.js.map +0 -1
  185. package/dist/ccip-NLCSCHKI.js +0 -19
  186. package/dist/chunk-27EPWVOY.js.map +0 -1
  187. package/dist/chunk-2XLC3AEX.js.map +0 -1
  188. package/dist/chunk-4ZZO6ULA.js.map +0 -1
  189. package/dist/chunk-5C32RLTA.js.map +0 -1
  190. package/dist/chunk-5IEP5EGE.js +0 -5332
  191. package/dist/chunk-5IEP5EGE.js.map +0 -1
  192. package/dist/chunk-5MARFNSB.js.map +0 -1
  193. package/dist/chunk-77TCKDEC.js.map +0 -1
  194. package/dist/chunk-7EKYXMUO.js +0 -7536
  195. package/dist/chunk-7EKYXMUO.js.map +0 -1
  196. package/dist/chunk-7QKHZQKW.js.map +0 -1
  197. package/dist/chunk-AGZ7PJKY.js.map +0 -1
  198. package/dist/chunk-AKWGE6JQ.js.map +0 -1
  199. package/dist/chunk-BL3332HQ.js +0 -7611
  200. package/dist/chunk-BL3332HQ.js.map +0 -1
  201. package/dist/chunk-D65GNPS3.js.map +0 -1
  202. package/dist/chunk-EGELTSPU.js +0 -2865
  203. package/dist/chunk-EGELTSPU.js.map +0 -1
  204. package/dist/chunk-GA7JETVM.js +0 -150
  205. package/dist/chunk-GA7JETVM.js.map +0 -1
  206. package/dist/chunk-I3EQFHCD.js +0 -175
  207. package/dist/chunk-I3EQFHCD.js.map +0 -1
  208. package/dist/chunk-K3I7C2MO.js +0 -1185
  209. package/dist/chunk-K3I7C2MO.js.map +0 -1
  210. package/dist/chunk-K72RURN3.js.map +0 -1
  211. package/dist/chunk-KXVP2VKA.js.map +0 -1
  212. package/dist/chunk-LEFIX6RS.js.map +0 -1
  213. package/dist/chunk-MNXS2U45.js.map +0 -1
  214. package/dist/chunk-NEFNKLBE.js.map +0 -1
  215. package/dist/chunk-OHRR5OYM.js.map +0 -1
  216. package/dist/chunk-P4NH7OUK.js.map +0 -1
  217. package/dist/chunk-QSCPK4F5.js.map +0 -1
  218. package/dist/chunk-SJLTEINJ.js.map +0 -1
  219. package/dist/chunk-TTNESUPQ.js.map +0 -1
  220. package/dist/chunk-UKY4CHNC.js.map +0 -1
  221. package/dist/chunk-V6BSF6OC.js +0 -260
  222. package/dist/chunk-V6BSF6OC.js.map +0 -1
  223. package/dist/chunk-YVFXE7RR.js.map +0 -1
  224. package/dist/codex-install-UUZ6QMBQ.js +0 -221
  225. package/dist/codex-install-UUZ6QMBQ.js.map +0 -1
  226. package/dist/doctor-KBR34Q4B.js +0 -601
  227. package/dist/doctor-KBR34Q4B.js.map +0 -1
  228. package/dist/hook-command-4TYCHHRL.js +0 -39
  229. package/dist/hosts-FWZOV26H.js.map +0 -1
  230. package/dist/install-XWGE4Q7L.js +0 -77
  231. package/dist/install-wallet-XQ6XFZV4.js +0 -117
  232. package/dist/install-wallet-XQ6XFZV4.js.map +0 -1
  233. package/dist/mcp-3LIJSSJB.js.map +0 -1
  234. package/dist/plugin-registration-5TIA564H.js +0 -54
  235. package/dist/status-OF7RH5HM.js.map +0 -1
  236. package/dist/uninstall-JXUAFNDB.js +0 -158
  237. package/dist/uninstall-JXUAFNDB.js.map +0 -1
  238. package/dist/update-ZKUERSO2.js +0 -44
  239. package/dist/wallet-2HA6W4R4.js +0 -43
  240. /package/dist/{_esm-MEXZI5DL.js.map → _esm-BIN7VY2L.js.map} +0 -0
  241. /package/dist/{alive-J64H46HI.js.map → alive-GSOWKUOY.js.map} +0 -0
  242. /package/dist/{ccip-7RMRLAGV.js.map → auto-update-Y24UL56V.js.map} +0 -0
  243. /package/dist/{ccip-NLCSCHKI.js.map → ccip-DHDFKTQV.js.map} +0 -0
  244. /package/dist/{chunk-UQUOVWBG.js.map → chunk-4K7TQHNP.js.map} +0 -0
  245. /package/dist/{chunk-KXQ4UIP7.js.map → chunk-4USCZ2NI.js.map} +0 -0
  246. /package/dist/{chunk-YFPY4ONH.js.map → chunk-AGMVASXZ.js.map} +0 -0
  247. /package/dist/{chunk-5K5W4S66.js.map → chunk-GTTUCOPD.js.map} +0 -0
  248. /package/dist/{chunk-ORWL5BSN.js.map → chunk-HGZEPQUT.js.map} +0 -0
  249. /package/dist/{chunk-7Q5FDF65.js.map → chunk-IE7P2BZE.js.map} +0 -0
  250. /package/dist/{chunk-WK7F3B2E.js.map → chunk-SO3XRZPX.js.map} +0 -0
  251. /package/dist/{chunk-B7HUUJOK.js.map → chunk-TKPF35W6.js.map} +0 -0
  252. /package/dist/{chunk-7ZRL2LBQ.js.map → chunk-V2LQLN5H.js.map} +0 -0
  253. /package/dist/{chunk-FW75G2W4.js.map → chunk-ZURZHELF.js.map} +0 -0
  254. /package/dist/{codex-event-PPNVRRDH.js.map → codex-event-ZO2GEFE6.js.map} +0 -0
  255. /package/dist/{codex-host-2RJOJW2B.js.map → codex-host-KECJVTA2.js.map} +0 -0
  256. /package/dist/{config-ZD4OB2DO.js.map → config-HY2E4GGW.js.map} +0 -0
  257. /package/dist/{env-proxy-XL4P73MZ.js.map → env-proxy-R6ZMLQTT.js.map} +0 -0
  258. /package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js.map → ethersCompat-Df4a6QIZ-X6YZWAML.js.map} +0 -0
  259. /package/dist/{hook-command-4TYCHHRL.js.map → hook-command-2UBCSZG6.js.map} +0 -0
  260. /package/dist/{install-XWGE4Q7L.js.map → hosts-DVQJ32QC.js.map} +0 -0
  261. /package/dist/{install-identity-K7EJIQFP.js.map → install-ILUX5C4A.js.map} +0 -0
  262. /package/dist/{package-ZKQFDWLE.js.map → install-identity-TZKGY6LQ.js.map} +0 -0
  263. /package/dist/{paths-POPTXJO6.js.map → package-IJFGMWEV.js.map} +0 -0
  264. /package/dist/{pay-WHBERZ3W.js.map → passphrase-IFTDS3CU.js.map} +0 -0
  265. /package/dist/{plugin-registration-5TIA564H.js.map → paths-XCSAKISU.js.map} +0 -0
  266. /package/dist/{redact-6W23GGJC.js.map → pay-WCG3IH4R.js.map} +0 -0
  267. /package/dist/{update-ZKUERSO2.js.map → plugin-registration-PZFI5GZW.js.map} +0 -0
  268. /package/dist/{usdc-OGOGEHV2.js.map → redact-D7ASVWKL.js.map} +0 -0
  269. /package/dist/{viemAdapter-By13KInL-S3DA7DFW.js.map → runtime-fetch-ZSSSK72Y.js.map} +0 -0
  270. /package/dist/{wallet-2HA6W4R4.js.map → runtime-layout-WIDILZ6K.js.map} +0 -0
@@ -0,0 +1,1321 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ isSourceCheckout,
4
+ readModSources
5
+ } from "./chunk-L6JEXB3E.js";
6
+ import {
7
+ LAUNCHER_MARKER,
8
+ PLUGIN_DIR,
9
+ renderCodexHostFiles,
10
+ renderHostFiles,
11
+ renderLauncherCmd,
12
+ renderLauncherSh,
13
+ renderPluginHooks,
14
+ renderPluginMcp
15
+ } from "./chunk-LRW6S53P.js";
16
+ import {
17
+ LockTimeoutError
18
+ } from "./chunk-MEFB5KHA.js";
19
+ import "./chunk-UUGOUOVT.js";
20
+ import "./chunk-MPZUYCAP.js";
21
+ import {
22
+ download,
23
+ downloadViaCurl,
24
+ extract,
25
+ nodeArtifact,
26
+ nodeKey,
27
+ runningGlibc,
28
+ unpinnedPlatform
29
+ } from "./chunk-4YOZGGTZ.js";
30
+ import {
31
+ proxyNodeStep,
32
+ proxySkipped
33
+ } from "./chunk-3FMZGI7I.js";
34
+ import {
35
+ hasCode
36
+ } from "./chunk-2I4QTOLB.js";
37
+ import "./chunk-XQJXNMSB.js";
38
+ import {
39
+ writeFileAtomic
40
+ } from "./chunk-7WEQQJLG.js";
41
+ import {
42
+ CliError
43
+ } from "./chunk-3UCIG4TG.js";
44
+ import {
45
+ nodeBinPath,
46
+ readRuntimeState,
47
+ runtimeBuild,
48
+ runtimeStatePath,
49
+ versionDir,
50
+ versionEntry
51
+ } from "./chunk-ZNNXRNFD.js";
52
+ import {
53
+ isNewer,
54
+ parseVersion
55
+ } from "./chunk-EDJWHDDL.js";
56
+ import {
57
+ defaultDataDir,
58
+ launcherDir,
59
+ runtimeDir
60
+ } from "./chunk-OJNTCYQQ.js";
61
+ import "./chunk-ZXTAQYNA.js";
62
+
63
+ // src/lib/runtime.ts
64
+ import { spawn } from "node:child_process";
65
+ import { createHash, randomBytes } from "node:crypto";
66
+ import {
67
+ existsSync,
68
+ mkdirSync,
69
+ readFileSync,
70
+ renameSync,
71
+ rmSync,
72
+ statSync,
73
+ writeFileSync
74
+ } from "node:fs";
75
+ import {
76
+ chmod,
77
+ cp,
78
+ lstat,
79
+ mkdir,
80
+ mkdtemp,
81
+ readdir,
82
+ readFile,
83
+ realpath,
84
+ rename,
85
+ rm,
86
+ stat,
87
+ utimes,
88
+ writeFile
89
+ } from "node:fs/promises";
90
+ import { tmpdir } from "node:os";
91
+ import { basename, dirname, join, posix, relative, resolve, sep, win32 } from "node:path";
92
+
93
+ // src/router/hook-form.ts
94
+ function isPlainObject(value) {
95
+ return typeof value === "object" && value !== null && !Array.isArray(value);
96
+ }
97
+ function handlersIn(file) {
98
+ const events = isPlainObject(file) ? file.hooks : void 0;
99
+ if (!isPlainObject(events)) return [];
100
+ return Object.values(events).flatMap(
101
+ (groups) => Array.isArray(groups) ? groups.flatMap((g) => isPlainObject(g) && Array.isArray(g.hooks) ? g.hooks : []) : []
102
+ );
103
+ }
104
+
105
+ // src/lib/runtime.ts
106
+ var NODE_VERSION_RE = /^\d+\.\d+\.\d+$/;
107
+ var SHA256_RE = /^[0-9a-f]{64}$/;
108
+ function readNodePin(packageRoot) {
109
+ try {
110
+ const pkg = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
111
+ const node = pkg.tenjinRuntime?.node;
112
+ if (typeof node?.version !== "string" || !NODE_VERSION_RE.test(node.version)) return null;
113
+ if (typeof node.sha256 !== "object" || node.sha256 === null) return null;
114
+ const sha256 = {};
115
+ for (const [key, value] of Object.entries(node.sha256)) {
116
+ if (typeof value === "string" && SHA256_RE.test(value)) sha256[key] = value;
117
+ }
118
+ return { version: node.version, sha256 };
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+ function packageRootOf(moduleDir) {
124
+ let dir = moduleDir;
125
+ for (let i = 0; i < 8; i += 1) {
126
+ try {
127
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
128
+ if (pkg.name === "tenjin-cli") return dir;
129
+ } catch {
130
+ }
131
+ const parent = dirname(dir);
132
+ if (parent === dir) break;
133
+ dir = parent;
134
+ }
135
+ return null;
136
+ }
137
+ var LOCK_STALE_MS = 10 * 6e4;
138
+ var OWNERLESS_STALE_MS = 1e4;
139
+ var TAKEOVER_STALE_MS = 6e4;
140
+ var LOCK_POLL_MS = 50;
141
+ var held = /* @__PURE__ */ new Map();
142
+ var exitHookInstalled = false;
143
+ function releaseHeld() {
144
+ for (const [path, ino] of held) releaseIfOurs(path, ino);
145
+ held.clear();
146
+ }
147
+ function releaseIfOurs(path, ino) {
148
+ try {
149
+ if (statSync(path).ino === ino) rmSync(path, { recursive: true, force: true });
150
+ } catch {
151
+ }
152
+ }
153
+ function pidAlive(pid) {
154
+ try {
155
+ process.kill(pid, 0);
156
+ return true;
157
+ } catch (err) {
158
+ return hasCode(err, "EPERM");
159
+ }
160
+ }
161
+ function staleLock(lock, isAlive, now) {
162
+ let info;
163
+ try {
164
+ info = statSync(lock);
165
+ } catch {
166
+ return null;
167
+ }
168
+ let text;
169
+ try {
170
+ text = readFileSync(join(lock, "owner.json"), "utf8");
171
+ } catch {
172
+ return now - info.mtimeMs > OWNERLESS_STALE_MS ? `${info.ino}:` : null;
173
+ }
174
+ let owner;
175
+ try {
176
+ owner = JSON.parse(text);
177
+ } catch {
178
+ return now - info.mtimeMs > OWNERLESS_STALE_MS ? `${info.ino}:${text}` : null;
179
+ }
180
+ const started = typeof owner.startedAt === "string" ? Date.parse(owner.startedAt) : NaN;
181
+ const dead = typeof owner.pid === "number" && !isAlive(owner.pid);
182
+ const old = Number.isNaN(started) || now - started > LOCK_STALE_MS;
183
+ return dead || old ? `${info.ino}:${text}` : null;
184
+ }
185
+ function takeOver(root, lock, judged, o) {
186
+ const gate = join(root, ".lock-takeover");
187
+ try {
188
+ mkdirSync(gate);
189
+ } catch (err) {
190
+ if (!hasCode(err, "EEXIST")) return false;
191
+ try {
192
+ if (o.now() - statSync(gate).mtimeMs > TAKEOVER_STALE_MS) {
193
+ rmSync(gate, { recursive: true, force: true });
194
+ }
195
+ } catch {
196
+ }
197
+ return false;
198
+ }
199
+ try {
200
+ if (staleLock(lock, o.isAlive, o.now()) !== judged) return false;
201
+ mkdirSync(join(root, "tmp"), { recursive: true });
202
+ renameSync(lock, join(root, "tmp", `trash-lock-${randomBytes(6).toString("hex")}`));
203
+ return true;
204
+ } catch {
205
+ return false;
206
+ } finally {
207
+ rmSync(gate, { recursive: true, force: true });
208
+ }
209
+ }
210
+ async function withRuntimeLock(root, fn, o = {}) {
211
+ const opts = {
212
+ lockWaitMs: o.lockWaitMs ?? 3e5,
213
+ isAlive: o.isAlive ?? pidAlive,
214
+ now: o.now ?? Date.now
215
+ };
216
+ const lock = join(root, ".lock");
217
+ const deadline = opts.now() + opts.lockWaitMs;
218
+ mkdirSync(root, { recursive: true });
219
+ let ino;
220
+ for (; ; ) {
221
+ try {
222
+ mkdirSync(lock);
223
+ ino = statSync(lock).ino;
224
+ held.set(lock, ino);
225
+ break;
226
+ } catch (err) {
227
+ if (!hasCode(err, "EEXIST")) throw err;
228
+ const judged = staleLock(lock, opts.isAlive, opts.now());
229
+ if (judged !== null && takeOver(root, lock, judged, opts)) continue;
230
+ if (opts.now() >= deadline) throw new LockTimeoutError(lock, opts.lockWaitMs);
231
+ await new Promise((done) => setTimeout(done, LOCK_POLL_MS));
232
+ }
233
+ }
234
+ if (!exitHookInstalled) {
235
+ exitHookInstalled = true;
236
+ process.once("exit", releaseHeld);
237
+ }
238
+ try {
239
+ writeFileSync(
240
+ join(lock, "owner.json"),
241
+ JSON.stringify({ pid: process.pid, startedAt: new Date(opts.now()).toISOString() })
242
+ );
243
+ return await fn();
244
+ } finally {
245
+ held.delete(lock);
246
+ releaseIfOurs(lock, ino);
247
+ }
248
+ }
249
+ var NODE_MAX_BYTES = 100 * 1024 * 1024;
250
+ var TARBALL_MAX_BYTES = 50 * 1024 * 1024;
251
+ var NODE_FIX = "Check access to nodejs.org and run `tenjin install` again.";
252
+ var rand = () => randomBytes(6).toString("hex");
253
+ var tmpOf = (root) => join(root, "tmp");
254
+ function completeValid(dir) {
255
+ try {
256
+ const marker = JSON.parse(readFileSync(join(dir, ".complete"), "utf8"));
257
+ return marker.version === basename(dir);
258
+ } catch {
259
+ return false;
260
+ }
261
+ }
262
+ async function markComplete(dir, version) {
263
+ await writeFile(join(dir, ".complete"), `${JSON.stringify({ version })}
264
+ `);
265
+ }
266
+ async function touchComplete(dir) {
267
+ const now = /* @__PURE__ */ new Date();
268
+ await utimes(join(dir, ".complete"), now, now).catch(() => void 0);
269
+ }
270
+ var RENAME_RETRY_MS = 2e3;
271
+ async function renameDir(from, to, platform = process.platform) {
272
+ const deadline = Date.now() + RENAME_RETRY_MS;
273
+ for (let wait = 20; ; wait = Math.min(wait * 2, 400)) {
274
+ try {
275
+ await rename(from, to);
276
+ return;
277
+ } catch (err) {
278
+ const transient = platform === "win32" && ["EPERM", "EACCES", "EBUSY"].some((c) => hasCode(err, c));
279
+ if (!transient || Date.now() + wait > deadline) throw err;
280
+ await new Promise((done) => setTimeout(done, wait));
281
+ }
282
+ }
283
+ }
284
+ async function trash(root, path, platform) {
285
+ if (!existsSync(path)) return;
286
+ await mkdir(tmpOf(root), { recursive: true });
287
+ const to = join(tmpOf(root), `trash-${rand()}`);
288
+ await renameDir(path, to, platform);
289
+ await rm(to, { recursive: true, force: true }).catch(() => void 0);
290
+ }
291
+ function nodeVersionOf(bin) {
292
+ return new Promise((done) => {
293
+ const child = spawn(bin, ["-p", "process.version"], {
294
+ shell: false,
295
+ stdio: ["ignore", "pipe", "ignore"],
296
+ windowsHide: true,
297
+ timeout: 15e3
298
+ });
299
+ let out = "";
300
+ child.stdout.setEncoding("utf8");
301
+ child.stdout.on("data", (chunk) => out += chunk);
302
+ child.on("error", () => done(null));
303
+ child.on("close", (code) => done(code === 0 ? out.trim() : null));
304
+ });
305
+ }
306
+ async function ensureNode(root, pin, o) {
307
+ const platform = o.platform ?? process.platform;
308
+ const arch = o.arch ?? process.arch;
309
+ const glibc = o.glibc !== void 0 ? o.glibc : platform === "linux" ? runningGlibc() : null;
310
+ const key = nodeKey(platform, arch, glibc);
311
+ const expected = key === null ? void 0 : pin.sha256[key];
312
+ if (key === null || expected === void 0) {
313
+ throw new CliError("UPDATE_FAILED", `no pinned Node for ${key ?? `${platform}-${arch}`}`);
314
+ }
315
+ return withRuntimeLock(
316
+ root,
317
+ async () => {
318
+ const dir = join(root, "node", pin.version);
319
+ const bin = nodeBinPath(root, pin.version, platform);
320
+ if (completeValid(dir) && existsSync(bin)) {
321
+ await touchComplete(dir);
322
+ return bin;
323
+ }
324
+ if (existsSync(bin) && await nodeVersionOf(bin) === `v${pin.version}`) {
325
+ await markComplete(dir, pin.version);
326
+ return bin;
327
+ }
328
+ const made = [];
329
+ try {
330
+ await mkdir(tmpOf(root), { recursive: true });
331
+ const artifact = nodeArtifact(pin.version, key);
332
+ let got;
333
+ try {
334
+ if (o.archivePath !== void 0) {
335
+ if ((await stat(o.archivePath)).size > NODE_MAX_BYTES) {
336
+ throw new CliError("UPDATE_FAILED", "The bootstrap Node archive is too large.");
337
+ }
338
+ const archive = await readFile(o.archivePath);
339
+ const file = join(tmpOf(root), `dl-${rand()}`);
340
+ await writeFile(file, archive, { mode: 384 });
341
+ got = { file, digest: createHash("sha256").update(archive).digest() };
342
+ } else if (o.proxyEnv !== void 0) {
343
+ got = await downloadViaCurl(artifact.url, {
344
+ dir: tmpOf(root),
345
+ maxBytes: NODE_MAX_BYTES,
346
+ timeoutMs: o.timeoutMs,
347
+ env: o.proxyEnv
348
+ });
349
+ } else {
350
+ got = await download(artifact.url, {
351
+ dir: tmpOf(root),
352
+ maxBytes: NODE_MAX_BYTES,
353
+ timeoutMs: o.timeoutMs,
354
+ hash: "sha256",
355
+ fetchImpl: o.fetchImpl
356
+ });
357
+ }
358
+ } catch (err) {
359
+ if (err instanceof CliError && err.code === "NETWORK_ERROR") {
360
+ throw new CliError("NETWORK_ERROR", err.message, { fix: NODE_FIX, cause: err });
361
+ }
362
+ throw err;
363
+ }
364
+ made.push(got.file);
365
+ if (got.digest.toString("hex") !== expected) {
366
+ throw new CliError(
367
+ "UPDATE_FAILED",
368
+ `the Node ${pin.version} download did not match its pinned checksum`
369
+ );
370
+ }
371
+ const stage = join(tmpOf(root), `node-${rand()}`);
372
+ made.push(stage);
373
+ await mkdir(stage);
374
+ await extract(got.file, stage, { member: artifact.member, strip: 1, platform });
375
+ const staged = join(stage, relative(dir, bin));
376
+ if (platform !== "win32") await chmod(staged, 493);
377
+ const said2 = await nodeVersionOf(staged);
378
+ if (said2 !== `v${pin.version}`) {
379
+ throw new CliError(
380
+ "UPDATE_FAILED",
381
+ `the downloaded Node ${pin.version} did not run (it printed ${said2 ?? "nothing"})`
382
+ );
383
+ }
384
+ await markComplete(stage, pin.version);
385
+ await trash(root, dir, platform);
386
+ await mkdir(dirname(dir), { recursive: true });
387
+ await renameDir(stage, dir, platform);
388
+ return bin;
389
+ } finally {
390
+ for (const path of made)
391
+ await rm(path, { recursive: true, force: true }).catch(() => void 0);
392
+ }
393
+ },
394
+ o
395
+ );
396
+ }
397
+ var NOT_COPIED = /* @__PURE__ */ new Set(["src", ".git", "runtime"]);
398
+ function copied(packageRoot, src) {
399
+ const rel = relative(packageRoot, src);
400
+ if (rel === "") return true;
401
+ const parts = rel.split(sep);
402
+ if (parts.includes("node_modules")) return false;
403
+ return !NOT_COPIED.has(parts[0]);
404
+ }
405
+ async function tally(dir, keep) {
406
+ let files = 0;
407
+ let bytes = 0;
408
+ const walk = async (current) => {
409
+ for (const entry of await readdir(current, { withFileTypes: true })) {
410
+ const path = join(current, entry.name);
411
+ if (!keep(path)) continue;
412
+ if (entry.isDirectory()) await walk(path);
413
+ else {
414
+ files += 1;
415
+ bytes += (await stat(path)).size;
416
+ }
417
+ }
418
+ };
419
+ await walk(dir);
420
+ return { files, bytes };
421
+ }
422
+ async function packageVersion(dir) {
423
+ return JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
424
+ }
425
+ async function stageSelf(root, packageRoot) {
426
+ const { version } = await packageVersion(packageRoot);
427
+ if (typeof version !== "string" || parseVersion(version) === null) {
428
+ throw new CliError("UPDATE_FAILED", `${packageRoot} names no tenjin-cli version`);
429
+ }
430
+ const stage = join(tmpOf(root), `stage-${version}-${rand()}`);
431
+ try {
432
+ await mkdir(tmpOf(root), { recursive: true });
433
+ await cp(packageRoot, stage, { recursive: true, filter: (src) => copied(packageRoot, src) });
434
+ const want = await tally(packageRoot, (p) => copied(packageRoot, p));
435
+ const got = await tally(stage, () => true);
436
+ if (want.files !== got.files || want.bytes !== got.bytes) {
437
+ throw new CliError(
438
+ "UPDATE_FAILED",
439
+ `the copy of tenjin-cli ${version} is incomplete (${got.files} of ${want.files} files)`
440
+ );
441
+ }
442
+ if ((await packageVersion(stage)).version !== version) {
443
+ throw new CliError(
444
+ "UPDATE_FAILED",
445
+ `the copy of tenjin-cli ${version} names another version`
446
+ );
447
+ }
448
+ return stage;
449
+ } catch (err) {
450
+ await rm(stage, { recursive: true, force: true }).catch(() => void 0);
451
+ throw err;
452
+ }
453
+ }
454
+ var REGISTRY = "https://registry.npmjs.org/tenjin-cli";
455
+ var REGISTRY_FIX = "Check access to registry.npmjs.org and run `tenjin update` again.";
456
+ var RELEASE_WORKFLOW = {
457
+ repository: "https://github.com/BackTrackCo/tenjin-agent",
458
+ path: ".github/workflows/release.yml",
459
+ ref: "refs/heads/main"
460
+ };
461
+ var SLSA_PROVENANCE = "https://slsa.dev/provenance/v1";
462
+ var ATTESTATIONS = "https://registry.npmjs.org/-/npm/v1/attestations";
463
+ function isReleaseWorkflow(workflow) {
464
+ if (typeof workflow !== "object" || workflow === null || Array.isArray(workflow)) return false;
465
+ const named = workflow;
466
+ const want = Object.entries(RELEASE_WORKFLOW);
467
+ return Object.keys(named).length === want.length && want.every(([key, value]) => named[key] === value);
468
+ }
469
+ function provenanceProblem(attestations, version, sha512Hex) {
470
+ const list = attestations?.attestations;
471
+ if (!Array.isArray(list)) return "npm holds no attestations for it";
472
+ const provenance = list.find(
473
+ (a) => a?.predicateType === SLSA_PROVENANCE
474
+ );
475
+ if (provenance === void 0) return "npm holds no build provenance for it";
476
+ const payload = provenance.bundle?.dsseEnvelope?.payload;
477
+ if (typeof payload !== "string") return "its provenance carries no statement";
478
+ let statement;
479
+ try {
480
+ statement = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
481
+ } catch {
482
+ return "its provenance statement is not JSON";
483
+ }
484
+ if (statement?.predicateType !== SLSA_PROVENANCE) return "its statement is not SLSA provenance";
485
+ const name = `pkg:npm/tenjin-cli@${version}`;
486
+ const subject = Array.isArray(statement.subject) ? statement.subject.find(
487
+ (s) => s?.name === name
488
+ ) : void 0;
489
+ if (subject === void 0) return `its provenance does not name ${name}`;
490
+ const digest = subject.digest?.sha512;
491
+ if (typeof digest !== "string" || digest.toLowerCase() !== sha512Hex) {
492
+ return "its provenance names another sha512 than the registry does";
493
+ }
494
+ if (!isReleaseWorkflow(statement.predicate?.buildDefinition?.externalParameters?.workflow)) {
495
+ return "it was built by something other than Tenjin's release workflow on main";
496
+ }
497
+ return null;
498
+ }
499
+ async function attestationsOf(version, o) {
500
+ try {
501
+ const res = await o.fetchImpl(`${ATTESTATIONS}/tenjin-cli@${version}`, {
502
+ signal: AbortSignal.timeout(o.timeoutMs),
503
+ headers: { accept: "application/json" }
504
+ });
505
+ if (res.status === 404) return null;
506
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
507
+ return await res.json();
508
+ } catch (err) {
509
+ throw new CliError(
510
+ "NETWORK_ERROR",
511
+ `could not read the build provenance of tenjin-cli ${version} from the npm registry: ${err instanceof Error ? err.message : String(err)}`,
512
+ { fix: REGISTRY_FIX, cause: err }
513
+ );
514
+ }
515
+ }
516
+ async function checkReleaseProvenance(version, o) {
517
+ const fetchImpl = o.fetchImpl ?? fetch;
518
+ let meta;
519
+ try {
520
+ const res = await fetchImpl(`${REGISTRY}/${version}`, {
521
+ signal: AbortSignal.timeout(o.timeoutMs),
522
+ headers: { accept: "application/json" }
523
+ });
524
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
525
+ meta = await res.json();
526
+ } catch (err) {
527
+ throw new CliError(
528
+ "NETWORK_ERROR",
529
+ `could not read tenjin-cli ${version} from the npm registry: ${err instanceof Error ? err.message : String(err)}`,
530
+ { fix: REGISTRY_FIX, cause: err }
531
+ );
532
+ }
533
+ const tarball = meta.dist?.tarball;
534
+ const integrity = typeof meta.dist?.integrity === "string" ? meta.dist.integrity.split(/\s+/).find((h) => h.startsWith("sha512-")) : void 0;
535
+ if (typeof tarball !== "string" || !tarball.startsWith(`${REGISTRY}/-/`)) {
536
+ throw new CliError(
537
+ "UPDATE_FAILED",
538
+ `tenjin-cli ${version} names a tarball outside the npm registry`
539
+ );
540
+ }
541
+ if (integrity === void 0) {
542
+ throw new CliError("UPDATE_FAILED", `tenjin-cli ${version} carries no sha512 integrity`);
543
+ }
544
+ const sha512Hex = Buffer.from(integrity.slice("sha512-".length), "base64").toString("hex");
545
+ const problem = provenanceProblem(
546
+ await attestationsOf(version, { timeoutMs: o.timeoutMs, fetchImpl }),
547
+ version,
548
+ sha512Hex
549
+ );
550
+ if (problem !== null) {
551
+ throw new CliError(
552
+ "UPDATE_FAILED",
553
+ `tenjin-cli ${version} has no valid build provenance from Tenjin's release workflow (${problem}), so it was not installed`,
554
+ {
555
+ fix: "Nothing to do: the version you have keeps running. Tenjin installs only releases npm shows were built by its own release workflow."
556
+ }
557
+ );
558
+ }
559
+ return { tarball, integrity, sha512Hex };
560
+ }
561
+ async function stageTarball(root, version, o) {
562
+ const fetchImpl = o.fetchImpl ?? fetch;
563
+ const { tarball, integrity, sha512Hex } = await checkReleaseProvenance(version, {
564
+ timeoutMs: o.timeoutMs,
565
+ fetchImpl
566
+ });
567
+ await mkdir(tmpOf(root), { recursive: true });
568
+ const got = await download(tarball, {
569
+ dir: tmpOf(root),
570
+ maxBytes: TARBALL_MAX_BYTES,
571
+ timeoutMs: o.timeoutMs,
572
+ hash: "sha512",
573
+ fetchImpl
574
+ });
575
+ const stage = join(tmpOf(root), `stage-${version}-${rand()}`);
576
+ try {
577
+ if (got.digest.toString("base64") !== integrity.slice("sha512-".length) || got.digest.toString("hex") !== sha512Hex) {
578
+ throw new CliError(
579
+ "UPDATE_FAILED",
580
+ `the tenjin-cli ${version} tarball did not match its integrity`
581
+ );
582
+ }
583
+ await mkdir(stage);
584
+ await extract(got.file, stage, { strip: 1 });
585
+ const pkg = await packageVersion(stage);
586
+ if (pkg.name !== "tenjin-cli" || pkg.version !== version) {
587
+ throw new CliError(
588
+ "UPDATE_FAILED",
589
+ `the tarball for tenjin-cli ${version} holds another package`
590
+ );
591
+ }
592
+ return stage;
593
+ } catch (err) {
594
+ await rm(stage, { recursive: true, force: true }).catch(() => void 0);
595
+ throw err;
596
+ } finally {
597
+ await rm(got.file, { force: true }).catch(() => void 0);
598
+ }
599
+ }
600
+ async function placeVersion(root, stageDir, version, o = {}) {
601
+ return withRuntimeLock(
602
+ root,
603
+ async () => {
604
+ const dir = versionDir(root, version);
605
+ if (completeValid(dir)) {
606
+ await touchComplete(dir);
607
+ await rm(stageDir, { recursive: true, force: true });
608
+ return dir;
609
+ }
610
+ await markComplete(stageDir, version);
611
+ await trash(root, dir, o.platform);
612
+ await mkdir(dirname(dir), { recursive: true });
613
+ await renameDir(stageDir, dir, o.platform);
614
+ return dir;
615
+ },
616
+ o
617
+ );
618
+ }
619
+ var spawnVerify = (command, args, o) => new Promise((done) => {
620
+ const child = spawn(command, args, {
621
+ env: o.env,
622
+ shell: false,
623
+ stdio: "pipe",
624
+ windowsHide: true
625
+ });
626
+ let stdout = "";
627
+ let stderr = "";
628
+ let settled = false;
629
+ const finish = (code, matched) => {
630
+ if (settled) return;
631
+ settled = true;
632
+ clearTimeout(timer);
633
+ if (child.exitCode === null) child.kill();
634
+ done({ code, stdout, stderr, matched });
635
+ };
636
+ const timer = setTimeout(() => finish(null, false), o.timeoutMs);
637
+ child.stdout.setEncoding("utf8");
638
+ child.stderr.setEncoding("utf8");
639
+ child.stdout.on("data", (chunk) => {
640
+ stdout += chunk;
641
+ if (o.until?.(stdout) === true) finish(0, true);
642
+ });
643
+ child.stderr.on("data", (chunk) => {
644
+ if (stderr.length < 4096) stderr += chunk;
645
+ });
646
+ child.stdin.on("error", () => void 0);
647
+ child.on("error", (err) => {
648
+ stderr += err.message;
649
+ finish(null, false);
650
+ });
651
+ child.on("close", (code) => finish(code, false));
652
+ child.stdin.write(o.input);
653
+ if (o.until === void 0) child.stdin.end();
654
+ });
655
+ var VERIFY_VERSION_MS = 1e4;
656
+ var VERIFY_HOOKS_MS = 1e4;
657
+ var VERIFY_MCP_MS = 15e3;
658
+ var said = (run) => {
659
+ const text = run.stderr.trim().slice(0, 200);
660
+ return `${run.code === null ? "no exit in time" : `exit ${run.code}`}${text ? `: ${text}` : ""}`;
661
+ };
662
+ async function verifyBuild(launch, version, o = {}) {
663
+ const run = o.spawnImpl ?? spawnVerify;
664
+ const deadline = Date.now() + (o.timeoutMs ?? VERIFY_VERSION_MS + VERIFY_HOOKS_MS + VERIFY_MCP_MS);
665
+ const budget = (own) => Math.min(own, deadline - Date.now());
666
+ const outOfTime = { ok: false, reason: `tenjin-cli ${version} was not checked in time` };
667
+ const data = await mkdtemp(join(tmpdir(), "tenjin-verify-"));
668
+ const env = {
669
+ ...process.env,
670
+ TENJIN_DATA_DIR: data,
671
+ TENJIN_NO_UPDATE_CHECK: "1",
672
+ TENJIN_HANDOFF: "1"
673
+ };
674
+ const bounded = (command, args, input, ms, until) => {
675
+ let timer;
676
+ return Promise.race([
677
+ run(command, args, { env, input, timeoutMs: ms, until }),
678
+ new Promise((done) => timer = setTimeout(() => done(null), ms + 250))
679
+ ]).finally(() => clearTimeout(timer));
680
+ };
681
+ try {
682
+ let ms = budget(VERIFY_VERSION_MS);
683
+ if (ms <= 0) return outOfTime;
684
+ const shown = await bounded(launch.node, [launch.entry, "--version"], "", ms);
685
+ if (shown === null) return outOfTime;
686
+ if (shown.code !== 0 || shown.stdout.trim() !== version) {
687
+ return {
688
+ ok: false,
689
+ reason: `tenjin-cli ${version} did not start (${shown.code === 0 ? `it printed ${shown.stdout.trim().slice(0, 50) || "nothing"}` : said(shown)})`
690
+ };
691
+ }
692
+ ms = budget(VERIFY_HOOKS_MS);
693
+ if (ms <= 0) return outOfTime;
694
+ const { hooks } = renderPluginHooks(launch.entry, { node: launch.node });
695
+ const commands = Object.entries(hooks).flatMap(
696
+ ([event, groups]) => handlersIn({ hooks: { [event]: groups } }).filter((h) => h.type === "command").map((h) => ({ event, command: h.command, args: h.args }))
697
+ );
698
+ const results = await Promise.all(
699
+ commands.map(async (c) => ({
700
+ ...c,
701
+ out: await bounded(
702
+ c.command,
703
+ c.args,
704
+ JSON.stringify({ session_id: "verify", hook_event_name: c.event }),
705
+ ms
706
+ )
707
+ }))
708
+ );
709
+ for (const { event, out } of results) {
710
+ if (out === null) return outOfTime;
711
+ if (out.code !== 0) return { ok: false, reason: `its ${event} hook failed (${said(out)})` };
712
+ if (out.stdout.trim().length > 0) {
713
+ try {
714
+ JSON.parse(out.stdout);
715
+ } catch {
716
+ return { ok: false, reason: `its ${event} hook printed something other than JSON` };
717
+ }
718
+ }
719
+ }
720
+ ms = budget(VERIFY_MCP_MS);
721
+ if (ms <= 0) return outOfTime;
722
+ const server = renderPluginMcp(launch.entry, { node: launch.node }).mcpServers.router;
723
+ const initialize = `${JSON.stringify({
724
+ jsonrpc: "2.0",
725
+ id: 1,
726
+ method: "initialize",
727
+ params: {
728
+ protocolVersion: "2025-06-18",
729
+ capabilities: {},
730
+ clientInfo: { name: "tenjin-verify", version }
731
+ }
732
+ })}
733
+ `;
734
+ const answered = await bounded(
735
+ server.command,
736
+ server.args,
737
+ initialize,
738
+ ms,
739
+ (stdout) => stdout.split("\n").some((line) => line.includes('"id":1') && line.includes('"result"'))
740
+ );
741
+ if (answered === null || !answered.matched) {
742
+ return {
743
+ ok: false,
744
+ reason: `its MCP server did not answer initialize (${answered === null ? "no answer in time" : said(answered)})`
745
+ };
746
+ }
747
+ return { ok: true };
748
+ } finally {
749
+ await rm(data, { recursive: true, force: true }).catch(() => void 0);
750
+ }
751
+ }
752
+ var launcherNames = (platform) => platform === "win32" ? ["tenjin", "tenjin.cmd"] : ["tenjin"];
753
+ function pathLine(env, _home, platform) {
754
+ if (platform === "win32") {
755
+ return `[Environment]::SetEnvironmentVariable('Path', "$env:USERPROFILE\\.local\\bin;" + [Environment]::GetEnvironmentVariable('Path','User'), 'User')`;
756
+ }
757
+ const add = `echo 'export PATH="$HOME/.local/bin:$PATH"' >>`;
758
+ const shell = basename(env.SHELL ?? "");
759
+ if (shell === "zsh") return `${add} ~/.zshrc`;
760
+ if (shell === "bash") return `${add} ${platform === "darwin" ? "~/.bash_profile" : "~/.bashrc"}`;
761
+ if (shell === "fish") return "fish_add_path ~/.local/bin";
762
+ return 'export PATH="$HOME/.local/bin:$PATH"';
763
+ }
764
+ function onPath(dir, env, platform) {
765
+ const p = platform === "win32" ? win32 : posix;
766
+ const raw = (platform === "win32" ? env.Path ?? env.PATH : env.PATH) ?? "";
767
+ const norm = (value) => {
768
+ const full = p.resolve(value).replace(/[\\/]+$/, "");
769
+ return platform === "win32" ? full.toLowerCase() : full;
770
+ };
771
+ const want = norm(dir);
772
+ return raw.split(p.delimiter).filter((entry) => entry.length > 0).some((entry) => norm(entry) === want);
773
+ }
774
+ async function npmsOwn(path, isLink, body) {
775
+ if (isLink) {
776
+ try {
777
+ return packageRootOf(dirname(await realpath(path))) !== null;
778
+ } catch {
779
+ return false;
780
+ }
781
+ }
782
+ return body !== null && /node_modules[\\/]tenjin-cli[\\/]/.test(body);
783
+ }
784
+ async function inspectLauncher(path) {
785
+ let link;
786
+ try {
787
+ link = await lstat(path);
788
+ } catch {
789
+ return { state: "absent", body: null };
790
+ }
791
+ const body = await readFile(path, "utf8").catch(() => null);
792
+ if (await npmsOwn(path, link.isSymbolicLink(), body)) return { state: "npm", body };
793
+ if (!link.isSymbolicLink() && body !== null && body.includes(LAUNCHER_MARKER)) {
794
+ return { state: "ours", body };
795
+ }
796
+ return { state: "foreign", body };
797
+ }
798
+ async function writeLaunchers(home, launch, o) {
799
+ const platform = o.platform ?? launch.platform ?? process.platform;
800
+ const dir = launcherDir(home);
801
+ const paths = launcherNames(platform).map((name) => join(dir, name));
802
+ const found = onPath(dir, o.env, platform);
803
+ const where = { onPath: found, ...found ? {} : { pathLine: pathLine(o.env, home, platform) } };
804
+ let bodies;
805
+ try {
806
+ const full = { ...launch, platform, home: launch.home ?? home };
807
+ bodies = [renderLauncherSh(full), ...platform === "win32" ? [renderLauncherCmd(full)] : []];
808
+ } catch (err) {
809
+ return {
810
+ paths,
811
+ state: "failed",
812
+ ...where,
813
+ reason: err instanceof Error ? err.message : String(err)
814
+ };
815
+ }
816
+ const existing = await Promise.all(paths.map(inspectLauncher));
817
+ const foreign = paths.filter((_, i) => existing[i].state === "foreign");
818
+ if (foreign.length > 0) {
819
+ return { paths, state: "foreign", ...where, reason: `${foreign.join(", ")} is not Tenjin's` };
820
+ }
821
+ if (existing.some((f) => f.state === "npm")) return { paths, state: "npm", ...where };
822
+ if (existing.every((f, i) => f.body === bodies[i])) return { paths, state: "current", ...where };
823
+ try {
824
+ for (const [i, path] of paths.entries()) {
825
+ if (existing[i].body !== bodies[i]) {
826
+ await writeFileAtomic(path, bodies[i], { mode: 493, dirMode: 493 });
827
+ }
828
+ }
829
+ } catch (err) {
830
+ return {
831
+ paths,
832
+ state: "failed",
833
+ ...where,
834
+ reason: err instanceof Error ? err.message : String(err)
835
+ };
836
+ }
837
+ return { paths, state: "written", ...where };
838
+ }
839
+ async function removeLaunchers(home, platform = process.platform) {
840
+ const removed = [];
841
+ const left = [];
842
+ for (const name of ["tenjin", "tenjin.cmd"]) {
843
+ const path = join(launcherDir(home), name);
844
+ const found = await inspectLauncher(path);
845
+ if (found.state === "absent") continue;
846
+ if (found.state !== "ours") {
847
+ if (name === "tenjin" || platform === "win32") left.push(path);
848
+ continue;
849
+ }
850
+ try {
851
+ await rm(path, { force: true });
852
+ removed.push(path);
853
+ } catch {
854
+ left.push(path);
855
+ }
856
+ }
857
+ return { removed, left };
858
+ }
859
+ function pointerOf(raw) {
860
+ if (typeof raw !== "object" || raw === null) return null;
861
+ const { cli, node } = raw;
862
+ if (typeof cli !== "string" || parseVersion(cli) === null) return null;
863
+ if (typeof node !== "string" || !NODE_VERSION_RE.test(node)) return null;
864
+ return { cli, node };
865
+ }
866
+ function readRawState(root) {
867
+ try {
868
+ const raw = JSON.parse(readFileSync(runtimeStatePath(root), "utf8"));
869
+ return {
870
+ current: pointerOf(raw.current),
871
+ previous: pointerOf(raw.previous),
872
+ pending: pointerOf(raw.pending),
873
+ ...typeof raw.activation === "string" ? { activation: raw.activation } : {}
874
+ };
875
+ } catch {
876
+ return { current: null, previous: null, pending: null };
877
+ }
878
+ }
879
+ async function writeState(root, state) {
880
+ await writeFileAtomic(
881
+ runtimeStatePath(root),
882
+ `${JSON.stringify({ schemaVersion: 1, ...state }, null, 2)}
883
+ `
884
+ );
885
+ }
886
+ var readOrNull = (path) => readFile(path, "utf8").catch(() => null);
887
+ async function putBack(path, body, mode) {
888
+ if (body === null) await rm(path, { force: true });
889
+ else await writeFileAtomic(path, body, { mode });
890
+ }
891
+ function renderOrder(files) {
892
+ const rank = (path) => {
893
+ const inHost = path.slice(path.indexOf("/") + 1);
894
+ if (inHost === "tenjin/hooks/hooks.json") return 1;
895
+ if (inHost.startsWith("tenjin/bin/")) return 2;
896
+ if (/^tenjin\/\.(claude|codex)-plugin\/plugin\.json$/.test(inHost)) return 3;
897
+ if ([".claude-plugin/marketplace.json", ".agents/plugins/marketplace.json"].includes(inHost)) {
898
+ return 4;
899
+ }
900
+ return 0;
901
+ };
902
+ return Object.keys(files).sort((a, b) => rank(a) - rank(b));
903
+ }
904
+ function runtimeMod(launch) {
905
+ return readModSources(join(dirname(launch.entry), "hosts", "claude", PLUGIN_DIR));
906
+ }
907
+ function runtimeHostFiles(root, version, launch, mod) {
908
+ const under = (host, files) => Object.entries(files).map(([path, body]) => [`${host}/${path}`, body]);
909
+ return Object.fromEntries([
910
+ ...under("claude", renderHostFiles(version, { launch, mod })),
911
+ ...under(
912
+ "codex",
913
+ renderCodexHostFiles({ launch, binDir: join(root, "codex", PLUGIN_DIR, "bin") })
914
+ )
915
+ ]);
916
+ }
917
+ var modeFor = (path) => path.includes("/tenjin/bin/") ? 493 : 420;
918
+ function runnable(root, p, platform) {
919
+ return existsSync(nodeBinPath(root, p.node, platform)) && existsSync(versionEntry(root, p.cli));
920
+ }
921
+ var NewerRuntime = class extends Error {
922
+ constructor(current) {
923
+ super(`Tenjin ${current.cli} is already set up here`);
924
+ this.current = current;
925
+ }
926
+ current;
927
+ };
928
+ async function activate(root, next, o) {
929
+ const platform = o.platform ?? process.platform;
930
+ const launch = {
931
+ node: nodeBinPath(root, next.node, platform),
932
+ entry: versionEntry(root, next.cli),
933
+ platform,
934
+ home: o.home
935
+ };
936
+ return withRuntimeLock(
937
+ root,
938
+ async () => {
939
+ const old = readRawState(root);
940
+ if (old.current !== null && isNewer(old.current.cli, next.cli) && runnable(root, old.current, platform)) {
941
+ throw new NewerRuntime(old.current);
942
+ }
943
+ if (!completeValid(versionDir(root, next.cli)) || !existsSync(launch.entry) || !completeValid(join(root, "node", next.node)) || !existsSync(launch.node)) {
944
+ throw new CliError(
945
+ "UPDATE_FAILED",
946
+ `tenjin-cli ${next.cli} or its Node ${next.node} is no longer in place in ${root}, so the runtime was not switched to it`
947
+ );
948
+ }
949
+ const oldStateText = await readOrNull(runtimeStatePath(root));
950
+ await writeState(root, { ...old, pending: next });
951
+ const files = runtimeHostFiles(root, next.cli, launch, await runtimeMod(launch));
952
+ const order = renderOrder(files);
953
+ const oldBodies = /* @__PURE__ */ new Map();
954
+ try {
955
+ for (const path of order) {
956
+ const target = join(root, path);
957
+ oldBodies.set(path, await readOrNull(target));
958
+ await writeFileAtomic(target, files[path], { mode: modeFor(path) });
959
+ }
960
+ } catch (err) {
961
+ for (const [path, body] of [...oldBodies].reverse()) {
962
+ await putBack(join(root, path), body, modeFor(path)).catch(() => void 0);
963
+ }
964
+ throw err;
965
+ }
966
+ const launcherPaths = launcherNames(platform).map((n) => join(launcherDir(o.home), n));
967
+ const oldLaunchers = await Promise.all(launcherPaths.map(inspectLauncher));
968
+ const launcher = await writeLaunchers(o.home, launch, { env: o.env, platform });
969
+ const previous = old.current !== null && old.current.cli !== next.cli ? old.current : old.previous;
970
+ const activation = rand();
971
+ await writeState(root, { current: next, previous, pending: null, activation });
972
+ const restore = () => withRuntimeLock(
973
+ root,
974
+ async () => {
975
+ if (readRawState(root).activation !== activation) return;
976
+ for (const path of [...order].reverse()) {
977
+ await putBack(join(root, path), oldBodies.get(path) ?? null, modeFor(path));
978
+ }
979
+ if (oldStateText === null) await rm(runtimeStatePath(root), { force: true });
980
+ else await writeFileAtomic(runtimeStatePath(root), oldStateText);
981
+ for (const [i, path] of launcherPaths.entries()) {
982
+ const before = oldLaunchers[i];
983
+ if (before.state === "ours") await putBack(path, before.body, 493);
984
+ else if (before.state === "absent" && (await inspectLauncher(path)).state === "ours") {
985
+ await rm(path, { force: true });
986
+ }
987
+ }
988
+ },
989
+ o
990
+ );
991
+ return { previous: old.current, launcher, restore };
992
+ },
993
+ o
994
+ );
995
+ }
996
+ var IN_USE = "in use; removed by a later install";
997
+ var PLACED = "placed for an activation still on its way";
998
+ var TMP_MAX_AGE_MS = 60 * 6e4;
999
+ var PLACED_GRACE_MS = 15 * 6e4;
1000
+ var KEPT_FOR_FOLDER = "a plugin folder runs it";
1001
+ async function collect(root, o = {}) {
1002
+ const isAlive = o.isAlive ?? pidAlive;
1003
+ const now = o.now ?? Date.now;
1004
+ return withRuntimeLock(
1005
+ root,
1006
+ async () => {
1007
+ const state = readRawState(root);
1008
+ const removed = [];
1009
+ const kept = [];
1010
+ const keepNode = /* @__PURE__ */ new Set();
1011
+ const roles = /* @__PURE__ */ new Map();
1012
+ for (const role of ["current", "previous", "pending"]) {
1013
+ const p = state[role];
1014
+ if (p === null) continue;
1015
+ if (!roles.has(p.cli)) roles.set(p.cli, role);
1016
+ keepNode.add(p.node);
1017
+ }
1018
+ for (const p of o.keep ?? []) {
1019
+ if (!roles.has(p.cli)) roles.set(p.cli, KEPT_FOR_FOLDER);
1020
+ keepNode.add(p.node);
1021
+ }
1022
+ const remove = async (path) => {
1023
+ const to = join(tmpOf(root), `trash-${rand()}`);
1024
+ try {
1025
+ await mkdir(tmpOf(root), { recursive: true });
1026
+ await renameDir(path, to, o.platform);
1027
+ } catch (err) {
1028
+ kept.push({
1029
+ path,
1030
+ reason: ["EBUSY", "EPERM", "ENOTEMPTY"].some((c) => hasCode(err, c)) ? IN_USE : `not removed: ${err instanceof Error ? err.message : String(err)}`
1031
+ });
1032
+ return;
1033
+ }
1034
+ removed.push(path);
1035
+ await rm(to, { recursive: true, force: true }).catch(() => void 0);
1036
+ };
1037
+ const placedJustNow = async (dir) => completeValid(dir) && await stat(join(dir, ".complete")).then(
1038
+ (s) => now() - s.mtimeMs < PLACED_GRACE_MS,
1039
+ () => false
1040
+ );
1041
+ const versions = join(root, "versions");
1042
+ for (const name of await readdir(versions).catch(() => [])) {
1043
+ const dir = join(versions, name);
1044
+ const liveDir = join(dir, ".live");
1045
+ let live = false;
1046
+ for (const pid of await readdir(liveDir).catch(() => [])) {
1047
+ if (/^\d+$/.test(pid) && isAlive(Number(pid))) live = true;
1048
+ else await rm(join(liveDir, pid), { force: true }).catch(() => void 0);
1049
+ }
1050
+ const role = roles.get(name);
1051
+ if (role !== void 0) {
1052
+ kept.push({ path: dir, reason: role });
1053
+ } else if (live) {
1054
+ kept.push({ path: dir, reason: "a running tenjin mcp uses it" });
1055
+ const pin = readNodePin(dir);
1056
+ if (pin !== null) keepNode.add(pin.version);
1057
+ } else if (await placedJustNow(dir)) {
1058
+ kept.push({ path: dir, reason: PLACED });
1059
+ const pin = readNodePin(dir);
1060
+ if (pin !== null) keepNode.add(pin.version);
1061
+ } else {
1062
+ await remove(dir);
1063
+ }
1064
+ }
1065
+ const nodes = join(root, "node");
1066
+ for (const name of await readdir(nodes).catch(() => [])) {
1067
+ const dir = join(nodes, name);
1068
+ if (keepNode.has(name)) kept.push({ path: dir, reason: "pinned by a kept version" });
1069
+ else if (await placedJustNow(dir)) kept.push({ path: dir, reason: PLACED });
1070
+ else await remove(dir);
1071
+ }
1072
+ for (const name of await readdir(tmpOf(root)).catch(() => [])) {
1073
+ const path = join(tmpOf(root), name);
1074
+ const age = await stat(path).then(
1075
+ (s) => now() - s.mtimeMs,
1076
+ () => 0
1077
+ );
1078
+ if (name.startsWith("trash-") || age > TMP_MAX_AGE_MS) {
1079
+ await rm(path, { recursive: true, force: true }).catch(() => void 0);
1080
+ }
1081
+ }
1082
+ return { removed, kept };
1083
+ },
1084
+ o
1085
+ );
1086
+ }
1087
+ async function removeWhatCan(dir) {
1088
+ try {
1089
+ await rm(dir, { recursive: true, force: true });
1090
+ return [];
1091
+ } catch (err) {
1092
+ if (!["EBUSY", "EPERM", "ENOTEMPTY"].some((c) => hasCode(err, c))) throw err;
1093
+ }
1094
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => null);
1095
+ if (entries === null) return [dir];
1096
+ const left = [];
1097
+ for (const entry of entries) {
1098
+ const path = join(dir, entry.name);
1099
+ if (entry.isDirectory()) left.push(...await removeWhatCan(path));
1100
+ else await rm(path, { force: true }).catch(() => left.push(path));
1101
+ }
1102
+ if (left.length === 0)
1103
+ await rm(dir, { recursive: true, force: true }).catch(() => left.push(dir));
1104
+ return left;
1105
+ }
1106
+ async function removeRuntime(root, o = {}) {
1107
+ if (!existsSync(root)) return { removed: false, left: [] };
1108
+ return withRuntimeLock(
1109
+ root,
1110
+ async () => {
1111
+ const left = await removeWhatCan(root);
1112
+ return { removed: left.length === 0, left };
1113
+ },
1114
+ o
1115
+ );
1116
+ }
1117
+ var REFRESH_BUDGET_MS = 35e3;
1118
+ var REFRESH_LOCK_MS = 5e3;
1119
+ var REFRESH_NODE_MS = 2e4;
1120
+ var REFRESH_VERIFY_MS = 18e3;
1121
+ var BUDGET_GONE = "the 35 s refresh budget ran out";
1122
+ var BudgetGone = class extends Error {
1123
+ constructor() {
1124
+ super(BUDGET_GONE);
1125
+ }
1126
+ };
1127
+ async function within(work, ms) {
1128
+ if (!Number.isFinite(ms)) return work;
1129
+ let timer;
1130
+ try {
1131
+ return await Promise.race([
1132
+ work,
1133
+ new Promise((_, fail) => timer = setTimeout(() => fail(new BudgetGone()), ms))
1134
+ ]);
1135
+ } finally {
1136
+ clearTimeout(timer);
1137
+ }
1138
+ }
1139
+ async function hostsMatch(root, version, launch) {
1140
+ const mod = await runtimeMod(launch);
1141
+ try {
1142
+ return Object.entries(runtimeHostFiles(root, version, launch, mod)).every(
1143
+ ([path, body]) => readFileSync(join(root, path), "utf8") === body
1144
+ );
1145
+ } catch {
1146
+ return false;
1147
+ }
1148
+ }
1149
+ async function setupRuntime(o) {
1150
+ const root = runtimeDir(o.dataDir);
1151
+ if (isSourceCheckout(o.moduleDir)) {
1152
+ return { state: "skipped", root, firstTime: false, launcher: null };
1153
+ }
1154
+ if (resolve(o.dataDir) !== resolve(defaultDataDir(o.home))) {
1155
+ return {
1156
+ state: "failed",
1157
+ root,
1158
+ firstTime: false,
1159
+ launcher: null,
1160
+ reason: "Plugin installation needs the default data directory.",
1161
+ fix: "Run without TENJIN_DATA_DIR."
1162
+ };
1163
+ }
1164
+ const platform = o.platform ?? process.platform;
1165
+ const arch = o.arch ?? process.arch;
1166
+ const deadline = o.refresh ? Date.now() + REFRESH_BUDGET_MS : Infinity;
1167
+ const left = (cap) => {
1168
+ if (!o.refresh) return Infinity;
1169
+ const ms = Math.min(cap, deadline - Date.now());
1170
+ if (ms <= 0) throw new BudgetGone();
1171
+ return ms;
1172
+ };
1173
+ const lockOpts = () => o.refresh ? { lockWaitMs: left(REFRESH_LOCK_MS) } : {};
1174
+ const firstTime = !existsSync(runtimeStatePath(root));
1175
+ const hostsDir = join(root, "claude");
1176
+ const launchOf = (p) => ({
1177
+ node: nodeBinPath(root, p.node, platform),
1178
+ entry: versionEntry(root, p.cli),
1179
+ platform,
1180
+ home: o.home
1181
+ });
1182
+ const runs = (p) => ({
1183
+ state: "kept",
1184
+ root,
1185
+ cli: p.cli,
1186
+ nodeVersion: p.node,
1187
+ node: launchOf(p).node,
1188
+ entry: launchOf(p).entry,
1189
+ hostsDir,
1190
+ firstTime,
1191
+ launcher: null
1192
+ });
1193
+ const keptNewer = (p) => ({
1194
+ ...runs(p),
1195
+ reason: `Tenjin ${p.cli} is already set up here; this ${o.version} did not replace it`,
1196
+ newer: true
1197
+ });
1198
+ const state = readRuntimeState(root);
1199
+ const usable = state !== null && runnable(root, state.current, platform) ? state.current : null;
1200
+ if (usable !== null && isNewer(usable.cli, o.version)) return keptNewer(usable);
1201
+ const alreadyCurrent = usable !== null && state !== null && usable.cli === o.version && state.pending === null && completeValid(versionDir(root, usable.cli)) && completeValid(join(root, "node", usable.node)) && await hostsMatch(root, o.version, launchOf(usable));
1202
+ const stillCurrent = (p) => withRuntimeLock(
1203
+ root,
1204
+ async () => {
1205
+ const now = readRawState(root);
1206
+ if (now.current !== null && isNewer(now.current.cli, p.cli) && runnable(root, now.current, platform)) {
1207
+ return keptNewer(now.current);
1208
+ }
1209
+ if (now.pending !== null || now.current?.cli !== p.cli || now.current.node !== p.node) {
1210
+ return null;
1211
+ }
1212
+ const launcher = await writeLaunchers(o.home, launchOf(p), { env: o.env, platform });
1213
+ return { ...runs(p), state: "current", launcher };
1214
+ },
1215
+ lockOpts()
1216
+ );
1217
+ const failed = (reason) => usable !== null ? { ...runs(usable), reason } : { state: "failed", root, firstTime, launcher: null, reason };
1218
+ let downloading = false;
1219
+ let usedProxyTransport = false;
1220
+ try {
1221
+ if (alreadyCurrent) {
1222
+ const current = await stillCurrent(usable);
1223
+ if (current !== null) return current;
1224
+ }
1225
+ const glibc = platform === "linux" ? runningGlibc() : null;
1226
+ const key = nodeKey(platform, arch, glibc);
1227
+ const unpinned = unpinnedPlatform(platform, arch, glibc);
1228
+ if (unpinned !== null) {
1229
+ return { ...failed(`no pinned Node for this platform, ${unpinned}`), unpinned };
1230
+ }
1231
+ const build = runtimeBuild(o.moduleDir);
1232
+ const packageRoot = build !== null ? versionDir(build.root, build.cli) : packageRootOf(o.moduleDir);
1233
+ const pin = packageRoot === null ? null : readNodePin(packageRoot);
1234
+ if (key === null || pin === null || pin.sha256[key] === void 0) {
1235
+ return failed(`no pinned Node for ${key ?? `${platform}-${arch}`}`);
1236
+ }
1237
+ const next = { cli: o.version, node: pin.version };
1238
+ if (build === null || build.cli !== o.version || resolve(build.root) !== resolve(root)) {
1239
+ const stage = await within(stageSelf(root, packageRoot), left(REFRESH_BUDGET_MS));
1240
+ await within(
1241
+ placeVersion(root, stage, o.version, { ...lockOpts(), platform }),
1242
+ left(REFRESH_BUDGET_MS)
1243
+ );
1244
+ }
1245
+ const nodeMs = left(REFRESH_NODE_MS);
1246
+ downloading = true;
1247
+ usedProxyTransport = o.fetchImpl === void 0 && proxySkipped(o.env, o.proxySupported) !== null;
1248
+ await within(
1249
+ ensureNode(root, pin, {
1250
+ ...lockOpts(),
1251
+ timeoutMs: Number.isFinite(nodeMs) ? nodeMs : 3e5,
1252
+ fetchImpl: o.fetchImpl,
1253
+ platform,
1254
+ arch,
1255
+ glibc,
1256
+ archivePath: o.env.TENJIN_BOOTSTRAP_NODE_ARCHIVE,
1257
+ proxyEnv: usedProxyTransport ? o.env : void 0
1258
+ }),
1259
+ nodeMs
1260
+ );
1261
+ downloading = false;
1262
+ const launch = launchOf(next);
1263
+ const verified = await (o.verify ?? verifyBuild)(
1264
+ launch,
1265
+ o.version,
1266
+ o.refresh ? { timeoutMs: left(REFRESH_VERIFY_MS) } : {}
1267
+ );
1268
+ if (!verified.ok) return failed(verified.reason.slice(0, 200));
1269
+ const activation = await activate(root, next, {
1270
+ ...lockOpts(),
1271
+ home: o.home,
1272
+ env: o.env,
1273
+ platform
1274
+ });
1275
+ return {
1276
+ state: "active",
1277
+ root,
1278
+ cli: next.cli,
1279
+ nodeVersion: next.node,
1280
+ node: launch.node,
1281
+ entry: launch.entry,
1282
+ hostsDir,
1283
+ firstTime,
1284
+ launcher: activation.launcher,
1285
+ restore: activation.restore
1286
+ };
1287
+ } catch (err) {
1288
+ if (err instanceof NewerRuntime) return keptNewer(err.current);
1289
+ const message = err instanceof Error ? err.message : String(err);
1290
+ const network = err instanceof CliError && err.code === "NETWORK_ERROR" || err instanceof BudgetGone;
1291
+ const skipped = downloading && network && !usedProxyTransport ? proxySkipped(o.env, o.proxySupported) : null;
1292
+ if (skipped !== null) {
1293
+ return {
1294
+ ...failed(`${skipped}: ${message}`.slice(0, 200)),
1295
+ fix: proxyNodeStep("tenjin install")
1296
+ };
1297
+ }
1298
+ return failed(message.slice(0, 200));
1299
+ }
1300
+ }
1301
+ export {
1302
+ NewerRuntime,
1303
+ activate,
1304
+ checkReleaseProvenance,
1305
+ collect,
1306
+ ensureNode,
1307
+ packageRootOf,
1308
+ pathLine,
1309
+ placeVersion,
1310
+ provenanceProblem,
1311
+ readNodePin,
1312
+ removeLaunchers,
1313
+ removeRuntime,
1314
+ setupRuntime,
1315
+ stageSelf,
1316
+ stageTarball,
1317
+ verifyBuild,
1318
+ withRuntimeLock,
1319
+ writeLaunchers
1320
+ };
1321
+ //# sourceMappingURL=runtime-UZOKSUZX.js.map