tenjin-cli 0.1.0-alpha.30 → 0.1.0-alpha.32

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 (280) hide show
  1. package/README.md +65 -116
  2. package/dist/{_esm-CE7KNONL.js → _esm-RLLC72MS.js} +127 -131
  3. package/dist/alive-MROUMFH3.js +38 -0
  4. package/dist/auto-update-OPWMRZLS.js +22 -0
  5. package/dist/{ccip-7RMRLAGV.js → ccip-DHDFKTQV.js} +2 -2
  6. package/dist/chunk-2GNOFONN.js +560 -0
  7. package/dist/chunk-2GNOFONN.js.map +1 -0
  8. package/dist/{chunk-TTNESUPQ.js → chunk-2GP3HRYK.js} +2120 -193
  9. package/dist/chunk-2GP3HRYK.js.map +1 -0
  10. package/dist/chunk-3623BLPV.js +184 -0
  11. package/dist/chunk-3623BLPV.js.map +1 -0
  12. package/dist/chunk-3AIHRXKO.js +72 -0
  13. package/dist/chunk-3AIHRXKO.js.map +1 -0
  14. package/dist/chunk-3DIL66VX.js +120 -0
  15. package/dist/chunk-3DIL66VX.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-3UCIG4TG.js +65 -0
  19. package/dist/chunk-3UCIG4TG.js.map +1 -0
  20. package/dist/{chunk-LFZJM56J.js → chunk-445VQTVM.js} +3 -3
  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-RAULEAZ6.js → chunk-4USCZ2NI.js} +3 -3
  24. package/dist/chunk-62KNUYWD.js +111 -0
  25. package/dist/chunk-62KNUYWD.js.map +1 -0
  26. package/dist/{chunk-POUWHWID.js → chunk-6CMM6YCB.js} +3 -3
  27. package/dist/{chunk-POUWHWID.js.map → chunk-6CMM6YCB.js.map} +1 -1
  28. package/dist/chunk-7WEQQJLG.js +68 -0
  29. package/dist/chunk-7WEQQJLG.js.map +1 -0
  30. package/dist/{chunk-3O2BQIF6.js → chunk-AD226HDR.js} +344 -534
  31. package/dist/chunk-AD226HDR.js.map +1 -0
  32. package/dist/chunk-ADV4LDTB.js +106 -0
  33. package/dist/chunk-ADV4LDTB.js.map +1 -0
  34. package/dist/{chunk-AWFUPKTM.js → chunk-AV5NZMYO.js} +15 -7
  35. package/dist/{chunk-AWFUPKTM.js.map → chunk-AV5NZMYO.js.map} +1 -1
  36. package/dist/chunk-B7EM4GGF.js +198 -0
  37. package/dist/chunk-B7EM4GGF.js.map +1 -0
  38. package/dist/chunk-BFDQ4WNW.js +119 -0
  39. package/dist/chunk-BFDQ4WNW.js.map +1 -0
  40. package/dist/{chunk-OSYTBCUC.js → chunk-BI673VEJ.js} +531 -503
  41. package/dist/chunk-BI673VEJ.js.map +1 -0
  42. package/dist/chunk-CEXSOI5R.js +808 -0
  43. package/dist/chunk-CEXSOI5R.js.map +1 -0
  44. package/dist/{chunk-OK2TDZQU.js → chunk-CISYM4EO.js} +9 -7
  45. package/dist/chunk-CISYM4EO.js.map +1 -0
  46. package/dist/{chunk-VFMQTSXG.js → chunk-D3ZURCG7.js} +3 -3
  47. package/dist/chunk-D5TOQSO4.js +474 -0
  48. package/dist/chunk-D5TOQSO4.js.map +1 -0
  49. package/dist/{chunk-P7LABKCW.js → chunk-DOQGNFHM.js} +33 -2
  50. package/dist/{chunk-P7LABKCW.js.map → chunk-DOQGNFHM.js.map} +1 -1
  51. package/dist/{chunk-QUVVWYJW.js → chunk-DRDUIZIA.js} +11 -9
  52. package/dist/{chunk-QUVVWYJW.js.map → chunk-DRDUIZIA.js.map} +1 -1
  53. package/dist/{chunk-O2FRQ2L2.js → chunk-DW4YTVR3.js} +5 -65
  54. package/dist/chunk-DW4YTVR3.js.map +1 -0
  55. package/dist/chunk-E7LGOMH6.js +449 -0
  56. package/dist/chunk-E7LGOMH6.js.map +1 -0
  57. package/dist/chunk-E7SW44LM.js +138 -0
  58. package/dist/chunk-E7SW44LM.js.map +1 -0
  59. package/dist/chunk-EDJWHDDL.js +33 -0
  60. package/dist/chunk-EDJWHDDL.js.map +1 -0
  61. package/dist/chunk-F3ED5WTR.js +13 -0
  62. package/dist/chunk-F3ED5WTR.js.map +1 -0
  63. package/dist/chunk-G75OPGAK.js +111 -0
  64. package/dist/chunk-G75OPGAK.js.map +1 -0
  65. package/dist/{chunk-YFQOA5AU.js → chunk-GAKUQHKA.js} +13 -17
  66. package/dist/{chunk-YFQOA5AU.js.map → chunk-GAKUQHKA.js.map} +1 -1
  67. package/dist/{chunk-PAYV4XUA.js → chunk-HDPUXS3Z.js} +20 -49
  68. package/dist/chunk-HDPUXS3Z.js.map +1 -0
  69. package/dist/{chunk-ORWL5BSN.js → chunk-HGZEPQUT.js} +2 -2
  70. package/dist/{chunk-HPWO4O6S.js → chunk-HREHWL32.js} +4 -4
  71. package/dist/{chunk-HPWO4O6S.js.map → chunk-HREHWL32.js.map} +1 -1
  72. package/dist/{chunk-VZGAONSJ.js → chunk-I5TDIUKM.js} +16 -35
  73. package/dist/chunk-I5TDIUKM.js.map +1 -0
  74. package/dist/{chunk-7QKHZQKW.js → chunk-IADZOXKN.js} +39 -6
  75. package/dist/chunk-IADZOXKN.js.map +1 -0
  76. package/dist/{chunk-U6YQ6FRI.js → chunk-IDTRSAHE.js} +32 -12
  77. package/dist/chunk-IDTRSAHE.js.map +1 -0
  78. package/dist/{chunk-SPAVAYSW.js → chunk-JEVQ5LKO.js} +7 -5
  79. package/dist/{chunk-SPAVAYSW.js.map → chunk-JEVQ5LKO.js.map} +1 -1
  80. package/dist/{chunk-EBVIKMCH.js → chunk-JKKAIPTU.js} +2 -2
  81. package/dist/chunk-JNJWBTU2.js +3497 -0
  82. package/dist/chunk-JNJWBTU2.js.map +1 -0
  83. package/dist/{chunk-TTBKWWTV.js → chunk-JRZBBPO6.js} +390 -146
  84. package/dist/chunk-JRZBBPO6.js.map +1 -0
  85. package/dist/{chunk-WVUSXNIE.js → chunk-MPZUYCAP.js} +9 -2
  86. package/dist/{chunk-WVUSXNIE.js.map → chunk-MPZUYCAP.js.map} +1 -1
  87. package/dist/{chunk-SJLTEINJ.js → chunk-OJNTCYQQ.js} +17 -1
  88. package/dist/chunk-OJNTCYQQ.js.map +1 -0
  89. package/dist/{chunk-IOODYAXL.js → chunk-OTWLERSW.js} +25 -6
  90. package/dist/chunk-OTWLERSW.js.map +1 -0
  91. package/dist/{chunk-AWQPGIR6.js → chunk-PJNENX2A.js} +1535 -422
  92. package/dist/chunk-PJNENX2A.js.map +1 -0
  93. package/dist/{chunk-KHE6L6TD.js → chunk-PKHI276N.js} +97 -11
  94. package/dist/chunk-PKHI276N.js.map +1 -0
  95. package/dist/{chunk-YHKXNYTB.js → chunk-QF3LSMGS.js} +2 -2
  96. package/dist/chunk-QXP3Z3JN.js +131 -0
  97. package/dist/chunk-QXP3Z3JN.js.map +1 -0
  98. package/dist/{chunk-XZKD7DIF.js → chunk-RL5UUDT4.js} +3 -3
  99. package/dist/{chunk-XZKD7DIF.js.map → chunk-RL5UUDT4.js.map} +1 -1
  100. package/dist/chunk-SFASB5FL.js +69 -0
  101. package/dist/chunk-SFASB5FL.js.map +1 -0
  102. package/dist/{chunk-WO5BJNIB.js → chunk-SNNSAGMT.js} +7273 -2741
  103. package/dist/chunk-SNNSAGMT.js.map +1 -0
  104. package/dist/{chunk-NZIP4PA2.js → chunk-SO3XRZPX.js} +3 -3
  105. package/dist/chunk-SYOS5CAC.js +176 -0
  106. package/dist/chunk-SYOS5CAC.js.map +1 -0
  107. package/dist/chunk-TAW4UFFF.js +293 -0
  108. package/dist/chunk-TAW4UFFF.js.map +1 -0
  109. package/dist/chunk-TF5HCP33.js +271 -0
  110. package/dist/chunk-TF5HCP33.js.map +1 -0
  111. package/dist/{chunk-AKWGE6JQ.js → chunk-UUGOUOVT.js} +37 -2
  112. package/dist/chunk-UUGOUOVT.js.map +1 -0
  113. package/dist/{chunk-AEG2PXBP.js → chunk-V2LQLN5H.js} +7 -7
  114. package/dist/{chunk-KYFZTGMC.js → chunk-VJUVFZ2D.js} +5 -3
  115. package/dist/{chunk-KYFZTGMC.js.map → chunk-VJUVFZ2D.js.map} +1 -1
  116. package/dist/{chunk-JMM6YE7J.js → chunk-VOZA6O7K.js} +708 -709
  117. package/dist/chunk-VOZA6O7K.js.map +1 -0
  118. package/dist/{chunk-5LJCEMFD.js → chunk-VUGQTZ2L.js} +209 -77
  119. package/dist/chunk-VUGQTZ2L.js.map +1 -0
  120. package/dist/chunk-WOM257PW.js +393 -0
  121. package/dist/chunk-WOM257PW.js.map +1 -0
  122. package/dist/chunk-WYXUQGOL.js +191 -0
  123. package/dist/chunk-WYXUQGOL.js.map +1 -0
  124. package/dist/chunk-X5ZBP3IY.js +97 -0
  125. package/dist/chunk-X5ZBP3IY.js.map +1 -0
  126. package/dist/chunk-XQJXNMSB.js +23 -0
  127. package/dist/chunk-XQJXNMSB.js.map +1 -0
  128. package/dist/chunk-Y527D4TV.js +56 -0
  129. package/dist/chunk-Y527D4TV.js.map +1 -0
  130. package/dist/{chunk-VUFAK2LW.js → chunk-YUY4SAGM.js} +17 -2
  131. package/dist/chunk-YUY4SAGM.js.map +1 -0
  132. package/dist/clack-EZ7TDWQU.js +19 -0
  133. package/dist/claude-cli-2YKABJJZ.js +31 -0
  134. package/dist/{cli-O5SN7ZJ4.js → cli-FB4LOA5A.js} +221 -68
  135. package/dist/{cli-O5SN7ZJ4.js.map → cli-FB4LOA5A.js.map} +1 -1
  136. package/dist/codex-event-TYVES3UX.js +16 -0
  137. package/dist/codex-host-WW4H2SKT.js +29 -0
  138. package/dist/codex-install-2C623HPW.js +393 -0
  139. package/dist/codex-install-2C623HPW.js.map +1 -0
  140. package/dist/{config-OJQI27LT.js → config-HOVJFEKD.js} +25 -15
  141. package/dist/doctor-NKU4V5OV.js +1312 -0
  142. package/dist/doctor-NKU4V5OV.js.map +1 -0
  143. package/dist/{env-proxy-XL4P73MZ.js → env-proxy-R6ZMLQTT.js} +6 -2
  144. package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js → ethersCompat-Df4a6QIZ-X6YZWAML.js} +3 -3
  145. package/dist/{fund-WEV6DMTD.js → fund-WEBHTZGN.js} +38 -30
  146. package/dist/{fund-WEV6DMTD.js.map → fund-WEBHTZGN.js.map} +1 -1
  147. package/dist/hook-command-ZA2PNKS6.js +44 -0
  148. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  149. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +3 -2
  150. package/dist/hosts/claude/tenjin/hooks/hooks.json +4 -1
  151. package/dist/hosts/claude/tenjin/hooks/register.tsx +589 -0
  152. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +82 -0
  153. package/dist/hosts/claude/tenjin/types/index.d.ts +41 -0
  154. package/dist/hosts/codex/.agents/plugins/marketplace.json +20 -0
  155. package/dist/hosts/codex/tenjin/.codex-plugin/plugin.json +16 -0
  156. package/dist/hosts/codex/tenjin/.mcp.json +15 -0
  157. package/dist/hosts/codex/tenjin/hooks/hooks.json +98 -0
  158. package/dist/hosts-AV5MHBAU.js +38 -0
  159. package/dist/index.js +28 -8
  160. package/dist/index.js.map +1 -1
  161. package/dist/install-PT4EZS4R.js +100 -0
  162. package/dist/{install-identity-WHPNMNMQ.js → install-identity-5A4OE6YC.js} +13 -8
  163. package/dist/install-wallet-SAAPKB73.js +281 -0
  164. package/dist/install-wallet-SAAPKB73.js.map +1 -0
  165. package/dist/{mcp-QML7ZMPH.js → mcp-HAWKCTPQ.js} +909 -208
  166. package/dist/mcp-HAWKCTPQ.js.map +1 -0
  167. package/dist/{mine.wasm-6PIT3DK6.js → mine.wasm-QFAHIFPY.js} +2 -2
  168. package/dist/{mine.wasm-6PIT3DK6.js.map → mine.wasm-QFAHIFPY.js.map} +1 -1
  169. package/dist/{package-LGKYOEPV.js → package-SR2WB6MK.js} +4 -2
  170. package/dist/passphrase-IFTDS3CU.js +44 -0
  171. package/dist/{paths-POPTXJO6.js → paths-XCSAKISU.js} +10 -2
  172. package/dist/pay-OXC3WKYV.js +55 -0
  173. package/dist/pay-OXC3WKYV.js.map +1 -0
  174. package/dist/{payments-C44QUFXU.js → payments-3KHMP2MG.js} +18 -13
  175. package/dist/{payments-C44QUFXU.js.map → payments-3KHMP2MG.js.map} +1 -1
  176. package/dist/plugin-registration-N3GRIZVM.js +67 -0
  177. package/dist/plugin-registration-N3GRIZVM.js.map +1 -0
  178. package/dist/{redact-6W23GGJC.js → redact-D7ASVWKL.js} +2 -2
  179. package/dist/redact-D7ASVWKL.js.map +1 -0
  180. package/dist/runtime-UVNUA3AS.js +1203 -0
  181. package/dist/runtime-UVNUA3AS.js.map +1 -0
  182. package/dist/runtime-fetch-EKFRNR6Z.js +20 -0
  183. package/dist/runtime-fetch-EKFRNR6Z.js.map +1 -0
  184. package/dist/runtime-layout-BDWZG2TQ.js +25 -0
  185. package/dist/runtime-layout-BDWZG2TQ.js.map +1 -0
  186. package/dist/{send-KVJX4XIR.js → send-HMKJLT34.js} +26 -18
  187. package/dist/{send-KVJX4XIR.js.map → send-HMKJLT34.js.map} +1 -1
  188. package/dist/{status-S7C3WMSH.js → status-RWXIIWYS.js} +57 -22
  189. package/dist/status-RWXIIWYS.js.map +1 -0
  190. package/dist/{status-line-YR2T5HC4.js → status-line-77XYZP7E.js} +13 -8
  191. package/dist/{status-line-YR2T5HC4.js.map → status-line-77XYZP7E.js.map} +1 -1
  192. package/dist/uninstall-D5G67UJH.js +480 -0
  193. package/dist/uninstall-D5G67UJH.js.map +1 -0
  194. package/dist/update-LRNOEGSB.js +53 -0
  195. package/dist/update-LRNOEGSB.js.map +1 -0
  196. package/dist/{usdc-JK4RRFFQ.js → usdc-D6X7EIQ2.js} +7 -8
  197. package/dist/usdc-D6X7EIQ2.js.map +1 -0
  198. package/dist/{viemAdapter-By13KInL-X2VY6CY3.js → viemAdapter-By13KInL-RL742ETX.js} +3 -3
  199. package/dist/viemAdapter-By13KInL-RL742ETX.js.map +1 -0
  200. package/dist/wallet-XFYC27BR.js +55 -0
  201. package/dist/wallet-XFYC27BR.js.map +1 -0
  202. package/dist/wallet-kdf-worker.mjs +8 -8
  203. package/docs/agent-permissions.md +56 -22
  204. package/docs/safety-model.md +1 -1
  205. package/docs/troubleshooting.md +72 -1
  206. package/package.json +14 -1
  207. package/dist/alive-3J3CHOQP.js +0 -21
  208. package/dist/ccip-NLCSCHKI.js +0 -19
  209. package/dist/chunk-3O2BQIF6.js.map +0 -1
  210. package/dist/chunk-5IEP5EGE.js +0 -5332
  211. package/dist/chunk-5IEP5EGE.js.map +0 -1
  212. package/dist/chunk-5LJCEMFD.js.map +0 -1
  213. package/dist/chunk-6W5GYG3W.js +0 -128
  214. package/dist/chunk-6W5GYG3W.js.map +0 -1
  215. package/dist/chunk-7EKYXMUO.js +0 -7536
  216. package/dist/chunk-7EKYXMUO.js.map +0 -1
  217. package/dist/chunk-7QKHZQKW.js.map +0 -1
  218. package/dist/chunk-AKWGE6JQ.js.map +0 -1
  219. package/dist/chunk-AWQPGIR6.js.map +0 -1
  220. package/dist/chunk-EGELTSPU.js +0 -2865
  221. package/dist/chunk-EGELTSPU.js.map +0 -1
  222. package/dist/chunk-EL56RW2J.js +0 -7611
  223. package/dist/chunk-EL56RW2J.js.map +0 -1
  224. package/dist/chunk-HE2MS4QO.js +0 -256
  225. package/dist/chunk-HE2MS4QO.js.map +0 -1
  226. package/dist/chunk-IOODYAXL.js.map +0 -1
  227. package/dist/chunk-JMM6YE7J.js.map +0 -1
  228. package/dist/chunk-KHE6L6TD.js.map +0 -1
  229. package/dist/chunk-N35E6CM2.js +0 -1185
  230. package/dist/chunk-N35E6CM2.js.map +0 -1
  231. package/dist/chunk-O2FRQ2L2.js.map +0 -1
  232. package/dist/chunk-OK2TDZQU.js.map +0 -1
  233. package/dist/chunk-OSYTBCUC.js.map +0 -1
  234. package/dist/chunk-PAYV4XUA.js.map +0 -1
  235. package/dist/chunk-SJLTEINJ.js.map +0 -1
  236. package/dist/chunk-TTBKWWTV.js.map +0 -1
  237. package/dist/chunk-TTNESUPQ.js.map +0 -1
  238. package/dist/chunk-U6YQ6FRI.js.map +0 -1
  239. package/dist/chunk-VUFAK2LW.js.map +0 -1
  240. package/dist/chunk-VZGAONSJ.js.map +0 -1
  241. package/dist/chunk-WO5BJNIB.js.map +0 -1
  242. package/dist/doctor-IQQJHGGM.js +0 -590
  243. package/dist/doctor-IQQJHGGM.js.map +0 -1
  244. package/dist/hook-command-D2P3ILRV.js +0 -32
  245. package/dist/install-TUCRF32I.js +0 -60
  246. package/dist/install-wallet-MA27FTQ5.js +0 -113
  247. package/dist/install-wallet-MA27FTQ5.js.map +0 -1
  248. package/dist/mcp-QML7ZMPH.js.map +0 -1
  249. package/dist/pay-2C2UBBXJ.js +0 -51
  250. package/dist/status-S7C3WMSH.js.map +0 -1
  251. package/dist/uninstall-HY6LKIIT.js +0 -149
  252. package/dist/uninstall-HY6LKIIT.js.map +0 -1
  253. package/dist/update-OJV22LR3.js +0 -36
  254. package/dist/wallet-PD2IMZDU.js +0 -39
  255. /package/dist/{_esm-CE7KNONL.js.map → _esm-RLLC72MS.js.map} +0 -0
  256. /package/dist/{alive-3J3CHOQP.js.map → alive-MROUMFH3.js.map} +0 -0
  257. /package/dist/{ccip-7RMRLAGV.js.map → auto-update-OPWMRZLS.js.map} +0 -0
  258. /package/dist/{ccip-NLCSCHKI.js.map → ccip-DHDFKTQV.js.map} +0 -0
  259. /package/dist/{chunk-LFZJM56J.js.map → chunk-445VQTVM.js.map} +0 -0
  260. /package/dist/{chunk-RAULEAZ6.js.map → chunk-4USCZ2NI.js.map} +0 -0
  261. /package/dist/{chunk-VFMQTSXG.js.map → chunk-D3ZURCG7.js.map} +0 -0
  262. /package/dist/{chunk-ORWL5BSN.js.map → chunk-HGZEPQUT.js.map} +0 -0
  263. /package/dist/{chunk-EBVIKMCH.js.map → chunk-JKKAIPTU.js.map} +0 -0
  264. /package/dist/{chunk-YHKXNYTB.js.map → chunk-QF3LSMGS.js.map} +0 -0
  265. /package/dist/{chunk-NZIP4PA2.js.map → chunk-SO3XRZPX.js.map} +0 -0
  266. /package/dist/{chunk-AEG2PXBP.js.map → chunk-V2LQLN5H.js.map} +0 -0
  267. /package/dist/{config-OJQI27LT.js.map → clack-EZ7TDWQU.js.map} +0 -0
  268. /package/dist/{env-proxy-XL4P73MZ.js.map → claude-cli-2YKABJJZ.js.map} +0 -0
  269. /package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js.map → codex-event-TYVES3UX.js.map} +0 -0
  270. /package/dist/{hook-command-D2P3ILRV.js.map → codex-host-WW4H2SKT.js.map} +0 -0
  271. /package/dist/{install-TUCRF32I.js.map → config-HOVJFEKD.js.map} +0 -0
  272. /package/dist/{install-identity-WHPNMNMQ.js.map → env-proxy-R6ZMLQTT.js.map} +0 -0
  273. /package/dist/{package-LGKYOEPV.js.map → ethersCompat-Df4a6QIZ-X6YZWAML.js.map} +0 -0
  274. /package/dist/{paths-POPTXJO6.js.map → hook-command-ZA2PNKS6.js.map} +0 -0
  275. /package/dist/{pay-2C2UBBXJ.js.map → hosts-AV5MHBAU.js.map} +0 -0
  276. /package/dist/{redact-6W23GGJC.js.map → install-PT4EZS4R.js.map} +0 -0
  277. /package/dist/{update-OJV22LR3.js.map → install-identity-5A4OE6YC.js.map} +0 -0
  278. /package/dist/{usdc-JK4RRFFQ.js.map → package-SR2WB6MK.js.map} +0 -0
  279. /package/dist/{viemAdapter-By13KInL-X2VY6CY3.js.map → passphrase-IFTDS3CU.js.map} +0 -0
  280. /package/dist/{wallet-PD2IMZDU.js.map → paths-XCSAKISU.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/update.ts","../src/router/install.ts","../src/lib/skill-placement.ts","../src/router/legacy-install.ts","../src/router/status-line-wiring.ts","../src/router/plugin-registration.ts","../src/router/reachability.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { existsSync, statSync } from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport pkg from '../../package.json';\nimport { proxyNodeStep, proxySkipped } from '../lib/env-proxy';\nimport { CliError } from '../lib/errors';\nimport { MANAGERS, classifyManager, refuse, resolveManagerScript } from '../lib/install-location';\nimport type { Delegable } from '../lib/install-location';\nimport { emitWriteNotice, sanitizeForTerminal } from '../lib/output';\nimport {\n NUDGE_OPT_OUT,\n channelTag,\n fetchDistTags,\n isNewer,\n resolveTarget,\n} from '../lib/update-check';\nimport { loadRawConfig } from '../lib/config';\nimport { defaultDataDir, runtimeDir } from '../lib/paths';\nimport type { ensureNode, placeVersion, stageTarball } from '../lib/runtime';\nimport type { CommandContext, CommandResult } from '../context';\nimport { persistRouterProject } from './config';\nimport { projectInstallAt } from '../router/install';\nimport { readMcpServers, type InstalledAt, type ListMcpProcesses } from '../router/mcp-processes';\n\n/**\n * `tenjin update`: move this machine to the newest version npm's `latest` tag\n * names. Which way depends on whether Tenjin's runtime (`~/.tenjin/runtime`,\n * the default data dir only) is here.\n *\n * THE RUNTIME BRANCH needs no npm. This OLD build downloads the release (the\n * registry tarball, checked against its sha512, or a copy of itself when it IS\n * that release), ensures the Node the release pins, and places it beside the\n * current version. The NEW build, spawned on that Node as `install --refresh`,\n * checks itself (`verifyBuild`), and only then switches the runtime to itself\n * and registers it. The parent reads the switch back from `state.json`: a\n * release that did not switch leaves the previous version current, and the\n * update fails saying so. The parent holds no runtime lock while a child runs.\n *\n * THE NPM BRANCH is kept for an install with no runtime. It spawns the package\n * manager that OWNS the install rather than reimplementing one:\n *\n * - The argv pins the EXACT version the registry just named, never the tag, so\n * the check and the install cannot disagree about what ships, and the version\n * string is certified parseable by the same `isNewer` gate the nudge trusts\n * before it goes anywhere near an argv.\n * - The owner performs the install. npm, pnpm and bun are each driven with their\n * own global-add command, because the PATH race that makes a second install\n * dangerous comes from CROSS-manager writes, not from asking the owner to do\n * what it already owns. What cannot be driven is refused instead of guessed\n * at: a source checkout updates by git, an npx run has nothing installed to\n * replace, a project-local copy updates where it is declared, and yarn's\n * global install exists only in yarn 1. See lib/install-location.\n * - The manager's chatter goes to stderr (live, human mode only, sanitized) and\n * its failure into the error envelope; stdout stays the one envelope every\n * command emits.\n *\n * On both, every child is a binary or `node <script>`, never a shell. That is\n * what makes a pinned argv worth pinning, and it is the only form that works on\n * win32, where the runtime's child is its absolute `node.exe`.\n */\n\n/** How long the npm child gets before it is killed. npm's own retry budget runs\n * into minutes, and an agent's turn should not hang on a wedged registry. */\nconst INSTALL_TIMEOUT_MS = 300_000;\n\n/** How long the release's tarball, and the Node it pins, may take to download. */\nconst STAGE_TIMEOUT_MS = 120_000;\nconst NODE_TIMEOUT_MS = 300_000;\n\nexport interface UpdateOptions {\n /** Report whether a newer version exists; never install. */\n check: boolean;\n /**\n * The detached run lib/auto-update starts: the runtime branch only, never\n * npm, with how it ended recorded in `<runtime>/auto-update.json`.\n */\n background?: boolean;\n}\n\n/**\n * How the child ended. Never rejects: all three outcomes are envelope-shaped\n * facts the caller reports, not exceptions, and each is separately testable.\n */\nexport type SpawnResult =\n { kind: 'exit'; code: number } | { kind: 'start-failed'; cause: unknown } | { kind: 'timeout' };\n\nexport type UpdateSpawn = (\n cmd: string,\n args: string[],\n opts: {\n cwd: string;\n timeoutMs: number;\n /** Variables layered ONTO this process's environment, for the per-profile\n * `TENJIN_DATA_DIR` the refresh pass sets. Absent means inherit unchanged. */\n env?: Record<string, string>;\n },\n onOutput: (chunk: string) => void,\n) => Promise<SpawnResult>;\n\n/** What to spawn for one manager: a command and any argv that must precede its own. */\ninterface ResolvedManager {\n cmd: string;\n prefix: readonly string[];\n}\n\n/**\n * Turn a manager into a spawnable command. A resolved script runs under THIS\n * node, keeping `shell` unset on every platform; otherwise the bare binary name\n * is used, which is correct for a native binary and fails closed on win32 for a\n * `.cmd` shim.\n */\nfunction resolveManager(manager: Delegable, deps: UpdateDeps): ResolvedManager {\n const script =\n deps.managerScript !== undefined\n ? deps.managerScript\n : resolveManagerScript(manager, process.execPath);\n return script === null\n ? { cmd: MANAGERS[manager].bin, prefix: [] }\n : { cmd: process.execPath, prefix: [script] };\n}\n\nexport interface UpdateDeps {\n fetchImpl?: typeof fetch;\n spawnImpl?: UpdateSpawn;\n /** Where this build's code lives on disk; tests point it at fixture trees. */\n moduleDir?: string;\n /** The running version; defaults to this build's. Injectable for tests. */\n currentVersion?: string;\n /** The owning manager's entry script, or null when it has none to find.\n * Injectable so the argv shape is asserted without depending on the runner. */\n managerScript?: string | null;\n /** Home whose manual-fix command the report names, and whose `.tenjin` is the\n * default data dir the runtime belongs to. Defaults to os.homedir(). */\n homeDir?: string;\n /**\n * The CLI entry the npm branch's refresh child runs. Defaults to `process.argv[1]`, which\n * after the swap resolves to the NEWLY installed script — that is the whole\n * point of spawning rather than calling.\n */\n refreshCommand?: string;\n /** This user's running `tenjin mcp` processes; tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When the new build was installed; tests inject it. */\n installedAt?: InstalledAt;\n /** Tenjin's runtime folder; defaults to the one under the data dir. */\n runtimeRoot?: string;\n /** The runtime branch's download, Node and placement; tests inject them. */\n stage?: typeof stageTarball;\n ensure?: typeof ensureNode;\n place?: typeof placeVersion;\n /** Test seam; production asks this Node whether it can use the shell's proxy. */\n proxySupported?: boolean;\n}\n\ninterface UpdateData {\n current: string;\n latest: string;\n updateAvailable: boolean;\n updated: boolean;\n}\n\nexport async function runUpdate(\n opts: UpdateOptions,\n ctx: CommandContext,\n deps: UpdateDeps = {},\n): Promise<CommandResult> {\n if (opts.background !== true) return update(opts, ctx, deps);\n // THE BACKGROUND RUN records how it ended for doctor, then answers as any\n // update does: its envelope goes to the log. Only where the runtime folder\n // already is, so a run with no runtime creates nothing.\n const root = deps.runtimeRoot ?? runtimeDir(ctx.dataDir);\n const [{ recordAutoUpdate }, { readRuntimeState }] = await Promise.all([\n import('../lib/auto-update'),\n import('../lib/runtime-layout'),\n ]);\n const from = readRuntimeState(root)?.current.cli;\n const record = (r: Parameters<typeof recordAutoUpdate>[1]): void => {\n if (!existsSync(root)) return;\n try {\n recordAutoUpdate(root, { finishedAt: new Date().toISOString(), ...r });\n } catch {\n // The update itself is the result; a record that cannot be written is not.\n }\n };\n try {\n const result = await update(opts, ctx, deps);\n const d = result.data as Partial<UpdateData> & { skipped?: string };\n record(\n d.skipped !== undefined\n ? { outcome: 'skipped', reason: d.skipped }\n : d.updated === true\n ? { outcome: 'updated', from: d.current, to: d.latest }\n : { outcome: 'current', from: d.current, to: d.current },\n );\n return result;\n } catch (err) {\n const reason = sanitizeForTerminal(err instanceof Error ? err.message : String(err)).trim();\n record({\n outcome: 'failed',\n ...(from !== undefined ? { from } : {}),\n reason: reason.slice(0, REASON_LIMIT),\n });\n throw err;\n }\n}\n\nasync function update(\n opts: UpdateOptions,\n ctx: CommandContext,\n deps: UpdateDeps,\n): Promise<CommandResult> {\n const current = deps.currentVersion ?? pkg.version;\n const channel = channelTag(current);\n const moduleDir = deps.moduleDir ?? fileURLToPath(new URL('.', import.meta.url));\n\n // Refused, not defaulted to a channel: a build whose version this package\n // cannot parse has no release line to compare against, and guessing one is how\n // a foreign build gets told it is up to date forever.\n if (channel === null) {\n throw new CliError('REFUSED', `tenjin-cli reports an unrecognizable version (${current})`, {\n fix: 'Reinstall a published build: npm i -g tenjin-cli',\n });\n }\n\n // First stage: everything whose fix string does not need a resolved version,\n // so it answers without the network. An offline contributor in a checkout is\n // told they are in a checkout, not told to go debug their registry access.\n refuse(moduleDir, { check: opts.check, spec: null });\n\n const tags = await fetchDistTags({\n fetchImpl: deps.fetchImpl,\n timeoutMs: ctx.flags.timeout,\n });\n if (tags === null) {\n throw new CliError('NETWORK_ERROR', 'Could not read tenjin-cli dist-tags from npm', {\n fix: 'Check access to registry.npmjs.org and retry',\n });\n }\n // THE RUNTIME'S VERSION IS THE ONE THAT RUNS, so it is what the answer is\n // about: an npm copy older than the runtime still moves the runtime forward,\n // and \"up to date\" or `--check` speak of what Claude Code starts.\n const runtime = await runtimeHere(ctx, deps, moduleDir);\n // The background run never reaches npm: with no runtime it has nothing to do.\n if (opts.background === true && runtime === null) {\n return {\n data: { skipped: 'no runtime' },\n humanLines: [\"Nothing to update in the background: Tenjin's runtime is not set up here.\"],\n };\n }\n const base = runtime?.current ?? current;\n const latest = resolveTarget(base, tags);\n // Not a NETWORK_ERROR: nothing about the connection is wrong, and telling the\n // user to check their access sends them after a fault that is not there.\n if (latest === null) {\n const raw = tags[channel];\n throw raw === undefined\n ? new CliError('RESOURCE_NOT_FOUND', 'npm has no published tenjin-cli on the latest tag', {\n fix: 'Pick a version yourself: npm view tenjin-cli versions',\n })\n : new CliError(\n 'RESOURCE_NOT_FOUND',\n // Registry-controlled: bounded here, escaped by the error emitter.\n `npm's latest tenjin-cli (${raw.slice(0, 40)}) is not a version this build can read`,\n {\n fix: 'Install it by name: npm i -g tenjin-cli@<version> (npm view tenjin-cli versions)',\n },\n );\n }\n\n const updateAvailable = isNewer(latest, base);\n const data = (updated: boolean): UpdateData => ({\n current: base,\n latest,\n updateAvailable,\n updated,\n });\n\n if (!updateAvailable) {\n return {\n data: data(false),\n humanLines: [`tenjin-cli ${base} is up to date`],\n };\n }\n if (opts.check) {\n return {\n data: data(false),\n humanLines: [\n `tenjin-cli ${latest} is available (you have ${base}).`,\n 'Run tenjin update to install it.',\n ],\n };\n }\n\n // No manager below this line is asked, so none of the stage-2 refusals about\n // how npm's copy was installed apply: an npx run updates the runtime too.\n if (runtime !== null) {\n return runtimeUpdate(ctx, deps, { ...runtime, base, latest, current, moduleDir, data });\n }\n\n await refuseRuntimeElsewhere(ctx, moduleDir, deps.homeDir ?? homedir());\n\n // `latest` is argv-safe here: isNewer returned true, so it matched VERSION_RE.\n const spec = `tenjin-cli@${latest}`;\n\n // Second stage: the entries whose fix strings name the version just resolved.\n // Reached only on the install path, since --check has already returned.\n refuse(moduleDir, { check: false, spec });\n\n // Live chatter is a human courtesy only; the tail rides in the error envelope\n // so a piped failure is still diagnosable. Sanitized per line, because npm\n // relays publisher-controlled text (deprecation notices) and a line break is\n // the one control character this stream must keep.\n const human = ctx.io.isTTY && !ctx.flags.json;\n let tail = '';\n const onOutput = (chunk: string): void => {\n tail = (tail + chunk).slice(-2000);\n if (human) ctx.io.stderr.write(chunk.split('\\n').map(sanitizeForTerminal).join('\\n'));\n };\n\n // Whoever owns the install performs it. The PATH-race objection that used to\n // make this a refusal only applies to CROSS-manager writes; invoking the owner\n // is exactly what the refusal used to tell the user to type by hand.\n //\n // The cast is sound only because `refuse` ran directly above and yarn is one\n // of its entries, so the one non-delegable manager has already thrown. Move\n // this line above that call and it becomes a lie.\n const manager = classifyManager(moduleDir) as Delegable;\n const plan = MANAGERS[manager];\n // --ignore-scripts where the manager has it (tenjin-cli has no runtime\n // dependencies and no registry install runs its own `prepare`), and cwd is the\n // home directory so the child never reads a project's config by accident.\n const args = plan.args(spec);\n const resolved = resolveManager(manager, deps);\n const manual = `Run it yourself: ${plan.manual(spec)}`;\n\n const outcome = await (deps.spawnImpl ?? spawnCapture)(\n resolved.cmd,\n [...resolved.prefix, ...args],\n { cwd: homedir(), timeoutMs: INSTALL_TIMEOUT_MS },\n onOutput,\n );\n if (outcome.kind === 'start-failed') {\n throw new CliError('UPDATE_FAILED', `Could not start ${manager}`, {\n fix: manual,\n cause: outcome.cause,\n });\n }\n if (outcome.kind === 'timeout') {\n throw new CliError(\n 'UPDATE_FAILED',\n `${manager} did not finish in ${INSTALL_TIMEOUT_MS / 1000}s`,\n { fix: manual, details: { output: tail } },\n );\n }\n if (outcome.code !== 0) {\n throw new CliError('UPDATE_FAILED', `${manager} ${args.join(' ')} exited ${outcome.code}`, {\n // EACCES on a root-owned global prefix is the common cause; the operator\n // fixing that themselves beats this CLI ever escalating.\n fix: manual,\n details: { output: tail },\n });\n }\n\n emitWriteNotice(\n ctx.io,\n `tenjin update: replaced the global tenjin-cli with ${latest} via ${manager}`,\n );\n\n const { refresh } = await refreshProfiles(ctx, deps, npmLaunch(deps));\n return updated(deps, data(true), refresh, [`Updated tenjin-cli ${current} -> ${latest}.`]);\n}\n\n/**\n * The report of an update that happened, on either branch. The refresh child's\n * output is captured, so the warning it would print about a `tenjin mcp` still\n * running the old build is checked again here, with the fix the child's\n * migration state calls for. `version` is the build the runtime now runs: a\n * router launched from the runtime is stale when it runs any other.\n */\nasync function updated(\n deps: UpdateDeps,\n data: UpdateData,\n refresh: RefreshOutcome,\n head: string[],\n version?: string,\n): Promise<CommandResult> {\n const servers = await readMcpServers(deps, {\n settingsInstallPending: refresh.settingsInstallPending,\n ...(version !== undefined ? { version } : {}),\n });\n return {\n data: { ...data, refresh, mcpServer: servers.check },\n humanLines: [\n ...head,\n ...refreshLines(refresh),\n ...projectLines(refresh),\n ...refresh.notices,\n ...(servers.stale > 0\n ? [`! ${servers.check.detail}. ${servers.check.fix ?? ''}`.trim()]\n : []),\n ],\n };\n}\n\n/** Tenjin's runtime as this update sees it. */\ninterface RuntimeHere {\n root: string;\n /** Its current version, or null when only this build's own location says it is one. */\n current: string | null;\n /** This build runs from the runtime itself. */\n inRuntime: boolean;\n}\n\n/**\n * The runtime to update, or null for the npm branch: the default data dir\n * only (a QA profile keeps npm's layout), and only where a runtime state\n * exists or this build runs from one. The runtime modules are imported\n * lazily: `router/plugin-registration` imports this module, and it sits in the\n * status line's chunk, which must not load them.\n */\nasync function runtimeHere(\n ctx: CommandContext,\n deps: UpdateDeps,\n moduleDir: string,\n): Promise<RuntimeHere | null> {\n if (resolve(ctx.dataDir) !== resolve(defaultDataDir(deps.homeDir ?? homedir()))) return null;\n const { readRuntimeState, runtimeBuild } = await import('../lib/runtime-layout');\n const root = deps.runtimeRoot ?? runtimeDir(ctx.dataDir);\n const state = readRuntimeState(root);\n const inRuntime = runtimeBuild(moduleDir) !== null;\n if (state === null && !inRuntime) return null;\n return { root, current: state?.current.cli ?? null, inRuntime };\n}\n\n/**\n * A RUNTIME BUILD UNDER ANOTHER DATA DIR has no npm install to update: it is\n * `~/.local/bin/tenjin` run with `TENJIN_DATA_DIR` set, and the runtime belongs\n * to the default data dir alone. Said as that, before the npm branch's\n * refusals would call it a project-local dependency.\n */\nasync function refuseRuntimeElsewhere(\n ctx: CommandContext,\n moduleDir: string,\n home: string,\n): Promise<void> {\n const { runtimeBuild } = await import('../lib/runtime-layout');\n if (runtimeBuild(moduleDir) === null) return;\n throw new CliError(\n 'REFUSED',\n `This tenjin runs from Tenjin's runtime, which only the default data dir (${tilde(defaultDataDir(home), home)}) uses, and TENJIN_DATA_DIR is ${tilde(ctx.dataDir, home)}, so nothing was updated`,\n {\n fix: 'Run `tenjin update` with TENJIN_DATA_DIR unset: the runtime belongs to the default data dir. Another data dir runs on an npm copy, updated with `npm i -g tenjin-cli@latest`.',\n },\n );\n}\n\n/**\n * THE RUNTIME BRANCH (see the header). Everything up to the spawn is this OLD\n * build's: download, Node, placement, each under the runtime lock and released\n * before the child starts. The switch is the NEW build's, so the verdict is read\n * back from `state.json` rather than trusted from an exit code: a child that\n * exits 0 having kept the previous version (its own checks failed) did not\n * update anything.\n */\nasync function runtimeUpdate(\n ctx: CommandContext,\n deps: UpdateDeps,\n o: RuntimeHere & {\n base: string;\n latest: string;\n current: string;\n moduleDir: string;\n data: (updated: boolean) => UpdateData;\n },\n): Promise<CommandResult> {\n const { root, base, latest } = o;\n const [rt, layout] = await Promise.all([\n import('../lib/runtime'),\n import('../lib/runtime-layout'),\n ]);\n const stays = `so ${base} stays`;\n\n // An npm copy that IS the release copies itself: the bytes are already here\n // and were installed by npm, with nothing to fetch. Anything else is fetched.\n let stage: string;\n if (latest === o.current && !o.inRuntime) {\n const packageRoot = rt.packageRootOf(o.moduleDir);\n if (packageRoot === null) {\n throw new CliError(\n 'UPDATE_FAILED',\n `tenjin-cli ${latest} cannot find its own package, ${stays}`,\n {\n fix: 'Run `npx -y tenjin-cli@latest install`.',\n },\n );\n }\n stage = await rt.stageSelf(root, packageRoot);\n } else {\n stage = await (deps.stage ?? rt.stageTarball)(root, latest, {\n timeoutMs: STAGE_TIMEOUT_MS,\n fetchImpl: deps.fetchImpl,\n }).catch((err: unknown) => {\n throw proxyNamed(err, deps);\n });\n }\n\n let node: string;\n try {\n // The NEW version's pin, read as data from the package just checked.\n const pin = rt.readNodePin(stage);\n if (pin === null) {\n throw new CliError('UPDATE_FAILED', `tenjin-cli ${latest} carries no Node pin, ${stays}`, {\n fix: `Nothing to do: ${base} keeps running. Run \\`tenjin update\\` again after the next release.`,\n });\n }\n node = await (deps.ensure ?? rt.ensureNode)(root, pin, {\n timeoutMs: NODE_TIMEOUT_MS,\n fetchImpl: deps.fetchImpl,\n });\n await (deps.place ?? rt.placeVersion)(root, stage, latest);\n } catch (err) {\n await rm(stage, { recursive: true, force: true }).catch(() => undefined);\n throw proxyNamed(err, deps);\n }\n const home = deps.homeDir ?? homedir();\n emitWriteNotice(ctx.io, `tenjin update: staged tenjin-cli ${latest} in ${tilde(root, home)}`);\n\n const { refresh, homeTail } = await refreshProfiles(ctx, deps, {\n node,\n entry: layout.versionEntry(root, latest),\n });\n if (layout.readRuntimeState(root)?.current.cli !== latest) {\n // `versions/<latest>` is left for the next collect(): nothing points at it.\n throw new CliError('UPDATE_FAILED', `tenjin-cli ${latest} did not pass its checks, ${stays}`, {\n fix: 'Run `tenjin update` again; if it fails again, run `tenjin doctor`',\n details: {\n reason:\n refresh.failed[0]?.reason ??\n runtimeReason(envelopeData(homeTail)) ??\n 'The new version did not switch the runtime to itself.',\n output: homeTail.slice(-2000),\n },\n });\n }\n return updated(\n deps,\n o.data(true),\n refresh,\n [\n `Updated tenjin-cli ${base} -> ${latest}.`,\n `The previous version (${base}) stays as the fallback.`,\n ],\n latest,\n );\n}\n\n/**\n * A download in the runtime branch that failed on a Node which skips the\n * shell's proxy (#470), said as that with the step that works: `tenjin update`\n * again on the same Node fails the same way.\n */\nfunction proxyNamed(err: unknown, deps: UpdateDeps): unknown {\n if (!(err instanceof CliError) || err.code !== 'NETWORK_ERROR') return err;\n const skipped = proxySkipped(process.env, deps.proxySupported);\n if (skipped === null) return err;\n const step = proxyNodeStep('tenjin update');\n return new CliError('NETWORK_ERROR', `${err.message}: ${skipped}`, {\n fix: `${step.charAt(0).toUpperCase()}${step.slice(1)}.`,\n cause: err,\n });\n}\n\n/** Why the child kept the previous runtime, from its `data.runtime.reason`. */\nfunction runtimeReason(data: Record<string, unknown> | null): string | undefined {\n const reason = (data?.runtime as { reason?: unknown } | undefined)?.reason;\n if (typeof reason !== 'string') return undefined;\n const text = sanitizeForTerminal(reason).trim();\n return text.length > 0 ? text.slice(0, REASON_LIMIT) : undefined;\n}\n\n/** `path` with the home folder written as `~`. */\nfunction tilde(path: string, home: string): string {\n return path === home || path.startsWith(`${home}${sep}`) ? `~${path.slice(home.length)}` : path;\n}\n\n/** How long one `install --refresh` child gets. Local file writes only, no\n * registry: a minute is already generous, and `update` must not hang a turn. */\nconst REFRESH_TIMEOUT_MS = 60_000;\n\n/** One profile this update did not bring up to date, and why. */\nexport interface RefreshFailure {\n /** The profile's data dir. */\n dataDir: string;\n /**\n * Why it is not up to date, in the words of whoever decided that: the child's\n * own `error.message` when it printed a failure envelope, this pass's own\n * account when the child was never run or never got that far. Always present,\n * because a failure whose four causes render identically is the reason this\n * field exists.\n */\n reason: string;\n /** The command that converges THIS profile; see {@link manualFix}. */\n fix: string;\n}\n\n/** What the post-swap re-materialize did, per profile. */\nexport interface RefreshOutcome {\n /** Data dirs a refresh was run for, whether or not it succeeded. */\n profiles: string[];\n /**\n * Profiles this update did not bring up to date, each with its reason and the\n * manual command to finish it. Both halves land here: a refresh that ran and\n * did not report success, and one that was never run at all (no entry to\n * re-exec, a data dir that is not a directory).\n */\n failed: RefreshFailure[];\n /**\n * What a refresh that succeeded said the person must know (the child's\n * `data.notices`): a plugin left for a newer Claude Code, a status line the\n * migration took out. Printed as given, one line each.\n */\n notices: string[];\n /** A refreshed profile still carries an earlier release's settings install. */\n settingsInstallPending: boolean;\n /** Project installs (`install --project`) refreshed from their own directory. */\n projects: string[];\n /** Project installs whose refresh did not succeed, each with its reason and fix. */\n projectsFailed: { project: string; reason: string; fix: string }[];\n}\n\n/**\n * Re-materialize what the swap left stale, on the NEW binary.\n *\n * `update` replaces the package and nothing else, but `install` bakes this\n * build's identity into files: the generated hook scripts carry a version, and\n * the wired skills carry this release's instructions. Until something rewrites\n * them the highest-volume request path keeps reporting the previous version and\n * agents keep reading the previous release's guidance (tenjin-agent#171).\n *\n * SPAWNED, NOT CALLED. This process is the OLD build; it cannot render the new\n * version's copies, and re-exec is the only way to reach code that can. The\n * child is the freshly installed entry (`launch`: npm's, on this Node, or the\n * runtime's new version, on the Node it pins), and what it runs is\n * `install --refresh` — a mode that converges existing surfaces and creates\n * none but the runtime and its launcher, which is the only kind of write an\n * unattended upgrade may make.\n *\n * ONCE PER HOOK-OWNER PROFILE. `install` bakes its data dir into the scripts it\n * generates, so a machine whose hooks were installed under `TENJIN_DATA_DIR`\n * has hooks belonging to THAT profile while a bare `tenjin update` resolves the\n * default one. Refreshing only the invoking profile there would leave the\n * registered scripts — the ones the harness actually fires — stale forever,\n * which is exactly the shelf runbook's manual re-install step. So the detector\n * reads the harness settings and each profile it names is refreshed with\n * `TENJIN_DATA_DIR` set to it. A machine with no registered hooks has no other\n * profile to find, and gets one refresh for the invoking one.\n *\n * NEVER FAILS THE UPDATE. The swap already happened and is the thing the\n * operator asked for. A refusal, a run with nothing to converge, a crash, a\n * timeout, or an older-binary \"unknown option --refresh\" all land here as a warn\n * naming the manual command.\n *\n * EACH FAILURE CARRIES ITS OWN REASON AND ITS OWN FIX. The four ways a profile\n * misses are not interchangeable — a dir that is not a directory, a settings\n * file that changed underneath, a machine that never ran `install`, and a\n * timeout each want a different next move — so the child's output is collected\n * and its `error.message` reported per profile rather than collapsed into one\n * parent line.\n */\nasync function refreshProfiles(\n ctx: CommandContext,\n deps: UpdateDeps,\n launch: ChildLaunch | null,\n): Promise<{ refresh: RefreshOutcome; homeTail: string }> {\n const home = deps.homeDir ?? homedir();\n // THE INVOKING PROFILE, AND ONLY IT. The pre-daemon installer baked its data\n // dir into eight generated scripts, so an upgrade had to find every profile\n // registered in settings.json and refresh each one's bodies. Nothing is baked\n // any more: the two bundles are the same bytes for every profile, and a\n // profile's daemon picks up the new build the next time its own `tenjin`\n // command runs. So there is nothing left to hunt for, and a detector reading\n // paths out of somebody's settings file is not worth keeping to say so.\n const candidates = [ctx.dataDir];\n const fixFor = (dataDir: string): string => manualFix(dataDir, home, ctx.dataDir);\n\n // The child would CREATE a data dir that is not there: `install --refresh`\n // converges surfaces rather than materializing them, but the process around it\n // mkdirs the tree for the update cache on its way out. So a path that is not\n // already a directory is reported unrefreshed instead of visited.\n const profiles: string[] = [];\n const unrun: RefreshFailure[] = [];\n for (const dataDir of candidates) {\n if (isExistingDir(dataDir)) profiles.push(dataDir);\n else unrun.push({ dataDir, reason: 'It is not a directory.', fix: fixFor(dataDir) });\n }\n\n // Nothing safe to re-exec (see npmLaunch): report the profiles as\n // unrefreshed rather than guessing, since guessing is how a hook script gets\n // rewritten by the wrong binary — and a refresh that ran the OLD build would\n // report success while writing the bytes the update just left.\n if (launch === null) {\n const reason = 'This build has no entry the update could safely re-execute.';\n return {\n refresh: {\n profiles: [],\n failed: candidates.map((d) => ({ dataDir: d, reason, fix: fixFor(d) })),\n notices: [],\n settingsInstallPending: false,\n projects: [],\n projectsFailed: [],\n },\n homeTail: '',\n };\n }\n\n const failed = [...unrun];\n const notices: string[] = [];\n let settingsInstallPending = false;\n const heard = (reported: Record<string, unknown> | null): void => {\n for (const notice of noticesOf(reported)) if (!notices.includes(notice)) notices.push(notice);\n const migration = reported?.migration as { state?: unknown } | undefined;\n if (migration?.state === 'pending' || migration?.state === 'blocked') {\n settingsInstallPending = true;\n }\n };\n let homeTail = '';\n for (const dataDir of profiles) {\n const { outcome, tail } = await refreshChild(launch, homedir(), dataDir, deps);\n homeTail = tail;\n // The child's exit code IS the verdict: `install --refresh` exits non-zero\n // when it refused or found nothing to converge, so a machine that never ran\n // `install` warns here instead of being told its hooks were refreshed. The\n // envelope on the pipe is what turns that verdict into a reason.\n if (outcome.kind !== 'exit' || outcome.code !== 0) {\n failed.push({ dataDir, reason: refreshReason(outcome, tail), fix: fixFor(dataDir) });\n continue;\n }\n heard(envelopeData(tail));\n }\n\n // PROJECT INSTALLS, EACH FROM ITS OWN DIRECTORY. The child above runs from\n // home, where a `--project` install (Claude Code's local scope) is not\n // visible, so each one `install --project` recorded is refreshed where it\n // lives, as `--project`, since the child cannot tell one at home from the\n // user install. A directory that is gone, or that no longer holds one, is\n // forgotten.\n const projects: string[] = [];\n const projectsFailed: RefreshOutcome['projectsFailed'] = [];\n const recorded = profiles.includes(ctx.dataDir)\n ? ((await loadRawConfig(ctx.dataDir).catch(() => null))?.install?.routerProjects ?? [])\n : [];\n for (const project of recorded) {\n const forget = () => persistRouterProject(ctx.dataDir, project, false).catch(() => undefined);\n if (!isExistingDir(project) || !(await projectInstallAt(project, home, process.env))) {\n await forget();\n continue;\n }\n const { outcome, tail } = await refreshChild(launch, project, ctx.dataDir, deps, ['--project']);\n if (outcome.kind !== 'exit' || outcome.code !== 0) {\n projectsFailed.push({\n project,\n reason: refreshReason(outcome, tail),\n fix: `Run \\`tenjin install --project\\` in ${project}.`,\n });\n continue;\n }\n projects.push(project);\n heard(envelopeData(tail));\n }\n return {\n refresh: { profiles, failed, notices, settingsInstallPending, projects, projectsFailed },\n homeTail,\n };\n}\n\n/** The new build a refresh child runs: its Node and its entry script. */\ninterface ChildLaunch {\n node: string;\n entry: string;\n}\n\n/**\n * The npm branch's child: the version-free entry npm just replaced, on this\n * Node. Null when there is no argv to re-exec (an embedder, a stripped argv),\n * or only a path that names the version being replaced (see versionFreeEntry).\n */\nfunction npmLaunch(deps: UpdateDeps): ChildLaunch | null {\n const entry = versionFreeEntry(deps.refreshCommand ?? process.argv[1]);\n return entry === null ? null : { node: process.execPath, entry };\n}\n\n/**\n * One `install --refresh` child of the new build, from `cwd`, for `dataDir`:\n * how it ended and the end of what it printed. Spawned as `<node> <entry>` by\n * absolute path, never through a shell or a `.cmd`.\n *\n * A BOUNDED COLLECTOR, not the manager's live echo. npm's chatter is minutes\n * of progress a human wants to see; this child emits one envelope on a pipe,\n * and painting that JSON into the human's stderr is noise. It is still kept,\n * because the envelope is where the child says WHICH refusal this was.\n */\nasync function refreshChild(\n launch: ChildLaunch,\n cwd: string,\n dataDir: string,\n deps: UpdateDeps,\n flags: string[] = [],\n): Promise<{ outcome: SpawnResult; tail: string }> {\n let tail = '';\n const outcome = await (deps.spawnImpl ?? spawnCapture)(\n launch.node,\n [launch.entry, 'install', '--refresh', ...flags],\n {\n cwd,\n timeoutMs: REFRESH_TIMEOUT_MS,\n // TENJIN_DATA_DIR aims the child at this profile; the nudge opt-out is\n // what keeps it from touching any other file in there (lib/update-check).\n env: { TENJIN_DATA_DIR: dataDir, [NUDGE_OPT_OUT]: '1' },\n },\n (chunk) => {\n tail = (tail + chunk).slice(-REFRESH_TAIL_LIMIT);\n },\n );\n return { outcome, tail };\n}\n\n/** The `data` of the one success envelope the child printed, or null. */\nfunction envelopeData(output: string): Record<string, unknown> | null {\n const lines = output.split('\\n');\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n if (lines[i]?.trim() !== '{' && !lines[i]?.trim().startsWith('{\"')) continue;\n try {\n const parsed = JSON.parse(lines.slice(i).join('\\n')) as { ok?: unknown; data?: unknown };\n if (parsed?.ok === true && parsed.data !== null && typeof parsed.data === 'object') {\n return parsed.data as Record<string, unknown>;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\n/**\n * The child's notices, each bounded and sanitized: the child is the build\n * this update just installed, but its text still reaches a terminal.\n */\nfunction noticesOf(data: Record<string, unknown> | null): string[] {\n const raw = data?.notices;\n if (!Array.isArray(raw)) return [];\n return raw\n .filter((n): n is string => typeof n === 'string')\n .map((n) => sanitizeForTerminal(n).trim().slice(0, REASON_LIMIT))\n .filter((n) => n.length > 0)\n .slice(0, 5);\n}\n\n/** How much of one refresh child's output is kept. It prints a single envelope,\n * not a build log, so this is headroom rather than a budget. */\nconst REFRESH_TAIL_LIMIT = 64_000;\n\n/** How much of a child's own message reaches the parent's report. Long enough\n * for every message `install --refresh` can produce, short enough that a child\n * which somehow printed prose cannot own the operator's terminal. */\nconst REASON_LIMIT = 300;\n\n/**\n * Why this profile is not up to date, preferring the child's own account.\n *\n * The exit code separates success from failure and nothing else, so the four\n * refusals `install --refresh` can reach would otherwise reach the operator as\n * one line that names none of them. The envelope on the pipe carries the\n * distinction; the outcome kind covers the deaths that never printed one.\n */\nfunction refreshReason(outcome: SpawnResult, output: string): string {\n const reported = envelopeMessage(output);\n if (reported !== undefined) return reported;\n if (outcome.kind === 'timeout') return `It did not finish in ${REFRESH_TIMEOUT_MS / 1000}s.`;\n if (outcome.kind === 'start-failed') return 'The refresh could not be started.';\n // An older binary rejecting `--refresh` is the expected shape here: commander\n // writes its own usage error and exits without an envelope of ours.\n return `The refresh exited ${outcome.code} without reporting a reason.`;\n}\n\n/**\n * The `error.message` out of the one failure envelope the child printed.\n *\n * Read from the LAST envelope because stdout carries exactly one while stderr\n * may carry notices ahead of it, and the two pipes are merged here.\n *\n * `writeJson` PRETTY-PRINTS, so the envelope spans many lines and its only line\n * starting with `{` is a bare `{` that does not parse alone. So scan backwards\n * for an opening line and parse from there to the end; a compact single line\n * still parses through the same path, which keeps an older child readable.\n *\n * Sanitized because this text is bound for a human's terminal and the child\n * relays paths and parse errors it did not author.\n */\nfunction envelopeMessage(output: string): string | undefined {\n const lines = output.split('\\n');\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const line = lines[i]?.trim();\n if (line === undefined || !line.startsWith('{')) continue;\n let parsed: { ok?: unknown; error?: { message?: unknown } };\n try {\n parsed = JSON.parse(lines.slice(i).join('\\n')) as typeof parsed;\n } catch {\n continue;\n }\n if (parsed?.ok !== false || typeof parsed.error?.message !== 'string') continue;\n const message = sanitizeForTerminal(parsed.error.message).trim();\n if (message.length > 0) return message.slice(0, REASON_LIMIT);\n }\n return undefined;\n}\n\n/** A path that already exists AND is a directory. Follows links on purpose: a\n * data dir behind a symlink is an ordinary machine layout, an absent one is not\n * a profile this command may create. */\nfunction isExistingDir(path: string): boolean {\n return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n}\n\n/**\n * The manual command that converges THIS profile.\n *\n * A bare `tenjin install` resolves one data dir, so handing it to an operator\n * whose failed profile is a shelf — the case the per-profile loop exists for —\n * is advice that cannot repair the thing it names. The bare form is emitted only\n * for a dir that is the default under this home AND the one this invocation\n * itself resolved, so it is right under either reading of \"what a bare install\n * would do next\"; every other profile gets the explicit env prefix, which is the\n * same form the shelf runbook uses and is right unconditionally.\n */\nfunction manualFix(dataDir: string, home: string, invoking: string): string {\n const bare =\n resolve(dataDir) === resolve(defaultDataDir(home)) && resolve(dataDir) === resolve(invoking);\n const command = bare ? 'tenjin install' : `TENJIN_DATA_DIR=${dataDir} tenjin install`;\n return `Run \\`${command}\\` to bring the Claude Code plugin up to this version.`;\n}\n\n/**\n * The entry to re-exec, or null when there is none this code may trust.\n *\n * `process.argv[1]` is the path Node RESOLVED, symlinks and all (see\n * `classifyManager`, which reads the manager off exactly that property). Under\n * npm and bun that path carries no version, so after the swap it is already the\n * new build. Under pnpm it points into the virtual store, whose directory names\n * PIN A VERSION: `.../node_modules/.pnpm/tenjin-cli@<version>/node_modules/tenjin-cli/dist/index.js`.\n * Re-executing that is the worst available outcome — it runs the build the\n * update just replaced and reports a successful refresh over the previous\n * version's bytes, which is the exact staleness this whole command exists to\n * end (tenjin-agent#171).\n *\n * The virtual store keeps the version-free link one level out, beside `.pnpm`,\n * and the swap repoints it, so the same path with the store segments removed is\n * the new build. It is derived rather than assumed: if the result is not on\n * disk, this returns null and the caller warns instead of running anything.\n */\nexport function versionFreeEntry(entry: string | undefined): string | null {\n if (entry === undefined || entry.length === 0) return null;\n const segs = entry.split(sep);\n const store = segs.indexOf('.pnpm');\n if (store === -1) return segs.join(sep);\n // `.pnpm/<name>@<version>/node_modules/<name>/...`: everything from the second\n // `node_modules` on is the package's own path within the global tree.\n const inner = segs.indexOf('node_modules', store);\n if (inner === -1) return null;\n const derived = [...segs.slice(0, store), ...segs.slice(inner + 1)].join(sep);\n return existsSync(derived) ? derived : null;\n}\n\n/**\n * What the refresh actually did, as lines.\n *\n * It replaces \"New builds pick it up immediately\", which was true of the binary\n * and false of everything install had written — so it read as reassurance about\n * precisely the thing that was NOT handled (tenjin-agent#171).\n *\n * The successes are reported ALONGSIDE the failures rather than instead of them:\n * a machine where 8 of 12 profiles converged is not a machine where the refresh\n * did nothing, and one line per failure is what lets its own reason and its own\n * command travel with it.\n */\nfunction refreshLines(refresh: RefreshOutcome): string[] {\n const failedDirs = new Set(refresh.failed.map((f) => f.dataDir));\n const done = refresh.profiles.filter((p) => !failedDirs.has(p));\n if (refresh.failed.length === 0) {\n return [\n done.length > 1\n ? `Refreshed the Claude Code plugin for ${done.length} profiles: ${done.join(', ')}.`\n : `Refreshed the Claude Code plugin for ${done[0]}.`,\n ];\n }\n const total = done.length + refresh.failed.length;\n const lines =\n done.length > 0\n ? [\n `Refreshed the Claude Code plugin for ${done.length} of ${total} profiles: ${done.join(', ')}.`,\n ]\n : [];\n lines.push(`Could not refresh the Claude Code plugin for ${refresh.failed.length}:`);\n lines.push(...refresh.failed.map((f) => `- ${f.dataDir}: ${f.reason} ${f.fix}`));\n return lines;\n}\n\n/** The project installs the refresh reached, and the ones it could not. */\nfunction projectLines(refresh: RefreshOutcome): string[] {\n return [\n ...(refresh.projects.length > 0\n ? [`Refreshed the project install in ${refresh.projects.join(', ')}.`]\n : []),\n ...(refresh.projectsFailed.length > 0\n ? [\n `Could not refresh the project install in ${refresh.projectsFailed.length}:`,\n ...refresh.projectsFailed.map((p) => `- ${p.project}: ${p.reason} ${p.fix}`),\n ]\n : []),\n ];\n}\n\n/**\n * Default spawn: merged stdout+stderr chunks out, an outcome back, no shell.\n * Bounded by its own timer rather than Node's `timeout` option so that a kill\n * this code ordered is distinguishable from any other death by signal.\n */\nexport const spawnCapture: UpdateSpawn = (cmd, args, opts, onOutput) =>\n new Promise((res) => {\n let child;\n try {\n child = spawn(cmd, args, {\n stdio: ['ignore', 'pipe', 'pipe'],\n cwd: opts.cwd,\n // Layered onto this process's environment rather than replacing it: the\n // child is a Node CLI that needs PATH and HOME, and only the keys named\n // here are being decided.\n ...(opts.env !== undefined ? { env: { ...process.env, ...opts.env } } : {}),\n });\n } catch (cause) {\n // An argv or option Node rejects outright throws here; ENOENT arrives on\n // the 'error' event instead. Both mean the same thing to the caller.\n res({ kind: 'start-failed', cause });\n return;\n }\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill('SIGKILL');\n }, opts.timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => onOutput(chunk.toString()));\n child.stderr?.on('data', (chunk: Buffer) => onOutput(chunk.toString()));\n child.on('error', (cause) => {\n clearTimeout(timer);\n res({ kind: 'start-failed', cause });\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n res(timedOut ? { kind: 'timeout' } : { kind: 'exit', code: code ?? 1 });\n });\n });\n","import { existsSync } from 'node:fs';\nimport { readFile, realpath, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport pkg from '../../package.json';\nimport { persistRouterDefaults, persistRouterProject, type RouterLimits } from '../commands/config';\nimport { askText, selectOne } from '../lib/clack';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { paint } from '../lib/output';\nimport { defaultDataDir, runtimeDir } from '../lib/paths';\nimport { resolveContextSettings } from '../lib/settings';\nimport type { SpendPolicy } from '../lib/policy';\nimport type { LauncherResult, RuntimeSetup, setupRuntime } from '../lib/runtime';\nimport { runtimeBuild, runtimeStatePath, type RuntimePointer } from '../lib/runtime-layout';\nimport { removeRetiredSkills } from '../lib/skill-placement';\nimport {\n loadRawConfig,\n MAX_AUTO_SPEND_FLOOR_ATOMIC,\n MAX_AUTO_SPEND_FLOOR_WHY,\n} from '../lib/config';\nimport type { WalletDeps, WalletOutcome } from '../commands/install-wallet';\nimport type { CommandContext, CommandResult } from '../context';\nimport { readAliveStamp } from './alive';\nimport { SUGGESTED_FUND_USD } from './fee';\nimport {\n findClaudeBinary,\n readClaudeCode,\n userMcpFile,\n userSettingsPath,\n type ClaudeBinary,\n type ClaudeCodeState,\n} from './claude-cli';\nimport {\n inspectLegacyInstall,\n projectMcpFile,\n removeLegacyInstall,\n type LegacyInstall,\n type LegacyRemoval,\n} from './legacy-install';\nimport { MCP_SERVER_NAME, PLUGIN_ID } from './names';\nimport { CLAUDE_CODE_FLOOR } from './claude-cli';\nimport { inspectPluginFolder } from './plugin-folder';\nimport {\n folderFor,\n folderState,\n marketplaceAdded,\n readPluginListing,\n recordedInstalls,\n registerPlugin,\n type PluginRegistration,\n type PluginScope,\n} from './plugin-registration';\nimport { probeRouter, type RouterCheck } from './reachability';\nimport {\n readMcpServers,\n type InstalledAt,\n type ListMcpProcesses,\n type ListProcesses,\n} from './mcp-processes';\nimport {\n ROUTER_DEFAULTS,\n ROUTING_FEE_TERMS,\n shownLimits,\n SPEND_QUESTION,\n spendChoiceQuestion,\n spendOptions,\n FEE_APPROVAL,\n type SpendOption,\n} from './spend-question';\nimport { underAgentHarness } from '../lib/session';\nimport { agentFixFor, REPAIR_CLAUSE, WALLET_REASONS } from './wallet-reasons';\n\n/**\n * `tenjin install` for the router product: the wallet, the spend limits, and\n * the Claude Code plugin `tenjin`, registered with no step left to the person.\n *\n * WHAT IT WRITES. The wallet and the spend defaults under the data dir, as\n * before. With the default data dir, this build is copied into Tenjin's own\n * runtime, `~/.tenjin/runtime`, with a pinned Node and a `tenjin` launcher in\n * `~/.local/bin` (see `lib/runtime.ts`), and the plugin is registered from\n * the runtime's `claude` folder, whose commands run that Node and that copy,\n * so neither a Node upgrade nor `npm rm -g tenjin-cli` stops it. A non-default\n * data dir, a source checkout, or a runtime that could not be set up keeps\n * the registration from this package's `dist/hosts/claude` folder, run by the\n * `node` on PATH. Either way the plugin goes through Claude Code's own `claude\n * plugin` commands (see `plugin-registration.ts`), or is written as a folder\n * under the config dir's `skills/` where no `claude` binary can be run. The\n * plugin carries the seven routing legs, the `router` MCP server, and the\n * hooks that allow the request tool and deny the legs' own tool to the model,\n * so this command writes nothing into `settings.json` or `~/.claude.json`\n * itself.\n *\n * NO STEP IS LEFT TO THE PERSON. An agent runs this in the person's session:\n * the spend question comes back for the agent to ask there, the funding question\n * with the install its answer picks, the `claude`\n * binary is found through `CLAUDE_CODE_EXECPATH` where PATH lacks it, a failed\n * plugin command falls back to the folder, and the one step after it is\n * starting a new Claude Code session: `/reload-plugins` does not run the\n * plugin's `SessionStart`, so only a new session loads Tenjin fully.\n *\n * THE SETTINGS INSTALL OF EARLIER RELEASES is left working until the plugin\n * has proven to load on this machine (see {@link migrateSettingsInstall}).\n */\n\nexport { AFTER_CALL_TIMEOUT_SECONDS, ROUTE_HOOK_TIMEOUT_SECONDS } from './plugin-files';\n\nexport const DISCLOSURE: readonly string[] = [\n \"What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error), each task handed to a subagent, and each question your assistant asks you with your answers, sent to Tenjin for the free routing gate, beside this session's id. When the gate offers free library docs for a search, that search query also goes to Tenjin's docs lookup, which asks Context7.\",\n 'What is kept when a lookup is paid: the capability chosen, a hash of the contract, a hash of the arguments, and your wallet address. No prompt text, no arguments, no hint text.',\n 'What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere.',\n];\n\n/**\n * What the person does after a successful install: only a new session.\n * `/reload-plugins` does not run the plugin's `SessionStart`, and while a\n * settings install is still here it would load the plugin beside the\n * pre-upgrade `x402` server that session is still running, so every event\n * would route twice.\n */\nexport const NEW_SESSION_STEP = 'start a new Claude Code session so Tenjin loads';\n/** The same step; kept as its own export for its callers. */\nexport const RELOAD_STEP = NEW_SESSION_STEP;\n\n/** The step that loads the plugin: a new session, whether or not a settings install is still here. */\nexport function loadStep(_settingsInstallPresent: boolean): string {\n return NEW_SESSION_STEP;\n}\n\nexport interface RouterInstallArgs {\n /**\n * Register the plugin for this project only (Claude Code's `local` scope,\n * `.claude/settings.local.json`), or write its folder under the project's\n * `.claude/skills/`.\n */\n project?: boolean;\n /**\n * Bring what this machine ALREADY has up to the running build: the plugin,\n * or a settings install the plugin then replaces, with no spend-limit\n * write. A refusal when nothing of ours is here; a runtime alone (Codex\n * kept it after Claude Code's install was removed) is brought up to the\n * running build with nothing for Claude Code created. It may add Tenjin's\n * runtime and its launcher to an install that predates them (never a\n * downgrade: a newer runtime is kept), and records the project installs\n * Claude Code lists so `tenjin update` refreshes them too. `tenjin update`\n * spawns exactly this after it swaps the binary, so the flag's name and\n * meaning are a compatibility contract.\n */\n refresh?: boolean;\n /**\n * Accept the defaults instead of asking: the selector's \"Use the defaults\",\n * for an agent running the person's answer.\n */\n yes?: boolean;\n /** Create no wallet, for CI and scripted machines. */\n noWallet?: boolean;\n /**\n * `--session-budget` and `--max-auto-spend`: the person's own limits, in USD\n * as typed (`none` for no daily limit; the per-call limit is at least $0.25).\n * Either one answers the question; the other then takes the default. A named\n * limit replaces what the config file holds.\n */\n maxAutoSpend?: string;\n sessionBudget?: string;\n}\n\nexport interface RouterInstallDeps extends WalletDeps {\n /** This user's running routers and Claude Code processes; tests inject them. */\n listProcesses?: ListProcesses;\n /** This user's running `tenjin mcp` processes; tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When this build was installed; tests inject it. */\n installedAt?: InstalledAt;\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** Finds the `claude` binary; tests inject one, production reads PATH and `CLAUDE_CODE_EXECPATH`. */\n findClaude?: (env: NodeJS.ProcessEnv) => ClaudeBinary | null;\n /** The marketplace folder; production reads this package's `dist/hosts/claude`. */\n hostsDir?: string | null;\n /** The CLI entry a plugin folder's commands run. Production reads this package's `dist/index.js`. */\n cliEntry?: string;\n /** Whether a person can answer the spend-limit question (a TTY on stdout and\n * stdin, no `--json`); injected in tests. */\n isInteractive?: boolean;\n /** The spend-limit selector; defaults to the clack list. */\n promptLimits?: (message: string) => Promise<LimitsChoice | null>;\n /** One amount question; defaults to the clack text input. */\n promptAmount?: (message: string, placeholder: string) => Promise<string | null>;\n /** The router reachability probe's transport; tests inject it. */\n fetchImpl?: typeof fetch;\n /** The wallet's USDC balance in atomic units; production reads Base. */\n walletBalance?: (address: string, rpcUrl: string) => Promise<bigint>;\n /** Sets up Tenjin's runtime for this build; tests inject it, production runs `setupRuntime`. */\n runtime?: (o: Parameters<typeof setupRuntime>[0]) => Promise<RuntimeSetup>;\n}\n\nexport type LimitsChoice = 'approve' | 'own';\n\n/** Where a settings install of this scope kept its entries and its server. */\nexport interface SettingsInstallPaths {\n settingsPath: string;\n mcpFile: string;\n mcpScope: 'user' | 'project';\n}\n\nexport function settingsInstallPaths(\n project: boolean,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): SettingsInstallPaths {\n return project\n ? {\n settingsPath: join(cwd, '.claude', 'settings.json'),\n mcpFile: projectMcpFile(cwd),\n mcpScope: 'project',\n }\n : {\n settingsPath: userSettingsPath(env, home),\n mcpFile: userMcpFile(env, home),\n mcpScope: 'user',\n };\n}\n\n/** The settings install's state, as install, update, doctor and uninstall report it. */\nexport interface Migration {\n /**\n * `none` (no settings install here), `pending` (left in place until the\n * plugin proves it loads), `done` (removed by this run), or `blocked` (the\n * settings file could not be read).\n */\n state: 'none' | 'pending' | 'done' | 'blocked';\n settingsPath: string;\n /** Why it is still pending or blocked. */\n reason?: string;\n removed?: LegacyRemoval;\n}\n\n/**\n * THE GUARDED MIGRATION. A working settings install is removed only once the\n * plugin has proven to load on this machine: Claude Code at or above the floor\n * and listing the plugin enabled (when a binary can be asked), and the\n * plugin's `alive` leg having stamped the machine from a real session. Until\n * then both stay, and the `alive` marker keeps the old legs silent in any\n * session the plugin serves. Only `install` and `update` migrate; doctor\n * reports.\n */\nexport async function pluginProof(\n claude: ClaudeCodeState,\n dataDir: string,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<{ proven: true } | { proven: false; reason: string }> {\n if (claude.binary !== null && !claude.meetsFloor) {\n return {\n proven: false,\n reason: `Claude Code ${claude.version ?? '(unknown)'} is older than the plugin needs`,\n };\n }\n if (claude.binary !== null) {\n const listing = await readPluginListing(claude.binary, env, cwd);\n if (!listing.enabled) {\n return { proven: false, reason: 'Claude Code does not list the plugin as enabled yet' };\n }\n }\n if ((await readAliveStamp(dataDir)) === null) {\n return {\n proven: false,\n reason: 'the plugin has not loaded in a Claude Code session on this machine yet',\n };\n }\n return { proven: true };\n}\n\nexport async function migrateSettingsInstall(\n legacy: LegacyInstall,\n claude: ClaudeCodeState,\n opts: { dataDir: string; env: NodeJS.ProcessEnv; cwd: string; mcpScope: 'user' | 'project' },\n): Promise<Migration> {\n if (!legacy.present) return { state: 'none', settingsPath: legacy.settingsPath };\n const proof = await pluginProof(claude, opts.dataDir, opts.env, opts.cwd);\n if (!proof.proven) {\n return { state: 'pending', settingsPath: legacy.settingsPath, reason: proof.reason };\n }\n const removed = await removeLegacyInstall(legacy, {\n binary: claude.binary,\n env: opts.env,\n cwd: opts.cwd,\n mcpScope: opts.mcpScope,\n });\n return { state: 'done', settingsPath: legacy.settingsPath, removed };\n}\n\n/**\n * Is there a project install here? A refresh, a bare doctor and a bare\n * uninstall are given no scope, and `tenjin update` runs its refresh from\n * home, where nothing proves one. A project install is taken when this\n * directory, not being home, holds one: the plugin enabled in its\n * `settings.local.json`, its plugin folder, or a settings install's entries.\n */\nexport async function projectInstallHere(\n cwd: string,\n home: string,\n env: NodeJS.ProcessEnv,\n): Promise<boolean> {\n if (await isHome(cwd, home)) return false;\n return projectInstallAt(cwd, home, env);\n}\n\n/**\n * Does `dir` still hold the project install `install --project` recorded\n * there? Home included: a `--project` install at home is supported, and there\n * its plugin folder and settings file are the user install's own, so only the\n * plugin enabled in `.claude/settings.local.json` proves it.\n */\nexport async function projectInstallAt(\n dir: string,\n home: string,\n env: NodeJS.ProcessEnv,\n): Promise<boolean> {\n const local = await readFile(join(dir, '.claude', 'settings.local.json'), 'utf8')\n .then((raw) => JSON.parse(raw) as { enabledPlugins?: Record<string, unknown> })\n .catch(() => null);\n if (local?.enabledPlugins?.[PLUGIN_ID] === true) return true;\n if (await isHome(dir, home)) return false;\n if ((await folderState('local', env, home, dir)).state === 'ours') return true;\n const paths = settingsInstallPaths(true, env, home, dir);\n return (await inspectLegacyInstall(paths.settingsPath, paths.mcpFile)).events.length > 0;\n}\n\nasync function isHome(dir: string, home: string): Promise<boolean> {\n const [dirPath, homePath] = await Promise.all([\n realpath(dir).catch(() => dir),\n realpath(home).catch(() => home),\n ]);\n return dirPath === homePath;\n}\n\n/** How a refresh with no Claude Code install to converge refuses. */\nexport const NOTHING_TO_REFRESH = 'Nothing to refresh';\n\n/** Is any install of ours here for a refresh to bring up to date? */\nasync function somethingToRefresh(\n claude: ClaudeCodeState,\n scope: PluginScope,\n legacy: LegacyInstall,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<boolean> {\n if (legacy.present) return true;\n if ((await folderState(scope, env, home, cwd)).state === 'ours') return true;\n if (claude.binary !== null) {\n const listing = await readPluginListing(claude.binary, env, cwd);\n if (listing.id === PLUGIN_ID) return true;\n }\n return false;\n}\n\nexport async function runRouterInstall(\n args: RouterInstallArgs,\n ctx: CommandContext,\n deps: RouterInstallDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) {\n throw new CliError('INTERNAL', 'The home directory is not an absolute path.', {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n });\n }\n const config = await loadRawConfig(ctx.dataDir); // Validate before any install writes; retired keys remain readable.\n const named = namedLimits(args);\n const cwd = deps.cwd ?? process.cwd();\n // An explicit --project wins, including for a project rooted at home.\n const project =\n args.project ?? (args.refresh === true && (await projectInstallHere(cwd, home, env)));\n const scope: PluginScope = project ? 'local' : 'user';\n const claude = await readClaudeCode(env, cwd, deps.findClaude ?? findClaudeBinary);\n const paths = settingsInstallPaths(project, env, home, cwd);\n const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);\n // CLAUDE CODE'S OWN PROJECT INSTALLS ARE RECORDED, before a refresh can\n // refuse: `tenjin update` refreshes every recorded project after its home\n // child, so a project an older release installed without recording it\n // moves to the runtime with the rest. A user-scope run only; never fatal.\n if (!project) {\n await recordClaudeProjects(ctx.dataDir, config.install?.routerProjects ?? [], env, home);\n }\n\n const setUpRuntime = () =>\n (deps.runtime ?? defaultRuntime)({\n dataDir: ctx.dataDir,\n home,\n env,\n version: pkg.version,\n moduleDir: dirname(fileURLToPath(import.meta.url)),\n refresh: args.refresh === true,\n });\n\n if (args.refresh === true && !(await somethingToRefresh(claude, scope, legacy, env, home, cwd))) {\n // A RUNTIME WITH NO CLAUDE CODE SURFACE: `tenjin uninstall --harness\n // claude` keeps the runtime and its launcher while Codex still runs them,\n // and `tenjin update` brings that runtime up to its new build through this\n // same refresh. Only the runtime step runs; nothing for Claude Code is\n // registered, written or migrated.\n if (!project && hasRuntime(ctx.dataDir, home)) {\n const rt = await setUpRuntime();\n if (runtimeLaunch(rt) !== null) {\n await collectRuntime(rt.root, await fallbackFolders(ctx.dataDir, env, home, cwd, false));\n }\n return runtimeOnlyRefresh(ctx, rt, home);\n }\n throw new CliError(\n 'REFUSED',\n `${NOTHING_TO_REFRESH}: neither the ${PLUGIN_ID} plugin nor a settings install of Tenjin is registered here.`,\n { fix: 'Run `tenjin install` to set this machine up.' },\n );\n }\n // The shelf install's gate: a refresh, `--json`, or a run with no terminal on\n // either side asks nothing. An agent's install is that run: its shell has no\n // terminal. Install then writes no spend limit, the defaults ($0.25 a call,\n // $5 a day) hold as they do for any key the file leaves out, and its output hands\n // the question to whoever ran it (see {@link spendApproval}).\n const humanOutput = ctx.flags.json === true ? false : (deps.isInteractive ?? ctx.io.isTTY);\n const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n // `--yes` is the selector's \"Use the defaults\", answered ahead, and the two\n // amount flags its \"Set my own limits\": the same install, run\n // again by an agent for the person's answer. A file that names either limit\n // has been answered before, so nothing asks again.\n const answered = args.yes === true || named.keys.length > 0;\n const unasked = config.maxAutoSpend === undefined && config.sessionBudget === undefined;\n const limits =\n args.refresh === true\n ? undefined\n : named.keys.length > 0\n ? { ...shownLimits(config), ...named.limits }\n : args.yes === true\n ? shownLimits(config)\n : canPrompt && unasked\n ? await approveLimits(deps)\n : {};\n const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true, limits, named.keys);\n const removedKeysLines =\n spend.removed.length > 0\n ? [\n `Removed retired settings: ${spend.removed.join(', ')}. Automatic router limits remain in effect; manual pay always requires consent.`,\n ]\n : [];\n const removedSkills = await removeRetiredSkills(home, project ? cwd : undefined);\n // BELOW THE FLOOR, A WORKING SETTINGS INSTALL WINS. The plugin's routing\n // legs need Claude Code 2.1.287, but its `alive` leg is a command that runs\n // on any version and would silence the settings install in every session,\n // leaving the machine unrouted. So nothing is registered until `claude\n // update`, and the settings install keeps routing, and no runtime is set up.\n const deferred = !claude.meetsFloor && legacy.present;\n // TENJIN'S OWN RUNTIME, set up before the plugin is registered from it. Only\n // a folder rendered from a build that passed its checks is registered;\n // anything else keeps today's registration from this package (`fallback`,\n // `skipped`). A `kept` runtime (newer, or this build failed its checks)\n // registers that runtime's own version. One user-scope `marketplace add`\n // repoints every project install too, since Claude Code keeps one global\n // `tenjin` row; a `--project` run repoints the same row to the same folder.\n const rt = deferred ? null : await setUpRuntime();\n const launch = runtimeLaunch(rt);\n const plugin: PluginRegistration = deferred\n ? deferredRegistration(scope, claude)\n : await registerPlugin({\n binary: claude.binary,\n scope,\n version: launch?.version ?? pkg.version,\n env,\n home,\n cwd,\n ...(launch !== null\n ? { hostsDir: launch.hostsDir, cliEntry: launch.cliEntry, node: launch.node }\n : {\n ...(deps.hostsDir !== undefined ? { hostsDir: deps.hostsDir } : {}),\n ...(deps.cliEntry !== undefined ? { cliEntry: deps.cliEntry } : {}),\n }),\n });\n // A registration that failed after this run switched the runtime puts the\n // runtime back, so Claude Code is never left on a folder it was not given.\n // UNLESS ITS `marketplace add` WENT THROUGH: Claude Code's one `tenjin` row\n // now names `runtime/claude` and reads it in place, so putting back what was\n // there (nothing at all, on a first activation) would leave it loading an\n // empty folder. The render it holds passed `verifyBuild`, so it stays.\n // Old versions are collected only once the plugin is registered.\n if (rt !== null && launch !== null) {\n if (plugin.state !== 'failed') {\n await collectRuntime(rt.root, await fallbackFolders(ctx.dataDir, env, home, cwd, project));\n } else if (!marketplaceAdded(plugin, launch.hostsDir)) {\n await rt.restore?.().catch(() => undefined);\n }\n }\n // A PROJECT INSTALL IS RECORDED, so `tenjin update`, which refreshes from\n // home where this scope is not visible, refreshes it from here too.\n if (project && plugin.state !== 'failed') {\n await persistRouterProject(ctx.dataDir, cwd).catch(() => undefined);\n }\n const migration =\n legacy.unreadable !== undefined && !legacy.present\n ? { state: 'blocked' as const, settingsPath: paths.settingsPath, reason: legacy.unreadable }\n : await migrateSettingsInstall(legacy, claude, {\n dataDir: ctx.dataDir,\n env,\n cwd,\n mcpScope: paths.mcpScope,\n });\n // A `tenjin mcp` that started before this install runs the old build until\n // its session reloads it. Named, never killed.\n const pending = settingsInstallStays(migration);\n const servers = await readMcpServers(deps, {\n settingsInstallPending: pending,\n ...(launch !== null ? { version: launch.version } : {}),\n });\n const serverLines =\n servers.stale > 0\n ? [paint(ctx.io, 'yellow', `! ${servers.check.detail}. ${servers.check.fix ?? ''}`.trim())]\n : [];\n const claudeCode = claudeCodeData(claude);\n const notices = refreshNotices(plugin, claude, migration, rt, home);\n if (args.refresh === true) {\n // A refresh that could not register the plugin is not a converged install,\n // unless the settings install it would replace still routes here.\n if (plugin.state === 'failed' && migration.state !== 'pending') {\n throw new CliError(\n 'REFUSED',\n `The ${PLUGIN_ID} plugin could not be registered: ${plugin.reason ?? 'unknown reason'}.`,\n { fix: registrationFix(plugin), details: { plugin, claudeCode, migration } },\n );\n }\n return {\n data: {\n plugin,\n claudeCode,\n migration,\n notices,\n refresh: true,\n spend,\n removedSkills,\n scope,\n mcpServer: servers.check,\n runtime: runtimeData(rt),\n launcher: rt?.launcher ?? null,\n },\n humanLines: [\n ...refreshLines(ctx, plugin, claude, migration, rt, home),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n }\n // The shelf install's wallet step, unchanged except that it never asks: a\n // lookup cannot be paid without a wallet, so install makes one. A failure is\n // reported, never fatal; everything above is useful without it. It checks\n // that the wallet can SIGN (`verify`), and nothing about routing or funds:\n // install computes no routing eligibility, and its funding step below is\n // today's (S6). Loaded lazily: the status line shares this module's chunk\n // and must not load the wallet layer.\n const { resolveWallet } = await import('../commands/install-wallet');\n const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? 'flag' : undefined, false);\n // Read back AFTER the write: a machine that already carried its own caps\n // keeps them, and a readout quoting the defaults would describe limits this\n // run did not set.\n const effective = await resolveContextSettings(ctx);\n const spendAsk = !canPrompt && !answered && unasked ? spendStep(args) : undefined;\n // A warning, never a failure: everything above is written and correct, and\n // the network this machine is on now may not be the one it uses later.\n const asksAgent = !canPrompt && underAgentHarness(env);\n const [router, fund] = await Promise.all([\n probeRouter(effective.baseUrl, {\n timeoutMs: ctx.flags.timeout,\n env,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n // The spend question comes first, because its answer picks the install\n // command. The funding question rides on the install that follows it.\n asksAgent && spendAsk === undefined\n ? fundStep(wallet, effective.rpcUrl, deps)\n : Promise.resolve(undefined),\n ]);\n const nextSteps: QuestionStep[] = [\n ...(spendAsk !== undefined ? [spendAsk] : []),\n ...(fund !== undefined ? [fund] : []),\n ];\n\n const data = {\n plugin,\n claudeCode,\n migration,\n next: nextStep(\n plugin,\n claude,\n wallet,\n migration,\n asksAgent && nextSteps.length > 0,\n ctx.io.isTTY,\n ),\n nextSteps,\n // The check for this scope, said outright; a bare doctor in the project\n // also finds it from what the project holds.\n ...(project ? { doctor: 'tenjin doctor --project' } : {}),\n spend: { ...spend, effective: effectiveLimits(effective.policy) },\n wallet,\n router: {\n status: router.status === 'ok' ? 'ok' : 'warn',\n detail: router.detail,\n ...(router.fix !== undefined ? { fix: router.fix } : {}),\n },\n disclosure: DISCLOSURE,\n removedSkills,\n mcpServer: servers.check,\n runtime: runtimeData(rt),\n launcher: rt?.launcher ?? null,\n };\n return {\n data,\n humanLines: [\n ...lines(ctx, {\n plugin,\n claude,\n migration,\n wallet,\n ...(fund !== undefined ? { fund } : {}),\n asks: asksAgent && nextSteps.length > 0,\n policy: effective.policy,\n ...(spendAsk !== undefined ? { spendAsk } : {}),\n router,\n rt,\n home,\n }),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n}\n\n/** Loaded lazily: the status line shares this module's chunk and must not load the runtime. */\nexport async function defaultRuntime(o: Parameters<typeof setupRuntime>[0]): Promise<RuntimeSetup> {\n const { setupRuntime } = await import('../lib/runtime');\n return setupRuntime(o);\n}\n\n/** Results a later host of one install run got from the first host's setup: their lines were said there. */\nconst sharedResults = new WeakSet<RuntimeSetup>();\n\n/**\n * ONE RUNTIME SETUP PER INSTALL RUN, however many hosts it installs. The first\n * host sets the runtime up; every later host gets that result rather than a\n * second setup, which would retry a failed Node download in full, and says\n * none of its lines again.\n */\nexport function runtimeOncePerRun(setup = defaultRuntime): typeof defaultRuntime {\n let first: Promise<RuntimeSetup> | undefined;\n return async (o) => {\n if (first === undefined) {\n first = setup(o);\n return first;\n }\n const rt = { ...(await first) };\n sharedResults.add(rt);\n return rt;\n };\n}\n\n/** Is there a runtime here? Only the default data dir has one, and only once an install set it up. */\nexport function hasRuntime(dataDir: string, home: string): boolean {\n return (\n resolve(dataDir) === resolve(defaultDataDir(home)) &&\n existsSync(runtimeStatePath(runtimeDir(dataDir)))\n );\n}\n\n/**\n * A refresh that brought only the runtime up to date, for a machine with no\n * Claude Code surface of Tenjin's: `plugin` is null, and the runtime's\n * sentences ride in `notices` for update's parent, as a full refresh's do.\n */\nfunction runtimeOnlyRefresh(ctx: CommandContext, rt: RuntimeSetup, home: string): CommandResult {\n return {\n data: {\n plugin: null,\n refresh: true,\n scope: 'user',\n notices: runtimeNotices(rt, home),\n runtime: runtimeData(rt),\n launcher: rt.launcher,\n },\n humanLines: [\n `${paint(ctx.io, 'green', '✓')} Tenjin's runtime is up to date; no Claude Code plugin is registered here, so none was refreshed`,\n ...runtimeLines(ctx, rt, home),\n ],\n };\n}\n\n/**\n * GC of the runtime's unused versions: an optimisation that never holds\n * install up or fails it. The plugin folders in `folders` that are ours run a\n * runtime version and its Node by absolute path, which `state.json` does not\n * name, so those are kept.\n */\nasync function collectRuntime(root: string, folders: readonly string[]): Promise<void> {\n try {\n const { collect } = await import('../lib/runtime');\n await collect(root, { lockWaitMs: 5_000, keep: await folderPointers(root, folders) });\n } catch {\n // The next install collects them.\n }\n}\n\n/**\n * Every plugin folder an install wrote where it could run no `claude` binary:\n * the user's under the config dir, and each recorded project's (plus this\n * run's, for a `--project` run not recorded yet) under its `.claude/skills/`.\n */\nasync function fallbackFolders(\n dataDir: string,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n project: boolean,\n): Promise<string[]> {\n const projects = (await loadRawConfig(dataDir).catch(() => null))?.install?.routerProjects ?? [];\n return [\n folderFor('user', env, home, cwd),\n ...[...projects, ...(project ? [cwd] : [])].map((dir) => folderFor('local', env, home, dir)),\n ];\n}\n\n/** A `node/<V>` folder name: digits and dots only, so a `..` can never pass. */\nconst NODE_DIR_RE = /^\\d+\\.\\d+\\.\\d+$/;\n\n/**\n * The runtime version and Node each folder that exists and is ours runs, read\n * from its `.mcp.json`: an entry under `<root>/versions/<cli>/` run by a Node\n * under `<root>/node/<V>/`. A folder run from a package, or unreadable, names\n * none.\n */\nasync function folderPointers(root: string, folders: readonly string[]): Promise<RuntimePointer[]> {\n const pointers: RuntimePointer[] = [];\n for (const dir of folders) {\n if ((await inspectPluginFolder(dir)) !== 'ours') continue;\n const server = await readFile(join(dir, '.mcp.json'), 'utf8')\n .then(\n (raw) =>\n (\n JSON.parse(raw) as {\n mcpServers?: Record<string, { command?: unknown; args?: unknown }>;\n }\n ).mcpServers?.[MCP_SERVER_NAME],\n )\n .catch(() => undefined);\n const entry = Array.isArray(server?.args) ? (server.args[0] as unknown) : undefined;\n const node = server?.command;\n if (typeof entry !== 'string' || typeof node !== 'string') continue;\n const build = runtimeBuild(dirname(entry));\n const nodeVersion = relative(join(root, 'node'), node).split(sep)[0] ?? '';\n if (build !== null && resolve(build.root) === resolve(root) && NODE_DIR_RE.test(nodeVersion)) {\n pointers.push({ cli: build.cli, node: nodeVersion });\n }\n }\n return pointers;\n}\n\n/** What the plugin is registered from when the runtime has a build for it, or null for this package. */\nfunction runtimeLaunch(\n rt: RuntimeSetup | null,\n): { version: string; hostsDir: string; cliEntry: string; node: string } | null {\n if (rt === null || (rt.state !== 'active' && rt.state !== 'current' && rt.state !== 'kept')) {\n return null;\n }\n if (\n rt.cli === undefined ||\n rt.hostsDir === undefined ||\n rt.entry === undefined ||\n rt.node === undefined\n ) {\n return null;\n }\n return { version: rt.cli, hostsDir: rt.hostsDir, cliEntry: rt.entry, node: rt.node };\n}\n\nexport function runtimeData(rt: RuntimeSetup | null): Record<string, unknown> | null {\n if (rt === null) return null;\n return {\n state: rt.state,\n root: rt.root,\n ...(rt.cli !== undefined ? { cli: rt.cli } : {}),\n ...(rt.nodeVersion !== undefined ? { nodeVersion: rt.nodeVersion } : {}),\n ...(rt.reason !== undefined ? { reason: rt.reason } : {}),\n ...(rt.fix !== undefined ? { fix: rt.fix } : {}),\n };\n}\n\n/**\n * Adds to `install.routerProjects` every project install Claude Code records\n * that is still on disk and not yet there. An unreadable record adds nothing.\n */\nasync function recordClaudeProjects(\n dataDir: string,\n known: readonly string[],\n env: NodeJS.ProcessEnv,\n home: string,\n): Promise<void> {\n const records = await recordedInstalls(env, home).catch(() => null);\n if (records === null || records.every((r) => r.projectPath === null)) return;\n const seen = new Set([\n ...known,\n ...(await Promise.all(known.map((dir) => realpath(dir).catch(() => dir)))),\n ]);\n for (const { projectPath } of records) {\n if (projectPath === null || seen.has(projectPath)) continue;\n if ((await stat(projectPath).catch(() => null))?.isDirectory() !== true) continue;\n seen.add(projectPath);\n await persistRouterProject(dataDir, projectPath).catch(() => undefined);\n }\n}\n\n/** `path` with the home folder written as `~`. */\nexport function tilde(path: string, home: string): string {\n return path === home || path.startsWith(`${home}${sep}`) ? `~${path.slice(home.length)}` : path;\n}\n\n/** The first activation's line, said once: where Tenjin runs from now. */\nfunction runtimeSentence(rt: RuntimeSetup, home: string): string | null {\n if (rt.state !== 'active' || !rt.firstTime) return null;\n return `Runs from ${tilde(rt.root, home)} on its own Node ${rt.nodeVersion ?? ''}, so a Node upgrade or \\`npm rm -g tenjin-cli\\` no longer stops it.`;\n}\n\n/**\n * Why the plugin still runs on the Node on PATH, or on an older runtime build\n * than this one. A platform Tenjin pins no Node for is said as it is, with no\n * retry: no install here can set the runtime up. A failure with a step that\n * works (a download that skipped the shell's proxy) names that step instead. A refresh that found a newer\n * runtime tried nothing, so it says nothing.\n */\nfunction fallbackSentence(rt: RuntimeSetup): string | null {\n if (rt.state === 'fallback' && rt.unpinned !== undefined) {\n return `Tenjin pins no Node for this platform (${rt.unpinned}), so the plugin runs from npm's copy on the Node on your PATH, as before.`;\n }\n const next = rt.fix ?? 'run `tenjin install` again to retry';\n if (rt.state === 'fallback') {\n return `Tenjin's own runtime could not be set up (${rt.reason ?? 'unknown reason'}), so the plugin still runs on the Node on your PATH; ${next}.`;\n }\n if (rt.state === 'kept' && rt.reason !== undefined && rt.newer !== true) {\n const retry = rt.unpinned === undefined ? `; ${next}` : '';\n return `tenjin-cli ${pkg.version} could not be set up (${rt.reason}), so Tenjin keeps running ${rt.cli ?? 'the runtime it has'}${retry}.`;\n }\n return null;\n}\n\n/**\n * What the person needs to know about the `tenjin` launcher: only a file in\n * its place that is not Tenjin's, a write that failed, or a launcher folder\n * off PATH. npm's own link there (npm prefix `~/.local`) says nothing.\n */\nfunction launcherSentence(launcher: LauncherResult | null, home: string): string | null {\n if (launcher === null) return null;\n if (launcher.state === 'foreign') {\n const who = launcher.reason?.replace(/ is not Tenjin's$/, '') ?? launcher.paths[0] ?? '';\n return `${who} is not Tenjin's, so it was left as it is, and \\`tenjin\\` there runs that file instead of Tenjin's runtime. Move it aside and run \\`tenjin install\\` again to put Tenjin's there.`;\n }\n if (launcher.state === 'failed') {\n const dir = launcher.paths[0] !== undefined ? tilde(dirname(launcher.paths[0]), home) : '';\n return `Tenjin's \\`tenjin\\` launcher could not be written to ${dir} (${launcher.reason ?? 'unknown reason'}), so a terminal finds \\`tenjin\\` only through npm's copy; run \\`tenjin install\\` again to retry.`;\n }\n if ((launcher.state === 'written' || launcher.state === 'current') && !launcher.onPath) {\n return `~/.local/bin is not on your PATH, so a terminal will not find \\`tenjin\\` once npm's copy is gone (inside Claude Code the plugin's own \\`tenjin\\` is on the Bash tool's PATH). Add it: ${launcher.pathLine ?? ''}`;\n }\n return null;\n}\n\n/** The runtime's lines under install's summary: where it runs from, or what needs the person. */\nexport function runtimeLines(ctx: CommandContext, rt: RuntimeSetup | null, home: string): string[] {\n if (rt === null || sharedResults.has(rt)) return [];\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const runs = runtimeSentence(rt, home);\n const fallback = fallbackSentence(rt);\n const launcher = launcherSentence(rt.launcher, home);\n return [\n ...(runs !== null ? [` ${runs}`] : []),\n ...(fallback !== null ? [warn(fallback)] : []),\n ...(launcher !== null ? [warn(launcher)] : []),\n ];\n}\n\nfunction claudeCodeData(claude: ClaudeCodeState): Record<string, unknown> {\n return {\n binary: claude.binary?.path ?? null,\n source: claude.binary?.source ?? null,\n version: claude.version,\n meetsFloor: claude.meetsFloor,\n ...(claude.fix !== undefined ? { fix: claude.fix } : {}),\n };\n}\n\n/**\n * The fix for a registration that did not happen, worded as a step the agent\n * can take in the session: never a command for the person to run elsewhere.\n */\nfunction registrationFix(plugin: PluginRegistration): string {\n // A project install is retried, and checked, as one.\n const flag = plugin.scope === 'local' ? ' --project' : '';\n if (plugin.id !== null && plugin.method === 'none') {\n return `${plugin.id} keeps serving this machine at the version Claude Code has; run \\`tenjin install${flag}\\` again to retry.`;\n }\n if (\n plugin.path !== undefined &&\n plugin.reason?.includes('not a folder this CLI wrote') === true\n ) {\n return `Move ${plugin.path} aside, then run \\`tenjin install${flag}\\` again.`;\n }\n return `Run \\`tenjin doctor${flag}\\` to see the cause, then run \\`tenjin install${flag}\\` again.`;\n}\n\n/** The unlock reasons `tenjin wallet repair` fixes: a saved passphrase that is gone or wrong. */\nconst REPAIRABLE: ReadonlySet<string> = new Set([\n 'passphrase_missing',\n 'passphrase_wrong',\n 'env_passphrase_wrong',\n]);\n\n/**\n * The repair step, worded for whoever reads install's output (decision 15):\n * a person at a terminal runs it; an agent (no TTY) asks the person to, and\n * never asks for the passphrase (B1).\n */\nfunction repairStep(tty: boolean): string {\n return tty\n ? `run \\`tenjin wallet repair\\` yourself ${REPAIR_CLAUSE}`\n : 'ask the person to run `tenjin wallet repair` in their own terminal (never ask for the passphrase)';\n}\n\n/**\n * The one step after the install, for the agent to relay in the session. A\n * wallet whose saved passphrase is gone or wrong is repaired first; otherwise\n * today's steps, unchanged (no new funding step for an existing wallet, S6).\n */\nfunction nextStep(\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n wallet: WalletOutcome,\n migration: Migration,\n asksQuestion: boolean,\n tty: boolean,\n): string {\n if (plugin.state === 'failed') return registrationFix(plugin);\n const steps = todaysSteps(plugin, claude, wallet, migration, asksQuestion);\n const signing = wallet.signing;\n if (signing?.status === 'blocked' && REPAIRABLE.has(signing.reason)) {\n steps.unshift(repairStep(tty));\n }\n return steps.join(', then ');\n}\n\nfunction todaysSteps(\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n wallet: WalletOutcome,\n migration: Migration,\n asksQuestion: boolean,\n): string[] {\n const steps: string[] = [];\n if (asksQuestion) {\n steps.push('ask the person the question in nextSteps, then run what the answer names');\n } else if (wallet.status === 'created') {\n steps.push('fund the wallet with `tenjin wallet fund`');\n }\n if (plugin.state === 'deferred') {\n steps.unshift('run `claude update`');\n steps.push(\n 'run `tenjin install` again; until then the earlier Tenjin setup keeps routing as before',\n );\n return steps;\n }\n if (!claude.meetsFloor) steps.unshift('run `claude update`');\n steps.push(loadStep(settingsInstallStays(migration)));\n return steps;\n}\n\n/** Is a settings install still on this machine after this run? */\nfunction settingsInstallStays(migration: Migration): boolean {\n return migration.state === 'pending' || migration.state === 'blocked';\n}\n\nfunction deferredRegistration(scope: PluginScope, claude: ClaudeCodeState): PluginRegistration {\n return {\n method: 'none',\n id: null,\n scope,\n state: 'deferred',\n version: pkg.version,\n steps: [],\n reason: `Claude Code ${claude.version ?? ''} is older than ${CLAUDE_CODE_FLOOR}, which the plugin needs, so it was not registered and the earlier settings setup keeps routing`,\n };\n}\n\n/** The status line a migration took out, in words, or nothing. */\nfunction statusLineNotice(migration: Migration): string | null {\n const status = migration.removed?.statusLine;\n if (status === 'removed') {\n return 'Removed the Tenjin status line (`tenjin status-line`) with the earlier settings setup; the plugin sets none. To keep it, set `tenjin status-line` as your Claude Code status line command.';\n }\n if (status === 'restored') {\n return 'Took the Tenjin footer out of your status line and put your own command back; the plugin sets none.';\n }\n return null;\n}\n\n/**\n * WHAT `tenjin update` PRINTS FROM THIS REFRESH. Update captures this run's\n * output and shows only its failures, so anything a person must know about a\n * refresh that succeeded rides here, as sentences the parent prints verbatim.\n */\nfunction refreshNotices(\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n migration: Migration,\n rt: RuntimeSetup | null,\n home: string,\n): string[] {\n const out: string[] = [];\n if (plugin.state === 'deferred') {\n out.push(\n `Claude Code ${claude.version ?? ''} is older than ${CLAUDE_CODE_FLOOR}, so the Tenjin plugin was not registered and the earlier settings setup keeps routing. Run \\`claude update\\`, then \\`tenjin install\\`.`,\n );\n } else if (plugin.state !== 'failed' && settingsInstallStays(migration)) {\n out.push(\n 'Start a new Claude Code session so the Tenjin plugin loads; the earlier settings setup is removed by the next `tenjin update` or `tenjin install` after that.',\n );\n }\n const status = statusLineNotice(migration);\n if (status !== null) out.push(status);\n if (rt !== null) out.push(...runtimeNotices(rt, home));\n return out;\n}\n\n/** The runtime's sentences among a refresh's notices: where it runs from, and what needs the person. */\nfunction runtimeNotices(rt: RuntimeSetup, home: string): string[] {\n const out: string[] = [];\n const runs = runtimeSentence(rt, home);\n if (runs !== null) out.push(`Tenjin ${runs.charAt(0).toLowerCase()}${runs.slice(1)}`);\n for (const sentence of [fallbackSentence(rt), launcherSentence(rt.launcher, home)]) {\n if (sentence !== null) out.push(sentence);\n }\n return out;\n}\n\n/** The one rule for every step the agent relays from install. */\nexport const SHOW_NOT_RUN =\n 'Show the person addresses as written, and never ask them to run a command.';\n\n/**\n * An agent runs install with `--json` or in a shell with no terminal, so the\n * CLI cannot ask. The agent can: this is what the selector would have shown\n * (the defaults, the routing fee) and what to run for each answer, the same\n * shape as the `request` tool's `needs_input` step. A script or CI ignores\n * it, and the defaults hold.\n */\nfunction spendStep(args: RouterInstallArgs): QuestionStep {\n return spendStepFor(installCommand(args));\n}\n\n/** The same question, for an install an agent runs again as `command`. */\nexport function spendStepFor(command: string): QuestionStep {\n const options = spendOptions(command);\n const [byDefault, custom] = options as [SpendOption, SpendOption];\n return {\n id: 'spend',\n question: spendChoiceQuestion(),\n options,\n next: `In this session, ask the person this question with your question tool, offering these two options in order with the defaults marked recommended. The defaults are already in effect. Use the defaults: run \\`${byDefault.command}\\`. Set my own limits: ask for the most per day in USD (or none for no daily limit) and the most per call in USD (at least 0.25), then run \\`${custom.command}\\` with their amounts. Run the command alone, never joined with another command, and do not ask again a question its output repeats. ${SHOW_NOT_RUN}`,\n };\n}\n\n/** The install this run was: what an agent runs again for the person's answer. */\nfunction installCommand(args: RouterInstallArgs): string {\n return [\n 'tenjin install',\n ...(args.project === true ? ['--project'] : []),\n ...(args.noWallet === true ? ['--no-wallet'] : []),\n ].join(' ');\n}\n\n/** The limits the person named with `--max-auto-spend` and `--session-budget`, refused before any write. */\nexport function namedLimits(\n args: Pick<RouterInstallArgs, 'maxAutoSpend' | 'sessionBudget' | 'refresh'>,\n): {\n limits: Partial<RouterLimits>;\n keys: (keyof RouterLimits)[];\n} {\n const flags = [\n ['maxAutoSpend', '--max-auto-spend', args.maxAutoSpend, 'call'],\n ['sessionBudget', '--session-budget', args.sessionBudget, 'day'],\n ] as const;\n const limits: Partial<RouterLimits> = {};\n const keys: (keyof RouterLimits)[] = [];\n for (const [key, flag, raw, per] of flags) {\n if (raw === undefined) continue;\n if (args.refresh === true) {\n throw new CliError('USAGE', `${flag} sets a spend limit, and --refresh writes none.`, {\n fix: `Run \\`tenjin install ${flag} ${raw}\\` without --refresh.`,\n });\n }\n const parsed = parseLimit(raw, per);\n if ('refusal' in parsed) {\n throw new CliError('USAGE', `${flag} ${raw}: ${parsed.refusal}`, {\n fix:\n per === 'day'\n ? `Give a positive USD amount or none, for example \\`${flag} 5\\`.`\n : `Give 0.25 USD or more, for example \\`${flag} 0.5\\`. ${MAX_AUTO_SPEND_FLOOR_WHY}`,\n });\n }\n limits[key] = parsed.value;\n keys.push(key);\n }\n return { limits, keys };\n}\n\n/** The funding question an agent's completed install hands over: the checkout's $5 minimum. */\nexport const FUND_QUESTION = `Do you want to add $${SUGGESTED_FUND_USD} to your Tenjin wallet now?`;\n/** Its yes: the agent runs this alone, in the turn the person answered. */\nexport const FUND_COMMAND = `tenjin wallet fund ${SUGGESTED_FUND_USD}`;\n\n/** One question install hands to the agent that ran it, with what each answer runs. */\nexport interface QuestionStep {\n id: 'spend' | 'fund';\n /** For the agent to put to the person as written, with `options`. */\n question: string;\n options: {\n id: string;\n label: string;\n recommended: boolean;\n /** What to ask the person after they pick this option, before running `command`. */\n ask?: string[];\n /** The one command the agent runs alone for this answer, or null: run nothing. */\n command: string | null;\n }[];\n /** What the agent does with each answer. */\n next: string;\n}\n\n/** The funding question, with the address the person needs to add funds later. */\nexport interface FundStep extends QuestionStep {\n id: 'fund';\n address: string;\n /** The address, for the agent to show the person as written. */\n show: string;\n}\n\n/**\n * THE QUESTION BEFORE THE ACTION. Under an agent harness, install opens no\n * browser and pays nothing: once the spend answer has picked the install, the\n * install hands the agent the funding question, so the page opens only after\n * an answer the person gave in the session. It mints no link: \"Not now\" shows\n * the address, and a later yes runs `tenjin wallet fund`. A wallet that\n * already holds USDC gets no question.\n */\nasync function fundStep(\n wallet: WalletOutcome,\n rpcUrl: string,\n deps: RouterInstallDeps,\n): Promise<FundStep | undefined> {\n const address = wallet.address;\n if (address === undefined || (wallet.status !== 'created' && wallet.status !== 'existing')) {\n return undefined;\n }\n const funded =\n wallet.status === 'created'\n ? false\n : await (deps.walletBalance ?? defaultBalance)(address, rpcUrl).then(\n (atomic) => atomic > 0n,\n () => null,\n );\n if (funded === true) return undefined;\n const show = `To add funds, send USDC on Base to ${address}.`;\n return {\n id: 'fund',\n question: FUND_QUESTION,\n options: [\n {\n id: 'fund',\n label: 'Yes, open the funding page',\n recommended: false,\n command: FUND_COMMAND,\n },\n { id: 'later', label: 'Not now', recommended: false, command: null },\n ],\n next: `The install is done. Ask the person this question with your question tool. On \"Yes, open the funding page\", run \\`${FUND_COMMAND}\\` alone, in the same turn. On \"Not now\", run nothing and show the person this for later: ${show} Never run \\`${FUND_COMMAND}\\` without this yes. ${SHOW_NOT_RUN}`,\n address,\n show,\n };\n}\n\n/** Loaded lazily: the status line shares this module's chunk and must not load viem. */\nasync function defaultBalance(address: string, rpcUrl: string): Promise<bigint> {\n const { getUsdcBalance } = await import('../lib/usdc');\n return getUsdcBalance(address as `0x${string}`, rpcUrl);\n}\n\n/** The funding question, as the summary prints it. */\nfunction fundLines(fund: FundStep): string[] {\n return [\n ` Ask the person: ${fund.question}`,\n ` Yes, open the funding page: ${FUND_COMMAND}`,\n ` Not now: run nothing, show them: ${fund.show}`,\n ];\n}\n\n/**\n * The one question install asks, before anything is written: the defaults, or\n * your own limits. It is asked only when the file names neither limit. The\n * question names the routing fee and its deposits too, and either answer\n * approves it. Cancelling at any step writes nothing.\n */\nexport async function approveLimits(\n deps: Pick<RouterInstallDeps, 'promptLimits' | 'promptAmount'>,\n): Promise<RouterLimits> {\n const choice = await (deps.promptLimits ?? promptLimits)(\n `${SPEND_QUESTION}\\n${ROUTING_FEE_TERMS}\\n${FEE_APPROVAL}`,\n );\n if (choice === null) throw installCancelled();\n if (choice === 'approve') return { ...ROUTER_DEFAULTS };\n const ask = deps.promptAmount ?? promptAmount;\n const sessionBudget = await askLimit(\n ask,\n 'Most it may pay in a day, in USD, or none',\n '5',\n 'day',\n );\n const maxAutoSpend = await askLimit(\n ask,\n 'Most it may pay for one call, in USD, at least 0.25',\n '0.25',\n 'call',\n );\n return { maxAutoSpend, sessionBudget };\n}\n\n/** Asks until the answer is a positive amount (or `none` for the daily limit). */\nasync function askLimit(\n ask: NonNullable<RouterInstallDeps['promptAmount']>,\n question: string,\n placeholder: string,\n per: 'call' | 'day',\n): Promise<string> {\n let message = question;\n for (;;) {\n const answer = await ask(message, placeholder);\n if (answer === null) throw installCancelled();\n const parsed = parseLimit(answer, per);\n if (!('refusal' in parsed)) return parsed.value;\n message = `${parsed.refusal} ${question}`;\n }\n}\n\n/** A daily limit is positive or `none`; zero is refused, because\n * `router.enabled false` is how to turn the router off. A per-call limit is\n * at least the $1 floor. */\nfunction parseLimit(answer: string, per: 'call' | 'day'): { value: string } | { refusal: string } {\n const trimmed = answer.trim();\n if (per === 'day' && trimmed === 'none') return { value: 'none' };\n let atomic: string;\n try {\n atomic = parseUsdToAtomic(trimmed);\n } catch (err) {\n if (err instanceof CliError) return { refusal: `${err.message}.` };\n throw err;\n }\n if (per === 'call' && BigInt(atomic) < MAX_AUTO_SPEND_FLOOR_ATOMIC) {\n return { refusal: 'The per-call limit is at least $0.25.' };\n }\n if (atomic === '0') {\n return {\n refusal:\n 'The limit must be more than zero; `tenjin config set router.enabled false` turns the router off.',\n };\n }\n return { value: atomic };\n}\n\nfunction installCancelled(): CliError {\n return new CliError('REFUSED', 'Install cancelled before anything was written.', {\n fix: 'Re-run `tenjin install` and choose the defaults or your own limits.',\n });\n}\n\nfunction promptLimits(message: string): Promise<LimitsChoice | null> {\n return selectOne<LimitsChoice>({\n message,\n choices: [\n { value: 'approve', label: 'Use the defaults' },\n { value: 'own', label: 'Set my own limits' },\n ],\n initialValue: 'approve',\n });\n}\n\nfunction promptAmount(message: string, placeholder: string): Promise<string | null> {\n return askText({ message, placeholder });\n}\n\nexport interface EffectiveLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\nexport function effectiveLimits(policy: SpendPolicy): EffectiveLimits {\n return {\n maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,\n sessionBudget:\n policy.sessionBudgetAtomic === null\n ? 'no daily ceiling'\n : toMoney(policy.sessionBudgetAtomic.toString()).usd,\n };\n}\n\n/**\n * THE WALLET LINE, and who reads it. At a TTY a person ran install, so the\n * person's wording; without one an agent did, and relays it, so a blocked\n * wallet's fix and the S7 passphrase line take the agent's wording (B1,\n * decision 15): ask the person, never ask for the passphrase.\n *\n * A ✓ only for a wallet every Claude Code can unlock: a durable store, a\n * legacy entry, or a variable a served router has already signed with. A\n * wallet that signs only through a variable in this shell is a yellow `!`\n * (S7), as is one that cannot be unlocked, or could not be checked.\n */\nfunction walletLines(ctx: CommandContext, ok: string, w: WalletOutcome): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', text);\n if (w.status === 'created' || w.status === 'existing') {\n const a = w.address ?? '';\n const signing = w.signing;\n const tty = ctx.io.isTTY;\n if (signing?.status === 'blocked') {\n const wallet = Object.prototype.hasOwnProperty.call(WALLET_REASONS, signing.reason)\n ? WALLET_REASONS[signing.reason as keyof typeof WALLET_REASONS]\n : undefined;\n return [\n warn(`! Wallet ${a} cannot be unlocked by Claude Code: ${signing.detail}.`),\n ` ${tty ? (wallet?.fix ?? signing.fix) : agentFixFor(signing.reason, signing.fix)}`,\n ];\n }\n if (signing?.status === 'unknown') {\n return [\n warn(`! Wallet: ${a}; could not check that it unlocks (${signing.detail}).`),\n ' Run `tenjin doctor` to check it again.',\n ];\n }\n if (w.shellOnly === 'key') {\n return [\n warn(\n `! Wallet: ${a} signs here only through TENJIN_WALLET_KEY in this shell; Claude Code must have the same variable.`,\n ),\n ];\n }\n if (w.shellOnly === 'passphrase') {\n return [\n warn(\n tty\n ? `! Wallet: ${a} unlocks here only through TENJIN_WALLET_PASSPHRASE in this shell; Claude Code must have the same variable, or run \\`tenjin wallet repair\\` yourself to store the passphrase ${REPAIR_CLAUSE}.`\n : `! Wallet: ${a} unlocks here only through TENJIN_WALLET_PASSPHRASE in this shell; Claude Code must have the same variable, or ask the person to run \\`tenjin wallet repair\\` in their own terminal to store the passphrase. Never ask for the passphrase.`,\n ),\n ];\n }\n if (w.status === 'created') {\n return [\n `${ok} Wallet created: ${a}`,\n ...(w.passphrase !== undefined ? [` ${w.passphrase.note}`] : []),\n ];\n }\n return [`${ok} Wallet: ${a}`];\n }\n if (w.reason === 'flag') return [' No wallet yet. Create one with: tenjin wallet create'];\n return [\n paint(ctx.io, 'yellow', `! No wallet was created. ${w.warning ?? ''}`.trimEnd()),\n ` ${w.fix ?? 'Create one with: tenjin wallet create'}`,\n ];\n}\n\n/** The plugin line: what Claude Code will list, or why nothing is registered. */\nfunction pluginLines(ctx: CommandContext, plugin: PluginRegistration): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (plugin.state === 'deferred') return [warn(`${plugin.reason ?? ''}`)];\n if (plugin.state === 'failed') {\n return [warn(`The Tenjin plugin was not registered: ${plugin.reason ?? 'unknown reason'}`)];\n }\n if (plugin.method === 'skills-dir') {\n return [\n ` Plugin ${plugin.id ?? ''} written to ${plugin.path ?? ''} (${plugin.fallbackReason ?? ''})`,\n ];\n }\n return [];\n}\n\n/** The settings install's line, when there is one. */\nfunction migrationLines(ctx: CommandContext, migration: Migration): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (migration.state === 'pending') {\n return [\n ` The settings install in ${migration.settingsPath} stays until the plugin has loaded (${migration.reason ?? ''}); \\`tenjin update\\` or \\`tenjin install\\` removes it then.`,\n ];\n }\n if (migration.state === 'blocked') {\n return [warn(`${migration.settingsPath} could not be read: ${migration.reason ?? ''}`)];\n }\n if (migration.state === 'done') {\n const removed = migration.removed;\n const status = statusLineNotice(migration);\n return [\n ` Removed the earlier settings setup from ${migration.settingsPath}: the plugin carries its hooks, permissions and server`,\n ...(status !== null ? [` ${status}`] : []),\n ...(removed?.warnings ?? []).map((w) => warn(w)),\n ];\n }\n return [];\n}\n\nfunction claudeLines(ctx: CommandContext, claude: ClaudeCodeState): string[] {\n if (claude.meetsFloor) return [];\n return [\n paint(\n ctx.io,\n 'yellow',\n `! Claude Code ${claude.version ?? ''} is older than the plugin needs. ${claude.fix ?? ''}`.trim(),\n ),\n ];\n}\n\n/**\n * A few lines a first-time user can read at a glance: it worked, here is your\n * wallet, here is the one thing to do next. Paths, steps and data-handling\n * detail stay in `--json` and the docs; the terminal only grows a line when\n * something needs the user.\n */\nfunction lines(\n ctx: CommandContext,\n s: {\n plugin: PluginRegistration;\n claude: ClaudeCodeState;\n migration: Migration;\n wallet: WalletOutcome;\n fund?: FundStep;\n asks: boolean;\n policy: SpendPolicy;\n spendAsk?: QuestionStep;\n router: RouterCheck;\n rt: RuntimeSetup | null;\n home: string;\n },\n): string[] {\n const ok = paint(ctx.io, 'green', '✓');\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const limits = effectiveLimits(s.policy);\n const daily =\n s.policy.sessionBudgetAtomic === null ? 'no daily limit' : `$${limits.sessionBudget} a day`;\n const spend = [\n ` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`,\n ...(s.spendAsk !== undefined\n ? [\n ` Ask the person in this session: ${s.spendAsk.question}`,\n ...s.spendAsk.options.map(\n (o) => ` ${o.label}${o.recommended ? ' (recommended)' : ''}: ${o.command}`,\n ),\n ]\n : []),\n ];\n const router =\n s.router.status === 'ok'\n ? []\n : [\n warn(`The router did not answer: ${s.router.detail}`),\n ...(s.router.fix !== undefined ? [` ${s.router.fix}`] : []),\n ];\n return [\n s.plugin.state === 'failed'\n ? warn('Tenjin could not finish setting up Claude Code')\n : s.plugin.state === 'deferred'\n ? warn('Tenjin keeps its earlier Claude Code setup until Claude Code is updated')\n : `${ok} Tenjin is set up for Claude Code (plugin ${s.plugin.id ?? PLUGIN_ID})`,\n ...(s.plugin.scope === 'local' && s.plugin.state !== 'failed'\n ? [' For this project only; check it with: tenjin doctor --project']\n : []),\n ...runtimeLines(ctx, s.rt, s.home),\n ...walletLines(ctx, ok, s.wallet),\n ...spend,\n ...(s.fund !== undefined ? fundLines(s.fund) : []),\n ...pluginLines(ctx, s.plugin),\n ...claudeLines(ctx, s.claude),\n ...migrationLines(ctx, s.migration),\n ...router,\n '',\n `Next: ${nextStep(s.plugin, s.claude, s.wallet, s.migration, s.asks, ctx.io.isTTY)}`,\n ];\n}\n\n/** \"Up to date\" only when nothing below it needs the user. */\nfunction refreshLines(\n ctx: CommandContext,\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n migration: Migration,\n rt: RuntimeSetup | null,\n home: string,\n): string[] {\n const issues = [\n ...runtimeLines(ctx, rt, home),\n ...pluginLines(ctx, plugin),\n ...claudeLines(ctx, claude),\n ...migrationLines(ctx, migration),\n ];\n const head =\n plugin.state === 'failed'\n ? paint(ctx.io, 'yellow', '! Tenjin is updated, but its plugin was not registered')\n : plugin.state === 'deferred'\n ? paint(ctx.io, 'yellow', '! Tenjin is updated; its plugin waits for a newer Claude Code')\n : `${paint(ctx.io, 'green', '✓')} Tenjin is up to date (plugin ${plugin.id ?? PLUGIN_ID})`;\n return [head, ...issues];\n}\n","import { lstatSync } from 'node:fs';\nimport { readdir, rm, rmdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport {\n CLI_SKILL_NAMES,\n readSkillFile,\n skillFrontmatterName,\n skillsDirsFor,\n} from './skill-wiring';\nimport { RETIRED_SKILL_NAMES, SHIPPED_SKILL_FILES } from './skills-source';\nimport { hasCode } from './errno';\n\nfunction isRealDirectory(path: string): boolean {\n try {\n return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n } catch (err) {\n // Linux reports ENOTDIR when an ancestor is a regular file. Nothing can\n // be installed below it, just as with an absent path. Do not follow symlinks.\n if (hasCode(err, 'ENOENT') || hasCode(err, 'ENOTDIR')) return false;\n throw err;\n }\n}\n\n/**\n * Remove only the files our named skill shipped (SKILL.md last, as the ownership\n * proof), then any directory they leave empty; preserve foreign skills and\n * adjacent user files.\n */\nexport async function removeOwnedSkill(\n name: string,\n skillsDir: string,\n): Promise<{ changed: boolean }> {\n if (!isRealDirectory(skillsDir)) {\n return { changed: false };\n }\n const skillDir = join(skillsDir, name);\n if (!isRealDirectory(skillDir)) {\n return { changed: false };\n }\n const path = join(skillDir, 'SKILL.md');\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return { changed: false };\n if (read.kind !== 'ok' || skillFrontmatterName(read.bytes.toString('utf8')) !== name) {\n return { changed: false }; // not ours to delete for sitting at our path\n }\n const shipped = (SHIPPED_SKILL_FILES as Record<string, readonly string[]>)[name] ?? [];\n const subdirs = new Set<string>();\n for (const rel of shipped) {\n if (rel === 'SKILL.md') continue;\n const file = join(skillDir, rel);\n // A symlinked `references/` would route the delete outside the skill.\n if (!isRealDirectory(dirname(file))) continue;\n subdirs.add(dirname(file));\n if (lstatSync(file, { throwIfNoEntry: false })?.isFile() === true) await rm(file);\n }\n await rm(path, { force: true });\n for (const dir of [...subdirs, skillDir].sort((a, b) => b.length - a.length)) {\n const rest = await readdir(dir).catch(() => null);\n if (rest !== null && rest.length === 0) await rmdir(dir).catch(() => undefined);\n }\n return { changed: true };\n}\n\n/**\n * Refresh retires obsolete skills without needing their old packaged source:\n * the retired names, and the shelf's CLI skills, whose `tenjin search` and\n * `tenjin publish` commands the router CLI does not ship.\n */\nexport async function removeRetiredSkills(home: string, project?: string): Promise<string[]> {\n const removed: string[] = [];\n const dirs = [...skillsDirsFor(home), ...(project ? skillsDirsFor(project) : [])];\n for (const dir of new Set(dirs)) {\n for (const name of [...RETIRED_SKILL_NAMES, ...CLI_SKILL_NAMES]) {\n if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));\n }\n }\n return removed;\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { inspectHooksFile } from '../lib/harness-hooks';\nimport { runClaude, type ClaudeBinary } from './claude-cli';\nimport { LEGACY_HOOK_TOOL, LEGACY_MCP_SERVER_NAME, LEGACY_REQUEST_TOOL } from './names';\nimport { classifyStatusLine, decomposeCommand, type StatusLineState } from './status-line-wiring';\n\n/**\n * THE SETTINGS-BASED INSTALL, READ AND REMOVED. Releases up to alpha.26 wrote\n * seven hook entries, an allow and a deny rule and a status line into\n * settings.json, and registered an `x402` MCP server with `claude mcp add`.\n * The plugin replaces all of it. `install` and `update` remove it only once the\n * plugin has proven to load on this machine, `uninstall` removes it outright,\n * and doctor only reads it.\n *\n * EXACT SHAPES ONLY. A hook handler is Tenjin's when it is an `mcp_tool` call\n * to the `x402` server's `hook` tool, or a command that is exactly\n * `tenjin hook <leg>` (optionally with a path). Any other command that merely\n * contains `tenjin hook` is the user's, kept and reported. Removal is handler\n * by handler, so a group holding a foreign handler beside ours keeps it. The\n * rules are touched only when the `x402` server is Tenjin's or gone, and a\n * status line only in a file that still held Tenjin's hooks, and only in the\n * exact shapes Tenjin wrote. A file is written only when something was removed\n * from it, and no key is ever added to it.\n *\n * SHIM: this module goes on or after 2026-12-01, the first release cut 30 or\n * more days after the plugin PR 2 ships, and doctor keeps naming an\n * unmigrated machine after that.\n */\n\nconst LEGACY_COMMAND_RE = /^(\\S*\\/)?tenjin hook [a-z]+$/;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** One handler, in an exact shape a settings install wrote. */\nexport function ownsLegacyHandler(handler: unknown): boolean {\n if (!isPlainObject(handler)) return false;\n if (handler.type === 'mcp_tool') {\n return handler.server === LEGACY_MCP_SERVER_NAME && handler.tool === 'hook';\n }\n const command = handler.command;\n return typeof command === 'string' && LEGACY_COMMAND_RE.test(command.trim());\n}\n\n/** A handler that mentions `tenjin hook` without being one of ours: reported, never removed. */\nfunction lookalike(handler: unknown): string | null {\n if (!isPlainObject(handler) || ownsLegacyHandler(handler)) return null;\n const command = handler.command;\n return typeof command === 'string' && command.includes('tenjin hook') ? command : null;\n}\n\nexport type McpEntryState = 'ok' | 'absent' | 'wrong-command' | 'unreadable';\n\n/**\n * What an entry named `x402` actually launches. The name proves nothing: a\n * stale entry pointing at another binary would read as a working request tool.\n */\nexport function classifyMcpEntry(entry: unknown): McpEntryState {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return 'absent';\n const { command, args } = entry as { command?: unknown; args?: unknown };\n if (typeof command !== 'string' || command.length === 0) return 'wrong-command';\n // The basename, so `/opt/homebrew/bin/tenjin` and a bare `tenjin` both pass.\n const binary = command.split(/[\\\\/]/).pop();\n const runsRouter =\n binary === 'tenjin' && Array.isArray(args) && args.length === 1 && args[0] === 'mcp';\n return runsRouter ? 'ok' : 'wrong-command';\n}\n\n/**\n * The `x402` entry in one registration file: `~/.claude.json` (or the one in\n * `CLAUDE_CONFIG_DIR`) for user scope, `<project>/.mcp.json` for project scope.\n * Only \"it is not there\" is an absence: a file that exists and cannot be read\n * or parsed says nothing about what is registered in it.\n */\nexport async function readLegacyMcpEntry(path: string): Promise<McpEntryState> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n return code === 'ENOENT' || code === 'ENOTDIR' ? 'absent' : 'unreadable';\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return 'unreadable';\n }\n const servers = (parsed as { mcpServers?: unknown } | null)?.mcpServers;\n if (servers === undefined) return 'absent';\n if (!isPlainObject(servers)) return 'unreadable';\n const entry = servers[LEGACY_MCP_SERVER_NAME];\n return entry === undefined ? 'absent' : classifyMcpEntry(entry);\n}\n\nexport interface LegacyInstall {\n settingsPath: string;\n /** The registration file the `x402` entry would be in. */\n mcpFile: string;\n /** Anything of the settings install left on this machine. */\n present: boolean;\n /** The events holding a handler of ours. */\n events: string[];\n allowRule: boolean;\n denyRule: boolean;\n statusLine: StatusLineState;\n mcp: McpEntryState;\n /** Commands that mention `tenjin hook` but are not ours, left in place. */\n lookalikes: string[];\n /** Set when the settings file could not be read; nothing is then known or removed. */\n unreadable?: string;\n}\n\n/** What the settings install left in one scope. Reads only. */\nexport async function inspectLegacyInstall(\n settingsPath: string,\n mcpFile: string,\n): Promise<LegacyInstall> {\n const mcp = await readLegacyMcpEntry(mcpFile);\n const base = {\n settingsPath,\n mcpFile,\n events: [] as string[],\n allowRule: false,\n denyRule: false,\n statusLine: 'absent' as StatusLineState,\n mcp,\n lookalikes: [] as string[],\n };\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { ...base, present: mcp === 'ok', unreadable: found.refusal.message };\n }\n const events = Object.entries(found.hooks)\n .filter(([, list]) => list.some((entry) => handlersOf(entry).some(ownsLegacyHandler)))\n .map(([event]) => event);\n const lookalikes = Object.values(found.hooks).flatMap((list) =>\n list.flatMap((entry) =>\n handlersOf(entry)\n .map(lookalike)\n .filter((c) => c !== null),\n ),\n );\n const rulesOurs = mcp === 'ok' || (mcp === 'absent' && events.length > 0);\n const allowRule = rulesOurs && listOf(found.settings, 'allow').includes(LEGACY_REQUEST_TOOL);\n const denyRule = rulesOurs && listOf(found.settings, 'deny').includes(LEGACY_HOOK_TOOL);\n const statusLine = events.length > 0 ? classifyStatusLine(found.settings.statusLine) : 'absent';\n const statusOurs = statusLine === 'ours' || statusLine === 'composed';\n return {\n ...base,\n present: events.length > 0 || allowRule || denyRule || statusOurs || mcp === 'ok',\n events,\n allowRule,\n denyRule,\n statusLine,\n lookalikes,\n };\n}\n\nfunction handlersOf(entry: unknown): unknown[] {\n return isPlainObject(entry) && Array.isArray(entry.hooks) ? entry.hooks : [];\n}\n\nfunction listOf(settings: Record<string, unknown>, key: 'allow' | 'deny'): unknown[] {\n const permissions = settings.permissions;\n if (!isPlainObject(permissions)) return [];\n const list = permissions[key];\n return Array.isArray(list) ? list : [];\n}\n\nexport interface LegacyRemoval {\n /** The events a handler of ours was taken out of. */\n events: string[];\n allowRule: boolean;\n denyRule: boolean;\n /** `removed` (ours alone), `restored` (the user's own command put back), or untouched. */\n statusLine: 'removed' | 'restored' | 'kept';\n /** The `x402` registration: removed, not there, or kept with the reason. */\n mcp: 'removed' | 'absent' | 'kept';\n wroteSettings: boolean;\n warnings: string[];\n}\n\nexport interface RemoveLegacyOptions {\n binary: ClaudeBinary | null;\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** The `claude mcp` scope the `x402` entry was registered at. */\n mcpScope: 'user' | 'project';\n}\n\n/** Take out what {@link inspectLegacyInstall} found, under the exact-shape rules above. */\nexport async function removeLegacyInstall(\n found: LegacyInstall,\n opts: RemoveLegacyOptions,\n): Promise<LegacyRemoval> {\n const out: LegacyRemoval = {\n events: [],\n allowRule: false,\n denyRule: false,\n statusLine: 'kept',\n mcp: found.mcp === 'absent' ? 'absent' : 'kept',\n wroteSettings: false,\n warnings: [],\n };\n if (found.unreadable === undefined) await removeFromSettings(found, out);\n else out.warnings.push(found.unreadable);\n if (found.mcp === 'ok') await removeMcpEntry(opts, out);\n else if (found.mcp === 'wrong-command') {\n out.warnings.push(\n `an MCP server named ${LEGACY_MCP_SERVER_NAME} launches something else, so it is not Tenjin's and was left in place`,\n );\n } else if (found.mcp === 'unreadable') {\n out.warnings.push(`${found.mcpFile} could not be read, so nothing was removed from it`);\n }\n return out;\n}\n\nasync function removeFromSettings(found: LegacyInstall, out: LegacyRemoval): Promise<void> {\n const read = await inspectHooksFile(found.settingsPath);\n if ('refusal' in read) {\n out.warnings.push(read.refusal.message);\n return;\n }\n if (read.raw === null) return;\n const next: Record<string, unknown> = { ...read.settings };\n if (isPlainObject(read.settings.hooks)) {\n const hooks: Record<string, unknown> = {};\n for (const [event, list] of Object.entries(read.hooks)) {\n const kept: unknown[] = [];\n for (const entry of list) {\n const handlers = handlersOf(entry);\n const left = handlers.filter((h) => !ownsLegacyHandler(h));\n if (left.length === handlers.length) kept.push(entry);\n else if (left.length > 0) kept.push({ ...(entry as Record<string, unknown>), hooks: left });\n }\n if (kept.length !== list.length || kept.some((e, i) => e !== list[i])) out.events.push(event);\n // An event WE emptied loses its key; one that was already empty stays.\n if (kept.length > 0 || list.length === 0) hooks[event] = kept;\n }\n next.hooks = hooks;\n }\n if ((found.allowRule || found.denyRule) && isPlainObject(read.settings.permissions)) {\n const permissions = { ...read.settings.permissions };\n if (found.allowRule && Array.isArray(permissions.allow)) {\n permissions.allow = permissions.allow.filter((r) => r !== LEGACY_REQUEST_TOOL);\n out.allowRule = true;\n }\n if (found.denyRule && Array.isArray(permissions.deny)) {\n permissions.deny = permissions.deny.filter((r) => r !== LEGACY_HOOK_TOOL);\n out.denyRule = true;\n }\n next.permissions = permissions;\n }\n if (found.statusLine === 'ours') {\n delete next.statusLine;\n out.statusLine = 'removed';\n } else if (found.statusLine === 'composed' && isPlainObject(read.settings.statusLine)) {\n const command = read.settings.statusLine.command;\n const original = typeof command === 'string' ? decomposeCommand(command) : null;\n if (original !== null) {\n next.statusLine = { ...read.settings.statusLine, command: original };\n out.statusLine = 'restored';\n }\n }\n // Only a removal writes: a file holding nothing of ours keeps its bytes,\n // whatever its formatting.\n const removed =\n out.events.length > 0 || out.allowRule || out.denyRule || out.statusLine !== 'kept';\n if (!removed) return;\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n const mode = await stat(read.path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n // Compared again just before the rename: a concurrent edit is refused, not lost.\n if ((await readFile(read.path, 'utf8').catch(() => null)) !== read.raw) {\n out.warnings.push(`${read.path} changed while it was read, so it was left as it is`);\n Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: 'kept' });\n return;\n }\n try {\n await writeFileAtomic(read.path, body, mode);\n out.wroteSettings = true;\n } catch (err) {\n out.warnings.push(err instanceof Error ? err.message : String(err));\n Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: 'kept' });\n }\n}\n\n/**\n * THE `x402` REGISTRATION GOES THROUGH CLAUDE'S OWN COMMAND, and only after\n * this CLI's own read of that file found it launching `tenjin mcp`: a server\n * the read did not find is never removed by name, because another tool may\n * own one called `x402`. With no binary it is left and reported; the plugin's\n * server is namespaced and does not collide with it.\n */\nasync function removeMcpEntry(opts: RemoveLegacyOptions, out: LegacyRemoval): Promise<void> {\n if (opts.binary === null) {\n out.warnings.push(\n `the ${LEGACY_MCP_SERVER_NAME} MCP registration stays until a run with the claude binary removes it`,\n );\n return;\n }\n const run = await runClaude(\n opts.binary,\n ['mcp', 'remove', LEGACY_MCP_SERVER_NAME, '-s', opts.mcpScope],\n { env: opts.env, cwd: opts.cwd },\n );\n if (run.code === 0) out.mcp = 'removed';\n else {\n out.warnings.push(\n `claude mcp remove ${LEGACY_MCP_SERVER_NAME} did not succeed: ${(run.stderr || run.stdout).trim().slice(0, 200) || 'no output'}`,\n );\n }\n}\n\n/** The project-scope registration file. */\nexport function projectMcpFile(cwd: string): string {\n return join(cwd, '.mcp.json');\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { CliError } from '../lib/errors';\nimport { inspectHooksFile } from '../lib/harness-hooks';\n\n/**\n * The `statusLine` key in Claude Code's settings file. `install` no longer\n * sets it (a plugin cannot), so the router reads this module only to recognise\n * and take back a status line an earlier release wrote (`legacy-install.ts`).\n * The writer below stays for the shelf code that still imports it.\n *\n * The one setting the live footer needs, and the one piece of harness\n * configuration a person is most likely to have already set for themselves.\n *\n * SO IT IS NEVER REPLACED. An existing status line that is not ours is left\n * exactly as it is, and `install` prints the composition line instead;\n * `--status-line compose` writes that line only because it was asked for by\n * name. Writing over it and saying so in the output destroys a configuration\n * this CLI did not create.\n *\n * OWNERSHIP IS ONE MARKER, the command naming `tenjin status-line`, used by\n * `install`, `install --refresh`, `uninstall` and `doctor` alike, so the four\n * can never disagree about which status line is Tenjin's.\n */\n\n/** The command `install` registers, in the shape the hook entries use: a plain\n * command line on PATH, with no path into this build's dist directory. */\nexport const STATUS_LINE_COMMAND = 'tenjin status-line';\n/** Claude Code re-runs the command on this interval, in seconds. */\nexport const STATUS_LINE_REFRESH_SECONDS = 1;\n/** The marker that makes a status line ours, composed or not. */\nconst OUR_MARKER = STATUS_LINE_COMMAND;\n\n/** What the user asked for, when they asked. Absent means the default path. */\nexport type StatusLineMode = 'own' | 'compose' | 'skip';\n\nconst MODES: readonly StatusLineMode[] = ['own', 'compose', 'skip'];\n\n/** `--status-line <mode>`, refused rather than guessed at. */\nexport function statusLineMode(value: string): StatusLineMode {\n const mode = MODES.find((known) => known === value);\n if (mode === undefined) {\n throw new CliError('USAGE', `--status-line takes ${MODES.join(', ')}, not \"${value}\".`, {\n fix: 'Run `tenjin install --status-line own`.',\n });\n }\n return mode;\n}\n\n/**\n * What is in the file: ours alone, ours appended to someone else's, someone\n * else's alone, or nothing.\n */\nexport type StatusLineState = 'ours' | 'composed' | 'foreign' | 'absent';\n\nexport interface StatusLineResult {\n path: string;\n state: StatusLineState;\n /** True when this run changed the file. */\n wrote: boolean;\n /** The command now registered, when one of ours is. */\n command?: string;\n /** The exact command to set by hand, printed when a foreign line is kept. */\n compose?: string;\n /** Why nothing was written, for a file this run would not touch. */\n warning?: string;\n}\n\nexport function classifyStatusLine(value: unknown): StatusLineState {\n if (value === null || value === undefined) return 'absent';\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n // A status line whose command this build cannot read is still the user's.\n if (typeof command !== 'string' || command.trim().length === 0) return 'foreign';\n if (command.trim() === OUR_MARKER) return 'ours';\n return command.includes(OUR_MARKER) ? 'composed' : 'foreign';\n}\n\nfunction ours(): Record<string, unknown> {\n return {\n type: 'command',\n command: STATUS_LINE_COMMAND,\n refreshInterval: STATUS_LINE_REFRESH_SECONDS,\n };\n}\n\nconst shQuote = (value: string): string => `'${value.replaceAll(\"'\", String.raw`'\\''`)}'`;\nconst shUnquote = (value: string): string => value.replaceAll(String.raw`'\\''`, \"'\");\n\n/** The inner script, with the user's own command as the one hole in it. */\nfunction composedScript(existing: string): string {\n return [\n 'event=$(cat)',\n `yours=$(printf %s \"$event\" | ${existing})`,\n `tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND})`,\n 'printf %s \"$yours${tenjin:+ · $tenjin}\"',\n ].join('; ');\n}\n\n/**\n * The command a composition was built from, or null when this is not a\n * composition this build wrote. It is the exact inverse of\n * {@link composeCommand}: a hand-edited line matches nothing and is kept whole,\n * because guessing at someone's shell is how an uninstall breaks a prompt.\n */\nexport function decomposeCommand(command: string): string | null {\n const trimmed = command.trim();\n if (!trimmed.startsWith(\"sh -c '\") || !trimmed.endsWith(\"'\")) return null;\n const script = shUnquote(trimmed.slice(\"sh -c '\".length, -1));\n const prefix = 'event=$(cat); yours=$(printf %s \"$event\" | ';\n if (!script.startsWith(prefix)) return null;\n const rest = script.slice(prefix.length);\n const suffix = `); tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND}); printf %s \"$yours\\${tenjin:+ · $tenjin}\"`;\n if (!rest.endsWith(suffix)) return null;\n const existing = rest.slice(0, -suffix.length);\n return existing.length > 0 && composedScript(existing) === script ? existing : null;\n}\n\n/**\n * The user's status line with ours appended after a separator, on one line.\n *\n * The harness writes its event on stdin ONCE, so a composition cannot simply\n * run two commands in sequence: the event is captured first and replayed into\n * each. Ours contributes nothing when this session has no activity, and the\n * separator goes with it, so a quiet session looks exactly as it did before.\n */\nexport function composeCommand(existing: string): string {\n return `sh -c ${shQuote(composedScript(existing))}`;\n}\n\n/** The command a status-line setting runs, in either shape it can take. */\nfunction commandOf(value: unknown): string | undefined {\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n return typeof command === 'string' && command.trim().length > 0 ? command.trim() : undefined;\n}\n\n/** What a foreign status line's owner is told to set, verbatim. */\nfunction composeFor(value: unknown): string | undefined {\n const command = commandOf(value);\n return command === undefined ? undefined : composeCommand(command);\n}\n\nexport interface EnsureStatusLineOpts {\n mode?: StatusLineMode;\n /**\n * `install --refresh` and the refresh `tenjin update` spawns: converge a\n * status line of ours that is already registered, and ADD NOTHING. A machine\n * whose owner removed ours, or never had it, keeps that answer across every\n * upgrade without a second place to record it.\n */\n refreshOnly?: boolean;\n}\n\nexport async function ensureStatusLine(\n settingsPath: string,\n opts: EnsureStatusLineOpts = {},\n): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (opts.mode === 'skip') {\n return { path, state, wrote: false, ...(state === 'foreign' ? kept(current) : {}) };\n }\n if (opts.mode === 'compose') {\n const composed = composeFor(current);\n if (composed === undefined) return writeStatusLine(found, ours(), 'ours');\n // THEIR OBJECT, with the command swapped. Rebuilding it from ours would\n // drop whatever else they had set on it, such as their own padding.\n const base =\n typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as Record<string, unknown>)\n : ours();\n return state === 'composed'\n ? { path, state, wrote: false, command: composed }\n : writeStatusLine(found, { ...base, command: composed }, 'composed');\n }\n if (state === 'foreign') {\n // NOT REPLACED, AND NOT WRITTEN AROUND. The user keeps what they set, and\n // gets the one command that adds ours to it.\n return { path, state, wrote: false, ...kept(current) };\n }\n if (state === 'composed') return { path, state, wrote: false };\n if (state === 'absent' && opts.refreshOnly === true) {\n return { path, state, wrote: false };\n }\n return writeStatusLine(found, ours(), 'ours');\n}\n\n/** `uninstall`: take out a status line of OURS, and only if it is ours alone. */\nexport async function removeStatusLine(settingsPath: string): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (state === 'ours') return writeStatusLine(found, undefined, 'absent');\n // A COMPOSED LINE IS MOSTLY THE USER'S TEXT, so it is not deleted: the half\n // this build wrote is unwound and their own command is put back exactly as it\n // was. A composition that was hand-edited since inverts to nothing and is\n // left whole, because guessing at someone's shell is the worse failure.\n if (state === 'composed') {\n const command = commandOf(current);\n const original = command === undefined ? null : decomposeCommand(command);\n if (original === null) return { path, state, wrote: false };\n const kept = { ...(current as Record<string, unknown>), command: original };\n return writeStatusLine(found, kept, 'foreign');\n }\n return { path, state, wrote: false };\n}\n\n/** What `doctor` reports, without writing anything. */\nexport async function inspectStatusLine(\n settingsPath: string,\n): Promise<{ path: string; state: StatusLineState; warning?: string }> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', warning: found.refusal.reason };\n }\n return { path: found.path, state: classifyStatusLine(found.settings.statusLine) };\n}\n\nfunction kept(current: unknown): { compose?: string } {\n const compose = composeFor(current);\n return compose === undefined ? {} : { compose };\n}\n\ntype Inspection = { path: string; raw: string | null; settings: Record<string, unknown> };\n\n/**\n * One key, written through the same read-compare-write the hooks writer uses:\n * every other key is copied through in its original order, the bytes are\n * re-read before the rename so a concurrent edit is refused rather than lost,\n * and the file keeps its mode.\n */\nasync function writeStatusLine(\n found: Inspection,\n value: Record<string, unknown> | undefined,\n state: StatusLineState,\n): Promise<StatusLineResult> {\n const { path, raw, settings } = found;\n const next: Record<string, unknown> = { ...settings };\n if (value === undefined) delete next.statusLine;\n else next.statusLine = value;\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n const result: StatusLineResult = {\n path,\n state,\n wrote: false,\n ...(typeof value?.command === 'string' ? { command: value.command } : {}),\n };\n if (body === raw) return result;\n const mode = await stat(path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n if (raw !== null && (await readFile(path, 'utf8').catch(() => null)) !== raw) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: 'changed-since-read',\n };\n }\n try {\n await writeFileAtomic(path, body, mode);\n } catch (err) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: err instanceof Error ? err.message : String(err),\n };\n }\n return { ...result, wrote: true };\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { versionFreeEntry } from '../commands/update';\nimport { hasCode } from '../lib/errno';\nimport {\n claudeConfigDir,\n jsonList,\n jsonResult,\n runClaude,\n type ClaudeBinary,\n type ClaudeRun,\n} from './claude-cli';\nimport { MARKETPLACE_NAME, PLUGIN_ID, PLUGIN_NAME, SKILLS_DIR_PLUGIN_ID } from './names';\nimport { PLUGIN_DIR, renderPluginFiles, type ModSources } from './plugin-files';\nimport {\n inspectPluginFolder,\n pluginFolderPath,\n readModSources,\n removePluginFolder,\n writePluginFolder,\n type FolderRemoval,\n} from './plugin-folder';\n\n/**\n * REGISTERING THE PLUGIN, WITH NO STEP LEFT TO THE PERSON. With a `claude`\n * binary (on PATH, or the one Claude Code names in `CLAUDE_CODE_EXECPATH`):\n *\n * claude plugin marketplace add <marketplace folder> --json\n * claude plugin install tenjin@tenjin --scope <scope> --json\n * claude plugin update tenjin@tenjin --scope <scope> --json (only when the version moved)\n *\n * The marketplace folder is Tenjin's runtime, `~/.tenjin/runtime/claude`, or,\n * where there is no runtime, the installed package's `dist/hosts/claude`. It is\n * a `directory` source Claude Code reads in place, so there is no git or\n * network step, the plugin is the CLI's own build, and an activation that\n * re-renders the runtime folder takes effect at the next session with no\n * command at all. Each command is non-interactive, idempotent and answers one JSON line\n * (lab, Claude Code 2.1.296): a second `add` of the same folder is a no-op, an\n * `add` of a moved folder repoints the marketplace, and `install` of an\n * installed plugin reports both versions. No binary, or a command that fails:\n * the plugin is written as a folder under the config dir's `skills/`, which\n * Claude Code loads with no command at all.\n */\n\nexport type PluginScope = 'user' | 'local';\n\nexport interface RegistrationStep {\n command: string;\n ok: boolean;\n detail?: string;\n}\n\nexport interface PluginRegistration {\n /** `plugin` through Claude's commands, `skills-dir` as a folder, `none` when neither worked. */\n method: 'plugin' | 'skills-dir' | 'none';\n /** The id Claude Code lists it under. */\n id: string | null;\n scope: PluginScope;\n /**\n * `installed` (new), `updated` (the version moved), `current` (already this\n * build), `written` (the folder), `deferred` (left for a newer Claude Code,\n * with a settings install still routing), or `failed` (nothing registered).\n */\n state: 'installed' | 'updated' | 'current' | 'written' | 'deferred' | 'failed';\n /** The marketplace folder or the plugin folder. */\n path?: string;\n version: string;\n steps: RegistrationStep[];\n /** Why the folder was written instead of running the commands. */\n fallbackReason?: string;\n /** Why nothing was registered. */\n reason?: string;\n /** A folder an earlier fallback wrote, removed because the commands now registered the plugin. */\n supersededFolder?: FolderRemoval;\n}\n\nexport interface RegisterOptions {\n binary: ClaudeBinary | null;\n scope: PluginScope;\n /** The CLI version the plugin files carry. */\n version: string;\n env: NodeJS.ProcessEnv;\n home: string;\n cwd: string;\n /** The marketplace folder; defaults to this package's `dist/hosts/claude`. */\n hostsDir?: string | null;\n /** The CLI entry the folder fallback's commands run. Defaults to this package's `dist/index.js`. */\n cliEntry?: string;\n /** The Node the folder fallback's commands run: the runtime's, or `node` from PATH when unset. */\n node?: string;\n}\n\n/** Where the folder fallback lives for this scope. */\nexport function folderFor(scope: PluginScope, env: NodeJS.ProcessEnv, home: string, cwd: string) {\n return pluginFolderPath(scope === 'local' ? join(cwd, '.claude') : claudeConfigDir(env, home));\n}\n\nexport async function registerPlugin(opts: RegisterOptions): Promise<PluginRegistration> {\n const folder = folderFor(opts.scope, opts.env, opts.home, opts.cwd);\n const steps: RegistrationStep[] = [];\n let fallbackReason: string;\n if (opts.binary !== null) {\n const hosts = opts.hostsDir === undefined ? await packageHostsDir() : opts.hostsDir;\n if (hosts === null) {\n fallbackReason = 'this build carries no plugin marketplace folder (dist/hosts/claude)';\n } else {\n const done = await viaPluginCommands(opts.binary, hosts, opts, steps);\n if (done.ok) {\n // A folder an earlier fallback wrote would load as a second copy.\n const superseded = await removePluginFolder(folder);\n return {\n method: 'plugin',\n id: PLUGIN_ID,\n scope: opts.scope,\n state: done.state,\n path: hosts,\n version: opts.version,\n steps,\n ...(superseded.removed ? { supersededFolder: superseded } : {}),\n };\n }\n fallbackReason = done.reason;\n }\n // NO SECOND COPY. A plugin Claude Code already has (an earlier install\n // whose update just failed, or a `tenjin` from another marketplace) would\n // load beside the folder, and every event would run both sets of legs and\n // pay twice. It is left as it is, and the run reports the failure.\n const existing = await existingCopy(opts.binary, opts.env, opts.home, opts.cwd);\n if (existing !== null) {\n return {\n method: 'none',\n id: existing,\n scope: opts.scope,\n state: 'failed',\n version: opts.version,\n steps,\n reason: `${fallbackReason}; ${existing} is already in Claude Code and was left as it is, so no second copy was written`,\n };\n }\n } else {\n fallbackReason = 'no claude binary on PATH or in CLAUDE_CODE_EXECPATH';\n // A plugin Claude's commands registered earlier must not get a second copy.\n if (await installedThroughCommands(opts.env, opts.home)) {\n return {\n method: 'plugin',\n id: PLUGIN_ID,\n scope: opts.scope,\n state: 'current',\n version: opts.version,\n steps,\n fallbackReason: `${fallbackReason}; ${PLUGIN_ID} is already registered, so it was left as it is`,\n };\n }\n }\n const written = await writePluginFolder(\n folder,\n renderPluginFiles(opts.version, opts.cliEntry ?? packageCliEntry(), {\n node: opts.node,\n mod: await packageMod(opts.hostsDir),\n }),\n );\n if (written.state === 'written') {\n return {\n method: 'skills-dir',\n id: SKILLS_DIR_PLUGIN_ID,\n scope: opts.scope,\n state: 'written',\n path: folder,\n version: opts.version,\n steps,\n fallbackReason,\n };\n }\n return {\n method: 'none',\n id: null,\n scope: opts.scope,\n state: 'failed',\n path: folder,\n version: opts.version,\n steps,\n fallbackReason,\n reason: written.reason ?? 'the plugin folder could not be written',\n };\n}\n\ntype CommandsOutcome =\n { ok: true; state: 'installed' | 'updated' | 'current' } | { ok: false; reason: string };\n\nasync function viaPluginCommands(\n binary: ClaudeBinary,\n hosts: string,\n opts: RegisterOptions,\n steps: RegistrationStep[],\n): Promise<CommandsOutcome> {\n const run = (args: string[]) => runClaude(binary, args, { env: opts.env, cwd: opts.cwd });\n const scopeArgs = ['--scope', opts.scope];\n // The marketplace is declared at user scope by default, the form every\n // release since 2.1.287 takes; only a project install names its scope.\n const marketplaceScope = opts.scope === 'user' ? [] : scopeArgs;\n\n // A marketplace called `tenjin` that is not this package's is somebody\n // else's, and `add` would repoint it: it is left alone. So is every\n // marketplace when the list cannot be read, because an unread list cannot\n // prove there is no such marketplace to repoint.\n const known = await run(['plugin', 'marketplace', 'list', '--json']);\n const listed = known.code === 0 ? jsonList(known.stdout) : null;\n steps.push({\n command: 'claude plugin marketplace list --json',\n ok: listed !== null,\n ...(listed === null ? { detail: commandDetail(known) } : {}),\n });\n if (listed === null) {\n return {\n ok: false,\n reason: `claude plugin marketplace list could not be read (${commandDetail(known)}), so no marketplace was added or repointed`,\n };\n }\n const existing = listed.find((m) => m.name === MARKETPLACE_NAME);\n if (existing !== undefined && !(await ownMarketplace(existing))) {\n return {\n ok: false,\n reason: `a marketplace named ${MARKETPLACE_NAME} that this CLI did not add is already configured, so it was left as it is`,\n };\n }\n\n const add = await step(\n steps,\n ['plugin', 'marketplace', 'add', hosts, '--json', ...marketplaceScope],\n run,\n );\n if (!add.ok) return { ok: false, reason: `claude plugin marketplace add failed: ${add.detail}` };\n const install = await step(steps, ['plugin', 'install', PLUGIN_ID, ...scopeArgs, '--json'], run);\n if (!install.ok) return { ok: false, reason: `claude plugin install failed: ${install.detail}` };\n const installed = install.result?.installedVersion;\n const available = install.result?.availableVersion;\n if (typeof installed !== 'string' || typeof available !== 'string') {\n return { ok: true, state: 'installed' };\n }\n if (installed === available) return { ok: true, state: 'current' };\n const update = await step(steps, ['plugin', 'update', PLUGIN_ID, ...scopeArgs, '--json'], run);\n if (!update.ok) return { ok: false, reason: `claude plugin update failed: ${update.detail}` };\n return { ok: true, state: 'updated' };\n}\n\n/**\n * Did this registration's `claude plugin marketplace add <hosts>` succeed?\n * Then Claude Code's one global `tenjin` row names `hosts` now, whatever\n * failed after it, and loads the plugin from there in place.\n */\nexport function marketplaceAdded(reg: PluginRegistration, hosts: string): boolean {\n const add = `claude plugin marketplace add ${hosts} `;\n return reg.steps.some((s) => s.ok && s.command.startsWith(add));\n}\n\nasync function step(\n steps: RegistrationStep[],\n args: string[],\n run: (args: string[]) => Promise<ClaudeRun>,\n): Promise<{ ok: boolean; detail: string; result: Record<string, unknown> | null }> {\n const out = await run(args);\n const result = jsonResult(out.stdout);\n const ok =\n out.code === 0 && (result === null || result.outcome === undefined || result.outcome === 'ok');\n const detail = commandDetail(out, result);\n steps.push({ command: `claude ${args.join(' ')}`, ok, ...(ok ? {} : { detail }) });\n return { ok, detail, result };\n}\n\n/** What a failed command said: its JSON message, else its output, else how it ended. */\nfunction commandDetail(out: ClaudeRun, result: Record<string, unknown> | null = null): string {\n if (typeof result?.message === 'string') return result.message;\n const text = (out.stderr || out.stdout).trim().slice(0, 300);\n if (text.length > 0) return text;\n return out.code === null ? 'the command could not be run' : `exit ${out.code}`;\n}\n\n/**\n * Is this marketplace one `install` added? A directory source whose plugin\n * folder carries the `tenjin-cli` marker in its manifest, or, when that folder\n * is gone (a package manager removed the old version's directory, or the\n * runtime was removed), one whose path is a `tenjin-cli` package's\n * `dist/hosts/claude` or Tenjin's `runtime/claude`.\n */\nexport async function ownMarketplace(row: Record<string, unknown>): Promise<boolean> {\n const path = typeof row.path === 'string' ? row.path : undefined;\n if (row.source !== 'directory' || path === undefined) return false;\n if ((await stat(path).catch(() => null)) === null) {\n return (\n /tenjin-cli[\\\\/]dist[\\\\/]hosts[\\\\/]claude$/.test(path) ||\n /[\\\\/]runtime[\\\\/]claude$/.test(path)\n );\n }\n return (await inspectPluginFolder(join(path, PLUGIN_DIR))) === 'ours';\n}\n\n/**\n * A `tenjin` plugin Claude Code already holds that a folder would duplicate:\n * any enabled `tenjin@<marketplace>`. The folder's own `tenjin@skills-dir` is\n * not a duplicate, since writing the folder updates it in place. When the list\n * cannot be read, Claude Code's own record of installed plugins answers.\n */\nasync function existingCopy(\n binary: ClaudeBinary,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<string | null> {\n const out = await runClaude(binary, ['plugin', 'list', '--json'], { env, cwd });\n const listed = out.code === 0 ? jsonList(out.stdout) : null;\n if (listed === null) return (await installedThroughCommands(env, home)) ? PLUGIN_ID : null;\n const row = listed.find(\n (p) =>\n typeof p.id === 'string' &&\n p.id.startsWith(`${PLUGIN_NAME}@`) &&\n p.id !== SKILLS_DIR_PLUGIN_ID &&\n p.enabled === true,\n );\n return typeof row?.id === 'string' ? row.id : null;\n}\n\n/** One `tenjin@tenjin` install in Claude Code's own record. */\nexport interface InstallRecord {\n scope: 'user' | 'local';\n /** The folder a `local` install ran in (not the git root); null for `user`. */\n projectPath: string | null;\n}\n\n/**\n * EVERY `tenjin@tenjin` INSTALL CLAUDE CODE RECORDS, in any scope or project,\n * from `plugins/installed_plugins.json` (`{version: 2, plugins: {\"tenjin@tenjin\":\n * [entry, …]}}`). `[]` when the file is absent, null when it is there but cannot\n * be read. Keys are read by name, since their order varies, and `installPath`\n * and `version` never: both go stale once the marketplace is repointed.\n */\nexport async function recordedInstalls(\n env: NodeJS.ProcessEnv,\n home: string,\n): Promise<InstallRecord[] | null> {\n let raw: string;\n try {\n raw = await readFile(\n join(claudeConfigDir(env, home), 'plugins', 'installed_plugins.json'),\n 'utf8',\n );\n } catch (err) {\n return hasCode(err, 'ENOENT') ? [] : null;\n }\n let plugins: unknown;\n try {\n plugins = (JSON.parse(raw) as { plugins?: unknown }).plugins;\n } catch {\n return null;\n }\n if (typeof plugins !== 'object' || plugins === null || Array.isArray(plugins)) return null;\n const entries = (plugins as Record<string, unknown>)[PLUGIN_ID];\n if (!Array.isArray(entries)) return [];\n const records: InstallRecord[] = [];\n for (const entry of entries) {\n if (typeof entry !== 'object' || entry === null) continue;\n const { scope, projectPath } = entry as { scope?: unknown; projectPath?: unknown };\n if (scope === 'user') records.push({ scope, projectPath: null });\n else if (scope === 'local' && typeof projectPath === 'string' && projectPath.length > 0) {\n records.push({ scope, projectPath });\n }\n }\n return records;\n}\n\n/** Claude Code's own record of installed plugins, read when no binary can be asked. */\nasync function installedThroughCommands(env: NodeJS.ProcessEnv, home: string): Promise<boolean> {\n try {\n const raw = await readFile(\n join(claudeConfigDir(env, home), 'plugins', 'installed_plugins.json'),\n 'utf8',\n );\n const plugins = (JSON.parse(raw) as { plugins?: unknown }).plugins;\n return plugins !== null && typeof plugins === 'object' && PLUGIN_ID in plugins;\n } catch {\n return false;\n }\n}\n\n/**\n * THIS PACKAGE'S MARKETPLACE FOLDER, `dist/hosts/claude`, beside the bundle\n * that is running. Under pnpm the running path pins a version\n * (`.pnpm/tenjin-cli@<v>/...`), and a marketplace registered there would point\n * at a directory the next upgrade deletes, so the version-free path beside the\n * store is used when it exists, as `tenjin update` does for its re-exec.\n */\nexport async function packageHostsDir(\n moduleDir: string = dirname(fileURLToPath(import.meta.url)),\n): Promise<string | null> {\n const catalog = join(moduleDir, 'hosts', 'claude', '.claude-plugin', 'marketplace.json');\n const stable = versionFreeEntry(catalog) ?? catalog;\n if ((await stat(stable).catch(() => null))?.isFile() !== true) return null;\n return dirname(dirname(stable));\n}\n\n/**\n * THE MOD'S SOURCES, ONE LOOKUP FOR EVERY PLUGIN FOLDER THIS MODULE WRITES.\n * The mod ships as written in the package's own plugin folder\n * (`dist/hosts/claude/tenjin`, or `hostsDir`'s), and a render carries it only\n * when it is passed in: a plugin folder rendered anywhere else (the folder\n * fallback here, or a marketplace folder rendered under the data dir) takes\n * this result, or it ships without the mod. Undefined when the folder carries\n * no mod or there is no package folder.\n */\nexport async function packageMod(hostsDir?: string | null): Promise<ModSources | undefined> {\n const hosts = hostsDir === undefined ? await packageHostsDir() : hostsDir;\n return hosts === null ? undefined : readModSources(join(hosts, PLUGIN_DIR));\n}\n\n/**\n * THIS PACKAGE'S CLI ENTRY, `dist/index.js` beside the running bundle, for a\n * plugin folder outside the package. The version-free path under pnpm, as\n * {@link packageHostsDir} uses, so an upgrade does not strand it.\n */\nexport function packageCliEntry(\n moduleDir: string = dirname(fileURLToPath(import.meta.url)),\n): string {\n const entry = join(moduleDir, 'index.js');\n return versionFreeEntry(entry) ?? entry;\n}\n\n/** Doctor's and the migration's read: is the plugin installed and enabled? */\nexport interface PluginListing {\n /** The row for `tenjin@tenjin` or `tenjin@skills-dir`, when Claude Code lists one. */\n id: string | null;\n enabled: boolean;\n version: string | null;\n /** False when the list itself could not be read. */\n read: boolean;\n /** The chosen row's scope (`user`, `project`, `local`), or null when it names none. */\n scope: string | null;\n /**\n * The projects a `tenjin@tenjin` install is recorded for and NOT enabled\n * here: each row's `projectPath`. A `local` install made in one project is\n * listed from every other directory as disabled, and enabling it there is\n * not the fix; running from that project is. Empty when the list was not\n * read or names none.\n */\n projects: string[];\n}\n\nexport async function readPluginListing(\n binary: ClaudeBinary,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<PluginListing> {\n const out = await runClaude(binary, ['plugin', 'list', '--json'], { env, cwd });\n const rows = out.code === 0 ? jsonList(out.stdout) : null;\n if (rows === null) {\n return { id: null, enabled: false, version: null, read: false, scope: null, projects: [] };\n }\n const projects = rows\n .filter(\n (r) =>\n r.id === PLUGIN_ID &&\n r.enabled !== true &&\n typeof r.projectPath === 'string' &&\n r.projectPath.length > 0,\n )\n .map((r) => r.projectPath as string);\n const row =\n rows.find((r) => r.id === PLUGIN_ID && r.enabled === true) ??\n rows.find((r) => r.id === SKILLS_DIR_PLUGIN_ID && r.enabled === true) ??\n rows.find((r) => r.id === PLUGIN_ID || r.id === SKILLS_DIR_PLUGIN_ID);\n if (row === undefined) {\n return { id: null, enabled: false, version: null, read: true, scope: null, projects };\n }\n return {\n id: String(row.id),\n enabled: row.enabled === true,\n version: typeof row.version === 'string' ? row.version : null,\n read: true,\n scope: typeof row.scope === 'string' ? row.scope : null,\n projects,\n };\n}\n\n/** Is a folder of ours there for this scope? */\nexport async function folderState(\n scope: PluginScope,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<{ path: string; state: 'absent' | 'ours' | 'foreign' }> {\n const path = folderFor(scope, env, home, cwd);\n return { path, state: await inspectPluginFolder(path) };\n}\n","import { envProxySupported, proxyVariable } from '../lib/env-proxy';\nimport { httpRequest, type HttpResponse } from '../lib/http';\nimport { isSameDeployment, PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { ROUTER_PATH } from './decision';\n\nexport interface RouterCheck {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n required: boolean;\n detail: string;\n fix?: string;\n /** false only when the check could not run: rendered warn, never ok, never counted \"to act on\". */\n checked?: false;\n}\n\n/**\n * One cheap request to the free decision route with an empty body. It checks\n * the route is reachable and enabled, not that it routes: a 400 is the route\n * refusing that body, and a 404 is the route switched off. Nothing is signed\n * and no Jev request is spent. `doctor` fails on it; `install` only warns.\n *\n * A refusal is blamed on the layer that sent it. A proxy, firewall or VPN that\n * blocks the host is not the origin asking for credentials, and on the\n * production base URL the fix is never \"set the base URL\", because that is the\n * one setting that is already right.\n */\nexport async function probeRouter(\n baseUrl: string,\n opts: {\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n env?: NodeJS.ProcessEnv;\n /** Test seam; production asks this Node whether it can use the proxy. */\n proxySupported?: boolean;\n },\n): Promise<RouterCheck> {\n const fail = (detail: string, fix: string): RouterCheck => ({\n name: 'router',\n status: 'fail',\n required: true,\n detail,\n fix,\n });\n // `TENJIN_BASE_URL` and `--base-url` reach here unvalidated. A throw would\n // fail an install that has already written everything else.\n let url: string;\n try {\n url = new URL(ROUTER_PATH, baseUrl).toString();\n } catch {\n return fail(\n `the base URL ${JSON.stringify(baseUrl)} is not a URL`,\n `Check TENJIN_BASE_URL, or set it with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n const host = new URL(url).host;\n const probe = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n blockRedirects: true,\n // A reachability check, not use: it must not count this machine as an install.\n anonymous: true,\n jsonBody: {},\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n });\n const production = isSameDeployment(new URL(url).origin, PRODUCTION_ORIGIN);\n const checkBase = production\n ? 'Try again later.'\n : 'Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.';\n const env = opts.env ?? process.env;\n const network = networkFix(host, env, production, opts.proxySupported ?? envProxySupported());\n const credentials = proxyCredentialsFix(env);\n // Off production, a host that does not resolve or answer is most likely a\n // typo or a dev server that is not running, not a blocked network.\n const unreached = production ? network : checkBase;\n if (!probe.ok) {\n const t = probe.transport;\n if (t?.layer === 'proxy' && t.proxyStatus === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (t?.layer === 'proxy') {\n return fail(\n `a proxy refused the connection to ${host} (${t.proxyStatus}), so the router never answered`,\n unreached,\n );\n }\n if (t?.layer === 'dns') {\n return fail(`${host} did not resolve (${t.code}), so the router was not reached`, unreached);\n }\n if (t?.layer === 'tls') {\n return fail(\n `the TLS connection to ${host} failed (${t.code}). A proxy that inspects TLS causes this`,\n `If this network inspects TLS, set NODE_EXTRA_CA_CERTS to its CA certificate. ${unreached}`,\n );\n }\n if (t?.layer === 'connect') {\n return fail(`could not connect to ${host} (${t.code})`, unreached);\n }\n return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, unreached);\n }\n // 429 is the route's own rate limit: proof the router is there.\n if (probe.status === 200 || probe.status === 400 || probe.status === 429) {\n return { name: 'router', status: 'ok', required: true, detail: `${url} is live` };\n }\n if (probe.status === 404) {\n return fail(`the router is not enabled at ${url}`, checkBase);\n }\n if (probe.status === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (probe.status === 401 || probe.status === 403) {\n if (!fromDeployment(probe)) {\n return fail(\n `${host} answered ${probe.status} without the headers a Tenjin deployment sends, so a proxy, firewall or VPN on the way most likely refused the request`,\n network,\n );\n }\n if (production) {\n return fail(`${url} refused this machine (${probe.status})`, checkBase);\n }\n return fail(\n `${url} is not a Tenjin router (it asked for credentials)`,\n `Set the router URL with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n if (probe.status >= 500) {\n return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);\n }\n return fail(\n `${url} answered ${probe.status}, which a Tenjin router does not`,\n 'Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`).',\n );\n}\n\n/**\n * Did the origin send this, rather than something in front of it? Every Vercel\n * response carries `x-vercel-id` (its own access protection included), and\n * every Tenjin API route adds `x-request-id`. A block page from a proxy,\n * firewall or VPN carries neither.\n */\nfunction fromDeployment(probe: HttpResponse): boolean {\n return probe.header('x-vercel-id') !== undefined || probe.header('x-request-id') !== undefined;\n}\n\nfunction networkFix(\n host: string,\n env: NodeJS.ProcessEnv,\n production: boolean,\n proxySupported: boolean,\n): string {\n const proxy = proxyVariable(env);\n const config = production ? \" Tenjin's own config is correct and needs no change.\" : '';\n if (proxy !== undefined && !proxySupported) {\n return `This shell sets ${proxy}, but Node ${process.versions.node} cannot send Tenjin's requests through it. Upgrade to Node 24.14 or newer, or run from a network that reaches ${host} directly.${config}`;\n }\n const via = proxy !== undefined ? ` (this shell sets ${proxy})` : '';\n return `Allow ${host} through your proxy, firewall or VPN${via}, or run from a network that reaches it.${config}`;\n}\n\nfunction proxyCredentialsFix(env: NodeJS.ProcessEnv): string {\n const proxy = proxyVariable(env) ?? 'HTTPS_PROXY';\n return `Put the proxy's credentials in ${proxy} (\\`http://user:password@proxy:port\\`), then try again.`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,cAAAA,aAAY,gBAAgB;AACrC,SAAS,MAAAC,WAAU;AACnB,SAAS,WAAAC,gBAAe;AACxB,SAAS,WAAAC,UAAS,OAAAC,YAAW;AAC7B,SAAS,iBAAAC,sBAAqB;;;ACL9B,SAAS,kBAAkB;AAC3B,SAAS,YAAAC,WAAU,UAAU,QAAAC,aAAY;AACzC,SAAS,eAAe;AACxB,SAAS,WAAAC,UAAS,YAAY,QAAAC,OAAM,UAAU,SAAS,WAAW;AAClE,SAAS,iBAAAC,sBAAqB;;;ACJ9B,SAAS,iBAAiB;AAC1B,SAAS,SAAS,IAAI,aAAa;AACnC,SAAS,SAAS,YAAY;AAU9B,SAAS,gBAAgB,MAAuB;AAC9C,MAAI;AACF,WAAO,UAAU,MAAM,EAAE,gBAAgB,MAAM,CAAC,GAAG,YAAY,MAAM;AAAA,EACvE,SAAS,KAAK;AAGZ,QAAI,QAAQ,KAAK,QAAQ,KAAK,QAAQ,KAAK,SAAS,EAAG,QAAO;AAC9D,UAAM;AAAA,EACR;AACF;AAOA,eAAsB,iBACpB,MACA,WAC+B;AAC/B,MAAI,CAAC,gBAAgB,SAAS,GAAG;AAC/B,WAAO,EAAE,SAAS,MAAM;AAAA,EAC1B;AACA,QAAM,WAAW,KA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olve","sep","fileURLToPath","readFile","stat","dirname","join","fileURLToPath","join","join","readFile","stat","dirname","join","join","update","stat","readFile","dirname","join","readFile","dirname","fileURLToPath","rt","stat","existsSync","fileURLToPath","updated","homedir","refreshLines","resolve","runtimeBuild","tilde","rm","step","sep","lines"]}