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,1889 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ paymentShortOfFunds,
4
+ reasonCode
5
+ } from "./chunk-5USBZ2MU.js";
6
+ import {
7
+ DEPOSIT_GATE_TIMEOUT_MS,
8
+ GATE_TIMEOUT_MS
9
+ } from "./chunk-F2KJAJ7T.js";
10
+ import {
11
+ FileClientChannelStorage,
12
+ channelCredit,
13
+ legacySharedInferenceChannel,
14
+ modelChannelDir,
15
+ modelChannelLane,
16
+ modelChannelScope,
17
+ modelInferenceRunDir,
18
+ modelInferenceRunScope,
19
+ modelRunDepositKeys
20
+ } from "./chunk-24XKUN2S.js";
21
+ import {
22
+ TOPPING_UP_MEMO_MS,
23
+ WARM_ABSENT_MS,
24
+ claimRouterMemo,
25
+ isDefiniteBlock,
26
+ readRouterMemo,
27
+ releaseRouterMemo,
28
+ writeRouterMemo
29
+ } from "./chunk-64WOMNYR.js";
30
+ import {
31
+ withHeldLock
32
+ } from "./chunk-TVWCLUBI.js";
33
+ import {
34
+ chosenOffer,
35
+ quoteOf,
36
+ routingOffers
37
+ } from "./chunk-YJGEVBKZ.js";
38
+ import {
39
+ BatchSettlementEvmScheme,
40
+ readChannelBalanceAndTotalClaimed,
41
+ toClientEvmSigner,
42
+ x402Client
43
+ } from "./chunk-JTILUN4W.js";
44
+ import {
45
+ computeChannelId
46
+ } from "./chunk-6QMDUDF2.js";
47
+ import {
48
+ SIWX_CHAIN_ID,
49
+ SIWX_HEADER,
50
+ buildSiwxHeader
51
+ } from "./chunk-OQWPRFAC.js";
52
+ import {
53
+ creditRefundedExposure,
54
+ releaseUnchargedExposure
55
+ } from "./chunk-FYFHH7V5.js";
56
+ import {
57
+ decodePaymentRequiredHeader,
58
+ decodePaymentResponseHeader,
59
+ decodePaymentSignatureHeader,
60
+ x402HTTPClient
61
+ } from "./chunk-RGVCOG2S.js";
62
+ import {
63
+ createPublicClient,
64
+ http,
65
+ zeroAddress
66
+ } from "./chunk-7V25UAQO.js";
67
+ import {
68
+ encodeAbiParameters,
69
+ keccak256,
70
+ parseAbi
71
+ } from "./chunk-INSIW65E.js";
72
+ import {
73
+ LockTimeoutError
74
+ } from "./chunk-2W4DQQUU.js";
75
+ import {
76
+ FEE_ABOVE_CEILING,
77
+ LEGACY_ROUTING_QUOTE_ATOMIC,
78
+ MAX_CHANNEL_DEPOSIT_ATOMIC,
79
+ ROUTING_DEPOSIT_KEY,
80
+ ROUTING_FEE_CEILING_ATOMIC,
81
+ feeRefusal,
82
+ payerDir,
83
+ refusedWhy,
84
+ routingDepositAtomic
85
+ } from "./chunk-HZKANST2.js";
86
+ import {
87
+ readJsonFile,
88
+ writePrivate
89
+ } from "./chunk-ILWCKCOI.js";
90
+ import {
91
+ UNKNOWN_DETAIL,
92
+ WALLET_REASONS
93
+ } from "./chunk-RFZA7PSM.js";
94
+ import {
95
+ DEFINITE_UNLOCK,
96
+ classifyUnlockError
97
+ } from "./chunk-JUUBBBY5.js";
98
+ import {
99
+ CHANNEL_BUSY,
100
+ DEADLINE_AFTER_PAYMENT_SENT,
101
+ DEPOSIT_DEFERRED,
102
+ PAYMENT_FAILED,
103
+ ROUTE_PAID_PATH,
104
+ RouteSkipped,
105
+ TOPPING_UP,
106
+ TOP_UP_UNAVAILABLE,
107
+ acceptsFor,
108
+ buildWarmBody,
109
+ isUnreachable,
110
+ isWarmAnswer
111
+ } from "./chunk-ZEYA2WWX.js";
112
+ import {
113
+ httpRequest
114
+ } from "./chunk-D6M3ZK66.js";
115
+ import {
116
+ external_exports
117
+ } from "./chunk-P6YQWIT2.js";
118
+
119
+ // src/router/routing-payer.ts
120
+ import { randomUUID } from "node:crypto";
121
+
122
+ // node_modules/.pnpm/@x402+fetch@2.28.0/node_modules/@x402/fetch/dist/esm/index.mjs
123
+ function wrapFetchWithPayment(fetch2, client) {
124
+ const httpClient = client instanceof x402HTTPClient ? client : new x402HTTPClient(client);
125
+ return async (input, init) => {
126
+ const request = new Request(input, init);
127
+ const clonedRequest = request.clone();
128
+ const response = await fetch2(request);
129
+ if (response.status !== 402) {
130
+ return response;
131
+ }
132
+ let paymentRequired;
133
+ try {
134
+ const getHeader = (name) => response.headers.get(name);
135
+ let body;
136
+ try {
137
+ const responseText = await response.text();
138
+ if (responseText) {
139
+ body = JSON.parse(responseText);
140
+ }
141
+ } catch {
142
+ }
143
+ paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);
144
+ } catch (error) {
145
+ throw new Error(
146
+ `Failed to parse payment requirements: ${error instanceof Error ? error.message : "Unknown error"}`
147
+ );
148
+ }
149
+ const requestUrl = response.url || request.url;
150
+ const hookHeaders = await httpClient.handlePaymentRequired(paymentRequired, requestUrl);
151
+ if (hookHeaders) {
152
+ const hookRequest = clonedRequest.clone();
153
+ for (const [key, value] of Object.entries(hookHeaders)) {
154
+ hookRequest.headers.set(key, value);
155
+ }
156
+ const hookResponse = await fetch2(hookRequest);
157
+ if (hookResponse.status !== 402) {
158
+ return hookResponse;
159
+ }
160
+ }
161
+ let paymentPayload;
162
+ try {
163
+ paymentPayload = await client.createPaymentPayload(paymentRequired);
164
+ } catch (error) {
165
+ throw new Error(
166
+ `Failed to create payment payload: ${error instanceof Error ? error.message : "Unknown error"}`
167
+ );
168
+ }
169
+ const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
170
+ if (clonedRequest.headers.has("PAYMENT-SIGNATURE") || clonedRequest.headers.has("X-PAYMENT")) {
171
+ throw new Error("Payment already attempted");
172
+ }
173
+ for (const [key, value] of Object.entries(paymentHeaders)) {
174
+ clonedRequest.headers.set(key, value);
175
+ }
176
+ clonedRequest.headers.set(
177
+ "Access-Control-Expose-Headers",
178
+ "PAYMENT-RESPONSE,X-PAYMENT-RESPONSE"
179
+ );
180
+ const secondResponse = await fetch2(clonedRequest.clone());
181
+ const result = await httpClient.processPaymentResult(
182
+ paymentPayload,
183
+ (name) => secondResponse.headers.get(name),
184
+ secondResponse.status
185
+ );
186
+ if (result.recovered) {
187
+ const freshPayload = await client.createPaymentPayload(paymentRequired);
188
+ const retryHeaders = httpClient.encodePaymentSignatureHeader(freshPayload);
189
+ const retryRequest = clonedRequest;
190
+ for (const [k, v] of Object.entries(retryHeaders)) {
191
+ retryRequest.headers.set(k, v);
192
+ }
193
+ retryRequest.headers.set(
194
+ "Access-Control-Expose-Headers",
195
+ "PAYMENT-RESPONSE,X-PAYMENT-RESPONSE"
196
+ );
197
+ const retryResponse = await fetch2(retryRequest);
198
+ await httpClient.processPaymentResult(
199
+ freshPayload,
200
+ (name) => retryResponse.headers.get(name),
201
+ retryResponse.status
202
+ );
203
+ return retryResponse;
204
+ }
205
+ return secondResponse;
206
+ };
207
+ }
208
+
209
+ // src/router/routing-payer.ts
210
+ var LocalSendBlocked = class extends Error {
211
+ constructor(cause) {
212
+ super("The local send guard refused transmission.", { cause });
213
+ }
214
+ };
215
+ var NOT_CHECKED = {
216
+ status: "unknown",
217
+ reason: "not_checked",
218
+ detail: UNKNOWN_DETAIL["not_checked"]
219
+ };
220
+ var ROUTING_SPEND_CAP = "$0.25";
221
+ var DEPOSIT_MULTIPLIER = 5;
222
+ var DEPOSIT_EXTRA_MS = DEPOSIT_GATE_TIMEOUT_MS - GATE_TIMEOUT_MS;
223
+ var DETACHED_CEILING_MS = 15e3;
224
+ var TOP_UP_TIMEOUT_MS = 15e3;
225
+ var TOP_UP_BACKOFF_MS = [3e4, 12e4, 6e5];
226
+ var WALLET_LOW_BACKOFF_MS = [3e4, 12e4];
227
+ var SIGNER_RECHECK_MS = 6e4;
228
+ var PAID_CALL_RESERVE_MS = 1e3;
229
+ var RPC_TIMEOUT_MS = 2e3;
230
+ function chainReader(rpcUrl, fetchFn) {
231
+ return (args, timeoutMs) => createPublicClient({
232
+ transport: http(rpcUrl, {
233
+ timeout: timeoutMs,
234
+ retryCount: 0,
235
+ ...fetchFn !== void 0 ? { fetchFn } : {}
236
+ })
237
+ }).readContract(args);
238
+ }
239
+ function chainRefundReads(rpcUrl) {
240
+ const client = (timeout) => createPublicClient({ transport: http(rpcUrl, { timeout, retryCount: 0 }) });
241
+ return {
242
+ readChainId: (timeoutMs) => client(timeoutMs).getChainId(),
243
+ readBlockTimestamp: async (timeoutMs) => (await client(timeoutMs).getBlock({ blockTag: "latest" })).timestamp
244
+ };
245
+ }
246
+ var ROUTING_BLOCKED = /* @__PURE__ */ new Set([
247
+ "wallet_low",
248
+ "limit_below_deposit",
249
+ "budget_reached",
250
+ "not_allowlisted",
251
+ FEE_ABOVE_CEILING
252
+ ]);
253
+ var ROUTING_SILENT = /* @__PURE__ */ new Set([
254
+ CHANNEL_BUSY,
255
+ "busy",
256
+ DEADLINE_AFTER_PAYMENT_SENT,
257
+ "no_call",
258
+ TOPPING_UP,
259
+ DEPOSIT_DEFERRED,
260
+ TOP_UP_UNAVAILABLE
261
+ ]);
262
+ var NO_BACKOFF = /* @__PURE__ */ new Set([
263
+ CHANNEL_BUSY,
264
+ "busy",
265
+ DEADLINE_AFTER_PAYMENT_SENT,
266
+ "no_call"
267
+ ]);
268
+ var routingPolicy = (version, requirements) => {
269
+ const chosen = chosenOffer(routingOffers(version, requirements));
270
+ return chosen?.allowed === true ? [chosen.offer] : [];
271
+ };
272
+ var NOT_ROUTE = "not_the_routing_route";
273
+ var CHANNEL_BUSY_ERROR = "invalid_batch_settlement_evm_channel_busy";
274
+ function modelOffer(offers, ceiling) {
275
+ return offers.find((offer2) => BigInt(offer2.amount) <= ceiling) ?? offers[0];
276
+ }
277
+ var RoutingPayer = class {
278
+ constructor(deps) {
279
+ this.deps = deps;
280
+ }
281
+ deps;
282
+ /**
283
+ * THE MOST ONE PAYMENT MAY BE. The routing lane has the tool router's own ceiling and no
284
+ * ceiling of its own, and a caller cannot widen it; the job's cap may narrow it for one call
285
+ * (`routeFor`'s `limitAtomic`). The inference lane keeps the ceiling its caller names.
286
+ */
287
+ paymentCeiling() {
288
+ const lane = this.deps.modelLane;
289
+ if (!lane) return ROUTING_FEE_CEILING_ATOMIC;
290
+ if (modelChannelLane(lane.path) !== "model-routing") return lane.ceilingAtomic;
291
+ const widest = lane.ceilingAtomic < ROUTING_FEE_CEILING_ATOMIC ? lane.ceilingAtomic : ROUTING_FEE_CEILING_ATOMIC;
292
+ const limit = this.call?.limitAtomic;
293
+ return limit !== void 0 && limit < widest ? limit : widest;
294
+ }
295
+ /** The offer the routing lane would pay, by the tool router's rule (`chosenOffer`). */
296
+ routingChoice(offers) {
297
+ const chosen = chosenOffer(offers);
298
+ return chosen && chosen.allowed && BigInt(chosen.offer.amount) <= this.paymentCeiling() ? chosen.offer : void 0;
299
+ }
300
+ paymentQuote(headers) {
301
+ if (!this.deps.modelLane) return quoteOf((name) => headers.get(name));
302
+ const value = headers.get("payment-required");
303
+ if (!value) return null;
304
+ try {
305
+ const required = decodePaymentRequiredHeader(value);
306
+ const offers = routingOffers(required.x402Version, required.accepts);
307
+ const chosen = modelChannelLane(this.deps.modelLane.path) === "model-routing" ? chosenOffer(offers)?.offer : modelOffer(offers, this.paymentCeiling());
308
+ return chosen ? BigInt(chosen.amount) : null;
309
+ } catch {
310
+ return null;
311
+ }
312
+ }
313
+ channel = null;
314
+ call = null;
315
+ /** The call `pay` ran last, for its one diagnostic line. */
316
+ last = null;
317
+ queue = Promise.resolve();
318
+ /** A detached request still finishing; the next call waits for it. */
319
+ tail = Promise.resolve();
320
+ /** A sent payment still settling after its caller returned. Only unsigned requests bypass it. */
321
+ settling = false;
322
+ /** The one unlock in flight, which every caller and the prewarm await. */
323
+ unlocking = null;
324
+ /** Calls waiting on `unlocking` right now (the prewarm is not one). */
325
+ waiters = 0;
326
+ /** A signer an unlock settled with after every call waiting on it gave up:
327
+ * the next call signs with it rather than unlocking again (B3). */
328
+ handoff = null;
329
+ /** The last settled unlock's verdict (decision 16). */
330
+ memo = null;
331
+ /** The sign and routing verdicts last reported to `observe`, as status:reason. */
332
+ reported = {};
333
+ /** The background top-up in flight, which a call that meets it waits for. */
334
+ topping = null;
335
+ /** The last top-up started, settled or not: what a call that deferred its
336
+ * deposit waits on. */
337
+ lastTopUp = null;
338
+ /** The last top-up's refusal, which holds the next off until `until`. */
339
+ failed = null;
340
+ /** What settled top-ups deposited that no leg has said yet. */
341
+ toppedUp = 0n;
342
+ /** Background work a test or a shutdown can wait out ({@link idle}). */
343
+ pending = Promise.resolve();
344
+ /**
345
+ * THE UNLOCK, ahead of any call: `tenjin mcp` starts it when it starts, so
346
+ * the first prompt finds a verdict (and usually a signer) waiting. The same
347
+ * single flight as a call's, with no budget; its answer goes to the memo and
348
+ * to `observe`, and nothing else. Never rejects.
349
+ */
350
+ async prewarm() {
351
+ await this.unlock().catch(() => void 0);
352
+ }
353
+ /**
354
+ * What the last settled unlock said, with no waiting; unknown `not_checked`
355
+ * before any. A definite block is believed only as the pay path believes it
356
+ * (decision 16): within {@link SIGNER_RECHECK_MS}, with no unlock running
357
+ * and nothing it was read from changed. Past that it reads unknown, which
358
+ * gates nothing, and an unlock starts in the background, so a wallet created
359
+ * or repaired mid-session is picked up although no call asks for the fee.
360
+ * The stamp is read in the background too: a change starts the unlock, and
361
+ * the next caller reads its answer.
362
+ */
363
+ signVerdict() {
364
+ const memo = this.memo;
365
+ if (memo === null) return NOT_CHECKED;
366
+ if (!isDefiniteBlock(memo.verdict)) return memo.verdict;
367
+ if (this.unlocking !== null) return NOT_CHECKED;
368
+ if (this.now() - memo.at >= SIGNER_RECHECK_MS) {
369
+ void this.prewarm();
370
+ return NOT_CHECKED;
371
+ }
372
+ void this.stamp().then((stamp) => {
373
+ if (this.memo === memo && stamp !== memo.stamp) void this.prewarm();
374
+ });
375
+ return memo.verdict;
376
+ }
377
+ /**
378
+ * The paid route for one routing call to the router at `baseUrl`. ONLY
379
+ * THAT ROUTE IS PAID: a URL on any other origin or path is refused before
380
+ * anything is sent, so the routing fee's ceiling and channel never meet a
381
+ * provider's 402.
382
+ */
383
+ routeFor(baseUrl, limitAtomic) {
384
+ const calls = [];
385
+ const route = new URL(this.deps.modelLane?.path ?? ROUTE_PAID_PATH, baseUrl);
386
+ return {
387
+ send: async (url, options) => {
388
+ const target = new URL(url);
389
+ if (target.origin !== route.origin || target.pathname !== route.pathname || this.deps.modelLane && route.origin !== new URL(this.deps.modelLane.origin).origin) {
390
+ throw new RouteSkipped(NOT_ROUTE);
391
+ }
392
+ const sent = this.now();
393
+ const until = sent + options.timeoutMs;
394
+ let firstChallenge;
395
+ if (this.topping !== null || this.settling) {
396
+ const call = {
397
+ host: target.host,
398
+ router: url,
399
+ until,
400
+ paid: false,
401
+ answered: false,
402
+ deposits: []
403
+ };
404
+ calls.push(call);
405
+ let headers;
406
+ const base = options.fetchImpl ?? this.deps.fetchImpl ?? fetch;
407
+ const response = call.result = await httpRequest(url, {
408
+ ...options,
409
+ timeoutMs: Math.max(0, until - this.now()),
410
+ fetchImpl: async (input, init) => {
411
+ const answer = await base(input, init);
412
+ call.answered = true;
413
+ headers = new Headers(answer.headers);
414
+ return answer;
415
+ }
416
+ });
417
+ if (!response.ok || response.status >= 500) {
418
+ this.note(PAYMENT_FAILED, call, sent);
419
+ this.reportRouting(PAYMENT_FAILED);
420
+ throw new RouteSkipped(PAYMENT_FAILED, {
421
+ answered: call.answered,
422
+ ...!response.ok && !call.answered && isUnreachable(response) ? { unreached: response } : {}
423
+ });
424
+ }
425
+ if (response.status !== 402) return response;
426
+ firstChallenge = new Response(response.text, { status: 402, headers });
427
+ }
428
+ const once = () => this.turn(
429
+ () => {
430
+ const first = firstChallenge;
431
+ firstChallenge = void 0;
432
+ return this.noted(
433
+ sent,
434
+ () => this.pay(url, options, until, calls, false, first, limitAtomic)
435
+ );
436
+ },
437
+ until,
438
+ sent
439
+ );
440
+ if (this.topping !== null && await this.waitForTopUp(this.topping, until, sent) === null) {
441
+ throw new RouteSkipped(TOPPING_UP, {
442
+ ...firstChallenge !== void 0 ? { answered: true } : {}
443
+ });
444
+ }
445
+ try {
446
+ return await once();
447
+ } catch (err) {
448
+ const flight = this.lastTopUp;
449
+ if (!(err instanceof RouteSkipped) || err.why !== DEPOSIT_DEFERRED || flight === null) {
450
+ throw err;
451
+ }
452
+ const answered = { answered: err.answered };
453
+ const outcome = await this.waitForTopUp(flight, until, sent);
454
+ if (outcome === null) throw new RouteSkipped(TOPPING_UP, answered);
455
+ if (outcome.status === "refused" && outcome.skip.why !== DEADLINE_AFTER_PAYMENT_SENT) {
456
+ const { quotedAtomic } = outcome.skip;
457
+ throw new RouteSkipped(outcome.skip.why, {
458
+ ...answered,
459
+ ...quotedAtomic !== void 0 ? { quotedAtomic } : {}
460
+ });
461
+ }
462
+ if (outcome.status !== "done" && outcome.status !== "absent") throw err;
463
+ return await once();
464
+ }
465
+ },
466
+ deposited: () => settledIn(calls),
467
+ toppedUp: () => this.takeToppedUp(),
468
+ paid: () => calls.at(-1)?.paidAnswer === true,
469
+ authorized: () => {
470
+ const last = calls.at(-1);
471
+ return last?.paid === true ? last.quoted ?? 0n : 0n;
472
+ }
473
+ };
474
+ }
475
+ /**
476
+ * THE SESSION'S FIRST TOP-UP. `tenjin mcp` calls this as it starts, after
477
+ * the prewarm, so a new channel, or one that cannot cover the next fee, is
478
+ * funded before the first prompt needs it. The channel is read from the
479
+ * SDK's own files, with no request. The fixed routing quote is the low-credit
480
+ * threshold; a dear answer funds its own larger shortfall inline. Never rejects.
481
+ */
482
+ async topUpIfLow(baseUrl) {
483
+ if (this.deps.modelLane) return;
484
+ await this.unlocking?.catch(() => void 0);
485
+ const memo = this.memo;
486
+ if (memo?.verdict.status !== "ready" || memo.address === void 0) return;
487
+ const credit = await channelCredit(this.deps.dataDir, memo.address).catch(() => null);
488
+ if (credit === null || credit >= LEGACY_ROUTING_QUOTE_ATOMIC) return;
489
+ await this.topUpWhenDue(new URL(ROUTE_PAID_PATH, baseUrl).toString(), memo.address);
490
+ }
491
+ /** Resolves once no top-up is in flight or about to start, and no payment
492
+ * is still finishing in the background: for `tenjin mcp`'s exit and the
493
+ * tests, anything that must not end the process mid-deposit. */
494
+ async idle() {
495
+ for (; ; ) {
496
+ const pending = this.pending;
497
+ await pending;
498
+ await this.topping;
499
+ await this.tail;
500
+ if (pending === this.pending && this.topping === null) return;
501
+ }
502
+ }
503
+ get timers() {
504
+ return this.deps.timers ?? globalThis;
505
+ }
506
+ now() {
507
+ return this.deps.now?.() ?? Date.now();
508
+ }
509
+ warn(line) {
510
+ (this.deps.warn ?? ((l) => process.stderr.write(`${l}
511
+ `)))(
512
+ `tenjin mcp: routing fee: ${line}`
513
+ );
514
+ }
515
+ /** Calls inside one process take turns on its channel, a detached
516
+ * request's tail included, so none starts from a stale channel. A queued
517
+ * call gives up at its own deadline (`busy`) rather than wait out the
518
+ * call ahead of it, and then never starts. The deadline covers the wait
519
+ * only: once a call runs, its own budget applies. */
520
+ turn(run, until, sent, carrier = false) {
521
+ let gaveUp = false;
522
+ let timer;
523
+ const go = () => {
524
+ if (gaveUp) return Promise.reject(new RouteSkipped("busy"));
525
+ this.timers.clearTimeout(timer);
526
+ return run();
527
+ };
528
+ const next = this.queue.then(go, go);
529
+ this.queue = next.catch(() => void 0).then(() => this.tail);
530
+ const deadline = new Promise((_resolve, reject) => {
531
+ timer = this.timers.setTimeout(
532
+ () => {
533
+ gaveUp = true;
534
+ this.note("busy", null, sent, void 0, carrier);
535
+ reject(new RouteSkipped("busy"));
536
+ },
537
+ Math.max(0, until - this.now())
538
+ );
539
+ });
540
+ return Promise.race([next, deadline]).finally(() => this.timers.clearTimeout(timer));
541
+ }
542
+ /** One stderr line for a call the paid path did not answer; a detached
543
+ * one says it when its request ends. `carrier`: the top-up's own call. */
544
+ async noted(sent, run, carrier = false) {
545
+ this.last = null;
546
+ try {
547
+ return await run();
548
+ } catch (err) {
549
+ const call = this.last;
550
+ if (err instanceof RouteSkipped && call?.detached !== true) {
551
+ this.note(err.why, call, sent, void 0, carrier);
552
+ }
553
+ if (err instanceof RouteSkipped) this.reportRouting(err.why);
554
+ throw err;
555
+ }
556
+ }
557
+ note(why, call, sent, late, carrier = false) {
558
+ const result = call?.result;
559
+ const cause = late ?? (call === null ? "queued" : call.skipped !== void 0 ? "refused" : result === void 0 ? "none" : result.ok ? `http ${result.status}` : call.expired === true ? "timeout" : result.kind);
560
+ const stage = call === null ? "queue" : call.paid ? call.deposit === true ? "deposit" : "voucher" : result?.ok === true ? "answer" : "challenge";
561
+ const what = carrier || call?.carrier === true ? `top-up ${why}` : why;
562
+ this.warn(`${what} (cause ${cause}, ${this.now() - sent}ms, stage ${stage})`);
563
+ }
564
+ /**
565
+ * THE DEADLINE CUTS NOTHING ALREADY PAID. Before a payment goes out, the
566
+ * call's budget aborts it as always. Once one is out, aborting would lose
567
+ * the answer that records it (the SDK's channel and the ledger) while the
568
+ * server settles it anyway, so the call returns at its deadline and the
569
+ * request runs on here, up to {@link DETACHED_CEILING_MS}; the next call
570
+ * waits for it. `httpRequest`'s own timeout is the outer bound.
571
+ */
572
+ detachable(call, sent, run) {
573
+ return (input, init) => {
574
+ const caller = init?.signal ?? void 0;
575
+ const own = new AbortController();
576
+ const work = run(input, { ...init, signal: own.signal });
577
+ return new Promise((resolve, reject) => {
578
+ let timer;
579
+ const settle = () => {
580
+ this.timers.clearTimeout(timer);
581
+ caller?.removeEventListener("abort", onAbort);
582
+ };
583
+ const stop = (reason) => {
584
+ settle();
585
+ if (!call.paid) return own.abort(reason);
586
+ call.detached = true;
587
+ this.settling = true;
588
+ this.tail = this.finishDetached(call, sent, work, own);
589
+ reject(reason);
590
+ };
591
+ const onAbort = () => stop(caller?.reason);
592
+ const check = () => {
593
+ const left = call.until - this.now();
594
+ if (left > 0) timer = this.timers.setTimeout(check, left);
595
+ else {
596
+ call.expired = true;
597
+ stop(new DOMException("The routing call ran out of time.", "TimeoutError"));
598
+ }
599
+ };
600
+ check();
601
+ if (caller?.aborted === true) onAbort();
602
+ else caller?.addEventListener("abort", onAbort);
603
+ work.then(
604
+ (response) => {
605
+ settle();
606
+ resolve(call.detached === true ? response : bounded(response, caller, own));
607
+ },
608
+ (err) => {
609
+ settle();
610
+ reject(err);
611
+ }
612
+ );
613
+ });
614
+ };
615
+ }
616
+ /** The detached request's end: its answer read and dropped, its one line. */
617
+ async finishDetached(call, sent, work, own) {
618
+ const ceiling = this.timers.setTimeout(() => own.abort(), DETACHED_CEILING_MS);
619
+ ceiling.unref?.();
620
+ try {
621
+ const response = await work;
622
+ await response.arrayBuffer().catch(() => void 0);
623
+ const why = response.ok ? DEADLINE_AFTER_PAYMENT_SENT : PAYMENT_FAILED;
624
+ this.note(why, call, sent, `late http ${response.status}`);
625
+ } catch {
626
+ this.note(PAYMENT_FAILED, call, sent, own.signal.aborted ? "late ceiling" : "late network");
627
+ } finally {
628
+ this.timers.clearTimeout(ceiling);
629
+ this.settling = false;
630
+ }
631
+ }
632
+ /**
633
+ * ONE PAID CALL on the wallet's channel, inside the caller's budget. The
634
+ * server's 402 becomes the stock wrapper's first answer, so asking before
635
+ * the unlock adds no round trip.
636
+ */
637
+ async pay(url, options, until, calls, carrier = false, firstChallenge, limitAtomic) {
638
+ if (until - this.now() <= 0) throw new RouteSkipped("busy");
639
+ const call = {
640
+ host: new URL(url).host,
641
+ router: url,
642
+ ...carrier ? { carrier } : {},
643
+ until,
644
+ paid: false,
645
+ answered: false,
646
+ deposits: [],
647
+ ...limitAtomic !== void 0 ? { limitAtomic } : {}
648
+ };
649
+ calls.push(call);
650
+ const base = options.fetchImpl ?? this.deps.fetchImpl ?? fetch;
651
+ const hookBody = options.jsonBody;
652
+ const refreshHookBudget = (request) => {
653
+ if (hookBody === null || typeof hookBody !== "object" || !("budgetMs" in hookBody)) {
654
+ return request;
655
+ }
656
+ return new Request(request, {
657
+ body: JSON.stringify({
658
+ ...hookBody,
659
+ budgetMs: Math.min(5e3, Math.max(0, call.until - this.now()))
660
+ })
661
+ });
662
+ };
663
+ const askFirst = async (input, init) => {
664
+ const request = refreshHookBudget(new Request(input, init));
665
+ const signal = init?.signal ?? request.signal;
666
+ let asked = firstChallenge ?? await base(request.clone(), { signal });
667
+ firstChallenge = void 0;
668
+ call.answered = true;
669
+ if (asked.status !== 402) return asked;
670
+ try {
671
+ const challenge = asked.headers;
672
+ const quoted = this.paymentQuote(challenge);
673
+ if (quoted !== null) call.quoted = quoted;
674
+ if (quoted !== null && quoted > this.paymentCeiling()) {
675
+ throw new RouteSkipped(FEE_ABOVE_CEILING);
676
+ }
677
+ const refused = feeRefusal(
678
+ await this.deps.policy(),
679
+ call.host,
680
+ quoted ?? this.paymentCeiling()
681
+ );
682
+ if (refused !== null) throw new RouteSkipped(refused);
683
+ call.channel = this.channelFor(await this.signer(call));
684
+ if (until - this.now() <= 0) throw new RouteSkipped("busy");
685
+ } catch (err) {
686
+ if (err instanceof RouteSkipped) call.skipped = err.why;
687
+ throw err;
688
+ }
689
+ const watched = async (input2, init2) => {
690
+ const request2 = refreshHookBudget(new Request(input2, init2));
691
+ const paying = request2.headers.has("PAYMENT-SIGNATURE") && !signal.aborted;
692
+ if (!paying && asked !== void 0) {
693
+ const first = asked;
694
+ asked = void 0;
695
+ return first;
696
+ }
697
+ const deposit = paying ? call.deposits.find((d) => d.state === "signed") : void 0;
698
+ const previouslyPaid = call.paid;
699
+ if (paying) call.paid = true;
700
+ if (deposit !== void 0) await this.commitDeposit(deposit);
701
+ let response2;
702
+ try {
703
+ response2 = await base(request2, { signal });
704
+ } catch (error) {
705
+ if (error instanceof LocalSendBlocked) {
706
+ call.paid = previouslyPaid;
707
+ if (deposit !== void 0) await this.releaseDeposit(deposit);
708
+ }
709
+ throw error;
710
+ }
711
+ if (deposit !== void 0 && response2.status >= 400) await this.releaseDeposit(deposit);
712
+ else if (deposit !== void 0) deposit.state = "settled";
713
+ return response2;
714
+ };
715
+ return wrapFetchWithPayment(watched, call.channel.http)(request);
716
+ };
717
+ this.call = call;
718
+ this.last = call;
719
+ let response;
720
+ try {
721
+ response = call.result = await httpRequest(url, {
722
+ ...options,
723
+ // The outer bound: a deposit's budget, which a call without one never reaches.
724
+ timeoutMs: until + DEPOSIT_EXTRA_MS - this.now(),
725
+ fetchImpl: this.detachable(call, until - options.timeoutMs, askFirst)
726
+ });
727
+ } finally {
728
+ this.call = null;
729
+ await this.settleDeposits(call);
730
+ }
731
+ const answered = { answered: call.answered };
732
+ if (call.skipped !== void 0) {
733
+ throw new RouteSkipped(call.skipped, {
734
+ ...answered,
735
+ ...call.quoted !== void 0 ? { quotedAtomic: call.quoted } : {}
736
+ });
737
+ }
738
+ if (!response.ok && !call.answered && isUnreachable(response)) {
739
+ throw new RouteSkipped(PAYMENT_FAILED, { unreached: response });
740
+ }
741
+ if (!response.ok) {
742
+ const late = call.detached === true || call.paid && response.kind === "timeout";
743
+ throw new RouteSkipped(late ? DEADLINE_AFTER_PAYMENT_SENT : PAYMENT_FAILED, answered);
744
+ }
745
+ if (response.status === 402) {
746
+ const error = call.channel === void 0 ? void 0 : paymentError(call.channel, response);
747
+ throw new RouteSkipped(
748
+ error === CHANNEL_BUSY_ERROR ? CHANNEL_BUSY : paymentShortOfFunds(response) ? "wallet_low" : PAYMENT_FAILED,
749
+ answered
750
+ );
751
+ }
752
+ if (response.status >= 500) throw new RouteSkipped(PAYMENT_FAILED, answered);
753
+ if (call.paid && response.status < 400) {
754
+ this.report({ routing: { status: "ready", at: this.now() } });
755
+ if (!carrier) {
756
+ if (response.status >= 200 && response.status < 300) call.paidAnswer = true;
757
+ this.track(this.afterPaid(call));
758
+ }
759
+ }
760
+ return response;
761
+ }
762
+ /**
763
+ * EACH RESERVED DEPOSIT ENDS IN THE LEDGER. It is committed as it is sent,
764
+ * so a lost answer leaves it counted whether or not it landed (an over-count
765
+ * of a few cents, never an under-count), and the SDK resyncs the channel on
766
+ * the next call. An answered 4xx or 5xx or a local refusal before fetch gives
767
+ * exactly that exposure back. A deposit left uncommitted releases its
768
+ * reservation (`settleDeposits`).
769
+ */
770
+ async commitDeposit(d) {
771
+ await d.authorizer.commit(d.reservationId, d.amountAtomic, { nonce: d.key });
772
+ d.state = "sent";
773
+ }
774
+ async releaseDeposit(d) {
775
+ d.state = "refused";
776
+ const released = await releaseUnchargedExposure(this.deps.dataDir, d.key, {
777
+ now: () => this.now()
778
+ });
779
+ if (released === null) this.ledgerWarn(new Error("the refused deposit stays counted"));
780
+ }
781
+ async settleDeposits(call) {
782
+ for (const d of call.deposits.filter((x) => x.state === "signed")) {
783
+ await d.authorizer.release(d.reservationId).catch((err) => this.ledgerWarn(err));
784
+ }
785
+ }
786
+ ledgerWarn(err) {
787
+ this.warn(`spend ledger: ${err instanceof Error ? err.message : String(err)}`);
788
+ }
789
+ /** Refuse to pay this call: nothing is signed, and the call is not made. */
790
+ refuse(why) {
791
+ if (this.call !== null) this.call.skipped = why;
792
+ throw new RouteSkipped(why);
793
+ }
794
+ /**
795
+ * A ROUTING CALL'S DEPOSIT, NOT MADE: the top-up starts in its place, and
796
+ * the call skips with `deposit_deferred` for `send` to wait out. While a
797
+ * refused top-up holds the next off, its refusal (a low wallet, with its
798
+ * balance, or a failed payment) is the call's own reason, which the hook
799
+ * says once per session, and nothing is sent for it.
800
+ */
801
+ deferral(call) {
802
+ const failed = this.backedOff();
803
+ if (failed !== null) {
804
+ if (failed.quotedAtomic !== void 0) call.quoted = failed.quotedAtomic;
805
+ this.refuse(failed.why);
806
+ }
807
+ void this.topUp(call.router, this.channel.payer);
808
+ this.refuse(DEPOSIT_DEFERRED);
809
+ }
810
+ /** Whether the router at `router` is known to have no `warm` form. */
811
+ async warmAbsent(router) {
812
+ if (this.deps.modelLane) return true;
813
+ return await readRouterMemo(this.deps.dataDir, "warm-absent", router, this.now()) !== null;
814
+ }
815
+ /** `payer`'s top-up, unless one is in flight, a refused one holds it off,
816
+ * or the router has no `warm` form (the next paid call deposits instead). */
817
+ async topUpWhenDue(router, payer) {
818
+ if (this.topping !== null || this.backedOff() !== null) return;
819
+ if (await this.warmAbsent(router)) return;
820
+ await this.topUp(router, payer);
821
+ }
822
+ /** The one top-up in flight, joined or started. Never rejects. */
823
+ topUp(router, payer) {
824
+ if (this.topping !== null) return this.topping;
825
+ const flight = this.runTopUp(router, payer).catch(() => this.refusedTopUp(new RouteSkipped(PAYMENT_FAILED))).finally(() => {
826
+ if (this.topping === flight) this.topping = null;
827
+ });
828
+ this.topping = this.lastTopUp = flight;
829
+ this.track(flight);
830
+ return flight;
831
+ }
832
+ /**
833
+ * THE BACKGROUND TOP-UP: one `warm` call to the paid route, through the
834
+ * same turns, payment checks, spend ledger and detach as any call, on its
835
+ * own {@link TOP_UP_TIMEOUT_MS}. The stock SDK adds the deposit the channel
836
+ * needs to it ({@link deposit} sizes it), and the server answers in code and
837
+ * charges $0. ONE PROCESS ON THIS MACHINE TOPS UP A WALLET'S CHANNEL AT A
838
+ * TIME: it claims the wallet's `topping-up` memo and holds it until a
839
+ * deposit still out at the budget has its answer. The SDK reads the channel
840
+ * file as it builds the payment, after the claim, so a top-up another
841
+ * process just made is in it and is not made twice.
842
+ * A refusal prints its one routing-fee line and backs the next off
843
+ * ({@link TOP_UP_BACKOFF_MS}). A router that answers with
844
+ * anything but the `warm` answer has no form, and the `warm-absent` memo
845
+ * says so for {@link WARM_ABSENT_MS}.
846
+ */
847
+ async runTopUp(router, payer) {
848
+ const { dataDir } = this.deps;
849
+ const scope = payer.toLowerCase();
850
+ const token = await claimRouterMemo(dataDir, "topping-up", router, {
851
+ now: this.now(),
852
+ ttlMs: TOPPING_UP_MEMO_MS,
853
+ scope
854
+ });
855
+ if (token === null) return { status: "elsewhere" };
856
+ let landing = null;
857
+ try {
858
+ const calls = [];
859
+ const sent = this.now();
860
+ const until = sent + TOP_UP_TIMEOUT_MS;
861
+ const options = {
862
+ method: "POST",
863
+ timeoutMs: TOP_UP_TIMEOUT_MS,
864
+ blockRedirects: true,
865
+ jsonBody: buildWarmBody({
866
+ accepts: acceptsFor(false),
867
+ harness: this.deps.harness ?? "claude"
868
+ })
869
+ };
870
+ let response;
871
+ try {
872
+ response = await this.turn(
873
+ () => this.noted(sent, () => this.pay(router, options, until, calls, true), true),
874
+ until,
875
+ sent,
876
+ true
877
+ );
878
+ } catch (err) {
879
+ if (!(err instanceof RouteSkipped)) throw err;
880
+ if (err.unreached !== void 0) {
881
+ return this.refusedTopUp(new RouteSkipped(TOP_UP_UNAVAILABLE));
882
+ }
883
+ if (err.why === DEADLINE_AFTER_PAYMENT_SENT) {
884
+ landing = this.tail.then(() => void (this.toppedUp += settledIn(calls)));
885
+ }
886
+ return this.refusedTopUp(err);
887
+ }
888
+ this.toppedUp += settledIn(calls);
889
+ const status = response.ok ? response.status : 0;
890
+ if (status >= 200 && status < 300 && response.ok && isWarmAnswer(response.json)) {
891
+ this.failed = null;
892
+ return { status: "done" };
893
+ }
894
+ if (status === 429) {
895
+ this.note(TOP_UP_UNAVAILABLE, calls.at(-1) ?? null, sent, void 0, true);
896
+ return this.refusedTopUp(new RouteSkipped(TOP_UP_UNAVAILABLE, { answered: true }));
897
+ }
898
+ await writeRouterMemo(dataDir, "warm-absent", router, {
899
+ now: this.now(),
900
+ ttlMs: WARM_ABSENT_MS,
901
+ detail: `http ${status}`
902
+ });
903
+ this.warn(
904
+ `top-up: the router has no warm form (http ${status}), so a deposit rides the next paid call`
905
+ );
906
+ return { status: "absent" };
907
+ } finally {
908
+ const release = () => releaseRouterMemo(dataDir, "topping-up", router, { token, now: this.now(), scope });
909
+ if (landing === null) await release();
910
+ else this.track(landing.then(release));
911
+ }
912
+ }
913
+ /** A top-up not paid: the next one waits out the backoff, unless the cause
914
+ * was contention or a payment still out, which back off nothing. A wallet
915
+ * too low has the shorter schedule ({@link WALLET_LOW_BACKOFF_MS}); a
916
+ * refusal on the other schedule starts it from its first step, so a server
917
+ * error just after a funded wallet waits 30 s, not 10 min. */
918
+ refusedTopUp(skip) {
919
+ if (!NO_BACKOFF.has(skip.why)) {
920
+ const steps = skip.why === "wallet_low" ? WALLET_LOW_BACKOFF_MS : TOP_UP_BACKOFF_MS;
921
+ const count = this.failed?.steps === steps ? this.failed.count + 1 : 1;
922
+ const wait = steps[Math.min(count, steps.length) - 1];
923
+ this.failed = { skip, steps, count, until: this.now() + wait };
924
+ }
925
+ return { status: "refused", skip };
926
+ }
927
+ /** The last top-up's refusal while it still holds the next off; else null. */
928
+ backedOff() {
929
+ return this.failed !== null && this.now() < this.failed.until ? this.failed.skip : null;
930
+ }
931
+ /**
932
+ * A CHANNEL RUNNING LOW: after a paid call, the SDK's record (one small file
933
+ * read, no request) says whether the next fee would need a deposit, and if
934
+ * so the top-up starts now rather than on the prompt that would need it.
935
+ * The mark is the fixed quote, which a `warm` call can replenish. A dear
936
+ * answer's larger shortfall is funded inline on that answer's call.
937
+ */
938
+ async afterPaid(call) {
939
+ if (this.deps.modelLane) return;
940
+ const payer = call.channel?.payer;
941
+ if (payer === void 0) return;
942
+ const credit = await channelCredit(this.deps.dataDir, payer).catch(() => null);
943
+ if (credit === null || credit >= LEGACY_ROUTING_QUOTE_ATOMIC) return;
944
+ await this.topUpWhenDue(call.router, payer);
945
+ }
946
+ /** `flight` raced against the call's budget less the paid call's reserve:
947
+ * its outcome, or null, with the call's one line, when time ran out first. */
948
+ async waitForTopUp(flight, until, sent) {
949
+ let timer;
950
+ const deadline = new Promise((resolve) => {
951
+ timer = this.timers.setTimeout(
952
+ () => resolve(null),
953
+ Math.max(0, until - PAID_CALL_RESERVE_MS - this.now())
954
+ );
955
+ });
956
+ try {
957
+ const outcome = await Promise.race([flight, deadline]);
958
+ if (outcome === null) this.note(TOPPING_UP, null, sent, "top-up in flight");
959
+ return outcome;
960
+ } finally {
961
+ this.timers.clearTimeout(timer);
962
+ }
963
+ }
964
+ /** What settled top-ups deposited since a leg last said it, now said. */
965
+ takeToppedUp() {
966
+ const amount = this.toppedUp;
967
+ this.toppedUp = 0n;
968
+ return amount;
969
+ }
970
+ /** Work that runs on after its caller returns, for {@link idle}. */
971
+ track(work) {
972
+ this.pending = Promise.all([this.pending, work.catch(() => void 0)]).then(() => void 0);
973
+ }
974
+ /**
975
+ * THE SDK'S `depositStrategy`, called right before it signs a deposit.
976
+ *
977
+ * ORDINARY FEES USE THE TOP-UP'S `warm` CALL. The top-up starts instead
978
+ * ({@link deferral}), and the routing call waits for it in `send`. A quote
979
+ * above the fixed fee can need credit that `warm` would not replenish, so
980
+ * it deposits inline. A router without `warm` also deposits inline, with
981
+ * the longer budget.
982
+ *
983
+ * THE SIZE is the SDK's target and voucher deficit, with local liquidity
984
+ * bounds ({@link routingDepositAtomic}). The balance read happens only for a
985
+ * deposit; vouchers use channel credit. A wallet too low is `wallet_low`,
986
+ * with its balance; a spend the authorizer denies (the per-call limit, the
987
+ * daily budget, the creator allowlist) refuses it too, and nothing is paid.
988
+ */
989
+ async deposit(ctx) {
990
+ const call = this.call;
991
+ if (call === null) this.refuse("no_call");
992
+ if (call.deposit !== true) {
993
+ call.deposit = true;
994
+ if (call.carrier !== true) call.until += DEPOSIT_EXTRA_MS;
995
+ }
996
+ if (call.carrier !== true && (call.quoted ?? 0n) <= LEGACY_ROUTING_QUOTE_ATOMIC && !await this.warmAbsent(call.router)) {
997
+ this.deferral(call);
998
+ }
999
+ const policy = await this.deps.policy();
1000
+ const needed = BigInt(ctx.minimumDepositAmount);
1001
+ const inference = this.deps.modelLane && modelChannelLane(this.deps.modelLane.path) === "model-inference";
1002
+ const laneMax = inference && needed > MAX_CHANNEL_DEPOSIT_ATOMIC ? needed : MAX_CHANNEL_DEPOSIT_ATOMIC;
1003
+ const sdkMax = ctx.maxDeposit === void 0 ? laneMax : BigInt(ctx.maxDeposit);
1004
+ const max = sdkMax < laneMax ? sdkMax : laneMax;
1005
+ if (needed > max || needed > policy.maxAutoSpendAtomic) this.refuse("limit_below_deposit");
1006
+ const balance = await this.depositBalance(ctx.channelConfig.payer);
1007
+ if (balance < needed) this.refuse("wallet_low");
1008
+ const amount = routingDepositAtomic({
1009
+ suggestedAtomic: BigInt(ctx.depositAmount),
1010
+ neededAtomic: needed,
1011
+ balanceAtomic: balance,
1012
+ perCallAtomic: policy.maxAutoSpendAtomic,
1013
+ maxAtomic: max
1014
+ });
1015
+ if (amount === 0n) this.refuse("wallet_low");
1016
+ if (call.until - this.now() <= 0) this.refuse("busy");
1017
+ const authorizer = this.deps.authorizer(policy);
1018
+ const auth = await authorizer.authorize({
1019
+ mode: "automatic",
1020
+ amountAtomic: amount,
1021
+ creator: call.host
1022
+ });
1023
+ if (auth.decision !== "allow") {
1024
+ await authorizer.release(auth.reservationId);
1025
+ this.refuse(refusedWhy(auth.reason));
1026
+ }
1027
+ call.deposits.push({
1028
+ authorizer,
1029
+ reservationId: auth.reservationId,
1030
+ amountAtomic: amount,
1031
+ // A run's own channel is refunded at its end: its deposits are counted under the run.
1032
+ key: `${inference && this.deps.modelLane?.inferenceRun ? modelRunDepositKeys(this.deps.modelLane.origin, this.deps.modelLane.inferenceRun).prefix : ROUTING_DEPOSIT_KEY}${auth.reservationId ?? randomUUID()}`,
1033
+ state: "signed"
1034
+ });
1035
+ return amount;
1036
+ }
1037
+ /** A failed or late balance read sends no new deposit or authorization. The
1038
+ * call skips as `balance_unreadable`, a no-fault reason (fee.ts `NO_FAULT`):
1039
+ * nothing failed and nothing was paid. */
1040
+ async depositBalance(address2) {
1041
+ const left = (this.call?.until ?? 0) - this.now() - PAID_CALL_RESERVE_MS;
1042
+ if (left <= 0) this.refuse("busy");
1043
+ const timeoutMs = Math.min(RPC_TIMEOUT_MS, left);
1044
+ let timer;
1045
+ try {
1046
+ const balance = await Promise.race([
1047
+ this.deps.walletBalance(address2, timeoutMs),
1048
+ new Promise((resolve) => {
1049
+ timer = this.timers.setTimeout(() => resolve(null), timeoutMs);
1050
+ })
1051
+ ]);
1052
+ if (balance === null || balance < 0n) this.refuse("balance_unreadable");
1053
+ return balance;
1054
+ } catch {
1055
+ this.refuse("balance_unreadable");
1056
+ } finally {
1057
+ this.timers.clearTimeout(timer);
1058
+ }
1059
+ }
1060
+ /**
1061
+ * THE WALLET, unlocked without a prompt, for `call`. One that cannot be pays
1062
+ * nothing, and the call skips with WHY, as `classifyUnlockError` names it: a
1063
+ * definite reason (`no_wallet`, `passphrase_wrong`, ...), `keychain_locked`,
1064
+ * `unlock_timeout`, or `wallet_locked` for a failure nobody classified.
1065
+ *
1066
+ * A definite block the memo still believes skips before any unlock
1067
+ * ({@link freshBlock}). Otherwise the call joins the one unlock in flight
1068
+ * (or starts it) and waits for it only until {@link PAID_CALL_RESERVE_MS}
1069
+ * before its own budget ends, then skips with `unlock_timeout`. THE BUDGET
1070
+ * BOUNDS THE WAIT, NEVER THE READ
1071
+ * (B3): the unlock runs on, unaborted, its store read under no deadline, so
1072
+ * an OS unlock dialog stays up; its answer lands in the memo, and a signer
1073
+ * nobody was left waiting for is the next call's.
1074
+ *
1075
+ * The warned line is the classified error's message, which never carries a
1076
+ * store's output (S2).
1077
+ */
1078
+ async signer(call) {
1079
+ const blocked = await this.freshBlock();
1080
+ if (blocked !== null) throw new RouteSkipped(blocked.reason);
1081
+ let signer;
1082
+ const held = this.handoff;
1083
+ this.handoff = null;
1084
+ if (held !== null && await this.freshReady()) signer = held;
1085
+ else {
1086
+ this.waiters += 1;
1087
+ try {
1088
+ signer = await this.waitFor(this.unlock(), call.until - PAID_CALL_RESERVE_MS);
1089
+ } catch (err) {
1090
+ if (err instanceof RouteSkipped) throw err;
1091
+ this.warn(err instanceof Error ? err.message : String(err));
1092
+ throw new RouteSkipped(classifyUnlockError(err).reason);
1093
+ } finally {
1094
+ this.waiters -= 1;
1095
+ }
1096
+ }
1097
+ return toClientEvmSigner(
1098
+ {
1099
+ address: signer.address,
1100
+ // Nothing is signed outside a call: a detached request finishes and
1101
+ // starts no retry, whose answer nobody would read.
1102
+ signTypedData: (message) => this.call === null ? Promise.reject(new RouteSkipped("busy")) : signer.signTypedData(message)
1103
+ },
1104
+ this.deps.readContract !== void 0 ? { readContract: (args) => this.chainRead(this.deps.readContract, args) } : void 0
1105
+ );
1106
+ }
1107
+ /**
1108
+ * THE ONE UNLOCK IN FLIGHT, joined or started. Its settlement, whoever is
1109
+ * still waiting, sets the memo (with the stamp read as it started, so a
1110
+ * repair that lands mid-unlock still reads as a change) and reports the
1111
+ * sign verdict, and clears the flight. A success no call is waiting for is
1112
+ * kept for the next call. Nothing here can abort it.
1113
+ */
1114
+ unlock() {
1115
+ if (this.unlocking !== null) return this.unlocking;
1116
+ const stamp = this.stamp();
1117
+ const flight = (async () => {
1118
+ try {
1119
+ const signer = await this.deps.getSigner();
1120
+ const address2 = signer.address.toLowerCase();
1121
+ this.settle({ status: "ready" }, await stamp, address2);
1122
+ if (this.waiters === 0) this.handoff = signer;
1123
+ return signer;
1124
+ } catch (err) {
1125
+ this.settle(verdictOf(err), await stamp);
1126
+ throw err;
1127
+ } finally {
1128
+ this.unlocking = null;
1129
+ }
1130
+ })();
1131
+ flight.catch(() => void 0);
1132
+ this.unlocking = flight;
1133
+ return flight;
1134
+ }
1135
+ /** `unlock` raced against `until`: `unlock_timeout` when the budget ends
1136
+ * first, and the unlock is left running. */
1137
+ async waitFor(unlock, until) {
1138
+ let timer;
1139
+ const deadline = new Promise((_resolve, reject) => {
1140
+ timer = this.timers.setTimeout(
1141
+ () => reject(new RouteSkipped("unlock_timeout")),
1142
+ Math.max(0, until - this.now())
1143
+ );
1144
+ });
1145
+ try {
1146
+ return await Promise.race([unlock, deadline]);
1147
+ } finally {
1148
+ this.timers.clearTimeout(timer);
1149
+ }
1150
+ }
1151
+ /** The memo, set from a settled unlock, and its verdict reported. */
1152
+ settle(verdict, stamp, address2) {
1153
+ this.memo = {
1154
+ verdict,
1155
+ at: this.now(),
1156
+ stamp,
1157
+ ...address2 !== void 0 ? { address: address2 } : {}
1158
+ };
1159
+ this.report({ sign: signObservation(verdict), ...address2 !== void 0 ? { address: address2 } : {} });
1160
+ }
1161
+ /** The wallet's unlock stamp, or null when there is none to read. */
1162
+ async stamp() {
1163
+ try {
1164
+ return await this.deps.unlockStamp?.() ?? null;
1165
+ } catch {
1166
+ return null;
1167
+ }
1168
+ }
1169
+ /** Whether the memo was set within {@link SIGNER_RECHECK_MS} and nothing it
1170
+ * was read from has changed since. */
1171
+ async freshMemo(memo) {
1172
+ return this.now() - memo.at < SIGNER_RECHECK_MS && await this.stamp() === memo.stamp;
1173
+ }
1174
+ /** The memo's definite block while it is fresh; null otherwise, an unknown
1175
+ * verdict always (decision 16: only a definite block may skip anything). */
1176
+ async freshBlock() {
1177
+ const memo = this.memo;
1178
+ if (memo === null || !isDefiniteBlock(memo.verdict)) return null;
1179
+ return await this.freshMemo(memo) ? memo.verdict : null;
1180
+ }
1181
+ /** Whether the memo is a fresh ready, so a handed-off signer is still this wallet's. */
1182
+ async freshReady() {
1183
+ const memo = this.memo;
1184
+ return memo !== null && memo.verdict.status === "ready" && await this.freshMemo(memo);
1185
+ }
1186
+ /** A routing outcome, reported when it says something (see {@link ROUTING_SILENT}). */
1187
+ reportRouting(why) {
1188
+ if (ROUTING_SILENT.has(why)) return;
1189
+ const blocked = DEFINITE_UNLOCK.has(why) || ROUTING_BLOCKED.has(why);
1190
+ this.report({
1191
+ routing: { status: blocked ? "blocked" : "unknown", reason: why, at: this.now() }
1192
+ });
1193
+ }
1194
+ /** `deps.observe`, with only the parts whose status or reason changed; not
1195
+ * called at all on a repeat. An observer that throws is ignored. */
1196
+ report(u) {
1197
+ const out = {};
1198
+ if (u.sign !== void 0) {
1199
+ const key = `${u.sign.status}:${u.sign.reason ?? ""}`;
1200
+ if (key !== this.reported.sign) {
1201
+ this.reported.sign = key;
1202
+ out.sign = u.sign;
1203
+ if (u.address !== void 0) out.address = u.address;
1204
+ }
1205
+ }
1206
+ if (u.routing !== void 0) {
1207
+ const key = `${u.routing.status}:${u.routing.reason ?? ""}`;
1208
+ if (key !== this.reported.routing) {
1209
+ this.reported.routing = key;
1210
+ out.routing = u.routing;
1211
+ }
1212
+ }
1213
+ if (out.sign === void 0 && out.routing === void 0) return;
1214
+ try {
1215
+ this.deps.observe?.(out);
1216
+ } catch {
1217
+ }
1218
+ }
1219
+ /**
1220
+ * ONE SDK CHAIN READ, inside {@link RPC_TIMEOUT_MS} and the call's budget.
1221
+ * One that fails or times out skips the call before anything is sent.
1222
+ */
1223
+ async chainRead(read, args) {
1224
+ const left = (this.call?.until ?? Infinity) - this.now();
1225
+ if (left <= 0) this.refuse("busy");
1226
+ try {
1227
+ return await read(args, Math.min(RPC_TIMEOUT_MS, left));
1228
+ } catch (err) {
1229
+ this.warn(`chain read: ${err instanceof Error ? err.message.split("\n")[0] : String(err)}`);
1230
+ this.refuse("chain_unreadable");
1231
+ }
1232
+ }
1233
+ /**
1234
+ * The stock client uses the wallet's channel for this lane, or the run's
1235
+ * own inference channel. A replaced wallet gets its own folder, and the old
1236
+ * channel stays in the old one.
1237
+ */
1238
+ channelFor(signer) {
1239
+ const payer = signer.address.toLowerCase();
1240
+ if (this.channel !== null && this.channel.payer === payer) return this.channel;
1241
+ const lane = this.deps.modelLane;
1242
+ const modelLane = lane ? modelChannelLane(lane.path) : void 0;
1243
+ const runId = modelLane === "model-inference" ? lane?.inferenceRun : void 0;
1244
+ if (modelLane === "model-inference" && !runId)
1245
+ throw new Error("An inference payment needs its run");
1246
+ const salt = lane && modelLane ? runId ? modelInferenceRunScope(lane.origin, runId).salt : modelChannelScope(lane.origin, modelLane).salt : void 0;
1247
+ const dir = lane && modelLane ? runId ? modelInferenceRunDir(this.deps.dataDir, payer, lane.origin, runId) : modelChannelDir(this.deps.dataDir, payer, modelLane, lane.origin) : payerDir(this.deps.dataDir, payer);
1248
+ const scheme = new BatchSettlementEvmScheme(signer, {
1249
+ storage: new FileClientChannelStorage({ directory: dir }),
1250
+ ...salt ? { salt } : {},
1251
+ depositPolicy: { depositMultiplier: DEPOSIT_MULTIPLIER },
1252
+ depositStrategy: (ctx) => this.deposit(ctx)
1253
+ });
1254
+ const client = new x402Client().register("eip155:*", scheme).registerPolicy(
1255
+ lane ? (version, requirements) => {
1256
+ const offers = routingOffers(version, requirements);
1257
+ if (modelChannelLane(lane.path) === "model-routing") {
1258
+ const paid = this.routingChoice(offers);
1259
+ return paid ? [paid] : [];
1260
+ }
1261
+ const chosen = modelOffer(offers, this.paymentCeiling());
1262
+ return chosen && BigInt(chosen.amount) <= this.paymentCeiling() ? [chosen] : [];
1263
+ } : routingPolicy
1264
+ ).setSpendControls({
1265
+ maxAmountPerPayment: lane && modelChannelLane(lane.path) === "model-inference" ? "$1" : ROUTING_SPEND_CAP
1266
+ });
1267
+ this.channel = { payer, http: new x402HTTPClient(client) };
1268
+ return this.channel;
1269
+ }
1270
+ };
1271
+ function settledIn(calls) {
1272
+ return calls.flatMap((call) => call.deposits).filter((d) => d.state === "settled").reduce((sum, d) => sum + d.amountAtomic, 0n);
1273
+ }
1274
+ function bounded(response, caller, own) {
1275
+ if (caller === void 0 || response.body === null) return response;
1276
+ if (caller.aborted) own.abort(caller.reason);
1277
+ else caller.addEventListener("abort", () => own.abort(caller.reason), { once: true });
1278
+ const body = response.body.pipeThrough(new TransformStream(), { signal: own.signal });
1279
+ return new Response(body, {
1280
+ status: response.status,
1281
+ statusText: response.statusText,
1282
+ headers: response.headers
1283
+ });
1284
+ }
1285
+ function verdictOf(err) {
1286
+ const c = classifyUnlockError(err);
1287
+ if (c.definite && c.reason !== "wallet_locked" && c.reason !== "unlock_timeout") {
1288
+ const r = WALLET_REASONS[c.reason];
1289
+ return { status: "blocked", reason: c.reason, detail: r.reason, fix: r.fix };
1290
+ }
1291
+ return {
1292
+ status: "unknown",
1293
+ reason: c.reason,
1294
+ detail: UNKNOWN_DETAIL[c.reason] ?? UNKNOWN_DETAIL["check_failed"]
1295
+ };
1296
+ }
1297
+ function signObservation(v) {
1298
+ if (v.status === "ready") {
1299
+ return { status: "ready", ...v.source !== void 0 ? { source: v.source } : {} };
1300
+ }
1301
+ if (v.status === "blocked") {
1302
+ return { status: "blocked", reason: v.reason, detail: v.detail, fix: v.fix };
1303
+ }
1304
+ return { status: "unknown", reason: v.reason, detail: v.detail };
1305
+ }
1306
+ function paymentError(channel2, response) {
1307
+ try {
1308
+ return reasonCode(
1309
+ channel2.http.getPaymentRequiredResponse((name) => response.header(name), response.json).error
1310
+ );
1311
+ } catch {
1312
+ return void 0;
1313
+ }
1314
+ }
1315
+
1316
+ // src/router/model-refund.ts
1317
+ import { lstat, mkdir, opendir, readdir, readFile, rm } from "node:fs/promises";
1318
+ import { basename, dirname, join } from "node:path";
1319
+ var REFUND_TIMEOUT_MS = 2e4;
1320
+ var REFUND_RETRY_MS = 3e5;
1321
+ var CORRECTION_RETRY_MS = 2e3;
1322
+ var PRE_BROADCAST_ERRORS = /* @__PURE__ */ new Set([
1323
+ "invalid_batch_settlement_evm_cumulative_amount_mismatch",
1324
+ "invalid_batch_settlement_evm_cumulative_below_claimed",
1325
+ "invalid_batch_settlement_evm_refund_no_balance"
1326
+ ]);
1327
+ var JOURNAL_BYTES = 256 * 1024;
1328
+ var AUTHORIZATION_STATE = parseAbi([
1329
+ "function authorizationState(address authorizer, bytes32 nonce) view returns (bool)"
1330
+ ]);
1331
+ var address = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/).transform(toHex);
1332
+ var bytes32 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).transform(toHex);
1333
+ var uint = external_exports.string().regex(/^\d{1,78}$/);
1334
+ var network = external_exports.string().regex(/^eip155:[1-9]\d{0,14}$/);
1335
+ var channel = external_exports.object({
1336
+ payer: address,
1337
+ payerAuthorizer: address,
1338
+ receiver: address,
1339
+ receiverAuthorizer: address,
1340
+ token: address,
1341
+ withdrawDelay: external_exports.number().int().nonnegative(),
1342
+ salt: bytes32
1343
+ });
1344
+ var offer = external_exports.object({
1345
+ scheme: external_exports.literal("batch-settlement"),
1346
+ network,
1347
+ asset: address,
1348
+ payTo: address,
1349
+ amount: uint,
1350
+ extra: external_exports.object({
1351
+ receiverAuthorizer: address.refine((value) => value !== zeroAddress),
1352
+ withdrawDelay: external_exports.number().int().nonnegative()
1353
+ })
1354
+ });
1355
+ var payment = external_exports.object({
1356
+ x402Version: external_exports.literal(2),
1357
+ accepted: offer,
1358
+ payload: external_exports.object({
1359
+ type: external_exports.enum(["deposit", "voucher", "refund"]),
1360
+ channelConfig: channel,
1361
+ voucher: external_exports.object({ channelId: bytes32 }),
1362
+ amount: external_exports.unknown().optional(),
1363
+ deposit: external_exports.unknown().optional()
1364
+ })
1365
+ });
1366
+ var funding = external_exports.object({ nonce: bytes32, validBefore: uint });
1367
+ var receipt = external_exports.object({
1368
+ amountAtomic: uint.refine((value) => BigInt(value) > 0n),
1369
+ transaction: bytes32
1370
+ });
1371
+ var record = external_exports.object({
1372
+ v: external_exports.literal(1),
1373
+ runId: external_exports.string().min(1),
1374
+ url: external_exports.string(),
1375
+ network,
1376
+ channel,
1377
+ channelId: bytes32,
1378
+ funding: external_exports.array(funding),
1379
+ retryAfter: external_exports.number().int().nonnegative(),
1380
+ sealed: external_exports.boolean(),
1381
+ /** Set only on the one-time recovery of an old shared channel (slot 0 or 1), never on a run's. */
1382
+ legacy: external_exports.union([external_exports.literal(0), external_exports.literal(1)]).optional(),
1383
+ submitted: receipt.extend({ balance: uint }).optional(),
1384
+ state: external_exports.enum(["pending", "no_balance", "closed", "refunded"])
1385
+ });
1386
+ var settlement = external_exports.object({
1387
+ success: external_exports.literal(true),
1388
+ network,
1389
+ payer: address,
1390
+ amount: uint,
1391
+ transaction: bytes32,
1392
+ extra: external_exports.object({
1393
+ channelState: external_exports.object({ channelId: bytes32, balance: uint, totalClaimed: uint })
1394
+ })
1395
+ });
1396
+ function toHex(value) {
1397
+ return value.toLowerCase();
1398
+ }
1399
+ function exactEndpoint(origin, rawUrl) {
1400
+ const url = new URL(rawUrl);
1401
+ if (url.origin !== origin || url.username || url.password || url.search || url.hash || url.pathname !== "/api/model-proxy/messages") {
1402
+ throw new Error("Invalid inference refund URL");
1403
+ }
1404
+ return url.href;
1405
+ }
1406
+ function refundDir(dataDir) {
1407
+ return join(dataDir, "model-refunds");
1408
+ }
1409
+ function recordPath(dataDir, origin, runId) {
1410
+ return join(refundDir(dataDir), modelInferenceRunScope(origin, runId).id + ".json");
1411
+ }
1412
+ function notePath(path) {
1413
+ return path.replace(/\.json$/, ".note");
1414
+ }
1415
+ async function writeNote(path, why) {
1416
+ if (await readNote(path) === why) return;
1417
+ await writePrivate(notePath(path), why.slice(0, 200));
1418
+ }
1419
+ async function readNote(path) {
1420
+ const raw = await readFile(notePath(path), "utf8").catch(() => void 0);
1421
+ return raw === void 0 || raw.length > 200 ? void 0 : raw;
1422
+ }
1423
+ var JOB_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1424
+ function modelRefundRunLock(dataDir, origin, runId) {
1425
+ const name = JOB_ID.test(runId) ? runId.toLowerCase() : modelInferenceRunScope(origin, runId).id;
1426
+ return join(dataDir, "model-jobs", `${name}.refund`);
1427
+ }
1428
+ async function readRecord(path) {
1429
+ const raw = await readJsonFile(path, JOURNAL_BYTES);
1430
+ if (raw === null) {
1431
+ const info = await lstat(path).catch((err) => {
1432
+ if (err.code !== "ENOENT") throw err;
1433
+ return null;
1434
+ });
1435
+ if (info === null) return null;
1436
+ }
1437
+ const value = record.parse(raw);
1438
+ const origin = new URL(value.url).origin;
1439
+ if (value.url !== exactEndpoint(origin, value.url) || basename(path) !== basename(recordPath("", origin, value.runId)) || value.channel.salt !== (value.legacy === void 0 ? modelInferenceRunScope(origin, value.runId).salt : legacySharedInferenceChannel(origin, value.legacy).salt) || computeChannelId(value.channel, value.network) !== value.channelId || value.state === "refunded" && !value.submitted) {
1440
+ throw new Error("Invalid inference refund record");
1441
+ }
1442
+ return value;
1443
+ }
1444
+ async function writeRecord(path, value) {
1445
+ const json = JSON.stringify(value);
1446
+ if (Buffer.byteLength(json) > JOURNAL_BYTES) throw new Error("Inference refund record too large");
1447
+ await writePrivate(path, json);
1448
+ }
1449
+ function refundResult(value) {
1450
+ if (value === null) return { state: "none" };
1451
+ if (value.state === "refunded" && value.submitted) {
1452
+ const { amountAtomic, transaction } = value.submitted;
1453
+ return { state: "refunded", amountAtomic, transaction };
1454
+ }
1455
+ return { state: value.state === "refunded" ? "pending" : value.state };
1456
+ }
1457
+ async function readModelRefundResult(dataDir, origin, runId) {
1458
+ try {
1459
+ return refundResult(await readRecord(recordPath(dataDir, origin, runId)));
1460
+ } catch {
1461
+ return { state: "pending" };
1462
+ }
1463
+ }
1464
+ async function* recordFiles(dataDir) {
1465
+ const dir = refundDir(dataDir);
1466
+ const entries = await opendir(dir).catch((err) => {
1467
+ if (err.code !== "ENOENT") throw err;
1468
+ return null;
1469
+ });
1470
+ if (entries === null) return;
1471
+ for await (const entry of entries) {
1472
+ if (entry.isFile() && /^[a-f0-9]{64}\.json$/.test(entry.name)) yield join(dir, entry.name);
1473
+ }
1474
+ }
1475
+ async function hasModelRefundRecords(dataDir) {
1476
+ for await (const path of recordFiles(dataDir)) {
1477
+ if ((await readRecord(path).catch(() => null))?.state === "pending") return true;
1478
+ }
1479
+ return false;
1480
+ }
1481
+ async function readModelRefundSummary(dataDir, origin, wallet) {
1482
+ const canonicalOrigin = new URL(origin).origin;
1483
+ let pending = 0;
1484
+ let refunded = 0n;
1485
+ const elsewhere = /* @__PURE__ */ new Map();
1486
+ for await (const path of recordFiles(dataDir)) {
1487
+ const candidate = await readRecord(path).catch(() => null);
1488
+ if (candidate === null || candidate.channel.payer !== wallet.toLowerCase()) continue;
1489
+ const recorded = new URL(candidate.url).origin;
1490
+ if (recorded !== canonicalOrigin) {
1491
+ if (candidate.state === "pending")
1492
+ elsewhere.set(recorded, (elsewhere.get(recorded) ?? 0) + 1);
1493
+ continue;
1494
+ }
1495
+ if (candidate.state === "pending") pending++;
1496
+ if (candidate.state === "refunded" && candidate.submitted) {
1497
+ refunded += BigInt(candidate.submitted.amountAtomic);
1498
+ }
1499
+ }
1500
+ return {
1501
+ pending,
1502
+ refundedAtomic: refunded.toString(),
1503
+ pendingElsewhere: [...elsewhere].map(([recorded, count]) => ({ origin: recorded, pending: count })).sort((a, b) => a.origin.localeCompare(b.origin))
1504
+ };
1505
+ }
1506
+ var NO_MODEL_REFUNDS = {
1507
+ pending: 0,
1508
+ refundedAtomic: "0",
1509
+ pendingElsewhere: []
1510
+ };
1511
+ function refundsElsewhereLines(summary) {
1512
+ return summary.pendingElsewhere.map(
1513
+ ({ origin, pending }) => `${pending} subagent channel refunds pending at ${origin}, retried only while that is the configured router`
1514
+ );
1515
+ }
1516
+ function verifyOffer(value, config) {
1517
+ if (value.asset !== config.token || value.payTo !== config.receiver || value.extra.receiverAuthorizer !== config.receiverAuthorizer || value.extra.withdrawDelay !== config.withdrawDelay) {
1518
+ throw new Error("Inference refund channel terms changed");
1519
+ }
1520
+ }
1521
+ function readChallenge(response, saved) {
1522
+ const required = response.headers.get("payment-required");
1523
+ if (response.status !== 402 || required === null) {
1524
+ throw new Error("Router did not provide an inference refund challenge");
1525
+ }
1526
+ const parsed = external_exports.object({ x402Version: external_exports.literal(2), accepts: external_exports.tuple([offer]), error: external_exports.string().optional() }).parse(decodePaymentRequiredHeader(required));
1527
+ const [quote] = parsed.accepts;
1528
+ if (BigInt(quote.amount) !== 0n || saved && quote.network !== saved.network) {
1529
+ throw new Error("Router provided an incompatible inference refund challenge");
1530
+ }
1531
+ if (saved) verifyOffer(quote, saved.channel);
1532
+ return { quote, error: parsed.error };
1533
+ }
1534
+ function verifyChallenge(response, saved) {
1535
+ return readChallenge(response, saved).error;
1536
+ }
1537
+ function fundingAttempt(raw, channelId) {
1538
+ const { validBefore, salt } = external_exports.object({
1539
+ authorization: external_exports.object({
1540
+ erc3009Authorization: external_exports.object({
1541
+ validBefore: uint,
1542
+ salt: bytes32
1543
+ })
1544
+ })
1545
+ }).parse(raw).authorization.erc3009Authorization;
1546
+ const nonce = keccak256(
1547
+ encodeAbiParameters([{ type: "bytes32" }, { type: "uint256" }], [channelId, BigInt(salt)])
1548
+ );
1549
+ return { validBefore, nonce };
1550
+ }
1551
+ function boundedSignal(ms, signal) {
1552
+ const timeout = AbortSignal.timeout(ms);
1553
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
1554
+ }
1555
+ var ModelRefundJournal = class {
1556
+ constructor(dataDir, origin, deps) {
1557
+ this.dataDir = dataDir;
1558
+ this.deps = deps;
1559
+ this.origin = new URL(origin).origin;
1560
+ this.fetchImpl = deps.fetchImpl ?? fetch;
1561
+ }
1562
+ dataDir;
1563
+ deps;
1564
+ origin;
1565
+ fetchImpl;
1566
+ /** Must run under the worker's lifetime lock before forwarding the payment. */
1567
+ async record(runId, url, header, signal) {
1568
+ const endpoint = exactEndpoint(this.origin, url);
1569
+ const signed = payment.parse(decodePaymentSignatureHeader(header));
1570
+ const config = signed.payload.channelConfig;
1571
+ const channelId = computeChannelId(config, signed.accepted.network);
1572
+ verifyOffer(signed.accepted, config);
1573
+ const signer = await this.deps.getSigner();
1574
+ if (BigInt(signed.accepted.amount) === 0n || signed.payload.type === "refund" || config.salt !== modelInferenceRunScope(this.origin, runId).salt || config.payer !== signer.address.toLowerCase() || config.payerAuthorizer !== config.payer || signed.payload.voucher.channelId !== channelId) {
1575
+ throw new Error("Payment does not belong to this inference run");
1576
+ }
1577
+ signal?.throwIfAborted();
1578
+ const path = recordPath(this.dataDir, this.origin, runId);
1579
+ const previous = await readRecord(path);
1580
+ if (previous !== null && (previous.state !== "pending" || previous.sealed || previous.channelId !== channelId || previous.url !== endpoint || previous.network !== signed.accepted.network)) {
1581
+ throw new Error("Inference refund record is already sealed or payment terms changed");
1582
+ }
1583
+ if (signed.payload.type === "voucher" && previous !== null) return;
1584
+ const next = previous ?? {
1585
+ v: 1,
1586
+ runId,
1587
+ url: endpoint,
1588
+ network: signed.accepted.network,
1589
+ channel: config,
1590
+ channelId,
1591
+ funding: [],
1592
+ retryAfter: 0,
1593
+ sealed: false,
1594
+ state: "pending"
1595
+ };
1596
+ if (signed.payload.type === "deposit") {
1597
+ const attempt = fundingAttempt(signed.payload.deposit, channelId);
1598
+ if (next.funding.some((value) => value.nonce === attempt.nonce)) return;
1599
+ next.funding.push(attempt);
1600
+ }
1601
+ signal?.throwIfAborted();
1602
+ await writeRecord(path, next);
1603
+ }
1604
+ /**
1605
+ * THE ONE-TIME RECOVERY of what earlier dev builds left in the two old shared inference
1606
+ * channels: each channel that still holds credit gets a journal record (marked `legacy`,
1607
+ * sealed, no deposit to wait for) and goes through the same refund as a run's channel, one
1608
+ * at a time, under its own lock. A channel with nothing left, or one already refunded,
1609
+ * returns nothing, so a second run finds nothing. Never a background pass.
1610
+ */
1611
+ async reclaimSharedCredit(signal) {
1612
+ const deadline = boundedSignal(REFUND_TIMEOUT_MS * 3, signal);
1613
+ const signer = await this.deps.getSigner();
1614
+ const chainId = await this.deps.readChainId?.(RPC_TIMEOUT_MS);
1615
+ const found = [];
1616
+ if (chainId === void 0) return found;
1617
+ const network2 = `eip155:${chainId}`;
1618
+ for (const slot of [0, 1]) {
1619
+ const shared = legacySharedInferenceChannel(this.origin, slot);
1620
+ const directory = join(payerDir(this.dataDir, signer.address), "model-inference", shared.id);
1621
+ const storage = new FileClientChannelStorage({ directory });
1622
+ for (const name of await readdir(join(directory, "client")).catch(() => [])) {
1623
+ const channelId = /^(0x[0-9a-f]{64})\.json$/.exec(name)?.[1];
1624
+ const stored = channelId === void 0 ? void 0 : await storage.get(channelId).catch(() => void 0);
1625
+ if (channelId === void 0 || stored === void 0) continue;
1626
+ const left = BigInt(stored.balance ?? "0") - BigInt(stored.chargedCumulativeAmount ?? "0");
1627
+ const runId = `legacy-${slot}-${channelId}`;
1628
+ const path = recordPath(this.dataDir, this.origin, runId);
1629
+ let existing = await readRecord(path).catch(() => null);
1630
+ if (existing === null && left <= 0n) continue;
1631
+ if (existing !== null && existing.state !== "pending") continue;
1632
+ if (existing === null) {
1633
+ const url = new URL("/api/model-proxy/messages", this.origin).href;
1634
+ const challenge = await this.fetchImpl(url, {
1635
+ method: "GET",
1636
+ redirect: "error",
1637
+ signal: deadline
1638
+ });
1639
+ const { quote } = await Promise.resolve(readChallenge(challenge)).finally(
1640
+ () => void challenge.body?.cancel().catch(() => void 0)
1641
+ );
1642
+ const config = {
1643
+ payer: signer.address.toLowerCase(),
1644
+ payerAuthorizer: signer.address.toLowerCase(),
1645
+ receiver: quote.payTo,
1646
+ receiverAuthorizer: quote.extra.receiverAuthorizer,
1647
+ token: quote.asset,
1648
+ withdrawDelay: quote.extra.withdrawDelay,
1649
+ salt: shared.salt
1650
+ };
1651
+ if (quote.network !== network2 || computeChannelId(config, network2) !== channelId)
1652
+ continue;
1653
+ existing = {
1654
+ v: 1,
1655
+ runId,
1656
+ url,
1657
+ network: network2,
1658
+ channel: config,
1659
+ channelId,
1660
+ funding: [],
1661
+ retryAfter: 0,
1662
+ sealed: true,
1663
+ legacy: slot,
1664
+ state: "pending"
1665
+ };
1666
+ await writeRecord(path, existing);
1667
+ }
1668
+ const result = await this.closeLocked(runId, deadline);
1669
+ if (result.state !== "none") found.push({ slot, channelId, result });
1670
+ }
1671
+ }
1672
+ return found;
1673
+ }
1674
+ async close(runId, signal) {
1675
+ return this.closeLocked(runId, boundedSignal(REFUND_TIMEOUT_MS, signal));
1676
+ }
1677
+ async recoverPending(signal) {
1678
+ const deadline = boundedSignal(REFUND_TIMEOUT_MS, signal);
1679
+ for await (const path of recordFiles(this.dataDir)) {
1680
+ if (deadline.aborted) return;
1681
+ const saved = await readRecord(path).catch(() => null);
1682
+ if (saved?.state === "pending" && saved.legacy === void 0 && new URL(saved.url).origin === this.origin) {
1683
+ await this.closeLocked(saved.runId, deadline);
1684
+ }
1685
+ }
1686
+ }
1687
+ async closeLocked(runId, signal) {
1688
+ const path = recordPath(this.dataDir, this.origin, runId);
1689
+ try {
1690
+ const lock = modelRefundRunLock(this.dataDir, this.origin, runId);
1691
+ await mkdir(dirname(lock), { recursive: true, mode: 448 });
1692
+ return await withHeldLock(
1693
+ lock,
1694
+ async () => {
1695
+ const saved = await readRecord(path);
1696
+ if (!saved || saved.state !== "pending") return refundResult(saved);
1697
+ if (!saved.sealed) {
1698
+ saved.sealed = true;
1699
+ await writeRecord(path, saved);
1700
+ }
1701
+ return this.refund(path, saved, signal);
1702
+ },
1703
+ { timeoutMs: 150, retryMs: 25, signal }
1704
+ );
1705
+ } catch (error) {
1706
+ await this.noteFailure(path, error).catch(() => void 0);
1707
+ return readModelRefundResult(this.dataDir, this.origin, runId);
1708
+ }
1709
+ }
1710
+ /** Records why a pending refund was left pending, once per reason. */
1711
+ async wait(path, why) {
1712
+ await writeNote(path, why).catch(() => void 0);
1713
+ return { state: "pending" };
1714
+ }
1715
+ /** Only the side note is written, so a session that never held the lock cannot touch the record. */
1716
+ async noteFailure(path, error) {
1717
+ if (error instanceof LockTimeoutError) return;
1718
+ const why = `failed: ${(error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").slice(0, 150)}`;
1719
+ const saved = await readRecord(path);
1720
+ if (saved && saved.state === "pending") await writeNote(path, why);
1721
+ }
1722
+ async refund(path, saved, signal) {
1723
+ const readContract = this.deps.readContract;
1724
+ if (!readContract || !this.deps.readChainId) return this.wait(path, "no chain reads");
1725
+ const signer = await this.deps.getSigner();
1726
+ if (saved.channel.payer !== signer.address.toLowerCase())
1727
+ return this.wait(path, "another wallet");
1728
+ if (saved.network !== `eip155:${await this.deps.readChainId(RPC_TIMEOUT_MS)}`) {
1729
+ return this.wait(path, "another chain");
1730
+ }
1731
+ const clientSigner = toClientEvmSigner(
1732
+ {
1733
+ address: signer.address,
1734
+ signTypedData: (message) => {
1735
+ signal.throwIfAborted();
1736
+ return signer.signTypedData(message);
1737
+ }
1738
+ },
1739
+ {
1740
+ readContract: (args) => {
1741
+ signal.throwIfAborted();
1742
+ return readContract(args, RPC_TIMEOUT_MS);
1743
+ }
1744
+ }
1745
+ );
1746
+ if (!await this.fundingSettled(saved, readContract, signal))
1747
+ return this.wait(path, "deposit not settled");
1748
+ const [balance, totalClaimed] = await readChannelBalanceAndTotalClaimed(
1749
+ clientSigner,
1750
+ saved.channelId
1751
+ );
1752
+ if (balance === totalClaimed) return this.finish(path, saved, balance);
1753
+ if (balance < totalClaimed || saved.submitted || saved.retryAfter > this.now()) {
1754
+ return this.wait(path, "waiting to retry");
1755
+ }
1756
+ const storage = new FileClientChannelStorage({
1757
+ directory: saved.legacy === void 0 ? modelInferenceRunDir(this.dataDir, signer.address, this.origin, saved.runId) : join(
1758
+ payerDir(this.dataDir, signer.address),
1759
+ "model-inference",
1760
+ legacySharedInferenceChannel(this.origin, saved.legacy).id
1761
+ )
1762
+ });
1763
+ const scheme = new BatchSettlementEvmScheme(clientSigner, {
1764
+ storage,
1765
+ salt: saved.channel.salt
1766
+ });
1767
+ await scheme.refund(saved.url, {
1768
+ fetch: async (url, init) => {
1769
+ if (url !== saved.url || init?.method !== "GET") {
1770
+ throw new Error("Invalid inference refund request");
1771
+ }
1772
+ signal.throwIfAborted();
1773
+ const headers = new Headers(init.headers);
1774
+ const header = headers.get("payment-signature");
1775
+ if (header !== null) {
1776
+ const signed = payment.parse(decodePaymentSignatureHeader(header));
1777
+ verifyOffer(signed.accepted, saved.channel);
1778
+ if (signed.accepted.network !== saved.network || BigInt(signed.accepted.amount) !== 0n || signed.payload.type !== "refund" || signed.payload.amount !== void 0 || signed.payload.voucher.channelId !== saved.channelId || computeChannelId(signed.payload.channelConfig, saved.network) !== saved.channelId) {
1779
+ throw new Error("Invalid signed inference refund request");
1780
+ }
1781
+ headers.set(
1782
+ SIWX_HEADER,
1783
+ await buildSiwxHeader(signer, {
1784
+ baseUrl: this.origin,
1785
+ chainId: SIWX_CHAIN_ID,
1786
+ ttlMs: REFUND_RETRY_MS
1787
+ })
1788
+ );
1789
+ signal.throwIfAborted();
1790
+ saved.retryAfter = this.now() + REFUND_RETRY_MS;
1791
+ await writeRecord(path, saved);
1792
+ }
1793
+ const response = await this.fetchImpl(saved.url, {
1794
+ method: "GET",
1795
+ headers,
1796
+ redirect: "error",
1797
+ signal
1798
+ });
1799
+ try {
1800
+ if (response.status === 402) {
1801
+ const code = verifyChallenge(response, saved);
1802
+ if (header !== null && code !== void 0 && PRE_BROADCAST_ERRORS.has(code) && !response.headers.has("payment-response")) {
1803
+ saved.retryAfter = this.now() + CORRECTION_RETRY_MS;
1804
+ await writeRecord(path, saved);
1805
+ }
1806
+ }
1807
+ if (header !== null && response.ok) {
1808
+ const raw = response.headers.get("payment-response");
1809
+ if (raw === null) throw new Error("Missing inference refund settlement");
1810
+ const result = settlement.parse(decodePaymentResponseHeader(raw));
1811
+ const state = result.extra.channelState;
1812
+ if (result.network !== saved.network || result.payer !== saved.channel.payer || state.channelId !== saved.channelId || state.balance !== state.totalClaimed || BigInt(result.amount) <= 0n || BigInt(result.amount) !== balance - BigInt(state.balance)) {
1813
+ throw new Error("Invalid inference refund settlement");
1814
+ }
1815
+ saved.submitted = {
1816
+ amountAtomic: result.amount,
1817
+ transaction: result.transaction,
1818
+ balance: state.balance
1819
+ };
1820
+ await writeRecord(path, saved);
1821
+ }
1822
+ return response;
1823
+ } finally {
1824
+ void response.body?.cancel().catch(() => void 0);
1825
+ }
1826
+ }
1827
+ });
1828
+ if (!saved.submitted) return this.wait(path, "no refund receipt");
1829
+ const [after, claimed] = await readChannelBalanceAndTotalClaimed(clientSigner, saved.channelId);
1830
+ return after === claimed ? this.finish(path, saved, after) : { state: "pending" };
1831
+ }
1832
+ async fundingSettled(saved, readContract, signal) {
1833
+ let timestamp;
1834
+ for (const { nonce, validBefore } of saved.funding) {
1835
+ signal.throwIfAborted();
1836
+ if (await readContract(
1837
+ {
1838
+ address: saved.channel.token,
1839
+ abi: AUTHORIZATION_STATE,
1840
+ functionName: "authorizationState",
1841
+ args: [saved.channel.payer, nonce]
1842
+ },
1843
+ RPC_TIMEOUT_MS
1844
+ ) === true) {
1845
+ continue;
1846
+ }
1847
+ timestamp ??= await this.deps.readBlockTimestamp?.(RPC_TIMEOUT_MS);
1848
+ if (timestamp === void 0 || timestamp <= BigInt(validBefore)) return false;
1849
+ }
1850
+ return true;
1851
+ }
1852
+ async finish(path, saved, balance) {
1853
+ if (saved.submitted && BigInt(saved.submitted.balance) === balance) {
1854
+ const credited = await creditRefundedExposure(
1855
+ this.dataDir,
1856
+ modelRunDepositKeys(new URL(saved.url).origin, saved.runId),
1857
+ BigInt(saved.submitted.amountAtomic),
1858
+ { now: () => this.now() }
1859
+ );
1860
+ if (credited === null) return { state: "pending" };
1861
+ saved.state = "refunded";
1862
+ } else {
1863
+ saved.state = saved.retryAfter > 0 ? "closed" : "no_balance";
1864
+ }
1865
+ await writeRecord(path, saved);
1866
+ await rm(notePath(path), { force: true }).catch(() => void 0);
1867
+ return refundResult(saved);
1868
+ }
1869
+ now() {
1870
+ return (this.deps.now ?? Date.now)();
1871
+ }
1872
+ };
1873
+
1874
+ export {
1875
+ LocalSendBlocked,
1876
+ DETACHED_CEILING_MS,
1877
+ TOP_UP_TIMEOUT_MS,
1878
+ chainReader,
1879
+ chainRefundReads,
1880
+ RoutingPayer,
1881
+ modelRefundRunLock,
1882
+ readModelRefundResult,
1883
+ hasModelRefundRecords,
1884
+ readModelRefundSummary,
1885
+ NO_MODEL_REFUNDS,
1886
+ refundsElsewhereLines,
1887
+ ModelRefundJournal
1888
+ };
1889
+ //# sourceMappingURL=chunk-V6GIVALQ.js.map