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

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 (495) hide show
  1. package/NOTICE.md +110 -0
  2. package/README.md +87 -81
  3. package/dist/{_esm-BIN7VY2L.js → _esm-2KST7HQ7.js} +7 -7
  4. package/dist/alive-5TV22PNF.js +51 -0
  5. package/dist/auth-XI7BJFLW.js +47 -0
  6. package/dist/{auto-update-Y24UL56V.js → auto-update-7L24KDWA.js} +4 -5
  7. package/dist/balance-DFHC6XEU.js +71 -0
  8. package/dist/{ccip-DHDFKTQV.js → ccip-HOW3DZYF.js} +4 -4
  9. package/dist/chunk-24XKUN2S.js +202 -0
  10. package/dist/chunk-24XKUN2S.js.map +1 -0
  11. package/dist/chunk-2L7TDGLV.js +56 -0
  12. package/dist/chunk-2L7TDGLV.js.map +1 -0
  13. package/dist/{chunk-C2Q76BVM.js → chunk-2U7H35IP.js} +29 -7
  14. package/dist/chunk-2U7H35IP.js.map +1 -0
  15. package/dist/chunk-2W4DQQUU.js +176 -0
  16. package/dist/chunk-2W4DQQUU.js.map +1 -0
  17. package/dist/{chunk-LRW6S53P.js → chunk-34SAECKZ.js} +35 -11
  18. package/dist/chunk-34SAECKZ.js.map +1 -0
  19. package/dist/{chunk-2I4QTOLB.js → chunk-3MZ7DYRO.js} +1 -1
  20. package/dist/chunk-3MZ7DYRO.js.map +1 -0
  21. package/dist/{chunk-RVPYTUP4.js → chunk-3Y2EHT4F.js} +13 -9
  22. package/dist/chunk-3Y2EHT4F.js.map +1 -0
  23. package/dist/chunk-3Y6BHIN6.js +169 -0
  24. package/dist/chunk-3Y6BHIN6.js.map +1 -0
  25. package/dist/{chunk-4K7TQHNP.js → chunk-3YPL6T3P.js} +17 -33
  26. package/dist/chunk-3YPL6T3P.js.map +1 -0
  27. package/dist/{chunk-E7SW44LM.js → chunk-44MVIRZH.js} +121 -6
  28. package/dist/chunk-44MVIRZH.js.map +1 -0
  29. package/dist/chunk-45MMSBHA.js +321 -0
  30. package/dist/chunk-45MMSBHA.js.map +1 -0
  31. package/dist/{chunk-3FMZGI7I.js → chunk-4CE6TMI5.js} +1 -1
  32. package/dist/chunk-4CE6TMI5.js.map +1 -0
  33. package/dist/{chunk-QXP3Z3JN.js → chunk-4MBCJFY4.js} +35 -3
  34. package/dist/chunk-4MBCJFY4.js.map +1 -0
  35. package/dist/chunk-4TPL54KW.js +227 -0
  36. package/dist/chunk-4TPL54KW.js.map +1 -0
  37. package/dist/chunk-54ELBTKE.js +1615 -0
  38. package/dist/chunk-54ELBTKE.js.map +1 -0
  39. package/dist/{chunk-NDGZDTSJ.js → chunk-5F4OB5B3.js} +115 -57
  40. package/dist/chunk-5F4OB5B3.js.map +1 -0
  41. package/dist/chunk-5HN4KVQU.js +3348 -0
  42. package/dist/chunk-5HN4KVQU.js.map +1 -0
  43. package/dist/{chunk-ZDZERB6L.js → chunk-5J4E5GYI.js} +572 -407
  44. package/dist/chunk-5J4E5GYI.js.map +1 -0
  45. package/dist/{chunk-ZNNXRNFD.js → chunk-5N4GGUBN.js} +48 -6
  46. package/dist/chunk-5N4GGUBN.js.map +1 -0
  47. package/dist/chunk-5USBZ2MU.js +58 -0
  48. package/dist/chunk-5USBZ2MU.js.map +1 -0
  49. package/dist/chunk-64WOMNYR.js +183 -0
  50. package/dist/chunk-64WOMNYR.js.map +1 -0
  51. package/dist/{chunk-ILNIZ5I2.js → chunk-65RS4LQS.js} +1825 -1715
  52. package/dist/chunk-65RS4LQS.js.map +1 -0
  53. package/dist/{chunk-IE7P2BZE.js → chunk-6QMDUDF2.js} +3 -3
  54. package/dist/{chunk-IADZOXKN.js → chunk-7SLOTLO7.js} +19 -697
  55. package/dist/chunk-7SLOTLO7.js.map +1 -0
  56. package/dist/{chunk-WFSPCCVW.js → chunk-7V25UAQO.js} +99 -99
  57. package/dist/{chunk-WFSPCCVW.js.map → chunk-7V25UAQO.js.map} +1 -1
  58. package/dist/chunk-BGA4DO5M.js +719 -0
  59. package/dist/chunk-BGA4DO5M.js.map +1 -0
  60. package/dist/chunk-BVP7YK2J.js +706 -0
  61. package/dist/chunk-BVP7YK2J.js.map +1 -0
  62. package/dist/chunk-C265QIMJ.js +83 -0
  63. package/dist/chunk-C265QIMJ.js.map +1 -0
  64. package/dist/{chunk-XQJXNMSB.js → chunk-CRG54LEB.js} +1 -1
  65. package/dist/chunk-CRG54LEB.js.map +1 -0
  66. package/dist/{chunk-KG3D7FIF.js → chunk-CZJOMUBP.js} +2 -2
  67. package/dist/{chunk-36RVGZNY.js → chunk-D6M3ZK66.js} +22 -39
  68. package/dist/chunk-D6M3ZK66.js.map +1 -0
  69. package/dist/{chunk-3UCIG4TG.js → chunk-DI4QAGRZ.js} +1 -11
  70. package/dist/chunk-DI4QAGRZ.js.map +1 -0
  71. package/dist/{chunk-JKKAIPTU.js → chunk-DIH2G3YG.js} +47 -10
  72. package/dist/chunk-DIH2G3YG.js.map +1 -0
  73. package/dist/chunk-DJ36BM62.js +78 -0
  74. package/dist/chunk-DJ36BM62.js.map +1 -0
  75. package/dist/chunk-DTEWAVNE.js +114 -0
  76. package/dist/chunk-DTEWAVNE.js.map +1 -0
  77. package/dist/chunk-F2KJAJ7T.js +13 -0
  78. package/dist/chunk-F2KJAJ7T.js.map +1 -0
  79. package/dist/{chunk-BF4XHEQK.js → chunk-F3QPGYOY.js} +6 -6
  80. package/dist/chunk-F3QPGYOY.js.map +1 -0
  81. package/dist/{chunk-3GNJXKIT.js → chunk-F43CV6UC.js} +2 -2
  82. package/dist/{chunk-J57UC3DD.js → chunk-FKVJKLPI.js} +3 -3
  83. package/dist/{chunk-V2LQLN5H.js → chunk-FYFHH7V5.js} +59 -8
  84. package/dist/{chunk-V2LQLN5H.js.map → chunk-FYFHH7V5.js.map} +1 -1
  85. package/dist/chunk-GAJC4BQZ.js +1096 -0
  86. package/dist/chunk-GAJC4BQZ.js.map +1 -0
  87. package/dist/{chunk-DOQGNFHM.js → chunk-GH5UKMZD.js} +2 -12
  88. package/dist/{chunk-DOQGNFHM.js.map → chunk-GH5UKMZD.js.map} +1 -1
  89. package/dist/{chunk-WYXUQGOL.js → chunk-HAZAN4UM.js} +7 -6
  90. package/dist/chunk-HAZAN4UM.js.map +1 -0
  91. package/dist/chunk-HI5XQOX2.js +393 -0
  92. package/dist/chunk-HI5XQOX2.js.map +1 -0
  93. package/dist/chunk-HKGUKAQW.js +488 -0
  94. package/dist/chunk-HKGUKAQW.js.map +1 -0
  95. package/dist/{chunk-SO3XRZPX.js → chunk-HPRVFJPM.js} +6 -6
  96. package/dist/{chunk-L6JEXB3E.js → chunk-HQR4BWKX.js} +3 -131
  97. package/dist/chunk-HQR4BWKX.js.map +1 -0
  98. package/dist/chunk-HZKANST2.js +177 -0
  99. package/dist/chunk-HZKANST2.js.map +1 -0
  100. package/dist/{chunk-UUGOUOVT.js → chunk-I557SAOM.js} +8 -2
  101. package/dist/chunk-I557SAOM.js.map +1 -0
  102. package/dist/{chunk-TC2WZLSC.js → chunk-IGLWLH73.js} +8 -7
  103. package/dist/chunk-IGLWLH73.js.map +1 -0
  104. package/dist/chunk-ILWCKCOI.js +58 -0
  105. package/dist/chunk-ILWCKCOI.js.map +1 -0
  106. package/dist/{chunk-2GP3HRYK.js → chunk-INSIW65E.js} +182 -182
  107. package/dist/{chunk-MPZUYCAP.js → chunk-IULCDMVG.js} +12 -1
  108. package/dist/chunk-IULCDMVG.js.map +1 -0
  109. package/dist/{chunk-INTFHMU4.js → chunk-IVNSUAVC.js} +25 -26
  110. package/dist/chunk-IVNSUAVC.js.map +1 -0
  111. package/dist/chunk-JDQZCREI.js +87 -0
  112. package/dist/chunk-JDQZCREI.js.map +1 -0
  113. package/dist/chunk-JHFFUVON.js +1050 -0
  114. package/dist/chunk-JHFFUVON.js.map +1 -0
  115. package/dist/{chunk-RL5UUDT4.js → chunk-JNUKLSMZ.js} +3 -3
  116. package/dist/chunk-JTILUN4W.js +2933 -0
  117. package/dist/chunk-JTILUN4W.js.map +1 -0
  118. package/dist/{chunk-OJNTCYQQ.js → chunk-JTX3BUDK.js} +37 -53
  119. package/dist/chunk-JTX3BUDK.js.map +1 -0
  120. package/dist/{chunk-X5ZBP3IY.js → chunk-JUUBBBY5.js} +2 -2
  121. package/dist/chunk-JUUBBBY5.js.map +1 -0
  122. package/dist/chunk-JWAK7JQB.js +15 -0
  123. package/dist/chunk-JWAK7JQB.js.map +1 -0
  124. package/dist/{chunk-UXZONNEQ.js → chunk-K5KNGC4I.js} +34 -31
  125. package/dist/chunk-K5KNGC4I.js.map +1 -0
  126. package/dist/chunk-KAQ4Q3TO.js +135 -0
  127. package/dist/chunk-KAQ4Q3TO.js.map +1 -0
  128. package/dist/chunk-KFVJYLVL.js +125 -0
  129. package/dist/chunk-KFVJYLVL.js.map +1 -0
  130. package/dist/chunk-KGUE5AVX.js +69 -0
  131. package/dist/chunk-KGUE5AVX.js.map +1 -0
  132. package/dist/{chunk-FVIGCDSV.js → chunk-KLDMLWXT.js} +11 -85
  133. package/dist/chunk-KLDMLWXT.js.map +1 -0
  134. package/dist/chunk-KNKDMTHU.js +453 -0
  135. package/dist/chunk-KNKDMTHU.js.map +1 -0
  136. package/dist/chunk-LDA6TAYQ.js +95 -0
  137. package/dist/chunk-LDA6TAYQ.js.map +1 -0
  138. package/dist/chunk-LWSSIZOY.js +347 -0
  139. package/dist/chunk-LWSSIZOY.js.map +1 -0
  140. package/dist/{chunk-ZURZHELF.js → chunk-MAHNZA6C.js} +158 -41
  141. package/dist/chunk-MAHNZA6C.js.map +1 -0
  142. package/dist/chunk-MEWZCIA6.js +220 -0
  143. package/dist/chunk-MEWZCIA6.js.map +1 -0
  144. package/dist/{chunk-2SNUOHAT.js → chunk-MEZJ3I63.js} +49 -1
  145. package/dist/chunk-MEZJ3I63.js.map +1 -0
  146. package/dist/chunk-MJDO4EXD.js +353 -0
  147. package/dist/chunk-MJDO4EXD.js.map +1 -0
  148. package/dist/chunk-NJA6NT3A.js +6595 -0
  149. package/dist/chunk-NJA6NT3A.js.map +1 -0
  150. package/dist/{chunk-LHHMV4GU.js → chunk-NVSKJPRC.js} +1 -1
  151. package/dist/{chunk-LHHMV4GU.js.map → chunk-NVSKJPRC.js.map} +1 -1
  152. package/dist/{chunk-4YOZGGTZ.js → chunk-OC7K2DVZ.js} +5 -5
  153. package/dist/chunk-OC7K2DVZ.js.map +1 -0
  154. package/dist/chunk-ODRPASFP.js +2078 -0
  155. package/dist/chunk-ODRPASFP.js.map +1 -0
  156. package/dist/chunk-OJJFANO6.js +133 -0
  157. package/dist/chunk-OJJFANO6.js.map +1 -0
  158. package/dist/{chunk-JNJWBTU2.js → chunk-OQWPRFAC.js} +332 -882
  159. package/dist/chunk-OQWPRFAC.js.map +1 -0
  160. package/dist/chunk-P4I7BFNJ.js +11 -0
  161. package/dist/chunk-P4I7BFNJ.js.map +1 -0
  162. package/dist/{chunk-SNNSAGMT.js → chunk-P6YQWIT2.js} +4058 -4039
  163. package/dist/chunk-P6YQWIT2.js.map +1 -0
  164. package/dist/{chunk-JRGFKVAZ.js → chunk-PETQ5WEA.js} +2 -2
  165. package/dist/{chunk-HMWYAUA6.js → chunk-Q6RSJCXB.js} +29 -69
  166. package/dist/chunk-Q6RSJCXB.js.map +1 -0
  167. package/dist/{chunk-U3IKUGRP.js → chunk-QKEUKBRK.js} +17 -23
  168. package/dist/chunk-QKEUKBRK.js.map +1 -0
  169. package/dist/{chunk-2RWB7RKE.js → chunk-QKYUCITR.js} +174 -5814
  170. package/dist/chunk-QKYUCITR.js.map +1 -0
  171. package/dist/chunk-QQDPRTLP.js +127 -0
  172. package/dist/chunk-QQDPRTLP.js.map +1 -0
  173. package/dist/chunk-QQYCYAKI.js +79 -0
  174. package/dist/chunk-QQYCYAKI.js.map +1 -0
  175. package/dist/chunk-R4KDH477.js +1064 -0
  176. package/dist/chunk-R4KDH477.js.map +1 -0
  177. package/dist/chunk-R5TR2DIK.js +119 -0
  178. package/dist/chunk-R5TR2DIK.js.map +1 -0
  179. package/dist/chunk-R62PKTAG.js +66 -0
  180. package/dist/chunk-R62PKTAG.js.map +1 -0
  181. package/dist/{chunk-BFDQ4WNW.js → chunk-RFZA7PSM.js} +4 -5
  182. package/dist/chunk-RFZA7PSM.js.map +1 -0
  183. package/dist/chunk-RGCPELQN.js +219 -0
  184. package/dist/chunk-RGCPELQN.js.map +1 -0
  185. package/dist/chunk-RGVCOG2S.js +910 -0
  186. package/dist/chunk-RGVCOG2S.js.map +1 -0
  187. package/dist/chunk-SOLNJ3AZ.js +209 -0
  188. package/dist/chunk-SOLNJ3AZ.js.map +1 -0
  189. package/dist/chunk-TFT2X7SH.js +77 -0
  190. package/dist/chunk-TFT2X7SH.js.map +1 -0
  191. package/dist/chunk-TUCKEEXE.js +2 -0
  192. package/dist/chunk-TVWCLUBI.js +293 -0
  193. package/dist/chunk-TVWCLUBI.js.map +1 -0
  194. package/dist/chunk-U4TRWSVE.js +78 -0
  195. package/dist/chunk-U4TRWSVE.js.map +1 -0
  196. package/dist/chunk-UIB33QQP.js +379 -0
  197. package/dist/chunk-UIB33QQP.js.map +1 -0
  198. package/dist/chunk-V6GIVALQ.js +1889 -0
  199. package/dist/chunk-V6GIVALQ.js.map +1 -0
  200. package/dist/chunk-VHXCPXUS.js +366 -0
  201. package/dist/chunk-VHXCPXUS.js.map +1 -0
  202. package/dist/{chunk-HGZEPQUT.js → chunk-VU6GMWF6.js} +17 -8
  203. package/dist/chunk-VU6GMWF6.js.map +1 -0
  204. package/dist/chunk-VWZYE3NC.js +8415 -0
  205. package/dist/chunk-VWZYE3NC.js.map +1 -0
  206. package/dist/{chunk-AGMVASXZ.js → chunk-W2GXIARJ.js} +88 -11
  207. package/dist/chunk-W2GXIARJ.js.map +1 -0
  208. package/dist/chunk-W4G3K3V7.js +288 -0
  209. package/dist/chunk-W4G3K3V7.js.map +1 -0
  210. package/dist/chunk-W74LJ5OT.js +588 -0
  211. package/dist/chunk-W74LJ5OT.js.map +1 -0
  212. package/dist/chunk-W7ELYLYK.js +233 -0
  213. package/dist/chunk-W7ELYLYK.js.map +1 -0
  214. package/dist/{chunk-BPMWXTFX.js → chunk-WFZX352D.js} +7 -7
  215. package/dist/chunk-WXA3WTPF.js +20 -0
  216. package/dist/chunk-WXA3WTPF.js.map +1 -0
  217. package/dist/chunk-XRGFH7FI.js +454 -0
  218. package/dist/chunk-XRGFH7FI.js.map +1 -0
  219. package/dist/chunk-XSCGUO2U.js +330 -0
  220. package/dist/chunk-XSCGUO2U.js.map +1 -0
  221. package/dist/chunk-XWROSMI5.js +1039 -0
  222. package/dist/chunk-XWROSMI5.js.map +1 -0
  223. package/dist/chunk-Y2EXZ47H.js +40 -0
  224. package/dist/chunk-Y2EXZ47H.js.map +1 -0
  225. package/dist/chunk-YJGEVBKZ.js +47 -0
  226. package/dist/chunk-YJGEVBKZ.js.map +1 -0
  227. package/dist/{chunk-6CMM6YCB.js → chunk-YWWMISDY.js} +2 -2
  228. package/dist/{chunk-WXA2BWTE.js → chunk-ZCT5DJ3G.js} +2 -48
  229. package/dist/chunk-ZCT5DJ3G.js.map +1 -0
  230. package/dist/chunk-ZEYA2WWX.js +982 -0
  231. package/dist/chunk-ZEYA2WWX.js.map +1 -0
  232. package/dist/chunk-ZRC7Z5X3.js +82 -0
  233. package/dist/chunk-ZRC7Z5X3.js.map +1 -0
  234. package/dist/{chunk-3AIHRXKO.js → chunk-ZS7JIUJ3.js} +12 -10
  235. package/dist/chunk-ZS7JIUJ3.js.map +1 -0
  236. package/dist/{clack-EZ7TDWQU.js → clack-Q4RNC5VE.js} +2 -6
  237. package/dist/{claude-cli-2YKABJJZ.js → claude-cli-GIIHOBGT.js} +4 -2
  238. package/dist/claude-install-BAUSJMW3.js +64 -0
  239. package/dist/{cli-E36SPKBW.js → cli-QY4KKA3D.js} +632 -150
  240. package/dist/cli-QY4KKA3D.js.map +1 -0
  241. package/dist/client-3YQKORVK.js +710 -0
  242. package/dist/client-3YQKORVK.js.map +1 -0
  243. package/dist/{codex-event-ZO2GEFE6.js → codex-event-EUTCAOTQ.js} +3 -5
  244. package/dist/{codex-host-KECJVTA2.js → codex-host-ZON3S6HU.js} +7 -7
  245. package/dist/{codex-install-HQZDGFXW.js → codex-install-HZV2DOAB.js} +242 -88
  246. package/dist/codex-install-HZV2DOAB.js.map +1 -0
  247. package/dist/config-QZOBMTEL.js +57 -0
  248. package/dist/config-names-Z5NZD5R2.js +224 -0
  249. package/dist/config-names-Z5NZD5R2.js.map +1 -0
  250. package/dist/config-rules-YOYHS6YL.js +55 -0
  251. package/dist/config-subagents-WQV2ZAD5.js +362 -0
  252. package/dist/config-subagents-WQV2ZAD5.js.map +1 -0
  253. package/dist/connect-YDWTYU4B.js +1020 -0
  254. package/dist/connect-YDWTYU4B.js.map +1 -0
  255. package/dist/core-0a66n3e7-TTP554XV.js +127 -0
  256. package/dist/core-0a66n3e7-TTP554XV.js.map +1 -0
  257. package/dist/core-0bmnpbz2-C2JIRVZO.js +10790 -0
  258. package/dist/core-0bmnpbz2-C2JIRVZO.js.map +1 -0
  259. package/dist/core-9je8ee1j-74DGHWPV.js +30 -0
  260. package/dist/core-9je8ee1j-74DGHWPV.js.map +1 -0
  261. package/dist/core-wadgcjfh-TSZFQZGH.js +666 -0
  262. package/dist/core-wadgcjfh-TSZFQZGH.js.map +1 -0
  263. package/dist/core-zg882d22-LKV5DZYW.js +37 -0
  264. package/dist/core-zg882d22-LKV5DZYW.js.map +1 -0
  265. package/dist/decision-QSKHOGCO.js +145 -0
  266. package/dist/{doctor-I6XQEKWD.js → doctor-ZWJXRD75.js} +162 -148
  267. package/dist/doctor-ZWJXRD75.js.map +1 -0
  268. package/dist/{env-proxy-R6ZMLQTT.js → env-proxy-XLSLHBKQ.js} +2 -2
  269. package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js → ethersCompat-Df4a6QIZ-K3DMHR6Y.js} +5 -5
  270. package/dist/explicit-ME2NRADQ.js +371 -0
  271. package/dist/explicit-ME2NRADQ.js.map +1 -0
  272. package/dist/flush-stdio-NYIJ3QXT.js +18 -0
  273. package/dist/fund-VF7TLDJH.js +722 -0
  274. package/dist/fund-VF7TLDJH.js.map +1 -0
  275. package/dist/hook-command-VZ27MGWO.js +49 -0
  276. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  277. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  278. package/dist/hosts/claude/tenjin/hooks/hook-data.ts +152 -0
  279. package/dist/hosts/claude/tenjin/hooks/hooks.json +7 -0
  280. package/dist/hosts/claude/tenjin/hooks/model-viewer.tsx +2987 -0
  281. package/dist/hosts/claude/tenjin/hooks/register.tsx +527 -56
  282. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +14 -4
  283. package/dist/hosts/claude/tenjin/types/index.d.ts +144 -1
  284. package/dist/{hosts-DVQJ32QC.js → hosts-3EMTVM4H.js} +7 -6
  285. package/dist/index.js +18 -15
  286. package/dist/index.js.map +1 -1
  287. package/dist/install-ZA7L2UF3.js +115 -0
  288. package/dist/install-funding-JDGYTF72.js +30 -0
  289. package/dist/install-identity-FFAYEFLX.js +30 -0
  290. package/dist/{install-wallet-5M4OTYLX.js → install-wallet-2SFOVE3Q.js} +68 -53
  291. package/dist/install-wallet-2SFOVE3Q.js.map +1 -0
  292. package/dist/mcp-36S6MK3C.js +67642 -0
  293. package/dist/mcp-36S6MK3C.js.map +1 -0
  294. package/dist/new-install-5L4GY3LN.js +51 -0
  295. package/dist/{package-IJFGMWEV.js → package-BONDXSV3.js} +2 -2
  296. package/dist/{passphrase-IFTDS3CU.js → passphrase-T4ULBN4M.js} +16 -12
  297. package/dist/{paths-XCSAKISU.js → paths-O2KDWZ76.js} +18 -28
  298. package/dist/pay-CMV5KL74.js +74 -0
  299. package/dist/{payments-HFPPWHTV.js → payments-Z6UBZL4Z.js} +36 -26
  300. package/dist/payments-Z6UBZL4Z.js.map +1 -0
  301. package/dist/reclaim-subagent-credit-ABSF67SJ.js +105 -0
  302. package/dist/reclaim-subagent-credit-ABSF67SJ.js.map +1 -0
  303. package/dist/{redact-D7ASVWKL.js → redact-LOTHE5TS.js} +2 -8
  304. package/dist/redact-LOTHE5TS.js.map +1 -0
  305. package/dist/routing-quote-AHLAREXR.js +40 -0
  306. package/dist/routing-quote-AHLAREXR.js.map +1 -0
  307. package/dist/run-JH7ELYAM.js +88 -0
  308. package/dist/run-JH7ELYAM.js.map +1 -0
  309. package/dist/runtime-2GX4ALJP.js +410 -0
  310. package/dist/runtime-2GX4ALJP.js.map +1 -0
  311. package/dist/runtime-activate-IDQ2NCSP.js +39 -0
  312. package/dist/runtime-activate-IDQ2NCSP.js.map +1 -0
  313. package/dist/{runtime-fetch-ZSSSK72Y.js → runtime-fetch-6LOBHBEN.js} +4 -4
  314. package/dist/runtime-fetch-6LOBHBEN.js.map +1 -0
  315. package/dist/runtime-launchers-YAPKCBHV.js +31 -0
  316. package/dist/runtime-launchers-YAPKCBHV.js.map +1 -0
  317. package/dist/{runtime-layout-WIDILZ6K.js → runtime-layout-QHZQJV7C.js} +5 -4
  318. package/dist/runtime-layout-QHZQJV7C.js.map +1 -0
  319. package/dist/runtime-place-4POL4KK4.js +37 -0
  320. package/dist/runtime-place-4POL4KK4.js.map +1 -0
  321. package/dist/runtime-provenance-MNJGVBV2.js +12 -0
  322. package/dist/runtime-provenance-MNJGVBV2.js.map +1 -0
  323. package/dist/{secp256k1-ZZZT2CAX.js → secp256k1-N5P2GVGF.js} +3 -3
  324. package/dist/secp256k1-N5P2GVGF.js.map +1 -0
  325. package/dist/{send-GCVEAQKL.js → send-ELXFKEKY.js} +35 -32
  326. package/dist/send-ELXFKEKY.js.map +1 -0
  327. package/dist/status-FXUFWJDM.js +404 -0
  328. package/dist/status-FXUFWJDM.js.map +1 -0
  329. package/dist/{status-line-OPCXDHL2.js → status-line-IH5JBWBC.js} +51 -43
  330. package/dist/status-line-IH5JBWBC.js.map +1 -0
  331. package/dist/streamableHttp-CP2ZQBIK.js +768 -0
  332. package/dist/streamableHttp-CP2ZQBIK.js.map +1 -0
  333. package/dist/{uninstall-BAWRBXXQ.js → uninstall-LJZUKM4D.js} +76 -76
  334. package/dist/uninstall-LJZUKM4D.js.map +1 -0
  335. package/dist/update-EUIX72IX.js +68 -0
  336. package/dist/update-EUIX72IX.js.map +1 -0
  337. package/dist/usage-EKDC7LUC.js +180 -0
  338. package/dist/usage-EKDC7LUC.js.map +1 -0
  339. package/dist/{usdc-VG4CIOUK.js → usdc-YIHK2OMC.js} +8 -12
  340. package/dist/usdc-YIHK2OMC.js.map +1 -0
  341. package/dist/{viemAdapter-By13KInL-DOFTEIJV.js → viemAdapter-By13KInL-PRLSIESK.js} +5 -5
  342. package/dist/viemAdapter-By13KInL-PRLSIESK.js.map +1 -0
  343. package/dist/wallet-HSW757W6.js +80 -0
  344. package/dist/wallet-HSW757W6.js.map +1 -0
  345. package/dist/wallet-kdf-worker.mjs +1433 -818
  346. package/docs/agent-permissions.md +88 -155
  347. package/docs/router-reference.md +236 -0
  348. package/docs/safety-model.md +31 -33
  349. package/docs/subagents-internals.md +97 -0
  350. package/docs/subagents.md +348 -0
  351. package/docs/troubleshooting.md +10 -6
  352. package/package.json +12 -8
  353. package/scripts/installers/install.sh +7 -1
  354. package/dist/alive-GSOWKUOY.js +0 -38
  355. package/dist/chunk-2I4QTOLB.js.map +0 -1
  356. package/dist/chunk-2M2VPI2E.js +0 -560
  357. package/dist/chunk-2M2VPI2E.js.map +0 -1
  358. package/dist/chunk-2RWB7RKE.js.map +0 -1
  359. package/dist/chunk-2SNUOHAT.js.map +0 -1
  360. package/dist/chunk-3623BLPV.js +0 -184
  361. package/dist/chunk-3623BLPV.js.map +0 -1
  362. package/dist/chunk-36RVGZNY.js.map +0 -1
  363. package/dist/chunk-3AIHRXKO.js.map +0 -1
  364. package/dist/chunk-3FMZGI7I.js.map +0 -1
  365. package/dist/chunk-3UCIG4TG.js.map +0 -1
  366. package/dist/chunk-4K7TQHNP.js.map +0 -1
  367. package/dist/chunk-4LMUQMBH.js +0 -29
  368. package/dist/chunk-4LMUQMBH.js.map +0 -1
  369. package/dist/chunk-4USCZ2NI.js +0 -228
  370. package/dist/chunk-4USCZ2NI.js.map +0 -1
  371. package/dist/chunk-4YOZGGTZ.js.map +0 -1
  372. package/dist/chunk-62KNUYWD.js +0 -111
  373. package/dist/chunk-62KNUYWD.js.map +0 -1
  374. package/dist/chunk-A5GKIG5O.js +0 -2037
  375. package/dist/chunk-A5GKIG5O.js.map +0 -1
  376. package/dist/chunk-AGMVASXZ.js.map +0 -1
  377. package/dist/chunk-BF4XHEQK.js.map +0 -1
  378. package/dist/chunk-BFDQ4WNW.js.map +0 -1
  379. package/dist/chunk-C2Q76BVM.js.map +0 -1
  380. package/dist/chunk-CEXSOI5R.js +0 -808
  381. package/dist/chunk-CEXSOI5R.js.map +0 -1
  382. package/dist/chunk-E7SW44LM.js.map +0 -1
  383. package/dist/chunk-EDJWHDDL.js +0 -33
  384. package/dist/chunk-EDJWHDDL.js.map +0 -1
  385. package/dist/chunk-FVIGCDSV.js.map +0 -1
  386. package/dist/chunk-GTTUCOPD.js +0 -105
  387. package/dist/chunk-GTTUCOPD.js.map +0 -1
  388. package/dist/chunk-HDPUXS3Z.js +0 -122
  389. package/dist/chunk-HDPUXS3Z.js.map +0 -1
  390. package/dist/chunk-HGGWCP7W.js +0 -120
  391. package/dist/chunk-HGGWCP7W.js.map +0 -1
  392. package/dist/chunk-HGZEPQUT.js.map +0 -1
  393. package/dist/chunk-HMWYAUA6.js.map +0 -1
  394. package/dist/chunk-IADZOXKN.js.map +0 -1
  395. package/dist/chunk-ILNIZ5I2.js.map +0 -1
  396. package/dist/chunk-INTFHMU4.js.map +0 -1
  397. package/dist/chunk-JKKAIPTU.js.map +0 -1
  398. package/dist/chunk-JNJWBTU2.js.map +0 -1
  399. package/dist/chunk-KM7RY2ZS.js +0 -246
  400. package/dist/chunk-KM7RY2ZS.js.map +0 -1
  401. package/dist/chunk-KOGZDMHO.js +0 -21
  402. package/dist/chunk-KOGZDMHO.js.map +0 -1
  403. package/dist/chunk-L6JEXB3E.js.map +0 -1
  404. package/dist/chunk-LRW6S53P.js.map +0 -1
  405. package/dist/chunk-LXAYUOXI.js +0 -511
  406. package/dist/chunk-LXAYUOXI.js.map +0 -1
  407. package/dist/chunk-MEFB5KHA.js +0 -59
  408. package/dist/chunk-MEFB5KHA.js.map +0 -1
  409. package/dist/chunk-MPZUYCAP.js.map +0 -1
  410. package/dist/chunk-NDGZDTSJ.js.map +0 -1
  411. package/dist/chunk-OJNTCYQQ.js.map +0 -1
  412. package/dist/chunk-P3LFTKE7.js +0 -58
  413. package/dist/chunk-P3LFTKE7.js.map +0 -1
  414. package/dist/chunk-QXP3Z3JN.js.map +0 -1
  415. package/dist/chunk-RVPYTUP4.js.map +0 -1
  416. package/dist/chunk-SNNSAGMT.js.map +0 -1
  417. package/dist/chunk-TC2WZLSC.js.map +0 -1
  418. package/dist/chunk-TKPF35W6.js +0 -29
  419. package/dist/chunk-TKPF35W6.js.map +0 -1
  420. package/dist/chunk-U3IKUGRP.js.map +0 -1
  421. package/dist/chunk-UUGOUOVT.js.map +0 -1
  422. package/dist/chunk-UXZONNEQ.js.map +0 -1
  423. package/dist/chunk-WXA2BWTE.js.map +0 -1
  424. package/dist/chunk-WYXUQGOL.js.map +0 -1
  425. package/dist/chunk-X5ZBP3IY.js.map +0 -1
  426. package/dist/chunk-XKESD27X.js +0 -10
  427. package/dist/chunk-XKESD27X.js.map +0 -1
  428. package/dist/chunk-XQJXNMSB.js.map +0 -1
  429. package/dist/chunk-Y527D4TV.js +0 -56
  430. package/dist/chunk-Y527D4TV.js.map +0 -1
  431. package/dist/chunk-ZDZERB6L.js.map +0 -1
  432. package/dist/chunk-ZNNXRNFD.js.map +0 -1
  433. package/dist/chunk-ZURZHELF.js.map +0 -1
  434. package/dist/cli-E36SPKBW.js.map +0 -1
  435. package/dist/codex-install-HQZDGFXW.js.map +0 -1
  436. package/dist/config-HY2E4GGW.js +0 -55
  437. package/dist/doctor-I6XQEKWD.js.map +0 -1
  438. package/dist/fund-2QRO7OJL.js +0 -378
  439. package/dist/fund-2QRO7OJL.js.map +0 -1
  440. package/dist/hook-command-2UBCSZG6.js +0 -43
  441. package/dist/install-ILUX5C4A.js +0 -107
  442. package/dist/install-identity-TZKGY6LQ.js +0 -31
  443. package/dist/install-wallet-5M4OTYLX.js.map +0 -1
  444. package/dist/mcp-LE4DUS22.js +0 -14127
  445. package/dist/mcp-LE4DUS22.js.map +0 -1
  446. package/dist/pay-WCG3IH4R.js +0 -55
  447. package/dist/payments-HFPPWHTV.js.map +0 -1
  448. package/dist/plugin-registration-PZFI5GZW.js +0 -68
  449. package/dist/runtime-UZOKSUZX.js +0 -1321
  450. package/dist/runtime-UZOKSUZX.js.map +0 -1
  451. package/dist/send-GCVEAQKL.js.map +0 -1
  452. package/dist/status-HCVAOCN7.js +0 -150
  453. package/dist/status-HCVAOCN7.js.map +0 -1
  454. package/dist/status-line-OPCXDHL2.js.map +0 -1
  455. package/dist/uninstall-BAWRBXXQ.js.map +0 -1
  456. package/dist/update-CACXLQLR.js +0 -56
  457. package/dist/wallet-QL4UUXEZ.js +0 -55
  458. /package/dist/{_esm-BIN7VY2L.js.map → _esm-2KST7HQ7.js.map} +0 -0
  459. /package/dist/{alive-GSOWKUOY.js.map → alive-5TV22PNF.js.map} +0 -0
  460. /package/dist/{auto-update-Y24UL56V.js.map → auth-XI7BJFLW.js.map} +0 -0
  461. /package/dist/{ccip-DHDFKTQV.js.map → auto-update-7L24KDWA.js.map} +0 -0
  462. /package/dist/{clack-EZ7TDWQU.js.map → balance-DFHC6XEU.js.map} +0 -0
  463. /package/dist/{claude-cli-2YKABJJZ.js.map → ccip-HOW3DZYF.js.map} +0 -0
  464. /package/dist/{chunk-IE7P2BZE.js.map → chunk-6QMDUDF2.js.map} +0 -0
  465. /package/dist/{chunk-KG3D7FIF.js.map → chunk-CZJOMUBP.js.map} +0 -0
  466. /package/dist/{chunk-3GNJXKIT.js.map → chunk-F43CV6UC.js.map} +0 -0
  467. /package/dist/{chunk-J57UC3DD.js.map → chunk-FKVJKLPI.js.map} +0 -0
  468. /package/dist/{chunk-SO3XRZPX.js.map → chunk-HPRVFJPM.js.map} +0 -0
  469. /package/dist/{chunk-2GP3HRYK.js.map → chunk-INSIW65E.js.map} +0 -0
  470. /package/dist/{chunk-RL5UUDT4.js.map → chunk-JNUKLSMZ.js.map} +0 -0
  471. /package/dist/{chunk-JRGFKVAZ.js.map → chunk-PETQ5WEA.js.map} +0 -0
  472. /package/dist/{codex-event-ZO2GEFE6.js.map → chunk-TUCKEEXE.js.map} +0 -0
  473. /package/dist/{chunk-BPMWXTFX.js.map → chunk-WFZX352D.js.map} +0 -0
  474. /package/dist/{chunk-6CMM6YCB.js.map → chunk-YWWMISDY.js.map} +0 -0
  475. /package/dist/{codex-host-KECJVTA2.js.map → clack-Q4RNC5VE.js.map} +0 -0
  476. /package/dist/{config-HY2E4GGW.js.map → claude-cli-GIIHOBGT.js.map} +0 -0
  477. /package/dist/{env-proxy-R6ZMLQTT.js.map → claude-install-BAUSJMW3.js.map} +0 -0
  478. /package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js.map → codex-event-EUTCAOTQ.js.map} +0 -0
  479. /package/dist/{hook-command-2UBCSZG6.js.map → codex-host-ZON3S6HU.js.map} +0 -0
  480. /package/dist/{hosts-DVQJ32QC.js.map → config-QZOBMTEL.js.map} +0 -0
  481. /package/dist/{install-ILUX5C4A.js.map → config-rules-YOYHS6YL.js.map} +0 -0
  482. /package/dist/{install-identity-TZKGY6LQ.js.map → decision-QSKHOGCO.js.map} +0 -0
  483. /package/dist/{package-IJFGMWEV.js.map → env-proxy-XLSLHBKQ.js.map} +0 -0
  484. /package/dist/{passphrase-IFTDS3CU.js.map → ethersCompat-Df4a6QIZ-K3DMHR6Y.js.map} +0 -0
  485. /package/dist/{paths-XCSAKISU.js.map → flush-stdio-NYIJ3QXT.js.map} +0 -0
  486. /package/dist/{pay-WCG3IH4R.js.map → hook-command-VZ27MGWO.js.map} +0 -0
  487. /package/dist/{plugin-registration-PZFI5GZW.js.map → hosts-3EMTVM4H.js.map} +0 -0
  488. /package/dist/{redact-D7ASVWKL.js.map → install-ZA7L2UF3.js.map} +0 -0
  489. /package/dist/{runtime-fetch-ZSSSK72Y.js.map → install-funding-JDGYTF72.js.map} +0 -0
  490. /package/dist/{runtime-layout-WIDILZ6K.js.map → install-identity-FFAYEFLX.js.map} +0 -0
  491. /package/dist/{secp256k1-ZZZT2CAX.js.map → new-install-5L4GY3LN.js.map} +0 -0
  492. /package/dist/{update-CACXLQLR.js.map → package-BONDXSV3.js.map} +0 -0
  493. /package/dist/{usdc-VG4CIOUK.js.map → passphrase-T4ULBN4M.js.map} +0 -0
  494. /package/dist/{viemAdapter-By13KInL-DOFTEIJV.js.map → paths-O2KDWZ76.js.map} +0 -0
  495. /package/dist/{wallet-QL4UUXEZ.js.map → pay-CMV5KL74.js.map} +0 -0
@@ -5,64 +5,33 @@ import {
5
5
  fetchDistTags,
6
6
  fetchPublishTime,
7
7
  resolveTarget
8
- } from "./chunk-U3IKUGRP.js";
8
+ } from "./chunk-QKEUKBRK.js";
9
9
  import {
10
- underAgentHarness
11
- } from "./chunk-KOGZDMHO.js";
12
- import {
13
- ROUTER_PATH
14
- } from "./chunk-LXAYUOXI.js";
10
+ recordTermsTold
11
+ } from "./chunk-Y2EXZ47H.js";
15
12
  import {
16
13
  readMcpServers
17
- } from "./chunk-3GNJXKIT.js";
18
- import {
19
- CLI_SKILL_NAMES,
20
- FEE_APPROVAL,
21
- RETIRED_SKILL_NAMES,
22
- ROUTER_DEFAULTS,
23
- ROUTING_FEE_TERMS,
24
- SHIPPED_SKILL_FILES,
25
- SPEND_QUESTION,
26
- inspectHooksFile,
27
- persistRouterDefaults,
28
- persistRouterProject,
29
- readSkillFile,
30
- shownLimits,
31
- skillFrontmatterName,
32
- skillsDirsFor,
33
- spendChoiceQuestion,
34
- spendOptions
35
- } from "./chunk-A5GKIG5O.js";
36
- import {
37
- emitWriteNotice,
38
- paint,
39
- sanitizeForTerminal
40
- } from "./chunk-FVIGCDSV.js";
41
- import {
42
- SUGGESTED_FUND_USD
43
- } from "./chunk-HDPUXS3Z.js";
44
- import {
45
- askText,
46
- selectOne
47
- } from "./chunk-DOQGNFHM.js";
14
+ } from "./chunk-F43CV6UC.js";
48
15
  import {
49
16
  MANAGERS,
50
17
  classifyManager,
51
- inspectPluginFolder,
52
18
  isSourceCheckout,
19
+ refuse,
20
+ resolveManagerScript
21
+ } from "./chunk-HQR4BWKX.js";
22
+ import {
23
+ inspectPluginFolder,
53
24
  pluginFolderPath,
54
25
  readModSources,
55
- refuse,
56
26
  removePluginFolder,
57
- resolveManagerScript,
58
27
  writePluginFolder
59
- } from "./chunk-L6JEXB3E.js";
28
+ } from "./chunk-OJJFANO6.js";
60
29
  import {
61
30
  PLUGIN_DIR,
62
31
  RUNTIME_MISSING_FIX,
63
32
  renderPluginFiles,
64
33
  shQuote
65
- } from "./chunk-LRW6S53P.js";
34
+ } from "./chunk-34SAECKZ.js";
66
35
  import {
67
36
  LEGACY_HOOK_TOOL,
68
37
  LEGACY_MCP_SERVER_NAME,
@@ -72,20 +41,16 @@ import {
72
41
  PLUGIN_ID,
73
42
  PLUGIN_NAME,
74
43
  SKILLS_DIR_PLUGIN_ID
75
- } from "./chunk-MPZUYCAP.js";
44
+ } from "./chunk-IULCDMVG.js";
76
45
  import {
77
- runningGlibc,
78
- unpinnedPlatform
79
- } from "./chunk-4YOZGGTZ.js";
46
+ underAgentHarness
47
+ } from "./chunk-WXA3WTPF.js";
80
48
  import {
81
- envProxySupported,
82
- proxyNodeStep,
83
- proxySkipped,
84
- proxyVariable
85
- } from "./chunk-3FMZGI7I.js";
49
+ fundStep
50
+ } from "./chunk-QQDPRTLP.js";
86
51
  import {
87
- httpRequest
88
- } from "./chunk-36RVGZNY.js";
52
+ isRecord
53
+ } from "./chunk-P4I7BFNJ.js";
89
54
  import {
90
55
  CLAUDE_CODE_FLOOR,
91
56
  claudeConfigDir,
@@ -96,76 +61,126 @@ import {
96
61
  runClaude,
97
62
  userMcpFile,
98
63
  userSettingsPath
99
- } from "./chunk-QXP3Z3JN.js";
64
+ } from "./chunk-4MBCJFY4.js";
100
65
  import {
101
- package_default
102
- } from "./chunk-RVPYTUP4.js";
66
+ runningGlibc,
67
+ unpinnedPlatform
68
+ } from "./chunk-OC7K2DVZ.js";
103
69
  import {
104
- resolveContextSettings
105
- } from "./chunk-KM7RY2ZS.js";
70
+ readAliveStamp
71
+ } from "./chunk-5F4OB5B3.js";
72
+ import {
73
+ captureNewInstall,
74
+ finishNewInstall,
75
+ reserveNewInstall
76
+ } from "./chunk-4TPL54KW.js";
77
+ import {
78
+ persistRouterDefaults,
79
+ persistRouterProject
80
+ } from "./chunk-W74LJ5OT.js";
81
+ import {
82
+ DEFAULTS_LABEL,
83
+ FEE_APPROVAL,
84
+ ROUTER_DEFAULTS,
85
+ ROUTING_FEE_TERMS,
86
+ SPEND_QUESTION,
87
+ limitsLine,
88
+ shownLimits,
89
+ spendChoiceQuestion,
90
+ spendOptions
91
+ } from "./chunk-KGUE5AVX.js";
92
+ import {
93
+ emitWriteNotice,
94
+ paint,
95
+ sanitizeForTerminal
96
+ } from "./chunk-KLDMLWXT.js";
97
+ import {
98
+ ROUTING_FEE_CEILING_ATOMIC,
99
+ SUGGESTED_FUND_USD,
100
+ usd
101
+ } from "./chunk-HZKANST2.js";
106
102
  import {
107
103
  parseUsdToAtomic,
108
104
  toMoney
109
- } from "./chunk-Y527D4TV.js";
110
- import {
111
- readAliveStamp
112
- } from "./chunk-NDGZDTSJ.js";
105
+ } from "./chunk-MEZJ3I63.js";
113
106
  import {
114
107
  WALLET_REASONS,
115
108
  agentFixFor
116
- } from "./chunk-BFDQ4WNW.js";
109
+ } from "./chunk-RFZA7PSM.js";
117
110
  import {
118
111
  REPAIR_CLAUSE
119
- } from "./chunk-X5ZBP3IY.js";
112
+ } from "./chunk-JUUBBBY5.js";
120
113
  import {
121
- hasCode
122
- } from "./chunk-2I4QTOLB.js";
114
+ askText,
115
+ selectOne
116
+ } from "./chunk-GH5UKMZD.js";
123
117
  import {
124
- MAX_AUTO_SPEND_FLOOR_ATOMIC,
125
- MAX_AUTO_SPEND_FLOOR_WHY,
126
- loadRawConfig
127
- } from "./chunk-2M2VPI2E.js";
118
+ hasRuntime,
119
+ isNewer,
120
+ runtimeBuild
121
+ } from "./chunk-5N4GGUBN.js";
128
122
  import {
129
- PRODUCTION_ORIGIN,
130
- isSameDeployment
131
- } from "./chunk-XQJXNMSB.js";
123
+ resolveContextSettings
124
+ } from "./chunk-DTEWAVNE.js";
125
+ import {
126
+ loadRawConfig
127
+ } from "./chunk-UIB33QQP.js";
132
128
  import {
133
129
  writeFileAtomic
134
130
  } from "./chunk-7WEQQJLG.js";
135
131
  import {
136
- CliError
137
- } from "./chunk-3UCIG4TG.js";
132
+ hasCode
133
+ } from "./chunk-3MZ7DYRO.js";
134
+ import {
135
+ defaultDataDir,
136
+ isDefaultDataDir,
137
+ realOr,
138
+ runtimeDir,
139
+ samePath,
140
+ tilde
141
+ } from "./chunk-JTX3BUDK.js";
138
142
  import {
139
- runtimeBuild,
140
- runtimeStatePath
141
- } from "./chunk-ZNNXRNFD.js";
143
+ ROUTE_PAID_PATH
144
+ } from "./chunk-ZEYA2WWX.js";
142
145
  import {
143
- isNewer
144
- } from "./chunk-EDJWHDDL.js";
146
+ httpRequest
147
+ } from "./chunk-D6M3ZK66.js";
145
148
  import {
146
- defaultDataDir,
147
- runtimeDir
148
- } from "./chunk-OJNTCYQQ.js";
149
+ PRODUCTION_ORIGIN,
150
+ isSameDeployment
151
+ } from "./chunk-CRG54LEB.js";
152
+ import {
153
+ CliError
154
+ } from "./chunk-DI4QAGRZ.js";
155
+ import {
156
+ package_default
157
+ } from "./chunk-3Y2EHT4F.js";
158
+ import {
159
+ envProxySupported,
160
+ proxyNodeStep,
161
+ proxySkipped,
162
+ proxyVariable
163
+ } from "./chunk-4CE6TMI5.js";
149
164
 
150
- // src/commands/update.ts
151
- import { spawn } from "node:child_process";
152
- import { existsSync as existsSync2, statSync } from "node:fs";
153
- import { rm as rm2 } from "node:fs/promises";
165
+ // src/router/install.ts
166
+ import { readFile as readFile5, stat as stat3 } from "node:fs/promises";
154
167
  import { homedir as homedir2 } from "node:os";
155
- import { resolve as resolve2, sep as sep2 } from "node:path";
168
+ import { dirname as dirname3, isAbsolute, join as join5, relative, resolve as resolve2, sep as sep2 } from "node:path";
156
169
  import { fileURLToPath as fileURLToPath3 } from "node:url";
157
170
 
158
- // src/router/install.ts
159
- import { existsSync } from "node:fs";
160
- import { readFile as readFile3, realpath, stat as stat3 } from "node:fs/promises";
161
- import { homedir } from "node:os";
162
- import { dirname as dirname3, isAbsolute, join as join4, relative, resolve, sep } from "node:path";
163
- import { fileURLToPath as fileURLToPath2 } from "node:url";
164
-
165
171
  // src/lib/skill-placement.ts
166
172
  import { lstatSync } from "node:fs";
167
- import { readdir, rm, rmdir } from "node:fs/promises";
173
+ import { constants, open, readdir, rm, rmdir } from "node:fs/promises";
168
174
  import { dirname, join } from "node:path";
175
+ var RETIRED_SKILL_NAMES = ["tenjin-pay", "tenjin-search", "tenjin-publish"];
176
+ var SHIPPED_SKILL_FILES = {
177
+ "tenjin-pay": ["SKILL.md"],
178
+ "tenjin-search": ["SKILL.md", "references/permissions.md"],
179
+ "tenjin-publish": ["SKILL.md", "references/maintain.md"]
180
+ };
181
+ function skillsDirsFor(home) {
182
+ return [join(home, ".claude", "skills"), join(home, ".agents", "skills")];
183
+ }
169
184
  function isRealDirectory(path) {
170
185
  try {
171
186
  return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
@@ -174,6 +189,35 @@ function isRealDirectory(path) {
174
189
  throw err;
175
190
  }
176
191
  }
192
+ async function readSkillFile(path) {
193
+ let handle;
194
+ try {
195
+ handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
196
+ } catch (err) {
197
+ if (hasCode(err, "ENOENT")) return { kind: "absent" };
198
+ return { kind: "unreadable", err };
199
+ }
200
+ try {
201
+ if (!(await handle.stat()).isFile()) return { kind: "not-regular" };
202
+ return { kind: "ok", bytes: await handle.readFile() };
203
+ } catch (err) {
204
+ return { kind: "unreadable", err };
205
+ } finally {
206
+ await handle.close().catch(() => void 0);
207
+ }
208
+ }
209
+ function skillFrontmatterName(skillMd) {
210
+ const lines2 = skillMd.replace(/^\uFEFF/, "").split(/\r?\n/);
211
+ const start = lines2.findIndex((l) => l.trim().length > 0);
212
+ if (start === -1 || lines2[start]?.trim() !== "---") return null;
213
+ const end = lines2.findIndex((l, i) => i > start && l.trim() === "---");
214
+ if (end === -1) return null;
215
+ for (const line of lines2.slice(start + 1, end)) {
216
+ const m = /^name:\s*(.+?)\s*$/.exec(line);
217
+ if (m !== null) return (m[1] ?? "").replace(/^["']|["']$/g, "");
218
+ }
219
+ return null;
220
+ }
177
221
  async function removeOwnedSkill(name, skillsDir) {
178
222
  if (!isRealDirectory(skillsDir)) {
179
223
  return { changed: false };
@@ -208,17 +252,102 @@ async function removeRetiredSkills(home, project) {
208
252
  const removed = [];
209
253
  const dirs = [...skillsDirsFor(home), ...project ? skillsDirsFor(project) : []];
210
254
  for (const dir of new Set(dirs)) {
211
- for (const name of [...RETIRED_SKILL_NAMES, ...CLI_SKILL_NAMES]) {
255
+ for (const name of RETIRED_SKILL_NAMES) {
212
256
  if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));
213
257
  }
214
258
  }
215
259
  return removed;
216
260
  }
217
261
 
262
+ // src/router/claude-install.ts
263
+ import { readFile as readFile4 } from "node:fs/promises";
264
+ import { join as join4 } from "node:path";
265
+
218
266
  // src/router/legacy-install.ts
219
- import { readFile, stat } from "node:fs/promises";
267
+ import { readFile as readFile2, stat } from "node:fs/promises";
220
268
  import { join as join2 } from "node:path";
221
269
 
270
+ // src/router/hooks-file.ts
271
+ import { lstat, readFile, realpath } from "node:fs/promises";
272
+ async function inspectHooksFile(declaredPath) {
273
+ const entry = await lstat(declaredPath).catch(() => null);
274
+ let path = declaredPath;
275
+ if (entry !== null) {
276
+ try {
277
+ path = await realpath(declaredPath);
278
+ } catch (err) {
279
+ return {
280
+ refusal: {
281
+ reason: "unresolvable",
282
+ path: declaredPath,
283
+ message: `${declaredPath} could not be resolved (${err.message}); its "hooks" key was left exactly as it is.`
284
+ }
285
+ };
286
+ }
287
+ }
288
+ let settings = {};
289
+ let raw = null;
290
+ if (entry !== null) {
291
+ try {
292
+ raw = await readFile(path, "utf8");
293
+ } catch (err) {
294
+ return {
295
+ refusal: {
296
+ reason: "unreadable",
297
+ path,
298
+ message: `${path} could not be read (${err.message}); no hooks were registered.`
299
+ }
300
+ };
301
+ }
302
+ let parsed;
303
+ try {
304
+ parsed = JSON.parse(raw);
305
+ } catch (err) {
306
+ return {
307
+ refusal: {
308
+ reason: "unparsable",
309
+ path,
310
+ message: `${path} is not valid JSON (${err.message}); its "hooks" key was left exactly as it is.`
311
+ }
312
+ };
313
+ }
314
+ if (!isRecord(parsed)) {
315
+ return {
316
+ refusal: {
317
+ reason: "unexpected-shape",
318
+ path,
319
+ message: `${path} is not a JSON object; its "hooks" key was left exactly as it is.`
320
+ }
321
+ };
322
+ }
323
+ settings = parsed;
324
+ }
325
+ const hooksValue = settings.hooks;
326
+ if (hooksValue !== void 0 && !isRecord(hooksValue)) {
327
+ return {
328
+ refusal: {
329
+ reason: "unexpected-shape",
330
+ path,
331
+ message: `${path} has a "hooks" key that is not an object; its "hooks" key was left exactly as it is.`
332
+ }
333
+ };
334
+ }
335
+ const hooks = {};
336
+ for (const [event, list] of Object.entries(hooksValue ?? {})) {
337
+ if (!Array.isArray(list)) {
338
+ return {
339
+ refusal: {
340
+ reason: "unexpected-shape",
341
+ path,
342
+ message: `${path} has a "hooks.${event}" that is not an array of entries; its "hooks" key was left exactly as it is.`
343
+ }
344
+ };
345
+ }
346
+ hooks[event] = list;
347
+ }
348
+ return { path, raw, settings, hooks };
349
+ }
350
+
222
351
  // src/router/status-line-wiring.ts
223
352
  var STATUS_LINE_COMMAND = "tenjin status-line";
224
353
  var OUR_MARKER = STATUS_LINE_COMMAND;
@@ -253,11 +382,8 @@ function decomposeCommand(command) {
253
382
 
254
383
  // src/router/legacy-install.ts
255
384
  var LEGACY_COMMAND_RE = /^(\S*\/)?tenjin hook [a-z]+$/;
256
- function isPlainObject(value) {
257
- return typeof value === "object" && value !== null && !Array.isArray(value);
258
- }
259
385
  function ownsLegacyHandler(handler) {
260
- if (!isPlainObject(handler)) return false;
386
+ if (!isRecord(handler)) return false;
261
387
  if (handler.type === "mcp_tool") {
262
388
  return handler.server === LEGACY_MCP_SERVER_NAME && handler.tool === "hook";
263
389
  }
@@ -265,7 +391,7 @@ function ownsLegacyHandler(handler) {
265
391
  return typeof command === "string" && LEGACY_COMMAND_RE.test(command.trim());
266
392
  }
267
393
  function lookalike(handler) {
268
- if (!isPlainObject(handler) || ownsLegacyHandler(handler)) return null;
394
+ if (!isRecord(handler) || ownsLegacyHandler(handler)) return null;
269
395
  const command = handler.command;
270
396
  return typeof command === "string" && command.includes("tenjin hook") ? command : null;
271
397
  }
@@ -280,7 +406,7 @@ function classifyMcpEntry(entry) {
280
406
  async function readLegacyMcpEntry(path) {
281
407
  let raw;
282
408
  try {
283
- raw = await readFile(path, "utf8");
409
+ raw = await readFile2(path, "utf8");
284
410
  } catch (err) {
285
411
  const code = err.code;
286
412
  return code === "ENOENT" || code === "ENOTDIR" ? "absent" : "unreadable";
@@ -293,7 +419,7 @@ async function readLegacyMcpEntry(path) {
293
419
  }
294
420
  const servers = parsed?.mcpServers;
295
421
  if (servers === void 0) return "absent";
296
- if (!isPlainObject(servers)) return "unreadable";
422
+ if (!isRecord(servers)) return "unreadable";
297
423
  const entry = servers[LEGACY_MCP_SERVER_NAME];
298
424
  return entry === void 0 ? "absent" : classifyMcpEntry(entry);
299
425
  }
@@ -335,11 +461,11 @@ async function inspectLegacyInstall(settingsPath, mcpFile) {
335
461
  };
336
462
  }
337
463
  function handlersOf(entry) {
338
- return isPlainObject(entry) && Array.isArray(entry.hooks) ? entry.hooks : [];
464
+ return isRecord(entry) && Array.isArray(entry.hooks) ? entry.hooks : [];
339
465
  }
340
466
  function listOf(settings, key) {
341
467
  const permissions = settings.permissions;
342
- if (!isPlainObject(permissions)) return [];
468
+ if (!isRecord(permissions)) return [];
343
469
  const list = permissions[key];
344
470
  return Array.isArray(list) ? list : [];
345
471
  }
@@ -373,7 +499,7 @@ async function removeFromSettings(found, out) {
373
499
  }
374
500
  if (read.raw === null) return;
375
501
  const next = { ...read.settings };
376
- if (isPlainObject(read.settings.hooks)) {
502
+ if (isRecord(read.settings.hooks)) {
377
503
  const hooks = {};
378
504
  for (const [event, list] of Object.entries(read.hooks)) {
379
505
  const kept = [];
@@ -388,7 +514,7 @@ async function removeFromSettings(found, out) {
388
514
  }
389
515
  next.hooks = hooks;
390
516
  }
391
- if ((found.allowRule || found.denyRule) && isPlainObject(read.settings.permissions)) {
517
+ if ((found.allowRule || found.denyRule) && isRecord(read.settings.permissions)) {
392
518
  const permissions = { ...read.settings.permissions };
393
519
  if (found.allowRule && Array.isArray(permissions.allow)) {
394
520
  permissions.allow = permissions.allow.filter((r) => r !== LEGACY_REQUEST_TOOL);
@@ -403,7 +529,7 @@ async function removeFromSettings(found, out) {
403
529
  if (found.statusLine === "ours") {
404
530
  delete next.statusLine;
405
531
  out.statusLine = "removed";
406
- } else if (found.statusLine === "composed" && isPlainObject(read.settings.statusLine)) {
532
+ } else if (found.statusLine === "composed" && isRecord(read.settings.statusLine)) {
407
533
  const command = read.settings.statusLine.command;
408
534
  const original = typeof command === "string" ? decomposeCommand(command) : null;
409
535
  if (original !== null) {
@@ -416,7 +542,7 @@ async function removeFromSettings(found, out) {
416
542
  const body = `${JSON.stringify(next, null, 2)}
417
543
  `;
418
544
  const mode = await stat(read.path).then((s) => ({ mode: s.mode & 511 })).catch(() => ({}));
419
- if (await readFile(read.path, "utf8").catch(() => null) !== read.raw) {
545
+ if (await readFile2(read.path, "utf8").catch(() => null) !== read.raw) {
420
546
  out.warnings.push(`${read.path} changed while it was read, so it was left as it is`);
421
547
  Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: "kept" });
422
548
  return;
@@ -453,1794 +579,1770 @@ function projectMcpFile(cwd) {
453
579
  }
454
580
 
455
581
  // src/router/plugin-registration.ts
456
- import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
582
+ import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
457
583
  import { dirname as dirname2, join as join3 } from "node:path";
584
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
585
+
586
+ // src/commands/update.ts
587
+ import { spawn } from "node:child_process";
588
+ import { existsSync, statSync } from "node:fs";
589
+ import { rm as rm2 } from "node:fs/promises";
590
+ import { homedir } from "node:os";
591
+ import { resolve, sep } from "node:path";
458
592
  import { fileURLToPath } from "node:url";
459
- function folderFor(scope, env, home, cwd) {
460
- return pluginFolderPath(scope === "local" ? join3(cwd, ".claude") : claudeConfigDir(env, home));
593
+ var INSTALL_TIMEOUT_MS = 3e5;
594
+ var STAGE_TIMEOUT_MS = 12e4;
595
+ var NODE_TIMEOUT_MS = 3e5;
596
+ var BACKGROUND_COOLDOWN_MS = 24 * 60 * 6e4;
597
+ function resolveManager(manager, deps) {
598
+ const script = deps.managerScript !== void 0 ? deps.managerScript : resolveManagerScript(manager, process.execPath);
599
+ return script === null ? { cmd: MANAGERS[manager].bin, prefix: [] } : { cmd: process.execPath, prefix: [script] };
461
600
  }
462
- async function registerPlugin(opts) {
463
- const folder = folderFor(opts.scope, opts.env, opts.home, opts.cwd);
464
- const steps = [];
465
- let fallbackReason;
466
- if (opts.binary !== null) {
467
- const hosts = opts.hostsDir === void 0 ? await packageHostsDir() : opts.hostsDir;
468
- if (hosts === null) {
469
- fallbackReason = "this build carries no plugin marketplace folder (dist/hosts/claude)";
470
- } else {
471
- const done = await viaPluginCommands(opts.binary, hosts, opts, steps);
472
- if (done.ok) {
473
- const superseded = await removePluginFolder(folder);
474
- return {
475
- method: "plugin",
476
- id: PLUGIN_ID,
477
- scope: opts.scope,
478
- state: done.state,
479
- path: hosts,
480
- version: opts.version,
481
- steps,
482
- ...superseded.removed ? { supersededFolder: superseded } : {}
483
- };
484
- }
485
- fallbackReason = done.reason;
486
- }
487
- const existing = await existingCopy(opts.binary, opts.env, opts.home, opts.cwd);
488
- if (existing !== null) {
489
- return {
490
- method: "none",
491
- id: existing,
492
- scope: opts.scope,
493
- state: "failed",
494
- version: opts.version,
495
- steps,
496
- reason: `${fallbackReason}; ${existing} is already in Claude Code and was left as it is, so no second copy was written`
497
- };
498
- }
499
- } else {
500
- fallbackReason = "no claude binary on PATH or in CLAUDE_CODE_EXECPATH";
501
- if (await installedThroughCommands(opts.env, opts.home)) {
502
- return {
503
- method: "plugin",
504
- id: PLUGIN_ID,
505
- scope: opts.scope,
506
- state: "current",
507
- version: opts.version,
508
- steps,
509
- fallbackReason: `${fallbackReason}; ${PLUGIN_ID} is already registered, so it was left as it is`
510
- };
601
+ async function runUpdate(opts, ctx, deps = {}) {
602
+ if (opts.background !== true) return update(opts, ctx, deps);
603
+ const root = deps.runtimeRoot ?? runtimeDir(ctx.dataDir);
604
+ const [{ recordAutoUpdate }, { readRuntimeState }] = await Promise.all([
605
+ import("./auto-update-7L24KDWA.js"),
606
+ import("./runtime-layout-QHZQJV7C.js")
607
+ ]);
608
+ const from = readRuntimeState(root)?.current.cli;
609
+ const record = (r) => {
610
+ if (!existsSync(root)) return;
611
+ try {
612
+ recordAutoUpdate(root, { finishedAt: (/* @__PURE__ */ new Date()).toISOString(), ...r });
613
+ } catch {
511
614
  }
615
+ };
616
+ try {
617
+ const result = await update(opts, ctx, deps);
618
+ const d = result.data;
619
+ record(
620
+ d.skipped !== void 0 ? { outcome: "skipped", reason: d.skipped } : d.updated === true ? { outcome: "updated", from: d.current, to: d.latest } : { outcome: "current", from: d.current, to: d.current }
621
+ );
622
+ return result;
623
+ } catch (err) {
624
+ const reason = sanitizeForTerminal(err instanceof Error ? err.message : String(err)).trim();
625
+ record({
626
+ outcome: "failed",
627
+ ...from !== void 0 ? { from } : {},
628
+ reason: reason.slice(0, REASON_LIMIT)
629
+ });
630
+ throw err;
512
631
  }
513
- const written = await writePluginFolder(
514
- folder,
515
- renderPluginFiles(opts.version, opts.cliEntry ?? packageCliEntry(), {
516
- node: opts.node,
517
- mod: await packageMod(opts.hostsDir)
518
- })
519
- );
520
- if (written.state === "written") {
521
- return {
522
- method: "skills-dir",
523
- id: SKILLS_DIR_PLUGIN_ID,
524
- scope: opts.scope,
525
- state: "written",
526
- path: folder,
527
- version: opts.version,
528
- steps,
529
- fallbackReason
530
- };
632
+ }
633
+ async function update(opts, ctx, deps) {
634
+ const current = deps.currentVersion ?? package_default.version;
635
+ const channel = channelTag(current);
636
+ const moduleDir = deps.moduleDir ?? fileURLToPath(new URL(".", import.meta.url));
637
+ if (channel === null) {
638
+ throw new CliError("REFUSED", `tenjin-cli reports an unrecognizable version (${current})`, {
639
+ fix: "Reinstall a published build: npm i -g tenjin-cli"
640
+ });
531
641
  }
532
- return {
533
- method: "none",
534
- id: null,
535
- scope: opts.scope,
536
- state: "failed",
537
- path: folder,
538
- version: opts.version,
539
- steps,
540
- fallbackReason,
541
- reason: written.reason ?? "the plugin folder could not be written"
542
- };
543
- }
544
- async function viaPluginCommands(binary, hosts, opts, steps) {
545
- const run = (args) => runClaude(binary, args, { env: opts.env, cwd: opts.cwd });
546
- const scopeArgs = ["--scope", opts.scope];
547
- const marketplaceScope = opts.scope === "user" ? [] : scopeArgs;
548
- const known = await run(["plugin", "marketplace", "list", "--json"]);
549
- const listed = known.code === 0 ? jsonList(known.stdout) : null;
550
- steps.push({
551
- command: "claude plugin marketplace list --json",
552
- ok: listed !== null,
553
- ...listed === null ? { detail: commandDetail(known) } : {}
642
+ refuse(moduleDir, { check: opts.check, spec: null });
643
+ const tags = await fetchDistTags({
644
+ fetchImpl: deps.fetchImpl,
645
+ timeoutMs: ctx.flags.timeout
554
646
  });
555
- if (listed === null) {
647
+ if (tags === null) {
648
+ throw new CliError("NETWORK_ERROR", "Could not read tenjin-cli dist-tags from npm", {
649
+ fix: "Check access to registry.npmjs.org and retry"
650
+ });
651
+ }
652
+ const runtime = await runtimeHere(ctx, deps, moduleDir);
653
+ if (opts.background === true && runtime === null) {
556
654
  return {
557
- ok: false,
558
- reason: `claude plugin marketplace list could not be read (${commandDetail(known)}), so no marketplace was added or repointed`
655
+ data: { skipped: "no runtime" },
656
+ humanLines: ["Nothing to update in the background: Tenjin's runtime is not set up here."]
559
657
  };
560
658
  }
561
- const existing = listed.find((m) => m.name === MARKETPLACE_NAME);
562
- if (existing !== void 0 && !await ownMarketplace(existing)) {
659
+ const base = runtime?.current ?? current;
660
+ const latest = resolveTarget(base, tags);
661
+ if (latest === null) {
662
+ const raw = tags[channel];
663
+ throw raw === void 0 ? new CliError("RESOURCE_NOT_FOUND", "npm has no published tenjin-cli on the latest tag", {
664
+ fix: "Pick a version yourself: npm view tenjin-cli versions"
665
+ }) : new CliError(
666
+ "RESOURCE_NOT_FOUND",
667
+ // Registry-controlled: bounded here, escaped by the error emitter.
668
+ `npm's latest tenjin-cli (${raw.slice(0, 40)}) is not a version this build can read`,
669
+ {
670
+ fix: "Install it by name: npm i -g tenjin-cli@<version> (npm view tenjin-cli versions)"
671
+ }
672
+ );
673
+ }
674
+ const updateAvailable = isNewer(latest, base);
675
+ const data = (updated2) => ({
676
+ current: base,
677
+ latest,
678
+ updateAvailable,
679
+ updated: updated2
680
+ });
681
+ if (!updateAvailable) {
563
682
  return {
564
- ok: false,
565
- reason: `a marketplace named ${MARKETPLACE_NAME} that this CLI did not add is already configured, so it was left as it is`
683
+ data: data(false),
684
+ humanLines: [`tenjin-cli ${base} is up to date`]
566
685
  };
567
686
  }
568
- const add = await step(
569
- steps,
570
- ["plugin", "marketplace", "add", hosts, "--json", ...marketplaceScope],
571
- run
687
+ if (opts.check) {
688
+ return {
689
+ data: data(false),
690
+ humanLines: [
691
+ `tenjin-cli ${latest} is available (you have ${base}).`,
692
+ "Run tenjin update to install it."
693
+ ]
694
+ };
695
+ }
696
+ if (opts.background === true) {
697
+ const wait = await tooNewForBackground(latest, ctx, deps);
698
+ if (wait !== null) {
699
+ return {
700
+ data: { ...data(false), skipped: wait },
701
+ humanLines: [`${wait}; the background update takes a release a day after it is published.`]
702
+ };
703
+ }
704
+ }
705
+ if (runtime !== null) {
706
+ return runtimeUpdate(ctx, deps, { ...runtime, base, latest, current, moduleDir, data });
707
+ }
708
+ await refuseRuntimeElsewhere(ctx, moduleDir, deps.homeDir ?? homedir());
709
+ const spec = `tenjin-cli@${latest}`;
710
+ refuse(moduleDir, { check: false, spec });
711
+ const { checkReleaseProvenance } = await import("./runtime-provenance-MNJGVBV2.js");
712
+ await checkReleaseProvenance(latest, {
713
+ timeoutMs: ctx.flags.timeout,
714
+ fetchImpl: deps.fetchImpl
715
+ });
716
+ const human = ctx.io.isTTY && !ctx.flags.json;
717
+ let tail = "";
718
+ const onOutput = (chunk) => {
719
+ tail = (tail + chunk).slice(-2e3);
720
+ if (human) ctx.io.stderr.write(chunk.split("\n").map(sanitizeForTerminal).join("\n"));
721
+ };
722
+ const manager = classifyManager(moduleDir);
723
+ const plan = MANAGERS[manager];
724
+ const args = plan.args(spec);
725
+ const resolved = resolveManager(manager, deps);
726
+ const manual = `Run it yourself: ${plan.manual(spec)}`;
727
+ const outcome = await (deps.spawnImpl ?? spawnCapture)(
728
+ resolved.cmd,
729
+ [...resolved.prefix, ...args],
730
+ { cwd: homedir(), timeoutMs: INSTALL_TIMEOUT_MS },
731
+ onOutput
572
732
  );
573
- if (!add.ok) return { ok: false, reason: `claude plugin marketplace add failed: ${add.detail}` };
574
- const install = await step(steps, ["plugin", "install", PLUGIN_ID, ...scopeArgs, "--json"], run);
575
- if (!install.ok) return { ok: false, reason: `claude plugin install failed: ${install.detail}` };
576
- const installed = install.result?.installedVersion;
577
- const available = install.result?.availableVersion;
578
- if (typeof installed !== "string" || typeof available !== "string") {
579
- return { ok: true, state: "installed" };
733
+ if (outcome.kind === "start-failed") {
734
+ throw new CliError("UPDATE_FAILED", `Could not start ${manager}`, {
735
+ fix: manual,
736
+ cause: outcome.cause
737
+ });
580
738
  }
581
- if (installed === available) return { ok: true, state: "current" };
582
- const update2 = await step(steps, ["plugin", "update", PLUGIN_ID, ...scopeArgs, "--json"], run);
583
- if (!update2.ok) return { ok: false, reason: `claude plugin update failed: ${update2.detail}` };
584
- return { ok: true, state: "updated" };
585
- }
586
- function marketplaceAdded(reg, hosts) {
587
- const add = `claude plugin marketplace add ${hosts} `;
588
- return reg.steps.some((s) => s.ok && s.command.startsWith(add));
739
+ if (outcome.kind === "timeout") {
740
+ throw new CliError(
741
+ "UPDATE_FAILED",
742
+ `${manager} did not finish in ${INSTALL_TIMEOUT_MS / 1e3}s`,
743
+ { fix: manual, details: { output: tail } }
744
+ );
745
+ }
746
+ if (outcome.code !== 0) {
747
+ throw new CliError("UPDATE_FAILED", `${manager} ${args.join(" ")} exited ${outcome.code}`, {
748
+ // EACCES on a root-owned global prefix is the common cause; the operator
749
+ // fixing that themselves beats this CLI ever escalating.
750
+ fix: manual,
751
+ details: { output: tail }
752
+ });
753
+ }
754
+ emitWriteNotice(
755
+ ctx.io,
756
+ `tenjin update: replaced the global tenjin-cli with ${latest} via ${manager}`
757
+ );
758
+ const { refresh } = await refreshProfiles(ctx, deps, npmLaunch(deps));
759
+ return updated(deps, data(true), refresh, [`Updated tenjin-cli ${current} -> ${latest}.`]);
589
760
  }
590
- async function step(steps, args, run) {
591
- const out = await run(args);
592
- const result = jsonResult(out.stdout);
593
- const ok = out.code === 0 && (result === null || result.outcome === void 0 || result.outcome === "ok");
594
- const detail = commandDetail(out, result);
595
- steps.push({ command: `claude ${args.join(" ")}`, ok, ...ok ? {} : { detail } });
596
- return { ok, detail, result };
761
+ async function updated(deps, data, refresh, head, version) {
762
+ const servers = await readMcpServers(deps, {
763
+ settingsInstallPending: refresh.settingsInstallPending,
764
+ ...version !== void 0 ? { version } : {}
765
+ });
766
+ return {
767
+ data: { ...data, refresh, mcpServer: servers.check },
768
+ humanLines: [
769
+ ...head,
770
+ ...refreshLines(refresh),
771
+ ...projectLines(refresh),
772
+ ...refresh.notices,
773
+ ...servers.stale > 0 ? [`! ${servers.check.detail}. ${servers.check.fix ?? ""}`.trim()] : []
774
+ ]
775
+ };
597
776
  }
598
- function commandDetail(out, result = null) {
599
- if (typeof result?.message === "string") return result.message;
600
- const text = (out.stderr || out.stdout).trim().slice(0, 300);
601
- if (text.length > 0) return text;
602
- return out.code === null ? "the command could not be run" : `exit ${out.code}`;
777
+ async function runtimeHere(ctx, deps, moduleDir) {
778
+ if (!isDefaultDataDir(ctx.dataDir, deps.homeDir ?? homedir())) return null;
779
+ const { readRuntimeState, runtimeBuild: runtimeBuild2 } = await import("./runtime-layout-QHZQJV7C.js");
780
+ const root = deps.runtimeRoot ?? runtimeDir(ctx.dataDir);
781
+ const state = readRuntimeState(root);
782
+ const inRuntime = runtimeBuild2(moduleDir) !== null;
783
+ if (state === null && !inRuntime) return null;
784
+ return { root, current: state?.current.cli ?? null, inRuntime };
603
785
  }
604
- async function ownMarketplace(row) {
605
- const path = typeof row.path === "string" ? row.path : void 0;
606
- if (row.source !== "directory" || path === void 0) return false;
607
- if (await stat2(path).catch(() => null) === null) {
608
- return /tenjin-cli[\\/]dist[\\/]hosts[\\/]claude$/.test(path) || /[\\/]runtime[\\/]claude$/.test(path);
786
+ async function tooNewForBackground(latest, ctx, deps) {
787
+ const answer = await fetchPublishTime(latest, {
788
+ fetchImpl: deps.fetchImpl,
789
+ timeoutMs: ctx.flags.timeout
790
+ });
791
+ if (answer === null) {
792
+ throw new CliError("NETWORK_ERROR", `Could not read when tenjin-cli ${latest} was published`, {
793
+ fix: "Check access to registry.npmjs.org and retry"
794
+ });
609
795
  }
610
- return await inspectPluginFolder(join3(path, PLUGIN_DIR)) === "ours";
796
+ if (answer.publishedAt === null) return `npm names no publish time for tenjin-cli ${latest}`;
797
+ const age = (deps.now ?? Date.now)() - answer.publishedAt;
798
+ return age >= BACKGROUND_COOLDOWN_MS ? null : `tenjin-cli ${latest} was published under 24 hours ago`;
611
799
  }
612
- async function existingCopy(binary, env, home, cwd) {
613
- const out = await runClaude(binary, ["plugin", "list", "--json"], { env, cwd });
614
- const listed = out.code === 0 ? jsonList(out.stdout) : null;
615
- if (listed === null) return await installedThroughCommands(env, home) ? PLUGIN_ID : null;
616
- const row = listed.find(
617
- (p) => typeof p.id === "string" && p.id.startsWith(`${PLUGIN_NAME}@`) && p.id !== SKILLS_DIR_PLUGIN_ID && p.enabled === true
800
+ async function refuseRuntimeElsewhere(ctx, moduleDir, home) {
801
+ const { runtimeBuild: runtimeBuild2 } = await import("./runtime-layout-QHZQJV7C.js");
802
+ if (runtimeBuild2(moduleDir) === null) return;
803
+ throw new CliError(
804
+ "REFUSED",
805
+ `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`,
806
+ {
807
+ 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`."
808
+ }
618
809
  );
619
- return typeof row?.id === "string" ? row.id : null;
620
810
  }
621
- async function recordedInstalls(env, home) {
622
- let raw;
623
- try {
624
- raw = await readFile2(
625
- join3(claudeConfigDir(env, home), "plugins", "installed_plugins.json"),
626
- "utf8"
627
- );
628
- } catch (err) {
629
- return hasCode(err, "ENOENT") ? [] : null;
811
+ async function runtimeUpdate(ctx, deps, o) {
812
+ const { root, base, latest } = o;
813
+ const [rt, layout] = await Promise.all([
814
+ import("./runtime-place-4POL4KK4.js"),
815
+ import("./runtime-layout-QHZQJV7C.js")
816
+ ]);
817
+ const stays = `so ${base} stays`;
818
+ let stage;
819
+ if (latest === o.current && !o.inRuntime) {
820
+ const packageRoot = rt.packageRootOf(o.moduleDir);
821
+ if (packageRoot === null) {
822
+ throw new CliError(
823
+ "UPDATE_FAILED",
824
+ `tenjin-cli ${latest} cannot find its own package, ${stays}`,
825
+ {
826
+ fix: RUNTIME_MISSING_FIX
827
+ }
828
+ );
829
+ }
830
+ stage = await rt.stageSelf(root, packageRoot);
831
+ } else {
832
+ stage = await (deps.stage ?? rt.stageTarball)(root, latest, {
833
+ timeoutMs: STAGE_TIMEOUT_MS,
834
+ fetchImpl: deps.fetchImpl
835
+ }).catch((err) => {
836
+ throw proxyNamed(err, deps);
837
+ });
630
838
  }
631
- let plugins;
839
+ let node;
632
840
  try {
633
- plugins = JSON.parse(raw).plugins;
634
- } catch {
635
- return null;
636
- }
637
- if (typeof plugins !== "object" || plugins === null || Array.isArray(plugins)) return null;
638
- const entries = plugins[PLUGIN_ID];
639
- if (!Array.isArray(entries)) return [];
640
- const records = [];
641
- for (const entry of entries) {
642
- if (typeof entry !== "object" || entry === null) continue;
643
- const { scope, projectPath } = entry;
644
- if (scope === "user") records.push({ scope, projectPath: null });
645
- else if (scope === "local" && typeof projectPath === "string" && projectPath.length > 0) {
646
- records.push({ scope, projectPath });
841
+ const pin = rt.readNodePin(stage);
842
+ if (pin === null) {
843
+ throw new CliError("UPDATE_FAILED", `tenjin-cli ${latest} carries no Node pin, ${stays}`, {
844
+ fix: `Nothing to do: ${base} keeps running. Run \`tenjin update\` again after the next release.`
845
+ });
647
846
  }
847
+ node = await (deps.ensure ?? rt.ensureNode)(root, pin, {
848
+ timeoutMs: NODE_TIMEOUT_MS,
849
+ fetchImpl: deps.fetchImpl
850
+ });
851
+ await (deps.place ?? rt.placeVersion)(root, stage, latest);
852
+ } catch (err) {
853
+ await rm2(stage, { recursive: true, force: true }).catch(() => void 0);
854
+ throw proxyNamed(err, deps);
648
855
  }
649
- return records;
650
- }
651
- async function installedThroughCommands(env, home) {
652
- try {
653
- const raw = await readFile2(
654
- join3(claudeConfigDir(env, home), "plugins", "installed_plugins.json"),
655
- "utf8"
656
- );
657
- const plugins = JSON.parse(raw).plugins;
658
- return plugins !== null && typeof plugins === "object" && PLUGIN_ID in plugins;
659
- } catch {
660
- return false;
856
+ const home = deps.homeDir ?? homedir();
857
+ emitWriteNotice(ctx.io, `tenjin update: staged tenjin-cli ${latest} in ${tilde(root, home)}`);
858
+ const { refresh, homeTail } = await refreshProfiles(ctx, deps, {
859
+ node,
860
+ entry: layout.versionEntry(root, latest)
861
+ });
862
+ if (layout.readRuntimeState(root)?.current.cli !== latest) {
863
+ throw new CliError("UPDATE_FAILED", `tenjin-cli ${latest} did not pass its checks, ${stays}`, {
864
+ fix: "Run `tenjin update` again; if it fails again, run `tenjin doctor`",
865
+ details: {
866
+ reason: refresh.failed[0]?.reason ?? runtimeReason(envelopeData(homeTail)) ?? "The new version did not switch the runtime to itself.",
867
+ output: homeTail.slice(-2e3)
868
+ }
869
+ });
661
870
  }
871
+ return updated(
872
+ deps,
873
+ o.data(true),
874
+ refresh,
875
+ [
876
+ `Updated tenjin-cli ${base} -> ${latest}.`,
877
+ `The previous version (${base}) stays as the fallback.`
878
+ ],
879
+ latest
880
+ );
662
881
  }
663
- async function packageHostsDir(moduleDir = dirname2(fileURLToPath(import.meta.url))) {
664
- const catalog = join3(moduleDir, "hosts", "claude", ".claude-plugin", "marketplace.json");
665
- const stable = versionFreeEntry(catalog) ?? catalog;
666
- if ((await stat2(stable).catch(() => null))?.isFile() !== true) return null;
667
- return dirname2(dirname2(stable));
668
- }
669
- async function packageMod(hostsDir) {
670
- const hosts = hostsDir === void 0 ? await packageHostsDir() : hostsDir;
671
- return hosts === null ? void 0 : readModSources(join3(hosts, PLUGIN_DIR));
882
+ function proxyNamed(err, deps) {
883
+ if (!(err instanceof CliError) || err.code !== "NETWORK_ERROR") return err;
884
+ const skipped = proxySkipped(process.env, deps.proxySupported);
885
+ if (skipped === null) return err;
886
+ const step2 = proxyNodeStep("tenjin update");
887
+ return new CliError("NETWORK_ERROR", `${err.message}: ${skipped}`, {
888
+ fix: `${step2.charAt(0).toUpperCase()}${step2.slice(1)}.`,
889
+ cause: err
890
+ });
672
891
  }
673
- function packageCliEntry(moduleDir = dirname2(fileURLToPath(import.meta.url))) {
674
- const entry = join3(moduleDir, "index.js");
675
- return versionFreeEntry(entry) ?? entry;
892
+ function runtimeReason(data) {
893
+ const reason = data?.runtime?.reason;
894
+ if (typeof reason !== "string") return void 0;
895
+ const text = sanitizeForTerminal(reason).trim();
896
+ return text.length > 0 ? text.slice(0, REASON_LIMIT) : void 0;
676
897
  }
677
- async function readPluginListing(binary, env, cwd) {
678
- const out = await runClaude(binary, ["plugin", "list", "--json"], { env, cwd });
679
- const rows = out.code === 0 ? jsonList(out.stdout) : null;
680
- if (rows === null) {
681
- return { id: null, enabled: false, version: null, read: false, scope: null, projects: [] };
898
+ var REFRESH_TIMEOUT_MS = 6e4;
899
+ async function refreshProfiles(ctx, deps, launch) {
900
+ const home = deps.homeDir ?? homedir();
901
+ const dataDir = ctx.dataDir;
902
+ const fix = manualFix(dataDir, home, dataDir);
903
+ const nothing = (reason) => ({
904
+ refresh: {
905
+ profiles: [],
906
+ failed: [{ dataDir, reason, fix }],
907
+ notices: [],
908
+ settingsInstallPending: false,
909
+ projects: [],
910
+ projectsFailed: []
911
+ },
912
+ homeTail: ""
913
+ });
914
+ if (launch === null)
915
+ return nothing("This build has no entry the update could safely re-execute.");
916
+ if (!isExistingDir(dataDir)) return nothing("It is not a directory.");
917
+ const profiles = [dataDir];
918
+ const failed = [];
919
+ const notices = [];
920
+ let settingsInstallPending = false;
921
+ const heard = (reported) => {
922
+ for (const notice of noticesOf(reported)) if (!notices.includes(notice)) notices.push(notice);
923
+ const migration = reported?.migration;
924
+ if (migration?.state === "pending" || migration?.state === "blocked") {
925
+ settingsInstallPending = true;
926
+ }
927
+ };
928
+ const { outcome, tail: homeTail } = await refreshChild(launch, homedir(), dataDir, deps);
929
+ if (outcome.kind !== "exit" || outcome.code !== 0) {
930
+ failed.push({ dataDir, reason: refreshReason(outcome, homeTail), fix });
931
+ } else {
932
+ heard(envelopeData(homeTail));
682
933
  }
683
- const projects = rows.filter(
684
- (r) => r.id === PLUGIN_ID && r.enabled !== true && typeof r.projectPath === "string" && r.projectPath.length > 0
685
- ).map((r) => r.projectPath);
686
- const row = rows.find((r) => r.id === PLUGIN_ID && r.enabled === true) ?? rows.find((r) => r.id === SKILLS_DIR_PLUGIN_ID && r.enabled === true) ?? rows.find((r) => r.id === PLUGIN_ID || r.id === SKILLS_DIR_PLUGIN_ID);
687
- if (row === void 0) {
688
- return { id: null, enabled: false, version: null, read: true, scope: null, projects };
934
+ const projects = [];
935
+ const projectsFailed = [];
936
+ const recorded = (await loadRawConfig(dataDir).catch(() => null))?.install?.routerProjects ?? [];
937
+ for (const project of recorded) {
938
+ const forget = () => persistRouterProject(dataDir, project, false).catch(() => void 0);
939
+ if (!isExistingDir(project) || !await projectInstallAt(project, home, process.env)) {
940
+ await forget();
941
+ continue;
942
+ }
943
+ const { outcome: outcome2, tail } = await refreshChild(launch, project, dataDir, deps, ["--project"]);
944
+ if (outcome2.kind !== "exit" || outcome2.code !== 0) {
945
+ projectsFailed.push({
946
+ project,
947
+ reason: refreshReason(outcome2, tail),
948
+ fix: `Run \`tenjin install --project\` in ${project}.`
949
+ });
950
+ continue;
951
+ }
952
+ projects.push(project);
953
+ heard(envelopeData(tail));
689
954
  }
690
955
  return {
691
- id: String(row.id),
692
- enabled: row.enabled === true,
693
- version: typeof row.version === "string" ? row.version : null,
694
- read: true,
695
- scope: typeof row.scope === "string" ? row.scope : null,
696
- projects
956
+ refresh: { profiles, failed, notices, settingsInstallPending, projects, projectsFailed },
957
+ homeTail
697
958
  };
698
959
  }
699
- async function folderState(scope, env, home, cwd) {
700
- const path = folderFor(scope, env, home, cwd);
701
- return { path, state: await inspectPluginFolder(path) };
960
+ function npmLaunch(deps) {
961
+ const entry = versionFreeEntry(deps.refreshCommand ?? process.argv[1]);
962
+ return entry === null ? null : { node: process.execPath, entry };
702
963
  }
703
-
704
- // src/router/reachability.ts
705
- async function probeRouter(baseUrl, opts) {
706
- const fail = (detail, fix) => ({
707
- name: "router",
708
- status: "fail",
709
- required: true,
710
- detail,
711
- fix
712
- });
713
- let url;
714
- try {
715
- url = new URL(ROUTER_PATH, baseUrl).toString();
716
- } catch {
717
- return fail(
718
- `the base URL ${JSON.stringify(baseUrl)} is not a URL`,
719
- `Check TENJIN_BASE_URL, or set it with \`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\`.`
720
- );
721
- }
722
- const host = new URL(url).host;
723
- const probe = await httpRequest(url, {
724
- method: "POST",
725
- timeoutMs: opts.timeoutMs,
726
- blockRedirects: true,
727
- // A reachability check, not use: it must not count this machine as an install.
728
- anonymous: true,
729
- jsonBody: {},
730
- ...opts.fetchImpl !== void 0 ? { fetchImpl: opts.fetchImpl } : {}
731
- });
732
- const production = isSameDeployment(new URL(url).origin, PRODUCTION_ORIGIN);
733
- const checkBase = production ? "Try again later." : "Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.";
734
- const env = opts.env ?? process.env;
735
- const network = networkFix(host, env, production, opts.proxySupported ?? envProxySupported());
736
- const credentials = proxyCredentialsFix(env);
737
- const unreached = production ? network : checkBase;
738
- if (!probe.ok) {
739
- const t = probe.transport;
740
- if (t?.layer === "proxy" && t.proxyStatus === 407) {
741
- return fail(
742
- `a proxy between this machine and ${host} asked for its own credentials (407)`,
743
- credentials
744
- );
745
- }
746
- if (t?.layer === "proxy") {
747
- return fail(
748
- `a proxy refused the connection to ${host} (${t.proxyStatus}), so the router never answered`,
749
- unreached
750
- );
751
- }
752
- if (t?.layer === "dns") {
753
- return fail(`${host} did not resolve (${t.code}), so the router was not reached`, unreached);
754
- }
755
- if (t?.layer === "tls") {
756
- return fail(
757
- `the TLS connection to ${host} failed (${t.code}). A proxy that inspects TLS causes this`,
758
- `If this network inspects TLS, set NODE_EXTRA_CA_CERTS to its CA certificate. ${unreached}`
759
- );
760
- }
761
- if (t?.layer === "connect") {
762
- return fail(`could not connect to ${host} (${t.code})`, unreached);
763
- }
764
- return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, unreached);
765
- }
766
- if (probe.status === 200 || probe.status === 400 || probe.status === 429) {
767
- return { name: "router", status: "ok", required: true, detail: `${url} is live` };
768
- }
769
- if (probe.status === 404) {
770
- return fail(`the router is not enabled at ${url}`, checkBase);
771
- }
772
- if (probe.status === 407) {
773
- return fail(
774
- `a proxy between this machine and ${host} asked for its own credentials (407)`,
775
- credentials
776
- );
777
- }
778
- if (probe.status === 401 || probe.status === 403) {
779
- if (!fromDeployment(probe)) {
780
- return fail(
781
- `${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`,
782
- network
783
- );
964
+ async function refreshChild(launch, cwd, dataDir, deps, flags = []) {
965
+ let tail = "";
966
+ const outcome = await (deps.spawnImpl ?? spawnCapture)(
967
+ launch.node,
968
+ [launch.entry, "install", "--refresh", ...flags],
969
+ {
970
+ cwd,
971
+ timeoutMs: REFRESH_TIMEOUT_MS,
972
+ // TENJIN_DATA_DIR aims the child at this profile; the nudge opt-out is
973
+ // what keeps it from touching any other file in there (lib/update-check).
974
+ env: { TENJIN_DATA_DIR: dataDir, [NUDGE_OPT_OUT]: "1" }
975
+ },
976
+ (chunk) => {
977
+ tail = (tail + chunk).slice(-REFRESH_TAIL_LIMIT);
784
978
  }
785
- if (production) {
786
- return fail(`${url} refused this machine (${probe.status})`, checkBase);
979
+ );
980
+ return { outcome, tail };
981
+ }
982
+ function envelopeData(output) {
983
+ const lines2 = output.split("\n");
984
+ for (let i = lines2.length - 1; i >= 0; i -= 1) {
985
+ if (lines2[i]?.trim() !== "{" && !lines2[i]?.trim().startsWith('{"')) continue;
986
+ try {
987
+ const parsed = JSON.parse(lines2.slice(i).join("\n"));
988
+ if (parsed?.ok === true && parsed.data !== null && typeof parsed.data === "object") {
989
+ return parsed.data;
990
+ }
991
+ } catch {
992
+ continue;
787
993
  }
788
- return fail(
789
- `${url} is not a Tenjin router (it asked for credentials)`,
790
- `Set the router URL with \`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\`.`
791
- );
792
- }
793
- if (probe.status >= 500) {
794
- return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);
795
994
  }
796
- return fail(
797
- `${url} answered ${probe.status}, which a Tenjin router does not`,
798
- "Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`)."
799
- );
995
+ return null;
800
996
  }
801
- function fromDeployment(probe) {
802
- return probe.header("x-vercel-id") !== void 0 || probe.header("x-request-id") !== void 0;
803
- }
804
- function networkFix(host, env, production, proxySupported) {
805
- const proxy = proxyVariable(env);
806
- const config = production ? " Tenjin's own config is correct and needs no change." : "";
807
- if (proxy !== void 0 && !proxySupported) {
808
- 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}`;
809
- }
810
- const via = proxy !== void 0 ? ` (this shell sets ${proxy})` : "";
811
- return `Allow ${host} through your proxy, firewall or VPN${via}, or run from a network that reaches it.${config}`;
812
- }
813
- function proxyCredentialsFix(env) {
814
- const proxy = proxyVariable(env) ?? "HTTPS_PROXY";
815
- return `Put the proxy's credentials in ${proxy} (\`http://user:password@proxy:port\`), then try again.`;
816
- }
817
-
818
- // src/router/install.ts
819
- var DISCLOSURE = [
820
- "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 your assistant calls the free library docs lookup, its query goes to Tenjin's docs lookup, which asks Context7.",
821
- "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.",
822
- "What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere."
823
- ];
824
- var NEW_SESSION_STEP = "start a new Claude Code session so Tenjin loads";
825
- var RELOAD_STEP = "run `/reload-plugins` in this conversation so Tenjin loads, then continue your task";
826
- function loadStep(settingsInstallPresent, env = {}, command = "tenjin") {
827
- if (env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop" || env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop-3p") {
828
- return `choose New session in Claude Desktop's Code tab for this same folder so Tenjin loads. Before switching, give the person one short ready-to-paste continuation prompt filled with this conversation's task, progress and next action; carry over the person's funding and spending choices, and have the next session check Tenjin with \`${command} doctor\`${process.platform === "win32" ? " in PowerShell" : ""} before continuing`;
829
- }
830
- return settingsInstallPresent ? NEW_SESSION_STEP : RELOAD_STEP;
997
+ function noticesOf(data) {
998
+ const raw = data?.notices;
999
+ if (!Array.isArray(raw)) return [];
1000
+ return raw.filter((n) => typeof n === "string").map((n) => sanitizeForTerminal(n).trim().slice(0, REASON_LIMIT)).filter((n) => n.length > 0).slice(0, 5);
831
1001
  }
832
- function settingsInstallPaths(project, env, home, cwd) {
833
- return project ? {
834
- settingsPath: join4(cwd, ".claude", "settings.json"),
835
- mcpFile: projectMcpFile(cwd),
836
- mcpScope: "project"
837
- } : {
838
- settingsPath: userSettingsPath(env, home),
839
- mcpFile: userMcpFile(env, home),
840
- mcpScope: "user"
841
- };
1002
+ var REFRESH_TAIL_LIMIT = 64e3;
1003
+ var REASON_LIMIT = 300;
1004
+ function refreshReason(outcome, output) {
1005
+ const reported = envelopeMessage(output);
1006
+ if (reported !== void 0) return reported;
1007
+ if (outcome.kind === "timeout") return `It did not finish in ${REFRESH_TIMEOUT_MS / 1e3}s.`;
1008
+ if (outcome.kind === "start-failed") return "The refresh could not be started.";
1009
+ return `The refresh exited ${outcome.code} without reporting a reason.`;
842
1010
  }
843
- async function pluginProof(claude, dataDir, env, cwd) {
844
- if (claude.binary !== null && !claude.meetsFloor) {
845
- return {
846
- proven: false,
847
- reason: `Claude Code ${claude.version ?? "(unknown)"} is older than the plugin needs`
848
- };
849
- }
850
- if (claude.binary !== null) {
851
- const listing = await readPluginListing(claude.binary, env, cwd);
852
- if (!listing.enabled) {
853
- return { proven: false, reason: "Claude Code does not list the plugin as enabled yet" };
1011
+ function envelopeMessage(output) {
1012
+ const lines2 = output.split("\n");
1013
+ for (let i = lines2.length - 1; i >= 0; i -= 1) {
1014
+ const line = lines2[i]?.trim();
1015
+ if (line === void 0 || !line.startsWith("{")) continue;
1016
+ let parsed;
1017
+ try {
1018
+ parsed = JSON.parse(lines2.slice(i).join("\n"));
1019
+ } catch {
1020
+ continue;
854
1021
  }
1022
+ if (parsed?.ok !== false || typeof parsed.error?.message !== "string") continue;
1023
+ const message = sanitizeForTerminal(parsed.error.message).trim();
1024
+ if (message.length > 0) return message.slice(0, REASON_LIMIT);
855
1025
  }
856
- if (await readAliveStamp(dataDir) === null) {
857
- return {
858
- proven: false,
859
- reason: "the plugin has not loaded in a Claude Code session on this machine yet"
860
- };
861
- }
862
- return { proven: true };
1026
+ return void 0;
863
1027
  }
864
- async function migrateSettingsInstall(legacy, claude, opts) {
865
- if (!legacy.present) return { state: "none", settingsPath: legacy.settingsPath };
866
- const proof = await pluginProof(claude, opts.dataDir, opts.env, opts.cwd);
867
- if (!proof.proven) {
868
- return { state: "pending", settingsPath: legacy.settingsPath, reason: proof.reason };
869
- }
870
- const removed = await removeLegacyInstall(legacy, {
871
- binary: claude.binary,
872
- env: opts.env,
873
- cwd: opts.cwd,
874
- mcpScope: opts.mcpScope
875
- });
876
- return { state: "done", settingsPath: legacy.settingsPath, removed };
1028
+ function isExistingDir(path) {
1029
+ return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
877
1030
  }
878
- async function projectInstallHere(cwd, home, env) {
879
- if (await isHome(cwd, home)) return false;
880
- return projectInstallAt(cwd, home, env);
1031
+ function manualFix(dataDir, home, invoking) {
1032
+ const bare = isDefaultDataDir(dataDir, home) && resolve(dataDir) === resolve(invoking);
1033
+ const command = bare ? "tenjin install" : `TENJIN_DATA_DIR=${dataDir} tenjin install`;
1034
+ return `Run \`${command}\` to bring the Claude Code plugin up to this version.`;
881
1035
  }
882
- async function projectInstallAt(dir, home, env) {
883
- const local = await readFile3(join4(dir, ".claude", "settings.local.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
884
- if (local?.enabledPlugins?.[PLUGIN_ID] === true) return true;
885
- if (await isHome(dir, home)) return false;
886
- if ((await folderState("local", env, home, dir)).state === "ours") return true;
887
- const paths = settingsInstallPaths(true, env, home, dir);
888
- return (await inspectLegacyInstall(paths.settingsPath, paths.mcpFile)).events.length > 0;
889
- }
890
- async function isHome(dir, home) {
891
- const [dirPath, homePath] = await Promise.all([
892
- realpath(dir).catch(() => dir),
893
- realpath(home).catch(() => home)
894
- ]);
895
- return dirPath === homePath;
1036
+ function versionFreeEntry(entry) {
1037
+ if (entry === void 0 || entry.length === 0) return null;
1038
+ const segs = entry.split(sep);
1039
+ const store = segs.indexOf(".pnpm");
1040
+ if (store === -1) return segs.join(sep);
1041
+ const inner = segs.indexOf("node_modules", store);
1042
+ if (inner === -1) return null;
1043
+ const derived = [...segs.slice(0, store), ...segs.slice(inner + 1)].join(sep);
1044
+ return existsSync(derived) ? derived : null;
896
1045
  }
897
- var NOTHING_TO_REFRESH = "Nothing to refresh";
898
- async function somethingToRefresh(claude, scope, legacy, env, home, cwd) {
899
- if (legacy.present) return true;
900
- if ((await folderState(scope, env, home, cwd)).state === "ours") return true;
901
- if (claude.binary !== null) {
902
- const listing = await readPluginListing(claude.binary, env, cwd);
903
- if (listing.id === PLUGIN_ID) return true;
1046
+ function refreshLines(refresh) {
1047
+ const failedDirs = new Set(refresh.failed.map((f) => f.dataDir));
1048
+ const done = refresh.profiles.filter((p) => !failedDirs.has(p));
1049
+ if (refresh.failed.length === 0) {
1050
+ return [
1051
+ done.length > 1 ? `Refreshed the Claude Code plugin for ${done.length} profiles: ${done.join(", ")}.` : `Refreshed the Claude Code plugin for ${done[0]}.`
1052
+ ];
904
1053
  }
905
- return false;
1054
+ const total = done.length + refresh.failed.length;
1055
+ const lines2 = done.length > 0 ? [
1056
+ `Refreshed the Claude Code plugin for ${done.length} of ${total} profiles: ${done.join(", ")}.`
1057
+ ] : [];
1058
+ lines2.push(`Could not refresh the Claude Code plugin for ${refresh.failed.length}:`);
1059
+ lines2.push(...refresh.failed.map((f) => `- ${f.dataDir}: ${f.reason} ${f.fix}`));
1060
+ return lines2;
906
1061
  }
907
- async function runRouterInstall(args, ctx, deps = {}) {
908
- const env = deps.env ?? process.env;
909
- const home = deps.homeDir ?? homedir();
910
- if (!isAbsolute(home)) {
911
- throw new CliError("INTERNAL", "The home directory is not an absolute path.", {
912
- fix: "Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`."
1062
+ function projectLines(refresh) {
1063
+ return [
1064
+ ...refresh.projects.length > 0 ? [`Refreshed the project install in ${refresh.projects.join(", ")}.`] : [],
1065
+ ...refresh.projectsFailed.length > 0 ? [
1066
+ `Could not refresh the project install in ${refresh.projectsFailed.length}:`,
1067
+ ...refresh.projectsFailed.map((p) => `- ${p.project}: ${p.reason} ${p.fix}`)
1068
+ ] : []
1069
+ ];
1070
+ }
1071
+ var spawnCapture = (cmd, args, opts, onOutput) => new Promise((res) => {
1072
+ let child;
1073
+ try {
1074
+ child = spawn(cmd, args, {
1075
+ stdio: ["ignore", "pipe", "pipe"],
1076
+ cwd: opts.cwd,
1077
+ // Layered onto this process's environment rather than replacing it: the
1078
+ // child is a Node CLI that needs PATH and HOME, and only the keys named
1079
+ // here are being decided.
1080
+ ...opts.env !== void 0 ? { env: { ...process.env, ...opts.env } } : {}
913
1081
  });
1082
+ } catch (cause) {
1083
+ res({ kind: "start-failed", cause });
1084
+ return;
914
1085
  }
915
- assertPluginInstallation(ctx.dataDir, home, env);
916
- const config = await loadRawConfig(ctx.dataDir);
917
- const named = namedLimits(args);
918
- const cwd = deps.cwd ?? process.cwd();
919
- const project = args.project ?? (args.refresh === true && await projectInstallHere(cwd, home, env));
920
- const scope = project ? "local" : "user";
921
- const claude = await readClaudeCode(env, cwd, deps.findClaude ?? findClaudeBinary);
922
- const paths = settingsInstallPaths(project, env, home, cwd);
923
- const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);
924
- const setUpRuntime = () => (deps.runtime ?? defaultRuntime)({
925
- dataDir: ctx.dataDir,
926
- home,
927
- env,
928
- version: package_default.version,
929
- moduleDir: dirname3(fileURLToPath2(import.meta.url)),
930
- refresh: args.refresh === true
1086
+ let timedOut = false;
1087
+ const timer = setTimeout(() => {
1088
+ timedOut = true;
1089
+ child.kill("SIGKILL");
1090
+ }, opts.timeoutMs);
1091
+ child.stdout?.on("data", (chunk) => onOutput(chunk.toString()));
1092
+ child.stderr?.on("data", (chunk) => onOutput(chunk.toString()));
1093
+ child.on("error", (cause) => {
1094
+ clearTimeout(timer);
1095
+ res({ kind: "start-failed", cause });
931
1096
  });
932
- if (args.refresh === true && !await somethingToRefresh(claude, scope, legacy, env, home, cwd)) {
933
- if (!project && hasRuntime(ctx.dataDir, home)) {
934
- const rt2 = await setUpRuntime();
935
- requireRuntime(rt2);
936
- await recordClaudeProjects(ctx.dataDir, config.install?.routerProjects ?? [], env, home);
937
- if (runtimeLaunch(rt2) !== null) {
938
- await collectRuntime(rt2.root, await fallbackFolders(ctx.dataDir, env, home, cwd, false));
1097
+ child.on("close", (code) => {
1098
+ clearTimeout(timer);
1099
+ res(timedOut ? { kind: "timeout" } : { kind: "exit", code: code ?? 1 });
1100
+ });
1101
+ });
1102
+
1103
+ // src/router/plugin-registration.ts
1104
+ function folderFor(scope, env, home, cwd) {
1105
+ return pluginFolderPath(scope === "local" ? join3(cwd, ".claude") : claudeConfigDir(env, home));
1106
+ }
1107
+ async function registerPlugin(opts) {
1108
+ const folder = folderFor(opts.scope, opts.env, opts.home, opts.cwd);
1109
+ const steps = [];
1110
+ let fallbackReason;
1111
+ if (opts.binary !== null) {
1112
+ const hosts = opts.hostsDir === void 0 ? await packageHostsDir() : opts.hostsDir;
1113
+ if (hosts === null) {
1114
+ fallbackReason = "this build carries no plugin marketplace folder (dist/hosts/claude)";
1115
+ } else {
1116
+ const done = await viaPluginCommands(opts.binary, hosts, opts, steps);
1117
+ if (done.ok) {
1118
+ const superseded = await removePluginFolder(folder);
1119
+ return {
1120
+ method: "plugin",
1121
+ id: PLUGIN_ID,
1122
+ scope: opts.scope,
1123
+ state: done.state,
1124
+ path: hosts,
1125
+ version: opts.version,
1126
+ steps,
1127
+ ...superseded.removed ? { supersededFolder: superseded } : {}
1128
+ };
939
1129
  }
940
- return runtimeOnlyRefresh(ctx, rt2, home);
1130
+ fallbackReason = done.reason;
1131
+ }
1132
+ const existing = await existingCopy(opts.binary, opts.env, opts.home, opts.cwd);
1133
+ if (existing !== null) {
1134
+ return {
1135
+ method: "none",
1136
+ id: existing,
1137
+ scope: opts.scope,
1138
+ state: "failed",
1139
+ version: opts.version,
1140
+ steps,
1141
+ reason: `${fallbackReason}; ${existing} is already in Claude Code and was left as it is, so no second copy was written`
1142
+ };
1143
+ }
1144
+ } else {
1145
+ fallbackReason = "no claude binary on PATH or in CLAUDE_CODE_EXECPATH";
1146
+ if (await installedThroughCommands(opts.env, opts.home)) {
1147
+ return {
1148
+ method: "plugin",
1149
+ id: PLUGIN_ID,
1150
+ scope: opts.scope,
1151
+ state: "current",
1152
+ version: opts.version,
1153
+ steps,
1154
+ fallbackReason: `${fallbackReason}; ${PLUGIN_ID} is already registered, so it was left as it is`
1155
+ };
941
1156
  }
942
- if (!project)
943
- await recordClaudeProjects(ctx.dataDir, config.install?.routerProjects ?? [], env, home);
944
- throw new CliError(
945
- "REFUSED",
946
- `${NOTHING_TO_REFRESH}: neither the ${PLUGIN_ID} plugin nor a settings install of Tenjin is registered here.`,
947
- { fix: "Run `tenjin install` to set this machine up." }
948
- );
949
1157
  }
950
- const humanOutput = ctx.flags.json === true ? false : deps.isInteractive ?? ctx.io.isTTY;
951
- const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));
952
- const answered = args.yes === true || named.keys.length > 0;
953
- const unasked = config.maxAutoSpend === void 0 && config.sessionBudget === void 0;
954
- const limits = args.refresh === true ? void 0 : named.keys.length > 0 ? { ...shownLimits(config), ...named.limits } : args.yes === true ? shownLimits(config) : canPrompt && unasked ? await approveLimits(deps) : {};
955
- const deferred = !claude.meetsFloor && legacy.present;
956
- const rt = deferred ? null : await setUpRuntime();
957
- requireRuntime(rt);
958
- if (!project) {
959
- await recordClaudeProjects(ctx.dataDir, config.install?.routerProjects ?? [], env, home);
1158
+ const written = await writePluginFolder(
1159
+ folder,
1160
+ renderPluginFiles(opts.version, opts.cliEntry ?? packageCliEntry(), {
1161
+ node: opts.node,
1162
+ mod: await packageMod(opts.hostsDir)
1163
+ })
1164
+ );
1165
+ if (written.state === "written") {
1166
+ return {
1167
+ method: "skills-dir",
1168
+ id: SKILLS_DIR_PLUGIN_ID,
1169
+ scope: opts.scope,
1170
+ state: "written",
1171
+ path: folder,
1172
+ version: opts.version,
1173
+ steps,
1174
+ fallbackReason
1175
+ };
960
1176
  }
961
- const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true, limits, named.keys);
962
- const removedKeysLines = spend.removed.length > 0 ? [
963
- `Removed retired settings: ${spend.removed.join(", ")}. Automatic router limits remain in effect; manual pay always requires consent.`
964
- ] : [];
965
- const removedSkills = await removeRetiredSkills(home, project ? cwd : void 0);
966
- const launch = runtimeLaunch(rt);
967
- const plugin = deferred ? deferredRegistration(scope, claude) : await registerPlugin({
968
- binary: claude.binary,
969
- scope,
970
- version: launch?.version ?? package_default.version,
971
- env,
972
- home,
973
- cwd,
974
- ...launch !== null ? { hostsDir: launch.hostsDir, cliEntry: launch.cliEntry, node: launch.node } : {
975
- ...deps.hostsDir !== void 0 ? { hostsDir: deps.hostsDir } : {},
976
- ...deps.cliEntry !== void 0 ? { cliEntry: deps.cliEntry } : {}
977
- }
1177
+ return {
1178
+ method: "none",
1179
+ id: null,
1180
+ scope: opts.scope,
1181
+ state: "failed",
1182
+ path: folder,
1183
+ version: opts.version,
1184
+ steps,
1185
+ fallbackReason,
1186
+ reason: written.reason ?? "the plugin folder could not be written"
1187
+ };
1188
+ }
1189
+ async function viaPluginCommands(binary, hosts, opts, steps) {
1190
+ const run = (args) => runClaude(binary, args, { env: opts.env, cwd: opts.cwd });
1191
+ const scopeArgs = ["--scope", opts.scope];
1192
+ const marketplaceScope = opts.scope === "user" ? [] : scopeArgs;
1193
+ const known = await run(["plugin", "marketplace", "list", "--json"]);
1194
+ const listed = known.code === 0 ? jsonList(known.stdout) : null;
1195
+ steps.push({
1196
+ command: "claude plugin marketplace list --json",
1197
+ ok: listed !== null,
1198
+ ...listed === null ? { detail: commandDetail(known) } : {}
978
1199
  });
979
- if (rt !== null && launch !== null) {
980
- if (plugin.state !== "failed") {
981
- await collectRuntime(rt.root, await fallbackFolders(ctx.dataDir, env, home, cwd, project));
982
- } else if (!marketplaceAdded(plugin, launch.hostsDir)) {
983
- await rt.restore?.().catch(() => void 0);
984
- }
985
- }
986
- if (project && plugin.state !== "failed") {
987
- await persistRouterProject(ctx.dataDir, cwd).catch(() => void 0);
1200
+ if (listed === null) {
1201
+ return {
1202
+ ok: false,
1203
+ reason: `claude plugin marketplace list could not be read (${commandDetail(known)}), so no marketplace was added or repointed`
1204
+ };
988
1205
  }
989
- const migration = legacy.unreadable !== void 0 && !legacy.present ? { state: "blocked", settingsPath: paths.settingsPath, reason: legacy.unreadable } : await migrateSettingsInstall(legacy, claude, {
990
- dataDir: ctx.dataDir,
991
- env,
992
- cwd,
993
- mcpScope: paths.mcpScope
994
- });
995
- const pending = settingsInstallStays(migration);
996
- const servers = await readMcpServers(deps, {
997
- settingsInstallPending: pending,
998
- ...launch !== null ? { version: launch.version } : {}
999
- });
1000
- const serverLines = servers.stale > 0 ? [paint(ctx.io, "yellow", `! ${servers.check.detail}. ${servers.check.fix ?? ""}`.trim())] : [];
1001
- const claudeCode = claudeCodeData(claude);
1002
- const notices = refreshNotices(plugin, claude, migration, rt, home);
1003
- if (args.refresh === true) {
1004
- if (plugin.state === "failed" && migration.state !== "pending") {
1005
- throw new CliError(
1006
- "REFUSED",
1007
- `The ${PLUGIN_ID} plugin could not be registered: ${plugin.reason ?? "unknown reason"}.`,
1008
- { fix: registrationFix(plugin), details: { plugin, claudeCode, migration } }
1009
- );
1010
- }
1206
+ const existing = listed.find((m) => m.name === MARKETPLACE_NAME);
1207
+ if (existing !== void 0 && !await ownMarketplace(existing)) {
1011
1208
  return {
1012
- data: {
1013
- plugin,
1014
- claudeCode,
1015
- migration,
1016
- notices,
1017
- refresh: true,
1018
- spend,
1019
- removedSkills,
1020
- scope,
1021
- mcpServer: servers.check,
1022
- runtime: runtimeData(rt),
1023
- launcher: rt?.launcher ?? null
1024
- },
1025
- humanLines: [
1026
- ...refreshLines(ctx, plugin, claude, migration, rt, home),
1027
- ...removedKeysLines,
1028
- ...serverLines
1029
- ]
1209
+ ok: false,
1210
+ reason: `a marketplace named ${MARKETPLACE_NAME} that this CLI did not add is already configured, so it was left as it is`
1030
1211
  };
1031
1212
  }
1032
- const { resolveWallet } = await import("./install-wallet-5M4OTYLX.js");
1033
- const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? "flag" : void 0, false);
1034
- const effective = await resolveContextSettings(ctx);
1035
- const command = continuationCommand(rt);
1036
- const spendAsk = !canPrompt && !answered && unasked ? spendStep(args, command) : void 0;
1037
- const asksAgent = !canPrompt && underAgentHarness(env);
1038
- const [router, funding] = await Promise.all([
1039
- probeRouter(effective.baseUrl, {
1040
- timeoutMs: ctx.flags.timeout,
1041
- env,
1042
- ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
1043
- }),
1044
- // The spend question comes first, because its answer picks the install
1045
- // command. The funding question rides on the install that follows it.
1046
- asksAgent && spendAsk === void 0 ? fundStep(wallet, effective.rpcUrl, deps, `${command} wallet fund ${SUGGESTED_FUND_USD}`) : Promise.resolve(void 0)
1047
- ]);
1048
- const fund = funding?.step;
1049
- const nextSteps = [
1050
- ...spendAsk !== void 0 ? [spendAsk] : [],
1051
- ...fund !== void 0 ? [fund] : []
1052
- ];
1053
- const data = {
1054
- plugin,
1055
- claudeCode,
1056
- migration,
1057
- next: nextStep(
1058
- plugin,
1059
- claude,
1060
- wallet,
1061
- migration,
1062
- asksAgent && nextSteps.length > 0,
1063
- ctx.io.isTTY,
1064
- command,
1065
- env
1066
- ),
1067
- nextSteps,
1068
- ...funding?.warning !== void 0 ? { fundingWarning: funding.warning } : {},
1069
- // The check for this scope, said outright; a bare doctor in the project
1070
- // also finds it from what the project holds.
1071
- ...project ? { doctor: `${command} doctor --project` } : {},
1072
- spend: { ...spend, effective: effectiveLimits(effective.policy) },
1073
- wallet,
1074
- router: {
1075
- status: router.status === "ok" ? "ok" : "warn",
1076
- detail: router.detail,
1077
- ...router.fix !== void 0 ? { fix: router.fix } : {}
1078
- },
1079
- disclosure: DISCLOSURE,
1080
- removedSkills,
1081
- mcpServer: servers.check,
1082
- runtime: runtimeData(rt),
1083
- launcher: rt?.launcher ?? null
1084
- };
1085
- return {
1086
- data,
1087
- humanLines: [
1088
- ...lines(ctx, {
1089
- plugin,
1090
- claude,
1091
- migration,
1092
- wallet,
1093
- ...fund !== void 0 ? { fund } : {},
1094
- ...funding?.warning !== void 0 ? { fundingWarning: funding.warning } : {},
1095
- asks: asksAgent && nextSteps.length > 0,
1096
- policy: effective.policy,
1097
- ...spendAsk !== void 0 ? { spendAsk } : {},
1098
- router,
1099
- rt,
1100
- home,
1101
- env
1102
- }),
1103
- ...removedKeysLines,
1104
- ...serverLines
1105
- ]
1106
- };
1213
+ const add = await step(
1214
+ steps,
1215
+ ["plugin", "marketplace", "add", hosts, "--json", ...marketplaceScope],
1216
+ run
1217
+ );
1218
+ if (!add.ok) return { ok: false, reason: `claude plugin marketplace add failed: ${add.detail}` };
1219
+ const install = await step(steps, ["plugin", "install", PLUGIN_ID, ...scopeArgs, "--json"], run);
1220
+ if (!install.ok) return { ok: false, reason: `claude plugin install failed: ${install.detail}` };
1221
+ const installed = install.result?.installedVersion;
1222
+ const available = install.result?.availableVersion;
1223
+ if (typeof installed !== "string" || typeof available !== "string") {
1224
+ return { ok: true, state: "installed" };
1225
+ }
1226
+ if (installed === available) return { ok: true, state: "current" };
1227
+ const update2 = await step(steps, ["plugin", "update", PLUGIN_ID, ...scopeArgs, "--json"], run);
1228
+ if (!update2.ok) return { ok: false, reason: `claude plugin update failed: ${update2.detail}` };
1229
+ return { ok: true, state: "updated" };
1107
1230
  }
1108
- async function defaultRuntime(o) {
1109
- const { setupRuntime } = await import("./runtime-UZOKSUZX.js");
1110
- return setupRuntime(o);
1231
+ function marketplaceAdded(reg, hosts) {
1232
+ const add = `claude plugin marketplace add ${hosts} `;
1233
+ return reg.steps.some((s) => s.ok && s.command.startsWith(add));
1111
1234
  }
1112
- var sharedResults = /* @__PURE__ */ new WeakSet();
1113
- function runtimeOncePerRun(setup = defaultRuntime) {
1114
- let first;
1115
- return async (o) => {
1116
- if (first === void 0) {
1117
- first = setup(o).then((rt2) => {
1118
- const restore = rt2.restore;
1119
- if (restore === void 0) return rt2;
1120
- return {
1121
- ...rt2,
1122
- restore: async () => {
1123
- try {
1124
- await restore();
1125
- } finally {
1126
- first = void 0;
1127
- }
1128
- }
1129
- };
1130
- });
1131
- return first;
1132
- }
1133
- const rt = { ...await first };
1134
- delete rt.restore;
1135
- sharedResults.add(rt);
1136
- return rt;
1137
- };
1235
+ async function step(steps, args, run) {
1236
+ const out = await run(args);
1237
+ const result = jsonResult(out.stdout);
1238
+ const ok = out.code === 0 && (result === null || result.outcome === void 0 || result.outcome === "ok");
1239
+ const detail = commandDetail(out, result);
1240
+ steps.push({ command: `claude ${args.join(" ")}`, ok, ...ok ? {} : { detail } });
1241
+ return { ok, detail, result };
1138
1242
  }
1139
- function hasRuntime(dataDir, home) {
1140
- return resolve(dataDir) === resolve(defaultDataDir(home)) && existsSync(runtimeStatePath(runtimeDir(dataDir)));
1243
+ function commandDetail(out, result = null) {
1244
+ if (typeof result?.message === "string") return result.message;
1245
+ const text = (out.stderr || out.stdout).trim().slice(0, 300);
1246
+ if (text.length > 0) return text;
1247
+ return out.code === null ? "the command could not be run" : `exit ${out.code}`;
1141
1248
  }
1142
- function runtimeOnlyRefresh(ctx, rt, home) {
1143
- return {
1144
- data: {
1145
- plugin: null,
1146
- refresh: true,
1147
- scope: "user",
1148
- notices: runtimeNotices(rt, home),
1149
- runtime: runtimeData(rt),
1150
- launcher: rt.launcher
1151
- },
1152
- humanLines: [
1153
- `${paint(ctx.io, "green", "\u2713")} Tenjin's runtime is up to date; no Claude Code plugin is registered here, so none was refreshed`,
1154
- ...runtimeLines(ctx, rt, home)
1155
- ]
1156
- };
1157
- }
1158
- async function collectRuntime(root, folders) {
1159
- try {
1160
- const { collect } = await import("./runtime-UZOKSUZX.js");
1161
- await collect(root, { lockWaitMs: 5e3, keep: await folderPointers(root, folders) });
1162
- } catch {
1163
- }
1164
- }
1165
- async function fallbackFolders(dataDir, env, home, cwd, project) {
1166
- const projects = (await loadRawConfig(dataDir).catch(() => null))?.install?.routerProjects ?? [];
1167
- return [
1168
- folderFor("user", env, home, cwd),
1169
- ...[...projects, ...project ? [cwd] : []].map((dir) => folderFor("local", env, home, dir))
1170
- ];
1171
- }
1172
- var NODE_DIR_RE = /^\d+\.\d+\.\d+$/;
1173
- async function folderPointers(root, folders) {
1174
- const pointers = [];
1175
- for (const dir of folders) {
1176
- if (await inspectPluginFolder(dir) !== "ours") continue;
1177
- const server = await readFile3(join4(dir, ".mcp.json"), "utf8").then(
1178
- (raw) => JSON.parse(raw).mcpServers?.[MCP_SERVER_NAME]
1179
- ).catch(() => void 0);
1180
- const entry = Array.isArray(server?.args) ? server.args[0] : void 0;
1181
- const node = server?.command;
1182
- if (typeof entry !== "string" || typeof node !== "string") continue;
1183
- const build = runtimeBuild(dirname3(entry));
1184
- const nodeVersion = relative(join4(root, "node"), node).split(sep)[0] ?? "";
1185
- if (build !== null && resolve(build.root) === resolve(root) && NODE_DIR_RE.test(nodeVersion)) {
1186
- pointers.push({ cli: build.cli, node: nodeVersion });
1187
- }
1188
- }
1189
- return pointers;
1190
- }
1191
- function assertPluginInstallation(dataDir, home, env) {
1192
- if (env.TENJIN_DATA_DIR && resolve(dataDir) !== resolve(defaultDataDir(home))) {
1193
- throw new CliError("REFUSED", "Plugin installation needs the default data directory.", {
1194
- fix: "Run without TENJIN_DATA_DIR. Other CLI commands still support it."
1195
- });
1196
- }
1197
- if (!isSourceCheckout(dirname3(fileURLToPath2(import.meta.url)))) {
1198
- const unsupported = unpinnedPlatform(process.platform, process.arch, runningGlibc());
1199
- if (unsupported !== null)
1200
- throw new CliError("REFUSED", `Plugin installation is unsupported on ${unsupported}.`, {
1201
- fix: "Use macOS, Windows or glibc Linux 2.28+ on x64/arm64. Your existing setup was kept."
1202
- });
1249
+ async function ownMarketplace(row) {
1250
+ const path = typeof row.path === "string" ? row.path : void 0;
1251
+ if (row.source !== "directory" || path === void 0) return false;
1252
+ if (await stat2(path).catch(() => null) === null) {
1253
+ return /tenjin-cli[\\/]dist[\\/]hosts[\\/]claude$/.test(path) || /[\\/]runtime[\\/]claude$/.test(path);
1203
1254
  }
1255
+ return await inspectPluginFolder(join3(path, PLUGIN_DIR)) === "ours";
1204
1256
  }
1205
- function continuationCommand(rt, platform = process.platform) {
1206
- if (rt === null || rt.state === "skipped" || rt.node === void 0 || rt.entry === void 0)
1207
- return "tenjin";
1208
- const launcher = rt.launcher;
1209
- const verifiedLauncher = launcher?.state === "written" || launcher?.state === "current";
1210
- const path = verifiedLauncher ? launcher.paths.find((p) => platform !== "win32" || p.endsWith(".cmd")) : void 0;
1211
- const parts = path === void 0 ? [rt.node, rt.entry] : [path];
1212
- return platform === "win32" ? `& ${parts.map((part) => `'${part.replaceAll("'", "''")}'`).join(" ")}` : parts.map(shQuote).join(" ");
1257
+ async function existingCopy(binary, env, home, cwd) {
1258
+ const out = await runClaude(binary, ["plugin", "list", "--json"], { env, cwd });
1259
+ const listed = out.code === 0 ? jsonList(out.stdout) : null;
1260
+ if (listed === null) return await installedThroughCommands(env, home) ? PLUGIN_ID : null;
1261
+ const row = listed.find(
1262
+ (p) => typeof p.id === "string" && p.id.startsWith(`${PLUGIN_NAME}@`) && p.id !== SKILLS_DIR_PLUGIN_ID && p.enabled === true
1263
+ );
1264
+ return typeof row?.id === "string" ? row.id : null;
1213
1265
  }
1214
- function requireRuntime(rt) {
1215
- if (rt === null || rt.state === "skipped") return;
1216
- if (rt.state === "failed" || rt.state === "kept" && rt.reason !== void 0 && rt.newer !== true) {
1217
- throw new CliError(
1218
- "UPDATE_FAILED",
1219
- `Tenjin could not finish installation: ${rt.reason ?? "runtime setup failed"}. Your existing plugin registration was kept.`,
1220
- {
1221
- fix: rt.fix ?? (rt.unpinned ? "Use macOS, Windows or glibc Linux 2.28+ on x64/arm64." : "Check your connection and run tenjin install again.")
1222
- }
1266
+ async function recordedInstalls(env, home) {
1267
+ let raw;
1268
+ try {
1269
+ raw = await readFile3(
1270
+ join3(claudeConfigDir(env, home), "plugins", "installed_plugins.json"),
1271
+ "utf8"
1223
1272
  );
1273
+ } catch (err) {
1274
+ return hasCode(err, "ENOENT") ? [] : null;
1224
1275
  }
1225
- }
1226
- function runtimeLaunch(rt) {
1227
- if (rt === null || rt.state !== "active" && rt.state !== "current" && rt.state !== "kept") {
1276
+ let plugins;
1277
+ try {
1278
+ plugins = JSON.parse(raw).plugins;
1279
+ } catch {
1228
1280
  return null;
1229
1281
  }
1230
- if (rt.cli === void 0 || rt.hostsDir === void 0 || rt.entry === void 0 || rt.node === void 0) {
1231
- return null;
1282
+ if (typeof plugins !== "object" || plugins === null || Array.isArray(plugins)) return null;
1283
+ const entries = plugins[PLUGIN_ID];
1284
+ if (!Array.isArray(entries)) return [];
1285
+ const records = [];
1286
+ for (const entry of entries) {
1287
+ if (typeof entry !== "object" || entry === null) continue;
1288
+ const { scope, projectPath } = entry;
1289
+ if (scope === "user") records.push({ scope, projectPath: null });
1290
+ else if (scope === "local" && typeof projectPath === "string" && projectPath.length > 0) {
1291
+ records.push({ scope, projectPath });
1292
+ }
1232
1293
  }
1233
- return { version: rt.cli, hostsDir: rt.hostsDir, cliEntry: rt.entry, node: rt.node };
1234
- }
1235
- function runtimeData(rt) {
1236
- if (rt === null) return null;
1237
- return {
1238
- state: rt.state,
1239
- root: rt.root,
1240
- ...rt.cli !== void 0 ? { cli: rt.cli } : {},
1241
- ...rt.nodeVersion !== void 0 ? { nodeVersion: rt.nodeVersion } : {},
1242
- ...rt.reason !== void 0 ? { reason: rt.reason } : {},
1243
- ...rt.fix !== void 0 ? { fix: rt.fix } : {}
1244
- };
1294
+ return records;
1245
1295
  }
1246
- async function recordClaudeProjects(dataDir, known, env, home) {
1247
- const records = await recordedInstalls(env, home).catch(() => null);
1248
- if (records === null || records.every((r) => r.projectPath === null)) return;
1249
- const seen = /* @__PURE__ */ new Set([
1250
- ...known,
1251
- ...await Promise.all(known.map((dir) => realpath(dir).catch(() => dir)))
1252
- ]);
1253
- for (const { projectPath } of records) {
1254
- if (projectPath === null || seen.has(projectPath)) continue;
1255
- if ((await stat3(projectPath).catch(() => null))?.isDirectory() !== true) continue;
1256
- seen.add(projectPath);
1257
- await persistRouterProject(dataDir, projectPath).catch(() => void 0);
1296
+ async function installedThroughCommands(env, home) {
1297
+ try {
1298
+ const raw = await readFile3(
1299
+ join3(claudeConfigDir(env, home), "plugins", "installed_plugins.json"),
1300
+ "utf8"
1301
+ );
1302
+ const plugins = JSON.parse(raw).plugins;
1303
+ return plugins !== null && typeof plugins === "object" && PLUGIN_ID in plugins;
1304
+ } catch {
1305
+ return false;
1258
1306
  }
1259
1307
  }
1260
- function tilde(path, home) {
1261
- return path === home || path.startsWith(`${home}${sep}`) ? `~${path.slice(home.length)}` : path;
1308
+ async function packageHostsDir(moduleDir = dirname2(fileURLToPath2(import.meta.url))) {
1309
+ const catalog = join3(moduleDir, "hosts", "claude", ".claude-plugin", "marketplace.json");
1310
+ const stable = versionFreeEntry(catalog) ?? catalog;
1311
+ if ((await stat2(stable).catch(() => null))?.isFile() !== true) return null;
1312
+ return dirname2(dirname2(stable));
1262
1313
  }
1263
- function runtimeSentence(rt, home) {
1264
- if (rt.state !== "active" || !rt.firstTime) return null;
1265
- 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.`;
1314
+ async function packageMod(hostsDir) {
1315
+ const hosts = hostsDir === void 0 ? await packageHostsDir() : hostsDir;
1316
+ return hosts === null ? void 0 : readModSources(join3(hosts, PLUGIN_DIR));
1266
1317
  }
1267
- function launcherSentence(launcher, home) {
1268
- if (launcher === null) return null;
1269
- if (launcher.state === "foreign") {
1270
- const who = launcher.reason?.replace(/ is not Tenjin's$/, "") ?? launcher.paths[0] ?? "";
1271
- 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.`;
1272
- }
1273
- if (launcher.state === "failed") {
1274
- const dir = launcher.paths[0] !== void 0 ? tilde(dirname3(launcher.paths[0]), home) : "";
1275
- 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.`;
1318
+ function packageCliEntry(moduleDir = dirname2(fileURLToPath2(import.meta.url))) {
1319
+ const entry = join3(moduleDir, "index.js");
1320
+ return versionFreeEntry(entry) ?? entry;
1321
+ }
1322
+ async function readPluginListing(binary, env, cwd) {
1323
+ const out = await runClaude(binary, ["plugin", "list", "--json"], { env, cwd });
1324
+ const rows = out.code === 0 ? jsonList(out.stdout) : null;
1325
+ if (rows === null) {
1326
+ return { id: null, enabled: false, version: null, read: false, scope: null, projects: [] };
1276
1327
  }
1277
- if ((launcher.state === "written" || launcher.state === "current") && !launcher.onPath) {
1278
- 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 ?? ""}`;
1328
+ const projects = rows.filter(
1329
+ (r) => r.id === PLUGIN_ID && r.enabled !== true && typeof r.projectPath === "string" && r.projectPath.length > 0
1330
+ ).map((r) => r.projectPath);
1331
+ const row = rows.find((r) => r.id === PLUGIN_ID && r.enabled === true) ?? rows.find((r) => r.id === SKILLS_DIR_PLUGIN_ID && r.enabled === true) ?? rows.find((r) => r.id === PLUGIN_ID || r.id === SKILLS_DIR_PLUGIN_ID);
1332
+ if (row === void 0) {
1333
+ return { id: null, enabled: false, version: null, read: true, scope: null, projects };
1279
1334
  }
1280
- return null;
1281
- }
1282
- function runtimeLines(ctx, rt, home) {
1283
- if (rt === null || sharedResults.has(rt)) return [];
1284
- const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
1285
- const runs = runtimeSentence(rt, home);
1286
- const launcher = launcherSentence(rt.launcher, home);
1287
- return [...runs !== null ? [` ${runs}`] : [], ...launcher !== null ? [warn(launcher)] : []];
1288
- }
1289
- function claudeCodeData(claude) {
1290
1335
  return {
1291
- binary: claude.binary?.path ?? null,
1292
- source: claude.binary?.source ?? null,
1293
- version: claude.version,
1294
- meetsFloor: claude.meetsFloor,
1295
- ...claude.fix !== void 0 ? { fix: claude.fix } : {}
1336
+ id: String(row.id),
1337
+ enabled: row.enabled === true,
1338
+ version: typeof row.version === "string" ? row.version : null,
1339
+ read: true,
1340
+ scope: typeof row.scope === "string" ? row.scope : null,
1341
+ projects
1296
1342
  };
1297
1343
  }
1298
- function registrationFix(plugin) {
1299
- const flag = plugin.scope === "local" ? " --project" : "";
1300
- if (plugin.id !== null && plugin.method === "none") {
1301
- return `${plugin.id} keeps serving this machine at the version Claude Code has; run \`tenjin install${flag}\` again to retry.`;
1302
- }
1303
- if (plugin.path !== void 0 && plugin.reason?.includes("not a folder this CLI wrote") === true) {
1304
- return `Move ${plugin.path} aside, then run \`tenjin install${flag}\` again.`;
1305
- }
1306
- return `Run \`tenjin doctor${flag}\` to see the cause, then run \`tenjin install${flag}\` again.`;
1344
+ async function folderState(scope, env, home, cwd) {
1345
+ const path = folderFor(scope, env, home, cwd);
1346
+ return { path, state: await inspectPluginFolder(path) };
1307
1347
  }
1308
- var REPAIRABLE = /* @__PURE__ */ new Set([
1309
- "passphrase_missing",
1310
- "passphrase_wrong",
1311
- "env_passphrase_wrong"
1312
- ]);
1313
- function repairStep(tty) {
1314
- return tty ? `run \`tenjin wallet repair\` yourself ${REPAIR_CLAUSE}` : "ask the person to run `tenjin wallet repair` in their own terminal (never ask for the passphrase)";
1348
+
1349
+ // src/router/claude-install.ts
1350
+ function settingsInstallPaths(project, env, home, cwd) {
1351
+ return project ? {
1352
+ settingsPath: join4(cwd, ".claude", "settings.json"),
1353
+ mcpFile: projectMcpFile(cwd),
1354
+ mcpScope: "project"
1355
+ } : {
1356
+ settingsPath: userSettingsPath(env, home),
1357
+ mcpFile: userMcpFile(env, home),
1358
+ mcpScope: "user"
1359
+ };
1315
1360
  }
1316
- function nextStep(plugin, claude, wallet, migration, asksQuestion, tty, command, env) {
1317
- if (plugin.state === "failed") return registrationFix(plugin);
1318
- const steps = todaysSteps(plugin, claude, wallet, migration, asksQuestion, command, env);
1319
- const signing = wallet.signing;
1320
- if (signing?.status === "blocked" && REPAIRABLE.has(signing.reason)) {
1321
- steps.unshift(repairStep(tty));
1322
- }
1323
- return steps.join(", then ");
1361
+ async function claudeInstallAt(scope, env, home, cwd, signs) {
1362
+ const counts = (sign) => signs.includes(sign);
1363
+ if (counts("record") && await installedThroughCommands(env, home)) return true;
1364
+ if (counts("enabled") && scope === "local" && await enabledIn(cwd)) return true;
1365
+ if (counts("folder") && (await folderState(scope, env, home, cwd)).state === "ours") return true;
1366
+ if (!counts("settings") && !counts("settings-hooks")) return false;
1367
+ const paths = settingsInstallPaths(scope === "local", env, home, cwd);
1368
+ const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);
1369
+ return counts("settings") ? legacy.present : legacy.events.length > 0;
1324
1370
  }
1325
- function todaysSteps(plugin, claude, wallet, migration, asksQuestion, command, env) {
1326
- const steps = [];
1327
- if (asksQuestion) {
1328
- steps.push("ask the person the question in nextSteps, then run what the answer names");
1329
- } else if (wallet.status === "created") {
1330
- steps.push(`fund the wallet with \`${command} wallet fund ${SUGGESTED_FUND_USD}\``);
1331
- }
1332
- if (plugin.state === "deferred") {
1333
- steps.unshift("run `claude update`");
1334
- steps.push(
1335
- `run \`${command} install\` again; until then the earlier Tenjin setup keeps routing as before`
1371
+ async function enabledIn(dir) {
1372
+ const local = await readFile4(join4(dir, ".claude", "settings.local.json"), "utf8").then((raw) => JSON.parse(raw)).catch(() => null);
1373
+ return local?.enabledPlugins?.[PLUGIN_ID] === true;
1374
+ }
1375
+
1376
+ // src/router/reachability.ts
1377
+ async function probeRouter(baseUrl, opts) {
1378
+ const fail = (detail, fix) => ({
1379
+ name: "router",
1380
+ status: "fail",
1381
+ required: true,
1382
+ detail,
1383
+ fix
1384
+ });
1385
+ let url;
1386
+ try {
1387
+ url = new URL(ROUTE_PAID_PATH, baseUrl).toString();
1388
+ } catch {
1389
+ return fail(
1390
+ `the base URL ${JSON.stringify(baseUrl)} is not a URL`,
1391
+ `Check TENJIN_BASE_URL, or set it with \`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\`.`
1336
1392
  );
1337
- return steps;
1338
1393
  }
1339
- if (!claude.meetsFloor) steps.unshift("run `claude update`");
1340
- steps.push(loadStep(settingsInstallStays(migration) || !claude.meetsFloor, env, command));
1341
- return steps;
1342
- }
1343
- function settingsInstallStays(migration) {
1344
- return migration.state === "pending" || migration.state === "blocked";
1345
- }
1346
- function deferredRegistration(scope, claude) {
1347
- return {
1348
- method: "none",
1349
- id: null,
1350
- scope,
1351
- state: "deferred",
1352
- version: package_default.version,
1353
- steps: [],
1354
- 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`
1355
- };
1356
- }
1357
- function statusLineNotice(migration) {
1358
- const status = migration.removed?.statusLine;
1359
- if (status === "removed") {
1360
- 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.";
1394
+ const host = new URL(url).host;
1395
+ const probe = await httpRequest(url, {
1396
+ method: "POST",
1397
+ timeoutMs: opts.timeoutMs,
1398
+ blockRedirects: true,
1399
+ // A reachability check, not use: it must not count this machine as an install.
1400
+ anonymous: true,
1401
+ jsonBody: { schemaVersion: 1, warm: true },
1402
+ ...opts.fetchImpl !== void 0 ? { fetchImpl: opts.fetchImpl } : {}
1403
+ });
1404
+ const production = isSameDeployment(new URL(url).origin, PRODUCTION_ORIGIN);
1405
+ const checkBase = production ? "Try again later." : "Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.";
1406
+ const env = opts.env ?? process.env;
1407
+ const network = networkFix(host, env, production, opts.proxySupported ?? envProxySupported());
1408
+ const credentials = proxyCredentialsFix(env);
1409
+ const unreached = production ? network : checkBase;
1410
+ if (!probe.ok) {
1411
+ const t = probe.transport;
1412
+ if (t?.layer === "proxy" && t.proxyStatus === 407) {
1413
+ return fail(
1414
+ `a proxy between this machine and ${host} asked for its own credentials (407)`,
1415
+ credentials
1416
+ );
1417
+ }
1418
+ if (t?.layer === "proxy") {
1419
+ return fail(
1420
+ `a proxy refused the connection to ${host} (${t.proxyStatus}), so the router never answered`,
1421
+ unreached
1422
+ );
1423
+ }
1424
+ if (t?.layer === "dns") {
1425
+ return fail(`${host} did not resolve (${t.code}), so the router was not reached`, unreached);
1426
+ }
1427
+ if (t?.layer === "tls") {
1428
+ return fail(
1429
+ `the TLS connection to ${host} failed (${t.code}). A proxy that inspects TLS causes this`,
1430
+ `If this network inspects TLS, set NODE_EXTRA_CA_CERTS to its CA certificate. ${unreached}`
1431
+ );
1432
+ }
1433
+ if (t?.layer === "connect") {
1434
+ return fail(`could not connect to ${host} (${t.code})`, unreached);
1435
+ }
1436
+ return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, unreached);
1361
1437
  }
1362
- if (status === "restored") {
1363
- return "Took the Tenjin footer out of your status line and put your own command back; the plugin sets none.";
1438
+ if (probe.status === 402) {
1439
+ const { quoteOf } = await import("./routing-quote-AHLAREXR.js");
1440
+ const quoted = quoteOf((name) => probe.header(name));
1441
+ if (quoted === null) {
1442
+ return {
1443
+ name: "router",
1444
+ status: "warn",
1445
+ required: true,
1446
+ detail: `${url} asks for a payment this CLI cannot read, so routing calls are skipped`,
1447
+ fix: checkBase
1448
+ };
1449
+ }
1450
+ if (quoted > ROUTING_FEE_CEILING_ATOMIC) {
1451
+ return {
1452
+ name: "router",
1453
+ status: "warn",
1454
+ required: true,
1455
+ detail: `${url} quotes $${usd(quoted)} a routing call, above this CLI\u2019s current routing limit, so this fee is not paid`,
1456
+ fix: "Paid routing resumes once the router quotes within that limit. Free routing still works."
1457
+ };
1458
+ }
1459
+ return { name: "router", status: "ok", required: true, detail: `${url} is live` };
1364
1460
  }
1365
- return null;
1366
- }
1367
- function refreshNotices(plugin, claude, migration, rt, home) {
1368
- const out = [];
1369
- if (plugin.state === "deferred") {
1370
- out.push(
1371
- `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\`.`
1372
- );
1373
- } else if (plugin.state !== "failed" && settingsInstallStays(migration)) {
1374
- out.push(
1375
- "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."
1461
+ if (probe.status === 200 || probe.status === 400 || probe.status === 429) {
1462
+ return { name: "router", status: "ok", required: true, detail: `${url} is live` };
1463
+ }
1464
+ if (probe.status === 404) {
1465
+ return fail(`the router is not enabled at ${url}`, checkBase);
1466
+ }
1467
+ if (probe.status === 407) {
1468
+ return fail(
1469
+ `a proxy between this machine and ${host} asked for its own credentials (407)`,
1470
+ credentials
1376
1471
  );
1377
1472
  }
1378
- const status = statusLineNotice(migration);
1379
- if (status !== null) out.push(status);
1380
- if (rt !== null) out.push(...runtimeNotices(rt, home));
1381
- return out;
1382
- }
1383
- function runtimeNotices(rt, home) {
1384
- const out = [];
1385
- const runs = runtimeSentence(rt, home);
1386
- if (runs !== null) out.push(`Tenjin ${runs.charAt(0).toLowerCase()}${runs.slice(1)}`);
1387
- const launcher = launcherSentence(rt.launcher, home);
1388
- if (launcher !== null) out.push(launcher);
1389
- return out;
1390
- }
1391
- var SHOW_NOT_RUN = "Show the person addresses as written, and never ask them to run a command.";
1392
- function spendStep(args, command) {
1393
- return spendStepFor(installCommand(args, command));
1394
- }
1395
- function spendStepFor(command) {
1396
- const options = spendOptions(command);
1397
- const [byDefault, custom] = options;
1398
- return {
1399
- id: "spend",
1400
- question: spendChoiceQuestion(),
1401
- options,
1402
- next: `${process.platform === "win32" ? "Use PowerShell for these commands. " : ""}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}`
1403
- };
1404
- }
1405
- function installCommand(args, command) {
1406
- return [
1407
- `${command} install`,
1408
- ...args.project === true ? ["--project"] : [],
1409
- ...args.noWallet === true ? ["--no-wallet"] : []
1410
- ].join(" ");
1411
- }
1412
- function namedLimits(args) {
1413
- const flags = [
1414
- ["maxAutoSpend", "--max-auto-spend", args.maxAutoSpend, "call"],
1415
- ["sessionBudget", "--session-budget", args.sessionBudget, "day"]
1416
- ];
1417
- const limits = {};
1418
- const keys = [];
1419
- for (const [key, flag, raw, per] of flags) {
1420
- if (raw === void 0) continue;
1421
- if (args.refresh === true) {
1422
- throw new CliError("USAGE", `${flag} sets a spend limit, and --refresh writes none.`, {
1423
- fix: `Run \`tenjin install ${flag} ${raw}\` without --refresh.`
1424
- });
1473
+ if (probe.status === 401 || probe.status === 403) {
1474
+ if (!fromDeployment(probe)) {
1475
+ return fail(
1476
+ `${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`,
1477
+ network
1478
+ );
1425
1479
  }
1426
- const parsed = parseLimit(raw, per);
1427
- if ("refusal" in parsed) {
1428
- throw new CliError("USAGE", `${flag} ${raw}: ${parsed.refusal}`, {
1429
- fix: per === "day" ? `Give a positive USD amount or none, for example \`${flag} 5\`.` : `Give 0.25 USD or more, for example \`${flag} 0.5\`. ${MAX_AUTO_SPEND_FLOOR_WHY}`
1430
- });
1480
+ if (production) {
1481
+ return fail(`${url} refused this machine (${probe.status})`, checkBase);
1431
1482
  }
1432
- limits[key] = parsed.value;
1433
- keys.push(key);
1483
+ return fail(
1484
+ `${url} is not a Tenjin router (it asked for credentials)`,
1485
+ `Set the router URL with \`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\`.`
1486
+ );
1434
1487
  }
1435
- return { limits, keys };
1436
- }
1437
- var FUND_QUESTION = `Add $${SUGGESTED_FUND_USD} to Tenjin now?`;
1438
- var FUND_COMMAND = `tenjin wallet fund ${SUGGESTED_FUND_USD}`;
1439
- async function fundStep(wallet, rpcUrl, deps, command) {
1440
- const address = wallet.address;
1441
- if (address === void 0 || wallet.status !== "created" && wallet.status !== "existing") {
1442
- return void 0;
1488
+ if (probe.status >= 500) {
1489
+ return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);
1443
1490
  }
1444
- const funded = wallet.status === "created" ? false : await (deps.walletBalance ?? defaultBalance)(address, rpcUrl).then(
1445
- (atomic) => atomic > 0n,
1446
- () => null
1491
+ return fail(
1492
+ `${url} answered ${probe.status}, which a Tenjin router does not`,
1493
+ "Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`)."
1447
1494
  );
1448
- if (funded === true) return void 0;
1449
- if (funded === null) {
1450
- return {
1451
- warning: "Could not check your Tenjin funds. Your usual tools keep working. Ask your agent to check your funds later; this check failing does not mean you need to add money again."
1452
- };
1495
+ }
1496
+ function fromDeployment(probe) {
1497
+ return probe.header("x-vercel-id") !== void 0 || probe.header("x-request-id") !== void 0;
1498
+ }
1499
+ function networkFix(host, env, production, proxySupported) {
1500
+ const proxy = proxyVariable(env);
1501
+ const config = production ? " Tenjin's own config is correct and needs no change." : "";
1502
+ if (proxy !== void 0 && !proxySupported) {
1503
+ 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}`;
1453
1504
  }
1454
- const show = "You can ask your agent to add funds to Tenjin later. Paid tools need funds; your usual tools keep working.";
1455
- return {
1456
- step: {
1457
- id: "fund",
1458
- question: FUND_QUESTION,
1459
- options: [
1460
- {
1461
- id: "fund",
1462
- label: `Add $${SUGGESTED_FUND_USD}`,
1463
- recommended: false,
1464
- command
1465
- },
1466
- { id: "later", label: "Not now", recommended: false, command: null }
1467
- ],
1468
- next: `${process.platform === "win32" ? "Use PowerShell for this command. " : ""}The install is done. Ask the person this question with your question tool. On "Add $${SUGGESTED_FUND_USD}", run \`${command}\` alone, in the same turn, then follow its nextStep. On "Not now", run nothing and show the person this for later: ${show} The address is an alternative only if they ask to transfer funds directly. Never run \`${command}\` without this yes. ${SHOW_NOT_RUN}`,
1469
- address,
1470
- show
1471
- }
1472
- };
1505
+ const via = proxy !== void 0 ? ` (this shell sets ${proxy})` : "";
1506
+ return `Allow ${host} through your proxy, firewall or VPN${via}, or run from a network that reaches it.${config}`;
1473
1507
  }
1474
- async function defaultBalance(address, rpcUrl) {
1475
- const { getUsdcBalance } = await import("./usdc-VG4CIOUK.js");
1476
- return getUsdcBalance(address, rpcUrl);
1508
+ function proxyCredentialsFix(env) {
1509
+ const proxy = proxyVariable(env) ?? "HTTPS_PROXY";
1510
+ return `Put the proxy's credentials in ${proxy} (\`http://user:password@proxy:port\`), then try again.`;
1477
1511
  }
1478
- function fundLines(fund) {
1512
+
1513
+ // src/router/install.ts
1514
+ var DISCLOSURE = [
1515
+ "Relevant task context and your wallet address are sent to Tenjin for routing. Documentation queries go to Context7. Your private key stays on this machine.",
1516
+ "Privacy: https://tenjin.sh/privacy \xB7 Terms: https://tenjin.sh/terms"
1517
+ ];
1518
+ var CAPABILITY_LINES = [
1519
+ "Your agent can now make images, voiceovers and music, look up people and companies, read pages normal fetches can't open, and more.",
1520
+ "See every tool at tenjin.sh/tools"
1521
+ ];
1522
+ function receiptTail(ctx, policy, next) {
1479
1523
  return [
1480
- ` Ask the person: ${fund.question}`,
1481
- ` Add $${SUGGESTED_FUND_USD}: ${fund.options[0]?.command ?? FUND_COMMAND}`,
1482
- ` Not now: run nothing, show them: ${fund.show}`
1524
+ "",
1525
+ `Limits ${limitsLine(policy)}`,
1526
+ "",
1527
+ `Next: ${next}`,
1528
+ "",
1529
+ ...DISCLOSURE.map((line) => paint(ctx.io, "dim", line))
1483
1530
  ];
1484
1531
  }
1485
- async function approveLimits(deps) {
1486
- const choice = await (deps.promptLimits ?? promptLimits)(
1487
- `${SPEND_QUESTION}
1488
- ${ROUTING_FEE_TERMS}
1489
- ${FEE_APPROVAL}`
1490
- );
1491
- if (choice === null) throw installCancelled();
1492
- if (choice === "approve") return { ...ROUTER_DEFAULTS };
1493
- const ask = deps.promptAmount ?? promptAmount;
1494
- const sessionBudget = await askLimit(
1495
- ask,
1496
- "Most it may pay in a day, in USD, or none",
1497
- "5",
1498
- "day"
1499
- );
1500
- const maxAutoSpend = await askLimit(
1501
- ask,
1502
- "Most it may pay for one call, in USD, at least 0.25",
1503
- "0.25",
1504
- "call"
1505
- );
1506
- return { maxAutoSpend, sessionBudget };
1507
- }
1508
- async function askLimit(ask, question, placeholder, per) {
1509
- let message = question;
1510
- for (; ; ) {
1511
- const answer = await ask(message, placeholder);
1512
- if (answer === null) throw installCancelled();
1513
- const parsed = parseLimit(answer, per);
1514
- if (!("refusal" in parsed)) return parsed.value;
1515
- message = `${parsed.refusal} ${question}`;
1532
+ var NEW_SESSION_STEP = "start a new Claude Code session so Tenjin loads";
1533
+ var RELOAD_STEP = "run `/reload-plugins` in this conversation so Tenjin loads, then continue your task";
1534
+ function loadStep(settingsInstallPresent, env = {}, command = "tenjin") {
1535
+ if (env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop" || env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop-3p") {
1536
+ return `choose New session in Claude Desktop's Code tab for this same folder so Tenjin loads. Before switching, give the person one short ready-to-paste continuation prompt filled with this conversation's task, progress and next action; carry over the person's funding and spending choices, and have the next session check Tenjin with \`${command} doctor\`${process.platform === "win32" ? " in PowerShell" : ""} before continuing`;
1516
1537
  }
1538
+ if (!underAgentHarness(env))
1539
+ return "open a new Claude Code session so Tenjin loads, then continue your task";
1540
+ return settingsInstallPresent ? NEW_SESSION_STEP : RELOAD_STEP;
1517
1541
  }
1518
- function parseLimit(answer, per) {
1519
- const trimmed = answer.trim();
1520
- if (per === "day" && trimmed === "none") return { value: "none" };
1521
- let atomic;
1522
- try {
1523
- atomic = parseUsdToAtomic(trimmed);
1524
- } catch (err) {
1525
- if (err instanceof CliError) return { refusal: `${err.message}.` };
1526
- throw err;
1542
+ async function pluginProof(claude, dataDir, env, cwd) {
1543
+ if (claude.binary !== null && !claude.meetsFloor) {
1544
+ return {
1545
+ proven: false,
1546
+ reason: `Claude Code ${claude.version ?? "(unknown)"} is older than the plugin needs`
1547
+ };
1527
1548
  }
1528
- if (per === "call" && BigInt(atomic) < MAX_AUTO_SPEND_FLOOR_ATOMIC) {
1529
- return { refusal: "The per-call limit is at least $0.25." };
1549
+ if (claude.binary !== null) {
1550
+ const listing = await readPluginListing(claude.binary, env, cwd);
1551
+ if (!listing.enabled) {
1552
+ return { proven: false, reason: "Claude Code does not list the plugin as enabled yet" };
1553
+ }
1530
1554
  }
1531
- if (atomic === "0") {
1555
+ if (await readAliveStamp(dataDir) === null) {
1532
1556
  return {
1533
- refusal: "The limit must be more than zero; `tenjin config set router.enabled false` turns the router off."
1557
+ proven: false,
1558
+ reason: "the plugin has not loaded in a Claude Code session on this machine yet"
1534
1559
  };
1535
1560
  }
1536
- return { value: atomic };
1537
- }
1538
- function installCancelled() {
1539
- return new CliError("REFUSED", "Install cancelled before anything was written.", {
1540
- fix: "Re-run `tenjin install` and choose the defaults or your own limits."
1541
- });
1561
+ return { proven: true };
1542
1562
  }
1543
- function promptLimits(message) {
1544
- return selectOne({
1545
- message,
1546
- choices: [
1547
- { value: "approve", label: "Use the defaults" },
1548
- { value: "own", label: "Set my own limits" }
1549
- ],
1550
- initialValue: "approve"
1563
+ async function migrateSettingsInstall(legacy, claude, opts) {
1564
+ if (!legacy.present) return { state: "none", settingsPath: legacy.settingsPath };
1565
+ const proof = await pluginProof(claude, opts.dataDir, opts.env, opts.cwd);
1566
+ if (!proof.proven) {
1567
+ return { state: "pending", settingsPath: legacy.settingsPath, reason: proof.reason };
1568
+ }
1569
+ const removed = await removeLegacyInstall(legacy, {
1570
+ binary: claude.binary,
1571
+ env: opts.env,
1572
+ cwd: opts.cwd,
1573
+ mcpScope: opts.mcpScope
1551
1574
  });
1575
+ return { state: "done", settingsPath: legacy.settingsPath, removed };
1552
1576
  }
1553
- function promptAmount(message, placeholder) {
1554
- return askText({ message, placeholder });
1577
+ async function projectInstallHere(cwd, home, env) {
1578
+ if (await samePath(cwd, home)) return false;
1579
+ return projectInstallAt(cwd, home, env);
1555
1580
  }
1556
- function effectiveLimits(policy) {
1557
- return {
1558
- maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,
1559
- sessionBudget: policy.sessionBudgetAtomic === null ? "no daily ceiling" : toMoney(policy.sessionBudgetAtomic.toString()).usd
1560
- };
1581
+ async function projectInstallAt(dir, home, env) {
1582
+ const atHome = await samePath(dir, home);
1583
+ return claudeInstallAt(
1584
+ "local",
1585
+ env,
1586
+ home,
1587
+ dir,
1588
+ atHome ? ["enabled"] : ["enabled", "folder", "settings-hooks"]
1589
+ );
1561
1590
  }
1562
- function walletLines(ctx, ok, w) {
1563
- const warn = (text) => paint(ctx.io, "yellow", text);
1564
- if (w.status === "created" || w.status === "existing") {
1565
- const a = w.address ?? "";
1566
- const signing = w.signing;
1567
- const tty = ctx.io.isTTY;
1568
- if (signing?.status === "blocked") {
1569
- const wallet = Object.prototype.hasOwnProperty.call(WALLET_REASONS, signing.reason) ? WALLET_REASONS[signing.reason] : void 0;
1570
- return [
1571
- warn(`! Wallet ${a} cannot be unlocked by Claude Code: ${signing.detail}.`),
1572
- ` ${tty ? wallet?.fix ?? signing.fix : agentFixFor(signing.reason, signing.fix)}`
1573
- ];
1574
- }
1575
- if (signing?.status === "unknown") {
1576
- return [
1577
- warn(`! Wallet: ${a}; could not check that it unlocks (${signing.detail}).`),
1578
- " Run `tenjin doctor` to check it again."
1579
- ];
1580
- }
1581
- if (w.shellOnly === "key") {
1582
- return [
1583
- warn(
1584
- `! Wallet: ${a} signs here only through TENJIN_WALLET_KEY in this shell; Claude Code must have the same variable.`
1585
- )
1586
- ];
1587
- }
1588
- if (w.shellOnly === "passphrase") {
1589
- return [
1590
- warn(
1591
- tty ? `! 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}.` : `! 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.`
1592
- )
1593
- ];
1594
- }
1595
- if (w.status === "created") {
1596
- return [
1597
- `${ok} Wallet created: ${a}`,
1598
- ...w.passphrase !== void 0 ? [` ${w.passphrase.note}`] : []
1599
- ];
1600
- }
1601
- return [`${ok} Wallet: ${a}`];
1591
+ var NOTHING_TO_REFRESH = "Nothing to refresh";
1592
+ async function somethingToRefresh(claude, scope, legacy, env, home, cwd) {
1593
+ if (legacy.present) return true;
1594
+ if ((await folderState(scope, env, home, cwd)).state === "ours") return true;
1595
+ if (claude.binary !== null) {
1596
+ const listing = await readPluginListing(claude.binary, env, cwd);
1597
+ if (listing.id === PLUGIN_ID) return true;
1602
1598
  }
1603
- if (w.reason === "flag") return [" No wallet yet. Create one with: tenjin wallet create"];
1604
- return [
1605
- paint(ctx.io, "yellow", `! No wallet was created. ${w.warning ?? ""}`.trimEnd()),
1606
- ` ${w.fix ?? "Create one with: tenjin wallet create"}`
1607
- ];
1599
+ return false;
1608
1600
  }
1609
- function pluginLines(ctx, plugin) {
1610
- const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
1611
- if (plugin.state === "deferred") return [warn(`${plugin.reason ?? ""}`)];
1612
- if (plugin.state === "failed") {
1613
- return [warn(`The Tenjin plugin was not registered: ${plugin.reason ?? "unknown reason"}`)];
1601
+ async function runRouterInstall(args, ctx, deps = {}) {
1602
+ const newInstall = deps.newInstall ?? await captureNewInstall(ctx.dataDir);
1603
+ const env = deps.env ?? process.env;
1604
+ const home = deps.homeDir ?? homedir2();
1605
+ if (!isAbsolute(home)) {
1606
+ throw new CliError("INTERNAL", "The home directory is not an absolute path.", {
1607
+ fix: "Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`."
1608
+ });
1614
1609
  }
1615
- if (plugin.method === "skills-dir") {
1616
- return [
1617
- ` Plugin ${plugin.id ?? ""} written to ${plugin.path ?? ""} (${plugin.fallbackReason ?? ""})`
1618
- ];
1610
+ assertPluginInstallation(ctx.dataDir, home, env);
1611
+ const config = await loadRawConfig(ctx.dataDir);
1612
+ const named = namedLimits(args);
1613
+ const cwd = deps.cwd ?? process.cwd();
1614
+ const project = args.project ?? (args.refresh === true && await projectInstallHere(cwd, home, env));
1615
+ const scope = project ? "local" : "user";
1616
+ const claude = await readClaudeCode(env, cwd, deps.findClaude ?? findClaudeBinary);
1617
+ const paths = settingsInstallPaths(project, env, home, cwd);
1618
+ const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);
1619
+ const setUpRuntime = () => (deps.runtime ?? defaultRuntime)({
1620
+ dataDir: ctx.dataDir,
1621
+ home,
1622
+ env,
1623
+ version: package_default.version,
1624
+ moduleDir: dirname3(fileURLToPath3(import.meta.url)),
1625
+ refresh: args.refresh === true
1626
+ });
1627
+ if (args.refresh === true && !await somethingToRefresh(claude, scope, legacy, env, home, cwd)) {
1628
+ if (!project && hasRuntime(ctx.dataDir, home)) {
1629
+ const rt2 = await setUpRuntime();
1630
+ requireRuntime(rt2);
1631
+ await recordClaudeProjects(ctx.dataDir, config.install?.routerProjects ?? [], env, home);
1632
+ if (runtimeLaunch(rt2) !== null) {
1633
+ await collectRuntime(rt2.root, await fallbackFolders(ctx.dataDir, env, home, cwd, false));
1634
+ }
1635
+ return runtimeOnlyRefresh(ctx, rt2, home);
1636
+ }
1637
+ if (!project)
1638
+ await recordClaudeProjects(ctx.dataDir, config.install?.routerProjects ?? [], env, home);
1639
+ throw new CliError(
1640
+ "REFUSED",
1641
+ `${NOTHING_TO_REFRESH}: neither the ${PLUGIN_ID} plugin nor a settings install of Tenjin is registered here.`,
1642
+ { fix: "Run `tenjin install` to set this machine up." }
1643
+ );
1619
1644
  }
1620
- return [];
1621
- }
1622
- function migrationLines(ctx, migration) {
1623
- const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
1624
- if (migration.state === "pending") {
1625
- return [
1626
- ` The settings install in ${migration.settingsPath} stays until the plugin has loaded (${migration.reason ?? ""}); \`tenjin update\` or \`tenjin install\` removes it then.`
1627
- ];
1645
+ const humanOutput = ctx.flags.json === true ? false : deps.isInteractive ?? ctx.io.isTTY;
1646
+ const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));
1647
+ const answered = args.yes === true || named.keys.length > 0;
1648
+ const unasked = config.maxAutoSpend === void 0 && config.sessionBudget === void 0;
1649
+ const limits = args.refresh === true ? void 0 : named.keys.length > 0 ? { ...shownLimits(config), ...named.limits } : args.yes === true ? shownLimits(config) : canPrompt && unasked ? await approveLimits(deps) : {};
1650
+ if (args.refresh !== true)
1651
+ await reserveNewInstall(
1652
+ newInstall,
1653
+ !legacy.present && (!newInstall.absent || !await somethingToRefresh(claude, scope, legacy, env, home, cwd))
1654
+ );
1655
+ const deferred = !claude.meetsFloor && legacy.present;
1656
+ const rt = deferred ? null : await setUpRuntime();
1657
+ requireRuntime(rt);
1658
+ if (!project) {
1659
+ await recordClaudeProjects(ctx.dataDir, config.install?.routerProjects ?? [], env, home);
1628
1660
  }
1629
- if (migration.state === "blocked") {
1630
- return [warn(`${migration.settingsPath} could not be read: ${migration.reason ?? ""}`)];
1661
+ const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true, limits, named.keys);
1662
+ if (args.refresh !== true && (answered || canPrompt && unasked)) {
1663
+ await recordTermsTold(ctx.dataDir);
1631
1664
  }
1632
- if (migration.state === "done") {
1633
- const removed = migration.removed;
1634
- const status = statusLineNotice(migration);
1635
- return [
1636
- ` Removed the earlier settings setup from ${migration.settingsPath}: the plugin carries its hooks, permissions and server`,
1637
- ...status !== null ? [` ${status}`] : [],
1638
- ...(removed?.warnings ?? []).map((w) => warn(w))
1639
- ];
1665
+ const removedKeysLines = spend.removed.length > 0 ? [
1666
+ `Removed retired settings: ${spend.removed.join(", ")}. Automatic router limits remain in effect; manual pay always requires consent.`
1667
+ ] : [];
1668
+ const removedSkills = await removeRetiredSkills(home, project ? cwd : void 0);
1669
+ const launch = runtimeLaunch(rt);
1670
+ const plugin = deferred ? deferredRegistration(scope, claude) : await registerPlugin({
1671
+ binary: claude.binary,
1672
+ scope,
1673
+ version: launch?.version ?? package_default.version,
1674
+ env,
1675
+ home,
1676
+ cwd,
1677
+ ...launch !== null ? { hostsDir: launch.hostsDir, cliEntry: launch.cliEntry, node: launch.node } : {
1678
+ ...deps.hostsDir !== void 0 ? { hostsDir: deps.hostsDir } : {},
1679
+ ...deps.cliEntry !== void 0 ? { cliEntry: deps.cliEntry } : {}
1680
+ }
1681
+ });
1682
+ if (rt !== null && launch !== null) {
1683
+ if (plugin.state !== "failed") {
1684
+ await collectRuntime(rt.root, await fallbackFolders(ctx.dataDir, env, home, cwd, project));
1685
+ } else if (!marketplaceAdded(plugin, launch.hostsDir)) {
1686
+ await rt.restore?.().catch(() => void 0);
1687
+ }
1640
1688
  }
1641
- return [];
1642
- }
1643
- function claudeLines(ctx, claude) {
1644
- if (claude.meetsFloor) return [];
1645
- return [
1646
- paint(
1647
- ctx.io,
1648
- "yellow",
1649
- `! Claude Code ${claude.version ?? ""} is older than the plugin needs. ${claude.fix ?? ""}`.trim()
1650
- )
1651
- ];
1652
- }
1653
- function lines(ctx, s) {
1654
- const ok = paint(ctx.io, "green", "\u2713");
1655
- const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
1656
- const limits = effectiveLimits(s.policy);
1657
- const daily = s.policy.sessionBudgetAtomic === null ? "no daily limit" : `$${limits.sessionBudget} a day`;
1658
- const spend = [
1659
- ` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`,
1660
- ...s.spendAsk !== void 0 ? [
1661
- ` Ask the person in this session: ${s.spendAsk.question}`,
1662
- ...s.spendAsk.options.map(
1663
- (o) => ` ${o.label}${o.recommended ? " (recommended)" : ""}: ${o.command}`
1664
- )
1665
- ] : []
1666
- ];
1667
- const router = s.router.status === "ok" ? [] : [
1668
- warn(`The router did not answer: ${s.router.detail}`),
1669
- ...s.router.fix !== void 0 ? [` ${s.router.fix}`] : []
1670
- ];
1671
- return [
1672
- s.plugin.state === "failed" ? warn("Tenjin could not finish setting up Claude Code") : s.plugin.state === "deferred" ? warn("Tenjin keeps its earlier Claude Code setup until Claude Code is updated") : `${ok} Tenjin is set up for Claude Code (plugin ${s.plugin.id ?? PLUGIN_ID})`,
1673
- ...s.plugin.scope === "local" && s.plugin.state !== "failed" ? [` For this project only; check it with: ${continuationCommand(s.rt)} doctor --project`] : [],
1674
- ...runtimeLines(ctx, s.rt, s.home),
1675
- ...walletLines(ctx, ok, s.wallet),
1676
- ...spend,
1677
- ...s.fund !== void 0 ? fundLines(s.fund) : [],
1678
- ...s.fundingWarning !== void 0 ? [warn(s.fundingWarning)] : [],
1679
- ...pluginLines(ctx, s.plugin),
1680
- ...claudeLines(ctx, s.claude),
1681
- ...migrationLines(ctx, s.migration),
1682
- ...router,
1683
- "",
1684
- `Next: ${nextStep(s.plugin, s.claude, s.wallet, s.migration, s.asks, ctx.io.isTTY, continuationCommand(s.rt), s.env)}`
1685
- ];
1686
- }
1687
- function refreshLines(ctx, plugin, claude, migration, rt, home) {
1688
- const issues = [
1689
- ...runtimeLines(ctx, rt, home),
1690
- ...pluginLines(ctx, plugin),
1691
- ...claudeLines(ctx, claude),
1692
- ...migrationLines(ctx, migration)
1689
+ if (project && plugin.state !== "failed") {
1690
+ await persistRouterProject(ctx.dataDir, cwd).catch(() => void 0);
1691
+ }
1692
+ const migration = legacy.unreadable !== void 0 && !legacy.present ? { state: "blocked", settingsPath: paths.settingsPath, reason: legacy.unreadable } : await migrateSettingsInstall(legacy, claude, {
1693
+ dataDir: ctx.dataDir,
1694
+ env,
1695
+ cwd,
1696
+ mcpScope: paths.mcpScope
1697
+ });
1698
+ const pending = settingsInstallStays(migration);
1699
+ const servers = await readMcpServers(deps, {
1700
+ settingsInstallPending: pending,
1701
+ ...launch !== null ? { version: launch.version } : {}
1702
+ });
1703
+ const serverLines = servers.stale > 0 ? [paint(ctx.io, "yellow", `! ${servers.check.detail}. ${servers.check.fix ?? ""}`.trim())] : [];
1704
+ const claudeCode = claudeCodeData(claude);
1705
+ const notices = refreshNotices(plugin, claude, migration, rt, home);
1706
+ if (args.refresh === true) {
1707
+ if (plugin.state === "failed" && migration.state !== "pending") {
1708
+ throw new CliError(
1709
+ "REFUSED",
1710
+ `The ${PLUGIN_ID} plugin could not be registered: ${plugin.reason ?? "unknown reason"}.`,
1711
+ { fix: registrationFix(plugin), details: { plugin, claudeCode, migration } }
1712
+ );
1713
+ }
1714
+ return {
1715
+ data: {
1716
+ plugin,
1717
+ claudeCode,
1718
+ migration,
1719
+ notices,
1720
+ refresh: true,
1721
+ spend,
1722
+ removedSkills,
1723
+ scope,
1724
+ mcpServer: servers.check,
1725
+ runtime: runtimeData(rt),
1726
+ launcher: rt?.launcher ?? null
1727
+ },
1728
+ humanLines: [
1729
+ ...refreshLines2(ctx, plugin, claude, migration, rt, home),
1730
+ ...removedKeysLines,
1731
+ ...serverLines
1732
+ ]
1733
+ };
1734
+ }
1735
+ const { resolveWallet } = await import("./install-wallet-2SFOVE3Q.js");
1736
+ const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? "flag" : void 0, false);
1737
+ const effective = await resolveContextSettings(ctx);
1738
+ const command = continuationCommand(rt);
1739
+ const spendAsk = !canPrompt && !answered && unasked ? spendStep(args, command) : void 0;
1740
+ const asksAgent = !canPrompt && underAgentHarness(env);
1741
+ const [router, funding] = await Promise.all([
1742
+ probeRouter(effective.baseUrl, {
1743
+ timeoutMs: ctx.flags.timeout,
1744
+ env,
1745
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
1746
+ }),
1747
+ // The spend question comes first, because its answer picks the install
1748
+ // command. Funding instructions ride on the install that follows it.
1749
+ (asksAgent || canPrompt) && spendAsk === void 0 && plugin.state !== "failed" && plugin.state !== "deferred" ? (deps.funding ?? fundStep)(
1750
+ wallet,
1751
+ effective.rpcUrl,
1752
+ deps,
1753
+ `${command} fund ${SUGGESTED_FUND_USD}`
1754
+ ) : Promise.resolve(void 0)
1755
+ ]);
1756
+ const fund = funding?.step;
1757
+ const nextSteps = [
1758
+ ...spendAsk !== void 0 ? [spendAsk] : [],
1759
+ ...fund !== void 0 ? [fund] : []
1693
1760
  ];
1694
- const head = plugin.state === "failed" ? paint(ctx.io, "yellow", "! Tenjin is updated, but its plugin was not registered") : plugin.state === "deferred" ? paint(ctx.io, "yellow", "! Tenjin is updated; its plugin waits for a newer Claude Code") : `${paint(ctx.io, "green", "\u2713")} Tenjin is up to date (plugin ${plugin.id ?? PLUGIN_ID})`;
1695
- return [head, ...issues];
1761
+ const data = {
1762
+ plugin,
1763
+ claudeCode,
1764
+ migration,
1765
+ next: nextStep(
1766
+ plugin,
1767
+ claude,
1768
+ wallet,
1769
+ migration,
1770
+ asksAgent ? nextSteps.length : 0,
1771
+ ctx.io.isTTY,
1772
+ command,
1773
+ env
1774
+ ),
1775
+ nextSteps,
1776
+ ...funding?.warning !== void 0 ? { fundingWarning: funding.warning } : {},
1777
+ // The check for this scope, said outright; a bare doctor in the project
1778
+ // also finds it from what the project holds.
1779
+ ...project ? { doctor: `${command} doctor --project` } : {},
1780
+ spend: { ...spend, effective: effectiveLimits(effective.policy) },
1781
+ wallet,
1782
+ router: {
1783
+ status: router.status === "ok" ? "ok" : "warn",
1784
+ detail: router.detail,
1785
+ ...router.fix !== void 0 ? { fix: router.fix } : {}
1786
+ },
1787
+ disclosure: DISCLOSURE,
1788
+ removedSkills,
1789
+ mcpServer: servers.check,
1790
+ runtime: runtimeData(rt),
1791
+ launcher: rt?.launcher ?? null
1792
+ };
1793
+ newInstall.completed.push(plugin.state !== "failed" && plugin.state !== "deferred");
1794
+ newInstall.continueWith ??= installCommand(args, command);
1795
+ const result = {
1796
+ data,
1797
+ humanLines: [
1798
+ ...lines(ctx, {
1799
+ plugin,
1800
+ claude,
1801
+ migration,
1802
+ wallet,
1803
+ ...funding?.warning !== void 0 ? { fundingWarning: funding.warning } : {},
1804
+ asks: asksAgent ? nextSteps.length : 0,
1805
+ policy: effective.policy,
1806
+ ...spendAsk !== void 0 ? { spendAsk } : {},
1807
+ router,
1808
+ rt,
1809
+ home,
1810
+ env
1811
+ }),
1812
+ ...removedKeysLines,
1813
+ ...serverLines
1814
+ ],
1815
+ humanTail: receiptTail(ctx, effective.policy, data.next)
1816
+ };
1817
+ return deps.newInstall ? result : finishNewInstall(result, newInstall, ctx, {
1818
+ ...args.subagents !== void 0 ? { choice: args.subagents } : {},
1819
+ yes: args.yes === true,
1820
+ isInteractive: canPrompt,
1821
+ ...deps.promptSubagents ? { promptSubagents: deps.promptSubagents } : {}
1822
+ });
1696
1823
  }
1697
-
1698
- // src/commands/update.ts
1699
- var INSTALL_TIMEOUT_MS = 3e5;
1700
- var STAGE_TIMEOUT_MS = 12e4;
1701
- var NODE_TIMEOUT_MS = 3e5;
1702
- var BACKGROUND_COOLDOWN_MS = 24 * 60 * 6e4;
1703
- function resolveManager(manager, deps) {
1704
- const script = deps.managerScript !== void 0 ? deps.managerScript : resolveManagerScript(manager, process.execPath);
1705
- return script === null ? { cmd: MANAGERS[manager].bin, prefix: [] } : { cmd: process.execPath, prefix: [script] };
1824
+ async function defaultRuntime(o) {
1825
+ const { setupRuntime } = await import("./runtime-2GX4ALJP.js");
1826
+ return setupRuntime(o);
1706
1827
  }
1707
- async function runUpdate(opts, ctx, deps = {}) {
1708
- if (opts.background !== true) return update(opts, ctx, deps);
1709
- const root = deps.runtimeRoot ?? runtimeDir(ctx.dataDir);
1710
- const [{ recordAutoUpdate }, { readRuntimeState }] = await Promise.all([
1711
- import("./auto-update-Y24UL56V.js"),
1712
- import("./runtime-layout-WIDILZ6K.js")
1713
- ]);
1714
- const from = readRuntimeState(root)?.current.cli;
1715
- const record = (r) => {
1716
- if (!existsSync2(root)) return;
1717
- try {
1718
- recordAutoUpdate(root, { finishedAt: (/* @__PURE__ */ new Date()).toISOString(), ...r });
1719
- } catch {
1828
+ var sharedResults = /* @__PURE__ */ new WeakSet();
1829
+ function runtimeOncePerRun(setup = defaultRuntime) {
1830
+ let first;
1831
+ return async (o) => {
1832
+ if (first === void 0) {
1833
+ first = setup(o).then((rt2) => {
1834
+ const restore = rt2.restore;
1835
+ if (restore === void 0) return rt2;
1836
+ return {
1837
+ ...rt2,
1838
+ restore: async () => {
1839
+ try {
1840
+ await restore();
1841
+ } finally {
1842
+ first = void 0;
1843
+ }
1844
+ }
1845
+ };
1846
+ });
1847
+ return first;
1720
1848
  }
1849
+ const rt = { ...await first };
1850
+ delete rt.restore;
1851
+ sharedResults.add(rt);
1852
+ return rt;
1721
1853
  };
1854
+ }
1855
+ function runtimeOnlyRefresh(ctx, rt, home) {
1856
+ return {
1857
+ data: {
1858
+ plugin: null,
1859
+ refresh: true,
1860
+ scope: "user",
1861
+ notices: runtimeNotices(rt, home),
1862
+ runtime: runtimeData(rt),
1863
+ launcher: rt.launcher
1864
+ },
1865
+ humanLines: [
1866
+ `${paint(ctx.io, "green", "\u2713")} Tenjin's runtime is up to date; no Claude Code plugin is registered here, so none was refreshed`,
1867
+ ...runtimeLines(ctx, rt, home)
1868
+ ]
1869
+ };
1870
+ }
1871
+ async function collectRuntime(root, folders) {
1722
1872
  try {
1723
- const result = await update(opts, ctx, deps);
1724
- const d = result.data;
1725
- record(
1726
- d.skipped !== void 0 ? { outcome: "skipped", reason: d.skipped } : d.updated === true ? { outcome: "updated", from: d.current, to: d.latest } : { outcome: "current", from: d.current, to: d.current }
1727
- );
1728
- return result;
1729
- } catch (err) {
1730
- const reason = sanitizeForTerminal(err instanceof Error ? err.message : String(err)).trim();
1731
- record({
1732
- outcome: "failed",
1733
- ...from !== void 0 ? { from } : {},
1734
- reason: reason.slice(0, REASON_LIMIT)
1735
- });
1736
- throw err;
1873
+ const { collect } = await import("./runtime-activate-IDQ2NCSP.js");
1874
+ await collect(root, { lockWaitMs: 5e3, keep: await folderPointers(root, folders) });
1875
+ } catch {
1737
1876
  }
1738
1877
  }
1739
- async function update(opts, ctx, deps) {
1740
- const current = deps.currentVersion ?? package_default.version;
1741
- const channel = channelTag(current);
1742
- const moduleDir = deps.moduleDir ?? fileURLToPath3(new URL(".", import.meta.url));
1743
- if (channel === null) {
1744
- throw new CliError("REFUSED", `tenjin-cli reports an unrecognizable version (${current})`, {
1745
- fix: "Reinstall a published build: npm i -g tenjin-cli"
1746
- });
1878
+ async function fallbackFolders(dataDir, env, home, cwd, project) {
1879
+ const projects = (await loadRawConfig(dataDir).catch(() => null))?.install?.routerProjects ?? [];
1880
+ return [
1881
+ folderFor("user", env, home, cwd),
1882
+ ...[...projects, ...project ? [cwd] : []].map((dir) => folderFor("local", env, home, dir))
1883
+ ];
1884
+ }
1885
+ var NODE_DIR_RE = /^\d+\.\d+\.\d+$/;
1886
+ async function folderPointers(root, folders) {
1887
+ const pointers = [];
1888
+ for (const dir of folders) {
1889
+ if (await inspectPluginFolder(dir) !== "ours") continue;
1890
+ const server = await readFile5(join5(dir, ".mcp.json"), "utf8").then(
1891
+ (raw) => JSON.parse(raw).mcpServers?.[MCP_SERVER_NAME]
1892
+ ).catch(() => void 0);
1893
+ const entry = Array.isArray(server?.args) ? server.args[0] : void 0;
1894
+ const node = server?.command;
1895
+ if (typeof entry !== "string" || typeof node !== "string") continue;
1896
+ const build = runtimeBuild(dirname3(entry));
1897
+ const nodeVersion = relative(join5(root, "node"), node).split(sep2)[0] ?? "";
1898
+ if (build !== null && resolve2(build.root) === resolve2(root) && NODE_DIR_RE.test(nodeVersion)) {
1899
+ pointers.push({ cli: build.cli, node: nodeVersion });
1900
+ }
1747
1901
  }
1748
- refuse(moduleDir, { check: opts.check, spec: null });
1749
- const tags = await fetchDistTags({
1750
- fetchImpl: deps.fetchImpl,
1751
- timeoutMs: ctx.flags.timeout
1752
- });
1753
- if (tags === null) {
1754
- throw new CliError("NETWORK_ERROR", "Could not read tenjin-cli dist-tags from npm", {
1755
- fix: "Check access to registry.npmjs.org and retry"
1902
+ return pointers;
1903
+ }
1904
+ function assertPluginInstallation(dataDir, home, env) {
1905
+ if (env.TENJIN_DATA_DIR && !isDefaultDataDir(dataDir, home)) {
1906
+ throw new CliError("REFUSED", "Plugin installation needs the default data directory.", {
1907
+ fix: "Run without TENJIN_DATA_DIR. Other CLI commands still support it."
1756
1908
  });
1757
1909
  }
1758
- const runtime = await runtimeHere(ctx, deps, moduleDir);
1759
- if (opts.background === true && runtime === null) {
1760
- return {
1761
- data: { skipped: "no runtime" },
1762
- humanLines: ["Nothing to update in the background: Tenjin's runtime is not set up here."]
1763
- };
1910
+ if (!isSourceCheckout(dirname3(fileURLToPath3(import.meta.url)))) {
1911
+ const unsupported = unpinnedPlatform(process.platform, process.arch, runningGlibc());
1912
+ if (unsupported !== null)
1913
+ throw new CliError("REFUSED", `Plugin installation is unsupported on ${unsupported}.`, {
1914
+ fix: "Use macOS, Windows or glibc Linux 2.28+ on x64/arm64. Your existing setup was kept."
1915
+ });
1764
1916
  }
1765
- const base = runtime?.current ?? current;
1766
- const latest = resolveTarget(base, tags);
1767
- if (latest === null) {
1768
- const raw = tags[channel];
1769
- throw raw === void 0 ? new CliError("RESOURCE_NOT_FOUND", "npm has no published tenjin-cli on the latest tag", {
1770
- fix: "Pick a version yourself: npm view tenjin-cli versions"
1771
- }) : new CliError(
1772
- "RESOURCE_NOT_FOUND",
1773
- // Registry-controlled: bounded here, escaped by the error emitter.
1774
- `npm's latest tenjin-cli (${raw.slice(0, 40)}) is not a version this build can read`,
1917
+ }
1918
+ function continuationCommand(rt, platform = process.platform) {
1919
+ if (rt === null || rt.state === "skipped" || rt.node === void 0 || rt.entry === void 0)
1920
+ return "tenjin";
1921
+ const launcher = rt.launcher;
1922
+ const verifiedLauncher = launcher?.state === "written" || launcher?.state === "current";
1923
+ const path = verifiedLauncher ? launcher.paths.find((p) => platform !== "win32" || p.endsWith(".cmd")) : void 0;
1924
+ const parts = path === void 0 ? [rt.node, rt.entry] : [path];
1925
+ return platform === "win32" ? `& ${parts.map((part) => `'${part.replaceAll("'", "''")}'`).join(" ")}` : parts.map(shQuote).join(" ");
1926
+ }
1927
+ function requireRuntime(rt) {
1928
+ if (rt === null || rt.state === "skipped") return;
1929
+ if (rt.state === "failed" || rt.state === "kept" && rt.reason !== void 0 && rt.newer !== true) {
1930
+ throw new CliError(
1931
+ "UPDATE_FAILED",
1932
+ `Tenjin could not finish installation: ${rt.reason ?? "runtime setup failed"}. Your existing plugin registration was kept.`,
1775
1933
  {
1776
- fix: "Install it by name: npm i -g tenjin-cli@<version> (npm view tenjin-cli versions)"
1934
+ fix: rt.fix ?? (rt.unpinned ? "Use macOS, Windows or glibc Linux 2.28+ on x64/arm64." : "Check your connection and run tenjin install again.")
1777
1935
  }
1778
1936
  );
1779
1937
  }
1780
- const updateAvailable = isNewer(latest, base);
1781
- const data = (updated2) => ({
1782
- current: base,
1783
- latest,
1784
- updateAvailable,
1785
- updated: updated2
1786
- });
1787
- if (!updateAvailable) {
1788
- return {
1789
- data: data(false),
1790
- humanLines: [`tenjin-cli ${base} is up to date`]
1791
- };
1792
- }
1793
- if (opts.check) {
1794
- return {
1795
- data: data(false),
1796
- humanLines: [
1797
- `tenjin-cli ${latest} is available (you have ${base}).`,
1798
- "Run tenjin update to install it."
1799
- ]
1800
- };
1801
- }
1802
- if (opts.background === true) {
1803
- const wait = await tooNewForBackground(latest, ctx, deps);
1804
- if (wait !== null) {
1805
- return {
1806
- data: { ...data(false), skipped: wait },
1807
- humanLines: [`${wait}; the background update takes a release a day after it is published.`]
1808
- };
1809
- }
1810
- }
1811
- if (runtime !== null) {
1812
- return runtimeUpdate(ctx, deps, { ...runtime, base, latest, current, moduleDir, data });
1813
- }
1814
- await refuseRuntimeElsewhere(ctx, moduleDir, deps.homeDir ?? homedir2());
1815
- const spec = `tenjin-cli@${latest}`;
1816
- refuse(moduleDir, { check: false, spec });
1817
- const { checkReleaseProvenance } = await import("./runtime-UZOKSUZX.js");
1818
- await checkReleaseProvenance(latest, {
1819
- timeoutMs: ctx.flags.timeout,
1820
- fetchImpl: deps.fetchImpl
1821
- });
1822
- const human = ctx.io.isTTY && !ctx.flags.json;
1823
- let tail = "";
1824
- const onOutput = (chunk) => {
1825
- tail = (tail + chunk).slice(-2e3);
1826
- if (human) ctx.io.stderr.write(chunk.split("\n").map(sanitizeForTerminal).join("\n"));
1827
- };
1828
- const manager = classifyManager(moduleDir);
1829
- const plan = MANAGERS[manager];
1830
- const args = plan.args(spec);
1831
- const resolved = resolveManager(manager, deps);
1832
- const manual = `Run it yourself: ${plan.manual(spec)}`;
1833
- const outcome = await (deps.spawnImpl ?? spawnCapture)(
1834
- resolved.cmd,
1835
- [...resolved.prefix, ...args],
1836
- { cwd: homedir2(), timeoutMs: INSTALL_TIMEOUT_MS },
1837
- onOutput
1838
- );
1839
- if (outcome.kind === "start-failed") {
1840
- throw new CliError("UPDATE_FAILED", `Could not start ${manager}`, {
1841
- fix: manual,
1842
- cause: outcome.cause
1843
- });
1844
- }
1845
- if (outcome.kind === "timeout") {
1846
- throw new CliError(
1847
- "UPDATE_FAILED",
1848
- `${manager} did not finish in ${INSTALL_TIMEOUT_MS / 1e3}s`,
1849
- { fix: manual, details: { output: tail } }
1850
- );
1938
+ }
1939
+ function runtimeLaunch(rt) {
1940
+ if (rt === null || rt.state !== "active" && rt.state !== "current" && rt.state !== "kept") {
1941
+ return null;
1851
1942
  }
1852
- if (outcome.code !== 0) {
1853
- throw new CliError("UPDATE_FAILED", `${manager} ${args.join(" ")} exited ${outcome.code}`, {
1854
- // EACCES on a root-owned global prefix is the common cause; the operator
1855
- // fixing that themselves beats this CLI ever escalating.
1856
- fix: manual,
1857
- details: { output: tail }
1858
- });
1943
+ if (rt.cli === void 0 || rt.hostsDir === void 0 || rt.entry === void 0 || rt.node === void 0) {
1944
+ return null;
1859
1945
  }
1860
- emitWriteNotice(
1861
- ctx.io,
1862
- `tenjin update: replaced the global tenjin-cli with ${latest} via ${manager}`
1863
- );
1864
- const { refresh } = await refreshProfiles(ctx, deps, npmLaunch(deps));
1865
- return updated(deps, data(true), refresh, [`Updated tenjin-cli ${current} -> ${latest}.`]);
1946
+ return { version: rt.cli, hostsDir: rt.hostsDir, cliEntry: rt.entry, node: rt.node };
1866
1947
  }
1867
- async function updated(deps, data, refresh, head, version) {
1868
- const servers = await readMcpServers(deps, {
1869
- settingsInstallPending: refresh.settingsInstallPending,
1870
- ...version !== void 0 ? { version } : {}
1871
- });
1948
+ function runtimeData(rt) {
1949
+ if (rt === null) return null;
1872
1950
  return {
1873
- data: { ...data, refresh, mcpServer: servers.check },
1874
- humanLines: [
1875
- ...head,
1876
- ...refreshLines2(refresh),
1877
- ...projectLines(refresh),
1878
- ...refresh.notices,
1879
- ...servers.stale > 0 ? [`! ${servers.check.detail}. ${servers.check.fix ?? ""}`.trim()] : []
1880
- ]
1951
+ state: rt.state,
1952
+ root: rt.root,
1953
+ ...rt.cli !== void 0 ? { cli: rt.cli } : {},
1954
+ ...rt.nodeVersion !== void 0 ? { nodeVersion: rt.nodeVersion } : {},
1955
+ ...rt.reason !== void 0 ? { reason: rt.reason } : {},
1956
+ ...rt.fix !== void 0 ? { fix: rt.fix } : {}
1881
1957
  };
1882
1958
  }
1883
- async function runtimeHere(ctx, deps, moduleDir) {
1884
- if (resolve2(ctx.dataDir) !== resolve2(defaultDataDir(deps.homeDir ?? homedir2()))) return null;
1885
- const { readRuntimeState, runtimeBuild: runtimeBuild2 } = await import("./runtime-layout-WIDILZ6K.js");
1886
- const root = deps.runtimeRoot ?? runtimeDir(ctx.dataDir);
1887
- const state = readRuntimeState(root);
1888
- const inRuntime = runtimeBuild2(moduleDir) !== null;
1889
- if (state === null && !inRuntime) return null;
1890
- return { root, current: state?.current.cli ?? null, inRuntime };
1891
- }
1892
- async function tooNewForBackground(latest, ctx, deps) {
1893
- const answer = await fetchPublishTime(latest, {
1894
- fetchImpl: deps.fetchImpl,
1895
- timeoutMs: ctx.flags.timeout
1896
- });
1897
- if (answer === null) {
1898
- throw new CliError("NETWORK_ERROR", `Could not read when tenjin-cli ${latest} was published`, {
1899
- fix: "Check access to registry.npmjs.org and retry"
1900
- });
1959
+ async function recordClaudeProjects(dataDir, known, env, home) {
1960
+ const records = await recordedInstalls(env, home).catch(() => null);
1961
+ if (records === null || records.every((r) => r.projectPath === null)) return;
1962
+ const seen = /* @__PURE__ */ new Set([...known, ...await Promise.all(known.map(realOr))]);
1963
+ for (const { projectPath } of records) {
1964
+ if (projectPath === null || seen.has(projectPath)) continue;
1965
+ if ((await stat3(projectPath).catch(() => null))?.isDirectory() !== true) continue;
1966
+ seen.add(projectPath);
1967
+ await persistRouterProject(dataDir, projectPath).catch(() => void 0);
1901
1968
  }
1902
- if (answer.publishedAt === null) return `npm names no publish time for tenjin-cli ${latest}`;
1903
- const age = (deps.now ?? Date.now)() - answer.publishedAt;
1904
- return age >= BACKGROUND_COOLDOWN_MS ? null : `tenjin-cli ${latest} was published under 24 hours ago`;
1905
1969
  }
1906
- async function refuseRuntimeElsewhere(ctx, moduleDir, home) {
1907
- const { runtimeBuild: runtimeBuild2 } = await import("./runtime-layout-WIDILZ6K.js");
1908
- if (runtimeBuild2(moduleDir) === null) return;
1909
- throw new CliError(
1910
- "REFUSED",
1911
- `This tenjin runs from Tenjin's runtime, which only the default data dir (${tilde2(defaultDataDir(home), home)}) uses, and TENJIN_DATA_DIR is ${tilde2(ctx.dataDir, home)}, so nothing was updated`,
1912
- {
1913
- 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`."
1914
- }
1915
- );
1970
+ function runtimeSentence(rt, home) {
1971
+ if (rt.state !== "active" || !rt.firstTime) return null;
1972
+ 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.`;
1916
1973
  }
1917
- async function runtimeUpdate(ctx, deps, o) {
1918
- const { root, base, latest } = o;
1919
- const [rt, layout] = await Promise.all([
1920
- import("./runtime-UZOKSUZX.js"),
1921
- import("./runtime-layout-WIDILZ6K.js")
1922
- ]);
1923
- const stays = `so ${base} stays`;
1924
- let stage;
1925
- if (latest === o.current && !o.inRuntime) {
1926
- const packageRoot = rt.packageRootOf(o.moduleDir);
1927
- if (packageRoot === null) {
1928
- throw new CliError(
1929
- "UPDATE_FAILED",
1930
- `tenjin-cli ${latest} cannot find its own package, ${stays}`,
1931
- {
1932
- fix: RUNTIME_MISSING_FIX
1933
- }
1934
- );
1935
- }
1936
- stage = await rt.stageSelf(root, packageRoot);
1937
- } else {
1938
- stage = await (deps.stage ?? rt.stageTarball)(root, latest, {
1939
- timeoutMs: STAGE_TIMEOUT_MS,
1940
- fetchImpl: deps.fetchImpl
1941
- }).catch((err) => {
1942
- throw proxyNamed(err, deps);
1943
- });
1974
+ function launcherSentence(launcher, home) {
1975
+ if (launcher === null) return null;
1976
+ if (launcher.state === "foreign") {
1977
+ const who = launcher.reason?.replace(/ is not Tenjin's$/, "") ?? launcher.paths[0] ?? "";
1978
+ 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.`;
1944
1979
  }
1945
- let node;
1946
- try {
1947
- const pin = rt.readNodePin(stage);
1948
- if (pin === null) {
1949
- throw new CliError("UPDATE_FAILED", `tenjin-cli ${latest} carries no Node pin, ${stays}`, {
1950
- fix: `Nothing to do: ${base} keeps running. Run \`tenjin update\` again after the next release.`
1951
- });
1952
- }
1953
- node = await (deps.ensure ?? rt.ensureNode)(root, pin, {
1954
- timeoutMs: NODE_TIMEOUT_MS,
1955
- fetchImpl: deps.fetchImpl
1956
- });
1957
- await (deps.place ?? rt.placeVersion)(root, stage, latest);
1958
- } catch (err) {
1959
- await rm2(stage, { recursive: true, force: true }).catch(() => void 0);
1960
- throw proxyNamed(err, deps);
1980
+ if (launcher.state === "failed") {
1981
+ const dir = launcher.paths[0] !== void 0 ? tilde(dirname3(launcher.paths[0]), home) : "";
1982
+ 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.`;
1961
1983
  }
1962
- const home = deps.homeDir ?? homedir2();
1963
- emitWriteNotice(ctx.io, `tenjin update: staged tenjin-cli ${latest} in ${tilde2(root, home)}`);
1964
- const { refresh, homeTail } = await refreshProfiles(ctx, deps, {
1965
- node,
1966
- entry: layout.versionEntry(root, latest)
1967
- });
1968
- if (layout.readRuntimeState(root)?.current.cli !== latest) {
1969
- throw new CliError("UPDATE_FAILED", `tenjin-cli ${latest} did not pass its checks, ${stays}`, {
1970
- fix: "Run `tenjin update` again; if it fails again, run `tenjin doctor`",
1971
- details: {
1972
- reason: refresh.failed[0]?.reason ?? runtimeReason(envelopeData(homeTail)) ?? "The new version did not switch the runtime to itself.",
1973
- output: homeTail.slice(-2e3)
1974
- }
1975
- });
1984
+ if ((launcher.state === "written" || launcher.state === "current") && !launcher.onPath) {
1985
+ 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 ?? ""}`;
1976
1986
  }
1977
- return updated(
1978
- deps,
1979
- o.data(true),
1980
- refresh,
1981
- [
1982
- `Updated tenjin-cli ${base} -> ${latest}.`,
1983
- `The previous version (${base}) stays as the fallback.`
1984
- ],
1985
- latest
1986
- );
1987
+ return null;
1987
1988
  }
1988
- function proxyNamed(err, deps) {
1989
- if (!(err instanceof CliError) || err.code !== "NETWORK_ERROR") return err;
1990
- const skipped = proxySkipped(process.env, deps.proxySupported);
1991
- if (skipped === null) return err;
1992
- const step2 = proxyNodeStep("tenjin update");
1993
- return new CliError("NETWORK_ERROR", `${err.message}: ${skipped}`, {
1994
- fix: `${step2.charAt(0).toUpperCase()}${step2.slice(1)}.`,
1995
- cause: err
1996
- });
1989
+ function runtimeLines(ctx, rt, home, concise = false) {
1990
+ if (rt === null || sharedResults.has(rt)) return [];
1991
+ const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
1992
+ const runs = runtimeSentence(rt, home);
1993
+ const launcher = launcherSentence(rt.launcher, home);
1994
+ return [
1995
+ ...!concise && runs !== null ? [` ${runs}`] : [],
1996
+ ...launcher !== null ? [warn(launcher)] : []
1997
+ ];
1997
1998
  }
1998
- function runtimeReason(data) {
1999
- const reason = data?.runtime?.reason;
2000
- if (typeof reason !== "string") return void 0;
2001
- const text = sanitizeForTerminal(reason).trim();
2002
- return text.length > 0 ? text.slice(0, REASON_LIMIT) : void 0;
1999
+ function claudeCodeData(claude) {
2000
+ return {
2001
+ binary: claude.binary?.path ?? null,
2002
+ source: claude.binary?.source ?? null,
2003
+ version: claude.version,
2004
+ meetsFloor: claude.meetsFloor,
2005
+ ...claude.fix !== void 0 ? { fix: claude.fix } : {}
2006
+ };
2003
2007
  }
2004
- function tilde2(path, home) {
2005
- return path === home || path.startsWith(`${home}${sep2}`) ? `~${path.slice(home.length)}` : path;
2008
+ function registrationFix(plugin) {
2009
+ const flag = plugin.scope === "local" ? " --project" : "";
2010
+ if (plugin.id !== null && plugin.method === "none") {
2011
+ return `${plugin.id} keeps serving this machine at the version Claude Code has; run \`tenjin install${flag}\` again to retry.`;
2012
+ }
2013
+ if (plugin.path !== void 0 && plugin.reason?.includes("not a folder this CLI wrote") === true) {
2014
+ return `Move ${plugin.path} aside, then run \`tenjin install${flag}\` again.`;
2015
+ }
2016
+ return `Run \`tenjin doctor${flag}\` to see the cause, then run \`tenjin install${flag}\` again.`;
2006
2017
  }
2007
- var REFRESH_TIMEOUT_MS = 6e4;
2008
- async function refreshProfiles(ctx, deps, launch) {
2009
- const home = deps.homeDir ?? homedir2();
2010
- const candidates = [ctx.dataDir];
2011
- const fixFor = (dataDir) => manualFix(dataDir, home, ctx.dataDir);
2012
- const profiles = [];
2013
- const unrun = [];
2014
- for (const dataDir of candidates) {
2015
- if (isExistingDir(dataDir)) profiles.push(dataDir);
2016
- else unrun.push({ dataDir, reason: "It is not a directory.", fix: fixFor(dataDir) });
2017
- }
2018
- if (launch === null) {
2019
- const reason = "This build has no entry the update could safely re-execute.";
2020
- return {
2021
- refresh: {
2022
- profiles: [],
2023
- failed: candidates.map((d) => ({ dataDir: d, reason, fix: fixFor(d) })),
2024
- notices: [],
2025
- settingsInstallPending: false,
2026
- projects: [],
2027
- projectsFailed: []
2028
- },
2029
- homeTail: ""
2030
- };
2018
+ var REPAIRABLE = /* @__PURE__ */ new Set([
2019
+ "passphrase_missing",
2020
+ "passphrase_wrong",
2021
+ "env_passphrase_wrong"
2022
+ ]);
2023
+ function repairStep(tty) {
2024
+ return tty ? `run \`tenjin wallet repair\` yourself ${REPAIR_CLAUSE}` : "ask the person to run `tenjin wallet repair` in their own terminal (never ask for the passphrase)";
2025
+ }
2026
+ function nextStep(plugin, claude, wallet, migration, pendingSteps, tty, command, env) {
2027
+ if (plugin.state === "failed") return registrationFix(plugin);
2028
+ const steps = todaysSteps(plugin, claude, wallet, migration, pendingSteps, command, env);
2029
+ const signing = wallet.signing;
2030
+ if (signing?.status === "blocked" && REPAIRABLE.has(signing.reason)) {
2031
+ steps.unshift(repairStep(tty));
2031
2032
  }
2032
- const failed = [...unrun];
2033
- const notices = [];
2034
- let settingsInstallPending = false;
2035
- const heard = (reported) => {
2036
- for (const notice of noticesOf(reported)) if (!notices.includes(notice)) notices.push(notice);
2037
- const migration = reported?.migration;
2038
- if (migration?.state === "pending" || migration?.state === "blocked") {
2039
- settingsInstallPending = true;
2040
- }
2033
+ return steps.join(", then ");
2034
+ }
2035
+ function todaysSteps(plugin, claude, wallet, migration, pendingSteps, command, env) {
2036
+ const steps = [];
2037
+ if (pendingSteps > 0) steps.push("follow the instructions in nextSteps");
2038
+ if (plugin.state === "deferred") {
2039
+ steps.unshift("run `claude update`");
2040
+ steps.push(
2041
+ `run \`${command} install\` again; until then the earlier Tenjin setup stays as it is`
2042
+ );
2043
+ return steps;
2044
+ }
2045
+ if (!claude.meetsFloor) steps.unshift("run `claude update`");
2046
+ steps.push(loadStep(settingsInstallStays(migration) || !claude.meetsFloor, env, command));
2047
+ return steps;
2048
+ }
2049
+ function settingsInstallStays(migration) {
2050
+ return migration.state === "pending" || migration.state === "blocked";
2051
+ }
2052
+ function deferredRegistration(scope, claude) {
2053
+ return {
2054
+ method: "none",
2055
+ id: null,
2056
+ scope,
2057
+ state: "deferred",
2058
+ version: package_default.version,
2059
+ steps: [],
2060
+ 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 stays as it is`
2041
2061
  };
2042
- let homeTail = "";
2043
- for (const dataDir of profiles) {
2044
- const { outcome, tail } = await refreshChild(launch, homedir2(), dataDir, deps);
2045
- homeTail = tail;
2046
- if (outcome.kind !== "exit" || outcome.code !== 0) {
2047
- failed.push({ dataDir, reason: refreshReason(outcome, tail), fix: fixFor(dataDir) });
2048
- continue;
2049
- }
2050
- heard(envelopeData(tail));
2062
+ }
2063
+ function statusLineNotice(migration) {
2064
+ const status = migration.removed?.statusLine;
2065
+ if (status === "removed") {
2066
+ 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.";
2051
2067
  }
2052
- const projects = [];
2053
- const projectsFailed = [];
2054
- const recorded = profiles.includes(ctx.dataDir) ? (await loadRawConfig(ctx.dataDir).catch(() => null))?.install?.routerProjects ?? [] : [];
2055
- for (const project of recorded) {
2056
- const forget = () => persistRouterProject(ctx.dataDir, project, false).catch(() => void 0);
2057
- if (!isExistingDir(project) || !await projectInstallAt(project, home, process.env)) {
2058
- await forget();
2059
- continue;
2060
- }
2061
- const { outcome, tail } = await refreshChild(launch, project, ctx.dataDir, deps, ["--project"]);
2062
- if (outcome.kind !== "exit" || outcome.code !== 0) {
2063
- projectsFailed.push({
2064
- project,
2065
- reason: refreshReason(outcome, tail),
2066
- fix: `Run \`tenjin install --project\` in ${project}.`
2067
- });
2068
- continue;
2069
- }
2070
- projects.push(project);
2071
- heard(envelopeData(tail));
2068
+ if (status === "restored") {
2069
+ return "Took the Tenjin footer out of your status line and put your own command back; the plugin sets none.";
2070
+ }
2071
+ return null;
2072
+ }
2073
+ function refreshNotices(plugin, claude, migration, rt, home) {
2074
+ const out = [];
2075
+ if (plugin.state === "deferred") {
2076
+ out.push(
2077
+ `Claude Code ${claude.version ?? ""} is older than ${CLAUDE_CODE_FLOOR}, so the Tenjin plugin was not registered and the earlier settings setup stays as it is. Run \`claude update\`, then \`tenjin install\`.`
2078
+ );
2079
+ } else if (plugin.state !== "failed" && settingsInstallStays(migration)) {
2080
+ out.push(
2081
+ "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."
2082
+ );
2072
2083
  }
2084
+ const status = statusLineNotice(migration);
2085
+ if (status !== null) out.push(status);
2086
+ if (rt !== null) out.push(...runtimeNotices(rt, home));
2087
+ return out;
2088
+ }
2089
+ function runtimeNotices(rt, home) {
2090
+ const out = [];
2091
+ const runs = runtimeSentence(rt, home);
2092
+ if (runs !== null) out.push(`Tenjin ${runs.charAt(0).toLowerCase()}${runs.slice(1)}`);
2093
+ const launcher = launcherSentence(rt.launcher, home);
2094
+ if (launcher !== null) out.push(launcher);
2095
+ return out;
2096
+ }
2097
+ var SHOW_NOT_RUN = "When the selected option includes a command, run it yourself; never ask the person to run it. Show an address only when requested or needed for recovery; storage and PATH details only for recovery.";
2098
+ function spendStep(args, command) {
2099
+ return spendStepFor(installCommand(args, command));
2100
+ }
2101
+ function spendStepFor(command) {
2102
+ const options = spendOptions(command);
2073
2103
  return {
2074
- refresh: { profiles, failed, notices, settingsInstallPending, projects, projectsFailed },
2075
- homeTail
2104
+ id: "spend",
2105
+ question: spendChoiceQuestion(),
2106
+ options,
2107
+ next: `${process.platform === "win32" ? "Use PowerShell. " : ""}Ask this question once, with these options and the defaults recommended. The defaults are already in effect. Run the selected option's command alone, filling in any requested amounts, then read its complete result for the next action. Do not repeat an answered question. ${SHOW_NOT_RUN}`
2076
2108
  };
2077
2109
  }
2078
- function npmLaunch(deps) {
2079
- const entry = versionFreeEntry(deps.refreshCommand ?? process.argv[1]);
2080
- return entry === null ? null : { node: process.execPath, entry };
2110
+ function installCommand(args, command) {
2111
+ return [
2112
+ `${command} install`,
2113
+ ...args.project === true ? ["--project"] : [],
2114
+ ...args.noWallet === true ? ["--no-wallet"] : []
2115
+ ].join(" ");
2081
2116
  }
2082
- async function refreshChild(launch, cwd, dataDir, deps, flags = []) {
2083
- let tail = "";
2084
- const outcome = await (deps.spawnImpl ?? spawnCapture)(
2085
- launch.node,
2086
- [launch.entry, "install", "--refresh", ...flags],
2087
- {
2088
- cwd,
2089
- timeoutMs: REFRESH_TIMEOUT_MS,
2090
- // TENJIN_DATA_DIR aims the child at this profile; the nudge opt-out is
2091
- // what keeps it from touching any other file in there (lib/update-check).
2092
- env: { TENJIN_DATA_DIR: dataDir, [NUDGE_OPT_OUT]: "1" }
2093
- },
2094
- (chunk) => {
2095
- tail = (tail + chunk).slice(-REFRESH_TAIL_LIMIT);
2117
+ function namedLimits(args) {
2118
+ const flags = [
2119
+ ["maxAutoSpend", "--max-auto-spend", args.maxAutoSpend, "call"],
2120
+ ["sessionBudget", "--session-budget", args.sessionBudget, "day"]
2121
+ ];
2122
+ const limits = {};
2123
+ const keys = [];
2124
+ for (const [key, flag, raw, per] of flags) {
2125
+ if (raw === void 0) continue;
2126
+ if (args.refresh === true) {
2127
+ throw new CliError("USAGE", `${flag} sets a spend limit, and --refresh writes none.`, {
2128
+ fix: `Run \`tenjin install ${flag} ${raw}\` without --refresh.`
2129
+ });
2130
+ }
2131
+ const parsed = parseLimit(raw, per);
2132
+ if ("refusal" in parsed) {
2133
+ throw new CliError("USAGE", `${flag} ${raw}: ${parsed.refusal}`, {
2134
+ fix: per === "day" ? `Give a positive USD amount or none, for example \`${flag} 5\`.` : `Give a non-negative USD amount with up to 6 decimal places, for example \`${flag} 0.1\`. Zero blocks positive automatic payments.`
2135
+ });
2096
2136
  }
2137
+ limits[key] = parsed.value;
2138
+ keys.push(key);
2139
+ }
2140
+ return { limits, keys };
2141
+ }
2142
+ async function approveLimits(deps) {
2143
+ const choice = await (deps.promptLimits ?? promptLimits)(
2144
+ `${SPEND_QUESTION}
2145
+ ${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`
2097
2146
  );
2098
- return { outcome, tail };
2147
+ if (choice === null) throw installCancelled();
2148
+ if (choice === "approve") return { ...ROUTER_DEFAULTS };
2149
+ const ask = deps.promptAmount ?? promptAmount;
2150
+ const sessionBudget = await askLimit(
2151
+ ask,
2152
+ "Daily budget shared across chats, in USD, or none",
2153
+ "5",
2154
+ "day"
2155
+ );
2156
+ const maxAutoSpend = await askLimit(
2157
+ ask,
2158
+ "Most it may pay for one call, in USD; 0 blocks positive automatic payments",
2159
+ toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd,
2160
+ "call"
2161
+ );
2162
+ return { maxAutoSpend, sessionBudget };
2099
2163
  }
2100
- function envelopeData(output) {
2101
- const lines2 = output.split("\n");
2102
- for (let i = lines2.length - 1; i >= 0; i -= 1) {
2103
- if (lines2[i]?.trim() !== "{" && !lines2[i]?.trim().startsWith('{"')) continue;
2104
- try {
2105
- const parsed = JSON.parse(lines2.slice(i).join("\n"));
2106
- if (parsed?.ok === true && parsed.data !== null && typeof parsed.data === "object") {
2107
- return parsed.data;
2108
- }
2109
- } catch {
2110
- continue;
2111
- }
2164
+ async function askLimit(ask, question, placeholder, per) {
2165
+ let message = question;
2166
+ for (; ; ) {
2167
+ const answer = await ask(message, placeholder);
2168
+ if (answer === null) throw installCancelled();
2169
+ const parsed = parseLimit(answer, per);
2170
+ if (!("refusal" in parsed)) return parsed.value;
2171
+ message = `${parsed.refusal} ${question}`;
2112
2172
  }
2113
- return null;
2114
2173
  }
2115
- function noticesOf(data) {
2116
- const raw = data?.notices;
2117
- if (!Array.isArray(raw)) return [];
2118
- return raw.filter((n) => typeof n === "string").map((n) => sanitizeForTerminal(n).trim().slice(0, REASON_LIMIT)).filter((n) => n.length > 0).slice(0, 5);
2174
+ function parseLimit(answer, per) {
2175
+ const trimmed = answer.trim();
2176
+ if (per === "day" && trimmed === "none") return { value: "none" };
2177
+ let atomic;
2178
+ try {
2179
+ atomic = parseUsdToAtomic(trimmed);
2180
+ } catch (err) {
2181
+ if (err instanceof CliError) return { refusal: `${err.message}.` };
2182
+ throw err;
2183
+ }
2184
+ if (per === "day" && atomic === "0") {
2185
+ return {
2186
+ refusal: "The limit must be more than zero; `tenjin config set router.enabled false` turns the router off."
2187
+ };
2188
+ }
2189
+ return { value: atomic };
2119
2190
  }
2120
- var REFRESH_TAIL_LIMIT = 64e3;
2121
- var REASON_LIMIT = 300;
2122
- function refreshReason(outcome, output) {
2123
- const reported = envelopeMessage(output);
2124
- if (reported !== void 0) return reported;
2125
- if (outcome.kind === "timeout") return `It did not finish in ${REFRESH_TIMEOUT_MS / 1e3}s.`;
2126
- if (outcome.kind === "start-failed") return "The refresh could not be started.";
2127
- return `The refresh exited ${outcome.code} without reporting a reason.`;
2191
+ function installCancelled() {
2192
+ return new CliError("REFUSED", "Install cancelled before anything was written.", {
2193
+ fix: "Re-run `tenjin install` and choose the defaults or your own limits."
2194
+ });
2128
2195
  }
2129
- function envelopeMessage(output) {
2130
- const lines2 = output.split("\n");
2131
- for (let i = lines2.length - 1; i >= 0; i -= 1) {
2132
- const line = lines2[i]?.trim();
2133
- if (line === void 0 || !line.startsWith("{")) continue;
2134
- let parsed;
2135
- try {
2136
- parsed = JSON.parse(lines2.slice(i).join("\n"));
2137
- } catch {
2138
- continue;
2139
- }
2140
- if (parsed?.ok !== false || typeof parsed.error?.message !== "string") continue;
2141
- const message = sanitizeForTerminal(parsed.error.message).trim();
2142
- if (message.length > 0) return message.slice(0, REASON_LIMIT);
2143
- }
2144
- return void 0;
2196
+ function promptLimits(message) {
2197
+ return selectOne({
2198
+ message,
2199
+ choices: [
2200
+ { value: "approve", label: `${DEFAULTS_LABEL} (recommended)` },
2201
+ { value: "own", label: "Set my own limits" }
2202
+ ],
2203
+ initialValue: "approve"
2204
+ });
2145
2205
  }
2146
- function isExistingDir(path) {
2147
- return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
2206
+ function promptAmount(message, placeholder) {
2207
+ return askText({ message, placeholder });
2148
2208
  }
2149
- function manualFix(dataDir, home, invoking) {
2150
- const bare = resolve2(dataDir) === resolve2(defaultDataDir(home)) && resolve2(dataDir) === resolve2(invoking);
2151
- const command = bare ? "tenjin install" : `TENJIN_DATA_DIR=${dataDir} tenjin install`;
2152
- return `Run \`${command}\` to bring the Claude Code plugin up to this version.`;
2209
+ function effectiveLimits(policy) {
2210
+ return {
2211
+ maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,
2212
+ sessionBudget: policy.sessionBudgetAtomic === null ? "no daily budget limit" : toMoney(policy.sessionBudgetAtomic.toString()).usd
2213
+ };
2153
2214
  }
2154
- function versionFreeEntry(entry) {
2155
- if (entry === void 0 || entry.length === 0) return null;
2156
- const segs = entry.split(sep2);
2157
- const store = segs.indexOf(".pnpm");
2158
- if (store === -1) return segs.join(sep2);
2159
- const inner = segs.indexOf("node_modules", store);
2160
- if (inner === -1) return null;
2161
- const derived = [...segs.slice(0, store), ...segs.slice(inner + 1)].join(sep2);
2162
- return existsSync2(derived) ? derived : null;
2215
+ function walletLines(ctx, w, host = "Claude Code") {
2216
+ const warn = (text) => paint(ctx.io, "yellow", text);
2217
+ if (w.status === "created" || w.status === "existing") {
2218
+ const a = w.address ?? "";
2219
+ const signing = w.signing;
2220
+ const tty = ctx.io.isTTY;
2221
+ if (signing?.status === "blocked") {
2222
+ const wallet = Object.prototype.hasOwnProperty.call(WALLET_REASONS, signing.reason) ? WALLET_REASONS[signing.reason] : void 0;
2223
+ return [
2224
+ warn(`! Wallet ${a} cannot be unlocked by ${host}: ${signing.detail}.`),
2225
+ ` ${tty ? wallet?.fix ?? signing.fix : agentFixFor(signing.reason, signing.fix)}`
2226
+ ];
2227
+ }
2228
+ if (signing?.status === "unknown") {
2229
+ return [
2230
+ warn(`! Wallet: ${a}; could not check that it unlocks (${signing.detail}).`),
2231
+ " Run `tenjin doctor` to check it again."
2232
+ ];
2233
+ }
2234
+ if (w.shellOnly === "key") {
2235
+ return [
2236
+ warn(
2237
+ `! Wallet: ${a} signs here only through TENJIN_WALLET_KEY in this shell; ${host} must have the same variable.`
2238
+ )
2239
+ ];
2240
+ }
2241
+ if (w.shellOnly === "passphrase") {
2242
+ return [
2243
+ warn(
2244
+ tty ? `! Wallet: ${a} unlocks here only through TENJIN_WALLET_PASSPHRASE in this shell; ${host} must have the same variable, or run \`tenjin wallet repair\` yourself to store the passphrase ${REPAIR_CLAUSE}.` : `! Wallet: ${a} unlocks here only through TENJIN_WALLET_PASSPHRASE in this shell; ${host} 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.`
2245
+ )
2246
+ ];
2247
+ }
2248
+ return [];
2249
+ }
2250
+ if (w.reason === "flag") return [" No wallet yet. Create one with: tenjin wallet create"];
2251
+ return [
2252
+ paint(ctx.io, "yellow", `! No wallet was created. ${w.warning ?? ""}`.trimEnd()),
2253
+ ` ${w.fix ?? "Create one with: tenjin wallet create"}`
2254
+ ];
2163
2255
  }
2164
- function refreshLines2(refresh) {
2165
- const failedDirs = new Set(refresh.failed.map((f) => f.dataDir));
2166
- const done = refresh.profiles.filter((p) => !failedDirs.has(p));
2167
- if (refresh.failed.length === 0) {
2256
+ function pluginLines(ctx, plugin) {
2257
+ const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
2258
+ if (plugin.state === "deferred") return [warn(`${plugin.reason ?? ""}`)];
2259
+ if (plugin.state === "failed") {
2260
+ return [warn(`The Tenjin plugin was not registered: ${plugin.reason ?? "unknown reason"}`)];
2261
+ }
2262
+ return [];
2263
+ }
2264
+ function migrationLines(ctx, migration) {
2265
+ const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
2266
+ if (migration.state === "pending") {
2168
2267
  return [
2169
- done.length > 1 ? `Refreshed the Claude Code plugin for ${done.length} profiles: ${done.join(", ")}.` : `Refreshed the Claude Code plugin for ${done[0]}.`
2268
+ ` The settings install in ${migration.settingsPath} stays until the plugin has loaded (${migration.reason ?? ""}); \`tenjin update\` or \`tenjin install\` removes it then.`
2170
2269
  ];
2171
2270
  }
2172
- const total = done.length + refresh.failed.length;
2173
- const lines2 = done.length > 0 ? [
2174
- `Refreshed the Claude Code plugin for ${done.length} of ${total} profiles: ${done.join(", ")}.`
2175
- ] : [];
2176
- lines2.push(`Could not refresh the Claude Code plugin for ${refresh.failed.length}:`);
2177
- lines2.push(...refresh.failed.map((f) => `- ${f.dataDir}: ${f.reason} ${f.fix}`));
2178
- return lines2;
2271
+ if (migration.state === "blocked") {
2272
+ return [warn(`${migration.settingsPath} could not be read: ${migration.reason ?? ""}`)];
2273
+ }
2274
+ if (migration.state === "done") {
2275
+ const removed = migration.removed;
2276
+ const status = statusLineNotice(migration);
2277
+ return [
2278
+ ` Removed the earlier settings setup from ${migration.settingsPath}: the plugin carries its hooks, permissions and server`,
2279
+ ...status !== null ? [` ${status}`] : [],
2280
+ ...(removed?.warnings ?? []).map((w) => warn(w))
2281
+ ];
2282
+ }
2283
+ return [];
2179
2284
  }
2180
- function projectLines(refresh) {
2285
+ function claudeLines(ctx, claude) {
2286
+ if (claude.meetsFloor) return [];
2181
2287
  return [
2182
- ...refresh.projects.length > 0 ? [`Refreshed the project install in ${refresh.projects.join(", ")}.`] : [],
2183
- ...refresh.projectsFailed.length > 0 ? [
2184
- `Could not refresh the project install in ${refresh.projectsFailed.length}:`,
2185
- ...refresh.projectsFailed.map((p) => `- ${p.project}: ${p.reason} ${p.fix}`)
2186
- ] : []
2288
+ paint(
2289
+ ctx.io,
2290
+ "yellow",
2291
+ `! Claude Code ${claude.version ?? ""} is older than the plugin needs. ${claude.fix ?? ""}`.trim()
2292
+ )
2187
2293
  ];
2188
2294
  }
2189
- var spawnCapture = (cmd, args, opts, onOutput) => new Promise((res) => {
2190
- let child;
2191
- try {
2192
- child = spawn(cmd, args, {
2193
- stdio: ["ignore", "pipe", "pipe"],
2194
- cwd: opts.cwd,
2195
- // Layered onto this process's environment rather than replacing it: the
2196
- // child is a Node CLI that needs PATH and HOME, and only the keys named
2197
- // here are being decided.
2198
- ...opts.env !== void 0 ? { env: { ...process.env, ...opts.env } } : {}
2199
- });
2200
- } catch (cause) {
2201
- res({ kind: "start-failed", cause });
2202
- return;
2203
- }
2204
- let timedOut = false;
2205
- const timer = setTimeout(() => {
2206
- timedOut = true;
2207
- child.kill("SIGKILL");
2208
- }, opts.timeoutMs);
2209
- child.stdout?.on("data", (chunk) => onOutput(chunk.toString()));
2210
- child.stderr?.on("data", (chunk) => onOutput(chunk.toString()));
2211
- child.on("error", (cause) => {
2212
- clearTimeout(timer);
2213
- res({ kind: "start-failed", cause });
2214
- });
2215
- child.on("close", (code) => {
2216
- clearTimeout(timer);
2217
- res(timedOut ? { kind: "timeout" } : { kind: "exit", code: code ?? 1 });
2218
- });
2219
- });
2295
+ function lines(ctx, s) {
2296
+ const ok = paint(ctx.io, "green", "\u2713");
2297
+ const warn = (text) => paint(ctx.io, "yellow", `! ${text}`);
2298
+ const spend = s.spendAsk !== void 0 ? [
2299
+ ` Ask the person in this session: ${s.spendAsk.question}`,
2300
+ ...s.spendAsk.options.map(
2301
+ (o) => ` ${o.label}${o.recommended ? " (recommended)" : ""}: ${o.command}`
2302
+ )
2303
+ ] : [];
2304
+ const installed = s.plugin.state !== "failed" && s.plugin.state !== "deferred";
2305
+ const router = s.router.status === "ok" ? [] : [
2306
+ warn(
2307
+ s.router.status === "warn" ? s.router.detail : `The router did not answer: ${s.router.detail}`
2308
+ ),
2309
+ ...s.router.fix !== void 0 ? [` ${s.router.fix}`] : []
2310
+ ];
2311
+ return [
2312
+ s.plugin.state === "failed" ? warn("Tenjin could not finish setting up Claude Code") : s.plugin.state === "deferred" ? warn("Tenjin keeps its earlier Claude Code setup until Claude Code is updated") : `${ok} Tenjin is set up for Claude Code (plugin ${s.plugin.id ?? PLUGIN_ID})`,
2313
+ ...installed ? CAPABILITY_LINES.map((line) => ` ${line}`) : [],
2314
+ ...s.plugin.scope === "local" && s.plugin.state !== "failed" ? [` For this project only; check it with: ${continuationCommand(s.rt)} doctor --project`] : [],
2315
+ ...spend,
2316
+ ...runtimeLines(ctx, s.rt, s.home, true),
2317
+ ...walletLines(ctx, s.wallet),
2318
+ ...s.fundingWarning !== void 0 ? [warn(s.fundingWarning)] : [],
2319
+ ...pluginLines(ctx, s.plugin),
2320
+ ...claudeLines(ctx, s.claude),
2321
+ ...migrationLines(ctx, s.migration),
2322
+ ...router
2323
+ ];
2324
+ }
2325
+ function refreshLines2(ctx, plugin, claude, migration, rt, home) {
2326
+ const issues = [
2327
+ ...runtimeLines(ctx, rt, home),
2328
+ ...pluginLines(ctx, plugin),
2329
+ ...claudeLines(ctx, claude),
2330
+ ...migrationLines(ctx, migration)
2331
+ ];
2332
+ const head = plugin.state === "failed" ? paint(ctx.io, "yellow", "! Tenjin is updated, but its plugin was not registered") : plugin.state === "deferred" ? paint(ctx.io, "yellow", "! Tenjin is updated; its plugin waits for a newer Claude Code") : `${paint(ctx.io, "green", "\u2713")} Tenjin is up to date (plugin ${plugin.id ?? PLUGIN_ID})`;
2333
+ return [head, ...issues];
2334
+ }
2220
2335
 
2221
2336
  export {
2222
2337
  inspectLegacyInstall,
2223
2338
  removeLegacyInstall,
2224
- BACKGROUND_COOLDOWN_MS,
2225
- runUpdate,
2226
- versionFreeEntry,
2227
- spawnCapture,
2228
- folderFor,
2229
- registerPlugin,
2230
- marketplaceAdded,
2231
- ownMarketplace,
2232
- recordedInstalls,
2233
- packageHostsDir,
2234
- packageMod,
2235
- packageCliEntry,
2236
- readPluginListing,
2237
- folderState,
2238
2339
  probeRouter,
2239
2340
  DISCLOSURE,
2341
+ CAPABILITY_LINES,
2342
+ receiptTail,
2240
2343
  NEW_SESSION_STEP,
2241
2344
  RELOAD_STEP,
2242
2345
  loadStep,
2243
- settingsInstallPaths,
2244
2346
  pluginProof,
2245
2347
  migrateSettingsInstall,
2246
2348
  projectInstallHere,
@@ -2249,19 +2351,27 @@ export {
2249
2351
  runRouterInstall,
2250
2352
  defaultRuntime,
2251
2353
  runtimeOncePerRun,
2252
- hasRuntime,
2253
2354
  assertPluginInstallation,
2254
2355
  continuationCommand,
2255
2356
  requireRuntime,
2256
2357
  runtimeData,
2257
- tilde,
2258
2358
  runtimeLines,
2259
2359
  SHOW_NOT_RUN,
2260
2360
  spendStepFor,
2261
2361
  namedLimits,
2262
- FUND_QUESTION,
2263
- FUND_COMMAND,
2264
2362
  approveLimits,
2265
- effectiveLimits
2363
+ effectiveLimits,
2364
+ walletLines,
2365
+ BACKGROUND_COOLDOWN_MS,
2366
+ runUpdate,
2367
+ versionFreeEntry,
2368
+ spawnCapture,
2369
+ folderFor,
2370
+ ownMarketplace,
2371
+ recordedInstalls,
2372
+ readPluginListing,
2373
+ folderState,
2374
+ settingsInstallPaths,
2375
+ claudeInstallAt
2266
2376
  };
2267
- //# sourceMappingURL=chunk-ILNIZ5I2.js.map
2377
+ //# sourceMappingURL=chunk-65RS4LQS.js.map