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,3348 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
LOW_FUNDS_TAIL,
|
|
4
|
+
admitPlan,
|
|
5
|
+
admitQuote,
|
|
6
|
+
createQuote,
|
|
7
|
+
isLowFundsRefusal,
|
|
8
|
+
policyFix,
|
|
9
|
+
quoteClosed,
|
|
10
|
+
quoteRouterCall,
|
|
11
|
+
readQuote,
|
|
12
|
+
reopenShortQuote,
|
|
13
|
+
runPay,
|
|
14
|
+
sellerLine,
|
|
15
|
+
settlementTx,
|
|
16
|
+
signInForPoll,
|
|
17
|
+
signInOnlyHeader,
|
|
18
|
+
wasShortOfFunds
|
|
19
|
+
} from "./chunk-ODRPASFP.js";
|
|
20
|
+
import {
|
|
21
|
+
MAX_MEDIA_BYTES,
|
|
22
|
+
MAX_MEDIA_FILES,
|
|
23
|
+
appendPaidRecord,
|
|
24
|
+
maskDeep,
|
|
25
|
+
mediaUrlsIn,
|
|
26
|
+
payerOf,
|
|
27
|
+
pinnedHttp,
|
|
28
|
+
reconcilePayments,
|
|
29
|
+
recordAccountRow,
|
|
30
|
+
recordedSent,
|
|
31
|
+
saveMedia,
|
|
32
|
+
updatePaidRecord,
|
|
33
|
+
writeNewFile
|
|
34
|
+
} from "./chunk-MAHNZA6C.js";
|
|
35
|
+
import {
|
|
36
|
+
KeptChoicesSchema,
|
|
37
|
+
KeptSpecSchema,
|
|
38
|
+
UNREADABLE,
|
|
39
|
+
claimSpecPayment,
|
|
40
|
+
markTaken,
|
|
41
|
+
readChoices,
|
|
42
|
+
readKeptSpec,
|
|
43
|
+
readSpec,
|
|
44
|
+
releaseSpecClaim,
|
|
45
|
+
settingsRefusal,
|
|
46
|
+
settleSpecPayment,
|
|
47
|
+
storeChoices,
|
|
48
|
+
storeFullResult,
|
|
49
|
+
storeSpecs
|
|
50
|
+
} from "./chunk-HKGUKAQW.js";
|
|
51
|
+
import {
|
|
52
|
+
assertResultSchema,
|
|
53
|
+
canonicalHash,
|
|
54
|
+
inputProblems,
|
|
55
|
+
projectBody,
|
|
56
|
+
validateResultBody
|
|
57
|
+
} from "./chunk-R4KDH477.js";
|
|
58
|
+
import {
|
|
59
|
+
termsNotice
|
|
60
|
+
} from "./chunk-Y2EXZ47H.js";
|
|
61
|
+
import {
|
|
62
|
+
resolveWalletProvider
|
|
63
|
+
} from "./chunk-K5KNGC4I.js";
|
|
64
|
+
import {
|
|
65
|
+
withFileLock
|
|
66
|
+
} from "./chunk-2W4DQQUU.js";
|
|
67
|
+
import {
|
|
68
|
+
depositSentence,
|
|
69
|
+
shortOfFunds,
|
|
70
|
+
unpaidSentence
|
|
71
|
+
} from "./chunk-HZKANST2.js";
|
|
72
|
+
import {
|
|
73
|
+
parseUsdToAtomic,
|
|
74
|
+
toMoney
|
|
75
|
+
} from "./chunk-MEZJ3I63.js";
|
|
76
|
+
import {
|
|
77
|
+
readJsonFile,
|
|
78
|
+
sweep,
|
|
79
|
+
writePrivate
|
|
80
|
+
} from "./chunk-ILWCKCOI.js";
|
|
81
|
+
import {
|
|
82
|
+
agentFixOf
|
|
83
|
+
} from "./chunk-RFZA7PSM.js";
|
|
84
|
+
import {
|
|
85
|
+
mask
|
|
86
|
+
} from "./chunk-7SLOTLO7.js";
|
|
87
|
+
import {
|
|
88
|
+
SILENT_FOOTER,
|
|
89
|
+
openLookupFooter
|
|
90
|
+
} from "./chunk-2U7H35IP.js";
|
|
91
|
+
import {
|
|
92
|
+
routerSettings
|
|
93
|
+
} from "./chunk-W2GXIARJ.js";
|
|
94
|
+
import {
|
|
95
|
+
resolveContextSettings
|
|
96
|
+
} from "./chunk-DTEWAVNE.js";
|
|
97
|
+
import {
|
|
98
|
+
downloadsDir,
|
|
99
|
+
jobsDir
|
|
100
|
+
} from "./chunk-JTX3BUDK.js";
|
|
101
|
+
import {
|
|
102
|
+
ALL_CHOICES,
|
|
103
|
+
AccountSpecSchema,
|
|
104
|
+
DEADLINE_AFTER_PAYMENT_SENT,
|
|
105
|
+
JobSchema,
|
|
106
|
+
MAX_INPUT_BYTES,
|
|
107
|
+
POLL_REFERENCE,
|
|
108
|
+
isAccountSpec,
|
|
109
|
+
reportSpecOutcome,
|
|
110
|
+
requestBrowse,
|
|
111
|
+
requestDecision,
|
|
112
|
+
requestToolSpec
|
|
113
|
+
} from "./chunk-ZEYA2WWX.js";
|
|
114
|
+
import {
|
|
115
|
+
assertPublicHttpsUrl,
|
|
116
|
+
resolvePublicDestination
|
|
117
|
+
} from "./chunk-DIH2G3YG.js";
|
|
118
|
+
import {
|
|
119
|
+
composeUserAgent,
|
|
120
|
+
isBinaryContentType,
|
|
121
|
+
requestHeaderProblem
|
|
122
|
+
} from "./chunk-D6M3ZK66.js";
|
|
123
|
+
import {
|
|
124
|
+
BUILT_IN_SOURCE,
|
|
125
|
+
SettingsHashSchema,
|
|
126
|
+
sha256Hex
|
|
127
|
+
} from "./chunk-RGCPELQN.js";
|
|
128
|
+
import {
|
|
129
|
+
external_exports
|
|
130
|
+
} from "./chunk-P6YQWIT2.js";
|
|
131
|
+
import {
|
|
132
|
+
CliError
|
|
133
|
+
} from "./chunk-DI4QAGRZ.js";
|
|
134
|
+
|
|
135
|
+
// src/router/accounts/jobs.ts
|
|
136
|
+
import { createHash } from "node:crypto";
|
|
137
|
+
import { rm } from "node:fs/promises";
|
|
138
|
+
import { join } from "node:path";
|
|
139
|
+
var DIR = join("progress", "account-jobs");
|
|
140
|
+
var ACCOUNT_JOB_KEEP_MS = 12 * 60 * 6e4;
|
|
141
|
+
var MAX_JOB_BYTES = 256 * 1024;
|
|
142
|
+
var AccountJobSchema = external_exports.strictObject({
|
|
143
|
+
version: external_exports.literal(1),
|
|
144
|
+
offerId: external_exports.string().min(1).max(64),
|
|
145
|
+
spec: AccountSpecSchema,
|
|
146
|
+
input: external_exports.record(external_exports.string(), external_exports.unknown()),
|
|
147
|
+
first: external_exports.unknown(),
|
|
148
|
+
firstAt: external_exports.number().int().nonnegative()
|
|
149
|
+
});
|
|
150
|
+
var pathOf = (dataDir, offerId) => join(dataDir, DIR, `${createHash("sha256").update(offerId).digest("hex")}.json`);
|
|
151
|
+
async function keepAccountJob(dataDir, job) {
|
|
152
|
+
try {
|
|
153
|
+
const text = JSON.stringify(job);
|
|
154
|
+
if (Buffer.byteLength(text, "utf8") > MAX_JOB_BYTES) return false;
|
|
155
|
+
await writePrivate(pathOf(dataDir, job.offerId), text);
|
|
156
|
+
return true;
|
|
157
|
+
} catch {
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async function readAccountJob(dataDir, offerId, now = Date.now()) {
|
|
162
|
+
const parsed = AccountJobSchema.safeParse(
|
|
163
|
+
await readJsonFile(pathOf(dataDir, offerId), MAX_JOB_BYTES)
|
|
164
|
+
);
|
|
165
|
+
if (!parsed.success || parsed.data.offerId !== offerId) return null;
|
|
166
|
+
return now - parsed.data.firstAt > ACCOUNT_JOB_KEEP_MS ? null : parsed.data;
|
|
167
|
+
}
|
|
168
|
+
async function endAccountJob(dataDir, offerId) {
|
|
169
|
+
await rm(pathOf(dataDir, offerId), { force: true }).catch(() => void 0);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// src/router/spec-call.ts
|
|
173
|
+
var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
174
|
+
var clip = (text, max) => text.length <= max ? text : `${text.slice(0, max - 1).trimEnd()}\u2026`;
|
|
175
|
+
function typeOf(schema) {
|
|
176
|
+
const type = Array.isArray(schema.type) ? schema.type.join(" | ") : schema.type;
|
|
177
|
+
if (type === "array") {
|
|
178
|
+
const items = record(schema.items);
|
|
179
|
+
return Object.keys(items).length ? `array of ${typeOf(items)}` : "array";
|
|
180
|
+
}
|
|
181
|
+
if (type === "object" || type === void 0 && schema.properties !== void 0) {
|
|
182
|
+
const names = Object.keys(record(schema.properties));
|
|
183
|
+
return names.length ? `object {${clip(names.join(", "), 120)}}` : "object";
|
|
184
|
+
}
|
|
185
|
+
if (typeof type === "string") return type;
|
|
186
|
+
if (Array.isArray(schema.anyOf) || Array.isArray(schema.oneOf)) return "one of several shapes";
|
|
187
|
+
return "any";
|
|
188
|
+
}
|
|
189
|
+
function fieldLine(name, schema, required, depth = 0) {
|
|
190
|
+
const parts = [`${name} (${typeOf(schema)}${required ? ", required" : ""})`];
|
|
191
|
+
if (typeof schema.description === "string") parts.push(clip(schema.description.trim(), 300));
|
|
192
|
+
if (Array.isArray(schema.enum))
|
|
193
|
+
parts.push(
|
|
194
|
+
`one of ${schema.enum.slice(0, 25).map((v) => JSON.stringify(v)).join(", ")}${schema.enum.length > 25 ? ", \u2026" : ""}`
|
|
195
|
+
);
|
|
196
|
+
const items = record(schema.items);
|
|
197
|
+
if (Array.isArray(items.enum))
|
|
198
|
+
parts.push(
|
|
199
|
+
`each one of ${items.enum.slice(0, 25).map((v) => JSON.stringify(v)).join(", ")}`
|
|
200
|
+
);
|
|
201
|
+
if (schema.default !== void 0) parts.push(`default ${JSON.stringify(schema.default)}`);
|
|
202
|
+
if (typeof schema.format === "string") parts.push(`format ${schema.format}`);
|
|
203
|
+
for (const [key, label] of [
|
|
204
|
+
["minimum", "min"],
|
|
205
|
+
["maximum", "max"],
|
|
206
|
+
["minLength", "min length"],
|
|
207
|
+
["maxLength", "max length"],
|
|
208
|
+
["maxItems", "max items"]
|
|
209
|
+
])
|
|
210
|
+
if (typeof schema[key] === "number") parts.push(`${label} ${String(schema[key])}`);
|
|
211
|
+
return `${" ".repeat(depth)}- ${parts.join("; ")}`;
|
|
212
|
+
}
|
|
213
|
+
var NESTED_DEPTH = 3;
|
|
214
|
+
var NESTED_LINES = 20;
|
|
215
|
+
function fieldLines(name, schema, required, budget, depth = 0) {
|
|
216
|
+
const lines = [fieldLine(name, schema, required, depth)];
|
|
217
|
+
if (depth >= NESTED_DEPTH) return lines;
|
|
218
|
+
const items = record(schema.items);
|
|
219
|
+
const nested = schema.properties !== void 0 ? [name, schema] : items.properties !== void 0 ? [`${name}[]`, items] : void 0;
|
|
220
|
+
if (nested === void 0) return lines;
|
|
221
|
+
const [at, object] = nested;
|
|
222
|
+
if (!Array.isArray(object.required)) return lines;
|
|
223
|
+
const properties = record(object.properties);
|
|
224
|
+
for (const sub of object.required) {
|
|
225
|
+
if (typeof sub !== "string") continue;
|
|
226
|
+
if (budget.left <= 0) {
|
|
227
|
+
if (budget.left === 0)
|
|
228
|
+
lines.push(`${" ".repeat(depth + 1)}- \u2026 more required fields, not listed here`);
|
|
229
|
+
budget.left = -1;
|
|
230
|
+
break;
|
|
231
|
+
}
|
|
232
|
+
budget.left -= 1;
|
|
233
|
+
lines.push(...fieldLines(`${at}.${sub}`, record(properties[sub]), true, budget, depth + 1));
|
|
234
|
+
}
|
|
235
|
+
return lines;
|
|
236
|
+
}
|
|
237
|
+
function priceLine(spec) {
|
|
238
|
+
const price = `$${toMoney(spec.priceAtomic).usd}`;
|
|
239
|
+
return spec.priceVaries ? `${price} per call at the listed input; the price varies with the input (up to $${toMoney(spec.maxAmountAtomic).usd}) and the live price is checked before paying` : `${price} per call`;
|
|
240
|
+
}
|
|
241
|
+
function accountLines(account) {
|
|
242
|
+
return [
|
|
243
|
+
`Price: billed to your ${account} account's own plan, not the Tenjin balance, and not counted in its limits.`,
|
|
244
|
+
`Runs on: your ${account} account.`
|
|
245
|
+
];
|
|
246
|
+
}
|
|
247
|
+
function specText(id, spec, account) {
|
|
248
|
+
const properties = record(spec.input.properties);
|
|
249
|
+
const required = new Set(Array.isArray(spec.input.required) ? spec.input.required : []);
|
|
250
|
+
const open = Object.keys(properties).filter((name) => !(name in spec.pinned));
|
|
251
|
+
const ordered = [
|
|
252
|
+
...open.filter((name) => required.has(name)),
|
|
253
|
+
...open.filter((name) => !required.has(name))
|
|
254
|
+
];
|
|
255
|
+
const budget = { left: NESTED_LINES };
|
|
256
|
+
const lines = [
|
|
257
|
+
`${spec.provider}: ${spec.description}`,
|
|
258
|
+
...isAccountSpec(spec) ? accountLines(account ?? spec.provider) : [
|
|
259
|
+
`Price: ${priceLine(spec)}, paid by this machine's wallet straight to the provider.`,
|
|
260
|
+
`Request: ${spec.request.method} ${spec.request.url}`
|
|
261
|
+
],
|
|
262
|
+
ordered.length ? `Inputs:
|
|
263
|
+
${ordered.flatMap((name) => fieldLines(name, record(properties[name]), required.has(name), budget)).join("\n")}` : "Inputs: none."
|
|
264
|
+
];
|
|
265
|
+
if (Object.keys(spec.pinned).length)
|
|
266
|
+
lines.push(
|
|
267
|
+
`Set by Tenjin on every call (leave these out): ${Object.entries(spec.pinned).map(([name, value]) => `${name} = ${JSON.stringify(value)}`).join("; ")}`
|
|
268
|
+
);
|
|
269
|
+
if (spec.example !== void 0) lines.push(`Example input: ${JSON.stringify(spec.example)}`);
|
|
270
|
+
if (spec.returns !== void 0) lines.push(`Returns: ${spec.returns}`);
|
|
271
|
+
if (spec.returnsExample !== void 0)
|
|
272
|
+
lines.push(`Example of what comes back (shortened): ${JSON.stringify(spec.returnsExample)}`);
|
|
273
|
+
lines.push(
|
|
274
|
+
`To run it, call request({id: ${JSON.stringify(id)}, input: {...}}) with the inputs above. ${isAccountSpec(spec) ? "Nothing has run yet." : "Nothing has been paid."}`
|
|
275
|
+
);
|
|
276
|
+
return lines.join("\n");
|
|
277
|
+
}
|
|
278
|
+
function mergedInput(spec, input) {
|
|
279
|
+
return { ...input, ...spec.pinned };
|
|
280
|
+
}
|
|
281
|
+
function specInputProblems(spec, merged) {
|
|
282
|
+
const problems = inputProblems(spec.input, merged);
|
|
283
|
+
if (problems === void 0) return void 0;
|
|
284
|
+
const properties = spec.input.properties;
|
|
285
|
+
if (properties === null || typeof properties !== "object" || Array.isArray(properties))
|
|
286
|
+
return problems;
|
|
287
|
+
for (const name of Object.keys(merged)) {
|
|
288
|
+
if (Object.hasOwn(properties, name) || Object.hasOwn(spec.pinned, name)) continue;
|
|
289
|
+
const problem = `the input has no field ${JSON.stringify(name)}`;
|
|
290
|
+
if (!problems.includes(problem)) problems.push(problem);
|
|
291
|
+
}
|
|
292
|
+
return problems;
|
|
293
|
+
}
|
|
294
|
+
var PLACEHOLDER_RE = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
|
|
295
|
+
var scalar = (value) => typeof value === "string" && value.length > 0 || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
|
|
296
|
+
var segment = (value) => scalar(value) && value !== "." && value !== "..";
|
|
297
|
+
function buildSpecRequest(spec, merged) {
|
|
298
|
+
const fixed = spec.request.headers ?? {};
|
|
299
|
+
const refused = Object.entries(fixed).find(([name, value]) => requestHeaderProblem(name, value));
|
|
300
|
+
if (refused !== void 0)
|
|
301
|
+
return {
|
|
302
|
+
problem: `the spec sets the header ${JSON.stringify(refused[0])}, which this build will not send`
|
|
303
|
+
};
|
|
304
|
+
const specHeaders = Object.keys(fixed).length ? { specHeaders: fixed } : {};
|
|
305
|
+
const where = (name) => spec.request.fields[name] ?? spec.request.location;
|
|
306
|
+
const inPath = [...spec.request.url.matchAll(PLACEHOLDER_RE)].map((match) => match[1]);
|
|
307
|
+
const missing = inPath.filter((name) => !segment(merged[name]));
|
|
308
|
+
if (missing.length)
|
|
309
|
+
return {
|
|
310
|
+
problem: `${missing.join(", ")} ${missing.length > 1 ? "go" : "goes"} in the URL path, so each must be a non-empty string or number other than "." or ".."`
|
|
311
|
+
};
|
|
312
|
+
let base;
|
|
313
|
+
let url;
|
|
314
|
+
try {
|
|
315
|
+
base = new URL(spec.request.url);
|
|
316
|
+
url = new URL(
|
|
317
|
+
spec.request.url.replace(
|
|
318
|
+
PLACEHOLDER_RE,
|
|
319
|
+
(_, name) => encodeURIComponent(String(merged[name]))
|
|
320
|
+
)
|
|
321
|
+
);
|
|
322
|
+
} catch {
|
|
323
|
+
return { problem: "the spec names a URL this build cannot parse" };
|
|
324
|
+
}
|
|
325
|
+
if (url.origin !== base.origin || url.protocol !== "https:")
|
|
326
|
+
return { problem: "the filled URL left the service it names" };
|
|
327
|
+
const body = {};
|
|
328
|
+
const nested = [];
|
|
329
|
+
for (const [name, value] of Object.entries(merged)) {
|
|
330
|
+
if (inPath.includes(name)) continue;
|
|
331
|
+
const location = where(name);
|
|
332
|
+
if (location === "path") continue;
|
|
333
|
+
if (location === "body") {
|
|
334
|
+
body[name] = value;
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
if (value === null || typeof value === "object") nested.push(name);
|
|
338
|
+
else url.searchParams.set(name, String(value));
|
|
339
|
+
}
|
|
340
|
+
if (nested.length)
|
|
341
|
+
return {
|
|
342
|
+
problem: `${nested.join(", ")} ${nested.length > 1 ? "go" : "goes"} in the query string, so each must be a string, number or boolean`
|
|
343
|
+
};
|
|
344
|
+
if (spec.request.method === "GET") {
|
|
345
|
+
if (Object.keys(body).length)
|
|
346
|
+
return {
|
|
347
|
+
problem: `a GET carries no body, so ${Object.keys(body).join(", ")} cannot be sent`
|
|
348
|
+
};
|
|
349
|
+
return {
|
|
350
|
+
url: url.toString(),
|
|
351
|
+
method: "GET",
|
|
352
|
+
headers: { accept: "application/json" },
|
|
353
|
+
...specHeaders
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
return {
|
|
357
|
+
url: url.toString(),
|
|
358
|
+
method: "POST",
|
|
359
|
+
headers: { accept: "application/json", "content-type": "application/json" },
|
|
360
|
+
...specHeaders,
|
|
361
|
+
body: JSON.stringify(body)
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// src/router/jobs.ts
|
|
366
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
367
|
+
var MAX_CALL_WAIT_MS = 3e5;
|
|
368
|
+
var MAX_POLL_INTERVAL_MS = 3e4;
|
|
369
|
+
var BACKOFF = 1.5;
|
|
370
|
+
var MAX_POLL_ERRORS = 3;
|
|
371
|
+
var POLL_REQUEST_TIMEOUT_MS = 12e4;
|
|
372
|
+
var MAX_STATUS_BYTES = 64 * 1024 * 1024;
|
|
373
|
+
var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
374
|
+
function fieldIn(json, field, values) {
|
|
375
|
+
const value = record2(json)[field];
|
|
376
|
+
return typeof value === "string" && values.includes(value);
|
|
377
|
+
}
|
|
378
|
+
function answerState(job, status, json, opts) {
|
|
379
|
+
if (job.failed !== void 0 && fieldIn(json, job.failed.field, job.failed.values)) {
|
|
380
|
+
return "failed";
|
|
381
|
+
}
|
|
382
|
+
if (status === 202 || opts.submit && job.always === true) return "running";
|
|
383
|
+
const rule = job.running;
|
|
384
|
+
if (rule.httpStatus !== void 0) return rule.httpStatus.includes(status) ? "running" : "done";
|
|
385
|
+
return fieldIn(json, rule.field, rule.values) ? "running" : "done";
|
|
386
|
+
}
|
|
387
|
+
function pollTarget(job, submit, input) {
|
|
388
|
+
let raw;
|
|
389
|
+
if (job.pollUrl.fixed !== void 0) raw = job.pollUrl.fixed;
|
|
390
|
+
else {
|
|
391
|
+
const { field, header } = job.pollUrl;
|
|
392
|
+
const fromBody = field !== void 0 ? record2(submit.json)[field] : void 0;
|
|
393
|
+
if (typeof fromBody === "string" && fromBody.trim().length > 0) raw = fromBody.trim();
|
|
394
|
+
else if (header !== void 0) raw = submit.header?.(header)?.trim() || void 0;
|
|
395
|
+
}
|
|
396
|
+
if (raw === void 0) return { problem: "the seller named no status URL to poll" };
|
|
397
|
+
if (raw.length > 2048) return { problem: "the status URL the seller named is too long" };
|
|
398
|
+
const named = sellerLine(raw);
|
|
399
|
+
let url;
|
|
400
|
+
let base;
|
|
401
|
+
try {
|
|
402
|
+
base = new URL(submit.url);
|
|
403
|
+
url = new URL(raw, base);
|
|
404
|
+
} catch {
|
|
405
|
+
return { problem: "the status URL the seller named cannot be parsed", named };
|
|
406
|
+
}
|
|
407
|
+
url.hash = "";
|
|
408
|
+
if (url.protocol !== "https:" || url.username !== "" || url.password !== "") {
|
|
409
|
+
return { problem: "the status URL the seller named is not plain HTTPS", named };
|
|
410
|
+
}
|
|
411
|
+
if (url.hostname !== base.hostname) {
|
|
412
|
+
return { problem: `the status URL is on ${url.hostname}, not ${base.hostname}`, named };
|
|
413
|
+
}
|
|
414
|
+
if (job.pollMethod === "GET") return { url: url.toString(), method: "GET" };
|
|
415
|
+
if (job.pollBody === void 0) return { url: url.toString(), method: "POST" };
|
|
416
|
+
const body = {};
|
|
417
|
+
for (const [name, value] of Object.entries(job.pollBody)) {
|
|
418
|
+
const reference = typeof value === "string" ? POLL_REFERENCE.exec(value) : null;
|
|
419
|
+
if (reference === null) {
|
|
420
|
+
body[name] = value;
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
const [, from, field] = reference;
|
|
424
|
+
const found = record2(from === "input" ? input : submit.json)[field];
|
|
425
|
+
if (found === void 0 || found === null) {
|
|
426
|
+
return {
|
|
427
|
+
problem: `the poll needs ${value}, which the ${from === "input" ? "input" : "seller's answer"} does not carry`
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
body[name] = found;
|
|
431
|
+
}
|
|
432
|
+
return { url: url.toString(), method: "POST", body: JSON.stringify(body) };
|
|
433
|
+
}
|
|
434
|
+
var pinnedRequest = async (target, request, signal) => {
|
|
435
|
+
const res = await pinnedHttp(target, request, signal);
|
|
436
|
+
return {
|
|
437
|
+
status: res.statusCode ?? 0,
|
|
438
|
+
header: (name) => {
|
|
439
|
+
const value = res.headers[name.toLowerCase()];
|
|
440
|
+
return Array.isArray(value) ? value.join(", ") : value;
|
|
441
|
+
},
|
|
442
|
+
body: res,
|
|
443
|
+
discard: () => res.destroy()
|
|
444
|
+
};
|
|
445
|
+
};
|
|
446
|
+
async function pollUntil(take, opts, deps = {}) {
|
|
447
|
+
const now = deps.now ?? Date.now;
|
|
448
|
+
const sleep = deps.sleep ?? ((ms) => delay(ms).then(() => void 0));
|
|
449
|
+
let interval = take.job.everyS * 1e3;
|
|
450
|
+
let wait = opts.firstWaitMs;
|
|
451
|
+
let errors = 0;
|
|
452
|
+
let last;
|
|
453
|
+
for (; ; ) {
|
|
454
|
+
if (wait > 0) {
|
|
455
|
+
const left = opts.deadline - now();
|
|
456
|
+
if (left <= 0) return { state: "running", ...last !== void 0 ? { status: last } : {} };
|
|
457
|
+
await sleep(Math.min(wait, left));
|
|
458
|
+
}
|
|
459
|
+
await Promise.resolve().then(() => deps.onPoll?.()).catch(() => void 0);
|
|
460
|
+
const answer = await pollSignedIn(take, deps);
|
|
461
|
+
wait = interval;
|
|
462
|
+
interval = Math.min(Math.round(interval * BACKOFF), MAX_POLL_INTERVAL_MS);
|
|
463
|
+
if (answer.kind === "refused") return { state: "failed", reason: answer.reason };
|
|
464
|
+
if (answer.kind === "wallet") {
|
|
465
|
+
return {
|
|
466
|
+
state: "running",
|
|
467
|
+
status: 402,
|
|
468
|
+
reason: `the seller returns the result only to the wallet that paid for it, ${answer.paidBy}, and this machine's wallet is now ${answer.current}; nothing was signed`,
|
|
469
|
+
otherWallet: { paidBy: answer.paidBy, current: answer.current }
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
const status = answer.kind === "answer" ? answer.status : void 0;
|
|
473
|
+
if (status !== void 0) last = status;
|
|
474
|
+
const transient = answer.kind === "error" || status === 429 || status !== void 0 && status >= 500;
|
|
475
|
+
if (transient) {
|
|
476
|
+
errors += 1;
|
|
477
|
+
if (errors >= MAX_POLL_ERRORS) {
|
|
478
|
+
return {
|
|
479
|
+
state: "running",
|
|
480
|
+
...status !== void 0 ? { status } : {},
|
|
481
|
+
reason: answer.kind === "error" ? answer.reason : `the status URL answered ${status} ${MAX_POLL_ERRORS} times in a row`
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
if (now() >= opts.deadline)
|
|
485
|
+
return { state: "running", ...status !== void 0 ? { status } : {} };
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
if (answer.kind !== "answer") continue;
|
|
489
|
+
errors = 0;
|
|
490
|
+
if (answer.status === 402) {
|
|
491
|
+
return {
|
|
492
|
+
state: "failed",
|
|
493
|
+
status: 402,
|
|
494
|
+
reason: answer.signIn === "refused" ? `the seller asks the wallet that paid it to sign in, and nothing was signed: ${answer.signInRefusal ?? "no reason given"}` : answer.signIn === "sent" ? "the seller did not accept this wallet's sign-in" : "the seller asked for another payment to return the result; none was sent"
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
if (answer.status === 404 || answer.status === 410) {
|
|
498
|
+
return { state: "expired", status: answer.status };
|
|
499
|
+
}
|
|
500
|
+
if (answer.status >= 300 && answer.status < 400) {
|
|
501
|
+
return {
|
|
502
|
+
state: "failed",
|
|
503
|
+
status: answer.status,
|
|
504
|
+
reason: "the status URL answered a redirect, which a poll does not follow"
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
if (answer.status < 200 || answer.status >= 300) {
|
|
508
|
+
const said = sellerSaid(answer.json, answer.text);
|
|
509
|
+
return {
|
|
510
|
+
state: "failed",
|
|
511
|
+
status: answer.status,
|
|
512
|
+
reason: `the seller ended the job with HTTP ${answer.status}`,
|
|
513
|
+
...said.length > 0 ? { said } : {}
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
if (answer.tooLarge) {
|
|
517
|
+
return {
|
|
518
|
+
state: "failed",
|
|
519
|
+
status: answer.status,
|
|
520
|
+
reason: "the finished file is over the size this call keeps"
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
const state = answerState(take.job, answer.status, answer.json, { submit: false });
|
|
524
|
+
if (state === "failed") {
|
|
525
|
+
const said = sellerSaid(answer.json, answer.text);
|
|
526
|
+
return {
|
|
527
|
+
state: "failed",
|
|
528
|
+
status: answer.status,
|
|
529
|
+
reason: "the seller says the job failed",
|
|
530
|
+
...said.length > 0 ? { said } : {}
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
if (state === "done") {
|
|
534
|
+
return {
|
|
535
|
+
state: "done",
|
|
536
|
+
status: answer.status,
|
|
537
|
+
header: answer.header,
|
|
538
|
+
text: answer.text,
|
|
539
|
+
json: answer.json,
|
|
540
|
+
...answer.bytes !== void 0 ? { bytes: answer.bytes } : {},
|
|
541
|
+
contentType: answer.header("content-type") ?? ""
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
if (now() >= opts.deadline) return { state: "running", status: answer.status };
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
async function completeJob(take, deps = {}) {
|
|
548
|
+
const fixed = take.job.completeUrl?.fixed;
|
|
549
|
+
if (fixed === void 0) return;
|
|
550
|
+
let url;
|
|
551
|
+
let base;
|
|
552
|
+
try {
|
|
553
|
+
base = new URL(take.submitUrl);
|
|
554
|
+
url = new URL(fixed);
|
|
555
|
+
} catch {
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
if (url.protocol !== "https:" || url.username !== "" || url.password !== "") return;
|
|
559
|
+
if (url.hostname !== base.hostname) return;
|
|
560
|
+
await pollOnce({ ...take, poll: { ...take.poll, url: url.toString() } }, deps).catch(
|
|
561
|
+
() => void 0
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
function sellerSaid(json, text) {
|
|
565
|
+
const body = record2(json);
|
|
566
|
+
const error = body.error;
|
|
567
|
+
const said = [
|
|
568
|
+
typeof error === "string" ? error : record2(error).message,
|
|
569
|
+
body.message,
|
|
570
|
+
body.reason,
|
|
571
|
+
body.detail
|
|
572
|
+
].find((value) => typeof value === "string" && value.trim().length > 0);
|
|
573
|
+
return sellerLine(said ?? text);
|
|
574
|
+
}
|
|
575
|
+
async function pollSignedIn(take, deps) {
|
|
576
|
+
const first = await pollOnce(take, deps);
|
|
577
|
+
if (first.kind !== "answer" || first.status !== 402 || deps.signIn === void 0) return first;
|
|
578
|
+
const challenge = first.header("PAYMENT-REQUIRED");
|
|
579
|
+
if (challenge === void 0) return first;
|
|
580
|
+
if (take.poll.method !== "GET") {
|
|
581
|
+
return signInOnlyHeader(challenge) !== void 0 ? {
|
|
582
|
+
...first,
|
|
583
|
+
signIn: "refused",
|
|
584
|
+
signInRefusal: `a sign-in answers only a GET, and this poll is a ${take.poll.method}`
|
|
585
|
+
} : first;
|
|
586
|
+
}
|
|
587
|
+
const answer = await deps.signIn(challenge, take.poll.url).catch((err) => ({ error: `the sign-in failed (${errorText(err)})` }));
|
|
588
|
+
if (answer === void 0) return first;
|
|
589
|
+
if ("error" in answer) {
|
|
590
|
+
return {
|
|
591
|
+
kind: "error",
|
|
592
|
+
reason: `the seller asks the wallet that paid it to sign in, and ${sellerLine(answer.error)}`
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
if ("refused" in answer) {
|
|
596
|
+
return { ...first, signIn: "refused", signInRefusal: sellerLine(answer.refused) };
|
|
597
|
+
}
|
|
598
|
+
if ("otherWallet" in answer) return { kind: "wallet", ...answer.otherWallet };
|
|
599
|
+
const signed = await pollOnce(take, deps, answer.headers);
|
|
600
|
+
return signed.kind === "answer" ? { ...signed, signIn: "sent" } : signed;
|
|
601
|
+
}
|
|
602
|
+
async function pollOnce(take, deps, signIn = {}) {
|
|
603
|
+
try {
|
|
604
|
+
assertPublicHttpsUrl(take.poll.url);
|
|
605
|
+
} catch {
|
|
606
|
+
return { kind: "refused", reason: "the status URL is not a public HTTPS endpoint" };
|
|
607
|
+
}
|
|
608
|
+
let pinned;
|
|
609
|
+
try {
|
|
610
|
+
pinned = await resolvePublicDestination(take.poll.url, deps.destination ?? {});
|
|
611
|
+
} catch (err) {
|
|
612
|
+
const unresolved = err instanceof CliError && err.details?.cause !== void 0;
|
|
613
|
+
return unresolved ? { kind: "error", reason: "the status URL host could not be resolved" } : { kind: "refused", reason: "the status URL resolves to a private address" };
|
|
614
|
+
}
|
|
615
|
+
const headers = {
|
|
616
|
+
accept: "application/json, */*;q=0.8",
|
|
617
|
+
"user-agent": composeUserAgent(),
|
|
618
|
+
...take.poll.body !== void 0 ? { "content-type": "application/json" } : {},
|
|
619
|
+
...signIn
|
|
620
|
+
};
|
|
621
|
+
const signal = AbortSignal.timeout(POLL_REQUEST_TIMEOUT_MS);
|
|
622
|
+
let res;
|
|
623
|
+
try {
|
|
624
|
+
res = await (deps.transport ?? pinnedRequest)(
|
|
625
|
+
pinned,
|
|
626
|
+
{
|
|
627
|
+
method: take.poll.method,
|
|
628
|
+
headers,
|
|
629
|
+
...take.poll.body !== void 0 ? { body: take.poll.body } : {}
|
|
630
|
+
},
|
|
631
|
+
signal
|
|
632
|
+
);
|
|
633
|
+
} catch (err) {
|
|
634
|
+
return { kind: "error", reason: `the status URL could not be reached (${errorText(err)})` };
|
|
635
|
+
}
|
|
636
|
+
if (res.status >= 300 && res.status < 400) {
|
|
637
|
+
res.discard();
|
|
638
|
+
return { kind: "answer", status: res.status, header: res.header, text: "", json: void 0 };
|
|
639
|
+
}
|
|
640
|
+
const binary = isBinaryContentType(res.header("content-type"));
|
|
641
|
+
const cap = binary ? MAX_MEDIA_BYTES : MAX_STATUS_BYTES;
|
|
642
|
+
const declared = Number(res.header("content-length") ?? "0");
|
|
643
|
+
if (Number.isFinite(declared) && declared > cap) {
|
|
644
|
+
res.discard();
|
|
645
|
+
return {
|
|
646
|
+
kind: "answer",
|
|
647
|
+
status: res.status,
|
|
648
|
+
header: res.header,
|
|
649
|
+
text: "",
|
|
650
|
+
json: void 0,
|
|
651
|
+
tooLarge: true
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
const chunks = [];
|
|
655
|
+
let size = 0;
|
|
656
|
+
try {
|
|
657
|
+
for await (const chunk of res.body) {
|
|
658
|
+
size += chunk.byteLength;
|
|
659
|
+
if (size > cap) {
|
|
660
|
+
res.discard();
|
|
661
|
+
return {
|
|
662
|
+
kind: "answer",
|
|
663
|
+
status: res.status,
|
|
664
|
+
header: res.header,
|
|
665
|
+
text: "",
|
|
666
|
+
json: void 0,
|
|
667
|
+
tooLarge: true
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
chunks.push(chunk);
|
|
671
|
+
}
|
|
672
|
+
} catch (err) {
|
|
673
|
+
return { kind: "error", reason: `the status answer could not be read (${errorText(err)})` };
|
|
674
|
+
}
|
|
675
|
+
const all = Buffer.concat(chunks);
|
|
676
|
+
if (binary) {
|
|
677
|
+
return {
|
|
678
|
+
kind: "answer",
|
|
679
|
+
status: res.status,
|
|
680
|
+
header: res.header,
|
|
681
|
+
text: "",
|
|
682
|
+
json: void 0,
|
|
683
|
+
bytes: new Uint8Array(all)
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
const text = all.toString("utf8");
|
|
687
|
+
let json;
|
|
688
|
+
try {
|
|
689
|
+
json = text.length > 0 ? JSON.parse(text) : void 0;
|
|
690
|
+
} catch {
|
|
691
|
+
json = void 0;
|
|
692
|
+
}
|
|
693
|
+
return { kind: "answer", status: res.status, header: res.header, text, json };
|
|
694
|
+
}
|
|
695
|
+
function errorText(err) {
|
|
696
|
+
return sellerLine(err instanceof Error ? err.message : String(err)) || "no reason given";
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// src/router/plan.ts
|
|
700
|
+
var Input = external_exports.record(external_exports.string(), external_exports.unknown());
|
|
701
|
+
var Digits = external_exports.string().regex(/^\d+$/);
|
|
702
|
+
var QuotedCallSchema = external_exports.discriminatedUnion("kind", [
|
|
703
|
+
external_exports.strictObject({
|
|
704
|
+
kind: external_exports.literal("spec"),
|
|
705
|
+
id: external_exports.string().min(1),
|
|
706
|
+
spec: KeptSpecSchema,
|
|
707
|
+
input: Input
|
|
708
|
+
}),
|
|
709
|
+
external_exports.strictObject({
|
|
710
|
+
kind: external_exports.literal("count"),
|
|
711
|
+
id: external_exports.string().min(1),
|
|
712
|
+
spec: KeptSpecSchema,
|
|
713
|
+
input: Input,
|
|
714
|
+
count: external_exports.number().int().min(2).max(5)
|
|
715
|
+
}),
|
|
716
|
+
external_exports.strictObject({
|
|
717
|
+
kind: external_exports.literal("choices"),
|
|
718
|
+
id: external_exports.string().min(1),
|
|
719
|
+
kept: KeptChoicesSchema,
|
|
720
|
+
specs: external_exports.array(KeptSpecSchema).min(2).max(4),
|
|
721
|
+
keys: external_exports.array(external_exports.string().min(1).max(64)).min(1).max(4),
|
|
722
|
+
input: Input
|
|
723
|
+
}),
|
|
724
|
+
external_exports.strictObject({
|
|
725
|
+
kind: external_exports.literal("call"),
|
|
726
|
+
call: external_exports.strictObject({
|
|
727
|
+
capabilityId: external_exports.string().min(1).max(200),
|
|
728
|
+
provider: external_exports.string().min(1).max(120),
|
|
729
|
+
label: external_exports.string().max(200).optional(),
|
|
730
|
+
media: external_exports.boolean(),
|
|
731
|
+
request: external_exports.strictObject({
|
|
732
|
+
url: external_exports.string().min(1).max(16384),
|
|
733
|
+
method: external_exports.string().min(1).max(8),
|
|
734
|
+
headers: external_exports.record(external_exports.string(), external_exports.string()),
|
|
735
|
+
body: external_exports.string().optional()
|
|
736
|
+
}),
|
|
737
|
+
terms: external_exports.strictObject({
|
|
738
|
+
source: external_exports.string().optional(),
|
|
739
|
+
maxAmountAtomic: Digits,
|
|
740
|
+
payTo: external_exports.string().optional(),
|
|
741
|
+
network: external_exports.string().optional(),
|
|
742
|
+
asset: external_exports.string().optional()
|
|
743
|
+
}),
|
|
744
|
+
requestKey: external_exports.string().min(1).max(1024),
|
|
745
|
+
resultSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
|
|
746
|
+
parameters: external_exports.unknown(),
|
|
747
|
+
sent: external_exports.string().max(16384),
|
|
748
|
+
note: external_exports.string().max(2e3).optional(),
|
|
749
|
+
settingsHash: SettingsHashSchema.optional(),
|
|
750
|
+
via: external_exports.literal("swap").optional()
|
|
751
|
+
})
|
|
752
|
+
})
|
|
753
|
+
]);
|
|
754
|
+
function quotedCall(quote) {
|
|
755
|
+
const parsed = QuotedCallSchema.safeParse(quote.call);
|
|
756
|
+
return parsed.success ? parsed.data : null;
|
|
757
|
+
}
|
|
758
|
+
var usd = (atomic) => `$${toMoney(atomic.toString()).usd}`;
|
|
759
|
+
function oneCall(provider, amountAtomic) {
|
|
760
|
+
return {
|
|
761
|
+
what: `one call to ${provider}`,
|
|
762
|
+
sentence: `One call to ${provider} costs ${usd(amountAtomic)}.`
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
function takesOf(provider, amounts) {
|
|
766
|
+
const what = `${amounts.length} takes of ${provider}`;
|
|
767
|
+
const total = amounts.reduce((sum, amount) => sum + amount, 0n);
|
|
768
|
+
const each = amounts.every((amount) => amount === amounts[0]) ? `${usd(amounts[0] ?? 0n)} each` : amounts.map(usd).join(" + ");
|
|
769
|
+
return { what, sentence: `${what} cost ${usd(total)} in total (${each}).` };
|
|
770
|
+
}
|
|
771
|
+
function choicesOf(labels, amounts) {
|
|
772
|
+
const what = `${labels.length} choices (${labels.join(", ")})`;
|
|
773
|
+
const total = amounts.reduce((sum, amount) => sum + amount, 0n);
|
|
774
|
+
return {
|
|
775
|
+
what,
|
|
776
|
+
sentence: `${what} cost ${usd(total)} in total (${amounts.map(usd).join(" + ")}).`
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
function whyAsked(over) {
|
|
780
|
+
return over.reason === "session_budget_exceeded" ? `That is more than today's automatic budget has left (${usd(over.budgetLeftAtomic ?? 0n)})` : `That is over the ${usd(over.maxAutoSpendAtomic)} this machine pays for one call without asking`;
|
|
781
|
+
}
|
|
782
|
+
function approveCall(quote) {
|
|
783
|
+
return `approve({quote: ${JSON.stringify(quote.id)}, total: ${JSON.stringify(usd(BigInt(quote.totalAtomic)))}, what: ${JSON.stringify(quote.what)}})`;
|
|
784
|
+
}
|
|
785
|
+
function approveStep(quote) {
|
|
786
|
+
return `Call ${approveCall(quote)}: it asks the user and runs only on their yes. Do not suggest changing a setting.`;
|
|
787
|
+
}
|
|
788
|
+
function quoteView(quote) {
|
|
789
|
+
return {
|
|
790
|
+
id: quote.id,
|
|
791
|
+
what: quote.what,
|
|
792
|
+
total: usd(BigInt(quote.totalAtomic)),
|
|
793
|
+
expiresAt: quote.expiresAt
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
async function planStop(admission, plan, deps, alternative) {
|
|
797
|
+
const or = alternative !== void 0 ? `, or ${alternative}` : "";
|
|
798
|
+
if ("refused" in admission) {
|
|
799
|
+
return {
|
|
800
|
+
status: "needs_approval",
|
|
801
|
+
reason: `${plan.sentence} ${admission.refused.message} ${policyFix("not_allowlisted", "this host")}`,
|
|
802
|
+
extras: { nextStep: `Tell the user${or}; nothing was paid.` },
|
|
803
|
+
outcome: { status: "needs_approval" }
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
const why = whyAsked(admission.over);
|
|
807
|
+
if (deps.approves !== true) {
|
|
808
|
+
return {
|
|
809
|
+
status: "needs_approval",
|
|
810
|
+
reason: `${plan.sentence} ${why}, so nothing was paid.`,
|
|
811
|
+
extras: { nextStep: `Tell the user what it would cost${or}; nothing was paid.` },
|
|
812
|
+
outcome: { status: "needs_approval" }
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
try {
|
|
816
|
+
const quote = await createQuote(
|
|
817
|
+
deps.ctx.dataDir,
|
|
818
|
+
{ what: plan.what, sentence: plan.sentence, payments: plan.payments, call: plan.call },
|
|
819
|
+
deps.now
|
|
820
|
+
);
|
|
821
|
+
return {
|
|
822
|
+
status: "needs_approval",
|
|
823
|
+
reason: `${plan.sentence} ${why}, so nothing was paid.`,
|
|
824
|
+
extras: { quote: quoteView(quote), nextStep: approveStep(quote) },
|
|
825
|
+
outcome: { status: "needs_approval" }
|
|
826
|
+
};
|
|
827
|
+
} catch (err) {
|
|
828
|
+
return {
|
|
829
|
+
status: "needs_approval",
|
|
830
|
+
reason: `${plan.sentence} ${why}, and this machine could not keep a quote for it (${err instanceof Error ? err.message : String(err)}), so nothing was paid.`,
|
|
831
|
+
extras: { nextStep: `Tell the user it needs their approval${or}; nothing was paid.` },
|
|
832
|
+
outcome: { status: "needs_approval" }
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
function paymentProvider(deps) {
|
|
837
|
+
return deps.provider ?? deps.payDeps?.provider ?? resolveWalletProvider(deps.ctx);
|
|
838
|
+
}
|
|
839
|
+
function quotedHashes(call) {
|
|
840
|
+
switch (call.kind) {
|
|
841
|
+
case "spec":
|
|
842
|
+
case "count":
|
|
843
|
+
return [call.spec.settingsHash];
|
|
844
|
+
case "choices":
|
|
845
|
+
return call.specs.map((spec) => spec.settingsHash);
|
|
846
|
+
case "call":
|
|
847
|
+
return [call.call.settingsHash];
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
// src/router/choices.ts
|
|
852
|
+
var COMPARE_NEXT_STEP = "Open each saved image, say which fits the request best and why, and let the user pick.";
|
|
853
|
+
async function pickChoice(dataDir, id, choice) {
|
|
854
|
+
if (id === void 0) {
|
|
855
|
+
return {
|
|
856
|
+
refused: fail(
|
|
857
|
+
"needs_input",
|
|
858
|
+
"A choice goes with the id from the line that offered it; send both."
|
|
859
|
+
)
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
const kept = await readChoices(dataDir, id);
|
|
863
|
+
if (kept === null) {
|
|
864
|
+
return {
|
|
865
|
+
refused: fail(
|
|
866
|
+
"needs_input",
|
|
867
|
+
"No choices are kept on this machine for that id (they expired, or its line offered none), so nothing was sent or paid.",
|
|
868
|
+
{
|
|
869
|
+
nextStep: "Call request({query}) with the task for a fresh offer, then fill its line. If its line listed no choices, call request({id, input}) without `choice`."
|
|
870
|
+
}
|
|
871
|
+
)
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
if (choice === ALL_CHOICES) return { all: kept };
|
|
875
|
+
const option = kept.choices.options.find((each) => each.key === choice);
|
|
876
|
+
if (option === void 0) {
|
|
877
|
+
return {
|
|
878
|
+
refused: fail(
|
|
879
|
+
"needs_input",
|
|
880
|
+
`${JSON.stringify(choice)} is not one of this offer's choices: ${keysOf(kept.choices)}.`,
|
|
881
|
+
{
|
|
882
|
+
nextStep: `Call request({id: ${JSON.stringify(id)}, choice, input: {...}}) with one of those.`
|
|
883
|
+
}
|
|
884
|
+
)
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
return { id: option.id };
|
|
888
|
+
}
|
|
889
|
+
function keysOf(choices) {
|
|
890
|
+
return [...choices.options.map((option) => option.key), ALL_CHOICES].map((key) => JSON.stringify(key)).join(", ");
|
|
891
|
+
}
|
|
892
|
+
function showChoices(id, kept) {
|
|
893
|
+
return {
|
|
894
|
+
isError: false,
|
|
895
|
+
summary: kept.hint,
|
|
896
|
+
envelope: {
|
|
897
|
+
status: "spec",
|
|
898
|
+
id,
|
|
899
|
+
choice: ALL_CHOICES,
|
|
900
|
+
nextStep: `Call request({id: ${JSON.stringify(id)}, choice: "${ALL_CHOICES}", input: {...}}) with ${kept.choices.input.join(", ")}.`,
|
|
901
|
+
cost: costLines(0n)
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
async function runTakes(steps, plan, deps, reportDeps, settings, words) {
|
|
906
|
+
const { dataDir } = deps.ctx;
|
|
907
|
+
const claimed = [];
|
|
908
|
+
const earlier = /* @__PURE__ */ new Map();
|
|
909
|
+
for (const step of steps) {
|
|
910
|
+
const claim = await claimSpecPayment(dataDir, step.claim);
|
|
911
|
+
if (claim === null) claimed.push(step);
|
|
912
|
+
else earlier.set(step, claim);
|
|
913
|
+
}
|
|
914
|
+
const release = async (dropped) => {
|
|
915
|
+
for (const step of dropped) {
|
|
916
|
+
await settleSpecPayment(dataDir, step.claim, { amountAtomic: 0n, signed: false });
|
|
917
|
+
}
|
|
918
|
+
};
|
|
919
|
+
const unquoted = /* @__PURE__ */ new Map();
|
|
920
|
+
const slots = /* @__PURE__ */ new Map();
|
|
921
|
+
let planned = [];
|
|
922
|
+
if (claimed.length > 0 && plan.approved !== void 0) {
|
|
923
|
+
if (plan.approved.length !== claimed.length) {
|
|
924
|
+
await release(claimed);
|
|
925
|
+
return {
|
|
926
|
+
refused: await words.refuse(
|
|
927
|
+
"needs_input",
|
|
928
|
+
"What is left to run is no longer what the quote approved, so nothing was paid.",
|
|
929
|
+
{ nextStep: "Call request again for a fresh quote." }
|
|
930
|
+
)
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
claimed.forEach((step, index) => slots.set(step, plan.approved[index]));
|
|
934
|
+
planned = claimed.map((step) => ({ step, amountAtomic: slots.get(step).amountAtomic }));
|
|
935
|
+
} else if (claimed.length > 0) {
|
|
936
|
+
const priced = await plan.price(claimed);
|
|
937
|
+
if ("stop" in priced) {
|
|
938
|
+
await release(claimed);
|
|
939
|
+
return { refused: priced.stop };
|
|
940
|
+
}
|
|
941
|
+
claimed.forEach((step, index) => {
|
|
942
|
+
const price = priced[index];
|
|
943
|
+
if (typeof price === "bigint") planned.push({ step, amountAtomic: price });
|
|
944
|
+
else unquoted.set(step, price.refused);
|
|
945
|
+
});
|
|
946
|
+
await release([...unquoted.keys()]);
|
|
947
|
+
if (planned.length > 0) {
|
|
948
|
+
const payments = planned.map(({ step, amountAtomic }) => ({
|
|
949
|
+
amountAtomic,
|
|
950
|
+
creator: new URL(step.prepared.built.url).host
|
|
951
|
+
}));
|
|
952
|
+
const admission = await admitPlan(payments, {
|
|
953
|
+
dataDir,
|
|
954
|
+
policy: settings.policy,
|
|
955
|
+
...deps.now !== void 0 ? { now: deps.now } : {}
|
|
956
|
+
});
|
|
957
|
+
if (!("admitted" in admission)) {
|
|
958
|
+
await release(planned.map(({ step }) => step));
|
|
959
|
+
const stop = await planStop(
|
|
960
|
+
admission,
|
|
961
|
+
{ ...plan.words(planned), payments, call: plan.call(planned) },
|
|
962
|
+
deps,
|
|
963
|
+
words.pickOne
|
|
964
|
+
);
|
|
965
|
+
words.stopped(
|
|
966
|
+
planned.map(({ step }) => step),
|
|
967
|
+
stop.outcome
|
|
968
|
+
);
|
|
969
|
+
return { refused: await words.refuse(stop.status, stop.reason, stop.extras) };
|
|
970
|
+
}
|
|
971
|
+
planned.forEach(({ step }, index) => slots.set(step, admission.admitted[index]));
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
const paid = new Map(
|
|
975
|
+
await Promise.all(
|
|
976
|
+
planned.map(
|
|
977
|
+
async ({ step }) => [
|
|
978
|
+
step,
|
|
979
|
+
await paySpec(
|
|
980
|
+
step.prepared,
|
|
981
|
+
{ slot: slots.get(step) },
|
|
982
|
+
deps,
|
|
983
|
+
SILENT_FOOTER,
|
|
984
|
+
reportDeps,
|
|
985
|
+
step.take
|
|
986
|
+
)
|
|
987
|
+
]
|
|
988
|
+
)
|
|
989
|
+
)
|
|
990
|
+
);
|
|
991
|
+
return {
|
|
992
|
+
claimed: planned.length,
|
|
993
|
+
ran: steps.map((step) => {
|
|
994
|
+
const done = paid.get(step);
|
|
995
|
+
if (done !== void 0) return { step, paid: done };
|
|
996
|
+
const refused = unquoted.get(step);
|
|
997
|
+
return refused !== void 0 ? { step, refused } : { step, earlier: earlier.get(step) };
|
|
998
|
+
})
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
function takesResult(entries, opts) {
|
|
1002
|
+
let total = 0n;
|
|
1003
|
+
const ran = [];
|
|
1004
|
+
const results = entries.map((entry) => {
|
|
1005
|
+
if ("earlier" in entry) return { ...entry.named, ...entry.earlier };
|
|
1006
|
+
total += entry.amountAtomic;
|
|
1007
|
+
const envelope = { ...entry.result.envelope };
|
|
1008
|
+
delete envelope.providerContentUntrusted;
|
|
1009
|
+
ran.push(envelope.status);
|
|
1010
|
+
return { ...entry.named, status: envelope.status, ...envelope };
|
|
1011
|
+
});
|
|
1012
|
+
const status = ran.every((each) => each === "fulfilled") ? "fulfilled" : ran.some((each) => each === "running") ? "running" : ran.some((each) => each === "fulfilled" || each === "unverified") ? "partial" : "failed";
|
|
1013
|
+
const cost = costLines(total);
|
|
1014
|
+
const who = (step) => step.label !== void 0 ? `${String(step.label)} (${String(step.key)})` : `take ${String(step.take)}`;
|
|
1015
|
+
const lines = results.map((step) => {
|
|
1016
|
+
const files = Array.isArray(step.savedFiles) ? step.savedFiles : [];
|
|
1017
|
+
return `- ${who(step)}: ${String(step.status)}${files.length ? `, saved to ${files.join(", ")}` : ""}`;
|
|
1018
|
+
});
|
|
1019
|
+
const running = results.filter((step) => step.status === "running");
|
|
1020
|
+
const jobsOf = (steps) => [
|
|
1021
|
+
...new Set(steps.flatMap((step) => typeof step.job === "string" ? [step.job] : []))
|
|
1022
|
+
];
|
|
1023
|
+
const resumeOf = (steps) => jobsOf(steps).map((job) => `request({job: ${JSON.stringify(job)}})`).join(" and ");
|
|
1024
|
+
const jobs = jobsOf(running);
|
|
1025
|
+
const blocked = running.filter((step) => step.reasonCode === "sign_in_wallet");
|
|
1026
|
+
const moving = running.filter((step) => step.reasonCode !== "sign_in_wallet");
|
|
1027
|
+
const resume = jobsOf(moving).length > 0 ? `Call ${resumeOf(moving)} in a minute or two for what is still running; nothing more is paid.` : void 0;
|
|
1028
|
+
const walletLines = [...new Set(blocked.map((step) => String(step.paidBy)))].map((paidBy) => {
|
|
1029
|
+
const paid = blocked.filter((step) => String(step.paidBy) === paidBy);
|
|
1030
|
+
const one = paid.length === 1;
|
|
1031
|
+
return `Tell the user ${paid.map(who).join(" and ")} ${one ? "was" : "were"} paid by the wallet ${paidBy}, and this machine's wallet cannot collect ${one ? "it" : "them"}. Once this machine uses that wallet again, call ${resumeOf(paid)}; nothing more is paid. Do not call request again for a new result: it would pay again.`;
|
|
1032
|
+
});
|
|
1033
|
+
const next = [...resume !== void 0 ? [resume] : [], ...walletLines];
|
|
1034
|
+
const walletBlocked = blocked.length > 0 && resume === void 0;
|
|
1035
|
+
return {
|
|
1036
|
+
isError: status === "failed" || walletBlocked,
|
|
1037
|
+
summary: [`${opts.head}, ${status} \xB7 ${cost.join(" \xB7 ")}`, ...lines, ...next].join("\n"),
|
|
1038
|
+
envelope: {
|
|
1039
|
+
status,
|
|
1040
|
+
...opts.envelope ?? {},
|
|
1041
|
+
...jobs.length === 1 ? { job: jobs[0] } : {},
|
|
1042
|
+
...walletBlocked ? { reasonCode: "sign_in_wallet" } : {},
|
|
1043
|
+
results,
|
|
1044
|
+
cost,
|
|
1045
|
+
nextStep: next.length > 0 ? next.join(" ") : opts.nextStep,
|
|
1046
|
+
providerContentUntrusted: true
|
|
1047
|
+
}
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
function earlierEntry(step, claim) {
|
|
1051
|
+
return {
|
|
1052
|
+
named: step.named,
|
|
1053
|
+
earlier: {
|
|
1054
|
+
status: claim.state === "unrecorded" ? "failed" : "already_paid",
|
|
1055
|
+
reason: alreadyPaid(step.claim, step.prepared.spec, claim).envelope.reason,
|
|
1056
|
+
cost: costLines(0n)
|
|
1057
|
+
}
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
function entriesOf(ran) {
|
|
1061
|
+
return ran.map(
|
|
1062
|
+
(each) => "paid" in each ? {
|
|
1063
|
+
named: each.step.named,
|
|
1064
|
+
result: each.paid.result,
|
|
1065
|
+
amountAtomic: each.paid.left.amountAtomic
|
|
1066
|
+
} : "refused" in each ? { named: each.step.named, result: each.refused, amountAtomic: 0n } : earlierEntry(each.step, each.earlier)
|
|
1067
|
+
);
|
|
1068
|
+
}
|
|
1069
|
+
function paidHere(ran) {
|
|
1070
|
+
return ran.reduce((sum, each) => sum + ("paid" in each ? each.paid.left.amountAtomic : 0n), 0n);
|
|
1071
|
+
}
|
|
1072
|
+
async function runChoiceSet(id, kept, input, deps, footer, reportDeps, settings, approved) {
|
|
1073
|
+
const { dataDir } = deps.ctx;
|
|
1074
|
+
const { choices } = kept;
|
|
1075
|
+
const startedAt = Date.now();
|
|
1076
|
+
const stopped = (options, outcome) => {
|
|
1077
|
+
for (const option of options) reportOutcome(reportDeps, option.id, outcome, startedAt);
|
|
1078
|
+
};
|
|
1079
|
+
const again = `request({id: ${JSON.stringify(id)}, choice: "${ALL_CHOICES}", input: {...}})`;
|
|
1080
|
+
const refuse = async (status, reason, extras) => {
|
|
1081
|
+
await footer.done(status);
|
|
1082
|
+
return fail(status, reason, extras);
|
|
1083
|
+
};
|
|
1084
|
+
const extra = Object.keys(input).filter((name) => !choices.input.includes(name));
|
|
1085
|
+
if (extra.length) {
|
|
1086
|
+
stopped(choices.options, { status: "unpaid", reason: "input" });
|
|
1087
|
+
return refuse(
|
|
1088
|
+
"needs_input",
|
|
1089
|
+
`Running all the choices takes only ${choices.input.join(", ")}, not ${extra.join(", ")}.`,
|
|
1090
|
+
{
|
|
1091
|
+
nextStep: `Call ${again} with only those, or pick one choice to set more; nothing was sent or paid.`
|
|
1092
|
+
}
|
|
1093
|
+
);
|
|
1094
|
+
}
|
|
1095
|
+
const specs = [];
|
|
1096
|
+
const prepared = [];
|
|
1097
|
+
for (const [index, option] of choices.options.entries()) {
|
|
1098
|
+
const named = `${option.label} (choice ${JSON.stringify(option.key)})`;
|
|
1099
|
+
const spec = approved !== void 0 ? approved.specs[index] : await readSpec(dataDir, option.id);
|
|
1100
|
+
if (spec === null || spec === void 0) {
|
|
1101
|
+
return refuse(
|
|
1102
|
+
"needs_input",
|
|
1103
|
+
`The spec for ${named} is no longer kept on this machine (it expired or was pruned), so nothing was sent or paid.`,
|
|
1104
|
+
{ nextStep: "Call request({query}) with the task for a fresh offer, then fill its line." }
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
specs.push(spec);
|
|
1108
|
+
const checked = await prepareSpec(option.id, spec, input, SILENT_FOOTER, reportDeps);
|
|
1109
|
+
if ("refused" in checked) {
|
|
1110
|
+
const { status, reason } = checked.refused.envelope;
|
|
1111
|
+
return refuse(status, `${named}: ${reason}`, {
|
|
1112
|
+
nextStep: status === "needs_input" ? `Fix the input and call ${again} again, or pick one of the other choices; nothing was sent or paid.` : "Pick one of the other choices; nothing was sent or paid."
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
prepared.push({ option, checked: checked.prepared });
|
|
1116
|
+
}
|
|
1117
|
+
const stale = await settingsRefusal(
|
|
1118
|
+
dataDir,
|
|
1119
|
+
specs.map((spec) => spec.settingsHash)
|
|
1120
|
+
);
|
|
1121
|
+
if (stale !== null) {
|
|
1122
|
+
await footer.done("needs_input");
|
|
1123
|
+
return settingsFail(stale);
|
|
1124
|
+
}
|
|
1125
|
+
const steps = prepared.filter(({ option }) => approved === void 0 || approved.keys.includes(option.key)).map(({ option, checked }) => ({
|
|
1126
|
+
named: { key: option.key, label: option.label, id: option.id },
|
|
1127
|
+
claim: option.id,
|
|
1128
|
+
prepared: checked
|
|
1129
|
+
}));
|
|
1130
|
+
const run = await runTakes(
|
|
1131
|
+
steps,
|
|
1132
|
+
{
|
|
1133
|
+
// EACH OPTION AT ITS LIVE PRICE: the plan is what the set will cost,
|
|
1134
|
+
// not what its ceilings allow. One its seller refuses there (the
|
|
1135
|
+
// prompt, the price) is its own entry, with nothing paid.
|
|
1136
|
+
price: async (claimed) => Promise.all(
|
|
1137
|
+
claimed.map(async (step) => {
|
|
1138
|
+
const quote = await quoteTake(step.prepared, deps);
|
|
1139
|
+
if (!("refused" in quote)) return quote.atomic;
|
|
1140
|
+
const { outcome, result } = quote.refused;
|
|
1141
|
+
if (outcome !== null) reportOutcome(reportDeps, step.claim, outcome, startedAt);
|
|
1142
|
+
return { refused: result };
|
|
1143
|
+
})
|
|
1144
|
+
),
|
|
1145
|
+
words: (planned) => choicesOf(
|
|
1146
|
+
planned.map(({ step }) => String(step.named.label)),
|
|
1147
|
+
planned.map(({ amountAtomic }) => amountAtomic)
|
|
1148
|
+
),
|
|
1149
|
+
call: (planned) => ({
|
|
1150
|
+
kind: "choices",
|
|
1151
|
+
id,
|
|
1152
|
+
kept,
|
|
1153
|
+
specs,
|
|
1154
|
+
keys: planned.map(({ step }) => String(step.named.key)),
|
|
1155
|
+
input
|
|
1156
|
+
}),
|
|
1157
|
+
...approved !== void 0 ? { approved: approved.slots } : {}
|
|
1158
|
+
},
|
|
1159
|
+
deps,
|
|
1160
|
+
reportDeps,
|
|
1161
|
+
settings,
|
|
1162
|
+
{
|
|
1163
|
+
stopped: (planned, outcome) => stopped(
|
|
1164
|
+
planned.map((step) => ({ id: step.claim })),
|
|
1165
|
+
outcome
|
|
1166
|
+
),
|
|
1167
|
+
refuse,
|
|
1168
|
+
pickOne: "pick one choice"
|
|
1169
|
+
}
|
|
1170
|
+
);
|
|
1171
|
+
if ("refused" in run) return run.refused;
|
|
1172
|
+
const ranAny = run.ran.some((each) => !("earlier" in each));
|
|
1173
|
+
if (!ranAny) {
|
|
1174
|
+
const earlier = run.ran.flatMap((each) => "earlier" in each ? [each] : []);
|
|
1175
|
+
const allRan = earlier.every(
|
|
1176
|
+
({ earlier: claim }) => claim.state === "paid" || claim.state === "possibly_paid"
|
|
1177
|
+
);
|
|
1178
|
+
return refuse(
|
|
1179
|
+
"needs_input",
|
|
1180
|
+
allRan ? "Every choice in this set already ran under its own id, so nothing was paid this time. Their results are in the earlier request result." : earlier.map(
|
|
1181
|
+
({ step, earlier: claim }) => `${String(step.named.label)}: ${String(alreadyPaid(step.claim, step.prepared.spec, claim).envelope.reason)}`
|
|
1182
|
+
).join(" "),
|
|
1183
|
+
{
|
|
1184
|
+
nextStep: "For another run, send request({query}) for a new offer; each choice pays once."
|
|
1185
|
+
}
|
|
1186
|
+
);
|
|
1187
|
+
}
|
|
1188
|
+
const set = takesResult(entriesOf(run.ran), {
|
|
1189
|
+
head: `Ran ${run.claimed} of ${steps.length} choices`,
|
|
1190
|
+
nextStep: COMPARE_NEXT_STEP,
|
|
1191
|
+
envelope: { choice: ALL_CHOICES }
|
|
1192
|
+
});
|
|
1193
|
+
await footer.done(String(set.envelope.status), {
|
|
1194
|
+
price: `$${toMoney(paidHere(run.ran).toString()).usd}`
|
|
1195
|
+
});
|
|
1196
|
+
return set;
|
|
1197
|
+
}
|
|
1198
|
+
var TAKES_NEXT_STEP = "Open each saved file, say which take fits the request best and why, and let the user pick.";
|
|
1199
|
+
async function runCount(id, spec, input, count, deps, footer, reportDeps, settings, approved) {
|
|
1200
|
+
const startedAt = Date.now();
|
|
1201
|
+
const refuse = async (status2, reason, extras) => {
|
|
1202
|
+
await footer.done(status2);
|
|
1203
|
+
return fail(status2, reason, extras);
|
|
1204
|
+
};
|
|
1205
|
+
const stale = await settingsRefusal(deps.ctx.dataDir, [spec.settingsHash]);
|
|
1206
|
+
if (stale !== null) {
|
|
1207
|
+
await footer.done("needs_input");
|
|
1208
|
+
return settingsFail(stale);
|
|
1209
|
+
}
|
|
1210
|
+
const checked = await prepareSpec(id, spec, input, footer, reportDeps);
|
|
1211
|
+
if ("refused" in checked) return checked.refused;
|
|
1212
|
+
const steps = Array.from({ length: count }, (_, index) => {
|
|
1213
|
+
const n = index + 1;
|
|
1214
|
+
const claim = n === 1 ? id : `${id}#${n}`;
|
|
1215
|
+
return {
|
|
1216
|
+
named: { take: n },
|
|
1217
|
+
claim,
|
|
1218
|
+
prepared: checked.prepared,
|
|
1219
|
+
take: { n, claim, report: false }
|
|
1220
|
+
};
|
|
1221
|
+
});
|
|
1222
|
+
const run = await runTakes(
|
|
1223
|
+
steps,
|
|
1224
|
+
{
|
|
1225
|
+
// THE LIVE PRICE, ONCE, for the takes still to run: the number a single
|
|
1226
|
+
// call of this input is planned at, so a price that varies by input is
|
|
1227
|
+
// planned at what this input costs, not at the spec's ceiling.
|
|
1228
|
+
price: async (claimed) => {
|
|
1229
|
+
const quoted = await quoteTake(checked.prepared, deps);
|
|
1230
|
+
if (!("refused" in quoted)) return claimed.map(() => quoted.atomic);
|
|
1231
|
+
const { outcome: outcome2, result } = quoted.refused;
|
|
1232
|
+
if (outcome2 !== null) reportOutcome(reportDeps, id, outcome2, startedAt);
|
|
1233
|
+
await footer.done(String(result.envelope.status));
|
|
1234
|
+
return { stop: result };
|
|
1235
|
+
},
|
|
1236
|
+
words: (planned) => takesOf(
|
|
1237
|
+
spec.provider,
|
|
1238
|
+
planned.map(({ amountAtomic }) => amountAtomic)
|
|
1239
|
+
),
|
|
1240
|
+
call: () => ({ kind: "count", id, spec, input, count }),
|
|
1241
|
+
...approved !== void 0 ? { approved } : {}
|
|
1242
|
+
},
|
|
1243
|
+
deps,
|
|
1244
|
+
reportDeps,
|
|
1245
|
+
settings,
|
|
1246
|
+
{
|
|
1247
|
+
stopped: (_claimed, outcome2) => reportOutcome(reportDeps, id, outcome2, startedAt),
|
|
1248
|
+
refuse,
|
|
1249
|
+
pickOne: "run fewer takes"
|
|
1250
|
+
}
|
|
1251
|
+
);
|
|
1252
|
+
if ("refused" in run) return run.refused;
|
|
1253
|
+
if (run.claimed === 0) {
|
|
1254
|
+
const running = await runningJob(deps.ctx.dataDir, id);
|
|
1255
|
+
return refuse(
|
|
1256
|
+
"needs_input",
|
|
1257
|
+
`Every one of these ${count} takes already ran under this id, so nothing was paid this time. Their results are in the earlier request result.`,
|
|
1258
|
+
{
|
|
1259
|
+
nextStep: running !== void 0 ? `Call request({job: ${JSON.stringify(running)}}) for the takes still running; nothing more is paid.` : `For more takes, send request({query}) for a new offer; this id (${id}) pays once per take.`
|
|
1260
|
+
}
|
|
1261
|
+
);
|
|
1262
|
+
}
|
|
1263
|
+
const ranHere = run.ran.flatMap((each) => "paid" in each ? [each] : []);
|
|
1264
|
+
const set = takesResult(entriesOf(run.ran), {
|
|
1265
|
+
head: `Ran ${run.claimed} of ${count} takes`,
|
|
1266
|
+
nextStep: TAKES_NEXT_STEP,
|
|
1267
|
+
envelope: { count }
|
|
1268
|
+
});
|
|
1269
|
+
const status = String(set.envelope.status);
|
|
1270
|
+
const outcome = status === "fulfilled" || status === "partial" ? { status: "fulfilled" } : status === "running" ? { status: "running" } : ranHere.some(({ paid }) => paid.outcome?.status === "failed") ? { status: "failed" } : ranHere.find(({ paid }) => paid.outcome !== null)?.paid.outcome ?? null;
|
|
1271
|
+
if (outcome !== null) reportOutcome(reportDeps, id, outcome, startedAt);
|
|
1272
|
+
await footer.done(status, { price: `$${toMoney(paidHere(run.ran).toString()).usd}` });
|
|
1273
|
+
return set;
|
|
1274
|
+
}
|
|
1275
|
+
async function quoteTake(prepared, deps) {
|
|
1276
|
+
const { spec, built } = prepared;
|
|
1277
|
+
try {
|
|
1278
|
+
const atomic = await quoteRouterCall(
|
|
1279
|
+
{
|
|
1280
|
+
url: built.url,
|
|
1281
|
+
method: built.method,
|
|
1282
|
+
headers: built.headers,
|
|
1283
|
+
...built.specHeaders !== void 0 ? { specHeaders: built.specHeaders } : {},
|
|
1284
|
+
...built.body !== void 0 ? { rawBody: built.body } : {},
|
|
1285
|
+
// The probe the call itself makes waits as long as its spec says.
|
|
1286
|
+
...spec.timeoutS !== void 0 ? { timeoutMs: spec.timeoutS * 1e3 } : {},
|
|
1287
|
+
terms: specTerms(spec)
|
|
1288
|
+
},
|
|
1289
|
+
deps.ctx,
|
|
1290
|
+
// The same seams, and the same wallet, the paid leg is given.
|
|
1291
|
+
{
|
|
1292
|
+
...deps.payDeps ?? {},
|
|
1293
|
+
...deps.provider !== void 0 ? { provider: deps.provider } : {}
|
|
1294
|
+
}
|
|
1295
|
+
);
|
|
1296
|
+
return { atomic };
|
|
1297
|
+
} catch (err) {
|
|
1298
|
+
const cli = err instanceof CliError ? err : void 0;
|
|
1299
|
+
const detail = cli?.details ?? {};
|
|
1300
|
+
const rejectedInput = detail.status === 400 || detail.status === 422;
|
|
1301
|
+
const live = detail.live?.amount;
|
|
1302
|
+
const overCeiling = spec.priceVaries && cli?.code === "REGISTRY_MISMATCH" && live !== void 0 && /^\d+$/.test(live);
|
|
1303
|
+
const reason = overCeiling ? `${spec.provider} prices this input at $${toMoney(live).usd}, over this spec's $${toMoney(spec.maxAmountAtomic).usd} ceiling, so nothing was signed. Change the input and call again with the same id.` : rejectedInput ? `${spec.provider} rejected this input before any payment (HTTP ${String(detail.status)}): see providerError. Fix the input and call again with the same id.` : cli !== void 0 ? `${cli.message} ${agentFixOf(cli)}`.trim() : String(err);
|
|
1304
|
+
const status = cli?.code === "POLICY_REFUSED" ? "needs_approval" : "failed";
|
|
1305
|
+
return {
|
|
1306
|
+
refused: {
|
|
1307
|
+
outcome: failureOutcome(err, { mayHaveMoved: false, rejectedInput }),
|
|
1308
|
+
result: fail(status, reason, {
|
|
1309
|
+
...typeof detail.status === "number" ? { providerStatus: detail.status } : {},
|
|
1310
|
+
...typeof detail.providerError === "string" ? { providerError: detail.providerError } : {},
|
|
1311
|
+
request: { method: built.method, url: built.url },
|
|
1312
|
+
parameters: prepared.sentInput,
|
|
1313
|
+
...overCeiling || rejectedInput ? { nextStep: "Change the input and call again with the same id." } : {}
|
|
1314
|
+
})
|
|
1315
|
+
}
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// src/router/inline-media.ts
|
|
1321
|
+
var MIN_INLINE_BYTES = 1024;
|
|
1322
|
+
var MAX_DEPTH = 8;
|
|
1323
|
+
var DATA_URI = /^data:([^;,]*)[^,]*;base64,/i;
|
|
1324
|
+
var BASE64_KEY = /base64|^b64(?:_json)?$/i;
|
|
1325
|
+
var BASE64 = /^[A-Za-z0-9+/_-]+={0,2}$/;
|
|
1326
|
+
var MEDIA_TYPE = /^[a-z0-9][\w.+-]*\/[\w.+-]+$/i;
|
|
1327
|
+
var TYPE_KEYS = /* @__PURE__ */ new Set(["mediatype", "mimetype", "contenttype"]);
|
|
1328
|
+
async function saveInlineMedia(bodyText, save, limit = MAX_MEDIA_FILES) {
|
|
1329
|
+
try {
|
|
1330
|
+
const root = JSON.parse(bodyText);
|
|
1331
|
+
const found = [];
|
|
1332
|
+
collect(root, void 0, void 0, 0, found, limit);
|
|
1333
|
+
const savedFiles = [];
|
|
1334
|
+
for (const file of found) {
|
|
1335
|
+
const path = await save(file.bytes, file.contentType).catch(() => null);
|
|
1336
|
+
if (path === null) continue;
|
|
1337
|
+
savedFiles.push(path);
|
|
1338
|
+
const note = `[inline file saved to ${path} (${file.contentType}, ${file.bytes.byteLength} bytes)]`;
|
|
1339
|
+
if (Array.isArray(file.holder)) file.holder[file.key] = note;
|
|
1340
|
+
else file.holder[file.key] = note;
|
|
1341
|
+
}
|
|
1342
|
+
if (savedFiles.length === 0) return null;
|
|
1343
|
+
return { bodyText: JSON.stringify(root), savedFiles };
|
|
1344
|
+
} catch {
|
|
1345
|
+
return null;
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
function collect(value, at, named, depth, found, limit) {
|
|
1349
|
+
if (found.length >= limit || depth > MAX_DEPTH) return;
|
|
1350
|
+
if (typeof value === "string") {
|
|
1351
|
+
if (at === void 0) return;
|
|
1352
|
+
const file = inlineFile(value, named);
|
|
1353
|
+
if (file !== null) found.push({ ...at, ...file });
|
|
1354
|
+
return;
|
|
1355
|
+
}
|
|
1356
|
+
if (Array.isArray(value)) {
|
|
1357
|
+
value.forEach(
|
|
1358
|
+
(item, index) => collect(item, { holder: value, key: index }, named, depth + 1, found, limit)
|
|
1359
|
+
);
|
|
1360
|
+
return;
|
|
1361
|
+
}
|
|
1362
|
+
if (value === null || typeof value !== "object") return;
|
|
1363
|
+
const object = value;
|
|
1364
|
+
for (const [key, item] of Object.entries(object)) {
|
|
1365
|
+
collect(item, { holder: object, key }, { key, siblings: object }, depth + 1, found, limit);
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
function inlineFile(text, named) {
|
|
1369
|
+
if (text.length < Math.ceil(MIN_INLINE_BYTES * 4 / 3)) return null;
|
|
1370
|
+
const uri = DATA_URI.exec(text);
|
|
1371
|
+
const payload = uri !== null ? text.slice(uri[0].length) : text;
|
|
1372
|
+
const bytes = decoded(payload);
|
|
1373
|
+
if (bytes === null) return null;
|
|
1374
|
+
const magic = sniff(bytes);
|
|
1375
|
+
if (uri === null && magic === null && !BASE64_KEY.test(named?.key ?? "")) return null;
|
|
1376
|
+
const declared = uri?.[1] !== void 0 && MEDIA_TYPE.test(uri[1]) ? uri[1] : siblingType(named);
|
|
1377
|
+
return {
|
|
1378
|
+
bytes,
|
|
1379
|
+
contentType: (declared ?? magic ?? "application/octet-stream").toLowerCase()
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
function decoded(payload) {
|
|
1383
|
+
const compact = payload.replace(/[\r\n]+/g, "");
|
|
1384
|
+
if (!BASE64.test(compact)) return null;
|
|
1385
|
+
const bytes = Buffer.from(compact, "base64");
|
|
1386
|
+
return bytes.byteLength >= MIN_INLINE_BYTES ? new Uint8Array(bytes) : null;
|
|
1387
|
+
}
|
|
1388
|
+
function siblingType(named) {
|
|
1389
|
+
if (named === void 0) return void 0;
|
|
1390
|
+
for (const [key, value] of Object.entries(named.siblings)) {
|
|
1391
|
+
if (!TYPE_KEYS.has(key.replace(/_/g, "").toLowerCase())) continue;
|
|
1392
|
+
if (typeof value === "string" && MEDIA_TYPE.test(value.trim())) return value.trim();
|
|
1393
|
+
}
|
|
1394
|
+
return void 0;
|
|
1395
|
+
}
|
|
1396
|
+
function sniff(bytes) {
|
|
1397
|
+
const ascii = (from, to) => Buffer.from(bytes.subarray(from, to)).toString("latin1");
|
|
1398
|
+
const starts = (...sig) => sig.every((byte, i) => bytes[i] === byte);
|
|
1399
|
+
if (starts(137, 80, 78, 71, 13, 10, 26, 10)) return "image/png";
|
|
1400
|
+
if (starts(255, 216, 255)) return "image/jpeg";
|
|
1401
|
+
if (ascii(0, 6) === "GIF87a" || ascii(0, 6) === "GIF89a") return "image/gif";
|
|
1402
|
+
if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP") return "image/webp";
|
|
1403
|
+
if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WAVE") return "audio/wav";
|
|
1404
|
+
if (ascii(4, 8) === "ftyp") {
|
|
1405
|
+
const brand = ascii(8, 12);
|
|
1406
|
+
if (brand === "qt ") return "video/quicktime";
|
|
1407
|
+
if (brand === "M4A ") return "audio/mp4";
|
|
1408
|
+
return "video/mp4";
|
|
1409
|
+
}
|
|
1410
|
+
if (starts(26, 69, 223, 163)) return "video/webm";
|
|
1411
|
+
if (ascii(0, 4) === "OggS") return "audio/ogg";
|
|
1412
|
+
if (ascii(0, 4) === "fLaC") return "audio/flac";
|
|
1413
|
+
if (ascii(0, 5) === "%PDF-") return "application/pdf";
|
|
1414
|
+
if (ascii(0, 3) === "ID3") return "audio/mpeg";
|
|
1415
|
+
if (bytes[0] === 255 && ((bytes[1] ?? 0) & 224) === 224) return "audio/mpeg";
|
|
1416
|
+
return null;
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// src/router/job-store.ts
|
|
1420
|
+
import { lstat } from "node:fs/promises";
|
|
1421
|
+
import { join as join2 } from "node:path";
|
|
1422
|
+
var MAX_TAKES = 5;
|
|
1423
|
+
var MAX_RECORD_BYTES = 256 * 1024;
|
|
1424
|
+
var KEPT_RESULT_CHARS = 8e3;
|
|
1425
|
+
var UNREADABLE_TTL_MS = 49 * 60 * 6e4;
|
|
1426
|
+
var Iso = external_exports.string().max(40);
|
|
1427
|
+
var Digits2 = external_exports.string().regex(/^\d+$/);
|
|
1428
|
+
var Authorization = external_exports.strictObject({
|
|
1429
|
+
from: external_exports.string().max(64),
|
|
1430
|
+
nonce: external_exports.string().max(80),
|
|
1431
|
+
validBefore: Digits2,
|
|
1432
|
+
network: external_exports.string().max(64).optional(),
|
|
1433
|
+
asset: external_exports.string().max(200).optional()
|
|
1434
|
+
});
|
|
1435
|
+
var TakeSchema = external_exports.strictObject({
|
|
1436
|
+
version: external_exports.literal(1),
|
|
1437
|
+
offerId: external_exports.string().min(1).max(200),
|
|
1438
|
+
take: external_exports.number().int().min(1).max(MAX_TAKES),
|
|
1439
|
+
poll: external_exports.strictObject({
|
|
1440
|
+
url: external_exports.string().min(1).max(2048),
|
|
1441
|
+
method: external_exports.enum(["GET", "POST"]),
|
|
1442
|
+
body: external_exports.string().max(64 * 1024).optional()
|
|
1443
|
+
}),
|
|
1444
|
+
job: JobSchema,
|
|
1445
|
+
/** What finishing the call needs once its spec is gone. */
|
|
1446
|
+
call: external_exports.strictObject({
|
|
1447
|
+
capabilityId: external_exports.string().min(1).max(200),
|
|
1448
|
+
provider: external_exports.string().min(1).max(120),
|
|
1449
|
+
url: external_exports.string().min(1).max(16384),
|
|
1450
|
+
media: external_exports.boolean(),
|
|
1451
|
+
sent: external_exports.string().max(8192),
|
|
1452
|
+
terms: external_exports.strictObject({
|
|
1453
|
+
source: external_exports.string().max(200).optional(),
|
|
1454
|
+
maxAmountAtomic: Digits2,
|
|
1455
|
+
payTo: external_exports.string().max(200).optional(),
|
|
1456
|
+
network: external_exports.string().max(64).optional(),
|
|
1457
|
+
asset: external_exports.string().max(200).optional()
|
|
1458
|
+
}),
|
|
1459
|
+
resultSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
|
|
1460
|
+
outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
|
|
1461
|
+
}),
|
|
1462
|
+
submittedAt: Iso,
|
|
1463
|
+
expiresAt: Iso,
|
|
1464
|
+
amountAtomic: Digits2,
|
|
1465
|
+
/** The wallet that signed the submit's payment, whatever its scheme: the
|
|
1466
|
+
* only wallet a seller's sign-in on a poll is answered with. A take from
|
|
1467
|
+
* before has none; its authorization's `from` stands in. */
|
|
1468
|
+
payer: external_exports.string().max(64).optional(),
|
|
1469
|
+
/** The submit's authorization, which its ledger row is found by. */
|
|
1470
|
+
authorization: Authorization.optional(),
|
|
1471
|
+
/** The submit's settlement, when the seller named it: paid for certain. */
|
|
1472
|
+
txHash: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).optional(),
|
|
1473
|
+
/** The chain showed the submit's authorization used when its paid leg was
|
|
1474
|
+
* cut off: paid for certain, with no tx named. */
|
|
1475
|
+
settled: external_exports.boolean().optional(),
|
|
1476
|
+
/** The submit's HTTP status. */
|
|
1477
|
+
httpStatus: external_exports.number().int().optional(),
|
|
1478
|
+
state: external_exports.enum(["running", "done", "failed", "expired"]),
|
|
1479
|
+
savedFiles: external_exports.array(external_exports.string().max(4096)).max(16),
|
|
1480
|
+
/** What the agent was handed when the take finished, cut short. */
|
|
1481
|
+
result: external_exports.string().max(KEPT_RESULT_CHARS + 16).optional(),
|
|
1482
|
+
/** That result missed its success rule, or the rule could not be run. */
|
|
1483
|
+
resultUnverified: external_exports.boolean().optional(),
|
|
1484
|
+
/** Why, as the agent was told. */
|
|
1485
|
+
resultCaveat: external_exports.string().max(1e3).optional(),
|
|
1486
|
+
/** Why a take failed, or why it stopped. */
|
|
1487
|
+
reason: external_exports.string().max(1e3).optional(),
|
|
1488
|
+
/** The seller's own words for it, bounded and redacted. Untrusted text. */
|
|
1489
|
+
said: external_exports.string().max(1e3).optional(),
|
|
1490
|
+
/** An unsigned status URL the agent may open itself. Seller text. */
|
|
1491
|
+
statusUrl: external_exports.string().max(2048).optional()
|
|
1492
|
+
});
|
|
1493
|
+
function takePath(dataDir, offerId, take) {
|
|
1494
|
+
return join2(jobsDir(dataDir), `${sha256Hex(offerId)}.${take}.json`);
|
|
1495
|
+
}
|
|
1496
|
+
async function writeTake(dataDir, take) {
|
|
1497
|
+
await writePrivate(takePath(dataDir, take.offerId, take.take), JSON.stringify(take));
|
|
1498
|
+
void pruneJobs(dataDir, Date.now());
|
|
1499
|
+
}
|
|
1500
|
+
async function readTake(dataDir, offerId, take) {
|
|
1501
|
+
const parsed = TakeSchema.safeParse(
|
|
1502
|
+
await readJsonFile(takePath(dataDir, offerId, take), MAX_RECORD_BYTES)
|
|
1503
|
+
);
|
|
1504
|
+
return parsed.success && parsed.data.offerId === offerId && parsed.data.take === take ? parsed.data : null;
|
|
1505
|
+
}
|
|
1506
|
+
async function readTakes(dataDir, offerId) {
|
|
1507
|
+
const takes = [];
|
|
1508
|
+
for (let n = 1; n <= MAX_TAKES; n += 1) {
|
|
1509
|
+
const take = await readTake(dataDir, offerId, n);
|
|
1510
|
+
if (take !== null) takes.push(take);
|
|
1511
|
+
}
|
|
1512
|
+
return takes;
|
|
1513
|
+
}
|
|
1514
|
+
async function updateTake(dataDir, offerId, take, change) {
|
|
1515
|
+
const path = takePath(dataDir, offerId, take);
|
|
1516
|
+
return withFileLock(
|
|
1517
|
+
`${path}.lock`,
|
|
1518
|
+
async () => {
|
|
1519
|
+
const current = await readTake(dataDir, offerId, take);
|
|
1520
|
+
if (current === null) return null;
|
|
1521
|
+
const next = await change(current);
|
|
1522
|
+
if (next === null) return null;
|
|
1523
|
+
await writeTake(dataDir, next);
|
|
1524
|
+
return next;
|
|
1525
|
+
},
|
|
1526
|
+
{ timeoutMs: 3e4 }
|
|
1527
|
+
);
|
|
1528
|
+
}
|
|
1529
|
+
async function endTake(dataDir, offerId, take, ending) {
|
|
1530
|
+
let ended = null;
|
|
1531
|
+
const written = await updateTake(dataDir, offerId, take, (current) => {
|
|
1532
|
+
if (current.state !== "running") {
|
|
1533
|
+
ended = current;
|
|
1534
|
+
return null;
|
|
1535
|
+
}
|
|
1536
|
+
return { ...current, ...ending };
|
|
1537
|
+
});
|
|
1538
|
+
if (written !== null) return { won: true, take: written };
|
|
1539
|
+
return ended !== null ? { won: false, take: ended } : null;
|
|
1540
|
+
}
|
|
1541
|
+
async function pruneJobs(dataDir, now) {
|
|
1542
|
+
await sweep(jobsDir(dataDir), async (name, path) => {
|
|
1543
|
+
if (!/^[0-9a-f]{64}\.\d\.json$/.test(name)) return false;
|
|
1544
|
+
const parsed = TakeSchema.safeParse(await readJsonFile(path, MAX_RECORD_BYTES));
|
|
1545
|
+
if (parsed.success) return Date.parse(parsed.data.expiresAt) < now;
|
|
1546
|
+
return now - (await lstat(path)).mtimeMs > UNREADABLE_TTL_MS;
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
// src/router/tool.ts
|
|
1551
|
+
var MAX_CALL_DOWNLOAD_BYTES = 1024 * 1024 * 1024;
|
|
1552
|
+
var CAP_REACHED = `not saved: this call already saved ${Math.round(MAX_CALL_DOWNLOAD_BYTES / 1048576)} MB, its cap`;
|
|
1553
|
+
var DOWNLOAD_FAILED = "a file it links to failed to download";
|
|
1554
|
+
async function runRequestTool(args, deps) {
|
|
1555
|
+
const routes = [];
|
|
1556
|
+
const { route } = deps;
|
|
1557
|
+
const call = {
|
|
1558
|
+
...deps,
|
|
1559
|
+
startedAt: deps.startedAt ?? (deps.now ?? Date.now)(),
|
|
1560
|
+
downloads: deps.downloads ?? { leftBytes: MAX_CALL_DOWNLOAD_BYTES }
|
|
1561
|
+
};
|
|
1562
|
+
const result = await requestTool(
|
|
1563
|
+
args,
|
|
1564
|
+
route === void 0 ? call : {
|
|
1565
|
+
...call,
|
|
1566
|
+
route: (baseUrl) => {
|
|
1567
|
+
const picked = route(baseUrl);
|
|
1568
|
+
routes.push(picked);
|
|
1569
|
+
return picked;
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
);
|
|
1573
|
+
const terms = routes.length > 0 ? await termsNotice(deps.ctx.dataDir) : null;
|
|
1574
|
+
const deposited = routes.reduce((sum, r) => sum + (r.deposited?.() ?? 0n), 0n);
|
|
1575
|
+
const notices = [terms, deposited > 0n ? depositSentence(deposited) : null].filter(
|
|
1576
|
+
(notice) => notice !== null
|
|
1577
|
+
);
|
|
1578
|
+
return notices.length > 0 ? { ...result, summary: [result.summary, ...notices].join("\n") } : result;
|
|
1579
|
+
}
|
|
1580
|
+
async function runApproveTool(args, deps) {
|
|
1581
|
+
const here = await routerHere(deps);
|
|
1582
|
+
if ("off" in here) return fail("needs_input", here.off, { nextStep: ROUTER_OFF_NEXT_STEP });
|
|
1583
|
+
const { dataDir } = deps.ctx;
|
|
1584
|
+
const now = deps.now ?? Date.now;
|
|
1585
|
+
const fresh = "Call request again with the same call for a fresh quote.";
|
|
1586
|
+
const quote = await readQuote(dataDir, args.quote.trim());
|
|
1587
|
+
const call = quote !== null ? quotedCall(quote) : null;
|
|
1588
|
+
if (quote === null || call === null) {
|
|
1589
|
+
return fail(
|
|
1590
|
+
"needs_input",
|
|
1591
|
+
"No quote is kept on this machine under that id, so nothing was paid.",
|
|
1592
|
+
{ nextStep: fresh }
|
|
1593
|
+
);
|
|
1594
|
+
}
|
|
1595
|
+
const closed = quoteClosed(quote, now());
|
|
1596
|
+
if (closed !== null) {
|
|
1597
|
+
return fail(
|
|
1598
|
+
"needs_input",
|
|
1599
|
+
closed === "used" ? "That quote already ran, and a quote pays once, so nothing more was paid." : "That quote expired (a quote waits ten minutes for a yes), so nothing was paid.",
|
|
1600
|
+
{
|
|
1601
|
+
nextStep: closed === "used" ? "Its result is in the approve call that ran it." : fresh
|
|
1602
|
+
}
|
|
1603
|
+
);
|
|
1604
|
+
}
|
|
1605
|
+
const total = BigInt(quote.totalAtomic);
|
|
1606
|
+
const echoedTotal = args.total !== void 0 ? usdAtomic(args.total) : void 0;
|
|
1607
|
+
if (args.total !== void 0 && echoedTotal !== total || args.what !== void 0 && args.what.trim() !== quote.what) {
|
|
1608
|
+
return fail(
|
|
1609
|
+
"needs_input",
|
|
1610
|
+
`That quote is for ${quote.what}, $${toMoney(quote.totalAtomic).usd} in total, not what this call said, so nothing was paid.`,
|
|
1611
|
+
{ quote: quoteView(quote), nextStep: `Call ${approveCall(quote)}.` }
|
|
1612
|
+
);
|
|
1613
|
+
}
|
|
1614
|
+
if (args.total === void 0 || args.what === void 0) {
|
|
1615
|
+
return fail(
|
|
1616
|
+
"needs_input",
|
|
1617
|
+
"Send the quote's total and what it buys with it, so the user sees them when asked; nothing was paid.",
|
|
1618
|
+
{ quote: quoteView(quote), nextStep: `Call ${approveCall(quote)}.` }
|
|
1619
|
+
);
|
|
1620
|
+
}
|
|
1621
|
+
const stale = await settingsRefusal(dataDir, quotedHashes(call));
|
|
1622
|
+
if (stale !== null) return settingsFail(stale);
|
|
1623
|
+
const provider = paymentProvider(deps);
|
|
1624
|
+
try {
|
|
1625
|
+
await provider.getSigner();
|
|
1626
|
+
} catch (err) {
|
|
1627
|
+
if (!(err instanceof CliError)) throw err;
|
|
1628
|
+
return fail(
|
|
1629
|
+
"failed",
|
|
1630
|
+
`${quote.sentence} ${err.message} No payment was signed. ${agentFixOf(err)}`.trim(),
|
|
1631
|
+
{ nextStep: "Tell the user. The quote waits for its ten minutes; nothing was paid." }
|
|
1632
|
+
);
|
|
1633
|
+
}
|
|
1634
|
+
const call_ = {
|
|
1635
|
+
...deps,
|
|
1636
|
+
provider,
|
|
1637
|
+
startedAt: deps.startedAt ?? now(),
|
|
1638
|
+
downloads: deps.downloads ?? { leftBytes: MAX_CALL_DOWNLOAD_BYTES }
|
|
1639
|
+
};
|
|
1640
|
+
const settings = await resolveContextSettings(deps.ctx);
|
|
1641
|
+
const admitted = await admitQuote(dataDir, quote.id, {
|
|
1642
|
+
now
|
|
1643
|
+
});
|
|
1644
|
+
if ("refused" in admitted) {
|
|
1645
|
+
return fail(
|
|
1646
|
+
"needs_input",
|
|
1647
|
+
admitted.refused === "used" ? "That quote already ran, and a quote pays once, so nothing more was paid." : "That quote can no longer run, so nothing was paid.",
|
|
1648
|
+
{ nextStep: fresh }
|
|
1649
|
+
);
|
|
1650
|
+
}
|
|
1651
|
+
const slots = admitted.admitted;
|
|
1652
|
+
const reportDeps = {
|
|
1653
|
+
ctx: deps.ctx,
|
|
1654
|
+
baseUrl: settings.baseUrl,
|
|
1655
|
+
...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
|
|
1656
|
+
};
|
|
1657
|
+
const footer = await openLookupFooter(dataDir, call.kind !== "call" ? { id: call.id } : {});
|
|
1658
|
+
await footer.routing();
|
|
1659
|
+
const result = await runQuoted(call, slots, call_, footer, reportDeps, settings);
|
|
1660
|
+
const reopened = await reopenShortQuote(dataDir, quote.id, slots, {
|
|
1661
|
+
now,
|
|
1662
|
+
releaseClaims: async () => {
|
|
1663
|
+
for (const slot of slots) {
|
|
1664
|
+
const held = claimOfSlot.get(slot);
|
|
1665
|
+
if (held !== void 0) await releaseSpecClaim(dataDir, held.claim, held.owner);
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
});
|
|
1669
|
+
if (!reopened) return result;
|
|
1670
|
+
return {
|
|
1671
|
+
...result,
|
|
1672
|
+
envelope: {
|
|
1673
|
+
...result.envelope,
|
|
1674
|
+
quote: quoteView(quote),
|
|
1675
|
+
nextStep: `${shortOfFunds(quoteFor(call, slots))} The quote stays open for its ten minutes: once the funds arrive, call ${approveCall(quote)} again.`
|
|
1676
|
+
}
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
function quoteFor(call, slots) {
|
|
1680
|
+
const refused = slots.filter(wasShortOfFunds);
|
|
1681
|
+
const one = (refused.length > 0 ? refused : slots).reduce(
|
|
1682
|
+
(dearest, slot) => slot.amountAtomic > dearest.amountAtomic ? slot : dearest
|
|
1683
|
+
);
|
|
1684
|
+
const priceAtomic = one.amountAtomic;
|
|
1685
|
+
if (call.kind === "call")
|
|
1686
|
+
return { label: call.call.label, provider: call.call.provider, priceAtomic };
|
|
1687
|
+
if (call.kind !== "choices")
|
|
1688
|
+
return { label: call.spec.label, provider: call.spec.provider, priceAtomic };
|
|
1689
|
+
const key = call.keys[slots.indexOf(one)];
|
|
1690
|
+
const spec = call.specs[call.kept.choices.options.findIndex((option) => option.key === key)] ?? call.specs[0];
|
|
1691
|
+
return { label: spec.label, provider: spec.provider, priceAtomic };
|
|
1692
|
+
}
|
|
1693
|
+
async function runQuoted(call, slots, call_, footer, reportDeps, settings) {
|
|
1694
|
+
switch (call.kind) {
|
|
1695
|
+
case "spec":
|
|
1696
|
+
return runSpec(call.id, call.spec, call.input, call_, footer, reportDeps, slots);
|
|
1697
|
+
case "count":
|
|
1698
|
+
return runCount(
|
|
1699
|
+
call.id,
|
|
1700
|
+
call.spec,
|
|
1701
|
+
call.input,
|
|
1702
|
+
call.count,
|
|
1703
|
+
call_,
|
|
1704
|
+
footer,
|
|
1705
|
+
reportDeps,
|
|
1706
|
+
settings,
|
|
1707
|
+
slots
|
|
1708
|
+
);
|
|
1709
|
+
case "choices":
|
|
1710
|
+
return runChoiceSet(call.id, call.kept, call.input, call_, footer, reportDeps, settings, {
|
|
1711
|
+
specs: call.specs,
|
|
1712
|
+
keys: call.keys,
|
|
1713
|
+
slots
|
|
1714
|
+
});
|
|
1715
|
+
case "call":
|
|
1716
|
+
return (await payAndDeliver(call.call, { slot: slots[0] }, call_, footer)).result;
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
function usdAtomic(text) {
|
|
1720
|
+
try {
|
|
1721
|
+
return BigInt(
|
|
1722
|
+
parseUsdToAtomic(
|
|
1723
|
+
text.trim().replace(/^\$/, "").replace(/\s*USD$/i, "")
|
|
1724
|
+
)
|
|
1725
|
+
);
|
|
1726
|
+
} catch {
|
|
1727
|
+
return void 0;
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
async function requestTool(args, deps) {
|
|
1731
|
+
const here = await routerHere(deps);
|
|
1732
|
+
if ("off" in here) return fail("needs_input", here.off, { nextStep: ROUTER_OFF_NEXT_STEP });
|
|
1733
|
+
if (here.settings.wire.status === "invalid" && (args.job === void 0 || args.job === "")) {
|
|
1734
|
+
return settingsFail(UNREADABLE);
|
|
1735
|
+
}
|
|
1736
|
+
const sent = here.settings.wire.status === "ok" ? here.settings.wire.settings : void 0;
|
|
1737
|
+
if (args.source !== void 0) {
|
|
1738
|
+
const others = ["query", "id", "choice", "browse", "count", "job"].filter(
|
|
1739
|
+
(key) => args[key] !== void 0
|
|
1740
|
+
);
|
|
1741
|
+
if (others.length > 0) {
|
|
1742
|
+
return fail("needs_input", "`source` goes with `tool` and `input` alone; nothing was sent.", {
|
|
1743
|
+
nextStep: "Call request({source}) for the account's tools."
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
return (await import("./explicit-ME2NRADQ.js")).runSourceRequest(
|
|
1747
|
+
{
|
|
1748
|
+
source: args.source,
|
|
1749
|
+
...args.tool !== void 0 ? { tool: args.tool } : {},
|
|
1750
|
+
...args.input !== void 0 ? { input: args.input } : {}
|
|
1751
|
+
},
|
|
1752
|
+
deps
|
|
1753
|
+
);
|
|
1754
|
+
}
|
|
1755
|
+
if (args.browse !== void 0 || args.tool !== void 0 && args.query === void 0)
|
|
1756
|
+
return readToolList(args, deps, sent);
|
|
1757
|
+
if (args.tool !== void 0) {
|
|
1758
|
+
if (args.tool.trim().length === 0 || args.tool.trim().length > 200)
|
|
1759
|
+
return fail("needs_input", "`tool` takes a row id from request({browse}).");
|
|
1760
|
+
if (["id", "input", "choice", "count", "job"].some((key) => args[key] !== void 0))
|
|
1761
|
+
return fail("needs_input", "A selected free lookup takes only its tool id and query.");
|
|
1762
|
+
if (mask(args.tool) !== args.tool)
|
|
1763
|
+
return fail("native", "the tool id carries a credential-shaped value, so nothing was sent");
|
|
1764
|
+
}
|
|
1765
|
+
if (args.job !== void 0 && args.job.length > 0) {
|
|
1766
|
+
if (args.input !== void 0 || args.choice !== void 0 || args.count !== void 0) {
|
|
1767
|
+
return fail("needs_input", "A job resumes on its own: send only its id, as `job`.", {
|
|
1768
|
+
nextStep: `Call request({job: ${JSON.stringify(args.job)}}); nothing was sent or paid.`
|
|
1769
|
+
});
|
|
1770
|
+
}
|
|
1771
|
+
return resumeJob(args.job, deps);
|
|
1772
|
+
}
|
|
1773
|
+
const offered = args.id !== void 0 && args.id.length > 0 ? args.id : void 0;
|
|
1774
|
+
if (offered !== void 0) await markTaken(deps.ctx.dataDir, offered);
|
|
1775
|
+
let id = offered;
|
|
1776
|
+
const { input } = args;
|
|
1777
|
+
const choice = args.choice !== void 0 && args.choice.length > 0 ? args.choice : void 0;
|
|
1778
|
+
const count = args.count !== void 0 && args.count !== 1 ? args.count : void 0;
|
|
1779
|
+
if (count !== void 0) {
|
|
1780
|
+
const refusal2 = !Number.isInteger(count) || count < 2 || count > MAX_TAKES ? `count is a whole number of takes from 2 to ${MAX_TAKES}` : choice !== void 0 ? "count runs several takes of one service, so it does not go with a choice" : input === void 0 || offered === void 0 ? "count goes with the offer's id and its filled input" : void 0;
|
|
1781
|
+
if (refusal2 !== void 0) {
|
|
1782
|
+
return fail("needs_input", `${refusal2}; nothing was sent or paid.`);
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
let set;
|
|
1786
|
+
if (choice !== void 0) {
|
|
1787
|
+
const picked = await pickChoice(deps.ctx.dataDir, offered, choice);
|
|
1788
|
+
if ("refused" in picked) return picked.refused;
|
|
1789
|
+
if ("all" in picked) set = picked.all;
|
|
1790
|
+
else id = picked.id;
|
|
1791
|
+
}
|
|
1792
|
+
if (set !== void 0 && input === void 0) return showChoices(id, set);
|
|
1793
|
+
const kept = id !== void 0 && set === void 0 ? await readKeptSpec(deps.ctx.dataDir, id) : null;
|
|
1794
|
+
if (kept?.account === true) {
|
|
1795
|
+
if (count !== void 0) {
|
|
1796
|
+
return fail(
|
|
1797
|
+
"needs_input",
|
|
1798
|
+
`${kept.spec.provider} runs one call at a time on your own account, so count was not used; nothing was sent.`,
|
|
1799
|
+
{ nextStep: `Call request({id: ${JSON.stringify(id)}, input: {...}}) without count.` }
|
|
1800
|
+
);
|
|
1801
|
+
}
|
|
1802
|
+
if (input === void 0)
|
|
1803
|
+
return (await import("./run-JH7ELYAM.js")).showAccountSpec(id, kept.spec, deps.ctx.dataDir);
|
|
1804
|
+
}
|
|
1805
|
+
const spec = kept !== null && kept.account !== true ? kept.spec : null;
|
|
1806
|
+
if (spec !== null && input === void 0) return showSpec(id, spec);
|
|
1807
|
+
if (count !== void 0 && spec !== null && (spec.takes === void 0 || count > spec.takes.max)) {
|
|
1808
|
+
return fail(
|
|
1809
|
+
"needs_input",
|
|
1810
|
+
spec.takes === void 0 ? `${spec.provider} does not run several takes of one call, so count was not used; nothing was sent or paid.` : `${spec.provider} runs at most ${spec.takes.max} takes of one call; nothing was sent or paid.`,
|
|
1811
|
+
{
|
|
1812
|
+
nextStep: `Call request({id: ${JSON.stringify(id)}, input: {...}})${spec.takes === void 0 ? " without count" : ` with count up to ${spec.takes.max}`}.`
|
|
1813
|
+
}
|
|
1814
|
+
);
|
|
1815
|
+
}
|
|
1816
|
+
const query = (args.query ?? "").trim().slice(0, 8e3);
|
|
1817
|
+
if (query.length === 0 && input === void 0) {
|
|
1818
|
+
if (args.tool !== void 0)
|
|
1819
|
+
return fail("needs_input", "Include what to look up in request({tool, query}).");
|
|
1820
|
+
return fail(
|
|
1821
|
+
"needs_input",
|
|
1822
|
+
id !== void 0 ? "No spec is kept for that id (it expired, or its line asked for a query), so send the query its line named with the id, or a query alone." : "A request needs an offer's id, or a query naming the task, its inputs and any constraints."
|
|
1823
|
+
);
|
|
1824
|
+
}
|
|
1825
|
+
if (mask(query) !== query) {
|
|
1826
|
+
return fail("native", "the query carries a credential-shaped value, so nothing was sent");
|
|
1827
|
+
}
|
|
1828
|
+
if (input !== void 0) {
|
|
1829
|
+
if (id === void 0) {
|
|
1830
|
+
return fail(
|
|
1831
|
+
"needs_input",
|
|
1832
|
+
"An input goes with the id from the line that named the service; send both."
|
|
1833
|
+
);
|
|
1834
|
+
}
|
|
1835
|
+
const serialized = JSON.stringify(input);
|
|
1836
|
+
if (Buffer.byteLength(serialized) > MAX_INPUT_BYTES) {
|
|
1837
|
+
return fail("needs_input", `The input is over ${MAX_INPUT_BYTES} bytes; send a smaller one.`);
|
|
1838
|
+
}
|
|
1839
|
+
if (JSON.stringify(maskDeep(input)) !== serialized) {
|
|
1840
|
+
return fail("native", "the input carries a credential-shaped value, so nothing was sent");
|
|
1841
|
+
}
|
|
1842
|
+
if (kept === null && set === void 0) {
|
|
1843
|
+
return fail(
|
|
1844
|
+
"needs_input",
|
|
1845
|
+
"The spec for that offer is no longer kept on this machine (it expired or was pruned), so nothing was sent or paid.",
|
|
1846
|
+
{
|
|
1847
|
+
nextStep: "Inspect the selected tool again with request({tool}) (browse for its tool id if needed), then retry with the fresh id and input. Use request({query}) only to choose a tool again."
|
|
1848
|
+
}
|
|
1849
|
+
);
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
const footer = await openLookupFooter(deps.ctx.dataDir, {
|
|
1853
|
+
...offered !== void 0 ? { id: offered } : {}
|
|
1854
|
+
});
|
|
1855
|
+
await footer.routing();
|
|
1856
|
+
const settings = await resolveContextSettings(deps.ctx);
|
|
1857
|
+
if (args.tool === void 0)
|
|
1858
|
+
void reconcilePayments(deps.ctx.dataDir, {
|
|
1859
|
+
rpcUrl: settings.rpcUrl,
|
|
1860
|
+
...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {},
|
|
1861
|
+
...deps.now !== void 0 ? { now: deps.now } : {}
|
|
1862
|
+
}).catch(() => void 0);
|
|
1863
|
+
const decisionDeps = {
|
|
1864
|
+
ctx: deps.ctx,
|
|
1865
|
+
baseUrl: settings.baseUrl,
|
|
1866
|
+
acceptsBazaar: settings.experimentalBazaar,
|
|
1867
|
+
harness: deps.harness ?? "claude",
|
|
1868
|
+
improve: here.settings.improve.value,
|
|
1869
|
+
// Read from the global file for this call, never cached: a change made
|
|
1870
|
+
// in another process reaches the next call with no restart.
|
|
1871
|
+
...sent !== void 0 ? { settings: sent } : {},
|
|
1872
|
+
...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
|
|
1873
|
+
};
|
|
1874
|
+
if (set !== void 0 && input !== void 0) {
|
|
1875
|
+
return runChoiceSet(id, set, input, deps, footer, decisionDeps, settings);
|
|
1876
|
+
}
|
|
1877
|
+
if (kept?.account === true && input !== void 0) {
|
|
1878
|
+
const { runAccountSpec } = await import("./run-JH7ELYAM.js");
|
|
1879
|
+
return runAccountSpec(id, kept.spec, input, deps, footer, decisionDeps);
|
|
1880
|
+
}
|
|
1881
|
+
if (spec !== null && input !== void 0) {
|
|
1882
|
+
const run = () => count !== void 0 ? runCount(id, spec, input, count, deps, footer, decisionDeps, settings) : runSpec(id, spec, input, deps, footer, decisionDeps);
|
|
1883
|
+
if (kept?.account !== true && kept?.replaces !== void 0) {
|
|
1884
|
+
const { runInPlaceOf } = await import("./run-JH7ELYAM.js");
|
|
1885
|
+
return runInPlaceOf(kept.replaces, id, run, deps.ctx.dataDir);
|
|
1886
|
+
}
|
|
1887
|
+
return run();
|
|
1888
|
+
}
|
|
1889
|
+
const fresh = args.tool !== void 0 ? await requestToolSpec(args.tool.trim(), decisionDeps, query) : await requestDecision(
|
|
1890
|
+
"tool",
|
|
1891
|
+
{ query, ...id !== void 0 ? { id } : {} },
|
|
1892
|
+
{ ...decisionDeps, route: deps.route?.(settings.baseUrl) }
|
|
1893
|
+
);
|
|
1894
|
+
if (fresh.status === "skipped") {
|
|
1895
|
+
await footer.done("native");
|
|
1896
|
+
const lasting = unpaidSentence(fresh.why, "agent", fresh.quotedAtomic);
|
|
1897
|
+
return fail(
|
|
1898
|
+
"native",
|
|
1899
|
+
fresh.why === DEADLINE_AFTER_PAYMENT_SENT ? "A routing payment (possibly the channel deposit) went out, and this call ran out of time before its answer. `tenjin mcp` lets it finish so it is recorded; nothing else was paid." : `${lasting ?? "Tenjin could not pay the routing fee in time for this call (another routing payment was in progress, the wallet was still unlocking, or its balance could not be read); the next call usually routes."} Nothing was routed and no provider was paid.`,
|
|
1900
|
+
{
|
|
1901
|
+
nextStep: lasting !== null ? "Tell the user this once, and use your own tools for now." : "Use your own tools for this one."
|
|
1902
|
+
}
|
|
1903
|
+
);
|
|
1904
|
+
}
|
|
1905
|
+
if (fresh.status === "failed") {
|
|
1906
|
+
await footer.done("failed");
|
|
1907
|
+
return fail("failed", fresh.reason, {
|
|
1908
|
+
...fresh.errorCode !== void 0 ? { errorCode: fresh.errorCode } : {}
|
|
1909
|
+
});
|
|
1910
|
+
}
|
|
1911
|
+
const { decision, note, settingsHash } = fresh.decision;
|
|
1912
|
+
if (args.tool !== void 0) {
|
|
1913
|
+
if (decision.action !== "native" && decision.action !== "needs_input" && (decision.action !== "execute" || decision.capabilityId !== args.tool.trim() || BigInt(decision.providerPriceAtomic) !== 0n)) {
|
|
1914
|
+
await footer.done("failed");
|
|
1915
|
+
return fail(
|
|
1916
|
+
"failed",
|
|
1917
|
+
"The answer is not a runnable free lookup for the selected tool. Nothing was sent to a provider or paid.",
|
|
1918
|
+
{
|
|
1919
|
+
nextStep: "Use your own tools for this lookup.",
|
|
1920
|
+
...note !== void 0 ? { note } : {}
|
|
1921
|
+
}
|
|
1922
|
+
);
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
if (decision.action === "spec") {
|
|
1926
|
+
if (isAccountSpec(decision.spec)) {
|
|
1927
|
+
const lead = { ...decision.spec, id: decision.id };
|
|
1928
|
+
const shown = await (await import("./run-JH7ELYAM.js")).offerAccountLead(lead, settingsHash, deps, decisionDeps, decision.hint);
|
|
1929
|
+
await footer.done("service found");
|
|
1930
|
+
return shown;
|
|
1931
|
+
}
|
|
1932
|
+
const picked = { ...decision.spec, id: decision.id };
|
|
1933
|
+
await storeSpecs(deps.ctx.dataDir, [picked], settingsHash);
|
|
1934
|
+
await footer.done("service found");
|
|
1935
|
+
return showSpec(picked.id, picked, [], decision.hint);
|
|
1936
|
+
}
|
|
1937
|
+
if (decision.action === "discovered") {
|
|
1938
|
+
await storeSpecs(deps.ctx.dataDir, decision.specs, settingsHash);
|
|
1939
|
+
const { choices } = decision;
|
|
1940
|
+
if (choices !== void 0) {
|
|
1941
|
+
await storeChoices(deps.ctx.dataDir, decision.id, { choices, hint: decision.hint });
|
|
1942
|
+
}
|
|
1943
|
+
await footer.done("service found");
|
|
1944
|
+
const picked = decision.specs?.find((spec2) => spec2.id === decision.id);
|
|
1945
|
+
if (picked !== void 0) {
|
|
1946
|
+
const options = new Set(choices?.options.map((option) => option.id));
|
|
1947
|
+
return showSpec(
|
|
1948
|
+
picked.id,
|
|
1949
|
+
picked,
|
|
1950
|
+
decision.specs.filter((spec2) => spec2 !== picked && !options.has(spec2.id)),
|
|
1951
|
+
choices !== void 0 ? decision.hint : void 0
|
|
1952
|
+
);
|
|
1953
|
+
}
|
|
1954
|
+
const { candidate } = decision;
|
|
1955
|
+
return {
|
|
1956
|
+
isError: false,
|
|
1957
|
+
summary: decision.hint,
|
|
1958
|
+
envelope: {
|
|
1959
|
+
status: "discovered",
|
|
1960
|
+
id: decision.id,
|
|
1961
|
+
service: {
|
|
1962
|
+
provider: candidate.provider,
|
|
1963
|
+
url: candidate.url,
|
|
1964
|
+
method: candidate.method,
|
|
1965
|
+
description: candidate.description,
|
|
1966
|
+
price: `$${toMoney(candidate.providerPriceAtomic).usd}`,
|
|
1967
|
+
input: candidate.input
|
|
1968
|
+
},
|
|
1969
|
+
cost: costLines(0n),
|
|
1970
|
+
...note !== void 0 ? { note } : {},
|
|
1971
|
+
providerContentUntrusted: true
|
|
1972
|
+
}
|
|
1973
|
+
};
|
|
1974
|
+
}
|
|
1975
|
+
if (decision.action !== "execute") {
|
|
1976
|
+
await footer.done(decision.action === "native" ? "native" : "needs_input");
|
|
1977
|
+
return fail(
|
|
1978
|
+
decision.action === "native" ? "native" : "needs_input",
|
|
1979
|
+
decision.reason ?? "The router did not select a paid capability.",
|
|
1980
|
+
{ diagnostics: decision.diagnostics, ...note !== void 0 ? { note } : {} }
|
|
1981
|
+
);
|
|
1982
|
+
}
|
|
1983
|
+
const contract = decision.contract;
|
|
1984
|
+
const refusal = checkContract(contract);
|
|
1985
|
+
if (refusal !== null) {
|
|
1986
|
+
await footer.done(refusal.status);
|
|
1987
|
+
return fail(refusal.status, refusal.reason);
|
|
1988
|
+
}
|
|
1989
|
+
const call = {
|
|
1990
|
+
capabilityId: decision.capabilityId,
|
|
1991
|
+
provider: decision.provider,
|
|
1992
|
+
...decision.label !== void 0 ? { label: decision.label } : {},
|
|
1993
|
+
// The free docs lookup, the one answer with no spec: text, never files.
|
|
1994
|
+
media: false,
|
|
1995
|
+
request: contract.request,
|
|
1996
|
+
terms: { source: decision.provider, maxAmountAtomic: decision.providerPriceAtomic },
|
|
1997
|
+
requestKey: `${decision.capabilityId}:${canonicalHash(contract.arguments ?? {})}`,
|
|
1998
|
+
...contract.resultSchema !== void 0 ? { resultSchema: contract.resultSchema } : {},
|
|
1999
|
+
...contract.arguments !== void 0 ? { parameters: contract.arguments } : {},
|
|
2000
|
+
// What the ledger records as sent: the host's input, or its query.
|
|
2001
|
+
sent: input !== void 0 ? JSON.stringify(maskDeep(input)) : query,
|
|
2002
|
+
...note !== void 0 ? { note } : {},
|
|
2003
|
+
...settingsHash !== void 0 ? { settingsHash } : {}
|
|
2004
|
+
};
|
|
2005
|
+
return (await payAndDeliver(call, { alone: { kind: "call", call } }, deps, footer)).result;
|
|
2006
|
+
}
|
|
2007
|
+
async function readToolList(args, deps, sent) {
|
|
2008
|
+
const others = ["query", "id", "input", "choice", "count", "job"].filter(
|
|
2009
|
+
(key) => args[key] !== void 0
|
|
2010
|
+
);
|
|
2011
|
+
if (args.browse !== void 0 && args.tool !== void 0 || others.length > 0) {
|
|
2012
|
+
return fail(
|
|
2013
|
+
"needs_input",
|
|
2014
|
+
"Browse with request({browse}), inspect with request({tool}), or run a free tool with request({tool, query})."
|
|
2015
|
+
);
|
|
2016
|
+
}
|
|
2017
|
+
const words = (args.browse ?? args.tool ?? "").trim().slice(0, 8e3);
|
|
2018
|
+
if (mask(words) !== words) {
|
|
2019
|
+
return fail("native", "the words carry a credential-shaped value, so nothing was sent");
|
|
2020
|
+
}
|
|
2021
|
+
const settings = await resolveContextSettings(deps.ctx);
|
|
2022
|
+
const decisionDeps = {
|
|
2023
|
+
ctx: deps.ctx,
|
|
2024
|
+
baseUrl: settings.baseUrl,
|
|
2025
|
+
acceptsBazaar: settings.experimentalBazaar,
|
|
2026
|
+
harness: deps.harness ?? "claude",
|
|
2027
|
+
...sent !== void 0 ? { settings: sent } : {},
|
|
2028
|
+
...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
|
|
2029
|
+
};
|
|
2030
|
+
if (args.browse !== void 0) {
|
|
2031
|
+
const listed = await requestBrowse(words, decisionDeps);
|
|
2032
|
+
if (listed.status !== "decided") return listFailure(listed);
|
|
2033
|
+
return showRows(listed.decision.rows);
|
|
2034
|
+
}
|
|
2035
|
+
if (words.length === 0) {
|
|
2036
|
+
return fail("needs_input", "`tool` takes a row id from request({browse}).");
|
|
2037
|
+
}
|
|
2038
|
+
const fetched = await requestToolSpec(words, decisionDeps);
|
|
2039
|
+
if (fetched.status !== "decided") return listFailure(fetched);
|
|
2040
|
+
const { decision, settingsHash } = fetched.decision;
|
|
2041
|
+
if (decision.action === "spec") {
|
|
2042
|
+
if (isAccountSpec(decision.spec)) {
|
|
2043
|
+
const lead = { ...decision.spec, id: decision.id };
|
|
2044
|
+
return (await import("./run-JH7ELYAM.js")).offerAccountLead(
|
|
2045
|
+
lead,
|
|
2046
|
+
settingsHash,
|
|
2047
|
+
deps,
|
|
2048
|
+
decisionDeps,
|
|
2049
|
+
decision.hint
|
|
2050
|
+
);
|
|
2051
|
+
}
|
|
2052
|
+
const picked = { ...decision.spec, id: decision.id };
|
|
2053
|
+
await storeSpecs(deps.ctx.dataDir, [picked], settingsHash);
|
|
2054
|
+
return showSpec(picked.id, picked, [], decision.hint);
|
|
2055
|
+
}
|
|
2056
|
+
if (decision.action === "native" || decision.action === "needs_input") {
|
|
2057
|
+
return fail(decision.action, decision.reason ?? "That tool has no spec to show.", {
|
|
2058
|
+
diagnostics: decision.diagnostics
|
|
2059
|
+
});
|
|
2060
|
+
}
|
|
2061
|
+
return fail(
|
|
2062
|
+
"needs_input",
|
|
2063
|
+
"The router answered that tool id with no spec, so nothing was kept or paid.",
|
|
2064
|
+
{ nextStep: "Call request({query}) with the task instead." }
|
|
2065
|
+
);
|
|
2066
|
+
}
|
|
2067
|
+
function listFailure(outcome) {
|
|
2068
|
+
if (outcome.status === "skipped") return fail("failed", outcome.why);
|
|
2069
|
+
return fail("failed", outcome.reason, {
|
|
2070
|
+
...outcome.errorCode !== void 0 ? { errorCode: outcome.errorCode } : {}
|
|
2071
|
+
});
|
|
2072
|
+
}
|
|
2073
|
+
var flat = (text) => text.replace(/[\p{Cc}\p{Cf}]+/gu, " ").trim();
|
|
2074
|
+
function showRows(rows) {
|
|
2075
|
+
const nextStep = 'Inspect a tool for free with request({tool: "<id>"}). Run a free tool with request({tool: "<id>", query: "<what to look up>"}).';
|
|
2076
|
+
if (rows.length === 0) {
|
|
2077
|
+
return {
|
|
2078
|
+
isError: false,
|
|
2079
|
+
summary: 'No tool in the list fits those words. Browse with other words, or with "" for every tool by kind.',
|
|
2080
|
+
envelope: { status: "browse", rows: [], nextStep, cost: costLines(0n) }
|
|
2081
|
+
};
|
|
2082
|
+
}
|
|
2083
|
+
const shown = rows.map((row) => ({
|
|
2084
|
+
id: row.id,
|
|
2085
|
+
label: flat(row.label),
|
|
2086
|
+
does: flat(row.does),
|
|
2087
|
+
price: row.free ? "free" : flat(row.price),
|
|
2088
|
+
kind: flat(row.kind)
|
|
2089
|
+
}));
|
|
2090
|
+
return {
|
|
2091
|
+
isError: false,
|
|
2092
|
+
summary: [
|
|
2093
|
+
...shown.map((row) => `${row.label} (id ${row.id}, ${row.price}, ${row.kind}): ${row.does}`),
|
|
2094
|
+
nextStep
|
|
2095
|
+
].join("\n"),
|
|
2096
|
+
envelope: {
|
|
2097
|
+
status: "browse",
|
|
2098
|
+
rows: shown,
|
|
2099
|
+
nextStep,
|
|
2100
|
+
cost: costLines(0n),
|
|
2101
|
+
providerContentUntrusted: true
|
|
2102
|
+
}
|
|
2103
|
+
};
|
|
2104
|
+
}
|
|
2105
|
+
function showSpec(id, spec, others = [], hint) {
|
|
2106
|
+
const also = others.map(
|
|
2107
|
+
(other) => `${other.provider} (${other.description}): request({id: ${JSON.stringify(other.id)}}) shows its spec`
|
|
2108
|
+
);
|
|
2109
|
+
const lines = [specText(id, spec)];
|
|
2110
|
+
if (also.length) lines.push(`Also offered: ${also.join("; ")}.`);
|
|
2111
|
+
if (hint !== void 0) lines.push(`Next: ${hint}`);
|
|
2112
|
+
return {
|
|
2113
|
+
isError: false,
|
|
2114
|
+
summary: lines.join("\n"),
|
|
2115
|
+
envelope: {
|
|
2116
|
+
status: "spec",
|
|
2117
|
+
id,
|
|
2118
|
+
nextStep: hint ?? `Call request({id: ${JSON.stringify(id)}, input: {...}}) with the inputs above.`,
|
|
2119
|
+
cost: costLines(0n)
|
|
2120
|
+
}
|
|
2121
|
+
};
|
|
2122
|
+
}
|
|
2123
|
+
function alreadyPaid(id, spec, earlier, running) {
|
|
2124
|
+
if (running !== void 0 && earlier.state !== "unrecorded") {
|
|
2125
|
+
return fail(
|
|
2126
|
+
"needs_input",
|
|
2127
|
+
`This offer from ${spec.provider} was already paid for, and ${spec.provider} is still working on it, so nothing was paid this time.`,
|
|
2128
|
+
{
|
|
2129
|
+
nextStep: `Call request({job: ${JSON.stringify(running)}}) for its result; nothing more is paid.`
|
|
2130
|
+
}
|
|
2131
|
+
);
|
|
2132
|
+
}
|
|
2133
|
+
const reason = earlier.state === "paid" ? `This offer from ${spec.provider} was already paid for at ${earlier.at} ($${toMoney(earlier.amountAtomic).usd}${earlier.txHash !== void 0 ? `, tx ${earlier.txHash}` : ""}), so nothing was paid this time. Its result is in the earlier request result for this id, and the payment is in \`tenjin payments\`.` : earlier.state === "possibly_paid" ? `A call for this offer from ${spec.provider} signed a payment at ${earlier.at} that may have left, and it ended without recording how much, so nothing was paid this time. Check \`tenjin payments\` before paying for this again.` : earlier.state === "running" ? `A call for this offer from ${spec.provider} already started and may have paid, so nothing was paid this time. Use that call's result.` : `This machine could not record this offer's payment, so nothing was sent or paid.`;
|
|
2134
|
+
return fail("needs_input", reason, {
|
|
2135
|
+
nextStep: `For another call, send request({query}) for a new offer; this id (${id}) pays once.`
|
|
2136
|
+
});
|
|
2137
|
+
}
|
|
2138
|
+
async function runSpec(id, spec, input, deps, footer, reportDeps, approved) {
|
|
2139
|
+
const stale = await settingsRefusal(deps.ctx.dataDir, [spec.settingsHash]);
|
|
2140
|
+
if (stale !== null) {
|
|
2141
|
+
await footer.done("needs_input");
|
|
2142
|
+
return settingsFail(stale);
|
|
2143
|
+
}
|
|
2144
|
+
const checked = await prepareSpec(id, spec, input, footer, reportDeps);
|
|
2145
|
+
if ("refused" in checked) return checked.refused;
|
|
2146
|
+
const earlier = await claimSpecPayment(deps.ctx.dataDir, id);
|
|
2147
|
+
if (earlier !== null) {
|
|
2148
|
+
await footer.done("needs_input");
|
|
2149
|
+
return alreadyPaid(id, spec, earlier, await runningJob(deps.ctx.dataDir, id));
|
|
2150
|
+
}
|
|
2151
|
+
const admission = approved !== void 0 ? { slot: approved[0] } : { alone: { kind: "spec", id, spec, input } };
|
|
2152
|
+
return (await paySpec(checked.prepared, admission, deps, footer, reportDeps)).result;
|
|
2153
|
+
}
|
|
2154
|
+
async function runningJob(dataDir, id) {
|
|
2155
|
+
const takes = await readTakes(dataDir, id).catch(() => []);
|
|
2156
|
+
return takes.some((take) => take.state === "running") ? id : void 0;
|
|
2157
|
+
}
|
|
2158
|
+
function reportOutcome(reportDeps, id, outcome, startedAt) {
|
|
2159
|
+
void reportSpecOutcome(
|
|
2160
|
+
{ id, ...outcome, ms: Date.now() - startedAt },
|
|
2161
|
+
{
|
|
2162
|
+
ctx: reportDeps.ctx,
|
|
2163
|
+
baseUrl: reportDeps.baseUrl,
|
|
2164
|
+
...reportDeps.fetchImpl !== void 0 ? { fetchImpl: reportDeps.fetchImpl } : {},
|
|
2165
|
+
...reportDeps.harness !== void 0 ? { harness: reportDeps.harness } : {}
|
|
2166
|
+
}
|
|
2167
|
+
);
|
|
2168
|
+
}
|
|
2169
|
+
async function prepareSpec(id, spec, input, footer, reportDeps) {
|
|
2170
|
+
const startedAt = Date.now();
|
|
2171
|
+
const unpaid = (reason) => reportOutcome(reportDeps, id, { status: "unpaid", reason }, startedAt);
|
|
2172
|
+
const merged = mergedInput(spec, input);
|
|
2173
|
+
const sentInput = maskDeep(merged);
|
|
2174
|
+
const refuse = async (problem) => {
|
|
2175
|
+
unpaid("input");
|
|
2176
|
+
await footer.done("needs_input");
|
|
2177
|
+
const refused = fail("needs_input", `The input does not fit ${spec.provider}: ${problem}.`, {
|
|
2178
|
+
nextStep: `Fix the input from the spec above and call request({id: ${JSON.stringify(id)}, input: {...}}) again; nothing was sent or paid.`,
|
|
2179
|
+
parameters: sentInput
|
|
2180
|
+
});
|
|
2181
|
+
return { refused: { ...refused, summary: `${refused.summary}
|
|
2182
|
+
|
|
2183
|
+
${specText(id, spec)}` } };
|
|
2184
|
+
};
|
|
2185
|
+
const problems = specInputProblems(spec, merged);
|
|
2186
|
+
if (problems === void 0) {
|
|
2187
|
+
unpaid("terms");
|
|
2188
|
+
await footer.done("failed");
|
|
2189
|
+
return {
|
|
2190
|
+
refused: fail(
|
|
2191
|
+
"failed",
|
|
2192
|
+
`The spec for ${spec.provider} has an input schema this build cannot check, so the call was not sent and nothing was paid.`,
|
|
2193
|
+
{
|
|
2194
|
+
nextStep: "Continue with your own tools. Nothing was sent or paid.",
|
|
2195
|
+
parameters: sentInput
|
|
2196
|
+
}
|
|
2197
|
+
)
|
|
2198
|
+
};
|
|
2199
|
+
}
|
|
2200
|
+
if (problems.length) return refuse(problems.join("; "));
|
|
2201
|
+
const built = buildSpecRequest(spec, merged);
|
|
2202
|
+
if ("problem" in built) return refuse(built.problem);
|
|
2203
|
+
const refusal = checkContract({
|
|
2204
|
+
request: built,
|
|
2205
|
+
...spec.resultSchema !== void 0 ? { resultSchema: spec.resultSchema } : {}
|
|
2206
|
+
});
|
|
2207
|
+
if (refusal !== null) {
|
|
2208
|
+
unpaid("terms");
|
|
2209
|
+
await footer.done(refusal.status);
|
|
2210
|
+
return { refused: fail(refusal.status, refusal.reason, { parameters: sentInput }) };
|
|
2211
|
+
}
|
|
2212
|
+
return { prepared: { id, spec, merged, sentInput, built } };
|
|
2213
|
+
}
|
|
2214
|
+
async function paySpec(prepared, admission, deps, footer, reportDeps, take) {
|
|
2215
|
+
const { id, spec, merged, sentInput, built } = prepared;
|
|
2216
|
+
const startedAt = Date.now();
|
|
2217
|
+
const suffix = take !== void 0 ? `#${take.n}` : "";
|
|
2218
|
+
const paid = await payAndDeliver(
|
|
2219
|
+
{
|
|
2220
|
+
capabilityId: spec.capabilityId,
|
|
2221
|
+
provider: spec.provider,
|
|
2222
|
+
...spec.label !== void 0 ? { label: spec.label } : {},
|
|
2223
|
+
media: savesMedia(spec),
|
|
2224
|
+
request: built,
|
|
2225
|
+
terms: specTerms(spec),
|
|
2226
|
+
requestKey: `${spec.capabilityId}:${canonicalHash(merged)}${suffix}`,
|
|
2227
|
+
...spec.resultSchema !== void 0 ? { resultSchema: spec.resultSchema } : {},
|
|
2228
|
+
...spec.outputSchema !== void 0 ? { project: { id: `${id}${suffix}`, schema: spec.outputSchema } } : {},
|
|
2229
|
+
parameters: sentInput,
|
|
2230
|
+
sent: JSON.stringify(sentInput),
|
|
2231
|
+
agentBuilt: true,
|
|
2232
|
+
priceVaries: spec.priceVaries,
|
|
2233
|
+
...spec.job !== void 0 ? { job: { spec: spec.job, offerId: id, take: take?.n ?? 1, input: merged } } : {},
|
|
2234
|
+
...spec.timeoutS !== void 0 ? { timeoutMs: spec.timeoutS * 1e3 } : {},
|
|
2235
|
+
...spec.maxBytes !== void 0 ? { maxBytes: spec.maxBytes } : {},
|
|
2236
|
+
...spec.settingsHash !== void 0 ? { settingsHash: spec.settingsHash } : {},
|
|
2237
|
+
...deps.via !== void 0 ? { via: deps.via } : {}
|
|
2238
|
+
},
|
|
2239
|
+
admission,
|
|
2240
|
+
deps,
|
|
2241
|
+
footer
|
|
2242
|
+
);
|
|
2243
|
+
const { outcome, left } = paid;
|
|
2244
|
+
const claim = take?.claim ?? id;
|
|
2245
|
+
const owner = await settleSpecPayment(deps.ctx.dataDir, claim, left);
|
|
2246
|
+
if ("slot" in admission && owner !== void 0) claimOfSlot.set(admission.slot, { claim, owner });
|
|
2247
|
+
if (outcome !== null && (take === void 0 || take.report)) {
|
|
2248
|
+
reportOutcome(
|
|
2249
|
+
reportDeps,
|
|
2250
|
+
id,
|
|
2251
|
+
deps.via !== void 0 ? { ...outcome, via: deps.via } : outcome,
|
|
2252
|
+
startedAt
|
|
2253
|
+
);
|
|
2254
|
+
}
|
|
2255
|
+
return paid;
|
|
2256
|
+
}
|
|
2257
|
+
var claimOfSlot = /* @__PURE__ */ new WeakMap();
|
|
2258
|
+
function specTerms(spec) {
|
|
2259
|
+
return {
|
|
2260
|
+
source: spec.provider,
|
|
2261
|
+
maxAmountAtomic: spec.maxAmountAtomic,
|
|
2262
|
+
payTo: spec.payTo,
|
|
2263
|
+
network: spec.network,
|
|
2264
|
+
asset: spec.asset
|
|
2265
|
+
};
|
|
2266
|
+
}
|
|
2267
|
+
function savesMedia(spec) {
|
|
2268
|
+
return spec.output !== void 0 ? spec.output === "media" : spec.capabilityId.startsWith("discovered:");
|
|
2269
|
+
}
|
|
2270
|
+
var PLAN_STOP = "planStop";
|
|
2271
|
+
function admitAlone(call, quoted, deps) {
|
|
2272
|
+
return async (amountAtomic) => {
|
|
2273
|
+
const settings = await resolveContextSettings(deps.ctx);
|
|
2274
|
+
const payments = [{ amountAtomic, creator: new URL(call.request.url).host }];
|
|
2275
|
+
const admission = await admitPlan(payments, {
|
|
2276
|
+
dataDir: deps.ctx.dataDir,
|
|
2277
|
+
policy: settings.policy,
|
|
2278
|
+
...deps.now !== void 0 ? { now: deps.now } : {}
|
|
2279
|
+
});
|
|
2280
|
+
if ("admitted" in admission) return admission.admitted[0];
|
|
2281
|
+
const stop = await planStop(
|
|
2282
|
+
admission,
|
|
2283
|
+
{ ...oneCall(call.provider, amountAtomic), payments, call: quoted },
|
|
2284
|
+
deps
|
|
2285
|
+
);
|
|
2286
|
+
throw new CliError(stop.status === "failed" ? "REFUSED" : "POLICY_REFUSED", stop.reason, {
|
|
2287
|
+
details: { [PLAN_STOP]: stop }
|
|
2288
|
+
});
|
|
2289
|
+
};
|
|
2290
|
+
}
|
|
2291
|
+
async function payAndDeliver(call, admission, deps, footer) {
|
|
2292
|
+
const stale = await settingsRefusal(deps.ctx.dataDir, [call.settingsHash]);
|
|
2293
|
+
if (stale !== null) {
|
|
2294
|
+
await footer.done("needs_input");
|
|
2295
|
+
return {
|
|
2296
|
+
result: settingsFail(stale),
|
|
2297
|
+
outcome: null,
|
|
2298
|
+
left: { amountAtomic: 0n, signed: false }
|
|
2299
|
+
};
|
|
2300
|
+
}
|
|
2301
|
+
const built = call.request;
|
|
2302
|
+
const parameters = call.parameters !== void 0 ? { parameters: call.parameters } : {};
|
|
2303
|
+
const named = call.label !== void 0 ? { label: call.label } : {};
|
|
2304
|
+
const signing = watchSigning(deps.payDeps?.authorizer ?? deps.authorizer);
|
|
2305
|
+
let leg;
|
|
2306
|
+
const submittedAt = (deps.now ?? Date.now)();
|
|
2307
|
+
try {
|
|
2308
|
+
await footer.calling({ provider: built.url, ...named, ...parameters });
|
|
2309
|
+
const paid = await runPay(
|
|
2310
|
+
{
|
|
2311
|
+
url: built.url,
|
|
2312
|
+
method: built.method,
|
|
2313
|
+
headers: built.headers,
|
|
2314
|
+
...built.specHeaders !== void 0 ? { specHeaders: built.specHeaders } : {},
|
|
2315
|
+
...built.body !== void 0 ? { rawBody: built.body } : {},
|
|
2316
|
+
terms: call.terms,
|
|
2317
|
+
execution: "router",
|
|
2318
|
+
admit: "slot" in admission ? async () => admission.slot : admitAlone(call, admission.alone, deps),
|
|
2319
|
+
requestKey: call.requestKey,
|
|
2320
|
+
...call.resultSchema !== void 0 ? { resultSchema: call.resultSchema } : {},
|
|
2321
|
+
...call.timeoutMs !== void 0 ? { timeoutMs: call.timeoutMs } : {},
|
|
2322
|
+
...call.maxBytes !== void 0 ? { maxBytes: call.maxBytes } : {},
|
|
2323
|
+
printBody: true,
|
|
2324
|
+
...call.job !== void 0 ? {
|
|
2325
|
+
onPaidLeg: (seen) => {
|
|
2326
|
+
leg = seen;
|
|
2327
|
+
}
|
|
2328
|
+
} : {}
|
|
2329
|
+
},
|
|
2330
|
+
deps.ctx,
|
|
2331
|
+
{
|
|
2332
|
+
...deps.payDeps ?? {},
|
|
2333
|
+
...deps.provider !== void 0 ? { provider: deps.provider } : {},
|
|
2334
|
+
...deps.paymentSignal !== void 0 ? { signal: deps.paymentSignal } : {},
|
|
2335
|
+
authorizer: signing.authorizer,
|
|
2336
|
+
confirm: async () => false
|
|
2337
|
+
}
|
|
2338
|
+
);
|
|
2339
|
+
const data = paid.data;
|
|
2340
|
+
const providerAtomic = BigInt(data.amountPaid?.atomic ?? "0");
|
|
2341
|
+
const tx = data.settlementTxHash !== void 0 ? { txHash: data.settlementTxHash } : {};
|
|
2342
|
+
const left = () => ({ amountAtomic: providerAtomic, ...tx, signed: signing.mayHaveSigned() });
|
|
2343
|
+
if (call.job !== void 0) {
|
|
2344
|
+
const state = data.bodyBytes !== void 0 && data.status !== 202 ? "done" : answerState(call.job.spec, data.status ?? 200, data.body, { submit: true });
|
|
2345
|
+
if (state !== "done") {
|
|
2346
|
+
const job = await startJob(call, call.job, deps, footer, {
|
|
2347
|
+
state,
|
|
2348
|
+
submittedAt,
|
|
2349
|
+
status: data.status,
|
|
2350
|
+
json: data.body,
|
|
2351
|
+
text: data.bodyText ?? "",
|
|
2352
|
+
...leg?.header !== void 0 ? { header: leg.header } : {},
|
|
2353
|
+
providerAtomic,
|
|
2354
|
+
...tx,
|
|
2355
|
+
...data.payer !== void 0 ? { payer: data.payer } : {},
|
|
2356
|
+
...data.authorization !== void 0 ? { authorization: data.authorization } : {}
|
|
2357
|
+
});
|
|
2358
|
+
return { ...job, left: left() };
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
const delivered = await deliverResult(
|
|
2362
|
+
call,
|
|
2363
|
+
deps,
|
|
2364
|
+
footer,
|
|
2365
|
+
{
|
|
2366
|
+
...data.status !== void 0 ? { status: data.status } : {},
|
|
2367
|
+
...data.bodyText !== void 0 ? { bodyText: data.bodyText } : {},
|
|
2368
|
+
...data.bodyBytes !== void 0 ? { bodyBytes: data.bodyBytes } : {},
|
|
2369
|
+
...data.contentType !== void 0 ? { contentType: data.contentType } : {},
|
|
2370
|
+
...data.resultUnverified === true ? { resultUnverified: true } : {},
|
|
2371
|
+
...data.resultCaveat !== void 0 ? { resultCaveat: data.resultCaveat } : {}
|
|
2372
|
+
},
|
|
2373
|
+
{
|
|
2374
|
+
providerAtomic,
|
|
2375
|
+
...tx,
|
|
2376
|
+
...data.payer !== void 0 ? { payer: data.payer } : {},
|
|
2377
|
+
...data.authorization !== void 0 ? { authorization: data.authorization } : {},
|
|
2378
|
+
ledger: "append"
|
|
2379
|
+
}
|
|
2380
|
+
);
|
|
2381
|
+
return { result: delivered.result, outcome: delivered.outcome, left: left() };
|
|
2382
|
+
} catch (err) {
|
|
2383
|
+
const cli = err instanceof CliError ? err : void 0;
|
|
2384
|
+
const stop = cli?.details?.[PLAN_STOP];
|
|
2385
|
+
if (stop !== void 0) {
|
|
2386
|
+
await footer.done(stop.status, { provider: built.url, ...named, ...parameters });
|
|
2387
|
+
return {
|
|
2388
|
+
left: { amountAtomic: 0n, signed: signing.mayHaveSigned() },
|
|
2389
|
+
outcome: stop.outcome,
|
|
2390
|
+
result: fail(stop.status, stop.reason, {
|
|
2391
|
+
...stop.extras,
|
|
2392
|
+
request: { method: built.method, url: built.url },
|
|
2393
|
+
...call.parameters !== void 0 ? { parameters: call.parameters } : {}
|
|
2394
|
+
})
|
|
2395
|
+
};
|
|
2396
|
+
}
|
|
2397
|
+
const status = cli?.code === "POLICY_REFUSED" ? "needs_approval" : "failed";
|
|
2398
|
+
const detail = cli?.details ?? {};
|
|
2399
|
+
const leftAtomic = status === "needs_approval" ? 0n : BigInt(detail.amountAtomic ?? "0");
|
|
2400
|
+
const cutJob = call.job;
|
|
2401
|
+
const cutHeader = leg?.header;
|
|
2402
|
+
if (cutJob !== void 0 && cutHeader !== void 0 && cli?.code === "NETWORK_ERROR" && leftAtomic > 0n && !("problem" in pollTarget(
|
|
2403
|
+
cutJob.spec,
|
|
2404
|
+
{ url: built.url, json: void 0, header: cutHeader },
|
|
2405
|
+
cutJob.input
|
|
2406
|
+
))) {
|
|
2407
|
+
const job = await startJob(call, cutJob, deps, footer, {
|
|
2408
|
+
state: "running",
|
|
2409
|
+
submittedAt,
|
|
2410
|
+
json: void 0,
|
|
2411
|
+
text: "",
|
|
2412
|
+
header: cutHeader,
|
|
2413
|
+
providerAtomic: leftAtomic,
|
|
2414
|
+
...detail.reportedTxHash !== void 0 ? { reportedTxHash: detail.reportedTxHash } : {},
|
|
2415
|
+
...detail.payer !== void 0 ? { payer: detail.payer } : {},
|
|
2416
|
+
...detail.authorization !== void 0 ? { authorization: detail.authorization } : {},
|
|
2417
|
+
...detail.settlement === "settled" ? { settled: true } : {}
|
|
2418
|
+
});
|
|
2419
|
+
return { ...job, left: { amountAtomic: leftAtomic, signed: true } };
|
|
2420
|
+
}
|
|
2421
|
+
const rejectedInput = call.agentBuilt === true && leftAtomic === 0n && (detail.status === 400 || detail.status === 422);
|
|
2422
|
+
const live = detail.live?.amount;
|
|
2423
|
+
const ceiling = call.terms.maxAmountAtomic;
|
|
2424
|
+
const overCeiling = call.priceVaries === true && cli?.code === "REGISTRY_MISMATCH" && live !== void 0 && ceiling !== void 0 && /^\d+$/.test(live) && BigInt(live) > BigInt(ceiling);
|
|
2425
|
+
const reason = overCeiling ? `${call.provider} prices this input at $${toMoney(live).usd}, over this spec's $${toMoney(ceiling).usd} ceiling, so nothing was signed. Change the input (a smaller size, a shorter clip, fewer items) and call again with the same id.` : rejectedInput ? `${call.provider} rejected this input before any payment (HTTP ${String(detail.status)}): see providerError. Fix the input and call again with the same id.` : cli !== void 0 && isLowFundsRefusal(cli) ? `${shortOfFunds({ label: call.label, provider: call.provider, priceAtomic: leftAtomic })} ${LOW_FUNDS_TAIL}` : cli !== void 0 ? `${cli.message} ${agentFixOf(cli)}`.trim() : String(err);
|
|
2426
|
+
await footer.done(status, {
|
|
2427
|
+
provider: built.url,
|
|
2428
|
+
...named,
|
|
2429
|
+
...parameters,
|
|
2430
|
+
price: `$${toMoney(leftAtomic.toString()).usd}`
|
|
2431
|
+
});
|
|
2432
|
+
if (leftAtomic > 0n) {
|
|
2433
|
+
await appendPaidRecord(
|
|
2434
|
+
deps.ctx.dataDir,
|
|
2435
|
+
paidRecord(call, built.url, call.sent, leftAtomic, {
|
|
2436
|
+
...detail.reportedTxHash !== void 0 ? { reportedTxHash: detail.reportedTxHash } : {},
|
|
2437
|
+
...detail.payer !== void 0 ? { payer: detail.payer } : {},
|
|
2438
|
+
...detail.authorization !== void 0 ? { authorization: detail.authorization } : {},
|
|
2439
|
+
...detail.settlement === "settled" ? { settled: true } : {},
|
|
2440
|
+
savedFiles: [],
|
|
2441
|
+
...deps.now !== void 0 ? { now: deps.now } : {}
|
|
2442
|
+
})
|
|
2443
|
+
);
|
|
2444
|
+
}
|
|
2445
|
+
const signed = signing.mayHaveSigned();
|
|
2446
|
+
const outcome = failureOutcome(err, { mayHaveMoved: leftAtomic > 0n || signed, rejectedInput });
|
|
2447
|
+
return {
|
|
2448
|
+
left: { amountAtomic: leftAtomic, signed },
|
|
2449
|
+
outcome: outcome === null ? null : {
|
|
2450
|
+
...outcome,
|
|
2451
|
+
...typeof detail.status === "number" ? { httpStatus: detail.status } : {}
|
|
2452
|
+
},
|
|
2453
|
+
result: fail(status, reason, {
|
|
2454
|
+
providerAtomic: leftAtomic,
|
|
2455
|
+
...detail.settlement !== void 0 ? { settlement: detail.settlement } : {},
|
|
2456
|
+
...detail.diagnosis !== void 0 ? { diagnosis: detail.diagnosis } : {},
|
|
2457
|
+
// WHY THE PROVIDER SAID NO: its HTTP status and a bounded, redacted
|
|
2458
|
+
// snippet of its body, which `runPay` cut. Without them a 403 read the
|
|
2459
|
+
// same as a timeout to the agent and to the logs.
|
|
2460
|
+
...typeof detail.status === "number" ? { providerStatus: detail.status } : {},
|
|
2461
|
+
...typeof detail.providerError === "string" ? { providerError: detail.providerError } : {},
|
|
2462
|
+
// THE SELLER SAID IT DID NOT SETTLE, and why: what an empty `{}` body
|
|
2463
|
+
// beside a rejected payment leaves out.
|
|
2464
|
+
...typeof detail.settlementError === "string" ? { settlementError: detail.settlementError } : {},
|
|
2465
|
+
// THE SELLER'S REASON FOR REFUSING THE PAYMENT, from its 402's own
|
|
2466
|
+
// PAYMENT-REQUIRED header, which the body may not repeat.
|
|
2467
|
+
...typeof detail.paymentError === "string" ? { paymentError: detail.paymentError } : {},
|
|
2468
|
+
// WHAT WAS SENT, on a failure too: the agent cannot match a 400 to a
|
|
2469
|
+
// field it cannot see.
|
|
2470
|
+
request: { method: built.method, url: built.url },
|
|
2471
|
+
...call.parameters !== void 0 ? { parameters: call.parameters } : {},
|
|
2472
|
+
// A LONG JOB STILL RUNNING: where its result will be, and that this
|
|
2473
|
+
// call was paid, so a second one would pay again.
|
|
2474
|
+
...typeof detail.statusUrl === "string" ? { statusUrl: detail.statusUrl } : {},
|
|
2475
|
+
...overCeiling ? { nextStep: "Change the input and call again with the same id." } : rejectedInput ? { nextStep: "Fix the input and call again with the same id." } : typeof detail.statusUrl === "string" ? {
|
|
2476
|
+
nextStep: "Check statusUrl for the result. Do not call request again for this: it would pay again."
|
|
2477
|
+
} : {}
|
|
2478
|
+
})
|
|
2479
|
+
};
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
async function deliverResult(call, deps, footer, got, money) {
|
|
2483
|
+
const built = call.request;
|
|
2484
|
+
const parameters = call.parameters !== void 0 ? { parameters: call.parameters } : {};
|
|
2485
|
+
const { providerAtomic } = money;
|
|
2486
|
+
const httpStatus = typeof got.status === "number" ? { httpStatus: got.status } : {};
|
|
2487
|
+
const budget = deps.downloads;
|
|
2488
|
+
const now = deps.now !== void 0 ? { now: deps.now } : {};
|
|
2489
|
+
const binary = got.bodyBytes !== void 0 ? await saveBinary(deps.ctx.dataDir, call.capabilityId, got.bodyBytes, {
|
|
2490
|
+
contentType: got.contentType ?? "",
|
|
2491
|
+
...now,
|
|
2492
|
+
...budget !== void 0 ? { budget } : {}
|
|
2493
|
+
}) : null;
|
|
2494
|
+
let unsaved = binary?.saveError;
|
|
2495
|
+
const files = [];
|
|
2496
|
+
for (const file of got.files ?? []) {
|
|
2497
|
+
const saved = await saveBinary(deps.ctx.dataDir, call.capabilityId, file.bytes, {
|
|
2498
|
+
contentType: file.contentType,
|
|
2499
|
+
...now,
|
|
2500
|
+
...budget !== void 0 ? { budget } : {}
|
|
2501
|
+
});
|
|
2502
|
+
unsaved ??= saved.saveError;
|
|
2503
|
+
if (saved.savedTo !== void 0) files.push(saved.savedTo);
|
|
2504
|
+
}
|
|
2505
|
+
const account = money.account;
|
|
2506
|
+
const media = (providerAtomic > 0n || account !== void 0) && binary === null && call.media;
|
|
2507
|
+
const inline = media && got.bodyText !== void 0 ? await saveInlineMedia(got.bodyText, async (bytes, contentType) => {
|
|
2508
|
+
const saved = await saveBinary(deps.ctx.dataDir, call.capabilityId, bytes, {
|
|
2509
|
+
contentType,
|
|
2510
|
+
...now,
|
|
2511
|
+
...budget !== void 0 ? { budget } : {}
|
|
2512
|
+
});
|
|
2513
|
+
unsaved ??= saved.saveError;
|
|
2514
|
+
return saved.savedTo ?? null;
|
|
2515
|
+
}) : null;
|
|
2516
|
+
const bodyText = inline?.bodyText ?? got.bodyText;
|
|
2517
|
+
const linked = media ? await saveLinked(
|
|
2518
|
+
deps,
|
|
2519
|
+
call.capabilityId,
|
|
2520
|
+
mediaUrlsIn(bodyText ?? "", MAX_MEDIA_FILES - (inline?.savedFiles.length ?? 0)),
|
|
2521
|
+
call.maxBytes
|
|
2522
|
+
) : { saved: [], capped: false, failed: false };
|
|
2523
|
+
if (linked.capped) unsaved ??= CAP_REACHED;
|
|
2524
|
+
if (linked.failed) unsaved ??= DOWNLOAD_FAILED;
|
|
2525
|
+
const savedFiles = [
|
|
2526
|
+
...binary?.savedTo !== void 0 ? [binary.savedTo] : [],
|
|
2527
|
+
...files,
|
|
2528
|
+
...inline?.savedFiles ?? [],
|
|
2529
|
+
...linked.saved
|
|
2530
|
+
];
|
|
2531
|
+
const cut = binary === null && call.project !== void 0 && bodyText !== void 0 ? await projected(deps.ctx.dataDir, call.project, bodyText) : null;
|
|
2532
|
+
if ((providerAtomic > 0n || account !== void 0) && money.ledger === "append") {
|
|
2533
|
+
await appendPaidRecord(
|
|
2534
|
+
deps.ctx.dataDir,
|
|
2535
|
+
paidRecord(call, built.url, call.sent, providerAtomic, {
|
|
2536
|
+
...money.txHash !== void 0 ? { txHash: money.txHash } : {},
|
|
2537
|
+
...money.payer !== void 0 ? { payer: money.payer } : {},
|
|
2538
|
+
...money.authorization !== void 0 ? { authorization: money.authorization } : {},
|
|
2539
|
+
savedFiles,
|
|
2540
|
+
...account !== void 0 ? { account: account.source } : {},
|
|
2541
|
+
...now
|
|
2542
|
+
})
|
|
2543
|
+
);
|
|
2544
|
+
} else if (typeof money.ledger === "object" && "job" in money.ledger) {
|
|
2545
|
+
await recordAccountRow(deps.ctx.dataDir, {
|
|
2546
|
+
...paidRecord(call, built.url, call.sent, providerAtomic, {
|
|
2547
|
+
savedFiles,
|
|
2548
|
+
...account !== void 0 ? { account: account.source } : {},
|
|
2549
|
+
...now
|
|
2550
|
+
}),
|
|
2551
|
+
job: money.ledger.job
|
|
2552
|
+
});
|
|
2553
|
+
} else if (typeof money.ledger === "object") {
|
|
2554
|
+
await updatePaidRecord(deps.ctx.dataDir, money.ledger.update, {
|
|
2555
|
+
savedFiles,
|
|
2556
|
+
...money.txHash !== void 0 ? { txHash: money.txHash } : {}
|
|
2557
|
+
});
|
|
2558
|
+
}
|
|
2559
|
+
const base = {
|
|
2560
|
+
supplier: supplierOf(built.url),
|
|
2561
|
+
// The service's display name, which the plugin's mod draws its row from.
|
|
2562
|
+
...call.label !== void 0 ? { label: call.label } : {},
|
|
2563
|
+
...parameters,
|
|
2564
|
+
cost: account !== void 0 ? accountCost(account.label) : costLines(providerAtomic),
|
|
2565
|
+
...money.txHash !== void 0 ? { settlementTxHash: money.txHash } : {},
|
|
2566
|
+
...call.note !== void 0 ? { note: call.note } : {},
|
|
2567
|
+
result: binary ?? cut?.result ?? bodyText ?? "",
|
|
2568
|
+
...cut !== null ? { fullResultPath: cut.fullResultPath } : {},
|
|
2569
|
+
...savedFiles.length > 0 ? { savedFiles } : {},
|
|
2570
|
+
providerContentUntrusted: true
|
|
2571
|
+
};
|
|
2572
|
+
const shown = {
|
|
2573
|
+
provider: built.url,
|
|
2574
|
+
...call.label !== void 0 ? { label: call.label } : {},
|
|
2575
|
+
...parameters,
|
|
2576
|
+
price: account !== void 0 ? "your account" : `$${toMoney(providerAtomic.toString()).usd}`
|
|
2577
|
+
};
|
|
2578
|
+
const receipt = account !== void 0 ? accountReceipt(account, binary === null ? cut?.result ?? bodyText : void 0, savedFiles) : `${base.supplier} \xB7 ${base.cost.join(" \xB7 ")}`;
|
|
2579
|
+
if (got.resultUnverified === true) {
|
|
2580
|
+
await footer.done("unverified", shown);
|
|
2581
|
+
return {
|
|
2582
|
+
outcome: { status: "unverified", ...httpStatus },
|
|
2583
|
+
savedFiles,
|
|
2584
|
+
...unsaved !== void 0 ? { unsaved } : {},
|
|
2585
|
+
result: {
|
|
2586
|
+
isError: true,
|
|
2587
|
+
summary: `Unverified result from ${receipt}`,
|
|
2588
|
+
envelope: {
|
|
2589
|
+
status: "unverified",
|
|
2590
|
+
...base,
|
|
2591
|
+
...got.resultCaveat !== void 0 ? { resultCaveat: got.resultCaveat } : {}
|
|
2592
|
+
}
|
|
2593
|
+
}
|
|
2594
|
+
};
|
|
2595
|
+
}
|
|
2596
|
+
await footer.done("fulfilled", shown);
|
|
2597
|
+
return {
|
|
2598
|
+
outcome: { status: "fulfilled", ...httpStatus },
|
|
2599
|
+
savedFiles,
|
|
2600
|
+
...unsaved !== void 0 ? { unsaved } : {},
|
|
2601
|
+
result: {
|
|
2602
|
+
isError: false,
|
|
2603
|
+
summary: account !== void 0 ? receipt : `Fulfilled by ${receipt}`,
|
|
2604
|
+
envelope: { status: "fulfilled", ...base, ...account !== void 0 ? { receipt } : {} }
|
|
2605
|
+
}
|
|
2606
|
+
};
|
|
2607
|
+
}
|
|
2608
|
+
async function saveLinked(deps, stem, urls, maxBytes) {
|
|
2609
|
+
return saveMedia(deps.ctx.dataDir, stem, urls, {
|
|
2610
|
+
...maxBytes !== void 0 ? { maxBytes } : {},
|
|
2611
|
+
...deps.mediaTransport !== void 0 ? { transport: deps.mediaTransport } : {},
|
|
2612
|
+
...deps.payDeps?.destination !== void 0 ? { destination: deps.payDeps.destination } : {},
|
|
2613
|
+
...deps.now !== void 0 ? { now: deps.now } : {},
|
|
2614
|
+
...deps.downloads !== void 0 ? { budget: deps.downloads } : {}
|
|
2615
|
+
});
|
|
2616
|
+
}
|
|
2617
|
+
async function startJob(call, job, deps, footer, submit) {
|
|
2618
|
+
const now = deps.now ?? Date.now;
|
|
2619
|
+
const built = call.request;
|
|
2620
|
+
const parameters = call.parameters !== void 0 ? { parameters: call.parameters } : {};
|
|
2621
|
+
const httpStatus = submit.status !== void 0 ? { httpStatus: submit.status } : {};
|
|
2622
|
+
const { providerAtomic } = submit;
|
|
2623
|
+
if (providerAtomic > 0n) {
|
|
2624
|
+
await appendPaidRecord(
|
|
2625
|
+
deps.ctx.dataDir,
|
|
2626
|
+
paidRecord(call, built.url, call.sent, providerAtomic, {
|
|
2627
|
+
...submit.txHash !== void 0 ? { txHash: submit.txHash } : {},
|
|
2628
|
+
...submit.reportedTxHash !== void 0 ? { reportedTxHash: submit.reportedTxHash } : {},
|
|
2629
|
+
...submit.payer !== void 0 ? { payer: submit.payer } : {},
|
|
2630
|
+
...submit.authorization !== void 0 ? { authorization: submit.authorization } : {},
|
|
2631
|
+
...submit.settled === true ? { settled: true } : {},
|
|
2632
|
+
savedFiles: [],
|
|
2633
|
+
now
|
|
2634
|
+
})
|
|
2635
|
+
);
|
|
2636
|
+
}
|
|
2637
|
+
const shown = {
|
|
2638
|
+
provider: built.url,
|
|
2639
|
+
...parameters,
|
|
2640
|
+
price: `$${toMoney(providerAtomic.toString()).usd}`
|
|
2641
|
+
};
|
|
2642
|
+
const paidFailure = async (reason, extras = {}) => {
|
|
2643
|
+
await footer.done("failed", shown);
|
|
2644
|
+
return {
|
|
2645
|
+
outcome: { status: "failed", ...httpStatus },
|
|
2646
|
+
result: fail("failed", `${reason} ${paidNothing(providerAtomic, submit)}`, {
|
|
2647
|
+
providerAtomic,
|
|
2648
|
+
settlement: settledOf(submit) ? "settled" : "unknown",
|
|
2649
|
+
...submit.status !== void 0 ? { providerStatus: submit.status } : {},
|
|
2650
|
+
request: { method: built.method, url: built.url },
|
|
2651
|
+
...parameters,
|
|
2652
|
+
nextStep: failedNextStep(settledOf(submit)),
|
|
2653
|
+
...extras
|
|
2654
|
+
})
|
|
2655
|
+
};
|
|
2656
|
+
};
|
|
2657
|
+
if (submit.state === "failed") {
|
|
2658
|
+
const said = sellerSaid(submit.json, submit.text);
|
|
2659
|
+
return paidFailure(
|
|
2660
|
+
`${call.provider}: the seller says the job failed.`,
|
|
2661
|
+
said.length > 0 ? { providerError: said } : {}
|
|
2662
|
+
);
|
|
2663
|
+
}
|
|
2664
|
+
const target = pollTarget(
|
|
2665
|
+
job.spec,
|
|
2666
|
+
{
|
|
2667
|
+
url: built.url,
|
|
2668
|
+
json: submit.json,
|
|
2669
|
+
...submit.header !== void 0 ? { header: submit.header } : {}
|
|
2670
|
+
},
|
|
2671
|
+
job.input
|
|
2672
|
+
);
|
|
2673
|
+
if ("problem" in target) {
|
|
2674
|
+
return paidFailure(
|
|
2675
|
+
`${call.provider} took the payment and is still working, but ${target.problem}, so it was not polled.`,
|
|
2676
|
+
target.named !== void 0 ? { statusUrl: target.named } : {}
|
|
2677
|
+
);
|
|
2678
|
+
}
|
|
2679
|
+
const take = {
|
|
2680
|
+
version: 1,
|
|
2681
|
+
offerId: job.offerId,
|
|
2682
|
+
take: job.take,
|
|
2683
|
+
poll: target,
|
|
2684
|
+
job: job.spec,
|
|
2685
|
+
call: {
|
|
2686
|
+
capabilityId: call.capabilityId,
|
|
2687
|
+
provider: call.provider,
|
|
2688
|
+
url: built.url,
|
|
2689
|
+
media: call.media,
|
|
2690
|
+
sent: recordedSent(call.sent),
|
|
2691
|
+
terms: {
|
|
2692
|
+
...call.terms.source !== void 0 ? { source: call.terms.source } : {},
|
|
2693
|
+
maxAmountAtomic: call.terms.maxAmountAtomic ?? "0",
|
|
2694
|
+
...call.terms.payTo !== void 0 ? { payTo: call.terms.payTo } : {},
|
|
2695
|
+
...call.terms.network !== void 0 ? { network: call.terms.network } : {},
|
|
2696
|
+
...call.terms.asset !== void 0 ? { asset: call.terms.asset } : {}
|
|
2697
|
+
},
|
|
2698
|
+
...call.resultSchema !== void 0 ? { resultSchema: call.resultSchema } : {},
|
|
2699
|
+
...call.project !== void 0 ? { outputSchema: call.project.schema } : {}
|
|
2700
|
+
},
|
|
2701
|
+
submittedAt: new Date(submit.submittedAt).toISOString(),
|
|
2702
|
+
expiresAt: new Date(submit.submittedAt + job.spec.keepH * 36e5).toISOString(),
|
|
2703
|
+
amountAtomic: providerAtomic.toString(),
|
|
2704
|
+
...submit.payer !== void 0 ? { payer: submit.payer } : {},
|
|
2705
|
+
...submit.authorization !== void 0 ? { authorization: submit.authorization } : {},
|
|
2706
|
+
...submit.txHash !== void 0 ? { txHash: submit.txHash } : {},
|
|
2707
|
+
...submit.settled === true ? { settled: true } : {},
|
|
2708
|
+
...httpStatus,
|
|
2709
|
+
state: "running",
|
|
2710
|
+
savedFiles: [],
|
|
2711
|
+
// A status URL the agent may open itself: a plain GET.
|
|
2712
|
+
...target.method === "GET" ? { statusUrl: target.url } : {}
|
|
2713
|
+
};
|
|
2714
|
+
const kept = await writeTake(deps.ctx.dataDir, take).then(
|
|
2715
|
+
() => true,
|
|
2716
|
+
() => false
|
|
2717
|
+
);
|
|
2718
|
+
const deadline = Math.min(
|
|
2719
|
+
deps.waitsForJobs === true ? Number.POSITIVE_INFINITY : (deps.startedAt ?? submit.submittedAt) + MAX_CALL_WAIT_MS,
|
|
2720
|
+
submit.submittedAt + job.spec.maxWaitS * 1e3
|
|
2721
|
+
);
|
|
2722
|
+
const answer = await pollUntil(
|
|
2723
|
+
take,
|
|
2724
|
+
{ deadline, firstWaitMs: job.spec.everyS * 1e3 },
|
|
2725
|
+
pollDeps(deps, take)
|
|
2726
|
+
);
|
|
2727
|
+
return finishTake(take, answer, deps, footer, { kept, parameters: call.parameters });
|
|
2728
|
+
}
|
|
2729
|
+
function settledOf(money) {
|
|
2730
|
+
return money.txHash !== void 0 || money.settled === true;
|
|
2731
|
+
}
|
|
2732
|
+
function paidNothing(amountAtomic, money) {
|
|
2733
|
+
const usd2 = `$${toMoney(amountAtomic.toString()).usd}`;
|
|
2734
|
+
if (money.txHash !== void 0) {
|
|
2735
|
+
return `It was paid (${usd2}, settled in tx ${money.txHash}) and nothing came back.`;
|
|
2736
|
+
}
|
|
2737
|
+
return money.settled === true ? `It was paid (${usd2}; the chain shows the payment taken) and nothing came back.` : `It was paid (${usd2}) and nothing came back; whether that payment settles is unknown until its authorization expires.`;
|
|
2738
|
+
}
|
|
2739
|
+
function failedNextStep(settled) {
|
|
2740
|
+
return settled ? "Tell the user it was paid and nothing came back; the payment is in `tenjin payments`. A new call pays again." : "Tell the user. The payment is in `tenjin payments`; one the seller never settles is given back to the daily budget once its authorization expires. A new call pays again.";
|
|
2741
|
+
}
|
|
2742
|
+
function pollDeps(deps, take) {
|
|
2743
|
+
const provider = deps.provider ?? deps.payDeps?.provider;
|
|
2744
|
+
const from = take !== void 0 ? payerOf(take) : void 0;
|
|
2745
|
+
return {
|
|
2746
|
+
...deps.pollTransport !== void 0 ? { transport: deps.pollTransport } : {},
|
|
2747
|
+
...deps.payDeps?.destination !== void 0 ? { destination: deps.payDeps.destination } : {},
|
|
2748
|
+
...deps.now !== void 0 ? { now: deps.now } : {},
|
|
2749
|
+
...deps.sleep !== void 0 ? { sleep: deps.sleep } : {},
|
|
2750
|
+
...deps.onPoll !== void 0 ? { onPoll: deps.onPoll } : {},
|
|
2751
|
+
...take !== void 0 ? {
|
|
2752
|
+
signIn: (challenge, url) => signInForPoll(challenge, url, deps.ctx, {
|
|
2753
|
+
...provider !== void 0 ? { provider } : {},
|
|
2754
|
+
paidBy: { ...from !== void 0 ? { from } : {}, url: take.call.url }
|
|
2755
|
+
})
|
|
2756
|
+
} : {}
|
|
2757
|
+
};
|
|
2758
|
+
}
|
|
2759
|
+
function callOf(take, parameters) {
|
|
2760
|
+
return {
|
|
2761
|
+
capabilityId: take.call.capabilityId,
|
|
2762
|
+
provider: take.call.provider,
|
|
2763
|
+
media: take.call.media,
|
|
2764
|
+
sent: take.call.sent,
|
|
2765
|
+
request: { url: take.call.url },
|
|
2766
|
+
...parameters !== void 0 ? { parameters } : {},
|
|
2767
|
+
...take.call.outputSchema !== void 0 ? {
|
|
2768
|
+
project: {
|
|
2769
|
+
id: take.take > 1 ? `${take.offerId}#${take.take}` : take.offerId,
|
|
2770
|
+
schema: take.call.outputSchema
|
|
2771
|
+
}
|
|
2772
|
+
} : {}
|
|
2773
|
+
};
|
|
2774
|
+
}
|
|
2775
|
+
async function finishTake(take, answer, deps, footer, opts) {
|
|
2776
|
+
const { dataDir } = deps.ctx;
|
|
2777
|
+
const providerAtomic = BigInt(take.amountAtomic);
|
|
2778
|
+
const call = callOf(take, opts.parameters);
|
|
2779
|
+
const shown = {
|
|
2780
|
+
provider: take.call.url,
|
|
2781
|
+
price: `$${toMoney(providerAtomic.toString()).usd}`
|
|
2782
|
+
};
|
|
2783
|
+
const end = (ending) => endTake(dataDir, take.offerId, take.take, ending).catch(() => void 0);
|
|
2784
|
+
const lostTo = async (ended2) => {
|
|
2785
|
+
const result = endedResult(ended2, { raced: true });
|
|
2786
|
+
const status = result.envelope.status;
|
|
2787
|
+
await footer.done(status, shown);
|
|
2788
|
+
return { result, outcome: { status } };
|
|
2789
|
+
};
|
|
2790
|
+
if (answer.state === "done") {
|
|
2791
|
+
const current = await readTake(dataDir, take.offerId, take.take) ?? take;
|
|
2792
|
+
if (current.state !== "running") return lostTo(current);
|
|
2793
|
+
const nonce = current.authorization?.nonce;
|
|
2794
|
+
let caveat;
|
|
2795
|
+
let unverified = false;
|
|
2796
|
+
if (take.call.resultSchema !== void 0 && answer.bytes === void 0) {
|
|
2797
|
+
const check = validateResultBody(take.call.resultSchema, answer.text);
|
|
2798
|
+
if (!check.valid || check.unvalidated === true) {
|
|
2799
|
+
unverified = true;
|
|
2800
|
+
caveat = check.reason ?? "The result does not satisfy its success schema.";
|
|
2801
|
+
}
|
|
2802
|
+
}
|
|
2803
|
+
const tx = settlementTx({ header: answer.header });
|
|
2804
|
+
const delivered = await deliverResult(
|
|
2805
|
+
call,
|
|
2806
|
+
deps,
|
|
2807
|
+
footer,
|
|
2808
|
+
{
|
|
2809
|
+
status: answer.status,
|
|
2810
|
+
...answer.bytes !== void 0 ? { bodyBytes: answer.bytes, contentType: answer.contentType } : { bodyText: answer.text },
|
|
2811
|
+
...unverified ? { resultUnverified: true } : {},
|
|
2812
|
+
...caveat !== void 0 ? { resultCaveat: caveat } : {}
|
|
2813
|
+
},
|
|
2814
|
+
{
|
|
2815
|
+
providerAtomic,
|
|
2816
|
+
...tx !== void 0 ? { txHash: tx } : {},
|
|
2817
|
+
ledger: nonce !== void 0 ? { update: nonce } : "none"
|
|
2818
|
+
}
|
|
2819
|
+
);
|
|
2820
|
+
if (delivered.unsaved !== void 0) {
|
|
2821
|
+
await footer.done("running", shown);
|
|
2822
|
+
return {
|
|
2823
|
+
outcome: { status: "running", httpStatus: answer.status },
|
|
2824
|
+
result: unsavedResult(take, call, opts.kept, delivered.unsaved)
|
|
2825
|
+
};
|
|
2826
|
+
}
|
|
2827
|
+
const ended2 = await end({
|
|
2828
|
+
state: "done",
|
|
2829
|
+
savedFiles: delivered.savedFiles.slice(0, 16),
|
|
2830
|
+
result: keptResult(delivered.result.envelope.result),
|
|
2831
|
+
...unverified ? { resultUnverified: true } : {},
|
|
2832
|
+
...caveat !== void 0 ? { resultCaveat: caveat.slice(0, 1e3) } : {}
|
|
2833
|
+
});
|
|
2834
|
+
if (ended2?.won === false) return lostTo(ended2.take);
|
|
2835
|
+
if (delivered.savedFiles.length > 0 && ended2 !== void 0) {
|
|
2836
|
+
await completeJob({ ...current, submitUrl: take.call.url }, pollDeps(deps));
|
|
2837
|
+
}
|
|
2838
|
+
return {
|
|
2839
|
+
result: withJob(delivered.result, take.offerId),
|
|
2840
|
+
outcome: delivered.outcome
|
|
2841
|
+
};
|
|
2842
|
+
}
|
|
2843
|
+
if (answer.state === "running") {
|
|
2844
|
+
await footer.done("running", shown);
|
|
2845
|
+
return {
|
|
2846
|
+
outcome: {
|
|
2847
|
+
status: "running",
|
|
2848
|
+
...take.httpStatus !== void 0 ? { httpStatus: take.httpStatus } : {}
|
|
2849
|
+
},
|
|
2850
|
+
result: answer.otherWallet !== void 0 ? otherWalletResult(take, call, opts.kept, answer.otherWallet) : runningResult(take, call, opts.kept, answer.reason)
|
|
2851
|
+
};
|
|
2852
|
+
}
|
|
2853
|
+
const reason = `${answer.state === "expired" ? `${take.call.provider} no longer has this job (HTTP ${answer.status}).` : `${take.call.provider}: ${answer.reason}.`} ${paidNothing(providerAtomic, take)}`;
|
|
2854
|
+
const said = answer.state === "failed" ? answer.said : void 0;
|
|
2855
|
+
const ended = await end({
|
|
2856
|
+
state: answer.state,
|
|
2857
|
+
reason: reason.slice(0, 1e3),
|
|
2858
|
+
...said !== void 0 ? { said } : {}
|
|
2859
|
+
});
|
|
2860
|
+
if (ended?.won === false) return lostTo(ended.take);
|
|
2861
|
+
await footer.done("failed", shown);
|
|
2862
|
+
return {
|
|
2863
|
+
outcome: {
|
|
2864
|
+
status: "failed",
|
|
2865
|
+
...answer.status !== void 0 ? { httpStatus: answer.status } : {}
|
|
2866
|
+
},
|
|
2867
|
+
result: withJob(failedResult(take, reason, answer.status, said, opts.parameters), take.offerId)
|
|
2868
|
+
};
|
|
2869
|
+
}
|
|
2870
|
+
function failedResult(take, reason, status, said, parameters) {
|
|
2871
|
+
return fail("failed", reason, {
|
|
2872
|
+
providerAtomic: BigInt(take.amountAtomic),
|
|
2873
|
+
settlement: settledOf(take) ? "settled" : "unknown",
|
|
2874
|
+
...status !== void 0 ? { providerStatus: status } : {},
|
|
2875
|
+
...said !== void 0 ? { providerError: said } : {},
|
|
2876
|
+
request: { method: take.poll.method, url: take.poll.url },
|
|
2877
|
+
...parameters !== void 0 ? { parameters } : {},
|
|
2878
|
+
nextStep: failedNextStep(settledOf(take))
|
|
2879
|
+
});
|
|
2880
|
+
}
|
|
2881
|
+
function withJob(result, offerId) {
|
|
2882
|
+
return { ...result, envelope: { ...result.envelope, job: offerId } };
|
|
2883
|
+
}
|
|
2884
|
+
function keptResult(result) {
|
|
2885
|
+
const text = typeof result === "string" ? result : JSON.stringify(result ?? "");
|
|
2886
|
+
return text.length <= KEPT_RESULT_CHARS ? text : `${text.slice(0, KEPT_RESULT_CHARS)}\u2026`;
|
|
2887
|
+
}
|
|
2888
|
+
function runningResult(take, call, kept, note) {
|
|
2889
|
+
const cost = costLines(BigInt(take.amountAtomic));
|
|
2890
|
+
const supplier = supplierOf(take.call.url);
|
|
2891
|
+
const nextStep = kept ? `Call request({job: ${JSON.stringify(take.offerId)}}) in a minute or two; nothing more is paid.` : `This machine could not keep the job, so it cannot be resumed here${take.statusUrl !== void 0 ? "; check statusUrl for the result" : ""}. Do not call again for this: it would pay again.`;
|
|
2892
|
+
return {
|
|
2893
|
+
isError: false,
|
|
2894
|
+
summary: `Still running at ${supplier} \xB7 ${cost.join(" \xB7 ")}. ${nextStep}`,
|
|
2895
|
+
envelope: {
|
|
2896
|
+
status: "running",
|
|
2897
|
+
job: take.offerId,
|
|
2898
|
+
...take.statusUrl !== void 0 ? { statusUrl: take.statusUrl } : {},
|
|
2899
|
+
supplier,
|
|
2900
|
+
...call.parameters !== void 0 ? { parameters: call.parameters } : {},
|
|
2901
|
+
cost,
|
|
2902
|
+
...note !== void 0 ? { note } : {},
|
|
2903
|
+
nextStep,
|
|
2904
|
+
providerContentUntrusted: true
|
|
2905
|
+
}
|
|
2906
|
+
};
|
|
2907
|
+
}
|
|
2908
|
+
function otherWalletResult(take, call, kept, wallet) {
|
|
2909
|
+
const running = runningResult(take, call, kept);
|
|
2910
|
+
const reason = `${supplierOf(take.call.url)} returns this result only to the wallet that paid for it (${wallet.paidBy}), and this machine's wallet is now ${wallet.current}, so nothing was signed. The job is still running; nothing more was paid.`;
|
|
2911
|
+
const nextStep = kept ? `Tell the user this job was paid by the wallet ${wallet.paidBy}. Once this machine uses that wallet again, call request({job: ${JSON.stringify(take.offerId)}}); nothing more is paid. Do not call request again for a new result: it would pay again.` : String(running.envelope.nextStep);
|
|
2912
|
+
return {
|
|
2913
|
+
isError: true,
|
|
2914
|
+
summary: `${reason} ${nextStep}`,
|
|
2915
|
+
envelope: {
|
|
2916
|
+
...running.envelope,
|
|
2917
|
+
reason,
|
|
2918
|
+
reasonCode: "sign_in_wallet",
|
|
2919
|
+
paidBy: wallet.paidBy,
|
|
2920
|
+
nextStep
|
|
2921
|
+
}
|
|
2922
|
+
};
|
|
2923
|
+
}
|
|
2924
|
+
function unsavedResult(take, call, kept, why) {
|
|
2925
|
+
const running = runningResult(
|
|
2926
|
+
take,
|
|
2927
|
+
call,
|
|
2928
|
+
kept,
|
|
2929
|
+
`The seller finished it and the payment went through, but it could not be saved here (${why}).`
|
|
2930
|
+
);
|
|
2931
|
+
const words = unsavedWords(
|
|
2932
|
+
`Paid; ${supplierOf(take.call.url)} finished it`,
|
|
2933
|
+
why,
|
|
2934
|
+
kept ? { job: take.offerId } : { otherwise: String(running.envelope.nextStep) }
|
|
2935
|
+
);
|
|
2936
|
+
return {
|
|
2937
|
+
...running,
|
|
2938
|
+
summary: words.summary,
|
|
2939
|
+
envelope: { ...running.envelope, nextStep: words.nextStep }
|
|
2940
|
+
};
|
|
2941
|
+
}
|
|
2942
|
+
function unsavedWords(finished, why, next) {
|
|
2943
|
+
const said = `${finished}, but it could not be saved here (${why}).`;
|
|
2944
|
+
const nextStep = "job" in next ? `Tell the user why it was not saved, then call request({job: ${JSON.stringify(next.job)}}) to fetch it again; nothing more is paid.` : next.otherwise;
|
|
2945
|
+
return { said, nextStep, summary: `${said} ${nextStep}` };
|
|
2946
|
+
}
|
|
2947
|
+
function endedResult(take, opts = {}) {
|
|
2948
|
+
const cost = costLines(BigInt(take.amountAtomic));
|
|
2949
|
+
const supplier = supplierOf(take.call.url);
|
|
2950
|
+
const how = opts.raced === true ? "another call finished this job first; nothing more was paid" : "already finished; nothing was polled or paid";
|
|
2951
|
+
if (take.state === "done") {
|
|
2952
|
+
const unverified = take.resultUnverified === true;
|
|
2953
|
+
return {
|
|
2954
|
+
isError: unverified,
|
|
2955
|
+
summary: `${unverified ? "Unverified result from" : "Fulfilled by"} ${supplier} \xB7 ${cost.join(" \xB7 ")} (${how})`,
|
|
2956
|
+
envelope: {
|
|
2957
|
+
status: unverified ? "unverified" : "fulfilled",
|
|
2958
|
+
job: take.offerId,
|
|
2959
|
+
supplier,
|
|
2960
|
+
cost,
|
|
2961
|
+
result: take.result ?? "",
|
|
2962
|
+
...take.savedFiles.length > 0 ? { savedFiles: take.savedFiles } : {},
|
|
2963
|
+
note: opts.raced === true ? "Another call finished this job first; this is its result, and nothing more was paid." : "This job had already finished; nothing was polled or paid.",
|
|
2964
|
+
providerContentUntrusted: true,
|
|
2965
|
+
...unverified && take.resultCaveat !== void 0 ? { resultCaveat: take.resultCaveat } : {}
|
|
2966
|
+
}
|
|
2967
|
+
};
|
|
2968
|
+
}
|
|
2969
|
+
return withJob(
|
|
2970
|
+
failedResult(
|
|
2971
|
+
take,
|
|
2972
|
+
take.reason ?? `${take.call.provider}: the job ended without a result. ${paidNothing(BigInt(take.amountAtomic), take)}`,
|
|
2973
|
+
void 0,
|
|
2974
|
+
take.said
|
|
2975
|
+
),
|
|
2976
|
+
take.offerId
|
|
2977
|
+
);
|
|
2978
|
+
}
|
|
2979
|
+
async function resumeJob(offerId, deps) {
|
|
2980
|
+
const { dataDir } = deps.ctx;
|
|
2981
|
+
const accountJob = await readAccountJob(dataDir, offerId);
|
|
2982
|
+
if (accountJob !== null) {
|
|
2983
|
+
const settings2 = await resolveContextSettings(deps.ctx);
|
|
2984
|
+
return (await import("./run-JH7ELYAM.js")).resumeAccountJob(accountJob, deps, {
|
|
2985
|
+
ctx: deps.ctx,
|
|
2986
|
+
baseUrl: settings2.baseUrl,
|
|
2987
|
+
acceptsBazaar: settings2.experimentalBazaar,
|
|
2988
|
+
...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {},
|
|
2989
|
+
...deps.harness !== void 0 ? { harness: deps.harness } : {}
|
|
2990
|
+
});
|
|
2991
|
+
}
|
|
2992
|
+
const takes = await readTakes(dataDir, offerId);
|
|
2993
|
+
if (takes.length === 0) {
|
|
2994
|
+
return fail(
|
|
2995
|
+
"needs_input",
|
|
2996
|
+
"No job is kept on this machine under that id (it never started here, or it ended and its keep time passed), so nothing was polled or paid.",
|
|
2997
|
+
{
|
|
2998
|
+
nextStep: "Check `tenjin payments` for what was paid. For a new result, call request({query}); that pays again."
|
|
2999
|
+
}
|
|
3000
|
+
);
|
|
3001
|
+
}
|
|
3002
|
+
const footer = await openLookupFooter(dataDir, { id: offerId });
|
|
3003
|
+
await footer.routing();
|
|
3004
|
+
const settings = await resolveContextSettings(deps.ctx);
|
|
3005
|
+
const startedAt = deps.startedAt ?? (deps.now ?? Date.now)();
|
|
3006
|
+
const started = Date.now();
|
|
3007
|
+
const ended = await Promise.all(
|
|
3008
|
+
takes.map(async (take) => {
|
|
3009
|
+
if (take.state !== "running") {
|
|
3010
|
+
return { take, result: endedResult(take), outcome: null };
|
|
3011
|
+
}
|
|
3012
|
+
const waited = startedAt + MAX_CALL_WAIT_MS;
|
|
3013
|
+
const deadline = Math.min(
|
|
3014
|
+
deps.waitsForJobs === true ? Math.max(waited, Date.parse(take.submittedAt) + take.job.maxWaitS * 1e3) : waited,
|
|
3015
|
+
Date.parse(take.expiresAt)
|
|
3016
|
+
);
|
|
3017
|
+
const answer = await pollUntil(take, { deadline, firstWaitMs: 0 }, pollDeps(deps, take));
|
|
3018
|
+
const done = await finishTake(take, answer, deps, SILENT_FOOTER, { kept: true });
|
|
3019
|
+
return { take, result: done.result, outcome: done.outcome };
|
|
3020
|
+
})
|
|
3021
|
+
);
|
|
3022
|
+
const changed = ended.find(({ outcome }) => outcome !== null && outcome.status !== "running");
|
|
3023
|
+
if (changed?.outcome) {
|
|
3024
|
+
reportOutcome(
|
|
3025
|
+
{
|
|
3026
|
+
ctx: deps.ctx,
|
|
3027
|
+
baseUrl: settings.baseUrl,
|
|
3028
|
+
...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
|
|
3029
|
+
},
|
|
3030
|
+
offerId,
|
|
3031
|
+
changed.outcome,
|
|
3032
|
+
started
|
|
3033
|
+
);
|
|
3034
|
+
}
|
|
3035
|
+
if (ended.length === 1) {
|
|
3036
|
+
const only = ended[0].result;
|
|
3037
|
+
await footer.done(String(only.envelope.status));
|
|
3038
|
+
return only;
|
|
3039
|
+
}
|
|
3040
|
+
const set = takesResult(
|
|
3041
|
+
ended.map(({ take, result }) => ({
|
|
3042
|
+
named: { take: take.take },
|
|
3043
|
+
result,
|
|
3044
|
+
// Paid when the job started: a resume pays nothing more of its own.
|
|
3045
|
+
amountAtomic: BigInt(take.amountAtomic)
|
|
3046
|
+
})),
|
|
3047
|
+
{
|
|
3048
|
+
head: `${ended.length} takes of ${takes[0].call.provider}`,
|
|
3049
|
+
nextStep: "Open each saved file, say which take fits the request best and why, and let the user pick."
|
|
3050
|
+
}
|
|
3051
|
+
);
|
|
3052
|
+
await footer.done(String(set.envelope.status));
|
|
3053
|
+
return set;
|
|
3054
|
+
}
|
|
3055
|
+
async function projected(dataDir, project, body) {
|
|
3056
|
+
const cut = projectBody(project.schema, body);
|
|
3057
|
+
if (cut === void 0) return null;
|
|
3058
|
+
const fullResultPath = await storeFullResult(dataDir, project.id, body);
|
|
3059
|
+
if (fullResultPath === null) return null;
|
|
3060
|
+
return { result: JSON.stringify(cut.value), fullResultPath };
|
|
3061
|
+
}
|
|
3062
|
+
function watchSigning(inner) {
|
|
3063
|
+
let reserved = false;
|
|
3064
|
+
let released = false;
|
|
3065
|
+
let committed = false;
|
|
3066
|
+
return {
|
|
3067
|
+
authorizer: {
|
|
3068
|
+
policyEnforcement: inner.policyEnforcement,
|
|
3069
|
+
authorize: async (req) => {
|
|
3070
|
+
const authorization = await inner.authorize(req);
|
|
3071
|
+
if (authorization.decision !== "deny") reserved = true;
|
|
3072
|
+
return authorization;
|
|
3073
|
+
},
|
|
3074
|
+
commit: async (reservationId, amountAtomic, opts) => {
|
|
3075
|
+
committed = true;
|
|
3076
|
+
await inner.commit(reservationId, amountAtomic, opts);
|
|
3077
|
+
},
|
|
3078
|
+
release: async (reservationId) => {
|
|
3079
|
+
released = true;
|
|
3080
|
+
await inner.release(reservationId);
|
|
3081
|
+
}
|
|
3082
|
+
},
|
|
3083
|
+
mayHaveSigned: () => committed || reserved && !released
|
|
3084
|
+
};
|
|
3085
|
+
}
|
|
3086
|
+
function failureOutcome(err, facts) {
|
|
3087
|
+
if (facts.mayHaveMoved) return { status: "failed" };
|
|
3088
|
+
if (!(err instanceof CliError)) return null;
|
|
3089
|
+
if (err.code === "POLICY_REFUSED") return { status: "needs_approval" };
|
|
3090
|
+
const unpaid = (reason) => ({ status: "unpaid", reason });
|
|
3091
|
+
if (facts.rejectedInput) return unpaid("input");
|
|
3092
|
+
const detail = err.details ?? {};
|
|
3093
|
+
if (detail.walletUnavailable === true || detail.reason === "insufficient_funds" || detail.reason === "balance_unavailable") {
|
|
3094
|
+
return unpaid("wallet");
|
|
3095
|
+
}
|
|
3096
|
+
switch (err.code) {
|
|
3097
|
+
// REGISTRY_MISMATCH: the live 402 is not the spec's deal, including a
|
|
3098
|
+
// varying price over its ceiling. PAYMENT_FAILED before a signature: no
|
|
3099
|
+
// entry this wallet can pay, or a price or deal that changed on the
|
|
3100
|
+
// re-check. USAGE and REFUSED: a request this build will not send.
|
|
3101
|
+
case "REGISTRY_MISMATCH":
|
|
3102
|
+
case "PAYMENT_FAILED":
|
|
3103
|
+
case "REFUSED":
|
|
3104
|
+
case "USAGE":
|
|
3105
|
+
return unpaid("terms");
|
|
3106
|
+
// A transport failure or a timeout: no answer came back.
|
|
3107
|
+
case "NETWORK_ERROR":
|
|
3108
|
+
return unpaid("unreachable");
|
|
3109
|
+
// AN ANSWER THAT WAS NOT A USABLE 402. API_UNREACHABLE from the provider
|
|
3110
|
+
// leg always carries one (another status, or a redirect this build will
|
|
3111
|
+
// not follow); a transport failure is NETWORK_ERROR. The others: a
|
|
3112
|
+
// challenge this build cannot read, or a free body that missed its rule.
|
|
3113
|
+
case "API_UNREACHABLE":
|
|
3114
|
+
case "CONTRACT_MISMATCH":
|
|
3115
|
+
case "CHALLENGE_TOO_LARGE":
|
|
3116
|
+
return unpaid("provider");
|
|
3117
|
+
default:
|
|
3118
|
+
return null;
|
|
3119
|
+
}
|
|
3120
|
+
}
|
|
3121
|
+
function paidRecord(decision, url, sent, amountAtomic, opts) {
|
|
3122
|
+
return {
|
|
3123
|
+
version: 1,
|
|
3124
|
+
ts: new Date((opts.now ?? Date.now)()).toISOString(),
|
|
3125
|
+
capabilityId: decision.capabilityId,
|
|
3126
|
+
provider: decision.provider,
|
|
3127
|
+
...decision.label !== void 0 ? { label: decision.label } : {},
|
|
3128
|
+
// Who the call ran through: Tenjin's own tools, or a connected account.
|
|
3129
|
+
source: opts.account ?? BUILT_IN_SOURCE,
|
|
3130
|
+
...decision.via !== void 0 ? { via: decision.via } : {},
|
|
3131
|
+
url,
|
|
3132
|
+
sent: recordedSent(sent),
|
|
3133
|
+
amountAtomic: amountAtomic.toString(),
|
|
3134
|
+
...opts.txHash !== void 0 ? { txHash: opts.txHash } : {},
|
|
3135
|
+
...opts.reportedTxHash !== void 0 ? { reportedTxHash: opts.reportedTxHash } : {},
|
|
3136
|
+
settlement: opts.account !== void 0 ? "account" : opts.txHash !== void 0 || opts.settled === true ? "settled" : "unknown",
|
|
3137
|
+
savedFiles: opts.savedFiles,
|
|
3138
|
+
...opts.payer !== void 0 ? { payer: opts.payer } : {},
|
|
3139
|
+
...opts.authorization !== void 0 ? { authorization: opts.authorization } : {}
|
|
3140
|
+
};
|
|
3141
|
+
}
|
|
3142
|
+
async function saveBinary(dataDir, capabilityId, bytes, opts) {
|
|
3143
|
+
const described = { contentType: opts.contentType, bytes: bytes.byteLength };
|
|
3144
|
+
if (opts.budget !== void 0 && bytes.byteLength > opts.budget.leftBytes) {
|
|
3145
|
+
return { saveError: CAP_REACHED, ...described };
|
|
3146
|
+
}
|
|
3147
|
+
if (opts.budget !== void 0) opts.budget.leftBytes -= bytes.byteLength;
|
|
3148
|
+
try {
|
|
3149
|
+
const savedTo = await writeNewFile(
|
|
3150
|
+
downloadsDir(dataDir),
|
|
3151
|
+
`${capabilityId.slice(0, 80)}-${(opts.now ?? Date.now)()}`,
|
|
3152
|
+
opts.contentType,
|
|
3153
|
+
bytes
|
|
3154
|
+
);
|
|
3155
|
+
return { savedTo, ...described };
|
|
3156
|
+
} catch (err) {
|
|
3157
|
+
if (opts.budget !== void 0) opts.budget.leftBytes += bytes.byteLength;
|
|
3158
|
+
return { saveError: err instanceof Error ? err.message : String(err), ...described };
|
|
3159
|
+
}
|
|
3160
|
+
}
|
|
3161
|
+
function checkContract(contract) {
|
|
3162
|
+
const built = contract.request;
|
|
3163
|
+
if (built.method !== "GET" && built.method !== "POST") {
|
|
3164
|
+
return {
|
|
3165
|
+
status: "failed",
|
|
3166
|
+
reason: `This build executes GET and POST only, not ${built.method}.`
|
|
3167
|
+
};
|
|
3168
|
+
}
|
|
3169
|
+
const header = unsafeHeader(built.headers);
|
|
3170
|
+
if (header !== null) {
|
|
3171
|
+
return {
|
|
3172
|
+
status: "failed",
|
|
3173
|
+
reason: `The decision sets a header this build will not send: ${header}`
|
|
3174
|
+
};
|
|
3175
|
+
}
|
|
3176
|
+
if (built.method === "GET" && built.body !== void 0) {
|
|
3177
|
+
return { status: "failed", reason: "The decision puts a body on a GET." };
|
|
3178
|
+
}
|
|
3179
|
+
if (contract.resultSchema !== void 0) {
|
|
3180
|
+
try {
|
|
3181
|
+
assertResultSchema(contract.resultSchema);
|
|
3182
|
+
} catch (err) {
|
|
3183
|
+
return {
|
|
3184
|
+
status: "failed",
|
|
3185
|
+
reason: `The decision's success rule is unusable: ${String(err)}`
|
|
3186
|
+
};
|
|
3187
|
+
}
|
|
3188
|
+
}
|
|
3189
|
+
try {
|
|
3190
|
+
new URL(built.url);
|
|
3191
|
+
} catch {
|
|
3192
|
+
return { status: "failed", reason: "The decision names a URL this build cannot parse." };
|
|
3193
|
+
}
|
|
3194
|
+
return null;
|
|
3195
|
+
}
|
|
3196
|
+
var SENDABLE_HEADERS = /* @__PURE__ */ new Set(["accept", "content-type"]);
|
|
3197
|
+
function unsafeHeader(headers) {
|
|
3198
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
3199
|
+
if (!SENDABLE_HEADERS.has(name.toLowerCase())) return name;
|
|
3200
|
+
if (value.length > 1024 || /[\r\n]/.test(value)) return name;
|
|
3201
|
+
}
|
|
3202
|
+
return null;
|
|
3203
|
+
}
|
|
3204
|
+
function supplierOf(url) {
|
|
3205
|
+
try {
|
|
3206
|
+
return new URL(url).hostname;
|
|
3207
|
+
} catch {
|
|
3208
|
+
return "unknown service";
|
|
3209
|
+
}
|
|
3210
|
+
}
|
|
3211
|
+
function accountCost(label) {
|
|
3212
|
+
return [`billed to your ${label} account, not the Tenjin balance`];
|
|
3213
|
+
}
|
|
3214
|
+
function accountReceipt(account, body, savedFiles) {
|
|
3215
|
+
const parts = [account.label, "your account"];
|
|
3216
|
+
if (savedFiles.length > 0) {
|
|
3217
|
+
parts.push(`${savedFiles.length} ${savedFiles.length === 1 ? "file" : "files"} saved`);
|
|
3218
|
+
return parts.join(" \xB7 ");
|
|
3219
|
+
}
|
|
3220
|
+
let value = body;
|
|
3221
|
+
if (typeof body === "string") {
|
|
3222
|
+
try {
|
|
3223
|
+
value = JSON.parse(body);
|
|
3224
|
+
} catch {
|
|
3225
|
+
return parts.join(" \xB7 ");
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
const lists = value !== null && typeof value === "object" && !Array.isArray(value) ? Object.values(value).filter(Array.isArray) : [];
|
|
3229
|
+
const items = Array.isArray(value) ? value : lists.length === 1 ? lists[0] : void 0;
|
|
3230
|
+
if (items !== void 0) {
|
|
3231
|
+
const noun = /^the ([a-z]+s)\b/.exec(account.returns ?? "")?.[1];
|
|
3232
|
+
parts.push(items.length === 1 ? "1 result" : `${items.length} ${noun ?? "results"}`);
|
|
3233
|
+
}
|
|
3234
|
+
return parts.join(" \xB7 ");
|
|
3235
|
+
}
|
|
3236
|
+
function costLines(providerAtomic) {
|
|
3237
|
+
return [`provider price ${toMoney(providerAtomic.toString()).usd} USD`];
|
|
3238
|
+
}
|
|
3239
|
+
var ROUTINE = /* @__PURE__ */ new Set(["native", "needs_input", "needs_approval"]);
|
|
3240
|
+
var ROUTER_OFF_NEXT_STEP = "Continue with your own tools. Nothing was sent to the router and nothing was bought.";
|
|
3241
|
+
async function routerHere(deps) {
|
|
3242
|
+
try {
|
|
3243
|
+
const settings = await routerSettings({
|
|
3244
|
+
cwd: deps.cwd ?? process.cwd(),
|
|
3245
|
+
dataDir: deps.ctx.dataDir
|
|
3246
|
+
});
|
|
3247
|
+
if (settings.enabled.value) return { settings };
|
|
3248
|
+
return {
|
|
3249
|
+
off: `router.enabled is false in ${settings.enabled.path ?? "the config"}, so the router is off here.`
|
|
3250
|
+
};
|
|
3251
|
+
} catch (err) {
|
|
3252
|
+
return {
|
|
3253
|
+
off: `router.enabled could not be read (${err instanceof Error ? err.message : String(err)}), so the router is off here.`
|
|
3254
|
+
};
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
var NEXT_STEP = {
|
|
3258
|
+
native: "Continue with your own tools. Nothing was bought.",
|
|
3259
|
+
needs_input: "Ask the user for the missing detail, then call `request` again with it. Nothing was bought.",
|
|
3260
|
+
needs_approval: "Tell the user what it would cost; nothing was paid."
|
|
3261
|
+
};
|
|
3262
|
+
var NEXT_STEP_BY_REASON = {
|
|
3263
|
+
page_target: "That URL is the lookup itself; call `request` again with the URL as the query.",
|
|
3264
|
+
contextual_url: "The URL was background, not the target; call `request` again with the question as the query.",
|
|
3265
|
+
unresolved_intent: "Ask the user for the scope choice or field named above, then call `request` again with it.",
|
|
3266
|
+
classifier_failure: "The router could not classify this one and charged nothing. Continue with your own tools, or call `request` once more."
|
|
3267
|
+
};
|
|
3268
|
+
function summaryFor(status, reason) {
|
|
3269
|
+
if (status === "native") return `Use your usual tools: ${reason}`;
|
|
3270
|
+
if (status === "needs_input") return `More input needed: ${reason}`;
|
|
3271
|
+
if (status === "needs_approval") return `Needs the user's approval: ${reason}`;
|
|
3272
|
+
return `x402 request ${status}: ${reason}`;
|
|
3273
|
+
}
|
|
3274
|
+
function nextStepFor(status, diagnostics) {
|
|
3275
|
+
const fromServer = diagnostics?.nextAction.trim() ?? "";
|
|
3276
|
+
if (fromServer.length > 0) return fromServer;
|
|
3277
|
+
const byReason = diagnostics !== void 0 ? NEXT_STEP_BY_REASON[diagnostics.reasonCode] : void 0;
|
|
3278
|
+
return byReason ?? NEXT_STEP[status] ?? "";
|
|
3279
|
+
}
|
|
3280
|
+
function settingsFail(refusal) {
|
|
3281
|
+
return fail("needs_input", refusal.reason, {
|
|
3282
|
+
diagnostics: {
|
|
3283
|
+
reasonCode: refusal.code,
|
|
3284
|
+
stage: "client",
|
|
3285
|
+
missing: [],
|
|
3286
|
+
nextAction: refusal.nextStep
|
|
3287
|
+
}
|
|
3288
|
+
});
|
|
3289
|
+
}
|
|
3290
|
+
function fail(status, reason, extras = {}) {
|
|
3291
|
+
const routine = ROUTINE.has(status);
|
|
3292
|
+
const { diagnostics } = extras;
|
|
3293
|
+
return {
|
|
3294
|
+
isError: !routine,
|
|
3295
|
+
summary: summaryFor(status, reason),
|
|
3296
|
+
envelope: {
|
|
3297
|
+
status,
|
|
3298
|
+
reason,
|
|
3299
|
+
...extras.errorCode !== void 0 ? { errorCode: extras.errorCode } : {},
|
|
3300
|
+
...extras.quote !== void 0 ? { quote: extras.quote } : {},
|
|
3301
|
+
// The status is the fact; the next step is what to do about it. The
|
|
3302
|
+
// BACKEND'S own next action wins when it sent one: it knows which field
|
|
3303
|
+
// is missing.
|
|
3304
|
+
...routine || diagnostics !== void 0 || extras.nextStep !== void 0 ? { nextStep: extras.nextStep ?? nextStepFor(status, diagnostics) } : {},
|
|
3305
|
+
...diagnostics !== void 0 ? {
|
|
3306
|
+
reasonCode: diagnostics.reasonCode,
|
|
3307
|
+
stage: diagnostics.stage,
|
|
3308
|
+
...diagnostics.missing.length > 0 ? { missing: diagnostics.missing } : {}
|
|
3309
|
+
} : {},
|
|
3310
|
+
// What LEFT, not what was delivered: an authorization that was
|
|
3311
|
+
// transmitted is money at risk whether or not a result came back.
|
|
3312
|
+
cost: costLines(extras.providerAtomic ?? 0n),
|
|
3313
|
+
...extras.note !== void 0 ? { note: extras.note } : {},
|
|
3314
|
+
...extras.settlement !== void 0 ? { settlement: extras.settlement } : {},
|
|
3315
|
+
...extras.diagnosis !== void 0 ? { diagnosis: extras.diagnosis } : {},
|
|
3316
|
+
...extras.providerStatus !== void 0 ? { providerStatus: extras.providerStatus } : {},
|
|
3317
|
+
...extras.providerError !== void 0 ? { providerError: extras.providerError } : {},
|
|
3318
|
+
...extras.settlementError !== void 0 ? { settlementError: extras.settlementError } : {},
|
|
3319
|
+
...extras.paymentError !== void 0 ? { paymentError: extras.paymentError } : {},
|
|
3320
|
+
...extras.statusUrl !== void 0 ? { statusUrl: extras.statusUrl } : {},
|
|
3321
|
+
...extras.request !== void 0 ? { request: extras.request } : {},
|
|
3322
|
+
...extras.parameters !== void 0 ? { parameters: extras.parameters } : {},
|
|
3323
|
+
providerContentUntrusted: true
|
|
3324
|
+
}
|
|
3325
|
+
};
|
|
3326
|
+
}
|
|
3327
|
+
|
|
3328
|
+
export {
|
|
3329
|
+
keepAccountJob,
|
|
3330
|
+
readAccountJob,
|
|
3331
|
+
endAccountJob,
|
|
3332
|
+
specText,
|
|
3333
|
+
mergedInput,
|
|
3334
|
+
specInputProblems,
|
|
3335
|
+
MAX_CALL_WAIT_MS,
|
|
3336
|
+
runRequestTool,
|
|
3337
|
+
runApproveTool,
|
|
3338
|
+
showSpec,
|
|
3339
|
+
runSpec,
|
|
3340
|
+
reportOutcome,
|
|
3341
|
+
deliverResult,
|
|
3342
|
+
unsavedWords,
|
|
3343
|
+
paidRecord,
|
|
3344
|
+
costLines,
|
|
3345
|
+
settingsFail,
|
|
3346
|
+
fail
|
|
3347
|
+
};
|
|
3348
|
+
//# sourceMappingURL=chunk-5HN4KVQU.js.map
|