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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (495) hide show
  1. package/NOTICE.md +110 -0
  2. package/README.md +87 -81
  3. package/dist/{_esm-BIN7VY2L.js → _esm-2KST7HQ7.js} +7 -7
  4. package/dist/alive-5TV22PNF.js +51 -0
  5. package/dist/auth-XI7BJFLW.js +47 -0
  6. package/dist/{auto-update-Y24UL56V.js → auto-update-7L24KDWA.js} +4 -5
  7. package/dist/balance-DFHC6XEU.js +71 -0
  8. package/dist/{ccip-DHDFKTQV.js → ccip-HOW3DZYF.js} +4 -4
  9. package/dist/chunk-24XKUN2S.js +202 -0
  10. package/dist/chunk-24XKUN2S.js.map +1 -0
  11. package/dist/chunk-2L7TDGLV.js +56 -0
  12. package/dist/chunk-2L7TDGLV.js.map +1 -0
  13. package/dist/{chunk-C2Q76BVM.js → chunk-2U7H35IP.js} +29 -7
  14. package/dist/chunk-2U7H35IP.js.map +1 -0
  15. package/dist/chunk-2W4DQQUU.js +176 -0
  16. package/dist/chunk-2W4DQQUU.js.map +1 -0
  17. package/dist/{chunk-LRW6S53P.js → chunk-34SAECKZ.js} +35 -11
  18. package/dist/chunk-34SAECKZ.js.map +1 -0
  19. package/dist/{chunk-2I4QTOLB.js → chunk-3MZ7DYRO.js} +1 -1
  20. package/dist/chunk-3MZ7DYRO.js.map +1 -0
  21. package/dist/{chunk-RVPYTUP4.js → chunk-3Y2EHT4F.js} +13 -9
  22. package/dist/chunk-3Y2EHT4F.js.map +1 -0
  23. package/dist/chunk-3Y6BHIN6.js +169 -0
  24. package/dist/chunk-3Y6BHIN6.js.map +1 -0
  25. package/dist/{chunk-4K7TQHNP.js → chunk-3YPL6T3P.js} +17 -33
  26. package/dist/chunk-3YPL6T3P.js.map +1 -0
  27. package/dist/{chunk-E7SW44LM.js → chunk-44MVIRZH.js} +121 -6
  28. package/dist/chunk-44MVIRZH.js.map +1 -0
  29. package/dist/chunk-45MMSBHA.js +321 -0
  30. package/dist/chunk-45MMSBHA.js.map +1 -0
  31. package/dist/{chunk-3FMZGI7I.js → chunk-4CE6TMI5.js} +1 -1
  32. package/dist/chunk-4CE6TMI5.js.map +1 -0
  33. package/dist/{chunk-QXP3Z3JN.js → chunk-4MBCJFY4.js} +35 -3
  34. package/dist/chunk-4MBCJFY4.js.map +1 -0
  35. package/dist/chunk-4TPL54KW.js +227 -0
  36. package/dist/chunk-4TPL54KW.js.map +1 -0
  37. package/dist/chunk-54ELBTKE.js +1615 -0
  38. package/dist/chunk-54ELBTKE.js.map +1 -0
  39. package/dist/{chunk-NDGZDTSJ.js → chunk-5F4OB5B3.js} +115 -57
  40. package/dist/chunk-5F4OB5B3.js.map +1 -0
  41. package/dist/chunk-5HN4KVQU.js +3348 -0
  42. package/dist/chunk-5HN4KVQU.js.map +1 -0
  43. package/dist/{chunk-ZDZERB6L.js → chunk-5J4E5GYI.js} +572 -407
  44. package/dist/chunk-5J4E5GYI.js.map +1 -0
  45. package/dist/{chunk-ZNNXRNFD.js → chunk-5N4GGUBN.js} +48 -6
  46. package/dist/chunk-5N4GGUBN.js.map +1 -0
  47. package/dist/chunk-5USBZ2MU.js +58 -0
  48. package/dist/chunk-5USBZ2MU.js.map +1 -0
  49. package/dist/chunk-64WOMNYR.js +183 -0
  50. package/dist/chunk-64WOMNYR.js.map +1 -0
  51. package/dist/{chunk-ILNIZ5I2.js → chunk-65RS4LQS.js} +1825 -1715
  52. package/dist/chunk-65RS4LQS.js.map +1 -0
  53. package/dist/{chunk-IE7P2BZE.js → chunk-6QMDUDF2.js} +3 -3
  54. package/dist/{chunk-IADZOXKN.js → chunk-7SLOTLO7.js} +19 -697
  55. package/dist/chunk-7SLOTLO7.js.map +1 -0
  56. package/dist/{chunk-WFSPCCVW.js → chunk-7V25UAQO.js} +99 -99
  57. package/dist/{chunk-WFSPCCVW.js.map → chunk-7V25UAQO.js.map} +1 -1
  58. package/dist/chunk-BGA4DO5M.js +719 -0
  59. package/dist/chunk-BGA4DO5M.js.map +1 -0
  60. package/dist/chunk-BVP7YK2J.js +706 -0
  61. package/dist/chunk-BVP7YK2J.js.map +1 -0
  62. package/dist/chunk-C265QIMJ.js +83 -0
  63. package/dist/chunk-C265QIMJ.js.map +1 -0
  64. package/dist/{chunk-XQJXNMSB.js → chunk-CRG54LEB.js} +1 -1
  65. package/dist/chunk-CRG54LEB.js.map +1 -0
  66. package/dist/{chunk-KG3D7FIF.js → chunk-CZJOMUBP.js} +2 -2
  67. package/dist/{chunk-36RVGZNY.js → chunk-D6M3ZK66.js} +22 -39
  68. package/dist/chunk-D6M3ZK66.js.map +1 -0
  69. package/dist/{chunk-3UCIG4TG.js → chunk-DI4QAGRZ.js} +1 -11
  70. package/dist/chunk-DI4QAGRZ.js.map +1 -0
  71. package/dist/{chunk-JKKAIPTU.js → chunk-DIH2G3YG.js} +47 -10
  72. package/dist/chunk-DIH2G3YG.js.map +1 -0
  73. package/dist/chunk-DJ36BM62.js +78 -0
  74. package/dist/chunk-DJ36BM62.js.map +1 -0
  75. package/dist/chunk-DTEWAVNE.js +114 -0
  76. package/dist/chunk-DTEWAVNE.js.map +1 -0
  77. package/dist/chunk-F2KJAJ7T.js +13 -0
  78. package/dist/chunk-F2KJAJ7T.js.map +1 -0
  79. package/dist/{chunk-BF4XHEQK.js → chunk-F3QPGYOY.js} +6 -6
  80. package/dist/chunk-F3QPGYOY.js.map +1 -0
  81. package/dist/{chunk-3GNJXKIT.js → chunk-F43CV6UC.js} +2 -2
  82. package/dist/{chunk-J57UC3DD.js → chunk-FKVJKLPI.js} +3 -3
  83. package/dist/{chunk-V2LQLN5H.js → chunk-FYFHH7V5.js} +59 -8
  84. package/dist/{chunk-V2LQLN5H.js.map → chunk-FYFHH7V5.js.map} +1 -1
  85. package/dist/chunk-GAJC4BQZ.js +1096 -0
  86. package/dist/chunk-GAJC4BQZ.js.map +1 -0
  87. package/dist/{chunk-DOQGNFHM.js → chunk-GH5UKMZD.js} +2 -12
  88. package/dist/{chunk-DOQGNFHM.js.map → chunk-GH5UKMZD.js.map} +1 -1
  89. package/dist/{chunk-WYXUQGOL.js → chunk-HAZAN4UM.js} +7 -6
  90. package/dist/chunk-HAZAN4UM.js.map +1 -0
  91. package/dist/chunk-HI5XQOX2.js +393 -0
  92. package/dist/chunk-HI5XQOX2.js.map +1 -0
  93. package/dist/chunk-HKGUKAQW.js +488 -0
  94. package/dist/chunk-HKGUKAQW.js.map +1 -0
  95. package/dist/{chunk-SO3XRZPX.js → chunk-HPRVFJPM.js} +6 -6
  96. package/dist/{chunk-L6JEXB3E.js → chunk-HQR4BWKX.js} +3 -131
  97. package/dist/chunk-HQR4BWKX.js.map +1 -0
  98. package/dist/chunk-HZKANST2.js +177 -0
  99. package/dist/chunk-HZKANST2.js.map +1 -0
  100. package/dist/{chunk-UUGOUOVT.js → chunk-I557SAOM.js} +8 -2
  101. package/dist/chunk-I557SAOM.js.map +1 -0
  102. package/dist/{chunk-TC2WZLSC.js → chunk-IGLWLH73.js} +8 -7
  103. package/dist/chunk-IGLWLH73.js.map +1 -0
  104. package/dist/chunk-ILWCKCOI.js +58 -0
  105. package/dist/chunk-ILWCKCOI.js.map +1 -0
  106. package/dist/{chunk-2GP3HRYK.js → chunk-INSIW65E.js} +182 -182
  107. package/dist/{chunk-MPZUYCAP.js → chunk-IULCDMVG.js} +12 -1
  108. package/dist/chunk-IULCDMVG.js.map +1 -0
  109. package/dist/{chunk-INTFHMU4.js → chunk-IVNSUAVC.js} +25 -26
  110. package/dist/chunk-IVNSUAVC.js.map +1 -0
  111. package/dist/chunk-JDQZCREI.js +87 -0
  112. package/dist/chunk-JDQZCREI.js.map +1 -0
  113. package/dist/chunk-JHFFUVON.js +1050 -0
  114. package/dist/chunk-JHFFUVON.js.map +1 -0
  115. package/dist/{chunk-RL5UUDT4.js → chunk-JNUKLSMZ.js} +3 -3
  116. package/dist/chunk-JTILUN4W.js +2933 -0
  117. package/dist/chunk-JTILUN4W.js.map +1 -0
  118. package/dist/{chunk-OJNTCYQQ.js → chunk-JTX3BUDK.js} +37 -53
  119. package/dist/chunk-JTX3BUDK.js.map +1 -0
  120. package/dist/{chunk-X5ZBP3IY.js → chunk-JUUBBBY5.js} +2 -2
  121. package/dist/chunk-JUUBBBY5.js.map +1 -0
  122. package/dist/chunk-JWAK7JQB.js +15 -0
  123. package/dist/chunk-JWAK7JQB.js.map +1 -0
  124. package/dist/{chunk-UXZONNEQ.js → chunk-K5KNGC4I.js} +34 -31
  125. package/dist/chunk-K5KNGC4I.js.map +1 -0
  126. package/dist/chunk-KAQ4Q3TO.js +135 -0
  127. package/dist/chunk-KAQ4Q3TO.js.map +1 -0
  128. package/dist/chunk-KFVJYLVL.js +125 -0
  129. package/dist/chunk-KFVJYLVL.js.map +1 -0
  130. package/dist/chunk-KGUE5AVX.js +69 -0
  131. package/dist/chunk-KGUE5AVX.js.map +1 -0
  132. package/dist/{chunk-FVIGCDSV.js → chunk-KLDMLWXT.js} +11 -85
  133. package/dist/chunk-KLDMLWXT.js.map +1 -0
  134. package/dist/chunk-KNKDMTHU.js +453 -0
  135. package/dist/chunk-KNKDMTHU.js.map +1 -0
  136. package/dist/chunk-LDA6TAYQ.js +95 -0
  137. package/dist/chunk-LDA6TAYQ.js.map +1 -0
  138. package/dist/chunk-LWSSIZOY.js +347 -0
  139. package/dist/chunk-LWSSIZOY.js.map +1 -0
  140. package/dist/{chunk-ZURZHELF.js → chunk-MAHNZA6C.js} +158 -41
  141. package/dist/chunk-MAHNZA6C.js.map +1 -0
  142. package/dist/chunk-MEWZCIA6.js +220 -0
  143. package/dist/chunk-MEWZCIA6.js.map +1 -0
  144. package/dist/{chunk-2SNUOHAT.js → chunk-MEZJ3I63.js} +49 -1
  145. package/dist/chunk-MEZJ3I63.js.map +1 -0
  146. package/dist/chunk-MJDO4EXD.js +353 -0
  147. package/dist/chunk-MJDO4EXD.js.map +1 -0
  148. package/dist/chunk-NJA6NT3A.js +6595 -0
  149. package/dist/chunk-NJA6NT3A.js.map +1 -0
  150. package/dist/{chunk-LHHMV4GU.js → chunk-NVSKJPRC.js} +1 -1
  151. package/dist/{chunk-LHHMV4GU.js.map → chunk-NVSKJPRC.js.map} +1 -1
  152. package/dist/{chunk-4YOZGGTZ.js → chunk-OC7K2DVZ.js} +5 -5
  153. package/dist/chunk-OC7K2DVZ.js.map +1 -0
  154. package/dist/chunk-ODRPASFP.js +2078 -0
  155. package/dist/chunk-ODRPASFP.js.map +1 -0
  156. package/dist/chunk-OJJFANO6.js +133 -0
  157. package/dist/chunk-OJJFANO6.js.map +1 -0
  158. package/dist/{chunk-JNJWBTU2.js → chunk-OQWPRFAC.js} +332 -882
  159. package/dist/chunk-OQWPRFAC.js.map +1 -0
  160. package/dist/chunk-P4I7BFNJ.js +11 -0
  161. package/dist/chunk-P4I7BFNJ.js.map +1 -0
  162. package/dist/{chunk-SNNSAGMT.js → chunk-P6YQWIT2.js} +4058 -4039
  163. package/dist/chunk-P6YQWIT2.js.map +1 -0
  164. package/dist/{chunk-JRGFKVAZ.js → chunk-PETQ5WEA.js} +2 -2
  165. package/dist/{chunk-HMWYAUA6.js → chunk-Q6RSJCXB.js} +29 -69
  166. package/dist/chunk-Q6RSJCXB.js.map +1 -0
  167. package/dist/{chunk-U3IKUGRP.js → chunk-QKEUKBRK.js} +17 -23
  168. package/dist/chunk-QKEUKBRK.js.map +1 -0
  169. package/dist/{chunk-2RWB7RKE.js → chunk-QKYUCITR.js} +174 -5814
  170. package/dist/chunk-QKYUCITR.js.map +1 -0
  171. package/dist/chunk-QQDPRTLP.js +127 -0
  172. package/dist/chunk-QQDPRTLP.js.map +1 -0
  173. package/dist/chunk-QQYCYAKI.js +79 -0
  174. package/dist/chunk-QQYCYAKI.js.map +1 -0
  175. package/dist/chunk-R4KDH477.js +1064 -0
  176. package/dist/chunk-R4KDH477.js.map +1 -0
  177. package/dist/chunk-R5TR2DIK.js +119 -0
  178. package/dist/chunk-R5TR2DIK.js.map +1 -0
  179. package/dist/chunk-R62PKTAG.js +66 -0
  180. package/dist/chunk-R62PKTAG.js.map +1 -0
  181. package/dist/{chunk-BFDQ4WNW.js → chunk-RFZA7PSM.js} +4 -5
  182. package/dist/chunk-RFZA7PSM.js.map +1 -0
  183. package/dist/chunk-RGCPELQN.js +219 -0
  184. package/dist/chunk-RGCPELQN.js.map +1 -0
  185. package/dist/chunk-RGVCOG2S.js +910 -0
  186. package/dist/chunk-RGVCOG2S.js.map +1 -0
  187. package/dist/chunk-SOLNJ3AZ.js +209 -0
  188. package/dist/chunk-SOLNJ3AZ.js.map +1 -0
  189. package/dist/chunk-TFT2X7SH.js +77 -0
  190. package/dist/chunk-TFT2X7SH.js.map +1 -0
  191. package/dist/chunk-TUCKEEXE.js +2 -0
  192. package/dist/chunk-TVWCLUBI.js +293 -0
  193. package/dist/chunk-TVWCLUBI.js.map +1 -0
  194. package/dist/chunk-U4TRWSVE.js +78 -0
  195. package/dist/chunk-U4TRWSVE.js.map +1 -0
  196. package/dist/chunk-UIB33QQP.js +379 -0
  197. package/dist/chunk-UIB33QQP.js.map +1 -0
  198. package/dist/chunk-V6GIVALQ.js +1889 -0
  199. package/dist/chunk-V6GIVALQ.js.map +1 -0
  200. package/dist/chunk-VHXCPXUS.js +366 -0
  201. package/dist/chunk-VHXCPXUS.js.map +1 -0
  202. package/dist/{chunk-HGZEPQUT.js → chunk-VU6GMWF6.js} +17 -8
  203. package/dist/chunk-VU6GMWF6.js.map +1 -0
  204. package/dist/chunk-VWZYE3NC.js +8415 -0
  205. package/dist/chunk-VWZYE3NC.js.map +1 -0
  206. package/dist/{chunk-AGMVASXZ.js → chunk-W2GXIARJ.js} +88 -11
  207. package/dist/chunk-W2GXIARJ.js.map +1 -0
  208. package/dist/chunk-W4G3K3V7.js +288 -0
  209. package/dist/chunk-W4G3K3V7.js.map +1 -0
  210. package/dist/chunk-W74LJ5OT.js +588 -0
  211. package/dist/chunk-W74LJ5OT.js.map +1 -0
  212. package/dist/chunk-W7ELYLYK.js +233 -0
  213. package/dist/chunk-W7ELYLYK.js.map +1 -0
  214. package/dist/{chunk-BPMWXTFX.js → chunk-WFZX352D.js} +7 -7
  215. package/dist/chunk-WXA3WTPF.js +20 -0
  216. package/dist/chunk-WXA3WTPF.js.map +1 -0
  217. package/dist/chunk-XRGFH7FI.js +454 -0
  218. package/dist/chunk-XRGFH7FI.js.map +1 -0
  219. package/dist/chunk-XSCGUO2U.js +330 -0
  220. package/dist/chunk-XSCGUO2U.js.map +1 -0
  221. package/dist/chunk-XWROSMI5.js +1039 -0
  222. package/dist/chunk-XWROSMI5.js.map +1 -0
  223. package/dist/chunk-Y2EXZ47H.js +40 -0
  224. package/dist/chunk-Y2EXZ47H.js.map +1 -0
  225. package/dist/chunk-YJGEVBKZ.js +47 -0
  226. package/dist/chunk-YJGEVBKZ.js.map +1 -0
  227. package/dist/{chunk-6CMM6YCB.js → chunk-YWWMISDY.js} +2 -2
  228. package/dist/{chunk-WXA2BWTE.js → chunk-ZCT5DJ3G.js} +2 -48
  229. package/dist/chunk-ZCT5DJ3G.js.map +1 -0
  230. package/dist/chunk-ZEYA2WWX.js +982 -0
  231. package/dist/chunk-ZEYA2WWX.js.map +1 -0
  232. package/dist/chunk-ZRC7Z5X3.js +82 -0
  233. package/dist/chunk-ZRC7Z5X3.js.map +1 -0
  234. package/dist/{chunk-3AIHRXKO.js → chunk-ZS7JIUJ3.js} +12 -10
  235. package/dist/chunk-ZS7JIUJ3.js.map +1 -0
  236. package/dist/{clack-EZ7TDWQU.js → clack-Q4RNC5VE.js} +2 -6
  237. package/dist/{claude-cli-2YKABJJZ.js → claude-cli-GIIHOBGT.js} +4 -2
  238. package/dist/claude-install-BAUSJMW3.js +64 -0
  239. package/dist/{cli-E36SPKBW.js → cli-QY4KKA3D.js} +632 -150
  240. package/dist/cli-QY4KKA3D.js.map +1 -0
  241. package/dist/client-3YQKORVK.js +710 -0
  242. package/dist/client-3YQKORVK.js.map +1 -0
  243. package/dist/{codex-event-ZO2GEFE6.js → codex-event-EUTCAOTQ.js} +3 -5
  244. package/dist/{codex-host-KECJVTA2.js → codex-host-ZON3S6HU.js} +7 -7
  245. package/dist/{codex-install-HQZDGFXW.js → codex-install-HZV2DOAB.js} +242 -88
  246. package/dist/codex-install-HZV2DOAB.js.map +1 -0
  247. package/dist/config-QZOBMTEL.js +57 -0
  248. package/dist/config-names-Z5NZD5R2.js +224 -0
  249. package/dist/config-names-Z5NZD5R2.js.map +1 -0
  250. package/dist/config-rules-YOYHS6YL.js +55 -0
  251. package/dist/config-subagents-WQV2ZAD5.js +362 -0
  252. package/dist/config-subagents-WQV2ZAD5.js.map +1 -0
  253. package/dist/connect-YDWTYU4B.js +1020 -0
  254. package/dist/connect-YDWTYU4B.js.map +1 -0
  255. package/dist/core-0a66n3e7-TTP554XV.js +127 -0
  256. package/dist/core-0a66n3e7-TTP554XV.js.map +1 -0
  257. package/dist/core-0bmnpbz2-C2JIRVZO.js +10790 -0
  258. package/dist/core-0bmnpbz2-C2JIRVZO.js.map +1 -0
  259. package/dist/core-9je8ee1j-74DGHWPV.js +30 -0
  260. package/dist/core-9je8ee1j-74DGHWPV.js.map +1 -0
  261. package/dist/core-wadgcjfh-TSZFQZGH.js +666 -0
  262. package/dist/core-wadgcjfh-TSZFQZGH.js.map +1 -0
  263. package/dist/core-zg882d22-LKV5DZYW.js +37 -0
  264. package/dist/core-zg882d22-LKV5DZYW.js.map +1 -0
  265. package/dist/decision-QSKHOGCO.js +145 -0
  266. package/dist/{doctor-I6XQEKWD.js → doctor-ZWJXRD75.js} +162 -148
  267. package/dist/doctor-ZWJXRD75.js.map +1 -0
  268. package/dist/{env-proxy-R6ZMLQTT.js → env-proxy-XLSLHBKQ.js} +2 -2
  269. package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js → ethersCompat-Df4a6QIZ-K3DMHR6Y.js} +5 -5
  270. package/dist/explicit-ME2NRADQ.js +371 -0
  271. package/dist/explicit-ME2NRADQ.js.map +1 -0
  272. package/dist/flush-stdio-NYIJ3QXT.js +18 -0
  273. package/dist/fund-VF7TLDJH.js +722 -0
  274. package/dist/fund-VF7TLDJH.js.map +1 -0
  275. package/dist/hook-command-VZ27MGWO.js +49 -0
  276. package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
  277. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
  278. package/dist/hosts/claude/tenjin/hooks/hook-data.ts +152 -0
  279. package/dist/hosts/claude/tenjin/hooks/hooks.json +7 -0
  280. package/dist/hosts/claude/tenjin/hooks/model-viewer.tsx +2987 -0
  281. package/dist/hosts/claude/tenjin/hooks/register.tsx +527 -56
  282. package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +14 -4
  283. package/dist/hosts/claude/tenjin/types/index.d.ts +144 -1
  284. package/dist/{hosts-DVQJ32QC.js → hosts-3EMTVM4H.js} +7 -6
  285. package/dist/index.js +18 -15
  286. package/dist/index.js.map +1 -1
  287. package/dist/install-ZA7L2UF3.js +115 -0
  288. package/dist/install-funding-JDGYTF72.js +30 -0
  289. package/dist/install-identity-FFAYEFLX.js +30 -0
  290. package/dist/{install-wallet-5M4OTYLX.js → install-wallet-2SFOVE3Q.js} +68 -53
  291. package/dist/install-wallet-2SFOVE3Q.js.map +1 -0
  292. package/dist/mcp-36S6MK3C.js +67642 -0
  293. package/dist/mcp-36S6MK3C.js.map +1 -0
  294. package/dist/new-install-5L4GY3LN.js +51 -0
  295. package/dist/{package-IJFGMWEV.js → package-BONDXSV3.js} +2 -2
  296. package/dist/{passphrase-IFTDS3CU.js → passphrase-T4ULBN4M.js} +16 -12
  297. package/dist/{paths-XCSAKISU.js → paths-O2KDWZ76.js} +18 -28
  298. package/dist/pay-CMV5KL74.js +74 -0
  299. package/dist/{payments-HFPPWHTV.js → payments-Z6UBZL4Z.js} +36 -26
  300. package/dist/payments-Z6UBZL4Z.js.map +1 -0
  301. package/dist/reclaim-subagent-credit-ABSF67SJ.js +105 -0
  302. package/dist/reclaim-subagent-credit-ABSF67SJ.js.map +1 -0
  303. package/dist/{redact-D7ASVWKL.js → redact-LOTHE5TS.js} +2 -8
  304. package/dist/redact-LOTHE5TS.js.map +1 -0
  305. package/dist/routing-quote-AHLAREXR.js +40 -0
  306. package/dist/routing-quote-AHLAREXR.js.map +1 -0
  307. package/dist/run-JH7ELYAM.js +88 -0
  308. package/dist/run-JH7ELYAM.js.map +1 -0
  309. package/dist/runtime-2GX4ALJP.js +410 -0
  310. package/dist/runtime-2GX4ALJP.js.map +1 -0
  311. package/dist/runtime-activate-IDQ2NCSP.js +39 -0
  312. package/dist/runtime-activate-IDQ2NCSP.js.map +1 -0
  313. package/dist/{runtime-fetch-ZSSSK72Y.js → runtime-fetch-6LOBHBEN.js} +4 -4
  314. package/dist/runtime-fetch-6LOBHBEN.js.map +1 -0
  315. package/dist/runtime-launchers-YAPKCBHV.js +31 -0
  316. package/dist/runtime-launchers-YAPKCBHV.js.map +1 -0
  317. package/dist/{runtime-layout-WIDILZ6K.js → runtime-layout-QHZQJV7C.js} +5 -4
  318. package/dist/runtime-layout-QHZQJV7C.js.map +1 -0
  319. package/dist/runtime-place-4POL4KK4.js +37 -0
  320. package/dist/runtime-place-4POL4KK4.js.map +1 -0
  321. package/dist/runtime-provenance-MNJGVBV2.js +12 -0
  322. package/dist/runtime-provenance-MNJGVBV2.js.map +1 -0
  323. package/dist/{secp256k1-ZZZT2CAX.js → secp256k1-N5P2GVGF.js} +3 -3
  324. package/dist/secp256k1-N5P2GVGF.js.map +1 -0
  325. package/dist/{send-GCVEAQKL.js → send-ELXFKEKY.js} +35 -32
  326. package/dist/send-ELXFKEKY.js.map +1 -0
  327. package/dist/status-FXUFWJDM.js +404 -0
  328. package/dist/status-FXUFWJDM.js.map +1 -0
  329. package/dist/{status-line-OPCXDHL2.js → status-line-IH5JBWBC.js} +51 -43
  330. package/dist/status-line-IH5JBWBC.js.map +1 -0
  331. package/dist/streamableHttp-CP2ZQBIK.js +768 -0
  332. package/dist/streamableHttp-CP2ZQBIK.js.map +1 -0
  333. package/dist/{uninstall-BAWRBXXQ.js → uninstall-LJZUKM4D.js} +76 -76
  334. package/dist/uninstall-LJZUKM4D.js.map +1 -0
  335. package/dist/update-EUIX72IX.js +68 -0
  336. package/dist/update-EUIX72IX.js.map +1 -0
  337. package/dist/usage-EKDC7LUC.js +180 -0
  338. package/dist/usage-EKDC7LUC.js.map +1 -0
  339. package/dist/{usdc-VG4CIOUK.js → usdc-YIHK2OMC.js} +8 -12
  340. package/dist/usdc-YIHK2OMC.js.map +1 -0
  341. package/dist/{viemAdapter-By13KInL-DOFTEIJV.js → viemAdapter-By13KInL-PRLSIESK.js} +5 -5
  342. package/dist/viemAdapter-By13KInL-PRLSIESK.js.map +1 -0
  343. package/dist/wallet-HSW757W6.js +80 -0
  344. package/dist/wallet-HSW757W6.js.map +1 -0
  345. package/dist/wallet-kdf-worker.mjs +1433 -818
  346. package/docs/agent-permissions.md +88 -155
  347. package/docs/router-reference.md +236 -0
  348. package/docs/safety-model.md +31 -33
  349. package/docs/subagents-internals.md +97 -0
  350. package/docs/subagents.md +348 -0
  351. package/docs/troubleshooting.md +10 -6
  352. package/package.json +12 -8
  353. package/scripts/installers/install.sh +7 -1
  354. package/dist/alive-GSOWKUOY.js +0 -38
  355. package/dist/chunk-2I4QTOLB.js.map +0 -1
  356. package/dist/chunk-2M2VPI2E.js +0 -560
  357. package/dist/chunk-2M2VPI2E.js.map +0 -1
  358. package/dist/chunk-2RWB7RKE.js.map +0 -1
  359. package/dist/chunk-2SNUOHAT.js.map +0 -1
  360. package/dist/chunk-3623BLPV.js +0 -184
  361. package/dist/chunk-3623BLPV.js.map +0 -1
  362. package/dist/chunk-36RVGZNY.js.map +0 -1
  363. package/dist/chunk-3AIHRXKO.js.map +0 -1
  364. package/dist/chunk-3FMZGI7I.js.map +0 -1
  365. package/dist/chunk-3UCIG4TG.js.map +0 -1
  366. package/dist/chunk-4K7TQHNP.js.map +0 -1
  367. package/dist/chunk-4LMUQMBH.js +0 -29
  368. package/dist/chunk-4LMUQMBH.js.map +0 -1
  369. package/dist/chunk-4USCZ2NI.js +0 -228
  370. package/dist/chunk-4USCZ2NI.js.map +0 -1
  371. package/dist/chunk-4YOZGGTZ.js.map +0 -1
  372. package/dist/chunk-62KNUYWD.js +0 -111
  373. package/dist/chunk-62KNUYWD.js.map +0 -1
  374. package/dist/chunk-A5GKIG5O.js +0 -2037
  375. package/dist/chunk-A5GKIG5O.js.map +0 -1
  376. package/dist/chunk-AGMVASXZ.js.map +0 -1
  377. package/dist/chunk-BF4XHEQK.js.map +0 -1
  378. package/dist/chunk-BFDQ4WNW.js.map +0 -1
  379. package/dist/chunk-C2Q76BVM.js.map +0 -1
  380. package/dist/chunk-CEXSOI5R.js +0 -808
  381. package/dist/chunk-CEXSOI5R.js.map +0 -1
  382. package/dist/chunk-E7SW44LM.js.map +0 -1
  383. package/dist/chunk-EDJWHDDL.js +0 -33
  384. package/dist/chunk-EDJWHDDL.js.map +0 -1
  385. package/dist/chunk-FVIGCDSV.js.map +0 -1
  386. package/dist/chunk-GTTUCOPD.js +0 -105
  387. package/dist/chunk-GTTUCOPD.js.map +0 -1
  388. package/dist/chunk-HDPUXS3Z.js +0 -122
  389. package/dist/chunk-HDPUXS3Z.js.map +0 -1
  390. package/dist/chunk-HGGWCP7W.js +0 -120
  391. package/dist/chunk-HGGWCP7W.js.map +0 -1
  392. package/dist/chunk-HGZEPQUT.js.map +0 -1
  393. package/dist/chunk-HMWYAUA6.js.map +0 -1
  394. package/dist/chunk-IADZOXKN.js.map +0 -1
  395. package/dist/chunk-ILNIZ5I2.js.map +0 -1
  396. package/dist/chunk-INTFHMU4.js.map +0 -1
  397. package/dist/chunk-JKKAIPTU.js.map +0 -1
  398. package/dist/chunk-JNJWBTU2.js.map +0 -1
  399. package/dist/chunk-KM7RY2ZS.js +0 -246
  400. package/dist/chunk-KM7RY2ZS.js.map +0 -1
  401. package/dist/chunk-KOGZDMHO.js +0 -21
  402. package/dist/chunk-KOGZDMHO.js.map +0 -1
  403. package/dist/chunk-L6JEXB3E.js.map +0 -1
  404. package/dist/chunk-LRW6S53P.js.map +0 -1
  405. package/dist/chunk-LXAYUOXI.js +0 -511
  406. package/dist/chunk-LXAYUOXI.js.map +0 -1
  407. package/dist/chunk-MEFB5KHA.js +0 -59
  408. package/dist/chunk-MEFB5KHA.js.map +0 -1
  409. package/dist/chunk-MPZUYCAP.js.map +0 -1
  410. package/dist/chunk-NDGZDTSJ.js.map +0 -1
  411. package/dist/chunk-OJNTCYQQ.js.map +0 -1
  412. package/dist/chunk-P3LFTKE7.js +0 -58
  413. package/dist/chunk-P3LFTKE7.js.map +0 -1
  414. package/dist/chunk-QXP3Z3JN.js.map +0 -1
  415. package/dist/chunk-RVPYTUP4.js.map +0 -1
  416. package/dist/chunk-SNNSAGMT.js.map +0 -1
  417. package/dist/chunk-TC2WZLSC.js.map +0 -1
  418. package/dist/chunk-TKPF35W6.js +0 -29
  419. package/dist/chunk-TKPF35W6.js.map +0 -1
  420. package/dist/chunk-U3IKUGRP.js.map +0 -1
  421. package/dist/chunk-UUGOUOVT.js.map +0 -1
  422. package/dist/chunk-UXZONNEQ.js.map +0 -1
  423. package/dist/chunk-WXA2BWTE.js.map +0 -1
  424. package/dist/chunk-WYXUQGOL.js.map +0 -1
  425. package/dist/chunk-X5ZBP3IY.js.map +0 -1
  426. package/dist/chunk-XKESD27X.js +0 -10
  427. package/dist/chunk-XKESD27X.js.map +0 -1
  428. package/dist/chunk-XQJXNMSB.js.map +0 -1
  429. package/dist/chunk-Y527D4TV.js +0 -56
  430. package/dist/chunk-Y527D4TV.js.map +0 -1
  431. package/dist/chunk-ZDZERB6L.js.map +0 -1
  432. package/dist/chunk-ZNNXRNFD.js.map +0 -1
  433. package/dist/chunk-ZURZHELF.js.map +0 -1
  434. package/dist/cli-E36SPKBW.js.map +0 -1
  435. package/dist/codex-install-HQZDGFXW.js.map +0 -1
  436. package/dist/config-HY2E4GGW.js +0 -55
  437. package/dist/doctor-I6XQEKWD.js.map +0 -1
  438. package/dist/fund-2QRO7OJL.js +0 -378
  439. package/dist/fund-2QRO7OJL.js.map +0 -1
  440. package/dist/hook-command-2UBCSZG6.js +0 -43
  441. package/dist/install-ILUX5C4A.js +0 -107
  442. package/dist/install-identity-TZKGY6LQ.js +0 -31
  443. package/dist/install-wallet-5M4OTYLX.js.map +0 -1
  444. package/dist/mcp-LE4DUS22.js +0 -14127
  445. package/dist/mcp-LE4DUS22.js.map +0 -1
  446. package/dist/pay-WCG3IH4R.js +0 -55
  447. package/dist/payments-HFPPWHTV.js.map +0 -1
  448. package/dist/plugin-registration-PZFI5GZW.js +0 -68
  449. package/dist/runtime-UZOKSUZX.js +0 -1321
  450. package/dist/runtime-UZOKSUZX.js.map +0 -1
  451. package/dist/send-GCVEAQKL.js.map +0 -1
  452. package/dist/status-HCVAOCN7.js +0 -150
  453. package/dist/status-HCVAOCN7.js.map +0 -1
  454. package/dist/status-line-OPCXDHL2.js.map +0 -1
  455. package/dist/uninstall-BAWRBXXQ.js.map +0 -1
  456. package/dist/update-CACXLQLR.js +0 -56
  457. package/dist/wallet-QL4UUXEZ.js +0 -55
  458. /package/dist/{_esm-BIN7VY2L.js.map → _esm-2KST7HQ7.js.map} +0 -0
  459. /package/dist/{alive-GSOWKUOY.js.map → alive-5TV22PNF.js.map} +0 -0
  460. /package/dist/{auto-update-Y24UL56V.js.map → auth-XI7BJFLW.js.map} +0 -0
  461. /package/dist/{ccip-DHDFKTQV.js.map → auto-update-7L24KDWA.js.map} +0 -0
  462. /package/dist/{clack-EZ7TDWQU.js.map → balance-DFHC6XEU.js.map} +0 -0
  463. /package/dist/{claude-cli-2YKABJJZ.js.map → ccip-HOW3DZYF.js.map} +0 -0
  464. /package/dist/{chunk-IE7P2BZE.js.map → chunk-6QMDUDF2.js.map} +0 -0
  465. /package/dist/{chunk-KG3D7FIF.js.map → chunk-CZJOMUBP.js.map} +0 -0
  466. /package/dist/{chunk-3GNJXKIT.js.map → chunk-F43CV6UC.js.map} +0 -0
  467. /package/dist/{chunk-J57UC3DD.js.map → chunk-FKVJKLPI.js.map} +0 -0
  468. /package/dist/{chunk-SO3XRZPX.js.map → chunk-HPRVFJPM.js.map} +0 -0
  469. /package/dist/{chunk-2GP3HRYK.js.map → chunk-INSIW65E.js.map} +0 -0
  470. /package/dist/{chunk-RL5UUDT4.js.map → chunk-JNUKLSMZ.js.map} +0 -0
  471. /package/dist/{chunk-JRGFKVAZ.js.map → chunk-PETQ5WEA.js.map} +0 -0
  472. /package/dist/{codex-event-ZO2GEFE6.js.map → chunk-TUCKEEXE.js.map} +0 -0
  473. /package/dist/{chunk-BPMWXTFX.js.map → chunk-WFZX352D.js.map} +0 -0
  474. /package/dist/{chunk-6CMM6YCB.js.map → chunk-YWWMISDY.js.map} +0 -0
  475. /package/dist/{codex-host-KECJVTA2.js.map → clack-Q4RNC5VE.js.map} +0 -0
  476. /package/dist/{config-HY2E4GGW.js.map → claude-cli-GIIHOBGT.js.map} +0 -0
  477. /package/dist/{env-proxy-R6ZMLQTT.js.map → claude-install-BAUSJMW3.js.map} +0 -0
  478. /package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js.map → codex-event-EUTCAOTQ.js.map} +0 -0
  479. /package/dist/{hook-command-2UBCSZG6.js.map → codex-host-ZON3S6HU.js.map} +0 -0
  480. /package/dist/{hosts-DVQJ32QC.js.map → config-QZOBMTEL.js.map} +0 -0
  481. /package/dist/{install-ILUX5C4A.js.map → config-rules-YOYHS6YL.js.map} +0 -0
  482. /package/dist/{install-identity-TZKGY6LQ.js.map → decision-QSKHOGCO.js.map} +0 -0
  483. /package/dist/{package-IJFGMWEV.js.map → env-proxy-XLSLHBKQ.js.map} +0 -0
  484. /package/dist/{passphrase-IFTDS3CU.js.map → ethersCompat-Df4a6QIZ-K3DMHR6Y.js.map} +0 -0
  485. /package/dist/{paths-XCSAKISU.js.map → flush-stdio-NYIJ3QXT.js.map} +0 -0
  486. /package/dist/{pay-WCG3IH4R.js.map → hook-command-VZ27MGWO.js.map} +0 -0
  487. /package/dist/{plugin-registration-PZFI5GZW.js.map → hosts-3EMTVM4H.js.map} +0 -0
  488. /package/dist/{redact-D7ASVWKL.js.map → install-ZA7L2UF3.js.map} +0 -0
  489. /package/dist/{runtime-fetch-ZSSSK72Y.js.map → install-funding-JDGYTF72.js.map} +0 -0
  490. /package/dist/{runtime-layout-WIDILZ6K.js.map → install-identity-FFAYEFLX.js.map} +0 -0
  491. /package/dist/{secp256k1-ZZZT2CAX.js.map → new-install-5L4GY3LN.js.map} +0 -0
  492. /package/dist/{update-CACXLQLR.js.map → package-BONDXSV3.js.map} +0 -0
  493. /package/dist/{usdc-VG4CIOUK.js.map → passphrase-T4ULBN4M.js.map} +0 -0
  494. /package/dist/{viemAdapter-By13KInL-DOFTEIJV.js.map → paths-O2KDWZ76.js.map} +0 -0
  495. /package/dist/{wallet-QL4UUXEZ.js.map → pay-CMV5KL74.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/wallet/passphrase.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { randomBytes } from 'node:crypto';\nimport { readFile, stat, unlink } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { CliError } from '../errors';\nimport { hasCode } from '../errno';\nimport { writeFileAtomic, writeFileAtomicExclusive } from '../atomic-json';\nimport { readPassphraseRecord } from '../passphrase-record';\nimport {\n dataDir,\n passphraseBlobPath,\n passphraseBlobPathFor,\n passphraseFilePathFor,\n} from '../paths';\nimport {\n FILE_STORE_FAILED_FIX,\n KEYCHAIN_LOCKED_FIX,\n KEYCHAIN_WAIT_LINE,\n REPAIR_IN_TERMINAL,\n unlockDetails,\n type DurableStore,\n} from '../wallet-unlock';\n\nexport type { DurableStore } from '../wallet-unlock';\n\n/**\n * Wallet passphrase resolution. The private key lives on disk as an encrypted\n * Keystore v3 document; the passphrase that unlocks it is resolved here, in a\n * fixed order, so signing works headlessly (env), transparently through the OS\n * store (macOS keychain, Windows DPAPI, desktop-Linux keyring), or interactively\n * (TTY). Every side-effecting seam — the store CLIs and the hidden-input prompt —\n * is injectable so tests never touch a real keychain or terminal.\n *\n * The passphrase never appears in any argv (which the OS process table can show):\n * reads come back on stdout, and writes pipe the secret over the child's stdin.\n * A failed store CLI never carries its stdout anywhere (for a read, that IS the\n * secret): it rejects with a {@link StoreExecError} holding only the exit code,\n * the signal and the stderr {@link classifyStoreFailure} reads, and every detail\n * built from it names only those.\n *\n * ONE ANNOUNCED PLAINTEXT EXCEPTION: where no OS store exists at all (headless\n * Linux, WSL, a sandbox; the probe says `absent`) or the user chose\n * `--insecure-storage`, the passphrase is saved to `passphrase.<address>.plain`\n * at 0600 in the 0700 data dir, the way the GitHub CLI keeps `hosts.yml`.\n * Create and repair say so in one line. A store that exists but is LOCKED never\n * routes there: a locked keychain is unlocked, not worked around. Everywhere\n * else no plaintext is written to disk (the Windows blob is DPAPI-encrypted, not\n * the passphrase itself).\n *\n * Durable entries are PER WALLET (account = lowercase address); the legacy\n * shared slot is only ever read, for migration (#32). Where each wallet's\n * passphrase went is recorded in the sidecar (`src/lib/passphrase-record.ts`),\n * so a recorded wallet reads exactly one store.\n */\n\nconst KEYCHAIN_SERVICE = 'tenjin-cli';\n/**\n * The pre-per-wallet shared slot (service `tenjin-cli`, account `wallet`) that\n * every create used to `-U`-overwrite. Never written anymore; read only as a\n * migration fallback and removed only after a verified per-address copy exists.\n */\nconst LEGACY_ACCOUNT = 'wallet';\n\n/**\n * The account the Secret Service probe looks up: the zero address, which no\n * wallet can own. A hit or a miss both prove a keyring answered.\n */\nconst PROBE_ACCOUNT = '0x0000000000000000000000000000000000000000';\n\n/** A lowercase 0x-prefixed 20-byte hex address — the per-wallet store account. */\nconst ACCOUNT_ADDRESS_RE = /^0x[0-9a-f]{40}$/;\n\n/**\n * base64url alphabet — what generated passphrases use. These still go to the\n * keychain as today's exact `-w '<value>'` line (no quote/backslash/space/newline\n * can appear inside the single quotes), so an existing reader of that shape sees\n * no change.\n */\nconst BASE64URL_RE = /^[A-Za-z0-9_-]+$/;\n\n/**\n * Printable ASCII: what the keychain writer stores at all. Anything outside the\n * base64url alphabet goes as `-X <utf8 hex>`, which carries only `[0-9a-f]` on\n * the piped `security -i` line, so nothing in the value can be read as syntax.\n * Non-printable bytes are refused, not encoded: `security -w` prints a value\n * with them back as hex, which would not read back byte-identical.\n */\nconst PRINTABLE_ASCII_RE = /^[\\x20-\\x7e]+$/;\n\n/**\n * The OS-store account for a wallet address: lowercased (checksum-insensitive)\n * and validated as plain hex before it can reach the piped `security -i` line.\n */\nexport function walletStoreAccount(address: string): string {\n const account = address.toLowerCase();\n if (!ACCOUNT_ADDRESS_RE.test(account)) {\n throw new CliError('INTERNAL', `Not a valid wallet address for passphrase storage: ${address}`);\n }\n return account;\n}\n\nexport type PassphraseSource = 'env' | DurableStore | 'prompt';\n\nexport interface ResolvedPassphrase {\n passphrase: string;\n source: PassphraseSource;\n /**\n * Present ONLY when the passphrase came from the legacy shared slot. Call it\n * strictly AFTER proving the passphrase decrypts this wallet's keystore; it\n * re-keys the slot per migrateLegacyEntry's contract. On a decrypt failure\n * do NOT call it — surface the ambiguity and leave the legacy entry alone.\n */\n migrateLegacy?: () => Promise<boolean>;\n /** true when the sidecar named the store that served it. */\n recorded?: boolean;\n}\n\n/**\n * Runs a command with an argv array (execFile semantics — never shell-interpolated).\n * When `stdin` is provided it is written to the child's stdin and the stream is\n * closed; this is how the passphrase reaches `security -i`, PowerShell, and\n * `secret-tool` WITHOUT ever appearing in an argv the process table can expose.\n *\n * `opts.timeoutMs` absent means the child is never killed: every signing read\n * passes none (B3), so an OS unlock dialog the person may be answering stays up.\n * Rejects only with a {@link StoreExecError} (S2).\n */\nexport type ExecFn = (\n file: string,\n args: string[],\n stdin?: string,\n opts?: { timeoutMs?: number },\n) => Promise<{ stdout: string; stderr: string }>;\n\n/** Reads one line of hidden input, writing `label` to stderr (never stdout). */\nexport type PromptFn = (label: string) => Promise<string>;\n\n/**\n * THE ONLY REJECTION OF {@link defaultExecFor} (S2). A fresh error built from the\n * Node one, never the Node one itself: Node's message and its `stdout` field can\n * carry the child's output, and for a store read that output is the passphrase.\n * There is no `stdout` field here, ever. `stderr` is kept only so\n * {@link classifyStoreFailure} can tell \"no such keychain\" from \"locked\"; it is\n * non-enumerable so a `JSON.stringify` or a log of this error cannot carry it,\n * and nothing copies it into a message, detail, warning or file.\n */\nexport class StoreExecError extends Error {\n readonly code: number | string | null;\n readonly signal: string | null;\n readonly killed: boolean;\n readonly enoent: boolean;\n declare readonly stderr: string;\n\n constructor(\n file: string,\n fields: {\n code?: number | string | null;\n signal?: string | null;\n killed?: boolean;\n enoent?: boolean;\n stderr?: string;\n } = {},\n ) {\n const code = fields.code ?? null;\n const signal = fields.signal ?? null;\n super(`${file} failed (${code ?? signal ?? 'no exit code'})`);\n this.name = 'StoreExecError';\n this.code = code;\n this.signal = signal;\n this.killed = fields.killed ?? false;\n this.enoent = fields.enoent ?? code === 'ENOENT';\n Object.defineProperty(this, 'stderr', {\n value: fields.stderr ?? '',\n enumerable: false,\n writable: false,\n });\n }\n}\n\n/**\n * Store-operation deadlines (decision 7). Reads are NOT here: the router never\n * kills a store read; only verify (doctor, install) bounds one, at\n * `verifyReadMs`. Writes are bounded as a whole: pre-read, write and read-back\n * share one deadline, 10 s headless or 60 s at a terminal, where the person may\n * be answering an OS unlock prompt (`waitLineAfterMs` in, they are told so).\n */\nexport const STORE_TIMEOUTS = {\n verifyReadMs: 5000,\n writeMs: 10000,\n interactiveWriteMs: 60000,\n probeMs: 3000,\n waitLineAfterMs: 1000,\n} as const;\n\n/** {@link STORE_TIMEOUTS}' shape, as plain numbers a test may override. */\nexport type StoreTimeouts = Record<keyof typeof STORE_TIMEOUTS, number>;\n\nexport interface PassphraseDeps {\n env: NodeJS.ProcessEnv;\n /** Data dir that holds the sidecar, the DPAPI blob and the passphrase file; defaults to the resolved data dir. */\n dir?: string;\n /** Defaults to `process.platform`; selects the OS store (or none). */\n platform?: NodeJS.Platform;\n /** Whether an interactive prompt is possible; defaults to `process.stdin.isTTY`. */\n isTTY?: boolean;\n /** The store-CLI exec seam; defaults to a real execFile with stdin support. */\n exec?: ExecFn;\n /** The hidden-input prompt seam; defaults to a raw-mode TTY reader. */\n prompt?: PromptFn;\n /** Test override for {@link STORE_TIMEOUTS}. */\n timeouts?: Partial<StoreTimeouts>;\n /**\n * Read deadline for verify only (doctor and install pass\n * `STORE_TIMEOUTS.verifyReadMs`). Absent means reads are never killed, which\n * is what every signing caller must stay (B3).\n */\n readDeadlineMs?: number;\n /**\n * Create and repair at a TTY: called once with KEYCHAIN_WAIT_LINE when\n * storeDurablyDetailed has not settled after `waitLineAfterMs`. Commands wire it to\n * stderr.\n */\n onWait?: (line: string) => void;\n}\n\n/** One store read, classified. `detail` never carries the store's output (S2). */\nexport type StoreRead =\n | { kind: 'hit'; value: string }\n | { kind: 'miss' }\n | { kind: 'absent'; detail: string }\n | { kind: 'locked'; detail: string };\n\n/** Whether the platform store can answer at all: before create or repair picks a target. */\nexport type StoreProbe = 'available' | 'absent' | 'uncertain';\n\n/**\n * 'kept-existing': the pre-read found a different value and replaceIf said keep it (nothing written).\n * 'conflict': a different value with no replaceIf, or a read-back that differs after the write (S1).\n */\nexport type DurableWrite =\n | 'stored'\n | 'already-stored'\n | 'kept-existing'\n | 'conflict'\n | 'uncertain'\n | 'store-failed'\n | 'rejected-characters';\n\n/** A --replace archive write's outcome ({@link toStoreOutcome}); `no-store`: nowhere to write. */\nexport type StorePassphraseOutcome =\n 'stored' | 'no-store' | 'rejected-characters' | 'store-failed' | 'uncertain';\n\n/** Per-call deadline for every store method (decision 7). Absent = never killed. The file store ignores it. */\nexport interface StoreCallOptions {\n timeoutMs?: number;\n}\n\n/**\n * A durable passphrase store, keyed by ACCOUNT (the wallet's lowercase address,\n * or the read-only legacy `wallet` slot). Reads never throw: they classify. A\n * write throws the StoreExecError (or the fs error, for the file store) so\n * storeDurablyDetailed can tell a killed write, which may have committed, from a\n * definite failure.\n */\ninterface PassphraseStore {\n /** The source label reported when this store serves the passphrase. */\n source: DurableStore;\n read(account: string, o?: StoreCallOptions): Promise<StoreRead>;\n store(account: string, value: string, o?: StoreCallOptions & { update?: boolean }): Promise<void>;\n remove(account: string, o?: StoreCallOptions): Promise<boolean>;\n probe(o?: StoreCallOptions): Promise<{ probe: StoreProbe; detail?: string }>;\n /**\n * When present, a cheap pre-check for values this backend's writer refuses on\n * principle (the keychain's printable-ASCII gate), or that its read would not\n * give back byte for byte (a trailing line break the read strips) — so\n * callers can tell \"this passphrase's characters\" apart from \"the store\n * write failed\", and nothing is written that reads back as another secret.\n */\n storable?(value: string): boolean;\n}\n\n/**\n * The real executor. Each call applies its own `opts.timeoutMs` when given, and\n * kills with SIGKILL: a store CLI that ignored SIGTERM would otherwise outlive\n * the deadline it was given.\n *\n * WHY A WRITE MAY BE KILLED NOW. A killed write used to be a correctness hazard:\n * create treated \"the write did not return\" as \"the write did not stick\" and fell\n * through to a different, prompted passphrase while the committed value won\n * every later decrypt. That fall-through is gone. One secret per address is\n * chosen before any write, and every write is followed by a read-back\n * (storeDurablyDetailed), so a killed write that did commit reads back as stored, and\n * one that did not reads back as missing. The worst a kill leaves is an orphan\n * keychain entry for an address whose create was then abandoned, which no\n * wallet will ever read.\n *\n * WHY READS STAY UNBOUNDED, except in verify. Killing a read closes an OS unlock\n * dialog the person may be answering. The router bounds its WAIT with the call\n * budget instead (routing-payer.ts), and the read keeps running so a later call\n * gets its answer. Only doctor's and install's verify, which run unattended and\n * must finish, pass a read deadline.\n */\nexport function defaultExecFor(): ExecFn {\n return (file, args, stdin, opts) =>\n new Promise((resolve, reject) => {\n const child = execFile(\n file,\n args,\n {\n encoding: 'utf8',\n killSignal: 'SIGKILL',\n // 0 would mean \"no timeout\" to Node; a spent deadline is still a deadline.\n ...(opts?.timeoutMs !== undefined ? { timeout: Math.max(1, opts.timeoutMs) } : {}),\n },\n (err, stdout, stderr) => {\n if (err) reject(toStoreExecError(file, err, stderr));\n else resolve({ stdout, stderr });\n },\n );\n if (stdin !== undefined) {\n // A child that exits before draining stdin closes the pipe; swallow the\n // resulting EPIPE so the exec callback surfaces the real exit error instead.\n child.stdin?.on('error', () => undefined);\n child.stdin?.end(stdin);\n }\n });\n}\n\n/** The scrubbed copy of a Node exec error: no message, no stdout (S2). */\nfunction toStoreExecError(file: string, err: unknown, stderr: unknown): StoreExecError {\n const e = err as { code?: unknown; signal?: unknown; killed?: unknown };\n const code = typeof e.code === 'number' || typeof e.code === 'string' ? e.code : null;\n return new StoreExecError(file, {\n code,\n signal: typeof e.signal === 'string' ? e.signal : null,\n killed: e.killed === true,\n enoent: code === 'ENOENT',\n stderr: typeof stderr === 'string' ? stderr : '',\n });\n}\n\n/** The effective deadlines: STORE_TIMEOUTS with any test override applied. */\nfunction timeoutsOf(deps: PassphraseDeps): StoreTimeouts {\n return { ...STORE_TIMEOUTS, ...deps.timeouts };\n}\n\n/** What a store is called in a sentence: \"the <noun> did not answer\". */\nexport function storeNoun(store: DurableStore): string {\n switch (store) {\n case 'keychain':\n return 'macOS keychain';\n case 'secret-service':\n return 'Linux keyring';\n case 'dpapi':\n return 'Windows DPAPI store';\n case 'file':\n return 'passphrase file';\n }\n}\n\n/**\n * WHY A STORE OPERATION FAILED, in a form that can gate (section 2.5). Anything\n * unclear is `locked`, which is unknown and never a block (Q5): only a store\n * that provably is not there is `absent`, and only the store's own \"no such\n * entry\" is a `miss`.\n *\n * `stderr` is read here to pick the kind and then dropped. Every detail is\n * built only from the kind, the exit code and the signal (S2), never from the\n * child's output or the error's message. A thrown value that is not a\n * StoreExecError (a test fake, a bug) is `locked` with a fixed detail and its\n * message is not read. The file store's fs errors are classified by errno code.\n */\nexport function classifyStoreFailure(\n store: DurableStore,\n err: unknown,\n): Exclude<StoreRead, { kind: 'hit' }> {\n if (store === 'file') {\n if (hasCode(err, 'ENOENT')) return { kind: 'miss' };\n const code = (err as { code?: unknown } | null)?.code;\n const errno = typeof code === 'string' && /^E[A-Z]+$/.test(code) ? ` (${code})` : '';\n return { kind: 'locked', detail: `the passphrase file could not be read${errno}` };\n }\n if (!(err instanceof StoreExecError)) {\n return {\n kind: 'locked',\n detail: `the ${storeNoun(store)} failed for a reason Tenjin could not classify`,\n };\n }\n if (err.killed || err.signal !== null) {\n return {\n kind: 'locked',\n detail: `the ${storeNoun(store)} did not answer (killed by ${err.signal ?? 'SIGKILL'})`,\n };\n }\n switch (store) {\n case 'keychain':\n if (err.enoent) return { kind: 'absent', detail: 'the `security` tool is not installed' };\n if (err.code === 44) return { kind: 'miss' };\n if (/default keychain could not be found/i.test(err.stderr)) {\n return { kind: 'absent', detail: 'there is no default keychain' };\n }\n if (/User interaction is not allowed/.test(err.stderr)) {\n return { kind: 'locked', detail: 'the keychain refused (user interaction is not allowed)' };\n }\n return { kind: 'locked', detail: `security exited ${String(err.code)}` };\n case 'secret-service':\n if (err.enoent) return { kind: 'absent', detail: 'secret-tool is not installed' };\n if (\n /Cannot autolaunch D-Bus|org\\.freedesktop\\.secrets was not provided|Could not connect/.test(\n err.stderr,\n )\n ) {\n return { kind: 'absent', detail: 'no Secret Service is reachable from this session' };\n }\n if (err.code === 1 && err.stderr.trim() === '') return { kind: 'miss' };\n return { kind: 'locked', detail: `secret-tool exited ${String(err.code)}` };\n case 'dpapi':\n if (err.enoent) return { kind: 'absent', detail: 'powershell.exe is not available' };\n return {\n kind: 'locked',\n detail: `the DPAPI unprotect failed (powershell.exe exited ${String(err.code)})`,\n };\n }\n}\n\n/** The durable store for this platform, or null where no built-in one exists. */\nfunction storeFor(deps: PassphraseDeps): PassphraseStore | null {\n switch (deps.platform ?? process.platform) {\n case 'darwin':\n return keychainStore(deps);\n case 'win32':\n return dpapiStore(deps);\n case 'linux':\n return secretServiceStore(deps);\n default:\n return null;\n }\n}\n\n/** Any store by name, the file store included: what a sidecar entry or a chosen target names. */\nfunction storeByName(deps: PassphraseDeps, name: DurableStore): PassphraseStore {\n switch (name) {\n case 'keychain':\n return keychainStore(deps);\n case 'secret-service':\n return secretServiceStore(deps);\n case 'dpapi':\n return dpapiStore(deps);\n case 'file':\n return fileStore(deps);\n }\n}\n\n/**\n * One classified read of `address`'s entry in a named store (repair: \"does the\n * store the sidecar names already hold this passphrase?\"). Never throws.\n */\nexport function readStoredPassphrase(\n deps: PassphraseDeps,\n store: DurableStore,\n address: string,\n o?: StoreCallOptions,\n): Promise<StoreRead> {\n return storeByName(deps, store).read(walletStoreAccount(address), o);\n}\n\n/**\n * Resolve the passphrase to DECRYPT the existing wallet at `address`.\n *\n * 1. `TENJIN_WALLET_PASSPHRASE`, unless `skipEnv` (the wrong-env fallthrough).\n * 2. A sidecar entry: read ONLY that store's per-address entry. There is no\n * other-store fallback: the sidecar is the answer to \"where did it go\".\n * 3. No sidecar entry (every wallet made before the sidecar existed): today's\n * order, so alpha.30 keychain users read exactly the same entry. The OS store\n * per-address, then the legacy slot (only when the OS store exists), then the\n * 0600 file, then the prompt.\n *\n * A store that is LOCKED stops the chain, recorded or not: falling through to\n * the legacy slot or the prompt would answer \"did the keychain say no?\" with a\n * guess. At a TTY the person is asked instead; elsewhere it throws\n * `keychain_locked`, whose fix is to unlock the keychain, never plaintext (S3).\n * A locked LEGACY slot still lets the file be read, but a file miss after it is\n * `keychain_locked` too, never `passphrase_missing`.\n *\n * A legacy hit carries a `migrateLegacy` handle the caller invokes only after\n * proving the passphrase decrypts this wallet (see ResolvedPassphrase). Reads\n * pass `deps.readDeadlineMs` when it is set (verify only) and no deadline\n * otherwise (B3).\n */\nexport async function resolvePassphrase(\n deps: PassphraseDeps,\n address: string,\n opts: { skipEnv?: boolean; promptLabel?: string } = {},\n): Promise<ResolvedPassphrase> {\n if (opts.skipEnv !== true) {\n const fromEnv = envPassphrase(deps.env);\n if (fromEnv !== null) return { passphrase: fromEnv, source: 'env' };\n }\n\n const account = walletStoreAccount(address);\n const readOpts: StoreCallOptions | undefined =\n deps.readDeadlineMs !== undefined ? { timeoutMs: deps.readDeadlineMs } : undefined;\n const prompted = async (): Promise<ResolvedPassphrase> => {\n const entered = await promptOf(deps)(opts.promptLabel ?? 'Wallet passphrase: ');\n if (entered.length === 0) throw noPassphraseError();\n return { passphrase: entered, source: 'prompt' };\n };\n\n const entry = await readPassphraseRecord(deps.dir ?? dataDir(), account);\n if (entry !== null) {\n const got = await storeByName(deps, entry.store).read(account, readOpts);\n if (got.kind === 'hit') return { passphrase: got.value, source: entry.store, recorded: true };\n if (canPrompt(deps)) return prompted();\n if (got.kind === 'miss') {\n throw noPassphraseError(describeStoreLocation(entry.store, account, deps.dir));\n }\n throw storeLockedError(entry.store, account, got.detail, deps.dir, true);\n }\n\n const store = storeFor(deps);\n // A legacy slot that holds an entry but did not answer. The 0600 file is\n // still read (it may hold this wallet's passphrase, and the shared legacy\n // slot may hold another wallet's), but if it misses too the answer is\n // `keychain_locked`, never a definite `passphrase_missing` (Unknown never blocks).\n let legacyLocked: { source: DurableStore; detail: string } | null = null;\n if (store !== null) {\n const own = await store.read(account, readOpts);\n if (own.kind === 'hit') return { passphrase: own.value, source: store.source };\n if (own.kind === 'locked') {\n if (canPrompt(deps)) return prompted();\n throw storeLockedError(store.source, account, own.detail, deps.dir, false);\n }\n if (own.kind === 'miss') {\n const legacy = await store.read(LEGACY_ACCOUNT, readOpts);\n if (legacy.kind === 'hit') {\n return {\n passphrase: legacy.value,\n source: store.source,\n migrateLegacy: () => migrateLegacyEntry(legacyOps(store, deps), account, legacy.value),\n };\n }\n if (legacy.kind === 'locked') legacyLocked = { source: store.source, detail: legacy.detail };\n }\n }\n\n const file = await fileStore(deps).read(account);\n if (file.kind === 'hit') return { passphrase: file.value, source: 'file' };\n\n if (canPrompt(deps)) return prompted();\n if (legacyLocked !== null) {\n throw storeLockedError(\n legacyLocked.source,\n LEGACY_ACCOUNT,\n legacyLocked.detail,\n deps.dir,\n false,\n );\n }\n throw noPassphraseError();\n}\n\n/** The three store operations a legacy migration makes, each under the store write bound. */\ninterface LegacyOps {\n copy(account: string, value: string): Promise<boolean>;\n readBack(account: string): Promise<string | null>;\n removeLegacy(): Promise<boolean>;\n}\n\n/**\n * The legacy migration on the store API (S10). Each call passes the store WRITE\n * bound (`writeMs`): a migration is a write and its check, not a signing read,\n * and a killed read-back is not a hit, so the legacy slot stays. Nothing here\n * writes the sidecar: only create, repair and `--replace` do.\n */\nfunction legacyOps(store: PassphraseStore, deps: PassphraseDeps): LegacyOps {\n const timeoutMs = timeoutsOf(deps).writeMs;\n return {\n async copy(account, value) {\n if (store.storable !== undefined && !store.storable(value)) return false;\n try {\n await store.store(account, value, { timeoutMs });\n return true;\n } catch {\n return false;\n }\n },\n async readBack(account) {\n const got = await store.read(account, { timeoutMs });\n return got.kind === 'hit' ? got.value : null;\n },\n removeLegacy: () => store.remove(LEGACY_ACCOUNT, { timeoutMs }),\n };\n}\n\n/**\n * Re-key the legacy shared slot under the owning wallet's own account: copy\n * first, verify the copy reads back byte-identical, and only then remove the\n * legacy entry. A failed copy or verify returns false with the legacy entry\n * still in place — the invariant is that at every step at least one durable\n * copy of the passphrase exists. The removal itself is best-effort: once the\n * copy has verified, a legacy entry that refuses to delete is redundant, not\n * unsafe (per-address reads win from then on), so it never fails the migration.\n */\nasync function migrateLegacyEntry(\n ops: LegacyOps,\n account: string,\n passphrase: string,\n): Promise<boolean> {\n if (!(await ops.copy(account, passphrase))) return false;\n if ((await ops.readBack(account)) !== passphrase) return false;\n await ops.removeLegacy();\n return true;\n}\n\n/** storeDurablyDetailed's outcome with the classified reason behind it, for the message. */\nexport interface DurableWriteResult {\n outcome: DurableWrite;\n /** Why it was not stored, built from the classified kind only (S2). Absent on success. */\n detail?: string;\n}\n\n/**\n * Save `secret` as `address`'s passphrase in `store`, and say only what a\n * read-back proves.\n *\n * (a) Pre-read. An equal value is `already-stored`. A different value is\n * `conflict` unless `replaceIf(existing)` says to replace it (repair, after\n * proving the old entry does not open the wallet), or `kept-existing` when it\n * says keep it. A locked or absent store is `uncertain` before any write.\n * (b) A value this store's writer refuses is `rejected-characters`.\n * (c) Exactly one write, of exactly this value.\n * (d) Always a read-back. Equal is `stored`; different is `conflict` (S1: some\n * other writer holds the entry, so this is never \"saved\"); a miss after a\n * killed write, or a store that does not answer the read-back, is\n * `uncertain`; a miss after any other write is `store-failed`.\n *\n * All three steps share ONE deadline (decision 7): 10 s headless, 60 s at a\n * terminal. Each call gets the time left; a step with none left is not\n * started. At a terminal, a write still unsettled after a second prints\n * KEYCHAIN_WAIT_LINE once through `onWait`. The file store never waits.\n */\nexport async function storeDurablyDetailed(\n deps: PassphraseDeps,\n storeName: DurableStore,\n address: string,\n secret: string,\n opts: { replaceIf?: (existing: string) => Promise<boolean> } = {},\n): Promise<DurableWriteResult> {\n const store = storeByName(deps, storeName);\n const account = walletStoreAccount(address);\n const t = timeoutsOf(deps);\n const end = Date.now() + (deps.isTTY === true ? t.interactiveWriteMs : t.writeMs);\n const left = (): number => end - Date.now();\n const outOfTime: DurableWriteResult = {\n outcome: 'uncertain',\n detail: `the ${storeNoun(storeName)} did not answer in time`,\n };\n\n let timer: NodeJS.Timeout | undefined;\n if (deps.isTTY === true && storeName !== 'file' && deps.onWait !== undefined) {\n const onWait = deps.onWait;\n timer = setTimeout(() => onWait(KEYCHAIN_WAIT_LINE), t.waitLineAfterMs);\n timer.unref?.();\n }\n try {\n if (left() <= 0) return outOfTime;\n const pre = await store.read(account, { timeoutMs: left() });\n if (pre.kind === 'locked' || pre.kind === 'absent') {\n return { outcome: 'uncertain', detail: pre.detail };\n }\n let update = false;\n if (pre.kind === 'hit') {\n if (pre.value === secret) return { outcome: 'already-stored' };\n if (opts.replaceIf === undefined) {\n return { outcome: 'conflict', detail: 'a different passphrase is already saved there' };\n }\n if (!(await opts.replaceIf(pre.value))) return { outcome: 'kept-existing' };\n update = true;\n }\n\n if (store.storable !== undefined && !store.storable(secret)) {\n return { outcome: 'rejected-characters' };\n }\n\n if (left() <= 0) return outOfTime;\n let writeError: unknown;\n let wrote = true;\n try {\n await store.store(account, secret, {\n timeoutMs: left(),\n ...(update ? { update: true } : {}),\n });\n } catch (err) {\n wrote = false;\n writeError = err;\n }\n\n if (left() <= 0) return outOfTime;\n const back = await store.read(account, { timeoutMs: left() });\n if (back.kind === 'hit') {\n return back.value === secret\n ? { outcome: 'stored' }\n : { outcome: 'conflict', detail: 'a different passphrase is saved there after the write' };\n }\n if (back.kind !== 'miss') return { outcome: 'uncertain', detail: back.detail };\n if (wrote) return { outcome: 'store-failed', detail: 'the saved passphrase did not read back' };\n const failure = classifyStoreFailure(storeName, writeError);\n if (isKilled(writeError)) {\n return { outcome: 'uncertain', detail: 'detail' in failure ? failure.detail : undefined };\n }\n return {\n outcome: 'store-failed',\n detail: writeFailureDetail(storeName, writeError, failure),\n };\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\n/** A write that was killed on its deadline: it may have committed, so only a read-back can say. */\nfunction isKilled(err: unknown): boolean {\n return err instanceof StoreExecError && (err.killed || err.signal !== null);\n}\n\n/** Why a write failed, in classified words: the read classification, or the fs errno for the file. */\nfunction writeFailureDetail(\n store: DurableStore,\n err: unknown,\n failure: Exclude<StoreRead, { kind: 'hit' }>,\n): string {\n if (store === 'file') {\n const code = (err as { code?: unknown } | null)?.code;\n return typeof code === 'string' && /^E[A-Z]+$/.test(code)\n ? `the passphrase file could not be written (${code})`\n : 'the passphrase file could not be written';\n }\n return 'detail' in failure ? failure.detail : `the ${storeNoun(store)} write failed`;\n}\n\n/**\n * S1: how the --replace archive writer (local.ts) maps storeDurablyDetailed's\n * DurableWrite. `stored` only ever means the store holds the intended value: a\n * store that holds a DIFFERENT one (`conflict`, or `kept-existing`, which that\n * writer never asks for since it passes no replaceIf) is `store-failed`.\n */\nexport function toStoreOutcome(w: DurableWrite): Exclude<StorePassphraseOutcome, 'no-store'> {\n switch (w) {\n case 'stored':\n return 'stored';\n case 'already-stored':\n return 'stored';\n case 'kept-existing':\n return 'store-failed';\n case 'conflict':\n return 'store-failed';\n case 'uncertain':\n return 'uncertain';\n case 'store-failed':\n return 'store-failed';\n case 'rejected-characters':\n return 'rejected-characters';\n }\n}\n\n/** What `resolvePassphraseForCreate` chose, and where the secret now lives. */\nexport interface CreatePassphraseResult {\n passphrase: string;\n source: DurableStore | 'env';\n origin: 'generated' | 'env';\n /** describeStoreLocation of the store, or `TENJIN_WALLET_PASSPHRASE` when nothing durable holds it. */\n location: string;\n /** false only for an env secret whose store write was uncertain or failed. */\n durable: boolean;\n /** Why the file store: the OS store probed absent (S4 line), or --insecure-storage. Absent otherwise. */\n fileReason?: 'no-keyring' | 'insecure-storage';\n /** durable:false only: the store the env secret could not be saved to (picks the passphraseNote wording). */\n attempted?: DurableStore;\n /** durable:false only: why it was not saved there (picks the passphraseNote wording). */\n notSaved?: Exclude<DurableWrite, 'stored' | 'already-stored'>;\n}\n\n/**\n * Is the platform's own store reachable, before create or repair picks a\n * target? `absent` is definite (no `secret-tool`, no D-Bus, no default\n * keychain, no PowerShell, or a platform with no OS store at all) and sends the\n * secret to the 0600 file. `uncertain` (killed at 3 s, refused, anything\n * unclear) is NOT absent: the store exists and may just be locked, so callers\n * refuse rather than fall to plaintext (S3). DPAPI has no lock, so its probe is\n * never `uncertain`: anything but a missing PowerShell is `available`.\n */\nexport async function probeDurableStore(\n deps: PassphraseDeps,\n): Promise<{ store: DurableStore; probe: StoreProbe; detail?: string }> {\n const store = storeFor(deps);\n if (store === null) {\n return { store: 'file', probe: 'absent', detail: 'this platform has no OS credential store' };\n }\n const result = await store.probe({ timeoutMs: timeoutsOf(deps).probeMs });\n return { store: store.source, ...result };\n}\n\n/**\n * Resolve the passphrase to ENCRYPT the new wallet at `address`. It NEVER\n * prompts (Q1): the secret is `TENJIN_WALLET_PASSPHRASE` when set, else 32\n * random bytes, chosen ONCE before any write. Users who want their own\n * passphrase set the variable.\n *\n * Where it goes: the file store with `insecureStorage`; otherwise the platform\n * store when its probe says available, the 0600 file when it says absent (S4),\n * and a refusal when it says uncertain (S3: a locked keychain is never routed\n * around). An env secret is saved durably too (Q2), so a one-shot agent install\n * with the variable set does not strand the wallet once the variable is gone.\n *\n * The write happens BEFORE the caller encrypts and is proven by reading it back\n * (storeDurablyDetailed), so a generated passphrase can never be lost between\n * generating it and persisting the encrypted key: a generated secret that is\n * not proven stored refuses the create. An env secret is still the user's to\n * keep, so its create goes ahead with `durable: false`. This path never touches\n * the legacy shared slot or any other wallet's entry.\n */\nexport async function resolvePassphraseForCreate(\n deps: PassphraseDeps,\n address: string,\n opts: { insecureStorage?: boolean } = {},\n): Promise<CreatePassphraseResult> {\n const fromEnv = envPassphrase(deps.env);\n const origin = fromEnv !== null ? 'env' : 'generated';\n const secret = fromEnv ?? randomBytes(32).toString('base64url');\n const account = walletStoreAccount(address);\n const envOnly = (\n attempted: DurableStore,\n notSaved: Exclude<DurableWrite, 'stored' | 'already-stored'>,\n ): CreatePassphraseResult => ({\n passphrase: secret,\n source: 'env',\n origin,\n location: 'TENJIN_WALLET_PASSPHRASE',\n durable: false,\n attempted,\n notSaved,\n });\n\n let target: DurableStore;\n let fileReason: CreatePassphraseResult['fileReason'];\n if (opts.insecureStorage === true) {\n target = 'file';\n fileReason = 'insecure-storage';\n } else {\n const probed = await probeDurableStore(deps);\n if (probed.probe === 'available') {\n target = probed.store;\n } else if (probed.probe === 'absent') {\n target = 'file';\n fileReason = 'no-keyring';\n } else {\n if (origin === 'env') return envOnly(probed.store, 'uncertain');\n throw new CliError(\n 'REFUSED',\n `The ${storeNoun(probed.store)} did not answer within ${Math.round(timeoutsOf(deps).probeMs / 1000)} s; it may be locked. No wallet was created.`,\n { fix: KEYCHAIN_LOCKED_FIX, details: unlockDetails('keychain_locked') },\n );\n }\n }\n\n const written = await storeDurablyDetailed(deps, target, address, secret);\n if (written.outcome === 'stored' || written.outcome === 'already-stored') {\n return {\n passphrase: secret,\n source: target,\n origin,\n location: describeStoreLocation(target, account, deps.dir),\n durable: true,\n ...(fileReason !== undefined ? { fileReason } : {}),\n };\n }\n if (origin === 'env') return envOnly(target, written.outcome);\n const detail = written.detail ?? `the ${storeNoun(target)} write failed`;\n if (target === 'file') {\n // Decision 6: there is no keychain to unlock here, so neither the fix nor\n // the details may point at one.\n const path = describeStoreLocation('file', account, deps.dir);\n throw new CliError(\n 'REFUSED',\n `Could not save the wallet passphrase to ${path} (${detail}); no wallet was created.`,\n {\n fix: FILE_STORE_FAILED_FIX(path),\n details: { passphraseStore: { kind: 'file-write-failed', path } },\n },\n );\n }\n throw new CliError(\n 'REFUSED',\n `Could not save the wallet passphrase to ${describeStoreLocation(target, account, deps.dir)} (${detail}); no wallet was created.`,\n { fix: KEYCHAIN_LOCKED_FIX, details: unlockDetails('keychain_locked', target) },\n );\n}\n\n/**\n * Where a store keeps `account`'s passphrase, in words an operator can find it\n * by. The file path shows the home directory as `~`.\n */\nexport function describeStoreLocation(store: DurableStore, account: string, dir?: string): string {\n switch (store) {\n case 'keychain':\n return `your macOS keychain (service ${KEYCHAIN_SERVICE}, account ${account})`;\n case 'secret-service':\n return `your Linux keyring (Secret Service, service ${KEYCHAIN_SERVICE}, account ${account})`;\n case 'dpapi':\n return `a DPAPI-encrypted file (passphrase.${account}.dpapi)`;\n case 'file':\n return tildePath(passphraseFilePathFor(account, dir));\n }\n}\n\n/** `path` with the home directory shown as `~`, as a person would type it. */\nfunction tildePath(path: string): string {\n const home = homedir();\n if (home.length > 1 && (path === home || path.startsWith(`${home}/`))) {\n return `~${path.slice(home.length)}`;\n }\n return path;\n}\n\n/** Ask for a passphrase at the hidden prompt (repair, and the `--replace` outgoing wallet). */\nexport function promptPassphrase(deps: PassphraseDeps, label: string): Promise<string> {\n return promptOf(deps)(label);\n}\n\n/**\n * macOS login keychain via the OS `security` tool — the same mechanism the GitHub\n * CLI uses. Reads use `-w`, so the secret comes back on stdout, never in argv.\n * Writes pipe an `add-generic-password` command to `security -i` over stdin so the\n * passphrase never appears in any argv either.\n */\nfunction keychainStore(deps: PassphraseDeps): PassphraseStore {\n const exec = deps.exec ?? defaultExecFor();\n return {\n source: 'keychain',\n async read(account, o) {\n try {\n const { stdout } = await exec(\n 'security',\n ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account, '-w'],\n undefined,\n callOpts(o),\n );\n const value = oneNewlineStripped(stdout);\n return value.length > 0 ? { kind: 'hit', value } : { kind: 'miss' };\n } catch (err) {\n return classifyStoreFailure('keychain', err);\n }\n },\n // The one backend that interpolates into a command line. base64url values\n // keep today's exact `-w '<value>'` line; any other printable-ASCII value is\n // sent as hex, so no character of it is ever syntax. Escaping is NOT a safe\n // alternative (backslash bites even inside single quotes there).\n storable: (value) => PRINTABLE_ASCII_RE.test(value),\n async store(account, value, o) {\n if (!ACCOUNT_ADDRESS_RE.test(account) || !PRINTABLE_ASCII_RE.test(value)) {\n throw new CliError('INTERNAL', 'Refusing to send this value to the keychain writer.');\n }\n const secret = BASE64URL_RE.test(value)\n ? `-w '${value}'`\n : `-X ${Buffer.from(value, 'utf8').toString('hex')}`;\n // No `-U` unless the caller proved the existing entry wrong (repair): a\n // plain add fails on a duplicate instead of overwriting it.\n const update = o?.update === true ? ' -U' : '';\n const command = `add-generic-password -s ${KEYCHAIN_SERVICE} -a ${account} ${secret}${update}\\n`;\n await exec('security', ['-i'], command, callOpts(o));\n },\n async remove(account, o) {\n try {\n // No secret transits here; plain argv is fine (and visible is harmless).\n await exec(\n 'security',\n ['delete-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account],\n undefined,\n callOpts(o),\n );\n return true;\n } catch {\n return false;\n }\n },\n async probe(o) {\n try {\n await exec('security', ['default-keychain'], undefined, callOpts(o));\n return { probe: 'available' };\n } catch (err) {\n const failure = classifyStoreFailure('keychain', err);\n if (failure.kind === 'absent') return { probe: 'absent', detail: failure.detail };\n return {\n probe: 'uncertain',\n ...('detail' in failure ? { detail: failure.detail } : {}),\n };\n }\n },\n };\n}\n\n// PowerShell scripts run via built-in Windows PowerShell 5.1 (zero dependency).\n// Each reads its input from stdin and writes its output to stdout, so the\n// passphrase and the blob transit ONLY stdin/stdout, never argv. The stored blob\n// is DPAPI-protected for the CurrentUser scope: it decrypts only as this user on\n// this machine, which is the protection class we want; it is NOT the passphrase in\n// plaintext.\nconst DPAPI_PROTECT_SCRIPT = [\n 'Add-Type -AssemblyName System.Security;',\n '$in = [Console]::In.ReadToEnd();',\n '$bytes = [System.Text.Encoding]::UTF8.GetBytes($in);',\n \"$prot = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser');\",\n '[Console]::Out.Write([Convert]::ToBase64String($prot));',\n].join(' ');\nconst DPAPI_UNPROTECT_SCRIPT = [\n 'Add-Type -AssemblyName System.Security;',\n '$in = [Console]::In.ReadToEnd();',\n '$blob = [Convert]::FromBase64String($in.Trim());',\n \"$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, 'CurrentUser');\",\n '[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($plain));',\n].join(' ');\n\nfunction powershellArgs(script: string): string[] {\n return ['-NoProfile', '-NonInteractive', '-Command', script];\n}\n\n/**\n * Windows DPAPI-protected files, via preinstalled PowerShell 5.1 (zero\n * dependency), one blob per account: `passphrase.<address>.dpapi` for wallet\n * accounts, legacy `passphrase.dpapi` for the pre-per-wallet slot. store():\n * protect the passphrase through DPAPI (CurrentUser) and write the base64 blob.\n * read(): a missing file is a miss; otherwise the blob is unprotected back to\n * the passphrase, and a failed unprotect is `locked` (unknown), never a miss.\n */\nfunction dpapiStore(deps: PassphraseDeps): PassphraseStore {\n const exec = deps.exec ?? defaultExecFor();\n const blobPathFor = (account: string): string =>\n account === LEGACY_ACCOUNT\n ? passphraseBlobPath(deps.dir)\n : passphraseBlobPathFor(account, deps.dir);\n return {\n source: 'dpapi',\n async read(account, o) {\n let blob: string;\n try {\n blob = await readFile(blobPathFor(account), 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'miss' }; // No blob yet: a miss, not an error.\n return { kind: 'locked', detail: 'the DPAPI passphrase file could not be read' };\n }\n try {\n const { stdout } = await exec(\n 'powershell.exe',\n powershellArgs(DPAPI_UNPROTECT_SCRIPT),\n blob,\n callOpts(o),\n );\n const value = stdout.replace(/\\r?\\n$/, '');\n return value.length > 0 ? { kind: 'hit', value } : { kind: 'miss' };\n } catch (err) {\n return classifyStoreFailure('dpapi', err);\n }\n },\n storable: readsBackFromStdout,\n async store(account, passphrase, o) {\n const { stdout } = await exec(\n 'powershell.exe',\n powershellArgs(DPAPI_PROTECT_SCRIPT),\n passphrase,\n callOpts(o),\n );\n const blob = stdout.replace(/\\r?\\n$/, '').trim();\n if (blob.length === 0) throw new StoreExecError('powershell.exe', { code: 0 });\n // DPAPI CurrentUser encryption is the real protection here; `mode` is inert\n // on win32 (writeFileAtomic drops it there) and only bites when a POSIX host\n // exercises this store in tests. The blob is ciphertext, not the passphrase.\n await writeFileAtomic(blobPathFor(account), blob, { mode: 0o600 });\n },\n async remove(account) {\n try {\n await unlink(blobPathFor(account));\n return true;\n } catch {\n return false;\n }\n },\n async probe(o) {\n try {\n await exec(\n 'powershell.exe',\n ['-NoProfile', '-NonInteractive', '-Command', '$null'],\n undefined,\n callOpts(o),\n );\n return { probe: 'available' };\n } catch (err) {\n // DPAPI has no lock state: the only thing a probe can learn is whether\n // powershell.exe exists. A slow cold start killed at the probe bound, or\n // any other answer, still means it does, so it is never `uncertain`\n // (which would refuse create and repair with an unlock fix that cannot\n // apply). A write that then fails is reported by the write itself.\n const failure = classifyStoreFailure('dpapi', err);\n if (failure.kind === 'absent') return { probe: 'absent', detail: failure.detail };\n return { probe: 'available' };\n }\n },\n };\n}\n\n/**\n * Desktop-Linux Secret Service via `secret-tool` (libsecret-tools). `secret-tool`\n * reads the secret from stdin when stdin is not a TTY, so the passphrase never\n * appears in argv. Headless Linux, WSL and CI usually have no Secret Service at\n * all: an absent `secret-tool` (ENOENT) or no D-Bus is `absent`, which is what\n * sends create to the 0600 file. A keyring that is there but does not answer is\n * `locked`, which is not.\n */\nfunction secretServiceStore(deps: PassphraseDeps): PassphraseStore {\n const exec = deps.exec ?? defaultExecFor();\n const read: PassphraseStore['read'] = async (account, o) => {\n try {\n const { stdout } = await exec(\n 'secret-tool',\n ['lookup', 'service', KEYCHAIN_SERVICE, 'account', account],\n undefined,\n callOpts(o),\n );\n const value = oneNewlineStripped(stdout);\n return value.length > 0 ? { kind: 'hit', value } : { kind: 'miss' };\n } catch (err) {\n return classifyStoreFailure('secret-service', err);\n }\n };\n return {\n source: 'secret-service',\n read,\n storable: readsBackFromStdout,\n async store(account, passphrase, o) {\n // secret-tool store replaces an existing item itself; `update` adds nothing here.\n await exec(\n 'secret-tool',\n [\n 'store',\n `--label=tenjin-cli wallet ${account}`,\n 'service',\n KEYCHAIN_SERVICE,\n 'account',\n account,\n ],\n passphrase,\n callOpts(o),\n );\n },\n async remove(account, o) {\n try {\n await exec(\n 'secret-tool',\n ['clear', 'service', KEYCHAIN_SERVICE, 'account', account],\n undefined,\n callOpts(o),\n );\n return true;\n } catch {\n return false;\n }\n },\n async probe(o) {\n const got = await read(PROBE_ACCOUNT, o);\n if (got.kind === 'hit' || got.kind === 'miss') return { probe: 'available' };\n if (got.kind === 'absent') return { probe: 'absent', detail: got.detail };\n return { probe: 'uncertain', detail: got.detail };\n },\n };\n}\n\n/**\n * The passphrase FILE store: `<dataDir>/passphrase.<address>.plain`, the\n * plaintext passphrase at 0600 in a 0700 dir, no trailing newline. Used only\n * where no OS store exists or with `--insecure-storage` (see the file header).\n * A first write is NO-CLOBBER, like the wallet file; only repair, after proving\n * the old value wrong, replaces one (`update`). fs calls are not killed, so the\n * per-call deadline is accepted and ignored. A read strips exactly one trailing\n * `\\n` (someone may have written it with `echo`) and nothing else: a secret\n * ending in other whitespace round-trips, and one ending in `\\n` is refused\n * before any write (`storable`), so a failed save never leaves a file that\n * reads back as a different secret.\n */\nfunction fileStore(deps: PassphraseDeps): PassphraseStore {\n const pathFor = (account: string): string => passphraseFilePathFor(account, deps.dir);\n return {\n source: 'file',\n async read(account) {\n try {\n const value = oneLfStripped(await readFile(pathFor(account), 'utf8'));\n return value.length > 0 ? { kind: 'hit', value } : { kind: 'miss' };\n } catch (err) {\n return classifyStoreFailure('file', err);\n }\n },\n // The read strips one trailing LF, so a value ending in one never reads back.\n storable: (value) => !value.endsWith('\\n'),\n async store(account, value, o) {\n const path = pathFor(account);\n const mode = { mode: 0o600, dirMode: 0o700 };\n if (o?.update === true) return writeFileAtomic(path, value, mode);\n try {\n await writeFileAtomicExclusive(path, value, mode);\n } catch (err) {\n // AN EMPTY FILE HOLDS NO SECRET. On Windows the exclusive write opens the\n // target itself before writing, so a crash in between leaves it empty;\n // it reads as a miss, and without this every later save (repair\n // included) would hit EEXIST forever. Replacing it loses nothing.\n if (!hasCode(err, 'EEXIST') || (await stat(path).catch(() => null))?.size !== 0) throw err;\n await writeFileAtomic(path, value, mode);\n }\n },\n async remove(account) {\n try {\n await unlink(pathFor(account));\n return true;\n } catch {\n return false;\n }\n },\n probe: async () => ({ probe: 'available' }),\n };\n}\n\n/** The per-call exec options for a store call: the deadline when one was given, else none. */\nfunction callOpts(o: StoreCallOptions | undefined): { timeoutMs?: number } | undefined {\n return o?.timeoutMs !== undefined ? { timeoutMs: o.timeoutMs } : undefined;\n}\n\n/**\n * Whether a value survives a read that strips one trailing newline (LF or\n * CRLF) from the store CLI's stdout: one that ends in CR or LF does not.\n */\nfunction readsBackFromStdout(value: string): boolean {\n return !/[\\r\\n]$/.test(value);\n}\n\n/**\n * Why `store`'s `storable` gate turned a value away, as a clause: the\n * keychain writer's printable-ASCII rule, or a line break at the end that the\n * other stores' reads strip, so the saved value would not read back.\n */\nexport function unstorableWhy(store: DurableStore): string {\n return store === 'keychain'\n ? 'the macOS keychain writer only stores printable ASCII passphrases'\n : `a passphrase that ends in a line break does not read back from the ${storeNoun(store)}`;\n}\n\n/** A store payload with exactly one optional trailing newline (LF or CRLF) stripped. */\nfunction oneNewlineStripped(stdout: string): string {\n return stdout.replace(/\\r?\\n$/, '');\n}\n\n/** File contents with exactly one trailing LF stripped. */\nfunction oneLfStripped(text: string): string {\n return text.endsWith('\\n') ? text.slice(0, -1) : text;\n}\n\n/** The env passphrase, non-empty and used exactly as given; null when unset/empty. */\nfunction envPassphrase(env: NodeJS.ProcessEnv): string | null {\n const value = env.TENJIN_WALLET_PASSPHRASE;\n return value !== undefined && value.length > 0 ? value : null;\n}\n\nfunction canPrompt(deps: PassphraseDeps): boolean {\n return deps.isTTY ?? Boolean(process.stdin.isTTY);\n}\n\nfunction promptOf(deps: PassphraseDeps): PromptFn {\n return deps.prompt ?? promptHidden;\n}\n\n/**\n * No source holds a passphrase (`passphrase_missing`). The message keeps its\n * prefix (install-wallet matches on it); `location` names the recorded store\n * that came back empty. The fix sends the PERSON to repair (B1): never \"set\n * TENJIN_WALLET_PASSPHRASE\", which invites an agent to ask for the value.\n */\nfunction noPassphraseError(location?: string): CliError {\n return new CliError(\n 'USAGE',\n location === undefined\n ? 'No wallet passphrase is available.'\n : `No wallet passphrase is available: ${location} has no entry for this wallet.`,\n { fix: REPAIR_IN_TERMINAL, details: unlockDetails('passphrase_missing') },\n );\n}\n\n/**\n * A store that exists but did not answer (`keychain_locked`): unknown, never a\n * block, and its fix is to unlock it, never plaintext or another passphrase\n * (S3). `detail` is the classified one (S2). It also rides in\n * `details.storeDetail` so verify can word its row without parsing this message.\n */\nfunction storeLockedError(\n store: DurableStore,\n account: string,\n detail: string,\n dir: string | undefined,\n recorded: boolean,\n): CliError {\n const where = describeStoreLocation(store, account, dir);\n return new CliError(\n 'USAGE',\n `The passphrase store ${recorded ? 'recorded ' : ''}for this wallet, ${where}, did not answer (${detail}).`,\n {\n fix: KEYCHAIN_LOCKED_FIX,\n details: { ...unlockDetails('keychain_locked', store), storeDetail: detail },\n },\n );\n}\n\n// Control bytes handled by the raw-mode reader, named to avoid literal control\n// characters in the source.\nconst CTRL_C = 0x03;\nconst CTRL_D = 0x04;\nconst BACKSPACE = 0x7f;\nconst BACKSPACE_ALT = 0x08;\n\n/**\n * Read one line of input without echoing it. The prompt label goes to stderr so\n * stdout stays the single JSON envelope; typed characters are consumed in raw\n * mode and never printed. Only ever called on a real TTY (canPrompt gates it),\n * so setRawMode is present; tests inject `prompt` and never reach this.\n */\nfunction promptHidden(label: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const stdin = process.stdin;\n const stderr = process.stderr;\n const wasRaw = stdin.isRaw;\n let value = '';\n\n const cleanup = (): void => {\n stdin.setRawMode?.(wasRaw ?? false);\n stdin.pause();\n stdin.removeListener('data', onData);\n };\n const onData = (chunk: Buffer | string): void => {\n for (const ch of chunk.toString('utf8')) {\n const code = ch.charCodeAt(0);\n if (ch === '\\n' || ch === '\\r' || code === CTRL_D) {\n // Enter or Ctrl-D: submit what we have.\n cleanup();\n stderr.write('\\n');\n resolve(value);\n return;\n }\n if (code === CTRL_C) {\n cleanup();\n stderr.write('\\n');\n reject(\n new CliError('USAGE', 'Passphrase entry was cancelled.', {\n fix: 'Run the command again, or set TENJIN_WALLET_PASSPHRASE.',\n }),\n );\n return;\n }\n if (code === BACKSPACE || code === BACKSPACE_ALT) {\n value = value.slice(0, -1);\n } else {\n value += ch;\n }\n }\n };\n\n stderr.write(label);\n stdin.setRawMode?.(true);\n stdin.resume();\n stdin.on('data', onData);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,mBAAmB;AAC5B,SAAS,UAAU,MAAM,cAAc;AACvC,SAAS,eAAe;AAoDxB,IAAM,mBAAmB;AAMzB,IAAM,iBAAiB;AAMvB,IAAM,gBAAgB;AAGtB,IAAM,qBAAqB;AAQ3B,IAAM,eAAe;AASrB,IAAM,qBAAqB;AAMpB,SAAS,mBAAmB,SAAyB;AAC1D,QAAM,UAAU,QAAQ,YAAY;AACpC,MAAI,CAAC,mBAAmB,KAAK,OAAO,GAAG;AACrC,UAAM,IAAI,SAAS,YAAY,sDAAsD,OAAO,EAAE;AAAA,EAChG;AACA,SAAO;AACT;AA+CO,IAAM,iBAAN,cAA6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,OAAO,QAAQ,SAAS,QAAQ;AAEjD,kBAAQ;AACR,iBAAO,MAAM,IAAI;AACjB,kBAAQ,KAAK;AACb;AAAA,QACF;AACA,YAAI,SAAS,QAAQ;AACnB,kBAAQ;AACR,iBAAO,MAAM,IAAI;AACjB;AAAA,YACE,IAAI,SAAS,SAAS,mCAAmC;AAAA,cACvD,KAAK;AAAA,YACP,CAAC;AAAA,UACH;AACA;AAAA,QACF;AACA,YAAI,SAAS,aAAa,SAAS,eAAe;AAChD,kBAAQ,MAAM,MAAM,GAAG,EAAE;AAAA,QAC3B,OAAO;AACL,mBAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAEA,WAAO,MAAM,KAAK;AAClB,UAAM,aAAa,IAAI;AACvB,UAAM,OAAO;AACb,UAAM,GAAG,QAAQ,MAAM;AAAA,EACzB,CAAC;AACH;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/codex-bin.ts","../src/lib/codex-app-server.ts"],"sourcesContent":["import { statSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * WHAT TO START TO RUN `codex`, WITH NO SHELL. The PATH walk tries the PATHEXT\n * extensions on win32, as `findClaudeBinary` does for `claude`. A native\n * `codex.exe` runs as found. npm's `codex.cmd` shim cannot be started without\n * a shell, so the script it points at, `@openai/codex/bin/codex.js` beside it,\n * runs under this Node instead.\n */\nexport interface CodexCommand {\n cmd: string;\n /** Arguments that go before Codex's own: the script, for an npm shim. */\n prefix: string[];\n}\n\nconst NPM_SCRIPT = ['node_modules', '@openai', 'codex', 'bin', 'codex.js'];\n\nfunction isFile(path: string): boolean {\n try {\n return statSync(path).isFile();\n } catch {\n return false;\n }\n}\n\n/** The `codex` this machine runs, or null when PATH holds none that can start. */\nexport function resolveCodex(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n execPath: string = process.execPath,\n): CodexCommand | null {\n const win = platform === 'win32';\n const exts = win\n ? (env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)\n : [''];\n for (const part of (env.PATH ?? '').split(win ? ';' : ':')) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n // PATHEXT is upper case; Windows matches names in any case, so try both.\n const candidate = [ext, ext.toLowerCase()].map((e) => join(part, `codex${e}`)).find(isFile);\n if (candidate === undefined) continue;\n if (/^\\.(cmd|bat)$/i.test(ext)) {\n const script = join(part, ...NPM_SCRIPT);\n if (isFile(script)) return { cmd: execPath, prefix: [script] };\n continue;\n }\n return { cmd: candidate, prefix: [] };\n }\n }\n return null;\n}\n","import { spawn } from 'node:child_process';\nimport { resolveCodex } from './codex-bin';\nimport { codexHome } from './codex-home';\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v);\n}\n\nexport async function withAppServer<T>(\n home: string,\n env: NodeJS.ProcessEnv,\n timeoutMs: number,\n fn: (request: (method: string, params: unknown) => Promise<unknown>) => Promise<T>,\n): Promise<T | null> {\n const codex = resolveCodex(env);\n if (codex === null) return null;\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn(codex.cmd, [...codex.prefix, 'app-server'], {\n env: { ...env, CODEX_HOME: codexHome(home, env) },\n stdio: ['pipe', 'pipe', 'ignore'],\n windowsHide: true,\n });\n } catch {\n return null;\n }\n\n let dead = false;\n const pending = new Map<number, (value: unknown) => void>();\n const fail = (): void => {\n dead = true;\n for (const resolve of pending.values()) resolve(undefined);\n pending.clear();\n };\n child.on('error', fail);\n child.on('exit', fail);\n\n let buffered = '';\n child.stdout?.setEncoding('utf8');\n child.stdout?.on('data', (chunk: string) => {\n buffered += chunk;\n let cut = buffered.indexOf('\\n');\n while (cut !== -1) {\n const line = buffered.slice(0, cut);\n buffered = buffered.slice(cut + 1);\n cut = buffered.indexOf('\\n');\n let msg: unknown;\n try {\n msg = JSON.parse(line);\n } catch {\n continue;\n }\n if (!isRecord(msg) || typeof msg.id !== 'number') continue;\n const waiting = pending.get(msg.id);\n if (waiting === undefined) continue;\n pending.delete(msg.id);\n waiting(msg.error !== undefined ? undefined : msg.result);\n }\n });\n\n let nextId = 1;\n const send = (payload: unknown): boolean => {\n try {\n child.stdin?.write(`${JSON.stringify(payload)}\\n`);\n return true;\n } catch {\n return false;\n }\n };\n const request = async (method: string, params: unknown): Promise<unknown> => {\n if (dead) return undefined;\n const id = ++nextId;\n return await new Promise<unknown>((resolve) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n resolve(undefined);\n }, timeoutMs);\n pending.set(id, (value) => {\n clearTimeout(timer);\n resolve(value);\n });\n if (!send({ jsonrpc: '2.0', id, method, params })) {\n pending.delete(id);\n clearTimeout(timer);\n resolve(undefined);\n }\n });\n };\n\n try {\n // Load-bearing in this order: a request sent before the `initialized`\n // notification is dropped with no reply and no error.\n send({\n jsonrpc: '2.0',\n id: 1,\n method: 'initialize',\n params: { clientInfo: { name: 'tenjin', title: 'tenjin', version: '1' } },\n });\n send({ jsonrpc: '2.0', method: 'initialized', params: {} });\n return await fn(request);\n } catch {\n return null;\n } finally {\n try {\n child.stdin?.end();\n } catch {\n // Already closed.\n }\n child.kill('SIGTERM');\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,YAAY;AAerB,IAAM,aAAa,CAAC,gBAAgB,WAAW,SAAS,OAAO,UAAU;AAEzE,SAAS,OAAO,MAAuB;AACrC,MAAI;AACF,WAAO,SAAS,IAAI,EAAE,OAAO;AAAA,EAC/B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,aACd,MAAyB,QAAQ,KACjC,WAA4B,QAAQ,UACpC,WAAmB,QAAQ,UACN;AACrB,QAAM,MAAM,aAAa;AACzB,QAAM,OAAO,OACR,IAAI,WAAW,uBAAuB,MAAM,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC,IAC5E,CAAC,EAAE;AACP,aAAW,SAAS,IAAI,QAAQ,IAAI,MAAM,MAAM,MAAM,GAAG,GAAG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Q,MAAS;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AAEA,MAAI;AAGF,SAAK;AAAA,MACH,SAAS;AAAA,MACT,IAAI;AAAA,MACJ,QAAQ;AAAA,MACR,QAAQ,EAAE,YAAY,EAAE,MAAM,UAAU,OAAO,UAAU,SAAS,IAAI,EAAE;AAAA,IAC1E,CAAC;AACD,SAAK,EAAE,SAAS,OAAO,QAAQ,eAAe,QAAQ,CAAC,EAAE,CAAC;AAC1D,WAAO,MAAM,GAAG,OAAO;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT,UAAE;AACA,QAAI;AACF,YAAM,OAAO,IAAI;AAAA,IACnB,QAAQ;AAAA,IAER;AACA,UAAM,KAAK,SAAS;AAAA,EACtB;AACF;","names":[]}
@@ -1,33 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
-
3
- // src/lib/version-order.ts
4
- var VERSION_RE = /^(\d+)\.(\d+)\.(\d+)(?:-alpha\.(\d+))?$/;
5
- function parseVersion(raw) {
6
- const m = VERSION_RE.exec(raw);
7
- if (m === null) return null;
8
- const [, major, minor, patch, alpha] = m;
9
- if (major === void 0 || minor === void 0 || patch === void 0) return null;
10
- return {
11
- major: Number(major),
12
- minor: Number(minor),
13
- patch: Number(patch),
14
- alpha: alpha !== void 0 ? Number(alpha) : null
15
- };
16
- }
17
- function isNewer(candidate, current) {
18
- const a = parseVersion(candidate);
19
- const b = parseVersion(current);
20
- if (a === null || b === null) return false;
21
- if (a.major !== b.major) return a.major > b.major;
22
- if (a.minor !== b.minor) return a.minor > b.minor;
23
- if (a.patch !== b.patch) return a.patch > b.patch;
24
- if (a.alpha === null) return b.alpha !== null;
25
- if (b.alpha === null) return false;
26
- return a.alpha > b.alpha;
27
- }
28
-
29
- export {
30
- parseVersion,
31
- isNewer
32
- };
33
- //# sourceMappingURL=chunk-EDJWHDDL.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/version-order.ts"],"sourcesContent":["/**\n * VERSION COMPARISON: this package's shape only, no semver dependency. Its own\n * module with no imports, so the runtime's layout code (which a hand-off reads\n * before anything else loads) can order versions without pulling in the update\n * check's config and output modules.\n */\n\n/** `major.minor.patch` with an optional `-alpha.N` — every version tenjin-cli\n * has ever published. Anything else is unparseable ON PURPOSE (see isNewer). */\nconst VERSION_RE = /^(\\d+)\\.(\\d+)\\.(\\d+)(?:-alpha\\.(\\d+))?$/;\n\ninterface Version {\n major: number;\n minor: number;\n patch: number;\n /** null = a release; a number = that prerelease counter. */\n alpha: number | null;\n}\n\nexport function parseVersion(raw: string): Version | null {\n const m = VERSION_RE.exec(raw);\n if (m === null) return null;\n const [, major, minor, patch, alpha] = m;\n if (major === undefined || minor === undefined || patch === undefined) return null;\n return {\n major: Number(major),\n minor: Number(minor),\n patch: Number(patch),\n alpha: alpha !== undefined ? Number(alpha) : null,\n };\n}\n\n/**\n * Is `candidate` newer than `current`? An unparseable version on EITHER side is\n * \"not newer\": the registry is untrusted input, and the failure mode of guessing\n * is nagging every single command with a line the user cannot act on. A true\n * return therefore also certifies that BOTH sides parse, which is what lets\n * `tenjin update` splice the candidate into an npm argv without re-validating.\n */\nexport function isNewer(candidate: string, current: string): boolean {\n const a = parseVersion(candidate);\n const b = parseVersion(current);\n if (a === null || b === null) return false;\n if (a.major !== b.major) return a.major > b.major;\n if (a.minor !== b.minor) return a.minor > b.minor;\n if (a.patch !== b.patch) return a.patch > b.patch;\n // Same release triple: semver says a prerelease precedes its own release, so\n // 0.1.0 beats 0.1.0-alpha.9 and never the other way around.\n if (a.alpha === null) return b.alpha !== null;\n if (b.alpha === null) return false;\n return a.alpha > b.alpha;\n}\n"],"mappings":";;;AASA,IAAM,aAAa;AAUZ,SAAS,aAAa,KAA6B;AACxD,QAAM,IAAI,WAAW,KAAK,GAAG;AAC7B,MAAI,MAAM,KAAM,QAAO;AACvB,QAAM,CAAC,EAAE,OAAO,OAAO,OAAO,KAAK,IAAI;AACvC,MAAI,UAAU,UAAa,UAAU,UAAa,UAAU,OAAW,QAAO;AAC9E,SAAO;AAAA,IACL,OAAO,OAAO,KAAK;AAAA,IACnB,OAAO,OAAO,KAAK;AAAA,IACnB,OAAO,OAAO,KAAK;AAAA,IACnB,OAAO,UAAU,SAAY,OAAO,KAAK,IAAI;AAAA,EAC/C;AACF;AASO,SAAS,QAAQ,WAAmB,SAA0B;AACnE,QAAM,IAAI,aAAa,SAAS;AAChC,QAAM,IAAI,aAAa,OAAO;AAC9B,MAAI,MAAM,QAAQ,MAAM,KAAM,QAAO;AACrC,MAAI,EAAE,UAAU,EAAE,MAAO,QAAO,EAAE,QAAQ,EAAE;AAC5C,MAAI,EAAE,UAAU,EAAE,MAAO,QAAO,EAAE,QAAQ,EAAE;AAC5C,MAAI,EAAE,UAAU,EAAE,MAAO,QAAO,EAAE,QAAQ,EAAE;AAG5C,MAAI,EAAE,UAAU,KAAM,QAAO,EAAE,UAAU;AACzC,MAAI,EAAE,UAAU,KAAM,QAAO;AAC7B,SAAO,EAAE,QAAQ,EAAE;AACrB;","names":[]}
@@ -1 +0,0 @@
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 * Safe to reuse despite the `g` flag: {@link sanitizeForTerminal} uses it\n * through `String.replace`, which starts at 0 and resets `lastIndex`. Do not\n * `test()` 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,CAAC;AAYM,IAAM,wBAA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,IAAI,MAAM,oBAAoB,OAAO,CAAC;AAAA,MACpH;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,UAAU,QAA+B,OAAsB;AACtE,SAAO,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,CAAI;AACpD;AAEA,SAAS,WAAW,QAA+B,OAAuB;AACxE,MAAI,MAAM,SAAS,EAAG,QAAO,MAAM,GAAG,MAAM,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,105 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- normalizeChannelId
4
- } from "./chunk-IE7P2BZE.js";
5
-
6
- // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-3632HGL3.mjs
7
- import { mkdir, readFile, rename, unlink, writeFile } from "fs/promises";
8
- import { dirname, join, resolve, sep } from "path";
9
- function resolveWithinDir(baseDir, filename) {
10
- const base = resolve(baseDir);
11
- const target = resolve(base, filename);
12
- if (target !== base && !target.startsWith(base + sep)) {
13
- throw new Error("resolved channel path escapes storage root");
14
- }
15
- return target;
16
- }
17
- function isNodeEnoent(err) {
18
- if (!err || typeof err !== "object" || !("code" in err)) return false;
19
- return err.code === "ENOENT";
20
- }
21
- async function readJsonFile(filePath) {
22
- try {
23
- const raw = await readFile(filePath, "utf8");
24
- return JSON.parse(raw);
25
- } catch (err) {
26
- if (isNodeEnoent(err)) return void 0;
27
- throw err;
28
- }
29
- }
30
- async function writeJsonAtomic(filePath, value) {
31
- const dir = dirname(filePath);
32
- await mkdir(dir, { recursive: true });
33
- const tmp = join(dir, `.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
34
- const body = `${JSON.stringify(value, null, 2)}
35
- `;
36
- await writeFile(tmp, body, "utf8");
37
- try {
38
- await rename(tmp, filePath);
39
- } catch {
40
- await unlink(filePath).catch(() => {
41
- });
42
- await rename(tmp, filePath);
43
- }
44
- }
45
-
46
- // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/batch-settlement/client/file-storage.mjs
47
- import { unlink as unlink2 } from "fs/promises";
48
- import { join as join2 } from "path";
49
- var FileClientChannelStorage = class {
50
- /**
51
- * Creates file-backed client channel storage under the given root directory.
52
- *
53
- * @param options - Configuration including the storage root directory.
54
- */
55
- constructor(options) {
56
- this.root = options.directory;
57
- }
58
- /**
59
- * Loads the stored client context for a channel, if present.
60
- *
61
- * @param key - Channel storage key (typically a lowercased channelId).
62
- * @returns Parsed context or `undefined` when the file is missing.
63
- */
64
- async get(key) {
65
- return readJsonFile(this.filePath(key));
66
- }
67
- /**
68
- * Persists the client context for a channel.
69
- *
70
- * @param key - Channel storage key.
71
- * @param context - Context record to write.
72
- */
73
- async set(key, context) {
74
- await writeJsonAtomic(this.filePath(key), context);
75
- }
76
- /**
77
- * Removes the persisted context file for a channel, if it exists.
78
- *
79
- * @param key - Channel storage key.
80
- */
81
- async delete(key) {
82
- try {
83
- await unlink2(this.filePath(key));
84
- } catch (err) {
85
- if (isNodeEnoent(err)) return;
86
- throw err;
87
- }
88
- }
89
- /**
90
- * Absolute path to the JSON file for a channel.
91
- *
92
- * @param key - Channel storage key (a canonical `bytes32` channel id).
93
- * @returns Filesystem path under `{root}/client/...`.
94
- * @throws When `key` is not a canonical `bytes32` string or escapes the storage root.
95
- */
96
- filePath(key) {
97
- const id = normalizeChannelId(key);
98
- return resolveWithinDir(join2(this.root, "client"), `${id}.json`);
99
- }
100
- };
101
-
102
- export {
103
- FileClientChannelStorage
104
- };
105
- //# sourceMappingURL=chunk-GTTUCOPD.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/storage-utils.ts","../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/client/fileStorage.ts"],"sourcesContent":["import { mkdir, readFile, rename, unlink, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve, sep } from \"node:path\";\n\n/**\n * Resolves `filename` under `baseDir` and asserts the result stays within `baseDir`.\n *\n * @param baseDir - Directory that must contain the resolved path.\n * @param filename - Filename to resolve against `baseDir`.\n * @returns The absolute resolved path.\n * @throws When the resolved path escapes `baseDir` (e.g. via `..` or separators).\n */\nexport function resolveWithinDir(baseDir: string, filename: string): string {\n const base = resolve(baseDir);\n const target = resolve(base, filename);\n if (target !== base && !target.startsWith(base + sep)) {\n throw new Error(\"resolved channel path escapes storage root\");\n }\n return target;\n}\n\n/**\n * Returns true when `err` is a Node.js `ENOENT` filesystem error (file does not exist).\n *\n * @param err - The thrown value to inspect.\n * @returns `true` for `ENOENT`, `false` for any other value or error code.\n */\nexport function isNodeEnoent(err: unknown): boolean {\n if (!err || typeof err !== \"object\" || !(\"code\" in err)) return false;\n return (err as NodeJS.ErrnoException).code === \"ENOENT\";\n}\n\n/**\n * Reads a JSON file and parses it. Returns `undefined` if the file does not exist.\n * Other errors (permission, malformed JSON) are rethrown.\n *\n * @param filePath - Path to the JSON file.\n * @returns Parsed value, or `undefined` for `ENOENT`.\n */\nexport async function readJsonFile<T>(filePath: string): Promise<T | undefined> {\n try {\n const raw = await readFile(filePath, \"utf8\");\n return JSON.parse(raw) as T;\n } catch (err: unknown) {\n if (isNodeEnoent(err)) return undefined;\n throw err;\n }\n}\n\n/**\n * Writes JSON to `filePath` atomically (temp file in the same directory, then rename).\n * Creates parent directories as needed.\n *\n * @param filePath - Destination file path; parent dirs are created if missing.\n * @param value - JSON-serializable value to persist.\n */\nexport async function writeJsonAtomic(filePath: string, value: unknown): Promise<void> {\n const dir = dirname(filePath);\n await mkdir(dir, { recursive: true });\n const tmp = join(dir, `.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);\n const body = `${JSON.stringify(value, null, 2)}\\n`;\n await writeFile(tmp, body, \"utf8\");\n try {\n await rename(tmp, filePath);\n } catch {\n // On Windows, rename() onto an existing file throws EEXIST; unlink + rename is intentional.\n await unlink(filePath).catch(() => {});\n await rename(tmp, filePath);\n }\n}\n","import { unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { isNodeEnoent, readJsonFile, resolveWithinDir, writeJsonAtomic } from \"../storage-utils\";\nimport { normalizeChannelId } from \"../utils\";\nimport type { FileChannelStorageOptions } from \"../types\";\nimport type { ClientChannelStorage, BatchSettlementClientContext } from \"./storage\";\n\nexport type { FileChannelStorageOptions };\n\n/**\n * Node.js file-backed {@link ClientChannelStorage} for the batched client scheme.\n * Each channel's context is persisted as `{root}/client/{channelId}.json` so that channel\n * records survive process restarts.\n */\nexport class FileClientChannelStorage implements ClientChannelStorage {\n private readonly root: string;\n\n /**\n * Creates file-backed client channel storage under the given root directory.\n *\n * @param options - Configuration including the storage root directory.\n */\n constructor(options: FileChannelStorageOptions) {\n this.root = options.directory;\n }\n\n /**\n * Loads the stored client context for a channel, if present.\n *\n * @param key - Channel storage key (typically a lowercased channelId).\n * @returns Parsed context or `undefined` when the file is missing.\n */\n async get(key: string): Promise<BatchSettlementClientContext | undefined> {\n return readJsonFile<BatchSettlementClientContext>(this.filePath(key));\n }\n\n /**\n * Persists the client context for a channel.\n *\n * @param key - Channel storage key.\n * @param context - Context record to write.\n */\n async set(key: string, context: BatchSettlementClientContext): Promise<void> {\n await writeJsonAtomic(this.filePath(key), context);\n }\n\n /**\n * Removes the persisted context file for a channel, if it exists.\n *\n * @param key - Channel storage key.\n */\n async delete(key: string): Promise<void> {\n try {\n await unlink(this.filePath(key));\n } catch (err: unknown) {\n if (isNodeEnoent(err)) return;\n throw err;\n }\n }\n\n /**\n * Absolute path to the JSON file for a channel.\n *\n * @param key - Channel storage key (a canonical `bytes32` channel id).\n * @returns Filesystem path under `{root}/client/...`.\n * @throws When `key` is not a canonical `bytes32` string or escapes the storage root.\n */\n private filePath(key: string): string {\n const id = normalizeChannelId(key);\n return resolveWithinDir(join(this.root, \"client\"), `${id}.json`);\n }\n}\n"],"mappings":";;;;;;AAAA,SAAS,OAAO,UAAU,QAAQ,QAAQ,iBAAiB;AAC3D,SAAS,SAAS,MAAM,SAAS,WAAW;AAUrC,SAAS,iBAAiB,SAAiB,UAA0B;AAC1E,QAAM,OAAO,QAAQ,OAAO;AAC5B,QAAM,SAAS,QAAQ,MAAM,QAAQ;AACrC,MAAI,WAAW,QAAQ,CAAC,OAAO,WAAW,OAAO,GAAG,GAAG;AACrD,UAAM,IAAI,MAAM,4CAA4C;EAC9D;AACA,SAAO;AACT;AAQO,SAAS,aAAa,KAAuB;AAClD,MAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,EAAE,UAAU,KAAM,QAAO;AAChE,SAAQ,IAA8B,SAAS;AACjD;AASA,eAAsB,aAAgB,UAA0C;AAC9E,MAAI;AACF,UAAM,MAAM,MAAM,SAAS,UAAU,MAAM;AAC3C,WAAO,KAAK,MAAM,GAAG;EACvB,SAAS,KAAc;AACrB,QAAI,aAAa,GAAG,EAAG,QAAO;AAC9B,UAAM;EACR;AACF;AASA,eAAsB,gBAAgB,UAAkB,OAA+B;AACrF,QAAM,MAAM,QAAQ,QAAQ;AAC5B,QAAM,MAAM,KAAK,EAAE,WAAW,KAAK,CAAC;AACpC,QAAM,MAAM,KAAK,KAAK,IAAI,QAAQ,GAAG,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC,MAAM;AAChG,QAAM,OAAO,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;;AAC9C,QAAM,UAAU,KAAK,MAAM,MAAM;AACjC,MAAI;AACF,UAAM,OAAO,KAAK,QAAQ;EAC5B,QAAQ;AAEN,UAAM,OAAO,QAAQ,EAAE,MAAM,MAAM;IAAC,CAAC;AACrC,UAAM,OAAO,KAAK,QAAQ;EAC5B;AACF;;;ACpEA,SAAS,UAAAA,eAAc;AACvB,SAAS,QAAAC,aAAY;AAcd,IAAM,2BAAN,MAA+D;;;;;;EAQpE,YAAY,SAAoC;AAC9C,SAAK,OAAO,QAAQ;EACtB;;;;;;;EAQA,MAAM,IAAI,KAAgE;AACxE,WAAO,aAA2C,KAAK,SAAS,GAAG,CAAC;EACtE;;;;;;;EAQA,MAAM,IAAI,KAAa,SAAsD;AAC3E,UAAM,gBAAgB,KAAK,SAAS,GAAG,GAAG,OAAO;EACnD;;;;;;EAOA,MAAM,OAAO,KAA4B;AACvC,QAAI;AACF,YAAMD,QAAO,KAAK,SAAS,GAAG,CAAC;IACjC,SAAS,KAAc;AACrB,UAAI,aAAa,GAAG,EAAG;AACvB,YAAM;IACR;EACF;;;;;;;;EASQ,SAAS,KAAqB;AACpC,UAAM,KAAK,mBAAmB,GAAG;AACjC,WAAO,iBAAiBC,MAAK,KAAK,MAAM,QAAQ,GAAG,GAAG,EAAE,OAAO;EACjE;AACF;","names":["unlink","join"]}
@@ -1,122 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- evaluateSpendPolicy
4
- } from "./chunk-2SNUOHAT.js";
5
- import {
6
- formatUsdDisplay
7
- } from "./chunk-Y527D4TV.js";
8
- import {
9
- WALLET_REASONS,
10
- agentFixFor
11
- } from "./chunk-BFDQ4WNW.js";
12
-
13
- // src/router/fee.ts
14
- import { join } from "node:path";
15
- var ROUTE_PAID_PATH = "/api/x402-router/route";
16
- var ROUTING_FEE_ATOMIC = 3000n;
17
- var CHANNEL_DEPOSIT_ATOMIC = 250000n;
18
- var SUGGESTED_FUND_USD = "5";
19
- var FUNDING_LINE = `Fund it with \`tenjin wallet fund ${SUGGESTED_FUND_USD}\`, or send USDC on Base.`;
20
- var FUND_COMMAND_LINE = `Fund it with \`tenjin wallet fund ${SUGGESTED_FUND_USD}\`.`;
21
- var ROUTING_DEPOSIT_KEY = "routing-deposit:";
22
- var REFUSED = {
23
- not_allowlisted: "not_allowlisted",
24
- session_budget_exceeded: "budget_reached",
25
- above_auto_spend: "limit_below_deposit"
26
- };
27
- function refusedWhy(reason) {
28
- return REFUSED[reason] ?? reason;
29
- }
30
- function feeRefusal(policy, host) {
31
- const evaluation = evaluateSpendPolicy(
32
- { ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },
33
- { mode: "automatic", amountAtomic: ROUTING_FEE_ATOMIC, creator: host, sessionSpentAtomic: 0n }
34
- );
35
- return evaluation.decision === "allow" ? null : refusedWhy(evaluation.reason);
36
- }
37
- var FEE_REQUIRED = "fee_required";
38
- function isFeeRequired(response) {
39
- const decision = response?.decision;
40
- const diagnostics = decision?.diagnostics;
41
- return decision?.action === "native" && diagnostics?.reasonCode === FEE_REQUIRED;
42
- }
43
- var WALLET_UNPAID = Object.fromEntries(
44
- Object.entries(WALLET_REASONS).map(([key, { reason, fix }]) => [key, { reason, fix }])
45
- );
46
- var UNPAID = {
47
- wallet_low: {
48
- reason: `the wallet holds less than the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,
49
- fix: `Fund it with \`tenjin wallet fund ${SUGGESTED_FUND_USD}\`.`
50
- },
51
- ...WALLET_UNPAID,
52
- limit_below_deposit: {
53
- reason: `the per-call spend limit is below the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,
54
- fix: "Run `tenjin doctor`."
55
- },
56
- budget_reached: {
57
- reason: "the daily spend limit has no room left for the routing fee or its deposit",
58
- fix: "Run `tenjin doctor`."
59
- },
60
- not_allowlisted: {
61
- reason: "allowlistCreators does not include the router",
62
- fix: "Run `tenjin doctor`."
63
- },
64
- payment_failed: {
65
- reason: "the routing payment failed",
66
- fix: "Run `tenjin doctor`."
67
- },
68
- [FEE_REQUIRED]: {
69
- reason: "the router now charges it, and this session cannot pay it",
70
- fix: "Run `tenjin doctor`."
71
- }
72
- };
73
- var NO_FAULT = /* @__PURE__ */ new Set([
74
- "channel_busy",
75
- "paid_path_absent",
76
- "busy",
77
- "no_call",
78
- "deadline_after_payment_sent",
79
- "unlock_timeout"
80
- ]);
81
- function unpaid(why) {
82
- if (NO_FAULT.has(why)) return null;
83
- return UNPAID[why] ?? UNPAID["payment_failed"];
84
- }
85
- function depositSentence(amountAtomic) {
86
- return `Tenjin moved $${usd(amountAtomic)} into prepaid routing credit; each routing call uses $${usd(ROUTING_FEE_ATOMIC)}.`;
87
- }
88
- function unpaidSentence(why, reader = "person") {
89
- const u = unpaid(why);
90
- if (u === null) return null;
91
- const fix = reader === "agent" ? agentFixFor(why, u.fix) : u.fix;
92
- return `Tenjin routing could not pay its $${usd(ROUTING_FEE_ATOMIC)} fee (${u.reason}), so Tenjin is not routing calls until that is fixed. ${fix}`;
93
- }
94
- var ADDRESS_RE = /^0x[0-9a-f]{40}$/;
95
- function payerDir(dataDir, payer) {
96
- const name = payer.toLowerCase();
97
- if (!ADDRESS_RE.test(name)) throw new Error(`not a wallet address: ${payer}`);
98
- return join(dataDir, "router", "fee", name);
99
- }
100
- function usd(atomic) {
101
- return formatUsdDisplay(atomic.toString());
102
- }
103
-
104
- export {
105
- ROUTE_PAID_PATH,
106
- ROUTING_FEE_ATOMIC,
107
- CHANNEL_DEPOSIT_ATOMIC,
108
- SUGGESTED_FUND_USD,
109
- FUNDING_LINE,
110
- FUND_COMMAND_LINE,
111
- ROUTING_DEPOSIT_KEY,
112
- refusedWhy,
113
- feeRefusal,
114
- FEE_REQUIRED,
115
- isFeeRequired,
116
- unpaid,
117
- depositSentence,
118
- unpaidSentence,
119
- payerDir,
120
- usd
121
- };
122
- //# sourceMappingURL=chunk-HDPUXS3Z.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/fee.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { formatUsdDisplay } from '../lib/money';\nimport { evaluateSpendPolicy, type PolicyReason, type SpendPolicy } from '../lib/policy';\nimport type { DecisionRoute } from './decision';\nimport { agentFixFor, WALLET_REASONS } from './wallet-reasons';\n\n/**\n * THE ROUTING FEE, WITHOUT ANYTHING THAT PAYS. Every routing call on the paid\n * path pays $0.003 over x402 `batch-settlement`, and the stock SDK client in\n * `tenjin mcp` does all of it (`routing-payer.ts`). Everything else, `tenjin\n * hook` included, is the free path exactly as before this fee existed.\n *\n * Hook-safe: `tenjin hook` loads this module, and its chunk graph stays free\n * of the wallet and the x402 SDK (`dist-chunks.test.ts`).\n */\n\nexport const ROUTE_PAID_PATH = '/api/x402-router/route';\n\n/** The flat fee per routing call, atomic USDC ($0.003). */\nexport const ROUTING_FEE_ATOMIC = 3_000n;\n/** The largest channel deposit, atomic USDC ($0.25), made inline by the SDK\n * on the first paid call of a channel that cannot cover the next fee. */\nexport const CHANNEL_DEPOSIT_ATOMIC = 250_000n;\n/**\n * The top-up every \"fund the wallet\" hint names, in USD: the checkout's Apple\n * Pay and Google Pay minimum, which covers the routing deposit and a few\n * hundred lookups. `tenjin wallet fund` sends it to the checkout as a preset.\n */\nexport const SUGGESTED_FUND_USD = '5';\n/** The funding line a new wallet is told, after `tenjin wallet create`. */\nexport const FUNDING_LINE = `Fund it with \\`tenjin wallet fund ${SUGGESTED_FUND_USD}\\`, or send USDC on Base.`;\n/** The funding line under a wallet at exactly $0, in `tenjin wallet balance` and `tenjin status`: the command alone. */\nexport const FUND_COMMAND_LINE = `Fund it with \\`tenjin wallet fund ${SUGGESTED_FUND_USD}\\`.`;\n/** The spend ledger key a deposit's exposure is recorded under, before its id. */\nexport const ROUTING_DEPOSIT_KEY = 'routing-deposit:';\n\n/** A spend refusal, as the reason the call was not paid. */\nconst REFUSED: Partial<Record<PolicyReason, string>> = {\n not_allowlisted: 'not_allowlisted',\n session_budget_exceeded: 'budget_reached',\n above_auto_spend: 'limit_below_deposit',\n};\n\n/** The reason a spend refusal leaves a routing call unpaid. */\nexport function refusedWhy(reason: PolicyReason): string {\n return REFUSED[reason] ?? reason;\n}\n\n/**\n * THE DEPOSIT IS THE SPEND. It meets the whole policy once, the day's budget\n * included, when the SDK's `depositStrategy` reserves it. Each fee paid from\n * it then gets only the per-payment checks: the per-call limit, the creator\n * allowlist (the router's host) and an explicit zero daily limit. It is never\n * refused for the day's running total, which the deposit already consumed.\n * Null when those checks allow the fee.\n */\nexport function feeRefusal(policy: SpendPolicy, host: string): string | null {\n const evaluation = evaluateSpendPolicy(\n { ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },\n { mode: 'automatic', amountAtomic: ROUTING_FEE_ATOMIC, creator: host, sessionSpentAtomic: 0n },\n );\n return evaluation.decision === 'allow' ? null : refusedWhy(evaluation.reason);\n}\n\n/** The paid path for this call, or null for the free path. `tenjin mcp` passes\n * its payer's; absent, every call is free. */\nexport type RouteFor = (baseUrl: string) => Promise<DecisionRoute | null>;\n\n/** The free path's reason code once the server routes only paid calls. */\nexport const FEE_REQUIRED = 'fee_required';\n\n/** Whether a decision is the free path's `fee_required` answer. */\nexport function isFeeRequired(response: unknown): boolean {\n const decision = (response as { decision?: { action?: unknown; diagnostics?: unknown } })\n ?.decision;\n const diagnostics = decision?.diagnostics as { reasonCode?: unknown } | undefined;\n return decision?.action === 'native' && diagnostics?.reasonCode === FEE_REQUIRED;\n}\n\n/**\n * WHY A CALL WAS NOT PAID, for the user: the reason and the fix, keyed by the\n * payer's skip reason (or `fee_required`, when the free path answered it and\n * nothing else explains why). Null for a reason that is no fault and needs no\n * fix: another session's call on the channel, a server with no paid path, or\n * a call queued past its own budget, or a payment still out when the call's\n * budget ran out (it finishes in the background), or an unlock that did not\n * finish inside the call's budget (it keeps running, and the next call gets\n * its answer).\n *\n * THE WALLET'S OWN REASONS ARE `WALLET_REASONS`, spread in rather than written\n * twice, so a notice names the same cause in the same words as doctor. They\n * carry the PERSON `fix`, never `agentFix`: this sentence goes in the hook's\n * `systemMessage`, which the harness shows the person (B1, decision 15), and a\n * fix that names `tenjin wallet repair` says it asks in their own terminal.\n * Every other entry, `wallet_low` included, is byte for byte what it was (S5).\n */\nconst WALLET_UNPAID: Record<string, { reason: string; fix: string }> = Object.fromEntries(\n Object.entries(WALLET_REASONS).map(([key, { reason, fix }]) => [key, { reason, fix }]),\n);\nconst UNPAID: Record<string, { reason: string; fix: string }> = {\n wallet_low: {\n reason: `the wallet holds less than the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,\n fix: `Fund it with \\`tenjin wallet fund ${SUGGESTED_FUND_USD}\\`.`,\n },\n ...WALLET_UNPAID,\n limit_below_deposit: {\n reason: `the per-call spend limit is below the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,\n fix: 'Run `tenjin doctor`.',\n },\n budget_reached: {\n reason: 'the daily spend limit has no room left for the routing fee or its deposit',\n fix: 'Run `tenjin doctor`.',\n },\n not_allowlisted: {\n reason: 'allowlistCreators does not include the router',\n fix: 'Run `tenjin doctor`.',\n },\n payment_failed: {\n reason: 'the routing payment failed',\n fix: 'Run `tenjin doctor`.',\n },\n [FEE_REQUIRED]: {\n reason: 'the router now charges it, and this session cannot pay it',\n fix: 'Run `tenjin doctor`.',\n },\n};\nconst NO_FAULT = new Set([\n 'channel_busy',\n 'paid_path_absent',\n 'busy',\n 'no_call',\n 'deadline_after_payment_sent',\n 'unlock_timeout',\n]);\n\n/** The reason and fix for an unpaid call, or null when it needs no word. */\nexport function unpaid(why: string): { reason: string; fix: string } | null {\n if (NO_FAULT.has(why)) return null;\n return UNPAID[why] ?? UNPAID['payment_failed']!;\n}\n\n/**\n * The one line said when a routing call's deposit went through: the money is\n * prepaid credit the next calls draw from, not a lookup it bought. It still\n * counts toward the daily limit ({@link feeRefusal}).\n */\nexport function depositSentence(amountAtomic: bigint): string {\n return `Tenjin moved $${usd(amountAtomic)} into prepaid routing credit; each routing call uses $${usd(ROUTING_FEE_ATOMIC)}.`;\n}\n\n/**\n * The one line the user sees, once per session and reason, when a call was not\n * paid. Its reader picks the fix (B1): the person's by default; for the model\n * (the `request` tool's text) a wallet unlock reason's `agentFix`, which asks\n * the person to act and never for the passphrase, and any other reason's own.\n */\nexport function unpaidSentence(why: string, reader: 'person' | 'agent' = 'person'): string | null {\n const u = unpaid(why);\n if (u === null) return null;\n const fix = reader === 'agent' ? agentFixFor(why, u.fix) : u.fix;\n return `Tenjin routing could not pay its $${usd(ROUTING_FEE_ATOMIC)} fee (${u.reason}), so Tenjin is not routing calls until that is fixed. ${fix}`;\n}\n\nconst ADDRESS_RE = /^0x[0-9a-f]{40}$/;\n\n/** One wallet's folder: the SDK's file storage for its routing channel\n * (`client/<channelId>.json`). */\nexport function payerDir(dataDir: string, payer: string): string {\n const name = payer.toLowerCase();\n if (!ADDRESS_RE.test(name)) throw new Error(`not a wallet address: ${payer}`);\n return join(dataDir, 'router', 'fee', name);\n}\n\n/** Atomic USDC as dollars with at least two decimals, never a float. */\nexport function usd(atomic: bigint): string {\n return formatUsdDisplay(atomic.toString());\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,YAAY;AAgBd,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,yBAAyB;AAM/B,IAAM,qBAAqB;AAE3B,IAAM,eAAe,qCAAqC,kBAAkB;AAE5E,IAAM,oBAAoB,qCAAqC,kBAAkB;AAEjF,IAAM,sBAAsB;AAGnC,IAA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