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
@@ -0,0 +1,2078 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ appendPaidRecord,
4
+ chargedOnChain,
5
+ recordedSent,
6
+ walletPaidHost,
7
+ writeNewFile
8
+ } from "./chunk-MAHNZA6C.js";
9
+ import {
10
+ promptYesNo
11
+ } from "./chunk-NVSKJPRC.js";
12
+ import {
13
+ validateResultBody
14
+ } from "./chunk-R4KDH477.js";
15
+ import {
16
+ paymentShortOfFunds
17
+ } from "./chunk-5USBZ2MU.js";
18
+ import {
19
+ buildExactPayment,
20
+ createPayerClient,
21
+ isCanonicalUsdc,
22
+ noPayableRequirement,
23
+ selectPayableRequirement,
24
+ signsEip3009
25
+ } from "./chunk-JTILUN4W.js";
26
+ import {
27
+ SIGN_IN_WITH_X,
28
+ SIWX_HEADER,
29
+ answerSignInChallenge,
30
+ buildSiwxHeader,
31
+ signInOnlyChallenge
32
+ } from "./chunk-OQWPRFAC.js";
33
+ import {
34
+ describeWallet,
35
+ resolveSpendAuthorizer,
36
+ resolveWalletProvider
37
+ } from "./chunk-K5KNGC4I.js";
38
+ import {
39
+ readSpendSummary,
40
+ spentOf
41
+ } from "./chunk-HPRVFJPM.js";
42
+ import {
43
+ HTTPFacilitatorClient,
44
+ PaymentRequirementsV2Schema,
45
+ decodePaymentRequiredHeader,
46
+ decodePaymentResponseHeader
47
+ } from "./chunk-RGVCOG2S.js";
48
+ import {
49
+ getAddress
50
+ } from "./chunk-INSIW65E.js";
51
+ import {
52
+ notePaymentSent
53
+ } from "./chunk-C265QIMJ.js";
54
+ import {
55
+ withFileLock
56
+ } from "./chunk-2W4DQQUU.js";
57
+ import {
58
+ sanitizeForTerminal
59
+ } from "./chunk-KLDMLWXT.js";
60
+ import {
61
+ evaluatePlan,
62
+ parseUsdToAtomic,
63
+ toMoney
64
+ } from "./chunk-MEZJ3I63.js";
65
+ import {
66
+ mask
67
+ } from "./chunk-7SLOTLO7.js";
68
+ import {
69
+ resolveContextSettings
70
+ } from "./chunk-DTEWAVNE.js";
71
+ import {
72
+ writeFileAtomic
73
+ } from "./chunk-7WEQQJLG.js";
74
+ import {
75
+ downloadsDir,
76
+ quotesDir
77
+ } from "./chunk-JTX3BUDK.js";
78
+ import {
79
+ assertPublicDestination
80
+ } from "./chunk-DIH2G3YG.js";
81
+ import {
82
+ fetchFailureToCliError,
83
+ httpRequest,
84
+ requestHeaderProblem
85
+ } from "./chunk-D6M3ZK66.js";
86
+ import {
87
+ isSameDeployment
88
+ } from "./chunk-CRG54LEB.js";
89
+ import {
90
+ external_exports
91
+ } from "./chunk-P6YQWIT2.js";
92
+ import {
93
+ CliError
94
+ } from "./chunk-DI4QAGRZ.js";
95
+
96
+ // src/commands/pay.ts
97
+ import { tmpdir } from "node:os";
98
+
99
+ // src/router/model-worker-context.ts
100
+ function isModelWorkerProcess(env = process.env) {
101
+ return env.TENJIN_MODEL_WORKER === "1";
102
+ }
103
+
104
+ // src/lib/bazaar.ts
105
+ import { readFile } from "node:fs/promises";
106
+ import { join } from "node:path";
107
+
108
+ // node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/dist/esm/chunk-SV2YHMOC.mjs
109
+ var BAZAAR = { key: "bazaar" };
110
+ var BRACKET_PARAM_REGEX = /\[([^\]]+)\]/;
111
+ var BRACKET_PARAM_REGEX_ALL = /\[([^\]]+)\]/g;
112
+ var COLON_PARAM_REGEX = /:([a-zA-Z_][a-zA-Z0-9_]*)/;
113
+ function isHTTPRequestContext(ctx) {
114
+ return ctx !== null && typeof ctx === "object" && "method" in ctx && "adapter" in ctx;
115
+ }
116
+ function normalizeWildcardPattern(pattern) {
117
+ if (!pattern.includes("*")) {
118
+ return pattern;
119
+ }
120
+ let counter = 0;
121
+ return pattern.split("/").map((seg) => {
122
+ if (seg === "*") {
123
+ counter++;
124
+ return `:var${counter}`;
125
+ }
126
+ return seg;
127
+ }).join("/");
128
+ }
129
+ function isWildcardOnlyPattern(pattern) {
130
+ const segments = pattern.split("/").filter((segment) => segment.length > 0);
131
+ return segments.length > 0 && segments.every((segment) => segment === "*");
132
+ }
133
+ function extractDynamicRouteInfo(routePattern, urlPath) {
134
+ const hasBracket = BRACKET_PARAM_REGEX.test(routePattern);
135
+ const hasColon = COLON_PARAM_REGEX.test(routePattern);
136
+ if (!hasBracket && !hasColon) {
137
+ return null;
138
+ }
139
+ const normalizedPattern = hasBracket ? routePattern.replace(BRACKET_PARAM_REGEX_ALL, ":$1") : routePattern;
140
+ const pathParams = extractPathParams(normalizedPattern, urlPath, false);
141
+ return { routeTemplate: normalizedPattern, pathParams };
142
+ }
143
+ function extractPathParams(routePattern, urlPath, isBracket) {
144
+ const paramNames = [];
145
+ const splitRegex = isBracket ? BRACKET_PARAM_REGEX : COLON_PARAM_REGEX;
146
+ const parts = routePattern.split(splitRegex);
147
+ const regexParts = [];
148
+ parts.forEach((part, i) => {
149
+ if (i % 2 === 0) {
150
+ regexParts.push(part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
151
+ } else {
152
+ paramNames.push(part);
153
+ regexParts.push("([^/]+)");
154
+ }
155
+ });
156
+ const regex = new RegExp(`^${regexParts.join("")}$`);
157
+ const match = urlPath.match(regex);
158
+ if (!match) return {};
159
+ const result = {};
160
+ paramNames.forEach((name, idx) => {
161
+ result[name] = match[idx + 1];
162
+ });
163
+ return result;
164
+ }
165
+ var bazaarResourceServerExtension = {
166
+ key: BAZAAR.key,
167
+ enrichDeclaration: (declaration, transportContext) => {
168
+ if (!isHTTPRequestContext(transportContext)) {
169
+ return declaration;
170
+ }
171
+ const extension = declaration;
172
+ if (extension.info?.input?.type === "mcp") {
173
+ return declaration;
174
+ }
175
+ const method = transportContext.method;
176
+ const existingInputProps = extension.schema?.properties?.input?.properties || {};
177
+ const updatedInputProps = {
178
+ ...existingInputProps,
179
+ method: {
180
+ type: "string",
181
+ enum: [method]
182
+ }
183
+ };
184
+ const enrichedResult = {
185
+ ...extension,
186
+ info: {
187
+ ...extension.info || {},
188
+ input: {
189
+ ...extension.info?.input || {},
190
+ method
191
+ }
192
+ },
193
+ schema: {
194
+ ...extension.schema || {},
195
+ properties: {
196
+ ...extension.schema?.properties || {},
197
+ input: {
198
+ ...extension.schema?.properties?.input || {},
199
+ properties: updatedInputProps,
200
+ required: [
201
+ ...extension.schema?.properties?.input?.required || [],
202
+ ...!(extension.schema?.properties?.input?.required || []).includes("method") ? ["method"] : []
203
+ ]
204
+ }
205
+ }
206
+ }
207
+ };
208
+ const rawRoutePattern = transportContext.routePattern;
209
+ if (rawRoutePattern && isWildcardOnlyPattern(rawRoutePattern)) {
210
+ return enrichedResult;
211
+ }
212
+ const routePattern = rawRoutePattern ? normalizeWildcardPattern(rawRoutePattern) : void 0;
213
+ const dynamicRoute = routePattern ? extractDynamicRouteInfo(routePattern, transportContext.adapter.getPath()) : null;
214
+ if (dynamicRoute) {
215
+ const inputSchemaProps = enrichedResult.schema?.properties?.input?.properties || {};
216
+ const hasPathParamsInSchema = "pathParams" in inputSchemaProps;
217
+ return {
218
+ ...enrichedResult,
219
+ routeTemplate: dynamicRoute.routeTemplate,
220
+ info: {
221
+ ...enrichedResult.info,
222
+ input: { ...enrichedResult.info.input, pathParams: dynamicRoute.pathParams }
223
+ },
224
+ ...!hasPathParamsInSchema ? {
225
+ schema: {
226
+ ...enrichedResult.schema,
227
+ properties: {
228
+ ...enrichedResult.schema?.properties,
229
+ input: {
230
+ ...enrichedResult.schema?.properties?.input,
231
+ properties: {
232
+ ...inputSchemaProps,
233
+ pathParams: { type: "object" }
234
+ }
235
+ }
236
+ }
237
+ }
238
+ } : {}
239
+ };
240
+ }
241
+ return enrichedResult;
242
+ }
243
+ };
244
+ var UNICODE_CONTROL_REGEX = new RegExp("\\p{Cc}", "u");
245
+ var VALID_QUERY_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "DELETE"]);
246
+ var VALID_BODY_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
247
+ var VALID_METHODS = /* @__PURE__ */ new Set([...VALID_QUERY_METHODS, ...VALID_BODY_METHODS]);
248
+ function withBazaar(client2) {
249
+ const existingExtensions = client2.extensions ?? {};
250
+ const extended = client2;
251
+ extended.extensions = {
252
+ ...existingExtensions,
253
+ bazaar: {
254
+ async listResources(params) {
255
+ let headers = {
256
+ "Content-Type": "application/json"
257
+ };
258
+ const authHeaders = await client2.createAuthHeaders("bazaar");
259
+ headers = { ...headers, ...authHeaders.headers };
260
+ const queryParams = new URLSearchParams();
261
+ if (params?.type !== void 0) {
262
+ queryParams.set("type", params.type);
263
+ }
264
+ if (params?.payTo !== void 0) {
265
+ queryParams.set("payTo", params.payTo);
266
+ }
267
+ if (params?.scheme !== void 0) {
268
+ queryParams.set("scheme", params.scheme);
269
+ }
270
+ if (params?.network !== void 0) {
271
+ queryParams.set("network", params.network);
272
+ }
273
+ if (params?.extensions !== void 0) {
274
+ queryParams.set("extensions", params.extensions);
275
+ }
276
+ if (params?.limit !== void 0) {
277
+ queryParams.set("limit", params.limit.toString());
278
+ }
279
+ if (params?.offset !== void 0) {
280
+ queryParams.set("offset", params.offset.toString());
281
+ }
282
+ const queryString = queryParams.toString();
283
+ const endpoint = `${client2.url}/discovery/resources${queryString ? `?${queryString}` : ""}`;
284
+ const response = await fetch(endpoint, {
285
+ method: "GET",
286
+ headers
287
+ });
288
+ if (!response.ok) {
289
+ const errorText = await response.text().catch(() => response.statusText);
290
+ throw new Error(
291
+ `Facilitator listDiscoveryResources failed (${response.status}): ${errorText}`
292
+ );
293
+ }
294
+ return await response.json();
295
+ },
296
+ async search(params) {
297
+ let headers = {
298
+ "Content-Type": "application/json"
299
+ };
300
+ const authHeaders = await client2.createAuthHeaders("bazaar");
301
+ headers = { ...headers, ...authHeaders.headers };
302
+ const queryParams = new URLSearchParams();
303
+ queryParams.set("query", params.query);
304
+ if (params.type !== void 0) {
305
+ queryParams.set("type", params.type);
306
+ }
307
+ if (params.payTo !== void 0) {
308
+ queryParams.set("payTo", params.payTo);
309
+ }
310
+ if (params.scheme !== void 0) {
311
+ queryParams.set("scheme", params.scheme);
312
+ }
313
+ if (params.network !== void 0) {
314
+ queryParams.set("network", params.network);
315
+ }
316
+ if (params.extensions !== void 0) {
317
+ queryParams.set("extensions", params.extensions);
318
+ }
319
+ if (params.limit !== void 0) {
320
+ queryParams.set("limit", params.limit.toString());
321
+ }
322
+ if (params.cursor !== void 0) {
323
+ queryParams.set("cursor", params.cursor);
324
+ }
325
+ const endpoint = `${client2.url}/discovery/search?${queryParams.toString()}`;
326
+ const response = await fetch(endpoint, {
327
+ method: "GET",
328
+ headers
329
+ });
330
+ if (!response.ok) {
331
+ const errorText = await response.text().catch(() => response.statusText);
332
+ throw new Error(
333
+ `Facilitator searchDiscoveryResources failed (${response.status}): ${errorText}`
334
+ );
335
+ }
336
+ return await response.json();
337
+ }
338
+ }
339
+ };
340
+ return extended;
341
+ }
342
+
343
+ // src/lib/bazaar.ts
344
+ var PAGE_LIMIT = 100;
345
+ var SEARCH_LIMIT = 20;
346
+ var MAX_PAGES = 5;
347
+ var MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
348
+ var ULTRAVIOLETA_ORIGIN = "https://facilitator.ultravioletadao.xyz";
349
+ function isUltravioleta(registry) {
350
+ return new URL(registry).origin === ULTRAVIOLETA_ORIGIN;
351
+ }
352
+ var paymentTerms = external_exports.custom((value) => {
353
+ const parsed = PaymentRequirementsV2Schema.safeParse(value);
354
+ return parsed.success && /^\d+$/.test(parsed.data.amount);
355
+ });
356
+ var ultravioletResource = external_exports.object({
357
+ url: external_exports.string().url(),
358
+ type: external_exports.string(),
359
+ x402Version: external_exports.number().int(),
360
+ description: external_exports.string().optional(),
361
+ accepts: external_exports.array(paymentTerms).max(100),
362
+ lastUpdated: external_exports.number().int().nonnegative().max(864e10)
363
+ });
364
+ var paginationSchema = external_exports.object({
365
+ limit: external_exports.number().int().positive().max(PAGE_LIMIT),
366
+ offset: external_exports.number().int().nonnegative(),
367
+ total: external_exports.number().int().nonnegative()
368
+ });
369
+ async function boundedJson(res) {
370
+ const reader = res.body?.getReader();
371
+ if (!reader) throw new Error("Registry response has no body");
372
+ const chunks = [];
373
+ let bytes = 0;
374
+ try {
375
+ for (; ; ) {
376
+ const next = await reader.read();
377
+ if (next.done) break;
378
+ bytes += next.value.byteLength;
379
+ if (bytes > MAX_RESPONSE_BYTES) throw new Error("Registry response exceeds size limit");
380
+ chunks.push(next.value);
381
+ }
382
+ } finally {
383
+ await reader.cancel();
384
+ }
385
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
386
+ }
387
+ async function ultravioletListings(registry, timeoutMs, query) {
388
+ const deadline = Date.now() + timeoutMs;
389
+ const items = [];
390
+ let offset = 0;
391
+ let incomplete;
392
+ for (let page = 0; page < MAX_PAGES; page++) {
393
+ const remaining = deadline - Date.now();
394
+ if (remaining <= 0) throw new Error("Registry lookup deadline exceeded");
395
+ const params = new URLSearchParams({
396
+ limit: String(PAGE_LIMIT),
397
+ offset: String(offset),
398
+ ...query !== void 0 ? { q: query } : {}
399
+ });
400
+ const res = await fetch(`${new URL(registry).origin}/discovery/resources?${params}`, {
401
+ headers: { accept: "application/json" },
402
+ signal: AbortSignal.timeout(remaining),
403
+ redirect: "error"
404
+ });
405
+ if (!res.ok) throw new Error(`listing ${registry} answered ${res.status}`);
406
+ const response = external_exports.object({ items: external_exports.array(external_exports.unknown()).max(PAGE_LIMIT), pagination: paginationSchema }).parse(await boundedJson(res));
407
+ const pagination = response.pagination;
408
+ if (pagination.offset !== offset || response.items.length > pagination.limit)
409
+ throw new Error("Invalid registry pagination");
410
+ for (const record of response.items) {
411
+ const parsed = ultravioletResource.safeParse(record);
412
+ if (!parsed.success) {
413
+ incomplete = "Registry search skipped malformed records";
414
+ continue;
415
+ }
416
+ const item = parsed.data;
417
+ items.push({
418
+ resource: item.url,
419
+ type: item.type,
420
+ x402Version: item.x402Version,
421
+ accepts: item.accepts,
422
+ lastUpdated: new Date(item.lastUpdated * 1e3).toISOString(),
423
+ ...item.description !== void 0 ? { description: item.description } : {}
424
+ });
425
+ }
426
+ const next = pagination.offset + response.items.length;
427
+ if (next >= pagination.total) return { items, ...incomplete ? { incomplete } : {} };
428
+ if (response.items.length === 0) break;
429
+ offset = next;
430
+ }
431
+ return { items, incomplete: "Registry search truncated at the pagination limit" };
432
+ }
433
+ function client(registry) {
434
+ return withBazaar(new HTTPFacilitatorClient({ url: registry }));
435
+ }
436
+ var DeadlineError = class extends Error {
437
+ };
438
+ async function withTimeout(work, timeoutMs, what) {
439
+ let timer;
440
+ try {
441
+ return await Promise.race([
442
+ work,
443
+ new Promise((_, reject) => {
444
+ timer = setTimeout(
445
+ () => reject(new DeadlineError(`${what} timed out after ${timeoutMs}ms`)),
446
+ timeoutMs
447
+ );
448
+ })
449
+ ]);
450
+ } finally {
451
+ clearTimeout(timer);
452
+ }
453
+ }
454
+ var LISTING_STORE_FILE = "bazaar-listings.json";
455
+ var LISTING_TTL_MS = 24 * 60 * 60 * 1e3;
456
+ function listingStorePath(dataDir) {
457
+ return join(dataDir, LISTING_STORE_FILE);
458
+ }
459
+ function isStoredListing(value) {
460
+ if (typeof value !== "object" || value === null) return false;
461
+ const listing = value;
462
+ return typeof listing.url === "string" && typeof listing.registry === "string" && typeof listing.fetchedAt === "string" && Array.isArray(listing.accepts);
463
+ }
464
+ async function loadListingStore(dataDir) {
465
+ try {
466
+ const raw = JSON.parse(await readFile(listingStorePath(dataDir), "utf8"));
467
+ const listings = raw?.listings;
468
+ return { listings: Array.isArray(listings) ? listings.filter(isStoredListing) : [] };
469
+ } catch {
470
+ return { listings: [] };
471
+ }
472
+ }
473
+ async function storedListingsFor(dataDir, url, now) {
474
+ const store = await loadListingStore(dataDir);
475
+ return store.listings.filter((l) => {
476
+ if (!sameResourceUrl(l.url, url)) return false;
477
+ const age = now() - Date.parse(l.fetchedAt);
478
+ return age >= 0 && age < LISTING_TTL_MS;
479
+ });
480
+ }
481
+ function sameResourceUrl(listed, requested) {
482
+ const a = resourceIdentity(listed);
483
+ return a !== null && a === resourceIdentity(requested);
484
+ }
485
+ function resourceIdentity(u) {
486
+ try {
487
+ const parsed = new URL(u);
488
+ const path = parsed.pathname.endsWith("/") ? parsed.pathname.slice(0, -1) : parsed.pathname;
489
+ return `${parsed.origin}${path}`;
490
+ } catch {
491
+ return null;
492
+ }
493
+ }
494
+ async function listingsFor(registry, url, payTo, timeoutMs) {
495
+ if (isUltravioleta(registry))
496
+ return ultravioletListings(registry, timeoutMs, resourceIdentity(url) ?? url);
497
+ const deadline = Date.now() + timeoutMs;
498
+ const params = new URLSearchParams({
499
+ urlSubstring: resourceIdentity(url) ?? url,
500
+ limit: String(SEARCH_LIMIT)
501
+ });
502
+ const res = await fetch(`${registry.replace(/\/+$/, "")}/discovery/search?${params.toString()}`, {
503
+ headers: { accept: "application/json" },
504
+ signal: AbortSignal.timeout(timeoutMs),
505
+ redirect: "error"
506
+ });
507
+ if (res.ok) {
508
+ const answer = await boundedJson(res);
509
+ if (Array.isArray(answer?.resources)) {
510
+ return {
511
+ items: answer.resources.slice(0, PAGE_LIMIT),
512
+ ...answer.resources.length > PAGE_LIMIT || answer.partialResults === true || answer.pagination?.cursor != null ? { incomplete: "Registry search results are truncated" } : {}
513
+ };
514
+ }
515
+ } else if (res.status !== 400 && res.status !== 404) {
516
+ throw new Error(`search on ${registry} answered ${res.status}`);
517
+ }
518
+ const bazaar = client(registry).extensions.bazaar;
519
+ const items = [];
520
+ let offset = 0;
521
+ for (let page = 0; page < MAX_PAGES; page++) {
522
+ const remaining = deadline - Date.now();
523
+ if (remaining <= 0) throw new Error("Registry lookup deadline exceeded");
524
+ const response = await withTimeout(
525
+ bazaar.listResources({ type: "http", payTo, limit: PAGE_LIMIT, offset }),
526
+ remaining,
527
+ registry
528
+ );
529
+ const pagination = paginationSchema.parse(response.pagination);
530
+ if (!Array.isArray(response.items) || response.items.length > PAGE_LIMIT || pagination.offset !== offset)
531
+ throw new Error("Invalid registry page");
532
+ items.push(...response.items);
533
+ offset = pagination.offset + response.items.length;
534
+ if (offset >= pagination.total) return { items };
535
+ if (response.items.length === 0) break;
536
+ }
537
+ return { items, incomplete: "Registry listing truncated at the pagination limit" };
538
+ }
539
+ async function verifyAgainstRegistries(registries, url, live, timeoutMs, opts = {}) {
540
+ const errors = [];
541
+ let mismatch;
542
+ if (opts.dataDir !== void 0) {
543
+ for (const listing of await storedListingsFor(opts.dataDir, url, opts.now ?? Date.now)) {
544
+ if (!registries.includes(listing.registry)) continue;
545
+ const detail = acceptsMismatch(listing.accepts, live);
546
+ if (detail === null) return { outcome: "verified", registry: listing.registry };
547
+ mismatch ??= { registry: listing.registry, detail };
548
+ }
549
+ }
550
+ const deadline = Date.now() + timeoutMs;
551
+ for (const registry of registries) {
552
+ try {
553
+ const remaining = deadline - Date.now();
554
+ if (remaining <= 0) throw new Error("Registry lookup deadline exceeded");
555
+ const listed = await withTimeout(
556
+ listingsFor(registry, url, live.payTo, remaining),
557
+ remaining,
558
+ `looking up this resource on ${registry}`
559
+ );
560
+ if (listed.incomplete) errors.push({ registry, message: listed.incomplete });
561
+ const matches = listed.items.filter(
562
+ (item) => item != null && item.type === "http" && typeof item.resource === "string" && Array.isArray(item.accepts) && sameResourceUrl(item.resource, url)
563
+ );
564
+ if (matches.length === 0) continue;
565
+ for (const item of matches) {
566
+ const detail = acceptsMismatch(item.accepts, live);
567
+ if (detail === null) return { outcome: "verified", registry };
568
+ mismatch ??= { registry, detail };
569
+ }
570
+ } catch (err) {
571
+ errors.push({ registry, message: err instanceof Error ? err.message : String(err) });
572
+ if (err instanceof DeadlineError || err instanceof Error && err.name === "TimeoutError") {
573
+ break;
574
+ }
575
+ }
576
+ }
577
+ if (mismatch !== void 0) return { outcome: "mismatch", ...mismatch };
578
+ if (errors.length > 0) {
579
+ return { outcome: "unavailable", errors };
580
+ }
581
+ return { outcome: "unlisted" };
582
+ }
583
+ function acceptsMismatch(advertised, live) {
584
+ let closest = "the listing advertises no payment terms";
585
+ for (const raw of advertised) {
586
+ const parsed = paymentTerms.safeParse(raw);
587
+ if (!parsed.success) {
588
+ closest = "malformed advertised payment terms";
589
+ continue;
590
+ }
591
+ const adv = parsed.data;
592
+ if (adv.scheme !== live.scheme) {
593
+ closest = `advertised scheme ${adv.scheme}, live ${live.scheme}`;
594
+ continue;
595
+ }
596
+ if (adv.network !== live.network) {
597
+ closest = `advertised network ${adv.network}, live ${live.network}`;
598
+ continue;
599
+ }
600
+ if (!sameAddress(adv.asset, live.asset)) {
601
+ closest = `advertised asset ${adv.asset}, live ${live.asset}`;
602
+ continue;
603
+ }
604
+ if (!sameAddress(adv.payTo, live.payTo)) {
605
+ closest = `advertised payTo ${adv.payTo}, live ${live.payTo}`;
606
+ continue;
607
+ }
608
+ let advertisedAmount;
609
+ let liveAmount;
610
+ try {
611
+ advertisedAmount = BigInt(adv.amount);
612
+ liveAmount = BigInt(live.amount);
613
+ } catch {
614
+ closest = "a non-integer amount in the listing or the live 402";
615
+ continue;
616
+ }
617
+ if (liveAmount > advertisedAmount) {
618
+ closest = `live amount ${live.amount} exceeds the advertised ${adv.amount}`;
619
+ continue;
620
+ }
621
+ return null;
622
+ }
623
+ return closest;
624
+ }
625
+ function sameAddress(a, b) {
626
+ try {
627
+ return getAddress(a) === getAddress(b);
628
+ } catch {
629
+ return false;
630
+ }
631
+ }
632
+
633
+ // src/lib/spend-gate.ts
634
+ async function gateSpend(input) {
635
+ const { authorizer, amountAtomic } = input;
636
+ const authorization = await authorizer.authorize({
637
+ mode: input.mode,
638
+ amountAtomic,
639
+ creator: input.creator,
640
+ ...input.maxPriceAtomic !== void 0 ? { maxPriceAtomic: input.maxPriceAtomic } : {},
641
+ ...input.requestKey !== void 0 ? { requestKey: input.requestKey } : {}
642
+ });
643
+ if (authorization.decision === "deny") {
644
+ throw new CliError("POLICY_REFUSED", authorization.message, {
645
+ fix: policyFix(authorization.reason, input.allowlistSubject),
646
+ details: { reason: authorization.reason, amountAtomic: amountAtomic.toString() }
647
+ });
648
+ }
649
+ const reservationId = authorization.reservationId;
650
+ if (authorization.decision === "confirm") {
651
+ let approved;
652
+ try {
653
+ approved = await confirmSpend(input);
654
+ } catch (err) {
655
+ await authorizer.release(reservationId);
656
+ throw err;
657
+ }
658
+ if (!approved) {
659
+ await authorizer.release(reservationId);
660
+ throw new CliError("POLICY_REFUSED", input.notConfirmedMessage, {
661
+ fix: "Obtain explicit user consent for this quoted payment, then re-run with --yes or confirm interactively. Manual pay is never an autonomous workaround for a router refusal.",
662
+ details: { reason: authorization.reason, amountAtomic: amountAtomic.toString() }
663
+ });
664
+ }
665
+ }
666
+ return reservationId;
667
+ }
668
+ function policyFix(reason, allowlistSubject) {
669
+ switch (reason) {
670
+ case "price_cap_exceeded":
671
+ return "Raise --max-price if this price is acceptable.";
672
+ case "not_allowlisted":
673
+ return `Add ${allowlistSubject} to allowlistCreators, or clear the allowlist.`;
674
+ case "session_budget_exceeded":
675
+ return "Today's automatic budget is spent; it comes back as the rolling 24 hours pass. Nothing more is paid without the user's yes.";
676
+ case "duplicate_in_flight":
677
+ return "Let the in-flight request finish and read its result; retrying the same request does not renew authorization.";
678
+ default:
679
+ return "This is over what this machine pays without asking, so it is not paid without the user's yes.";
680
+ }
681
+ }
682
+ async function confirmSpend(input) {
683
+ if (input.yes) return true;
684
+ const prompt = `Pay ${toMoney(input.amountAtomic.toString()).usd} USD to ${input.payeeLabel}? [y/N] `;
685
+ if (input.confirm !== void 0) return input.confirm(prompt);
686
+ if (!input.ctx.io.isTTY) return false;
687
+ if (!process.stdin.isTTY) return false;
688
+ return promptYesNo(prompt);
689
+ }
690
+
691
+ // src/lib/spend-quotes.ts
692
+ import { randomBytes } from "node:crypto";
693
+ import { constants } from "node:fs";
694
+ import { open, opendir, rm } from "node:fs/promises";
695
+ import { join as join2 } from "node:path";
696
+ var QUOTE_TTL_MS = 10 * 6e4;
697
+ var MAX_QUOTE_BYTES = 512 * 1024;
698
+ var QUOTE_ID = /^q_[A-Za-z0-9_-]{12}$/;
699
+ var Iso = external_exports.string().max(40);
700
+ var Digits = external_exports.string().regex(/^\d+$/);
701
+ var QuoteSchema = external_exports.strictObject({
702
+ version: external_exports.literal(1),
703
+ id: external_exports.string().regex(QUOTE_ID),
704
+ createdAt: Iso,
705
+ expiresAt: Iso,
706
+ /** What the payments buy, as the user is asked about it. */
707
+ what: external_exports.string().min(1).max(400),
708
+ /** The one sentence the agent repeats and the user answers. */
709
+ sentence: external_exports.string().min(1).max(800),
710
+ totalAtomic: Digits,
711
+ payments: external_exports.array(external_exports.strictObject({ amountAtomic: Digits, creator: external_exports.string().min(1).max(300) })).min(1).max(8),
712
+ /** The call this quote runs, exactly: the router's own shape. */
713
+ call: external_exports.unknown(),
714
+ /** It ran: nothing more is paid on it. */
715
+ usedAt: Iso.optional()
716
+ });
717
+ function isQuoteId(id) {
718
+ return QUOTE_ID.test(id);
719
+ }
720
+ function quotePath(dataDir, id) {
721
+ return join2(quotesDir(dataDir), `${id}.json`);
722
+ }
723
+ async function createQuote(dataDir, plan, now = Date.now) {
724
+ const at = now();
725
+ const quote = {
726
+ version: 1,
727
+ id: `q_${randomBytes(9).toString("base64url")}`,
728
+ createdAt: new Date(at).toISOString(),
729
+ expiresAt: new Date(at + QUOTE_TTL_MS).toISOString(),
730
+ what: plan.what.slice(0, 400),
731
+ sentence: plan.sentence.slice(0, 800),
732
+ totalAtomic: plan.payments.reduce((sum, payment) => sum + payment.amountAtomic, 0n).toString(),
733
+ payments: plan.payments.map((payment) => ({
734
+ amountAtomic: payment.amountAtomic.toString(),
735
+ creator: payment.creator
736
+ })),
737
+ call: plan.call
738
+ };
739
+ await writeQuote(dataDir, quote);
740
+ void pruneQuotes(dataDir, at);
741
+ return quote;
742
+ }
743
+ async function writeQuote(dataDir, quote) {
744
+ await writeFileAtomic(quotePath(dataDir, quote.id), JSON.stringify(quote), {
745
+ mode: 384,
746
+ dirMode: 448
747
+ });
748
+ }
749
+ async function readQuote(dataDir, id) {
750
+ if (!isQuoteId(id)) return null;
751
+ const file = await open(quotePath(dataDir, id), constants.O_RDONLY | constants.O_NOFOLLOW).catch(
752
+ () => void 0
753
+ );
754
+ if (file === void 0) return null;
755
+ try {
756
+ const stat = await file.stat();
757
+ if (!stat.isFile() || stat.size > MAX_QUOTE_BYTES) return null;
758
+ const parsed = QuoteSchema.safeParse(JSON.parse(await file.readFile("utf8")));
759
+ return parsed.success && parsed.data.id === id ? parsed.data : null;
760
+ } catch {
761
+ return null;
762
+ } finally {
763
+ await file.close().catch(() => void 0);
764
+ }
765
+ }
766
+ function quoteClosed(quote, now) {
767
+ if (quote.usedAt !== void 0) return "used";
768
+ return Date.parse(quote.expiresAt) <= now ? "expired" : null;
769
+ }
770
+ async function changeQuote(dataDir, id, change) {
771
+ if (!isQuoteId(id)) return { refused: "missing" };
772
+ return withFileLock(
773
+ `${quotePath(dataDir, id)}.lock`,
774
+ async () => {
775
+ const current = await readQuote(dataDir, id);
776
+ if (current === null) return { refused: "missing" };
777
+ const next = await change(current);
778
+ if (typeof next === "string") return { refused: next };
779
+ await writeQuote(dataDir, next);
780
+ return { quote: next };
781
+ },
782
+ { timeoutMs: 3e4 }
783
+ );
784
+ }
785
+ function useQuote(dataDir, id, now = Date.now) {
786
+ return changeQuote(dataDir, id, (quote) => {
787
+ const at = now();
788
+ return quoteClosed(quote, at) ?? { ...quote, usedAt: new Date(at).toISOString() };
789
+ });
790
+ }
791
+ function reopenQuote(dataDir, id, releaseClaims, now = Date.now) {
792
+ return changeQuote(dataDir, id, async (quote) => {
793
+ if (Date.parse(quote.expiresAt) <= now()) return "expired";
794
+ await releaseClaims();
795
+ const open2 = { ...quote };
796
+ delete open2.usedAt;
797
+ return open2;
798
+ });
799
+ }
800
+ async function pruneQuotes(dataDir, now) {
801
+ try {
802
+ const dir = quotesDir(dataDir);
803
+ for await (const entry of await opendir(dir)) {
804
+ const id = entry.name.replace(/\.json$/, "");
805
+ if (!entry.isFile() || !entry.name.endsWith(".json") || !isQuoteId(id)) continue;
806
+ const quote = await readQuote(dataDir, id);
807
+ const stale = quote !== null ? Date.parse(quote.expiresAt) < now : await open(join2(dir, entry.name), constants.O_RDONLY | constants.O_NOFOLLOW).then(async (file) => {
808
+ try {
809
+ return now - (await file.stat()).mtimeMs > 24 * 60 * 6e4;
810
+ } finally {
811
+ await file.close().catch(() => void 0);
812
+ }
813
+ }).catch(() => false);
814
+ if (stale) await rm(join2(dir, entry.name), { force: true }).catch(() => void 0);
815
+ }
816
+ } catch {
817
+ }
818
+ }
819
+
820
+ // src/lib/spend-plan.ts
821
+ var minted = /* @__PURE__ */ new WeakSet();
822
+ var spent = /* @__PURE__ */ new WeakSet();
823
+ var shortOfFunds = /* @__PURE__ */ new WeakSet();
824
+ function mint(amountAtomic, approved) {
825
+ const slot = Object.freeze({ amountAtomic, approved });
826
+ minted.add(slot);
827
+ return slot;
828
+ }
829
+ function spendSlot(slot, amountAtomic) {
830
+ if (typeof slot !== "object" || slot === null || !minted.has(slot)) {
831
+ return "unplanned";
832
+ }
833
+ const held = slot;
834
+ if (spent.has(held)) return "spent";
835
+ if (amountAtomic > held.amountAtomic) return "above_plan";
836
+ spent.add(held);
837
+ return null;
838
+ }
839
+ function markShortOfFunds(slot) {
840
+ if (slot !== void 0 && minted.has(slot) && spent.has(slot)) shortOfFunds.add(slot);
841
+ }
842
+ function wasShortOfFunds(slot) {
843
+ return shortOfFunds.has(slot);
844
+ }
845
+ async function admitPlan(payments, opts) {
846
+ const totalAtomic = payments.reduce((sum, payment) => sum + payment.amountAtomic, 0n);
847
+ const ledger = await readSpendSummary(opts.dataDir, {
848
+ ...opts.now !== void 0 ? { now: opts.now } : {}
849
+ });
850
+ const spentAtomic = ledger === null ? 0n : spentOf(ledger);
851
+ const evaluation = evaluatePlan(opts.policy, payments, spentAtomic);
852
+ if (evaluation.reason === "not_allowlisted") return { refused: { message: evaluation.message } };
853
+ const over = evaluation.decision !== "allow";
854
+ if (over) {
855
+ const budget = opts.policy.sessionBudgetAtomic;
856
+ return {
857
+ over: {
858
+ reason: evaluation.reason === "session_budget_exceeded" ? "session_budget_exceeded" : "above_auto_spend",
859
+ totalAtomic,
860
+ maxAutoSpendAtomic: opts.policy.maxAutoSpendAtomic,
861
+ budgetLeftAtomic: budget === null ? null : budget > spentAtomic ? budget - spentAtomic : 0n
862
+ }
863
+ };
864
+ }
865
+ return { admitted: payments.map((payment) => mint(payment.amountAtomic, false)) };
866
+ }
867
+ async function admitQuote(dataDir, id, opts = {}) {
868
+ const now = opts.now ?? Date.now;
869
+ const kept = await readQuote(dataDir, id);
870
+ if (kept === null) return { refused: "missing" };
871
+ const closed = quoteClosed(kept, now());
872
+ if (closed !== null) return { refused: closed };
873
+ const used = await useQuote(dataDir, id, now);
874
+ if ("refused" in used) return used;
875
+ return {
876
+ quote: used.quote,
877
+ admitted: used.quote.payments.map((payment) => mint(BigInt(payment.amountAtomic), true))
878
+ };
879
+ }
880
+ async function reopenShortQuote(dataDir, id, slots, opts) {
881
+ const signed = slots.filter((slot) => spent.has(slot));
882
+ if (signed.length === 0 || !signed.every((slot) => shortOfFunds.has(slot))) return false;
883
+ return "quote" in await reopenQuote(dataDir, id, opts.releaseClaims, opts.now ?? Date.now);
884
+ }
885
+
886
+ // src/commands/pay.ts
887
+ var PAYMENT_REQUIRED_HEADER = "PAYMENT-REQUIRED";
888
+ var PAYMENT_RESPONSE_HEADER = "PAYMENT-RESPONSE";
889
+ var PAYMENT_RESPONSE_HEADER_V1 = "X-PAYMENT-RESPONSE";
890
+ var BODY_PREVIEW_CHARS = 1200;
891
+ var LOW_FUNDS_MESSAGE = "The wallet does not hold enough USDC for this payment.";
892
+ var LOW_FUNDS_TAIL = "The signed authorization stays counted until it expires and is recorded as transmitted exposure. Do not simply retry: each attempt signs a fresh authorization.";
893
+ function isLowFundsRefusal(err) {
894
+ return err.code === "PAYMENT_FAILED" && err.message === LOW_FUNDS_MESSAGE;
895
+ }
896
+ async function runPay(args, ctx, deps = {}) {
897
+ if (isModelWorkerProcess())
898
+ throw new CliError(
899
+ "REFUSED",
900
+ "Nested Tenjin payments are unavailable inside a model worker; use the native tools."
901
+ );
902
+ const warnings = [];
903
+ try {
904
+ return await executePay(args, ctx, deps, warnings);
905
+ } catch (err) {
906
+ if (err instanceof CliError && warnings.length > 0) {
907
+ throw new CliError(err.code, err.message, {
908
+ exitCode: err.exitCode,
909
+ ...err.fix !== void 0 ? { fix: err.fix } : {},
910
+ details: {
911
+ ...typeof err.details === "object" && err.details !== null ? err.details : {},
912
+ warnings
913
+ },
914
+ cause: err
915
+ });
916
+ }
917
+ throw err;
918
+ }
919
+ }
920
+ function checkPaymentActive(signal) {
921
+ if (signal?.aborted)
922
+ throw new CliError("REFUSED", "The request was stopped before payment was sent.", {
923
+ details: { reason: "cancelled" }
924
+ });
925
+ }
926
+ async function executePay(args, ctx, deps, warnings) {
927
+ const { signal } = deps;
928
+ checkPaymentActive(signal);
929
+ const router = args.execution === "router" || args.terms !== void 0;
930
+ if (router) {
931
+ const terms = args.terms;
932
+ if (args.ignoreWarnings === true || !terms || typeof terms.maxAmountAtomic !== "string" || !/^\d+$/.test(terms.maxAmountAtomic) || [terms.network, terms.asset, terms.payTo, terms.source].some(
933
+ (v) => v !== void 0 && (typeof v !== "string" || v.trim().length === 0)
934
+ )) {
935
+ throw new CliError(
936
+ "REFUSED",
937
+ "Router payments require valid advertised terms and cannot acknowledge registry warnings.",
938
+ { details: { reason: "invalid_router_terms" } }
939
+ );
940
+ }
941
+ if (args.admit === void 0) {
942
+ throw new CliError(
943
+ "REFUSED",
944
+ "A router payment is signed only against its call's spend plan, and this one has none; nothing was sent.",
945
+ { details: { reason: "unplanned" } }
946
+ );
947
+ }
948
+ }
949
+ const settings = await resolveContextSettings(ctx);
950
+ const maxPriceAtomic = args.maxPrice !== void 0 ? BigInt(parseUsdToAtomic(args.maxPrice)) : void 0;
951
+ const openedSigner = {};
952
+ const url = args.url.trim();
953
+ const lane = resolveLane(url, settings);
954
+ if (lane === "bazaar") await assertPublicDestination(url, deps.destination ?? {});
955
+ const method = resolveMethod(args);
956
+ const operator = operatorHeaders(args.header, args.dataRaw !== void 0);
957
+ const body = resolveBody(args, operator);
958
+ const headers = {
959
+ ...operator,
960
+ ...specHeaders(args.specHeaders),
961
+ ...callerHeaders(args.headers)
962
+ };
963
+ const legTimeoutMs = args.timeoutMs ?? ctx.flags.timeout;
964
+ const fetchOpts = {
965
+ timeoutMs: legTimeoutMs,
966
+ // Both legs: the probe's 402 is money-path input, and the paid retry
967
+ // carries a signed header (which pins redirects on its own; this pins the
968
+ // probe too, so the challenge always comes from the URL that was gated).
969
+ blockRedirects: true,
970
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {},
971
+ ...body,
972
+ ...Object.keys(headers).length > 0 ? { headers } : {},
973
+ // A call can buy a file (a sound, an image): its bytes are kept whole,
974
+ // never decoded as text. The router's tool saves them itself; a direct
975
+ // pay writes them to a file and hands back its path (`keepBody`).
976
+ binaryBody: true,
977
+ ...args.maxBytes !== void 0 ? { maxBinaryBytes: args.maxBytes } : {},
978
+ method
979
+ };
980
+ const fetchImpl = deps.fetchImpl ?? fetch;
981
+ const prepaymentFetchOpts = signal === void 0 ? fetchOpts : {
982
+ ...fetchOpts,
983
+ fetchImpl: ((input, init) => {
984
+ checkPaymentActive(signal);
985
+ return fetchImpl(input, {
986
+ ...init,
987
+ signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal
988
+ });
989
+ })
990
+ };
991
+ checkPaymentActive(signal);
992
+ const probe = await httpRequest(url, prepaymentFetchOpts);
993
+ checkPaymentActive(signal);
994
+ if (!probe.ok) {
995
+ throw fetchFailureToCliError(probe, {
996
+ fix: `Nothing was sent and nothing was paid. ${legFix(probe)}`
997
+ });
998
+ }
999
+ const keep = async (res) => router ? void 0 : args.quote === true ? describeBody(res) : keepBody(ctx.dataDir, url, res);
1000
+ if (probe.status >= 200 && probe.status < 300) {
1001
+ const caveat = assertUsableResult(args.resultSchema, probe.text, probe.status, "free");
1002
+ args.onPaidLeg?.({ status: probe.status, header: probe.header });
1003
+ const saved = await keep(probe);
1004
+ return deliver(url, lane, probe, {
1005
+ paid: false,
1006
+ ...caveat !== void 0 ? { caveat } : {},
1007
+ ...saved !== void 0 ? { saved } : {},
1008
+ printBody: args.printBody === true
1009
+ });
1010
+ }
1011
+ if (probe.status !== 402) {
1012
+ const said2 = providerMessage(probe.json);
1013
+ throw new CliError(
1014
+ "API_UNREACHABLE",
1015
+ `${url} answered ${probe.status}${said2 === null ? "." : `: ${said2}`}`,
1016
+ {
1017
+ fix: probe.status === 404 ? "Nothing was paid. The same request will answer 404 again." : "Check the URL and the endpoint status, then retry.",
1018
+ details: { status: probe.status, body: probe.json, ...providerError(probe.text) }
1019
+ }
1020
+ );
1021
+ }
1022
+ if (router && BigInt(args.terms.maxAmountAtomic) === 0n && args.terms.payTo === void 0) {
1023
+ throw new CliError(
1024
+ "REGISTRY_MISMATCH",
1025
+ "This lookup was advertised as free, but the endpoint requires payment.",
1026
+ {
1027
+ fix: "Nothing was signed or paid. Use your usual tools for this lookup.",
1028
+ details: { status: 402, advertised: args.terms }
1029
+ }
1030
+ );
1031
+ }
1032
+ const paymentRequired = decodeChallenge(probe, url);
1033
+ const payer = createPayerClient(() => signerOrThrow(openedSigner));
1034
+ const requirement = selectRequirement(payer.core, paymentRequired, args.terms);
1035
+ if (args.quote === true) {
1036
+ return deliverQuote(url, lane, probe, paymentRequired, requirement, args.printBody === true);
1037
+ }
1038
+ const signIn = router ? void 0 : signInOnlyChallenge(paymentRequired);
1039
+ if (signIn !== void 0) {
1040
+ if (method !== "GET") {
1041
+ throw new CliError(
1042
+ "REFUSED",
1043
+ `${new URL(url).host} asks the wallet that paid it to sign in, and nothing was signed: a sign-in answers only a GET, and this is a ${method}.`,
1044
+ {
1045
+ fix: "Nothing was signed or paid. Fetch the result with a plain GET (no -X, no body).",
1046
+ details: { status: 402, reason: "sign_in_method", signIn: true }
1047
+ }
1048
+ );
1049
+ }
1050
+ const provider2 = resolveWalletProvider(
1051
+ ctx,
1052
+ deps.provider !== void 0 ? { provider: deps.provider } : {}
1053
+ );
1054
+ const answer = await answerSignInChallenge(paymentRequired, signIn, url, {
1055
+ address: async () => (await describeOpenable(provider2)).address,
1056
+ paidHost: (host2, address) => walletPaidHost(ctx.dataDir, host2, address),
1057
+ signer: () => openWallet(provider2)
1058
+ });
1059
+ if ("refused" in answer) {
1060
+ throw new CliError(
1061
+ "REFUSED",
1062
+ `${new URL(url).host} asks the wallet that paid it to sign in, and nothing was signed: ${answer.reason}.`,
1063
+ {
1064
+ fix: answer.refused === "unpaid" ? "Nothing was signed or paid. This seller returns the result only to the wallet that paid for it; sign in from that wallet." : answer.refused === "payer_unknown" ? "Nothing was signed or paid. The payment was recorded before this CLI kept the wallet that paid, so it cannot show this wallet paid; `tenjin payments` lists it." : "Nothing was signed or paid.",
1065
+ details: { status: 402, reason: `sign_in_${answer.refused}`, signIn: true }
1066
+ }
1067
+ );
1068
+ }
1069
+ const signed = await httpRequest(url, {
1070
+ ...prepaymentFetchOpts,
1071
+ headers: { ...headers, ...answer.headers }
1072
+ });
1073
+ checkPaymentActive(signal);
1074
+ if (!signed.ok) {
1075
+ throw fetchFailureToCliError(signed, {
1076
+ fix: `Nothing was paid: the request carried a sign-in, not a payment. ${legFix(signed)}`
1077
+ });
1078
+ }
1079
+ if (signed.status >= 200 && signed.status < 300) {
1080
+ const caveat = assertUsableResult(args.resultSchema, signed.text, signed.status, "signed-in");
1081
+ const saved = await keep(signed);
1082
+ return deliver(url, lane, signed, {
1083
+ paid: false,
1084
+ signedIn: true,
1085
+ ...caveat !== void 0 ? { caveat } : {},
1086
+ ...saved !== void 0 ? { saved } : {},
1087
+ printBody: args.printBody === true
1088
+ });
1089
+ }
1090
+ const said2 = providerMessage(signed.json);
1091
+ throw new CliError(
1092
+ "API_UNREACHABLE",
1093
+ signed.status === 402 ? `${new URL(url).host} did not accept this wallet's sign-in.` : `${url} answered ${signed.status} to this wallet's sign-in${said2 === null ? "." : `: ${said2}`}`,
1094
+ {
1095
+ fix: "Nothing was paid: the request carried a sign-in, not a payment. This seller returns the result only to the wallet that paid for it.",
1096
+ details: { status: signed.status, body: signed.json, ...providerError(signed.text) }
1097
+ }
1098
+ );
1099
+ }
1100
+ if (requirement === void 0) {
1101
+ throw noMatchingEntry(paymentRequired, args.terms);
1102
+ }
1103
+ const firstSeenAmount = BigInt(requirement.amount);
1104
+ const host = new URL(url).host;
1105
+ let registry;
1106
+ let termsLabel;
1107
+ if (args.terms !== void 0) termsLabel = assertWithinTerms(args.terms, requirement);
1108
+ else if (lane === "bazaar" && paymentRequired.extensions?.[SIGN_IN_WITH_X] === void 0) {
1109
+ registry = await checkRegistry(
1110
+ settings,
1111
+ url,
1112
+ requirement,
1113
+ ctx,
1114
+ args.ignoreWarnings === true,
1115
+ warnings
1116
+ );
1117
+ }
1118
+ const entitlement = paymentRequired.extensions?.[SIGN_IN_WITH_X] !== void 0;
1119
+ checkPaymentActive(signal);
1120
+ let slot = router && !entitlement ? await args.admit(firstSeenAmount) : void 0;
1121
+ checkPaymentActive(signal);
1122
+ const provider = resolveWalletProvider(
1123
+ ctx,
1124
+ deps.provider !== void 0 ? { provider: deps.provider } : {}
1125
+ );
1126
+ const signer = await openWallet(provider);
1127
+ openedSigner.current = signer;
1128
+ checkPaymentActive(signal);
1129
+ let effectiveChallenge = paymentRequired;
1130
+ let effectiveRequirement = requirement;
1131
+ if (entitlement) {
1132
+ const siwxHeader = await buildSiwxHeader(signer, {
1133
+ baseUrl: new URL(url).origin,
1134
+ chainId: requirement.network
1135
+ });
1136
+ const recheck = await httpRequest(url, {
1137
+ ...prepaymentFetchOpts,
1138
+ headers: { ...headers, [SIWX_HEADER]: siwxHeader }
1139
+ });
1140
+ checkPaymentActive(signal);
1141
+ if (!recheck.ok) throw fetchFailureToCliError(recheck);
1142
+ if (recheck.status >= 200 && recheck.status < 300) {
1143
+ const caveat = assertUsableResult(
1144
+ args.resultSchema,
1145
+ recheck.text,
1146
+ recheck.status,
1147
+ "entitled"
1148
+ );
1149
+ args.onPaidLeg?.({ status: recheck.status, header: recheck.header });
1150
+ const saved = await keep(recheck);
1151
+ return deliver(url, lane, recheck, {
1152
+ paid: false,
1153
+ entitled: true,
1154
+ ...caveat !== void 0 ? { caveat } : {},
1155
+ ...saved !== void 0 ? { saved } : {},
1156
+ printBody: args.printBody === true
1157
+ });
1158
+ }
1159
+ if (recheck.status !== 402) {
1160
+ throw new CliError(
1161
+ "API_UNREACHABLE",
1162
+ `${url} answered ${recheck.status} on the entitlement re-check.`,
1163
+ {
1164
+ fix: "Retry; if it persists the endpoint looks misconfigured.",
1165
+ details: { status: recheck.status, body: recheck.json, ...providerError(recheck.text) }
1166
+ }
1167
+ );
1168
+ }
1169
+ effectiveChallenge = decodeChallenge(recheck, url);
1170
+ const fresh = selectRequirement(payer.core, effectiveChallenge, args.terms);
1171
+ if (fresh === void 0) {
1172
+ throw noMatchingEntry(effectiveChallenge, args.terms);
1173
+ }
1174
+ if (BigInt(fresh.amount) > firstSeenAmount) {
1175
+ throw new CliError("PAYMENT_FAILED", "The price increased before signing; refusing to pay.", {
1176
+ fix: "Re-run `tenjin pay` to review the new price, and set --max-price to cap it.",
1177
+ details: {
1178
+ firstSeenAtomic: firstSeenAmount.toString(),
1179
+ currentAtomic: fresh.amount
1180
+ }
1181
+ });
1182
+ }
1183
+ if (fresh.scheme !== requirement.scheme || fresh.network !== requirement.network || fresh.asset.toLowerCase() !== requirement.asset.toLowerCase() || fresh.payTo.toLowerCase() !== requirement.payTo.toLowerCase() || JSON.stringify(fresh.extra) !== JSON.stringify(requirement.extra)) {
1184
+ throw new CliError(
1185
+ "PAYMENT_FAILED",
1186
+ "The payment terms changed before signing; refusing to pay.",
1187
+ { fix: "Review a fresh challenge before paying again." }
1188
+ );
1189
+ }
1190
+ effectiveRequirement = fresh;
1191
+ if (args.terms !== void 0) termsLabel = assertWithinTerms(args.terms, fresh);
1192
+ else if (lane === "bazaar") {
1193
+ registry = await checkRegistry(
1194
+ settings,
1195
+ url,
1196
+ fresh,
1197
+ ctx,
1198
+ args.ignoreWarnings === true,
1199
+ warnings
1200
+ );
1201
+ }
1202
+ }
1203
+ const amountAtomic = BigInt(effectiveRequirement.amount);
1204
+ checkPaymentActive(signal);
1205
+ if (router && entitlement) slot = await args.admit(amountAtomic);
1206
+ if (router) {
1207
+ const refusal2 = spendSlot(slot, amountAtomic);
1208
+ if (refusal2 === "above_plan") {
1209
+ throw new CliError(
1210
+ "PAYMENT_FAILED",
1211
+ `The live price ($${toMoney(amountAtomic.toString()).usd}) is above the $${toMoney(slot.amountAtomic.toString()).usd} this call planned for it, so nothing was signed.`,
1212
+ {
1213
+ fix: "Call again for a fresh plan at the new price.",
1214
+ details: {
1215
+ reason: "above_plan",
1216
+ plannedAtomic: slot.amountAtomic.toString(),
1217
+ live: { amount: amountAtomic.toString() }
1218
+ }
1219
+ }
1220
+ );
1221
+ }
1222
+ if (refusal2 !== null) {
1223
+ throw new CliError(
1224
+ "REFUSED",
1225
+ "A router payment is signed only against an unspent slot of its call's spend plan; nothing was signed.",
1226
+ { details: { reason: refusal2 } }
1227
+ );
1228
+ }
1229
+ }
1230
+ const approved = slot?.approved === true;
1231
+ const authorizer = resolveSpendAuthorizer(
1232
+ ctx,
1233
+ settings.policy,
1234
+ deps.authorizer !== void 0 ? { authorizer: deps.authorizer } : {}
1235
+ );
1236
+ const verifiedVia = registry ?? termsLabel;
1237
+ const via = verifiedVia !== void 0 ? ` (${sanitizeForTerminal(verifiedVia)})` : "";
1238
+ const mode = router && !approved ? "automatic" : "manual";
1239
+ checkPaymentActive(signal);
1240
+ const reservationId = await gateSpend({
1241
+ mode,
1242
+ ctx,
1243
+ authorizer,
1244
+ amountAtomic,
1245
+ creator: host,
1246
+ ...maxPriceAtomic !== void 0 ? { maxPriceAtomic } : {},
1247
+ ...args.requestKey !== void 0 ? { requestKey: args.requestKey } : {},
1248
+ yes: args.yes === true || approved,
1249
+ ...deps.confirm !== void 0 ? { confirm: deps.confirm } : {},
1250
+ payeeLabel: `${sanitizeForTerminal(url)}${via}; recipient ${sanitizeForTerminal(effectiveRequirement.payTo)}, ${sanitizeForTerminal(effectiveRequirement.network)} / ${sanitizeForTerminal(effectiveRequirement.asset)}`,
1251
+ allowlistSubject: "this host",
1252
+ notConfirmedMessage: "Payment not confirmed."
1253
+ });
1254
+ let payment;
1255
+ try {
1256
+ checkPaymentActive(signal);
1257
+ payment = await buildExactPayment(effectiveChallenge, signer, effectiveRequirement);
1258
+ } catch (err) {
1259
+ await authorizer.release(reservationId);
1260
+ throw err;
1261
+ }
1262
+ const paidTimeoutMs = paidLegTimeoutMs(
1263
+ effectiveRequirement,
1264
+ Math.max(legTimeoutMs, ctx.flags.timeout)
1265
+ );
1266
+ let transmitted = false;
1267
+ const paid = await httpRequest(url, {
1268
+ ...fetchOpts,
1269
+ timeoutMs: paidTimeoutMs,
1270
+ headers: { ...headers, ...payment.headers },
1271
+ ...signal !== void 0 ? {
1272
+ fetchImpl: ((input, init) => {
1273
+ checkPaymentActive(signal);
1274
+ transmitted = true;
1275
+ return fetchImpl(input, init);
1276
+ })
1277
+ } : {}
1278
+ });
1279
+ if (!transmitted && signal?.aborted) {
1280
+ await authorizer.release(reservationId);
1281
+ checkPaymentActive(signal);
1282
+ }
1283
+ await authorizer.commit(reservationId, payment.amountAtomic, {
1284
+ mode,
1285
+ ...payment.authorization !== void 0 ? { nonce: payment.authorization.nonce } : {}
1286
+ });
1287
+ notePaymentSent();
1288
+ const recordDirect = async (entry) => {
1289
+ if (router) return;
1290
+ await appendPaidRecord(ctx.dataDir, {
1291
+ version: 1,
1292
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
1293
+ capabilityId: "pay",
1294
+ provider: host,
1295
+ url,
1296
+ sent: recordedSent(args.data ?? args.dataRaw ?? ""),
1297
+ amountAtomic: payment.amountAtomic.toString(),
1298
+ ...entry.txHash !== void 0 ? { txHash: entry.txHash } : {},
1299
+ ...entry.reportedTxHash !== void 0 ? { reportedTxHash: entry.reportedTxHash } : {},
1300
+ settlement: entry.settlement,
1301
+ savedFiles: entry.savedFiles ?? [],
1302
+ payer: payment.payer,
1303
+ ...payment.authorization !== void 0 ? { authorization: payment.authorization } : {}
1304
+ });
1305
+ };
1306
+ const failedSettlement = async (header) => {
1307
+ const reportedTxHash2 = header !== void 0 ? settledTx({ header }) : void 0;
1308
+ const tx = reportedTxHash2 !== void 0 ? { reportedTxHash: reportedTxHash2 } : {};
1309
+ const settlement2 = await chargedOnChain(payment.authorization, settings.rpcUrl, {
1310
+ ...(deps.chainFetch ?? deps.fetchImpl) !== void 0 ? { fetchImpl: deps.chainFetch ?? deps.fetchImpl } : {}
1311
+ });
1312
+ if (settlement2 === "settled") {
1313
+ return {
1314
+ settlement: settlement2,
1315
+ ...tx,
1316
+ charged: "The chain shows the authorization was used, so it was charged."
1317
+ };
1318
+ }
1319
+ return reportedTxHash2 !== void 0 ? {
1320
+ settlement: settlement2,
1321
+ ...tx,
1322
+ reported: `The seller reports a charge (tx ${reportedTxHash2}), but the chain does not show it yet. Check \`tenjin payments\` before paying again.`
1323
+ } : { settlement: settlement2 };
1324
+ };
1325
+ if (paid.ok || paid.header !== void 0) {
1326
+ args.onPaidLeg?.({
1327
+ ...paid.status !== void 0 ? { status: paid.status } : {},
1328
+ ...paid.header !== void 0 ? { header: paid.header } : {}
1329
+ });
1330
+ }
1331
+ if (!paid.ok) {
1332
+ const statusUrl = paid.kind === "timeout" ? statusUrlOf(paid, url) : null;
1333
+ const { settlement: settlement2, reportedTxHash: reportedTxHash2, charged: charged2, reported: reported2 } = await failedSettlement(paid.header);
1334
+ await recordDirect({ settlement: settlement2, ...reportedTxHash2 !== void 0 ? { reportedTxHash: reportedTxHash2 } : {} });
1335
+ const known2 = charged2 ?? reported2;
1336
+ if (statusUrl !== null) {
1337
+ throw new CliError(
1338
+ "NETWORK_ERROR",
1339
+ `The seller is still working on this: no result within ${Math.round(paidTimeoutMs / 1e3)} s, and it named a status URL to check: ${statusUrl}`,
1340
+ {
1341
+ fix: (known2 !== void 0 ? `${known2} ` : "The authorization was transmitted and settlement is unknown until the job ends; it is recorded as transmitted exposure. ") + "Do not pay again: check the status URL for the result.",
1342
+ details: {
1343
+ statusUrl,
1344
+ amountAtomic: payment.amountAtomic.toString(),
1345
+ settlement: settlement2,
1346
+ ...reportedTxHash2 !== void 0 ? { reportedTxHash: reportedTxHash2 } : {},
1347
+ payer: payment.payer,
1348
+ ...payment.authorization !== void 0 ? { authorization: payment.authorization } : {}
1349
+ }
1350
+ }
1351
+ );
1352
+ }
1353
+ throw fetchFailureToCliError(paid, {
1354
+ fix: (known2 !== void 0 ? `The authorization was transmitted. ${known2} ` : "The authorization was transmitted and settlement is unknown; it is recorded as transmitted exposure. ") + `Do not simply retry: each attempt signs a fresh authorization. ${legFix(paid)}`,
1355
+ details: {
1356
+ amountAtomic: payment.amountAtomic.toString(),
1357
+ settlement: settlement2,
1358
+ ...reportedTxHash2 !== void 0 ? { reportedTxHash: reportedTxHash2 } : {},
1359
+ payer: payment.payer,
1360
+ ...payment.authorization !== void 0 ? { authorization: payment.authorization } : {}
1361
+ }
1362
+ });
1363
+ }
1364
+ if (paid.status >= 200 && paid.status < 300) {
1365
+ let caveat;
1366
+ if (args.resultSchema !== void 0) {
1367
+ const check = validateResultBody(args.resultSchema, paid.text);
1368
+ if (check.unvalidated === true) caveat = unvalidatedCaveat(check);
1369
+ else if (!check.valid) caveat = failedRuleCaveat(check);
1370
+ }
1371
+ const saved = await keep(paid);
1372
+ const txHash = settlementTx(paid);
1373
+ await recordDirect({
1374
+ settlement: txHash !== void 0 ? "settled" : "unknown",
1375
+ ...txHash !== void 0 ? { txHash } : {},
1376
+ savedFiles: saved?.savedTo !== void 0 ? [saved.savedTo] : []
1377
+ });
1378
+ return deliver(url, lane, paid, {
1379
+ paid: true,
1380
+ warnings,
1381
+ amountAtomic: payment.amountAtomic,
1382
+ requirement: effectiveRequirement,
1383
+ payer: payment.payer,
1384
+ ...payment.authorization !== void 0 ? { authorization: payment.authorization } : {},
1385
+ ...registry !== void 0 ? { registry } : {},
1386
+ ...caveat !== void 0 ? { caveat } : {},
1387
+ ...saved !== void 0 ? { saved } : {},
1388
+ printBody: args.printBody === true
1389
+ });
1390
+ }
1391
+ const { settlement, reportedTxHash, charged, reported } = await failedSettlement(paid.header);
1392
+ await recordDirect({ settlement, ...reportedTxHash !== void 0 ? { reportedTxHash } : {} });
1393
+ const known = charged ?? reported;
1394
+ const refusal = settlementRefusal(paid);
1395
+ const sellerShort = paymentShortOfFunds(paid);
1396
+ const paymentError = paymentRequiredError(payer.http, paid);
1397
+ const lowFunds = sellerShort && known === void 0;
1398
+ if (lowFunds) markShortOfFunds(slot);
1399
+ const said = sellerShort ? known !== void 0 ? "The seller said the wallet does not hold enough USDC for this payment." : LOW_FUNDS_MESSAGE : refusal !== void 0 ? `The endpoint did not settle the payment${refusal.reason !== void 0 ? `: ${refusal.reason.replace(/\.+$/, "")}` : ""}.` : paid.status === 402 ? `Payment was not accepted by the endpoint${paymentError !== void 0 ? `: ${paymentError.replace(/\.+$/, "")}` : ""}.` : known !== void 0 ? `The endpoint answered ${paid.status} on the paid request.` : `The endpoint answered ${paid.status} on the paid request; whether it settled is unknown.`;
1400
+ throw new CliError(
1401
+ "PAYMENT_FAILED",
1402
+ charged !== void 0 ? `The payment was charged, and the endpoint answered ${paid.status} with no result. ${charged}` : reported !== void 0 ? `The endpoint answered ${paid.status} with no result. ${reported}` : said,
1403
+ {
1404
+ fix: charged !== void 0 ? "The payment was charged and is recorded as settled. Do not simply retry: each attempt pays again. Read the seller's reason in the details, fix the request, and quote again." : reported !== void 0 ? "The payment is recorded as transmitted exposure until the chain shows it taken. Do not simply retry: each attempt signs a fresh authorization. Read the seller's reason in the details, fix the request, and quote again." : lowFunds ? `Ask the person once to add funds; on yes, run \`tenjin fund\`. ${LOW_FUNDS_TAIL}` : refusal !== void 0 ? "The seller reported that nothing settled, but the signed authorization stays valid until it expires, so it is recorded as transmitted exposure. Do not simply retry: each attempt signs a fresh authorization. Use a different service for this." : "The signed payment already left and is recorded as transmitted exposure; the endpoint may still settle it. Do not simply retry: each attempt signs a fresh authorization. Verify the endpoint (and this listing, if Bazaar) before paying again.",
1405
+ // The amount rides on the failure so a caller can report what is at risk
1406
+ // rather than a zero.
1407
+ details: {
1408
+ status: paid.status,
1409
+ body: paid.json,
1410
+ ...providerError(paid.text),
1411
+ ...known !== void 0 ? { sellerReason: said } : {},
1412
+ ...paymentError !== void 0 ? { paymentError } : {},
1413
+ ...refusal?.reason !== void 0 ? { settlementError: refusal.reason } : {},
1414
+ amountAtomic: payment.amountAtomic.toString(),
1415
+ settlement,
1416
+ ...reportedTxHash !== void 0 ? { reportedTxHash } : {},
1417
+ payer: payment.payer,
1418
+ ...payment.authorization !== void 0 ? { authorization: payment.authorization } : {}
1419
+ }
1420
+ }
1421
+ );
1422
+ }
1423
+ var MAX_PAID_LEG_TIMEOUT_MS = 12e4;
1424
+ function paidLegTimeoutMs(requirement, cliTimeoutMs) {
1425
+ const advertised = requirement.maxTimeoutSeconds;
1426
+ if (typeof advertised !== "number" || !Number.isFinite(advertised) || advertised <= 0) {
1427
+ return cliTimeoutMs;
1428
+ }
1429
+ return Math.max(cliTimeoutMs, Math.min(advertised * 1e3, MAX_PAID_LEG_TIMEOUT_MS));
1430
+ }
1431
+ async function quoteRouterCall(args, ctx, deps = {}) {
1432
+ const settings = await resolveContextSettings(ctx);
1433
+ const url = args.url.trim();
1434
+ if (resolveLane(url, settings) === "bazaar") {
1435
+ await assertPublicDestination(url, deps.destination ?? {});
1436
+ }
1437
+ const headers = { ...specHeaders(args.specHeaders), ...callerHeaders(args.headers) };
1438
+ const probe = await httpRequest(url, {
1439
+ timeoutMs: args.timeoutMs ?? ctx.flags.timeout,
1440
+ blockRedirects: true,
1441
+ binaryBody: true,
1442
+ method: resolveMethod(args),
1443
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {},
1444
+ ...args.rawBody !== void 0 ? { rawBody: args.rawBody } : {},
1445
+ ...Object.keys(headers).length > 0 ? { headers } : {}
1446
+ });
1447
+ if (!probe.ok) {
1448
+ throw fetchFailureToCliError(probe, {
1449
+ fix: `Nothing was sent and nothing was paid. ${legFix(probe)}`
1450
+ });
1451
+ }
1452
+ if (probe.status >= 200 && probe.status < 300) return 0n;
1453
+ if (probe.status !== 402) {
1454
+ const said = providerMessage(probe.json);
1455
+ throw new CliError(
1456
+ "API_UNREACHABLE",
1457
+ `${url} answered ${probe.status}${said === null ? "." : `: ${said}`}`,
1458
+ {
1459
+ fix: "Nothing was paid.",
1460
+ details: { status: probe.status, body: probe.json, ...providerError(probe.text) }
1461
+ }
1462
+ );
1463
+ }
1464
+ const challenge = decodeChallenge(probe, url);
1465
+ const payer = createPayerClient(() => signerOrThrow({}));
1466
+ const requirement = selectRequirement(payer.core, challenge, args.terms);
1467
+ if (requirement === void 0) throw noMatchingEntry(challenge, args.terms);
1468
+ assertWithinTerms(args.terms, requirement);
1469
+ if (challenge.extensions?.[SIGN_IN_WITH_X] === void 0) return BigInt(requirement.amount);
1470
+ const signer = await openWallet(
1471
+ resolveWalletProvider(ctx, deps.provider !== void 0 ? { provider: deps.provider } : {})
1472
+ );
1473
+ const recheck = await httpRequest(url, {
1474
+ timeoutMs: args.timeoutMs ?? ctx.flags.timeout,
1475
+ blockRedirects: true,
1476
+ binaryBody: true,
1477
+ method: resolveMethod(args),
1478
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {},
1479
+ ...args.rawBody !== void 0 ? { rawBody: args.rawBody } : {},
1480
+ headers: {
1481
+ ...headers,
1482
+ [SIWX_HEADER]: await buildSiwxHeader(signer, {
1483
+ baseUrl: new URL(url).origin,
1484
+ chainId: requirement.network
1485
+ })
1486
+ }
1487
+ });
1488
+ if (!recheck.ok) throw fetchFailureToCliError(recheck);
1489
+ if (recheck.status >= 200 && recheck.status < 300) return 0n;
1490
+ if (recheck.status !== 402) {
1491
+ throw new CliError(
1492
+ "API_UNREACHABLE",
1493
+ `${url} answered ${recheck.status} on the entitlement re-check.`,
1494
+ {
1495
+ fix: "Nothing was paid.",
1496
+ details: { status: recheck.status, body: recheck.json, ...providerError(recheck.text) }
1497
+ }
1498
+ );
1499
+ }
1500
+ const fresh = decodeChallenge(recheck, url);
1501
+ const owed = selectRequirement(payer.core, fresh, args.terms);
1502
+ if (owed === void 0) throw noMatchingEntry(fresh, args.terms);
1503
+ assertWithinTerms(args.terms, owed);
1504
+ return BigInt(owed.amount);
1505
+ }
1506
+ function resolveLane(url, settings) {
1507
+ let target;
1508
+ try {
1509
+ target = new URL(url);
1510
+ } catch {
1511
+ throw new CliError("USAGE", `Invalid URL: ${JSON.stringify(url)}`, {
1512
+ fix: "Pass an absolute http(s) URL."
1513
+ });
1514
+ }
1515
+ if (target.protocol !== "http:" && target.protocol !== "https:") {
1516
+ throw new CliError("USAGE", `URL must be http or https: ${JSON.stringify(url)}`, {
1517
+ fix: "Pass an absolute http(s) URL."
1518
+ });
1519
+ }
1520
+ if (isSameDeployment(target.origin, new URL(settings.baseUrl).origin)) return "tenjin";
1521
+ if (target.protocol !== "https:") {
1522
+ throw new CliError("USAGE", "The Bazaar lane pays https endpoints only.", {
1523
+ fix: "Use a public HTTPS endpoint."
1524
+ });
1525
+ }
1526
+ return "bazaar";
1527
+ }
1528
+ var METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
1529
+ var BODY_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
1530
+ function hasBody(args) {
1531
+ return args.data !== void 0 || args.dataRaw !== void 0 || args.rawBody !== void 0;
1532
+ }
1533
+ function resolveMethod(args) {
1534
+ const method = args.method?.toUpperCase() ?? (hasBody(args) ? "POST" : "GET");
1535
+ if (!METHODS.has(method)) {
1536
+ throw new CliError("USAGE", `Unsupported method ${JSON.stringify(args.method)}`, {
1537
+ fix: "Use -X GET, POST, PUT, PATCH or DELETE."
1538
+ });
1539
+ }
1540
+ if (hasBody(args) && !BODY_METHODS.has(method)) {
1541
+ throw new CliError("USAGE", "A request body needs -X POST, PUT or PATCH.", {
1542
+ fix: "Drop the body, or pass -X POST, PUT or PATCH."
1543
+ });
1544
+ }
1545
+ return method;
1546
+ }
1547
+ function resolveBody(args, operator) {
1548
+ const given = [args.data, args.dataRaw, args.rawBody].filter((b) => b !== void 0);
1549
+ if (given.length > 1) {
1550
+ throw new CliError("USAGE", "Pass one request body: --data or --data-raw, not both.", {
1551
+ fix: "Use --data for a JSON body, or --data-raw with its own Content-Type."
1552
+ });
1553
+ }
1554
+ if (args.data !== void 0) return { jsonBody: parseBody(args.data) };
1555
+ if (args.dataRaw !== void 0) {
1556
+ if (operator["content-type"] === void 0) {
1557
+ throw new CliError("USAGE", "A --data-raw body needs its content type.", {
1558
+ fix: "Pass -H 'Content-Type: <type>' with --data-raw."
1559
+ });
1560
+ }
1561
+ return { rawBody: args.dataRaw };
1562
+ }
1563
+ return args.rawBody !== void 0 ? { rawBody: args.rawBody } : {};
1564
+ }
1565
+ function operatorHeaders(lines, rawBody) {
1566
+ if (lines === void 0) return {};
1567
+ const out = {};
1568
+ for (const line of lines) {
1569
+ const at = line.indexOf(":");
1570
+ const name = at > 0 ? line.slice(0, at).trim() : "";
1571
+ const value = at > 0 ? line.slice(at + 1).trim() : "";
1572
+ const problem = requestHeaderProblem(name, value, rawBody);
1573
+ if (problem === "name") {
1574
+ throw new CliError("USAGE", `Not a request header: ${JSON.stringify(line)}`, {
1575
+ fix: "Pass -H 'Name: value'."
1576
+ });
1577
+ }
1578
+ if (problem === "reserved") {
1579
+ throw new CliError("USAGE", `This command sets the header ${JSON.stringify(name)} itself.`, {
1580
+ fix: "Payment, sign-in, bypass and transport headers are never taken from -H. --data is always application/json; only --data-raw takes a Content-Type from -H."
1581
+ });
1582
+ }
1583
+ if (problem === "value") {
1584
+ throw new CliError(
1585
+ "USAGE",
1586
+ `The value of ${JSON.stringify(name)} is too long or spans lines.`,
1587
+ {
1588
+ fix: "Keep each -H value on one line, under 1,024 characters."
1589
+ }
1590
+ );
1591
+ }
1592
+ const lowered = name.toLowerCase();
1593
+ if (lowered in out) {
1594
+ throw new CliError("USAGE", `The header ${JSON.stringify(name)} was given twice.`, {
1595
+ fix: "Pass each header name once."
1596
+ });
1597
+ }
1598
+ out[lowered] = value;
1599
+ }
1600
+ return out;
1601
+ }
1602
+ function callerHeaders(headers) {
1603
+ if (headers === void 0) return {};
1604
+ const allowed = /* @__PURE__ */ new Set(["accept", "content-type"]);
1605
+ const out = {};
1606
+ for (const [name, value] of Object.entries(headers)) {
1607
+ const lowered = name.toLowerCase();
1608
+ if (!allowed.has(lowered) || value.length > 1024 || /[\r\n]/.test(value)) {
1609
+ throw new CliError(
1610
+ "USAGE",
1611
+ `This command will not send the header ${JSON.stringify(name)}.`,
1612
+ {
1613
+ fix: "Only bounded accept and content-type headers ride on a paid request."
1614
+ }
1615
+ );
1616
+ }
1617
+ out[lowered] = value;
1618
+ }
1619
+ return out;
1620
+ }
1621
+ function specHeaders(headers) {
1622
+ if (headers === void 0) return {};
1623
+ const out = {};
1624
+ for (const [name, value] of Object.entries(headers)) {
1625
+ if (requestHeaderProblem(name, value) !== null) {
1626
+ throw new CliError(
1627
+ "USAGE",
1628
+ `This command will not send the header ${JSON.stringify(name)}.`,
1629
+ {
1630
+ fix: "A spec header is a bounded, single-line value, and never a payment, sign-in, bypass or transport header."
1631
+ }
1632
+ );
1633
+ }
1634
+ out[name.toLowerCase()] = value;
1635
+ }
1636
+ return out;
1637
+ }
1638
+ function parseBody(data) {
1639
+ if (data === void 0) return void 0;
1640
+ try {
1641
+ return JSON.parse(data);
1642
+ } catch {
1643
+ throw new CliError("USAGE", "The --data value is not valid JSON.", {
1644
+ fix: `Pass a JSON object/array/string, e.g. --data '{"question":"..."}'.`
1645
+ });
1646
+ }
1647
+ }
1648
+ function decodeChallenge(res, url) {
1649
+ const encoded = res.header(PAYMENT_REQUIRED_HEADER);
1650
+ if (encoded === void 0) {
1651
+ throw new CliError(
1652
+ "CONTRACT_MISMATCH",
1653
+ `The 402 from ${url} carried no PAYMENT-REQUIRED header.`,
1654
+ {
1655
+ fix: "The endpoint does not speak x402 v2; nothing was paid."
1656
+ }
1657
+ );
1658
+ }
1659
+ try {
1660
+ return decodePaymentRequiredHeader(encoded);
1661
+ } catch (err) {
1662
+ throw new CliError("CONTRACT_MISMATCH", "Could not decode the PAYMENT-REQUIRED header.", {
1663
+ cause: err
1664
+ });
1665
+ }
1666
+ }
1667
+ function assertUsableResult(schema, body, status, how) {
1668
+ if (schema === void 0) return void 0;
1669
+ const check = validateResultBody(schema, body);
1670
+ if (check.valid) return void 0;
1671
+ if (check.unvalidated === true) return unvalidatedCaveat(check);
1672
+ throw new CliError("CONTRACT_MISMATCH", "The response is not a usable result.", {
1673
+ fix: `Nothing was paid on this ${how} delivery. The endpoint answered ${status} with a body that fails the success rule it was asked under.`,
1674
+ details: {
1675
+ status,
1676
+ reason: check.reason,
1677
+ ...check.diagnosis !== void 0 ? { diagnosis: check.diagnosis } : {},
1678
+ paid: false
1679
+ }
1680
+ });
1681
+ }
1682
+ function unvalidatedCaveat(check) {
1683
+ return `${check.reason ?? "The result could not be validated."} The body is delivered unverified: its shape was never checked against the success rule.`;
1684
+ }
1685
+ function failedRuleCaveat(check) {
1686
+ return `${check.reason ?? "The result does not satisfy its success schema."} The payment settled, so the body is delivered as received, unverified: treat it as possibly not the answer that was paid for.`;
1687
+ }
1688
+ var STATUS_URL_HEADERS = ["x-status-url"];
1689
+ function statusUrlOf(failure, requestUrl) {
1690
+ for (const name of STATUS_URL_HEADERS) {
1691
+ const value = failure.header?.(name)?.trim();
1692
+ if (value === void 0 || value.length === 0 || value.length > 2048) continue;
1693
+ try {
1694
+ const status = new URL(value, requestUrl);
1695
+ if (status.protocol === "https:" && status.host === new URL(requestUrl).host) {
1696
+ return status.toString();
1697
+ }
1698
+ } catch {
1699
+ }
1700
+ }
1701
+ return null;
1702
+ }
1703
+ function legFix(failure) {
1704
+ return failure.kind === "oversized-header" ? "Raising `--max-http-header-size` on the node process that runs this CLI would let the header be read; that is an operator decision, not a default this build changes." : "";
1705
+ }
1706
+ function providerMessage(body) {
1707
+ const error = body?.error;
1708
+ const message = error?.message;
1709
+ if (typeof message !== "string") return null;
1710
+ const line = message.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim().slice(0, 300);
1711
+ return line.length > 0 ? line : null;
1712
+ }
1713
+ var PROVIDER_ERROR_CHARS = 500;
1714
+ function providerError(text) {
1715
+ const line = sellerLine(text);
1716
+ return line.length > 0 ? { providerError: line } : {};
1717
+ }
1718
+ function sellerLine(text) {
1719
+ const flat = sanitizeForTerminal(
1720
+ mask(text.slice(0, PROVIDER_ERROR_CHARS * 8)).replace(/\s+/g, " ")
1721
+ ).trim();
1722
+ const chars = Array.from(flat);
1723
+ return chars.length <= PROVIDER_ERROR_CHARS ? flat : `${chars.slice(0, PROVIDER_ERROR_CHARS).join("")}\u2026`;
1724
+ }
1725
+ function noMatchingEntry(challenge, terms) {
1726
+ const unsupportedMethod = challenge.accepts.some(
1727
+ (a) => !signsEip3009(a) && (terms?.network === void 0 || a.network === terms.network)
1728
+ );
1729
+ if (terms === void 0 || terms.network === void 0 && terms.asset === void 0 || unsupportedMethod) {
1730
+ return noPayableRequirement(challenge.accepts);
1731
+ }
1732
+ const advertised = challenge.accepts.map((a) => `${a.scheme}/${a.network}/${a.asset}`);
1733
+ return new CliError(
1734
+ "REGISTRY_MISMATCH",
1735
+ `The 402 advertises nothing on ${terms.network ?? "any supported chain"} in ${terms.asset ?? "any supported token"}, which is what this call was authorized against.`,
1736
+ {
1737
+ fix: "Nothing was signed. The endpoint changed the deal since those terms were issued; ask for a fresh decision.",
1738
+ details: { advertised, terms }
1739
+ }
1740
+ );
1741
+ }
1742
+ function selectRequirement(core, challenge, terms) {
1743
+ return selectPayableRequirement(
1744
+ core,
1745
+ challenge,
1746
+ terms === void 0 ? void 0 : { network: terms.network, asset: terms.asset }
1747
+ );
1748
+ }
1749
+ function assertWithinTerms(terms, requirement) {
1750
+ const overQuote = terms.maxAmountAtomic !== void 0 && BigInt(requirement.amount) > BigInt(terms.maxAmountAtomic);
1751
+ const mismatch = overQuote ? `amount ${requirement.amount} over the advertised ${terms.maxAmountAtomic ?? "0"}` : terms.payTo !== void 0 && requirement.payTo.toLowerCase() !== terms.payTo.toLowerCase() ? `payTo ${requirement.payTo}` : void 0;
1752
+ if (mismatch !== void 0) {
1753
+ throw new CliError(
1754
+ "REGISTRY_MISMATCH",
1755
+ `The live 402 exceeds the terms this call was authorized against (${mismatch}).`,
1756
+ {
1757
+ fix: "Nothing was signed. The endpoint changed its deal since those terms were issued; ask for a fresh decision.",
1758
+ details: { advertised: terms, live: requirement }
1759
+ }
1760
+ );
1761
+ }
1762
+ return terms.source ?? "the advertised terms";
1763
+ }
1764
+ async function checkRegistry(settings, url, requirement, ctx, acknowledged, warnings) {
1765
+ const verification = await verifyAgainstRegistries(
1766
+ settings.bazaarRegistries,
1767
+ url,
1768
+ requirement,
1769
+ ctx.flags.timeout,
1770
+ { dataDir: ctx.dataDir }
1771
+ );
1772
+ if (verification.outcome === "verified") return verification.registry;
1773
+ if (verification.outcome === "unlisted") return void 0;
1774
+ const warning = {
1775
+ ...verification,
1776
+ acknowledged,
1777
+ quote: { url, ...requirement }
1778
+ };
1779
+ warnings.push(warning);
1780
+ const message = warningMessage(warning);
1781
+ if (!ctx.flags.json) {
1782
+ ctx.io.stderr.write(
1783
+ `Live quote: ${sanitizeForTerminal(url)}; recipient ${sanitizeForTerminal(requirement.payTo)}; ${sanitizeForTerminal(requirement.network)} / ${sanitizeForTerminal(requirement.asset)}; ${toMoney(requirement.amount).usd} USD
1784
+ `
1785
+ );
1786
+ ctx.io.stderr.write(
1787
+ `${sanitizeForTerminal(message)}${acknowledged ? " (acknowledged for this invocation)" : ""}
1788
+ `
1789
+ );
1790
+ }
1791
+ if (!acknowledged) {
1792
+ throw new CliError("REFUSED", message, {
1793
+ fix: "Review the live quote and use --ignore-warnings to acknowledge this registry warning for this invocation. --yes only confirms payment; normal payment checks still apply.",
1794
+ details: { reason: "registry_acknowledgement_required", quote: { url, ...requirement } }
1795
+ });
1796
+ }
1797
+ return void 0;
1798
+ }
1799
+ function warningMessage(warning) {
1800
+ switch (warning.outcome) {
1801
+ case "unavailable":
1802
+ return "Registry warning: verification is unavailable or incomplete.";
1803
+ case "mismatch":
1804
+ return `Registry warning: the live terms differ from ${warning.registry} (${warning.detail}).`;
1805
+ }
1806
+ }
1807
+ function deliverQuote(url, lane, res, challenge, chosen, printBody) {
1808
+ const chosenAt = chosen === void 0 ? -1 : challenge.accepts.findIndex((a) => sameDeal(a, chosen));
1809
+ const accepts = challenge.accepts.map((a, i) => ({
1810
+ scheme: a.scheme,
1811
+ network: a.network,
1812
+ asset: a.asset,
1813
+ amount: a.amount,
1814
+ ...isCanonicalUsdc(a) ? { usd: toMoney(a.amount).usd } : {},
1815
+ ...i === chosenAt ? { payable: true } : {},
1816
+ payTo: a.payTo,
1817
+ maxTimeoutSeconds: a.maxTimeoutSeconds,
1818
+ ...a.extra !== void 0 ? { extra: a.extra } : {}
1819
+ }));
1820
+ const signIn = signInOnlyChallenge(challenge) !== void 0;
1821
+ const data = {
1822
+ url,
1823
+ lane,
1824
+ status: res.status,
1825
+ paid: false,
1826
+ quote: true,
1827
+ resource: challenge.resource,
1828
+ accepts,
1829
+ ...signIn ? { signIn: true } : {},
1830
+ ...challenge.extensions !== void 0 ? { extensions: challenge.extensions } : {},
1831
+ ...res.json !== void 0 ? { body: res.json } : {},
1832
+ bodyText: res.text
1833
+ };
1834
+ const host = sanitizeForTerminal(new URL(url).host);
1835
+ const payable = accepts[chosenAt];
1836
+ const headline = payable?.usd !== void 0 ? `quote: ${payable.usd} USD to ${host} on ${sanitizeForTerminal(payable.network)} (nothing paid)` : signIn ? `quote: ${host} asks the wallet that paid it to sign in, and lists no payment option (nothing paid)` : accepts.length === 0 ? `quote: ${host} answered 402 with no payment option (nothing paid)` : `quote: ${host} lists no option this wallet can pay, only USDC on Base is supported (nothing paid)`;
1837
+ const body = sanitizeForTerminal(res.text);
1838
+ const preview = printBody || body.length <= BODY_PREVIEW_CHARS ? body : `${body.slice(0, BODY_PREVIEW_CHARS)}
1839
+ \u2026 truncated; run with --print-body or --json for the full body`;
1840
+ return { data, humanLines: [headline, ...preview.length > 0 ? [preview] : []] };
1841
+ }
1842
+ function sameDeal(a, b) {
1843
+ return a === b || a.scheme === b.scheme && a.network === b.network && a.asset.toLowerCase() === b.asset.toLowerCase() && a.amount === b.amount && a.payTo.toLowerCase() === b.payTo.toLowerCase();
1844
+ }
1845
+ function deliver(url, lane, res, opts) {
1846
+ const settlementTxHash = opts.paid ? settlementTx(res) : void 0;
1847
+ const data = {
1848
+ url,
1849
+ lane,
1850
+ status: res.status,
1851
+ paid: opts.paid,
1852
+ ...opts.warnings !== void 0 ? { warnings: opts.warnings } : {},
1853
+ ...opts.paid ? {
1854
+ amountPaid: toMoney(opts.amountAtomic.toString()),
1855
+ payTo: opts.requirement.payTo,
1856
+ network: opts.requirement.network,
1857
+ asset: opts.requirement.asset,
1858
+ payer: opts.payer,
1859
+ ...opts.authorization !== void 0 ? { authorization: opts.authorization } : {},
1860
+ ...opts.registry !== void 0 ? { registry: opts.registry } : {}
1861
+ } : opts.entitled === true ? { entitled: true } : opts.signedIn === true ? { signedIn: true } : {},
1862
+ ...settlementTxHash !== void 0 ? { settlementTxHash } : {},
1863
+ // Beside the body, never instead of it: the caller gets the product AND the
1864
+ // fact that its shape was never checked. The flag is what a machine reads:
1865
+ // a caller branching on a delivery must not have to match on prose, which
1866
+ // is how an unchecked body passed for a checked one one layer up.
1867
+ ...opts.caveat !== void 0 ? { resultUnverified: true, resultCaveat: opts.caveat } : {},
1868
+ // The body is the product: JSON when the endpoint spoke it, raw text always,
1869
+ // and, when it was a file, where a direct pay saved it, or the bytes
1870
+ // themselves for the router's tool to save.
1871
+ ...res.json !== void 0 ? { body: res.json } : {},
1872
+ bodyText: res.text,
1873
+ ...opts.saved !== void 0 ? opts.saved : res.bytes !== void 0 ? { bodyBytes: res.bytes, contentType: res.header("content-type") ?? "" } : {}
1874
+ };
1875
+ const headline = opts.paid ? `paid ${toMoney(opts.amountAtomic.toString()).usd} USD to ${sanitizeForTerminal(new URL(url).host)}` + (settlementTxHash !== void 0 ? ` (tx ${settlementTxHash})` : "") : opts.entitled === true ? `free (entitled, no charge)` : opts.signedIn === true ? `free (signed in, no charge)` : `free (${res.status}, no charge)`;
1876
+ const body = sanitizeForTerminal(res.text);
1877
+ const preview = opts.printBody || body.length <= BODY_PREVIEW_CHARS ? body : `${body.slice(0, BODY_PREVIEW_CHARS)}
1878
+ \u2026 truncated; run with --print-body or --json for the full body`;
1879
+ return {
1880
+ data,
1881
+ humanLines: [
1882
+ headline,
1883
+ ...(opts.warnings ?? []).map(
1884
+ (w) => `${sanitizeForTerminal(warningMessage(w))} (acknowledged)`
1885
+ ),
1886
+ ...opts.caveat !== void 0 ? [sanitizeForTerminal(opts.caveat)] : [],
1887
+ ...opts.saved !== void 0 ? [savedLine(opts.saved)] : [],
1888
+ // The paid bytes no folder took: the only copy, so printed whole.
1889
+ ...opts.saved?.bodyBase64 !== void 0 ? [opts.saved.bodyBase64] : [],
1890
+ ...preview.length > 0 ? [preview] : []
1891
+ ]
1892
+ };
1893
+ }
1894
+ function describeBody(res) {
1895
+ if (res.bytes === void 0) return void 0;
1896
+ return {
1897
+ notSaved: "--quote writes no file; run it without --quote to save it",
1898
+ contentType: res.header("content-type") ?? "",
1899
+ bytes: res.bytes.byteLength
1900
+ };
1901
+ }
1902
+ async function keepBody(dataDir, url, res) {
1903
+ if (res.bytes === void 0) return void 0;
1904
+ const contentType = res.header("content-type") ?? "";
1905
+ const described = { contentType, bytes: res.bytes.byteLength };
1906
+ const stem = `pay-${new URL(url).hostname.slice(0, 60)}-${Date.now()}`;
1907
+ const first = await writeBody(downloadsDir(dataDir), stem, contentType, res.bytes);
1908
+ if ("path" in first) return { savedTo: first.path, ...described };
1909
+ const second = await writeBody(tmpdir(), stem, contentType, res.bytes);
1910
+ if ("path" in second) return { savedTo: second.path, saveError: first.error, ...described };
1911
+ return {
1912
+ saveError: `${first.error}; the temp folder failed too: ${second.error}`,
1913
+ bodyBase64: Buffer.from(res.bytes).toString("base64"),
1914
+ ...described
1915
+ };
1916
+ }
1917
+ async function writeBody(directory, stem, contentType, bytes) {
1918
+ try {
1919
+ return { path: await writeNewFile(directory, stem, contentType, bytes) };
1920
+ } catch (err) {
1921
+ return { error: err instanceof Error ? err.message : String(err) };
1922
+ }
1923
+ }
1924
+ function savedLine(saved) {
1925
+ const what = `${saved.bytes}-byte ${sanitizeForTerminal(saved.contentType) || "binary"} body`;
1926
+ const why = sanitizeForTerminal(saved.saveError ?? "unknown error");
1927
+ if (saved.savedTo !== void 0) {
1928
+ return saved.saveError !== void 0 ? `the downloads folder could not take the ${what} (${why}), so it was saved to ${saved.savedTo}` : `saved the ${what} to ${saved.savedTo}`;
1929
+ }
1930
+ if (saved.notSaved !== void 0) return `the ${what} was not saved: ${saved.notSaved}`;
1931
+ return saved.bodyBase64 !== void 0 ? `the ${what} could not be saved (${why}); its bytes follow as base64` : `the ${what} could not be saved: ${why}`;
1932
+ }
1933
+ function settlementTx(res) {
1934
+ const tx = paymentResponse(res)?.transaction;
1935
+ return typeof tx === "string" && /^0x[0-9a-fA-F]{64}$/.test(tx) ? tx : void 0;
1936
+ }
1937
+ function settledTx(res) {
1938
+ return paymentResponse(res)?.success === true ? settlementTx(res) : void 0;
1939
+ }
1940
+ function settlementRefusal(res) {
1941
+ const settle = paymentResponse(res);
1942
+ if (settle?.success !== false) return void 0;
1943
+ const said = [settle.errorReason, settle.errorMessage].find(
1944
+ (value) => typeof value === "string" && value.trim().length > 0
1945
+ );
1946
+ const reason = said !== void 0 ? sellerLine(said) : "";
1947
+ return reason.length > 0 ? { reason } : {};
1948
+ }
1949
+ function paymentResponse(res) {
1950
+ const header = res.header(PAYMENT_RESPONSE_HEADER) ?? res.header(PAYMENT_RESPONSE_HEADER_V1);
1951
+ if (header === void 0) return void 0;
1952
+ try {
1953
+ const settle = decodePaymentResponseHeader(header);
1954
+ return typeof settle === "object" && settle !== null ? settle : void 0;
1955
+ } catch {
1956
+ return void 0;
1957
+ }
1958
+ }
1959
+ async function openWallet(provider) {
1960
+ try {
1961
+ await describeWallet(provider);
1962
+ return await provider.getSigner();
1963
+ } catch (err) {
1964
+ throw walletError(err);
1965
+ }
1966
+ }
1967
+ async function describeOpenable(provider) {
1968
+ try {
1969
+ return await describeWallet(provider);
1970
+ } catch (err) {
1971
+ throw walletError(err);
1972
+ }
1973
+ }
1974
+ function walletError(err) {
1975
+ if (!(err instanceof CliError)) return err;
1976
+ return new CliError(err.code, err.message, {
1977
+ exitCode: err.exitCode,
1978
+ ...err.fix !== void 0 ? { fix: err.fix } : {},
1979
+ details: {
1980
+ ...typeof err.details === "object" && err.details !== null ? err.details : {},
1981
+ walletUnavailable: true
1982
+ },
1983
+ cause: err
1984
+ });
1985
+ }
1986
+ var MAX_CHALLENGE_CHARS = 16384;
1987
+ function paymentRequiredError(http, res) {
1988
+ let said;
1989
+ try {
1990
+ said = http.getPaymentRequiredResponse((name) => {
1991
+ const value = res.header(name);
1992
+ return value !== void 0 && value.length <= MAX_CHALLENGE_CHARS ? value : void 0;
1993
+ }, res.json).error;
1994
+ } catch {
1995
+ said = void 0;
1996
+ }
1997
+ if (typeof said !== "string") return void 0;
1998
+ const line = sellerLine(said);
1999
+ return line.length > 0 ? line : void 0;
2000
+ }
2001
+ function signInOnlyHeader(paymentRequiredHeader) {
2002
+ if (paymentRequiredHeader.length > MAX_CHALLENGE_CHARS) return void 0;
2003
+ let challenge;
2004
+ try {
2005
+ challenge = decodePaymentRequiredHeader(paymentRequiredHeader);
2006
+ } catch {
2007
+ return void 0;
2008
+ }
2009
+ const extension = signInOnlyChallenge(challenge);
2010
+ return extension !== void 0 ? { challenge, extension } : void 0;
2011
+ }
2012
+ async function signInForPoll(paymentRequiredHeader, url, ctx, deps) {
2013
+ const read = signInOnlyHeader(paymentRequiredHeader);
2014
+ if (read === void 0) return void 0;
2015
+ const { challenge, extension } = read;
2016
+ const { paidBy } = deps;
2017
+ try {
2018
+ const provider = resolveWalletProvider(
2019
+ ctx,
2020
+ deps.provider !== void 0 ? { provider: deps.provider } : {}
2021
+ );
2022
+ let current;
2023
+ const answer = await answerSignInChallenge(challenge, extension, url, {
2024
+ address: async () => current = (await describeOpenable(provider)).address,
2025
+ paidHost: async (host, address) => paidBy.from === void 0 ? "payer_unknown" : hostOf(paidBy.url) === host && paidBy.from.toLowerCase() === address.toLowerCase() ? "paid" : "unpaid",
2026
+ signer: async () => {
2027
+ const signer = await openWallet(provider);
2028
+ current = signer.address;
2029
+ return signer;
2030
+ }
2031
+ });
2032
+ if (!("refused" in answer)) return answer;
2033
+ if (answer.refused === "unpaid" && paidBy.from !== void 0 && current !== void 0 && hostOf(paidBy.url) === hostOf(url) && current.toLowerCase() !== paidBy.from.toLowerCase()) {
2034
+ return { otherWallet: { paidBy: paidBy.from, current } };
2035
+ }
2036
+ return { refused: answer.reason };
2037
+ } catch (err) {
2038
+ return {
2039
+ error: `the wallet could not be opened (${sellerLine(err instanceof Error ? err.message : String(err)) || "no reason given"})`
2040
+ };
2041
+ }
2042
+ }
2043
+ function hostOf(url) {
2044
+ try {
2045
+ return new URL(url).host;
2046
+ } catch {
2047
+ return void 0;
2048
+ }
2049
+ }
2050
+ function signerOrThrow(held) {
2051
+ if (held.current === void 0) {
2052
+ throw new CliError("INTERNAL", "The payment was built before the wallet was opened.");
2053
+ }
2054
+ return held.current;
2055
+ }
2056
+
2057
+ export {
2058
+ isModelWorkerProcess,
2059
+ policyFix,
2060
+ createQuote,
2061
+ readQuote,
2062
+ quoteClosed,
2063
+ wasShortOfFunds,
2064
+ admitPlan,
2065
+ admitQuote,
2066
+ reopenShortQuote,
2067
+ LOW_FUNDS_TAIL,
2068
+ isLowFundsRefusal,
2069
+ runPay,
2070
+ MAX_PAID_LEG_TIMEOUT_MS,
2071
+ paidLegTimeoutMs,
2072
+ quoteRouterCall,
2073
+ sellerLine,
2074
+ settlementTx,
2075
+ signInOnlyHeader,
2076
+ signInForPoll
2077
+ };
2078
+ //# sourceMappingURL=chunk-ODRPASFP.js.map