tenjin-cli 0.1.0-alpha.34 → 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 (332) hide show
  1. package/NOTICE.md +30 -0
  2. package/README.md +20 -18
  3. package/dist/{_esm-MMYV66AX.js → _esm-2KST7HQ7.js} +4 -4
  4. package/dist/{alive-VOIL5W3I.js → alive-5TV22PNF.js} +13 -13
  5. package/dist/{auth-UHD3QFX4.js → auth-XI7BJFLW.js} +4 -4
  6. package/dist/balance-DFHC6XEU.js +71 -0
  7. package/dist/{ccip-CS7K5QRQ.js → ccip-HOW3DZYF.js} +3 -3
  8. package/dist/{chunk-RJ5HRPAZ.js → chunk-24XKUN2S.js} +68 -10
  9. package/dist/chunk-24XKUN2S.js.map +1 -0
  10. package/dist/chunk-2L7TDGLV.js +56 -0
  11. package/dist/chunk-2L7TDGLV.js.map +1 -0
  12. package/dist/{chunk-PZHBPGDE.js → chunk-34SAECKZ.js} +34 -10
  13. package/dist/chunk-34SAECKZ.js.map +1 -0
  14. package/dist/{chunk-EQZ2CCWC.js → chunk-3Y2EHT4F.js} +5 -2
  15. package/dist/chunk-3Y2EHT4F.js.map +1 -0
  16. package/dist/{chunk-FSYH7J75.js → chunk-3Y6BHIN6.js} +3 -3
  17. package/dist/{chunk-FZZWTDWP.js → chunk-3YPL6T3P.js} +6 -6
  18. package/dist/{chunk-JEZMWJEF.js → chunk-44MVIRZH.js} +4 -4
  19. package/dist/{chunk-27FIHFXF.js → chunk-45MMSBHA.js} +5 -5
  20. package/dist/{chunk-QXP3Z3JN.js → chunk-4MBCJFY4.js} +35 -3
  21. package/dist/chunk-4MBCJFY4.js.map +1 -0
  22. package/dist/chunk-4TPL54KW.js +227 -0
  23. package/dist/chunk-4TPL54KW.js.map +1 -0
  24. package/dist/{chunk-7JB6SYJX.js → chunk-54ELBTKE.js} +2 -2
  25. package/dist/{chunk-6J64MQFD.js → chunk-5F4OB5B3.js} +21 -15
  26. package/dist/chunk-5F4OB5B3.js.map +1 -0
  27. package/dist/{chunk-PYVQ74D5.js → chunk-5HN4KVQU.js} +189 -117
  28. package/dist/chunk-5HN4KVQU.js.map +1 -0
  29. package/dist/{chunk-VFKPIIV2.js → chunk-5J4E5GYI.js} +35 -32
  30. package/dist/chunk-5J4E5GYI.js.map +1 -0
  31. package/dist/chunk-5USBZ2MU.js +58 -0
  32. package/dist/chunk-5USBZ2MU.js.map +1 -0
  33. package/dist/chunk-64WOMNYR.js +183 -0
  34. package/dist/chunk-64WOMNYR.js.map +1 -0
  35. package/dist/{chunk-APWELUI7.js → chunk-65RS4LQS.js} +57 -43
  36. package/dist/chunk-65RS4LQS.js.map +1 -0
  37. package/dist/{chunk-HWZO6HYZ.js → chunk-6QMDUDF2.js} +3 -3
  38. package/dist/{chunk-FNBGRKS6.js → chunk-7V25UAQO.js} +2 -2
  39. package/dist/chunk-BGA4DO5M.js +719 -0
  40. package/dist/chunk-BGA4DO5M.js.map +1 -0
  41. package/dist/chunk-BVP7YK2J.js +706 -0
  42. package/dist/chunk-BVP7YK2J.js.map +1 -0
  43. package/dist/chunk-C265QIMJ.js +83 -0
  44. package/dist/chunk-C265QIMJ.js.map +1 -0
  45. package/dist/{chunk-MXN2ZEUB.js → chunk-D6M3ZK66.js} +2 -2
  46. package/dist/chunk-D6M3ZK66.js.map +1 -0
  47. package/dist/chunk-DJ36BM62.js +78 -0
  48. package/dist/chunk-DJ36BM62.js.map +1 -0
  49. package/dist/{chunk-JOKPBYXP.js → chunk-DTEWAVNE.js} +2 -2
  50. package/dist/chunk-F2KJAJ7T.js +13 -0
  51. package/dist/chunk-F2KJAJ7T.js.map +1 -0
  52. package/dist/{chunk-KAILF7QA.js → chunk-F43CV6UC.js} +2 -2
  53. package/dist/{chunk-ACO7ZCR2.js → chunk-FKVJKLPI.js} +2 -2
  54. package/dist/{chunk-43HLS2HM.js → chunk-FYFHH7V5.js} +54 -3
  55. package/dist/{chunk-43HLS2HM.js.map → chunk-FYFHH7V5.js.map} +1 -1
  56. package/dist/{chunk-2F5JUAHZ.js → chunk-GAJC4BQZ.js} +3 -3
  57. package/dist/{chunk-L7N73ZAW.js → chunk-HAZAN4UM.js} +2 -2
  58. package/dist/{chunk-6QJZA6EX.js → chunk-HI5XQOX2.js} +2 -2
  59. package/dist/{chunk-BOENA6XR.js → chunk-HKGUKAQW.js} +6 -6
  60. package/dist/{chunk-LJSCGIYH.js → chunk-HPRVFJPM.js} +2 -2
  61. package/dist/{chunk-OO6FIBL7.js → chunk-HZKANST2.js} +3 -6
  62. package/dist/chunk-HZKANST2.js.map +1 -0
  63. package/dist/{chunk-UVDJ5SSQ.js → chunk-I557SAOM.js} +8 -2
  64. package/dist/chunk-I557SAOM.js.map +1 -0
  65. package/dist/{chunk-SDUOJRSV.js → chunk-IGLWLH73.js} +3 -3
  66. package/dist/{chunk-3AKH7ODX.js → chunk-INSIW65E.js} +5 -5
  67. package/dist/{chunk-PNHNXUSL.js → chunk-IULCDMVG.js} +12 -1
  68. package/dist/chunk-IULCDMVG.js.map +1 -0
  69. package/dist/{chunk-JF4T4HCQ.js → chunk-IVNSUAVC.js} +10 -5
  70. package/dist/chunk-IVNSUAVC.js.map +1 -0
  71. package/dist/chunk-JDQZCREI.js +87 -0
  72. package/dist/chunk-JDQZCREI.js.map +1 -0
  73. package/dist/{chunk-2P3NJTHE.js → chunk-JHFFUVON.js} +23 -23
  74. package/dist/{chunk-7JVARP5R.js → chunk-JTILUN4W.js} +55 -29
  75. package/dist/{chunk-7JVARP5R.js.map → chunk-JTILUN4W.js.map} +1 -1
  76. package/dist/{chunk-2TO5F6CT.js → chunk-K5KNGC4I.js} +8 -8
  77. package/dist/{chunk-HUWTFKEM.js → chunk-KAQ4Q3TO.js} +3 -3
  78. package/dist/{chunk-E6VP6MQM.js → chunk-KGUE5AVX.js} +4 -4
  79. package/dist/chunk-KGUE5AVX.js.map +1 -0
  80. package/dist/{chunk-GS5RZF7U.js → chunk-KLDMLWXT.js} +2 -2
  81. package/dist/{chunk-HN2EN6P4.js → chunk-KNKDMTHU.js} +5 -5
  82. package/dist/chunk-LDA6TAYQ.js +95 -0
  83. package/dist/chunk-LDA6TAYQ.js.map +1 -0
  84. package/dist/chunk-LWSSIZOY.js +347 -0
  85. package/dist/chunk-LWSSIZOY.js.map +1 -0
  86. package/dist/{chunk-5VWQSCDO.js → chunk-MAHNZA6C.js} +89 -9
  87. package/dist/chunk-MAHNZA6C.js.map +1 -0
  88. package/dist/{chunk-46HAB26L.js → chunk-MEWZCIA6.js} +56 -9
  89. package/dist/chunk-MEWZCIA6.js.map +1 -0
  90. package/dist/{chunk-R2KMLONN.js → chunk-MJDO4EXD.js} +4 -4
  91. package/dist/{chunk-IHVUE3XF.js → chunk-NJA6NT3A.js} +3 -3
  92. package/dist/{chunk-TSIID2LV.js → chunk-ODRPASFP.js} +375 -1166
  93. package/dist/chunk-ODRPASFP.js.map +1 -0
  94. package/dist/{chunk-S3JKF3IK.js → chunk-OJJFANO6.js} +3 -3
  95. package/dist/{chunk-56SOPRM2.js → chunk-OQWPRFAC.js} +344 -4
  96. package/dist/chunk-OQWPRFAC.js.map +1 -0
  97. package/dist/{chunk-QEZZDIQT.js → chunk-P6YQWIT2.js} +4053 -4039
  98. package/dist/chunk-P6YQWIT2.js.map +1 -0
  99. package/dist/{chunk-GGGEGMWC.js → chunk-Q6RSJCXB.js} +9 -9
  100. package/dist/{chunk-OTIUEUIS.js → chunk-QKEUKBRK.js} +7 -7
  101. package/dist/{chunk-X52BVGCJ.js → chunk-QQDPRTLP.js} +5 -5
  102. package/dist/chunk-QQYCYAKI.js +79 -0
  103. package/dist/chunk-QQYCYAKI.js.map +1 -0
  104. package/dist/chunk-R4KDH477.js +1064 -0
  105. package/dist/chunk-R4KDH477.js.map +1 -0
  106. package/dist/{chunk-6AQSUBNR.js → chunk-RGCPELQN.js} +2 -2
  107. package/dist/{chunk-AXODGQ23.js → chunk-RGVCOG2S.js} +9 -2
  108. package/dist/{chunk-AXODGQ23.js.map → chunk-RGVCOG2S.js.map} +1 -1
  109. package/dist/chunk-SOLNJ3AZ.js +209 -0
  110. package/dist/chunk-SOLNJ3AZ.js.map +1 -0
  111. package/dist/{chunk-LQ33RLHL.js → chunk-TFT2X7SH.js} +3 -3
  112. package/dist/chunk-TVWCLUBI.js +293 -0
  113. package/dist/chunk-TVWCLUBI.js.map +1 -0
  114. package/dist/{chunk-VH7JMLTG.js → chunk-UIB33QQP.js} +25 -16
  115. package/dist/chunk-UIB33QQP.js.map +1 -0
  116. package/dist/chunk-V6GIVALQ.js +1889 -0
  117. package/dist/chunk-V6GIVALQ.js.map +1 -0
  118. package/dist/{chunk-IVHGQNIN.js → chunk-VHXCPXUS.js} +8 -8
  119. package/dist/{chunk-7DW7GAM6.js → chunk-VU6GMWF6.js} +2 -2
  120. package/dist/chunk-VWZYE3NC.js +8415 -0
  121. package/dist/chunk-VWZYE3NC.js.map +1 -0
  122. package/dist/{chunk-3X4GOMXT.js → chunk-W2GXIARJ.js} +12 -7
  123. package/dist/chunk-W2GXIARJ.js.map +1 -0
  124. package/dist/chunk-W4G3K3V7.js +288 -0
  125. package/dist/chunk-W4G3K3V7.js.map +1 -0
  126. package/dist/{chunk-FHXTEVO7.js → chunk-W74LJ5OT.js} +21 -28
  127. package/dist/chunk-W74LJ5OT.js.map +1 -0
  128. package/dist/{chunk-FOEPH67T.js → chunk-W7ELYLYK.js} +1 -74
  129. package/dist/chunk-W7ELYLYK.js.map +1 -0
  130. package/dist/{chunk-YU3DLVSQ.js → chunk-XSCGUO2U.js} +5 -5
  131. package/dist/{chunk-EPCIJLLU.js → chunk-XWROSMI5.js} +9 -9
  132. package/dist/{chunk-HMT6L65V.js → chunk-YJGEVBKZ.js} +4 -4
  133. package/dist/{chunk-7U3P4PB7.js → chunk-ZEYA2WWX.js} +4 -4
  134. package/dist/chunk-ZEYA2WWX.js.map +1 -0
  135. package/dist/chunk-ZRC7Z5X3.js +82 -0
  136. package/dist/chunk-ZRC7Z5X3.js.map +1 -0
  137. package/dist/{chunk-I47ARU5G.js → chunk-ZS7JIUJ3.js} +2 -2
  138. package/dist/{claude-cli-2YKABJJZ.js → claude-cli-GIIHOBGT.js} +4 -2
  139. package/dist/claude-install-BAUSJMW3.js +64 -0
  140. package/dist/{cli-BFDKEX53.js → cli-QY4KKA3D.js} +116 -49
  141. package/dist/cli-QY4KKA3D.js.map +1 -0
  142. package/dist/{client-XMWEKXX7.js → client-3YQKORVK.js} +4 -4
  143. package/dist/{codex-host-B6NAUWL6.js → codex-host-ZON3S6HU.js} +5 -5
  144. package/dist/{codex-install-GTGO5FYN.js → codex-install-HZV2DOAB.js} +62 -47
  145. package/dist/codex-install-HZV2DOAB.js.map +1 -0
  146. package/dist/{config-THJANIU5.js → config-QZOBMTEL.js} +18 -18
  147. package/dist/{config-names-JU54HYWY.js → config-names-Z5NZD5R2.js} +18 -18
  148. package/dist/{config-rules-VNU23RL4.js → config-rules-YOYHS6YL.js} +19 -19
  149. package/dist/config-subagents-WQV2ZAD5.js +362 -0
  150. package/dist/config-subagents-WQV2ZAD5.js.map +1 -0
  151. package/dist/{connect-HPWS7U63.js → connect-YDWTYU4B.js} +28 -27
  152. package/dist/{connect-HPWS7U63.js.map → connect-YDWTYU4B.js.map} +1 -1
  153. package/dist/core-0a66n3e7-TTP554XV.js +127 -0
  154. package/dist/core-0a66n3e7-TTP554XV.js.map +1 -0
  155. package/dist/core-0bmnpbz2-C2JIRVZO.js +10790 -0
  156. package/dist/core-0bmnpbz2-C2JIRVZO.js.map +1 -0
  157. package/dist/core-9je8ee1j-74DGHWPV.js +30 -0
  158. package/dist/core-9je8ee1j-74DGHWPV.js.map +1 -0
  159. package/dist/core-wadgcjfh-TSZFQZGH.js +666 -0
  160. package/dist/core-wadgcjfh-TSZFQZGH.js.map +1 -0
  161. package/dist/core-zg882d22-LKV5DZYW.js +37 -0
  162. package/dist/core-zg882d22-LKV5DZYW.js.map +1 -0
  163. package/dist/{decision-JIIHDTOF.js → decision-QSKHOGCO.js} +6 -6
  164. package/dist/{doctor-4MMHBRDU.js → doctor-ZWJXRD75.js} +67 -66
  165. package/dist/doctor-ZWJXRD75.js.map +1 -0
  166. package/dist/{explicit-AGENAX6E.js → explicit-ME2NRADQ.js} +45 -42
  167. package/dist/{explicit-AGENAX6E.js.map → explicit-ME2NRADQ.js.map} +1 -1
  168. package/dist/flush-stdio-NYIJ3QXT.js +18 -0
  169. package/dist/{fund-MLXUH24Q.js → fund-VF7TLDJH.js} +110 -34
  170. package/dist/fund-VF7TLDJH.js.map +1 -0
  171. package/dist/{hook-command-UB7FOEUL.js → hook-command-VZ27MGWO.js} +21 -20
  172. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  173. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  174. package/dist/hosts/claude/tenjin/hooks/hook-data.ts +152 -0
  175. package/dist/hosts/claude/tenjin/hooks/hooks.json +7 -0
  176. package/dist/hosts/claude/tenjin/hooks/model-viewer.tsx +2987 -0
  177. package/dist/hosts/claude/tenjin/hooks/register.tsx +265 -30
  178. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +14 -4
  179. package/dist/hosts/claude/tenjin/types/index.d.ts +133 -0
  180. package/dist/{hosts-WNQKYKP2.js → hosts-3EMTVM4H.js} +5 -3
  181. package/dist/index.js +16 -13
  182. package/dist/index.js.map +1 -1
  183. package/dist/{install-Q5SHHEDH.js → install-ZA7L2UF3.js} +34 -30
  184. package/dist/{install-funding-EGSW2KEP.js → install-funding-JDGYTF72.js} +9 -13
  185. package/dist/{install-identity-OID43B4D.js → install-identity-FFAYEFLX.js} +8 -8
  186. package/dist/{install-wallet-TZFWY5GK.js → install-wallet-2SFOVE3Q.js} +48 -33
  187. package/dist/{install-wallet-TZFWY5GK.js.map → install-wallet-2SFOVE3Q.js.map} +1 -1
  188. package/dist/mcp-36S6MK3C.js +67642 -0
  189. package/dist/mcp-36S6MK3C.js.map +1 -0
  190. package/dist/new-install-5L4GY3LN.js +51 -0
  191. package/dist/{package-NRHU7HBR.js → package-BONDXSV3.js} +2 -2
  192. package/dist/{passphrase-3JEVW5XG.js → passphrase-T4ULBN4M.js} +4 -4
  193. package/dist/{pay-I47AIUQR.js → pay-CMV5KL74.js} +37 -30
  194. package/dist/{payments-A5FNI5GN.js → payments-Z6UBZL4Z.js} +10 -10
  195. package/dist/reclaim-subagent-credit-ABSF67SJ.js +105 -0
  196. package/dist/reclaim-subagent-credit-ABSF67SJ.js.map +1 -0
  197. package/dist/{routing-quote-QQW2I5MH.js → routing-quote-AHLAREXR.js} +16 -18
  198. package/dist/{run-4SHEOBIU.js → run-JH7ELYAM.js} +41 -38
  199. package/dist/{runtime-BABJMHY7.js → runtime-2GX4ALJP.js} +12 -12
  200. package/dist/{runtime-activate-N6VLQI2C.js → runtime-activate-IDQ2NCSP.js} +9 -9
  201. package/dist/{runtime-launchers-GMAUICRW.js → runtime-launchers-YAPKCBHV.js} +7 -7
  202. package/dist/{runtime-place-DOEWFTF3.js → runtime-place-4POL4KK4.js} +3 -3
  203. package/dist/{send-ECXS6JEO.js → send-ELXFKEKY.js} +17 -17
  204. package/dist/{status-AHE5HSR7.js → status-FXUFWJDM.js} +89 -36
  205. package/dist/status-FXUFWJDM.js.map +1 -0
  206. package/dist/{status-line-63XFJAXR.js → status-line-IH5JBWBC.js} +11 -11
  207. package/dist/{streamableHttp-Z3YF6LTQ.js → streamableHttp-CP2ZQBIK.js} +4 -4
  208. package/dist/{uninstall-YGQPRCVY.js → uninstall-LJZUKM4D.js} +42 -38
  209. package/dist/{uninstall-YGQPRCVY.js.map → uninstall-LJZUKM4D.js.map} +1 -1
  210. package/dist/{update-GTLMLFA3.js → update-EUIX72IX.js} +34 -30
  211. package/dist/{usage-FCWP2CHO.js → usage-EKDC7LUC.js} +13 -13
  212. package/dist/{usdc-25RNBYYR.js → usdc-YIHK2OMC.js} +5 -5
  213. package/dist/{viemAdapter-By13KInL-3CG63XDX.js → viemAdapter-By13KInL-PRLSIESK.js} +2 -2
  214. package/dist/viemAdapter-By13KInL-PRLSIESK.js.map +1 -0
  215. package/dist/wallet-HSW757W6.js +80 -0
  216. package/dist/wallet-HSW757W6.js.map +1 -0
  217. package/docs/agent-permissions.md +19 -11
  218. package/docs/router-reference.md +21 -12
  219. package/docs/safety-model.md +4 -2
  220. package/docs/subagents-internals.md +97 -0
  221. package/docs/subagents.md +348 -0
  222. package/package.json +4 -1
  223. package/dist/balance-RQW5T5FB.js +0 -55
  224. package/dist/chunk-3X4GOMXT.js.map +0 -1
  225. package/dist/chunk-46HAB26L.js.map +0 -1
  226. package/dist/chunk-56SOPRM2.js.map +0 -1
  227. package/dist/chunk-5VWQSCDO.js.map +0 -1
  228. package/dist/chunk-6J64MQFD.js.map +0 -1
  229. package/dist/chunk-7U3P4PB7.js.map +0 -1
  230. package/dist/chunk-APWELUI7.js.map +0 -1
  231. package/dist/chunk-E6VP6MQM.js.map +0 -1
  232. package/dist/chunk-EQZ2CCWC.js.map +0 -1
  233. package/dist/chunk-FHXTEVO7.js.map +0 -1
  234. package/dist/chunk-FOEPH67T.js.map +0 -1
  235. package/dist/chunk-IVXPIIZJ.js +0 -91
  236. package/dist/chunk-IVXPIIZJ.js.map +0 -1
  237. package/dist/chunk-JF4T4HCQ.js.map +0 -1
  238. package/dist/chunk-LPQNZKSG.js +0 -269
  239. package/dist/chunk-LPQNZKSG.js.map +0 -1
  240. package/dist/chunk-MXN2ZEUB.js.map +0 -1
  241. package/dist/chunk-OO6FIBL7.js.map +0 -1
  242. package/dist/chunk-PNHNXUSL.js.map +0 -1
  243. package/dist/chunk-PYVQ74D5.js.map +0 -1
  244. package/dist/chunk-PZHBPGDE.js.map +0 -1
  245. package/dist/chunk-QEZZDIQT.js.map +0 -1
  246. package/dist/chunk-QXP3Z3JN.js.map +0 -1
  247. package/dist/chunk-RJ5HRPAZ.js.map +0 -1
  248. package/dist/chunk-TSIID2LV.js.map +0 -1
  249. package/dist/chunk-UVDJ5SSQ.js.map +0 -1
  250. package/dist/chunk-VFKPIIV2.js.map +0 -1
  251. package/dist/chunk-VH7JMLTG.js.map +0 -1
  252. package/dist/claude-install-7CVYQ73E.js +0 -60
  253. package/dist/cli-BFDKEX53.js.map +0 -1
  254. package/dist/codex-install-GTGO5FYN.js.map +0 -1
  255. package/dist/doctor-4MMHBRDU.js.map +0 -1
  256. package/dist/fund-MLXUH24Q.js.map +0 -1
  257. package/dist/mcp-CC3H7LFO.js +0 -3655
  258. package/dist/mcp-CC3H7LFO.js.map +0 -1
  259. package/dist/status-AHE5HSR7.js.map +0 -1
  260. package/dist/wallet-CJGEHP2Q.js +0 -64
  261. /package/dist/{_esm-MMYV66AX.js.map → _esm-2KST7HQ7.js.map} +0 -0
  262. /package/dist/{alive-VOIL5W3I.js.map → alive-5TV22PNF.js.map} +0 -0
  263. /package/dist/{auth-UHD3QFX4.js.map → auth-XI7BJFLW.js.map} +0 -0
  264. /package/dist/{balance-RQW5T5FB.js.map → balance-DFHC6XEU.js.map} +0 -0
  265. /package/dist/{ccip-CS7K5QRQ.js.map → ccip-HOW3DZYF.js.map} +0 -0
  266. /package/dist/{chunk-FSYH7J75.js.map → chunk-3Y6BHIN6.js.map} +0 -0
  267. /package/dist/{chunk-FZZWTDWP.js.map → chunk-3YPL6T3P.js.map} +0 -0
  268. /package/dist/{chunk-JEZMWJEF.js.map → chunk-44MVIRZH.js.map} +0 -0
  269. /package/dist/{chunk-27FIHFXF.js.map → chunk-45MMSBHA.js.map} +0 -0
  270. /package/dist/{chunk-7JB6SYJX.js.map → chunk-54ELBTKE.js.map} +0 -0
  271. /package/dist/{chunk-HWZO6HYZ.js.map → chunk-6QMDUDF2.js.map} +0 -0
  272. /package/dist/{chunk-FNBGRKS6.js.map → chunk-7V25UAQO.js.map} +0 -0
  273. /package/dist/{chunk-JOKPBYXP.js.map → chunk-DTEWAVNE.js.map} +0 -0
  274. /package/dist/{chunk-KAILF7QA.js.map → chunk-F43CV6UC.js.map} +0 -0
  275. /package/dist/{chunk-ACO7ZCR2.js.map → chunk-FKVJKLPI.js.map} +0 -0
  276. /package/dist/{chunk-2F5JUAHZ.js.map → chunk-GAJC4BQZ.js.map} +0 -0
  277. /package/dist/{chunk-L7N73ZAW.js.map → chunk-HAZAN4UM.js.map} +0 -0
  278. /package/dist/{chunk-6QJZA6EX.js.map → chunk-HI5XQOX2.js.map} +0 -0
  279. /package/dist/{chunk-BOENA6XR.js.map → chunk-HKGUKAQW.js.map} +0 -0
  280. /package/dist/{chunk-LJSCGIYH.js.map → chunk-HPRVFJPM.js.map} +0 -0
  281. /package/dist/{chunk-SDUOJRSV.js.map → chunk-IGLWLH73.js.map} +0 -0
  282. /package/dist/{chunk-3AKH7ODX.js.map → chunk-INSIW65E.js.map} +0 -0
  283. /package/dist/{chunk-2P3NJTHE.js.map → chunk-JHFFUVON.js.map} +0 -0
  284. /package/dist/{chunk-2TO5F6CT.js.map → chunk-K5KNGC4I.js.map} +0 -0
  285. /package/dist/{chunk-HUWTFKEM.js.map → chunk-KAQ4Q3TO.js.map} +0 -0
  286. /package/dist/{chunk-GS5RZF7U.js.map → chunk-KLDMLWXT.js.map} +0 -0
  287. /package/dist/{chunk-HN2EN6P4.js.map → chunk-KNKDMTHU.js.map} +0 -0
  288. /package/dist/{chunk-R2KMLONN.js.map → chunk-MJDO4EXD.js.map} +0 -0
  289. /package/dist/{chunk-IHVUE3XF.js.map → chunk-NJA6NT3A.js.map} +0 -0
  290. /package/dist/{chunk-S3JKF3IK.js.map → chunk-OJJFANO6.js.map} +0 -0
  291. /package/dist/{chunk-GGGEGMWC.js.map → chunk-Q6RSJCXB.js.map} +0 -0
  292. /package/dist/{chunk-OTIUEUIS.js.map → chunk-QKEUKBRK.js.map} +0 -0
  293. /package/dist/{chunk-X52BVGCJ.js.map → chunk-QQDPRTLP.js.map} +0 -0
  294. /package/dist/{chunk-6AQSUBNR.js.map → chunk-RGCPELQN.js.map} +0 -0
  295. /package/dist/{chunk-LQ33RLHL.js.map → chunk-TFT2X7SH.js.map} +0 -0
  296. /package/dist/{chunk-IVHGQNIN.js.map → chunk-VHXCPXUS.js.map} +0 -0
  297. /package/dist/{chunk-7DW7GAM6.js.map → chunk-VU6GMWF6.js.map} +0 -0
  298. /package/dist/{chunk-YU3DLVSQ.js.map → chunk-XSCGUO2U.js.map} +0 -0
  299. /package/dist/{chunk-EPCIJLLU.js.map → chunk-XWROSMI5.js.map} +0 -0
  300. /package/dist/{chunk-HMT6L65V.js.map → chunk-YJGEVBKZ.js.map} +0 -0
  301. /package/dist/{chunk-I47ARU5G.js.map → chunk-ZS7JIUJ3.js.map} +0 -0
  302. /package/dist/{claude-cli-2YKABJJZ.js.map → claude-cli-GIIHOBGT.js.map} +0 -0
  303. /package/dist/{claude-install-7CVYQ73E.js.map → claude-install-BAUSJMW3.js.map} +0 -0
  304. /package/dist/{client-XMWEKXX7.js.map → client-3YQKORVK.js.map} +0 -0
  305. /package/dist/{codex-host-B6NAUWL6.js.map → codex-host-ZON3S6HU.js.map} +0 -0
  306. /package/dist/{config-THJANIU5.js.map → config-QZOBMTEL.js.map} +0 -0
  307. /package/dist/{config-names-JU54HYWY.js.map → config-names-Z5NZD5R2.js.map} +0 -0
  308. /package/dist/{config-rules-VNU23RL4.js.map → config-rules-YOYHS6YL.js.map} +0 -0
  309. /package/dist/{decision-JIIHDTOF.js.map → decision-QSKHOGCO.js.map} +0 -0
  310. /package/dist/{hook-command-UB7FOEUL.js.map → flush-stdio-NYIJ3QXT.js.map} +0 -0
  311. /package/dist/{hosts-WNQKYKP2.js.map → hook-command-VZ27MGWO.js.map} +0 -0
  312. /package/dist/{install-Q5SHHEDH.js.map → hosts-3EMTVM4H.js.map} +0 -0
  313. /package/dist/{install-funding-EGSW2KEP.js.map → install-ZA7L2UF3.js.map} +0 -0
  314. /package/dist/{install-identity-OID43B4D.js.map → install-funding-JDGYTF72.js.map} +0 -0
  315. /package/dist/{package-NRHU7HBR.js.map → install-identity-FFAYEFLX.js.map} +0 -0
  316. /package/dist/{passphrase-3JEVW5XG.js.map → new-install-5L4GY3LN.js.map} +0 -0
  317. /package/dist/{pay-I47AIUQR.js.map → package-BONDXSV3.js.map} +0 -0
  318. /package/dist/{routing-quote-QQW2I5MH.js.map → passphrase-T4ULBN4M.js.map} +0 -0
  319. /package/dist/{run-4SHEOBIU.js.map → pay-CMV5KL74.js.map} +0 -0
  320. /package/dist/{payments-A5FNI5GN.js.map → payments-Z6UBZL4Z.js.map} +0 -0
  321. /package/dist/{runtime-activate-N6VLQI2C.js.map → routing-quote-AHLAREXR.js.map} +0 -0
  322. /package/dist/{runtime-launchers-GMAUICRW.js.map → run-JH7ELYAM.js.map} +0 -0
  323. /package/dist/{runtime-BABJMHY7.js.map → runtime-2GX4ALJP.js.map} +0 -0
  324. /package/dist/{runtime-place-DOEWFTF3.js.map → runtime-activate-IDQ2NCSP.js.map} +0 -0
  325. /package/dist/{update-GTLMLFA3.js.map → runtime-launchers-YAPKCBHV.js.map} +0 -0
  326. /package/dist/{usdc-25RNBYYR.js.map → runtime-place-4POL4KK4.js.map} +0 -0
  327. /package/dist/{send-ECXS6JEO.js.map → send-ELXFKEKY.js.map} +0 -0
  328. /package/dist/{status-line-63XFJAXR.js.map → status-line-IH5JBWBC.js.map} +0 -0
  329. /package/dist/{streamableHttp-Z3YF6LTQ.js.map → streamableHttp-CP2ZQBIK.js.map} +0 -0
  330. /package/dist/{viemAdapter-By13KInL-3CG63XDX.js.map → update-EUIX72IX.js.map} +0 -0
  331. /package/dist/{usage-FCWP2CHO.js.map → usage-EKDC7LUC.js.map} +0 -0
  332. /package/dist/{wallet-CJGEHP2Q.js.map → usdc-YIHK2OMC.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/install.ts","../src/lib/skill-placement.ts","../src/router/claude-install.ts","../src/router/legacy-install.ts","../src/router/hooks-file.ts","../src/router/status-line-wiring.ts","../src/router/plugin-registration.ts","../src/commands/update.ts","../src/router/reachability.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport pkg from '../../package.json';\nimport { persistRouterDefaults, persistRouterProject, type RouterLimits } from '../commands/config';\nimport { askText, selectOne } from '../lib/clack';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { paint } from '../lib/output';\nimport { isDefaultDataDir, realOr, samePath, tilde } from '../lib/paths';\nimport { isSourceCheckout } from '../lib/install-location';\nimport { runningGlibc, unpinnedPlatform } from '../lib/runtime-fetch';\nimport { resolveContextSettings } from '../lib/settings';\nimport type { SpendPolicy } from '../lib/policy';\nimport type { RuntimeSetup, setupRuntime } from '../lib/runtime';\nimport type { LauncherResult } from '../lib/runtime-launchers';\nimport { hasRuntime, runtimeBuild, type RuntimePointer } from '../lib/runtime-layout';\nimport { removeRetiredSkills } from '../lib/skill-placement';\nimport { loadRawConfig } from '../lib/config';\nimport type { WalletDeps, WalletOutcome } from '../commands/install-wallet';\nimport type { CommandContext, CommandResult } from '../context';\nimport { readAliveStamp } from './alive';\nimport {\n captureNewInstall,\n reserveNewInstall,\n finishNewInstall,\n type InstallSubagentChoice,\n type NewInstallSession,\n} from './new-install';\nimport { SUGGESTED_FUND_USD } from './fee';\nimport {\n findClaudeBinary,\n readClaudeCode,\n type ClaudeBinary,\n type ClaudeCodeState,\n} from './claude-cli';\nimport { claudeInstallAt, settingsInstallPaths } from './claude-install';\nimport {\n inspectLegacyInstall,\n removeLegacyInstall,\n type LegacyInstall,\n type LegacyRemoval,\n} from './legacy-install';\nimport { MCP_SERVER_NAME, PLUGIN_ID } from './names';\nimport { CLAUDE_CODE_FLOOR } from './claude-cli';\nimport { inspectPluginFolder } from './plugin-folder';\nimport {\n folderFor,\n folderState,\n marketplaceAdded,\n readPluginListing,\n recordedInstalls,\n registerPlugin,\n type PluginRegistration,\n type PluginScope,\n} from './plugin-registration';\nimport { probeRouter, type RouterCheck } from './reachability';\nimport {\n readMcpServers,\n type InstalledAt,\n type ListMcpProcesses,\n type ListProcesses,\n} from './mcp-processes';\nimport {\n DEFAULTS_LABEL,\n limitsLine,\n ROUTER_DEFAULTS,\n ROUTING_FEE_TERMS,\n shownLimits,\n SPEND_QUESTION,\n spendChoiceQuestion,\n spendOptions,\n FEE_APPROVAL,\n} from './spend-question';\nimport { recordTermsTold } from './terms-notice';\nimport { shQuote } from './plugin-files';\nimport { fundStep, type FundingDeps } from './install-funding';\nimport { underAgentHarness } from '../lib/session';\nimport { agentFixFor, REPAIR_CLAUSE, WALLET_REASONS } from './wallet-reasons';\n\n/**\n * `tenjin install` prepares the wallet, spending limits and Claude Code plugin.\n * Registration does not establish activation in an already open session.\n *\n * What it writes: the wallet and the spend defaults under the data dir. With\n * the default data dir, this build is copied into Tenjin's own runtime,\n * `~/.tenjin/runtime`, with a pinned Node and a `tenjin` launcher in\n * `~/.local/bin` (see `lib/runtime.ts`), and the plugin is registered from\n * the runtime's `claude` folder, whose commands run that Node and that copy,\n * so neither a Node upgrade nor `npm rm -g tenjin-cli` stops it. Unsupported\n * profiles and runtime failures stop registration. Only source checkouts use\n * this package's development plugin folder. The plugin goes through Claude\n * Code's own `claude plugin` commands (see `plugin-registration.ts`), or is\n * written as a folder under the config dir's `skills/` where no `claude`\n * binary can be run. The plugin carries the seven routing legs, the `router`\n * MCP server, and the hooks that allow the request tool and deny the legs' own\n * tool to the model, so this command writes nothing into `settings.json` or\n * `~/.claude.json` itself.\n *\n * An agent relays the spending choice and prepares a funding link; a terminal\n * asks both choices directly. Funding is optional. Activation follows the host-specific step.\n *\n * THE SETTINGS INSTALL OF EARLIER RELEASES is left working until the plugin\n * has proven to load on this machine (see {@link migrateSettingsInstall}).\n */\n\nexport { AFTER_CALL_TIMEOUT_SECONDS, ROUTE_HOOK_TIMEOUT_SECONDS } from './plugin-files';\n\nexport const DISCLOSURE: readonly string[] = [\n '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.',\n 'Privacy: https://tenjin.sh/privacy · Terms: https://tenjin.sh/terms',\n];\n\n/**\n * What Tenjin adds, said right after the success line: three things an agent\n * cannot do on its own (the groups tenjin.sh/tools leads with), and where the\n * rest is.\n */\nexport const CAPABILITY_LINES: readonly string[] = [\n \"Your agent can now make images, voiceovers and music, look up people and companies, read pages normal fetches can't open, and more.\",\n 'See every tool at tenjin.sh/tools',\n];\n\n/**\n * The end of an install's receipt, kept apart (`humanTail`) so a checkout run\n * in the terminal comes before it: the limits, the one next step, then the\n * disclosure, dimmed and word for word.\n */\nexport function receiptTail(ctx: CommandContext, policy: SpendPolicy, next: string): string[] {\n return [\n '',\n `Limits ${limitsLine(policy)}`,\n '',\n `Next: ${next}`,\n '',\n ...DISCLOSURE.map((line) => paint(ctx.io, 'dim', line)),\n ];\n}\n\n/**\n * While a settings install is still here, a reload would load the plugin beside the\n * pre-upgrade `x402` server that session is still running, so every event\n * would route twice.\n */\nexport const NEW_SESSION_STEP = 'start a new Claude Code session so Tenjin loads';\nexport const RELOAD_STEP =\n 'run `/reload-plugins` in this conversation so Tenjin loads, then continue your task';\n\n/** Desktop reload cannot attach the plugin's MCP server; terminal reload can. */\nexport function loadStep(\n settingsInstallPresent: boolean,\n env: NodeJS.ProcessEnv = {},\n command = 'tenjin',\n): string {\n if (\n env.CLAUDE_CODE_ENTRYPOINT === 'claude-desktop' ||\n env.CLAUDE_CODE_ENTRYPOINT === 'claude-desktop-3p'\n ) {\n return (\n \"choose New session in Claude Desktop's Code tab for this same folder so Tenjin loads. \" +\n \"Before switching, give the person one short ready-to-paste continuation prompt filled with this conversation's task, progress and next action; \" +\n `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`\n );\n }\n if (!underAgentHarness(env))\n return 'open a new Claude Code session so Tenjin loads, then continue your task';\n return settingsInstallPresent ? NEW_SESSION_STEP : RELOAD_STEP;\n}\n\nexport interface RouterInstallArgs {\n /**\n * Register the plugin for this project only (Claude Code's `local` scope,\n * `.claude/settings.local.json`), or write its folder under the project's\n * `.claude/skills/`.\n */\n project?: boolean;\n /**\n * Bring what this machine ALREADY has up to the running build: the plugin,\n * or a settings install the plugin then replaces, with no spend-limit\n * write. A refusal when nothing of ours is here; a runtime alone (Codex\n * kept it after Claude Code's install was removed) is brought up to the\n * running build with nothing for Claude Code created. It may add Tenjin's\n * runtime and its launcher to an install that predates them (never a\n * downgrade: a newer runtime is kept), and records the project installs\n * Claude Code lists so `tenjin update` refreshes them too. `tenjin update`\n * spawns exactly this after it swaps the binary, so the flag's name and\n * meaning are a compatibility contract.\n */\n refresh?: boolean;\n /**\n * Accept the defaults instead of asking: the selector's \"Use the defaults\",\n * for an agent running the person's answer.\n */\n yes?: boolean;\n subagents?: InstallSubagentChoice;\n /** Create no wallet, for CI and scripted machines. */\n noWallet?: boolean;\n /**\n * `--session-budget` and `--max-auto-spend`: the person's own limits, in USD\n * as typed (`none` for no daily limit; zero blocks positive automatic payments).\n * Either one answers the question; the other then takes the default. A named\n * limit replaces what the config file holds.\n */\n maxAutoSpend?: string;\n sessionBudget?: string;\n}\n\nexport interface RouterInstallDeps extends WalletDeps, FundingDeps {\n /** Shared by both host installers; the core action finalizes it after every host succeeds. */\n newInstall?: NewInstallSession;\n /** This user's running routers and Claude Code processes; tests inject them. */\n listProcesses?: ListProcesses;\n /** This user's running `tenjin mcp` processes; tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When this build was installed; tests inject it. */\n installedAt?: InstalledAt;\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** Finds the `claude` binary; tests inject one, production reads PATH and `CLAUDE_CODE_EXECPATH`. */\n findClaude?: (env: NodeJS.ProcessEnv) => ClaudeBinary | null;\n /** The marketplace folder; production reads this package's `dist/hosts/claude`. */\n hostsDir?: string | null;\n /** The CLI entry a plugin folder's commands run. Production reads this package's `dist/index.js`. */\n cliEntry?: string;\n /** Whether a person can answer the spend-limit question (a TTY on stdout and\n * stdin, no `--json`); injected in tests. */\n isInteractive?: boolean;\n promptSubagents?: () => Promise<InstallSubagentChoice | null>;\n /** The spend-limit selector; defaults to the clack list. */\n promptLimits?: (message: string) => Promise<LimitsChoice | null>;\n /** One amount question; defaults to the clack text input. */\n promptAmount?: (message: string, placeholder: string) => Promise<string | null>;\n /** The router reachability probe's transport; tests inject it. */\n fetchImpl?: typeof fetch;\n /** Sets up Tenjin's runtime for this build; tests inject it, production runs `setupRuntime`. */\n runtime?: (o: Parameters<typeof setupRuntime>[0]) => Promise<RuntimeSetup>;\n}\n\nexport type LimitsChoice = 'approve' | 'own';\n\n/** The settings install's state, as install, update, doctor and uninstall report it. */\nexport interface Migration {\n /**\n * `none` (no settings install here), `pending` (left in place until the\n * plugin proves it loads), `done` (removed by this run), or `blocked` (the\n * settings file could not be read).\n */\n state: 'none' | 'pending' | 'done' | 'blocked';\n settingsPath: string;\n /** Why it is still pending or blocked. */\n reason?: string;\n removed?: LegacyRemoval;\n}\n\n/**\n * THE GUARDED MIGRATION. A working settings install is removed only once the\n * plugin has proven to load on this machine: Claude Code at or above the floor\n * and listing the plugin enabled (when a binary can be asked), and the\n * plugin's `alive` leg having stamped the machine from a real session. Until\n * then both stay, and the `alive` marker keeps the old legs silent in any\n * session the plugin serves. Only `install` and `update` migrate; doctor\n * reports.\n */\nexport async function pluginProof(\n claude: ClaudeCodeState,\n dataDir: string,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<{ proven: true } | { proven: false; reason: string }> {\n if (claude.binary !== null && !claude.meetsFloor) {\n return {\n proven: false,\n reason: `Claude Code ${claude.version ?? '(unknown)'} is older than the plugin needs`,\n };\n }\n if (claude.binary !== null) {\n const listing = await readPluginListing(claude.binary, env, cwd);\n if (!listing.enabled) {\n return { proven: false, reason: 'Claude Code does not list the plugin as enabled yet' };\n }\n }\n if ((await readAliveStamp(dataDir)) === null) {\n return {\n proven: false,\n reason: 'the plugin has not loaded in a Claude Code session on this machine yet',\n };\n }\n return { proven: true };\n}\n\nexport async function migrateSettingsInstall(\n legacy: LegacyInstall,\n claude: ClaudeCodeState,\n opts: { dataDir: string; env: NodeJS.ProcessEnv; cwd: string; mcpScope: 'user' | 'project' },\n): Promise<Migration> {\n if (!legacy.present) return { state: 'none', settingsPath: legacy.settingsPath };\n const proof = await pluginProof(claude, opts.dataDir, opts.env, opts.cwd);\n if (!proof.proven) {\n return { state: 'pending', settingsPath: legacy.settingsPath, reason: proof.reason };\n }\n const removed = await removeLegacyInstall(legacy, {\n binary: claude.binary,\n env: opts.env,\n cwd: opts.cwd,\n mcpScope: opts.mcpScope,\n });\n return { state: 'done', settingsPath: legacy.settingsPath, removed };\n}\n\n/**\n * Is there a project install here? A refresh, a bare doctor and a bare\n * uninstall are given no scope, and `tenjin update` runs its refresh from\n * home, where nothing proves one. A project install is taken when this\n * directory, not being home, holds one: the plugin enabled in its\n * `settings.local.json`, its plugin folder, or a settings install's entries.\n */\nexport async function projectInstallHere(\n cwd: string,\n home: string,\n env: NodeJS.ProcessEnv,\n): Promise<boolean> {\n if (await samePath(cwd, home)) return false;\n return projectInstallAt(cwd, home, env);\n}\n\n/**\n * Does `dir` still hold the project install `install --project` recorded\n * there? Home included: a `--project` install at home is supported, and there\n * its plugin folder and settings file are the user install's own, so only the\n * plugin enabled in `.claude/settings.local.json` proves it.\n */\nexport async function projectInstallAt(\n dir: string,\n home: string,\n env: NodeJS.ProcessEnv,\n): Promise<boolean> {\n const atHome = await samePath(dir, home);\n return claudeInstallAt(\n 'local',\n env,\n home,\n dir,\n atHome ? ['enabled'] : ['enabled', 'folder', 'settings-hooks'],\n );\n}\n\n/** How a refresh with no Claude Code install to converge refuses. */\nexport const NOTHING_TO_REFRESH = 'Nothing to refresh';\n\n/** Is any install of ours here for a refresh to bring up to date? */\nasync function somethingToRefresh(\n claude: ClaudeCodeState,\n scope: PluginScope,\n legacy: LegacyInstall,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<boolean> {\n if (legacy.present) return true;\n if ((await folderState(scope, env, home, cwd)).state === 'ours') return true;\n if (claude.binary !== null) {\n const listing = await readPluginListing(claude.binary, env, cwd);\n if (listing.id === PLUGIN_ID) return true;\n }\n return false;\n}\n\nexport async function runRouterInstall(\n args: RouterInstallArgs,\n ctx: CommandContext,\n deps: RouterInstallDeps = {},\n): Promise<CommandResult> {\n const newInstall = deps.newInstall ?? (await captureNewInstall(ctx.dataDir));\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) {\n throw new CliError('INTERNAL', 'The home directory is not an absolute path.', {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n });\n }\n assertPluginInstallation(ctx.dataDir, home, env);\n const config = await loadRawConfig(ctx.dataDir); // Validate before any install writes; retired keys remain readable.\n const named = namedLimits(args);\n const cwd = deps.cwd ?? process.cwd();\n // An explicit --project wins, including for a project rooted at home.\n const project =\n args.project ?? (args.refresh === true && (await projectInstallHere(cwd, home, env)));\n const scope: PluginScope = project ? 'local' : 'user';\n const claude = await readClaudeCode(env, cwd, deps.findClaude ?? findClaudeBinary);\n const paths = settingsInstallPaths(project, env, home, cwd);\n const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);\n\n const setUpRuntime = () =>\n (deps.runtime ?? defaultRuntime)({\n dataDir: ctx.dataDir,\n home,\n env,\n version: pkg.version,\n moduleDir: dirname(fileURLToPath(import.meta.url)),\n refresh: args.refresh === true,\n });\n\n if (args.refresh === true && !(await somethingToRefresh(claude, scope, legacy, env, home, cwd))) {\n // A RUNTIME WITH NO CLAUDE CODE SURFACE: `tenjin uninstall --harness\n // claude` keeps the runtime and its launcher while Codex still runs them,\n // and `tenjin update` brings that runtime up to its new build through this\n // same refresh. Only the runtime step runs; nothing for Claude Code is\n // registered, written or migrated.\n if (!project && hasRuntime(ctx.dataDir, home)) {\n const rt = await setUpRuntime();\n requireRuntime(rt);\n await recordClaudeProjects(ctx.dataDir, config.install?.routerProjects ?? [], env, home);\n if (runtimeLaunch(rt) !== null) {\n await collectRuntime(rt.root, await fallbackFolders(ctx.dataDir, env, home, cwd, false));\n }\n return runtimeOnlyRefresh(ctx, rt, home);\n }\n if (!project)\n await recordClaudeProjects(ctx.dataDir, config.install?.routerProjects ?? [], env, home);\n throw new CliError(\n 'REFUSED',\n `${NOTHING_TO_REFRESH}: neither the ${PLUGIN_ID} plugin nor a settings install of Tenjin is registered here.`,\n { fix: 'Run `tenjin install` to set this machine up.' },\n );\n }\n // The install's gate: a refresh, `--json`, or a run with no terminal on\n // either side asks nothing. An agent's install is that run: its shell has no\n // terminal. Install then writes no spend limit, the defaults ($1 a call,\n // $5 a day) hold as they do for any key the file leaves out, and its output hands\n // the question to whoever ran it (see {@link spendApproval}).\n const humanOutput = ctx.flags.json === true ? false : (deps.isInteractive ?? ctx.io.isTTY);\n const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n // `--yes` is the selector's \"Use the defaults\", answered ahead, and the two\n // amount flags its \"Set my own limits\": the same install, run\n // again by an agent for the person's answer. A file that names either limit\n // has been answered before, so nothing asks again.\n const answered = args.yes === true || named.keys.length > 0;\n const unasked = config.maxAutoSpend === undefined && config.sessionBudget === undefined;\n const limits =\n args.refresh === true\n ? undefined\n : named.keys.length > 0\n ? { ...shownLimits(config), ...named.limits }\n : args.yes === true\n ? shownLimits(config)\n : canPrompt && unasked\n ? await approveLimits(deps)\n : {};\n if (args.refresh !== true)\n await reserveNewInstall(\n newInstall,\n !legacy.present &&\n (!newInstall.absent || !(await somethingToRefresh(claude, scope, legacy, env, home, cwd))),\n );\n // BELOW THE FLOOR, THE SETTINGS INSTALL WINS. The plugin's routing legs\n // need Claude Code 2.1.287, but its `alive` leg is a command that runs on\n // any version and would silence the settings install in every session,\n // leaving the machine unrouted and the person untold. So nothing is\n // registered until `claude update`, the settings install stays as it is\n // (its `tenjin hook` commands, where it wrote those, only tell the person\n // to set Tenjin up again), and no runtime is set up.\n const deferred = !claude.meetsFloor && legacy.present;\n const rt = deferred ? null : await setUpRuntime();\n requireRuntime(rt);\n // CLAUDE CODE'S OWN PROJECT INSTALLS ARE RECORDED, before a refresh can\n // refuse: `tenjin update` refreshes every recorded project after its home\n // child, so a project an older release installed without recording it\n // moves to the runtime with the rest. A user-scope run only; never fatal.\n if (!project) {\n await recordClaudeProjects(ctx.dataDir, config.install?.routerProjects ?? [], env, home);\n }\n\n const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true, limits, named.keys);\n // Limits approved in this run were approved on today's routing terms, so\n // the first routing call does not tell them again (`terms-notice.ts`).\n if (args.refresh !== true && (answered || (canPrompt && unasked))) {\n await recordTermsTold(ctx.dataDir);\n }\n const removedKeysLines =\n spend.removed.length > 0\n ? [\n `Removed retired settings: ${spend.removed.join(', ')}. Automatic router limits remain in effect; manual pay always requires consent.`,\n ]\n : [];\n const removedSkills = await removeRetiredSkills(home, project ? cwd : undefined);\n const launch = runtimeLaunch(rt);\n const plugin: PluginRegistration = deferred\n ? deferredRegistration(scope, claude)\n : await registerPlugin({\n binary: claude.binary,\n scope,\n version: launch?.version ?? pkg.version,\n env,\n home,\n cwd,\n ...(launch !== null\n ? { hostsDir: launch.hostsDir, cliEntry: launch.cliEntry, node: launch.node }\n : {\n ...(deps.hostsDir !== undefined ? { hostsDir: deps.hostsDir } : {}),\n ...(deps.cliEntry !== undefined ? { cliEntry: deps.cliEntry } : {}),\n }),\n });\n // A registration that failed after this run switched the runtime puts the\n // runtime back, so Claude Code is never left on a folder it was not given.\n // UNLESS ITS `marketplace add` WENT THROUGH: Claude Code's one `tenjin` row\n // now names `runtime/claude` and reads it in place, so putting back what was\n // there (nothing at all, on a first activation) would leave it loading an\n // empty folder. The render it holds passed `verifyBuild`, so it stays.\n // Old versions are collected only once the plugin is registered.\n if (rt !== null && launch !== null) {\n if (plugin.state !== 'failed') {\n await collectRuntime(rt.root, await fallbackFolders(ctx.dataDir, env, home, cwd, project));\n } else if (!marketplaceAdded(plugin, launch.hostsDir)) {\n await rt.restore?.().catch(() => undefined);\n }\n }\n // A PROJECT INSTALL IS RECORDED, so `tenjin update`, which refreshes from\n // home where this scope is not visible, refreshes it from here too.\n if (project && plugin.state !== 'failed') {\n await persistRouterProject(ctx.dataDir, cwd).catch(() => undefined);\n }\n const migration =\n legacy.unreadable !== undefined && !legacy.present\n ? { state: 'blocked' as const, settingsPath: paths.settingsPath, reason: legacy.unreadable }\n : await migrateSettingsInstall(legacy, claude, {\n dataDir: ctx.dataDir,\n env,\n cwd,\n mcpScope: paths.mcpScope,\n });\n // A `tenjin mcp` that started before this install runs the old build until\n // its session reloads it. Named, never killed.\n const pending = settingsInstallStays(migration);\n const servers = await readMcpServers(deps, {\n settingsInstallPending: pending,\n ...(launch !== null ? { version: launch.version } : {}),\n });\n const serverLines =\n servers.stale > 0\n ? [paint(ctx.io, 'yellow', `! ${servers.check.detail}. ${servers.check.fix ?? ''}`.trim())]\n : [];\n const claudeCode = claudeCodeData(claude);\n const notices = refreshNotices(plugin, claude, migration, rt, home);\n if (args.refresh === true) {\n // A refresh that could not register the plugin is not a converged install,\n // unless the settings install it would replace is still here.\n if (plugin.state === 'failed' && migration.state !== 'pending') {\n throw new CliError(\n 'REFUSED',\n `The ${PLUGIN_ID} plugin could not be registered: ${plugin.reason ?? 'unknown reason'}.`,\n { fix: registrationFix(plugin), details: { plugin, claudeCode, migration } },\n );\n }\n return {\n data: {\n plugin,\n claudeCode,\n migration,\n notices,\n refresh: true,\n spend,\n removedSkills,\n scope,\n mcpServer: servers.check,\n runtime: runtimeData(rt),\n launcher: rt?.launcher ?? null,\n },\n humanLines: [\n ...refreshLines(ctx, plugin, claude, migration, rt, home),\n ...removedKeysLines,\n ...serverLines,\n ],\n };\n }\n // The wallet step, which never asks here: a\n // lookup cannot be paid without a wallet, so install makes one. A failure is\n // reported, never fatal; everything above is useful without it. It checks\n // that the wallet can SIGN (`verify`), and nothing about routing or funds:\n // install computes no routing eligibility. Loaded lazily: the status line\n // shares this module's chunk\n // and must not load the wallet layer.\n const { resolveWallet } = await import('../commands/install-wallet');\n const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? 'flag' : undefined, false);\n // Read back AFTER the write: a machine that already carried its own caps\n // keeps them, and a readout quoting the defaults would describe limits this\n // run did not set.\n const effective = await resolveContextSettings(ctx);\n const command = continuationCommand(rt);\n const spendAsk = !canPrompt && !answered && unasked ? spendStep(args, command) : undefined;\n // A warning, never a failure: everything above is written and correct, and\n // the network this machine is on now may not be the one it uses later.\n const asksAgent = !canPrompt && underAgentHarness(env);\n const [router, funding] = await Promise.all([\n probeRouter(effective.baseUrl, {\n timeoutMs: ctx.flags.timeout,\n env,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n // The spend question comes first, because its answer picks the install\n // command. Funding instructions ride on the install that follows it.\n (asksAgent || canPrompt) &&\n spendAsk === undefined &&\n plugin.state !== 'failed' &&\n plugin.state !== 'deferred'\n ? (deps.funding ?? fundStep)(\n wallet,\n effective.rpcUrl,\n deps,\n `${command} fund ${SUGGESTED_FUND_USD}`,\n )\n : Promise.resolve(undefined),\n ]);\n const fund = funding?.step;\n const nextSteps: QuestionStep[] = [\n ...(spendAsk !== undefined ? [spendAsk] : []),\n ...(fund !== undefined ? [fund] : []),\n ];\n\n const data = {\n plugin,\n claudeCode,\n migration,\n next: nextStep(\n plugin,\n claude,\n wallet,\n migration,\n asksAgent ? nextSteps.length : 0,\n ctx.io.isTTY,\n command,\n env,\n ),\n nextSteps,\n ...(funding?.warning !== undefined ? { fundingWarning: funding.warning } : {}),\n // The check for this scope, said outright; a bare doctor in the project\n // also finds it from what the project holds.\n ...(project ? { doctor: `${command} doctor --project` } : {}),\n spend: { ...spend, effective: effectiveLimits(effective.policy) },\n wallet,\n router: {\n status: router.status === 'ok' ? 'ok' : 'warn',\n detail: router.detail,\n ...(router.fix !== undefined ? { fix: router.fix } : {}),\n },\n disclosure: DISCLOSURE,\n removedSkills,\n mcpServer: servers.check,\n runtime: runtimeData(rt),\n launcher: rt?.launcher ?? null,\n };\n newInstall.completed.push(plugin.state !== 'failed' && plugin.state !== 'deferred');\n newInstall.continueWith ??= installCommand(args, command);\n const result: CommandResult = {\n data,\n humanLines: [\n ...lines(ctx, {\n plugin,\n claude,\n migration,\n wallet,\n ...(funding?.warning !== undefined ? { fundingWarning: funding.warning } : {}),\n asks: asksAgent ? nextSteps.length : 0,\n policy: effective.policy,\n ...(spendAsk !== undefined ? { spendAsk } : {}),\n router,\n rt,\n home,\n env,\n }),\n ...removedKeysLines,\n ...serverLines,\n ],\n humanTail: receiptTail(ctx, effective.policy, data.next),\n };\n return deps.newInstall\n ? result\n : finishNewInstall(result, newInstall, ctx, {\n ...(args.subagents !== undefined ? { choice: args.subagents } : {}),\n yes: args.yes === true,\n isInteractive: canPrompt,\n ...(deps.promptSubagents ? { promptSubagents: deps.promptSubagents } : {}),\n });\n}\n\n/** Loaded lazily: the status line shares this module's chunk and must not load the runtime. */\nexport async function defaultRuntime(o: Parameters<typeof setupRuntime>[0]): Promise<RuntimeSetup> {\n const { setupRuntime } = await import('../lib/runtime');\n return setupRuntime(o);\n}\n\n/** Results a later host of one install run got from the first host's setup: their lines were said there. */\nconst sharedResults = new WeakSet<RuntimeSetup>();\n\n/**\n * ONE RUNTIME SETUP PER INSTALL RUN, however many hosts it installs. The first\n * host sets the runtime up; every later host gets that result rather than a\n * second setup, which would retry a failed Node download in full, and says\n * none of its lines again. Only the activating host may roll that switch\n * back: a later host shares folders the first may already have registered.\n * If the first host does roll back, the next host must set the runtime up again.\n */\nexport function runtimeOncePerRun(setup = defaultRuntime): typeof defaultRuntime {\n let first: Promise<RuntimeSetup> | undefined;\n return async (o) => {\n if (first === undefined) {\n first = setup(o).then((rt) => {\n const restore = rt.restore;\n if (restore === undefined) return rt;\n return {\n ...rt,\n restore: async () => {\n try {\n await restore();\n } finally {\n first = undefined;\n }\n },\n };\n });\n return first;\n }\n const rt = { ...(await first) };\n delete rt.restore;\n sharedResults.add(rt);\n return rt;\n };\n}\n\n/**\n * A refresh that brought only the runtime up to date, for a machine with no\n * Claude Code surface of Tenjin's: `plugin` is null, and the runtime's\n * sentences ride in `notices` for update's parent, as a full refresh's do.\n */\nfunction runtimeOnlyRefresh(ctx: CommandContext, rt: RuntimeSetup, home: string): CommandResult {\n return {\n data: {\n plugin: null,\n refresh: true,\n scope: 'user',\n notices: runtimeNotices(rt, home),\n runtime: runtimeData(rt),\n launcher: rt.launcher,\n },\n humanLines: [\n `${paint(ctx.io, 'green', '✓')} Tenjin's runtime is up to date; no Claude Code plugin is registered here, so none was refreshed`,\n ...runtimeLines(ctx, rt, home),\n ],\n };\n}\n\n/**\n * GC of the runtime's unused versions: an optimisation that never holds\n * install up or fails it. The plugin folders in `folders` that are ours run a\n * runtime version and its Node by absolute path, which `state.json` does not\n * name, so those are kept.\n */\nasync function collectRuntime(root: string, folders: readonly string[]): Promise<void> {\n try {\n const { collect } = await import('../lib/runtime-activate');\n await collect(root, { lockWaitMs: 5_000, keep: await folderPointers(root, folders) });\n } catch {\n // The next install collects them.\n }\n}\n\n/**\n * Every plugin folder an install wrote where it could run no `claude` binary:\n * the user's under the config dir, and each recorded project's (plus this\n * run's, for a `--project` run not recorded yet) under its `.claude/skills/`.\n */\nasync function fallbackFolders(\n dataDir: string,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n project: boolean,\n): Promise<string[]> {\n const projects = (await loadRawConfig(dataDir).catch(() => null))?.install?.routerProjects ?? [];\n return [\n folderFor('user', env, home, cwd),\n ...[...projects, ...(project ? [cwd] : [])].map((dir) => folderFor('local', env, home, dir)),\n ];\n}\n\n/** A `node/<V>` folder name: digits and dots only, so a `..` can never pass. */\nconst NODE_DIR_RE = /^\\d+\\.\\d+\\.\\d+$/;\n\n/**\n * The runtime version and Node each folder that exists and is ours runs, read\n * from its `.mcp.json`: an entry under `<root>/versions/<cli>/` run by a Node\n * under `<root>/node/<V>/`. A folder run from a package, or unreadable, names\n * none.\n */\nasync function folderPointers(root: string, folders: readonly string[]): Promise<RuntimePointer[]> {\n const pointers: RuntimePointer[] = [];\n for (const dir of folders) {\n if ((await inspectPluginFolder(dir)) !== 'ours') continue;\n const server = await readFile(join(dir, '.mcp.json'), 'utf8')\n .then(\n (raw) =>\n (\n JSON.parse(raw) as {\n mcpServers?: Record<string, { command?: unknown; args?: unknown }>;\n }\n ).mcpServers?.[MCP_SERVER_NAME],\n )\n .catch(() => undefined);\n const entry = Array.isArray(server?.args) ? (server.args[0] as unknown) : undefined;\n const node = server?.command;\n if (typeof entry !== 'string' || typeof node !== 'string') continue;\n const build = runtimeBuild(dirname(entry));\n const nodeVersion = relative(join(root, 'node'), node).split(sep)[0] ?? '';\n if (build !== null && resolve(build.root) === resolve(root) && NODE_DIR_RE.test(nodeVersion)) {\n pointers.push({ cli: build.cli, node: nodeVersion });\n }\n }\n return pointers;\n}\n\nexport function assertPluginInstallation(\n dataDir: string,\n home: string,\n env: NodeJS.ProcessEnv,\n): void {\n if (env.TENJIN_DATA_DIR && !isDefaultDataDir(dataDir, home)) {\n throw new CliError('REFUSED', 'Plugin installation needs the default data directory.', {\n fix: 'Run without TENJIN_DATA_DIR. Other CLI commands still support it.',\n });\n }\n if (!isSourceCheckout(dirname(fileURLToPath(import.meta.url)))) {\n const unsupported = unpinnedPlatform(process.platform, process.arch, runningGlibc());\n if (unsupported !== null)\n throw new CliError('REFUSED', `Plugin installation is unsupported on ${unsupported}.`, {\n fix: 'Use macOS, Windows or glibc Linux 2.28+ on x64/arm64. Your existing setup was kept.',\n });\n }\n}\n\n/** Setup continuations must work before a reload adds the plugin's bin folder to PATH. */\nexport function continuationCommand(\n rt: RuntimeSetup | null,\n platform: NodeJS.Platform = process.platform,\n): string {\n if (rt === null || rt.state === 'skipped' || rt.node === undefined || rt.entry === undefined)\n return 'tenjin';\n const launcher = rt.launcher;\n const verifiedLauncher = launcher?.state === 'written' || launcher?.state === 'current';\n const path = verifiedLauncher\n ? launcher.paths.find((p) => platform !== 'win32' || p.endsWith('.cmd'))\n : undefined;\n const parts = path === undefined ? [rt.node, rt.entry] : [path];\n return platform === 'win32'\n ? `& ${parts.map((part) => `'${part.replaceAll(\"'\", \"''\")}'`).join(' ')}`\n : parts.map(shQuote).join(' ');\n}\n\nexport function requireRuntime(rt: RuntimeSetup | null): void {\n if (rt === null || rt.state === 'skipped') return;\n if (\n rt.state === 'failed' ||\n (rt.state === 'kept' && rt.reason !== undefined && rt.newer !== true)\n ) {\n throw new CliError(\n 'UPDATE_FAILED',\n `Tenjin could not finish installation: ${rt.reason ?? 'runtime setup failed'}. Your existing plugin registration was kept.`,\n {\n fix:\n rt.fix ??\n (rt.unpinned\n ? 'Use macOS, Windows or glibc Linux 2.28+ on x64/arm64.'\n : 'Check your connection and run tenjin install again.'),\n },\n );\n }\n}\n\n/** A verified runtime launch, or the explicit source-checkout development path. */\nfunction runtimeLaunch(\n rt: RuntimeSetup | null,\n): { version: string; hostsDir: string; cliEntry: string; node: string } | null {\n if (rt === null || (rt.state !== 'active' && rt.state !== 'current' && rt.state !== 'kept')) {\n return null;\n }\n if (\n rt.cli === undefined ||\n rt.hostsDir === undefined ||\n rt.entry === undefined ||\n rt.node === undefined\n ) {\n return null;\n }\n return { version: rt.cli, hostsDir: rt.hostsDir, cliEntry: rt.entry, node: rt.node };\n}\n\nexport function runtimeData(rt: RuntimeSetup | null): Record<string, unknown> | null {\n if (rt === null) return null;\n return {\n state: rt.state,\n root: rt.root,\n ...(rt.cli !== undefined ? { cli: rt.cli } : {}),\n ...(rt.nodeVersion !== undefined ? { nodeVersion: rt.nodeVersion } : {}),\n ...(rt.reason !== undefined ? { reason: rt.reason } : {}),\n ...(rt.fix !== undefined ? { fix: rt.fix } : {}),\n };\n}\n\n/**\n * Adds to `install.routerProjects` every project install Claude Code records\n * that is still on disk and not yet there. An unreadable record adds nothing.\n */\nasync function recordClaudeProjects(\n dataDir: string,\n known: readonly string[],\n env: NodeJS.ProcessEnv,\n home: string,\n): Promise<void> {\n const records = await recordedInstalls(env, home).catch(() => null);\n if (records === null || records.every((r) => r.projectPath === null)) return;\n const seen = new Set([...known, ...(await Promise.all(known.map(realOr)))]);\n for (const { projectPath } of records) {\n if (projectPath === null || seen.has(projectPath)) continue;\n if ((await stat(projectPath).catch(() => null))?.isDirectory() !== true) continue;\n seen.add(projectPath);\n await persistRouterProject(dataDir, projectPath).catch(() => undefined);\n }\n}\n\n/** The first activation's line, said once: where Tenjin runs from now. */\nfunction runtimeSentence(rt: RuntimeSetup, home: string): string | null {\n if (rt.state !== 'active' || !rt.firstTime) return null;\n return `Runs from ${tilde(rt.root, home)} on its own Node ${rt.nodeVersion ?? ''}, so a Node upgrade or \\`npm rm -g tenjin-cli\\` no longer stops it.`;\n}\n\n/**\n * What the person needs to know about the `tenjin` launcher: only a file in\n * its place that is not Tenjin's, a write that failed, or a launcher folder\n * off PATH. npm's own link there (npm prefix `~/.local`) says nothing.\n */\nfunction launcherSentence(launcher: LauncherResult | null, home: string): string | null {\n if (launcher === null) return null;\n if (launcher.state === 'foreign') {\n const who = launcher.reason?.replace(/ is not Tenjin's$/, '') ?? launcher.paths[0] ?? '';\n return `${who} is not Tenjin's, so it was left as it is, and \\`tenjin\\` there runs that file instead of Tenjin's runtime. Move it aside and run \\`tenjin install\\` again to put Tenjin's there.`;\n }\n if (launcher.state === 'failed') {\n const dir = launcher.paths[0] !== undefined ? tilde(dirname(launcher.paths[0]), home) : '';\n return `Tenjin's \\`tenjin\\` launcher could not be written to ${dir} (${launcher.reason ?? 'unknown reason'}), so a terminal finds \\`tenjin\\` only through npm's copy; run \\`tenjin install\\` again to retry.`;\n }\n if ((launcher.state === 'written' || launcher.state === 'current') && !launcher.onPath) {\n return `~/.local/bin is not on your PATH, so a terminal will not find \\`tenjin\\` once npm's copy is gone (inside Claude Code the plugin's own \\`tenjin\\` is on the Bash tool's PATH). Add it: ${launcher.pathLine ?? ''}`;\n }\n return null;\n}\n\n/** The runtime's lines under install's summary: where it runs from, or what needs the person. */\nexport function runtimeLines(\n ctx: CommandContext,\n rt: RuntimeSetup | null,\n home: string,\n concise = false,\n): string[] {\n if (rt === null || sharedResults.has(rt)) return [];\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const runs = runtimeSentence(rt, home);\n const launcher = launcherSentence(rt.launcher, home);\n return [\n ...(!concise && runs !== null ? [` ${runs}`] : []),\n ...(launcher !== null ? [warn(launcher)] : []),\n ];\n}\n\nfunction claudeCodeData(claude: ClaudeCodeState): Record<string, unknown> {\n return {\n binary: claude.binary?.path ?? null,\n source: claude.binary?.source ?? null,\n version: claude.version,\n meetsFloor: claude.meetsFloor,\n ...(claude.fix !== undefined ? { fix: claude.fix } : {}),\n };\n}\n\n/**\n * The fix for a registration that did not happen, worded as a step the agent\n * can take in the session: never a command for the person to run elsewhere.\n */\nfunction registrationFix(plugin: PluginRegistration): string {\n // A project install is retried, and checked, as one.\n const flag = plugin.scope === 'local' ? ' --project' : '';\n if (plugin.id !== null && plugin.method === 'none') {\n return `${plugin.id} keeps serving this machine at the version Claude Code has; run \\`tenjin install${flag}\\` again to retry.`;\n }\n if (\n plugin.path !== undefined &&\n plugin.reason?.includes('not a folder this CLI wrote') === true\n ) {\n return `Move ${plugin.path} aside, then run \\`tenjin install${flag}\\` again.`;\n }\n return `Run \\`tenjin doctor${flag}\\` to see the cause, then run \\`tenjin install${flag}\\` again.`;\n}\n\n/** The unlock reasons `tenjin wallet repair` fixes: a saved passphrase that is gone or wrong. */\nconst REPAIRABLE: ReadonlySet<string> = new Set([\n 'passphrase_missing',\n 'passphrase_wrong',\n 'env_passphrase_wrong',\n]);\n\n/**\n * The repair step, worded for whoever reads install's output: a person at a\n * terminal runs it; an agent (no TTY) asks the person to, and never asks for\n * the passphrase.\n */\nfunction repairStep(tty: boolean): string {\n return tty\n ? `run \\`tenjin wallet repair\\` yourself ${REPAIR_CLAUSE}`\n : 'ask the person to run `tenjin wallet repair` in their own terminal (never ask for the passphrase)';\n}\n\n/**\n * The one step after the install, for the agent to relay in the session. A\n * wallet whose saved passphrase is gone or wrong is repaired first; otherwise\n * the usual steps include funding instructions for an empty usable wallet.\n */\nfunction nextStep(\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n wallet: WalletOutcome,\n migration: Migration,\n pendingSteps: number,\n tty: boolean,\n command: string,\n env: NodeJS.ProcessEnv,\n): string {\n if (plugin.state === 'failed') return registrationFix(plugin);\n const steps = todaysSteps(plugin, claude, wallet, migration, pendingSteps, command, env);\n const signing = wallet.signing;\n if (signing?.status === 'blocked' && REPAIRABLE.has(signing.reason)) {\n steps.unshift(repairStep(tty));\n }\n return steps.join(', then ');\n}\n\nfunction todaysSteps(\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n wallet: WalletOutcome,\n migration: Migration,\n pendingSteps: number,\n command: string,\n env: NodeJS.ProcessEnv,\n): string[] {\n const steps: string[] = [];\n if (pendingSteps > 0) steps.push('follow the instructions in nextSteps');\n if (plugin.state === 'deferred') {\n steps.unshift('run `claude update`');\n steps.push(\n `run \\`${command} install\\` again; until then the earlier Tenjin setup stays as it is`,\n );\n return steps;\n }\n if (!claude.meetsFloor) steps.unshift('run `claude update`');\n steps.push(loadStep(settingsInstallStays(migration) || !claude.meetsFloor, env, command));\n return steps;\n}\n\n/** Is a settings install still on this machine after this run? */\nfunction settingsInstallStays(migration: Migration): boolean {\n return migration.state === 'pending' || migration.state === 'blocked';\n}\n\nfunction deferredRegistration(scope: PluginScope, claude: ClaudeCodeState): PluginRegistration {\n return {\n method: 'none',\n id: null,\n scope,\n state: 'deferred',\n version: pkg.version,\n steps: [],\n reason: `Claude Code ${claude.version ?? ''} is older than ${CLAUDE_CODE_FLOOR}, which the plugin needs, so it was not registered and the earlier settings setup stays as it is`,\n };\n}\n\n/** The status line a migration took out, in words, or nothing. */\nfunction statusLineNotice(migration: Migration): string | null {\n const status = migration.removed?.statusLine;\n if (status === 'removed') {\n return 'Removed the Tenjin status line (`tenjin status-line`) with the earlier settings setup; the plugin sets none. To keep it, set `tenjin status-line` as your Claude Code status line command.';\n }\n if (status === 'restored') {\n return 'Took the Tenjin footer out of your status line and put your own command back; the plugin sets none.';\n }\n return null;\n}\n\n/**\n * WHAT `tenjin update` PRINTS FROM THIS REFRESH. Update captures this run's\n * output and shows only its failures, so anything a person must know about a\n * refresh that succeeded rides here, as sentences the parent prints verbatim.\n */\nfunction refreshNotices(\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n migration: Migration,\n rt: RuntimeSetup | null,\n home: string,\n): string[] {\n const out: string[] = [];\n if (plugin.state === 'deferred') {\n out.push(\n `Claude Code ${claude.version ?? ''} is older than ${CLAUDE_CODE_FLOOR}, so the Tenjin plugin was not registered and the earlier settings setup stays as it is. Run \\`claude update\\`, then \\`tenjin install\\`.`,\n );\n } else if (plugin.state !== 'failed' && settingsInstallStays(migration)) {\n out.push(\n 'Start a new Claude Code session so the Tenjin plugin loads; the earlier settings setup is removed by the next `tenjin update` or `tenjin install` after that.',\n );\n }\n const status = statusLineNotice(migration);\n if (status !== null) out.push(status);\n if (rt !== null) out.push(...runtimeNotices(rt, home));\n return out;\n}\n\n/** The runtime's sentences among a refresh's notices: where it runs from, and what needs the person. */\nfunction runtimeNotices(rt: RuntimeSetup, home: string): string[] {\n const out: string[] = [];\n const runs = runtimeSentence(rt, home);\n if (runs !== null) out.push(`Tenjin ${runs.charAt(0).toLowerCase()}${runs.slice(1)}`);\n const launcher = launcherSentence(rt.launcher, home);\n if (launcher !== null) out.push(launcher);\n return out;\n}\n\n/** The one rule for every step the agent relays from install. */\nexport const SHOW_NOT_RUN =\n '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.';\n\n/**\n * An agent runs install with `--json` or in a shell with no terminal, so the\n * CLI cannot ask. The agent can: this is what the selector would have shown\n * (the defaults, the routing fee) and what to run for each answer, the same\n * shape as the `request` tool's `needs_input` step. A script or CI ignores\n * it, and the defaults hold.\n */\nfunction spendStep(args: RouterInstallArgs, command: string): QuestionStep {\n return spendStepFor(installCommand(args, command));\n}\n\n/** The same question, for an install an agent runs again as `command`. */\nexport function spendStepFor(command: string): QuestionStep {\n const options = spendOptions(command);\n return {\n id: 'spend',\n question: spendChoiceQuestion(),\n options,\n 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}`,\n };\n}\n\n/** The install this run was: what an agent runs again for the person's answer. */\nfunction installCommand(args: RouterInstallArgs, command: string): string {\n return [\n `${command} install`,\n ...(args.project === true ? ['--project'] : []),\n ...(args.noWallet === true ? ['--no-wallet'] : []),\n ].join(' ');\n}\n\n/** The limits the person named with `--max-auto-spend` and `--session-budget`, refused before any write. */\nexport function namedLimits(\n args: Pick<RouterInstallArgs, 'maxAutoSpend' | 'sessionBudget' | 'refresh'>,\n): {\n limits: Partial<RouterLimits>;\n keys: (keyof RouterLimits)[];\n} {\n const flags = [\n ['maxAutoSpend', '--max-auto-spend', args.maxAutoSpend, 'call'],\n ['sessionBudget', '--session-budget', args.sessionBudget, 'day'],\n ] as const;\n const limits: Partial<RouterLimits> = {};\n const keys: (keyof RouterLimits)[] = [];\n for (const [key, flag, raw, per] of flags) {\n if (raw === undefined) continue;\n if (args.refresh === true) {\n throw new CliError('USAGE', `${flag} sets a spend limit, and --refresh writes none.`, {\n fix: `Run \\`tenjin install ${flag} ${raw}\\` without --refresh.`,\n });\n }\n const parsed = parseLimit(raw, per);\n if ('refusal' in parsed) {\n throw new CliError('USAGE', `${flag} ${raw}: ${parsed.refusal}`, {\n fix:\n per === 'day'\n ? `Give a positive USD amount or none, for example \\`${flag} 5\\`.`\n : `Give a non-negative USD amount with up to 6 decimal places, for example \\`${flag} 0.1\\`. Zero blocks positive automatic payments.`,\n });\n }\n limits[key] = parsed.value;\n keys.push(key);\n }\n return { limits, keys };\n}\n\n/** A pending install step, handled according to its next instructions. */\nexport interface QuestionStep {\n id: 'spend' | 'subagents' | 'fund';\n /** Prompt text for the terminal choice or agent explanation; follow `next`. */\n question: string;\n options: {\n id: string;\n label: string;\n recommended: boolean;\n /** What to ask the person after they pick this option, before running `command`. */\n ask?: string[];\n /** The command for this option; `next` says whether the agent asks first. */\n command: string | null;\n }[];\n /** How the agent handles this step. */\n next: string;\n}\n\n/**\n * The one question install asks, before anything is written: the defaults, or\n * your own limits. It is asked only when the file names neither limit. The\n * question names the routing fee and its deposits too, and either answer\n * approves it. Cancelling at any step writes nothing.\n */\nexport async function approveLimits(\n deps: Pick<RouterInstallDeps, 'promptLimits' | 'promptAmount'>,\n): Promise<RouterLimits> {\n const choice = await (deps.promptLimits ?? promptLimits)(\n `${SPEND_QUESTION}\\n${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`,\n );\n if (choice === null) throw installCancelled();\n if (choice === 'approve') return { ...ROUTER_DEFAULTS };\n const ask = deps.promptAmount ?? promptAmount;\n const sessionBudget = await askLimit(\n ask,\n 'Daily budget shared across chats, in USD, or none',\n '5',\n 'day',\n );\n const maxAutoSpend = await askLimit(\n ask,\n 'Most it may pay for one call, in USD; 0 blocks positive automatic payments',\n toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd,\n 'call',\n );\n return { maxAutoSpend, sessionBudget };\n}\n\n/** Asks until the answer is a valid amount (or `none` for the daily limit). */\nasync function askLimit(\n ask: NonNullable<RouterInstallDeps['promptAmount']>,\n question: string,\n placeholder: string,\n per: 'call' | 'day',\n): Promise<string> {\n let message = question;\n for (;;) {\n const answer = await ask(message, placeholder);\n if (answer === null) throw installCancelled();\n const parsed = parseLimit(answer, per);\n if (!('refusal' in parsed)) return parsed.value;\n message = `${parsed.refusal} ${question}`;\n }\n}\n\n/** A daily limit is positive or `none`; the per-call limit is non-negative. */\nfunction parseLimit(answer: string, per: 'call' | 'day'): { value: string } | { refusal: string } {\n const trimmed = answer.trim();\n if (per === 'day' && trimmed === 'none') return { value: 'none' };\n let atomic: string;\n try {\n atomic = parseUsdToAtomic(trimmed);\n } catch (err) {\n if (err instanceof CliError) return { refusal: `${err.message}.` };\n throw err;\n }\n if (per === 'day' && atomic === '0') {\n return {\n refusal:\n 'The limit must be more than zero; `tenjin config set router.enabled false` turns the router off.',\n };\n }\n return { value: atomic };\n}\n\nfunction installCancelled(): CliError {\n return new CliError('REFUSED', 'Install cancelled before anything was written.', {\n fix: 'Re-run `tenjin install` and choose the defaults or your own limits.',\n });\n}\n\nfunction promptLimits(message: string): Promise<LimitsChoice | null> {\n return selectOne<LimitsChoice>({\n message,\n choices: [\n { value: 'approve', label: `${DEFAULTS_LABEL} (recommended)` },\n { value: 'own', label: 'Set my own limits' },\n ],\n initialValue: 'approve',\n });\n}\n\nfunction promptAmount(message: string, placeholder: string): Promise<string | null> {\n return askText({ message, placeholder });\n}\n\nexport interface EffectiveLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\nexport function effectiveLimits(policy: SpendPolicy): EffectiveLimits {\n return {\n maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,\n sessionBudget:\n policy.sessionBudgetAtomic === null\n ? 'no daily budget limit'\n : toMoney(policy.sessionBudgetAtomic.toString()).usd,\n };\n}\n\n/**\n * The wallet line, and who reads it. At a TTY a person ran install, so the\n * person's wording; without one an agent did, and relays it, so a blocked\n * wallet's fix and the passphrase line take the agent's wording: ask the\n * person, never ask for the passphrase.\n *\n * A ready wallet needs no first-use diagnostic. A wallet that only this\n * shell can unlock, a blocked signer or an unknown check retains its warning.\n */\nexport function walletLines(ctx: CommandContext, w: WalletOutcome, host = 'Claude Code'): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', text);\n if (w.status === 'created' || w.status === 'existing') {\n const a = w.address ?? '';\n const signing = w.signing;\n const tty = ctx.io.isTTY;\n if (signing?.status === 'blocked') {\n const wallet = Object.prototype.hasOwnProperty.call(WALLET_REASONS, signing.reason)\n ? WALLET_REASONS[signing.reason as keyof typeof WALLET_REASONS]\n : undefined;\n return [\n warn(`! Wallet ${a} cannot be unlocked by ${host}: ${signing.detail}.`),\n ` ${tty ? (wallet?.fix ?? signing.fix) : agentFixFor(signing.reason, signing.fix)}`,\n ];\n }\n if (signing?.status === 'unknown') {\n return [\n warn(`! Wallet: ${a}; could not check that it unlocks (${signing.detail}).`),\n ' Run `tenjin doctor` to check it again.',\n ];\n }\n if (w.shellOnly === 'key') {\n return [\n warn(\n `! Wallet: ${a} signs here only through TENJIN_WALLET_KEY in this shell; ${host} must have the same variable.`,\n ),\n ];\n }\n if (w.shellOnly === 'passphrase') {\n return [\n warn(\n tty\n ? `! Wallet: ${a} unlocks here only through TENJIN_WALLET_PASSPHRASE in this shell; ${host} must have the same variable, or run \\`tenjin wallet repair\\` yourself to store the passphrase ${REPAIR_CLAUSE}.`\n : `! Wallet: ${a} unlocks here only through TENJIN_WALLET_PASSPHRASE in this shell; ${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.`,\n ),\n ];\n }\n return [];\n }\n if (w.reason === 'flag') return [' No wallet yet. Create one with: tenjin wallet create'];\n return [\n paint(ctx.io, 'yellow', `! No wallet was created. ${w.warning ?? ''}`.trimEnd()),\n ` ${w.fix ?? 'Create one with: tenjin wallet create'}`,\n ];\n}\n\n/** The plugin line: what Claude Code will list, or why nothing is registered. */\nfunction pluginLines(ctx: CommandContext, plugin: PluginRegistration): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (plugin.state === 'deferred') return [warn(`${plugin.reason ?? ''}`)];\n if (plugin.state === 'failed') {\n return [warn(`The Tenjin plugin was not registered: ${plugin.reason ?? 'unknown reason'}`)];\n }\n return [];\n}\n\n/** The settings install's line, when there is one. */\nfunction migrationLines(ctx: CommandContext, migration: Migration): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (migration.state === 'pending') {\n return [\n ` The settings install in ${migration.settingsPath} stays until the plugin has loaded (${migration.reason ?? ''}); \\`tenjin update\\` or \\`tenjin install\\` removes it then.`,\n ];\n }\n if (migration.state === 'blocked') {\n return [warn(`${migration.settingsPath} could not be read: ${migration.reason ?? ''}`)];\n }\n if (migration.state === 'done') {\n const removed = migration.removed;\n const status = statusLineNotice(migration);\n return [\n ` Removed the earlier settings setup from ${migration.settingsPath}: the plugin carries its hooks, permissions and server`,\n ...(status !== null ? [` ${status}`] : []),\n ...(removed?.warnings ?? []).map((w) => warn(w)),\n ];\n }\n return [];\n}\n\nfunction claudeLines(ctx: CommandContext, claude: ClaudeCodeState): string[] {\n if (claude.meetsFloor) return [];\n return [\n paint(\n ctx.io,\n 'yellow',\n `! Claude Code ${claude.version ?? ''} is older than the plugin needs. ${claude.fix ?? ''}`.trim(),\n ),\n ];\n}\n\n/**\n * The first-use receipt: installed state, disclosure, limits and activation.\n * Successful storage/runtime details stay in diagnostics; failures and a\n * launcher action remain visible.\n */\nfunction lines(\n ctx: CommandContext,\n s: {\n plugin: PluginRegistration;\n claude: ClaudeCodeState;\n migration: Migration;\n wallet: WalletOutcome;\n fundingWarning?: string;\n /** How many pending steps the agent is handed. */\n asks: number;\n policy: SpendPolicy;\n spendAsk?: QuestionStep;\n router: RouterCheck;\n rt: RuntimeSetup | null;\n home: string;\n env: NodeJS.ProcessEnv;\n },\n): string[] {\n const ok = paint(ctx.io, 'green', '✓');\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const spend =\n s.spendAsk !== undefined\n ? [\n ` Ask the person in this session: ${s.spendAsk.question}`,\n ...s.spendAsk.options.map(\n (o) => ` ${o.label}${o.recommended ? ' (recommended)' : ''}: ${o.command}`,\n ),\n ]\n : [];\n const installed = s.plugin.state !== 'failed' && s.plugin.state !== 'deferred';\n // A warning is the router answering with a 402 this CLI does not pay.\n const router =\n s.router.status === 'ok'\n ? []\n : [\n warn(\n s.router.status === 'warn'\n ? s.router.detail\n : `The router did not answer: ${s.router.detail}`,\n ),\n ...(s.router.fix !== undefined ? [` ${s.router.fix}`] : []),\n ];\n return [\n s.plugin.state === 'failed'\n ? warn('Tenjin could not finish setting up Claude Code')\n : s.plugin.state === 'deferred'\n ? warn('Tenjin keeps its earlier Claude Code setup until Claude Code is updated')\n : `${ok} Tenjin is set up for Claude Code (plugin ${s.plugin.id ?? PLUGIN_ID})`,\n ...(installed ? CAPABILITY_LINES.map((line) => ` ${line}`) : []),\n ...(s.plugin.scope === 'local' && s.plugin.state !== 'failed'\n ? [` For this project only; check it with: ${continuationCommand(s.rt)} doctor --project`]\n : []),\n ...spend,\n ...runtimeLines(ctx, s.rt, s.home, true),\n ...walletLines(ctx, s.wallet),\n ...(s.fundingWarning !== undefined ? [warn(s.fundingWarning)] : []),\n ...pluginLines(ctx, s.plugin),\n ...claudeLines(ctx, s.claude),\n ...migrationLines(ctx, s.migration),\n ...router,\n ];\n}\n\n/** \"Up to date\" only when nothing below it needs the user. */\nfunction refreshLines(\n ctx: CommandContext,\n plugin: PluginRegistration,\n claude: ClaudeCodeState,\n migration: Migration,\n rt: RuntimeSetup | null,\n home: string,\n): string[] {\n const issues = [\n ...runtimeLines(ctx, rt, home),\n ...pluginLines(ctx, plugin),\n ...claudeLines(ctx, claude),\n ...migrationLines(ctx, migration),\n ];\n const head =\n plugin.state === 'failed'\n ? paint(ctx.io, 'yellow', '! Tenjin is updated, but its plugin was not registered')\n : plugin.state === 'deferred'\n ? paint(ctx.io, 'yellow', '! Tenjin is updated; its plugin waits for a newer Claude Code')\n : `${paint(ctx.io, 'green', '✓')} Tenjin is up to date (plugin ${plugin.id ?? PLUGIN_ID})`;\n return [head, ...issues];\n}\n","import { lstatSync } from 'node:fs';\nimport { constants, open, readdir, rm, rmdir } from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { hasCode } from './errno';\n\n/**\n * What a refresh takes back from each harness's skills directory: the retired\n * `tenjin-pay`, and the shelf's CLI skills, whose `tenjin search` and\n * `tenjin publish` commands the router CLI does not ship.\n */\nconst RETIRED_SKILL_NAMES = ['tenjin-pay', 'tenjin-search', 'tenjin-publish'] as const;\n\n/**\n * Every file each retired skill shipped, as a path relative to the skill\n * directory. DECLARED rather than discovered, because the packaged source is\n * gone, and \"remove exactly the files an earlier install wrote\" is not a\n * question a refresh can answer by listing the operator's directory:\n * everything else in there is theirs.\n */\nconst SHIPPED_SKILL_FILES: Readonly<Record<string, readonly string[]>> = {\n 'tenjin-pay': ['SKILL.md'],\n 'tenjin-search': ['SKILL.md', 'references/permissions.md'],\n 'tenjin-publish': ['SKILL.md', 'references/maintain.md'],\n};\n\n/** Every skills directory a harness on this machine reads. */\nfunction skillsDirsFor(home: string): string[] {\n return [join(home, '.claude', 'skills'), join(home, '.agents', 'skills')];\n}\n\nfunction isRealDirectory(path: string): boolean {\n try {\n return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n } catch (err) {\n // Linux reports ENOTDIR when an ancestor is a regular file. Nothing can\n // be installed below it, just as with an absent path. Do not follow symlinks.\n if (hasCode(err, 'ENOENT') || hasCode(err, 'ENOTDIR')) return false;\n throw err;\n }\n}\n\n/**\n * What reading a SKILL.md found. A skill path is operator-controlled, so it is not\n * necessarily a file at all.\n */\ntype SkillFileRead =\n | { kind: 'ok'; bytes: Buffer }\n | { kind: 'absent' }\n | { kind: 'not-regular' }\n | { kind: 'unreadable'; err: unknown };\n\n/**\n * Read a SKILL.md through ONE descriptor, and only when it is a regular file.\n *\n * `readFile` on a FIFO blocks until a writer appears, and on a character device it\n * streams without end; neither call fails, so no error handling reaches them. A\n * pipe at a wired SKILL.md path hung `tenjin install` past SIGTERM. Opening\n * non-blocking returns immediately whatever the node type is, `fstat` on that\n * descriptor says what it actually is, and only a regular file is read. Checking\n * the pathname and then reading the pathname would let the two answer about\n * different files.\n *\n * O_NONBLOCK does not exist on Windows, where it degrades to 0; FIFOs are not a\n * meaningful case there.\n */\nasync function readSkillFile(path: string): Promise<SkillFileRead> {\n let handle: FileHandle;\n try {\n handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', err };\n }\n try {\n if (!(await handle.stat()).isFile()) return { kind: 'not-regular' };\n return { kind: 'ok', bytes: await handle.readFile() };\n } catch (err) {\n return { kind: 'unreadable', err };\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\n/**\n * The `name:` a SKILL.md declares in its leading frontmatter, or null when it\n * declares none. It is what a harness registers the skill AS, so it is also the\n * cheapest evidence that a file at one of our paths is one of ours. Deliberately\n * not a general YAML parse: only the leading `---` block is read.\n */\nfunction skillFrontmatterName(skillMd: string): string | null {\n // Tolerate a UTF-8 BOM, CRLF, and leading blank lines before the opening fence.\n const lines = skillMd.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const start = lines.findIndex((l) => l.trim().length > 0);\n if (start === -1 || lines[start]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > start && l.trim() === '---');\n if (end === -1) return null;\n for (const line of lines.slice(start + 1, end)) {\n const m = /^name:\\s*(.+?)\\s*$/.exec(line);\n if (m !== null) return (m[1] ?? '').replace(/^[\"']|[\"']$/g, '');\n }\n return null;\n}\n\n/**\n * Remove only the files our named skill shipped (SKILL.md last, as the ownership\n * proof), then any directory they leave empty; preserve foreign skills and\n * adjacent user files.\n */\nexport async function removeOwnedSkill(\n name: string,\n skillsDir: string,\n): Promise<{ changed: boolean }> {\n if (!isRealDirectory(skillsDir)) {\n return { changed: false };\n }\n const skillDir = join(skillsDir, name);\n if (!isRealDirectory(skillDir)) {\n return { changed: false };\n }\n const path = join(skillDir, 'SKILL.md');\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return { changed: false };\n if (read.kind !== 'ok' || skillFrontmatterName(read.bytes.toString('utf8')) !== name) {\n return { changed: false }; // not ours to delete for sitting at our path\n }\n const shipped = SHIPPED_SKILL_FILES[name] ?? [];\n const subdirs = new Set<string>();\n for (const rel of shipped) {\n if (rel === 'SKILL.md') continue;\n const file = join(skillDir, rel);\n // A symlinked `references/` would route the delete outside the skill.\n if (!isRealDirectory(dirname(file))) continue;\n subdirs.add(dirname(file));\n if (lstatSync(file, { throwIfNoEntry: false })?.isFile() === true) await rm(file);\n }\n await rm(path, { force: true });\n for (const dir of [...subdirs, skillDir].sort((a, b) => b.length - a.length)) {\n const rest = await readdir(dir).catch(() => null);\n if (rest !== null && rest.length === 0) await rmdir(dir).catch(() => undefined);\n }\n return { changed: true };\n}\n\n/**\n * Refresh retires obsolete skills without needing their old packaged source:\n * see {@link RETIRED_SKILL_NAMES}.\n */\nexport async function removeRetiredSkills(home: string, project?: string): Promise<string[]> {\n const removed: string[] = [];\n const dirs = [...skillsDirsFor(home), ...(project ? skillsDirsFor(project) : [])];\n for (const dir of new Set(dirs)) {\n for (const name of RETIRED_SKILL_NAMES) {\n if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));\n }\n }\n return removed;\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { userMcpFile, userSettingsPath } from './claude-cli';\nimport { inspectLegacyInstall, projectMcpFile } from './legacy-install';\nimport { PLUGIN_ID } from './names';\nimport { folderState, installedThroughCommands, type PluginScope } from './plugin-registration';\n\n/**\n * Is Tenjin installed for Claude Code here? Read from disk, with no `claude`\n * binary asked. Install, uninstall, doctor and the host record each count\n * different signs of an install, so each caller names the ones it counts.\n */\n\n/**\n * What shows an install of ours, read in this order and only when named. A\n * file that cannot be read shows nothing.\n *\n * - `record`: Claude Code's own `plugins/installed_plugins.json` lists\n * `tenjin@tenjin`, in any scope.\n * - `enabled`: the project's `.claude/settings.local.json` enables it (a\n * project only).\n * - `folder`: the plugin folder of ours for the scope.\n * - `settings`: anything the settings install of an earlier release left in\n * the scope: its hook entries, rules, status line or `x402` server.\n * - `settings-hooks`: only that settings install's hook entries.\n *\n * SHIM: the two settings signs go with `legacy-install.ts`, on or after 2026-12-01.\n */\nexport type InstallSign = 'record' | 'enabled' | 'folder' | 'settings' | 'settings-hooks';\n\n/** Where a settings install of this scope kept its entries and its server. */\nexport interface SettingsInstallPaths {\n settingsPath: string;\n mcpFile: string;\n mcpScope: 'user' | 'project';\n}\n\nexport function settingsInstallPaths(\n project: boolean,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): SettingsInstallPaths {\n return project\n ? {\n settingsPath: join(cwd, '.claude', 'settings.json'),\n mcpFile: projectMcpFile(cwd),\n mcpScope: 'project',\n }\n : {\n settingsPath: userSettingsPath(env, home),\n mcpFile: userMcpFile(env, home),\n mcpScope: 'user',\n };\n}\n\n/** Does any of `signs` show an install of ours at `scope` (for a project, the one in `cwd`)? */\nexport async function claudeInstallAt(\n scope: PluginScope,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n signs: readonly InstallSign[],\n): Promise<boolean> {\n const counts = (sign: InstallSign): boolean => signs.includes(sign);\n if (counts('record') && (await installedThroughCommands(env, home))) return true;\n if (counts('enabled') && scope === 'local' && (await enabledIn(cwd))) return true;\n if (counts('folder') && (await folderState(scope, env, home, cwd)).state === 'ours') return true;\n if (!counts('settings') && !counts('settings-hooks')) return false;\n const paths = settingsInstallPaths(scope === 'local', env, home, cwd);\n const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);\n return counts('settings') ? legacy.present : legacy.events.length > 0;\n}\n\n/** `tenjin@tenjin` enabled in the project's own `.claude/settings.local.json`. */\nasync function enabledIn(dir: string): Promise<boolean> {\n const local = await readFile(join(dir, '.claude', 'settings.local.json'), 'utf8')\n .then((raw) => JSON.parse(raw) as { enabledPlugins?: Record<string, unknown> })\n .catch(() => null);\n return local?.enabledPlugins?.[PLUGIN_ID] === true;\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { inspectHooksFile } from './hooks-file';\nimport { runClaude, type ClaudeBinary } from './claude-cli';\nimport { LEGACY_HOOK_TOOL, LEGACY_MCP_SERVER_NAME, LEGACY_REQUEST_TOOL } from './names';\nimport { classifyStatusLine, decomposeCommand, type StatusLineState } from './status-line-wiring';\nimport { isRecord } from '../lib/guards';\n\n/**\n * The settings-based install, read and removed. Older releases wrote seven\n * hook entries, an allow and a deny rule and a status line into settings.json,\n * and registered an `x402` MCP server with `claude mcp add`. The plugin\n * replaces all of it. `install` and `update` remove it only once the plugin has\n * proven to load on this machine, `uninstall` removes it outright, and doctor\n * only reads it.\n *\n * Exact shapes only. A hook handler is Tenjin's when it is an `mcp_tool` call\n * to the `x402` server's `hook` tool, or a command that is exactly\n * `tenjin hook <leg>` (optionally with a path). Any other command that merely\n * contains `tenjin hook` is the user's, kept and reported. Removal is handler\n * by handler, so a group holding a foreign handler beside ours keeps it. The\n * rules are touched only when the `x402` server is Tenjin's or gone, and a\n * status line only in a file that still held Tenjin's hooks, and only in the\n * exact shapes Tenjin wrote. A file is written only when something was removed\n * from it, and no key is ever added to it.\n *\n * SHIM: this module goes on or after 2026-12-01, the first release cut 30 or\n * more days after the plugin PR 2 ships, and doctor keeps naming an\n * unmigrated machine after that.\n */\n\nconst LEGACY_COMMAND_RE = /^(\\S*\\/)?tenjin hook [a-z]+$/;\n\n/** One handler, in an exact shape a settings install wrote. */\nexport function ownsLegacyHandler(handler: unknown): boolean {\n if (!isRecord(handler)) return false;\n if (handler.type === 'mcp_tool') {\n return handler.server === LEGACY_MCP_SERVER_NAME && handler.tool === 'hook';\n }\n const command = handler.command;\n return typeof command === 'string' && LEGACY_COMMAND_RE.test(command.trim());\n}\n\n/** A handler that mentions `tenjin hook` without being one of ours: reported, never removed. */\nfunction lookalike(handler: unknown): string | null {\n if (!isRecord(handler) || ownsLegacyHandler(handler)) return null;\n const command = handler.command;\n return typeof command === 'string' && command.includes('tenjin hook') ? command : null;\n}\n\nexport type McpEntryState = 'ok' | 'absent' | 'wrong-command' | 'unreadable';\n\n/**\n * What an entry named `x402` actually launches. The name proves nothing: a\n * stale entry pointing at another binary would read as a working request tool.\n */\nexport function classifyMcpEntry(entry: unknown): McpEntryState {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return 'absent';\n const { command, args } = entry as { command?: unknown; args?: unknown };\n if (typeof command !== 'string' || command.length === 0) return 'wrong-command';\n // The basename, so `/opt/homebrew/bin/tenjin` and a bare `tenjin` both pass.\n const binary = command.split(/[\\\\/]/).pop();\n const runsRouter =\n binary === 'tenjin' && Array.isArray(args) && args.length === 1 && args[0] === 'mcp';\n return runsRouter ? 'ok' : 'wrong-command';\n}\n\n/**\n * The `x402` entry in one registration file: `~/.claude.json` (or the one in\n * `CLAUDE_CONFIG_DIR`) for user scope, `<project>/.mcp.json` for project scope.\n * Only \"it is not there\" is an absence: a file that exists and cannot be read\n * or parsed says nothing about what is registered in it.\n */\nexport async function readLegacyMcpEntry(path: string): Promise<McpEntryState> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n return code === 'ENOENT' || code === 'ENOTDIR' ? 'absent' : 'unreadable';\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return 'unreadable';\n }\n const servers = (parsed as { mcpServers?: unknown } | null)?.mcpServers;\n if (servers === undefined) return 'absent';\n if (!isRecord(servers)) return 'unreadable';\n const entry = servers[LEGACY_MCP_SERVER_NAME];\n return entry === undefined ? 'absent' : classifyMcpEntry(entry);\n}\n\nexport interface LegacyInstall {\n settingsPath: string;\n /** The registration file the `x402` entry would be in. */\n mcpFile: string;\n /** Anything of the settings install left on this machine. */\n present: boolean;\n /** The events holding a handler of ours. */\n events: string[];\n allowRule: boolean;\n denyRule: boolean;\n statusLine: StatusLineState;\n mcp: McpEntryState;\n /** Commands that mention `tenjin hook` but are not ours, left in place. */\n lookalikes: string[];\n /** Set when the settings file could not be read; nothing is then known or removed. */\n unreadable?: string;\n}\n\n/** What the settings install left in one scope. Reads only. */\nexport async function inspectLegacyInstall(\n settingsPath: string,\n mcpFile: string,\n): Promise<LegacyInstall> {\n const mcp = await readLegacyMcpEntry(mcpFile);\n const base = {\n settingsPath,\n mcpFile,\n events: [] as string[],\n allowRule: false,\n denyRule: false,\n statusLine: 'absent' as StatusLineState,\n mcp,\n lookalikes: [] as string[],\n };\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { ...base, present: mcp === 'ok', unreadable: found.refusal.message };\n }\n const events = Object.entries(found.hooks)\n .filter(([, list]) => list.some((entry) => handlersOf(entry).some(ownsLegacyHandler)))\n .map(([event]) => event);\n const lookalikes = Object.values(found.hooks).flatMap((list) =>\n list.flatMap((entry) =>\n handlersOf(entry)\n .map(lookalike)\n .filter((c) => c !== null),\n ),\n );\n const rulesOurs = mcp === 'ok' || (mcp === 'absent' && events.length > 0);\n const allowRule = rulesOurs && listOf(found.settings, 'allow').includes(LEGACY_REQUEST_TOOL);\n const denyRule = rulesOurs && listOf(found.settings, 'deny').includes(LEGACY_HOOK_TOOL);\n const statusLine = events.length > 0 ? classifyStatusLine(found.settings.statusLine) : 'absent';\n const statusOurs = statusLine === 'ours' || statusLine === 'composed';\n return {\n ...base,\n present: events.length > 0 || allowRule || denyRule || statusOurs || mcp === 'ok',\n events,\n allowRule,\n denyRule,\n statusLine,\n lookalikes,\n };\n}\n\nfunction handlersOf(entry: unknown): unknown[] {\n return isRecord(entry) && Array.isArray(entry.hooks) ? entry.hooks : [];\n}\n\nfunction listOf(settings: Record<string, unknown>, key: 'allow' | 'deny'): unknown[] {\n const permissions = settings.permissions;\n if (!isRecord(permissions)) return [];\n const list = permissions[key];\n return Array.isArray(list) ? list : [];\n}\n\nexport interface LegacyRemoval {\n /** The events a handler of ours was taken out of. */\n events: string[];\n allowRule: boolean;\n denyRule: boolean;\n /** `removed` (ours alone), `restored` (the user's own command put back), or untouched. */\n statusLine: 'removed' | 'restored' | 'kept';\n /** The `x402` registration: removed, not there, or kept with the reason. */\n mcp: 'removed' | 'absent' | 'kept';\n wroteSettings: boolean;\n warnings: string[];\n}\n\nexport interface RemoveLegacyOptions {\n binary: ClaudeBinary | null;\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** The `claude mcp` scope the `x402` entry was registered at. */\n mcpScope: 'user' | 'project';\n}\n\n/** Take out what {@link inspectLegacyInstall} found, under the exact-shape rules above. */\nexport async function removeLegacyInstall(\n found: LegacyInstall,\n opts: RemoveLegacyOptions,\n): Promise<LegacyRemoval> {\n const out: LegacyRemoval = {\n events: [],\n allowRule: false,\n denyRule: false,\n statusLine: 'kept',\n mcp: found.mcp === 'absent' ? 'absent' : 'kept',\n wroteSettings: false,\n warnings: [],\n };\n if (found.unreadable === undefined) await removeFromSettings(found, out);\n else out.warnings.push(found.unreadable);\n if (found.mcp === 'ok') await removeMcpEntry(opts, out);\n else if (found.mcp === 'wrong-command') {\n out.warnings.push(\n `an MCP server named ${LEGACY_MCP_SERVER_NAME} launches something else, so it is not Tenjin's and was left in place`,\n );\n } else if (found.mcp === 'unreadable') {\n out.warnings.push(`${found.mcpFile} could not be read, so nothing was removed from it`);\n }\n return out;\n}\n\nasync function removeFromSettings(found: LegacyInstall, out: LegacyRemoval): Promise<void> {\n const read = await inspectHooksFile(found.settingsPath);\n if ('refusal' in read) {\n out.warnings.push(read.refusal.message);\n return;\n }\n if (read.raw === null) return;\n const next: Record<string, unknown> = { ...read.settings };\n if (isRecord(read.settings.hooks)) {\n const hooks: Record<string, unknown> = {};\n for (const [event, list] of Object.entries(read.hooks)) {\n const kept: unknown[] = [];\n for (const entry of list) {\n const handlers = handlersOf(entry);\n const left = handlers.filter((h) => !ownsLegacyHandler(h));\n if (left.length === handlers.length) kept.push(entry);\n else if (left.length > 0) kept.push({ ...(entry as Record<string, unknown>), hooks: left });\n }\n if (kept.length !== list.length || kept.some((e, i) => e !== list[i])) out.events.push(event);\n // An event WE emptied loses its key; one that was already empty stays.\n if (kept.length > 0 || list.length === 0) hooks[event] = kept;\n }\n next.hooks = hooks;\n }\n if ((found.allowRule || found.denyRule) && isRecord(read.settings.permissions)) {\n const permissions = { ...read.settings.permissions };\n if (found.allowRule && Array.isArray(permissions.allow)) {\n permissions.allow = permissions.allow.filter((r) => r !== LEGACY_REQUEST_TOOL);\n out.allowRule = true;\n }\n if (found.denyRule && Array.isArray(permissions.deny)) {\n permissions.deny = permissions.deny.filter((r) => r !== LEGACY_HOOK_TOOL);\n out.denyRule = true;\n }\n next.permissions = permissions;\n }\n if (found.statusLine === 'ours') {\n delete next.statusLine;\n out.statusLine = 'removed';\n } else if (found.statusLine === 'composed' && isRecord(read.settings.statusLine)) {\n const command = read.settings.statusLine.command;\n const original = typeof command === 'string' ? decomposeCommand(command) : null;\n if (original !== null) {\n next.statusLine = { ...read.settings.statusLine, command: original };\n out.statusLine = 'restored';\n }\n }\n // Only a removal writes: a file holding nothing of ours keeps its bytes,\n // whatever its formatting.\n const removed =\n out.events.length > 0 || out.allowRule || out.denyRule || out.statusLine !== 'kept';\n if (!removed) return;\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n const mode = await stat(read.path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n // Compared again just before the rename: a concurrent edit is refused, not lost.\n if ((await readFile(read.path, 'utf8').catch(() => null)) !== read.raw) {\n out.warnings.push(`${read.path} changed while it was read, so it was left as it is`);\n Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: 'kept' });\n return;\n }\n try {\n await writeFileAtomic(read.path, body, mode);\n out.wroteSettings = true;\n } catch (err) {\n out.warnings.push(err instanceof Error ? err.message : String(err));\n Object.assign(out, { events: [], allowRule: false, denyRule: false, statusLine: 'kept' });\n }\n}\n\n/**\n * THE `x402` REGISTRATION GOES THROUGH CLAUDE'S OWN COMMAND, and only after\n * this CLI's own read of that file found it launching `tenjin mcp`: a server\n * the read did not find is never removed by name, because another tool may\n * own one called `x402`. With no binary it is left and reported; the plugin's\n * server is namespaced and does not collide with it.\n */\nasync function removeMcpEntry(opts: RemoveLegacyOptions, out: LegacyRemoval): Promise<void> {\n if (opts.binary === null) {\n out.warnings.push(\n `the ${LEGACY_MCP_SERVER_NAME} MCP registration stays until a run with the claude binary removes it`,\n );\n return;\n }\n const run = await runClaude(\n opts.binary,\n ['mcp', 'remove', LEGACY_MCP_SERVER_NAME, '-s', opts.mcpScope],\n { env: opts.env, cwd: opts.cwd },\n );\n if (run.code === 0) out.mcp = 'removed';\n else {\n out.warnings.push(\n `claude mcp remove ${LEGACY_MCP_SERVER_NAME} did not succeed: ${(run.stderr || run.stdout).trim().slice(0, 200) || 'no output'}`,\n );\n }\n}\n\n/** The project-scope registration file. */\nexport function projectMcpFile(cwd: string): string {\n return join(cwd, '.mcp.json');\n}\n","import { lstat, readFile, realpath } from 'node:fs/promises';\nimport { isRecord } from '../lib/guards';\n\n/**\n * Claude Code's settings file, read once with every refusal decided here, for\n * the removal of the settings-based install (`legacy-install.ts`), which goes\n * with it on or after 2026-12-01.\n */\n\n/** Why a settings file is left alone. */\nexport type HooksFileRefusalReason =\n 'unresolvable' | 'unreadable' | 'unparsable' | 'unexpected-shape';\n\nexport interface HooksInspection {\n path: string;\n /** The exact bytes read, so a commit can prove nothing changed underneath it. */\n raw: string | null;\n settings: Record<string, unknown>;\n /** Every event's entries, already known to be a list: {@link inspectHooksFile}\n * refuses the file rather than hand a writer a shape it would skip. */\n hooks: Record<string, unknown[]>;\n}\n\n/** Why a settings file cannot be written. */\nexport interface HooksRefusal {\n reason: HooksFileRefusalReason;\n message: string;\n path: string;\n}\n\n/**\n * Resolve and read a settings file. Symlinks are resolved before any write:\n * committing with a rename over a dotfiles-managed link would sever it.\n */\nexport async function inspectHooksFile(\n declaredPath: string,\n): Promise<HooksInspection | { refusal: HooksRefusal }> {\n const entry = await lstat(declaredPath).catch(() => null);\n let path = declaredPath;\n if (entry !== null) {\n try {\n path = await realpath(declaredPath);\n } catch (err) {\n return {\n refusal: {\n reason: 'unresolvable',\n path: declaredPath,\n message: `${declaredPath} could not be resolved (${(err as Error).message}); its \"hooks\" key was left exactly as it is.`,\n },\n };\n }\n }\n\n let settings: Record<string, unknown> = {};\n let raw: string | null = null;\n if (entry !== null) {\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n return {\n refusal: {\n reason: 'unreadable',\n path,\n message: `${path} could not be read (${(err as Error).message}); no hooks were registered.`,\n },\n };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return {\n refusal: {\n reason: 'unparsable',\n path,\n message: `${path} is not valid JSON (${(err as Error).message}); its \"hooks\" key was left exactly as it is.`,\n },\n };\n }\n if (!isRecord(parsed)) {\n return {\n refusal: {\n reason: 'unexpected-shape',\n path,\n message: `${path} is not a JSON object; its \"hooks\" key was left exactly as it is.`,\n },\n };\n }\n settings = parsed;\n }\n\n const hooksValue = settings.hooks;\n if (hooksValue !== undefined && !isRecord(hooksValue)) {\n return {\n refusal: {\n reason: 'unexpected-shape',\n path,\n message: `${path} has a \"hooks\" key that is not an object; its \"hooks\" key was left exactly as it is.`,\n },\n };\n }\n // An event whose value is not a list is refused for the same reason a\n // non-object `hooks` is: a writer would copy it through untouched and\n // silently drop this event's share of the plan while the receipt still\n // counted it. A file we do not understand is left alone and reported.\n const hooks: Record<string, unknown[]> = {};\n for (const [event, list] of Object.entries(hooksValue ?? {})) {\n if (!Array.isArray(list)) {\n return {\n refusal: {\n reason: 'unexpected-shape',\n path,\n message: `${path} has a \"hooks.${event}\" that is not an array of entries; its \"hooks\" key was left exactly as it is.`,\n },\n };\n }\n hooks[event] = list;\n }\n return { path, raw, settings, hooks };\n}\n","/**\n * The `statusLine` key in Claude Code's settings file, as the settings install\n * wrote it. A plugin cannot set it, so this module only recognises a status\n * line an earlier release wrote and takes it back (`legacy-install.ts`).\n *\n * Ownership is one marker, the command naming `tenjin status-line`, so a status\n * line that is not Tenjin's is never touched.\n */\n\n/** The command an earlier `install` registered. */\nexport const STATUS_LINE_COMMAND = 'tenjin status-line';\n/** The marker that makes a status line ours, composed or not. */\nconst OUR_MARKER = STATUS_LINE_COMMAND;\n\n/**\n * What is in the file: ours alone, ours appended to someone else's, someone\n * else's alone, or nothing.\n */\nexport type StatusLineState = 'ours' | 'composed' | 'foreign' | 'absent';\n\nexport function classifyStatusLine(value: unknown): StatusLineState {\n if (value === null || value === undefined) return 'absent';\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n // A status line whose command this build cannot read is still the user's.\n if (typeof command !== 'string' || command.trim().length === 0) return 'foreign';\n if (command.trim() === OUR_MARKER) return 'ours';\n return command.includes(OUR_MARKER) ? 'composed' : 'foreign';\n}\n\nconst shQuote = (value: string): string => `'${value.replaceAll(\"'\", String.raw`'\\''`)}'`;\nconst shUnquote = (value: string): string => value.replaceAll(String.raw`'\\''`, \"'\");\n\n/** The inner script, with the user's own command as the one hole in it. */\nfunction composedScript(existing: string): string {\n return [\n 'event=$(cat)',\n `yours=$(printf %s \"$event\" | ${existing})`,\n `tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND})`,\n 'printf %s \"$yours${tenjin:+ · $tenjin}\"',\n ].join('; ');\n}\n\n/**\n * The command a composition was built from, or null when this is not a\n * composition an earlier release wrote. It is the exact inverse of\n * {@link composeCommand}: a hand-edited line matches nothing and is kept whole,\n * because guessing at someone's shell is how an uninstall breaks a prompt.\n */\nexport function decomposeCommand(command: string): string | null {\n const trimmed = command.trim();\n if (!trimmed.startsWith(\"sh -c '\") || !trimmed.endsWith(\"'\")) return null;\n const script = shUnquote(trimmed.slice(\"sh -c '\".length, -1));\n const prefix = 'event=$(cat); yours=$(printf %s \"$event\" | ';\n if (!script.startsWith(prefix)) return null;\n const rest = script.slice(prefix.length);\n const suffix = `); tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND}); printf %s \"$yours\\${tenjin:+ · $tenjin}\"`;\n if (!rest.endsWith(suffix)) return null;\n const existing = rest.slice(0, -suffix.length);\n return existing.length > 0 && composedScript(existing) === script ? existing : null;\n}\n\n/**\n * The user's status line with ours appended after a separator, on one line, as\n * an earlier `install --status-line compose` wrote it. The harness writes its\n * event on stdin ONCE, so the event is captured first and replayed into each.\n */\nexport function composeCommand(existing: string): string {\n return `sh -c ${shQuote(composedScript(existing))}`;\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { versionFreeEntry } from '../commands/update';\nimport { hasCode } from '../lib/errno';\nimport {\n claudeConfigDir,\n jsonList,\n jsonResult,\n runClaude,\n type ClaudeBinary,\n type ClaudeRun,\n} from './claude-cli';\nimport { MARKETPLACE_NAME, PLUGIN_ID, PLUGIN_NAME, SKILLS_DIR_PLUGIN_ID } from './names';\nimport { PLUGIN_DIR, renderPluginFiles, type ModSources } from './plugin-files';\nimport {\n inspectPluginFolder,\n pluginFolderPath,\n readModSources,\n removePluginFolder,\n writePluginFolder,\n type FolderRemoval,\n} from './plugin-folder';\n\n/**\n * REGISTERING THE PLUGIN, WITH NO STEP LEFT TO THE PERSON. With a `claude`\n * binary (on PATH, or the one Claude Code names in `CLAUDE_CODE_EXECPATH`):\n *\n * claude plugin marketplace add <marketplace folder> --json\n * claude plugin install tenjin@tenjin --scope <scope> --json\n * claude plugin update tenjin@tenjin --scope <scope> --json (only when the version moved)\n *\n * The marketplace folder is Tenjin's runtime, `~/.tenjin/runtime/claude`, or,\n * where there is no runtime, the installed package's `dist/hosts/claude`. It is\n * a `directory` source Claude Code reads in place, so there is no git or\n * network step, the plugin is the CLI's own build, and an activation that\n * re-renders the runtime folder takes effect at the next session with no\n * command at all. Each command is non-interactive, idempotent and answers one JSON line\n * (lab, Claude Code 2.1.296): a second `add` of the same folder is a no-op, an\n * `add` of a moved folder repoints the marketplace, and `install` of an\n * installed plugin reports both versions. No binary, or a command that fails:\n * the plugin is written as a folder under the config dir's `skills/`, which\n * Claude Code loads with no command at all.\n */\n\nexport type PluginScope = 'user' | 'local';\n\nexport interface RegistrationStep {\n command: string;\n ok: boolean;\n detail?: string;\n}\n\nexport interface PluginRegistration {\n /** `plugin` through Claude's commands, `skills-dir` as a folder, `none` when neither worked. */\n method: 'plugin' | 'skills-dir' | 'none';\n /** The id Claude Code lists it under. */\n id: string | null;\n scope: PluginScope;\n /**\n * `installed` (new), `updated` (the version moved), `current` (already this\n * build), `written` (the folder), `deferred` (left for a newer Claude Code,\n * with a settings install still routing), or `failed` (nothing registered).\n */\n state: 'installed' | 'updated' | 'current' | 'written' | 'deferred' | 'failed';\n /** The marketplace folder or the plugin folder. */\n path?: string;\n version: string;\n steps: RegistrationStep[];\n /** Why the folder was written instead of running the commands. */\n fallbackReason?: string;\n /** Why nothing was registered. */\n reason?: string;\n /** A folder an earlier fallback wrote, removed because the commands now registered the plugin. */\n supersededFolder?: FolderRemoval;\n}\n\nexport interface RegisterOptions {\n binary: ClaudeBinary | null;\n scope: PluginScope;\n /** The CLI version the plugin files carry. */\n version: string;\n env: NodeJS.ProcessEnv;\n home: string;\n cwd: string;\n /** The marketplace folder; defaults to this package's `dist/hosts/claude`. */\n hostsDir?: string | null;\n /** The CLI entry the folder fallback's commands run. Defaults to this package's `dist/index.js`. */\n cliEntry?: string;\n /** The Node the folder fallback's commands run: the runtime's, or `node` from PATH when unset. */\n node?: string;\n}\n\n/** Where the folder fallback lives for this scope. */\nexport function folderFor(scope: PluginScope, env: NodeJS.ProcessEnv, home: string, cwd: string) {\n return pluginFolderPath(scope === 'local' ? join(cwd, '.claude') : claudeConfigDir(env, home));\n}\n\nexport async function registerPlugin(opts: RegisterOptions): Promise<PluginRegistration> {\n const folder = folderFor(opts.scope, opts.env, opts.home, opts.cwd);\n const steps: RegistrationStep[] = [];\n let fallbackReason: string;\n if (opts.binary !== null) {\n const hosts = opts.hostsDir === undefined ? await packageHostsDir() : opts.hostsDir;\n if (hosts === null) {\n fallbackReason = 'this build carries no plugin marketplace folder (dist/hosts/claude)';\n } else {\n const done = await viaPluginCommands(opts.binary, hosts, opts, steps);\n if (done.ok) {\n // A folder an earlier fallback wrote would load as a second copy.\n const superseded = await removePluginFolder(folder);\n return {\n method: 'plugin',\n id: PLUGIN_ID,\n scope: opts.scope,\n state: done.state,\n path: hosts,\n version: opts.version,\n steps,\n ...(superseded.removed ? { supersededFolder: superseded } : {}),\n };\n }\n fallbackReason = done.reason;\n }\n // NO SECOND COPY. A plugin Claude Code already has (an earlier install\n // whose update just failed, or a `tenjin` from another marketplace) would\n // load beside the folder, and every event would run both sets of legs and\n // pay twice. It is left as it is, and the run reports the failure.\n const existing = await existingCopy(opts.binary, opts.env, opts.home, opts.cwd);\n if (existing !== null) {\n return {\n method: 'none',\n id: existing,\n scope: opts.scope,\n state: 'failed',\n version: opts.version,\n steps,\n reason: `${fallbackReason}; ${existing} is already in Claude Code and was left as it is, so no second copy was written`,\n };\n }\n } else {\n fallbackReason = 'no claude binary on PATH or in CLAUDE_CODE_EXECPATH';\n // A plugin Claude's commands registered earlier must not get a second copy.\n if (await installedThroughCommands(opts.env, opts.home)) {\n return {\n method: 'plugin',\n id: PLUGIN_ID,\n scope: opts.scope,\n state: 'current',\n version: opts.version,\n steps,\n fallbackReason: `${fallbackReason}; ${PLUGIN_ID} is already registered, so it was left as it is`,\n };\n }\n }\n const written = await writePluginFolder(\n folder,\n renderPluginFiles(opts.version, opts.cliEntry ?? packageCliEntry(), {\n node: opts.node,\n mod: await packageMod(opts.hostsDir),\n }),\n );\n if (written.state === 'written') {\n return {\n method: 'skills-dir',\n id: SKILLS_DIR_PLUGIN_ID,\n scope: opts.scope,\n state: 'written',\n path: folder,\n version: opts.version,\n steps,\n fallbackReason,\n };\n }\n return {\n method: 'none',\n id: null,\n scope: opts.scope,\n state: 'failed',\n path: folder,\n version: opts.version,\n steps,\n fallbackReason,\n reason: written.reason ?? 'the plugin folder could not be written',\n };\n}\n\ntype CommandsOutcome =\n { ok: true; state: 'installed' | 'updated' | 'current' } | { ok: false; reason: string };\n\nasync function viaPluginCommands(\n binary: ClaudeBinary,\n hosts: string,\n opts: RegisterOptions,\n steps: RegistrationStep[],\n): Promise<CommandsOutcome> {\n const run = (args: string[]) => runClaude(binary, args, { env: opts.env, cwd: opts.cwd });\n const scopeArgs = ['--scope', opts.scope];\n // The marketplace is declared at user scope by default, the form every\n // release since 2.1.287 takes; only a project install names its scope.\n const marketplaceScope = opts.scope === 'user' ? [] : scopeArgs;\n\n // A marketplace called `tenjin` that is not this package's is somebody\n // else's, and `add` would repoint it: it is left alone. So is every\n // marketplace when the list cannot be read, because an unread list cannot\n // prove there is no such marketplace to repoint.\n const known = await run(['plugin', 'marketplace', 'list', '--json']);\n const listed = known.code === 0 ? jsonList(known.stdout) : null;\n steps.push({\n command: 'claude plugin marketplace list --json',\n ok: listed !== null,\n ...(listed === null ? { detail: commandDetail(known) } : {}),\n });\n if (listed === null) {\n return {\n ok: false,\n reason: `claude plugin marketplace list could not be read (${commandDetail(known)}), so no marketplace was added or repointed`,\n };\n }\n const existing = listed.find((m) => m.name === MARKETPLACE_NAME);\n if (existing !== undefined && !(await ownMarketplace(existing))) {\n return {\n ok: false,\n reason: `a marketplace named ${MARKETPLACE_NAME} that this CLI did not add is already configured, so it was left as it is`,\n };\n }\n\n const add = await step(\n steps,\n ['plugin', 'marketplace', 'add', hosts, '--json', ...marketplaceScope],\n run,\n );\n if (!add.ok) return { ok: false, reason: `claude plugin marketplace add failed: ${add.detail}` };\n const install = await step(steps, ['plugin', 'install', PLUGIN_ID, ...scopeArgs, '--json'], run);\n if (!install.ok) return { ok: false, reason: `claude plugin install failed: ${install.detail}` };\n const installed = install.result?.installedVersion;\n const available = install.result?.availableVersion;\n if (typeof installed !== 'string' || typeof available !== 'string') {\n return { ok: true, state: 'installed' };\n }\n if (installed === available) return { ok: true, state: 'current' };\n const update = await step(steps, ['plugin', 'update', PLUGIN_ID, ...scopeArgs, '--json'], run);\n if (!update.ok) return { ok: false, reason: `claude plugin update failed: ${update.detail}` };\n return { ok: true, state: 'updated' };\n}\n\n/**\n * Did this registration's `claude plugin marketplace add <hosts>` succeed?\n * Then Claude Code's one global `tenjin` row names `hosts` now, whatever\n * failed after it, and loads the plugin from there in place.\n */\nexport function marketplaceAdded(reg: PluginRegistration, hosts: string): boolean {\n const add = `claude plugin marketplace add ${hosts} `;\n return reg.steps.some((s) => s.ok && s.command.startsWith(add));\n}\n\nasync function step(\n steps: RegistrationStep[],\n args: string[],\n run: (args: string[]) => Promise<ClaudeRun>,\n): Promise<{ ok: boolean; detail: string; result: Record<string, unknown> | null }> {\n const out = await run(args);\n const result = jsonResult(out.stdout);\n const ok =\n out.code === 0 && (result === null || result.outcome === undefined || result.outcome === 'ok');\n const detail = commandDetail(out, result);\n steps.push({ command: `claude ${args.join(' ')}`, ok, ...(ok ? {} : { detail }) });\n return { ok, detail, result };\n}\n\n/** What a failed command said: its JSON message, else its output, else how it ended. */\nfunction commandDetail(out: ClaudeRun, result: Record<string, unknown> | null = null): string {\n if (typeof result?.message === 'string') return result.message;\n const text = (out.stderr || out.stdout).trim().slice(0, 300);\n if (text.length > 0) return text;\n return out.code === null ? 'the command could not be run' : `exit ${out.code}`;\n}\n\n/**\n * Is this marketplace one `install` added? A directory source whose plugin\n * folder carries the `tenjin-cli` marker in its manifest, or, when that folder\n * is gone (a package manager removed the old version's directory, or the\n * runtime was removed), one whose path is a `tenjin-cli` package's\n * `dist/hosts/claude` or Tenjin's `runtime/claude`.\n */\nexport async function ownMarketplace(row: Record<string, unknown>): Promise<boolean> {\n const path = typeof row.path === 'string' ? row.path : undefined;\n if (row.source !== 'directory' || path === undefined) return false;\n if ((await stat(path).catch(() => null)) === null) {\n return (\n /tenjin-cli[\\\\/]dist[\\\\/]hosts[\\\\/]claude$/.test(path) ||\n /[\\\\/]runtime[\\\\/]claude$/.test(path)\n );\n }\n return (await inspectPluginFolder(join(path, PLUGIN_DIR))) === 'ours';\n}\n\n/**\n * A `tenjin` plugin Claude Code already holds that a folder would duplicate:\n * any enabled `tenjin@<marketplace>`. The folder's own `tenjin@skills-dir` is\n * not a duplicate, since writing the folder updates it in place. When the list\n * cannot be read, Claude Code's own record of installed plugins answers.\n */\nasync function existingCopy(\n binary: ClaudeBinary,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<string | null> {\n const out = await runClaude(binary, ['plugin', 'list', '--json'], { env, cwd });\n const listed = out.code === 0 ? jsonList(out.stdout) : null;\n if (listed === null) return (await installedThroughCommands(env, home)) ? PLUGIN_ID : null;\n const row = listed.find(\n (p) =>\n typeof p.id === 'string' &&\n p.id.startsWith(`${PLUGIN_NAME}@`) &&\n p.id !== SKILLS_DIR_PLUGIN_ID &&\n p.enabled === true,\n );\n return typeof row?.id === 'string' ? row.id : null;\n}\n\n/** One `tenjin@tenjin` install in Claude Code's own record. */\nexport interface InstallRecord {\n scope: 'user' | 'local';\n /** The folder a `local` install ran in (not the git root); null for `user`. */\n projectPath: string | null;\n}\n\n/**\n * EVERY `tenjin@tenjin` INSTALL CLAUDE CODE RECORDS, in any scope or project,\n * from `plugins/installed_plugins.json` (`{version: 2, plugins: {\"tenjin@tenjin\":\n * [entry, …]}}`). `[]` when the file is absent, null when it is there but cannot\n * be read. Keys are read by name, since their order varies, and `installPath`\n * and `version` never: both go stale once the marketplace is repointed.\n */\nexport async function recordedInstalls(\n env: NodeJS.ProcessEnv,\n home: string,\n): Promise<InstallRecord[] | null> {\n let raw: string;\n try {\n raw = await readFile(\n join(claudeConfigDir(env, home), 'plugins', 'installed_plugins.json'),\n 'utf8',\n );\n } catch (err) {\n return hasCode(err, 'ENOENT') ? [] : null;\n }\n let plugins: unknown;\n try {\n plugins = (JSON.parse(raw) as { plugins?: unknown }).plugins;\n } catch {\n return null;\n }\n if (typeof plugins !== 'object' || plugins === null || Array.isArray(plugins)) return null;\n const entries = (plugins as Record<string, unknown>)[PLUGIN_ID];\n if (!Array.isArray(entries)) return [];\n const records: InstallRecord[] = [];\n for (const entry of entries) {\n if (typeof entry !== 'object' || entry === null) continue;\n const { scope, projectPath } = entry as { scope?: unknown; projectPath?: unknown };\n if (scope === 'user') records.push({ scope, projectPath: null });\n else if (scope === 'local' && typeof projectPath === 'string' && projectPath.length > 0) {\n records.push({ scope, projectPath });\n }\n }\n return records;\n}\n\n/** Claude Code's own record of installed plugins, read when no binary can be asked. */\nexport async function installedThroughCommands(\n env: NodeJS.ProcessEnv,\n home: string,\n): Promise<boolean> {\n try {\n const raw = await readFile(\n join(claudeConfigDir(env, home), 'plugins', 'installed_plugins.json'),\n 'utf8',\n );\n const plugins = (JSON.parse(raw) as { plugins?: unknown }).plugins;\n return plugins !== null && typeof plugins === 'object' && PLUGIN_ID in plugins;\n } catch {\n return false;\n }\n}\n\n/**\n * THIS PACKAGE'S MARKETPLACE FOLDER, `dist/hosts/claude`, beside the bundle\n * that is running. Under pnpm the running path pins a version\n * (`.pnpm/tenjin-cli@<v>/...`), and a marketplace registered there would point\n * at a directory the next upgrade deletes, so the version-free path beside the\n * store is used when it exists, as `tenjin update` does for its re-exec.\n */\nexport async function packageHostsDir(\n moduleDir: string = dirname(fileURLToPath(import.meta.url)),\n): Promise<string | null> {\n const catalog = join(moduleDir, 'hosts', 'claude', '.claude-plugin', 'marketplace.json');\n const stable = versionFreeEntry(catalog) ?? catalog;\n if ((await stat(stable).catch(() => null))?.isFile() !== true) return null;\n return dirname(dirname(stable));\n}\n\n/**\n * THE MOD'S SOURCES, ONE LOOKUP FOR EVERY PLUGIN FOLDER THIS MODULE WRITES.\n * The mod ships as written in the package's own plugin folder\n * (`dist/hosts/claude/tenjin`, or `hostsDir`'s), and a render carries it only\n * when it is passed in: a plugin folder rendered anywhere else (the folder\n * fallback here, or a marketplace folder rendered under the data dir) takes\n * this result, or it ships without the mod. Undefined when the folder carries\n * no mod or there is no package folder.\n */\nexport async function packageMod(hostsDir?: string | null): Promise<ModSources | undefined> {\n const hosts = hostsDir === undefined ? await packageHostsDir() : hostsDir;\n return hosts === null ? undefined : readModSources(join(hosts, PLUGIN_DIR));\n}\n\n/**\n * THIS PACKAGE'S CLI ENTRY, `dist/index.js` beside the running bundle, for a\n * plugin folder outside the package. The version-free path under pnpm, as\n * {@link packageHostsDir} uses, so an upgrade does not strand it.\n */\nexport function packageCliEntry(\n moduleDir: string = dirname(fileURLToPath(import.meta.url)),\n): string {\n const entry = join(moduleDir, 'index.js');\n return versionFreeEntry(entry) ?? entry;\n}\n\n/** Doctor's and the migration's read: is the plugin installed and enabled? */\nexport interface PluginListing {\n /** The row for `tenjin@tenjin` or `tenjin@skills-dir`, when Claude Code lists one. */\n id: string | null;\n enabled: boolean;\n version: string | null;\n /** False when the list itself could not be read. */\n read: boolean;\n /** The chosen row's scope (`user`, `project`, `local`), or null when it names none. */\n scope: string | null;\n /**\n * The projects a `tenjin@tenjin` install is recorded for and NOT enabled\n * here: each row's `projectPath`. A `local` install made in one project is\n * listed from every other directory as disabled, and enabling it there is\n * not the fix; running from that project is. Empty when the list was not\n * read or names none.\n */\n projects: string[];\n}\n\nexport async function readPluginListing(\n binary: ClaudeBinary,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<PluginListing> {\n const out = await runClaude(binary, ['plugin', 'list', '--json'], { env, cwd });\n const rows = out.code === 0 ? jsonList(out.stdout) : null;\n if (rows === null) {\n return { id: null, enabled: false, version: null, read: false, scope: null, projects: [] };\n }\n const projects = rows\n .filter(\n (r) =>\n r.id === PLUGIN_ID &&\n r.enabled !== true &&\n typeof r.projectPath === 'string' &&\n r.projectPath.length > 0,\n )\n .map((r) => r.projectPath as string);\n const row =\n rows.find((r) => r.id === PLUGIN_ID && r.enabled === true) ??\n rows.find((r) => r.id === SKILLS_DIR_PLUGIN_ID && r.enabled === true) ??\n rows.find((r) => r.id === PLUGIN_ID || r.id === SKILLS_DIR_PLUGIN_ID);\n if (row === undefined) {\n return { id: null, enabled: false, version: null, read: true, scope: null, projects };\n }\n return {\n id: String(row.id),\n enabled: row.enabled === true,\n version: typeof row.version === 'string' ? row.version : null,\n read: true,\n scope: typeof row.scope === 'string' ? row.scope : null,\n projects,\n };\n}\n\n/** Is a folder of ours there for this scope? */\nexport async function folderState(\n scope: PluginScope,\n env: NodeJS.ProcessEnv,\n home: string,\n cwd: string,\n): Promise<{ path: string; state: 'absent' | 'ours' | 'foreign' }> {\n const path = folderFor(scope, env, home, cwd);\n return { path, state: await inspectPluginFolder(path) };\n}\n","import { spawn } from 'node:child_process';\nimport { existsSync, statSync } from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport pkg from '../../package.json';\nimport { proxyNodeStep, proxySkipped } from '../lib/env-proxy';\nimport { CliError } from '../lib/errors';\nimport { MANAGERS, classifyManager, refuse, resolveManagerScript } from '../lib/install-location';\nimport type { Delegable } from '../lib/install-location';\nimport { emitWriteNotice, sanitizeForTerminal } from '../lib/output';\nimport {\n NUDGE_OPT_OUT,\n channelTag,\n fetchDistTags,\n fetchPublishTime,\n isNewer,\n resolveTarget,\n} from '../lib/update-check';\nimport { loadRawConfig } from '../lib/config';\nimport { defaultDataDir, isDefaultDataDir, runtimeDir, tilde } from '../lib/paths';\nimport type { ensureNode, placeVersion, stageTarball } from '../lib/runtime-place';\nimport type { CommandContext, CommandResult } from '../context';\nimport { persistRouterProject } from './config';\nimport { projectInstallAt } from '../router/install';\nimport { readMcpServers, type InstalledAt, type ListMcpProcesses } from '../router/mcp-processes';\nimport { RUNTIME_MISSING_FIX } from '../router/plugin-files';\n\n/**\n * `tenjin update`: move this machine to the newest version npm's `latest` tag\n * names. Which way depends on whether Tenjin's runtime (`~/.tenjin/runtime`,\n * the default data dir only) is here.\n *\n * THE RUNTIME BRANCH needs no npm. This OLD build downloads the release (the\n * registry tarball, once npm's provenance shows Tenjin's release workflow built\n * it, checked against its sha512; or a copy of itself when it IS that\n * release), ensures the Node the release pins, and places it beside the\n * current version. The NEW build, spawned on that Node as `install --refresh`,\n * checks itself (`verifyBuild`), and only then switches the runtime to itself\n * and registers it. The parent reads the switch back from `state.json`: a\n * release that did not switch leaves the previous version current, and the\n * update fails saying so. The parent holds no runtime lock while a child runs.\n *\n * THE NPM BRANCH is kept for an install with no runtime. It spawns the package\n * manager that OWNS the install rather than reimplementing one:\n *\n * - The argv pins the EXACT version the registry just named, never the tag, so\n * the check and the install cannot disagree about what ships, and the version\n * string is certified parseable by the same `isNewer` gate the nudge trusts\n * before it goes anywhere near an argv.\n * - That version passes the runtime branch's provenance check (lib/runtime-provenance's\n * `checkReleaseProvenance`) before the manager is spawned: what npm installs\n * here can become the first runtime on its refresh.\n * - The owner performs the install. npm, pnpm and bun are each driven with their\n * own global-add command, because the PATH race that makes a second install\n * dangerous comes from CROSS-manager writes, not from asking the owner to do\n * what it already owns. What cannot be driven is refused instead of guessed\n * at: a source checkout updates by git, an npx run has nothing installed to\n * replace, a project-local copy updates where it is declared, and yarn's\n * global install exists only in yarn 1. See lib/install-location.\n * - The manager's chatter goes to stderr (live, human mode only, sanitized) and\n * its failure into the error envelope; stdout stays the one envelope every\n * command emits.\n *\n * On both, every child is a binary or `node <script>`, never a shell. That is\n * what makes a pinned argv worth pinning, and it is the only form that works on\n * win32, where the runtime's child is its absolute `node.exe`.\n */\n\n/** How long the npm child gets before it is killed. npm's own retry budget runs\n * into minutes, and an agent's turn should not hang on a wedged registry. */\nconst INSTALL_TIMEOUT_MS = 300_000;\n\n/** How long the release's tarball, and the Node it pins, may take to download. */\nconst STAGE_TIMEOUT_MS = 120_000;\nconst NODE_TIMEOUT_MS = 300_000;\n\n/**\n * HOW OLD A RELEASE MUST BE BEFORE THE BACKGROUND RUN TAKES IT: a day since\n * the registry published it. The window lets maintainers move `latest` back\n * (`npm dist-tag add tenjin-cli@<good> latest`) before any auto-updater runs\n * a bad or malicious release, which the provenance check (lib/runtime-provenance's\n * `RELEASE_WORKFLOW`) cannot catch when the release workflow itself was\n * compromised. Publish times are set by the registry and cannot be backdated.\n * A manual `tenjin update` is the person choosing the release now, and does\n * not wait.\n */\nexport const BACKGROUND_COOLDOWN_MS = 24 * 60 * 60_000;\n\nexport interface UpdateOptions {\n /** Report whether a newer version exists; never install. */\n check: boolean;\n /**\n * The detached run lib/auto-update starts: the runtime branch only, never\n * npm, only a release published at least a day ago\n * ({@link BACKGROUND_COOLDOWN_MS}), with how it ended recorded in\n * `<runtime>/auto-update.json`.\n */\n background?: boolean;\n}\n\n/**\n * How the child ended. Never rejects: all three outcomes are envelope-shaped\n * facts the caller reports, not exceptions, and each is separately testable.\n */\nexport type SpawnResult =\n { kind: 'exit'; code: number } | { kind: 'start-failed'; cause: unknown } | { kind: 'timeout' };\n\nexport type UpdateSpawn = (\n cmd: string,\n args: string[],\n opts: {\n cwd: string;\n timeoutMs: number;\n /** Variables layered ONTO this process's environment, for the per-profile\n * `TENJIN_DATA_DIR` the refresh pass sets. Absent means inherit unchanged. */\n env?: Record<string, string>;\n },\n onOutput: (chunk: string) => void,\n) => Promise<SpawnResult>;\n\n/** What to spawn for one manager: a command and any argv that must precede its own. */\ninterface ResolvedManager {\n cmd: string;\n prefix: readonly string[];\n}\n\n/**\n * Turn a manager into a spawnable command. A resolved script runs under THIS\n * node, keeping `shell` unset on every platform; otherwise the bare binary name\n * is used, which is correct for a native binary and fails closed on win32 for a\n * `.cmd` shim.\n */\nfunction resolveManager(manager: Delegable, deps: UpdateDeps): ResolvedManager {\n const script =\n deps.managerScript !== undefined\n ? deps.managerScript\n : resolveManagerScript(manager, process.execPath);\n return script === null\n ? { cmd: MANAGERS[manager].bin, prefix: [] }\n : { cmd: process.execPath, prefix: [script] };\n}\n\nexport interface UpdateDeps {\n fetchImpl?: typeof fetch;\n spawnImpl?: UpdateSpawn;\n /** Where this build's code lives on disk; tests point it at fixture trees. */\n moduleDir?: string;\n /** The running version; defaults to this build's. Injectable for tests. */\n currentVersion?: string;\n /** The owning manager's entry script, or null when it has none to find.\n * Injectable so the argv shape is asserted without depending on the runner. */\n managerScript?: string | null;\n /** Home whose manual-fix command the report names, and whose `.tenjin` is the\n * default data dir the runtime belongs to. Defaults to os.homedir(). */\n homeDir?: string;\n /**\n * The CLI entry the npm branch's refresh child runs. Defaults to `process.argv[1]`, which\n * after the swap resolves to the NEWLY installed script — that is the whole\n * point of spawning rather than calling.\n */\n refreshCommand?: string;\n /** This user's running `tenjin mcp` processes; tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When the new build was installed; tests inject it. */\n installedAt?: InstalledAt;\n /** Tenjin's runtime folder; defaults to the one under the data dir. */\n runtimeRoot?: string;\n /** The runtime branch's download, Node and placement; tests inject them. */\n stage?: typeof stageTarball;\n ensure?: typeof ensureNode;\n place?: typeof placeVersion;\n /** Test seam; production asks this Node whether it can use the shell's proxy. */\n proxySupported?: boolean;\n /** The clock the background run's cooldown reads; tests pin it. */\n now?: () => number;\n}\n\ninterface UpdateData {\n current: string;\n latest: string;\n updateAvailable: boolean;\n updated: boolean;\n}\n\nexport async function runUpdate(\n opts: UpdateOptions,\n ctx: CommandContext,\n deps: UpdateDeps = {},\n): Promise<CommandResult> {\n if (opts.background !== true) return update(opts, ctx, deps);\n // THE BACKGROUND RUN records how it ended for doctor, then answers as any\n // update does: its envelope goes to the log. Only where the runtime folder\n // already is, so a run with no runtime creates nothing.\n const root = deps.runtimeRoot ?? runtimeDir(ctx.dataDir);\n const [{ recordAutoUpdate }, { readRuntimeState }] = await Promise.all([\n import('../lib/auto-update'),\n import('../lib/runtime-layout'),\n ]);\n const from = readRuntimeState(root)?.current.cli;\n const record = (r: Parameters<typeof recordAutoUpdate>[1]): void => {\n if (!existsSync(root)) return;\n try {\n recordAutoUpdate(root, { finishedAt: new Date().toISOString(), ...r });\n } catch {\n // The update itself is the result; a record that cannot be written is not.\n }\n };\n try {\n const result = await update(opts, ctx, deps);\n const d = result.data as Partial<UpdateData> & { skipped?: string };\n record(\n d.skipped !== undefined\n ? { outcome: 'skipped', reason: d.skipped }\n : d.updated === true\n ? { outcome: 'updated', from: d.current, to: d.latest }\n : { outcome: 'current', from: d.current, to: d.current },\n );\n return result;\n } catch (err) {\n const reason = sanitizeForTerminal(err instanceof Error ? err.message : String(err)).trim();\n record({\n outcome: 'failed',\n ...(from !== undefined ? { from } : {}),\n reason: reason.slice(0, REASON_LIMIT),\n });\n throw err;\n }\n}\n\nasync function update(\n opts: UpdateOptions,\n ctx: CommandContext,\n deps: UpdateDeps,\n): Promise<CommandResult> {\n const current = deps.currentVersion ?? pkg.version;\n const channel = channelTag(current);\n const moduleDir = deps.moduleDir ?? fileURLToPath(new URL('.', import.meta.url));\n\n // Refused, not defaulted to a channel: a build whose version this package\n // cannot parse has no release line to compare against, and guessing one is how\n // a foreign build gets told it is up to date forever.\n if (channel === null) {\n throw new CliError('REFUSED', `tenjin-cli reports an unrecognizable version (${current})`, {\n fix: 'Reinstall a published build: npm i -g tenjin-cli',\n });\n }\n\n // First stage: everything whose fix string does not need a resolved version,\n // so it answers without the network. An offline contributor in a checkout is\n // told they are in a checkout, not told to go debug their registry access.\n refuse(moduleDir, { check: opts.check, spec: null });\n\n const tags = await fetchDistTags({\n fetchImpl: deps.fetchImpl,\n timeoutMs: ctx.flags.timeout,\n });\n if (tags === null) {\n throw new CliError('NETWORK_ERROR', 'Could not read tenjin-cli dist-tags from npm', {\n fix: 'Check access to registry.npmjs.org and retry',\n });\n }\n // THE RUNTIME'S VERSION IS THE ONE THAT RUNS, so it is what the answer is\n // about: an npm copy older than the runtime still moves the runtime forward,\n // and \"up to date\" or `--check` speak of what Claude Code starts.\n const runtime = await runtimeHere(ctx, deps, moduleDir);\n // The background run never reaches npm: with no runtime it has nothing to do.\n if (opts.background === true && runtime === null) {\n return {\n data: { skipped: 'no runtime' },\n humanLines: [\"Nothing to update in the background: Tenjin's runtime is not set up here.\"],\n };\n }\n const base = runtime?.current ?? current;\n const latest = resolveTarget(base, tags);\n // Not a NETWORK_ERROR: nothing about the connection is wrong, and telling the\n // user to check their access sends them after a fault that is not there.\n if (latest === null) {\n const raw = tags[channel];\n throw raw === undefined\n ? new CliError('RESOURCE_NOT_FOUND', 'npm has no published tenjin-cli on the latest tag', {\n fix: 'Pick a version yourself: npm view tenjin-cli versions',\n })\n : new CliError(\n 'RESOURCE_NOT_FOUND',\n // Registry-controlled: bounded here, escaped by the error emitter.\n `npm's latest tenjin-cli (${raw.slice(0, 40)}) is not a version this build can read`,\n {\n fix: 'Install it by name: npm i -g tenjin-cli@<version> (npm view tenjin-cli versions)',\n },\n );\n }\n\n const updateAvailable = isNewer(latest, base);\n const data = (updated: boolean): UpdateData => ({\n current: base,\n latest,\n updateAvailable,\n updated,\n });\n\n if (!updateAvailable) {\n return {\n data: data(false),\n humanLines: [`tenjin-cli ${base} is up to date`],\n };\n }\n if (opts.check) {\n return {\n data: data(false),\n humanLines: [\n `tenjin-cli ${latest} is available (you have ${base}).`,\n 'Run tenjin update to install it.',\n ],\n };\n }\n\n // THE BACKGROUND RUN WAITS A DAY after a release is published (see\n // BACKGROUND_COOLDOWN_MS) and switches nothing before then; the next daily\n // run takes it. Only the background run: here it always has a runtime.\n if (opts.background === true) {\n const wait = await tooNewForBackground(latest, ctx, deps);\n if (wait !== null) {\n return {\n data: { ...data(false), skipped: wait },\n humanLines: [`${wait}; the background update takes a release a day after it is published.`],\n };\n }\n }\n\n // No manager below this line is asked, so none of the stage-2 refusals about\n // how npm's copy was installed apply: an npx run updates the runtime too.\n if (runtime !== null) {\n return runtimeUpdate(ctx, deps, { ...runtime, base, latest, current, moduleDir, data });\n }\n\n await refuseRuntimeElsewhere(ctx, moduleDir, deps.homeDir ?? homedir());\n\n // `latest` is argv-safe here: isNewer returned true, so it matched VERSION_RE.\n const spec = `tenjin-cli@${latest}`;\n\n // Second stage: the entries whose fix strings name the version just resolved.\n // Reached only on the install path, since --check has already returned.\n refuse(moduleDir, { check: false, spec });\n\n // THE SAME PROVENANCE GATE THE RUNTIME BRANCH'S DOWNLOAD PASSES, before any\n // manager is asked: the build installed here runs its own `install --refresh`\n // next, which on the default data dir copies it into a first runtime, wallet\n // and auto-update included. The manager then installs this exact version\n // and checks its tarball against the same `dist.integrity` the provenance\n // was matched to, which a published version can never change, so it\n // installs the attested bytes. A manager configured to fetch from another\n // registry (a mirror) gets them from there, which this check does not see.\n const { checkReleaseProvenance } = await import('../lib/runtime-provenance');\n await checkReleaseProvenance(latest, {\n timeoutMs: ctx.flags.timeout,\n fetchImpl: deps.fetchImpl,\n });\n\n // Live chatter is a human courtesy only; the tail rides in the error envelope\n // so a piped failure is still diagnosable. Sanitized per line, because npm\n // relays publisher-controlled text (deprecation notices) and a line break is\n // the one control character this stream must keep.\n const human = ctx.io.isTTY && !ctx.flags.json;\n let tail = '';\n const onOutput = (chunk: string): void => {\n tail = (tail + chunk).slice(-2000);\n if (human) ctx.io.stderr.write(chunk.split('\\n').map(sanitizeForTerminal).join('\\n'));\n };\n\n // Whoever owns the install performs it. The PATH-race objection that used to\n // make this a refusal only applies to CROSS-manager writes; invoking the owner\n // is exactly what the refusal used to tell the user to type by hand.\n //\n // The cast is sound only because `refuse` ran directly above and yarn is one\n // of its entries, so the one non-delegable manager has already thrown. Move\n // this line above that call and it becomes a lie.\n const manager = classifyManager(moduleDir) as Delegable;\n const plan = MANAGERS[manager];\n // --ignore-scripts where the manager has it (tenjin-cli has no runtime\n // dependencies and no registry install runs its own `prepare`), and cwd is the\n // home directory so the child never reads a project's config by accident.\n const args = plan.args(spec);\n const resolved = resolveManager(manager, deps);\n const manual = `Run it yourself: ${plan.manual(spec)}`;\n\n const outcome = await (deps.spawnImpl ?? spawnCapture)(\n resolved.cmd,\n [...resolved.prefix, ...args],\n { cwd: homedir(), timeoutMs: INSTALL_TIMEOUT_MS },\n onOutput,\n );\n if (outcome.kind === 'start-failed') {\n throw new CliError('UPDATE_FAILED', `Could not start ${manager}`, {\n fix: manual,\n cause: outcome.cause,\n });\n }\n if (outcome.kind === 'timeout') {\n throw new CliError(\n 'UPDATE_FAILED',\n `${manager} did not finish in ${INSTALL_TIMEOUT_MS / 1000}s`,\n { fix: manual, details: { output: tail } },\n );\n }\n if (outcome.code !== 0) {\n throw new CliError('UPDATE_FAILED', `${manager} ${args.join(' ')} exited ${outcome.code}`, {\n // EACCES on a root-owned global prefix is the common cause; the operator\n // fixing that themselves beats this CLI ever escalating.\n fix: manual,\n details: { output: tail },\n });\n }\n\n emitWriteNotice(\n ctx.io,\n `tenjin update: replaced the global tenjin-cli with ${latest} via ${manager}`,\n );\n\n const { refresh } = await refreshProfiles(ctx, deps, npmLaunch(deps));\n return updated(deps, data(true), refresh, [`Updated tenjin-cli ${current} -> ${latest}.`]);\n}\n\n/**\n * The report of an update that happened, on either branch. The refresh child's\n * output is captured, so the warning it would print about a `tenjin mcp` still\n * running the old build is checked again here, with the fix the child's\n * migration state calls for. `version` is the build the runtime now runs: a\n * router launched from the runtime is stale when it runs any other.\n */\nasync function updated(\n deps: UpdateDeps,\n data: UpdateData,\n refresh: RefreshOutcome,\n head: string[],\n version?: string,\n): Promise<CommandResult> {\n const servers = await readMcpServers(deps, {\n settingsInstallPending: refresh.settingsInstallPending,\n ...(version !== undefined ? { version } : {}),\n });\n return {\n data: { ...data, refresh, mcpServer: servers.check },\n humanLines: [\n ...head,\n ...refreshLines(refresh),\n ...projectLines(refresh),\n ...refresh.notices,\n ...(servers.stale > 0\n ? [`! ${servers.check.detail}. ${servers.check.fix ?? ''}`.trim()]\n : []),\n ],\n };\n}\n\n/** Tenjin's runtime as this update sees it. */\ninterface RuntimeHere {\n root: string;\n /** Its current version, or null when only this build's own location says it is one. */\n current: string | null;\n /** This build runs from the runtime itself. */\n inRuntime: boolean;\n}\n\n/**\n * The runtime to update, or null for the npm branch: the default data dir\n * only (a QA profile keeps npm's layout), and only where a runtime state\n * exists or this build runs from one. The runtime modules are imported\n * lazily: `router/plugin-registration` imports this module, and it sits in the\n * status line's chunk, which must not load them.\n */\nasync function runtimeHere(\n ctx: CommandContext,\n deps: UpdateDeps,\n moduleDir: string,\n): Promise<RuntimeHere | null> {\n if (!isDefaultDataDir(ctx.dataDir, deps.homeDir ?? homedir())) return null;\n const { readRuntimeState, runtimeBuild } = await import('../lib/runtime-layout');\n const root = deps.runtimeRoot ?? runtimeDir(ctx.dataDir);\n const state = readRuntimeState(root);\n const inRuntime = runtimeBuild(moduleDir) !== null;\n if (state === null && !inRuntime) return null;\n return { root, current: state?.current.cli ?? null, inRuntime };\n}\n\n/**\n * Why the background run does not take `latest` yet, or null once the registry\n * published it at least {@link BACKGROUND_COOLDOWN_MS} ago. A publish time that\n * is missing, does not parse, or lies in the future counts as too new: waiting\n * is the safe side. A registry that cannot be asked fails the run, as the\n * dist-tags read does, and the next daily run asks again.\n */\nasync function tooNewForBackground(\n latest: string,\n ctx: CommandContext,\n deps: UpdateDeps,\n): Promise<string | null> {\n const answer = await fetchPublishTime(latest, {\n fetchImpl: deps.fetchImpl,\n timeoutMs: ctx.flags.timeout,\n });\n if (answer === null) {\n throw new CliError('NETWORK_ERROR', `Could not read when tenjin-cli ${latest} was published`, {\n fix: 'Check access to registry.npmjs.org and retry',\n });\n }\n if (answer.publishedAt === null) return `npm names no publish time for tenjin-cli ${latest}`;\n const age = (deps.now ?? Date.now)() - answer.publishedAt;\n // A time in the future gives a negative age, so it waits too.\n return age >= BACKGROUND_COOLDOWN_MS\n ? null\n : `tenjin-cli ${latest} was published under 24 hours ago`;\n}\n\n/**\n * A RUNTIME BUILD UNDER ANOTHER DATA DIR has no npm install to update: it is\n * `~/.local/bin/tenjin` run with `TENJIN_DATA_DIR` set, and the runtime belongs\n * to the default data dir alone. Said as that, before the npm branch's\n * refusals would call it a project-local dependency.\n */\nasync function refuseRuntimeElsewhere(\n ctx: CommandContext,\n moduleDir: string,\n home: string,\n): Promise<void> {\n const { runtimeBuild } = await import('../lib/runtime-layout');\n if (runtimeBuild(moduleDir) === null) return;\n throw new CliError(\n 'REFUSED',\n `This tenjin runs from Tenjin's runtime, which only the default data dir (${tilde(defaultDataDir(home), home)}) uses, and TENJIN_DATA_DIR is ${tilde(ctx.dataDir, home)}, so nothing was updated`,\n {\n fix: 'Run `tenjin update` with TENJIN_DATA_DIR unset: the runtime belongs to the default data dir. Another data dir runs on an npm copy, updated with `npm i -g tenjin-cli@latest`.',\n },\n );\n}\n\n/**\n * THE RUNTIME BRANCH (see the header). Everything up to the spawn is this OLD\n * build's: download, Node, placement, each under the runtime lock and released\n * before the child starts. The switch is the NEW build's, so the verdict is read\n * back from `state.json` rather than trusted from an exit code: a child that\n * exits 0 having kept the previous version (its own checks failed) did not\n * update anything.\n */\nasync function runtimeUpdate(\n ctx: CommandContext,\n deps: UpdateDeps,\n o: RuntimeHere & {\n base: string;\n latest: string;\n current: string;\n moduleDir: string;\n data: (updated: boolean) => UpdateData;\n },\n): Promise<CommandResult> {\n const { root, base, latest } = o;\n const [rt, layout] = await Promise.all([\n import('../lib/runtime-place'),\n import('../lib/runtime-layout'),\n ]);\n const stays = `so ${base} stays`;\n\n // An npm copy that IS the release copies itself: the bytes are already here\n // and were installed by npm, with nothing to fetch. Anything else is fetched.\n let stage: string;\n if (latest === o.current && !o.inRuntime) {\n const packageRoot = rt.packageRootOf(o.moduleDir);\n if (packageRoot === null) {\n throw new CliError(\n 'UPDATE_FAILED',\n `tenjin-cli ${latest} cannot find its own package, ${stays}`,\n {\n fix: RUNTIME_MISSING_FIX,\n },\n );\n }\n stage = await rt.stageSelf(root, packageRoot);\n } else {\n stage = await (deps.stage ?? rt.stageTarball)(root, latest, {\n timeoutMs: STAGE_TIMEOUT_MS,\n fetchImpl: deps.fetchImpl,\n }).catch((err: unknown) => {\n throw proxyNamed(err, deps);\n });\n }\n\n let node: string;\n try {\n // The NEW version's pin, read as data from the package just checked.\n const pin = rt.readNodePin(stage);\n if (pin === null) {\n throw new CliError('UPDATE_FAILED', `tenjin-cli ${latest} carries no Node pin, ${stays}`, {\n fix: `Nothing to do: ${base} keeps running. Run \\`tenjin update\\` again after the next release.`,\n });\n }\n node = await (deps.ensure ?? rt.ensureNode)(root, pin, {\n timeoutMs: NODE_TIMEOUT_MS,\n fetchImpl: deps.fetchImpl,\n });\n await (deps.place ?? rt.placeVersion)(root, stage, latest);\n } catch (err) {\n await rm(stage, { recursive: true, force: true }).catch(() => undefined);\n throw proxyNamed(err, deps);\n }\n const home = deps.homeDir ?? homedir();\n emitWriteNotice(ctx.io, `tenjin update: staged tenjin-cli ${latest} in ${tilde(root, home)}`);\n\n const { refresh, homeTail } = await refreshProfiles(ctx, deps, {\n node,\n entry: layout.versionEntry(root, latest),\n });\n if (layout.readRuntimeState(root)?.current.cli !== latest) {\n // `versions/<latest>` is left for the next collect(): nothing points at it.\n throw new CliError('UPDATE_FAILED', `tenjin-cli ${latest} did not pass its checks, ${stays}`, {\n fix: 'Run `tenjin update` again; if it fails again, run `tenjin doctor`',\n details: {\n reason:\n refresh.failed[0]?.reason ??\n runtimeReason(envelopeData(homeTail)) ??\n 'The new version did not switch the runtime to itself.',\n output: homeTail.slice(-2000),\n },\n });\n }\n return updated(\n deps,\n o.data(true),\n refresh,\n [\n `Updated tenjin-cli ${base} -> ${latest}.`,\n `The previous version (${base}) stays as the fallback.`,\n ],\n latest,\n );\n}\n\n/**\n * A download in the runtime branch that failed on a Node which skips the\n * shell's proxy (#470), said as that with the step that works: `tenjin update`\n * again on the same Node fails the same way.\n */\nfunction proxyNamed(err: unknown, deps: UpdateDeps): unknown {\n if (!(err instanceof CliError) || err.code !== 'NETWORK_ERROR') return err;\n const skipped = proxySkipped(process.env, deps.proxySupported);\n if (skipped === null) return err;\n const step = proxyNodeStep('tenjin update');\n return new CliError('NETWORK_ERROR', `${err.message}: ${skipped}`, {\n fix: `${step.charAt(0).toUpperCase()}${step.slice(1)}.`,\n cause: err,\n });\n}\n\n/** Why the child kept the previous runtime, from its `data.runtime.reason`. */\nfunction runtimeReason(data: Record<string, unknown> | null): string | undefined {\n const reason = (data?.runtime as { reason?: unknown } | undefined)?.reason;\n if (typeof reason !== 'string') return undefined;\n const text = sanitizeForTerminal(reason).trim();\n return text.length > 0 ? text.slice(0, REASON_LIMIT) : undefined;\n}\n\n/** How long one `install --refresh` child gets. Local file writes only, no\n * registry: a minute is already generous, and `update` must not hang a turn. */\nconst REFRESH_TIMEOUT_MS = 60_000;\n\n/** One profile this update did not bring up to date, and why. */\nexport interface RefreshFailure {\n /** The profile's data dir. */\n dataDir: string;\n /**\n * Why it is not up to date, in the words of whoever decided that: the child's\n * own `error.message` when it printed a failure envelope, this pass's own\n * account when the child was never run or never got that far. Always present,\n * because a failure whose four causes render identically is the reason this\n * field exists.\n */\n reason: string;\n /** The command that converges THIS profile; see {@link manualFix}. */\n fix: string;\n}\n\n/** What the post-swap re-materialize did, per profile. */\nexport interface RefreshOutcome {\n /** Data dirs a refresh was run for, whether or not it succeeded. */\n profiles: string[];\n /**\n * Profiles this update did not bring up to date, each with its reason and the\n * manual command to finish it. Both halves land here: a refresh that ran and\n * did not report success, and one that was never run at all (no entry to\n * re-exec, a data dir that is not a directory).\n */\n failed: RefreshFailure[];\n /**\n * What a refresh that succeeded said the person must know (the child's\n * `data.notices`): a plugin left for a newer Claude Code, a status line the\n * migration took out. Printed as given, one line each.\n */\n notices: string[];\n /** A refreshed profile still carries an earlier release's settings install. */\n settingsInstallPending: boolean;\n /** Project installs (`install --project`) refreshed from their own directory. */\n projects: string[];\n /** Project installs whose refresh did not succeed, each with its reason and fix. */\n projectsFailed: { project: string; reason: string; fix: string }[];\n}\n\n/**\n * Re-materialize what the swap left stale, on the NEW binary: the plugin\n * files and skills carry this build's identity and instructions, and until\n * something rewrites them agents keep reading the previous release's.\n *\n * SPAWNED, NOT CALLED. This process is the OLD build; it cannot render the new\n * version's copies, and re-exec is the only way to reach code that can. The\n * child is the freshly installed entry (`launch`: npm's, on this Node, or the\n * runtime's new version, on the Node it pins), and what it runs is\n * `install --refresh` — a mode that converges existing surfaces and creates\n * none but the runtime and its launcher, which is the only kind of write an\n * unattended upgrade may make. It refreshes the invoking profile only: nothing\n * installed is baked per profile.\n *\n * NEVER FAILS THE UPDATE. The swap already happened and is the thing the\n * operator asked for. A refusal, a run with nothing to converge, a crash, a\n * timeout, or an older-binary \"unknown option --refresh\" all land here as a warn\n * naming the manual command, each with its own reason and fix: the child's\n * output is collected and its `error.message` reported.\n */\nasync function refreshProfiles(\n ctx: CommandContext,\n deps: UpdateDeps,\n launch: ChildLaunch | null,\n): Promise<{ refresh: RefreshOutcome; homeTail: string }> {\n const home = deps.homeDir ?? homedir();\n const dataDir = ctx.dataDir;\n const fix = manualFix(dataDir, home, dataDir);\n const nothing = (reason: string) => ({\n refresh: {\n profiles: [],\n failed: [{ dataDir, reason, fix }],\n notices: [],\n settingsInstallPending: false,\n projects: [],\n projectsFailed: [],\n },\n homeTail: '',\n });\n\n // Nothing safe to re-exec (see npmLaunch): report the profile as\n // unrefreshed rather than guessing, since a refresh that ran the OLD build\n // would report success while writing the bytes the update just left.\n if (launch === null)\n return nothing('This build has no entry the update could safely re-execute.');\n // The child would CREATE a data dir that is not there: `install --refresh`\n // converges surfaces rather than materializing them, but the process around it\n // mkdirs the tree for the update cache on its way out.\n if (!isExistingDir(dataDir)) return nothing('It is not a directory.');\n\n const profiles = [dataDir];\n const failed: RefreshFailure[] = [];\n const notices: string[] = [];\n let settingsInstallPending = false;\n const heard = (reported: Record<string, unknown> | null): void => {\n for (const notice of noticesOf(reported)) if (!notices.includes(notice)) notices.push(notice);\n const migration = reported?.migration as { state?: unknown } | undefined;\n if (migration?.state === 'pending' || migration?.state === 'blocked') {\n settingsInstallPending = true;\n }\n };\n const { outcome, tail: homeTail } = await refreshChild(launch, homedir(), dataDir, deps);\n // The child's exit code IS the verdict: `install --refresh` exits non-zero\n // when it refused or found nothing to converge, so a machine that never ran\n // `install` warns here instead of being told it was refreshed. The envelope\n // on the pipe is what turns that verdict into a reason.\n if (outcome.kind !== 'exit' || outcome.code !== 0) {\n failed.push({ dataDir, reason: refreshReason(outcome, homeTail), fix });\n } else {\n heard(envelopeData(homeTail));\n }\n\n // PROJECT INSTALLS, EACH FROM ITS OWN DIRECTORY. The child above runs from\n // home, where a `--project` install (Claude Code's local scope) is not\n // visible, so each one `install --project` recorded is refreshed where it\n // lives, as `--project`, since the child cannot tell one at home from the\n // user install. A directory that is gone, or that no longer holds one, is\n // forgotten.\n const projects: string[] = [];\n const projectsFailed: RefreshOutcome['projectsFailed'] = [];\n const recorded = (await loadRawConfig(dataDir).catch(() => null))?.install?.routerProjects ?? [];\n for (const project of recorded) {\n const forget = () => persistRouterProject(dataDir, project, false).catch(() => undefined);\n if (!isExistingDir(project) || !(await projectInstallAt(project, home, process.env))) {\n await forget();\n continue;\n }\n const { outcome, tail } = await refreshChild(launch, project, dataDir, deps, ['--project']);\n if (outcome.kind !== 'exit' || outcome.code !== 0) {\n projectsFailed.push({\n project,\n reason: refreshReason(outcome, tail),\n fix: `Run \\`tenjin install --project\\` in ${project}.`,\n });\n continue;\n }\n projects.push(project);\n heard(envelopeData(tail));\n }\n return {\n refresh: { profiles, failed, notices, settingsInstallPending, projects, projectsFailed },\n homeTail,\n };\n}\n\n/** The new build a refresh child runs: its Node and its entry script. */\ninterface ChildLaunch {\n node: string;\n entry: string;\n}\n\n/**\n * The npm branch's child: the version-free entry npm just replaced, on this\n * Node. Null when there is no argv to re-exec (an embedder, a stripped argv),\n * or only a path that names the version being replaced (see versionFreeEntry).\n */\nfunction npmLaunch(deps: UpdateDeps): ChildLaunch | null {\n const entry = versionFreeEntry(deps.refreshCommand ?? process.argv[1]);\n return entry === null ? null : { node: process.execPath, entry };\n}\n\n/**\n * One `install --refresh` child of the new build, from `cwd`, for `dataDir`:\n * how it ended and the end of what it printed. Spawned as `<node> <entry>` by\n * absolute path, never through a shell or a `.cmd`.\n *\n * A BOUNDED COLLECTOR, not the manager's live echo. npm's chatter is minutes\n * of progress a human wants to see; this child emits one envelope on a pipe,\n * and painting that JSON into the human's stderr is noise. It is still kept,\n * because the envelope is where the child says WHICH refusal this was.\n */\nasync function refreshChild(\n launch: ChildLaunch,\n cwd: string,\n dataDir: string,\n deps: UpdateDeps,\n flags: string[] = [],\n): Promise<{ outcome: SpawnResult; tail: string }> {\n let tail = '';\n const outcome = await (deps.spawnImpl ?? spawnCapture)(\n launch.node,\n [launch.entry, 'install', '--refresh', ...flags],\n {\n cwd,\n timeoutMs: REFRESH_TIMEOUT_MS,\n // TENJIN_DATA_DIR aims the child at this profile; the nudge opt-out is\n // what keeps it from touching any other file in there (lib/update-check).\n env: { TENJIN_DATA_DIR: dataDir, [NUDGE_OPT_OUT]: '1' },\n },\n (chunk) => {\n tail = (tail + chunk).slice(-REFRESH_TAIL_LIMIT);\n },\n );\n return { outcome, tail };\n}\n\n/** The `data` of the one success envelope the child printed, or null. */\nfunction envelopeData(output: string): Record<string, unknown> | null {\n const lines = output.split('\\n');\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n if (lines[i]?.trim() !== '{' && !lines[i]?.trim().startsWith('{\"')) continue;\n try {\n const parsed = JSON.parse(lines.slice(i).join('\\n')) as { ok?: unknown; data?: unknown };\n if (parsed?.ok === true && parsed.data !== null && typeof parsed.data === 'object') {\n return parsed.data as Record<string, unknown>;\n }\n } catch {\n continue;\n }\n }\n return null;\n}\n\n/**\n * The child's notices, each bounded and sanitized: the child is the build\n * this update just installed, but its text still reaches a terminal.\n */\nfunction noticesOf(data: Record<string, unknown> | null): string[] {\n const raw = data?.notices;\n if (!Array.isArray(raw)) return [];\n return raw\n .filter((n): n is string => typeof n === 'string')\n .map((n) => sanitizeForTerminal(n).trim().slice(0, REASON_LIMIT))\n .filter((n) => n.length > 0)\n .slice(0, 5);\n}\n\n/** How much of one refresh child's output is kept. It prints a single envelope,\n * not a build log, so this is headroom rather than a budget. */\nconst REFRESH_TAIL_LIMIT = 64_000;\n\n/** How much of a child's own message reaches the parent's report. Long enough\n * for every message `install --refresh` can produce, short enough that a child\n * which somehow printed prose cannot own the operator's terminal. */\nconst REASON_LIMIT = 300;\n\n/**\n * Why this profile is not up to date, preferring the child's own account.\n *\n * The exit code separates success from failure and nothing else, so the four\n * refusals `install --refresh` can reach would otherwise reach the operator as\n * one line that names none of them. The envelope on the pipe carries the\n * distinction; the outcome kind covers the deaths that never printed one.\n */\nfunction refreshReason(outcome: SpawnResult, output: string): string {\n const reported = envelopeMessage(output);\n if (reported !== undefined) return reported;\n if (outcome.kind === 'timeout') return `It did not finish in ${REFRESH_TIMEOUT_MS / 1000}s.`;\n if (outcome.kind === 'start-failed') return 'The refresh could not be started.';\n // An older binary rejecting `--refresh` is the expected shape here: commander\n // writes its own usage error and exits without an envelope of ours.\n return `The refresh exited ${outcome.code} without reporting a reason.`;\n}\n\n/**\n * The `error.message` out of the one failure envelope the child printed.\n *\n * Read from the LAST envelope because stdout carries exactly one while stderr\n * may carry notices ahead of it, and the two pipes are merged here.\n *\n * `writeJson` PRETTY-PRINTS, so the envelope spans many lines and its only line\n * starting with `{` is a bare `{` that does not parse alone. So scan backwards\n * for an opening line and parse from there to the end; a compact single line\n * still parses through the same path, which keeps an older child readable.\n *\n * Sanitized because this text is bound for a human's terminal and the child\n * relays paths and parse errors it did not author.\n */\nfunction envelopeMessage(output: string): string | undefined {\n const lines = output.split('\\n');\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const line = lines[i]?.trim();\n if (line === undefined || !line.startsWith('{')) continue;\n let parsed: { ok?: unknown; error?: { message?: unknown } };\n try {\n parsed = JSON.parse(lines.slice(i).join('\\n')) as typeof parsed;\n } catch {\n continue;\n }\n if (parsed?.ok !== false || typeof parsed.error?.message !== 'string') continue;\n const message = sanitizeForTerminal(parsed.error.message).trim();\n if (message.length > 0) return message.slice(0, REASON_LIMIT);\n }\n return undefined;\n}\n\n/** A path that already exists AND is a directory. Follows links on purpose: a\n * data dir behind a symlink is an ordinary machine layout, an absent one is not\n * a profile this command may create. */\nfunction isExistingDir(path: string): boolean {\n return statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n}\n\n/**\n * The manual command that converges THIS profile.\n *\n * A bare `tenjin install` resolves one data dir, so handing it to an operator\n * whose failed profile is another one — the case the per-profile loop exists\n * for — is advice that cannot repair the thing it names. The bare form is emitted only\n * for a dir that is the default under this home AND the one this invocation\n * itself resolved, so it is right under either reading of \"what a bare install\n * would do next\"; every other profile gets the explicit env prefix, which is\n * right unconditionally.\n */\nfunction manualFix(dataDir: string, home: string, invoking: string): string {\n const bare = isDefaultDataDir(dataDir, home) && resolve(dataDir) === resolve(invoking);\n const command = bare ? 'tenjin install' : `TENJIN_DATA_DIR=${dataDir} tenjin install`;\n return `Run \\`${command}\\` to bring the Claude Code plugin up to this version.`;\n}\n\n/**\n * The entry to re-exec, or null when there is none this code may trust.\n *\n * `process.argv[1]` is the path Node RESOLVED, symlinks and all (see\n * `classifyManager`, which reads the manager off exactly that property). Under\n * npm and bun that path carries no version, so after the swap it is already the\n * new build. Under pnpm it points into the virtual store, whose directory names\n * PIN A VERSION: `.../node_modules/.pnpm/tenjin-cli@<version>/node_modules/tenjin-cli/dist/index.js`.\n * Re-executing that is the worst available outcome — it runs the build the\n * update just replaced and reports a successful refresh over the previous\n * version's bytes, which is the exact staleness this whole command exists to\n * end (tenjin-agent#171).\n *\n * The virtual store keeps the version-free link one level out, beside `.pnpm`,\n * and the swap repoints it, so the same path with the store segments removed is\n * the new build. It is derived rather than assumed: if the result is not on\n * disk, this returns null and the caller warns instead of running anything.\n */\nexport function versionFreeEntry(entry: string | undefined): string | null {\n if (entry === undefined || entry.length === 0) return null;\n const segs = entry.split(sep);\n const store = segs.indexOf('.pnpm');\n if (store === -1) return segs.join(sep);\n // `.pnpm/<name>@<version>/node_modules/<name>/...`: everything from the second\n // `node_modules` on is the package's own path within the global tree.\n const inner = segs.indexOf('node_modules', store);\n if (inner === -1) return null;\n const derived = [...segs.slice(0, store), ...segs.slice(inner + 1)].join(sep);\n return existsSync(derived) ? derived : null;\n}\n\n/**\n * What the refresh actually did, as lines.\n *\n * It replaces \"New builds pick it up immediately\", which was true of the binary\n * and false of everything install had written — so it read as reassurance about\n * precisely the thing that was NOT handled (tenjin-agent#171).\n *\n * The successes are reported ALONGSIDE the failures rather than instead of them:\n * a machine where 8 of 12 profiles converged is not a machine where the refresh\n * did nothing, and one line per failure is what lets its own reason and its own\n * command travel with it.\n */\nfunction refreshLines(refresh: RefreshOutcome): string[] {\n const failedDirs = new Set(refresh.failed.map((f) => f.dataDir));\n const done = refresh.profiles.filter((p) => !failedDirs.has(p));\n if (refresh.failed.length === 0) {\n return [\n done.length > 1\n ? `Refreshed the Claude Code plugin for ${done.length} profiles: ${done.join(', ')}.`\n : `Refreshed the Claude Code plugin for ${done[0]}.`,\n ];\n }\n const total = done.length + refresh.failed.length;\n const lines =\n done.length > 0\n ? [\n `Refreshed the Claude Code plugin for ${done.length} of ${total} profiles: ${done.join(', ')}.`,\n ]\n : [];\n lines.push(`Could not refresh the Claude Code plugin for ${refresh.failed.length}:`);\n lines.push(...refresh.failed.map((f) => `- ${f.dataDir}: ${f.reason} ${f.fix}`));\n return lines;\n}\n\n/** The project installs the refresh reached, and the ones it could not. */\nfunction projectLines(refresh: RefreshOutcome): string[] {\n return [\n ...(refresh.projects.length > 0\n ? [`Refreshed the project install in ${refresh.projects.join(', ')}.`]\n : []),\n ...(refresh.projectsFailed.length > 0\n ? [\n `Could not refresh the project install in ${refresh.projectsFailed.length}:`,\n ...refresh.projectsFailed.map((p) => `- ${p.project}: ${p.reason} ${p.fix}`),\n ]\n : []),\n ];\n}\n\n/**\n * Default spawn: merged stdout+stderr chunks out, an outcome back, no shell.\n * Bounded by its own timer rather than Node's `timeout` option so that a kill\n * this code ordered is distinguishable from any other death by signal.\n */\nexport const spawnCapture: UpdateSpawn = (cmd, args, opts, onOutput) =>\n new Promise((res) => {\n let child;\n try {\n child = spawn(cmd, args, {\n stdio: ['ignore', 'pipe', 'pipe'],\n cwd: opts.cwd,\n // Layered onto this process's environment rather than replacing it: the\n // child is a Node CLI that needs PATH and HOME, and only the keys named\n // here are being decided.\n ...(opts.env !== undefined ? { env: { ...process.env, ...opts.env } } : {}),\n });\n } catch (cause) {\n // An argv or option Node rejects outright throws here; ENOENT arrives on\n // the 'error' event instead. Both mean the same thing to the caller.\n res({ kind: 'start-failed', cause });\n return;\n }\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill('SIGKILL');\n }, opts.timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => onOutput(chunk.toString()));\n child.stderr?.on('data', (chunk: Buffer) => onOutput(chunk.toString()));\n child.on('error', (cause) => {\n clearTimeout(timer);\n res({ kind: 'start-failed', cause });\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n res(timedOut ? { kind: 'timeout' } : { kind: 'exit', code: code ?? 1 });\n });\n });\n","import { envProxySupported, proxyVariable } from '../lib/env-proxy';\nimport { httpRequest, type HttpResponse } from '../lib/http';\nimport { isSameDeployment, PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { ROUTE_PAID_PATH } from './decision';\nimport { ROUTING_FEE_CEILING_ATOMIC, usd } from './fee';\n\nexport interface RouterCheck {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n required: boolean;\n detail: string;\n fix?: string;\n /** false only when the check could not run: rendered warn, never ok, never counted \"to act on\". */\n checked?: false;\n}\n\n/**\n * One cheap request to the paid route every routing call takes, in the server's\n * `warm` form, which asks for no routing decision: this probe signs nothing and\n * sends no prompt. The paywall answers a request with no payment 402 before it\n * reads the body, so a 402 is the route live and charging, and its quote is\n * read: one above `ROUTING_FEE_CEILING_ATOMIC` warns, since every routing call\n * is then skipped. A 200 is the route live with the fee off, and a 400 one with\n * no `warm` form refusing the body; a 404 is the route switched off, and a 5xx\n * a route erroring. `doctor` fails on it; `install` only warns.\n *\n * A refusal is blamed on the layer that sent it. A proxy, firewall or VPN that\n * blocks the host is not the origin asking for credentials, and on the\n * production base URL the fix is never \"set the base URL\", because that is the\n * one setting that is already right.\n */\nexport async function probeRouter(\n baseUrl: string,\n opts: {\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n env?: NodeJS.ProcessEnv;\n /** Test seam; production asks this Node whether it can use the proxy. */\n proxySupported?: boolean;\n },\n): Promise<RouterCheck> {\n const fail = (detail: string, fix: string): RouterCheck => ({\n name: 'router',\n status: 'fail',\n required: true,\n detail,\n fix,\n });\n // `TENJIN_BASE_URL` and `--base-url` reach here unvalidated. A throw would\n // fail an install that has already written everything else.\n let url: string;\n try {\n url = new URL(ROUTE_PAID_PATH, baseUrl).toString();\n } catch {\n return fail(\n `the base URL ${JSON.stringify(baseUrl)} is not a URL`,\n `Check TENJIN_BASE_URL, or set it with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n const host = new URL(url).host;\n const probe = await httpRequest(url, {\n method: 'POST',\n timeoutMs: opts.timeoutMs,\n blockRedirects: true,\n // A reachability check, not use: it must not count this machine as an install.\n anonymous: true,\n jsonBody: { schemaVersion: 1, warm: true },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n });\n const production = isSameDeployment(new URL(url).origin, PRODUCTION_ORIGIN);\n const checkBase = production\n ? 'Try again later.'\n : 'Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.';\n const env = opts.env ?? process.env;\n const network = networkFix(host, env, production, opts.proxySupported ?? envProxySupported());\n const credentials = proxyCredentialsFix(env);\n // Off production, a host that does not resolve or answer is most likely a\n // typo or a dev server that is not running, not a blocked network.\n const unreached = production ? network : checkBase;\n if (!probe.ok) {\n const t = probe.transport;\n if (t?.layer === 'proxy' && t.proxyStatus === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (t?.layer === 'proxy') {\n return fail(\n `a proxy refused the connection to ${host} (${t.proxyStatus}), so the router never answered`,\n unreached,\n );\n }\n if (t?.layer === 'dns') {\n return fail(`${host} did not resolve (${t.code}), so the router was not reached`, unreached);\n }\n if (t?.layer === 'tls') {\n return fail(\n `the TLS connection to ${host} failed (${t.code}). A proxy that inspects TLS causes this`,\n `If this network inspects TLS, set NODE_EXTRA_CA_CERTS to its CA certificate. ${unreached}`,\n );\n }\n if (t?.layer === 'connect') {\n return fail(`could not connect to ${host} (${t.code})`, unreached);\n }\n return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, unreached);\n }\n if (probe.status === 402) {\n // Loaded only for a 402: it reads x402 headers, which install's and the\n // status line's shared chunk must not carry (`dist-chunks.test.ts`).\n const { quoteOf } = await import('./routing-quote');\n const quoted = quoteOf((name) => probe.header(name));\n if (quoted === null) {\n return {\n name: 'router',\n status: 'warn',\n required: true,\n detail: `${url} asks for a payment this CLI cannot read, so routing calls are skipped`,\n fix: checkBase,\n };\n }\n if (quoted > ROUTING_FEE_CEILING_ATOMIC) {\n return {\n name: 'router',\n status: 'warn',\n required: true,\n detail: `${url} quotes $${usd(quoted)} a routing call, above this CLI’s current routing limit, so this fee is not paid`,\n fix: 'Paid routing resumes once the router quotes within that limit. Free routing still works.',\n };\n }\n return { name: 'router', status: 'ok', required: true, detail: `${url} is live` };\n }\n // 429 is the route's own rate limit: proof the router is there.\n if (probe.status === 200 || probe.status === 400 || probe.status === 429) {\n return { name: 'router', status: 'ok', required: true, detail: `${url} is live` };\n }\n if (probe.status === 404) {\n return fail(`the router is not enabled at ${url}`, checkBase);\n }\n if (probe.status === 407) {\n return fail(\n `a proxy between this machine and ${host} asked for its own credentials (407)`,\n credentials,\n );\n }\n if (probe.status === 401 || probe.status === 403) {\n if (!fromDeployment(probe)) {\n return fail(\n `${host} answered ${probe.status} without the headers a Tenjin deployment sends, so a proxy, firewall or VPN on the way most likely refused the request`,\n network,\n );\n }\n if (production) {\n return fail(`${url} refused this machine (${probe.status})`, checkBase);\n }\n return fail(\n `${url} is not a Tenjin router (it asked for credentials)`,\n `Set the router URL with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n if (probe.status >= 500) {\n return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);\n }\n return fail(\n `${url} answered ${probe.status}, which a Tenjin router does not`,\n 'Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`).',\n );\n}\n\n/**\n * Did the origin send this, rather than something in front of it? Every Vercel\n * response carries `x-vercel-id` (its own access protection included), and\n * every Tenjin API route adds `x-request-id`. A block page from a proxy,\n * firewall or VPN carries neither.\n */\nfunction fromDeployment(probe: HttpResponse): boolean {\n return probe.header('x-vercel-id') !== undefined || probe.header('x-request-id') !== undefined;\n}\n\nfunction networkFix(\n host: string,\n env: NodeJS.ProcessEnv,\n production: boolean,\n proxySupported: boolean,\n): string {\n const proxy = proxyVariable(env);\n const config = production ? \" Tenjin's own config is correct and needs no change.\" : '';\n if (proxy !== undefined && !proxySupported) {\n return `This shell sets ${proxy}, but Node ${process.versions.node} cannot send Tenjin's requests through it. Upgrade to Node 24.14 or newer, or run from a network that reaches ${host} directly.${config}`;\n }\n const via = proxy !== undefined ? ` (this shell sets ${proxy})` : '';\n return `Allow ${host} through your proxy, firewall or VPN${via}, or run from a network that reaches it.${config}`;\n}\n\nfunction proxyCredentialsFix(env: NodeJS.ProcessEnv): string {\n const proxy = proxyVariable(env) ?? 'HTTPS_PROXY';\n return `Put the proxy's credentials in ${proxy} (\\`http://user:password@proxy:port\\`), then try again.`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAAA,WAAU,QAAAC,aAAY;AAC/B,SAAS,WAAAC,gBAAe;AACxB,SAAS,WAAAC,UAAS,YAAY,QAAAC,OAAM,UAAU,WAAAC,UAAS,OAAAC,YAAW;AAClE,SAAS,iBAAAC,sBAAqB;;;ACH9B,SAAS,iBAAiB;AAC1B,SAAS,WAAW,MAAM,SAAS,IAAI,aAAa;AAEpD,SAAS,SAAS,YAAY;AAQ9B,IAAM,sBAAsB,CAAC,cAAc,iBAAiB,gBAAgB;AAS5E,IAAM,sBAAmE;AAAA,EACvE,cAAc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AAG,YAAY,KAAK,EAAE,MAAM;AAAA,IAC5B,GAAG,eAAe,KAAK,EAAE,SAAS;AAAA,IAClC,GAAG;AAAA,EACL;AACF;AAGA,SAASG,cACP,KACA,QACA,QACA,WACA,IACA,MACU;AACV,QAAM,SAAS;AAAA,IACb,GAAG,aAAa,KAAK,IAAI,IAAI;AAAA,IAC7B,GAAG,YAAY,KAAK,MAAM;AAAA,IAC1B,GAAG,YAAY,KAAK,MAAM;AAAA,IAC1B,GAAG,eAAe,KAAK,SAAS;AAAA,EAClC;AACA,QAAM,OACJ,OAAO,UAAU,WACb,MAAM,IAAI,IAAI,UAAU,wDAAwD,IAChF,OAAO,UAAU,aACf,MAAM,IAAI,IAAI,UAAU,+DAA+D,IACvF,GAAG,MAAM,IAAI,IAAI,SAAS,QAAG,CAAC,iCAAiC,OAAO,MAAM,SAAS;AAC7F,SAAO,CAAC,MAAM,GAAG,MAAM;AACzB;","names":["readFile","stat","homedir","dirname","join","resolve","sep","fileURLToPath","lines","readFile","join","readFile","join","readFile","join","readFile","stat","dirname","join","fileURLToPath","rm","updated","runtimeBuild","rm","step","outcome","lines","join","update","stat","readFile","dirname","fileURLToPath","join","readFile","homedir","dirname","fileURLToPath","rt","refreshLines","readFile","join","sep","resolve","stat"]}
@@ -1,13 +1,13 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  hashTypedData
4
- } from "./chunk-FNBGRKS6.js";
4
+ } from "./chunk-7V25UAQO.js";
5
5
  import {
6
6
  getAddress,
7
7
  keccak256,
8
8
  toBytes,
9
9
  toHex
10
- } from "./chunk-3AKH7ODX.js";
10
+ } from "./chunk-INSIW65E.js";
11
11
 
12
12
  // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-EKCH75YB.mjs
13
13
  var EIP155_NETWORK_REGEX = /^eip155:(\d+)$/;
@@ -156,4 +156,4 @@ export {
156
156
  computeChannelId,
157
157
  getBatchSettlementEip712Domain
158
158
  };
159
- //# sourceMappingURL=chunk-HWZO6HYZ.js.map
159
+ //# sourceMappingURL=chunk-6QMDUDF2.js.map
@@ -189,7 +189,7 @@ import {
189
189
  validate,
190
190
  validate2,
191
191
  withResolvers
192
- } from "./chunk-3AKH7ODX.js";
192
+ } from "./chunk-INSIW65E.js";
193
193
  import {
194
194
  keccak_256
195
195
  } from "./chunk-CZJOMUBP.js";
@@ -11413,4 +11413,4 @@ export {
11413
11413
  serializeCompactSignature,
11414
11414
  signatureToCompactSignature
11415
11415
  };
11416
- //# sourceMappingURL=chunk-FNBGRKS6.js.map
11416
+ //# sourceMappingURL=chunk-7V25UAQO.js.map