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.
- package/NOTICE.md +110 -0
- package/README.md +87 -81
- package/dist/{_esm-BIN7VY2L.js → _esm-2KST7HQ7.js} +7 -7
- package/dist/alive-5TV22PNF.js +51 -0
- package/dist/auth-XI7BJFLW.js +47 -0
- package/dist/{auto-update-Y24UL56V.js → auto-update-7L24KDWA.js} +4 -5
- package/dist/balance-DFHC6XEU.js +71 -0
- package/dist/{ccip-DHDFKTQV.js → ccip-HOW3DZYF.js} +4 -4
- package/dist/chunk-24XKUN2S.js +202 -0
- package/dist/chunk-24XKUN2S.js.map +1 -0
- package/dist/chunk-2L7TDGLV.js +56 -0
- package/dist/chunk-2L7TDGLV.js.map +1 -0
- package/dist/{chunk-C2Q76BVM.js → chunk-2U7H35IP.js} +29 -7
- package/dist/chunk-2U7H35IP.js.map +1 -0
- package/dist/chunk-2W4DQQUU.js +176 -0
- package/dist/chunk-2W4DQQUU.js.map +1 -0
- package/dist/{chunk-LRW6S53P.js → chunk-34SAECKZ.js} +35 -11
- package/dist/chunk-34SAECKZ.js.map +1 -0
- package/dist/{chunk-2I4QTOLB.js → chunk-3MZ7DYRO.js} +1 -1
- package/dist/chunk-3MZ7DYRO.js.map +1 -0
- package/dist/{chunk-RVPYTUP4.js → chunk-3Y2EHT4F.js} +13 -9
- package/dist/chunk-3Y2EHT4F.js.map +1 -0
- package/dist/chunk-3Y6BHIN6.js +169 -0
- package/dist/chunk-3Y6BHIN6.js.map +1 -0
- package/dist/{chunk-4K7TQHNP.js → chunk-3YPL6T3P.js} +17 -33
- package/dist/chunk-3YPL6T3P.js.map +1 -0
- package/dist/{chunk-E7SW44LM.js → chunk-44MVIRZH.js} +121 -6
- package/dist/chunk-44MVIRZH.js.map +1 -0
- package/dist/chunk-45MMSBHA.js +321 -0
- package/dist/chunk-45MMSBHA.js.map +1 -0
- package/dist/{chunk-3FMZGI7I.js → chunk-4CE6TMI5.js} +1 -1
- package/dist/chunk-4CE6TMI5.js.map +1 -0
- package/dist/{chunk-QXP3Z3JN.js → chunk-4MBCJFY4.js} +35 -3
- package/dist/chunk-4MBCJFY4.js.map +1 -0
- package/dist/chunk-4TPL54KW.js +227 -0
- package/dist/chunk-4TPL54KW.js.map +1 -0
- package/dist/chunk-54ELBTKE.js +1615 -0
- package/dist/chunk-54ELBTKE.js.map +1 -0
- package/dist/{chunk-NDGZDTSJ.js → chunk-5F4OB5B3.js} +115 -57
- package/dist/chunk-5F4OB5B3.js.map +1 -0
- package/dist/chunk-5HN4KVQU.js +3348 -0
- package/dist/chunk-5HN4KVQU.js.map +1 -0
- package/dist/{chunk-ZDZERB6L.js → chunk-5J4E5GYI.js} +572 -407
- package/dist/chunk-5J4E5GYI.js.map +1 -0
- package/dist/{chunk-ZNNXRNFD.js → chunk-5N4GGUBN.js} +48 -6
- package/dist/chunk-5N4GGUBN.js.map +1 -0
- package/dist/chunk-5USBZ2MU.js +58 -0
- package/dist/chunk-5USBZ2MU.js.map +1 -0
- package/dist/chunk-64WOMNYR.js +183 -0
- package/dist/chunk-64WOMNYR.js.map +1 -0
- package/dist/{chunk-ILNIZ5I2.js → chunk-65RS4LQS.js} +1825 -1715
- package/dist/chunk-65RS4LQS.js.map +1 -0
- package/dist/{chunk-IE7P2BZE.js → chunk-6QMDUDF2.js} +3 -3
- package/dist/{chunk-IADZOXKN.js → chunk-7SLOTLO7.js} +19 -697
- package/dist/chunk-7SLOTLO7.js.map +1 -0
- package/dist/{chunk-WFSPCCVW.js → chunk-7V25UAQO.js} +99 -99
- package/dist/{chunk-WFSPCCVW.js.map → chunk-7V25UAQO.js.map} +1 -1
- package/dist/chunk-BGA4DO5M.js +719 -0
- package/dist/chunk-BGA4DO5M.js.map +1 -0
- package/dist/chunk-BVP7YK2J.js +706 -0
- package/dist/chunk-BVP7YK2J.js.map +1 -0
- package/dist/chunk-C265QIMJ.js +83 -0
- package/dist/chunk-C265QIMJ.js.map +1 -0
- package/dist/{chunk-XQJXNMSB.js → chunk-CRG54LEB.js} +1 -1
- package/dist/chunk-CRG54LEB.js.map +1 -0
- package/dist/{chunk-KG3D7FIF.js → chunk-CZJOMUBP.js} +2 -2
- package/dist/{chunk-36RVGZNY.js → chunk-D6M3ZK66.js} +22 -39
- package/dist/chunk-D6M3ZK66.js.map +1 -0
- package/dist/{chunk-3UCIG4TG.js → chunk-DI4QAGRZ.js} +1 -11
- package/dist/chunk-DI4QAGRZ.js.map +1 -0
- package/dist/{chunk-JKKAIPTU.js → chunk-DIH2G3YG.js} +47 -10
- package/dist/chunk-DIH2G3YG.js.map +1 -0
- package/dist/chunk-DJ36BM62.js +78 -0
- package/dist/chunk-DJ36BM62.js.map +1 -0
- package/dist/chunk-DTEWAVNE.js +114 -0
- package/dist/chunk-DTEWAVNE.js.map +1 -0
- package/dist/chunk-F2KJAJ7T.js +13 -0
- package/dist/chunk-F2KJAJ7T.js.map +1 -0
- package/dist/{chunk-BF4XHEQK.js → chunk-F3QPGYOY.js} +6 -6
- package/dist/chunk-F3QPGYOY.js.map +1 -0
- package/dist/{chunk-3GNJXKIT.js → chunk-F43CV6UC.js} +2 -2
- package/dist/{chunk-J57UC3DD.js → chunk-FKVJKLPI.js} +3 -3
- package/dist/{chunk-V2LQLN5H.js → chunk-FYFHH7V5.js} +59 -8
- package/dist/{chunk-V2LQLN5H.js.map → chunk-FYFHH7V5.js.map} +1 -1
- package/dist/chunk-GAJC4BQZ.js +1096 -0
- package/dist/chunk-GAJC4BQZ.js.map +1 -0
- package/dist/{chunk-DOQGNFHM.js → chunk-GH5UKMZD.js} +2 -12
- package/dist/{chunk-DOQGNFHM.js.map → chunk-GH5UKMZD.js.map} +1 -1
- package/dist/{chunk-WYXUQGOL.js → chunk-HAZAN4UM.js} +7 -6
- package/dist/chunk-HAZAN4UM.js.map +1 -0
- package/dist/chunk-HI5XQOX2.js +393 -0
- package/dist/chunk-HI5XQOX2.js.map +1 -0
- package/dist/chunk-HKGUKAQW.js +488 -0
- package/dist/chunk-HKGUKAQW.js.map +1 -0
- package/dist/{chunk-SO3XRZPX.js → chunk-HPRVFJPM.js} +6 -6
- package/dist/{chunk-L6JEXB3E.js → chunk-HQR4BWKX.js} +3 -131
- package/dist/chunk-HQR4BWKX.js.map +1 -0
- package/dist/chunk-HZKANST2.js +177 -0
- package/dist/chunk-HZKANST2.js.map +1 -0
- package/dist/{chunk-UUGOUOVT.js → chunk-I557SAOM.js} +8 -2
- package/dist/chunk-I557SAOM.js.map +1 -0
- package/dist/{chunk-TC2WZLSC.js → chunk-IGLWLH73.js} +8 -7
- package/dist/chunk-IGLWLH73.js.map +1 -0
- package/dist/chunk-ILWCKCOI.js +58 -0
- package/dist/chunk-ILWCKCOI.js.map +1 -0
- package/dist/{chunk-2GP3HRYK.js → chunk-INSIW65E.js} +182 -182
- package/dist/{chunk-MPZUYCAP.js → chunk-IULCDMVG.js} +12 -1
- package/dist/chunk-IULCDMVG.js.map +1 -0
- package/dist/{chunk-INTFHMU4.js → chunk-IVNSUAVC.js} +25 -26
- package/dist/chunk-IVNSUAVC.js.map +1 -0
- package/dist/chunk-JDQZCREI.js +87 -0
- package/dist/chunk-JDQZCREI.js.map +1 -0
- package/dist/chunk-JHFFUVON.js +1050 -0
- package/dist/chunk-JHFFUVON.js.map +1 -0
- package/dist/{chunk-RL5UUDT4.js → chunk-JNUKLSMZ.js} +3 -3
- package/dist/chunk-JTILUN4W.js +2933 -0
- package/dist/chunk-JTILUN4W.js.map +1 -0
- package/dist/{chunk-OJNTCYQQ.js → chunk-JTX3BUDK.js} +37 -53
- package/dist/chunk-JTX3BUDK.js.map +1 -0
- package/dist/{chunk-X5ZBP3IY.js → chunk-JUUBBBY5.js} +2 -2
- package/dist/chunk-JUUBBBY5.js.map +1 -0
- package/dist/chunk-JWAK7JQB.js +15 -0
- package/dist/chunk-JWAK7JQB.js.map +1 -0
- package/dist/{chunk-UXZONNEQ.js → chunk-K5KNGC4I.js} +34 -31
- package/dist/chunk-K5KNGC4I.js.map +1 -0
- package/dist/chunk-KAQ4Q3TO.js +135 -0
- package/dist/chunk-KAQ4Q3TO.js.map +1 -0
- package/dist/chunk-KFVJYLVL.js +125 -0
- package/dist/chunk-KFVJYLVL.js.map +1 -0
- package/dist/chunk-KGUE5AVX.js +69 -0
- package/dist/chunk-KGUE5AVX.js.map +1 -0
- package/dist/{chunk-FVIGCDSV.js → chunk-KLDMLWXT.js} +11 -85
- package/dist/chunk-KLDMLWXT.js.map +1 -0
- package/dist/chunk-KNKDMTHU.js +453 -0
- package/dist/chunk-KNKDMTHU.js.map +1 -0
- package/dist/chunk-LDA6TAYQ.js +95 -0
- package/dist/chunk-LDA6TAYQ.js.map +1 -0
- package/dist/chunk-LWSSIZOY.js +347 -0
- package/dist/chunk-LWSSIZOY.js.map +1 -0
- package/dist/{chunk-ZURZHELF.js → chunk-MAHNZA6C.js} +158 -41
- package/dist/chunk-MAHNZA6C.js.map +1 -0
- package/dist/chunk-MEWZCIA6.js +220 -0
- package/dist/chunk-MEWZCIA6.js.map +1 -0
- package/dist/{chunk-2SNUOHAT.js → chunk-MEZJ3I63.js} +49 -1
- package/dist/chunk-MEZJ3I63.js.map +1 -0
- package/dist/chunk-MJDO4EXD.js +353 -0
- package/dist/chunk-MJDO4EXD.js.map +1 -0
- package/dist/chunk-NJA6NT3A.js +6595 -0
- package/dist/chunk-NJA6NT3A.js.map +1 -0
- package/dist/{chunk-LHHMV4GU.js → chunk-NVSKJPRC.js} +1 -1
- package/dist/{chunk-LHHMV4GU.js.map → chunk-NVSKJPRC.js.map} +1 -1
- package/dist/{chunk-4YOZGGTZ.js → chunk-OC7K2DVZ.js} +5 -5
- package/dist/chunk-OC7K2DVZ.js.map +1 -0
- package/dist/chunk-ODRPASFP.js +2078 -0
- package/dist/chunk-ODRPASFP.js.map +1 -0
- package/dist/chunk-OJJFANO6.js +133 -0
- package/dist/chunk-OJJFANO6.js.map +1 -0
- package/dist/{chunk-JNJWBTU2.js → chunk-OQWPRFAC.js} +332 -882
- package/dist/chunk-OQWPRFAC.js.map +1 -0
- package/dist/chunk-P4I7BFNJ.js +11 -0
- package/dist/chunk-P4I7BFNJ.js.map +1 -0
- package/dist/{chunk-SNNSAGMT.js → chunk-P6YQWIT2.js} +4058 -4039
- package/dist/chunk-P6YQWIT2.js.map +1 -0
- package/dist/{chunk-JRGFKVAZ.js → chunk-PETQ5WEA.js} +2 -2
- package/dist/{chunk-HMWYAUA6.js → chunk-Q6RSJCXB.js} +29 -69
- package/dist/chunk-Q6RSJCXB.js.map +1 -0
- package/dist/{chunk-U3IKUGRP.js → chunk-QKEUKBRK.js} +17 -23
- package/dist/chunk-QKEUKBRK.js.map +1 -0
- package/dist/{chunk-2RWB7RKE.js → chunk-QKYUCITR.js} +174 -5814
- package/dist/chunk-QKYUCITR.js.map +1 -0
- package/dist/chunk-QQDPRTLP.js +127 -0
- package/dist/chunk-QQDPRTLP.js.map +1 -0
- package/dist/chunk-QQYCYAKI.js +79 -0
- package/dist/chunk-QQYCYAKI.js.map +1 -0
- package/dist/chunk-R4KDH477.js +1064 -0
- package/dist/chunk-R4KDH477.js.map +1 -0
- package/dist/chunk-R5TR2DIK.js +119 -0
- package/dist/chunk-R5TR2DIK.js.map +1 -0
- package/dist/chunk-R62PKTAG.js +66 -0
- package/dist/chunk-R62PKTAG.js.map +1 -0
- package/dist/{chunk-BFDQ4WNW.js → chunk-RFZA7PSM.js} +4 -5
- package/dist/chunk-RFZA7PSM.js.map +1 -0
- package/dist/chunk-RGCPELQN.js +219 -0
- package/dist/chunk-RGCPELQN.js.map +1 -0
- package/dist/chunk-RGVCOG2S.js +910 -0
- package/dist/chunk-RGVCOG2S.js.map +1 -0
- package/dist/chunk-SOLNJ3AZ.js +209 -0
- package/dist/chunk-SOLNJ3AZ.js.map +1 -0
- package/dist/chunk-TFT2X7SH.js +77 -0
- package/dist/chunk-TFT2X7SH.js.map +1 -0
- package/dist/chunk-TUCKEEXE.js +2 -0
- package/dist/chunk-TVWCLUBI.js +293 -0
- package/dist/chunk-TVWCLUBI.js.map +1 -0
- package/dist/chunk-U4TRWSVE.js +78 -0
- package/dist/chunk-U4TRWSVE.js.map +1 -0
- package/dist/chunk-UIB33QQP.js +379 -0
- package/dist/chunk-UIB33QQP.js.map +1 -0
- package/dist/chunk-V6GIVALQ.js +1889 -0
- package/dist/chunk-V6GIVALQ.js.map +1 -0
- package/dist/chunk-VHXCPXUS.js +366 -0
- package/dist/chunk-VHXCPXUS.js.map +1 -0
- package/dist/{chunk-HGZEPQUT.js → chunk-VU6GMWF6.js} +17 -8
- package/dist/chunk-VU6GMWF6.js.map +1 -0
- package/dist/chunk-VWZYE3NC.js +8415 -0
- package/dist/chunk-VWZYE3NC.js.map +1 -0
- package/dist/{chunk-AGMVASXZ.js → chunk-W2GXIARJ.js} +88 -11
- package/dist/chunk-W2GXIARJ.js.map +1 -0
- package/dist/chunk-W4G3K3V7.js +288 -0
- package/dist/chunk-W4G3K3V7.js.map +1 -0
- package/dist/chunk-W74LJ5OT.js +588 -0
- package/dist/chunk-W74LJ5OT.js.map +1 -0
- package/dist/chunk-W7ELYLYK.js +233 -0
- package/dist/chunk-W7ELYLYK.js.map +1 -0
- package/dist/{chunk-BPMWXTFX.js → chunk-WFZX352D.js} +7 -7
- package/dist/chunk-WXA3WTPF.js +20 -0
- package/dist/chunk-WXA3WTPF.js.map +1 -0
- package/dist/chunk-XRGFH7FI.js +454 -0
- package/dist/chunk-XRGFH7FI.js.map +1 -0
- package/dist/chunk-XSCGUO2U.js +330 -0
- package/dist/chunk-XSCGUO2U.js.map +1 -0
- package/dist/chunk-XWROSMI5.js +1039 -0
- package/dist/chunk-XWROSMI5.js.map +1 -0
- package/dist/chunk-Y2EXZ47H.js +40 -0
- package/dist/chunk-Y2EXZ47H.js.map +1 -0
- package/dist/chunk-YJGEVBKZ.js +47 -0
- package/dist/chunk-YJGEVBKZ.js.map +1 -0
- package/dist/{chunk-6CMM6YCB.js → chunk-YWWMISDY.js} +2 -2
- package/dist/{chunk-WXA2BWTE.js → chunk-ZCT5DJ3G.js} +2 -48
- package/dist/chunk-ZCT5DJ3G.js.map +1 -0
- package/dist/chunk-ZEYA2WWX.js +982 -0
- package/dist/chunk-ZEYA2WWX.js.map +1 -0
- package/dist/chunk-ZRC7Z5X3.js +82 -0
- package/dist/chunk-ZRC7Z5X3.js.map +1 -0
- package/dist/{chunk-3AIHRXKO.js → chunk-ZS7JIUJ3.js} +12 -10
- package/dist/chunk-ZS7JIUJ3.js.map +1 -0
- package/dist/{clack-EZ7TDWQU.js → clack-Q4RNC5VE.js} +2 -6
- package/dist/{claude-cli-2YKABJJZ.js → claude-cli-GIIHOBGT.js} +4 -2
- package/dist/claude-install-BAUSJMW3.js +64 -0
- package/dist/{cli-E36SPKBW.js → cli-QY4KKA3D.js} +632 -150
- package/dist/cli-QY4KKA3D.js.map +1 -0
- package/dist/client-3YQKORVK.js +710 -0
- package/dist/client-3YQKORVK.js.map +1 -0
- package/dist/{codex-event-ZO2GEFE6.js → codex-event-EUTCAOTQ.js} +3 -5
- package/dist/{codex-host-KECJVTA2.js → codex-host-ZON3S6HU.js} +7 -7
- package/dist/{codex-install-HQZDGFXW.js → codex-install-HZV2DOAB.js} +242 -88
- package/dist/codex-install-HZV2DOAB.js.map +1 -0
- package/dist/config-QZOBMTEL.js +57 -0
- package/dist/config-names-Z5NZD5R2.js +224 -0
- package/dist/config-names-Z5NZD5R2.js.map +1 -0
- package/dist/config-rules-YOYHS6YL.js +55 -0
- package/dist/config-subagents-WQV2ZAD5.js +362 -0
- package/dist/config-subagents-WQV2ZAD5.js.map +1 -0
- package/dist/connect-YDWTYU4B.js +1020 -0
- package/dist/connect-YDWTYU4B.js.map +1 -0
- package/dist/core-0a66n3e7-TTP554XV.js +127 -0
- package/dist/core-0a66n3e7-TTP554XV.js.map +1 -0
- package/dist/core-0bmnpbz2-C2JIRVZO.js +10790 -0
- package/dist/core-0bmnpbz2-C2JIRVZO.js.map +1 -0
- package/dist/core-9je8ee1j-74DGHWPV.js +30 -0
- package/dist/core-9je8ee1j-74DGHWPV.js.map +1 -0
- package/dist/core-wadgcjfh-TSZFQZGH.js +666 -0
- package/dist/core-wadgcjfh-TSZFQZGH.js.map +1 -0
- package/dist/core-zg882d22-LKV5DZYW.js +37 -0
- package/dist/core-zg882d22-LKV5DZYW.js.map +1 -0
- package/dist/decision-QSKHOGCO.js +145 -0
- package/dist/{doctor-I6XQEKWD.js → doctor-ZWJXRD75.js} +162 -148
- package/dist/doctor-ZWJXRD75.js.map +1 -0
- package/dist/{env-proxy-R6ZMLQTT.js → env-proxy-XLSLHBKQ.js} +2 -2
- package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js → ethersCompat-Df4a6QIZ-K3DMHR6Y.js} +5 -5
- package/dist/explicit-ME2NRADQ.js +371 -0
- package/dist/explicit-ME2NRADQ.js.map +1 -0
- package/dist/flush-stdio-NYIJ3QXT.js +18 -0
- package/dist/fund-VF7TLDJH.js +722 -0
- package/dist/fund-VF7TLDJH.js.map +1 -0
- package/dist/hook-command-VZ27MGWO.js +49 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
- package/dist/hosts/claude/tenjin/hooks/hook-data.ts +152 -0
- package/dist/hosts/claude/tenjin/hooks/hooks.json +7 -0
- package/dist/hosts/claude/tenjin/hooks/model-viewer.tsx +2987 -0
- package/dist/hosts/claude/tenjin/hooks/register.tsx +527 -56
- package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +14 -4
- package/dist/hosts/claude/tenjin/types/index.d.ts +144 -1
- package/dist/{hosts-DVQJ32QC.js → hosts-3EMTVM4H.js} +7 -6
- package/dist/index.js +18 -15
- package/dist/index.js.map +1 -1
- package/dist/install-ZA7L2UF3.js +115 -0
- package/dist/install-funding-JDGYTF72.js +30 -0
- package/dist/install-identity-FFAYEFLX.js +30 -0
- package/dist/{install-wallet-5M4OTYLX.js → install-wallet-2SFOVE3Q.js} +68 -53
- package/dist/install-wallet-2SFOVE3Q.js.map +1 -0
- package/dist/mcp-36S6MK3C.js +67642 -0
- package/dist/mcp-36S6MK3C.js.map +1 -0
- package/dist/new-install-5L4GY3LN.js +51 -0
- package/dist/{package-IJFGMWEV.js → package-BONDXSV3.js} +2 -2
- package/dist/{passphrase-IFTDS3CU.js → passphrase-T4ULBN4M.js} +16 -12
- package/dist/{paths-XCSAKISU.js → paths-O2KDWZ76.js} +18 -28
- package/dist/pay-CMV5KL74.js +74 -0
- package/dist/{payments-HFPPWHTV.js → payments-Z6UBZL4Z.js} +36 -26
- package/dist/payments-Z6UBZL4Z.js.map +1 -0
- package/dist/reclaim-subagent-credit-ABSF67SJ.js +105 -0
- package/dist/reclaim-subagent-credit-ABSF67SJ.js.map +1 -0
- package/dist/{redact-D7ASVWKL.js → redact-LOTHE5TS.js} +2 -8
- package/dist/redact-LOTHE5TS.js.map +1 -0
- package/dist/routing-quote-AHLAREXR.js +40 -0
- package/dist/routing-quote-AHLAREXR.js.map +1 -0
- package/dist/run-JH7ELYAM.js +88 -0
- package/dist/run-JH7ELYAM.js.map +1 -0
- package/dist/runtime-2GX4ALJP.js +410 -0
- package/dist/runtime-2GX4ALJP.js.map +1 -0
- package/dist/runtime-activate-IDQ2NCSP.js +39 -0
- package/dist/runtime-activate-IDQ2NCSP.js.map +1 -0
- package/dist/{runtime-fetch-ZSSSK72Y.js → runtime-fetch-6LOBHBEN.js} +4 -4
- package/dist/runtime-fetch-6LOBHBEN.js.map +1 -0
- package/dist/runtime-launchers-YAPKCBHV.js +31 -0
- package/dist/runtime-launchers-YAPKCBHV.js.map +1 -0
- package/dist/{runtime-layout-WIDILZ6K.js → runtime-layout-QHZQJV7C.js} +5 -4
- package/dist/runtime-layout-QHZQJV7C.js.map +1 -0
- package/dist/runtime-place-4POL4KK4.js +37 -0
- package/dist/runtime-place-4POL4KK4.js.map +1 -0
- package/dist/runtime-provenance-MNJGVBV2.js +12 -0
- package/dist/runtime-provenance-MNJGVBV2.js.map +1 -0
- package/dist/{secp256k1-ZZZT2CAX.js → secp256k1-N5P2GVGF.js} +3 -3
- package/dist/secp256k1-N5P2GVGF.js.map +1 -0
- package/dist/{send-GCVEAQKL.js → send-ELXFKEKY.js} +35 -32
- package/dist/send-ELXFKEKY.js.map +1 -0
- package/dist/status-FXUFWJDM.js +404 -0
- package/dist/status-FXUFWJDM.js.map +1 -0
- package/dist/{status-line-OPCXDHL2.js → status-line-IH5JBWBC.js} +51 -43
- package/dist/status-line-IH5JBWBC.js.map +1 -0
- package/dist/streamableHttp-CP2ZQBIK.js +768 -0
- package/dist/streamableHttp-CP2ZQBIK.js.map +1 -0
- package/dist/{uninstall-BAWRBXXQ.js → uninstall-LJZUKM4D.js} +76 -76
- package/dist/uninstall-LJZUKM4D.js.map +1 -0
- package/dist/update-EUIX72IX.js +68 -0
- package/dist/update-EUIX72IX.js.map +1 -0
- package/dist/usage-EKDC7LUC.js +180 -0
- package/dist/usage-EKDC7LUC.js.map +1 -0
- package/dist/{usdc-VG4CIOUK.js → usdc-YIHK2OMC.js} +8 -12
- package/dist/usdc-YIHK2OMC.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-DOFTEIJV.js → viemAdapter-By13KInL-PRLSIESK.js} +5 -5
- package/dist/viemAdapter-By13KInL-PRLSIESK.js.map +1 -0
- package/dist/wallet-HSW757W6.js +80 -0
- package/dist/wallet-HSW757W6.js.map +1 -0
- package/dist/wallet-kdf-worker.mjs +1433 -818
- package/docs/agent-permissions.md +88 -155
- package/docs/router-reference.md +236 -0
- package/docs/safety-model.md +31 -33
- package/docs/subagents-internals.md +97 -0
- package/docs/subagents.md +348 -0
- package/docs/troubleshooting.md +10 -6
- package/package.json +12 -8
- package/scripts/installers/install.sh +7 -1
- package/dist/alive-GSOWKUOY.js +0 -38
- package/dist/chunk-2I4QTOLB.js.map +0 -1
- package/dist/chunk-2M2VPI2E.js +0 -560
- package/dist/chunk-2M2VPI2E.js.map +0 -1
- package/dist/chunk-2RWB7RKE.js.map +0 -1
- package/dist/chunk-2SNUOHAT.js.map +0 -1
- package/dist/chunk-3623BLPV.js +0 -184
- package/dist/chunk-3623BLPV.js.map +0 -1
- package/dist/chunk-36RVGZNY.js.map +0 -1
- package/dist/chunk-3AIHRXKO.js.map +0 -1
- package/dist/chunk-3FMZGI7I.js.map +0 -1
- package/dist/chunk-3UCIG4TG.js.map +0 -1
- package/dist/chunk-4K7TQHNP.js.map +0 -1
- package/dist/chunk-4LMUQMBH.js +0 -29
- package/dist/chunk-4LMUQMBH.js.map +0 -1
- package/dist/chunk-4USCZ2NI.js +0 -228
- package/dist/chunk-4USCZ2NI.js.map +0 -1
- package/dist/chunk-4YOZGGTZ.js.map +0 -1
- package/dist/chunk-62KNUYWD.js +0 -111
- package/dist/chunk-62KNUYWD.js.map +0 -1
- package/dist/chunk-A5GKIG5O.js +0 -2037
- package/dist/chunk-A5GKIG5O.js.map +0 -1
- package/dist/chunk-AGMVASXZ.js.map +0 -1
- package/dist/chunk-BF4XHEQK.js.map +0 -1
- package/dist/chunk-BFDQ4WNW.js.map +0 -1
- package/dist/chunk-C2Q76BVM.js.map +0 -1
- package/dist/chunk-CEXSOI5R.js +0 -808
- package/dist/chunk-CEXSOI5R.js.map +0 -1
- package/dist/chunk-E7SW44LM.js.map +0 -1
- package/dist/chunk-EDJWHDDL.js +0 -33
- package/dist/chunk-EDJWHDDL.js.map +0 -1
- package/dist/chunk-FVIGCDSV.js.map +0 -1
- package/dist/chunk-GTTUCOPD.js +0 -105
- package/dist/chunk-GTTUCOPD.js.map +0 -1
- package/dist/chunk-HDPUXS3Z.js +0 -122
- package/dist/chunk-HDPUXS3Z.js.map +0 -1
- package/dist/chunk-HGGWCP7W.js +0 -120
- package/dist/chunk-HGGWCP7W.js.map +0 -1
- package/dist/chunk-HGZEPQUT.js.map +0 -1
- package/dist/chunk-HMWYAUA6.js.map +0 -1
- package/dist/chunk-IADZOXKN.js.map +0 -1
- package/dist/chunk-ILNIZ5I2.js.map +0 -1
- package/dist/chunk-INTFHMU4.js.map +0 -1
- package/dist/chunk-JKKAIPTU.js.map +0 -1
- package/dist/chunk-JNJWBTU2.js.map +0 -1
- package/dist/chunk-KM7RY2ZS.js +0 -246
- package/dist/chunk-KM7RY2ZS.js.map +0 -1
- package/dist/chunk-KOGZDMHO.js +0 -21
- package/dist/chunk-KOGZDMHO.js.map +0 -1
- package/dist/chunk-L6JEXB3E.js.map +0 -1
- package/dist/chunk-LRW6S53P.js.map +0 -1
- package/dist/chunk-LXAYUOXI.js +0 -511
- package/dist/chunk-LXAYUOXI.js.map +0 -1
- package/dist/chunk-MEFB5KHA.js +0 -59
- package/dist/chunk-MEFB5KHA.js.map +0 -1
- package/dist/chunk-MPZUYCAP.js.map +0 -1
- package/dist/chunk-NDGZDTSJ.js.map +0 -1
- package/dist/chunk-OJNTCYQQ.js.map +0 -1
- package/dist/chunk-P3LFTKE7.js +0 -58
- package/dist/chunk-P3LFTKE7.js.map +0 -1
- package/dist/chunk-QXP3Z3JN.js.map +0 -1
- package/dist/chunk-RVPYTUP4.js.map +0 -1
- package/dist/chunk-SNNSAGMT.js.map +0 -1
- package/dist/chunk-TC2WZLSC.js.map +0 -1
- package/dist/chunk-TKPF35W6.js +0 -29
- package/dist/chunk-TKPF35W6.js.map +0 -1
- package/dist/chunk-U3IKUGRP.js.map +0 -1
- package/dist/chunk-UUGOUOVT.js.map +0 -1
- package/dist/chunk-UXZONNEQ.js.map +0 -1
- package/dist/chunk-WXA2BWTE.js.map +0 -1
- package/dist/chunk-WYXUQGOL.js.map +0 -1
- package/dist/chunk-X5ZBP3IY.js.map +0 -1
- package/dist/chunk-XKESD27X.js +0 -10
- package/dist/chunk-XKESD27X.js.map +0 -1
- package/dist/chunk-XQJXNMSB.js.map +0 -1
- package/dist/chunk-Y527D4TV.js +0 -56
- package/dist/chunk-Y527D4TV.js.map +0 -1
- package/dist/chunk-ZDZERB6L.js.map +0 -1
- package/dist/chunk-ZNNXRNFD.js.map +0 -1
- package/dist/chunk-ZURZHELF.js.map +0 -1
- package/dist/cli-E36SPKBW.js.map +0 -1
- package/dist/codex-install-HQZDGFXW.js.map +0 -1
- package/dist/config-HY2E4GGW.js +0 -55
- package/dist/doctor-I6XQEKWD.js.map +0 -1
- package/dist/fund-2QRO7OJL.js +0 -378
- package/dist/fund-2QRO7OJL.js.map +0 -1
- package/dist/hook-command-2UBCSZG6.js +0 -43
- package/dist/install-ILUX5C4A.js +0 -107
- package/dist/install-identity-TZKGY6LQ.js +0 -31
- package/dist/install-wallet-5M4OTYLX.js.map +0 -1
- package/dist/mcp-LE4DUS22.js +0 -14127
- package/dist/mcp-LE4DUS22.js.map +0 -1
- package/dist/pay-WCG3IH4R.js +0 -55
- package/dist/payments-HFPPWHTV.js.map +0 -1
- package/dist/plugin-registration-PZFI5GZW.js +0 -68
- package/dist/runtime-UZOKSUZX.js +0 -1321
- package/dist/runtime-UZOKSUZX.js.map +0 -1
- package/dist/send-GCVEAQKL.js.map +0 -1
- package/dist/status-HCVAOCN7.js +0 -150
- package/dist/status-HCVAOCN7.js.map +0 -1
- package/dist/status-line-OPCXDHL2.js.map +0 -1
- package/dist/uninstall-BAWRBXXQ.js.map +0 -1
- package/dist/update-CACXLQLR.js +0 -56
- package/dist/wallet-QL4UUXEZ.js +0 -55
- /package/dist/{_esm-BIN7VY2L.js.map → _esm-2KST7HQ7.js.map} +0 -0
- /package/dist/{alive-GSOWKUOY.js.map → alive-5TV22PNF.js.map} +0 -0
- /package/dist/{auto-update-Y24UL56V.js.map → auth-XI7BJFLW.js.map} +0 -0
- /package/dist/{ccip-DHDFKTQV.js.map → auto-update-7L24KDWA.js.map} +0 -0
- /package/dist/{clack-EZ7TDWQU.js.map → balance-DFHC6XEU.js.map} +0 -0
- /package/dist/{claude-cli-2YKABJJZ.js.map → ccip-HOW3DZYF.js.map} +0 -0
- /package/dist/{chunk-IE7P2BZE.js.map → chunk-6QMDUDF2.js.map} +0 -0
- /package/dist/{chunk-KG3D7FIF.js.map → chunk-CZJOMUBP.js.map} +0 -0
- /package/dist/{chunk-3GNJXKIT.js.map → chunk-F43CV6UC.js.map} +0 -0
- /package/dist/{chunk-J57UC3DD.js.map → chunk-FKVJKLPI.js.map} +0 -0
- /package/dist/{chunk-SO3XRZPX.js.map → chunk-HPRVFJPM.js.map} +0 -0
- /package/dist/{chunk-2GP3HRYK.js.map → chunk-INSIW65E.js.map} +0 -0
- /package/dist/{chunk-RL5UUDT4.js.map → chunk-JNUKLSMZ.js.map} +0 -0
- /package/dist/{chunk-JRGFKVAZ.js.map → chunk-PETQ5WEA.js.map} +0 -0
- /package/dist/{codex-event-ZO2GEFE6.js.map → chunk-TUCKEEXE.js.map} +0 -0
- /package/dist/{chunk-BPMWXTFX.js.map → chunk-WFZX352D.js.map} +0 -0
- /package/dist/{chunk-6CMM6YCB.js.map → chunk-YWWMISDY.js.map} +0 -0
- /package/dist/{codex-host-KECJVTA2.js.map → clack-Q4RNC5VE.js.map} +0 -0
- /package/dist/{config-HY2E4GGW.js.map → claude-cli-GIIHOBGT.js.map} +0 -0
- /package/dist/{env-proxy-R6ZMLQTT.js.map → claude-install-BAUSJMW3.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js.map → codex-event-EUTCAOTQ.js.map} +0 -0
- /package/dist/{hook-command-2UBCSZG6.js.map → codex-host-ZON3S6HU.js.map} +0 -0
- /package/dist/{hosts-DVQJ32QC.js.map → config-QZOBMTEL.js.map} +0 -0
- /package/dist/{install-ILUX5C4A.js.map → config-rules-YOYHS6YL.js.map} +0 -0
- /package/dist/{install-identity-TZKGY6LQ.js.map → decision-QSKHOGCO.js.map} +0 -0
- /package/dist/{package-IJFGMWEV.js.map → env-proxy-XLSLHBKQ.js.map} +0 -0
- /package/dist/{passphrase-IFTDS3CU.js.map → ethersCompat-Df4a6QIZ-K3DMHR6Y.js.map} +0 -0
- /package/dist/{paths-XCSAKISU.js.map → flush-stdio-NYIJ3QXT.js.map} +0 -0
- /package/dist/{pay-WCG3IH4R.js.map → hook-command-VZ27MGWO.js.map} +0 -0
- /package/dist/{plugin-registration-PZFI5GZW.js.map → hosts-3EMTVM4H.js.map} +0 -0
- /package/dist/{redact-D7ASVWKL.js.map → install-ZA7L2UF3.js.map} +0 -0
- /package/dist/{runtime-fetch-ZSSSK72Y.js.map → install-funding-JDGYTF72.js.map} +0 -0
- /package/dist/{runtime-layout-WIDILZ6K.js.map → install-identity-FFAYEFLX.js.map} +0 -0
- /package/dist/{secp256k1-ZZZT2CAX.js.map → new-install-5L4GY3LN.js.map} +0 -0
- /package/dist/{update-CACXLQLR.js.map → package-BONDXSV3.js.map} +0 -0
- /package/dist/{usdc-VG4CIOUK.js.map → passphrase-T4ULBN4M.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-DOFTEIJV.js.map → paths-O2KDWZ76.js.map} +0 -0
- /package/dist/{wallet-QL4UUXEZ.js.map → pay-CMV5KL74.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/pay.ts","../src/router/model-worker-context.ts","../src/lib/bazaar.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/http/types.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/mcp/types.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/types.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/http/resourceService.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/mcp/resourceService.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/resourceService.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/server.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/facilitator.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/v1/facilitator.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/startupValidation.ts","../node_modules/.pnpm/@x402+extensions@2.28.0_typescript@6.0.3/node_modules/@x402/extensions/src/bazaar/facilitatorClient.ts","../src/lib/spend-gate.ts","../src/lib/spend-quotes.ts","../src/lib/spend-plan.ts"],"sourcesContent":["import { tmpdir } from 'node:os';\nimport { isModelWorkerProcess } from '../router/model-worker-context';\nimport { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';\nimport { SIGN_IN_WITH_X } from '@x402/extensions/sign-in-with-x';\nimport type { PaymentRequired, PaymentRequirements } from '@x402/core/types';\nimport { verifyAgainstRegistries, type RegistryVerification } from '../lib/bazaar';\nimport type { readUsdcBalance } from '../lib/usdc-balance';\nimport { assertPublicDestination, type DestinationOptions } from '../lib/destination';\nimport { CliError } from '../lib/errors';\nimport { notePaymentSent } from '../lib/flush-stdio';\nimport { paymentShortOfFunds } from '../lib/payment-failure';\nimport { validateResultBody, type ResultCheck } from '../lib/request-schema';\nimport { fetchFailureToCliError, httpRequest, requestHeaderProblem } from '../lib/http';\nimport type { FetchJsonFailure, HttpResponse } from '../lib/http';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { sanitizeForTerminal } from '../lib/output';\nimport { mask } from '../lib/redact';\nimport { isSameDeployment } from '../lib/production-origin';\nimport { resolveContextSettings } from '../lib/settings';\nimport {\n SIWX_HEADER,\n answerSignInChallenge,\n buildSiwxHeader,\n signInOnlyChallenge,\n} from '../lib/siwx';\nimport { downloadsDir } from '../lib/paths';\nimport { gateSpend } from '../lib/spend-gate';\nimport { markShortOfFunds, spendSlot, type PlanSlot } from '../lib/spend-plan';\nimport type { ResolvedSettings } from '../lib/settings';\nimport {\n describeWallet,\n resolveSpendAuthorizer,\n resolveWalletProvider,\n type SpendAuthorizer,\n type WalletProvider,\n} from '../lib/wallet';\nimport {\n buildExactPayment,\n createPayerClient,\n isCanonicalUsdc,\n noPayableRequirement,\n selectPayableRequirement,\n signsEip3009,\n} from '../lib/x402-pay';\nimport type { x402Client, x402HTTPClient } from '@x402/core/client';\nimport type { TenjinSigner } from '../lib/wallet/provider';\nimport {\n appendPaidRecord,\n chargedOnChain,\n walletPaidHost,\n recordedSent,\n writeNewFile,\n type Settlement,\n type SignedAuthorization,\n} from '../router/paid';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin pay <url>`: the standard x402 client verb, for ANY paid endpoint\n * rather than marketplace pieces. One probe; a 2xx delivers free; a 402 runs\n * shared payment gate (automatic limits for the router, mandatory consent for\n * manual pay, hard price/creator checks for both) and retries once with the\n * `PAYMENT-SIGNATURE`. Deliberately NOT `buy`: no library idempotence (every\n * paid call pays; manual consent and optional `--max-price` are the brakes) and no\n * search attribution. SIWX rides ONLY when the 402 advertises the standard\n * sign-in-with-x extension, and the signature is bound to the TARGET origin\n * (never the configured deployment's), so an entitled wallet re-reads free at\n * any seller that supports it while nothing origin-bound can leak elsewhere.\n *\n * Direct third-party payments require acknowledgement of registry warnings.\n * Router calls retain their advertised-price and supplied-term hard checks,\n * and each is signed only against its call's spend plan (`admit`).\n * Signing is offline; the facilitator verifies funds when the seller submits payment.\n */\n\nconst PAYMENT_REQUIRED_HEADER = 'PAYMENT-REQUIRED';\nconst PAYMENT_RESPONSE_HEADER = 'PAYMENT-RESPONSE';\n/** x402 v1's name for the same header. */\nconst PAYMENT_RESPONSE_HEADER_V1 = 'X-PAYMENT-RESPONSE';\n\n/** Terminal preview cap; `--print-body` lifts it. The machine body is never cut. */\nconst BODY_PREVIEW_CHARS = 1200;\n\n/** A paid leg the seller refused as short of funds (`paymentShortOfFunds`). */\nconst LOW_FUNDS_MESSAGE = 'The wallet does not hold enough USDC for this payment.';\n/** What a low-funds refusal says after its ask for funds: the `request` tool\n * keeps it behind its own ask, which names the call ({@link isLowFundsRefusal}). */\nexport const LOW_FUNDS_TAIL =\n 'The signed authorization stays counted until it expires and is recorded as transmitted exposure. Do not simply retry: each attempt signs a fresh authorization.';\n\n/** A `runPay` failure that is the seller refusing the payment as short of funds. */\nexport function isLowFundsRefusal(err: CliError): boolean {\n return err.code === 'PAYMENT_FAILED' && err.message === LOW_FUNDS_MESSAGE;\n}\n\n/**\n * What a caller was told this endpoint costs, BEFORE the live 402 is seen. It\n * stands in for the registry lookup on a lane that has one from elsewhere (the\n * router's paid decision carries it), and it is a ceiling, never a licence: the\n * live requirement has to match the network and asset exactly and may not\n * exceed the amount. Direct calls without offered terms use registry warning acknowledgement.\n */\nexport interface AdvertisedTerms {\n /** Pins the deal's chain and token when the caller was told them. */\n network?: string;\n asset?: string;\n /**\n * A ceiling the caller was quoted, when there was one: a live 402 above it is\n * refused. It only ever refuses; the amount actually signed still meets\n * `maxAutoSpend` and `sessionBudget` in `gateSpend`, the payment authority.\n */\n maxAmountAtomic?: string;\n /** The advertised recipient, when the caller was given one. Checked exactly. */\n payTo?: string;\n /** Free-text provenance for the payee label, e.g. a registry name. */\n source?: string;\n}\n\nexport interface PayArgs {\n url: string;\n /** GET, POST, PUT, PATCH or DELETE. GET by default, POST when a body is given. */\n method?: string;\n /** A JSON request body; content-type is always application/json. */\n data?: string;\n /**\n * `--data-raw`: a body sent byte for byte, for an endpoint that does not\n * take JSON. Its content type is the operator's own `-H 'Content-Type: …'`,\n * which is required with it and refused everywhere else.\n */\n dataRaw?: string;\n /** Decimal USD; the hard price cap, never bypassed by --yes. */\n maxPrice?: string;\n /** Bypass the interactive confirm only (never the price cap or a hard deny). */\n yes?: boolean;\n /** Acknowledge direct-payment registry warnings for this invocation only. */\n ignoreWarnings?: boolean;\n /** Internal router entrypoint; missing terms must never become direct pay. */\n execution?: 'router';\n /** Print the full body to the terminal instead of the capped preview. */\n printBody?: boolean;\n /** Advertised terms that replace the registry lookup on this call. */\n terms?: AdvertisedTerms;\n /**\n * Request headers a caller was handed rather than composed: the router's\n * provider leg sends the decision's own `accept` and `content-type`. Only\n * those two names are accepted, so nothing can smuggle a credential or a\n * payment header in beside the one this command signs.\n */\n headers?: Record<string, string>;\n /**\n * A catalog spec's fixed request headers, on the router's provider leg: the\n * same bar as `-H`, checked again here, and set under `headers`, so a spec\n * never replaces the leg's own `accept` or `content-type`.\n */\n specHeaders?: Record<string, string>;\n /**\n * `-H 'Name: value'` lines from the operator, for a header the endpoint\n * itself asks for (a beta opt-in, an API version). Manual lane only. Any\n * name this command signs or sets is refused before the probe.\n */\n header?: string[];\n /**\n * `--quote`: decode and report the 402 (every payment option, the resource\n * line, the seller's extensions and the body) and stop there. No wallet is\n * opened and nothing is signed. A 2xx on the probe still delivers free.\n */\n quote?: boolean;\n /** The router's body, already encoded; sent byte for byte. Needs POST, PUT or PATCH. */\n rawBody?: string;\n /** The provider's own deadline for each leg, from its spec, in place of\n * `--timeout`: the probe's, and the least the paid leg waits. */\n timeoutMs?: number;\n /** The largest binary body kept, from the provider's spec; absent, the\n * transport's own cap. */\n maxBytes?: number;\n /** The same-turn duplicate guard's identity for this request. */\n requestKey?: string;\n /**\n * The caller's APPLICATION success rule for the delivered body. On a free or\n * entitled 2xx, a body that fails it is refused: nothing was paid. On the\n * PAID leg the money already moved, so the body is always delivered: one\n * that fails the rule, or that is past this client's own validation limit so\n * the rule never ran, comes back with `resultUnverified` and a\n * `resultCaveat` saying which.\n */\n resultSchema?: unknown;\n /**\n * The router's job seam: called once with the answer that delivered (free,\n * entitled or paid), or with a paid leg that timed out after its headers\n * came. A long job's status URL can be a header. Never part of `data`,\n * which `tenjin pay --json` prints.\n */\n onPaidLeg?: (leg: PaidLeg) => void;\n /**\n * THE CALL'S SPEND PLAN, which every router payment is signed against.\n * Handed the live price before the wallet is opened, it returns the slot an\n * admitted plan holds for this payment (`lib/spend-plan.ts`), or throws the\n * refusal: over the limits, the router's quote. Required in router mode: a\n * router payment no plan admitted is refused with nothing sent.\n */\n admit?: (amountAtomic: bigint) => Promise<PlanSlot>;\n}\n\n/** What {@link PayArgs.onPaidLeg} is handed. */\nexport interface PaidLeg {\n status?: number;\n header?: (name: string) => string | undefined;\n}\n\nexport interface PayDeps {\n fetchImpl?: typeof fetch;\n /** Cancel before transmission. The signed leg keeps its own settlement deadline. */\n signal?: AbortSignal;\n /** Legacy injection seam, no longer consulted: exact payment signing is offline. */\n readBalance?: typeof readUsdcBalance;\n provider?: WalletProvider;\n authorizer?: SpendAuthorizer;\n confirm?: (prompt: string) => Promise<boolean>;\n /** Resolver seam for the destination preflight; production leaves it unset. */\n destination?: DestinationOptions;\n /** The transport a failed paid call's chain read goes through; unset, the\n * call's own `fetchImpl`, else the global one. */\n chainFetch?: typeof fetch;\n}\n\ntype Lane = 'tenjin' | 'bazaar';\n\ntype RegistryWarning = Exclude<RegistryVerification, { outcome: 'verified' | 'unlisted' }> & {\n acknowledged: boolean;\n quote: PaymentRequirements & { url: string };\n};\n\nexport async function runPay(\n args: PayArgs,\n ctx: CommandContext,\n deps: PayDeps = {},\n): Promise<CommandResult> {\n if (isModelWorkerProcess())\n throw new CliError(\n 'REFUSED',\n 'Nested Tenjin payments are unavailable inside a model worker; use the native tools.',\n );\n const warnings: RegistryWarning[] = [];\n try {\n return await executePay(args, ctx, deps, warnings);\n } catch (err) {\n if (err instanceof CliError && warnings.length > 0) {\n throw new CliError(err.code, err.message, {\n exitCode: err.exitCode,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n details: {\n ...(typeof err.details === 'object' && err.details !== null ? err.details : {}),\n warnings,\n },\n cause: err,\n });\n }\n throw err;\n }\n}\n\nfunction checkPaymentActive(signal: AbortSignal | undefined): void {\n if (signal?.aborted)\n throw new CliError('REFUSED', 'The request was stopped before payment was sent.', {\n details: { reason: 'cancelled' },\n });\n}\n\nasync function executePay(\n args: PayArgs,\n ctx: CommandContext,\n deps: PayDeps,\n warnings: RegistryWarning[],\n): Promise<CommandResult> {\n const { signal } = deps;\n checkPaymentActive(signal);\n const router = args.execution === 'router' || args.terms !== undefined;\n if (router) {\n const terms = args.terms;\n if (\n args.ignoreWarnings === true ||\n !terms ||\n typeof terms.maxAmountAtomic !== 'string' ||\n !/^\\d+$/.test(terms.maxAmountAtomic) ||\n [terms.network, terms.asset, terms.payTo, terms.source].some(\n (v) => v !== undefined && (typeof v !== 'string' || v.trim().length === 0),\n )\n ) {\n throw new CliError(\n 'REFUSED',\n 'Router payments require valid advertised terms and cannot acknowledge registry warnings.',\n { details: { reason: 'invalid_router_terms' } },\n );\n }\n if (args.admit === undefined) {\n throw new CliError(\n 'REFUSED',\n \"A router payment is signed only against its call's spend plan, and this one has none; nothing was sent.\",\n { details: { reason: 'unplanned' } },\n );\n }\n }\n const settings = await resolveContextSettings(ctx);\n const maxPriceAtomic =\n args.maxPrice !== undefined ? BigInt(parseUsdToAtomic(args.maxPrice)) : undefined;\n // Filled once the wallet is opened; the payer client closes over it so\n // selection can run first without one.\n const openedSigner: { current?: TenjinSigner } = {};\n const url = args.url.trim();\n const lane = resolveLane(url, settings);\n // BEFORE the probe, and only on the third-party lane: the configured base URL\n // is the operator's own deployment and is legitimately a local origin in\n // development, while any other host is a destination something else chose, so\n // that is the one that has to prove it is not on this network.\n if (lane === 'bazaar') await assertPublicDestination(url, deps.destination ?? {});\n const method = resolveMethod(args);\n const operator = operatorHeaders(args.header, args.dataRaw !== undefined);\n const body = resolveBody(args, operator);\n const headers = {\n ...operator,\n ...specHeaders(args.specHeaders),\n ...callerHeaders(args.headers),\n };\n\n const legTimeoutMs = args.timeoutMs ?? ctx.flags.timeout;\n const fetchOpts = {\n timeoutMs: legTimeoutMs,\n // Both legs: the probe's 402 is money-path input, and the paid retry\n // carries a signed header (which pins redirects on its own; this pins the\n // probe too, so the challenge always comes from the URL that was gated).\n blockRedirects: true as const,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n ...body,\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n // A call can buy a file (a sound, an image): its bytes are kept whole,\n // never decoded as text. The router's tool saves them itself; a direct\n // pay writes them to a file and hands back its path (`keepBody`).\n binaryBody: true as const,\n ...(args.maxBytes !== undefined ? { maxBinaryBytes: args.maxBytes } : {}),\n method,\n };\n\n const fetchImpl = deps.fetchImpl ?? fetch;\n const prepaymentFetchOpts =\n signal === undefined\n ? fetchOpts\n : {\n ...fetchOpts,\n fetchImpl: ((input, init) => {\n checkPaymentActive(signal);\n return fetchImpl(input, {\n ...init,\n signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal,\n });\n }) satisfies typeof fetch,\n };\n checkPaymentActive(signal);\n const probe = await httpRequest(url, prepaymentFetchOpts);\n checkPaymentActive(signal);\n // The unpaid leg says so itself: the transport is shared with the paid retry\n // and asserts nothing about money either way.\n if (!probe.ok) {\n throw fetchFailureToCliError(probe, {\n fix: `Nothing was sent and nothing was paid. ${legFix(probe)}`,\n });\n }\n // A BINARY BODY ON A DIRECT PAY IS A FILE: written under the downloads\n // directory, and its path is what comes back. The router's provider leg\n // keeps the bytes for its own tool to save. A quote writes nothing: a free\n // file it met is described, and a run without `--quote` saves it.\n const keep = async (res: HttpResponse): Promise<SavedBody | undefined> =>\n router ? undefined : args.quote === true ? describeBody(res) : keepBody(ctx.dataDir, url, res);\n if (probe.status >= 200 && probe.status < 300) {\n const caveat = assertUsableResult(args.resultSchema, probe.text, probe.status, 'free');\n args.onPaidLeg?.({ status: probe.status, header: probe.header });\n const saved = await keep(probe);\n return deliver(url, lane, probe, {\n paid: false,\n ...(caveat !== undefined ? { caveat } : {}),\n ...(saved !== undefined ? { saved } : {}),\n printBody: args.printBody === true,\n });\n }\n if (probe.status !== 402) {\n // THE PROVIDER'S OWN WORDS, when it sent `{error: {message}}`: a free docs\n // lookup's 404 says no library matched and to use your own tools, which a\n // bare status line turned into \"retry\". A 404 is the endpoint's answer, not\n // a transient failure, so it is never told to retry either.\n const said = providerMessage(probe.json);\n throw new CliError(\n 'API_UNREACHABLE',\n `${url} answered ${probe.status}${said === null ? '.' : `: ${said}`}`,\n {\n fix:\n probe.status === 404\n ? 'Nothing was paid. The same request will answer 404 again.'\n : 'Check the URL and the endpoint status, then retry.',\n details: { status: probe.status, body: probe.json, ...providerError(probe.text) },\n },\n );\n }\n\n // An anonymous free contract has no payee. A zero-price x402 spec still\n // names one and may need sign-in to re-read an entitled result.\n if (router && BigInt(args.terms!.maxAmountAtomic!) === 0n && args.terms!.payTo === undefined) {\n throw new CliError(\n 'REGISTRY_MISMATCH',\n 'This lookup was advertised as free, but the endpoint requires payment.',\n {\n fix: 'Nothing was signed or paid. Use your usual tools for this lookup.',\n details: { status: 402, advertised: args.terms },\n },\n );\n }\n\n const paymentRequired = decodeChallenge(probe, url);\n // The client is built BEFORE the wallet is opened on purpose: selection needs\n // only the registered networks and the policies, never a key, so an\n // unpayable or unverifiable deal is refused before a signer exists.\n const payer = createPayerClient(() => signerOrThrow(openedSigner));\n const requirement = selectRequirement(payer.core, paymentRequired, args.terms);\n // `--quote` is a READ: the 402 is reported as it came, with the entry the\n // paid path would sign marked by the same selection. Nothing below this line\n // runs, so no wallet is opened and nothing is signed.\n if (args.quote === true) {\n return deliverQuote(url, lane, probe, paymentRequired, requirement, args.printBody === true);\n }\n // A SELLER THAT ASKS ONLY FOR A SIGN-IN: a 402 offering no payment, with\n // its own sign-in-with-x challenge, as Monid answers a poll of a run it was\n // paid for. It is signed only for a GET, as a poll is, when the challenge\n // matches the responding origin and the ledger shows this wallet paid\n // that host, and nothing is paid on this path. A write behind a sign-in could spend the wallet's credit with the\n // seller off-protocol, so it is refused unsigned. The router's provider leg\n // never takes it: its job polls answer the same challenge in\n // `router/jobs.ts`, through {@link signInForPoll}.\n const signIn = router ? undefined : signInOnlyChallenge(paymentRequired);\n if (signIn !== undefined) {\n if (method !== 'GET') {\n throw new CliError(\n 'REFUSED',\n `${new URL(url).host} asks the wallet that paid it to sign in, and nothing was signed: a sign-in answers only a GET, and this is a ${method}.`,\n {\n fix: 'Nothing was signed or paid. Fetch the result with a plain GET (no -X, no body).',\n details: { status: 402, reason: 'sign_in_method', signIn: true },\n },\n );\n }\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n const answer = await answerSignInChallenge(paymentRequired, signIn, url, {\n address: async () => (await describeOpenable(provider)).address,\n paidHost: (host, address) => walletPaidHost(ctx.dataDir, host, address),\n signer: () => openWallet(provider),\n });\n if ('refused' in answer) {\n throw new CliError(\n 'REFUSED',\n `${new URL(url).host} asks the wallet that paid it to sign in, and nothing was signed: ${answer.reason}.`,\n {\n fix:\n answer.refused === 'unpaid'\n ? 'Nothing was signed or paid. This seller returns the result only to the wallet that paid for it; sign in from that wallet.'\n : answer.refused === 'payer_unknown'\n ? 'Nothing was signed or paid. The payment was recorded before this CLI kept the wallet that paid, so it cannot show this wallet paid; `tenjin payments` lists it.'\n : 'Nothing was signed or paid.',\n details: { status: 402, reason: `sign_in_${answer.refused}`, signIn: true },\n },\n );\n }\n const signed = await httpRequest(url, {\n ...prepaymentFetchOpts,\n headers: { ...headers, ...answer.headers },\n });\n checkPaymentActive(signal);\n if (!signed.ok) {\n throw fetchFailureToCliError(signed, {\n fix: `Nothing was paid: the request carried a sign-in, not a payment. ${legFix(signed)}`,\n });\n }\n if (signed.status >= 200 && signed.status < 300) {\n const caveat = assertUsableResult(args.resultSchema, signed.text, signed.status, 'signed-in');\n const saved = await keep(signed);\n return deliver(url, lane, signed, {\n paid: false,\n signedIn: true,\n ...(caveat !== undefined ? { caveat } : {}),\n ...(saved !== undefined ? { saved } : {}),\n printBody: args.printBody === true,\n });\n }\n const said = providerMessage(signed.json);\n throw new CliError(\n 'API_UNREACHABLE',\n signed.status === 402\n ? `${new URL(url).host} did not accept this wallet's sign-in.`\n : `${url} answered ${signed.status} to this wallet's sign-in${said === null ? '.' : `: ${said}`}`,\n {\n fix: 'Nothing was paid: the request carried a sign-in, not a payment. This seller returns the result only to the wallet that paid for it.',\n details: { status: signed.status, body: signed.json, ...providerError(signed.text) },\n },\n );\n }\n if (requirement === undefined) {\n throw noMatchingEntry(paymentRequired, args.terms);\n }\n // The FIRST-SEEN amount: a later challenge may never cost more than this.\n const firstSeenAmount = BigInt(requirement.amount);\n const host = new URL(url).host;\n\n // Both checks run BEFORE the wallet is even opened: an unverifiable deal must\n // not reach a signer. Terms a caller was given bind on EVERY lane, since a\n // routing decision can name a contract on the configured origin too; the\n // registry check is the Bazaar lane's own.\n let registry: string | undefined;\n let termsLabel: string | undefined;\n if (args.terms !== undefined) termsLabel = assertWithinTerms(args.terms, requirement);\n else if (lane === 'bazaar' && paymentRequired.extensions?.[SIGN_IN_WITH_X] === undefined) {\n registry = await checkRegistry(\n settings,\n url,\n requirement,\n ctx,\n args.ignoreWarnings === true,\n warnings,\n );\n }\n // THE CALL'S PLAN ADMITS ONLY A PAYMENT STILL NEEDED. With no entitlement\n // to check, it is admitted here, at the price first seen, before the wallet\n // is opened; over the limits, the refusal is the router's quote. A seller\n // that takes sign-in-with-x is asked first, below: a wallet that already\n // owns the result re-reads it free, and is never quoted a payment for it.\n const entitlement = paymentRequired.extensions?.[SIGN_IN_WITH_X] !== undefined;\n checkPaymentActive(signal);\n let slot = router && !entitlement ? await args.admit!(firstSeenAmount) : undefined;\n\n checkPaymentActive(signal);\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n const signer = await openWallet(provider);\n openedSigner.current = signer;\n checkPaymentActive(signal);\n\n // The standard sign-in-with-x extension, same sequence as `buy`: when the 402\n // advertises it, an entitled wallet re-reads FREE before any payment exists,\n // and the re-check doubles as the fresh-challenge refetch the payment is\n // built against. The signature binds to the TARGET origin (host-with-port),\n // so a foreign seller gets a credential worth nothing anywhere else.\n let effectiveChallenge = paymentRequired;\n let effectiveRequirement = requirement;\n if (entitlement) {\n const siwxHeader = await buildSiwxHeader(signer, {\n baseUrl: new URL(url).origin,\n chainId: requirement.network,\n });\n const recheck = await httpRequest(url, {\n ...prepaymentFetchOpts,\n headers: { ...headers, [SIWX_HEADER]: siwxHeader },\n });\n checkPaymentActive(signal);\n if (!recheck.ok) throw fetchFailureToCliError(recheck);\n if (recheck.status >= 200 && recheck.status < 300) {\n const caveat = assertUsableResult(\n args.resultSchema,\n recheck.text,\n recheck.status,\n 'entitled',\n );\n args.onPaidLeg?.({ status: recheck.status, header: recheck.header });\n const saved = await keep(recheck);\n return deliver(url, lane, recheck, {\n paid: false,\n entitled: true,\n ...(caveat !== undefined ? { caveat } : {}),\n ...(saved !== undefined ? { saved } : {}),\n printBody: args.printBody === true,\n });\n }\n if (recheck.status !== 402) {\n throw new CliError(\n 'API_UNREACHABLE',\n `${url} answered ${recheck.status} on the entitlement re-check.`,\n {\n fix: 'Retry; if it persists the endpoint looks misconfigured.',\n details: { status: recheck.status, body: recheck.json, ...providerError(recheck.text) },\n },\n );\n }\n effectiveChallenge = decodeChallenge(recheck, url);\n const fresh = selectRequirement(payer.core, effectiveChallenge, args.terms);\n if (fresh === undefined) {\n throw noMatchingEntry(effectiveChallenge, args.terms);\n }\n // Refuse a price bump between the first look and signing, exactly as `buy`.\n if (BigInt(fresh.amount) > firstSeenAmount) {\n throw new CliError('PAYMENT_FAILED', 'The price increased before signing; refusing to pay.', {\n fix: 'Re-run `tenjin pay` to review the new price, and set --max-price to cap it.',\n details: {\n firstSeenAtomic: firstSeenAmount.toString(),\n currentAtomic: fresh.amount,\n },\n });\n }\n if (\n fresh.scheme !== requirement.scheme ||\n fresh.network !== requirement.network ||\n fresh.asset.toLowerCase() !== requirement.asset.toLowerCase() ||\n fresh.payTo.toLowerCase() !== requirement.payTo.toLowerCase() ||\n JSON.stringify(fresh.extra) !== JSON.stringify(requirement.extra)\n ) {\n throw new CliError(\n 'PAYMENT_FAILED',\n 'The payment terms changed before signing; refusing to pay.',\n { fix: 'Review a fresh challenge before paying again.' },\n );\n }\n effectiveRequirement = fresh;\n // The challenge it will actually SIGN is checked again: the store answers\n // the registry question without a network round trip in the common case.\n if (args.terms !== undefined) termsLabel = assertWithinTerms(args.terms, fresh);\n else if (lane === 'bazaar') {\n registry = await checkRegistry(\n settings,\n url,\n fresh,\n ctx,\n args.ignoreWarnings === true,\n warnings,\n );\n }\n }\n const amountAtomic = BigInt(effectiveRequirement.amount);\n checkPaymentActive(signal);\n if (router && entitlement) slot = await args.admit!(amountAtomic);\n if (router) {\n const refusal = spendSlot(slot, amountAtomic);\n if (refusal === 'above_plan') {\n throw new CliError(\n 'PAYMENT_FAILED',\n `The live price ($${toMoney(amountAtomic.toString()).usd}) is above the $${toMoney(slot!.amountAtomic.toString()).usd} this call planned for it, so nothing was signed.`,\n {\n fix: 'Call again for a fresh plan at the new price.',\n details: {\n reason: 'above_plan',\n plannedAtomic: slot!.amountAtomic.toString(),\n live: { amount: amountAtomic.toString() },\n },\n },\n );\n }\n if (refusal !== null) {\n throw new CliError(\n 'REFUSED',\n \"A router payment is signed only against an unspent slot of its call's spend plan; nothing was signed.\",\n { details: { reason: refusal } },\n );\n }\n }\n // A PLAN A PERSON APPROVED is theirs, as a manual payment is: it may pass\n // the automatic limits, and it does not use up the automatic budget.\n const approved = slot?.approved === true;\n\n const authorizer = resolveSpendAuthorizer(\n ctx,\n settings.policy,\n deps.authorizer !== undefined ? { authorizer: deps.authorizer } : {},\n );\n // The host is the creator identity here (`allowlistCreators` users pin\n // hosts); the gate itself is shared with `buy` so the two verbs cannot drift.\n const verifiedVia = registry ?? termsLabel;\n const via = verifiedVia !== undefined ? ` (${sanitizeForTerminal(verifiedVia)})` : '';\n const mode = router && !approved ? 'automatic' : 'manual';\n checkPaymentActive(signal);\n const reservationId = await gateSpend({\n mode,\n ctx,\n authorizer,\n amountAtomic,\n creator: host,\n ...(maxPriceAtomic !== undefined ? { maxPriceAtomic } : {}),\n ...(args.requestKey !== undefined ? { requestKey: args.requestKey } : {}),\n yes: args.yes === true || approved,\n ...(deps.confirm !== undefined ? { confirm: deps.confirm } : {}),\n payeeLabel: `${sanitizeForTerminal(url)}${via}; recipient ${sanitizeForTerminal(effectiveRequirement.payTo)}, ${sanitizeForTerminal(effectiveRequirement.network)} / ${sanitizeForTerminal(effectiveRequirement.asset)}`,\n allowlistSubject: 'this host',\n notConfirmedMessage: 'Payment not confirmed.',\n });\n\n // Cancellation or signing failure before transmission releases the reservation.\n let payment: Awaited<ReturnType<typeof buildExactPayment>>;\n try {\n checkPaymentActive(signal);\n // The SIGNED entry is the CHECKED entry, by construction: the challenge is\n // narrowed to the one selection everything above ran against, so a seller\n // advertising several chains cannot have one entry priced and another\n // signed. Without this the builder re-picked `accepts[0]`.\n payment = await buildExactPayment(effectiveChallenge, signer, effectiveRequirement);\n } catch (err) {\n await authorizer.release(reservationId);\n throw err;\n }\n\n // Once the signed EIP-3009 authorization leaves the process, it is a\n // bearer instrument: the counterparty can settle it whatever it answers, or\n // if it answers nothing. So EVERY post-transmission outcome commits the\n // reservation; money that may move is money accounted. Releasing here let a\n // hostile registry-listed seller answer 402 after each signature while\n // sessionBudget counted zero of the authorizations it was stacking up.\n // (httpRequest never throws on transport failure; it returns ok:false.)\n // A spec's deadline may lengthen this leg, never shorten it: the\n // authorization has left, and a cut here loses a result already paid for.\n const paidTimeoutMs = paidLegTimeoutMs(\n effectiveRequirement,\n Math.max(legTimeoutMs, ctx.flags.timeout),\n );\n // The HTTP helper can await request preparation before invoking fetch.\n let transmitted = false;\n const paid = await httpRequest(url, {\n ...fetchOpts,\n timeoutMs: paidTimeoutMs,\n headers: { ...headers, ...payment.headers },\n ...(signal !== undefined\n ? {\n fetchImpl: ((input, init) => {\n checkPaymentActive(signal);\n transmitted = true;\n return fetchImpl(input, init);\n }) satisfies typeof fetch,\n }\n : {}),\n });\n if (!transmitted && signal?.aborted) {\n await authorizer.release(reservationId);\n checkPaymentActive(signal);\n }\n await authorizer.commit(reservationId, payment.amountAtomic, {\n mode,\n ...(payment.authorization !== undefined ? { nonce: payment.authorization.nonce } : {}),\n });\n // From here, output this process loses follows a payment (lib/flush-stdio).\n notePaymentSent();\n // EVERY DIRECT PAY THAT SIGNED goes in the paid ledger, as a `request`\n // call does (a router leg is recorded by `request` itself): a delivered one\n // with the file it saved, so a seller's later sign-in challenge can be\n // answered for a host this wallet paid; one that may not have settled so\n // the same reconcile pass gives its amount back to the daily budget once the\n // chain is past its `validBefore` and shows the authorization unused.\n const recordDirect = async (entry: {\n settlement: Settlement;\n txHash?: string;\n reportedTxHash?: string;\n savedFiles?: string[];\n }): Promise<void> => {\n if (router) return;\n await appendPaidRecord(ctx.dataDir, {\n version: 1,\n ts: new Date().toISOString(),\n capabilityId: 'pay',\n provider: host,\n url,\n sent: recordedSent(args.data ?? args.dataRaw ?? ''),\n amountAtomic: payment.amountAtomic.toString(),\n ...(entry.txHash !== undefined ? { txHash: entry.txHash } : {}),\n ...(entry.reportedTxHash !== undefined ? { reportedTxHash: entry.reportedTxHash } : {}),\n settlement: entry.settlement,\n savedFiles: entry.savedFiles ?? [],\n payer: payment.payer,\n ...(payment.authorization !== undefined ? { authorization: payment.authorization } : {}),\n });\n };\n // A PAID CALL THAT FAILED MAY STILL HAVE BEEN CHARGED: a seller can settle\n // and then answer an error (AiSpace's voiceover queue did). Only the chain\n // proves it: read once, as reconcile reads it, on the payment's own network\n // and token. An unused authorization, or one this machine cannot read,\n // stays unknown: it can still be settled until its `validBefore`.\n //\n // A SELLER THAT SAYS IT SETTLED (`success: true` naming a tx) is reported,\n // not believed: its tx rides as `reportedTxHash`, and the row stays unknown\n // for reconcile, which gives an unused authorization back to the daily\n // budget. Its claim still keeps a quote used, so it is never paid twice.\n const failedSettlement = async (\n header: ((name: string) => string | undefined) | undefined,\n ): Promise<{\n settlement: 'settled' | 'unknown';\n reportedTxHash?: string;\n /** The chain shows it charged. */\n charged?: string;\n /** Only the seller says it charged. */\n reported?: string;\n }> => {\n const reportedTxHash = header !== undefined ? settledTx({ header }) : undefined;\n const tx = reportedTxHash !== undefined ? { reportedTxHash } : {};\n const settlement = await chargedOnChain(payment.authorization, settings.rpcUrl, {\n ...((deps.chainFetch ?? deps.fetchImpl) !== undefined\n ? { fetchImpl: deps.chainFetch ?? deps.fetchImpl }\n : {}),\n });\n if (settlement === 'settled') {\n return {\n settlement,\n ...tx,\n charged: 'The chain shows the authorization was used, so it was charged.',\n };\n }\n return reportedTxHash !== undefined\n ? {\n settlement,\n ...tx,\n reported: `The seller reports a charge (tx ${reportedTxHash}), but the chain does not show it yet. Check \\`tenjin payments\\` before paying again.`,\n }\n : { settlement };\n };\n if (paid.ok || paid.header !== undefined) {\n args.onPaidLeg?.({\n ...(paid.status !== undefined ? { status: paid.status } : {}),\n ...(paid.header !== undefined ? { header: paid.header } : {}),\n });\n }\n // A TRANSPORT failure on this leg is a post-transmission outcome like any\n // other: the authorization has left, the reservation is committed above, and\n // a receipt that said nothing was paid would report a provider cost of zero\n // for money the ledger has already counted. The transport's own reason and\n // code survive; only the fix and the amounts are this leg's to state.\n if (!paid.ok) {\n // A LONG JOB THAT NAMED WHERE ITS RESULT WILL BE: the seller is still\n // working, so the agent is pointed there rather than told it failed.\n // Settlement is just as unknown as on any other timeout, unless the chain\n // already shows it.\n const statusUrl = paid.kind === 'timeout' ? statusUrlOf(paid, url) : null;\n const { settlement, reportedTxHash, charged, reported } = await failedSettlement(paid.header);\n await recordDirect({ settlement, ...(reportedTxHash !== undefined ? { reportedTxHash } : {}) });\n const known = charged ?? reported;\n if (statusUrl !== null) {\n throw new CliError(\n 'NETWORK_ERROR',\n `The seller is still working on this: no result within ${Math.round(paidTimeoutMs / 1000)} s, and it named a status URL to check: ${statusUrl}`,\n {\n fix:\n (known !== undefined\n ? `${known} `\n : 'The authorization was transmitted and settlement is unknown until the job ends; it is recorded as transmitted exposure. ') +\n 'Do not pay again: check the status URL for the result.',\n details: {\n statusUrl,\n amountAtomic: payment.amountAtomic.toString(),\n settlement,\n ...(reportedTxHash !== undefined ? { reportedTxHash } : {}),\n payer: payment.payer,\n ...(payment.authorization !== undefined\n ? { authorization: payment.authorization }\n : {}),\n },\n },\n );\n }\n throw fetchFailureToCliError(paid, {\n fix:\n (known !== undefined\n ? `The authorization was transmitted. ${known} `\n : 'The authorization was transmitted and settlement is unknown; it is recorded as transmitted exposure. ') +\n `Do not simply retry: each attempt signs a fresh authorization. ${legFix(paid)}`,\n details: {\n amountAtomic: payment.amountAtomic.toString(),\n settlement,\n ...(reportedTxHash !== undefined ? { reportedTxHash } : {}),\n payer: payment.payer,\n ...(payment.authorization !== undefined ? { authorization: payment.authorization } : {}),\n },\n });\n }\n if (paid.status >= 200 && paid.status < 300) {\n let caveat: string | undefined;\n if (args.resultSchema !== undefined) {\n const check = validateResultBody(args.resultSchema, paid.text);\n // A PAID BODY IS ALWAYS DELIVERED. The authorization has already left and\n // the money moved, so the success rule is a check on the body, never a\n // reason to withhold it: withholding charged the caller and threw the\n // product away. A body past this client's validation limit (never\n // checked) and one that fails the rule (checked, and missed) both come\n // back whole, flagged unverified, with a caveat that says which.\n if (check.unvalidated === true) caveat = unvalidatedCaveat(check);\n else if (!check.valid) caveat = failedRuleCaveat(check);\n }\n const saved = await keep(paid);\n const txHash = settlementTx(paid);\n await recordDirect({\n settlement: txHash !== undefined ? 'settled' : 'unknown',\n ...(txHash !== undefined ? { txHash } : {}),\n savedFiles: saved?.savedTo !== undefined ? [saved.savedTo] : [],\n });\n return deliver(url, lane, paid, {\n paid: true,\n warnings,\n amountAtomic: payment.amountAtomic,\n requirement: effectiveRequirement,\n payer: payment.payer,\n ...(payment.authorization !== undefined ? { authorization: payment.authorization } : {}),\n ...(registry !== undefined ? { registry } : {}),\n ...(caveat !== undefined ? { caveat } : {}),\n ...(saved !== undefined ? { saved } : {}),\n printBody: args.printBody === true,\n });\n }\n // Still 402 (payment rejected) or anything else: nothing was delivered, but\n // the seller holds a live authorization, so the amount stays counted and the\n // fix must NOT coach a retry loop, since each retry signs a fresh authorization.\n //\n // SETTLEMENT IS RESOLVED FIRST. A seller can settle and still answer 402\n // `insufficient_funds`: read as short of funds, that charged slot reopened\n // an approved quote, and the same quote could pay the seller again on the\n // next yes. A charged payment keeps its quote used, its message says it was\n // charged, and the seller's reason rides in the details. One the seller\n // only says it took keeps its quote used too, and says so.\n const { settlement, reportedTxHash, charged, reported } = await failedSettlement(paid.header);\n await recordDirect({ settlement, ...(reportedTxHash !== undefined ? { reportedTxHash } : {}) });\n const known = charged ?? reported;\n // A SELLER THAT SAYS IT DID NOT SETTLE is named as saying so, with its reason\n // from the payment-response header: its body can be an empty `{}`. A 402's\n // own reason rides in its PAYMENT-REQUIRED header's `error`. The\n // authorization stays valid until it expires, so settlement is unknown\n // unless the chain shows it taken.\n const refusal = settlementRefusal(paid);\n const sellerShort = paymentShortOfFunds(paid);\n const paymentError = paymentRequiredError(payer.http, paid);\n const lowFunds = sellerShort && known === undefined;\n if (lowFunds) markShortOfFunds(slot);\n const said = sellerShort\n ? known !== undefined\n ? 'The seller said the wallet does not hold enough USDC for this payment.'\n : LOW_FUNDS_MESSAGE\n : refusal !== undefined\n ? `The endpoint did not settle the payment${refusal.reason !== undefined ? `: ${refusal.reason.replace(/\\.+$/, '')}` : ''}.`\n : paid.status === 402\n ? `Payment was not accepted by the endpoint${paymentError !== undefined ? `: ${paymentError.replace(/\\.+$/, '')}` : ''}.`\n : known !== undefined\n ? `The endpoint answered ${paid.status} on the paid request.`\n : `The endpoint answered ${paid.status} on the paid request; whether it settled is unknown.`;\n throw new CliError(\n 'PAYMENT_FAILED',\n charged !== undefined\n ? `The payment was charged, and the endpoint answered ${paid.status} with no result. ${charged}`\n : reported !== undefined\n ? `The endpoint answered ${paid.status} with no result. ${reported}`\n : said,\n {\n fix:\n charged !== undefined\n ? \"The payment was charged and is recorded as settled. Do not simply retry: each attempt pays again. Read the seller's reason in the details, fix the request, and quote again.\"\n : reported !== undefined\n ? \"The payment is recorded as transmitted exposure until the chain shows it taken. Do not simply retry: each attempt signs a fresh authorization. Read the seller's reason in the details, fix the request, and quote again.\"\n : lowFunds\n ? `Ask the person once to add funds; on yes, run \\`tenjin fund\\`. ${LOW_FUNDS_TAIL}`\n : refusal !== undefined\n ? 'The seller reported that nothing settled, but the signed authorization stays valid until it expires, so it is recorded as transmitted exposure. Do not simply retry: each attempt signs a fresh authorization. Use a different service for this.'\n : 'The signed payment already left and is recorded as transmitted exposure; the endpoint may still settle it. Do not simply retry: each attempt signs a fresh authorization. Verify the endpoint (and this listing, if Bazaar) before paying again.',\n // The amount rides on the failure so a caller can report what is at risk\n // rather than a zero.\n details: {\n status: paid.status,\n body: paid.json,\n ...providerError(paid.text),\n ...(known !== undefined ? { sellerReason: said } : {}),\n ...(paymentError !== undefined ? { paymentError } : {}),\n ...(refusal?.reason !== undefined ? { settlementError: refusal.reason } : {}),\n amountAtomic: payment.amountAtomic.toString(),\n settlement,\n ...(reportedTxHash !== undefined ? { reportedTxHash } : {}),\n payer: payment.payer,\n ...(payment.authorization !== undefined ? { authorization: payment.authorization } : {}),\n },\n },\n );\n}\n\n/**\n * THE PAID LEG WAITS AS LONG AS THE SELLER SAID IT WOULD TAKE, within reason.\n * A signed authorization is already out when this leg starts, so a client\n * timeout here abandons money the seller can still settle: a 10 s default cut\n * off a provider advertising 360 s of work and threw its answer away. The\n * requirement's `maxTimeoutSeconds` is that promise; it is clamped to\n * {@link MAX_PAID_LEG_TIMEOUT_MS} so a hostile seller cannot hang the caller,\n * and it never shortens what the user asked for with `--timeout`, nor does a\n * spec's `timeoutS`. The probe leg takes the spec's deadline, else the CLI\n * timeout: nothing is at stake there.\n */\nexport const MAX_PAID_LEG_TIMEOUT_MS = 120_000;\n\nexport function paidLegTimeoutMs(requirement: PaymentRequirements, cliTimeoutMs: number): number {\n const advertised = requirement.maxTimeoutSeconds;\n if (typeof advertised !== 'number' || !Number.isFinite(advertised) || advertised <= 0) {\n return cliTimeoutMs;\n }\n return Math.max(cliTimeoutMs, Math.min(advertised * 1000, MAX_PAID_LEG_TIMEOUT_MS));\n}\n\n/**\n * WHAT A ROUTER CALL WILL COST, from one unpaid probe: the live 402's amount\n * on the entry this call would sign, held to the advertised terms, with\n * nothing signed and nothing reserved. It is the number a single call gates\n * on, so several takes of one call are checked at it rather than at the\n * spec's ceiling: a price that varies by input is quoted for this input.\n * A probe that answers 2xx is free: 0. A seller that takes sign-in-with-x is\n * asked as the paid leg asks it, so a wallet that already owns the result\n * quotes 0 and is never planned a payment for it. Every refusal is the paid\n * leg's own, with nothing sent but the probe and that re-read.\n */\nexport async function quoteRouterCall(\n args: Pick<PayArgs, 'url' | 'method' | 'headers' | 'specHeaders' | 'rawBody' | 'timeoutMs'> & {\n terms: AdvertisedTerms;\n },\n ctx: CommandContext,\n deps: PayDeps = {},\n): Promise<bigint> {\n const settings = await resolveContextSettings(ctx);\n const url = args.url.trim();\n if (resolveLane(url, settings) === 'bazaar') {\n await assertPublicDestination(url, deps.destination ?? {});\n }\n const headers = { ...specHeaders(args.specHeaders), ...callerHeaders(args.headers) };\n const probe = await httpRequest(url, {\n timeoutMs: args.timeoutMs ?? ctx.flags.timeout,\n blockRedirects: true,\n binaryBody: true,\n method: resolveMethod(args),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n ...(args.rawBody !== undefined ? { rawBody: args.rawBody } : {}),\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n });\n if (!probe.ok) {\n throw fetchFailureToCliError(probe, {\n fix: `Nothing was sent and nothing was paid. ${legFix(probe)}`,\n });\n }\n if (probe.status >= 200 && probe.status < 300) return 0n;\n if (probe.status !== 402) {\n const said = providerMessage(probe.json);\n throw new CliError(\n 'API_UNREACHABLE',\n `${url} answered ${probe.status}${said === null ? '.' : `: ${said}`}`,\n {\n fix: 'Nothing was paid.',\n details: { status: probe.status, body: probe.json, ...providerError(probe.text) },\n },\n );\n }\n const challenge = decodeChallenge(probe, url);\n const payer = createPayerClient(() => signerOrThrow({}));\n const requirement = selectRequirement(payer.core, challenge, args.terms);\n if (requirement === undefined) throw noMatchingEntry(challenge, args.terms);\n assertWithinTerms(args.terms, requirement);\n if (challenge.extensions?.[SIGN_IN_WITH_X] === undefined) return BigInt(requirement.amount);\n const signer = await openWallet(\n resolveWalletProvider(ctx, deps.provider !== undefined ? { provider: deps.provider } : {}),\n );\n const recheck = await httpRequest(url, {\n timeoutMs: args.timeoutMs ?? ctx.flags.timeout,\n blockRedirects: true,\n binaryBody: true,\n method: resolveMethod(args),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n ...(args.rawBody !== undefined ? { rawBody: args.rawBody } : {}),\n headers: {\n ...headers,\n [SIWX_HEADER]: await buildSiwxHeader(signer, {\n baseUrl: new URL(url).origin,\n chainId: requirement.network,\n }),\n },\n });\n if (!recheck.ok) throw fetchFailureToCliError(recheck);\n if (recheck.status >= 200 && recheck.status < 300) return 0n;\n if (recheck.status !== 402) {\n throw new CliError(\n 'API_UNREACHABLE',\n `${url} answered ${recheck.status} on the entitlement re-check.`,\n {\n fix: 'Nothing was paid.',\n details: { status: recheck.status, body: recheck.json, ...providerError(recheck.text) },\n },\n );\n }\n const fresh = decodeChallenge(recheck, url);\n const owed = selectRequirement(payer.core, fresh, args.terms);\n if (owed === undefined) throw noMatchingEntry(fresh, args.terms);\n assertWithinTerms(args.terms, owed);\n return BigInt(owed.amount);\n}\n\n/** Which lane may pay this URL, or the exact refusal. */\nfunction resolveLane(url: string, settings: ResolvedSettings): Lane {\n let target: URL;\n try {\n target = new URL(url);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(url)}`, {\n fix: 'Pass an absolute http(s) URL.',\n });\n }\n if (target.protocol !== 'http:' && target.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(url)}`, {\n fix: 'Pass an absolute http(s) URL.',\n });\n }\n // Same deployment, not merely the same spelling: without this a URL on the\n // deployment's other origin falls through to the Bazaar lane, which then\n // refuses it as a third-party endpoint or pays it under registry rules meant\n // for one. The SIWX signature below binds to the TARGET origin either way.\n if (isSameDeployment(target.origin, new URL(settings.baseUrl).origin)) return 'tenjin';\n if (target.protocol !== 'https:') {\n throw new CliError('USAGE', 'The Bazaar lane pays https endpoints only.', {\n fix: 'Use a public HTTPS endpoint.',\n });\n }\n return 'bazaar';\n}\n\ntype Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\nconst METHODS: ReadonlySet<string> = new Set<Method>(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);\n/** The methods that carry a body. GET and DELETE never do here. */\nconst BODY_METHODS: ReadonlySet<string> = new Set<Method>(['POST', 'PUT', 'PATCH']);\n\nfunction hasBody(args: PayArgs): boolean {\n return args.data !== undefined || args.dataRaw !== undefined || args.rawBody !== undefined;\n}\n\nfunction resolveMethod(args: PayArgs): Method {\n const method = args.method?.toUpperCase() ?? (hasBody(args) ? 'POST' : 'GET');\n if (!METHODS.has(method)) {\n throw new CliError('USAGE', `Unsupported method ${JSON.stringify(args.method)}`, {\n fix: 'Use -X GET, POST, PUT, PATCH or DELETE.',\n });\n }\n if (hasBody(args) && !BODY_METHODS.has(method)) {\n throw new CliError('USAGE', 'A request body needs -X POST, PUT or PATCH.', {\n fix: 'Drop the body, or pass -X POST, PUT or PATCH.',\n });\n }\n return method as Method;\n}\n\n/**\n * The one body this request carries, or none. `--data` is JSON and sets its\n * own content type; `--data-raw` goes byte for byte under the operator's\n * Content-Type; `rawBody` is the router's, already encoded. Two at once is a\n * usage error, never a silent pick.\n */\nfunction resolveBody(\n args: PayArgs,\n operator: Record<string, string>,\n): { jsonBody?: unknown; rawBody?: string } {\n const given = [args.data, args.dataRaw, args.rawBody].filter((b) => b !== undefined);\n if (given.length > 1) {\n throw new CliError('USAGE', 'Pass one request body: --data or --data-raw, not both.', {\n fix: 'Use --data for a JSON body, or --data-raw with its own Content-Type.',\n });\n }\n if (args.data !== undefined) return { jsonBody: parseBody(args.data) };\n if (args.dataRaw !== undefined) {\n if (operator['content-type'] === undefined) {\n throw new CliError('USAGE', 'A --data-raw body needs its content type.', {\n fix: \"Pass -H 'Content-Type: <type>' with --data-raw.\",\n });\n }\n return { rawBody: args.dataRaw };\n }\n return args.rawBody !== undefined ? { rawBody: args.rawBody } : {};\n}\n\n/**\n * The operator's `-H` lines, or a refusal. The opposite rule from\n * {@link callerHeaders}: a person typing the command may name any header the\n * endpoint asks for, except what this command signs or sets itself. Values\n * are bounded and single-line, the same bar the router's two names meet.\n * `content-type` is the operator's only with `--data-raw`, whose bytes this\n * command does not encode; `--data` is always JSON.\n */\nfunction operatorHeaders(lines: string[] | undefined, rawBody: boolean): Record<string, string> {\n if (lines === undefined) return {};\n const out: Record<string, string> = {};\n for (const line of lines) {\n const at = line.indexOf(':');\n const name = at > 0 ? line.slice(0, at).trim() : '';\n const value = at > 0 ? line.slice(at + 1).trim() : '';\n const problem = requestHeaderProblem(name, value, rawBody);\n if (problem === 'name') {\n throw new CliError('USAGE', `Not a request header: ${JSON.stringify(line)}`, {\n fix: \"Pass -H 'Name: value'.\",\n });\n }\n if (problem === 'reserved') {\n throw new CliError('USAGE', `This command sets the header ${JSON.stringify(name)} itself.`, {\n fix: 'Payment, sign-in, bypass and transport headers are never taken from -H. --data is always application/json; only --data-raw takes a Content-Type from -H.',\n });\n }\n if (problem === 'value') {\n throw new CliError(\n 'USAGE',\n `The value of ${JSON.stringify(name)} is too long or spans lines.`,\n {\n fix: 'Keep each -H value on one line, under 1,024 characters.',\n },\n );\n }\n const lowered = name.toLowerCase();\n if (lowered in out) {\n throw new CliError('USAGE', `The header ${JSON.stringify(name)} was given twice.`, {\n fix: 'Pass each header name once.',\n });\n }\n out[lowered] = value;\n }\n return out;\n}\n\n/**\n * The router's headers, or a refusal. Two names only: a decision composes\n * `accept` and `content-type`, and everything else on this request is either\n * this command's to set (the payment signature, the user agent) or the\n * operator's through `-H`.\n */\nfunction callerHeaders(headers: Record<string, string> | undefined): Record<string, string> {\n if (headers === undefined) return {};\n const allowed = new Set(['accept', 'content-type']);\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n const lowered = name.toLowerCase();\n if (!allowed.has(lowered) || value.length > 1_024 || /[\\r\\n]/.test(value)) {\n throw new CliError(\n 'USAGE',\n `This command will not send the header ${JSON.stringify(name)}.`,\n {\n fix: 'Only bounded accept and content-type headers ride on a paid request.',\n },\n );\n }\n out[lowered] = value;\n }\n return out;\n}\n\n/**\n * A catalog spec's fixed headers, or a refusal. The spec was checked when its\n * request was built; this is the last stop before the wire, so the same\n * check runs again.\n */\nfunction specHeaders(headers: Record<string, string> | undefined): Record<string, string> {\n if (headers === undefined) return {};\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (requestHeaderProblem(name, value) !== null) {\n throw new CliError(\n 'USAGE',\n `This command will not send the header ${JSON.stringify(name)}.`,\n {\n fix: 'A spec header is a bounded, single-line value, and never a payment, sign-in, bypass or transport header.',\n },\n );\n }\n out[name.toLowerCase()] = value;\n }\n return out;\n}\n\nfunction parseBody(data: string | undefined): unknown {\n if (data === undefined) return undefined;\n try {\n return JSON.parse(data);\n } catch {\n throw new CliError('USAGE', 'The --data value is not valid JSON.', {\n fix: 'Pass a JSON object/array/string, e.g. --data \\'{\"question\":\"...\"}\\'.',\n });\n }\n}\n\nfunction decodeChallenge(res: HttpResponse, url: string): PaymentRequired {\n const encoded = res.header(PAYMENT_REQUIRED_HEADER);\n if (encoded === undefined) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The 402 from ${url} carried no PAYMENT-REQUIRED header.`,\n {\n fix: 'The endpoint does not speak x402 v2; nothing was paid.',\n },\n );\n }\n try {\n return decodePaymentRequiredHeader(encoded);\n } catch (err) {\n throw new CliError('CONTRACT_MISMATCH', 'Could not decode the PAYMENT-REQUIRED header.', {\n cause: err,\n });\n }\n}\n\n/**\n * The caller's success rule, on EVERY delivery this command makes: a body that\n * fails it is not a result, whether it arrived free, by entitlement or paid.\n * Applying it only to the paid branch let a `{success:false}` body come back as\n * `fulfilled` the moment the wallet was already entitled.\n *\n * Returns the caveat for a body the rule could not be RUN against, so the three\n * branches treat an over-limit body the same way; `undefined` when the rule\n * passed or there was none.\n */\nfunction assertUsableResult(\n schema: unknown,\n body: string,\n status: number,\n how: 'free' | 'entitled' | 'signed-in',\n): string | undefined {\n if (schema === undefined) return undefined;\n const check = validateResultBody(schema, body);\n if (check.valid) return undefined;\n if (check.unvalidated === true) return unvalidatedCaveat(check);\n throw new CliError('CONTRACT_MISMATCH', 'The response is not a usable result.', {\n fix: `Nothing was paid on this ${how} delivery. The endpoint answered ${status} with a body that fails the success rule it was asked under.`,\n details: {\n status,\n reason: check.reason,\n ...(check.diagnosis !== undefined ? { diagnosis: check.diagnosis } : {}),\n paid: false,\n },\n });\n}\n\n/**\n * What the caller is told INSTEAD of a refusal when the success rule could not\n * run: the byte count, that the check was skipped, and that the body in hand is\n * unverified. It rides in the result rather than only in a log, because the\n * agent reading the envelope is the one that has to discount it.\n */\nfunction unvalidatedCaveat(check: ResultCheck): string {\n return `${check.reason ?? 'The result could not be validated.'} The body is delivered unverified: its shape was never checked against the success rule.`;\n}\n\n/** What the caller is told when a PAID body was checked and missed its success\n * rule: the rule that failed, and that the body is handed back unverified. */\nfunction failedRuleCaveat(check: ResultCheck): string {\n return `${check.reason ?? 'The result does not satisfy its success schema.'} The payment settled, so the body is delivered as received, unverified: treat it as possibly not the answer that was paid for.`;\n}\n\n/**\n * Headers a seller sends with the first byte of a long job to say where its\n * result can be checked. Treza sends `X-Status-Url`; another seller's name for\n * the same thing goes here.\n */\nconst STATUS_URL_HEADERS = ['x-status-url'];\n\n/** The https status URL a timed-out paid response named, resolved against the\n * paid URL, or null. Its bytes are the seller's: bounded, https only, same host. */\nfunction statusUrlOf(failure: FetchJsonFailure, requestUrl: string): string | null {\n for (const name of STATUS_URL_HEADERS) {\n const value = failure.header?.(name)?.trim();\n if (value === undefined || value.length === 0 || value.length > 2_048) continue;\n try {\n const status = new URL(value, requestUrl);\n if (status.protocol === 'https:' && status.host === new URL(requestUrl).host) {\n return status.toString();\n }\n } catch {\n // Not a URL: the next name, or the plain timeout.\n }\n }\n return null;\n}\n\n/** The transport's own remedy, when it has one, appended after the leg's\n * payment sentence so the two never contradict each other. */\nfunction legFix(failure: { kind: string }): string {\n return failure.kind === 'oversized-header'\n ? 'Raising `--max-http-header-size` on the node process that runs this CLI would let the header be read; that is an operator decision, not a default this build changes.'\n : '';\n}\n\n/** `{error: {message}}` from the provider, as one bounded plain line, or null.\n * It reaches a model's context, so control characters do not survive. */\nfunction providerMessage(body: unknown): string | null {\n const error = (body as { error?: unknown } | null | undefined)?.error;\n const message = (error as { message?: unknown } | null | undefined)?.message;\n if (typeof message !== 'string') return null;\n const line = message\n .replace(/[\\p{Cc}\\p{Cf}]/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 300);\n return line.length > 0 ? line : null;\n}\n\n/** Cap on {@link providerError}: enough for a provider's reason, never its page. */\nconst PROVIDER_ERROR_CHARS = 500;\n\n/**\n * WHY THE PROVIDER REFUSED, in its own words: the first\n * {@link PROVIDER_ERROR_CHARS} characters of a non-2xx body, redacted and on\n * one plain line, whatever its type. `body` above is the parse, which an HTML\n * error page has none of, and without this a 403 reached the agent as a bare\n * status. Other people's content, never instructions.\n */\nfunction providerError(text: string): { providerError?: string } {\n const line = sellerLine(text);\n return line.length > 0 ? { providerError: line } : {};\n}\n\n/** Seller text as one plain, redacted line of at most\n * {@link PROVIDER_ERROR_CHARS} characters; empty when nothing is left. */\nexport function sellerLine(text: string): string {\n // Masked in a window well past the cap, so a large page costs nothing and a\n // secret that starts inside the snippet is seen whole.\n const flat = sanitizeForTerminal(\n mask(text.slice(0, PROVIDER_ERROR_CHARS * 8)).replace(/\\s+/g, ' '),\n ).trim();\n const chars = Array.from(flat);\n return chars.length <= PROVIDER_ERROR_CHARS\n ? flat\n : `${chars.slice(0, PROVIDER_ERROR_CHARS).join('')}…`;\n}\n\n/** Nothing this caller may pay: no entry at all, or none on the advertised\n * scheme, network and asset. Refused before a signer is even opened. */\nfunction noMatchingEntry(challenge: PaymentRequired, terms: AdvertisedTerms | undefined): CliError {\n // No terms, or terms that pinned no chain and no token: the 402 simply\n // advertises nothing this wallet can pay, which the shared refusal already\n // names in the SDK's own vocabulary.\n // An entry on the terms' chain is the deal, in a transfer method this CLI\n // does not sign (Permit2, or another): the shared refusal names the method.\n const unsupportedMethod = challenge.accepts.some(\n (a) => !signsEip3009(a) && (terms?.network === undefined || a.network === terms.network),\n );\n if (\n terms === undefined ||\n (terms.network === undefined && terms.asset === undefined) ||\n unsupportedMethod\n ) {\n return noPayableRequirement(challenge.accepts);\n }\n const advertised = challenge.accepts.map((a) => `${a.scheme}/${a.network}/${a.asset}`);\n return new CliError(\n 'REGISTRY_MISMATCH',\n `The 402 advertises nothing on ${terms.network ?? 'any supported chain'} in ${terms.asset ?? 'any supported token'}, which is what this call was authorized against.`,\n {\n fix: 'Nothing was signed. The endpoint changed the deal since those terms were issued; ask for a fresh decision.',\n details: { advertised, terms },\n },\n );\n}\n\n/**\n * WHICH advertised entry this call is about, from the SDK's own selection\n * (`src/lib/x402-pay.ts`): the registered networks, the `exact` scheme and the\n * canonical-USDC policy, narrowed further by advertised terms when the caller\n * has them. Every paying path asks this one question, so a 402 that lists\n * seven entries cannot have one priced and another signed.\n */\nfunction selectRequirement(\n core: x402Client,\n challenge: PaymentRequired,\n terms: AdvertisedTerms | undefined,\n): PaymentRequirements | undefined {\n return selectPayableRequirement(\n core,\n challenge,\n terms === undefined ? undefined : { network: terms.network, asset: terms.asset },\n );\n}\n\n/**\n * The advertised-terms gate. Same shape of answer as the registry gate and the\n * same failure code, because it answers the same question: is the live 402 the\n * deal this call was authorized against? Exact on scheme, network and asset, at\n * most on the amount. Returns the label the payee line names.\n */\nfunction assertWithinTerms(terms: AdvertisedTerms, requirement: PaymentRequirements): string {\n // Scheme, network and asset already matched: `selectRequirement` chose this\n // entry BY them. What is left is the deal's price and its destination.\n const overQuote =\n terms.maxAmountAtomic !== undefined &&\n BigInt(requirement.amount) > BigInt(terms.maxAmountAtomic);\n const mismatch = overQuote\n ? `amount ${requirement.amount} over the advertised ${terms.maxAmountAtomic ?? '0'}`\n : terms.payTo !== undefined && requirement.payTo.toLowerCase() !== terms.payTo.toLowerCase()\n ? `payTo ${requirement.payTo}`\n : undefined;\n if (mismatch !== undefined) {\n throw new CliError(\n 'REGISTRY_MISMATCH',\n `The live 402 exceeds the terms this call was authorized against (${mismatch}).`,\n {\n fix: 'Nothing was signed. The endpoint changed its deal since those terms were issued; ask for a fresh decision.',\n details: { advertised: terms, live: requirement },\n },\n );\n }\n return terms.source ?? 'the advertised terms';\n}\n\n/** Registry evidence informs direct payments; only this invocation can acknowledge a warning. */\nasync function checkRegistry(\n settings: ResolvedSettings,\n url: string,\n requirement: PaymentRequirements,\n ctx: CommandContext,\n acknowledged: boolean,\n warnings: RegistryWarning[],\n): Promise<string | undefined> {\n const verification = await verifyAgainstRegistries(\n settings.bazaarRegistries,\n url,\n requirement,\n ctx.flags.timeout,\n { dataDir: ctx.dataDir },\n );\n if (verification.outcome === 'verified') return verification.registry;\n if (verification.outcome === 'unlisted') return undefined;\n const warning: RegistryWarning = {\n ...verification,\n acknowledged,\n quote: { url, ...requirement },\n };\n warnings.push(warning);\n const message = warningMessage(warning);\n if (!ctx.flags.json) {\n ctx.io.stderr.write(\n `Live quote: ${sanitizeForTerminal(url)}; recipient ${sanitizeForTerminal(requirement.payTo)}; ${sanitizeForTerminal(requirement.network)} / ${sanitizeForTerminal(requirement.asset)}; ${toMoney(requirement.amount).usd} USD\\n`,\n );\n ctx.io.stderr.write(\n `${sanitizeForTerminal(message)}${acknowledged ? ' (acknowledged for this invocation)' : ''}\\n`,\n );\n }\n if (!acknowledged) {\n throw new CliError('REFUSED', message, {\n fix: 'Review the live quote and use --ignore-warnings to acknowledge this registry warning for this invocation. --yes only confirms payment; normal payment checks still apply.',\n details: { reason: 'registry_acknowledgement_required', quote: { url, ...requirement } },\n });\n }\n return undefined;\n}\n\nfunction warningMessage(warning: RegistryWarning): string {\n switch (warning.outcome) {\n case 'unavailable':\n return 'Registry warning: verification is unavailable or incomplete.';\n case 'mismatch':\n return `Registry warning: the live terms differ from ${warning.registry} (${warning.detail}).`;\n }\n}\n\n/** Discriminated on `paid`: a paid delivery always carries what it paid and to\n * whom, so no branch ever reaches for an amount that might not be there. */\ntype DeliverOpts = {\n /** Set when the body is delivered UNVERIFIED: the success rule could not run. */\n caveat?: string;\n warnings?: RegistryWarning[];\n /** A direct pay's binary body, written to a file ({@link keepBody}). */\n saved?: SavedBody;\n} & (\n | {\n paid: false;\n /** Free because the wallet was already entitled (SIWX), not free-of-price. */\n entitled?: boolean;\n /** Free because the seller asked only for a sign-in, and got one. */\n signedIn?: boolean;\n printBody: boolean;\n }\n | {\n paid: true;\n amountAtomic: bigint;\n requirement: PaymentRequirements;\n /** The wallet that signed it (`BuiltPayment.payer`). */\n payer: string;\n authorization?: SignedAuthorization;\n registry?: string;\n printBody: boolean;\n }\n);\n\n/**\n * The 402 as a quote: every accepted payment option in the seller's order, the\n * resource line, the extensions the seller attached (a listing's advertised\n * request shape rides there), and the 402 body as data. Nothing was paid, and\n * the terminal line says so.\n *\n * `usd` rides only on a canonical USDC entry, the one kind whose amount is\n * 6-decimal by construction: a seller listing an 18-decimal entry first had it\n * labelled as dollars. `payable` marks the entry the paid path would sign, and\n * the headline prices that entry or says there is none.\n */\nfunction deliverQuote(\n url: string,\n lane: Lane,\n res: HttpResponse,\n challenge: PaymentRequired,\n chosen: PaymentRequirements | undefined,\n printBody: boolean,\n): CommandResult {\n const chosenAt =\n chosen === undefined ? -1 : challenge.accepts.findIndex((a) => sameDeal(a, chosen));\n const accepts = challenge.accepts.map((a, i) => ({\n scheme: a.scheme,\n network: a.network,\n asset: a.asset,\n amount: a.amount,\n ...(isCanonicalUsdc(a) ? { usd: toMoney(a.amount).usd } : {}),\n ...(i === chosenAt ? { payable: true as const } : {}),\n payTo: a.payTo,\n maxTimeoutSeconds: a.maxTimeoutSeconds,\n ...(a.extra !== undefined ? { extra: a.extra } : {}),\n }));\n // A 402 that asks only for a sign-in: `tenjin pay` answers it, paying\n // nothing, when this wallet paid that host.\n const signIn = signInOnlyChallenge(challenge) !== undefined;\n const data = {\n url,\n lane,\n status: res.status,\n paid: false,\n quote: true,\n resource: challenge.resource,\n accepts,\n ...(signIn ? { signIn: true } : {}),\n ...(challenge.extensions !== undefined ? { extensions: challenge.extensions } : {}),\n ...(res.json !== undefined ? { body: res.json } : {}),\n bodyText: res.text,\n };\n const host = sanitizeForTerminal(new URL(url).host);\n const payable = accepts[chosenAt];\n const headline =\n payable?.usd !== undefined\n ? `quote: ${payable.usd} USD to ${host} on ${sanitizeForTerminal(payable.network)} (nothing paid)`\n : signIn\n ? `quote: ${host} asks the wallet that paid it to sign in, and lists no payment option (nothing paid)`\n : accepts.length === 0\n ? `quote: ${host} answered 402 with no payment option (nothing paid)`\n : `quote: ${host} lists no option this wallet can pay, only USDC on Base is supported (nothing paid)`;\n const body = sanitizeForTerminal(res.text);\n const preview =\n printBody || body.length <= BODY_PREVIEW_CHARS\n ? body\n : `${body.slice(0, BODY_PREVIEW_CHARS)}\\n… truncated; run with --print-body or --json for the full body`;\n return { data, humanLines: [headline, ...(preview.length > 0 ? [preview] : [])] };\n}\n\n/** The same advertised deal, whether or not the SDK handed back the same object. */\nfunction sameDeal(a: PaymentRequirements, b: PaymentRequirements): boolean {\n return (\n a === b ||\n (a.scheme === b.scheme &&\n a.network === b.network &&\n a.asset.toLowerCase() === b.asset.toLowerCase() &&\n a.amount === b.amount &&\n a.payTo.toLowerCase() === b.payTo.toLowerCase())\n );\n}\n\nfunction deliver(url: string, lane: Lane, res: HttpResponse, opts: DeliverOpts): CommandResult {\n const settlementTxHash = opts.paid ? settlementTx(res) : undefined;\n const data = {\n url,\n lane,\n status: res.status,\n paid: opts.paid,\n ...(opts.warnings !== undefined ? { warnings: opts.warnings } : {}),\n ...(opts.paid\n ? {\n amountPaid: toMoney(opts.amountAtomic.toString()),\n payTo: opts.requirement.payTo,\n network: opts.requirement.network,\n asset: opts.requirement.asset,\n payer: opts.payer,\n ...(opts.authorization !== undefined ? { authorization: opts.authorization } : {}),\n ...(opts.registry !== undefined ? { registry: opts.registry } : {}),\n }\n : opts.entitled === true\n ? { entitled: true }\n : opts.signedIn === true\n ? { signedIn: true }\n : {}),\n ...(settlementTxHash !== undefined ? { settlementTxHash } : {}),\n // Beside the body, never instead of it: the caller gets the product AND the\n // fact that its shape was never checked. The flag is what a machine reads:\n // a caller branching on a delivery must not have to match on prose, which\n // is how an unchecked body passed for a checked one one layer up.\n ...(opts.caveat !== undefined ? { resultUnverified: true, resultCaveat: opts.caveat } : {}),\n // The body is the product: JSON when the endpoint spoke it, raw text always,\n // and, when it was a file, where a direct pay saved it, or the bytes\n // themselves for the router's tool to save.\n ...(res.json !== undefined ? { body: res.json } : {}),\n bodyText: res.text,\n ...(opts.saved !== undefined\n ? opts.saved\n : res.bytes !== undefined\n ? { bodyBytes: res.bytes, contentType: res.header('content-type') ?? '' }\n : {}),\n };\n const headline = opts.paid\n ? `paid ${toMoney(opts.amountAtomic.toString()).usd} USD to ${sanitizeForTerminal(new URL(url).host)}` +\n (settlementTxHash !== undefined ? ` (tx ${settlementTxHash})` : '')\n : opts.entitled === true\n ? `free (entitled, no charge)`\n : opts.signedIn === true\n ? `free (signed in, no charge)`\n : `free (${res.status}, no charge)`;\n const body = sanitizeForTerminal(res.text);\n const preview =\n opts.printBody || body.length <= BODY_PREVIEW_CHARS\n ? body\n : `${body.slice(0, BODY_PREVIEW_CHARS)}\\n… truncated; run with --print-body or --json for the full body`;\n return {\n data,\n humanLines: [\n headline,\n ...(opts.warnings ?? []).map(\n (w) => `${sanitizeForTerminal(warningMessage(w))} (acknowledged)`,\n ),\n ...(opts.caveat !== undefined ? [sanitizeForTerminal(opts.caveat)] : []),\n ...(opts.saved !== undefined ? [savedLine(opts.saved)] : []),\n // The paid bytes no folder took: the only copy, so printed whole.\n ...(opts.saved?.bodyBase64 !== undefined ? [opts.saved.bodyBase64] : []),\n ...(preview.length > 0 ? [preview] : []),\n ],\n };\n}\n\n/** A binary body a direct pay wrote to a file, tried to, or (on a quote)\n * left unwritten. `bodyBase64` holds the bytes when no folder took them. */\ninterface SavedBody {\n savedTo?: string;\n saveError?: string;\n notSaved?: string;\n bodyBase64?: string;\n contentType: string;\n bytes: number;\n}\n\n/** A quote's binary body, described and never written. */\nfunction describeBody(res: Pick<HttpResponse, 'bytes' | 'header'>): SavedBody | undefined {\n if (res.bytes === undefined) return undefined;\n return {\n notSaved: '--quote writes no file; run it without --quote to save it',\n contentType: res.header('content-type') ?? '',\n bytes: res.bytes.byteLength,\n };\n}\n\n/**\n * WRITE A DIRECT PAY'S BINARY BODY TO A FILE, under the downloads directory,\n * named for the host with the extension its type implies, and say where. A\n * text body is undefined: it is delivered as text. NEVER THROWS, AND NEVER\n * DROPS THE BYTES: on the paid leg the money has already moved, and a retry\n * pays again. A downloads folder that cannot take the file (full, or not\n * writable) falls back to the OS temp folder, with the first error said. When\n * that fails too, the bytes come back in the result as base64.\n */\nasync function keepBody(\n dataDir: string,\n url: string,\n res: Pick<HttpResponse, 'bytes' | 'header'>,\n): Promise<SavedBody | undefined> {\n if (res.bytes === undefined) return undefined;\n const contentType = res.header('content-type') ?? '';\n const described = { contentType, bytes: res.bytes.byteLength };\n const stem = `pay-${new URL(url).hostname.slice(0, 60)}-${Date.now()}`;\n const first = await writeBody(downloadsDir(dataDir), stem, contentType, res.bytes);\n if ('path' in first) return { savedTo: first.path, ...described };\n const second = await writeBody(tmpdir(), stem, contentType, res.bytes);\n if ('path' in second) return { savedTo: second.path, saveError: first.error, ...described };\n return {\n saveError: `${first.error}; the temp folder failed too: ${second.error}`,\n bodyBase64: Buffer.from(res.bytes).toString('base64'),\n ...described,\n };\n}\n\n/** One try at a new file in `directory` ({@link writeNewFile}), as a path\n * or the reason it was not saved. */\nasync function writeBody(\n directory: string,\n stem: string,\n contentType: string,\n bytes: Uint8Array,\n): Promise<{ path: string } | { error: string }> {\n try {\n return { path: await writeNewFile(directory, stem, contentType, bytes) };\n } catch (err) {\n return { error: err instanceof Error ? err.message : String(err) };\n }\n}\n\nfunction savedLine(saved: SavedBody): string {\n const what = `${saved.bytes}-byte ${sanitizeForTerminal(saved.contentType) || 'binary'} body`;\n const why = sanitizeForTerminal(saved.saveError ?? 'unknown error');\n if (saved.savedTo !== undefined) {\n return saved.saveError !== undefined\n ? `the downloads folder could not take the ${what} (${why}), so it was saved to ${saved.savedTo}`\n : `saved the ${what} to ${saved.savedTo}`;\n }\n if (saved.notSaved !== undefined) return `the ${what} was not saved: ${saved.notSaved}`;\n return saved.bodyBase64 !== undefined\n ? `the ${what} could not be saved (${why}); its bytes follow as base64`\n : `the ${what} could not be saved: ${why}`;\n}\n\n/**\n * The settlement transaction the payment-response header names (v2's\n * `PAYMENT-RESPONSE`, or v1's `X-PAYMENT-RESPONSE`): base64 JSON carrying\n * `transaction`. Read from the protocol header only, never the seller's body.\n */\nexport function settlementTx(res: Pick<HttpResponse, 'header'>): string | undefined {\n const tx = paymentResponse(res)?.transaction;\n return typeof tx === 'string' && /^0x[0-9a-fA-F]{64}$/.test(tx) ? tx : undefined;\n}\n\n/**\n * The seller's own word that it DID settle, on a failure: its payment-response\n * header with `success: true` and the settlement transaction it names.\n */\nfunction settledTx(res: Pick<HttpResponse, 'header'>): string | undefined {\n return paymentResponse(res)?.success === true ? settlementTx(res) : undefined;\n}\n\n/**\n * The seller's own word that it did NOT settle: its payment-response header\n * with `success: false`, and the `errorReason` (or `errorMessage`) it gave, as\n * one bounded redacted line. Seller text, never instructions. `undefined` when\n * the header is absent, unreadable or says it settled.\n */\nfunction settlementRefusal(res: Pick<HttpResponse, 'header'>): { reason?: string } | undefined {\n const settle = paymentResponse(res);\n if (settle?.success !== false) return undefined;\n const said = [settle.errorReason, settle.errorMessage].find(\n (value): value is string => typeof value === 'string' && value.trim().length > 0,\n );\n const reason = said !== undefined ? sellerLine(said) : '';\n return reason.length > 0 ? { reason } : {};\n}\n\n/** The decoded payment-response header (v2's `PAYMENT-RESPONSE`, or v1's\n * `X-PAYMENT-RESPONSE`) when it is a JSON object, else `undefined`. */\nfunction paymentResponse(res: Pick<HttpResponse, 'header'>): Record<string, unknown> | undefined {\n const header = res.header(PAYMENT_RESPONSE_HEADER) ?? res.header(PAYMENT_RESPONSE_HEADER_V1);\n if (header === undefined) return undefined;\n try {\n const settle: unknown = decodePaymentResponseHeader(header);\n return typeof settle === 'object' && settle !== null\n ? (settle as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * THE WALLET, OPENED, and a refusal from it marked as the wallet's\n * (`walletUnavailable`): a missing wallet, one with no passphrase in a process\n * that cannot prompt, or a key that will not decrypt. The locked wallet's\n * `USAGE` reads the same as a refused destination's otherwise, and a caller\n * reporting why nothing was paid has to tell the two apart. The code, message\n * and fix stay the wallet's own.\n */\nasync function openWallet(provider: WalletProvider): Promise<TenjinSigner> {\n try {\n await describeWallet(provider); // WALLET_MISSING with its own fix if none exists\n return await provider.getSigner();\n } catch (err) {\n throw walletError(err);\n }\n}\n\n/** The wallet's description, read without opening it; a refusal is marked\n * the wallet's as {@link openWallet} marks it. */\nasync function describeOpenable(\n provider: WalletProvider,\n): Promise<Awaited<ReturnType<typeof describeWallet>>> {\n try {\n return await describeWallet(provider);\n } catch (err) {\n throw walletError(err);\n }\n}\n\nfunction walletError(err: unknown): unknown {\n if (!(err instanceof CliError)) return err;\n return new CliError(err.code, err.message, {\n exitCode: err.exitCode,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n details: {\n ...(typeof err.details === 'object' && err.details !== null ? err.details : {}),\n walletUnavailable: true,\n },\n cause: err,\n });\n}\n\n/** Cap on a seller's PAYMENT-REQUIRED header before it is decoded for its reason. */\nconst MAX_CHALLENGE_CHARS = 16_384;\n\n/**\n * WHY A SELLER REFUSED A PAYMENT, in its words: the `error` of the challenge\n * the SDK reads from the 402 (its PAYMENT-REQUIRED header, x402 v2, else an\n * x402 v1 body), as one bounded, redacted plain line. A header past the cap\n * is not decoded. Seller text, never instructions.\n */\nfunction paymentRequiredError(\n http: Pick<x402HTTPClient, 'getPaymentRequiredResponse'>,\n res: Pick<HttpResponse, 'header' | 'json'>,\n): string | undefined {\n let said: unknown;\n try {\n said = http.getPaymentRequiredResponse((name) => {\n const value = res.header(name);\n return value !== undefined && value.length <= MAX_CHALLENGE_CHARS ? value : undefined;\n }, res.json).error;\n } catch {\n said = undefined;\n }\n if (typeof said !== 'string') return undefined;\n const line = sellerLine(said);\n return line.length > 0 ? line : undefined;\n}\n\n/**\n * A SELLER'S SIGN-IN CHALLENGE, read from a 402's PAYMENT-REQUIRED header:\n * the challenge and its `sign-in-with-x` extension when the 402 offers no\n * payment and asks only for a sign-in, else undefined (a price, a header too\n * long or one that does not decode). Reading it signs nothing and opens no\n * wallet, so a router poll uses it to tell a sign-in it refuses from a seller\n * asking to be paid again.\n */\nexport function signInOnlyHeader(\n paymentRequiredHeader: string,\n):\n | { challenge: PaymentRequired; extension: NonNullable<ReturnType<typeof signInOnlyChallenge>> }\n | undefined {\n if (paymentRequiredHeader.length > MAX_CHALLENGE_CHARS) return undefined;\n let challenge: PaymentRequired;\n try {\n challenge = decodePaymentRequiredHeader(paymentRequiredHeader);\n } catch {\n return undefined;\n }\n const extension = signInOnlyChallenge(challenge);\n return extension !== undefined ? { challenge, extension } : undefined;\n}\n\n/** What a poll's sign-in comes to (`PollSignIn` in `router/jobs.ts`). */\nexport type PollSignInAnswer =\n | { headers: Record<string, string> }\n | { refused: string }\n | { error: string }\n | { otherWallet: { paidBy: string; current: string } }\n | undefined;\n\n/**\n * THE ROUTER'S JOB POLLS, SIGNED IN AS A DIRECT PAY IS (tenjin#977): a poll\n * the seller answered 402 with a sign-in challenge and no way to pay gets the\n * headers that answer it, when the challenge matches the responding origin,\n * signed by the wallet that paid. The take is that proof, and the only one:\n * `paidBy` names the wallet that signed its submit (its recorded payer, else,\n * on a take from before payers were kept, its authorization's `from`) and\n * the submit's URL, and the wallet signs only when it is that address and\n * the poll is on that host. A take that names no payer signs nothing; the\n * ledger is not asked, since any payment there to the host is not this\n * take's. A wallet switched since the submit signs nothing either, and is\n * `otherWallet`, naming the wallet that paid: the take is still the seller's\n * to finish, for that wallet. Undefined for any other 402, which the poll\n * treats as a seller asking to be paid again.\n * A wallet that could not be opened is an `error`, which the poll counts and\n * survives, never a refusal that ends a paid take. Never pays: the challenge\n * offers no payment, and none is built. Only a GET poll is handed here: a\n * POST poll's challenge is refused unsigned in `router/jobs.ts`, as a direct\n * pay's write is (`sign_in_method`).\n */\nexport async function signInForPoll(\n paymentRequiredHeader: string,\n url: string,\n ctx: CommandContext,\n deps: {\n provider?: WalletProvider;\n paidBy: { from?: string; url: string };\n },\n): Promise<PollSignInAnswer> {\n const read = signInOnlyHeader(paymentRequiredHeader);\n if (read === undefined) return undefined;\n const { challenge, extension } = read;\n const { paidBy } = deps;\n try {\n const provider = resolveWalletProvider(\n ctx,\n deps.provider !== undefined ? { provider: deps.provider } : {},\n );\n // The wallet this machine holds now, as described and as opened.\n let current: string | undefined;\n const answer = await answerSignInChallenge(challenge, extension, url, {\n address: async () => (current = (await describeOpenable(provider)).address),\n paidHost: async (host, address) =>\n paidBy.from === undefined\n ? 'payer_unknown'\n : hostOf(paidBy.url) === host && paidBy.from.toLowerCase() === address.toLowerCase()\n ? 'paid'\n : 'unpaid',\n signer: async () => {\n const signer = await openWallet(provider);\n current = signer.address;\n return signer;\n },\n });\n if (!('refused' in answer)) return answer;\n // A WALLET SWITCHED SINCE THE SUBMIT is this machine's state, not the\n // seller's answer: nothing is signed with it, and the take waits for the\n // wallet that paid.\n if (\n answer.refused === 'unpaid' &&\n paidBy.from !== undefined &&\n current !== undefined &&\n hostOf(paidBy.url) === hostOf(url) &&\n current.toLowerCase() !== paidBy.from.toLowerCase()\n ) {\n return { otherWallet: { paidBy: paidBy.from, current } };\n }\n return { refused: answer.reason };\n } catch (err) {\n return {\n error: `the wallet could not be opened (${sellerLine(err instanceof Error ? err.message : String(err)) || 'no reason given'})`,\n };\n }\n}\n\nfunction hostOf(url: string): string | undefined {\n try {\n return new URL(url).host;\n } catch {\n return undefined;\n }\n}\n\n/** The signer, once the wallet has been opened. Selection never reaches it. */\nfunction signerOrThrow(held: { current?: TenjinSigner }): TenjinSigner {\n if (held.current === undefined) {\n throw new CliError('INTERNAL', 'The payment was built before the wallet was opened.');\n }\n return held.current;\n}\n","export function isModelWorkerProcess(env: NodeJS.ProcessEnv = process.env): boolean {\n return env.TENJIN_MODEL_WORKER === '1';\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { HTTPFacilitatorClient } from '@x402/core/http';\nimport { withBazaar } from '@x402/extensions/bazaar';\nimport type { DiscoveryResource } from '@x402/extensions/bazaar';\nimport type { PaymentRequirements } from '@x402/core/types';\nimport { getAddress } from 'viem';\nimport { PaymentRequirementsV2Schema } from '@x402/core/schemas';\nimport { z } from 'zod';\nimport { writeFileAtomic } from './atomic-json';\n\n/**\n * Discovery is evidence, never payment authority. Standard registries use the\n * SDK; Ultravioleta has an explicit adapter for its different discovery shape.\n * Every payment candidate is matched locally against the live requirement.\n */\n\nexport interface RegistryResource {\n /** The payable resource URL, exactly as the registry lists it. */\n url: string;\n registry: string;\n description?: string;\n accepts: PaymentRequirements[];\n lastUpdated?: string;\n}\n\nexport interface RegistryError {\n registry: string;\n message: string;\n}\n\nexport interface RegistrySweep {\n resources: RegistryResource[];\n /** Registries that did not answer; a sweep with errors is PARTIAL, never silently complete. */\n errors: RegistryError[];\n /** Listings skipped because they are not plain HTTP resources (e.g. MCP servers). */\n skippedNonHttp: number;\n}\n\n/** One page is the sweep unit; a payTo filter narrows far below this. */\nconst PAGE_LIMIT = 100;\n/** CDP's search endpoint rejects limits above 20 (verified live 2026-08-14). */\nconst SEARCH_LIMIT = 20;\n\nconst MAX_PAGES = 5;\nconst MAX_RESPONSE_BYTES = 2 * 1024 * 1024;\nconst ULTRAVIOLETA_ORIGIN = 'https://facilitator.ultravioletadao.xyz';\n\nfunction isUltravioleta(registry: string): boolean {\n return new URL(registry).origin === ULTRAVIOLETA_ORIGIN;\n}\n\nconst paymentTerms = z.custom<PaymentRequirements>((value: unknown) => {\n const parsed = PaymentRequirementsV2Schema.safeParse(value);\n return parsed.success && /^\\d+$/.test(parsed.data.amount);\n});\nconst ultravioletResource = z.object({\n url: z.string().url(),\n type: z.string(),\n x402Version: z.number().int(),\n description: z.string().optional(),\n accepts: z.array(paymentTerms).max(100),\n lastUpdated: z.number().int().nonnegative().max(8_640_000_000_000),\n});\nconst paginationSchema = z.object({\n limit: z.number().int().positive().max(PAGE_LIMIT),\n offset: z.number().int().nonnegative(),\n total: z.number().int().nonnegative(),\n});\ninterface Listings {\n items: DiscoveryResource[];\n incomplete?: string;\n}\n\n/** A registry controls its response size as well as its latency. */\nasync function boundedJson(res: Response): Promise<unknown> {\n const reader = res.body?.getReader();\n if (!reader) throw new Error('Registry response has no body');\n const chunks: Uint8Array[] = [];\n let bytes = 0;\n try {\n for (;;) {\n const next = await reader.read();\n if (next.done) break;\n bytes += next.value.byteLength;\n if (bytes > MAX_RESPONSE_BYTES) throw new Error('Registry response exceeds size limit');\n chunks.push(next.value);\n }\n } finally {\n await reader.cancel();\n }\n return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;\n}\n\n/** Ultravioleta's documented resources API uses q, url and Unix seconds. */\nasync function ultravioletListings(\n registry: string,\n timeoutMs: number,\n query?: string,\n): Promise<Listings> {\n const deadline = Date.now() + timeoutMs;\n const items: DiscoveryResource[] = [];\n let offset = 0;\n let incomplete: string | undefined;\n for (let page = 0; page < MAX_PAGES; page++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw new Error('Registry lookup deadline exceeded');\n const params = new URLSearchParams({\n limit: String(PAGE_LIMIT),\n offset: String(offset),\n ...(query !== undefined ? { q: query } : {}),\n });\n const res = await fetch(`${new URL(registry).origin}/discovery/resources?${params}`, {\n headers: { accept: 'application/json' },\n signal: AbortSignal.timeout(remaining),\n redirect: 'error',\n });\n if (!res.ok) throw new Error(`listing ${registry} answered ${res.status}`);\n const response = z\n .object({ items: z.array(z.unknown()).max(PAGE_LIMIT), pagination: paginationSchema })\n .parse(await boundedJson(res));\n const pagination = response.pagination;\n if (pagination.offset !== offset || response.items.length > pagination.limit)\n throw new Error('Invalid registry pagination');\n for (const record of response.items) {\n const parsed = ultravioletResource.safeParse(record);\n if (!parsed.success) {\n incomplete = 'Registry search skipped malformed records';\n continue;\n }\n const item = parsed.data;\n items.push({\n resource: item.url,\n type: item.type,\n x402Version: item.x402Version,\n accepts: item.accepts as PaymentRequirements[],\n lastUpdated: new Date(item.lastUpdated * 1000).toISOString(),\n ...(item.description !== undefined ? { description: item.description } : {}),\n });\n }\n const next = pagination.offset + response.items.length;\n if (next >= pagination.total) return { items, ...(incomplete ? { incomplete } : {}) };\n if (response.items.length === 0) break;\n offset = next;\n }\n return { items, incomplete: 'Registry search truncated at the pagination limit' };\n}\n\nfunction client(registry: string) {\n return withBazaar(new HTTPFacilitatorClient({ url: registry }));\n}\n\n/** A `withTimeout` that ran out of time. */\nclass DeadlineError extends Error {}\n\n/** The SDK fetch carries no deadline; a registry that stalls loses its slot. */\nasync function withTimeout<T>(work: Promise<T>, timeoutMs: number, what: string): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n try {\n return await Promise.race([\n work,\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new DeadlineError(`${what} timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction toResource(item: DiscoveryResource, registry: string): RegistryResource {\n return {\n url: item.resource,\n registry,\n ...(item.description !== undefined ? { description: item.description } : {}),\n accepts: item.accepts,\n ...(item.lastUpdated !== undefined ? { lastUpdated: item.lastUpdated } : {}),\n };\n}\n\n/** List HTTP-type resources across every configured registry. */\nexport async function sweepRegistries(\n registries: readonly string[],\n opts: { timeoutMs: number; query?: string },\n): Promise<RegistrySweep> {\n const resources: RegistryResource[] = [];\n const errors: RegistryError[] = [];\n let skippedNonHttp = 0;\n const deadline = Date.now() + opts.timeoutMs;\n for (const registry of registries) {\n try {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw new Error('Registry lookup deadline exceeded');\n const bazaar = client(registry).extensions.bazaar;\n const ultraviolet = isUltravioleta(registry)\n ? await withTimeout(\n ultravioletListings(registry, remaining, opts.query),\n remaining,\n registry,\n )\n : undefined;\n if (ultraviolet?.incomplete) errors.push({ registry, message: ultraviolet.incomplete });\n const items =\n ultraviolet?.items ??\n (opts.query !== undefined\n ? (\n await withTimeout(\n bazaar.search({ query: opts.query, limit: SEARCH_LIMIT }),\n remaining,\n `search on ${registry}`,\n )\n ).resources\n : (\n await withTimeout(\n bazaar.listResources({ type: 'http', limit: PAGE_LIMIT }),\n remaining,\n `listing ${registry}`,\n )\n ).items);\n for (const item of items) {\n if (item.type !== 'http') {\n // An MCP-type listing is a seller this CLI cannot speak x402-over-HTTP\n // to; counted so the sweep never silently narrows what it covered.\n skippedNonHttp += 1;\n continue;\n }\n resources.push(toResource(item, registry));\n }\n } catch (err) {\n errors.push({ registry, message: err instanceof Error ? err.message : String(err) });\n }\n }\n return { resources, errors, skippedNonHttp };\n}\n\n// ---------------------------------------------------------------------------\n// The local listing store: what a `discover` sweep returned, kept as pay-time\n// evidence (bounded, TTL'd). The pay lane checks a fresh stored listing first,\n// then asks each registry live (`listingsFor`), so the store is a shortcut and\n// never the only way a listed resource can be paid.\n// ---------------------------------------------------------------------------\n\nconst LISTING_STORE_FILE = 'bazaar-listings.json';\n/** A listing older than this is not pay-time evidence; the live lookup decides. */\nconst LISTING_TTL_MS = 24 * 60 * 60 * 1000;\n/** Newest-first cap so the store cannot grow without bound. */\nconst LISTING_STORE_CAP = 1000;\n\nexport interface StoredListing {\n url: string;\n registry: string;\n accepts: PaymentRequirements[];\n fetchedAt: string;\n}\n\ninterface ListingStore {\n listings: StoredListing[];\n}\n\nfunction listingStorePath(dataDir: string): string {\n return join(dataDir, LISTING_STORE_FILE);\n}\n\n/**\n * Shape-checked PER ENTRY, not just per array. `acceptsMismatch` iterates\n * `accepts`, so one malformed row from a truncated write or a hand-edit throws a\n * raw TypeError out of the check that decides whether a payment may be signed.\n * A row that is not the shape this module writes is dropped, which costs at\n * worst a live lookup.\n */\nfunction isStoredListing(value: unknown): value is StoredListing {\n if (typeof value !== 'object' || value === null) return false;\n const listing = value as Partial<StoredListing>;\n return (\n typeof listing.url === 'string' &&\n typeof listing.registry === 'string' &&\n typeof listing.fetchedAt === 'string' &&\n Array.isArray(listing.accepts)\n );\n}\n\nasync function loadListingStore(dataDir: string): Promise<ListingStore> {\n try {\n const raw: unknown = JSON.parse(await readFile(listingStorePath(dataDir), 'utf8'));\n const listings = (raw as { listings?: unknown } | null)?.listings;\n return { listings: Array.isArray(listings) ? listings.filter(isStoredListing) : [] };\n } catch {\n return { listings: [] };\n }\n}\n\n/** Persist a sweep's listings, newest first, deduplicated on (identity, registry). */\nexport async function saveSweepListings(\n dataDir: string,\n resources: readonly RegistryResource[],\n now: () => number = Date.now,\n): Promise<void> {\n const store = await loadListingStore(dataDir);\n const fetchedAt = new Date(now()).toISOString();\n const fresh: StoredListing[] = resources.map((r) => ({\n url: r.url,\n registry: r.registry,\n accepts: r.accepts,\n fetchedAt,\n }));\n const seen = new Set(fresh.map((l) => `${l.registry} ${l.url}`));\n const kept = store.listings.filter((l) => !seen.has(`${l.registry} ${l.url}`));\n await writeFileAtomic(\n listingStorePath(dataDir),\n JSON.stringify({ listings: [...fresh, ...kept].slice(0, LISTING_STORE_CAP) }, null, 2),\n );\n}\n\n/** Fresh stored listings for this resource identity, newest first. */\nasync function storedListingsFor(\n dataDir: string,\n url: string,\n now: () => number,\n): Promise<StoredListing[]> {\n const store = await loadListingStore(dataDir);\n return store.listings.filter((l) => {\n if (!sameResourceUrl(l.url, url)) return false;\n const age = now() - Date.parse(l.fetchedAt);\n // BOUNDED AT BOTH ENDS. A negative age is not extra-fresh evidence, it is a\n // stamp the clock disagrees with (skew, a restored or copied data dir), and\n // an unbounded `age < TTL` made such a listing permanent pay-time evidence\n // that no 24h re-sweep could ever expire. NaN (an unparseable stamp) fails\n // the same comparison.\n return age >= 0 && age < LISTING_TTL_MS;\n });\n}\n\nexport type RegistryVerification =\n | { outcome: 'verified'; registry: string }\n /** Listed somewhere, but no listing matches the live 402's terms. */\n | { outcome: 'mismatch'; registry: string; detail: string }\n | { outcome: 'unlisted' }\n /** Some required evidence could not be checked; absence is not established. */\n | { outcome: 'unavailable'; errors: RegistryError[] };\n\n/**\n * Resource identity is origin + path (trailing slash normalized): a registry\n * lists the ENDPOINT, and the query string is the per-call request riding it\n * (verified live: the Bazaar lists `/search`, callers pay `/search?query=...`).\n * An unparseable listing matches nothing.\n */\nfunction sameResourceUrl(listed: string, requested: string): boolean {\n const a = resourceIdentity(listed);\n return a !== null && a === resourceIdentity(requested);\n}\n\nfunction resourceIdentity(u: string): string | null {\n try {\n const parsed = new URL(u);\n const path = parsed.pathname.endsWith('/') ? parsed.pathname.slice(0, -1) : parsed.pathname;\n return `${parsed.origin}${path}`;\n } catch {\n return null;\n }\n}\n\n/** Search by endpoint identity so differing recipients remain visible. Registries\n * without search retain the SDK's recipient-filtered listing fallback. */\nasync function listingsFor(\n registry: string,\n url: string,\n payTo: string,\n timeoutMs: number,\n): Promise<Listings> {\n if (isUltravioleta(registry))\n return ultravioletListings(registry, timeoutMs, resourceIdentity(url) ?? url);\n const deadline = Date.now() + timeoutMs;\n const params = new URLSearchParams({\n urlSubstring: resourceIdentity(url) ?? url,\n limit: String(SEARCH_LIMIT),\n });\n const res = await fetch(`${registry.replace(/\\/+$/, '')}/discovery/search?${params.toString()}`, {\n headers: { accept: 'application/json' },\n signal: AbortSignal.timeout(timeoutMs),\n redirect: 'error',\n });\n if (res.ok) {\n const answer = (await boundedJson(res)) as {\n resources?: unknown;\n partialResults?: boolean;\n pagination?: { cursor?: unknown };\n } | null;\n if (Array.isArray(answer?.resources)) {\n return {\n items: answer.resources.slice(0, PAGE_LIMIT) as DiscoveryResource[],\n ...(answer.resources.length > PAGE_LIMIT ||\n answer.partialResults === true ||\n answer.pagination?.cursor != null\n ? { incomplete: 'Registry search results are truncated' }\n : {}),\n };\n }\n } else if (res.status !== 400 && res.status !== 404) {\n throw new Error(`search on ${registry} answered ${res.status}`);\n }\n const bazaar = client(registry).extensions.bazaar;\n const items: DiscoveryResource[] = [];\n let offset = 0;\n for (let page = 0; page < MAX_PAGES; page++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw new Error('Registry lookup deadline exceeded');\n const response = await withTimeout(\n bazaar.listResources({ type: 'http', payTo, limit: PAGE_LIMIT, offset }),\n remaining,\n registry,\n );\n const pagination = paginationSchema.parse(response.pagination);\n if (\n !Array.isArray(response.items) ||\n response.items.length > PAGE_LIMIT ||\n pagination.offset !== offset\n )\n throw new Error('Invalid registry page');\n items.push(...response.items);\n offset = pagination.offset + response.items.length;\n if (offset >= pagination.total) return { items };\n if (response.items.length === 0) break;\n }\n return { items, incomplete: 'Registry listing truncated at the pagination limit' };\n}\n\n/** An exact resource match must cover the live scheme, network, asset, recipient\n * and price. Missing or incomplete evidence is never a verified listing. */\nexport async function verifyAgainstRegistries(\n registries: readonly string[],\n url: string,\n live: PaymentRequirements,\n timeoutMs: number,\n opts: { dataDir?: string; now?: () => number } = {},\n): Promise<RegistryVerification> {\n const errors: RegistryError[] = [];\n let mismatch: { registry: string; detail: string } | undefined;\n\n // A fresh listing a `discover` sweep stored IS the registry's word for this\n // resource, and it answers without a round trip.\n if (opts.dataDir !== undefined) {\n for (const listing of await storedListingsFor(opts.dataDir, url, opts.now ?? Date.now)) {\n if (!registries.includes(listing.registry)) continue; // no longer configured\n const detail = acceptsMismatch(listing.accepts, live);\n if (detail === null) return { outcome: 'verified', registry: listing.registry };\n mismatch ??= { registry: listing.registry, detail };\n }\n }\n\n const deadline = Date.now() + timeoutMs;\n for (const registry of registries) {\n try {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw new Error('Registry lookup deadline exceeded');\n const listed = await withTimeout(\n listingsFor(registry, url, live.payTo, remaining),\n remaining,\n `looking up this resource on ${registry}`,\n );\n if (listed.incomplete) errors.push({ registry, message: listed.incomplete });\n const matches = listed.items.filter(\n (item) =>\n item != null &&\n item.type === 'http' &&\n typeof item.resource === 'string' &&\n Array.isArray(item.accepts) &&\n sameResourceUrl(item.resource, url),\n );\n if (matches.length === 0) continue;\n for (const item of matches) {\n const detail = acceptsMismatch(item.accepts, live);\n if (detail === null) return { outcome: 'verified', registry };\n mismatch ??= { registry, detail };\n }\n } catch (err) {\n errors.push({ registry, message: err instanceof Error ? err.message : String(err) });\n // Each lookup is given ALL the time left, so its timeout means the deadline\n // is spent, even when a timer that fired a millisecond early leaves the\n // clock reading 1 ms short of it.\n if (err instanceof DeadlineError || (err instanceof Error && err.name === 'TimeoutError')) {\n break;\n }\n }\n }\n if (mismatch !== undefined) return { outcome: 'mismatch', ...mismatch };\n if (errors.length > 0) {\n return { outcome: 'unavailable', errors };\n }\n return { outcome: 'unlisted' };\n}\n\n/** Null when some advertised accept covers the live requirement; else why not. */\nfunction acceptsMismatch(\n advertised: PaymentRequirements[],\n live: PaymentRequirements,\n): string | null {\n let closest = 'the listing advertises no payment terms';\n for (const raw of advertised) {\n const parsed = paymentTerms.safeParse(raw);\n if (!parsed.success) {\n closest = 'malformed advertised payment terms';\n continue;\n }\n const adv = parsed.data;\n if (adv.scheme !== live.scheme) {\n closest = `advertised scheme ${adv.scheme}, live ${live.scheme}`;\n continue;\n }\n if (adv.network !== live.network) {\n closest = `advertised network ${adv.network}, live ${live.network}`;\n continue;\n }\n if (!sameAddress(adv.asset, live.asset)) {\n closest = `advertised asset ${adv.asset}, live ${live.asset}`;\n continue;\n }\n if (!sameAddress(adv.payTo, live.payTo)) {\n closest = `advertised payTo ${adv.payTo}, live ${live.payTo}`;\n continue;\n }\n let advertisedAmount: bigint;\n let liveAmount: bigint;\n try {\n advertisedAmount = BigInt(adv.amount);\n liveAmount = BigInt(live.amount);\n } catch {\n closest = 'a non-integer amount in the listing or the live 402';\n continue;\n }\n if (liveAmount > advertisedAmount) {\n closest = `live amount ${live.amount} exceeds the advertised ${adv.amount}`;\n continue;\n }\n return null;\n }\n return closest;\n}\n\nfunction sameAddress(a: string, b: string): boolean {\n try {\n return getAddress(a) === getAddress(b);\n } catch {\n return false;\n }\n}\n","/**\n * HTTP-specific type definitions for the Bazaar Discovery Extension\n */\n\nimport type { BodyMethods, QueryParamMethods } from \"@x402/core/http\";\nimport type { DiscoveryInfo } from \"../types\";\n\n/** Shared schema definition for an object-typed parameter map (queryParams, pathParams, etc.) */\ninterface ParamMapSchemaProperty {\n type: \"object\";\n properties?: Record<string, unknown>;\n additionalProperties?: boolean;\n}\n\n/**\n * Discovery info for query parameter methods (GET, HEAD, DELETE)\n */\nexport interface QueryDiscoveryInfo {\n input: {\n type: \"http\";\n /** Absent at declaration time; set by bazaarResourceServerExtension.enrichDeclaration */\n method?: QueryParamMethods;\n queryParams?: Record<string, unknown>;\n pathParams?: Record<string, unknown>;\n headers?: Record<string, string>;\n };\n output?: {\n type?: string;\n format?: string;\n example?: unknown;\n };\n}\n\n/**\n * Discovery info for body methods (POST, PUT, PATCH)\n */\nexport interface BodyDiscoveryInfo {\n input: {\n type: \"http\";\n /** Absent at declaration time; set by bazaarResourceServerExtension.enrichDeclaration */\n method?: BodyMethods;\n bodyType: \"json\" | \"form-data\" | \"text\";\n body: Record<string, unknown>;\n queryParams?: Record<string, unknown>;\n pathParams?: Record<string, unknown>;\n headers?: Record<string, string>;\n };\n output?: {\n type?: string;\n format?: string;\n example?: unknown;\n };\n}\n\n/**\n * Discovery extension for query parameter methods (GET, HEAD, DELETE)\n */\nexport interface QueryDiscoveryExtension {\n info: QueryDiscoveryInfo;\n routeTemplate?: string;\n\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n type: \"object\";\n properties: {\n input: {\n type: \"object\";\n properties: {\n type: {\n type: \"string\";\n const: \"http\";\n };\n method: {\n type: \"string\";\n enum: QueryParamMethods[];\n };\n queryParams?: ParamMapSchemaProperty & { required?: string[] };\n pathParams?: ParamMapSchemaProperty;\n headers?: {\n type: \"object\";\n additionalProperties: {\n type: \"string\";\n };\n };\n };\n required: (\"type\" | \"method\")[];\n additionalProperties?: boolean;\n };\n output?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: readonly string[];\n additionalProperties?: boolean;\n };\n };\n required: [\"input\"];\n };\n}\n\n/**\n * Discovery extension for body methods (POST, PUT, PATCH)\n */\nexport interface BodyDiscoveryExtension {\n info: BodyDiscoveryInfo;\n routeTemplate?: string;\n\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n type: \"object\";\n properties: {\n input: {\n type: \"object\";\n properties: {\n type: {\n type: \"string\";\n const: \"http\";\n };\n method: {\n type: \"string\";\n enum: BodyMethods[];\n };\n bodyType: {\n type: \"string\";\n enum: [\"json\", \"form-data\", \"text\"];\n };\n body: Record<string, unknown>;\n queryParams?: ParamMapSchemaProperty & { required?: string[] };\n pathParams?: ParamMapSchemaProperty;\n headers?: {\n type: \"object\";\n additionalProperties: {\n type: \"string\";\n };\n };\n };\n required: (\"type\" | \"method\" | \"bodyType\" | \"body\")[];\n additionalProperties?: boolean;\n };\n output?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: readonly string[];\n additionalProperties?: boolean;\n };\n };\n required: [\"input\"];\n };\n}\n\nexport interface DeclareQueryDiscoveryExtensionConfig {\n method?: QueryParamMethods;\n input?: Record<string, unknown>;\n inputSchema?: Record<string, unknown>;\n pathParams?: Record<string, unknown>;\n pathParamsSchema?: Record<string, unknown>;\n output?: {\n example?: unknown;\n schema?: Record<string, unknown>;\n };\n}\n\nexport interface DeclareBodyDiscoveryExtensionConfig {\n method?: BodyMethods;\n input?: Record<string, unknown>;\n inputSchema?: Record<string, unknown>;\n pathParams?: Record<string, unknown>;\n pathParamsSchema?: Record<string, unknown>;\n bodyType: \"json\" | \"form-data\" | \"text\";\n output?: {\n example?: unknown;\n schema?: Record<string, unknown>;\n };\n}\n\nexport interface DiscoveredHTTPResource {\n resourceUrl: string;\n description?: string;\n mimeType?: string;\n /** Sanitized service metadata. See `sanitizeResourceServiceMetadata` for rules. */\n serviceName?: string;\n tags?: string[];\n iconUrl?: string;\n /** Present after server extension enrichment; may be absent for pre-enrichment data */\n method?: string;\n routeTemplate?: string;\n x402Version: number;\n discoveryInfo: DiscoveryInfo;\n /** Extension payloads for catalog echo (v2: payload.extensions; v1: synthesized extensions.bazaar) */\n extensions?: Record<string, unknown>;\n}\n\nexport const isQueryExtensionConfig = (\n config: DeclareQueryDiscoveryExtensionConfig | DeclareBodyDiscoveryExtensionConfig,\n): config is DeclareQueryDiscoveryExtensionConfig => {\n return !(\"bodyType\" in config) && !(\"toolName\" in config);\n};\n\nexport const isBodyExtensionConfig = (\n config: DeclareQueryDiscoveryExtensionConfig | DeclareBodyDiscoveryExtensionConfig,\n): config is DeclareBodyDiscoveryExtensionConfig => {\n return \"bodyType\" in config;\n};\n","/**\n * MCP-specific type definitions for the Bazaar Discovery Extension\n */\n\nimport type { DiscoveryInfo } from \"../types\";\n\n/**\n * Discovery info for MCP tools\n */\nexport interface McpDiscoveryInfo {\n input: {\n type: \"mcp\";\n toolName: string;\n description?: string;\n transport?: string;\n inputSchema: Record<string, unknown>;\n example?: Record<string, unknown>;\n };\n output?: {\n type?: string;\n format?: string;\n example?: unknown;\n };\n}\n\n/**\n * Discovery extension for MCP tools\n */\nexport interface McpDiscoveryExtension {\n info: McpDiscoveryInfo;\n\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\";\n type: \"object\";\n properties: {\n input: {\n type: \"object\";\n properties: {\n type: {\n type: \"string\";\n const: \"mcp\";\n };\n toolName: {\n type: \"string\";\n };\n description?: {\n type: \"string\";\n };\n transport?: {\n type: \"string\";\n enum?: string[];\n };\n inputSchema: Record<string, unknown>;\n example?: Record<string, unknown>;\n };\n required: (\"type\" | \"toolName\" | \"inputSchema\")[];\n additionalProperties?: boolean;\n };\n output?: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: readonly string[];\n additionalProperties?: boolean;\n };\n };\n required: [\"input\"];\n };\n}\n\nexport interface DeclareMcpDiscoveryExtensionConfig {\n toolName: string;\n description?: string;\n transport?: string;\n inputSchema: Record<string, unknown>;\n example?: Record<string, unknown>;\n output?: {\n example?: unknown;\n schema?: Record<string, unknown>;\n };\n}\n\nexport interface DiscoveredMCPResource {\n resourceUrl: string;\n description?: string;\n mimeType?: string;\n /** Sanitized service metadata. See `sanitizeResourceServiceMetadata` for rules. */\n serviceName?: string;\n tags?: string[];\n iconUrl?: string;\n toolName: string;\n x402Version: number;\n discoveryInfo: DiscoveryInfo;\n /** Extension payloads for catalog echo (v2: payload.extensions; v1: synthesized extensions.bazaar) */\n extensions?: Record<string, unknown>;\n}\n\nexport const isMcpExtensionConfig = (\n config: DeclareMcpDiscoveryExtensionConfig | Record<string, unknown>,\n): config is DeclareMcpDiscoveryExtensionConfig => {\n return \"toolName\" in config;\n};\n","/**\n * Shared type definitions for the Bazaar Discovery Extension\n *\n * Protocol-specific types live in their own directories (http/, mcp/).\n * This file defines the shared unions, constants, and utility types,\n * and re-exports all protocol-specific types for backwards compatibility.\n */\n\nimport type { FacilitatorExtension } from \"@x402/core/types\";\n\n// --- Shared union types ---\n\nimport type { QueryDiscoveryInfo, BodyDiscoveryInfo } from \"./http/types\";\nimport type { McpDiscoveryInfo } from \"./mcp/types\";\nimport type { QueryDiscoveryExtension, BodyDiscoveryExtension } from \"./http/types\";\nimport type { McpDiscoveryExtension } from \"./mcp/types\";\nimport type {\n DeclareQueryDiscoveryExtensionConfig,\n DeclareBodyDiscoveryExtensionConfig,\n} from \"./http/types\";\nimport type { DeclareMcpDiscoveryExtensionConfig } from \"./mcp/types\";\n\n// Re-export protocol-specific types\nexport type {\n QueryDiscoveryInfo,\n BodyDiscoveryInfo,\n QueryDiscoveryExtension,\n BodyDiscoveryExtension,\n DeclareQueryDiscoveryExtensionConfig,\n DeclareBodyDiscoveryExtensionConfig,\n DiscoveredHTTPResource,\n} from \"./http/types\";\n\nexport { isQueryExtensionConfig, isBodyExtensionConfig } from \"./http/types\";\n\nexport type {\n McpDiscoveryInfo,\n McpDiscoveryExtension,\n DeclareMcpDiscoveryExtensionConfig,\n DiscoveredMCPResource,\n} from \"./mcp/types\";\n\nexport { isMcpExtensionConfig } from \"./mcp/types\";\n\n// --- Shared constants ---\n\n/**\n * Extension identifier for the Bazaar discovery extension.\n */\nexport const BAZAAR: FacilitatorExtension = { key: \"bazaar\" };\n\n/**\n * Combined discovery info type\n */\nexport type DiscoveryInfo = QueryDiscoveryInfo | BodyDiscoveryInfo | McpDiscoveryInfo;\n\n/**\n * Combined discovery extension type\n */\nexport type DiscoveryExtension =\n | QueryDiscoveryExtension\n | BodyDiscoveryExtension\n | McpDiscoveryExtension;\n\nexport type DeclareDiscoveryExtensionConfig =\n | DeclareQueryDiscoveryExtensionConfig\n | DeclareBodyDiscoveryExtensionConfig\n | DeclareMcpDiscoveryExtensionConfig;\n\n/**\n * Distributive Omit - properly distributes Omit over union types.\n *\n * Standard `Omit<A | B, K>` collapses to common properties only,\n * losing discriminant properties like `bodyType`.\n *\n * This type uses conditional type distribution to preserve the union:\n * `DistributiveOmit<A | B, K>` = `Omit<A, K> | Omit<B, K>`\n */\nexport type DistributiveOmit<T, K extends keyof T> = T extends T ? Omit<T, K> : never;\n\n/**\n * Config type for declareDiscoveryExtension function.\n * Uses DistributiveOmit to preserve bodyType discriminant in the union for HTTP configs.\n * MCP config has no `method` field so it's included directly.\n */\nexport type DeclareDiscoveryExtensionInput =\n | DistributiveOmit<DeclareQueryDiscoveryExtensionConfig, \"method\">\n | DistributiveOmit<DeclareBodyDiscoveryExtensionConfig, \"method\">\n | DeclareMcpDiscoveryExtensionConfig;\n","/**\n * HTTP resource service functions for creating Bazaar discovery extensions\n */\n\nimport type {\n QueryDiscoveryExtension,\n BodyDiscoveryExtension,\n DeclareQueryDiscoveryExtensionConfig,\n DeclareBodyDiscoveryExtensionConfig,\n} from \"./types\";\n\n/**\n * Create a query discovery extension (GET, HEAD, DELETE)\n *\n * @param root0 - Configuration object for query discovery extension\n * @param root0.method - HTTP method (GET, HEAD, DELETE)\n * @param root0.input - Query parameters\n * @param root0.inputSchema - JSON schema for query parameters\n * @param root0.output - Output specification with example\n * @param root0.pathParams - Concrete path parameter values extracted from the request\n * @param root0.pathParamsSchema - JSON schema for path parameters\n * @returns QueryDiscoveryExtension with info and schema\n */\nexport function createQueryDiscoveryExtension({\n method,\n input = {},\n inputSchema = { properties: {} },\n pathParams,\n pathParamsSchema,\n output,\n}: DeclareQueryDiscoveryExtensionConfig): QueryDiscoveryExtension {\n return {\n info: {\n input: {\n type: \"http\" as const,\n ...(method ? { method } : {}),\n ...(input ? { queryParams: input } : {}),\n ...(pathParams ? { pathParams } : {}),\n },\n ...(output?.example\n ? {\n output: {\n type: \"json\",\n example: output.example,\n },\n }\n : {}),\n },\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n const: \"http\",\n },\n method: {\n type: \"string\",\n enum: [\"GET\", \"HEAD\", \"DELETE\"],\n },\n ...(inputSchema\n ? {\n queryParams: {\n type: \"object\" as const,\n ...(typeof inputSchema === \"object\" ? inputSchema : {}),\n },\n }\n : {}),\n ...(pathParamsSchema\n ? {\n pathParams: {\n type: \"object\" as const,\n ...(typeof pathParamsSchema === \"object\" ? pathParamsSchema : {}),\n },\n }\n : {}),\n },\n required: [\"type\", \"method\"] as (\"type\" | \"method\")[],\n // pathParams are not declared here at schema build time --\n // the server extension's enrichDeclaration adds them to both info and schema\n // atomically at request time, keeping data and schema consistent.\n additionalProperties: false,\n },\n ...(output?.example\n ? {\n output: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\" as const,\n },\n example: {\n type: \"object\" as const,\n ...(output.schema && typeof output.schema === \"object\" ? output.schema : {}),\n },\n },\n required: [\"type\"] as const,\n },\n }\n : {}),\n },\n required: [\"input\"],\n },\n };\n}\n\n/**\n * Create a body discovery extension (POST, PUT, PATCH)\n *\n * @param root0 - Configuration object for body discovery extension\n * @param root0.method - HTTP method (POST, PUT, PATCH)\n * @param root0.input - Request body specification\n * @param root0.inputSchema - JSON schema for request body\n * @param root0.bodyType - Content type of body (json, form-data, text)\n * @param root0.output - Output specification with example\n * @param root0.pathParams - Concrete path parameter values extracted from the request\n * @param root0.pathParamsSchema - JSON schema for path parameters\n * @returns BodyDiscoveryExtension with info and schema\n */\nexport function createBodyDiscoveryExtension({\n method,\n input = {},\n inputSchema = { properties: {} },\n pathParams,\n pathParamsSchema,\n bodyType,\n output,\n}: DeclareBodyDiscoveryExtensionConfig): BodyDiscoveryExtension {\n return {\n info: {\n input: {\n type: \"http\" as const,\n ...(method ? { method } : {}),\n bodyType,\n body: input,\n ...(pathParams ? { pathParams } : {}),\n },\n ...(output?.example\n ? {\n output: {\n type: \"json\",\n example: output.example,\n },\n }\n : {}),\n },\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n const: \"http\",\n },\n method: {\n type: \"string\",\n enum: [\"POST\", \"PUT\", \"PATCH\"],\n },\n bodyType: {\n type: \"string\",\n enum: [\"json\", \"form-data\", \"text\"],\n },\n body: inputSchema,\n ...(pathParamsSchema\n ? {\n pathParams: {\n type: \"object\" as const,\n ...(typeof pathParamsSchema === \"object\" ? pathParamsSchema : {}),\n },\n }\n : {}),\n },\n required: [\"type\", \"method\", \"bodyType\", \"body\"] as (\n | \"type\"\n | \"method\"\n | \"bodyType\"\n | \"body\"\n )[],\n // pathParams are not declared here at schema build time --\n // the server extension's enrichDeclaration adds them to both info and schema\n // atomically at request time, keeping data and schema consistent.\n additionalProperties: false,\n },\n ...(output?.example\n ? {\n output: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\" as const,\n },\n example: {\n type: \"object\" as const,\n ...(output.schema && typeof output.schema === \"object\" ? output.schema : {}),\n },\n },\n required: [\"type\"] as const,\n },\n }\n : {}),\n },\n required: [\"input\"],\n },\n };\n}\n","/**\n * MCP resource service functions for creating Bazaar discovery extensions\n */\n\nimport type { McpDiscoveryExtension, DeclareMcpDiscoveryExtensionConfig } from \"./types\";\n\n/**\n * Create an MCP tool discovery extension\n *\n * @param root0 - Configuration object for MCP discovery extension\n * @param root0.toolName - MCP tool name\n * @param root0.description - Tool description\n * @param root0.inputSchema - JSON Schema for tool arguments\n * @param root0.example - Example tool arguments\n * @param root0.output - Output specification with example\n * @param root0.transport - MCP transport type (streamable-http or sse)\n * @returns McpDiscoveryExtension with info and schema\n */\nexport function createMcpDiscoveryExtension({\n toolName,\n description,\n transport,\n inputSchema,\n example,\n output,\n}: DeclareMcpDiscoveryExtensionConfig): McpDiscoveryExtension {\n return {\n info: {\n input: {\n type: \"mcp\",\n toolName,\n ...(description !== undefined ? { description } : {}),\n ...(transport !== undefined ? { transport } : {}),\n inputSchema,\n ...(example !== undefined ? { example } : {}),\n },\n ...(output?.example\n ? {\n output: {\n type: \"json\",\n example: output.example,\n },\n }\n : {}),\n },\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n const: \"mcp\",\n },\n toolName: {\n type: \"string\",\n },\n ...(description !== undefined\n ? {\n description: {\n type: \"string\" as const,\n },\n }\n : {}),\n ...(transport !== undefined\n ? {\n transport: {\n type: \"string\" as const,\n ...(transport === \"streamable-http\" || transport === \"sse\"\n ? { enum: [transport] }\n : {}),\n },\n }\n : {}),\n inputSchema: {\n type: \"object\" as const,\n },\n ...(example !== undefined\n ? {\n example: {\n type: \"object\" as const,\n },\n }\n : {}),\n },\n required: [\"type\", \"toolName\", \"inputSchema\"] as (\"type\" | \"toolName\" | \"inputSchema\")[],\n additionalProperties: false,\n },\n ...(output?.example\n ? {\n output: {\n type: \"object\" as const,\n properties: {\n type: {\n type: \"string\" as const,\n },\n example: {\n type: \"object\" as const,\n ...(output.schema && typeof output.schema === \"object\" ? output.schema : {}),\n },\n },\n required: [\"type\"] as const,\n },\n }\n : {}),\n },\n required: [\"input\"],\n },\n };\n}\n","/**\n * Resource Service entry point for creating Bazaar discovery extensions\n *\n * This module provides the unified `declareDiscoveryExtension` function that\n * routes to protocol-specific builders in http/ and mcp/.\n */\n\nimport type { DiscoveryExtension, DeclareDiscoveryExtensionInput } from \"./types\";\nimport type {\n DeclareQueryDiscoveryExtensionConfig,\n DeclareBodyDiscoveryExtensionConfig,\n} from \"./http/types\";\nimport type { DeclareMcpDiscoveryExtensionConfig } from \"./mcp/types\";\nimport {\n createQueryDiscoveryExtension,\n createBodyDiscoveryExtension,\n} from \"./http/resourceService\";\nimport { createMcpDiscoveryExtension } from \"./mcp/resourceService\";\n\n/**\n * Create a discovery extension for any HTTP method or MCP tool\n *\n * This function helps servers declare how their endpoint should be called,\n * including the expected input parameters/body and output format.\n *\n * @param config - Configuration object for the discovery extension\n * @returns A discovery extension object with both info and schema\n *\n * @example\n * ```typescript\n * // For a GET endpoint with no input\n * const getExtension = declareDiscoveryExtension({\n * method: \"GET\",\n * output: {\n * example: { message: \"Success\", timestamp: \"2024-01-01T00:00:00Z\" }\n * }\n * });\n *\n * // For a GET endpoint with query params\n * const getWithParams = declareDiscoveryExtension({\n * method: \"GET\",\n * input: { query: \"example\" },\n * inputSchema: {\n * properties: {\n * query: { type: \"string\" }\n * },\n * required: [\"query\"]\n * }\n * });\n *\n * // For a POST endpoint with JSON body\n * const postExtension = declareDiscoveryExtension({\n * method: \"POST\",\n * input: { name: \"John\", age: 30 },\n * inputSchema: {\n * properties: {\n * name: { type: \"string\" },\n * age: { type: \"number\" }\n * },\n * required: [\"name\"]\n * },\n * bodyType: \"json\",\n * output: {\n * example: { success: true, id: \"123\" }\n * }\n * });\n *\n * // For an MCP tool\n * const mcpExtension = declareDiscoveryExtension({\n * toolName: \"financial_analysis\",\n * description: \"Analyze financial data for a given ticker\",\n * inputSchema: {\n * type: \"object\",\n * properties: {\n * ticker: { type: \"string\" },\n * },\n * required: [\"ticker\"],\n * },\n * output: {\n * example: { pe_ratio: 28.5, recommendation: \"hold\" }\n * }\n * });\n * ```\n */\nexport function declareDiscoveryExtension(\n config: DeclareDiscoveryExtensionInput,\n): Record<string, DiscoveryExtension> {\n if (\"toolName\" in config) {\n const extension = createMcpDiscoveryExtension(config as DeclareMcpDiscoveryExtensionConfig);\n return { bazaar: extension as DiscoveryExtension };\n }\n\n const bodyType = (config as DeclareBodyDiscoveryExtensionConfig).bodyType;\n const isBodyMethod = bodyType !== undefined;\n\n const extension = isBodyMethod\n ? createBodyDiscoveryExtension(config as DeclareBodyDiscoveryExtensionConfig)\n : createQueryDiscoveryExtension(config as DeclareQueryDiscoveryExtensionConfig);\n\n return { bazaar: extension as DiscoveryExtension };\n}\n","import type { ResourceServerExtension } from \"@x402/core/types\";\nimport type { HTTPRequestContext } from \"@x402/core/http\";\nimport { BAZAAR } from \"./types\";\n\n// Non-global: safe for test/split (no stateful lastIndex side-effects).\nconst BRACKET_PARAM_REGEX = /\\[([^\\]]+)\\]/;\n// Global variant required for String.replace to substitute ALL occurrences.\n// JS String.replace with a non-global regex replaces only the first match.\n// (String.replaceAll with a non-global regex would work in ES2021+, but the\n// target lib is ES2020 — keep this separate constant to avoid that constraint.)\nconst BRACKET_PARAM_REGEX_ALL = /\\[([^\\]]+)\\]/g;\n\nconst COLON_PARAM_REGEX = /:([a-zA-Z_][a-zA-Z0-9_]*)/;\n\n/**\n * Type guard to check if context is an HTTP request context.\n *\n * @param ctx - The context to check\n * @returns True if context is an HTTPRequestContext\n */\nfunction isHTTPRequestContext(ctx: unknown): ctx is HTTPRequestContext {\n return ctx !== null && typeof ctx === \"object\" && \"method\" in ctx && \"adapter\" in ctx;\n}\n\n/**\n * Converts wildcard segments in a route pattern to named :varN parameters\n * so they can be treated as dynamic routes for discovery catalog normalization.\n *\n * @param pattern - Route pattern that may contain wildcard segments\n * @returns The pattern with wildcard segments replaced by :var1, :var2, etc.\n */\nfunction normalizeWildcardPattern(pattern: string): string {\n if (!pattern.includes(\"*\")) {\n return pattern;\n }\n let counter = 0;\n return pattern\n .split(\"/\")\n .map(seg => {\n if (seg === \"*\") {\n counter++;\n return `:var${counter}`;\n }\n return seg;\n })\n .join(\"/\");\n}\n\n/**\n * Returns true when a route pattern contains only wildcard segments (e.g. `\"*\"`),\n * with no literal path segments. Bare wildcards must not produce a routeTemplate\n * for discovery catalog indexing.\n *\n * @param pattern - Route pattern from route matching (path only, no HTTP method)\n * @returns True if every segment is a wildcard\n */\nfunction isWildcardOnlyPattern(pattern: string): boolean {\n const segments = pattern.split(\"/\").filter(segment => segment.length > 0);\n return segments.length > 0 && segments.every(segment => segment === \"*\");\n}\n\n/**\n * Converts a parameterized route pattern into a :param template and extracts concrete\n * param values from the URL path in a single call.\n *\n * Supports both [param] (Next.js) and :param (Express) syntax. The output routeTemplate\n * always uses :param syntax regardless of input format.\n *\n * @param routePattern - Route pattern (e.g. \"/users/[userId]\" or \"/users/:userId\")\n * @param urlPath - Concrete URL path (e.g. \"/users/123\")\n * @returns Object with routeTemplate and pathParams, or null if no params detected\n */\nfunction extractDynamicRouteInfo(\n routePattern: string,\n urlPath: string,\n): { routeTemplate: string; pathParams: Record<string, string> } | null {\n const hasBracket = BRACKET_PARAM_REGEX.test(routePattern);\n const hasColon = COLON_PARAM_REGEX.test(routePattern);\n if (!hasBracket && !hasColon) {\n return null;\n }\n // When both [param] and :param are present, normalize brackets to colons first\n // so all params are extracted uniformly.\n const normalizedPattern = hasBracket\n ? routePattern.replace(BRACKET_PARAM_REGEX_ALL, \":$1\")\n : routePattern;\n const pathParams = extractPathParams(normalizedPattern, urlPath, false);\n return { routeTemplate: normalizedPattern, pathParams };\n}\n\n/**\n * Extracts concrete path parameter values by matching a URL path against a route pattern.\n *\n * @param routePattern - Route pattern with [paramName] or :paramName segments\n * @param urlPath - Concrete URL path (e.g. \"/users/123\")\n * @param isBracket - True if pattern uses [param] syntax, false for :param\n * @returns Record mapping param names to their values\n */\nfunction extractPathParams(\n routePattern: string,\n urlPath: string,\n isBracket: boolean,\n): Record<string, string> {\n const paramNames: string[] = [];\n const splitRegex = isBracket ? BRACKET_PARAM_REGEX : COLON_PARAM_REGEX;\n // Split on param markers so literal segments can be regex-escaped independently.\n // Without escaping, a route like /api/v1.0/[id] would produce a regex where '.' matches\n // any character (e.g. /api/v1X0/123 would incorrectly match).\n const parts = routePattern.split(splitRegex);\n const regexParts: string[] = [];\n parts.forEach((part, i) => {\n if (i % 2 === 0) {\n // Literal segment – escape all regex metacharacters\n regexParts.push(part.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"));\n } else {\n // Param name\n paramNames.push(part);\n regexParts.push(\"([^/]+)\");\n }\n });\n\n const regex = new RegExp(`^${regexParts.join(\"\")}$`);\n const match = urlPath.match(regex);\n\n if (!match) return {};\n\n const result: Record<string, string> = {};\n paramNames.forEach((name, idx) => {\n result[name] = match[idx + 1];\n });\n return result;\n}\n\ninterface ExtensionDeclaration {\n [key: string]: unknown;\n info?: {\n [key: string]: unknown;\n input?: Record<string, unknown>;\n };\n schema?: {\n [key: string]: unknown;\n properties?: {\n [key: string]: unknown;\n input?: {\n [key: string]: unknown;\n properties?: {\n [key: string]: unknown;\n method?: Record<string, unknown>;\n };\n required?: string[];\n };\n };\n };\n}\n\nexport const bazaarResourceServerExtension: ResourceServerExtension = {\n key: BAZAAR.key,\n\n enrichDeclaration: (declaration, transportContext) => {\n if (!isHTTPRequestContext(transportContext)) {\n return declaration;\n }\n\n const extension = declaration as ExtensionDeclaration;\n\n // MCP extensions don't need HTTP method enrichment\n if (extension.info?.input?.type === \"mcp\") {\n return declaration;\n }\n\n const method = transportContext.method;\n\n // At declaration time, the schema uses a broad enum ([\"GET\", \"HEAD\", \"DELETE\"] or [\"POST\", \"PUT\", \"PATCH\"])\n // because the method isn't known until the HTTP context is available.\n // Here we narrow it to the actual method for precise schema validation.\n const existingInputProps = extension.schema?.properties?.input?.properties || {};\n const updatedInputProps = {\n ...existingInputProps,\n method: {\n type: \"string\",\n enum: [method],\n },\n };\n\n const enrichedResult = {\n ...extension,\n info: {\n ...(extension.info || {}),\n input: {\n ...(extension.info?.input || {}),\n method,\n },\n },\n schema: {\n ...(extension.schema || {}),\n properties: {\n ...(extension.schema?.properties || {}),\n input: {\n ...(extension.schema?.properties?.input || {}),\n properties: updatedInputProps,\n required: [\n ...(extension.schema?.properties?.input?.required || []),\n ...(!(extension.schema?.properties?.input?.required || []).includes(\"method\")\n ? [\"method\"]\n : []),\n ],\n },\n },\n },\n };\n\n // Dynamic routes: translate [param]/:param → :param for the routeTemplate catalog key;\n // pathParams carries runtime values (distinct from pathParamsSchema in the declaration).\n // Wildcard * segments are auto-converted to :var1, :var2, etc. for catalog normalization.\n const rawRoutePattern = (transportContext as HTTPRequestContext).routePattern;\n if (rawRoutePattern && isWildcardOnlyPattern(rawRoutePattern)) {\n return enrichedResult;\n }\n const routePattern = rawRoutePattern ? normalizeWildcardPattern(rawRoutePattern) : undefined;\n const dynamicRoute = routePattern\n ? extractDynamicRouteInfo(routePattern, transportContext.adapter.getPath())\n : null;\n if (dynamicRoute) {\n const inputSchemaProps = enrichedResult.schema?.properties?.input?.properties || {};\n const hasPathParamsInSchema = \"pathParams\" in inputSchemaProps;\n return {\n ...enrichedResult,\n routeTemplate: dynamicRoute.routeTemplate,\n info: {\n ...enrichedResult.info,\n input: { ...enrichedResult.info.input, pathParams: dynamicRoute.pathParams },\n },\n ...(!hasPathParamsInSchema\n ? {\n schema: {\n ...enrichedResult.schema,\n properties: {\n ...enrichedResult.schema?.properties,\n input: {\n ...enrichedResult.schema?.properties?.input,\n properties: {\n ...inputSchemaProps,\n pathParams: { type: \"object\" },\n },\n },\n },\n },\n }\n : {}),\n };\n }\n\n return enrichedResult;\n },\n};\n","/**\n * Facilitator functions for validating and extracting Bazaar discovery extensions\n *\n * These functions help facilitators validate extension data against schemas\n * and extract the discovery information for cataloging in the Bazaar.\n *\n * Supports both v2 (extensions in PaymentRequired) and v1 (outputSchema in PaymentRequirements).\n */\n\nimport { domainToASCII } from \"node:url\";\nimport Ajv from \"ajv/dist/2020.js\";\nimport type {\n PaymentPayload,\n PaymentRequirements,\n PaymentRequirementsV1,\n ResourceInfo,\n} from \"@x402/core/types\";\nimport type { DiscoveryExtension, DiscoveryInfo } from \"./types\";\nimport type { McpDiscoveryInfo } from \"./mcp/types\";\nimport type { DiscoveredHTTPResource } from \"./http/types\";\nimport type { DiscoveredMCPResource } from \"./mcp/types\";\nimport { BAZAAR } from \"./types\";\nimport { buildV1CatalogExtensions, extractDiscoveryInfoV1 } from \"./v1/facilitator\";\n\n/**\n * Valid routeTemplate pattern: must start with \"/\", contain only safe URL path characters\n * and :param identifiers, and not include traversal sequences or scheme markers.\n *\n * Allowed: /users/:userId, /weather/:country/:city, /api/v1/items\n */\nconst ROUTE_TEMPLATE_REGEX = /^\\/[a-zA-Z0-9_/:.\\-~%]+$/;\n\n/**\n * Maximum number of successive `decodeURIComponent` passes applied while\n * canonicalizing a routeTemplate before giving up and rejecting it.\n *\n * A legitimate single-encoded value reaches a fixed point (further decoding\n * changes nothing) after one pass. This allows a few extra passes so\n * multiply-encoded traversal/injection payloads (not just doubly-encoded\n * ones) are still caught, while bounding the work done on adversarial input.\n */\nconst MAX_ROUTE_TEMPLATE_DECODE_PASSES = 5;\n\n/**\n * Repeatedly percent-decodes `value` until a fixed point is reached (further\n * decoding produces no change) or {@link MAX_ROUTE_TEMPLATE_DECODE_PASSES} is\n * exhausted, returning the fully-canonicalized string.\n *\n * A single decode pass only catches a payload encoded exactly once (e.g.\n * `%2e%2e`); a double- or triple-encoded payload (`%252e%252e`,\n * `%25252e%25252e`, ...) would still contain literal `%` sequences after one\n * pass and slip past a traversal/injection substring check performed on that\n * partially-decoded result. Decoding to a fixed point closes that gap for any\n * encoding depth, not just the double-encoded case.\n *\n * @param value - The string to canonicalize.\n * @returns The fully-decoded string, or `undefined` if any pass fails to\n * parse (malformed percent-encoding) or the pass budget is exhausted\n * without reaching a fixed point.\n */\nfunction fullyDecodeRouteTemplate(value: string): string | undefined {\n let decoded = value;\n for (let i = 0; i < MAX_ROUTE_TEMPLATE_DECODE_PASSES; i++) {\n let next: string;\n try {\n next = decodeURIComponent(decoded);\n } catch {\n return undefined;\n }\n if (next === decoded) return decoded;\n decoded = next;\n }\n // Still changing after the pass budget: either pathologically deep\n // encoding or a `%` that never resolves to a fixed point. Either way,\n // there's no safe canonical form to validate against — reject.\n return undefined;\n}\n\n/**\n * Checks whether a routeTemplate value is structurally valid.\n *\n * Expected format: \"/:param\" segments using colon-prefixed identifiers\n * (e.g. \"/users/:userId\", \"/weather/:country/:city\").\n *\n * The facilitator is a trust boundary: clients control the payment payload and\n * can modify routeTemplate before submission. A malicious value could cause the\n * facilitator to catalog the payment under an arbitrary URL (catalog poisoning).\n * This function enforces minimal structural requirements:\n * - Must be a non-empty string starting with \"/\"\n * - Must match the safe URL path character set (alphanumeric, _, :, /, ., -, ~, %)\n * - Must not contain \"..\" (path traversal), at any percent-encoding depth\n * - Must not contain \"://\" (URL injection), at any percent-encoding depth\n *\n * @param value - The raw routeTemplate string from the client payload\n * @returns true if the value is a valid routeTemplate, false otherwise\n *\n * @internal Exported for facilitator use.\n */\nexport function isValidRouteTemplate(value: string | undefined): value is string {\n if (!value) return false;\n if (!ROUTE_TEMPLATE_REGEX.test(value)) return false;\n // Decode to a fixed point before traversal checks, so that %2e%2e,\n // %252e%252e, and deeper encodings are all caught rather than just the\n // single-encoded case.\n const decoded = fullyDecodeRouteTemplate(value);\n if (decoded === undefined) return false;\n if (decoded.includes(\"..\")) return false;\n if (decoded.includes(\"://\")) return false;\n return true;\n}\n\n/**\n * Validates a routeTemplate and returns it if valid, undefined otherwise.\n *\n * @param value - The raw routeTemplate string to validate\n * @returns The validated value, or undefined if invalid\n * @deprecated Use `isValidRouteTemplate` instead.\n */\nexport function validateRouteTemplate(value: string | undefined): string | undefined {\n return isValidRouteTemplate(value) ? value : undefined;\n}\n\n/**\n * Maximum lengths for resource service metadata fields. Spec: see\n * `specs/extensions/bazaar.md` \"Service Metadata on `resource`\".\n */\nconst MAX_SERVICE_NAME_LEN = 32;\nconst MAX_TAG_LEN = 32;\nconst MAX_TAGS = 5;\nconst MAX_ICON_URL_LEN = 2048;\n// Matches ASCII control characters (C0 + DEL).\nconst CONTROL_CHAR_REGEX = /[\\x00-\\x1f\\x7f]/;\n// Printable ASCII range (U+0020–U+007E). `serviceName` and `tags` are\n// constrained to this range so that String.length (UTF-16 code units),\n// len() in Python (code points), and len() in Go (UTF-8 bytes) all agree\n// on the character count. Same convention as paymentidentifier.id.\nconst PRINTABLE_ASCII_REGEX = /^[\\x20-\\x7e]+$/;\n// Unicode control characters (category Cc). Defense-in-depth: the printable\n// ASCII regex already rejects every control character, but this explicit\n// check documents intent and would survive any future relaxation of the\n// ASCII restriction. Mirrors `unicode.IsControl` (Go).\nconst UNICODE_CONTROL_REGEX = /\\p{Cc}/u;\n\n// Loopback hostnames that must be rejected for SSRF defense. Includes the\n// common /etc/hosts aliases on Linux/macOS (`localhost.localdomain`,\n// `ip6-localhost`, `ip6-loopback`) — without these, a hostile provider could\n// route the facilitator's image fetcher to its own loopback interface.\nconst LOOPBACK_HOSTNAMES = new Set([\n \"localhost\",\n \"localhost.localdomain\",\n \"ip6-localhost\",\n \"ip6-loopback\",\n]);\n// Matches a bare IPv4 dotted-quad. IPv6 literals are detected via hostname brackets.\nconst IPV4_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\n// SSRF defense: any all-digit hostname is suspect because no legitimate DNS name\n// is purely numeric. Catches decimal-encoded IPs (`http://2130706433/` → 127.0.0.1)\n// and short-form IPs (`http://0/` → 0.0.0.0, treated as loopback on Linux).\nconst ALL_DIGITS_REGEX = /^\\d+$/;\n// SSRF defense: hex-encoded IPs (`http://0x7f000001/` → 127.0.0.1) — same family\n// of bypasses as the decimal form above.\nconst HEX_LITERAL_REGEX = /^0x[0-9a-f]+$/i;\n\n/**\n * Checks whether a serviceName value is structurally valid for the bazaar\n * `resource.serviceName` field. Non-empty string of printable ASCII\n * (U+0020–U+007E), length ≤ 32.\n *\n * The ASCII restriction matches the `paymentidentifier.id` convention and\n * keeps `len()` semantics identical across TS / Python / Go.\n *\n * Mirrors `_is_valid_service_name` (Python) and `isValidServiceName` (Go).\n * All three implementations must stay in sync.\n *\n * @param value - The raw serviceName string from the resource object\n * @returns true if the value is a valid serviceName, false otherwise\n *\n * @internal Exported for facilitator use.\n */\nexport function isValidServiceName(value: string | undefined): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length === 0 || value.length > MAX_SERVICE_NAME_LEN) return false;\n if (UNICODE_CONTROL_REGEX.test(value)) return false;\n if (!PRINTABLE_ASCII_REGEX.test(value)) return false;\n return true;\n}\n\n/**\n * Sanitizes a tags array for the bazaar `resource.tags` field. Drops entries\n * that are not non-empty printable-ASCII strings of at most 32 characters,\n * then truncates to the first 5 valid entries. Returns undefined when no\n * entries survive (so the field can be omitted from the catalog).\n *\n * The ASCII restriction matches the `paymentidentifier.id` convention and\n * keeps `len()` semantics identical across TS / Python / Go.\n *\n * Mirrors `_sanitize_tags` (Python) and `sanitizeTags` (Go).\n * All three implementations must stay in sync.\n *\n * @param value - The raw tags value from the resource object (typed as unknown\n * because callers pass it directly from a parsed JSON payload)\n * @returns The sanitized tags array, or undefined if no entries survive\n *\n * @internal Exported for facilitator use.\n */\nexport function sanitizeTags(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const out: string[] = [];\n // Case-insensitive dedup: keeps the first occurrence's casing.\n // Prevents catalog noise like [\"Weather\", \"weather\", \"WEATHER\"].\n const seen = new Set<string>();\n for (const entry of value) {\n if (typeof entry !== \"string\") continue;\n if (entry.length === 0 || entry.length > MAX_TAG_LEN) continue;\n if (UNICODE_CONTROL_REGEX.test(entry)) continue;\n if (!PRINTABLE_ASCII_REGEX.test(entry)) continue;\n const key = entry.toLowerCase();\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(entry);\n if (out.length === MAX_TAGS) break;\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * Checks whether an iconUrl value is structurally safe for the bazaar\n * `resource.iconUrl` field.\n *\n * Rules (see `specs/extensions/bazaar.md` \"Service Metadata on `resource`\"):\n * - String of length ≤ 2048\n * - No ASCII control characters\n * - Parses as an absolute http:// or https:// URL\n * - No userinfo (user@host)\n * - Host is IDN-normalized (UTS #46) before checks, so confusable\n * full-width / Unicode forms (e.g. `localhost`) collapse to their\n * ASCII canonical and get caught by the loopback check\n * - Host is not an IP literal (v4 or v6), not in the loopback set\n * (`localhost`, `localhost.localdomain`, `ip6-localhost`, `ip6-loopback`)\n * - Host is not a decimal IP encoding (e.g. `2130706433` → 127.0.0.1) or\n * hex literal (e.g. `0x7f000001`) — common SSRF bypass forms\n *\n * Percent-decoding is applied to the hostname before IDN normalization, and\n * IDN normalization runs before the IP / loopback checks (parallel to the\n * routeTemplate decoder).\n *\n * Mirrors `_is_valid_icon_url` (Python) and `isValidIconUrl` (Go).\n * All three implementations must stay in sync.\n *\n * @param value - The raw iconUrl string from the resource object\n * @returns true if the value is a structurally safe iconUrl, false otherwise\n *\n * @internal Exported for facilitator use.\n */\nexport function isValidIconUrl(value: string | undefined): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length === 0 || value.length > MAX_ICON_URL_LEN) return false;\n if (CONTROL_CHAR_REGEX.test(value)) return false;\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return false;\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n if (parsed.username !== \"\" || parsed.password !== \"\") return false;\n // URL.hostname strips IPv6 brackets, so detect IPv6 from the bracketed host instead.\n if (parsed.host.startsWith(\"[\")) return false;\n let hostname: string;\n try {\n hostname = decodeURIComponent(parsed.hostname);\n } catch {\n return false;\n }\n // IDN/full-width normalization: e.g. \"localhost\" (full-width Latin)\n // → \"localhost\". Without this the loopback alias check would miss\n // confusable Unicode hostnames. domainToASCII applies the same WHATWG /\n // UTS #46 mapping that idna.Lookup.ToASCII (Go) and idna.encode (Python)\n // use; returns \"\" on failure.\n const asciiHost = domainToASCII(hostname);\n if (asciiHost === \"\") return false;\n hostname = asciiHost.toLowerCase();\n if (hostname === \"\") return false;\n if (LOOPBACK_HOSTNAMES.has(hostname)) return false;\n if (IPV4_REGEX.test(hostname)) return false;\n if (ALL_DIGITS_REGEX.test(hostname)) return false;\n if (HEX_LITERAL_REGEX.test(hostname)) return false;\n return true;\n}\n\n/**\n * Sanitized service metadata extracted from a `resource` object.\n */\nexport interface SanitizedResourceServiceMetadata {\n serviceName?: string;\n tags?: string[];\n iconUrl?: string;\n}\n\n/**\n * Applies the bazaar service-metadata validation rules to a `resource` object\n * and returns only the fields that survive. Missing or invalid fields are\n * dropped silently (soft-drop semantics — see spec).\n *\n * @param resource - The raw `resource` object from a PaymentRequired or\n * PaymentPayload, or undefined.\n * @returns An object containing only the valid serviceName / tags / iconUrl.\n *\n * @internal Exported for facilitator use.\n */\nexport function sanitizeResourceServiceMetadata(\n resource: ResourceInfo | undefined | null,\n): SanitizedResourceServiceMetadata {\n if (!resource) return {};\n const out: SanitizedResourceServiceMetadata = {};\n if (isValidServiceName(resource.serviceName)) {\n out.serviceName = resource.serviceName;\n }\n const tags = sanitizeTags(resource.tags);\n if (tags) {\n out.tags = tags;\n }\n if (isValidIconUrl(resource.iconUrl)) {\n out.iconUrl = resource.iconUrl;\n }\n return out;\n}\n\n/**\n * Validation result for discovery extensions\n */\nexport interface ValidationResult {\n valid: boolean;\n errors?: string[];\n}\n\n/**\n * Recursively scans a decoded JSON Schema document for \"$ref\"/\"$id\" values that are not\n * same-document fragments (i.e. do not start with \"#\").\n *\n * Ajv's default `compile` throws rather than dereferencing an unregistered absolute/relative\n * `$ref`, so this SDK does not fetch or read anything by default. This guard exists for\n * defense-in-depth and to give a consistent, explicit rejection message across all x402 SDKs,\n * since schema is client-controlled (it arrives in the payment payload) and any external\n * $ref/$id is a CWE-918 SSRF / local file disclosure pattern other JSON Schema tooling\n * (including future Ajv options like `loadSchema`) can act on.\n *\n * @param node - The (sub)tree of a decoded JSON Schema document to scan\n * @returns True if any non-fragment \"$ref\"/\"$id\" value is found\n */\nfunction hasExternalSchemaReference(node: unknown): boolean {\n if (Array.isArray(node)) {\n return node.some(item => hasExternalSchemaReference(item));\n }\n if (node && typeof node === \"object\") {\n for (const [key, value] of Object.entries(node as Record<string, unknown>)) {\n if (key === \"$ref\" || key === \"$id\") {\n if (typeof value !== \"string\" || !value.startsWith(\"#\")) {\n return true;\n }\n }\n if (hasExternalSchemaReference(value)) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Validates a discovery extension's info against its schema\n *\n * @param extension - The discovery extension containing info and schema\n * @returns Validation result indicating if the info matches the schema\n *\n * @example\n * ```typescript\n * const extension = declareDiscoveryExtension(...);\n * const result = validateDiscoveryExtension(extension);\n *\n * if (result.valid) {\n * console.log(\"Extension is valid\");\n * } else {\n * console.error(\"Validation errors:\", result.errors);\n * }\n * ```\n */\nexport function validateDiscoveryExtension(extension: DiscoveryExtension): ValidationResult {\n try {\n // The schema is attacker-controlled (it arrives in the client's payment payload). Only\n // same-document fragment references (e.g. \"#/definitions/foo\") are safe, since they\n // resolve against the in-memory document instead of fetching or reading anything.\n if (hasExternalSchemaReference(extension.schema)) {\n return {\n valid: false,\n errors: [\"schema must not contain external $ref/$id references\"],\n };\n }\n\n const ajv = new Ajv({ strict: false, allErrors: true });\n const validate = ajv.compile(extension.schema);\n\n // The schema describes the structure of info directly\n // Schema has properties: { input: {...}, output: {...} }\n // So we validate extension.info which has { input: {...}, output: {...} }\n const valid = validate(extension.info);\n\n if (valid) {\n return { valid: true };\n }\n\n const errors = validate.errors?.map(err => {\n const path = err.instancePath || \"(root)\";\n return `${path}: ${err.message}`;\n }) || [\"Unknown validation error\"];\n\n return { valid: false, errors };\n } catch (error) {\n return {\n valid: false,\n errors: [\n `Schema validation failed: ${error instanceof Error ? error.message : String(error)}`,\n ],\n };\n }\n}\n\nconst VALID_QUERY_METHODS = new Set([\"GET\", \"HEAD\", \"DELETE\"]);\nconst VALID_BODY_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\"]);\nconst VALID_METHODS = new Set([...VALID_QUERY_METHODS, ...VALID_BODY_METHODS]);\nconst VALID_BODY_TYPES = new Set([\"json\", \"form-data\", \"text\"]);\nconst VALID_MCP_TRANSPORTS = new Set([\"streamable-http\", \"sse\"]);\n\n/**\n * Validates a discovery extension against the Bazaar protocol specification.\n *\n * Unlike `validateDiscoveryExtension` which checks internal consistency (info vs schema),\n * this function enforces protocol-level invariants:\n * - `info.input.type` must be \"http\" or \"mcp\"\n * - HTTP: if `method` is present it must be GET/POST/PUT/PATCH/DELETE/HEAD\n * - HTTP body methods: `bodyType` must be \"json\" | \"form-data\" | \"text\"\n * - MCP: `toolName` (string) and `inputSchema` (object) are required\n * - MCP: if `transport` is present it must be \"streamable-http\" | \"sse\"\n *\n * Designed to be safe for pre-enrichment HTTP extensions where `method` may be absent.\n *\n * @param extension - The discovery extension to validate\n * @returns Validation result with spec-level errors\n */\nexport function validateDiscoveryExtensionSpec(\n extension: Record<string, unknown>,\n): ValidationResult {\n const errors: string[] = [];\n\n const info = extension.info;\n if (!info || typeof info !== \"object\") {\n return { valid: false, errors: [\"Missing or invalid 'info' field\"] };\n }\n\n const input = (info as Record<string, unknown>).input;\n if (!input || typeof input !== \"object\") {\n return { valid: false, errors: [\"Missing or invalid 'info.input' field\"] };\n }\n\n const inputObj = input as Record<string, unknown>;\n const inputType = inputObj.type;\n\n if (inputType !== \"http\" && inputType !== \"mcp\") {\n errors.push(`info.input.type must be \"http\" or \"mcp\", got \"${String(inputType)}\"`);\n return { valid: false, errors };\n }\n\n if (inputType === \"http\") {\n const method = inputObj.method;\n if (method !== undefined && !VALID_METHODS.has(method as string)) {\n errors.push(\n `info.input.method must be one of ${[...VALID_METHODS].join(\", \")}, got \"${String(method)}\"`,\n );\n }\n\n const bodyType = inputObj.bodyType;\n if (bodyType !== undefined) {\n if (!VALID_BODY_TYPES.has(bodyType as string)) {\n errors.push(\n `info.input.bodyType must be one of ${[...VALID_BODY_TYPES].join(\", \")}, got \"${String(bodyType)}\"`,\n );\n }\n if (method !== undefined && !VALID_BODY_METHODS.has(method as string)) {\n errors.push(\n `info.input.bodyType is set but method \"${String(method)}\" is not a body method (POST, PUT, PATCH)`,\n );\n }\n }\n }\n\n if (inputType === \"mcp\") {\n if (typeof inputObj.toolName !== \"string\" || inputObj.toolName.length === 0) {\n errors.push(\n \"info.input.toolName is required and must be a non-empty string for MCP extensions\",\n );\n }\n if (!inputObj.inputSchema || typeof inputObj.inputSchema !== \"object\") {\n errors.push(\"info.input.inputSchema is required and must be an object for MCP extensions\");\n }\n const transport = inputObj.transport;\n if (transport !== undefined && !VALID_MCP_TRANSPORTS.has(transport as string)) {\n errors.push(\n `info.input.transport must be one of ${[...VALID_MCP_TRANSPORTS].join(\", \")}, got \"${String(transport)}\"`,\n );\n }\n }\n\n return errors.length === 0 ? { valid: true } : { valid: false, errors };\n}\n\n/**\n * Extracts the discovery info from payment payload and requirements\n *\n * This function handles both v2 (extensions) and v1 (outputSchema) formats.\n *\n * For v2: Discovery info is in PaymentPayload.extensions (client copied it from PaymentRequired)\n * For v1: Discovery info is in PaymentRequirements.outputSchema\n *\n * V1 data is automatically transformed to v2 DiscoveryInfo format, making smart\n * assumptions about field names (queryParams/query/params for GET, bodyFields/body/data for POST, etc.)\n *\n * @param paymentPayload - The payment payload containing extensions (v2) and version info\n * @param paymentRequirements - The payment requirements (contains outputSchema for v1)\n * @param validate - Whether to validate v2 extensions before extracting (default: true)\n * @returns The discovery info in v2 format if present, or null if not discoverable\n *\n * @example\n * ```typescript\n * // V2 - extensions are in PaymentPayload\n * const info = extractDiscoveryInfo(paymentPayload, paymentRequirements);\n *\n * // V1 - discovery info is in PaymentRequirements.outputSchema\n * const info = extractDiscoveryInfo(paymentPayloadV1, paymentRequirementsV1);\n *\n * if (info) {\n * // Both v1 and v2 return the same DiscoveryInfo structure\n * console.log(\"Method:\", info.input.method);\n * }\n * ```\n */\nexport type { DiscoveredHTTPResource } from \"./http/types\";\nexport type { DiscoveredMCPResource } from \"./mcp/types\";\n\nexport type DiscoveredResource = DiscoveredHTTPResource | DiscoveredMCPResource;\n\n/**\n * Extracts discovery information from payment payload and requirements.\n * Combines resource URL, HTTP method, version, and discovery info into a single object.\n *\n * @param paymentPayload - The payment payload containing extensions and resource info\n * @param paymentRequirements - The payment requirements to validate against\n * @param validate - Whether to validate the discovery info against the schema (default: true)\n * @returns Discovered resource info with URL, method, version, discovery data, and catalog\n * extensions echo (v2: `paymentPayload.extensions`; v1: synthesized `extensions.bazaar`\n * from requirements outputSchema), or null if not found\n */\nexport function extractDiscoveryInfo(\n paymentPayload: PaymentPayload,\n paymentRequirements: PaymentRequirements | PaymentRequirementsV1,\n validate: boolean = true,\n): DiscoveredResource | null {\n let discoveryInfo: DiscoveryInfo | null = null;\n let resourceUrl: string;\n\n let routeTemplate: string | undefined;\n\n if (paymentPayload.x402Version === 2) {\n resourceUrl = paymentPayload.resource?.url ?? \"\";\n\n if (paymentPayload.extensions) {\n const bazaarExtension = paymentPayload.extensions[BAZAAR.key];\n\n if (bazaarExtension && typeof bazaarExtension === \"object\") {\n try {\n // routeTemplate uses :param syntax (e.g. \"/users/:userId\", \"/weather/:country/:city\").\n // Must start with \"/\", must not contain \"..\" or \"://\".\n // Validate before use: the client controls this field in the payment payload.\n const rawExt = bazaarExtension as Record<string, unknown>;\n const rawTemplate =\n typeof rawExt.routeTemplate === \"string\" ? rawExt.routeTemplate : undefined;\n if (isValidRouteTemplate(rawTemplate)) {\n routeTemplate = rawTemplate;\n }\n const extension = bazaarExtension as DiscoveryExtension;\n\n if (validate) {\n const result = validateDiscoveryExtension(extension);\n if (!result.valid) {\n console.warn(\n `V2 discovery extension validation failed: ${result.errors?.join(\", \")}`,\n );\n } else {\n discoveryInfo = extension.info;\n }\n } else {\n discoveryInfo = extension.info;\n }\n } catch (error) {\n console.warn(`V2 discovery extension extraction failed: ${error}`);\n }\n }\n }\n } else if (paymentPayload.x402Version === 1) {\n const requirementsV1 = paymentRequirements as PaymentRequirementsV1;\n resourceUrl = requirementsV1.resource;\n discoveryInfo = extractDiscoveryInfoV1(requirementsV1);\n } else {\n return null;\n }\n\n if (!discoveryInfo) {\n return null;\n }\n\n // Strip query params (?) and hash sections (#) for discovery cataloging\n const url = new URL(resourceUrl);\n // If a routeTemplate is present (dynamic route), use it as the canonical path\n const canonicalUrl = routeTemplate\n ? `${url.origin}${routeTemplate}`\n : `${url.origin}${url.pathname}`;\n\n // Extract description and mimeType from resource info (v2) or requirements (v1)\n let description: string | undefined;\n let mimeType: string | undefined;\n let serviceMetadata: SanitizedResourceServiceMetadata = {};\n\n if (paymentPayload.x402Version === 2) {\n description = paymentPayload.resource?.description;\n mimeType = paymentPayload.resource?.mimeType;\n // Service metadata only exists in v2; v1 had no equivalent.\n serviceMetadata = sanitizeResourceServiceMetadata(paymentPayload.resource);\n } else if (paymentPayload.x402Version === 1) {\n const requirementsV1 = paymentRequirements as PaymentRequirementsV1;\n description = requirementsV1.description;\n mimeType = requirementsV1.mimeType;\n }\n\n let extensions: Record<string, unknown> | undefined;\n if (paymentPayload.x402Version === 2) {\n extensions = paymentPayload.extensions;\n } else if (paymentPayload.x402Version === 1) {\n extensions = buildV1CatalogExtensions(paymentPayload.extensions, discoveryInfo);\n }\n\n const base = {\n resourceUrl: canonicalUrl,\n description,\n mimeType,\n ...serviceMetadata,\n x402Version: paymentPayload.x402Version,\n discoveryInfo,\n extensions,\n };\n\n if (discoveryInfo.input.type === \"mcp\") {\n // MCP routes are not parameterized; routeTemplate is not applicable.\n return { ...base, toolName: (discoveryInfo as McpDiscoveryInfo).input.toolName };\n }\n\n return { ...base, routeTemplate, method: discoveryInfo.input.method };\n}\n\n/**\n * Extracts discovery info from a v2 extension directly\n *\n * This is a lower-level function for when you already have the extension object.\n * For general use, prefer the main extractDiscoveryInfo function.\n *\n * @param extension - The discovery extension to extract info from\n * @param validate - Whether to validate before extracting (default: true)\n * @returns The discovery info if valid\n * @throws Error if validation fails and validate is true\n */\nexport function extractDiscoveryInfoFromExtension(\n extension: DiscoveryExtension,\n validate: boolean = true,\n): DiscoveryInfo {\n if (validate) {\n const result = validateDiscoveryExtension(extension);\n if (!result.valid) {\n throw new Error(\n `Invalid discovery extension: ${result.errors?.join(\", \") || \"Unknown error\"}`,\n );\n }\n }\n\n return extension.info;\n}\n\n/**\n * Validates and extracts discovery info in one step\n *\n * This is a convenience function that combines validation and extraction,\n * returning both the validation result and the info if valid.\n *\n * @param extension - The discovery extension to validate and extract\n * @returns Object containing validation result and info (if valid)\n *\n * @example\n * ```typescript\n * const extension = declareDiscoveryExtension(...);\n * const { valid, info, errors } = validateAndExtract(extension);\n *\n * if (valid && info) {\n * // Store info in Bazaar catalog\n * } else {\n * console.error(\"Validation errors:\", errors);\n * }\n * ```\n */\nexport function validateAndExtract(extension: DiscoveryExtension): {\n valid: boolean;\n info?: DiscoveryInfo;\n errors?: string[];\n} {\n const result = validateDiscoveryExtension(extension);\n\n if (result.valid) {\n return {\n valid: true,\n info: extension.info,\n };\n }\n\n return {\n valid: false,\n errors: result.errors,\n };\n}\n","/**\n * V1 Facilitator functions for extracting Bazaar discovery information\n *\n * In v1, discovery information is stored in the `outputSchema` field\n * of PaymentRequirements, which has a different structure than v2.\n *\n * This module transforms v1 data into v2 DiscoveryInfo format.\n */\n\nimport type { PaymentRequirementsV1 } from \"@x402/core/types\";\nimport type { BodyMethods, QueryParamMethods } from \"@x402/core/http\";\nimport type {\n DiscoveryExtension,\n DiscoveryInfo,\n QueryDiscoveryInfo,\n BodyDiscoveryInfo,\n} from \"../types\";\nimport { BAZAAR } from \"../types\";\n\n/**\n * Type guard to check if an object has the v1 outputSchema structure\n *\n * @param obj - The object to check\n * @returns True if object has v1 outputSchema structure\n */\nfunction hasV1OutputSchema(\n obj: unknown,\n): obj is { input: Record<string, unknown>; output?: Record<string, unknown> } {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n \"input\" in obj &&\n obj.input !== null &&\n typeof obj.input === \"object\" &&\n \"type\" in obj.input &&\n obj.input.type === \"http\" &&\n \"method\" in obj.input\n );\n}\n\n/**\n * Checks if a method is a query parameter method\n *\n * @param method - HTTP method string to check\n * @returns True if method is GET, HEAD, or DELETE\n */\nfunction isQueryMethod(method: string): method is QueryParamMethods {\n const upperMethod = method.toUpperCase();\n return upperMethod === \"GET\" || upperMethod === \"HEAD\" || upperMethod === \"DELETE\";\n}\n\n/**\n * Checks if a method is a body method\n *\n * @param method - HTTP method string to check\n * @returns True if method is POST, PUT, or PATCH\n */\nfunction isBodyMethod(method: string): method is BodyMethods {\n const upperMethod = method.toUpperCase();\n return upperMethod === \"POST\" || upperMethod === \"PUT\" || upperMethod === \"PATCH\";\n}\n\n/**\n * Extracts query parameters from v1 input, making smart assumptions\n * about common field names used in v1\n *\n * @param v1Input - V1 input object from payment requirements\n * @returns Extracted query parameters or undefined\n */\nfunction extractQueryParams(v1Input: Record<string, unknown>): Record<string, unknown> | undefined {\n // Check various common field names used in v1 (both camelCase and snake_case)\n if (v1Input.queryParams && typeof v1Input.queryParams === \"object\") {\n return v1Input.queryParams as Record<string, unknown>;\n }\n if (v1Input.query_params && typeof v1Input.query_params === \"object\") {\n return v1Input.query_params as Record<string, unknown>;\n }\n if (v1Input.query && typeof v1Input.query === \"object\") {\n return v1Input.query as Record<string, unknown>;\n }\n if (v1Input.params && typeof v1Input.params === \"object\") {\n return v1Input.params as Record<string, unknown>;\n }\n return undefined;\n}\n\n/**\n * Extracts body information from v1 input, making smart assumptions\n *\n * @param v1Input - V1 input object from payment requirements\n * @returns Object containing body content and bodyType\n */\nfunction extractBodyInfo(v1Input: Record<string, unknown>): {\n body: Record<string, unknown>;\n bodyType: \"json\" | \"form-data\" | \"text\";\n} {\n // Determine body type (check both camelCase and snake_case)\n let bodyType: \"json\" | \"form-data\" | \"text\" = \"json\";\n const bodyTypeField = v1Input.bodyType || v1Input.body_type;\n\n if (bodyTypeField && typeof bodyTypeField === \"string\") {\n const type = bodyTypeField.toLowerCase();\n if (type.includes(\"form\") || type.includes(\"multipart\")) {\n bodyType = \"form-data\";\n } else if (type.includes(\"text\") || type.includes(\"plain\")) {\n bodyType = \"text\";\n } else {\n bodyType = \"json\";\n }\n }\n\n // Extract body content from various possible fields\n // Priority order based on observed patterns in real data\n let body: Record<string, unknown> = {};\n\n if (v1Input.bodyFields && typeof v1Input.bodyFields === \"object\") {\n body = v1Input.bodyFields as Record<string, unknown>;\n } else if (\n v1Input.body_fields &&\n v1Input.body_fields !== null &&\n typeof v1Input.body_fields === \"object\"\n ) {\n body = v1Input.body_fields as Record<string, unknown>;\n } else if (v1Input.bodyParams && typeof v1Input.bodyParams === \"object\") {\n body = v1Input.bodyParams as Record<string, unknown>;\n } else if (v1Input.body && typeof v1Input.body === \"object\") {\n body = v1Input.body as Record<string, unknown>;\n } else if (v1Input.data && typeof v1Input.data === \"object\") {\n body = v1Input.data as Record<string, unknown>;\n } else if (v1Input.properties && typeof v1Input.properties === \"object\") {\n // Some endpoints have properties directly at the input level\n body = v1Input.properties as Record<string, unknown>;\n }\n\n return { body, bodyType };\n}\n\n/**\n * Extracts discovery info from v1 PaymentRequirements and transforms to v2 format\n *\n * In v1, the discovery information is stored in the `outputSchema` field,\n * which contains both input (endpoint shape) and output (response schema) information.\n *\n * This function makes smart assumptions to normalize v1 data into v2 DiscoveryInfo format:\n * - For GET/HEAD/DELETE: Looks for queryParams, query, or params fields\n * - For POST/PUT/PATCH: Looks for bodyFields, body, or data fields and normalizes bodyType\n * - Extracts optional headers if present\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns Discovery info in v2 format if present and valid, or null if not discoverable\n *\n * @example\n * ```typescript\n * const requirements: PaymentRequirementsV1 = {\n * scheme: \"exact\",\n * network: \"eip155:8453\",\n * maxAmountRequired: \"100000\",\n * resource: \"https://api.example.com/data\",\n * description: \"Get data\",\n * mimeType: \"application/json\",\n * outputSchema: {\n * input: {\n * type: \"http\",\n * method: \"GET\",\n * discoverable: true,\n * queryParams: { query: \"string\" }\n * },\n * output: { type: \"object\" }\n * },\n * payTo: \"0x...\",\n * maxTimeoutSeconds: 300,\n * asset: \"0x...\",\n * extra: {}\n * };\n *\n * const info = extractDiscoveryInfoV1(requirements);\n * if (info) {\n * console.log(\"Endpoint method:\", info.input.method);\n * }\n * ```\n */\nexport function extractDiscoveryInfoV1(\n paymentRequirements: PaymentRequirementsV1,\n): DiscoveryInfo | null {\n const { outputSchema } = paymentRequirements;\n\n // Check if outputSchema exists and has the expected structure\n if (!outputSchema || !hasV1OutputSchema(outputSchema)) {\n return null;\n }\n\n const v1Input = outputSchema.input;\n\n // Check if the endpoint is marked as discoverable\n // Default to true if not specified (for backwards compatibility)\n const isDiscoverable = v1Input.discoverable ?? true;\n\n if (!isDiscoverable) {\n return null;\n }\n\n const method = typeof v1Input.method === \"string\" ? v1Input.method.toUpperCase() : \"\";\n\n // Extract headers if present (check both camelCase and snake_case)\n const headersRaw = v1Input.headerFields || v1Input.header_fields || v1Input.headers;\n const headers =\n headersRaw && typeof headersRaw === \"object\"\n ? (headersRaw as Record<string, string>)\n : undefined;\n\n // Extract output example/schema if present\n const output = outputSchema.output\n ? {\n type: \"json\" as const,\n example: outputSchema.output,\n }\n : undefined;\n\n // Transform based on method type\n if (isQueryMethod(method)) {\n // Query parameter method (GET, HEAD, DELETE)\n const queryParams = extractQueryParams(v1Input);\n\n const discoveryInfo: QueryDiscoveryInfo = {\n input: {\n type: \"http\",\n method: method as QueryParamMethods,\n ...(queryParams ? { queryParams } : {}),\n ...(headers ? { headers } : {}),\n },\n ...(output ? { output } : {}),\n };\n\n return discoveryInfo;\n } else if (isBodyMethod(method)) {\n // Body method (POST, PUT, PATCH)\n const { body, bodyType } = extractBodyInfo(v1Input);\n const queryParams = extractQueryParams(v1Input); // Some POST requests also have query params\n\n const discoveryInfo: BodyDiscoveryInfo = {\n input: {\n type: \"http\",\n method: method as BodyMethods,\n bodyType,\n body,\n ...(queryParams ? { queryParams } : {}),\n ...(headers ? { headers } : {}),\n },\n ...(output ? { output } : {}),\n };\n\n return discoveryInfo;\n }\n\n // Unsupported method, return null\n return null;\n}\n\n/**\n * Checks if v1 PaymentRequirements contains discoverable information\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns True if the requirements contain valid discovery info\n *\n * @example\n * ```typescript\n * if (isDiscoverableV1(requirements)) {\n * const info = extractDiscoveryInfoV1(requirements);\n * // Catalog info in Bazaar\n * }\n * ```\n */\nexport function isDiscoverableV1(paymentRequirements: PaymentRequirementsV1): boolean {\n return extractDiscoveryInfoV1(paymentRequirements) !== null;\n}\n\n/**\n * Extracts resource metadata from v1 PaymentRequirements\n *\n * In v1, resource information is embedded directly in the payment requirements\n * rather than in a separate resource object.\n *\n * @param paymentRequirements - V1 payment requirements\n * @returns Resource metadata\n *\n * @example\n * ```typescript\n * const metadata = extractResourceMetadataV1(requirements);\n * console.log(\"Resource URL:\", metadata.url);\n * console.log(\"Description:\", metadata.description);\n * ```\n */\nexport function extractResourceMetadataV1(paymentRequirements: PaymentRequirementsV1): {\n url: string;\n description: string;\n mimeType: string;\n} {\n return {\n url: paymentRequirements.resource,\n description: paymentRequirements.description,\n mimeType: paymentRequirements.mimeType,\n };\n}\n\n/**\n * Builds a v2 bazaar extension from extracted v1 discovery info.\n *\n * V1 had no formal schema validation, so the synthesized schema is permissive.\n *\n * @param discoveryInfo - Discovery info extracted from v1 payment requirements\n * @returns A bazaar extension suitable for catalog echo\n */\nexport function buildBazaarExtensionFromDiscoveryInfo(\n discoveryInfo: DiscoveryInfo,\n): DiscoveryExtension {\n // V1 had no formal schema; use a permissive envelope for catalog echo only.\n return {\n info: discoveryInfo,\n schema: {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n type: \"object\",\n properties: {\n input: { type: \"object\" },\n output: { type: \"object\" },\n },\n required: [\"input\"],\n },\n } as DiscoveryExtension;\n}\n\n/**\n * Normalizes v1 catalog extension payloads to v2 bazaar format.\n *\n * Preserves non-bazaar extensions from the payment payload. Replaces legacy\n * `outputSchema` entries with a synthesized `bazaar` extension.\n *\n * @param existingExtensions - Extension payloads from the v1 payment payload, if any\n * @param discoveryInfo - Discovery info extracted from v1 payment requirements\n * @returns Normalized extension payloads with a `bazaar` entry\n */\nexport function buildV1CatalogExtensions(\n existingExtensions: Record<string, unknown> | undefined,\n discoveryInfo: DiscoveryInfo,\n): Record<string, unknown> {\n if (existingExtensions?.[BAZAAR.key]) {\n return existingExtensions;\n }\n\n const extensions: Record<string, unknown> = existingExtensions ? { ...existingExtensions } : {};\n delete extensions.outputSchema;\n extensions[BAZAAR.key] = buildBazaarExtensionFromDiscoveryInfo(discoveryInfo);\n return extensions;\n}\n","/**\n * Shared startup-time validation utilities for bazaar extensions in route configs.\n *\n * Used by middleware packages (Express, Hono, Next) to validate bazaar extensions\n * at server startup without duplicating the iteration and warning logic.\n */\n\nimport type { RoutesConfig } from \"@x402/core/server\";\nimport type { DiscoveryExtension } from \"./types\";\nimport { validateDiscoveryExtension, validateDiscoveryExtensionSpec } from \"./facilitator\";\n\nexport { checkIfBazaarNeeded } from \"@x402/core/server\";\n\nconst HTTP_VERB_RE = /^(GET|POST|PUT|PATCH|DELETE|HEAD)\\b/i;\n\n/**\n * Inject a synthetic method into a pre-enrichment extension so the schema's\n * required:[\"method\"] check doesn't produce a false-positive warning at startup.\n * Priority: (1) route pattern verb (e.g. \"GET /api\"), (2) body vs query inference.\n * Returns the same object unchanged if method is already present.\n *\n * @param ext - The raw bazaar extension object\n * @param pattern - The route pattern key (e.g. \"GET /api\" or \"*\")\n * @returns The extension with a synthetic method injected into info.input if needed\n */\nfunction withSyntheticMethod(\n ext: Record<string, unknown>,\n pattern: string,\n): Record<string, unknown> {\n const info = ext.info as Record<string, unknown> | undefined;\n const input = info?.input as Record<string, unknown> | undefined;\n if (!input || (typeof input.method === \"string\" && input.method)) {\n return ext;\n }\n const verbMatch = pattern.match(HTTP_VERB_RE);\n const method = verbMatch\n ? verbMatch[1].toUpperCase()\n : input.body !== undefined || input.bodyType !== undefined\n ? \"POST\"\n : \"GET\";\n return { ...ext, info: { ...info, input: { ...input, method } } };\n}\n\n/**\n * Validate bazaar extensions on all routes using JSON-schema validation.\n * Emits console warnings for invalid extensions but does not throw.\n *\n * @param routes - Route configuration to scan for bazaar extensions\n */\nexport function validateBazaarRouteExtensions(routes: RoutesConfig): void {\n const entries: [string, { extensions?: Record<string, unknown> }][] =\n \"accepts\" in routes ? [[\"*\", routes]] : Object.entries(routes);\n\n for (const [pattern, config] of entries) {\n const bazaarExt = config.extensions?.[\"bazaar\"];\n if (!bazaarExt) continue;\n if (\n typeof bazaarExt === \"object\" &&\n bazaarExt !== null &&\n \"info\" in (bazaarExt as Record<string, unknown>) &&\n \"schema\" in (bazaarExt as Record<string, unknown>)\n ) {\n const specResult = validateDiscoveryExtensionSpec(bazaarExt as Record<string, unknown>);\n if (!specResult.valid) {\n console.warn(\n `x402: Route \"${pattern}\" has an invalid bazaar extension: ${specResult.errors?.join(\", \")}`,\n );\n continue;\n }\n const extForSchema = withSyntheticMethod(bazaarExt as Record<string, unknown>, pattern);\n const schemaResult = validateDiscoveryExtension(\n extForSchema as unknown as DiscoveryExtension,\n );\n if (!schemaResult.valid) {\n console.warn(\n `x402: Route \"${pattern}\" has an invalid bazaar extension: ${schemaResult.errors?.join(\", \")}`,\n );\n }\n } else {\n console.warn(\n `x402: Route \"${pattern}\" declares a bazaar extension but it is malformed ` +\n `(expected an object with \"info\" and \"schema\" fields)`,\n );\n }\n }\n}\n","/**\n * Client extensions for querying Bazaar discovery resources\n */\n\nimport { HTTPFacilitatorClient } from \"@x402/core/http\";\nimport type { PaymentRequirements } from \"@x402/core/types\";\nimport { WithExtensions } from \"../types\";\n\n/**\n * Parameters for listing discovery resources.\n * All parameters are optional and used for filtering/pagination.\n */\nexport interface ListDiscoveryResourcesParams {\n /**\n * Filter by protocol type (e.g., \"http\", \"mcp\").\n */\n type?: string;\n\n /**\n * Filter by payment recipient address.\n */\n payTo?: string;\n\n /**\n * Filter by payment scheme (e.g., \"exact\").\n */\n scheme?: string;\n\n /**\n * Filter by payment network (e.g., \"eip155:8453\").\n */\n network?: string;\n\n /**\n * Filter by extension key present on the discovered resource.\n */\n extensions?: string;\n\n /**\n * The number of discovered x402 resources to return per page.\n */\n limit?: number;\n\n /**\n * The offset of the first discovered x402 resource to return.\n */\n offset?: number;\n}\n\n/**\n * Parameters for searching discovery resources.\n */\nexport interface SearchDiscoveryResourcesParams {\n /**\n * Natural-language search query.\n */\n query: string;\n\n /**\n * Filter by protocol type (e.g., \"http\", \"mcp\").\n */\n type?: string;\n\n /**\n * Filter by payment recipient address.\n */\n payTo?: string;\n\n /**\n * Filter by payment scheme (e.g., \"exact\").\n */\n scheme?: string;\n\n /**\n * Filter by payment network (e.g., \"eip155:8453\").\n */\n network?: string;\n\n /**\n * Filter by extension key present on the discovered resource.\n */\n extensions?: string;\n\n /**\n * Advisory maximum number of results. The server may return fewer or ignore this.\n */\n limit?: number;\n\n /**\n * Advisory continuation cursor from a previous response. The server may ignore this.\n */\n cursor?: string;\n}\n\n/**\n * A discovered x402 resource from the bazaar.\n */\nexport interface DiscoveryResource {\n /** The URL or identifier of the discovered resource */\n resource: string;\n /** The protocol type of the resource (e.g., \"http\") */\n type: string;\n /** The x402 protocol version supported by this resource */\n x402Version: number;\n /** Array of accepted payment methods for this resource */\n accepts: PaymentRequirements[];\n /** ISO 8601 timestamp of when the resource was last updated */\n lastUpdated: string;\n /** Human-readable description of the resource */\n description?: string;\n /** MIME type of the resource response */\n mimeType?: string;\n /** Human-readable name for the service hosting the resource */\n serviceName?: string;\n /** Short topical tags for discovery search */\n tags?: string[];\n /** Absolute http(s) URL to a service icon */\n iconUrl?: string;\n /** Extension payloads echoed from discovery (e.g. bazaar info/schema) */\n extensions?: Record<string, unknown>;\n}\n\n/**\n * Response from listing discovery resources.\n */\nexport interface DiscoveryResourcesResponse {\n /** The x402 protocol version of this response */\n x402Version: number;\n /** The list of discovered resources */\n items: DiscoveryResource[];\n /** Pagination information for the response */\n pagination: {\n /** Maximum number of results returned */\n limit: number;\n /** Number of results skipped */\n offset: number;\n /** Total count of resources matching the query */\n total: number;\n };\n}\n\n/**\n * Response from searching discovery resources.\n */\nexport interface SearchDiscoveryResourcesResponse {\n /** The x402 protocol version of this response */\n x402Version: number;\n /** The list of matching discovered resources */\n resources: DiscoveryResource[];\n /** Whether additional matches were truncated by facilitator */\n partialResults?: boolean;\n /** Optional pagination details when a paginated response is returned */\n pagination?: {\n /** Number of results in this page */\n limit: number;\n /** Continuation cursor for the next page; may be null */\n cursor: string | null;\n } | null;\n}\n\n/**\n * Bazaar client extension interface providing discovery query functionality.\n */\nexport interface BazaarClientExtension {\n bazaar: {\n /**\n * List x402 discovery resources from the bazaar.\n *\n * @param params - Optional filtering and pagination parameters\n * @returns A promise resolving to the discovery resources response\n */\n listResources(params?: ListDiscoveryResourcesParams): Promise<DiscoveryResourcesResponse>;\n\n /**\n * Search x402 discovery resources from the bazaar using a natural-language query.\n *\n * Pagination is optional: facilitators may ignore `limit` and `cursor`, or include\n * `response.pagination` when pagination is used.\n *\n * @param params - Search parameters including the required query string\n * @returns A promise resolving to the search response\n */\n search(params: SearchDiscoveryResourcesParams): Promise<SearchDiscoveryResourcesResponse>;\n };\n}\n\n/**\n * Extends a facilitator client with Bazaar discovery query functionality.\n * Preserves and merges with any existing extensions from prior chaining.\n *\n * @param client - The facilitator client to extend\n * @returns The client extended with bazaar discovery capabilities\n *\n * @example\n * ```ts\n * // Basic usage\n * const client = withBazaar(new HTTPFacilitatorClient());\n * const resources = await client.extensions.bazaar.listResources({ type: \"http\" });\n *\n * // Search\n * const results = await client.extensions.bazaar.search({ query: \"weather APIs\" });\n *\n * // Chaining with other extensions\n * const client = withBazaar(withOtherExtension(new HTTPFacilitatorClient()));\n * await client.extensions.other.someMethod();\n * await client.extensions.bazaar.listResources();\n * ```\n */\nexport function withBazaar<T extends HTTPFacilitatorClient>(\n client: T,\n): WithExtensions<T, BazaarClientExtension> {\n // Preserve any existing extensions from prior chaining\n const existingExtensions =\n (client as T & { extensions?: Record<string, unknown> }).extensions ?? {};\n\n const extended = client as WithExtensions<T, BazaarClientExtension>;\n\n extended.extensions = {\n ...existingExtensions,\n bazaar: {\n async listResources(\n params?: ListDiscoveryResourcesParams,\n ): Promise<DiscoveryResourcesResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n const authHeaders = await client.createAuthHeaders(\"bazaar\");\n headers = { ...headers, ...authHeaders.headers };\n\n const queryParams = new URLSearchParams();\n if (params?.type !== undefined) {\n queryParams.set(\"type\", params.type);\n }\n if (params?.payTo !== undefined) {\n queryParams.set(\"payTo\", params.payTo);\n }\n if (params?.scheme !== undefined) {\n queryParams.set(\"scheme\", params.scheme);\n }\n if (params?.network !== undefined) {\n queryParams.set(\"network\", params.network);\n }\n if (params?.extensions !== undefined) {\n queryParams.set(\"extensions\", params.extensions);\n }\n if (params?.limit !== undefined) {\n queryParams.set(\"limit\", params.limit.toString());\n }\n if (params?.offset !== undefined) {\n queryParams.set(\"offset\", params.offset.toString());\n }\n\n const queryString = queryParams.toString();\n const endpoint = `${client.url}/discovery/resources${queryString ? `?${queryString}` : \"\"}`;\n\n const response = await fetch(endpoint, {\n method: \"GET\",\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n throw new Error(\n `Facilitator listDiscoveryResources failed (${response.status}): ${errorText}`,\n );\n }\n\n return (await response.json()) as DiscoveryResourcesResponse;\n },\n\n async search(\n params: SearchDiscoveryResourcesParams,\n ): Promise<SearchDiscoveryResourcesResponse> {\n let headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n const authHeaders = await client.createAuthHeaders(\"bazaar\");\n headers = { ...headers, ...authHeaders.headers };\n\n const queryParams = new URLSearchParams();\n queryParams.set(\"query\", params.query);\n if (params.type !== undefined) {\n queryParams.set(\"type\", params.type);\n }\n if (params.payTo !== undefined) {\n queryParams.set(\"payTo\", params.payTo);\n }\n if (params.scheme !== undefined) {\n queryParams.set(\"scheme\", params.scheme);\n }\n if (params.network !== undefined) {\n queryParams.set(\"network\", params.network);\n }\n if (params.extensions !== undefined) {\n queryParams.set(\"extensions\", params.extensions);\n }\n if (params.limit !== undefined) {\n queryParams.set(\"limit\", params.limit.toString());\n }\n if (params.cursor !== undefined) {\n queryParams.set(\"cursor\", params.cursor);\n }\n\n const endpoint = `${client.url}/discovery/search?${queryParams.toString()}`;\n\n const response = await fetch(endpoint, {\n method: \"GET\",\n headers,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => response.statusText);\n throw new Error(\n `Facilitator searchDiscoveryResources failed (${response.status}): ${errorText}`,\n );\n }\n\n return (await response.json()) as SearchDiscoveryResourcesResponse;\n },\n },\n } as WithExtensions<T, BazaarClientExtension>[\"extensions\"];\n\n return extended;\n}\n","import type { PaymentMode } from './policy';\nimport { CliError } from './errors';\nimport { toMoney } from './money';\nimport { promptYesNo } from './prompt';\nimport type { SpendAuthorizer } from './wallet';\nimport type { CommandContext } from '../context';\n\n/**\n * The one money gate `buy` and `pay` share: policy authorization, the confirm\n * ceremony, and the refusal shapes. Both verbs run EXACTLY this sequence\n * between seeing a price and building a signature, so the two cannot drift on\n * what `--yes` clears (the confirm only), what a deny looks like, or when a\n * reservation is released. The caller still owns everything around it: the\n * challenge it priced, the payment build, and settling the reservation after a\n * failure: releasing only while no signature has left the process, committing\n * once one has (pay.ts), because a transmitted authorization can still settle.\n */\n\nexport interface SpendGateInput {\n ctx: CommandContext;\n mode: PaymentMode;\n authorizer: SpendAuthorizer;\n amountAtomic: bigint;\n /** The policy's creator identity (a handle for buy, the target host for pay). */\n creator: string;\n maxPriceAtomic?: bigint;\n /** The same-turn duplicate guard's identity for this request; see SpendRequest. */\n requestKey?: string;\n /** --yes: bypasses the interactive confirm only, never a cap or a deny. */\n yes: boolean;\n /** Interactive-confirm seam; defaults to a TTY y/n prompt. */\n confirm?: (prompt: string) => Promise<boolean>;\n /**\n * Who the human is told they are paying, PRE-SANITIZED by the caller (it\n * knows which parts are external input). Rendered before the price so escape\n * sequences could never repaint the amount being approved.\n */\n payeeLabel: string;\n /** \"Add the creator\" (buy) vs \"Add this host\" (pay) in the allowlist fix. */\n allowlistSubject: string;\n /** \"Purchase not confirmed.\" (buy) vs \"Payment not confirmed.\" (pay). */\n notConfirmedMessage: string;\n}\n\n/** Runs the gate; returns the reservation to commit or release (undefined\n * mirrors the authorizer's own optionality, same as before the extraction).\n * Throws POLICY_REFUSED (deny, or confirm declined), releasing first. */\nexport async function gateSpend(input: SpendGateInput): Promise<string | undefined> {\n const { authorizer, amountAtomic } = input;\n const authorization = await authorizer.authorize({\n mode: input.mode,\n amountAtomic,\n creator: input.creator,\n ...(input.maxPriceAtomic !== undefined ? { maxPriceAtomic: input.maxPriceAtomic } : {}),\n ...(input.requestKey !== undefined ? { requestKey: input.requestKey } : {}),\n });\n if (authorization.decision === 'deny') {\n throw new CliError('POLICY_REFUSED', authorization.message, {\n fix: policyFix(authorization.reason, input.allowlistSubject),\n details: { reason: authorization.reason, amountAtomic: amountAtomic.toString() },\n });\n }\n const reservationId = authorization.reservationId;\n if (authorization.decision === 'confirm') {\n let approved: boolean;\n try {\n approved = await confirmSpend(input);\n } catch (err) {\n await authorizer.release(reservationId);\n throw err;\n }\n if (!approved) {\n await authorizer.release(reservationId);\n throw new CliError('POLICY_REFUSED', input.notConfirmedMessage, {\n fix: 'Obtain explicit user consent for this quoted payment, then re-run with --yes or confirm interactively. Manual pay is never an autonomous workaround for a router refusal.',\n details: { reason: authorization.reason, amountAtomic: amountAtomic.toString() },\n });\n }\n }\n return reservationId;\n}\n\n/** What follows a refusal, by its policy reason. */\nexport function policyFix(reason: string, allowlistSubject: string): string {\n switch (reason) {\n case 'price_cap_exceeded':\n return 'Raise --max-price if this price is acceptable.';\n case 'not_allowlisted':\n return `Add ${allowlistSubject} to allowlistCreators, or clear the allowlist.`;\n case 'session_budget_exceeded':\n return \"Today's automatic budget is spent; it comes back as the rolling 24 hours pass. Nothing more is paid without the user's yes.\";\n case 'duplicate_in_flight':\n return 'Let the in-flight request finish and read its result; retrying the same request does not renew authorization.';\n default:\n return \"This is over what this machine pays without asking, so it is not paid without the user's yes.\";\n }\n}\n\nasync function confirmSpend(input: SpendGateInput): Promise<boolean> {\n if (input.yes) return true;\n const prompt = `Pay ${toMoney(input.amountAtomic.toString()).usd} USD to ${input.payeeLabel}? [y/N] `;\n if (input.confirm !== undefined) return input.confirm(prompt);\n if (!input.ctx.io.isTTY) return false; // non-interactive without --yes: refuse (exit 3)\n // The real prompt reads stdin, so stdin must be interactive too: at EOF the\n // question could never be answered and the process would exit with no answer.\n if (!process.stdin.isTTY) return false;\n return promptYesNo(prompt); // default-no: only an explicit y/yes approves\n}\n","import { randomBytes } from 'node:crypto';\nimport { constants } from 'node:fs';\nimport { open, opendir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { writeFileAtomic } from './atomic-json';\nimport { withFileLock } from './lock';\nimport { quotesDir } from './paths';\n\n/**\n * A SPEND THE USER IS ASKED ABOUT BEFORE IT IS MADE. A router call whose plan\n * is over the automatic limits pays nothing: on a host that asks the user\n * before every `approve` call, its exact plan is kept here as a quote (what\n * it buys, each payment, the total, and the call to run) until it runs or\n * expires. One file per quote, `~/.tenjin/quotes/<id>.json`, written 0600\n * through an atomic rename and read with O_NOFOLLOW, as a job's record is.\n *\n * NOTHING IN THE FILE IS AN APPROVAL. The user's yes is the host's own\n * permission prompt on the `approve` call; a quote only says what that call\n * runs. A QUOTE RUNS ONCE: `useQuote` marks it used under its lock before\n * anything is signed, so two calls racing on one quote pay once between them;\n * only a run whose every payment was refused as short of funds reopens it\n * (`spend-plan.ts`).\n * One past its ten minutes is refused, and pruned. What it runs (`call`) is\n * the router's to read; this file keeps the money.\n */\n\n/** How long a quote waits for the user's yes. */\nconst QUOTE_TTL_MS = 10 * 60_000;\n/** A quote holds every spec it runs: a few of them, and their inputs. */\nconst MAX_QUOTE_BYTES = 512 * 1024;\nconst QUOTE_ID = /^q_[A-Za-z0-9_-]{12}$/;\n\nconst Iso = z.string().max(40);\nconst Digits = z.string().regex(/^\\d+$/);\n\nconst QuoteSchema = z.strictObject({\n version: z.literal(1),\n id: z.string().regex(QUOTE_ID),\n createdAt: Iso,\n expiresAt: Iso,\n /** What the payments buy, as the user is asked about it. */\n what: z.string().min(1).max(400),\n /** The one sentence the agent repeats and the user answers. */\n sentence: z.string().min(1).max(800),\n totalAtomic: Digits,\n payments: z\n .array(z.strictObject({ amountAtomic: Digits, creator: z.string().min(1).max(300) }))\n .min(1)\n .max(8),\n /** The call this quote runs, exactly: the router's own shape. */\n call: z.unknown(),\n /** It ran: nothing more is paid on it. */\n usedAt: Iso.optional(),\n});\nexport type Quote = z.infer<typeof QuoteSchema>;\n\nexport type QuoteRefusal = 'missing' | 'expired' | 'used';\n\nexport function isQuoteId(id: string): boolean {\n return QUOTE_ID.test(id);\n}\n\nfunction quotePath(dataDir: string, id: string): string {\n return join(quotesDir(dataDir), `${id}.json`);\n}\n\n/** Keep a plan for the user's yes. Throws when it cannot be written: a quote\n * nobody can run is not one to hand the agent. */\nexport async function createQuote(\n dataDir: string,\n plan: {\n what: string;\n sentence: string;\n payments: readonly { amountAtomic: bigint; creator: string }[];\n call: unknown;\n },\n now: () => number = Date.now,\n): Promise<Quote> {\n const at = now();\n const quote: Quote = {\n version: 1,\n id: `q_${randomBytes(9).toString('base64url')}`,\n createdAt: new Date(at).toISOString(),\n expiresAt: new Date(at + QUOTE_TTL_MS).toISOString(),\n what: plan.what.slice(0, 400),\n sentence: plan.sentence.slice(0, 800),\n totalAtomic: plan.payments.reduce((sum, payment) => sum + payment.amountAtomic, 0n).toString(),\n payments: plan.payments.map((payment) => ({\n amountAtomic: payment.amountAtomic.toString(),\n creator: payment.creator,\n })),\n call: plan.call,\n };\n await writeQuote(dataDir, quote);\n void pruneQuotes(dataDir, at);\n return quote;\n}\n\nasync function writeQuote(dataDir: string, quote: Quote): Promise<void> {\n await writeFileAtomic(quotePath(dataDir, quote.id), JSON.stringify(quote), {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n/** The quote kept under this id, or null: none, damaged, or a symlink. */\nexport async function readQuote(dataDir: string, id: string): Promise<Quote | null> {\n if (!isQuoteId(id)) return null;\n const file = await open(quotePath(dataDir, id), constants.O_RDONLY | constants.O_NOFOLLOW).catch(\n () => undefined,\n );\n if (file === undefined) return null;\n try {\n const stat = await file.stat();\n if (!stat.isFile() || stat.size > MAX_QUOTE_BYTES) return null;\n const parsed = QuoteSchema.safeParse(JSON.parse(await file.readFile('utf8')));\n return parsed.success && parsed.data.id === id ? parsed.data : null;\n } catch {\n return null;\n } finally {\n await file.close().catch(() => undefined);\n }\n}\n\n/** Why a quote can no longer run, or null while it can. */\nexport function quoteClosed(quote: Quote, now: number): Exclude<QuoteRefusal, 'missing'> | null {\n if (quote.usedAt !== undefined) return 'used';\n return Date.parse(quote.expiresAt) <= now ? 'expired' : null;\n}\n\n/**\n * CHANGE ONE QUOTE under its lock: `change` sees it as it is on disk and\n * returns the quote to write, or a refusal that leaves it as it is.\n */\nasync function changeQuote(\n dataDir: string,\n id: string,\n change: (quote: Quote) => Quote | QuoteRefusal | Promise<Quote | QuoteRefusal>,\n): Promise<{ quote: Quote } | { refused: QuoteRefusal }> {\n if (!isQuoteId(id)) return { refused: 'missing' };\n return withFileLock(\n `${quotePath(dataDir, id)}.lock`,\n async () => {\n const current = await readQuote(dataDir, id);\n if (current === null) return { refused: 'missing' as const };\n const next = await change(current);\n if (typeof next === 'string') return { refused: next };\n await writeQuote(dataDir, next);\n return { quote: next };\n },\n { timeoutMs: 30_000 },\n );\n}\n\n/** USE A QUOTE UP: marked used before anything is signed, so it pays once\n * whatever happens next, unless {@link reopenQuote} reopens it. */\nexport function useQuote(\n dataDir: string,\n id: string,\n now: () => number = Date.now,\n): Promise<{ quote: Quote } | { refused: QuoteRefusal }> {\n return changeQuote(dataDir, id, (quote) => {\n const at = now();\n return quoteClosed(quote, at) ?? { ...quote, usedAt: new Date(at).toISOString() };\n });\n}\n\n/** Reopen after its short run's claims are released, under the quote lock.\n * Another approval cannot use the quote while cleanup is still in flight. */\nexport function reopenQuote(\n dataDir: string,\n id: string,\n releaseClaims: () => Promise<void>,\n now: () => number = Date.now,\n): Promise<{ quote: Quote } | { refused: QuoteRefusal }> {\n return changeQuote(dataDir, id, async (quote) => {\n if (Date.parse(quote.expiresAt) <= now()) return 'expired';\n await releaseClaims();\n const open: Quote = { ...quote };\n delete open.usedAt;\n return open;\n });\n}\n\n/** Drop every quote past its expiry, and anything unreadable past a day.\n * Housekeeping only: never throws. */\nexport async function pruneQuotes(dataDir: string, now: number): Promise<void> {\n try {\n const dir = quotesDir(dataDir);\n for await (const entry of await opendir(dir)) {\n const id = entry.name.replace(/\\.json$/, '');\n if (!entry.isFile() || !entry.name.endsWith('.json') || !isQuoteId(id)) continue;\n const quote = await readQuote(dataDir, id);\n const stale =\n quote !== null\n ? Date.parse(quote.expiresAt) < now\n : await open(join(dir, entry.name), constants.O_RDONLY | constants.O_NOFOLLOW)\n .then(async (file) => {\n try {\n return now - (await file.stat()).mtimeMs > 24 * 60 * 60_000;\n } finally {\n await file.close().catch(() => undefined);\n }\n })\n .catch(() => false);\n if (stale) await rm(join(dir, entry.name), { force: true }).catch(() => undefined);\n }\n } catch {\n // Housekeeping only.\n }\n}\n","import { evaluatePlan, type SpendPolicy } from './policy';\nimport { readSpendSummary, spentOf } from './spend-ledger';\nimport {\n quoteClosed,\n readQuote,\n reopenQuote,\n useQuote,\n type Quote,\n type QuoteRefusal,\n} from './spend-quotes';\n\n/**\n * ONE SPEND RULE FOR EVERY ROUTER CALL. A call that pays first lists the\n * payments it will make at their quoted amounts: its plan. The plan's total\n * meets the automatic limits once, before anything is signed: `maxAutoSpend`\n * for the whole call and the rolling day's `sessionBudget`. Under them it\n * runs. Over them nothing is paid; on a host that asks\n * the user, the router keeps the plan as a quote for their yes\n * (`spend-quotes.ts`), and a quote they approved may pass both limits. No\n * balance is read: the facilitator verifies funds when each payment settles,\n * on its own, so a plan of several payments can settle some and not others.\n *\n * A ROUTER PAYMENT IS SIGNED ONLY AGAINST A PLAN. Admitting a plan here, or\n * using up an approved quote, is the only way to get the slots `runPay`\n * accepts in router mode: one per payment, for at most its planned amount,\n * each spent once. A payment no plan admitted is refused at signing, so a\n * feature that forgets to plan cannot pay.\n */\n\nexport interface PlannedPayment {\n amountAtomic: bigint;\n /** The payee's host: the policy's creator identity. */\n creator: string;\n}\n\n/** What one payment of an admitted plan may sign. */\nexport interface PlanSlot {\n /** The most it may sign: its planned amount. */\n readonly amountAtomic: bigint;\n /** A person said yes to the plan, so it is theirs, not automatic. */\n readonly approved: boolean;\n}\n\nconst minted = new WeakSet<PlanSlot>();\nconst spent = new WeakSet<PlanSlot>();\nconst shortOfFunds = new WeakSet<PlanSlot>();\n\nfunction mint(amountAtomic: bigint, approved: boolean): PlanSlot {\n const slot: PlanSlot = Object.freeze({ amountAtomic, approved });\n minted.add(slot);\n return slot;\n}\n\n/** Why a slot cannot pay this amount: not admitted here, already spent, or\n * less than the live price. */\nexport type SlotRefusal = 'unplanned' | 'spent' | 'above_plan';\n\n/** Spend a slot on a payment of `amountAtomic`, or say why it cannot be. */\nexport function spendSlot(slot: unknown, amountAtomic: bigint): SlotRefusal | null {\n if (typeof slot !== 'object' || slot === null || !minted.has(slot as PlanSlot)) {\n return 'unplanned';\n }\n const held = slot as PlanSlot;\n if (spent.has(held)) return 'spent';\n if (amountAtomic > held.amountAtomic) return 'above_plan';\n spent.add(held);\n return null;\n}\n\n/** The payment signed on this spent slot was refused as short of funds\n * (`paymentShortOfFunds`). Anything else is ignored. */\nexport function markShortOfFunds(slot: PlanSlot | undefined): void {\n if (slot !== undefined && minted.has(slot) && spent.has(slot)) shortOfFunds.add(slot);\n}\n\n/** The payment signed on this slot was refused as short of funds. */\nexport function wasShortOfFunds(slot: PlanSlot): boolean {\n return shortOfFunds.has(slot);\n}\n\n/** A plan over the automatic limits: what a person is asked about. */\nexport interface PlanOver {\n reason: 'above_auto_spend' | 'session_budget_exceeded';\n totalAtomic: bigint;\n maxAutoSpendAtomic: bigint;\n /** What the rolling day's budget has left; null with no budget. */\n budgetLeftAtomic: bigint | null;\n}\n\nexport type PlanAdmission =\n | { admitted: PlanSlot[] }\n | { over: PlanOver }\n /** A payee outside `allowlistCreators`: no one's yes clears that. */\n | { refused: { message: string } };\n\n/** Admit a plan against local spend policy, without a balance preflight. */\nexport async function admitPlan(\n payments: readonly PlannedPayment[],\n opts: {\n dataDir: string;\n policy: SpendPolicy;\n now?: () => number;\n },\n): Promise<PlanAdmission> {\n const totalAtomic = payments.reduce((sum, payment) => sum + payment.amountAtomic, 0n);\n const ledger = await readSpendSummary(opts.dataDir, {\n ...(opts.now !== undefined ? { now: opts.now } : {}),\n });\n const spentAtomic = ledger === null ? 0n : spentOf(ledger);\n const evaluation = evaluatePlan(opts.policy, payments, spentAtomic);\n if (evaluation.reason === 'not_allowlisted') return { refused: { message: evaluation.message } };\n const over = evaluation.decision !== 'allow';\n if (over) {\n const budget = opts.policy.sessionBudgetAtomic;\n return {\n over: {\n reason:\n evaluation.reason === 'session_budget_exceeded'\n ? 'session_budget_exceeded'\n : 'above_auto_spend',\n totalAtomic,\n maxAutoSpendAtomic: opts.policy.maxAutoSpendAtomic,\n budgetLeftAtomic: budget === null ? null : budget > spentAtomic ? budget - spentAtomic : 0n,\n },\n };\n }\n return { admitted: payments.map((payment) => mint(payment.amountAtomic, false)) };\n}\n\n/**\n * RUN A QUOTE A PERSON APPROVED: its plan's slots, one per quoted payment,\n * minted approved, and the quote used up so it pays once. The caller is the\n * `approve` call, which reaches this process only after the host's own\n * prompt put it to a person; nothing on disk says anyone approved anything.\n * The caller opens the wallet first, so a wallet that will not open leaves\n * the quote open. Once used, a quote stays consumed when a payment fails,\n * except a short wallet's: see {@link reopenShortQuote}.\n */\nexport async function admitQuote(\n dataDir: string,\n id: string,\n opts: { now?: () => number } = {},\n): Promise<{ admitted: PlanSlot[]; quote: Quote } | { refused: QuoteRefusal }> {\n const now = opts.now ?? Date.now;\n const kept = await readQuote(dataDir, id);\n if (kept === null) return { refused: 'missing' };\n const closed = quoteClosed(kept, now());\n if (closed !== null) return { refused: closed };\n const used = await useQuote(dataDir, id, now);\n if ('refused' in used) return used;\n return {\n quote: used.quote,\n admitted: used.quote.payments.map((payment) => mint(BigInt(payment.amountAtomic), true)),\n };\n}\n\n/**\n * A SHORT WALLET LEAVES AN APPROVED QUOTE OPEN, for the person to fund the\n * wallet and say yes to the same quote again: reopened when every payment its\n * run signed was refused as short of funds, and at least one was signed. A\n * payment that delivered, or failed any other way, keeps the quote used, so a\n * plan is never run twice over a payment that may have settled. Each refused\n * authorization stays counted until reconcile proves it unused. A seller that\n * claims low funds falsely gains nothing a person did not agree to: the\n * quote's next run is another `approve` call, which the host puts to them.\n * The quote stays used until its claims are released under the quote lock.\n * True when it reopened.\n */\nexport async function reopenShortQuote(\n dataDir: string,\n id: string,\n slots: readonly PlanSlot[],\n opts: { now?: () => number; releaseClaims: () => Promise<void> },\n): Promise<boolean> {\n const signed = slots.filter((slot) => spent.has(slot));\n if (signed.length === 0 || !signed.every((slot) => shortOfFunds.has(slot))) return false;\n return 'quote' in (await reopenQuote(dataDir, id, opts.releaseClaims, opts.now ?? Date.now));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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A,EACtF;AACA,SAAO,KAAK;AACd;","names":["client","join","join","open","said","provider","host","refusal","reportedTxHash","settlement","charged","reported","known"]}
|