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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/README.md +65 -116
  2. package/dist/{_esm-CE7KNONL.js → _esm-RLLC72MS.js} +127 -131
  3. package/dist/alive-MROUMFH3.js +38 -0
  4. package/dist/auto-update-OPWMRZLS.js +22 -0
  5. package/dist/{ccip-7RMRLAGV.js → ccip-DHDFKTQV.js} +2 -2
  6. package/dist/chunk-2GNOFONN.js +560 -0
  7. package/dist/chunk-2GNOFONN.js.map +1 -0
  8. package/dist/{chunk-TTNESUPQ.js → chunk-2GP3HRYK.js} +2120 -193
  9. package/dist/chunk-2GP3HRYK.js.map +1 -0
  10. package/dist/chunk-3623BLPV.js +184 -0
  11. package/dist/chunk-3623BLPV.js.map +1 -0
  12. package/dist/chunk-3AIHRXKO.js +72 -0
  13. package/dist/chunk-3AIHRXKO.js.map +1 -0
  14. package/dist/chunk-3DIL66VX.js +120 -0
  15. package/dist/chunk-3DIL66VX.js.map +1 -0
  16. package/dist/{chunk-S4SAZ7OD.js → chunk-3FMZGI7I.js} +12 -2
  17. package/dist/{chunk-S4SAZ7OD.js.map → chunk-3FMZGI7I.js.map} +1 -1
  18. package/dist/chunk-3UCIG4TG.js +65 -0
  19. package/dist/chunk-3UCIG4TG.js.map +1 -0
  20. package/dist/{chunk-LFZJM56J.js → chunk-445VQTVM.js} +3 -3
  21. package/dist/{chunk-A36LQPHV.js → chunk-4LMUQMBH.js} +1 -1
  22. package/dist/{chunk-A36LQPHV.js.map → chunk-4LMUQMBH.js.map} +1 -1
  23. package/dist/{chunk-RAULEAZ6.js → chunk-4USCZ2NI.js} +3 -3
  24. package/dist/chunk-62KNUYWD.js +111 -0
  25. package/dist/chunk-62KNUYWD.js.map +1 -0
  26. package/dist/{chunk-POUWHWID.js → chunk-6CMM6YCB.js} +3 -3
  27. package/dist/{chunk-POUWHWID.js.map → chunk-6CMM6YCB.js.map} +1 -1
  28. package/dist/chunk-7WEQQJLG.js +68 -0
  29. package/dist/chunk-7WEQQJLG.js.map +1 -0
  30. package/dist/{chunk-3O2BQIF6.js → chunk-AD226HDR.js} +344 -534
  31. package/dist/chunk-AD226HDR.js.map +1 -0
  32. package/dist/chunk-ADV4LDTB.js +106 -0
  33. package/dist/chunk-ADV4LDTB.js.map +1 -0
  34. package/dist/{chunk-AWFUPKTM.js → chunk-AV5NZMYO.js} +15 -7
  35. package/dist/{chunk-AWFUPKTM.js.map → chunk-AV5NZMYO.js.map} +1 -1
  36. package/dist/chunk-B7EM4GGF.js +198 -0
  37. package/dist/chunk-B7EM4GGF.js.map +1 -0
  38. package/dist/chunk-BFDQ4WNW.js +119 -0
  39. package/dist/chunk-BFDQ4WNW.js.map +1 -0
  40. package/dist/{chunk-OSYTBCUC.js → chunk-BI673VEJ.js} +531 -503
  41. package/dist/chunk-BI673VEJ.js.map +1 -0
  42. package/dist/chunk-CEXSOI5R.js +808 -0
  43. package/dist/chunk-CEXSOI5R.js.map +1 -0
  44. package/dist/{chunk-OK2TDZQU.js → chunk-CISYM4EO.js} +9 -7
  45. package/dist/chunk-CISYM4EO.js.map +1 -0
  46. package/dist/{chunk-VFMQTSXG.js → chunk-D3ZURCG7.js} +3 -3
  47. package/dist/chunk-D5TOQSO4.js +474 -0
  48. package/dist/chunk-D5TOQSO4.js.map +1 -0
  49. package/dist/{chunk-P7LABKCW.js → chunk-DOQGNFHM.js} +33 -2
  50. package/dist/{chunk-P7LABKCW.js.map → chunk-DOQGNFHM.js.map} +1 -1
  51. package/dist/{chunk-QUVVWYJW.js → chunk-DRDUIZIA.js} +11 -9
  52. package/dist/{chunk-QUVVWYJW.js.map → chunk-DRDUIZIA.js.map} +1 -1
  53. package/dist/{chunk-O2FRQ2L2.js → chunk-DW4YTVR3.js} +5 -65
  54. package/dist/chunk-DW4YTVR3.js.map +1 -0
  55. package/dist/chunk-E7LGOMH6.js +449 -0
  56. package/dist/chunk-E7LGOMH6.js.map +1 -0
  57. package/dist/chunk-E7SW44LM.js +138 -0
  58. package/dist/chunk-E7SW44LM.js.map +1 -0
  59. package/dist/chunk-EDJWHDDL.js +33 -0
  60. package/dist/chunk-EDJWHDDL.js.map +1 -0
  61. package/dist/chunk-F3ED5WTR.js +13 -0
  62. package/dist/chunk-F3ED5WTR.js.map +1 -0
  63. package/dist/chunk-G75OPGAK.js +111 -0
  64. package/dist/chunk-G75OPGAK.js.map +1 -0
  65. package/dist/{chunk-YFQOA5AU.js → chunk-GAKUQHKA.js} +13 -17
  66. package/dist/{chunk-YFQOA5AU.js.map → chunk-GAKUQHKA.js.map} +1 -1
  67. package/dist/{chunk-PAYV4XUA.js → chunk-HDPUXS3Z.js} +20 -49
  68. package/dist/chunk-HDPUXS3Z.js.map +1 -0
  69. package/dist/{chunk-ORWL5BSN.js → chunk-HGZEPQUT.js} +2 -2
  70. package/dist/{chunk-HPWO4O6S.js → chunk-HREHWL32.js} +4 -4
  71. package/dist/{chunk-HPWO4O6S.js.map → chunk-HREHWL32.js.map} +1 -1
  72. package/dist/{chunk-VZGAONSJ.js → chunk-I5TDIUKM.js} +16 -35
  73. package/dist/chunk-I5TDIUKM.js.map +1 -0
  74. package/dist/{chunk-7QKHZQKW.js → chunk-IADZOXKN.js} +39 -6
  75. package/dist/chunk-IADZOXKN.js.map +1 -0
  76. package/dist/{chunk-U6YQ6FRI.js → chunk-IDTRSAHE.js} +32 -12
  77. package/dist/chunk-IDTRSAHE.js.map +1 -0
  78. package/dist/{chunk-SPAVAYSW.js → chunk-JEVQ5LKO.js} +7 -5
  79. package/dist/{chunk-SPAVAYSW.js.map → chunk-JEVQ5LKO.js.map} +1 -1
  80. package/dist/{chunk-EBVIKMCH.js → chunk-JKKAIPTU.js} +2 -2
  81. package/dist/chunk-JNJWBTU2.js +3497 -0
  82. package/dist/chunk-JNJWBTU2.js.map +1 -0
  83. package/dist/{chunk-TTBKWWTV.js → chunk-JRZBBPO6.js} +390 -146
  84. package/dist/chunk-JRZBBPO6.js.map +1 -0
  85. package/dist/{chunk-WVUSXNIE.js → chunk-MPZUYCAP.js} +9 -2
  86. package/dist/{chunk-WVUSXNIE.js.map → chunk-MPZUYCAP.js.map} +1 -1
  87. package/dist/{chunk-SJLTEINJ.js → chunk-OJNTCYQQ.js} +17 -1
  88. package/dist/chunk-OJNTCYQQ.js.map +1 -0
  89. package/dist/{chunk-IOODYAXL.js → chunk-OTWLERSW.js} +25 -6
  90. package/dist/chunk-OTWLERSW.js.map +1 -0
  91. package/dist/{chunk-AWQPGIR6.js → chunk-PJNENX2A.js} +1535 -422
  92. package/dist/chunk-PJNENX2A.js.map +1 -0
  93. package/dist/{chunk-KHE6L6TD.js → chunk-PKHI276N.js} +97 -11
  94. package/dist/chunk-PKHI276N.js.map +1 -0
  95. package/dist/{chunk-YHKXNYTB.js → chunk-QF3LSMGS.js} +2 -2
  96. package/dist/chunk-QXP3Z3JN.js +131 -0
  97. package/dist/chunk-QXP3Z3JN.js.map +1 -0
  98. package/dist/{chunk-XZKD7DIF.js → chunk-RL5UUDT4.js} +3 -3
  99. package/dist/{chunk-XZKD7DIF.js.map → chunk-RL5UUDT4.js.map} +1 -1
  100. package/dist/chunk-SFASB5FL.js +69 -0
  101. package/dist/chunk-SFASB5FL.js.map +1 -0
  102. package/dist/{chunk-WO5BJNIB.js → chunk-SNNSAGMT.js} +7273 -2741
  103. package/dist/chunk-SNNSAGMT.js.map +1 -0
  104. package/dist/{chunk-NZIP4PA2.js → chunk-SO3XRZPX.js} +3 -3
  105. package/dist/chunk-SYOS5CAC.js +176 -0
  106. package/dist/chunk-SYOS5CAC.js.map +1 -0
  107. package/dist/chunk-TAW4UFFF.js +293 -0
  108. package/dist/chunk-TAW4UFFF.js.map +1 -0
  109. package/dist/chunk-TF5HCP33.js +271 -0
  110. package/dist/chunk-TF5HCP33.js.map +1 -0
  111. package/dist/{chunk-AKWGE6JQ.js → chunk-UUGOUOVT.js} +37 -2
  112. package/dist/chunk-UUGOUOVT.js.map +1 -0
  113. package/dist/{chunk-AEG2PXBP.js → chunk-V2LQLN5H.js} +7 -7
  114. package/dist/{chunk-KYFZTGMC.js → chunk-VJUVFZ2D.js} +5 -3
  115. package/dist/{chunk-KYFZTGMC.js.map → chunk-VJUVFZ2D.js.map} +1 -1
  116. package/dist/{chunk-JMM6YE7J.js → chunk-VOZA6O7K.js} +708 -709
  117. package/dist/chunk-VOZA6O7K.js.map +1 -0
  118. package/dist/{chunk-5LJCEMFD.js → chunk-VUGQTZ2L.js} +209 -77
  119. package/dist/chunk-VUGQTZ2L.js.map +1 -0
  120. package/dist/chunk-WOM257PW.js +393 -0
  121. package/dist/chunk-WOM257PW.js.map +1 -0
  122. package/dist/chunk-WYXUQGOL.js +191 -0
  123. package/dist/chunk-WYXUQGOL.js.map +1 -0
  124. package/dist/chunk-X5ZBP3IY.js +97 -0
  125. package/dist/chunk-X5ZBP3IY.js.map +1 -0
  126. package/dist/chunk-XQJXNMSB.js +23 -0
  127. package/dist/chunk-XQJXNMSB.js.map +1 -0
  128. package/dist/chunk-Y527D4TV.js +56 -0
  129. package/dist/chunk-Y527D4TV.js.map +1 -0
  130. package/dist/{chunk-VUFAK2LW.js → chunk-YUY4SAGM.js} +17 -2
  131. package/dist/chunk-YUY4SAGM.js.map +1 -0
  132. package/dist/clack-EZ7TDWQU.js +19 -0
  133. package/dist/claude-cli-2YKABJJZ.js +31 -0
  134. package/dist/{cli-O5SN7ZJ4.js → cli-FB4LOA5A.js} +221 -68
  135. package/dist/{cli-O5SN7ZJ4.js.map → cli-FB4LOA5A.js.map} +1 -1
  136. package/dist/codex-event-TYVES3UX.js +16 -0
  137. package/dist/codex-host-WW4H2SKT.js +29 -0
  138. package/dist/codex-install-2C623HPW.js +393 -0
  139. package/dist/codex-install-2C623HPW.js.map +1 -0
  140. package/dist/{config-OJQI27LT.js → config-HOVJFEKD.js} +25 -15
  141. package/dist/doctor-NKU4V5OV.js +1312 -0
  142. package/dist/doctor-NKU4V5OV.js.map +1 -0
  143. package/dist/{env-proxy-XL4P73MZ.js → env-proxy-R6ZMLQTT.js} +6 -2
  144. package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js → ethersCompat-Df4a6QIZ-X6YZWAML.js} +3 -3
  145. package/dist/{fund-WEV6DMTD.js → fund-WEBHTZGN.js} +38 -30
  146. package/dist/{fund-WEV6DMTD.js.map → fund-WEBHTZGN.js.map} +1 -1
  147. package/dist/hook-command-ZA2PNKS6.js +44 -0
  148. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  149. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +3 -2
  150. package/dist/hosts/claude/tenjin/hooks/hooks.json +4 -1
  151. package/dist/hosts/claude/tenjin/hooks/register.tsx +589 -0
  152. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +82 -0
  153. package/dist/hosts/claude/tenjin/types/index.d.ts +41 -0
  154. package/dist/hosts/codex/.agents/plugins/marketplace.json +20 -0
  155. package/dist/hosts/codex/tenjin/.codex-plugin/plugin.json +16 -0
  156. package/dist/hosts/codex/tenjin/.mcp.json +15 -0
  157. package/dist/hosts/codex/tenjin/hooks/hooks.json +98 -0
  158. package/dist/hosts-AV5MHBAU.js +38 -0
  159. package/dist/index.js +28 -8
  160. package/dist/index.js.map +1 -1
  161. package/dist/install-PT4EZS4R.js +100 -0
  162. package/dist/{install-identity-WHPNMNMQ.js → install-identity-5A4OE6YC.js} +13 -8
  163. package/dist/install-wallet-SAAPKB73.js +281 -0
  164. package/dist/install-wallet-SAAPKB73.js.map +1 -0
  165. package/dist/{mcp-QML7ZMPH.js → mcp-HAWKCTPQ.js} +909 -208
  166. package/dist/mcp-HAWKCTPQ.js.map +1 -0
  167. package/dist/{mine.wasm-6PIT3DK6.js → mine.wasm-QFAHIFPY.js} +2 -2
  168. package/dist/{mine.wasm-6PIT3DK6.js.map → mine.wasm-QFAHIFPY.js.map} +1 -1
  169. package/dist/{package-LGKYOEPV.js → package-SR2WB6MK.js} +4 -2
  170. package/dist/passphrase-IFTDS3CU.js +44 -0
  171. package/dist/{paths-POPTXJO6.js → paths-XCSAKISU.js} +10 -2
  172. package/dist/pay-OXC3WKYV.js +55 -0
  173. package/dist/pay-OXC3WKYV.js.map +1 -0
  174. package/dist/{payments-C44QUFXU.js → payments-3KHMP2MG.js} +18 -13
  175. package/dist/{payments-C44QUFXU.js.map → payments-3KHMP2MG.js.map} +1 -1
  176. package/dist/plugin-registration-N3GRIZVM.js +67 -0
  177. package/dist/plugin-registration-N3GRIZVM.js.map +1 -0
  178. package/dist/{redact-6W23GGJC.js → redact-D7ASVWKL.js} +2 -2
  179. package/dist/redact-D7ASVWKL.js.map +1 -0
  180. package/dist/runtime-UVNUA3AS.js +1203 -0
  181. package/dist/runtime-UVNUA3AS.js.map +1 -0
  182. package/dist/runtime-fetch-EKFRNR6Z.js +20 -0
  183. package/dist/runtime-fetch-EKFRNR6Z.js.map +1 -0
  184. package/dist/runtime-layout-BDWZG2TQ.js +25 -0
  185. package/dist/runtime-layout-BDWZG2TQ.js.map +1 -0
  186. package/dist/{send-KVJX4XIR.js → send-HMKJLT34.js} +26 -18
  187. package/dist/{send-KVJX4XIR.js.map → send-HMKJLT34.js.map} +1 -1
  188. package/dist/{status-S7C3WMSH.js → status-RWXIIWYS.js} +57 -22
  189. package/dist/status-RWXIIWYS.js.map +1 -0
  190. package/dist/{status-line-YR2T5HC4.js → status-line-77XYZP7E.js} +13 -8
  191. package/dist/{status-line-YR2T5HC4.js.map → status-line-77XYZP7E.js.map} +1 -1
  192. package/dist/uninstall-D5G67UJH.js +480 -0
  193. package/dist/uninstall-D5G67UJH.js.map +1 -0
  194. package/dist/update-LRNOEGSB.js +53 -0
  195. package/dist/update-LRNOEGSB.js.map +1 -0
  196. package/dist/{usdc-JK4RRFFQ.js → usdc-D6X7EIQ2.js} +7 -8
  197. package/dist/usdc-D6X7EIQ2.js.map +1 -0
  198. package/dist/{viemAdapter-By13KInL-X2VY6CY3.js → viemAdapter-By13KInL-RL742ETX.js} +3 -3
  199. package/dist/viemAdapter-By13KInL-RL742ETX.js.map +1 -0
  200. package/dist/wallet-XFYC27BR.js +55 -0
  201. package/dist/wallet-XFYC27BR.js.map +1 -0
  202. package/dist/wallet-kdf-worker.mjs +8 -8
  203. package/docs/agent-permissions.md +56 -22
  204. package/docs/safety-model.md +1 -1
  205. package/docs/troubleshooting.md +72 -1
  206. package/package.json +14 -1
  207. package/dist/alive-3J3CHOQP.js +0 -21
  208. package/dist/ccip-NLCSCHKI.js +0 -19
  209. package/dist/chunk-3O2BQIF6.js.map +0 -1
  210. package/dist/chunk-5IEP5EGE.js +0 -5332
  211. package/dist/chunk-5IEP5EGE.js.map +0 -1
  212. package/dist/chunk-5LJCEMFD.js.map +0 -1
  213. package/dist/chunk-6W5GYG3W.js +0 -128
  214. package/dist/chunk-6W5GYG3W.js.map +0 -1
  215. package/dist/chunk-7EKYXMUO.js +0 -7536
  216. package/dist/chunk-7EKYXMUO.js.map +0 -1
  217. package/dist/chunk-7QKHZQKW.js.map +0 -1
  218. package/dist/chunk-AKWGE6JQ.js.map +0 -1
  219. package/dist/chunk-AWQPGIR6.js.map +0 -1
  220. package/dist/chunk-EGELTSPU.js +0 -2865
  221. package/dist/chunk-EGELTSPU.js.map +0 -1
  222. package/dist/chunk-EL56RW2J.js +0 -7611
  223. package/dist/chunk-EL56RW2J.js.map +0 -1
  224. package/dist/chunk-HE2MS4QO.js +0 -256
  225. package/dist/chunk-HE2MS4QO.js.map +0 -1
  226. package/dist/chunk-IOODYAXL.js.map +0 -1
  227. package/dist/chunk-JMM6YE7J.js.map +0 -1
  228. package/dist/chunk-KHE6L6TD.js.map +0 -1
  229. package/dist/chunk-N35E6CM2.js +0 -1185
  230. package/dist/chunk-N35E6CM2.js.map +0 -1
  231. package/dist/chunk-O2FRQ2L2.js.map +0 -1
  232. package/dist/chunk-OK2TDZQU.js.map +0 -1
  233. package/dist/chunk-OSYTBCUC.js.map +0 -1
  234. package/dist/chunk-PAYV4XUA.js.map +0 -1
  235. package/dist/chunk-SJLTEINJ.js.map +0 -1
  236. package/dist/chunk-TTBKWWTV.js.map +0 -1
  237. package/dist/chunk-TTNESUPQ.js.map +0 -1
  238. package/dist/chunk-U6YQ6FRI.js.map +0 -1
  239. package/dist/chunk-VUFAK2LW.js.map +0 -1
  240. package/dist/chunk-VZGAONSJ.js.map +0 -1
  241. package/dist/chunk-WO5BJNIB.js.map +0 -1
  242. package/dist/doctor-IQQJHGGM.js +0 -590
  243. package/dist/doctor-IQQJHGGM.js.map +0 -1
  244. package/dist/hook-command-D2P3ILRV.js +0 -32
  245. package/dist/install-TUCRF32I.js +0 -60
  246. package/dist/install-wallet-MA27FTQ5.js +0 -113
  247. package/dist/install-wallet-MA27FTQ5.js.map +0 -1
  248. package/dist/mcp-QML7ZMPH.js.map +0 -1
  249. package/dist/pay-2C2UBBXJ.js +0 -51
  250. package/dist/status-S7C3WMSH.js.map +0 -1
  251. package/dist/uninstall-HY6LKIIT.js +0 -149
  252. package/dist/uninstall-HY6LKIIT.js.map +0 -1
  253. package/dist/update-OJV22LR3.js +0 -36
  254. package/dist/wallet-PD2IMZDU.js +0 -39
  255. /package/dist/{_esm-CE7KNONL.js.map → _esm-RLLC72MS.js.map} +0 -0
  256. /package/dist/{alive-3J3CHOQP.js.map → alive-MROUMFH3.js.map} +0 -0
  257. /package/dist/{ccip-7RMRLAGV.js.map → auto-update-OPWMRZLS.js.map} +0 -0
  258. /package/dist/{ccip-NLCSCHKI.js.map → ccip-DHDFKTQV.js.map} +0 -0
  259. /package/dist/{chunk-LFZJM56J.js.map → chunk-445VQTVM.js.map} +0 -0
  260. /package/dist/{chunk-RAULEAZ6.js.map → chunk-4USCZ2NI.js.map} +0 -0
  261. /package/dist/{chunk-VFMQTSXG.js.map → chunk-D3ZURCG7.js.map} +0 -0
  262. /package/dist/{chunk-ORWL5BSN.js.map → chunk-HGZEPQUT.js.map} +0 -0
  263. /package/dist/{chunk-EBVIKMCH.js.map → chunk-JKKAIPTU.js.map} +0 -0
  264. /package/dist/{chunk-YHKXNYTB.js.map → chunk-QF3LSMGS.js.map} +0 -0
  265. /package/dist/{chunk-NZIP4PA2.js.map → chunk-SO3XRZPX.js.map} +0 -0
  266. /package/dist/{chunk-AEG2PXBP.js.map → chunk-V2LQLN5H.js.map} +0 -0
  267. /package/dist/{config-OJQI27LT.js.map → clack-EZ7TDWQU.js.map} +0 -0
  268. /package/dist/{env-proxy-XL4P73MZ.js.map → claude-cli-2YKABJJZ.js.map} +0 -0
  269. /package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js.map → codex-event-TYVES3UX.js.map} +0 -0
  270. /package/dist/{hook-command-D2P3ILRV.js.map → codex-host-WW4H2SKT.js.map} +0 -0
  271. /package/dist/{install-TUCRF32I.js.map → config-HOVJFEKD.js.map} +0 -0
  272. /package/dist/{install-identity-WHPNMNMQ.js.map → env-proxy-R6ZMLQTT.js.map} +0 -0
  273. /package/dist/{package-LGKYOEPV.js.map → ethersCompat-Df4a6QIZ-X6YZWAML.js.map} +0 -0
  274. /package/dist/{paths-POPTXJO6.js.map → hook-command-ZA2PNKS6.js.map} +0 -0
  275. /package/dist/{pay-2C2UBBXJ.js.map → hosts-AV5MHBAU.js.map} +0 -0
  276. /package/dist/{redact-6W23GGJC.js.map → install-PT4EZS4R.js.map} +0 -0
  277. /package/dist/{update-OJV22LR3.js.map → install-identity-5A4OE6YC.js.map} +0 -0
  278. /package/dist/{usdc-JK4RRFFQ.js.map → package-SR2WB6MK.js.map} +0 -0
  279. /package/dist/{viemAdapter-By13KInL-X2VY6CY3.js.map → passphrase-IFTDS3CU.js.map} +0 -0
  280. /package/dist/{wallet-PD2IMZDU.js.map → paths-XCSAKISU.js.map} +0 -0
@@ -0,0 +1,271 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ HARNESSES
4
+ } from "./chunk-MPZUYCAP.js";
5
+ import {
6
+ writeFileAtomic
7
+ } from "./chunk-7WEQQJLG.js";
8
+ import {
9
+ CliError
10
+ } from "./chunk-3UCIG4TG.js";
11
+
12
+ // src/router/hosts.ts
13
+ import { readFile, rm } from "node:fs/promises";
14
+ import { homedir } from "node:os";
15
+ import { join } from "node:path";
16
+ var HOSTS_FILE = "installed-hosts.json";
17
+ var LABEL = { claude: "Claude Code", codex: "Codex" };
18
+ async function readInstalledHosts(dataDir) {
19
+ let raw;
20
+ try {
21
+ raw = await readFile(join(dataDir, HOSTS_FILE), "utf8");
22
+ } catch {
23
+ return null;
24
+ }
25
+ try {
26
+ const hosts = JSON.parse(raw).hosts;
27
+ if (!Array.isArray(hosts)) return null;
28
+ return HARNESSES.filter((h) => hosts.includes(h));
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+ async function writeHosts(dataDir, hosts) {
34
+ const path = join(dataDir, HOSTS_FILE);
35
+ if (hosts.length === 0) {
36
+ await rm(path, { force: true });
37
+ return;
38
+ }
39
+ await writeFileAtomic(path, `${JSON.stringify({ hosts }, null, 2)}
40
+ `, { mode: 384 });
41
+ }
42
+ async function claudePluginPresent(env = process.env, home = homedir()) {
43
+ const [{ listedInClaudeFiles }, { folderState }] = await Promise.all([
44
+ import("./doctor-NKU4V5OV.js"),
45
+ import("./plugin-registration-N3GRIZVM.js")
46
+ ]);
47
+ if (await listedInClaudeFiles(env, home)) return true;
48
+ return (await folderState("user", env, home, home)).state === "ours";
49
+ }
50
+ async function recordInstalledHost(dataDir, host, present = () => claudePluginPresent()) {
51
+ const recorded = await readInstalledHosts(dataDir);
52
+ const hosts = recorded ?? (host !== "claude" && await present().catch(() => false) ? ["claude"] : []);
53
+ if (hosts.includes(host)) return;
54
+ await writeHosts(
55
+ dataDir,
56
+ HARNESSES.filter((h) => h === host || hosts.includes(h))
57
+ );
58
+ }
59
+ async function forgetInstalledHost(dataDir, host) {
60
+ const hosts = await readInstalledHosts(dataDir);
61
+ if (hosts === null || !hosts.includes(host)) return;
62
+ await writeHosts(
63
+ dataDir,
64
+ hosts.filter((h) => h !== host)
65
+ );
66
+ }
67
+ function agentHost(env) {
68
+ const set = (v) => typeof v === "string" && v.trim().length > 0;
69
+ if (set(env.CLAUDECODE) || set(env.CLAUDE_CODE_SESSION_ID) || set(env.CLAUDE_CODE_EXECPATH)) {
70
+ return "claude";
71
+ }
72
+ if (set(env.CODEX_SESSION_ID)) return "codex";
73
+ return void 0;
74
+ }
75
+ async function detectHosts(env) {
76
+ const [{ readClaudeCode }, { codexVersion }] = await Promise.all([
77
+ import("./claude-cli-2YKABJJZ.js"),
78
+ import("./codex-host-WW4H2SKT.js")
79
+ ]);
80
+ const [claude, codex] = await Promise.all([
81
+ readClaudeCode(env, process.cwd()).then(
82
+ (s) => s.version !== null,
83
+ () => false
84
+ ),
85
+ codexVersion().then(
86
+ (v) => v !== null,
87
+ () => false
88
+ )
89
+ ]);
90
+ return HARNESSES.filter((h) => h === "claude" ? claude : codex);
91
+ }
92
+ async function askHosts(found) {
93
+ const { selectMany } = await import("./clack-EZ7TDWQU.js");
94
+ return selectMany({
95
+ message: "Set up Tenjin for which agents?",
96
+ choices: found.map((h) => ({ value: h, label: LABEL[h] })),
97
+ initialValues: found
98
+ });
99
+ }
100
+ async function installHosts(args, ctx, deps = {}) {
101
+ if (args.harness !== void 0) return [args.harness];
102
+ if (args.refresh === true || args.project === true) return ["claude"];
103
+ const env = deps.env ?? process.env;
104
+ const agent = agentHost(env);
105
+ if (agent !== void 0) return [agent];
106
+ const found = await (deps.detect ?? detectHosts)(env);
107
+ if (found.length === 0) return ["claude"];
108
+ if (found.length === 1 || args.yes === true) return found;
109
+ const interactive = ctx.flags.json !== true && (deps.isInteractive ?? (ctx.io.isTTY && Boolean(process.stdin.isTTY)));
110
+ if (!interactive) return found;
111
+ const picked = await (deps.ask ?? askHosts)(found);
112
+ if (picked === null || picked.length === 0) {
113
+ throw new CliError("REFUSED", "Install cancelled before anything was written.", {
114
+ fix: "Re-run `tenjin install` and pick at least one agent."
115
+ });
116
+ }
117
+ return HARNESSES.filter((h) => picked.includes(h));
118
+ }
119
+ async function otherHostNote(args, deps = {}) {
120
+ if (args.harness !== void 0 || args.refresh === true || args.project === true) {
121
+ return void 0;
122
+ }
123
+ const env = deps.env ?? process.env;
124
+ const agent = agentHost(env);
125
+ if (agent === void 0) return void 0;
126
+ const other = agent === "claude" ? "codex" : "claude";
127
+ if (!(await (deps.detect ?? detectHosts)(env)).includes(other)) return void 0;
128
+ return `${LABEL[other]} is also installed on this machine. Ask the person: "Should I also set up Tenjin for ${LABEL[other]}?" On yes, run \`tenjin install --harness ${other}\`.`;
129
+ }
130
+ function withNote(out, note) {
131
+ if (note === void 0) return out;
132
+ const data = out.data ?? {};
133
+ const notices = Array.isArray(data.notices) ? data.notices : [];
134
+ return {
135
+ data: { ...data, notices: [...notices, note] },
136
+ humanLines: [...out.humanLines ?? [], note]
137
+ };
138
+ }
139
+ async function recordedHosts(args, dataDir) {
140
+ if (args.harness !== void 0) return [args.harness];
141
+ if (args.project === true) return ["claude"];
142
+ const hosts = await readInstalledHosts(dataDir);
143
+ return hosts === null || hosts.length === 0 ? ["claude"] : hosts;
144
+ }
145
+ async function runEach(hosts, run) {
146
+ const [only] = hosts;
147
+ if (hosts.length === 1 && only !== void 0) return run(only);
148
+ const data = { hosts };
149
+ const humanLines = [];
150
+ for (const host of hosts) {
151
+ const out = await run(host);
152
+ data[host] = out.data;
153
+ humanLines.push(`${LABEL[host]}:`, ...(out.humanLines ?? []).map((l) => ` ${l}`));
154
+ }
155
+ return { data, humanLines };
156
+ }
157
+ async function uninstallEach(hosts, dataDir, target, run, shared) {
158
+ const done = [];
159
+ const failed = [];
160
+ let claudeGone = false;
161
+ for (const host of hosts) {
162
+ try {
163
+ const out2 = await run(host);
164
+ done.push({ host, out: out2 });
165
+ const gone = host === "claude" ? nothingRemains(out2.data) : target.kind !== "project";
166
+ if (gone) await forgetInstalledHost(dataDir, host);
167
+ if (host === "claude") claudeGone = gone;
168
+ } catch (err) {
169
+ if (!(err instanceof CliError)) throw err;
170
+ failed.push({ host, err });
171
+ }
172
+ }
173
+ const [only] = done;
174
+ if (failed.length > 0) {
175
+ const [first] = failed;
176
+ if (hosts.length === 1 && first !== void 0) throw first.err;
177
+ const data = { hosts };
178
+ for (const { host, out: out2 } of done) data[host] = out2.data;
179
+ for (const { host, err } of failed) {
180
+ data[host] = {
181
+ error: err.message,
182
+ ...err.details !== void 0 ? { details: err.details } : {}
183
+ };
184
+ }
185
+ throw new CliError(
186
+ "REFUSED",
187
+ failed.map(({ host, err }) => `${LABEL[host]}: ${err.message}`).join(" "),
188
+ {
189
+ details: data,
190
+ fix: failed.map(({ host, err }) => `${LABEL[host]}:
191
+ ${err.fix ?? err.message}`).join("\n")
192
+ }
193
+ );
194
+ }
195
+ const out = hosts.length === 1 && only !== void 0 ? only.out : {
196
+ data: Object.fromEntries([["hosts", hosts], ...done.map((d) => [d.host, d.out.data])]),
197
+ humanLines: done.flatMap((d) => [
198
+ `${LABEL[d.host]}:`,
199
+ ...(d.out.humanLines ?? []).map((l) => ` ${l}`)
200
+ ])
201
+ };
202
+ if (shared === void 0) return out;
203
+ const claudeRan = done.some((d) => d.host === "claude");
204
+ if (claudeRan ? !claudeGone : await shared.claudeLeft()) return out;
205
+ const recorded = await readInstalledHosts(dataDir) ?? [];
206
+ if (recorded.length > 0) {
207
+ const line = shared.keptFor(recorded.map((h) => LABEL[h]));
208
+ return line === null ? out : { ...out, humanLines: [...out.humanLines ?? [], line] };
209
+ }
210
+ const removed = await shared.remove();
211
+ return {
212
+ data: {
213
+ ...out.data,
214
+ ...removed.data
215
+ },
216
+ humanLines: [...out.humanLines ?? [], ...removed.humanLines ?? []]
217
+ };
218
+ }
219
+ function nothingRemains(data) {
220
+ const remaining = data?.remaining;
221
+ return Array.isArray(remaining) && remaining.length === 0;
222
+ }
223
+ async function checkEach(hosts, run) {
224
+ const [only] = hosts;
225
+ if (hosts.length === 1 && only !== void 0) return run(only);
226
+ const data = { hosts };
227
+ const humanLines = [];
228
+ const failed = [];
229
+ for (const host of hosts) {
230
+ try {
231
+ const out = await run(host);
232
+ data[host] = out.data;
233
+ humanLines.push(`${LABEL[host]}:`, ...(out.humanLines ?? []).map((l) => ` ${l}`));
234
+ } catch (err) {
235
+ if (!(err instanceof CliError)) throw err;
236
+ data[host] = {
237
+ error: err.message,
238
+ ...err.details !== void 0 ? { details: err.details } : {}
239
+ };
240
+ failed.push({ host, err });
241
+ }
242
+ }
243
+ if (failed.length === 0) return { data, humanLines };
244
+ throw new CliError(
245
+ "REFUSED",
246
+ failed.map(({ host, err }) => `${LABEL[host]}: ${err.message}`).join(" "),
247
+ {
248
+ details: data,
249
+ fix: failed.map(({ host, err }) => `${LABEL[host]}:
250
+ ${err.fix ?? err.message}`).join("\n")
251
+ }
252
+ );
253
+ }
254
+
255
+ export {
256
+ HOSTS_FILE,
257
+ readInstalledHosts,
258
+ claudePluginPresent,
259
+ recordInstalledHost,
260
+ forgetInstalledHost,
261
+ agentHost,
262
+ detectHosts,
263
+ installHosts,
264
+ otherHostNote,
265
+ withNote,
266
+ recordedHosts,
267
+ runEach,
268
+ uninstallEach,
269
+ checkEach
270
+ };
271
+ //# sourceMappingURL=chunk-TF5HCP33.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/hosts.ts"],"sourcesContent":["import { readFile, rm } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { CommandContext, CommandResult } from '../context';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { CliError } from '../lib/errors';\nimport { HARNESSES, type Harness } from './names';\nimport type { UninstallTarget } from './uninstall';\n\n/**\n * WHICH AGENT HOSTS `install`, `doctor` AND `uninstall` SERVE. Nobody names a\n * host on the normal path: an agent's install goes to the host it runs in, a\n * terminal install to the hosts this machine has (asking when it has both),\n * and doctor and uninstall read the hosts install recorded. `--harness` only\n * overrides.\n */\n\n/** The record install writes in the Tenjin data dir: the hosts it set up. */\nexport const HOSTS_FILE = 'installed-hosts.json';\n\nconst LABEL: Record<Harness, string> = { claude: 'Claude Code', codex: 'Codex' };\n\n/** The hosts install recorded, or null on a machine set up before the record. */\nexport async function readInstalledHosts(dataDir: string): Promise<Harness[] | null> {\n let raw: string;\n try {\n raw = await readFile(join(dataDir, HOSTS_FILE), 'utf8');\n } catch {\n return null;\n }\n try {\n const hosts = (JSON.parse(raw) as { hosts?: unknown }).hosts;\n if (!Array.isArray(hosts)) return null;\n return HARNESSES.filter((h) => hosts.includes(h));\n } catch {\n return null;\n }\n}\n\nasync function writeHosts(dataDir: string, hosts: readonly Harness[]): Promise<void> {\n const path = join(dataDir, HOSTS_FILE);\n if (hosts.length === 0) {\n await rm(path, { force: true });\n return;\n }\n await writeFileAtomic(path, `${JSON.stringify({ hosts }, null, 2)}\\n`, { mode: 0o600 });\n}\n\n/**\n * Is the Claude Code plugin here already, from a release that wrote no record?\n * Claude Code's own plugin list file, as doctor reads it with no binary, or\n * the plugin folder of ours at user scope.\n */\nexport async function claudePluginPresent(\n env: NodeJS.ProcessEnv = process.env,\n home: string = homedir(),\n): Promise<boolean> {\n const [{ listedInClaudeFiles }, { folderState }] = await Promise.all([\n import('./doctor'),\n import('./plugin-registration'),\n ]);\n if (await listedInClaudeFiles(env, home)) return true;\n return (await folderState('user', env, home, home)).state === 'ours';\n}\n\n/**\n * A host whose setup finished. The first record on a machine whose Claude\n * Code plugin came from a release before the record starts with Claude Code,\n * so doctor and uninstall keep covering it.\n */\nexport async function recordInstalledHost(\n dataDir: string,\n host: Harness,\n present: () => Promise<boolean> = () => claudePluginPresent(),\n): Promise<void> {\n const recorded = await readInstalledHosts(dataDir);\n const hosts =\n recorded ?? (host !== 'claude' && (await present().catch(() => false)) ? ['claude'] : []);\n if (hosts.includes(host)) return;\n await writeHosts(\n dataDir,\n HARNESSES.filter((h) => h === host || hosts.includes(h)),\n );\n}\n\nexport async function forgetInstalledHost(dataDir: string, host: Harness): Promise<void> {\n const hosts = await readInstalledHosts(dataDir);\n if (hosts === null || !hosts.includes(host)) return;\n await writeHosts(\n dataDir,\n hosts.filter((h) => h !== host),\n );\n}\n\n/**\n * The host whose agent runs this command, from the variables each exports, or\n * undefined in a person's own terminal. A Claude Code variable wins when both\n * are set, as `readActor` reads them.\n */\nexport function agentHost(env: NodeJS.ProcessEnv): Harness | undefined {\n const set = (v: string | undefined) => typeof v === 'string' && v.trim().length > 0;\n if (set(env.CLAUDECODE) || set(env.CLAUDE_CODE_SESSION_ID) || set(env.CLAUDE_CODE_EXECPATH)) {\n return 'claude';\n }\n if (set(env.CODEX_SESSION_ID)) return 'codex';\n return undefined;\n}\n\n/** The hosts this machine can run: each counts only when its `--version` answers. */\nexport async function detectHosts(env: NodeJS.ProcessEnv): Promise<Harness[]> {\n const [{ readClaudeCode }, { codexVersion }] = await Promise.all([\n import('./claude-cli'),\n import('./codex-host'),\n ]);\n const [claude, codex] = await Promise.all([\n readClaudeCode(env, process.cwd()).then(\n (s) => s.version !== null,\n () => false,\n ),\n codexVersion().then(\n (v) => v !== null,\n () => false,\n ),\n ]);\n return HARNESSES.filter((h) => (h === 'claude' ? claude : codex));\n}\n\nasync function askHosts(found: readonly Harness[]): Promise<Harness[] | null> {\n const { selectMany } = await import('../lib/clack');\n return selectMany<Harness>({\n message: 'Set up Tenjin for which agents?',\n choices: found.map((h) => ({ value: h, label: LABEL[h] })),\n initialValues: found,\n });\n}\n\nexport interface HostDeps {\n env?: NodeJS.ProcessEnv;\n detect?: (env: NodeJS.ProcessEnv) => Promise<Harness[]>;\n ask?: (found: readonly Harness[]) => Promise<Harness[] | null>;\n isInteractive?: boolean;\n}\n\nexport interface InstallHostArgs {\n harness?: Harness;\n project?: boolean;\n refresh?: boolean;\n yes?: boolean;\n}\n\n/**\n * The hosts this install sets up. A refresh and a project install are Claude\n * Code's alone; an agent's install goes to its own host; a terminal install\n * goes to every host found, asking first when there are two and a person can\n * answer. A machine with neither gets the Claude Code setup, which needs no\n * `claude` binary.\n */\nexport async function installHosts(\n args: InstallHostArgs,\n ctx: CommandContext,\n deps: HostDeps = {},\n): Promise<Harness[]> {\n if (args.harness !== undefined) return [args.harness];\n if (args.refresh === true || args.project === true) return ['claude'];\n const env = deps.env ?? process.env;\n const agent = agentHost(env);\n if (agent !== undefined) return [agent];\n const found = await (deps.detect ?? detectHosts)(env);\n if (found.length === 0) return ['claude'];\n if (found.length === 1 || args.yes === true) return found;\n const interactive =\n ctx.flags.json !== true &&\n (deps.isInteractive ?? (ctx.io.isTTY && Boolean(process.stdin.isTTY)));\n if (!interactive) return found;\n const picked = await (deps.ask ?? askHosts)(found);\n if (picked === null || picked.length === 0) {\n throw new CliError('REFUSED', 'Install cancelled before anything was written.', {\n fix: 'Re-run `tenjin install` and pick at least one agent.',\n });\n }\n return HARNESSES.filter((h) => picked.includes(h));\n}\n\n/**\n * Under an agent, the line naming the other host when its `--version` runs\n * too: a yes/no question the agent asks the person, and what a yes runs.\n */\nexport async function otherHostNote(\n args: InstallHostArgs,\n deps: HostDeps = {},\n): Promise<string | undefined> {\n if (args.harness !== undefined || args.refresh === true || args.project === true) {\n return undefined;\n }\n const env = deps.env ?? process.env;\n const agent = agentHost(env);\n if (agent === undefined) return undefined;\n const other: Harness = agent === 'claude' ? 'codex' : 'claude';\n if (!(await (deps.detect ?? detectHosts)(env)).includes(other)) return undefined;\n return `${LABEL[other]} is also installed on this machine. Ask the person: \"Should I also set up Tenjin for ${LABEL[other]}?\" On yes, run \\`tenjin install --harness ${other}\\`.`;\n}\n\n/** The install result with `note` in its `notices` and as its last line. */\nexport function withNote(out: CommandResult, note: string | undefined): CommandResult {\n if (note === undefined) return out;\n const data = (out.data ?? {}) as { notices?: unknown };\n const notices = Array.isArray(data.notices) ? (data.notices as string[]) : [];\n return {\n data: { ...data, notices: [...notices, note] },\n humanLines: [...(out.humanLines ?? []), note],\n };\n}\n\n/** The hosts doctor checks and uninstall removes: the record, else Claude Code. */\nexport async function recordedHosts(\n args: { harness?: Harness; project?: boolean },\n dataDir: string,\n): Promise<Harness[]> {\n if (args.harness !== undefined) return [args.harness];\n if (args.project === true) return ['claude'];\n const hosts = await readInstalledHosts(dataDir);\n return hosts === null || hosts.length === 0 ? ['claude'] : hosts;\n}\n\n/** One run per host, in order. One host keeps its own result shape. */\nexport async function runEach(\n hosts: readonly Harness[],\n run: (host: Harness) => Promise<CommandResult>,\n): Promise<CommandResult> {\n const [only] = hosts;\n if (hosts.length === 1 && only !== undefined) return run(only);\n const data: Record<string, unknown> = { hosts };\n const humanLines: string[] = [];\n for (const host of hosts) {\n const out = await run(host);\n data[host] = out.data;\n humanLines.push(`${LABEL[host]}:`, ...(out.humanLines ?? []).map((l) => ` ${l}`));\n }\n return { data, humanLines };\n}\n\n/** What every install shares (Tenjin's runtime and its launcher), as uninstall settles it last. */\nexport interface SharedParts {\n /** Removes them; their result is appended to the run's. */\n remove: () => Promise<CommandResult>;\n /** Whether Claude Code still holds an install anywhere; asked only when this run did not remove Claude Code's. */\n claudeLeft: () => Promise<boolean>;\n /** The line saying they were kept for these hosts, or null where there are none (a data dir of its own). */\n keptFor: (hosts: string[]) => string | null;\n}\n\n/**\n * Uninstall over the hosts: a host leaves the record only once its removal\n * left nothing behind. Claude Code leaves it when no install of it is left in\n * any scope or project (its result's `remaining` is empty); Codex, user scope\n * only, when its removal succeeded. A host whose removal failed (it throws)\n * stays recorded, so a later uninstall or doctor still finds it, and every\n * host is tried before one aggregated refusal.\n *\n * `shared` IS SETTLED BY THE END STATE, last: removed only when every host\n * succeeded, no host is still recorded, and Claude Code holds no install\n * (this run's `remaining` is empty, or, when Claude Code was not part of this\n * run, it records none), so the last host removed takes them whichever it is.\n * Kept, and said so, when only another recorded host still uses them.\n */\nexport async function uninstallEach(\n hosts: readonly Harness[],\n dataDir: string,\n target: UninstallTarget,\n run: (host: Harness) => Promise<CommandResult>,\n shared?: SharedParts,\n): Promise<CommandResult> {\n const done: { host: Harness; out: CommandResult }[] = [];\n const failed: { host: Harness; err: CliError }[] = [];\n let claudeGone = false;\n for (const host of hosts) {\n try {\n const out = await run(host);\n done.push({ host, out });\n const gone = host === 'claude' ? nothingRemains(out.data) : target.kind !== 'project';\n if (gone) await forgetInstalledHost(dataDir, host);\n if (host === 'claude') claudeGone = gone;\n } catch (err) {\n if (!(err instanceof CliError)) throw err;\n failed.push({ host, err });\n }\n }\n const [only] = done;\n if (failed.length > 0) {\n const [first] = failed;\n if (hosts.length === 1 && first !== undefined) throw first.err;\n const data: Record<string, unknown> = { hosts };\n for (const { host, out } of done) data[host] = out.data;\n for (const { host, err } of failed) {\n data[host] = {\n error: err.message,\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n }\n throw new CliError(\n 'REFUSED',\n failed.map(({ host, err }) => `${LABEL[host]}: ${err.message}`).join(' '),\n {\n details: data,\n fix: failed.map(({ host, err }) => `${LABEL[host]}:\\n${err.fix ?? err.message}`).join('\\n'),\n },\n );\n }\n // One host keeps its own result shape, as runEach does.\n const out: CommandResult =\n hosts.length === 1 && only !== undefined\n ? only.out\n : {\n data: Object.fromEntries([['hosts', hosts], ...done.map((d) => [d.host, d.out.data])]),\n humanLines: done.flatMap((d) => [\n `${LABEL[d.host]}:`,\n ...(d.out.humanLines ?? []).map((l) => ` ${l}`),\n ]),\n };\n if (shared === undefined) return out;\n // Claude Code's own result already names what it keeps for its installs.\n const claudeRan = done.some((d) => d.host === 'claude');\n if (claudeRan ? !claudeGone : await shared.claudeLeft()) return out;\n const recorded = (await readInstalledHosts(dataDir)) ?? [];\n if (recorded.length > 0) {\n const line = shared.keptFor(recorded.map((h) => LABEL[h]));\n return line === null ? out : { ...out, humanLines: [...(out.humanLines ?? []), line] };\n }\n const removed = await shared.remove();\n return {\n data: {\n ...(out.data as Record<string, unknown>),\n ...(removed.data as Record<string, unknown>),\n },\n humanLines: [...(out.humanLines ?? []), ...(removed.humanLines ?? [])],\n };\n}\n\n/** The Claude Code removal's `remaining: []`: no install of it is left anywhere. */\nfunction nothingRemains(data: unknown): boolean {\n const remaining = (data as { remaining?: unknown } | null)?.remaining;\n return Array.isArray(remaining) && remaining.length === 0;\n}\n\n/**\n * Doctor over several hosts: every host is checked before any failure is\n * reported, and the failure names each host that failed.\n */\nexport async function checkEach(\n hosts: readonly Harness[],\n run: (host: Harness) => Promise<CommandResult>,\n): Promise<CommandResult> {\n const [only] = hosts;\n if (hosts.length === 1 && only !== undefined) return run(only);\n const data: Record<string, unknown> = { hosts };\n const humanLines: string[] = [];\n const failed: { host: Harness; err: CliError }[] = [];\n for (const host of hosts) {\n try {\n const out = await run(host);\n data[host] = out.data;\n humanLines.push(`${LABEL[host]}:`, ...(out.humanLines ?? []).map((l) => ` ${l}`));\n } catch (err) {\n if (!(err instanceof CliError)) throw err;\n data[host] = {\n error: err.message,\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n failed.push({ host, err });\n }\n }\n if (failed.length === 0) return { data, humanLines };\n throw new CliError(\n 'REFUSED',\n failed.map(({ host, err }) => `${LABEL[host]}: ${err.message}`).join(' '),\n {\n details: data,\n fix: failed.map(({ host, err }) => `${LABEL[host]}:\\n${err.fix ?? err.message}`).join('\\n'),\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,UAAU,UAAU;AAC7B,SAAS,eAAe;AACxB,SAAS,YAAY;AAgBd,IAAM,aAAa;AAE1B,IAAM,QAAiC,EAAE,QAAQ,eAAe,OAAO,QAAQ;AAG/E,eAAsB,mBAAmB,SAA4C;AACnF,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,SAAS,KAAK,SAAS,UAAU,GAAG,MAAM;AAAA,EACxD,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI;AACF,UAAM,QAAS,KAAK,MAAM,GAAG,EAA0B;AACvD,QAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO;AAClC,WAAO,UAAU,OAAO,CAAC,MAAM,MAAM,SAAS,CAAC,CAAC;AAAA,EAClD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAe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AE,eAAe,UAAW,OAAM;AACtC,WAAK,IAAI,IAAI;AAAA,QACX,OAAO,IAAI;AAAA,QACX,GAAI,IAAI,YAAY,SAAY,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;AAAA,MAC9D;AACA,aAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AAAA,IAC3B;AAAA,EACF;AACA,MAAI,OAAO,WAAW,EAAG,QAAO,EAAE,MAAM,WAAW;AACnD,QAAM,IAAI;AAAA,IACR;AAAA,IACA,OAAO,IAAI,CAAC,EAAE,MAAM,IAAI,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,IAAI,OAAO,EAAE,EAAE,KAAK,GAAG;AAAA,IACxE;AAAA,MACE,SAAS;AAAA,MACT,KAAK,OAAO,IAAI,CAAC,EAAE,MAAM,IAAI,MAAM,GAAG,MAAM,IAAI,CAAC;AAAA,EAAM,IAAI,OAAO,IAAI,OAAO,EAAE,EAAE,KAAK,IAAI;AAAA,IAC5F;AAAA,EACF;AACF;","names":["out"]}
@@ -38,12 +38,47 @@ function eventFromToolInput(args) {
38
38
  }
39
39
  return event;
40
40
  }
41
+ var CODEX_HOOK_KINDS = ["prompt", "native", "shortfall"];
42
+ var CODEX_COMMON = [
43
+ "hook_event_name",
44
+ "session_id",
45
+ "turn_id",
46
+ "transcript_path",
47
+ "cwd"
48
+ ];
49
+ var CODEX_CALL = ["tool_name", "tool_input", "tool_use_id"];
50
+ var CODEX_FIELDS = {
51
+ prompt: [...CODEX_COMMON, "prompt"],
52
+ native: [...CODEX_COMMON, ...CODEX_CALL],
53
+ shortfall: [...CODEX_COMMON, ...CODEX_CALL, "tool_response"]
54
+ };
55
+ function codexHookToolInput(kind) {
56
+ return Object.fromEntries([
57
+ ["kind", kind],
58
+ ...CODEX_FIELDS[kind].map((field) => [field, `\${${field}}`])
59
+ ]);
60
+ }
61
+ var CODEX_HOOK_TOOL_FIELDS = [
62
+ ...new Set(Object.values(CODEX_FIELDS).flat())
63
+ ];
64
+ function codexEventFromToolInput(args) {
65
+ const event = {};
66
+ for (const field of CODEX_HOOK_TOOL_FIELDS) {
67
+ const value = args[field];
68
+ if (value !== void 0 && value !== null) event[field] = value;
69
+ }
70
+ return event;
71
+ }
41
72
 
42
73
  export {
43
74
  HOOK_KINDS,
44
75
  HOOK_TOOL,
45
76
  hookToolInput,
46
77
  HOOK_TOOL_FIELDS,
47
- eventFromToolInput
78
+ eventFromToolInput,
79
+ CODEX_HOOK_KINDS,
80
+ codexHookToolInput,
81
+ CODEX_HOOK_TOOL_FIELDS,
82
+ codexEventFromToolInput
48
83
  };
49
- //# sourceMappingURL=chunk-AKWGE6JQ.js.map
84
+ //# sourceMappingURL=chunk-UUGOUOVT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/hook-tool.ts"],"sourcesContent":["/**\n * THE HOOK EVENT, CARRIED BY AN `mcp_tool` ENTRY. Claude Code calls the `hook`\n * tool of the session's own `tenjin mcp` for each routing leg, with the event's\n * fields substituted into the entry's `input` (`${session_id}` and so on): a\n * string field arrives as written, an object one (`tool_input`,\n * `tool_response`) as its JSON text, a boolean as `true` or `false`, and a\n * field the event lacks as an empty string. This turns that back into the\n * event the handlers already read, and spells the `input` `install` writes.\n */\n\n/** The routing legs, one per hook entry `install` writes. */\nexport const HOOK_KINDS = ['prompt', 'native', 'shortfall', 'agent', 'ask', 'answer'] as const;\nexport type HookKind = (typeof HOOK_KINDS)[number];\n\n/** The tool `tenjin mcp` registers for the hook entries. */\nexport const HOOK_TOOL = 'hook';\n\n/** The event fields each leg reads, as Claude Code names them. */\nconst COMMON = ['hook_event_name', 'session_id', 'transcript_path', 'cwd'] as const;\nconst CALL = ['tool_name', 'tool_input', 'tool_use_id', 'agent_id', 'agent_type'] as const;\n\nconst FIELDS: Record<HookKind, readonly string[]> = {\n prompt: [...COMMON, 'prompt'],\n native: [...COMMON, ...CALL],\n agent: [...COMMON, ...CALL],\n ask: [...COMMON, ...CALL],\n answer: [...COMMON, ...CALL, 'tool_response'],\n shortfall: [...COMMON, ...CALL, 'tool_response', 'error', 'is_interrupt'],\n};\n\n/** Fields whose value is an object or a boolean, sent as JSON text. */\nconst JSON_FIELDS = new Set(['tool_input', 'tool_response', 'is_interrupt']);\n\n/** The `input` of one leg's `mcp_tool` entry. */\nexport function hookToolInput(kind: HookKind): Record<string, string> {\n return Object.fromEntries([\n ['kind', kind],\n ...FIELDS[kind].map((field) => [field, `\\${${field}}`]),\n ]);\n}\n\n/** Every field any leg sends, for the tool's input schema. */\nexport const HOOK_TOOL_FIELDS: readonly string[] = [...new Set(Object.values(FIELDS).flat())];\n\nexport function isHookKind(value: unknown): value is HookKind {\n return typeof value === 'string' && (HOOK_KINDS as readonly string[]).includes(value);\n}\n\n/**\n * The harness event from the tool's arguments: empty fields dropped (the\n * event did not carry them), the JSON ones parsed back. A JSON field that does\n * not parse is kept as the string it is.\n */\nexport function eventFromToolInput(args: Record<string, unknown>): Record<string, unknown> {\n const event: Record<string, unknown> = {};\n for (const field of HOOK_TOOL_FIELDS) {\n const value = args[field];\n if (typeof value !== 'string' || value.length === 0) continue;\n if (!JSON_FIELDS.has(field)) {\n event[field] = value;\n continue;\n }\n try {\n event[field] = JSON.parse(value) as unknown;\n } catch {\n event[field] = value;\n }\n }\n return event;\n}\n\n/**\n * THE SAME EVENT, CARRIED BY A CODEX `mcp_tool` ENTRY (Codex 0.149 and later).\n * Codex substitutes `${field}` from the event too, with two differences\n * (openai/codex `hooks/src/engine/mcp_runner.rs`): a whole placeholder keeps\n * the field's JSON type, so `tool_input` arrives as an object and a null\n * `transcript_path` as null; and a field the event lacks fails the hook. So\n * each leg names only the fields Codex always sends for its event, and the\n * optional `agent_id` is never one of them: the call's `threadId` metadata\n * tells a subagent's leg apart instead (`admitCodexHookEvent`).\n */\nexport const CODEX_HOOK_KINDS = ['prompt', 'native', 'shortfall'] as const;\nexport type CodexHookKind = (typeof CODEX_HOOK_KINDS)[number];\n\nconst CODEX_COMMON = [\n 'hook_event_name',\n 'session_id',\n 'turn_id',\n 'transcript_path',\n 'cwd',\n] as const;\nconst CODEX_CALL = ['tool_name', 'tool_input', 'tool_use_id'] as const;\n\nconst CODEX_FIELDS: Record<CodexHookKind, readonly string[]> = {\n prompt: [...CODEX_COMMON, 'prompt'],\n native: [...CODEX_COMMON, ...CODEX_CALL],\n shortfall: [...CODEX_COMMON, ...CODEX_CALL, 'tool_response'],\n};\n\n/** The `input` of one Codex leg's `mcp_tool` entry. */\nexport function codexHookToolInput(kind: CodexHookKind): Record<string, string> {\n return Object.fromEntries([\n ['kind', kind],\n ...CODEX_FIELDS[kind].map((field) => [field, `\\${${field}}`]),\n ]);\n}\n\n/** Every field any Codex leg sends, for the tool's input schema. */\nexport const CODEX_HOOK_TOOL_FIELDS: readonly string[] = [\n ...new Set(Object.values(CODEX_FIELDS).flat()),\n];\n\n/** The Codex event from the tool's arguments, each field as Codex typed it; nulls dropped. */\nexport function codexEventFromToolInput(args: Record<string, unknown>): Record<string, unknown> {\n const event: Record<string, unknown> = {};\n for (const field of CODEX_HOOK_TOOL_FIELDS) {\n const value = args[field];\n if (value !== undefined && value !== null) event[field] = value;\n }\n return event;\n}\n"],"mappings":";;;AAWO,IAAM,aAAa,CAAC,UAAU,UAAU,aAAa,SAAS,OAAO,QAAQ;AAI7E,IAAM,YAAY;AAGzB,IAAM,SAAS,CAAC,mBAAmB,cAAc,mBAAmB,KAAK;AACzE,IAAM,OAAO,CAAC,aAAa,cAAc,eAAe,YAAY,YAAY;AAEhF,IAAM,SAA8C;AAAA,EAClD,QAAQ,CAAC,GAAG,QAAQ,QAAQ;AAAA,EAC5B,QAAQ,CAAC,GAAG,QAAQ,GAAG,IAAI;AAAA,EAC3B,OAAO,CAAC,GAAG,QAAQ,GAAG,IAAI;AAAA,EAC1B,KAAK,CAAC,GAAG,QAAQ,GAAG,IAAI;AAAA,EACxB,QAAQ,CAAC,GAAG,QAAQ,GAAG,MAAM,eAAe;AAAA,EAC5C,WAAW,CAAC,GAAG,QAAQ,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UAAU,CAAC,OAAO,MAAM,KAAK,GAAG,CAAC;AAAA,EAC9D,CAAC;AACH;AAGO,IAAM,yBAA4C;AAAA,EACvD,GAAG,IAAI,IAAI,OAAO,OAAO,YAAY,EAAE,KAAK,CAAC;AAC/C;AAGO,SAAS,wBAAwB,MAAwD;AAC9F,QAAM,QAAiC,CAAC;AACxC,aAAW,SAAS,wBAAwB;AAC1C,UAAM,QAAQ,KAAK,KAAK;AACxB,QAAI,UAAU,UAAa,UAAU,KAAM,OAAM,KAAK,IAAI;AAAA,EAC5D;AACA,SAAO;AACT;","names":[]}
@@ -5,19 +5,19 @@ import {
5
5
  emptyLedger,
6
6
  readLedger,
7
7
  spentOf
8
- } from "./chunk-NZIP4PA2.js";
9
- import {
10
- withFileLock
11
- } from "./chunk-MEFB5KHA.js";
8
+ } from "./chunk-SO3XRZPX.js";
12
9
  import {
13
10
  evaluateSpendPolicy
14
11
  } from "./chunk-2SNUOHAT.js";
12
+ import {
13
+ withFileLock
14
+ } from "./chunk-MEFB5KHA.js";
15
15
  import {
16
16
  writeFileAtomic
17
- } from "./chunk-O2FRQ2L2.js";
17
+ } from "./chunk-7WEQQJLG.js";
18
18
  import {
19
19
  spendLedgerPath
20
- } from "./chunk-SJLTEINJ.js";
20
+ } from "./chunk-OJNTCYQQ.js";
21
21
 
22
22
  // src/lib/wallet/spend.ts
23
23
  import { mkdir } from "node:fs/promises";
@@ -189,4 +189,4 @@ export {
189
189
  createLocalSpendAuthorizer,
190
190
  releaseUnchargedExposure
191
191
  };
192
- //# sourceMappingURL=chunk-AEG2PXBP.js.map
192
+ //# sourceMappingURL=chunk-V2LQLN5H.js.map
@@ -1,8 +1,10 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
- CliError,
4
3
  external_exports
5
- } from "./chunk-WO5BJNIB.js";
4
+ } from "./chunk-SNNSAGMT.js";
5
+ import {
6
+ CliError
7
+ } from "./chunk-3UCIG4TG.js";
6
8
 
7
9
  // src/lib/output.ts
8
10
  import { WriteStream } from "node:tty";
@@ -234,4 +236,4 @@ export {
234
236
  style,
235
237
  paint
236
238
  };
237
- //# sourceMappingURL=chunk-KYFZTGMC.js.map
239
+ //# sourceMappingURL=chunk-VJUVFZ2D.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/output.ts","../src/schemas.ts"],"sourcesContent":["import { WriteStream } from 'node:tty';\nimport { styleText } from 'node:util';\nimport { CliError } from './errors';\nimport type { StdinInput } from './stdin';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { UpdateAvailable } from '../schemas';\nimport type { FailureEnvelope, OutputError, SuccessEnvelope } from '../schemas';\n\n/**\n * Injected streams + TTY facts. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` describes stdout; the separate `--json` flag (passed to the emit\n * functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output. `stdin` is\n * optional for compatibility with command-core contexts that never read it;\n * defaultIo supplies the real stream, and only the CLI forwards that capability\n * to commands that accept Markdown on stdin.\n */\nexport interface Io {\n stdin?: StdinInput;\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdin: { stream: process.stdin, isTTY: Boolean(process.stdin.isTTY) },\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, the JSON envelope is emitted even at a TTY. */\n json?: boolean;\n /**\n * \"A newer tenjin-cli exists\", from the daily check's cache. Rides the\n * envelope so the AGENT running the command learns it; the human at a TTY\n * gets the dim stderr line instead, and neither path fetches anything.\n */\n updateAvailable?: UpdateAvailable | null;\n}\n\n/**\n * The two pure envelope builders, shared by the CLI's emit functions and the MCP\n * adapter so both surfaces produce the identical wire object by construction. They\n * hold no I/O and no --json branching: they turn a (command, data) or a normalized\n * CliError into the exact object that goes to stdout / structuredContent.\n */\nexport function buildSuccessEnvelope(\n command: string,\n data: unknown,\n updateAvailable?: UpdateAvailable | null,\n): SuccessEnvelope {\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: true,\n data,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\nexport function buildFailureEnvelope(\n command: string,\n err: CliError,\n updateAvailable?: UpdateAvailable | null,\n): FailureEnvelope {\n const error: OutputError = {\n code: err.code,\n message: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: false,\n error,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\n/**\n * Output contract (human-first): at a TTY without `--json`, print ONLY the human\n * rendering to stdout, no JSON envelope. With `--json`, or when stdout is not a\n * TTY (a pipe, an agent), print exactly one JSON envelope to stdout and nothing\n * else. Exit codes are identical on both paths; only the stdout shape differs.\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n if (humanMode(io, opts)) {\n writeLines(io.stdout, humanLines);\n return;\n }\n writeJson(io.stdout, buildSuccessEnvelope(command, data, opts.updateAvailable));\n}\n\n/**\n * The failure half of the same contract: at a TTY without `--json`, a red error\n * line plus a `fix` line to stdout and no envelope; otherwise exactly one failure\n * envelope to stdout. Accepts a CliError or any thrown value (non-CliError\n * normalizes to INTERNAL). Returns the normalized CliError so the caller reads its\n * `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n if (humanMode(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n // Scan findings are the one detail shape a human needs inline: without them\n // an interactive publish hitting NEEDS_CONFIRMATION / PUBLISH_BLOCKED sees\n // the count but not WHICH lines tripped. Every other shape is machine-only.\n lines.push(...findingLines(io, cliErr.details));\n writeLines(io.stdout, lines);\n return cliErr;\n }\n writeJson(io.stdout, buildFailureEnvelope(command, cliErr, opts.updateAvailable));\n return cliErr;\n}\n\n/**\n * One dim advisory line on stderr, human mode only. This is for facts that belong\n * to NO command's result — an unreadable spend ledger, a newer release on npm —\n * so they can never join the envelope on stdout or reach a machine consumer at\n * all. Sanitized here rather than by each caller: what these lines quote (a\n * registry version string, a parse error) is not the command's own prose.\n */\nexport function emitNotice(io: Io, text: string, opts: EmitOptions = {}): void {\n if (!humanMode(io, opts)) return;\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * The same dim stderr line, delivered whatever the surface is: no TTY gate and no\n * `--json` gate. Only for an advisory a piped or agent-driven run must not miss,\n * which today is two things: a WRITE to the operator's own files, and `fund`'s\n * checkout link, which expires long before the stdout envelope that also carries\n * it is written. Anything a piped run can simply do without belongs in\n * {@link emitNotice} instead. stdout is untouched either way, so the exactly-one\n * JSON object contract is unaffected.\n */\nexport function emitWriteNotice(io: Io, text: string): void {\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * Every escape sequence a terminal writes: CSI (colour, cursor), OSC — which\n * covers the OSC-8 hyperlinks pnpm wraps package names in, terminated by BEL\n * or ST — charset selection, and a stray ESC with a single final byte.\n *\n * ONE COPY, because the other reader is the failure lane: `stripAnsi`\n * (`hooks/text.ts`) takes colour off a runner's output before the arm scans it\n * for a diagnostic, and a pattern that misses OSC-8 leaves `]8;;https://…`\n * sitting in front of the very line the start-anchored markers must match.\n * That reader CANNOT call {@link sanitizeForTerminal}: this is only its first\n * clause, and the second strips `\\n`, which would flatten the output it is\n * about to split into lines.\n *\n * Safe to share despite the `g` flag: both callers use it through\n * `String.replace`, which starts at 0 and resets `lastIndex`. Do not `test()`\n * or `exec()` it.\n */\nexport const ANSI_ESCAPE_RE =\n // eslint-disable-next-line no-control-regex\n /\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g;\n\n/**\n * Strip ANSI escape sequences, C0/C1 control characters, Unicode bidirectional\n * formatting, and invisible tag/BOM characters from a string headed for a\n * terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm, a right-to-left override to reorder\n * that same line on screen into one that reads as a different price, or tag\n * characters to carry a payload that draws as nothing at all. It is not\n * applied to whole human lines here because trusted callers (doctor) paint\n * their own ANSI colors. JSON stdout is untouched: JSON.stringify escapes C0\n * controls itself, but the bidi and tag/BOM sets ride through it raw, and that\n * is deliberate rather than covered — the envelope is machine-read data whose\n * bytes must be what the server said, and a consumer reading codepoints is not\n * deceived by rendering order the way a human reading a drawn line is.\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n .replace(ANSI_ESCAPE_RE, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n // The UAX#9 directional formatting set: the marks (LRM/RLM/ALM), the\n // embeddings and overrides (U+202A-U+202E), and the isolates\n // (U+2066-U+2069). Removed, not escaped, so what a human reads is the\n // order the bytes are in. Deliberately this set and NOT all of category\n // Cf: U+200D (ZWJ) joins legitimate emoji sequences, and dropping it\n // would corrupt honest titles to defend against dishonest ones.\n .replace(/[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n // The Unicode tag block (U+E0000-U+E007F) and the BOM/ZWNBSP, neither of\n // which has a legitimate mid-title use. Tag characters render as nothing\n // at all, so a payload spelled in them is invisible in the line a human\n // is reading and in the line they would paste back to report it.\n //\n // The three RGI subdivision flags are the exception and survive\n // byte-identical: they are ordinary title content. The whitelist is those\n // three sequences and NOT \"any well-formed tag sequence\", because a\n // non-RGI sequence draws as a bare black flag with the payload hidden\n // behind it, which is the exact channel this closes.\n //\n // Kept for the same reason as ZWJ above: U+200B (ZWSP) hints line breaks\n // in CJK and U+200C (ZWNJ) is orthographically required in Persian, so\n // stripping them would corrupt honest titles to defend against dishonest\n // ones.\n .replace(\n /(\\u{1F3F4}\\u{E0067}\\u{E0062}(?:\\u{E0065}\\u{E006E}\\u{E0067}|\\u{E0073}\\u{E0063}\\u{E0074}|\\u{E0077}\\u{E006C}\\u{E0073})\\u{E007F})|[\\u{E0000}-\\u{E007F}\\u{FEFF}]/gu,\n (_match, rgiFlag: string | undefined) => rgiFlag ?? '',\n )\n );\n}\n\n/**\n * The same strip, for text that ships to OTHER PEOPLE rather than to this\n * terminal: a post's title, its public excerpt, and every free-text field of the\n * answer card a buyer reads before paying.\n *\n * The threat is the same one {@link sanitizeForTerminal} closes, one hop further\n * out. None of this text is necessarily typed by the person publishing: a card\n * question can be prefilled from a stored search, and every field can arrive over\n * MCP from an agent that read them off a fetched page. `trim()` removes neither a\n * CSI sequence nor a right-to-left override, so without this a payload rides into\n * the marketplace and renders in every future reader's terminal.\n *\n * Newlines and tabs fold to a single space FIRST, because these are all\n * single-line display fields and a bare strip would join the words on either side\n * of a line break into one. NOT for the post BODY: that is the author's document,\n * markdown and all, and rewriting it is not this function's business.\n */\nexport function sanitizeWireText(text: string): string {\n return sanitizeForTerminal(text.replace(/[\\r\\n\\t]+/g, ' ')).trim();\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\n/** True in human-first mode: a TTY without --json. Otherwise the JSON envelope wins. */\nfunction humanMode(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\n/**\n * Render `details.findings` (the scan-finding projection publish attaches to\n * NEEDS_CONFIRMATION / PUBLISH_BLOCKED) as one dim line per finding:\n * ` <check> (line N): <excerpt>`. The excerpt is already masked for secret\n * findings at the source; sanitize it anyway since it can echo file content.\n * Returns [] for any other details shape, so no other error leaks a detail dump.\n *\n * A finding the SERVER gate contributed carries a `source`, and the marker is\n * printed because it is the difference between \"fix your file\" and \"the\n * marketplace refused this\": the detector may be one this release predates, so\n * the line has to stand on the server's own words rather than on recognition.\n * The tier rides the same line, for the payloads that mix block and warn.\n */\nfunction findingLines(io: Io, details: unknown): string[] {\n if (typeof details !== 'object' || details === null || !('findings' in details)) return [];\n const { findings } = details as { findings: unknown };\n if (!Array.isArray(findings) || findings.length === 0) return [];\n const rendered: string[] = [];\n for (const f of findings) {\n if (typeof f !== 'object' || f === null) continue;\n const { check, line, excerpt, source, severity } = f as {\n check?: unknown;\n line?: unknown;\n excerpt?: unknown;\n source?: unknown;\n severity?: unknown;\n };\n if (typeof check !== 'string' || typeof line !== 'number' || typeof excerpt !== 'string') {\n continue;\n }\n const from = source === 'server' ? ' [server]' : source === 'both' ? ' [local+server]' : '';\n // THE TIER IS PRINTED because one payload can mix them: a `scan_blocked`\n // envelope ships the block finding alongside the warns the same pass found,\n // and without the tier nothing on the page says which one is the refusal.\n // An open string, sanitized like the rest: the server owns its own tier names.\n const tier = typeof severity === 'string' && severity.length > 0 ? `${severity}, ` : '';\n // The detector id is sanitized too: on a server finding it is a name this\n // release may never have seen, so it is untrusted text like the excerpt.\n rendered.push(\n paint(\n io,\n 'dim',\n ` ${sanitizeForTerminal(check)}${from} (${sanitizeForTerminal(tier)}line ${line}): ${sanitizeForTerminal(excerpt)}`,\n ),\n );\n }\n return rendered;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\nexport type StyleFormat = Parameters<typeof styleText>[0];\n\n/**\n * Does `stream` take ANSI color? Node's own rule (`shouldColorize`): FORCE_COLOR\n * wins when set, otherwise a TTY whose color depth is above 2 (which reads\n * NO_COLOR, NODE_DISABLE_COLORS and TERM). Decided here because styleText only\n * checks the stream from Node 22.13 and colors unconditionally before it.\n */\nexport function colorCapable(stream: unknown, env: NodeJS.ProcessEnv = process.env): boolean {\n const force = env.FORCE_COLOR;\n if (force !== undefined) return ['', '1', 'true', '2', '3'].includes(force);\n return stream instanceof WriteStream && stream.isTTY && stream.getColorDepth(env) > 2;\n}\n\n/** `text` in `format` when `stream` takes color, else plain. */\nexport function style(format: StyleFormat, text: string, stream: unknown = process.stdout): string {\n return colorCapable(stream) ? styleText(format, text, { validateStream: false }) : text;\n}\n\n/** Color a human line for stdout. A test or redirected sink is no TTY, so it comes out plain. */\nexport function paint(io: Io, format: StyleFormat, text: string): string {\n return style(format, text, io.stdout);\n}\n","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'SEARCH_NOT_FOUND',\n // A 429 from the anonymous search/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n // A send that reverted or produced no receipt AFTER the human approved it and\n // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.\n 'SEND_FAILED',\n // `tenjin delete`: the soft-delete failed AFTER the human confirmed it (exit\n // 4). Its own code rather than PUBLISH_FAILED because the two say opposite\n // things about what is now live, and an agent reporting the outcome to a user\n // must not read \"the piece is still up\" as \"the piece went up\".\n 'DELETE_FAILED',\n // `tenjin update`: the npm install it spawned exited nonzero or never started.\n // Exit 1, not the post-decision class: nothing is half-written that the\n // operator must reconcile, and the old build keeps running.\n 'UPDATE_FAILED',\n // `tenjin pay` Bazaar lane: the live 402 does not match what a configured\n // registry publicly advertises for this resource (understood-but-refused, 3);\n // nothing was signed and nothing was spent.\n 'REGISTRY_MISMATCH',\n // The seller's 402 challenge exceeds this process's response-header limit, so\n // its terms could never be read (understood-but-refused, 3). Nothing was\n // signed and nothing was sent; a retry changes nothing without an operator\n // raising `--max-http-header-size` on the process that runs the CLI.\n 'CHALLENGE_TOO_LARGE',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\n/**\n * \"A newer tenjin-cli exists\", carried on the envelope so an AGENT learns it.\n *\n * The daily check's other surface is one dim stderr line, which only a human at\n * a terminal ever sees; on the machines that run this CLI most, nobody does.\n * This field is how the agent driving the command finds out it can run\n * `tenjin update` itself. Read from the check's cache, never fetched here: the\n * envelope must not wait on a network call it did not need.\n */\nexport const UpdateAvailableSchema = z.object({\n current: z.string(),\n latest: z.string(),\n});\nexport type UpdateAvailable = z.infer<typeof UpdateAvailableSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n /** Present only when a newer version is known and update.mode is not `off`. */\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discriminatedUnion('ok', [\n SuccessEnvelopeSchema,\n FailureEnvelopeSchema,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KAAK,IAAI,CAAC;AAAA,CAAI;AAC5D;AAUO,SAAS,aAAa,QAAiB,MAAyB,QAAQ,KAAc;AAC3F,QAAM,QAAQ,IAAI;AAClB,MAAI,UAAU,OAAW,QAAO,CAAC,IAAI,KAAK,QAAQ,KAAK,GAAG,EAAE,SAAS,KAAK;AAC1E,SAAO,kBAAkB,eAAe,OAAO,SAAS,OAAO,cAAc,GAAG,IAAI;AACtF;AAGO,SAAS,MAAM,QAAqB,MAAc,SAAkB,QAAQ,QAAgB;AACjG,SAAO,aAAa,MAAM,IAAI,UAAU,QAAQ,MAAM,EAAE,gBAAgB,MAAM,CAAC,IAAI;AACrF;AAGO,SAAS,MAAM,IAAQ,QAAqB,MAAsB;AACvE,SAAO,MAAM,QAAQ,MAAM,GAAG,MAAM;AACtC;","names":[]}
1
+ {"version":3,"sources":["../src/lib/output.ts","../src/schemas.ts"],"sourcesContent":["import { WriteStream } from 'node:tty';\nimport { styleText } from 'node:util';\nimport { CliError } from './errors';\nimport type { StdinInput } from './stdin';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { UpdateAvailable } from '../schemas';\nimport type { FailureEnvelope, OutputError, SuccessEnvelope } from '../schemas';\n\n/**\n * Injected streams + TTY facts. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` describes stdout; the separate `--json` flag (passed to the emit\n * functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output. `stdin` is\n * optional for compatibility with command-core contexts that never read it;\n * defaultIo supplies the real stream, and only the CLI forwards that capability\n * to commands that accept Markdown on stdin.\n */\nexport interface Io {\n stdin?: StdinInput;\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdin: { stream: process.stdin, isTTY: Boolean(process.stdin.isTTY) },\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, the JSON envelope is emitted even at a TTY. */\n json?: boolean;\n /**\n * \"A newer tenjin-cli exists\", from the daily check's cache. Rides the\n * envelope so the AGENT running the command learns it; the human at a TTY\n * gets the dim stderr line instead, and neither path fetches anything.\n */\n updateAvailable?: UpdateAvailable | null;\n}\n\n/**\n * The two pure envelope builders, shared by the CLI's emit functions and the MCP\n * adapter so both surfaces produce the identical wire object by construction. They\n * hold no I/O and no --json branching: they turn a (command, data) or a normalized\n * CliError into the exact object that goes to stdout / structuredContent.\n */\nexport function buildSuccessEnvelope(\n command: string,\n data: unknown,\n updateAvailable?: UpdateAvailable | null,\n): SuccessEnvelope {\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: true,\n data,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\nexport function buildFailureEnvelope(\n command: string,\n err: CliError,\n updateAvailable?: UpdateAvailable | null,\n): FailureEnvelope {\n const error: OutputError = {\n code: err.code,\n message: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: false,\n error,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\n/**\n * Output contract (human-first): at a TTY without `--json`, print ONLY the human\n * rendering to stdout, no JSON envelope. With `--json`, or when stdout is not a\n * TTY (a pipe, an agent), print exactly one JSON envelope to stdout and nothing\n * else. Exit codes are identical on both paths; only the stdout shape differs.\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n if (humanMode(io, opts)) {\n writeLines(io.stdout, humanLines);\n return;\n }\n writeJson(io.stdout, buildSuccessEnvelope(command, data, opts.updateAvailable));\n}\n\n/**\n * The failure half of the same contract: at a TTY without `--json`, a red error\n * line plus a `fix` line to stdout and no envelope; otherwise exactly one failure\n * envelope to stdout. Accepts a CliError or any thrown value (non-CliError\n * normalizes to INTERNAL). Returns the normalized CliError so the caller reads its\n * `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n if (humanMode(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n // Scan findings are the one detail shape a human needs inline: without them\n // an interactive publish hitting NEEDS_CONFIRMATION / PUBLISH_BLOCKED sees\n // the count but not WHICH lines tripped. Every other shape is machine-only.\n lines.push(...findingLines(io, cliErr.details));\n writeLines(io.stdout, lines);\n return cliErr;\n }\n writeJson(io.stdout, buildFailureEnvelope(command, cliErr, opts.updateAvailable));\n return cliErr;\n}\n\n/**\n * One dim advisory line on stderr, human mode only. This is for facts that belong\n * to NO command's result — an unreadable spend ledger, a newer release on npm —\n * so they can never join the envelope on stdout or reach a machine consumer at\n * all. Sanitized here rather than by each caller: what these lines quote (a\n * registry version string, a parse error) is not the command's own prose.\n */\nexport function emitNotice(io: Io, text: string, opts: EmitOptions = {}): void {\n if (!humanMode(io, opts)) return;\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * The same dim stderr line, delivered whatever the surface is: no TTY gate and no\n * `--json` gate. Only for an advisory a piped or agent-driven run must not miss,\n * which today is two things: a WRITE to the operator's own files, and `fund`'s\n * checkout link, which expires long before the stdout envelope that also carries\n * it is written. Anything a piped run can simply do without belongs in\n * {@link emitNotice} instead. stdout is untouched either way, so the exactly-one\n * JSON object contract is unaffected.\n */\nexport function emitWriteNotice(io: Io, text: string): void {\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * Every escape sequence a terminal writes: CSI (colour, cursor), OSC — which\n * covers the OSC-8 hyperlinks pnpm wraps package names in, terminated by BEL\n * or ST — charset selection, and a stray ESC with a single final byte.\n *\n * ONE COPY, because the other reader is the failure lane: `stripAnsi`\n * (`hooks/text.ts`) takes colour off a runner's output before the arm scans it\n * for a diagnostic, and a pattern that misses OSC-8 leaves `]8;;https://…`\n * sitting in front of the very line the start-anchored markers must match.\n * That reader CANNOT call {@link sanitizeForTerminal}: this is only its first\n * clause, and the second strips `\\n`, which would flatten the output it is\n * about to split into lines.\n *\n * Safe to share despite the `g` flag: both callers use it through\n * `String.replace`, which starts at 0 and resets `lastIndex`. Do not `test()`\n * or `exec()` it.\n */\nexport const ANSI_ESCAPE_RE =\n // eslint-disable-next-line no-control-regex\n /\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g;\n\n/**\n * Strip ANSI escape sequences, C0/C1 control characters, Unicode bidirectional\n * formatting, and invisible tag/BOM characters from a string headed for a\n * terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm, a right-to-left override to reorder\n * that same line on screen into one that reads as a different price, or tag\n * characters to carry a payload that draws as nothing at all. It is not\n * applied to whole human lines here because trusted callers (doctor) paint\n * their own ANSI colors. JSON stdout is untouched: JSON.stringify escapes C0\n * controls itself, but the bidi and tag/BOM sets ride through it raw, and that\n * is deliberate rather than covered — the envelope is machine-read data whose\n * bytes must be what the server said, and a consumer reading codepoints is not\n * deceived by rendering order the way a human reading a drawn line is.\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n .replace(ANSI_ESCAPE_RE, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n // The UAX#9 directional formatting set: the marks (LRM/RLM/ALM), the\n // embeddings and overrides (U+202A-U+202E), and the isolates\n // (U+2066-U+2069). Removed, not escaped, so what a human reads is the\n // order the bytes are in. Deliberately this set and NOT all of category\n // Cf: U+200D (ZWJ) joins legitimate emoji sequences, and dropping it\n // would corrupt honest titles to defend against dishonest ones.\n .replace(/[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n // The Unicode tag block (U+E0000-U+E007F) and the BOM/ZWNBSP, neither of\n // which has a legitimate mid-title use. Tag characters render as nothing\n // at all, so a payload spelled in them is invisible in the line a human\n // is reading and in the line they would paste back to report it.\n //\n // The three RGI subdivision flags are the exception and survive\n // byte-identical: they are ordinary title content. The whitelist is those\n // three sequences and NOT \"any well-formed tag sequence\", because a\n // non-RGI sequence draws as a bare black flag with the payload hidden\n // behind it, which is the exact channel this closes.\n //\n // Kept for the same reason as ZWJ above: U+200B (ZWSP) hints line breaks\n // in CJK and U+200C (ZWNJ) is orthographically required in Persian, so\n // stripping them would corrupt honest titles to defend against dishonest\n // ones.\n .replace(\n /(\\u{1F3F4}\\u{E0067}\\u{E0062}(?:\\u{E0065}\\u{E006E}\\u{E0067}|\\u{E0073}\\u{E0063}\\u{E0074}|\\u{E0077}\\u{E006C}\\u{E0073})\\u{E007F})|[\\u{E0000}-\\u{E007F}\\u{FEFF}]/gu,\n (_match, rgiFlag: string | undefined) => rgiFlag ?? '',\n )\n );\n}\n\n/**\n * The same strip, for text that ships to OTHER PEOPLE rather than to this\n * terminal: a post's title, its public excerpt, and every free-text field of the\n * answer card a buyer reads before paying.\n *\n * The threat is the same one {@link sanitizeForTerminal} closes, one hop further\n * out. None of this text is necessarily typed by the person publishing: a card\n * question can be prefilled from a stored search, and every field can arrive over\n * MCP from an agent that read them off a fetched page. `trim()` removes neither a\n * CSI sequence nor a right-to-left override, so without this a payload rides into\n * the marketplace and renders in every future reader's terminal.\n *\n * Newlines and tabs fold to a single space FIRST, because these are all\n * single-line display fields and a bare strip would join the words on either side\n * of a line break into one. NOT for the post BODY: that is the author's document,\n * markdown and all, and rewriting it is not this function's business.\n */\nexport function sanitizeWireText(text: string): string {\n return sanitizeForTerminal(text.replace(/[\\r\\n\\t]+/g, ' ')).trim();\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\n/** True in human-first mode: a TTY without --json. Otherwise the JSON envelope wins. */\nfunction humanMode(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\n/**\n * Render `details.findings` (the scan-finding projection publish attaches to\n * NEEDS_CONFIRMATION / PUBLISH_BLOCKED) as one dim line per finding:\n * ` <check> (line N): <excerpt>`. The excerpt is already masked for secret\n * findings at the source; sanitize it anyway since it can echo file content.\n * Returns [] for any other details shape, so no other error leaks a detail dump.\n *\n * A finding the SERVER gate contributed carries a `source`, and the marker is\n * printed because it is the difference between \"fix your file\" and \"the\n * marketplace refused this\": the detector may be one this release predates, so\n * the line has to stand on the server's own words rather than on recognition.\n * The tier rides the same line, for the payloads that mix block and warn.\n */\nfunction findingLines(io: Io, details: unknown): string[] {\n if (typeof details !== 'object' || details === null || !('findings' in details)) return [];\n const { findings } = details as { findings: unknown };\n if (!Array.isArray(findings) || findings.length === 0) return [];\n const rendered: string[] = [];\n for (const f of findings) {\n if (typeof f !== 'object' || f === null) continue;\n const { check, line, excerpt, source, severity } = f as {\n check?: unknown;\n line?: unknown;\n excerpt?: unknown;\n source?: unknown;\n severity?: unknown;\n };\n if (typeof check !== 'string' || typeof line !== 'number' || typeof excerpt !== 'string') {\n continue;\n }\n const from = source === 'server' ? ' [server]' : source === 'both' ? ' [local+server]' : '';\n // THE TIER IS PRINTED because one payload can mix them: a `scan_blocked`\n // envelope ships the block finding alongside the warns the same pass found,\n // and without the tier nothing on the page says which one is the refusal.\n // An open string, sanitized like the rest: the server owns its own tier names.\n const tier = typeof severity === 'string' && severity.length > 0 ? `${severity}, ` : '';\n // The detector id is sanitized too: on a server finding it is a name this\n // release may never have seen, so it is untrusted text like the excerpt.\n rendered.push(\n paint(\n io,\n 'dim',\n ` ${sanitizeForTerminal(check)}${from} (${sanitizeForTerminal(tier)}line ${line}): ${sanitizeForTerminal(excerpt)}`,\n ),\n );\n }\n return rendered;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\nexport type StyleFormat = Parameters<typeof styleText>[0];\n\n/**\n * Does `stream` take ANSI color? Node's own rule (`shouldColorize`): FORCE_COLOR\n * wins when set, otherwise a TTY whose color depth is above 2 (which reads\n * NO_COLOR, NODE_DISABLE_COLORS and TERM). Decided here because styleText only\n * checks the stream from Node 22.13 and colors unconditionally before it.\n */\nexport function colorCapable(stream: unknown, env: NodeJS.ProcessEnv = process.env): boolean {\n const force = env.FORCE_COLOR;\n if (force !== undefined) return ['', '1', 'true', '2', '3'].includes(force);\n return stream instanceof WriteStream && stream.isTTY && stream.getColorDepth(env) > 2;\n}\n\n/** `text` in `format` when `stream` takes color, else plain. */\nexport function style(format: StyleFormat, text: string, stream: unknown = process.stdout): string {\n return colorCapable(stream) ? styleText(format, text, { validateStream: false }) : text;\n}\n\n/** Color a human line for stdout. A test or redirected sink is no TTY, so it comes out plain. */\nexport function paint(io: Io, format: StyleFormat, text: string): string {\n return style(format, text, io.stdout);\n}\n","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'SEARCH_NOT_FOUND',\n // A 429 from the anonymous search/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n // A send that reverted or produced no receipt AFTER the human approved it and\n // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.\n 'SEND_FAILED',\n // `tenjin delete`: the soft-delete failed AFTER the human confirmed it (exit\n // 4). Its own code rather than PUBLISH_FAILED because the two say opposite\n // things about what is now live, and an agent reporting the outcome to a user\n // must not read \"the piece is still up\" as \"the piece went up\".\n 'DELETE_FAILED',\n // `tenjin update`: the npm install it spawned exited nonzero or never started.\n // Exit 1, not the post-decision class: nothing is half-written that the\n // operator must reconcile, and the old build keeps running.\n 'UPDATE_FAILED',\n // `tenjin pay` Bazaar lane: the live 402 does not match what a configured\n // registry publicly advertises for this resource (understood-but-refused, 3);\n // nothing was signed and nothing was spent.\n 'REGISTRY_MISMATCH',\n // The seller's 402 challenge exceeds this process's response-header limit, so\n // its terms could never be read (understood-but-refused, 3). Nothing was\n // signed and nothing was sent; a retry changes nothing without an operator\n // raising `--max-http-header-size` on the process that runs the CLI.\n 'CHALLENGE_TOO_LARGE',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\n/**\n * \"A newer tenjin-cli exists\", carried on the envelope so an AGENT learns it.\n *\n * The daily check's other surface is one dim stderr line, which only a human at\n * a terminal ever sees; on the machines that run this CLI most, nobody does.\n * This field is how the agent driving the command finds out it can run\n * `tenjin update` itself. Read from the check's cache, never fetched here: the\n * envelope must not wait on a network call it did not need.\n */\nexport const UpdateAvailableSchema = z.object({\n current: z.string(),\n latest: z.string(),\n});\nexport type UpdateAvailable = z.infer<typeof UpdateAvailableSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n /** Present only when a newer version is known and update.mode is not `off`. */\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discriminatedUnion('ok', [\n SuccessEnvelopeSchema,\n FailureEnvelopeSchema,\n]);\nexport type OutputEnvelope = z.infer<typeof OutputEnvelopeSchema>;\n"],"mappings":";;;;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB;;;ACMnB,IAAM,iBAAiB;AAQvB,IAAM,kBAAkB,iBAAE,KAAK;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AACF,CAAC;AASM,IAAM,cAAc,iBAAE,OAAO;AAAA,EAClC,QAAQ,iBAAE,OAAO;AAAA,EACjB,KAAK,iBAAE,OAAO;AAChB,CAAC;AAGM,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACxC,MAAM;AAAA,EACN,SAAS,iBAAE,OAAO;AAAA,EAClB,KAAK,iBAAE,OAAO,EAAE,SAAS;AAAA,EACzB,SAAS,iBAAE,QAAQ,EAAE,SAAS;AAChC,C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