tenjin-cli 0.1.0-alpha.34 → 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 +30 -0
- package/README.md +20 -18
- package/dist/{_esm-MMYV66AX.js → _esm-2KST7HQ7.js} +4 -4
- package/dist/{alive-VOIL5W3I.js → alive-5TV22PNF.js} +13 -13
- package/dist/{auth-UHD3QFX4.js → auth-XI7BJFLW.js} +4 -4
- package/dist/balance-DFHC6XEU.js +71 -0
- package/dist/{ccip-CS7K5QRQ.js → ccip-HOW3DZYF.js} +3 -3
- package/dist/{chunk-RJ5HRPAZ.js → chunk-24XKUN2S.js} +68 -10
- 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-PZHBPGDE.js → chunk-34SAECKZ.js} +34 -10
- package/dist/chunk-34SAECKZ.js.map +1 -0
- package/dist/{chunk-EQZ2CCWC.js → chunk-3Y2EHT4F.js} +5 -2
- package/dist/chunk-3Y2EHT4F.js.map +1 -0
- package/dist/{chunk-FSYH7J75.js → chunk-3Y6BHIN6.js} +3 -3
- package/dist/{chunk-FZZWTDWP.js → chunk-3YPL6T3P.js} +6 -6
- package/dist/{chunk-JEZMWJEF.js → chunk-44MVIRZH.js} +4 -4
- package/dist/{chunk-27FIHFXF.js → chunk-45MMSBHA.js} +5 -5
- 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-7JB6SYJX.js → chunk-54ELBTKE.js} +2 -2
- package/dist/{chunk-6J64MQFD.js → chunk-5F4OB5B3.js} +21 -15
- package/dist/chunk-5F4OB5B3.js.map +1 -0
- package/dist/{chunk-PYVQ74D5.js → chunk-5HN4KVQU.js} +189 -117
- package/dist/chunk-5HN4KVQU.js.map +1 -0
- package/dist/{chunk-VFKPIIV2.js → chunk-5J4E5GYI.js} +35 -32
- package/dist/chunk-5J4E5GYI.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-APWELUI7.js → chunk-65RS4LQS.js} +57 -43
- package/dist/chunk-65RS4LQS.js.map +1 -0
- package/dist/{chunk-HWZO6HYZ.js → chunk-6QMDUDF2.js} +3 -3
- package/dist/{chunk-FNBGRKS6.js → chunk-7V25UAQO.js} +2 -2
- 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-MXN2ZEUB.js → chunk-D6M3ZK66.js} +2 -2
- package/dist/chunk-D6M3ZK66.js.map +1 -0
- package/dist/chunk-DJ36BM62.js +78 -0
- package/dist/chunk-DJ36BM62.js.map +1 -0
- package/dist/{chunk-JOKPBYXP.js → chunk-DTEWAVNE.js} +2 -2
- package/dist/chunk-F2KJAJ7T.js +13 -0
- package/dist/chunk-F2KJAJ7T.js.map +1 -0
- package/dist/{chunk-KAILF7QA.js → chunk-F43CV6UC.js} +2 -2
- package/dist/{chunk-ACO7ZCR2.js → chunk-FKVJKLPI.js} +2 -2
- package/dist/{chunk-43HLS2HM.js → chunk-FYFHH7V5.js} +54 -3
- package/dist/{chunk-43HLS2HM.js.map → chunk-FYFHH7V5.js.map} +1 -1
- package/dist/{chunk-2F5JUAHZ.js → chunk-GAJC4BQZ.js} +3 -3
- package/dist/{chunk-L7N73ZAW.js → chunk-HAZAN4UM.js} +2 -2
- package/dist/{chunk-6QJZA6EX.js → chunk-HI5XQOX2.js} +2 -2
- package/dist/{chunk-BOENA6XR.js → chunk-HKGUKAQW.js} +6 -6
- package/dist/{chunk-LJSCGIYH.js → chunk-HPRVFJPM.js} +2 -2
- package/dist/{chunk-OO6FIBL7.js → chunk-HZKANST2.js} +3 -6
- package/dist/chunk-HZKANST2.js.map +1 -0
- package/dist/{chunk-UVDJ5SSQ.js → chunk-I557SAOM.js} +8 -2
- package/dist/chunk-I557SAOM.js.map +1 -0
- package/dist/{chunk-SDUOJRSV.js → chunk-IGLWLH73.js} +3 -3
- package/dist/{chunk-3AKH7ODX.js → chunk-INSIW65E.js} +5 -5
- package/dist/{chunk-PNHNXUSL.js → chunk-IULCDMVG.js} +12 -1
- package/dist/chunk-IULCDMVG.js.map +1 -0
- package/dist/{chunk-JF4T4HCQ.js → chunk-IVNSUAVC.js} +10 -5
- 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-2P3NJTHE.js → chunk-JHFFUVON.js} +23 -23
- package/dist/{chunk-7JVARP5R.js → chunk-JTILUN4W.js} +55 -29
- package/dist/{chunk-7JVARP5R.js.map → chunk-JTILUN4W.js.map} +1 -1
- package/dist/{chunk-2TO5F6CT.js → chunk-K5KNGC4I.js} +8 -8
- package/dist/{chunk-HUWTFKEM.js → chunk-KAQ4Q3TO.js} +3 -3
- package/dist/{chunk-E6VP6MQM.js → chunk-KGUE5AVX.js} +4 -4
- package/dist/chunk-KGUE5AVX.js.map +1 -0
- package/dist/{chunk-GS5RZF7U.js → chunk-KLDMLWXT.js} +2 -2
- package/dist/{chunk-HN2EN6P4.js → chunk-KNKDMTHU.js} +5 -5
- 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-5VWQSCDO.js → chunk-MAHNZA6C.js} +89 -9
- package/dist/chunk-MAHNZA6C.js.map +1 -0
- package/dist/{chunk-46HAB26L.js → chunk-MEWZCIA6.js} +56 -9
- package/dist/chunk-MEWZCIA6.js.map +1 -0
- package/dist/{chunk-R2KMLONN.js → chunk-MJDO4EXD.js} +4 -4
- package/dist/{chunk-IHVUE3XF.js → chunk-NJA6NT3A.js} +3 -3
- package/dist/{chunk-TSIID2LV.js → chunk-ODRPASFP.js} +375 -1166
- package/dist/chunk-ODRPASFP.js.map +1 -0
- package/dist/{chunk-S3JKF3IK.js → chunk-OJJFANO6.js} +3 -3
- package/dist/{chunk-56SOPRM2.js → chunk-OQWPRFAC.js} +344 -4
- package/dist/chunk-OQWPRFAC.js.map +1 -0
- package/dist/{chunk-QEZZDIQT.js → chunk-P6YQWIT2.js} +4053 -4039
- package/dist/chunk-P6YQWIT2.js.map +1 -0
- package/dist/{chunk-GGGEGMWC.js → chunk-Q6RSJCXB.js} +9 -9
- package/dist/{chunk-OTIUEUIS.js → chunk-QKEUKBRK.js} +7 -7
- package/dist/{chunk-X52BVGCJ.js → chunk-QQDPRTLP.js} +5 -5
- 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-6AQSUBNR.js → chunk-RGCPELQN.js} +2 -2
- package/dist/{chunk-AXODGQ23.js → chunk-RGVCOG2S.js} +9 -2
- package/dist/{chunk-AXODGQ23.js.map → chunk-RGVCOG2S.js.map} +1 -1
- package/dist/chunk-SOLNJ3AZ.js +209 -0
- package/dist/chunk-SOLNJ3AZ.js.map +1 -0
- package/dist/{chunk-LQ33RLHL.js → chunk-TFT2X7SH.js} +3 -3
- package/dist/chunk-TVWCLUBI.js +293 -0
- package/dist/chunk-TVWCLUBI.js.map +1 -0
- package/dist/{chunk-VH7JMLTG.js → chunk-UIB33QQP.js} +25 -16
- 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-IVHGQNIN.js → chunk-VHXCPXUS.js} +8 -8
- package/dist/{chunk-7DW7GAM6.js → chunk-VU6GMWF6.js} +2 -2
- package/dist/chunk-VWZYE3NC.js +8415 -0
- package/dist/chunk-VWZYE3NC.js.map +1 -0
- package/dist/{chunk-3X4GOMXT.js → chunk-W2GXIARJ.js} +12 -7
- 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-FHXTEVO7.js → chunk-W74LJ5OT.js} +21 -28
- package/dist/chunk-W74LJ5OT.js.map +1 -0
- package/dist/{chunk-FOEPH67T.js → chunk-W7ELYLYK.js} +1 -74
- package/dist/chunk-W7ELYLYK.js.map +1 -0
- package/dist/{chunk-YU3DLVSQ.js → chunk-XSCGUO2U.js} +5 -5
- package/dist/{chunk-EPCIJLLU.js → chunk-XWROSMI5.js} +9 -9
- package/dist/{chunk-HMT6L65V.js → chunk-YJGEVBKZ.js} +4 -4
- package/dist/{chunk-7U3P4PB7.js → chunk-ZEYA2WWX.js} +4 -4
- 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-I47ARU5G.js → chunk-ZS7JIUJ3.js} +2 -2
- package/dist/{claude-cli-2YKABJJZ.js → claude-cli-GIIHOBGT.js} +4 -2
- package/dist/claude-install-BAUSJMW3.js +64 -0
- package/dist/{cli-BFDKEX53.js → cli-QY4KKA3D.js} +116 -49
- package/dist/cli-QY4KKA3D.js.map +1 -0
- package/dist/{client-XMWEKXX7.js → client-3YQKORVK.js} +4 -4
- package/dist/{codex-host-B6NAUWL6.js → codex-host-ZON3S6HU.js} +5 -5
- package/dist/{codex-install-GTGO5FYN.js → codex-install-HZV2DOAB.js} +62 -47
- package/dist/codex-install-HZV2DOAB.js.map +1 -0
- package/dist/{config-THJANIU5.js → config-QZOBMTEL.js} +18 -18
- package/dist/{config-names-JU54HYWY.js → config-names-Z5NZD5R2.js} +18 -18
- package/dist/{config-rules-VNU23RL4.js → config-rules-YOYHS6YL.js} +19 -19
- package/dist/config-subagents-WQV2ZAD5.js +362 -0
- package/dist/config-subagents-WQV2ZAD5.js.map +1 -0
- package/dist/{connect-HPWS7U63.js → connect-YDWTYU4B.js} +28 -27
- package/dist/{connect-HPWS7U63.js.map → connect-YDWTYU4B.js.map} +1 -1
- 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-JIIHDTOF.js → decision-QSKHOGCO.js} +6 -6
- package/dist/{doctor-4MMHBRDU.js → doctor-ZWJXRD75.js} +67 -66
- package/dist/doctor-ZWJXRD75.js.map +1 -0
- package/dist/{explicit-AGENAX6E.js → explicit-ME2NRADQ.js} +45 -42
- package/dist/{explicit-AGENAX6E.js.map → explicit-ME2NRADQ.js.map} +1 -1
- package/dist/flush-stdio-NYIJ3QXT.js +18 -0
- package/dist/{fund-MLXUH24Q.js → fund-VF7TLDJH.js} +110 -34
- package/dist/fund-VF7TLDJH.js.map +1 -0
- package/dist/{hook-command-UB7FOEUL.js → hook-command-VZ27MGWO.js} +21 -20
- 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 +265 -30
- package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +14 -4
- package/dist/hosts/claude/tenjin/types/index.d.ts +133 -0
- package/dist/{hosts-WNQKYKP2.js → hosts-3EMTVM4H.js} +5 -3
- package/dist/index.js +16 -13
- package/dist/index.js.map +1 -1
- package/dist/{install-Q5SHHEDH.js → install-ZA7L2UF3.js} +34 -30
- package/dist/{install-funding-EGSW2KEP.js → install-funding-JDGYTF72.js} +9 -13
- package/dist/{install-identity-OID43B4D.js → install-identity-FFAYEFLX.js} +8 -8
- package/dist/{install-wallet-TZFWY5GK.js → install-wallet-2SFOVE3Q.js} +48 -33
- package/dist/{install-wallet-TZFWY5GK.js.map → install-wallet-2SFOVE3Q.js.map} +1 -1
- 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-NRHU7HBR.js → package-BONDXSV3.js} +2 -2
- package/dist/{passphrase-3JEVW5XG.js → passphrase-T4ULBN4M.js} +4 -4
- package/dist/{pay-I47AIUQR.js → pay-CMV5KL74.js} +37 -30
- package/dist/{payments-A5FNI5GN.js → payments-Z6UBZL4Z.js} +10 -10
- package/dist/reclaim-subagent-credit-ABSF67SJ.js +105 -0
- package/dist/reclaim-subagent-credit-ABSF67SJ.js.map +1 -0
- package/dist/{routing-quote-QQW2I5MH.js → routing-quote-AHLAREXR.js} +16 -18
- package/dist/{run-4SHEOBIU.js → run-JH7ELYAM.js} +41 -38
- package/dist/{runtime-BABJMHY7.js → runtime-2GX4ALJP.js} +12 -12
- package/dist/{runtime-activate-N6VLQI2C.js → runtime-activate-IDQ2NCSP.js} +9 -9
- package/dist/{runtime-launchers-GMAUICRW.js → runtime-launchers-YAPKCBHV.js} +7 -7
- package/dist/{runtime-place-DOEWFTF3.js → runtime-place-4POL4KK4.js} +3 -3
- package/dist/{send-ECXS6JEO.js → send-ELXFKEKY.js} +17 -17
- package/dist/{status-AHE5HSR7.js → status-FXUFWJDM.js} +89 -36
- package/dist/status-FXUFWJDM.js.map +1 -0
- package/dist/{status-line-63XFJAXR.js → status-line-IH5JBWBC.js} +11 -11
- package/dist/{streamableHttp-Z3YF6LTQ.js → streamableHttp-CP2ZQBIK.js} +4 -4
- package/dist/{uninstall-YGQPRCVY.js → uninstall-LJZUKM4D.js} +42 -38
- package/dist/{uninstall-YGQPRCVY.js.map → uninstall-LJZUKM4D.js.map} +1 -1
- package/dist/{update-GTLMLFA3.js → update-EUIX72IX.js} +34 -30
- package/dist/{usage-FCWP2CHO.js → usage-EKDC7LUC.js} +13 -13
- package/dist/{usdc-25RNBYYR.js → usdc-YIHK2OMC.js} +5 -5
- package/dist/{viemAdapter-By13KInL-3CG63XDX.js → viemAdapter-By13KInL-PRLSIESK.js} +2 -2
- 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/docs/agent-permissions.md +19 -11
- package/docs/router-reference.md +21 -12
- package/docs/safety-model.md +4 -2
- package/docs/subagents-internals.md +97 -0
- package/docs/subagents.md +348 -0
- package/package.json +4 -1
- package/dist/balance-RQW5T5FB.js +0 -55
- package/dist/chunk-3X4GOMXT.js.map +0 -1
- package/dist/chunk-46HAB26L.js.map +0 -1
- package/dist/chunk-56SOPRM2.js.map +0 -1
- package/dist/chunk-5VWQSCDO.js.map +0 -1
- package/dist/chunk-6J64MQFD.js.map +0 -1
- package/dist/chunk-7U3P4PB7.js.map +0 -1
- package/dist/chunk-APWELUI7.js.map +0 -1
- package/dist/chunk-E6VP6MQM.js.map +0 -1
- package/dist/chunk-EQZ2CCWC.js.map +0 -1
- package/dist/chunk-FHXTEVO7.js.map +0 -1
- package/dist/chunk-FOEPH67T.js.map +0 -1
- package/dist/chunk-IVXPIIZJ.js +0 -91
- package/dist/chunk-IVXPIIZJ.js.map +0 -1
- package/dist/chunk-JF4T4HCQ.js.map +0 -1
- package/dist/chunk-LPQNZKSG.js +0 -269
- package/dist/chunk-LPQNZKSG.js.map +0 -1
- package/dist/chunk-MXN2ZEUB.js.map +0 -1
- package/dist/chunk-OO6FIBL7.js.map +0 -1
- package/dist/chunk-PNHNXUSL.js.map +0 -1
- package/dist/chunk-PYVQ74D5.js.map +0 -1
- package/dist/chunk-PZHBPGDE.js.map +0 -1
- package/dist/chunk-QEZZDIQT.js.map +0 -1
- package/dist/chunk-QXP3Z3JN.js.map +0 -1
- package/dist/chunk-RJ5HRPAZ.js.map +0 -1
- package/dist/chunk-TSIID2LV.js.map +0 -1
- package/dist/chunk-UVDJ5SSQ.js.map +0 -1
- package/dist/chunk-VFKPIIV2.js.map +0 -1
- package/dist/chunk-VH7JMLTG.js.map +0 -1
- package/dist/claude-install-7CVYQ73E.js +0 -60
- package/dist/cli-BFDKEX53.js.map +0 -1
- package/dist/codex-install-GTGO5FYN.js.map +0 -1
- package/dist/doctor-4MMHBRDU.js.map +0 -1
- package/dist/fund-MLXUH24Q.js.map +0 -1
- package/dist/mcp-CC3H7LFO.js +0 -3655
- package/dist/mcp-CC3H7LFO.js.map +0 -1
- package/dist/status-AHE5HSR7.js.map +0 -1
- package/dist/wallet-CJGEHP2Q.js +0 -64
- /package/dist/{_esm-MMYV66AX.js.map → _esm-2KST7HQ7.js.map} +0 -0
- /package/dist/{alive-VOIL5W3I.js.map → alive-5TV22PNF.js.map} +0 -0
- /package/dist/{auth-UHD3QFX4.js.map → auth-XI7BJFLW.js.map} +0 -0
- /package/dist/{balance-RQW5T5FB.js.map → balance-DFHC6XEU.js.map} +0 -0
- /package/dist/{ccip-CS7K5QRQ.js.map → ccip-HOW3DZYF.js.map} +0 -0
- /package/dist/{chunk-FSYH7J75.js.map → chunk-3Y6BHIN6.js.map} +0 -0
- /package/dist/{chunk-FZZWTDWP.js.map → chunk-3YPL6T3P.js.map} +0 -0
- /package/dist/{chunk-JEZMWJEF.js.map → chunk-44MVIRZH.js.map} +0 -0
- /package/dist/{chunk-27FIHFXF.js.map → chunk-45MMSBHA.js.map} +0 -0
- /package/dist/{chunk-7JB6SYJX.js.map → chunk-54ELBTKE.js.map} +0 -0
- /package/dist/{chunk-HWZO6HYZ.js.map → chunk-6QMDUDF2.js.map} +0 -0
- /package/dist/{chunk-FNBGRKS6.js.map → chunk-7V25UAQO.js.map} +0 -0
- /package/dist/{chunk-JOKPBYXP.js.map → chunk-DTEWAVNE.js.map} +0 -0
- /package/dist/{chunk-KAILF7QA.js.map → chunk-F43CV6UC.js.map} +0 -0
- /package/dist/{chunk-ACO7ZCR2.js.map → chunk-FKVJKLPI.js.map} +0 -0
- /package/dist/{chunk-2F5JUAHZ.js.map → chunk-GAJC4BQZ.js.map} +0 -0
- /package/dist/{chunk-L7N73ZAW.js.map → chunk-HAZAN4UM.js.map} +0 -0
- /package/dist/{chunk-6QJZA6EX.js.map → chunk-HI5XQOX2.js.map} +0 -0
- /package/dist/{chunk-BOENA6XR.js.map → chunk-HKGUKAQW.js.map} +0 -0
- /package/dist/{chunk-LJSCGIYH.js.map → chunk-HPRVFJPM.js.map} +0 -0
- /package/dist/{chunk-SDUOJRSV.js.map → chunk-IGLWLH73.js.map} +0 -0
- /package/dist/{chunk-3AKH7ODX.js.map → chunk-INSIW65E.js.map} +0 -0
- /package/dist/{chunk-2P3NJTHE.js.map → chunk-JHFFUVON.js.map} +0 -0
- /package/dist/{chunk-2TO5F6CT.js.map → chunk-K5KNGC4I.js.map} +0 -0
- /package/dist/{chunk-HUWTFKEM.js.map → chunk-KAQ4Q3TO.js.map} +0 -0
- /package/dist/{chunk-GS5RZF7U.js.map → chunk-KLDMLWXT.js.map} +0 -0
- /package/dist/{chunk-HN2EN6P4.js.map → chunk-KNKDMTHU.js.map} +0 -0
- /package/dist/{chunk-R2KMLONN.js.map → chunk-MJDO4EXD.js.map} +0 -0
- /package/dist/{chunk-IHVUE3XF.js.map → chunk-NJA6NT3A.js.map} +0 -0
- /package/dist/{chunk-S3JKF3IK.js.map → chunk-OJJFANO6.js.map} +0 -0
- /package/dist/{chunk-GGGEGMWC.js.map → chunk-Q6RSJCXB.js.map} +0 -0
- /package/dist/{chunk-OTIUEUIS.js.map → chunk-QKEUKBRK.js.map} +0 -0
- /package/dist/{chunk-X52BVGCJ.js.map → chunk-QQDPRTLP.js.map} +0 -0
- /package/dist/{chunk-6AQSUBNR.js.map → chunk-RGCPELQN.js.map} +0 -0
- /package/dist/{chunk-LQ33RLHL.js.map → chunk-TFT2X7SH.js.map} +0 -0
- /package/dist/{chunk-IVHGQNIN.js.map → chunk-VHXCPXUS.js.map} +0 -0
- /package/dist/{chunk-7DW7GAM6.js.map → chunk-VU6GMWF6.js.map} +0 -0
- /package/dist/{chunk-YU3DLVSQ.js.map → chunk-XSCGUO2U.js.map} +0 -0
- /package/dist/{chunk-EPCIJLLU.js.map → chunk-XWROSMI5.js.map} +0 -0
- /package/dist/{chunk-HMT6L65V.js.map → chunk-YJGEVBKZ.js.map} +0 -0
- /package/dist/{chunk-I47ARU5G.js.map → chunk-ZS7JIUJ3.js.map} +0 -0
- /package/dist/{claude-cli-2YKABJJZ.js.map → claude-cli-GIIHOBGT.js.map} +0 -0
- /package/dist/{claude-install-7CVYQ73E.js.map → claude-install-BAUSJMW3.js.map} +0 -0
- /package/dist/{client-XMWEKXX7.js.map → client-3YQKORVK.js.map} +0 -0
- /package/dist/{codex-host-B6NAUWL6.js.map → codex-host-ZON3S6HU.js.map} +0 -0
- /package/dist/{config-THJANIU5.js.map → config-QZOBMTEL.js.map} +0 -0
- /package/dist/{config-names-JU54HYWY.js.map → config-names-Z5NZD5R2.js.map} +0 -0
- /package/dist/{config-rules-VNU23RL4.js.map → config-rules-YOYHS6YL.js.map} +0 -0
- /package/dist/{decision-JIIHDTOF.js.map → decision-QSKHOGCO.js.map} +0 -0
- /package/dist/{hook-command-UB7FOEUL.js.map → flush-stdio-NYIJ3QXT.js.map} +0 -0
- /package/dist/{hosts-WNQKYKP2.js.map → hook-command-VZ27MGWO.js.map} +0 -0
- /package/dist/{install-Q5SHHEDH.js.map → hosts-3EMTVM4H.js.map} +0 -0
- /package/dist/{install-funding-EGSW2KEP.js.map → install-ZA7L2UF3.js.map} +0 -0
- /package/dist/{install-identity-OID43B4D.js.map → install-funding-JDGYTF72.js.map} +0 -0
- /package/dist/{package-NRHU7HBR.js.map → install-identity-FFAYEFLX.js.map} +0 -0
- /package/dist/{passphrase-3JEVW5XG.js.map → new-install-5L4GY3LN.js.map} +0 -0
- /package/dist/{pay-I47AIUQR.js.map → package-BONDXSV3.js.map} +0 -0
- /package/dist/{routing-quote-QQW2I5MH.js.map → passphrase-T4ULBN4M.js.map} +0 -0
- /package/dist/{run-4SHEOBIU.js.map → pay-CMV5KL74.js.map} +0 -0
- /package/dist/{payments-A5FNI5GN.js.map → payments-Z6UBZL4Z.js.map} +0 -0
- /package/dist/{runtime-activate-N6VLQI2C.js.map → routing-quote-AHLAREXR.js.map} +0 -0
- /package/dist/{runtime-launchers-GMAUICRW.js.map → run-JH7ELYAM.js.map} +0 -0
- /package/dist/{runtime-BABJMHY7.js.map → runtime-2GX4ALJP.js.map} +0 -0
- /package/dist/{runtime-place-DOEWFTF3.js.map → runtime-activate-IDQ2NCSP.js.map} +0 -0
- /package/dist/{update-GTLMLFA3.js.map → runtime-launchers-YAPKCBHV.js.map} +0 -0
- /package/dist/{usdc-25RNBYYR.js.map → runtime-place-4POL4KK4.js.map} +0 -0
- /package/dist/{send-ECXS6JEO.js.map → send-ELXFKEKY.js.map} +0 -0
- /package/dist/{status-line-63XFJAXR.js.map → status-line-IH5JBWBC.js.map} +0 -0
- /package/dist/{streamableHttp-Z3YF6LTQ.js.map → streamableHttp-CP2ZQBIK.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-3CG63XDX.js.map → update-EUIX72IX.js.map} +0 -0
- /package/dist/{usage-FCWP2CHO.js.map → usage-EKDC7LUC.js.map} +0 -0
- /package/dist/{wallet-CJGEHP2Q.js.map → usdc-YIHK2OMC.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/accounts/jobs.ts","../src/router/spec-call.ts","../src/router/jobs.ts","../src/router/plan.ts","../src/router/choices.ts","../src/router/inline-media.ts","../src/router/job-store.ts","../src/router/tool.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { AccountSpecSchema } from '../decision';\nimport { readJsonFile, writePrivate } from '../store-files';\n\n/**\n * A JOB ON THE USER'S ACCOUNT THAT OUTLASTED ITS CALL, kept by the offer's id\n * so `request({job})` can finish it: the spec, the merged input, and the\n * billing call's own result, which is what its follow-up reads. Resuming sends\n * only the follow-up (its status calls and the fetch of the result); the call\n * that bills is never sent again. No credential is kept here: a resume reads\n * the account's sign-in like any call, and only while the account is still\n * connected here; a rule saved since does not stop it, since its billing call\n * already went out (`run.ts`).\n */\n\nconst DIR = join('progress', 'account-jobs');\n/** How long a job can be picked up again after its billing call. */\nexport const ACCOUNT_JOB_KEEP_MS = 12 * 60 * 60_000;\n/** The first result is kept whole; past this a job is not kept. */\nconst MAX_JOB_BYTES = 256 * 1024;\n\nconst AccountJobSchema = z.strictObject({\n version: z.literal(1),\n offerId: z.string().min(1).max(64),\n spec: AccountSpecSchema,\n input: z.record(z.string(), z.unknown()),\n first: z.unknown(),\n firstAt: z.number().int().nonnegative(),\n});\nexport type AccountJob = z.infer<typeof AccountJobSchema>;\n\nconst pathOf = (dataDir: string, offerId: string) =>\n join(dataDir, DIR, `${createHash('sha256').update(offerId).digest('hex')}.json`);\n\n/** Keep a job for a resume; false when it could not be kept. Never throws. */\nexport async function keepAccountJob(dataDir: string, job: AccountJob): Promise<boolean> {\n try {\n const text = JSON.stringify(job);\n if (Buffer.byteLength(text, 'utf8') > MAX_JOB_BYTES) return false;\n await writePrivate(pathOf(dataDir, job.offerId), text);\n return true;\n } catch {\n return false;\n }\n}\n\n/** The job kept under this id, or null: none, expired, damaged or not ours. */\nexport async function readAccountJob(\n dataDir: string,\n offerId: string,\n now: number = Date.now(),\n): Promise<AccountJob | null> {\n const parsed = AccountJobSchema.safeParse(\n await readJsonFile(pathOf(dataDir, offerId), MAX_JOB_BYTES),\n );\n if (!parsed.success || parsed.data.offerId !== offerId) return null;\n return now - parsed.data.firstAt > ACCOUNT_JOB_KEEP_MS ? null : parsed.data;\n}\n\n/** A job that ended: delivered, failed or past its keep time. */\nexport async function endAccountJob(dataDir: string, offerId: string): Promise<void> {\n await rm(pathOf(dataDir, offerId), { force: true }).catch(() => undefined);\n}\n","import { requestHeaderProblem } from '../lib/http';\nimport { toMoney } from '../lib/money';\nimport { inputProblems } from '../lib/request-schema';\nimport { isAccountSpec, type AccountSpec, type ToolSpec } from './decision';\n\n/**\n * A REQUEST SPEC, READ AND RUN. `request({id})` shows the agent a spec as text:\n * what the service does and costs, each input with its description and allowed\n * values, the fields Tenjin sets, one example and what comes back. `request({id,\n * input})` merges the pinned fields over the agent's input, checks the result\n * against the spec's schema, and builds the HTTP request the spec describes.\n * Nothing here talks to the network: the caller pays through `runPay`.\n */\n\ntype Json = Record<string, unknown>;\n\nconst record = (value: unknown): Json =>\n value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : {};\n\nconst clip = (text: string, max: number): string =>\n text.length <= max ? text : `${text.slice(0, max - 1).trimEnd()}…`;\n\n/** A schema's type as one short phrase: `string`, `array of string`, `object {a, b}`. */\nfunction typeOf(schema: Json): string {\n const type = Array.isArray(schema.type) ? schema.type.join(' | ') : schema.type;\n if (type === 'array') {\n const items = record(schema.items);\n return Object.keys(items).length ? `array of ${typeOf(items)}` : 'array';\n }\n if (type === 'object' || (type === undefined && schema.properties !== undefined)) {\n const names = Object.keys(record(schema.properties));\n return names.length ? `object {${clip(names.join(', '), 120)}}` : 'object';\n }\n if (typeof type === 'string') return type;\n if (Array.isArray(schema.anyOf) || Array.isArray(schema.oneOf)) return 'one of several shapes';\n return 'any';\n}\n\n/** One input as a line: its name, type, whether required, its description and\n * the values or bounds it allows. */\nfunction fieldLine(name: string, schema: Json, required: boolean, depth = 0): string {\n const parts = [`${name} (${typeOf(schema)}${required ? ', required' : ''})`];\n if (typeof schema.description === 'string') parts.push(clip(schema.description.trim(), 300));\n if (Array.isArray(schema.enum))\n parts.push(\n `one of ${schema.enum\n .slice(0, 25)\n .map((v) => JSON.stringify(v))\n .join(', ')}${schema.enum.length > 25 ? ', …' : ''}`,\n );\n const items = record(schema.items);\n if (Array.isArray(items.enum))\n parts.push(\n `each one of ${items.enum\n .slice(0, 25)\n .map((v) => JSON.stringify(v))\n .join(', ')}`,\n );\n if (schema.default !== undefined) parts.push(`default ${JSON.stringify(schema.default)}`);\n if (typeof schema.format === 'string') parts.push(`format ${schema.format}`);\n for (const [key, label] of [\n ['minimum', 'min'],\n ['maximum', 'max'],\n ['minLength', 'min length'],\n ['maxLength', 'max length'],\n ['maxItems', 'max items'],\n ] as const)\n if (typeof schema[key] === 'number') parts.push(`${label} ${String(schema[key])}`);\n return `${' '.repeat(depth)}- ${parts.join('; ')}`;\n}\n\n/** How far below an input its required sub-fields are spelled out, and how\n * many sub-field lines one spec may add in all: Google Maps' location circle\n * is three levels down, and a schema that nests without end stays short. */\nconst NESTED_DEPTH = 3;\nconst NESTED_LINES = 20;\n\n/**\n * An input's line, then each required field of the object it holds (or of\n * each item, for an array of objects), as its own line under the path a\n * problem names it by (`agent_context.agent_type`, `attachments[].filename`).\n * A required object is then filled from the spec, not learned one problem at\n * a time. Optional sub-fields stay names in the type; the example shows some.\n */\nfunction fieldLines(\n name: string,\n schema: Json,\n required: boolean,\n budget: { left: number },\n depth = 0,\n): string[] {\n const lines = [fieldLine(name, schema, required, depth)];\n if (depth >= NESTED_DEPTH) return lines;\n const items = record(schema.items);\n const nested: [string, Json] | undefined =\n schema.properties !== undefined\n ? [name, schema]\n : items.properties !== undefined\n ? [`${name}[]`, items]\n : undefined;\n if (nested === undefined) return lines;\n const [at, object] = nested;\n if (!Array.isArray(object.required)) return lines;\n const properties = record(object.properties);\n for (const sub of object.required) {\n if (typeof sub !== 'string') continue;\n if (budget.left <= 0) {\n if (budget.left === 0)\n lines.push(`${' '.repeat(depth + 1)}- … more required fields, not listed here`);\n budget.left = -1;\n break;\n }\n budget.left -= 1;\n lines.push(...fieldLines(`${at}.${sub}`, record(properties[sub]), true, budget, depth + 1));\n }\n return lines;\n}\n\n/** What one call costs, as the spec says it. */\nfunction priceLine(spec: ToolSpec): string {\n const price = `$${toMoney(spec.priceAtomic).usd}`;\n return spec.priceVaries\n ? `${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`\n : `${price} per call`;\n}\n\n/**\n * Who pays for a call on the user's own account, and where it runs: their\n * plan, never the Tenjin balance, and no address is shown, since the call\n * goes to the server they connected. `account` is the account's name.\n */\nfunction accountLines(account: string): string[] {\n return [\n `Price: billed to your ${account} account's own plan, not the Tenjin balance, and not counted in its limits.`,\n `Runs on: your ${account} account.`,\n ];\n}\n\n/** The spec as the agent reads it, ending with the call that runs it. An\n * account service's says the account pays, named by `account`. */\nexport function specText(id: string, spec: ToolSpec | AccountSpec, account?: string): string {\n const properties = record(spec.input.properties);\n const required = new Set(Array.isArray(spec.input.required) ? spec.input.required : []);\n const open = Object.keys(properties).filter((name) => !(name in spec.pinned));\n const ordered = [\n ...open.filter((name) => required.has(name)),\n ...open.filter((name) => !required.has(name)),\n ];\n const budget = { left: NESTED_LINES };\n const lines = [\n `${spec.provider}: ${spec.description}`,\n ...(isAccountSpec(spec)\n ? accountLines(account ?? spec.provider)\n : [\n `Price: ${priceLine(spec)}, paid by this machine's wallet straight to the provider.`,\n `Request: ${spec.request.method} ${spec.request.url}`,\n ]),\n ordered.length\n ? `Inputs:\\n${ordered.flatMap((name) => fieldLines(name, record(properties[name]), required.has(name), budget)).join('\\n')}`\n : 'Inputs: none.',\n ];\n if (Object.keys(spec.pinned).length)\n lines.push(\n `Set by Tenjin on every call (leave these out): ${Object.entries(spec.pinned)\n .map(([name, value]) => `${name} = ${JSON.stringify(value)}`)\n .join('; ')}`,\n );\n if (spec.example !== undefined) lines.push(`Example input: ${JSON.stringify(spec.example)}`);\n if (spec.returns !== undefined) lines.push(`Returns: ${spec.returns}`);\n if (spec.returnsExample !== undefined)\n lines.push(`Example of what comes back (shortened): ${JSON.stringify(spec.returnsExample)}`);\n lines.push(\n `To run it, call request({id: ${JSON.stringify(id)}, input: {...}}) with the inputs above. ${isAccountSpec(spec) ? 'Nothing has run yet.' : 'Nothing has been paid.'}`,\n );\n return lines.join('\\n');\n}\n\n/** The agent's input with the pinned fields over it: a pin always wins. */\nexport function mergedInput(spec: Pick<ToolSpec, 'pinned'>, input: Json): Json {\n return { ...input, ...spec.pinned };\n}\n\n/**\n * Every problem with the merged input, against the spec's own schema; [] when\n * it fits; undefined when this build cannot compile the schema, so nothing\n * here can say the input fits and the call must not be paid. A field the spec\n * does not name is a problem too, whatever the schema says about extras: the\n * agent has no description for it, so it is a guess, and a paid guess at that.\n */\nexport function specInputProblems(\n spec: Pick<ToolSpec, 'input' | 'pinned'>,\n merged: Json,\n): string[] | undefined {\n const problems = inputProblems(spec.input, merged);\n if (problems === undefined) return undefined;\n const properties = spec.input.properties;\n if (properties === null || typeof properties !== 'object' || Array.isArray(properties))\n return problems;\n for (const name of Object.keys(merged)) {\n if (Object.hasOwn(properties, name) || Object.hasOwn(spec.pinned, name)) continue;\n const problem = `the input has no field ${JSON.stringify(name)}`;\n if (!problems.includes(problem)) problems.push(problem);\n }\n return problems;\n}\n\nexport interface SpecRequest {\n url: string;\n method: 'GET' | 'POST';\n headers: Record<string, string>;\n /** The spec's fixed headers, kept apart from `headers` so a decision's own\n * two-name contract still holds; the paid leg sets them under `headers`. */\n specHeaders?: Record<string, string>;\n body?: string;\n}\n\nconst PLACEHOLDER_RE = /\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g;\n\nconst scalar = (value: unknown): value is string | number | boolean =>\n (typeof value === 'string' && value.length > 0) ||\n (typeof value === 'number' && Number.isFinite(value)) ||\n typeof value === 'boolean';\n\n/** A value one path segment can hold: `encodeURIComponent` leaves `.` and `..`\n * as they are, and either would move the call to another path on the origin. */\nconst segment = (value: unknown): boolean => scalar(value) && value !== '.' && value !== '..';\n\n/**\n * The HTTP request the spec describes, filled from the merged input, or why it\n * cannot be built. A path placeholder takes its field's value as one encoded\n * segment; a query field is sent as text; the rest is the JSON body. The\n * request never leaves the spec's own origin.\n */\nexport function buildSpecRequest(spec: ToolSpec, merged: Json): SpecRequest | { problem: string } {\n const fixed = spec.request.headers ?? {};\n const refused = Object.entries(fixed).find(([name, value]) => requestHeaderProblem(name, value));\n if (refused !== undefined)\n return {\n problem: `the spec sets the header ${JSON.stringify(refused[0])}, which this build will not send`,\n };\n const specHeaders = Object.keys(fixed).length ? { specHeaders: fixed } : {};\n const where = (name: string) => spec.request.fields[name] ?? spec.request.location;\n const inPath = [...spec.request.url.matchAll(PLACEHOLDER_RE)].map((match) => match[1]!);\n const missing = inPath.filter((name) => !segment(merged[name]));\n if (missing.length)\n return {\n 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 \"..\"`,\n };\n let base: URL;\n let url: URL;\n try {\n base = new URL(spec.request.url);\n url = new URL(\n spec.request.url.replace(PLACEHOLDER_RE, (_, name: string) =>\n encodeURIComponent(String(merged[name])),\n ),\n );\n } catch {\n return { problem: 'the spec names a URL this build cannot parse' };\n }\n if (url.origin !== base.origin || url.protocol !== 'https:')\n return { problem: 'the filled URL left the service it names' };\n const body: Json = {};\n const nested: string[] = [];\n for (const [name, value] of Object.entries(merged)) {\n if (inPath.includes(name)) continue;\n const location = where(name);\n if (location === 'path') continue;\n if (location === 'body') {\n body[name] = value;\n continue;\n }\n if (value === null || typeof value === 'object') nested.push(name);\n else url.searchParams.set(name, String(value));\n }\n if (nested.length)\n return {\n problem: `${nested.join(', ')} ${nested.length > 1 ? 'go' : 'goes'} in the query string, so each must be a string, number or boolean`,\n };\n if (spec.request.method === 'GET') {\n if (Object.keys(body).length)\n return {\n problem: `a GET carries no body, so ${Object.keys(body).join(', ')} cannot be sent`,\n };\n return {\n url: url.toString(),\n method: 'GET',\n headers: { accept: 'application/json' },\n ...specHeaders,\n };\n }\n return {\n url: url.toString(),\n method: 'POST',\n headers: { accept: 'application/json', 'content-type': 'application/json' },\n ...specHeaders,\n body: JSON.stringify(body),\n };\n}\n","import { setTimeout as delay } from 'node:timers/promises';\nimport { sellerLine } from '../commands/pay';\nimport { composeUserAgent } from '../lib/client-meta';\nimport {\n assertPublicHttpsUrl,\n resolvePublicDestination,\n type DestinationOptions,\n} from '../lib/destination';\nimport { CliError } from '../lib/errors';\nimport { isBinaryContentType } from '../lib/http';\nimport { POLL_REFERENCE, type Job } from './decision';\nimport { MAX_MEDIA_BYTES, pinnedHttp, type PinnedTarget } from './paid';\n\n/**\n * A PAID CALL THE SELLER ANSWERED BEFORE ITS RESULT WAS READY, finished by\n * polling. The spec's `job` says where the status is, how a poll is sent, and\n * what says it is still running or failed; this file checks the poll URL\n * against the submit, sends each poll and reads its answer. The caller\n * (`tool.ts`) owns the money, the record and what the agent is told.\n *\n * A POLL NEVER CARRIES A PAYMENT. The take's cost is its one payment, made at\n * the submit; no header from it is kept or re-sent, and nothing is signed for\n * a poll, a status or a complete URL. A seller that asks for a payment there\n * ends the take failed.\n *\n * WHAT A POLL MAY TOUCH. The URL is the submit's own host, over HTTPS; it is\n * checked when the job starts and again before every poll, resolved to a\n * public address and connected to that address, with no redirect followed.\n * A poll carries `accept`, the CLI's user agent and `content-type` on a POST.\n * Its body is the seller's: untrusted, and capped.\n */\n\n/** How long one call waits for a job before it answers `running`. */\nexport const MAX_CALL_WAIT_MS = 300_000;\n/** The interval grows by half each poll, up to this. */\nexport const MAX_POLL_INTERVAL_MS = 30_000;\nconst BACKOFF = 1.5;\n/** This many transport failures or 5xx answers in a row end the call `running`. */\nexport const MAX_POLL_ERRORS = 3;\n/** One poll, its body included: a finished video is a large download. */\nconst POLL_REQUEST_TIMEOUT_MS = 120_000;\n/** A status answer that is not a file: JSON, inline base64 included. */\nconst MAX_STATUS_BYTES = 64 * 1024 * 1024;\n\ntype Json = Record<string, unknown>;\n\nconst record = (value: unknown): Json =>\n value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : {};\n\nfunction fieldIn(json: unknown, field: string, values: readonly string[]): boolean {\n const value = record(json)[field];\n return typeof value === 'string' && values.includes(value);\n}\n\n/**\n * WHAT A 2xx SAYS ABOUT THE JOB. `always`: the seller never answers inline,\n * so any 2xx to the submit is a job. A 202 is never a result, to the submit\n * or to a poll. Then the job's own rules: `failed` first, then `running`;\n * anything else is the result itself.\n */\nexport function answerState(\n job: Job,\n status: number,\n json: unknown,\n opts: { submit: boolean },\n): 'running' | 'failed' | 'done' {\n if (job.failed !== undefined && fieldIn(json, job.failed.field, job.failed.values)) {\n return 'failed';\n }\n if (status === 202 || (opts.submit && job.always === true)) return 'running';\n const rule = job.running;\n if (rule.httpStatus !== undefined) return rule.httpStatus.includes(status) ? 'running' : 'done';\n return fieldIn(json, rule.field, rule.values) ? 'running' : 'done';\n}\n\n/** One poll as it will be sent. */\nexport interface PollRequestSpec {\n url: string;\n method: 'GET' | 'POST';\n body?: string;\n}\n\n/**\n * WHERE THE JOB IS POLLED, from the submit's answer, or why it cannot be. A\n * URL a field or header names is resolved against the submit's URL, then held\n * to its host over HTTPS. A fixed URL was checked the same way by the server,\n * and is checked again here. `named` is the URL the seller gave, for the agent\n * to see as untrusted, when one was given and refused.\n */\nexport function pollTarget(\n job: Job,\n submit: { url: string; json: unknown; header?: (name: string) => string | undefined },\n input: Json,\n): PollRequestSpec | { problem: string; named?: string } {\n let raw: string | undefined;\n if (job.pollUrl.fixed !== undefined) raw = job.pollUrl.fixed;\n else {\n const { field, header } = job.pollUrl;\n const fromBody = field !== undefined ? record(submit.json)[field] : undefined;\n if (typeof fromBody === 'string' && fromBody.trim().length > 0) raw = fromBody.trim();\n else if (header !== undefined) raw = submit.header?.(header)?.trim() || undefined;\n }\n if (raw === undefined) return { problem: 'the seller named no status URL to poll' };\n if (raw.length > 2_048) return { problem: 'the status URL the seller named is too long' };\n const named = sellerLine(raw);\n let url: URL;\n let base: URL;\n try {\n base = new URL(submit.url);\n url = new URL(raw, base);\n } catch {\n return { problem: 'the status URL the seller named cannot be parsed', named };\n }\n url.hash = '';\n if (url.protocol !== 'https:' || url.username !== '' || url.password !== '') {\n return { problem: 'the status URL the seller named is not plain HTTPS', named };\n }\n if (url.hostname !== base.hostname) {\n return { problem: `the status URL is on ${url.hostname}, not ${base.hostname}`, named };\n }\n if (job.pollMethod === 'GET') return { url: url.toString(), method: 'GET' };\n if (job.pollBody === undefined) return { url: url.toString(), method: 'POST' };\n const body: Json = {};\n for (const [name, value] of Object.entries(job.pollBody)) {\n const reference = typeof value === 'string' ? POLL_REFERENCE.exec(value) : null;\n if (reference === null) {\n body[name] = value;\n continue;\n }\n const [, from, field] = reference as unknown as [string, 'input' | 'result', string];\n const found = record(from === 'input' ? input : submit.json)[field];\n if (found === undefined || found === null) {\n return {\n problem: `the poll needs ${value}, which the ${from === 'input' ? 'input' : \"seller's answer\"} does not carry`,\n };\n }\n body[name] = found;\n }\n return { url: url.toString(), method: 'POST', body: JSON.stringify(body) };\n}\n\n/** One poll's request, connected to the address that was checked. */\nexport interface PollRequest {\n method: 'GET' | 'POST';\n headers: Record<string, string>;\n body?: string;\n}\n\nexport interface PollResponse {\n status: number;\n header: (name: string) => string | undefined;\n body: AsyncIterable<Uint8Array>;\n /** Drop the connection without reading the rest. */\n discard: () => void;\n}\n\nexport type PollTransport = (\n target: PinnedTarget,\n request: PollRequest,\n signal: AbortSignal,\n) => Promise<PollResponse>;\n\n/**\n * THE POLL, CONNECTED TO THE ADDRESS THAT WAS CHECKED, as the media download\n * is (`paid.ts`): `node:https` with a `lookup` that answers the one validated\n * address, so a name that turns private between the check and the connect\n * gets nothing. TLS still verifies the certificate against the URL's host.\n * No redirect is followed: the answer is whatever this URL said.\n */\nexport const pinnedRequest: PollTransport = async (target, request, signal) => {\n const res = await pinnedHttp(target, request, signal);\n return {\n status: res.statusCode ?? 0,\n header: (name) => {\n const value = res.headers[name.toLowerCase()];\n return Array.isArray(value) ? value.join(', ') : value;\n },\n body: res,\n discard: () => res.destroy(),\n };\n};\n\n/** How a job stood when polling stopped. */\nexport type PollAnswer =\n | {\n state: 'done';\n status: number;\n header: (name: string) => string | undefined;\n text: string;\n json: unknown;\n bytes?: Uint8Array;\n contentType: string;\n }\n | { state: 'running'; status?: number; reason?: string }\n | {\n state: 'failed';\n status?: number;\n reason: string;\n /** The seller's own words for it, one bounded plain line: untrusted. */\n said?: string;\n }\n | { state: 'expired'; status: number };\n\nexport interface PollDeps {\n transport?: PollTransport;\n destination?: DestinationOptions;\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n /** Told before each poll; a failure here never stops one. */\n onPoll?: () => Promise<void> | void;\n}\n\n/** What polling needs of a take. */\nexport interface PolledTake {\n poll: PollRequestSpec;\n job: Job;\n}\n\n/**\n * POLL ONE TAKE UNTIL IT ENDS OR THE DEADLINE PASSES. The first poll waits\n * `firstWaitMs` (the job's interval after a submit, none on a resume), each\n * later one half as long again as the last, up to {@link MAX_POLL_INTERVAL_MS}.\n * A 402 is a seller asking to be paid again for a result already paid for:\n * nothing is signed, and the take fails. A 404 or 410 is a job the seller no\n * longer has. Any other 4xx ends the job failed, in the seller's words: AiSpace\n * answers a refused prompt's retrieve with a 422, and every later one the\n * same. {@link MAX_POLL_ERRORS} 5xx, 429 or transport failures in a row stop\n * the call `running`, and the job stays resumable.\n */\nexport async function pollUntil(\n take: PolledTake,\n opts: { deadline: number; firstWaitMs: number },\n deps: PollDeps = {},\n): Promise<PollAnswer> {\n const now = deps.now ?? Date.now;\n const sleep = deps.sleep ?? ((ms: number) => delay(ms).then(() => undefined));\n let interval = take.job.everyS * 1000;\n let wait = opts.firstWaitMs;\n let errors = 0;\n let last: number | undefined;\n for (;;) {\n if (wait > 0) {\n const left = opts.deadline - now();\n if (left <= 0) return { state: 'running', ...(last !== undefined ? { status: last } : {}) };\n await sleep(Math.min(wait, left));\n }\n await Promise.resolve()\n .then(() => deps.onPoll?.())\n .catch(() => undefined);\n const answer = await pollOnce(take, deps);\n wait = interval;\n interval = Math.min(Math.round(interval * BACKOFF), MAX_POLL_INTERVAL_MS);\n if (answer.kind === 'refused') return { state: 'failed', reason: answer.reason };\n const status = answer.kind === 'answer' ? answer.status : undefined;\n if (status !== undefined) last = status;\n const transient =\n answer.kind === 'error' || status === 429 || (status !== undefined && status >= 500);\n if (transient) {\n errors += 1;\n if (errors >= MAX_POLL_ERRORS) {\n return {\n state: 'running',\n ...(status !== undefined ? { status } : {}),\n reason:\n answer.kind === 'error'\n ? answer.reason\n : `the status URL answered ${status} ${MAX_POLL_ERRORS} times in a row`,\n };\n }\n if (now() >= opts.deadline)\n return { state: 'running', ...(status !== undefined ? { status } : {}) };\n continue;\n }\n if (answer.kind !== 'answer') continue;\n errors = 0;\n if (answer.status === 402) {\n return {\n state: 'failed',\n status: 402,\n reason: 'the seller asked for another payment to return the result; none was sent',\n };\n }\n if (answer.status === 404 || answer.status === 410) {\n return { state: 'expired', status: answer.status };\n }\n if (answer.status >= 300 && answer.status < 400) {\n return {\n state: 'failed',\n status: answer.status,\n reason: 'the status URL answered a redirect, which a poll does not follow',\n };\n }\n if (answer.status < 200 || answer.status >= 300) {\n const said = sellerSaid(answer.json, answer.text);\n return {\n state: 'failed',\n status: answer.status,\n reason: `the seller ended the job with HTTP ${answer.status}`,\n ...(said.length > 0 ? { said } : {}),\n };\n }\n if (answer.tooLarge) {\n return {\n state: 'failed',\n status: answer.status,\n reason: 'the finished file is over the size this call keeps',\n };\n }\n const state = answerState(take.job, answer.status, answer.json, { submit: false });\n if (state === 'failed') {\n const said = sellerSaid(answer.json, answer.text);\n return {\n state: 'failed',\n status: answer.status,\n reason: 'the seller says the job failed',\n ...(said.length > 0 ? { said } : {}),\n };\n }\n if (state === 'done') {\n return {\n state: 'done',\n status: answer.status,\n header: answer.header,\n text: answer.text,\n json: answer.json,\n ...(answer.bytes !== undefined ? { bytes: answer.bytes } : {}),\n contentType: answer.header('content-type') ?? '',\n };\n }\n if (now() >= opts.deadline) return { state: 'running', status: answer.status };\n }\n}\n\n/**\n * FREE THE SELLER'S COPY once ours is saved: the job's `completeUrl`, held to\n * the submit's host over HTTPS as a poll is, sent once with the poll's method\n * and body. Its answer, and any failure, is ignored: the result is already on\n * disk. The caller sends it only after the save succeeded.\n */\nexport async function completeJob(\n take: PolledTake & { submitUrl: string },\n deps: PollDeps = {},\n): Promise<void> {\n const fixed = take.job.completeUrl?.fixed;\n if (fixed === undefined) return;\n let url: URL;\n let base: URL;\n try {\n base = new URL(take.submitUrl);\n url = new URL(fixed);\n } catch {\n return;\n }\n if (url.protocol !== 'https:' || url.username !== '' || url.password !== '') return;\n if (url.hostname !== base.hostname) return;\n await pollOnce({ ...take, poll: { ...take.poll, url: url.toString() } }, deps).catch(\n () => undefined,\n );\n}\n\n/**\n * THE SELLER'S OWN WORDS for a job that failed: its `error` (a string, or one\n * with a `message`), `message`, `reason` or `detail`, else the body, as one\n * bounded, redacted plain line; empty when it said nothing. Untrusted text.\n */\nexport function sellerSaid(json: unknown, text: string): string {\n const body = record(json);\n const error = body.error;\n const said = [\n typeof error === 'string' ? error : record(error).message,\n body.message,\n body.reason,\n body.detail,\n ].find((value): value is string => typeof value === 'string' && value.trim().length > 0);\n return sellerLine(said ?? text);\n}\n\ntype Attempt =\n | {\n kind: 'answer';\n status: number;\n header: (name: string) => string | undefined;\n text: string;\n json: unknown;\n bytes?: Uint8Array;\n tooLarge?: true;\n }\n | { kind: 'error'; reason: string }\n | { kind: 'refused'; reason: string };\n\nasync function pollOnce(take: PolledTake, deps: PollDeps): Promise<Attempt> {\n try {\n assertPublicHttpsUrl(take.poll.url);\n } catch {\n return { kind: 'refused', reason: 'the status URL is not a public HTTPS endpoint' };\n }\n let pinned: PinnedTarget;\n try {\n pinned = await resolvePublicDestination(take.poll.url, deps.destination ?? {});\n } catch (err) {\n // A name that did not resolve is the network's failure, and the next poll\n // may get past it; one that resolved onto a private address is a refusal.\n const unresolved =\n err instanceof CliError &&\n (err.details as { cause?: unknown } | undefined)?.cause !== undefined;\n return unresolved\n ? { kind: 'error', reason: 'the status URL host could not be resolved' }\n : { kind: 'refused', reason: 'the status URL resolves to a private address' };\n }\n const headers: Record<string, string> = {\n accept: 'application/json, */*;q=0.8',\n 'user-agent': composeUserAgent(),\n ...(take.poll.body !== undefined ? { 'content-type': 'application/json' } : {}),\n };\n const signal = AbortSignal.timeout(POLL_REQUEST_TIMEOUT_MS);\n let res: PollResponse;\n try {\n res = await (deps.transport ?? pinnedRequest)(\n pinned,\n {\n method: take.poll.method,\n headers,\n ...(take.poll.body !== undefined ? { body: take.poll.body } : {}),\n },\n signal,\n );\n } catch (err) {\n return { kind: 'error', reason: `the status URL could not be reached (${errorText(err)})` };\n }\n if (res.status >= 300 && res.status < 400) {\n res.discard();\n return { kind: 'answer', status: res.status, header: res.header, text: '', json: undefined };\n }\n const binary = isBinaryContentType(res.header('content-type'));\n // A file is read whole under the media cap; what the call may write of it\n // is the save's to check, so a file this call has no room for stays\n // resumable rather than failing here.\n const cap = binary ? MAX_MEDIA_BYTES : MAX_STATUS_BYTES;\n const declared = Number(res.header('content-length') ?? '0');\n if (Number.isFinite(declared) && declared > cap) {\n res.discard();\n return {\n kind: 'answer',\n status: res.status,\n header: res.header,\n text: '',\n json: undefined,\n tooLarge: true,\n };\n }\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n for await (const chunk of res.body) {\n size += chunk.byteLength;\n if (size > cap) {\n res.discard();\n return {\n kind: 'answer',\n status: res.status,\n header: res.header,\n text: '',\n json: undefined,\n tooLarge: true,\n };\n }\n chunks.push(chunk);\n }\n } catch (err) {\n return { kind: 'error', reason: `the status answer could not be read (${errorText(err)})` };\n }\n const all = Buffer.concat(chunks);\n if (binary) {\n return {\n kind: 'answer',\n status: res.status,\n header: res.header,\n text: '',\n json: undefined,\n bytes: new Uint8Array(all),\n };\n }\n const text = all.toString('utf8');\n let json: unknown;\n try {\n json = text.length > 0 ? JSON.parse(text) : undefined;\n } catch {\n json = undefined;\n }\n return { kind: 'answer', status: res.status, header: res.header, text, json };\n}\n\nfunction errorText(err: unknown): string {\n return sellerLine(err instanceof Error ? err.message : String(err)) || 'no reason given';\n}\n","import { z } from 'zod';\nimport { toMoney } from '../lib/money';\nimport { policyFix } from '../lib/spend-gate';\nimport type { PlanAdmission, PlannedPayment } from '../lib/spend-plan';\nimport { createQuote, type Quote } from '../lib/spend-quotes';\nimport { resolveWalletProvider, type WalletProvider } from '../lib/wallet';\nimport type { SpecOutcome } from './decision';\nimport { KeptChoicesSchema, KeptSpecSchema, type KeptChoices, type KeptSpec } from './specs';\nimport { SettingsHashSchema } from './settings-wire';\nimport type { FailExtras, FailStatus, ProviderCall, RequestToolDeps } from './tool';\n\n/**\n * A CALL'S SPEND PLAN, AS THE AGENT AND THE USER HEAR IT. Every request-tool\n * call that pays plans its payments first (`lib/spend-plan.ts`): a single\n * offer is a plan of one at its live price, a count is N takes at the price\n * one take is quoted, and a choice set is each option at its own quote. This\n * file says what such a plan buys, keeps one over the automatic limits as a\n * quote with exactly what it runs where the host offers `approve`, and words\n * the stop: the sentence the agent repeats, and, with a quote, the one call\n * that asks the user.\n *\n * Imported by `tool.ts` and `choices.ts` alone, so it stays in the request\n * tool's chunk.\n */\n\n/** What a quote runs when the user says yes: a spec's call, a count's takes,\n * a choice set's options, or a server-built call. Nothing about it changes\n * after the quote: the agent cannot send a different input to approve. */\nexport type QuotedCall =\n | { kind: 'spec'; id: string; spec: KeptSpec; input: Record<string, unknown> }\n | {\n kind: 'count';\n id: string;\n spec: KeptSpec;\n input: Record<string, unknown>;\n count: number;\n }\n | {\n kind: 'choices';\n id: string;\n kept: KeptChoices;\n /** Each option's spec, in the set's order. */\n specs: KeptSpec[];\n /** The options the quote runs: those its seller quoted. */\n keys: string[];\n input: Record<string, unknown>;\n }\n | { kind: 'call'; call: ProviderCall };\n\nconst Input = z.record(z.string(), z.unknown());\nconst Digits = z.string().regex(/^\\d+$/);\n\nconst QuotedCallSchema = z.discriminatedUnion('kind', [\n z.strictObject({\n kind: z.literal('spec'),\n id: z.string().min(1),\n spec: KeptSpecSchema,\n input: Input,\n }),\n z.strictObject({\n kind: z.literal('count'),\n id: z.string().min(1),\n spec: KeptSpecSchema,\n input: Input,\n count: z.number().int().min(2).max(5),\n }),\n z.strictObject({\n kind: z.literal('choices'),\n id: z.string().min(1),\n kept: KeptChoicesSchema,\n specs: z.array(KeptSpecSchema).min(2).max(4),\n keys: z.array(z.string().min(1).max(64)).min(1).max(4),\n input: Input,\n }),\n z.strictObject({\n kind: z.literal('call'),\n call: z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n label: z.string().max(200).optional(),\n media: z.boolean(),\n request: z.strictObject({\n url: z.string().min(1).max(16_384),\n method: z.string().min(1).max(8),\n headers: z.record(z.string(), z.string()),\n body: z.string().optional(),\n }),\n terms: z.strictObject({\n source: z.string().optional(),\n maxAmountAtomic: Digits,\n payTo: z.string().optional(),\n network: z.string().optional(),\n asset: z.string().optional(),\n }),\n requestKey: z.string().min(1).max(1_024),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n parameters: z.unknown(),\n sent: z.string().max(16_384),\n note: z.string().max(2_000).optional(),\n settingsHash: SettingsHashSchema.optional(),\n via: z.literal('swap').optional(),\n }),\n }),\n]);\n\n/** The call a kept quote runs, or null when its file does not hold one. */\nexport function quotedCall(quote: Quote): QuotedCall | null {\n const parsed = QuotedCallSchema.safeParse(quote.call);\n return parsed.success ? (parsed.data as QuotedCall) : null;\n}\n\nconst usd = (atomic: bigint): string => `$${toMoney(atomic.toString()).usd}`;\n\n/** What a plan buys, and the one sentence that says it with its cost. */\nexport interface PlanWords {\n what: string;\n sentence: string;\n}\n\nexport function oneCall(provider: string, amountAtomic: bigint): PlanWords {\n return {\n what: `one call to ${provider}`,\n sentence: `One call to ${provider} costs ${usd(amountAtomic)}.`,\n };\n}\n\nexport function takesOf(provider: string, amounts: readonly bigint[]): PlanWords {\n const what = `${amounts.length} takes of ${provider}`;\n const total = amounts.reduce((sum, amount) => sum + amount, 0n);\n const each = amounts.every((amount) => amount === amounts[0])\n ? `${usd(amounts[0] ?? 0n)} each`\n : amounts.map(usd).join(' + ');\n return { what, sentence: `${what} cost ${usd(total)} in total (${each}).` };\n}\n\nexport function choicesOf(labels: readonly string[], amounts: readonly bigint[]): PlanWords {\n const what = `${labels.length} choices (${labels.join(', ')})`;\n const total = amounts.reduce((sum, amount) => sum + amount, 0n);\n return {\n what,\n sentence: `${what} cost ${usd(total)} in total (${amounts.map(usd).join(' + ')}).`,\n };\n}\n\n/** Why a plan over the limits is asked about rather than paid. */\nfunction whyAsked(over: Extract<PlanAdmission, { over: unknown }>['over']): string {\n return over.reason === 'session_budget_exceeded'\n ? `That is more than today's automatic budget has left (${usd(over.budgetLeftAtomic ?? 0n)})`\n : `That is over the ${usd(over.maxAutoSpendAtomic)} this machine pays for one call without asking`;\n}\n\n/** The one call that puts a quote to the user, with what they are shown. */\nexport function approveCall(quote: Quote): string {\n return `approve({quote: ${JSON.stringify(quote.id)}, total: ${JSON.stringify(usd(BigInt(quote.totalAtomic)))}, what: ${JSON.stringify(quote.what)}})`;\n}\n\n/** The step a quote's result names: the approve call, and nothing else. */\nexport function approveStep(quote: Quote): string {\n return `Call ${approveCall(quote)}: it asks the user and runs only on their yes. Do not suggest changing a setting.`;\n}\n\n/** A quote as the agent is handed it. */\nexport function quoteView(quote: Quote): Record<string, unknown> {\n return {\n id: quote.id,\n what: quote.what,\n total: usd(BigInt(quote.totalAtomic)),\n expiresAt: quote.expiresAt,\n };\n}\n\n/** How a plan that was not admitted ends the call: nothing paid. */\nexport interface PlanStop {\n status: Extract<FailStatus, 'needs_approval' | 'failed'>;\n reason: string;\n extras: FailExtras;\n /** What the server is told: an approval is not a refusal of the offer. */\n outcome: Omit<SpecOutcome, 'id' | 'ms'>;\n}\n\n/**\n * WHY A PLAN DID NOT RUN, AND WHAT FOLLOWS. Over the automatic limits it is\n * kept as a quote, and the answer is the sentence and the approve call. A\n * payee outside `allowlistCreators` is the user's own hard rule, which no\n * approval clears. `alternative` is the smaller call the agent may make instead.\n * A host that does not offer `approve` keeps no quote: nobody could run it.\n */\nexport async function planStop(\n admission: Exclude<PlanAdmission, { admitted: unknown }>,\n plan: PlanWords & { payments: readonly PlannedPayment[]; call: QuotedCall },\n deps: Pick<RequestToolDeps, 'ctx' | 'now' | 'approves'>,\n alternative?: string,\n): Promise<PlanStop> {\n const or = alternative !== undefined ? `, or ${alternative}` : '';\n if ('refused' in admission) {\n return {\n status: 'needs_approval',\n reason: `${plan.sentence} ${admission.refused.message} ${policyFix('not_allowlisted', 'this host')}`,\n extras: { nextStep: `Tell the user${or}; nothing was paid.` },\n outcome: { status: 'needs_approval' },\n };\n }\n const why = whyAsked(admission.over);\n if (deps.approves !== true) {\n return {\n status: 'needs_approval',\n reason: `${plan.sentence} ${why}, so nothing was paid.`,\n extras: { nextStep: `Tell the user what it would cost${or}; nothing was paid.` },\n outcome: { status: 'needs_approval' },\n };\n }\n try {\n const quote = await createQuote(\n deps.ctx.dataDir,\n { what: plan.what, sentence: plan.sentence, payments: plan.payments, call: plan.call },\n deps.now,\n );\n return {\n status: 'needs_approval',\n reason: `${plan.sentence} ${why}, so nothing was paid.`,\n extras: { quote: quoteView(quote), nextStep: approveStep(quote) },\n outcome: { status: 'needs_approval' },\n };\n } catch (err) {\n return {\n status: 'needs_approval',\n 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.`,\n extras: { nextStep: `Tell the user it needs their approval${or}; nothing was paid.` },\n outcome: { status: 'needs_approval' },\n };\n }\n}\n\n/** The wallet a call pays from, as `runPay` resolves it: the pre-warmed\n * provider, the test seam's, or this machine's own. */\nexport function paymentProvider(deps: RequestToolDeps): WalletProvider {\n return deps.provider ?? deps.payDeps?.provider ?? resolveWalletProvider(deps.ctx);\n}\n\n/** The settings hash each offer a quote runs was decided under, for the\n * check before every call: one per spec, or the server-built call's own. */\nexport function quotedHashes(call: QuotedCall): (string | undefined)[] {\n switch (call.kind) {\n case 'spec':\n case 'count':\n return [call.spec.settingsHash];\n case 'choices':\n return call.specs.map((spec) => spec.settingsHash);\n case 'call':\n return [call.call.settingsHash];\n }\n}\n","import { quoteRouterCall } from '../commands/pay';\nimport { CliError } from '../lib/errors';\nimport { toMoney } from '../lib/money';\nimport type { SpendPolicy } from '../lib/policy';\nimport { admitPlan, type PlanSlot } from '../lib/spend-plan';\nimport { ALL_CHOICES, type Choices, type SpecOutcome } from './decision';\nimport { settingsRefusal } from './settings-check';\nimport { choicesOf, planStop, takesOf, type PlanWords, type QuotedCall } from './plan';\nimport { SILENT_FOOTER, type LookupFooter } from './progress';\nimport {\n claimSpecPayment,\n readChoices,\n readSpec,\n settleSpecPayment,\n type EarlierPayment,\n type KeptChoices,\n type KeptSpec,\n} from './specs';\nimport {\n alreadyPaid,\n costLines,\n fail,\n failureOutcome,\n type FailExtras,\n paySpec,\n prepareSpec,\n reportOutcome,\n runningJob,\n settingsFail,\n specTerms,\n type FailStatus,\n type PreparedSpec,\n type ReportDeps,\n type RequestToolDeps,\n type RequestToolResult,\n type TakeOf,\n} from './tool';\nimport { agentFixOf } from './wallet-reasons';\n\n/**\n * A CHOICE SET: the services a line offers the user to pick between, or to run\n * all of. The set is the server's data, kept by the line's id (`specs.ts`);\n * this file only executes it, and every option is an ordinary offer with its\n * own id, spec and one payment.\n *\n * `request({id, choice: key})` is that option's offer, run by `tool.ts` as\n * `request({id: option.id})` would be. `request({id, choice: \"all\"})` runs\n * every option here, side by side, through the same three steps as one offer:\n * the checks, the claim and the payment. Nothing is signed until every option\n * passed its checks and was quoted, and the whole set's plan was admitted at\n * once, so a set the policy would stop halfway is stopped before its first\n * payment. Each payment still meets `gateSpend` when it is signed.\n *\n * Imported by `tool.ts` alone, so it stays in the request tool's chunk.\n */\n\n/** What the host does with a set's results: they are files to look at. */\nconst COMPARE_NEXT_STEP =\n 'Open each saved image, say which fits the request best and why, and let the user pick.';\n\n/** The option a choice names, the whole set for `all`, or why neither. */\nexport async function pickChoice(\n dataDir: string,\n id: string | undefined,\n choice: string,\n): Promise<{ id: string } | { all: KeptChoices } | { refused: RequestToolResult }> {\n if (id === undefined) {\n return {\n refused: fail(\n 'needs_input',\n 'A choice goes with the id from the line that offered it; send both.',\n ),\n };\n }\n const kept = await readChoices(dataDir, id);\n if (kept === null) {\n return {\n refused: fail(\n 'needs_input',\n 'No choices are kept on this machine for that id (they expired, or its line offered none), so nothing was sent or paid.',\n {\n nextStep:\n '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`.',\n },\n ),\n };\n }\n if (choice === ALL_CHOICES) return { all: kept };\n const option = kept.choices.options.find((each) => each.key === choice);\n if (option === undefined) {\n return {\n refused: fail(\n 'needs_input',\n `${JSON.stringify(choice)} is not one of this offer's choices: ${keysOf(kept.choices)}.`,\n {\n nextStep: `Call request({id: ${JSON.stringify(id)}, choice, input: {...}}) with one of those.`,\n },\n ),\n };\n }\n return { id: option.id };\n}\n\n/** The keys a choice may name, `all` last. */\nfunction keysOf(choices: Choices): string {\n return [...choices.options.map((option) => option.key), ALL_CHOICES]\n .map((key) => JSON.stringify(key))\n .join(', ');\n}\n\n/**\n * `request({id, choice: \"all\"})` with no input: the line the set came with,\n * which names every option, its price and the call, and nothing paid. The\n * server wrote it; this client composes no second wording of the same set.\n */\nexport function showChoices(id: string, kept: KeptChoices): RequestToolResult {\n return {\n isError: false,\n summary: kept.hint,\n envelope: {\n status: 'spec',\n id,\n choice: ALL_CHOICES,\n nextStep: `Call request({id: ${JSON.stringify(id)}, choice: \"${ALL_CHOICES}\", input: {...}}) with ${kept.choices.input.join(', ')}.`,\n cost: costLines(0n),\n },\n };\n}\n\n/**\n * ONE OF SEVERAL PAYMENTS RUN SIDE BY SIDE: a choice of a set, under its own\n * offer, or a take of a count, under its offer's id and its number.\n */\nexport interface TakeStep {\n /** Who it is in the set's result: a choice's key, label and id, or a take's number. */\n named: Record<string, unknown>;\n /** The claim its one payment holds. */\n claim: string;\n prepared: PreparedSpec;\n /** A take of a count: its number, and that the count reports for it. */\n take?: TakeOf;\n}\n\n/** One step's ending: paid in this call, or claimed by an earlier one. */\ntype StepRan =\n | { step: TakeStep; paid: Awaited<ReturnType<typeof paySpec>> }\n | { step: TakeStep; earlier: EarlierPayment }\n /** Its seller refused it at its quote: nothing was paid, and it may run again. */\n | { step: TakeStep; refused: RequestToolResult };\n\n/** A claimed step and what its payment is planned at. */\ninterface PlannedStep {\n step: TakeStep;\n amountAtomic: bigint;\n}\n\n/** A claimed step's live price, or why its seller would not quote it. */\ntype Priced = bigint | { refused: RequestToolResult };\n\n/** One option's entry in a set's result: who it was, then the fields its\n * own single-offer result carries. */\ntype StepResult = { status: unknown } & Record<string, unknown>;\n\n/**\n * Steps 3 to 5 of running several payments at once, a choice set's or a\n * count's:\n *\n * 3. Each step's one payment is claimed. One already claimed runs no second\n * time; when none is left, the caller says so in its own words.\n * 4. The claimed steps are priced live (`price`), and are the call's plan,\n * each at its price; one its seller would not quote drops its claim and\n * is its own entry, or stops them all. The plan is admitted as a whole:\n * its total under `maxAutoSpend` and the day's budget. If not, every claim\n * is dropped and nothing is signed: over the limits, the plan is kept as a quote for the user's yes. A quote the\n * user approved brings its own slots instead, one per claimed step, or\n * nothing runs.\n * 5. Every planned step pays at once, each against its own slot, through the\n * single-offer pay step.\n */\nasync function runTakes(\n steps: TakeStep[],\n plan: {\n price: (claimed: TakeStep[]) => Promise<Priced[] | { stop: RequestToolResult }>;\n words: (planned: PlannedStep[]) => PlanWords;\n /** What a quote of the planned steps runs. */\n call: (planned: PlannedStep[]) => QuotedCall;\n /** The slots of a quote the user approved, in the steps' order. */\n approved?: PlanSlot[];\n },\n deps: RequestToolDeps,\n reportDeps: ReportDeps,\n settings: { policy: SpendPolicy; rpcUrl: string },\n words: {\n stopped: (planned: TakeStep[], outcome: Omit<SpecOutcome, 'id' | 'ms'>) => void;\n refuse: (status: FailStatus, reason: string, extras: FailExtras) => Promise<RequestToolResult>;\n pickOne: string;\n },\n): Promise<{ refused: RequestToolResult } | { ran: StepRan[]; claimed: number }> {\n const { dataDir } = deps.ctx;\n const claimed: TakeStep[] = [];\n const earlier = new Map<TakeStep, EarlierPayment>();\n for (const step of steps) {\n const claim = await claimSpecPayment(dataDir, step.claim);\n if (claim === null) claimed.push(step);\n else earlier.set(step, claim);\n }\n // Every claim a refusal drops: nothing was signed for it.\n const release = async (dropped: TakeStep[]): Promise<void> => {\n for (const step of dropped) {\n await settleSpecPayment(dataDir, step.claim, { amountAtomic: 0n, signed: false });\n }\n };\n const unquoted = new Map<TakeStep, RequestToolResult>();\n const slots = new Map<TakeStep, PlanSlot>();\n let planned: PlannedStep[] = [];\n if (claimed.length > 0 && plan.approved !== undefined) {\n if (plan.approved.length !== claimed.length) {\n await release(claimed);\n return {\n refused: await words.refuse(\n 'needs_input',\n 'What is left to run is no longer what the quote approved, so nothing was paid.',\n { nextStep: 'Call request again for a fresh quote.' },\n ),\n };\n }\n claimed.forEach((step, index) => slots.set(step, plan.approved![index]!));\n planned = claimed.map((step) => ({ step, amountAtomic: slots.get(step)!.amountAtomic }));\n } else if (claimed.length > 0) {\n const priced = await plan.price(claimed);\n if ('stop' in priced) {\n await release(claimed);\n return { refused: priced.stop };\n }\n claimed.forEach((step, index) => {\n const price = priced[index]!;\n if (typeof price === 'bigint') planned.push({ step, amountAtomic: price });\n else unquoted.set(step, price.refused);\n });\n await release([...unquoted.keys()]);\n if (planned.length > 0) {\n const payments = planned.map(({ step, amountAtomic }) => ({\n amountAtomic,\n creator: new URL(step.prepared.built.url).host,\n }));\n const admission = await admitPlan(payments, {\n dataDir,\n policy: settings.policy,\n ...(deps.now !== undefined ? { now: deps.now } : {}),\n });\n if (!('admitted' in admission)) {\n await release(planned.map(({ step }) => step));\n const stop = await planStop(\n admission,\n { ...plan.words(planned), payments, call: plan.call(planned) },\n deps,\n words.pickOne,\n );\n words.stopped(\n planned.map(({ step }) => step),\n stop.outcome,\n );\n return { refused: await words.refuse(stop.status, stop.reason, stop.extras) };\n }\n planned.forEach(({ step }, index) => slots.set(step, admission.admitted[index]!));\n }\n }\n\n const paid = new Map(\n await Promise.all(\n planned.map(\n async ({ step }) =>\n [\n step,\n await paySpec(\n step.prepared,\n { slot: slots.get(step)! },\n deps,\n SILENT_FOOTER,\n reportDeps,\n step.take,\n ),\n ] as const,\n ),\n ),\n );\n return {\n claimed: planned.length,\n ran: steps.map((step): StepRan => {\n const done = paid.get(step);\n if (done !== undefined) return { step, paid: done };\n const refused = unquoted.get(step);\n return refused !== undefined ? { step, refused } : { step, earlier: earlier.get(step)! };\n }),\n };\n}\n\n/** One entry of a set's result: a step that ran in this call, with its own\n * single result, or one an earlier call already ran. */\nexport type SetEntry =\n | { named: Record<string, unknown>; result: RequestToolResult; amountAtomic: bigint }\n | { named: Record<string, unknown>; earlier: StepResult };\n\n/**\n * Step 6: ONE RESULT, one entry per step in its order, each the fields its\n * own single result carries. Of the steps that ran here, the set is\n * `fulfilled` when every one is; `running` while any is, with the job that\n * resumes it; `partial` when some delivered; `failed` when none did. The\n * cost is what ran here, summed.\n */\nexport function takesResult(\n entries: SetEntry[],\n opts: { head: string; nextStep: string; envelope?: Record<string, unknown> },\n): RequestToolResult {\n let total = 0n;\n const ran: unknown[] = [];\n const results: StepResult[] = entries.map((entry) => {\n if ('earlier' in entry) return { ...entry.named, ...entry.earlier };\n total += entry.amountAtomic;\n // The set's own envelope says once that provider content is untrusted.\n const envelope = { ...entry.result.envelope };\n delete envelope.providerContentUntrusted;\n ran.push(envelope.status);\n return { ...entry.named, status: envelope.status, ...envelope };\n });\n const status = ran.every((each) => each === 'fulfilled')\n ? 'fulfilled'\n : ran.some((each) => each === 'running')\n ? 'running'\n : ran.some((each) => each === 'fulfilled' || each === 'unverified')\n ? 'partial'\n : 'failed';\n const cost = costLines(total);\n const lines = results.map((step) => {\n const files = Array.isArray(step.savedFiles) ? step.savedFiles : [];\n const who =\n step.label !== undefined\n ? `${String(step.label)} (${String(step.key)})`\n : `take ${String(step.take)}`;\n return `- ${who}: ${String(step.status)}${files.length ? `, saved to ${files.join(', ')}` : ''}`;\n });\n // Each entry still running names its job: one for a count's takes, one per\n // option for a choice set's.\n const jobs = [\n ...new Set(\n results.flatMap((step) =>\n step.status === 'running' && typeof step.job === 'string' ? [step.job] : [],\n ),\n ),\n ];\n const resume =\n jobs.length > 0\n ? `Call ${jobs.map((job) => `request({job: ${JSON.stringify(job)}})`).join(' and ')} in a minute or two for what is still running; nothing more is paid.`\n : undefined;\n return {\n isError: status === 'failed',\n summary: [\n `${opts.head}, ${status} · ${cost.join(' · ')}`,\n ...lines,\n ...(resume !== undefined ? [resume] : []),\n ].join('\\n'),\n envelope: {\n status,\n ...(opts.envelope ?? {}),\n ...(jobs.length === 1 ? { job: jobs[0] } : {}),\n results,\n cost,\n nextStep: resume ?? opts.nextStep,\n providerContentUntrusted: true,\n },\n };\n}\n\n/** A step an earlier call already claimed, as its entry says it. */\nfunction earlierEntry(step: TakeStep, claim: EarlierPayment): SetEntry {\n return {\n named: step.named,\n earlier: {\n status: claim.state === 'unrecorded' ? 'failed' : 'already_paid',\n reason: alreadyPaid(step.claim, step.prepared.spec, claim).envelope.reason,\n cost: costLines(0n),\n },\n };\n}\n\n/** Every step's entry, in the set's order. */\nfunction entriesOf(ran: StepRan[]): SetEntry[] {\n return ran.map((each) =>\n 'paid' in each\n ? {\n named: each.step.named,\n result: each.paid.result,\n amountAtomic: each.paid.left.amountAtomic,\n }\n : 'refused' in each\n ? { named: each.step.named, result: each.refused, amountAtomic: 0n }\n : earlierEntry(each.step, each.earlier),\n );\n}\n\n/** What the steps that ran in this call paid, together. */\nfunction paidHere(ran: StepRan[]): bigint {\n return ran.reduce((sum, each) => sum + ('paid' in each ? each.paid.left.amountAtomic : 0n), 0n);\n}\n\n/**\n * `request({id, choice: \"all\", input})`: every option, each its own offer.\n *\n * 1. The input carries only the fields the options share.\n * 2. Every option's spec is kept and its call checks; one that does not\n * stops the set, naming it. Each is then quoted at its live price by one\n * unpaid probe, side by side. An option its seller refuses there (the\n * prompt, the price) is that option's own entry, with nothing paid, and\n * the rest run without it.\n * 3 to 5. Claimed, planned and admitted as one, and paid side by side\n * ({@link runTakes}).\n * 6. One result, one entry per option, in the set's order ({@link takesResult}).\n *\n * `approved`: a quote the user said yes to, with the specs it was quoted on,\n * the options it covers and its slots; nothing is probed or planned again.\n */\nexport async function runChoiceSet(\n id: string,\n kept: KeptChoices,\n input: Record<string, unknown>,\n deps: RequestToolDeps,\n footer: LookupFooter,\n reportDeps: ReportDeps,\n settings: { policy: SpendPolicy; rpcUrl: string },\n approved?: { specs: KeptSpec[]; keys: string[]; slots: PlanSlot[] },\n): Promise<RequestToolResult> {\n const { dataDir } = deps.ctx;\n const { choices } = kept;\n const startedAt = Date.now();\n // A set stopped before payment is reported once per choice, as each\n // choice's own offer would be.\n const stopped = (\n options: readonly { id: string }[],\n outcome: Omit<SpecOutcome, 'id' | 'ms'>,\n ): void => {\n for (const option of options) reportOutcome(reportDeps, option.id, outcome, startedAt);\n };\n const again = `request({id: ${JSON.stringify(id)}, choice: \"${ALL_CHOICES}\", input: {...}})`;\n const refuse = async (\n status: FailStatus,\n reason: string,\n extras: FailExtras,\n ): Promise<RequestToolResult> => {\n await footer.done(status);\n return fail(status, reason, extras);\n };\n\n const extra = Object.keys(input).filter((name) => !choices.input.includes(name));\n if (extra.length) {\n stopped(choices.options, { status: 'unpaid', reason: 'input' });\n return refuse(\n 'needs_input',\n `Running all the choices takes only ${choices.input.join(', ')}, not ${extra.join(', ')}.`,\n {\n nextStep: `Call ${again} with only those, or pick one choice to set more; nothing was sent or paid.`,\n },\n );\n }\n\n const specs: KeptSpec[] = [];\n const prepared: { option: (typeof choices.options)[number]; checked: PreparedSpec }[] = [];\n for (const [index, option] of choices.options.entries()) {\n const named = `${option.label} (choice ${JSON.stringify(option.key)})`;\n const spec =\n approved !== undefined ? approved.specs[index] : await readSpec(dataDir, option.id);\n if (spec === null || spec === undefined) {\n return refuse(\n 'needs_input',\n `The spec for ${named} is no longer kept on this machine (it expired or was pruned), so nothing was sent or paid.`,\n { nextStep: 'Call request({query}) with the task for a fresh offer, then fill its line.' },\n );\n }\n specs.push(spec);\n const checked = await prepareSpec(option.id, spec, input, SILENT_FOOTER, reportDeps);\n if ('refused' in checked) {\n const { status, reason } = checked.refused.envelope as { status: FailStatus; reason: string };\n return refuse(status, `${named}: ${reason}`, {\n nextStep:\n status === 'needs_input'\n ? `Fix the input and call ${again} again, or pick one of the other choices; nothing was sent or paid.`\n : 'Pick one of the other choices; nothing was sent or paid.',\n });\n }\n prepared.push({ option, checked: checked.prepared });\n }\n // THE WHOLE SET, BEFORE ANY OPTION IS PRICED OR PAID: one option decided\n // under other rules than the ones saved now refuses them all, so the set\n // never shrinks into a different charge. Each option's call checks again.\n const stale = await settingsRefusal(\n dataDir,\n specs.map((spec) => spec.settingsHash),\n );\n if (stale !== null) {\n await footer.done('needs_input');\n return settingsFail(stale);\n }\n\n // A quote the user approved runs only the options it covered.\n const steps: TakeStep[] = prepared\n .filter(({ option }) => approved === undefined || approved.keys.includes(option.key))\n .map(({ option, checked }) => ({\n named: { key: option.key, label: option.label, id: option.id },\n claim: option.id,\n prepared: checked,\n }));\n const run = await runTakes(\n steps,\n {\n // EACH OPTION AT ITS LIVE PRICE: the plan is what the set will cost,\n // not what its ceilings allow. One its seller refuses there (the\n // prompt, the price) is its own entry, with nothing paid.\n price: async (claimed) =>\n Promise.all(\n claimed.map(async (step): Promise<Priced> => {\n const quote = await quoteTake(step.prepared, deps);\n if (!('refused' in quote)) return quote.atomic;\n const { outcome, result } = quote.refused;\n if (outcome !== null) reportOutcome(reportDeps, step.claim, outcome, startedAt);\n return { refused: result };\n }),\n ),\n words: (planned) =>\n choicesOf(\n planned.map(({ step }) => String(step.named.label)),\n planned.map(({ amountAtomic }) => amountAtomic),\n ),\n call: (planned) => ({\n kind: 'choices',\n id,\n kept,\n specs,\n keys: planned.map(({ step }) => String(step.named.key)),\n input,\n }),\n ...(approved !== undefined ? { approved: approved.slots } : {}),\n },\n deps,\n reportDeps,\n settings,\n {\n stopped: (planned, outcome) =>\n stopped(\n planned.map((step) => ({ id: step.claim })),\n outcome,\n ),\n refuse,\n pickOne: 'pick one choice',\n },\n );\n if ('refused' in run) return run.refused;\n const ranAny = run.ran.some((each) => !('earlier' in each));\n if (!ranAny) {\n // \"Already ran\" only when each one did; a claim this machine could not\n // write, or a call still running, says so in its own words.\n const earlier = run.ran.flatMap((each) => ('earlier' in each ? [each] : []));\n const allRan = earlier.every(\n ({ earlier: claim }) => claim.state === 'paid' || claim.state === 'possibly_paid',\n );\n return refuse(\n 'needs_input',\n allRan\n ? '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.'\n : earlier\n .map(\n ({ step, earlier: claim }) =>\n `${String(step.named.label)}: ${String(alreadyPaid(step.claim, step.prepared.spec, claim).envelope.reason)}`,\n )\n .join(' '),\n {\n nextStep: 'For another run, send request({query}) for a new offer; each choice pays once.',\n },\n );\n }\n const set = takesResult(entriesOf(run.ran), {\n head: `Ran ${run.claimed} of ${steps.length} choices`,\n nextStep: COMPARE_NEXT_STEP,\n envelope: { choice: ALL_CHOICES },\n });\n await footer.done(String(set.envelope.status), {\n price: `$${toMoney(paidHere(run.ran).toString()).usd}`,\n });\n return set;\n}\n\n/** What the host does with a count's results: several takes to compare. */\nconst TAKES_NEXT_STEP =\n 'Open each saved file, say which take fits the request best and why, and let the user pick.';\n\n/**\n * `request({id, input, count})`: SEVERAL TAKES OF ONE CALL, each its own\n * payment. Take 1 is the offer's own claim, as a plain call's is; take n\n * claims `${id}#n`, so a repeat pays only for the takes not yet run. Each\n * take's request key ends in `#n`, or the same-turn duplicate guard would\n * deny takes 2 to N as one request repeated. One unpaid probe quotes a take\n * at this input's live price, and the count's plan is N takes at it: their\n * total meets the automatic limits before any take is\n * signed, and a take quoted higher when it is signed is refused there. A take\n * the seller answers before it is ready is a job under the offer's id,\n * resumed with `request({job})`. The offer is reported once, for the count as\n * a whole. `approved`: the slots of a quote the user said yes to; nothing is\n * probed or planned again.\n */\nexport async function runCount(\n id: string,\n spec: KeptSpec,\n input: Record<string, unknown>,\n count: number,\n deps: RequestToolDeps,\n footer: LookupFooter,\n reportDeps: ReportDeps,\n settings: { policy: SpendPolicy; rpcUrl: string },\n approved?: PlanSlot[],\n): Promise<RequestToolResult> {\n const startedAt = Date.now();\n const refuse = async (\n status: FailStatus,\n reason: string,\n extras: FailExtras,\n ): Promise<RequestToolResult> => {\n await footer.done(status);\n return fail(status, reason, extras);\n };\n // Every take was decided under one answer's rules, checked before the\n // price is asked; each take's own call checks them again.\n const stale = await settingsRefusal(deps.ctx.dataDir, [spec.settingsHash]);\n if (stale !== null) {\n await footer.done('needs_input');\n return settingsFail(stale);\n }\n const checked = await prepareSpec(id, spec, input, footer, reportDeps);\n if ('refused' in checked) return checked.refused;\n const steps: TakeStep[] = Array.from({ length: count }, (_, index) => {\n const n = index + 1;\n const claim = n === 1 ? id : `${id}#${n}`;\n return {\n named: { take: n },\n claim,\n prepared: checked.prepared,\n take: { n, claim, report: false },\n };\n });\n const run = await runTakes(\n steps,\n {\n // THE LIVE PRICE, ONCE, for the takes still to run: the number a single\n // call of this input is planned at, so a price that varies by input is\n // planned at what this input costs, not at the spec's ceiling.\n price: async (claimed) => {\n const quoted = await quoteTake(checked.prepared, deps);\n if (!('refused' in quoted)) return claimed.map(() => quoted.atomic);\n const { outcome, result } = quoted.refused;\n if (outcome !== null) reportOutcome(reportDeps, id, outcome, startedAt);\n await footer.done(String(result.envelope.status));\n return { stop: result };\n },\n words: (planned) =>\n takesOf(\n spec.provider,\n planned.map(({ amountAtomic }) => amountAtomic),\n ),\n call: () => ({ kind: 'count', id, spec, input, count }),\n ...(approved !== undefined ? { approved } : {}),\n },\n deps,\n reportDeps,\n settings,\n {\n stopped: (_claimed, outcome) => reportOutcome(reportDeps, id, outcome, startedAt),\n refuse,\n pickOne: 'run fewer takes',\n },\n );\n if ('refused' in run) return run.refused;\n if (run.claimed === 0) {\n const running = await runningJob(deps.ctx.dataDir, id);\n return refuse(\n 'needs_input',\n `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.`,\n {\n nextStep:\n running !== undefined\n ? `Call request({job: ${JSON.stringify(running)}}) for the takes still running; nothing more is paid.`\n : `For more takes, send request({query}) for a new offer; this id (${id}) pays once per take.`,\n },\n );\n }\n const ranHere = run.ran.flatMap((each) => ('paid' in each ? [each] : []));\n const set = takesResult(entriesOf(run.ran), {\n head: `Ran ${run.claimed} of ${count} takes`,\n nextStep: TAKES_NEXT_STEP,\n envelope: { count },\n });\n const status = String(set.envelope.status);\n // ONE REPORT FOR THE OFFER: a take that delivered is the offer taken.\n const outcome: Omit<SpecOutcome, 'id' | 'ms'> | null =\n status === 'fulfilled' || status === 'partial'\n ? { status: 'fulfilled' }\n : status === 'running'\n ? { status: 'running' }\n : ranHere.some(({ paid }) => paid.outcome?.status === 'failed')\n ? { status: 'failed' }\n : (ranHere.find(({ paid }) => paid.outcome !== null)?.paid.outcome ?? null);\n if (outcome !== null) reportOutcome(reportDeps, id, outcome, startedAt);\n await footer.done(status, { price: `$${toMoney(paidHere(run.ran).toString()).usd}` });\n return set;\n}\n\n/**\n * ONE TAKE'S LIVE PRICE, from an unpaid probe held to the spec's terms, or\n * the refusal a single call would have met there, with nothing signed: an\n * input the seller rejects, a price over the spec's ceiling, a seller that\n * cannot be reached.\n */\nasync function quoteTake(\n prepared: PreparedSpec,\n deps: RequestToolDeps,\n): Promise<\n | { atomic: bigint }\n | {\n refused: {\n result: RequestToolResult;\n outcome: ReturnType<typeof failureOutcome>;\n };\n }\n> {\n const { spec, built } = prepared;\n try {\n const atomic = await quoteRouterCall(\n {\n url: built.url,\n method: built.method,\n headers: built.headers,\n ...(built.specHeaders !== undefined ? { specHeaders: built.specHeaders } : {}),\n ...(built.body !== undefined ? { rawBody: built.body } : {}),\n // The probe the call itself makes waits as long as its spec says.\n ...(spec.timeoutS !== undefined ? { timeoutMs: spec.timeoutS * 1000 } : {}),\n terms: specTerms(spec),\n },\n deps.ctx,\n // The same seams, and the same wallet, the paid leg is given.\n {\n ...(deps.payDeps ?? {}),\n ...(deps.provider !== undefined ? { provider: deps.provider } : {}),\n },\n );\n return { atomic };\n } catch (err) {\n const cli = err instanceof CliError ? err : undefined;\n const detail = (cli?.details ?? {}) as {\n status?: number;\n providerError?: string;\n live?: { amount?: string };\n };\n const rejectedInput = detail.status === 400 || detail.status === 422;\n const live = detail.live?.amount;\n const overCeiling =\n spec.priceVaries &&\n cli?.code === 'REGISTRY_MISMATCH' &&\n live !== undefined &&\n /^\\d+$/.test(live);\n const reason = overCeiling\n ? `${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.`\n : rejectedInput\n ? `${spec.provider} rejected this input before any payment (HTTP ${String(detail.status)}): see providerError. Fix the input and call again with the same id.`\n : cli !== undefined\n ? `${cli.message} ${agentFixOf(cli)}`.trim()\n : String(err);\n const status: FailStatus = cli?.code === 'POLICY_REFUSED' ? 'needs_approval' : 'failed';\n return {\n refused: {\n outcome: failureOutcome(err, { mayHaveMoved: false, rejectedInput }),\n result: fail(status, reason, {\n ...(typeof detail.status === 'number' ? { providerStatus: detail.status } : {}),\n ...(typeof detail.providerError === 'string'\n ? { providerError: detail.providerError }\n : {}),\n request: { method: built.method, url: built.url },\n parameters: prepared.sentInput,\n ...(overCeiling || rejectedInput\n ? { nextStep: 'Change the input and call again with the same id.' }\n : {}),\n }),\n },\n };\n }\n}\n","import { MAX_MEDIA_FILES } from './paid';\n\n/**\n * A PAID FILE CARRIED INSIDE THE JSON, saved to disk instead of handed to the\n * agent as text. A generator can answer with the file itself as base64: a\n * four-second video came back as `{\"data\":[{\"b64_json\":\"<4.2 MB>\",\n * \"media_type\":\"video/mp4\"}]}`, and the agent stalled decoding it by hand.\n *\n * A string is a file when it is a `data:<type>;base64,` URI, when it sits\n * under a key naming base64 (`b64_json`, `b64`, `audio_base64`,\n * `bytesBase64Encoded`), or when its bytes open like a known media file;\n * in every case it is valid base64 of at least {@link MIN_INLINE_BYTES}, so\n * an id or a hash that happens to look like base64 stays where it is.\n */\n\n/** Below this a base64 string is an id, a hash or a token, not a file. */\nexport const MIN_INLINE_BYTES = 1024;\n\n/** Deep enough for `{data: [{b64_json}]}` and its cousins, and no deeper. */\nconst MAX_DEPTH = 8;\n\nconst DATA_URI = /^data:([^;,]*)[^,]*;base64,/i;\nconst BASE64_KEY = /base64|^b64(?:_json)?$/i;\nconst BASE64 = /^[A-Za-z0-9+/_-]+={0,2}$/;\nconst MEDIA_TYPE = /^[a-z0-9][\\w.+-]*\\/[\\w.+-]+$/i;\n/** Sibling keys that name the file's type, compared without `_` or case. */\nconst TYPE_KEYS = new Set(['mediatype', 'mimetype', 'contenttype']);\n\n/** Where one inline file sits, and what it is. */\ninterface Found {\n holder: Record<string, unknown> | unknown[];\n key: string | number;\n bytes: Uint8Array;\n contentType: string;\n}\n\n/**\n * Every inline file in `bodyText`, saved with `save` and replaced by a note\n * naming where it went, its type and its size: the rewritten JSON and the\n * paths. At most `limit` files. A file `save` could not write stays inline.\n * Null when the body is not JSON, holds no inline file, or nothing was saved.\n *\n * NEVER THROWS: it runs after the money moved, and any failure leaves the\n * body exactly as it came.\n */\nexport async function saveInlineMedia(\n bodyText: string,\n save: (bytes: Uint8Array, contentType: string) => Promise<string | null>,\n limit = MAX_MEDIA_FILES,\n): Promise<{ bodyText: string; savedFiles: string[] } | null> {\n try {\n const root: unknown = JSON.parse(bodyText);\n const found: Found[] = [];\n collect(root, undefined, undefined, 0, found, limit);\n const savedFiles: string[] = [];\n for (const file of found) {\n const path = await save(file.bytes, file.contentType).catch(() => null);\n if (path === null) continue;\n savedFiles.push(path);\n const note = `[inline file saved to ${path} (${file.contentType}, ${file.bytes.byteLength} bytes)]`;\n if (Array.isArray(file.holder)) file.holder[file.key as number] = note;\n else file.holder[file.key as string] = note;\n }\n if (savedFiles.length === 0) return null;\n return { bodyText: JSON.stringify(root), savedFiles };\n } catch {\n return null;\n }\n}\n\n/** Walk `value`, which sits at `holder[key]`; an array's items take the key\n * and the siblings of the object that holds the array. */\nfunction collect(\n value: unknown,\n at: { holder: Record<string, unknown> | unknown[]; key: string | number } | undefined,\n named: { key: string; siblings: Record<string, unknown> } | undefined,\n depth: number,\n found: Found[],\n limit: number,\n): void {\n if (found.length >= limit || depth > MAX_DEPTH) return;\n if (typeof value === 'string') {\n if (at === undefined) return;\n const file = inlineFile(value, named);\n if (file !== null) found.push({ ...at, ...file });\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) =>\n collect(item, { holder: value, key: index }, named, depth + 1, found, limit),\n );\n return;\n }\n if (value === null || typeof value !== 'object') return;\n const object = value as Record<string, unknown>;\n for (const [key, item] of Object.entries(object)) {\n collect(item, { holder: object, key }, { key, siblings: object }, depth + 1, found, limit);\n }\n}\n\n/** The file a string carries, or null when it carries none. */\nfunction inlineFile(\n text: string,\n named: { key: string; siblings: Record<string, unknown> } | undefined,\n): { bytes: Uint8Array; contentType: string } | null {\n // Too short to hold a file once decoded: skipped before any regex runs.\n if (text.length < Math.ceil((MIN_INLINE_BYTES * 4) / 3)) return null;\n const uri = DATA_URI.exec(text);\n const payload = uri !== null ? text.slice(uri[0].length) : text;\n const bytes = decoded(payload);\n if (bytes === null) return null;\n const magic = sniff(bytes);\n if (uri === null && magic === null && !BASE64_KEY.test(named?.key ?? '')) return null;\n const declared = uri?.[1] !== undefined && MEDIA_TYPE.test(uri[1]) ? uri[1] : siblingType(named);\n return {\n bytes,\n contentType: (declared ?? magic ?? 'application/octet-stream').toLowerCase(),\n };\n}\n\n/** Valid base64 (standard or URL-safe, line breaks allowed) of at least\n * {@link MIN_INLINE_BYTES}, decoded; null otherwise. */\nfunction decoded(payload: string): Uint8Array | null {\n const compact = payload.replace(/[\\r\\n]+/g, '');\n if (!BASE64.test(compact)) return null;\n const bytes = Buffer.from(compact, 'base64');\n return bytes.byteLength >= MIN_INLINE_BYTES ? new Uint8Array(bytes) : null;\n}\n\n/** The type a sibling key declares (`media_type`, `mimeType`, ...), if any. */\nfunction siblingType(\n named: { key: string; siblings: Record<string, unknown> } | undefined,\n): string | undefined {\n if (named === undefined) return undefined;\n for (const [key, value] of Object.entries(named.siblings)) {\n if (!TYPE_KEYS.has(key.replace(/_/g, '').toLowerCase())) continue;\n if (typeof value === 'string' && MEDIA_TYPE.test(value.trim())) return value.trim();\n }\n return undefined;\n}\n\n/** The media type the first bytes name, for the formats a paid lookup\n * plausibly returns; null for anything else. */\nexport function sniff(bytes: Uint8Array): string | null {\n const ascii = (from: number, to: number) =>\n Buffer.from(bytes.subarray(from, to)).toString('latin1');\n const starts = (...sig: number[]) => sig.every((byte, i) => bytes[i] === byte);\n if (starts(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return 'image/png';\n if (starts(0xff, 0xd8, 0xff)) return 'image/jpeg';\n if (ascii(0, 6) === 'GIF87a' || ascii(0, 6) === 'GIF89a') return 'image/gif';\n if (ascii(0, 4) === 'RIFF' && ascii(8, 12) === 'WEBP') return 'image/webp';\n if (ascii(0, 4) === 'RIFF' && ascii(8, 12) === 'WAVE') return 'audio/wav';\n if (ascii(4, 8) === 'ftyp') {\n const brand = ascii(8, 12);\n if (brand === 'qt ') return 'video/quicktime';\n if (brand === 'M4A ') return 'audio/mp4';\n return 'video/mp4';\n }\n if (starts(0x1a, 0x45, 0xdf, 0xa3)) return 'video/webm';\n if (ascii(0, 4) === 'OggS') return 'audio/ogg';\n if (ascii(0, 4) === 'fLaC') return 'audio/flac';\n if (ascii(0, 5) === '%PDF-') return 'application/pdf';\n if (ascii(0, 3) === 'ID3') return 'audio/mpeg';\n // An MPEG audio frame with no ID3 tag: eleven sync bits.\n if (bytes[0] === 0xff && ((bytes[1] ?? 0) & 0xe0) === 0xe0) return 'audio/mpeg';\n return null;\n}\n","import { lstat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { withFileLock } from '../lib/lock';\nimport { jobsDir } from '../lib/paths';\nimport { JobSchema } from './decision';\nimport { sha256Hex } from '../lib/hash';\nimport { readJsonFile, sweep, writePrivate } from './store-files';\n\n/**\n * A PAID CALL WHOSE SELLER WAS STILL WORKING, kept on this machine so any later\n * process can finish it. One file per take, `~/.tenjin/jobs/<sha256(offerId)>.<take>.json`:\n * where to poll and how, until when, what it cost, and how it ended. Everything\n * a resume needs rides in the record, because the offer's spec is kept for\n * fifteen minutes and a job for up to two days.\n *\n * NO PAYMENT RIDES IN IT: a poll is never signed. The record still names a\n * status URL that can be the result's only key and what the user asked for,\n * so it is written 0600 through an atomic rename (which replaces a planted\n * symlink rather than writing through it) and read with O_NOFOLLOW. A record\n * past its `expiresAt` is pruned.\n */\n\n/** At most this many takes per call, so at most this many files per job. */\nexport const MAX_TAKES = 5;\n/** A record is the server's and the seller's words plus a result cut short. */\nconst MAX_RECORD_BYTES = 256 * 1024;\n/** What a finished take keeps of the result it handed the agent. */\nexport const KEPT_RESULT_CHARS = 8_000;\n/** A record whose `expiresAt` cannot be read is pruned once it is this old. */\nconst UNREADABLE_TTL_MS = 49 * 60 * 60_000;\n\nconst Iso = z.string().max(40);\nconst Digits = z.string().regex(/^\\d+$/);\nconst Authorization = z.strictObject({\n from: z.string().max(64),\n nonce: z.string().max(80),\n validBefore: Digits,\n});\n\nconst TakeSchema = z.strictObject({\n version: z.literal(1),\n offerId: z.string().min(1).max(200),\n take: z.number().int().min(1).max(MAX_TAKES),\n poll: z.strictObject({\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n body: z\n .string()\n .max(64 * 1024)\n .optional(),\n }),\n job: JobSchema,\n /** What finishing the call needs once its spec is gone. */\n call: z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(16_384),\n media: z.boolean(),\n sent: z.string().max(8_192),\n terms: z.strictObject({\n source: z.string().max(200).optional(),\n maxAmountAtomic: Digits,\n payTo: z.string().max(200).optional(),\n network: z.string().max(64).optional(),\n asset: z.string().max(200).optional(),\n }),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n }),\n submittedAt: Iso,\n expiresAt: Iso,\n amountAtomic: Digits,\n /** The submit's authorization, which its ledger row is found by. */\n authorization: Authorization.optional(),\n /** The submit's settlement, when the seller named it: paid for certain. */\n txHash: z\n .string()\n .regex(/^0x[0-9a-fA-F]{64}$/)\n .optional(),\n /** The submit's HTTP status. */\n httpStatus: z.number().int().optional(),\n state: z.enum(['running', 'done', 'failed', 'expired']),\n savedFiles: z.array(z.string().max(4_096)).max(16),\n /** What the agent was handed when the take finished, cut short. */\n result: z\n .string()\n .max(KEPT_RESULT_CHARS + 16)\n .optional(),\n /** That result missed its success rule, or the rule could not be run. */\n resultUnverified: z.boolean().optional(),\n /** Why, as the agent was told. */\n resultCaveat: z.string().max(1_000).optional(),\n /** Why a take failed, or why it stopped. */\n reason: z.string().max(1_000).optional(),\n /** The seller's own words for it, bounded and redacted. Untrusted text. */\n said: z.string().max(1_000).optional(),\n /** An unsigned status URL the agent may open itself. Seller text. */\n statusUrl: z.string().max(2_048).optional(),\n});\nexport type JobTake = z.infer<typeof TakeSchema>;\n\nexport function takePath(dataDir: string, offerId: string, take: number): string {\n return join(jobsDir(dataDir), `${sha256Hex(offerId)}.${take}.json`);\n}\n\n/**\n * Write a take. Throws: a job that cannot be recorded before its first poll is\n * one no later process can finish, and the caller says so.\n */\nexport async function writeTake(dataDir: string, take: JobTake): Promise<void> {\n await writePrivate(takePath(dataDir, take.offerId, take.take), JSON.stringify(take));\n void pruneJobs(dataDir, Date.now());\n}\n\n/** The take kept for this offer, or null: none, damaged, not ours, or a symlink. */\nexport async function readTake(\n dataDir: string,\n offerId: string,\n take: number,\n): Promise<JobTake | null> {\n const parsed = TakeSchema.safeParse(\n await readJsonFile(takePath(dataDir, offerId, take), MAX_RECORD_BYTES),\n );\n return parsed.success && parsed.data.offerId === offerId && parsed.data.take === take\n ? parsed.data\n : null;\n}\n\n/** Every take kept for this offer, in order. */\nexport async function readTakes(dataDir: string, offerId: string): Promise<JobTake[]> {\n const takes: JobTake[] = [];\n for (let n = 1; n <= MAX_TAKES; n += 1) {\n const take = await readTake(dataDir, offerId, n);\n if (take !== null) takes.push(take);\n }\n return takes;\n}\n\n/**\n * READ, CHANGE AND WRITE ONE TAKE under its own lock, so two processes\n * resuming the same job cannot each lose the other's ending. `change` sees the record as it is on disk now and\n * returns the one to write, or null to leave it. The record written, or null.\n */\nexport async function updateTake(\n dataDir: string,\n offerId: string,\n take: number,\n change: (current: JobTake) => Promise<JobTake | null> | JobTake | null,\n): Promise<JobTake | null> {\n const path = takePath(dataDir, offerId, take);\n return withFileLock(\n `${path}.lock`,\n async () => {\n const current = await readTake(dataDir, offerId, take);\n if (current === null) return null;\n const next = await change(current);\n if (next === null) return null;\n await writeTake(dataDir, next);\n return next;\n },\n { timeoutMs: 30_000 },\n );\n}\n\n/**\n * END A RUNNING TAKE, FIRST ENDING WINS. Two calls can poll one take (a host\n * that gave up on a call this process kept polling, then a resume), and the\n * second ending (a 404 once the first freed the seller's copy) must never\n * overwrite the first. Under the take's lock, a take no longer `running` is\n * left as it is. `won`: this ending was written; else `take` is the one that\n * was. Null when no record is kept; throws when it cannot be written.\n */\nexport async function endTake(\n dataDir: string,\n offerId: string,\n take: number,\n ending: Partial<JobTake>,\n): Promise<{ won: boolean; take: JobTake } | null> {\n let ended = null as JobTake | null;\n const written = await updateTake(dataDir, offerId, take, (current) => {\n if (current.state !== 'running') {\n ended = current;\n return null;\n }\n return { ...current, ...ending };\n });\n if (written !== null) return { won: true, take: written };\n return ended !== null ? { won: false, take: ended } : null;\n}\n\n/** Drop every take past its `expiresAt`, and any unreadable one past two days.\n * Housekeeping only: never throws. */\nexport async function pruneJobs(dataDir: string, now: number): Promise<void> {\n await sweep(jobsDir(dataDir), async (name, path) => {\n if (!/^[0-9a-f]{64}\\.\\d\\.json$/.test(name)) return false;\n const parsed = TakeSchema.safeParse(await readJsonFile(path, MAX_RECORD_BYTES));\n if (parsed.success) return Date.parse(parsed.data.expiresAt) < now;\n // Unreadable, or gone (which rejects, and is left for the next pass).\n return now - (await lstat(path)).mtimeMs > UNREADABLE_TTL_MS;\n });\n}\n","import {\n isLowFundsRefusal,\n LOW_FUNDS_TAIL,\n runPay,\n settlementTx,\n type AdvertisedTerms,\n type PaidLeg,\n type PayDeps,\n} from '../commands/pay';\nimport { CliError } from '../lib/errors';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { downloadsDir } from '../lib/paths';\nimport { mask } from '../lib/redact';\nimport {\n assertResultSchema,\n canonicalHash,\n projectBody,\n validateResultBody,\n} from '../lib/request-schema';\nimport { resolveContextSettings, type ResolvedSettings } from '../lib/settings';\nimport {\n admitPlan,\n admitQuote,\n reopenShortQuote,\n wasShortOfFunds,\n type PlanSlot,\n} from '../lib/spend-plan';\nimport { quoteClosed, readQuote } from '../lib/spend-quotes';\nimport type { SpendAuthorizer, WalletProvider } from '../lib/wallet';\nimport type { TenjinSigner } from '../lib/wallet/provider';\nimport type { CommandContext } from '../context';\nimport type { ExecFn } from '../lib/os-store';\nimport type { OpenAccountSession } from './accounts/client';\nimport { readAccountJob } from './accounts/jobs';\nimport {\n buildSpecRequest,\n specInputProblems,\n specText,\n mergedInput,\n type SpecRequest,\n} from './spec-call';\nimport {\n claimSpecPayment,\n readKeptSpec,\n releaseSpecClaim,\n settleSpecPayment,\n storeChoices,\n storeFullResult,\n storeSpecs,\n type EarlierPayment,\n type KeptChoices,\n type KeptSpec,\n} from './specs';\nimport { settingsRefusal, UNREADABLE, type SettingsRefusal } from './settings-check';\nimport type { WireSettings } from './settings-wire';\nimport {\n DEADLINE_AFTER_PAYMENT_SENT,\n isAccountSpec,\n MAX_INPUT_BYTES,\n reportSpecOutcome,\n requestBrowse,\n requestDecision,\n requestToolSpec,\n type BrowseRow,\n type DecisionOutcome,\n type SpecOutcome,\n type UnpaidReason,\n type DecisionContract,\n type DecisionDeps,\n type DecisionDiagnostics,\n type DecisionRoute,\n type Job,\n type OfferSpec,\n} from './decision';\nimport { BUILT_IN_SOURCE } from './settings-wire';\nimport { pickChoice, runChoiceSet, runCount, showChoices, takesResult } from './choices';\nimport {\n approveCall,\n oneCall,\n quotedHashes,\n paymentProvider,\n planStop,\n quotedCall,\n quoteView,\n type PlanStop,\n type QuotedCall,\n} from './plan';\nimport { depositSentence, shortOfFunds, unpaidSentence, type RouteFor } from './fee';\nimport { termsNotice } from './terms-notice';\nimport { agentFixOf } from './wallet-reasons';\nimport { openLookupFooter, SILENT_FOOTER, type LookupFooter } from './progress';\nimport { saveInlineMedia } from './inline-media';\nimport {\n appendPaidRecord,\n MAX_MEDIA_FILES,\n mediaUrlsIn,\n reconcilePayments,\n recordedSent,\n saveMedia,\n createUniqueFile,\n maskDeep,\n recordAccountRow,\n updatePaidRecord,\n writeAll,\n type MediaTransport,\n type PaidRecord,\n type SignedAuthorization,\n} from './paid';\nimport { routerSettings, type RouterSettings } from './settings';\nimport { markTaken } from './untaken';\nimport type { Harness } from './names';\nimport {\n answerState,\n completeJob,\n MAX_CALL_WAIT_MS,\n pollTarget,\n pollUntil,\n sellerSaid,\n type PollAnswer,\n type PollDeps,\n type PollTransport,\n} from './jobs';\nimport {\n endTake,\n KEPT_RESULT_CHARS,\n MAX_TAKES,\n readTake,\n readTakes,\n writeTake,\n type JobTake,\n} from './job-store';\n\n/**\n * The `request` tool: one routing decision per lookup, paid its routing fee\n * by `tenjin mcp`'s payer, then one payment per take to the provider.\n *\n * AN OFFER WITH A SPEC RUNS HERE, IN ONE CALL. The hook keeps each offered\n * service's spec by its id, and its line is the skeleton of the call:\n * `{id, input}` is checked against the spec, built into the spec's request and\n * paid straight to the provider, with no second decision. An input that misses\n * gets every problem and the whole spec back, locally, with nothing paid; `{id}`\n * alone shows the spec too. The server is told only how the call ended. A\n * query with no id comes back as the picked service's spec under a fresh id,\n * with nothing paid; the next call fills it.\n *\n * AN ID WITH NO KEPT SPEC builds nothing. An input for it (the spec expired\n * or was pruned) is answered here, with no server call and nothing paid: the\n * agent starts over with `request({query})`. A query with it goes to the\n * server, which binds the free docs lookup, the one offer with no spec, from\n * the query in code, and points any other id back to a fresh query.\n *\n * A CHOICE SET, when a line offers one, is the user's to pick from:\n * `request({id, choice})` runs the picked option as its own offer, under its\n * own id, and `choice: \"all\"` runs every option side by side, one payment\n * each (`choices.ts`).\n *\n * WHAT IS CHECKED LOCALLY, BEFORE ANYTHING IS SIGNED: the input against the\n * spec's schema, the decision's arguments against the schema it carries, its\n * success rule against the compiler, its destination against the shared\n * preflight inside `runPay`, and the call's SPEND PLAN: every payment it will\n * make, at its quoted amount, whose total meets `maxAutoSpend` (the limit for\n * the whole call) and the day's `sessionBudget` at once\n * (`lib/spend-plan.ts`). `runPay` signs a router payment only against a slot\n * of an admitted plan, and `gateSpend` still meets each one. That is the\n * whole money story: a hostile backend can name any origin and spend at most\n * one `maxAutoSpend` per call inside the daily budget without the user's yes.\n *\n * `needs_approval` is a LOCAL outcome only. The server never sends it: it is\n * what a plan over the limits looks like from here. Nothing is paid. Where the\n * host offers `approve`, the plan is kept as a quote, and the user's yes to\n * the host's own prompt on `approve({quote})` runs it exactly\n * ({@link runApproveTool}).\n */\n\nexport interface RequestToolArgs {\n /** The task to route, or the query for an explicitly selected free tool. */\n query?: string;\n /** The turn id from the hook's line. It names the service that line offered;\n * it grants nothing locally, every cap still applies. */\n id?: string;\n /** The host's own input for the offered service, per its spec. This client\n * builds the request from the spec kept for the id; with none kept, nothing\n * is built. Every cap still applies. */\n input?: Record<string, unknown>;\n /** One option's key from the choice set the line offered with `id`, run as\n * that option's own offer under its own id, or `all` for every option side\n * by side, one payment each. Every cap still applies. */\n choice?: string;\n /** A free browse of the tool list: the need in a few words, or `\"\"` for\n * every tool by kind. Sent alone; nothing is paid. */\n browse?: string;\n /** A browse row's id: alone, its spec for `{id, input}`; with a query,\n * an explicitly selected free lookup, without paid routing. */\n tool?: string;\n /** Several takes of one media call, 2 to 5, each its own payment, where the\n * spec allows them. The whole set meets the spend policy before any is\n * signed. */\n count?: number;\n /** A job an earlier call left running, by the id its result named: polled\n * again, with nothing paid. */\n job?: string;\n /** One of the user's connected accounts, by name, when the user asks for\n * it by name: alone it lists the account's tools, with `tool` it shows\n * one, and with `tool` and `input` it runs that tool on the account\n * (`accounts/explicit.ts`). Never routed, never from the balance. */\n source?: string;\n}\n\nexport interface RequestToolDeps {\n ctx: CommandContext;\n /** The SAME provider the MCP server pre-warmed. `runPay` opens its own\n * otherwise, and the local one re-runs scrypt per process, which is the\n * 2.3 s the background unlock exists to hide. */\n provider?: WalletProvider;\n signer?: TenjinSigner;\n authorizer: SpendAuthorizer;\n fetchImpl?: typeof fetch;\n /** Test seam forwarded to the provider leg. */\n payDeps?: PayDeps;\n /** The directory `router.*` resolves from; defaults to `process.cwd()`, which\n * Claude Code sets to the project directory for an MCP server. */\n cwd?: string;\n /** Clock seam for a saved file's name. */\n now?: () => number;\n /** The payer's route, passed by `tenjin mcp`. Absent, the routing call goes\n * unpaid, and a router that asks for the fee skips it. */\n route?: RouteFor;\n /** Test seam for the media download; production pins each connection to\n * the address it validated. */\n mediaTransport?: MediaTransport;\n /** Test seam for a job's polls, pinned the same way in production. */\n pollTransport?: PollTransport;\n /** Clock seam for the wait between polls. */\n sleep?: (ms: number) => Promise<void>;\n /** When this tool call started: every job it runs waits from here. Set by\n * {@link runRequestTool}. */\n startedAt?: number;\n /** What this tool call may still write to the downloads directory, shared by\n * every take. Set by {@link runRequestTool}. */\n downloads?: { leftBytes: number };\n /** Told before each poll of a job this call waits on: the MCP server sends\n * it as a progress notification, which keeps a waiting host's timeout from\n * running out. */\n onPoll?: () => Promise<void> | void;\n /** The host puts every `approve` call to a person first (Claude Code's\n * `requiresUserInteraction`, `mcp.ts`), so a call over the limits is kept\n * as a quote for it. Without it, such a call is refused with nothing kept. */\n approves?: boolean;\n /** The host lets one call wait as long as a job's own `maxWaitS` (Claude\n * Code moves a long call into the background and delivers it when it\n * ends), so the call is not handed back `running` at\n * {@link MAX_CALL_WAIT_MS}. */\n waitsForJobs?: boolean;\n /** The host that launched this server; absent is Claude Code. */\n harness?: Harness;\n /** `swap`: this call answers a native search or fetch in place\n * (`swap.ts`), so its ledger record and outcome report say so. */\n via?: 'swap';\n /** Seams for a call on the user's own account (plan 37): the OS store its\n * vault key is read from, and its MCP session. Tests pass them; production\n * uses the platform's. */\n accounts?: {\n exec?: ExecFn;\n platform?: NodeJS.Platform;\n openSession?: OpenAccountSession;\n lockTimeoutMs?: number;\n };\n}\n\n/** What one tool call may save to disk, across every take and file. */\nexport const MAX_CALL_DOWNLOAD_BYTES = 1024 * 1024 * 1024;\n/** Why a file this call had no room left for was not saved. */\nconst CAP_REACHED = `not saved: this call already saved ${Math.round(MAX_CALL_DOWNLOAD_BYTES / 1_048_576)} MB, its cap`;\nconst DOWNLOAD_FAILED = 'a file it links to failed to download';\n\nexport interface RequestToolResult {\n isError: boolean;\n summary: string;\n envelope: Record<string, unknown>;\n}\n\nexport async function runRequestTool(\n args: RequestToolArgs,\n deps: RequestToolDeps,\n): Promise<RequestToolResult> {\n // A ROUTING DEPOSIT IS SAID WHERE THE AGENT READS IT: once, in the result of\n // the call that took it, beside whatever that call answered. A hook leg says\n // it in its `systemMessage` instead, and a background top-up's is the hook\n // leg's alone (`toppedUp`), so the person is the one told.\n const routes: DecisionRoute[] = [];\n const { route } = deps;\n const call: RequestToolDeps = {\n ...deps,\n startedAt: deps.startedAt ?? (deps.now ?? Date.now)(),\n downloads: deps.downloads ?? { leftBytes: MAX_CALL_DOWNLOAD_BYTES },\n };\n const result = await requestTool(\n args,\n route === undefined\n ? call\n : {\n ...call,\n route: (baseUrl) => {\n const picked = route(baseUrl);\n routes.push(picked);\n return picked;\n },\n },\n );\n const terms = routes.length > 0 ? await termsNotice(deps.ctx.dataDir) : null;\n const deposited = routes.reduce((sum, r) => sum + (r.deposited?.() ?? 0n), 0n);\n const notices = [terms, deposited > 0n ? depositSentence(deposited) : null].filter(\n (notice) => notice !== null,\n );\n return notices.length > 0\n ? { ...result, summary: [result.summary, ...notices].join('\\n') }\n : result;\n}\n\nexport interface ApproveToolArgs {\n /** The quote a `needs_approval` result named. */\n quote: string;\n /** The quote's total and what it buys, which the host's prompt shows the\n * user; each must match the quote. */\n total?: string;\n what?: string;\n}\n\n/**\n * `approve({quote, total, what})`: A QUOTE THE USER SAID YES TO, RUN EXACTLY.\n * The quote is the plan a call over the automatic limits kept, with nothing\n * paid: the call, its input, each payment and the total. Nothing about it\n * changes here; the agent sends only its id and the numbers it was shown.\n *\n * THE YES IS THE HOST'S OWN PROMPT. The tool is offered only to a host that\n * puts every call of it to a person before it reaches this process (Claude\n * Code's `requiresUserInteraction`, `mcp.ts`), so a call here is that\n * person's yes; nothing on disk counts as one. The prompt shows the call's\n * arguments, so the total and what it buys must be there and must be the\n * quote's. A yes runs the quote once, past `maxAutoSpend` and the day's\n * budget, which a person just agreed to, and answers\n * as `request` would have. A run whose every payment was refused as short of\n * funds leaves the quote open for the next yes (`reopenShortQuote`).\n */\nexport async function runApproveTool(\n args: ApproveToolArgs,\n deps: RequestToolDeps,\n): Promise<RequestToolResult> {\n const here = await routerHere(deps);\n if ('off' in here) return fail('needs_input', here.off, { nextStep: ROUTER_OFF_NEXT_STEP });\n const { dataDir } = deps.ctx;\n const now = deps.now ?? Date.now;\n const fresh = 'Call request again with the same call for a fresh quote.';\n const quote = await readQuote(dataDir, args.quote.trim());\n const call = quote !== null ? quotedCall(quote) : null;\n if (quote === null || call === null) {\n return fail(\n 'needs_input',\n 'No quote is kept on this machine under that id, so nothing was paid.',\n { nextStep: fresh },\n );\n }\n const closed = quoteClosed(quote, now());\n if (closed !== null) {\n return fail(\n 'needs_input',\n closed === 'used'\n ? 'That quote already ran, and a quote pays once, so nothing more was paid.'\n : 'That quote expired (a quote waits ten minutes for a yes), so nothing was paid.',\n {\n nextStep: closed === 'used' ? 'Its result is in the approve call that ran it.' : fresh,\n },\n );\n }\n // THE NUMBERS A PERSON IS SHOWN ARE THE QUOTE'S: an echo that differs is\n // refused with the true ones, never run.\n const total = BigInt(quote.totalAtomic);\n const echoedTotal = args.total !== undefined ? usdAtomic(args.total) : undefined;\n if (\n (args.total !== undefined && echoedTotal !== total) ||\n (args.what !== undefined && args.what.trim() !== quote.what)\n ) {\n return fail(\n 'needs_input',\n `That quote is for ${quote.what}, $${toMoney(quote.totalAtomic).usd} in total, not what this call said, so nothing was paid.`,\n { quote: quoteView(quote), nextStep: `Call ${approveCall(quote)}.` },\n );\n }\n // The prompt showed this call's arguments: without the total and what they\n // buy, nobody saw what they said yes to.\n if (args.total === undefined || args.what === undefined) {\n return fail(\n 'needs_input',\n \"Send the quote's total and what it buys with it, so the user sees them when asked; nothing was paid.\",\n { quote: quoteView(quote), nextStep: `Call ${approveCall(quote)}.` },\n );\n }\n // THE RULES THE QUOTED OFFERS WERE DECIDED UNDER, before the quote is used\n // up: settings changed since leave it unused, and the agent asks again.\n const stale = await settingsRefusal(dataDir, quotedHashes(call));\n if (stale !== null) return settingsFail(stale);\n // THE WALLET OPENS BEFORE THE QUOTE IS USED UP. `admitQuote` spends the\n // quote's one run, so a wallet that will not sign (a passphrase gone or\n // wrong) must stop here, with the quote still open for a yes after the\n // person repairs it. `runPay` reuses this provider and its opened signer.\n const provider = paymentProvider(deps);\n try {\n await provider.getSigner();\n } catch (err) {\n if (!(err instanceof CliError)) throw err;\n return fail(\n 'failed',\n `${quote.sentence} ${err.message} No payment was signed. ${agentFixOf(err)}`.trim(),\n { nextStep: 'Tell the user. The quote waits for its ten minutes; nothing was paid.' },\n );\n }\n const call_: RequestToolDeps = {\n ...deps,\n provider,\n startedAt: deps.startedAt ?? now(),\n downloads: deps.downloads ?? { leftBytes: MAX_CALL_DOWNLOAD_BYTES },\n };\n const settings = await resolveContextSettings(deps.ctx);\n const admitted = await admitQuote(dataDir, quote.id, {\n now,\n });\n if ('refused' in admitted) {\n return fail(\n 'needs_input',\n admitted.refused === 'used'\n ? 'That quote already ran, and a quote pays once, so nothing more was paid.'\n : 'That quote can no longer run, so nothing was paid.',\n { nextStep: fresh },\n );\n }\n const slots = admitted.admitted;\n const reportDeps: ReportDeps = {\n ctx: deps.ctx,\n baseUrl: settings.baseUrl,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n const footer = await openLookupFooter(dataDir, call.kind !== 'call' ? { id: call.id } : {});\n await footer.routing();\n const result = await runQuoted(call, slots, call_, footer, reportDeps, settings);\n // A SHORT WALLET'S QUOTE STAYS OPEN: funded, the same quote runs on the\n // person's next yes, with no new quote to ask for. Its offers' claims go\n // with it, or the rerun would find each one paid.\n const reopened = await reopenShortQuote(dataDir, quote.id, slots, {\n now,\n releaseClaims: async () => {\n for (const slot of slots) {\n const held = claimOfSlot.get(slot);\n if (held !== undefined) await releaseSpecClaim(dataDir, held.claim, held.owner);\n }\n },\n });\n if (!reopened) return result;\n return {\n ...result,\n envelope: {\n ...result.envelope,\n quote: quoteView(quote),\n nextStep: `${shortOfFunds(quoteFor(call, slots))} The quote stays open for its ten minutes: once the funds arrive, call ${approveCall(quote)} again.`,\n },\n };\n}\n\n/**\n * What a short quote's ask for funds names: ONE call, by its display label\n * (else its provider), at one call's price, because the fund page and\n * `tenjin fund` show that price per call. A count names one take. A choice\n * set names the option its run was refused for (the dearest, when several\n * were), else its dearest option. `slots` are the quote's, in its payments'\n * order.\n */\nfunction quoteFor(\n call: QuotedCall,\n slots: readonly PlanSlot[],\n): { label?: string | undefined; provider: string; priceAtomic: bigint } {\n const refused = slots.filter(wasShortOfFunds);\n const one = (refused.length > 0 ? refused : slots).reduce((dearest, slot) =>\n slot.amountAtomic > dearest.amountAtomic ? slot : dearest,\n );\n const priceAtomic = one.amountAtomic;\n if (call.kind === 'call')\n return { label: call.call.label, provider: call.call.provider, priceAtomic };\n if (call.kind !== 'choices')\n return { label: call.spec.label, provider: call.spec.provider, priceAtomic };\n // A choice set's slots follow its keys; its specs follow the set's options.\n const key = call.keys[slots.indexOf(one)];\n const spec =\n call.specs[call.kept.choices.options.findIndex((option) => option.key === key)] ??\n call.specs[0]!;\n return { label: spec.label, provider: spec.provider, priceAtomic };\n}\n\n/** Run an approved quote's call on its slots. */\nasync function runQuoted(\n call: QuotedCall,\n slots: PlanSlot[],\n call_: RequestToolDeps,\n footer: LookupFooter,\n reportDeps: ReportDeps,\n settings: ResolvedSettings,\n): Promise<RequestToolResult> {\n switch (call.kind) {\n case 'spec':\n return runSpec(call.id, call.spec, call.input, call_, footer, reportDeps, slots);\n case 'count':\n return runCount(\n call.id,\n call.spec,\n call.input,\n call.count,\n call_,\n footer,\n reportDeps,\n settings,\n slots,\n );\n case 'choices':\n return runChoiceSet(call.id, call.kept, call.input, call_, footer, reportDeps, settings, {\n specs: call.specs,\n keys: call.keys,\n slots,\n });\n case 'call':\n return (await payAndDeliver(call.call, { slot: slots[0]! }, call_, footer)).result;\n }\n}\n\n/** An echoed total in USD, `$0.775` or `0.775`, as atomic units; undefined\n * when it is not one. */\nfunction usdAtomic(text: string): bigint | undefined {\n try {\n return BigInt(\n parseUsdToAtomic(\n text\n .trim()\n .replace(/^\\$/, '')\n .replace(/\\s*USD$/i, ''),\n ),\n );\n } catch {\n return undefined;\n }\n}\n\nasync function requestTool(\n args: RequestToolArgs,\n deps: RequestToolDeps,\n): Promise<RequestToolResult> {\n // THE SAME SWITCH THE HOOKS OBEY, read first. The tool is pre-allowed, so\n // without this it would be a second path off the machine in a repository the\n // user marked private: nothing is sent and nothing is paid.\n const here = await routerHere(deps);\n if ('off' in here) return fail('needs_input', here.off, { nextStep: ROUTER_OFF_NEXT_STEP });\n // RULES THIS BUILD CANNOT READ ARE NEVER GUESSED: nothing is asked, sent or\n // run until they are fixed. A job already paid for may still be polled.\n if (here.settings.wire.status === 'invalid' && (args.job === undefined || args.job === '')) {\n return settingsFail(UNREADABLE);\n }\n const sent = here.settings.wire.status === 'ok' ? here.settings.wire.settings : undefined;\n // AN ACCOUNT THE USER NAMED (plan 37): its own tools, never a lookup.\n if (args.source !== undefined) {\n const others = (['query', 'id', 'choice', 'browse', 'count', 'job'] as const).filter(\n (key) => args[key] !== undefined,\n );\n if (others.length > 0) {\n return fail('needs_input', '`source` goes with `tool` and `input` alone; nothing was sent.', {\n nextStep: \"Call request({source}) for the account's tools.\",\n });\n }\n return (await import('./accounts/explicit')).runSourceRequest(\n {\n source: args.source,\n ...(args.tool !== undefined ? { tool: args.tool } : {}),\n ...(args.input !== undefined ? { input: args.input } : {}),\n },\n deps,\n );\n }\n if (args.browse !== undefined || (args.tool !== undefined && args.query === undefined))\n return readToolList(args, deps, sent);\n if (args.tool !== undefined) {\n if (args.tool.trim().length === 0 || args.tool.trim().length > 200)\n return fail('needs_input', '`tool` takes a row id from request({browse}).');\n if ((['id', 'input', 'choice', 'count', 'job'] as const).some((key) => args[key] !== undefined))\n return fail('needs_input', 'A selected free lookup takes only its tool id and query.');\n if (mask(args.tool) !== args.tool)\n return fail('native', 'the tool id carries a credential-shaped value, so nothing was sent');\n }\n // A JOB AN EARLIER CALL LEFT RUNNING, by the id its result named: polled from\n // its record, with nothing built and nothing paid.\n if (args.job !== undefined && args.job.length > 0) {\n if (args.input !== undefined || args.choice !== undefined || args.count !== undefined) {\n return fail('needs_input', 'A job resumes on its own: send only its id, as `job`.', {\n nextStep: `Call request({job: ${JSON.stringify(args.job)}}); nothing was sent or paid.`,\n });\n }\n return resumeJob(args.job, deps);\n }\n const offered = args.id !== undefined && args.id.length > 0 ? args.id : undefined;\n // A call naming an offer's id takes it, whatever it asks: that offer was not\n // ignored, so nothing reports it so (`untaken.ts`).\n if (offered !== undefined) await markTaken(deps.ctx.dataDir, offered);\n let id = offered;\n const { input } = args;\n const choice = args.choice !== undefined && args.choice.length > 0 ? args.choice : undefined;\n // SEVERAL TAKES OF ONE CALL, refused here, before anything is read or sent,\n // unless they can run: a whole number of takes, on an offer's filled input,\n // never beside a choice.\n const count = args.count !== undefined && args.count !== 1 ? args.count : undefined;\n if (count !== undefined) {\n const refusal =\n !Number.isInteger(count) || count < 2 || count > MAX_TAKES\n ? `count is a whole number of takes from 2 to ${MAX_TAKES}`\n : choice !== undefined\n ? 'count runs several takes of one service, so it does not go with a choice'\n : input === undefined || offered === undefined\n ? \"count goes with the offer's id and its filled input\"\n : undefined;\n if (refusal !== undefined) {\n return fail('needs_input', `${refusal}; nothing was sent or paid.`);\n }\n }\n // A CHOICE NAMES AN OPTION OF THE SET KEPT FOR THE LINE'S ID, and from here\n // the call is that option's own offer, under its own id: its spec, its one\n // payment. `all` is every option, run below once the input is checked.\n let set: KeptChoices | undefined;\n if (choice !== undefined) {\n const picked = await pickChoice(deps.ctx.dataDir, offered, choice);\n if ('refused' in picked) return picked.refused;\n if ('all' in picked) set = picked.all;\n else id = picked.id;\n }\n if (set !== undefined && input === undefined) return showChoices(id!, set);\n // THE OFFER'S SPEC, when the hook kept one for this id: its id alone shows\n // the spec, with no network call and nothing paid, so the agent sees the\n // real inputs before it builds any.\n const kept =\n id !== undefined && set === undefined ? await readKeptSpec(deps.ctx.dataDir, id) : null;\n // A SERVICE ON THE USER'S OWN ACCOUNT (plan 37): one call at a time, which\n // their plan pays, so never several takes.\n if (kept?.account === true) {\n if (count !== undefined) {\n return fail(\n 'needs_input',\n `${kept.spec.provider} runs one call at a time on your own account, so count was not used; nothing was sent.`,\n { nextStep: `Call request({id: ${JSON.stringify(id)}, input: {...}}) without count.` },\n );\n }\n if (input === undefined)\n return (await import('./accounts/run')).showAccountSpec(id!, kept.spec, deps.ctx.dataDir);\n }\n const spec = kept !== null && kept.account !== true ? kept.spec : null;\n if (spec !== null && input === undefined) return showSpec(id!, spec);\n // Takes only where the spec says its service runs them, and no more of\n // them than it allows: a count is several payments, and one service's\n // files are what several takes are for.\n if (\n count !== undefined &&\n spec !== null &&\n (spec.takes === undefined || count > spec.takes.max)\n ) {\n return fail(\n 'needs_input',\n spec.takes === undefined\n ? `${spec.provider} does not run several takes of one call, so count was not used; nothing was sent or paid.`\n : `${spec.provider} runs at most ${spec.takes.max} takes of one call; nothing was sent or paid.`,\n {\n nextStep: `Call request({id: ${JSON.stringify(id)}, input: {...}})${spec.takes === undefined ? ' without count' : ` with count up to ${spec.takes.max}`}.`,\n },\n );\n }\n const query = (args.query ?? '').trim().slice(0, 8_000);\n if (query.length === 0 && input === undefined) {\n if (args.tool !== undefined)\n return fail('needs_input', 'Include what to look up in request({tool, query}).');\n return fail(\n 'needs_input',\n id !== undefined\n ? '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.'\n : \"A request needs an offer's id, or a query naming the task, its inputs and any constraints.\",\n );\n }\n // THE HOOKS NEVER SEE THIS CALL, so the native hook's rule applies here too: a\n // query the mask would change is not sent, masked or otherwise. The server\n // stores it against the id and the provider logs it, and an injected page can\n // write it.\n if (mask(query) !== query) {\n return fail('native', 'the query carries a credential-shaped value, so nothing was sent');\n }\n // The same rule for an input, which goes to the seller as the request body\n // or its query string.\n if (input !== undefined) {\n // An input fills the spec of the service that id named, so with no id it\n // has nothing to go to.\n if (id === undefined) {\n return fail(\n 'needs_input',\n 'An input goes with the id from the line that named the service; send both.',\n );\n }\n const serialized = JSON.stringify(input);\n if (Buffer.byteLength(serialized) > MAX_INPUT_BYTES) {\n return fail('needs_input', `The input is over ${MAX_INPUT_BYTES} bytes; send a smaller one.`);\n }\n // EVERY KEY AND STRING LEAF, masked on its own: in the serialized JSON a\n // key after an escaped `\\n` reads as one word (`nsk-ant-…`), so the\n // boundaries the mask anchors on are not there.\n if (JSON.stringify(maskDeep(input)) !== serialized) {\n return fail('native', 'the input carries a credential-shaped value, so nothing was sent');\n }\n // NO SPEC KEPT FOR THE ID: it expired or was pruned, and nobody else builds\n // the call. Answered here, with no server call: one more call costs less\n // than a guess. A set reads each option's spec itself.\n if (kept === null && set === undefined) {\n return fail(\n 'needs_input',\n 'The spec for that offer is no longer kept on this machine (it expired or was pruned), so nothing was sent or paid.',\n {\n nextStep:\n '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.',\n },\n );\n }\n }\n // THE FOOTER, OPENED FIRST AND TRUSTED WITH NOTHING: it shows this lookup in\n // the terminal while it runs, resolved to a session through the hook's own\n // binding for the line's id (never a chosen option's), and every call on it\n // swallows its own failure.\n const footer = await openLookupFooter(deps.ctx.dataDir, {\n ...(offered !== undefined ? { id: offered } : {}),\n });\n await footer.routing();\n const settings = await resolveContextSettings(deps.ctx);\n // SETTLEMENTS EARLIER CALLS LEFT UNKNOWN, resolved a few at a time from the\n // chain, BESIDE the lookup and never in front of it: a slow or rate-limited\n // RPC costs this call nothing, and a record it could not answer for waits\n // `RECHECK_MS` before it is asked about again. Its own errors are its own.\n if (args.tool === undefined)\n void reconcilePayments(deps.ctx.dataDir, {\n rpcUrl: settings.rpcUrl,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n ...(deps.now !== undefined ? { now: deps.now } : {}),\n }).catch(() => undefined);\n const decisionDeps = {\n ctx: deps.ctx,\n baseUrl: settings.baseUrl,\n acceptsBazaar: settings.experimentalBazaar,\n harness: deps.harness ?? 'claude',\n improve: here.settings.improve.value,\n // Read from the global file for this call, never cached: a change made\n // in another process reaches the next call with no restart.\n ...(sent !== undefined ? { settings: sent } : {}),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n\n // EVERY OPTION OF A SET, each its own offer, checked, claimed and paid\n // through the same steps as one, after one spend check for them all.\n if (set !== undefined && input !== undefined) {\n return runChoiceSet(id!, set, input, deps, footer, decisionDeps, settings);\n }\n\n // AN ACCOUNT SERVICE'S SPEC AND AN INPUT: run on the user's own account,\n // which their plan pays (`accounts/run.ts`).\n if (kept?.account === true && input !== undefined) {\n const { runAccountSpec } = await import('./accounts/run');\n return runAccountSpec(id!, kept.spec, input, deps, footer, decisionDeps);\n }\n\n // A SPEC AND AN INPUT: the agent filled the spec's request itself, so it is\n // checked and sent here and paid straight to the provider, with no second\n // decision. The server hears only how it ended.\n if (spec !== null && input !== undefined) {\n // SEVERAL TAKES: each its own claim and payment, after one spend check\n // for them all (`choices.ts`).\n const run = () =>\n count !== undefined\n ? runCount(id!, spec, input, count, deps, footer, decisionDeps, settings)\n : runSpec(id!, spec, input, deps, footer, decisionDeps);\n // OFFERED IN A REFUSED ACCOUNT OFFER'S PLACE (plan 37): that offer never\n // runs too once this one has.\n if (kept?.account !== true && kept?.replaces !== undefined) {\n const { runInPlaceOf } = await import('./accounts/run');\n return runInPlaceOf(kept.replaces, id!, run, deps.ctx.dataDir);\n }\n return run();\n }\n\n // ONE CALL, ONE DECISION. The query the model wrote goes to the backend with\n // the turn id when it has one: the free docs offer's id binds the query, and\n // with no id the gate picks a service and answers with its spec. An id the\n // backend does not know is its own plain note, and the pick still runs from\n // the query.\n // ON THE PAID ROUTE the payer pays the routing fee with the stock x402\n // client. A call it cannot pay is answered here at once: nothing was\n // routed, and the agent uses its own tools.\n const fresh =\n args.tool !== undefined\n ? await requestToolSpec(args.tool.trim(), decisionDeps, query)\n : await requestDecision(\n 'tool',\n { query, ...(id !== undefined ? { id } : {}) },\n { ...decisionDeps, route: deps.route?.(settings.baseUrl) },\n );\n if (fresh.status === 'skipped') {\n await footer.done('native');\n // A reason that lasts (money, the wallet, a limit, the fee's price) is\n // the user's to hear once; a busy channel, a slow unlock or a top-up still\n // on its way is not.\n const lasting = unpaidSentence(fresh.why, 'agent', fresh.quotedAtomic);\n return fail(\n 'native',\n fresh.why === DEADLINE_AFTER_PAYMENT_SENT\n ? '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.'\n : `${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.`,\n {\n nextStep:\n lasting !== null\n ? 'Tell the user this once, and use your own tools for now.'\n : 'Use your own tools for this one.',\n },\n );\n }\n if (fresh.status === 'failed') {\n await footer.done('failed');\n return fail('failed', fresh.reason, {\n ...(fresh.errorCode !== undefined ? { errorCode: fresh.errorCode } : {}),\n });\n }\n const { decision, note, settingsHash } = fresh.decision;\n\n if (args.tool !== undefined) {\n if (\n decision.action !== 'native' &&\n decision.action !== 'needs_input' &&\n (decision.action !== 'execute' ||\n decision.capabilityId !== args.tool.trim() ||\n BigInt(decision.providerPriceAtomic) !== 0n)\n ) {\n await footer.done('failed');\n return fail(\n 'failed',\n 'The answer is not a runnable free lookup for the selected tool. Nothing was sent to a provider or paid.',\n {\n nextStep: 'Use your own tools for this lookup.',\n ...(note !== undefined ? { note } : {}),\n },\n );\n }\n }\n\n // THE PICKED SERVICE'S SPEC, for a query with no id, kept like a hook's and\n // shown with the skeleton of the next call, `request({id, input})`. Nothing\n // is paid on this answer: only a filled spec pays.\n if (decision.action === 'spec') {\n // A SERVICE ON THE USER'S OWN ACCOUNT.\n if (isAccountSpec(decision.spec)) {\n const lead = { ...decision.spec, id: decision.id };\n const shown = await (\n await import('./accounts/run')\n ).offerAccountLead(lead, settingsHash, deps, decisionDeps, decision.hint);\n await footer.done('service found');\n return shown;\n }\n const picked: OfferSpec = { ...decision.spec, id: decision.id };\n await storeSpecs(deps.ctx.dataDir, [picked], settingsHash);\n await footer.done('service found');\n return showSpec(picked.id, picked, [], decision.hint);\n }\n\n // A SERVICE NOBODY CURATED, named for the host to judge. Nothing is paid on\n // this answer. With specs they are kept like the hook's, and the pick's own\n // spec is shown, as for a curated pick. Without, the server's line says how\n // to call it, with the id it minted and the input the host builds, and that\n // second call pays through the execute path below like any other.\n if (decision.action === 'discovered') {\n await storeSpecs(deps.ctx.dataDir, decision.specs, settingsHash);\n // A CHOICE SET is kept like the hook's, and its line, which names every\n // option and the call, is the next step in place of an \"also offered\"\n // line per option.\n const { choices } = decision;\n if (choices !== undefined) {\n await storeChoices(deps.ctx.dataDir, decision.id, { choices, hint: decision.hint });\n }\n await footer.done('service found');\n const picked = decision.specs?.find((spec) => spec.id === decision.id);\n if (picked !== undefined) {\n const options = new Set(choices?.options.map((option) => option.id));\n return showSpec(\n picked.id,\n picked,\n decision.specs!.filter((spec) => spec !== picked && !options.has(spec.id)),\n choices !== undefined ? decision.hint : undefined,\n );\n }\n const { candidate } = decision;\n return {\n isError: false,\n summary: decision.hint,\n envelope: {\n status: 'discovered',\n id: decision.id,\n service: {\n provider: candidate.provider,\n url: candidate.url,\n method: candidate.method,\n description: candidate.description,\n price: `$${toMoney(candidate.providerPriceAtomic).usd}`,\n input: candidate.input,\n },\n cost: costLines(0n),\n ...(note !== undefined ? { note } : {}),\n providerContentUntrusted: true,\n },\n };\n }\n\n if (decision.action !== 'execute') {\n await footer.done(decision.action === 'native' ? 'native' : 'needs_input');\n // Both non-execute arms carry diagnostics by construction now: an answer\n // without them does not parse, so there is nothing to fall back to here.\n return fail(\n decision.action === 'native' ? 'native' : 'needs_input',\n decision.reason ?? 'The router did not select a paid capability.',\n { diagnostics: decision.diagnostics, ...(note !== undefined ? { note } : {}) },\n );\n }\n\n const contract = decision.contract;\n const refusal = checkContract(contract);\n if (refusal !== null) {\n await footer.done(refusal.status);\n return fail(refusal.status, refusal.reason);\n }\n\n // The decision's advertised price caps the live 402, refused before signing.\n // It bounds a provider or stale catalog charging over that price, and an\n // injected `request` call; it does not bound a hostile server, which can\n // still quote up to `maxAutoSpend`. `gateSpend` stays the money authority.\n // The request is the server's, sent verbatim: the only thing built here is\n // the decision about whether to send it.\n const call: ProviderCall = {\n capabilityId: decision.capabilityId,\n provider: decision.provider,\n ...(decision.label !== undefined ? { label: decision.label } : {}),\n // The free docs lookup, the one answer with no spec: text, never files.\n media: false,\n request: contract.request,\n terms: { source: decision.provider, maxAmountAtomic: decision.providerPriceAtomic },\n requestKey: `${decision.capabilityId}:${canonicalHash(contract.arguments ?? {})}`,\n ...(contract.resultSchema !== undefined ? { resultSchema: contract.resultSchema } : {}),\n ...(contract.arguments !== undefined ? { parameters: contract.arguments } : {}),\n // What the ledger records as sent: the host's input, or its query.\n sent: input !== undefined ? JSON.stringify(maskDeep(input)) : query,\n ...(note !== undefined ? { note } : {}),\n ...(settingsHash !== undefined ? { settingsHash } : {}),\n };\n return (await payAndDeliver(call, { alone: { kind: 'call', call } }, deps, footer)).result;\n}\n\n/**\n * THE TOOL LIST, READ FOR FREE. `{browse}` returns the rows the server's tool\n * list has for a need, or every row by kind; `{tool}` fetches one row's spec\n * and keeps it under the fresh offer id the server minted, so `{id, input}`\n * runs it exactly as it runs a hook's offer. Neither is a lookup: no gate call,\n * no routing fee, nothing paid, and the hooks' per-lookup routing is unchanged.\n * This handles list and spec reads; selected `{tool, query}` runs above.\n * The credential rule every other call follows applies to its words.\n */\nasync function readToolList(\n args: RequestToolArgs,\n deps: RequestToolDeps,\n sent: WireSettings | undefined,\n): Promise<RequestToolResult> {\n const others = (['query', 'id', 'input', 'choice', 'count', 'job'] as const).filter(\n (key) => args[key] !== undefined,\n );\n if ((args.browse !== undefined && args.tool !== undefined) || others.length > 0) {\n return fail(\n 'needs_input',\n 'Browse with request({browse}), inspect with request({tool}), or run a free tool with request({tool, query}).',\n );\n }\n const words = (args.browse ?? args.tool ?? '').trim().slice(0, 8_000);\n if (mask(words) !== words) {\n return fail('native', 'the words carry a credential-shaped value, so nothing was sent');\n }\n const settings = await resolveContextSettings(deps.ctx);\n const decisionDeps = {\n ctx: deps.ctx,\n baseUrl: settings.baseUrl,\n acceptsBazaar: settings.experimentalBazaar,\n harness: deps.harness ?? 'claude',\n ...(sent !== undefined ? { settings: sent } : {}),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n if (args.browse !== undefined) {\n const listed = await requestBrowse(words, decisionDeps);\n if (listed.status !== 'decided') return listFailure(listed);\n // THE AGENT IS ASKING, so every row it can run is listed: the user's rules\n // govern only what Tenjin picks on its own.\n return showRows(listed.decision.rows);\n }\n if (words.length === 0) {\n return fail('needs_input', '`tool` takes a row id from request({browse}).');\n }\n const fetched = await requestToolSpec(words, decisionDeps);\n if (fetched.status !== 'decided') return listFailure(fetched);\n const { decision, settingsHash } = fetched.decision;\n if (decision.action === 'spec') {\n // A SERVICE ON THE USER'S OWN ACCOUNT, NAMED BY ITS ID.\n if (isAccountSpec(decision.spec)) {\n const lead = { ...decision.spec, id: decision.id };\n return (await import('./accounts/run')).offerAccountLead(\n lead,\n settingsHash,\n deps,\n decisionDeps,\n decision.hint,\n );\n }\n const picked: OfferSpec = { ...decision.spec, id: decision.id };\n await storeSpecs(deps.ctx.dataDir, [picked], settingsHash);\n return showSpec(picked.id, picked, [], decision.hint);\n }\n if (decision.action === 'native' || decision.action === 'needs_input') {\n return fail(decision.action, decision.reason ?? 'That tool has no spec to show.', {\n diagnostics: decision.diagnostics,\n });\n }\n return fail(\n 'needs_input',\n 'The router answered that tool id with no spec, so nothing was kept or paid.',\n { nextStep: 'Call request({query}) with the task instead.' },\n );\n}\n\n/** A read of the list that got no answer. Nothing was paid on either form. */\nfunction listFailure(\n outcome: Exclude<DecisionOutcome<unknown>, { status: 'decided' }>,\n): RequestToolResult {\n if (outcome.status === 'skipped') return fail('failed', outcome.why);\n return fail('failed', outcome.reason, {\n ...(outcome.errorCode !== undefined ? { errorCode: outcome.errorCode } : {}),\n });\n}\n\n/** One plain line of the server's text, for a row shown to the model. */\nconst flat = (text: string): string => text.replace(/[\\p{Cc}\\p{Cf}]+/gu, ' ').trim();\n\n/** The rows as the model reads them: each tool's name, what it does, its\n * price and the call that fetches its spec. */\nfunction showRows(rows: readonly BrowseRow[]): RequestToolResult {\n const nextStep =\n 'Inspect a tool for free with request({tool: \"<id>\"}). ' +\n 'Run a free tool with request({tool: \"<id>\", query: \"<what to look up>\"}).';\n if (rows.length === 0) {\n return {\n isError: false,\n summary:\n 'No tool in the list fits those words. Browse with other words, or with \"\" for every tool by kind.',\n envelope: { status: 'browse', rows: [], nextStep, cost: costLines(0n) },\n };\n }\n const shown = rows.map((row) => ({\n id: row.id,\n label: flat(row.label),\n does: flat(row.does),\n price: row.free ? 'free' : flat(row.price),\n kind: flat(row.kind),\n }));\n return {\n isError: false,\n summary: [\n ...shown.map((row) => `${row.label} (id ${row.id}, ${row.price}, ${row.kind}): ${row.does}`),\n nextStep,\n ].join('\\n'),\n envelope: {\n status: 'browse',\n rows: shown,\n nextStep,\n cost: costLines(0n),\n providerContentUntrusted: true,\n },\n };\n}\n\n/** The answer to `request({id})` when the hook kept that offer's spec, or to\n * a query the server answered with one: the spec as text, any other service\n * offered beside it one `request({id})` away, and nothing sent or paid. The\n * server's `hint`, when it sent one, is the skeleton of the call to make. */\nexport function showSpec(\n id: string,\n spec: OfferSpec,\n others: readonly OfferSpec[] = [],\n hint?: string,\n): RequestToolResult {\n const also = others.map(\n (other) =>\n `${other.provider} (${other.description}): request({id: ${JSON.stringify(other.id)}}) shows its spec`,\n );\n const lines = [specText(id, spec)];\n if (also.length) lines.push(`Also offered: ${also.join('; ')}.`);\n if (hint !== undefined) lines.push(`Next: ${hint}`);\n return {\n isError: false,\n summary: lines.join('\\n'),\n envelope: {\n status: 'spec',\n id,\n nextStep:\n hint ?? `Call request({id: ${JSON.stringify(id)}, input: {...}}) with the inputs above.`,\n cost: costLines(0n),\n },\n };\n}\n\n/** A spec's id that an earlier call already claimed: nothing sent or paid,\n * and the agent pointed at that call's result or at a new offer. */\nexport function alreadyPaid(\n id: string,\n spec: OfferSpec,\n earlier: EarlierPayment,\n /** A job that call left is still running, under this id. */\n running?: string,\n): RequestToolResult {\n if (running !== undefined && earlier.state !== 'unrecorded') {\n return fail(\n 'needs_input',\n `This offer from ${spec.provider} was already paid for, and ${spec.provider} is still working on it, so nothing was paid this time.`,\n {\n nextStep: `Call request({job: ${JSON.stringify(running)}}) for its result; nothing more is paid.`,\n },\n );\n }\n const reason =\n earlier.state === 'paid'\n ? `This offer from ${spec.provider} was already paid for at ${earlier.at} ($${toMoney(earlier.amountAtomic).usd}${earlier.txHash !== undefined ? `, 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\\`.`\n : earlier.state === 'possibly_paid'\n ? `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.`\n : earlier.state === 'running'\n ? `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.`\n : `This machine could not record this offer's payment, so nothing was sent or paid.`;\n return fail('needs_input', reason, {\n nextStep: `For another call, send request({query}) for a new offer; this id (${id}) pays once.`,\n });\n}\n\n/**\n * `request({id, input})` FROM A SPEC. The pinned fields go over the agent's\n * input, the result is checked against the spec's schema (every problem at\n * once, with the allowed values and the example), and the spec's request is\n * filled and paid through `runPay` like any router call: the live 402's price\n * against the spec's ceiling, its payee against the spec's, and the amount\n * signed against the spend policy. Then the server is told how it ended.\n *\n * Three steps, which a choice set runs per option too: the checks, the claim,\n * and the payment. The payment is a plan of one at its live price, or the\n * one slot of a quote the user approved (`approved`).\n */\nexport async function runSpec(\n id: string,\n spec: KeptSpec,\n input: Record<string, unknown>,\n deps: RequestToolDeps,\n footer: LookupFooter,\n reportDeps: ReportDeps,\n approved?: PlanSlot[],\n): Promise<RequestToolResult> {\n // THE RULES THIS OFFER WAS DECIDED UNDER ARE STILL THE ONES SAVED, or\n // nothing about it runs: no claim, no probe, no signature.\n const stale = await settingsRefusal(deps.ctx.dataDir, [spec.settingsHash]);\n if (stale !== null) {\n await footer.done('needs_input');\n return settingsFail(stale);\n }\n const checked = await prepareSpec(id, spec, input, footer, reportDeps);\n if ('refused' in checked) return checked.refused;\n // ONE PAYMENT PER OFFER, claimed before anything is signed: a retry of this\n // id, or a second call racing it, pays nothing. A repeat is not an outcome,\n // so it is not reported.\n const earlier = await claimSpecPayment(deps.ctx.dataDir, id);\n if (earlier !== null) {\n await footer.done('needs_input');\n return alreadyPaid(id, spec, earlier, await runningJob(deps.ctx.dataDir, id));\n }\n const admission: Admission =\n approved !== undefined ? { slot: approved[0]! } : { alone: { kind: 'spec', id, spec, input } };\n return (await paySpec(checked.prepared, admission, deps, footer, reportDeps)).result;\n}\n\n/** The job id to resume when a take of this offer is still running. */\nexport async function runningJob(dataDir: string, id: string): Promise<string | undefined> {\n const takes = await readTakes(dataDir, id).catch(() => []);\n return takes.some((take) => take.state === 'running') ? id : undefined;\n}\n\n/** Where a spec call's outcome report goes. */\nexport type ReportDeps = Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl' | 'harness'>;\n\n/**\n * EVERY CALL FROM A SPEC IS REPORTED, refused or run, so the server can tell\n * an offer never called from one called and stopped. A refusal before payment\n * is `unpaid` with its reason, which the server never counts as the offer\n * taken. Fire and forget: it never holds or changes the result.\n */\nexport function reportOutcome(\n reportDeps: ReportDeps,\n id: string,\n outcome: Omit<SpecOutcome, 'id' | 'ms'>,\n startedAt: number,\n): void {\n void reportSpecOutcome(\n { id, ...outcome, ms: Date.now() - startedAt },\n {\n ctx: reportDeps.ctx,\n baseUrl: reportDeps.baseUrl,\n ...(reportDeps.fetchImpl !== undefined ? { fetchImpl: reportDeps.fetchImpl } : {}),\n ...(reportDeps.harness !== undefined ? { harness: reportDeps.harness } : {}),\n },\n );\n}\n\n/** A spec's call, checked and built: what is claimed and then paid. */\nexport interface PreparedSpec {\n id: string;\n spec: KeptSpec;\n merged: Record<string, unknown>;\n /** The merged input, masked: what is shown and recorded as sent. */\n sentInput: Record<string, unknown>;\n built: SpecRequest;\n}\n\n/**\n * EVERY CHECK A SPEC'S CALL MEETS BEFORE ANYTHING IS CLAIMED: the input\n * against the spec, the request it builds, and the contract a server-built\n * call meets. Local, with nothing sent to the provider or paid; a refusal is\n * the result to hand back, already told to the footer and reported `unpaid`.\n */\nexport async function prepareSpec(\n id: string,\n spec: KeptSpec,\n input: Record<string, unknown>,\n footer: LookupFooter,\n reportDeps: ReportDeps,\n): Promise<{ prepared: PreparedSpec } | { refused: RequestToolResult }> {\n const startedAt = Date.now();\n const unpaid = (reason: UnpaidReason): void =>\n reportOutcome(reportDeps, id, { status: 'unpaid', reason }, startedAt);\n const merged = mergedInput(spec, input);\n const sentInput = maskDeep(merged) as Record<string, unknown>;\n // A WRONG GUESS COSTS ONE MORE CALL, NOT A PAYMENT: every problem, then the\n // whole spec (each input with its description and allowed values, the\n // required fields inside a nested object, the example, what comes back), so\n // the next call can be right. Local, with nothing sent to the provider or\n // paid.\n const refuse = async (problem: string): Promise<{ refused: RequestToolResult }> => {\n unpaid('input');\n await footer.done('needs_input');\n const refused = fail('needs_input', `The input does not fit ${spec.provider}: ${problem}.`, {\n nextStep: `Fix the input from the spec above and call request({id: ${JSON.stringify(id)}, input: {...}}) again; nothing was sent or paid.`,\n parameters: sentInput,\n });\n return { refused: { ...refused, summary: `${refused.summary}\\n\\n${specText(id, spec)}` } };\n };\n const problems = specInputProblems(spec, merged);\n // A SCHEMA THIS BUILD CANNOT COMPILE CHECKS NOTHING, so the call is not\n // paid: an input nobody checked is a paid guess, and no change to it helps.\n if (problems === undefined) {\n unpaid('terms');\n await footer.done('failed');\n return {\n refused: fail(\n 'failed',\n `The spec for ${spec.provider} has an input schema this build cannot check, so the call was not sent and nothing was paid.`,\n {\n nextStep: 'Continue with your own tools. Nothing was sent or paid.',\n parameters: sentInput,\n },\n ),\n };\n }\n if (problems.length) return refuse(problems.join('; '));\n const built = buildSpecRequest(spec, merged);\n if ('problem' in built) return refuse(built.problem);\n // The same checks a server-built call meets: GET or POST, only the headers\n // this build sends, and a success rule that compiles before anything is paid.\n const refusal = checkContract({\n request: built,\n ...(spec.resultSchema !== undefined ? { resultSchema: spec.resultSchema } : {}),\n });\n if (refusal !== null) {\n unpaid('terms');\n await footer.done(refusal.status);\n return { refused: fail(refusal.status, refusal.reason, { parameters: sentInput }) };\n }\n return { prepared: { id, spec, merged, sentInput, built } };\n}\n\n/** One take of several of the same call (`count`): its number, the claim it\n * holds, and whether this take reports the offer's outcome itself. */\nexport interface TakeOf {\n n: number;\n claim: string;\n report: boolean;\n}\n\n/**\n * PAY A CLAIMED SPEC'S CALL, settle its claim, and tell the server how it\n * ended. The caller holds the claim; this is where it is kept or dropped. A\n * take of several pays under its own request key and claim, so the same-turn\n * duplicate guard sees N different requests, not one request N times.\n */\nexport async function paySpec(\n prepared: PreparedSpec,\n admission: Admission,\n deps: RequestToolDeps,\n footer: LookupFooter,\n reportDeps: ReportDeps,\n take?: TakeOf,\n): Promise<Awaited<ReturnType<typeof payAndDeliver>>> {\n const { id, spec, merged, sentInput, built } = prepared;\n const startedAt = Date.now();\n const suffix = take !== undefined ? `#${take.n}` : '';\n const paid = await payAndDeliver(\n {\n capabilityId: spec.capabilityId,\n provider: spec.provider,\n ...(spec.label !== undefined ? { label: spec.label } : {}),\n media: savesMedia(spec),\n request: built,\n terms: specTerms(spec),\n requestKey: `${spec.capabilityId}:${canonicalHash(merged)}${suffix}`,\n ...(spec.resultSchema !== undefined ? { resultSchema: spec.resultSchema } : {}),\n ...(spec.outputSchema !== undefined\n ? { project: { id: `${id}${suffix}`, schema: spec.outputSchema } }\n : {}),\n parameters: sentInput,\n sent: JSON.stringify(sentInput),\n agentBuilt: true,\n priceVaries: spec.priceVaries,\n ...(spec.job !== undefined\n ? { job: { spec: spec.job, offerId: id, take: take?.n ?? 1, input: merged } }\n : {}),\n ...(spec.timeoutS !== undefined ? { timeoutMs: spec.timeoutS * 1000 } : {}),\n ...(spec.maxBytes !== undefined ? { maxBytes: spec.maxBytes } : {}),\n ...(spec.settingsHash !== undefined ? { settingsHash: spec.settingsHash } : {}),\n ...(deps.via !== undefined ? { via: deps.via } : {}),\n },\n admission,\n deps,\n footer,\n );\n const { outcome, left } = paid;\n // The claim survives anything that may have signed: only a call that\n // signed nothing frees the id for a fixed input, or a short wallet's\n // reopened quote (`runApproveTool`), which drops the record this payment\n // wrote and no other.\n const claim = take?.claim ?? id;\n const owner = await settleSpecPayment(deps.ctx.dataDir, claim, left);\n if ('slot' in admission && owner !== undefined) claimOfSlot.set(admission.slot, { claim, owner });\n // A refusal before payment (the spend policy, the spec's terms, the\n // provider's own 4xx) arrives as `unpaid` or `needs_approval`, neither of\n // which the server counts as the offer taken; a call that ran, or may have\n // moved money, keeps its own status. Null is a failure this build cannot\n // place, which says nothing rather than guess.\n if (outcome !== null && (take === undefined || take.report)) {\n reportOutcome(\n reportDeps,\n id,\n deps.via !== undefined ? { ...outcome, via: deps.via } : outcome,\n startedAt,\n );\n }\n return paid;\n}\n\n/** The spec claim an approved quote's slot paid under, and the owner token\n * of the record its payment wrote. */\nconst claimOfSlot = new WeakMap<PlanSlot, { claim: string; owner: string }>();\n\n/** The deal a spec's call is held to: its price ceiling, payee, chain and token. */\nexport function specTerms(spec: OfferSpec): AdvertisedTerms {\n return {\n source: spec.provider,\n maxAmountAtomic: spec.maxAmountAtomic,\n payTo: spec.payTo,\n network: spec.network,\n asset: spec.asset,\n };\n}\n\n/**\n * WHETHER A PAID RESULT'S FILES ARE SAVED: the spec's `output` says (`media`\n * on every Tenjin list and open-Bazaar spec, so their files are saved as\n * before), and a spec without one is media when its id is a `discovered:` one.\n */\nfunction savesMedia(spec: Pick<OfferSpec, 'capabilityId' | 'output'>): boolean {\n return spec.output !== undefined\n ? spec.output === 'media'\n : spec.capabilityId.startsWith('discovered:');\n}\n\n/** One provider call to make and pay for, from a decision or a spec. */\nexport interface ProviderCall {\n capabilityId: string;\n provider: string;\n /** The service's display name, from its decision or spec: what the footer\n * and the ledger name in place of the URL called. */\n label?: string;\n /** A media service: a paid result's links and inline files are saved\n * locally ({@link savesMedia}). */\n media: boolean;\n request: {\n url: string;\n method: string;\n headers: Record<string, string>;\n /** A catalog spec's fixed headers ({@link SpecRequest}). */\n specHeaders?: Record<string, string>;\n body?: string;\n };\n terms: AdvertisedTerms;\n requestKey: string;\n resultSchema?: Record<string, unknown>;\n /** What was bound or built, shown on every outcome. */\n parameters?: unknown;\n /** What the ledger records as sent. */\n sent: string;\n note?: string;\n /** The agent built this input itself, from a spec: a provider that refuses\n * it before payment is said to have, so the agent fixes it. */\n agentBuilt?: boolean;\n /** The spec prices by input, up to `terms.maxAmountAtomic`. */\n priceVaries?: boolean;\n /** The spec's promised fields: the result is cut to them, and the whole\n * body is saved under the offer's id. */\n project?: { id: string; schema: Record<string, unknown> };\n /** The spec's job: how this call is finished when the seller answers\n * before its result is ready, and which take of which offer it is. */\n job?: CallJob;\n /** The spec's own deadline and file cap (its `timeoutS` and `maxBytes`),\n * in place of the CLI's. */\n timeoutMs?: number;\n maxBytes?: number;\n /** The settings hash the answer that offered this call echoed; absent when\n * it echoed none. Checked against the rules saved now at this call's own\n * boundary, before anything is sent ({@link settingsRefusal}). */\n settingsHash?: string;\n /** `swap`: this call answers a native search or fetch in place. */\n via?: 'swap';\n}\n\ninterface CallJob {\n spec: Job;\n offerId: string;\n take: number;\n /** The merged input, which a poll body's `$input` names. */\n input: Record<string, unknown>;\n}\n\n/**\n * WHERE A PAYMENT'S PLACE IN ITS CALL'S PLAN COMES FROM: a slot the plan\n * already admitted (several payments, planned together, or a quote the user\n * approved), or a plan of one admitted at the live price as it is signed,\n * which over the limits is kept as the quote `alone` replays.\n */\nexport type Admission = { slot: PlanSlot } | { alone: QuotedCall };\n\n/** What a payment's plan of one is stopped with: `runPay` throws it, and the\n * caller answers with it. */\nconst PLAN_STOP = 'planStop';\n\n/**\n * A PLAN OF ONE, admitted at the price `runPay` is about to sign, before the\n * wallet is opened: the same planner several payments meet, so one call is\n * one rule. Over the limits or outside the allowlist it is\n * stopped, and the stop rides the throw back to {@link payAndDeliver}.\n */\nfunction admitAlone(\n call: ProviderCall,\n quoted: QuotedCall,\n deps: RequestToolDeps,\n): (amountAtomic: bigint) => Promise<PlanSlot> {\n return async (amountAtomic) => {\n const settings = await resolveContextSettings(deps.ctx);\n const payments = [{ amountAtomic, creator: new URL(call.request.url).host }];\n const admission = await admitPlan(payments, {\n dataDir: deps.ctx.dataDir,\n policy: settings.policy,\n ...(deps.now !== undefined ? { now: deps.now } : {}),\n });\n if ('admitted' in admission) return admission.admitted[0]!;\n const stop = await planStop(\n admission,\n { ...oneCall(call.provider, amountAtomic), payments, call: quoted },\n deps,\n );\n throw new CliError(stop.status === 'failed' ? 'REFUSED' : 'POLICY_REFUSED', stop.reason, {\n details: { [PLAN_STOP]: stop },\n });\n };\n}\n\n/**\n * PAY THE PROVIDER AND DELIVER WHAT CAME BACK: `runPay` under the caller's\n * terms, the binary or media result saved, the ledger written, and the\n * envelope the host reads, with what was sent on every outcome. `outcome` is\n * the short form the server's report takes, null for a failure\n * {@link failureOutcome} cannot place.\n */\nasync function payAndDeliver(\n call: ProviderCall,\n admission: Admission,\n deps: RequestToolDeps,\n footer: LookupFooter,\n): Promise<{\n result: RequestToolResult;\n outcome: Omit<SpecOutcome, 'id' | 'ms'> | null;\n /** What left this machine for the call, whatever came back. `signed`: a\n * payment may have been signed, even where the amount is unknown. */\n left: { amountAtomic: bigint; txHash?: string; signed: boolean };\n}> {\n // EVERY CALL'S OWN BOUNDARY: a later take, option or quoted payment meets\n // the rules saved now, as the first did, before any probe or signature.\n const stale = await settingsRefusal(deps.ctx.dataDir, [call.settingsHash]);\n if (stale !== null) {\n await footer.done('needs_input');\n return {\n result: settingsFail(stale),\n outcome: null,\n left: { amountAtomic: 0n, signed: false },\n };\n }\n const built = call.request;\n const parameters = call.parameters !== undefined ? { parameters: call.parameters } : {};\n const named = call.label !== undefined ? { label: call.label } : {};\n const signing = watchSigning(deps.payDeps?.authorizer ?? deps.authorizer);\n // The answer that delivered, or a paid leg cut off after its headers came,\n // and the payment it carried: what a job is started from.\n let leg: PaidLeg | undefined;\n const submittedAt = (deps.now ?? Date.now)();\n try {\n // WHAT IS ABOUT TO BE CALLED, named while it is being called. This is the\n // executed destination, not the hint's suggestion, which is the whole point\n // of showing it.\n await footer.calling({ provider: built.url, ...named, ...parameters });\n const paid = await runPay(\n {\n url: built.url,\n method: built.method,\n headers: built.headers,\n ...(built.specHeaders !== undefined ? { specHeaders: built.specHeaders } : {}),\n ...(built.body !== undefined ? { rawBody: built.body } : {}),\n terms: call.terms,\n execution: 'router',\n admit:\n 'slot' in admission\n ? async () => admission.slot\n : admitAlone(call, admission.alone, deps),\n requestKey: call.requestKey,\n ...(call.resultSchema !== undefined ? { resultSchema: call.resultSchema } : {}),\n ...(call.timeoutMs !== undefined ? { timeoutMs: call.timeoutMs } : {}),\n ...(call.maxBytes !== undefined ? { maxBytes: call.maxBytes } : {}),\n printBody: true,\n ...(call.job !== undefined\n ? {\n onPaidLeg: (seen: PaidLeg) => {\n leg = seen;\n },\n }\n : {}),\n },\n deps.ctx,\n {\n ...(deps.payDeps ?? {}),\n ...(deps.provider !== undefined ? { provider: deps.provider } : {}),\n authorizer: signing.authorizer,\n confirm: async () => false,\n },\n );\n const data = paid.data as {\n /** The provider's HTTP status on the call that delivered. */\n status?: number;\n /** The body, parsed, when it was JSON. */\n body?: unknown;\n bodyText?: string;\n /** A binary body's bytes and type, kept whole by the provider leg. */\n bodyBytes?: Uint8Array;\n contentType?: string;\n /** From the payment-response header, when the seller sent one. */\n settlementTxHash?: string;\n authorization?: SignedAuthorization;\n amountPaid?: { atomic: string };\n /** Set when the body missed its success rule, or the rule never ran. */\n resultUnverified?: boolean;\n resultCaveat?: string;\n };\n const providerAtomic = BigInt(data.amountPaid?.atomic ?? '0');\n const tx = data.settlementTxHash !== undefined ? { txHash: data.settlementTxHash } : {};\n const left = () => ({ amountAtomic: providerAtomic, ...tx, signed: signing.mayHaveSigned() });\n // A 2xx THAT IS NOT THE RESULT YET: the job's own rules say so, or the\n // seller never answers inline, or it is a 202. A file is a result unless it\n // came with a 202. The submit's success rule is not the result's: a job's\n // first answer is a receipt, and the rule runs on what the last poll says.\n if (call.job !== undefined) {\n const state =\n data.bodyBytes !== undefined && data.status !== 202\n ? 'done'\n : answerState(call.job.spec, data.status ?? 200, data.body, { submit: true });\n if (state !== 'done') {\n const job = await startJob(call, call.job, deps, footer, {\n state,\n submittedAt,\n status: data.status,\n json: data.body,\n text: data.bodyText ?? '',\n ...(leg?.header !== undefined ? { header: leg.header } : {}),\n providerAtomic,\n ...tx,\n ...(data.authorization !== undefined ? { authorization: data.authorization } : {}),\n });\n return { ...job, left: left() };\n }\n }\n const delivered = await deliverResult(\n call,\n deps,\n footer,\n {\n ...(data.status !== undefined ? { status: data.status } : {}),\n ...(data.bodyText !== undefined ? { bodyText: data.bodyText } : {}),\n ...(data.bodyBytes !== undefined ? { bodyBytes: data.bodyBytes } : {}),\n ...(data.contentType !== undefined ? { contentType: data.contentType } : {}),\n ...(data.resultUnverified === true ? { resultUnverified: true } : {}),\n ...(data.resultCaveat !== undefined ? { resultCaveat: data.resultCaveat } : {}),\n },\n {\n providerAtomic,\n ...tx,\n ...(data.authorization !== undefined ? { authorization: data.authorization } : {}),\n ledger: 'append',\n },\n );\n return { result: delivered.result, outcome: delivered.outcome, left: left() };\n } catch (err) {\n const cli = err instanceof CliError ? err : undefined;\n // THE PLAN WAS STOPPED before anything was signed: over the limits, its\n // quote and the approve call; otherwise why, with nothing paid.\n const stop = (cli?.details as Record<string, unknown> | undefined)?.[PLAN_STOP] as\n PlanStop | undefined;\n if (stop !== undefined) {\n await footer.done(stop.status, { provider: built.url, ...named, ...parameters });\n return {\n left: { amountAtomic: 0n, signed: signing.mayHaveSigned() },\n outcome: stop.outcome,\n result: fail(stop.status, stop.reason, {\n ...stop.extras,\n request: { method: built.method, url: built.url },\n ...(call.parameters !== undefined ? { parameters: call.parameters } : {}),\n }),\n };\n }\n const status = cli?.code === 'POLICY_REFUSED' ? 'needs_approval' : 'failed';\n // A provider failure AFTER transmission carries the amount at risk on its\n // details. Reporting zero there told the model the call was free when the\n // ledger had already counted it.\n const detail = (cli?.details ?? {}) as {\n amountAtomic?: string;\n settlement?: string;\n diagnosis?: Record<string, unknown>;\n status?: number;\n providerError?: string;\n /** The seller's reason for not settling, from its payment-response header. */\n settlementError?: string;\n /** Where a long job's result will be, named by the seller before the paid\n * leg timed out. */\n statusUrl?: string;\n authorization?: SignedAuthorization;\n /** The live 402's terms, on a REGISTRY_MISMATCH. */\n live?: { amount?: string };\n };\n // A SPEND-POLICY REFUSAL SIGNED NOTHING. Its details carry the price it\n // refused, not an amount that left, so it is neither a cost nor a ledger\n // row: the PDL refusal sat in the ledger as $0.28 paid.\n const leftAtomic = status === 'needs_approval' ? 0n : BigInt(detail.amountAtomic ?? '0');\n // THE PAID LEG CUT OFF WHILE THE SELLER WORKS, from a service whose spec\n // says how its job is polled, with the status URL in the headers that did\n // come: that job, still running, not a failure. With no usable status URL\n // it stays the timeout it was.\n const cutJob = call.job;\n const cutHeader = leg?.header;\n if (\n cutJob !== undefined &&\n cutHeader !== undefined &&\n cli?.code === 'NETWORK_ERROR' &&\n leftAtomic > 0n &&\n !(\n 'problem' in\n pollTarget(\n cutJob.spec,\n { url: built.url, json: undefined, header: cutHeader },\n cutJob.input,\n )\n )\n ) {\n const job = await startJob(call, cutJob, deps, footer, {\n state: 'running',\n submittedAt,\n json: undefined,\n text: '',\n header: cutHeader,\n providerAtomic: leftAtomic,\n ...(detail.authorization !== undefined ? { authorization: detail.authorization } : {}),\n });\n return { ...job, left: { amountAtomic: leftAtomic, signed: true } };\n }\n // AN INPUT THE AGENT BUILT, REFUSED BEFORE ANY PAYMENT: said as that, so\n // the next step is fixing the input, not checking the URL.\n const rejectedInput =\n call.agentBuilt === true &&\n leftAtomic === 0n &&\n (detail.status === 400 || detail.status === 422);\n // A PRICE THAT VARIES WITH THE INPUT, quoted over the spec's ceiling for\n // this one: a smaller input is the fix, and a fresh decision would only\n // hand back the same spec.\n const live = detail.live?.amount;\n const ceiling = call.terms.maxAmountAtomic;\n const overCeiling =\n call.priceVaries === true &&\n cli?.code === 'REGISTRY_MISMATCH' &&\n live !== undefined &&\n ceiling !== undefined &&\n /^\\d+$/.test(live) &&\n BigInt(live) > BigInt(ceiling);\n const reason = overCeiling\n ? `${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.`\n : rejectedInput\n ? `${call.provider} rejected this input before any payment (HTTP ${String(detail.status)}): see providerError. Fix the input and call again with the same id.`\n : cli !== undefined && isLowFundsRefusal(cli)\n ? `${shortOfFunds({ label: call.label, provider: call.provider, priceAtomic: leftAtomic })} ${LOW_FUNDS_TAIL}`\n : cli !== undefined\n ? `${cli.message} ${agentFixOf(cli)}`.trim()\n : String(err);\n await footer.done(status, {\n provider: built.url,\n ...named,\n ...parameters,\n price: `$${toMoney(leftAtomic.toString()).usd}`,\n });\n // An authorization that left is a paid call whatever came back: recorded\n // with its settlement unknown, for `tenjin payments reconcile` to resolve.\n if (leftAtomic > 0n) {\n await appendPaidRecord(\n deps.ctx.dataDir,\n paidRecord(call, built.url, call.sent, leftAtomic, {\n ...(detail.authorization !== undefined ? { authorization: detail.authorization } : {}),\n savedFiles: [],\n ...(deps.now !== undefined ? { now: deps.now } : {}),\n }),\n );\n }\n const signed = signing.mayHaveSigned();\n const outcome = failureOutcome(err, { mayHaveMoved: leftAtomic > 0n || signed, rejectedInput });\n return {\n left: { amountAtomic: leftAtomic, signed },\n outcome:\n outcome === null\n ? null\n : {\n ...outcome,\n ...(typeof detail.status === 'number' ? { httpStatus: detail.status } : {}),\n },\n result: fail(status, reason, {\n providerAtomic: leftAtomic,\n ...(detail.settlement !== undefined ? { settlement: detail.settlement } : {}),\n ...(detail.diagnosis !== undefined ? { diagnosis: detail.diagnosis } : {}),\n // WHY THE PROVIDER SAID NO: its HTTP status and a bounded, redacted\n // snippet of its body, which `runPay` cut. Without them a 403 read the\n // same as a timeout to the agent and to the logs.\n ...(typeof detail.status === 'number' ? { providerStatus: detail.status } : {}),\n ...(typeof detail.providerError === 'string'\n ? { providerError: detail.providerError }\n : {}),\n // THE SELLER SAID IT DID NOT SETTLE, and why: what an empty `{}` body\n // beside a rejected payment leaves out.\n ...(typeof detail.settlementError === 'string'\n ? { settlementError: detail.settlementError }\n : {}),\n // WHAT WAS SENT, on a failure too: the agent cannot match a 400 to a\n // field it cannot see.\n request: { method: built.method, url: built.url },\n ...(call.parameters !== undefined ? { parameters: call.parameters } : {}),\n // A LONG JOB STILL RUNNING: where its result will be, and that this\n // call was paid, so a second one would pay again.\n ...(typeof detail.statusUrl === 'string' ? { statusUrl: detail.statusUrl } : {}),\n ...(overCeiling\n ? { nextStep: 'Change the input and call again with the same id.' }\n : rejectedInput\n ? { nextStep: 'Fix the input and call again with the same id.' }\n : typeof detail.statusUrl === 'string'\n ? {\n nextStep:\n 'Check statusUrl for the result. Do not call request again for this: it would pay again.',\n }\n : {}),\n }),\n };\n }\n}\n\n/** What came back on the answer that delivered a result. */\nexport interface Delivered {\n status?: number;\n bodyText?: string;\n bodyBytes?: Uint8Array;\n contentType?: string;\n /** Media an account's tool answered with inline, each saved as a file. */\n files?: { bytes: Uint8Array; contentType: string }[];\n /** The body missed its success rule, or the rule never ran. */\n resultUnverified?: boolean;\n resultCaveat?: string;\n}\n\n/** The money behind a delivered result, and where its ledger row goes. */\nexport interface DeliveredMoney {\n providerAtomic: bigint;\n txHash?: string;\n authorization?: SignedAuthorization;\n /** Append the call's row; finish the row a job wrote when it was paid,\n * found by its nonce; keep a job on the user's account to one row, found\n * by its offer id; or leave the ledger alone. */\n ledger: 'append' | { update: string } | { job: string } | 'none';\n /** A call on the user's own account (plan 37): their plan paid, nothing\n * left the balance. Its files are saved and its row kept all the same,\n * and the receipt names the account. `returns` is what the spec says\n * comes back; `source` is the account's id, kept on its row. */\n account?: { label: string; source: string; returns?: string };\n}\n\n/** What delivering needs of a call: a provider call, or a job's record of one. */\nexport type DeliverCall = Pick<\n ProviderCall,\n | 'capabilityId'\n | 'provider'\n | 'label'\n | 'media'\n | 'parameters'\n | 'sent'\n | 'note'\n | 'project'\n | 'maxBytes'\n | 'via'\n> & { request: { url: string } };\n\n/**\n * DELIVER A PAID OR FREE RESULT: the binary or media saved, the ledger\n * written, and the envelope the host reads. The same for a call that answered\n * inline and a job's last poll.\n */\nexport async function deliverResult(\n call: DeliverCall,\n deps: RequestToolDeps,\n footer: LookupFooter,\n got: Delivered,\n money: DeliveredMoney,\n): Promise<{\n result: RequestToolResult;\n outcome: Omit<SpecOutcome, 'id' | 'ms'>;\n savedFiles: string[];\n /** Why a file the result carries was not saved: a job's take stays\n * resumable over it, since the seller still holds the result. */\n unsaved?: string;\n}> {\n const built = call.request;\n const parameters = call.parameters !== undefined ? { parameters: call.parameters } : {};\n const { providerAtomic } = money;\n const httpStatus = typeof got.status === 'number' ? { httpStatus: got.status } : {};\n const budget = deps.downloads;\n const now = deps.now !== undefined ? { now: deps.now } : {};\n // A FILE IS SAVED, NOT INLINED: its bytes are no use as text in a tool\n // result, so the result names where they are.\n const binary =\n got.bodyBytes !== undefined\n ? await saveBinary(deps.ctx.dataDir, call.capabilityId, got.bodyBytes, {\n contentType: got.contentType ?? '',\n ...now,\n ...(budget !== undefined ? { budget } : {}),\n })\n : null;\n let unsaved = binary?.saveError;\n // MEDIA AN ACCOUNT'S TOOL ANSWERED WITH INLINE, each its own file.\n const files: string[] = [];\n for (const file of got.files ?? []) {\n const saved = await saveBinary(deps.ctx.dataDir, call.capabilityId, file.bytes, {\n contentType: file.contentType,\n ...now,\n ...(budget !== undefined ? { budget } : {}),\n });\n unsaved ??= saved.saveError;\n if (saved.savedTo !== undefined) files.push(saved.savedTo);\n }\n const account = money.account;\n // AND A PAID MEDIA RESULT THAT LINKS TO ITS FILES brings them home: the\n // links can expire, and the user paid for what is behind them. Only a\n // media service (every discovered one, where generated images, audio and\n // video come from) does this: a curated page read or search links whatever\n // the page links, on hosts the page picked. Best effort only. A call on the\n // user's own account paid too, from their plan.\n const media = (providerAtomic > 0n || account !== undefined) && binary === null && call.media;\n // ONE CARRYING ITS FILES INLINE, as base64 in its JSON, has them saved\n // the same way, each replaced by a note naming its file: megabytes of\n // base64 are no use to the agent as text. The rewritten body is the one\n // cut, saved and handed back below; on any failure it is the body as it\n // came.\n const inline =\n media && got.bodyText !== undefined\n ? await saveInlineMedia(got.bodyText, async (bytes, contentType) => {\n const saved = await saveBinary(deps.ctx.dataDir, call.capabilityId, bytes, {\n contentType,\n ...now,\n ...(budget !== undefined ? { budget } : {}),\n });\n unsaved ??= saved.saveError;\n return saved.savedTo ?? null;\n })\n : null;\n const bodyText = inline?.bodyText ?? got.bodyText;\n const linked = media\n ? await saveLinked(\n deps,\n call.capabilityId,\n mediaUrlsIn(bodyText ?? '', MAX_MEDIA_FILES - (inline?.savedFiles.length ?? 0)),\n call.maxBytes,\n )\n : { saved: [], capped: false, failed: false };\n if (linked.capped) unsaved ??= CAP_REACHED;\n if (linked.failed) unsaved ??= DOWNLOAD_FAILED;\n const savedFiles = [\n ...(binary?.savedTo !== undefined ? [binary.savedTo] : []),\n ...files,\n ...(inline?.savedFiles ?? []),\n ...linked.saved,\n ];\n const cut =\n binary === null && call.project !== undefined && bodyText !== undefined\n ? await projected(deps.ctx.dataDir, call.project, bodyText)\n : null;\n if ((providerAtomic > 0n || account !== undefined) && money.ledger === 'append') {\n await appendPaidRecord(\n deps.ctx.dataDir,\n paidRecord(call, built.url, call.sent, providerAtomic, {\n ...(money.txHash !== undefined ? { txHash: money.txHash } : {}),\n ...(money.authorization !== undefined ? { authorization: money.authorization } : {}),\n savedFiles,\n ...(account !== undefined ? { account: account.source } : {}),\n ...now,\n }),\n );\n } else if (typeof money.ledger === 'object' && 'job' in money.ledger) {\n await recordAccountRow(deps.ctx.dataDir, {\n ...paidRecord(call, built.url, call.sent, providerAtomic, {\n savedFiles,\n ...(account !== undefined ? { account: account.source } : {}),\n ...now,\n }),\n job: money.ledger.job,\n });\n } else if (typeof money.ledger === 'object') {\n await updatePaidRecord(deps.ctx.dataDir, money.ledger.update, {\n savedFiles,\n ...(money.txHash !== undefined ? { txHash: money.txHash } : {}),\n });\n }\n const base = {\n supplier: supplierOf(built.url),\n // The service's display name, which the plugin's mod draws its row from.\n ...(call.label !== undefined ? { label: call.label } : {}),\n ...parameters,\n cost: account !== undefined ? accountCost(account.label) : costLines(providerAtomic),\n ...(money.txHash !== undefined ? { settlementTxHash: money.txHash } : {}),\n ...(call.note !== undefined ? { note: call.note } : {}),\n result: binary ?? cut?.result ?? bodyText ?? '',\n ...(cut !== null ? { fullResultPath: cut.fullResultPath } : {}),\n ...(savedFiles.length > 0 ? { savedFiles } : {}),\n providerContentUntrusted: true,\n };\n // UNVERIFIED IS NOT FULFILLED. A body that missed its success rule, or\n // that the rule could not be run against, may be exactly the contract\n // failure the rule exists to catch, and a caveat inside a `fulfilled`\n // envelope does not reach code that branches on the status: a provider\n // could pad a broken answer past the validation limit and have it read as\n // a checked, paid result. The body still rides along (whole, or cut to\n // the spec's fields with the whole saved), because the money moved and\n // withholding the product would be a second loss on top of the first.\n const shown = {\n provider: built.url,\n ...(call.label !== undefined ? { label: call.label } : {}),\n ...parameters,\n price: account !== undefined ? 'your account' : `$${toMoney(providerAtomic.toString()).usd}`,\n };\n // THE RECEIPT: \"Apify · your account · 20 places\".\n const receipt =\n account !== undefined\n ? accountReceipt(account, binary === null ? (cut?.result ?? bodyText) : undefined, savedFiles)\n : `${base.supplier} · ${base.cost.join(' · ')}`;\n if (got.resultUnverified === true) {\n await footer.done('unverified', shown);\n return {\n outcome: { status: 'unverified', ...httpStatus },\n savedFiles,\n ...(unsaved !== undefined ? { unsaved } : {}),\n result: {\n isError: true,\n summary: `Unverified result from ${receipt}`,\n envelope: {\n status: 'unverified',\n ...base,\n ...(got.resultCaveat !== undefined ? { resultCaveat: got.resultCaveat } : {}),\n },\n },\n };\n }\n await footer.done('fulfilled', shown);\n return {\n outcome: { status: 'fulfilled', ...httpStatus },\n savedFiles,\n ...(unsaved !== undefined ? { unsaved } : {}),\n result: {\n isError: false,\n summary: account !== undefined ? receipt : `Fulfilled by ${receipt}`,\n envelope: { status: 'fulfilled', ...base, ...(account !== undefined ? { receipt } : {}) },\n },\n };\n}\n\n/** The files a paid result links to, saved within what this call may still\n * write, each under the spec's file cap when it names one. Best effort, like\n * every save after the money moved. */\nasync function saveLinked(\n deps: RequestToolDeps,\n stem: string,\n urls: string[],\n maxBytes: number | undefined,\n): Promise<{ saved: string[]; capped: boolean; failed: boolean }> {\n return saveMedia(deps.ctx.dataDir, stem, urls, {\n ...(maxBytes !== undefined ? { maxBytes } : {}),\n ...(deps.mediaTransport !== undefined ? { transport: deps.mediaTransport } : {}),\n ...(deps.payDeps?.destination !== undefined ? { destination: deps.payDeps.destination } : {}),\n ...(deps.now !== undefined ? { now: deps.now } : {}),\n ...(deps.downloads !== undefined ? { budget: deps.downloads } : {}),\n });\n}\n\n/** What starting a job is handed: the submit's answer and its payment. */\ninterface SubmitSeen {\n state: 'running' | 'failed';\n submittedAt: number;\n status?: number;\n json: unknown;\n text: string;\n header?: (name: string) => string | undefined;\n providerAtomic: bigint;\n /** The submit's settlement, when its payment-response header named it. */\n txHash?: string;\n authorization?: SignedAuthorization;\n}\n\n/** What a job's take answers, for the caller to hand back and report. */\ninterface TakeEnding {\n result: RequestToolResult;\n outcome: Omit<SpecOutcome, 'id' | 'ms'>;\n}\n\n/**\n * A PAID CALL THE SELLER ANSWERED BEFORE ITS RESULT WAS READY. The submit is\n * on the ledger first, so a crash mid-poll loses no row. A seller that says\n * the job failed is that failure. A status URL that is not the submit's host\n * is never fetched: the money moved, so the call fails naming the URL as\n * untrusted. Otherwise the take is recorded,\n * 0600, before its first poll, and polled until it ends or this call's wait\n * runs out, when it answers `running` with the id that resumes it.\n */\nasync function startJob(\n call: ProviderCall,\n job: CallJob,\n deps: RequestToolDeps,\n footer: LookupFooter,\n submit: SubmitSeen,\n): Promise<TakeEnding> {\n const now = deps.now ?? Date.now;\n const built = call.request;\n const parameters = call.parameters !== undefined ? { parameters: call.parameters } : {};\n const httpStatus = submit.status !== undefined ? { httpStatus: submit.status } : {};\n const { providerAtomic } = submit;\n if (providerAtomic > 0n) {\n await appendPaidRecord(\n deps.ctx.dataDir,\n paidRecord(call, built.url, call.sent, providerAtomic, {\n ...(submit.txHash !== undefined ? { txHash: submit.txHash } : {}),\n ...(submit.authorization !== undefined ? { authorization: submit.authorization } : {}),\n savedFiles: [],\n now,\n }),\n );\n }\n const shown = {\n provider: built.url,\n ...parameters,\n price: `$${toMoney(providerAtomic.toString()).usd}`,\n };\n const paidFailure = async (reason: string, extras: FailExtras = {}): Promise<TakeEnding> => {\n await footer.done('failed', shown);\n return {\n outcome: { status: 'failed', ...httpStatus },\n result: fail('failed', `${reason} ${paidNothing(providerAtomic, submit.txHash)}`, {\n providerAtomic,\n settlement: submit.txHash !== undefined ? 'settled' : 'unknown',\n ...(submit.status !== undefined ? { providerStatus: submit.status } : {}),\n request: { method: built.method, url: built.url },\n ...parameters,\n nextStep: failedNextStep(submit.txHash),\n ...extras,\n }),\n };\n };\n if (submit.state === 'failed') {\n const said = sellerSaid(submit.json, submit.text);\n return paidFailure(\n `${call.provider}: the seller says the job failed.`,\n said.length > 0 ? { providerError: said } : {},\n );\n }\n const target = pollTarget(\n job.spec,\n {\n url: built.url,\n json: submit.json,\n ...(submit.header !== undefined ? { header: submit.header } : {}),\n },\n job.input,\n );\n if ('problem' in target) {\n return paidFailure(\n `${call.provider} took the payment and is still working, but ${target.problem}, so it was not polled.`,\n target.named !== undefined ? { statusUrl: target.named } : {},\n );\n }\n const take: JobTake = {\n version: 1,\n offerId: job.offerId,\n take: job.take,\n poll: target,\n job: job.spec,\n call: {\n capabilityId: call.capabilityId,\n provider: call.provider,\n url: built.url,\n media: call.media,\n sent: recordedSent(call.sent),\n terms: {\n ...(call.terms.source !== undefined ? { source: call.terms.source } : {}),\n maxAmountAtomic: call.terms.maxAmountAtomic ?? '0',\n ...(call.terms.payTo !== undefined ? { payTo: call.terms.payTo } : {}),\n ...(call.terms.network !== undefined ? { network: call.terms.network } : {}),\n ...(call.terms.asset !== undefined ? { asset: call.terms.asset } : {}),\n },\n ...(call.resultSchema !== undefined ? { resultSchema: call.resultSchema } : {}),\n ...(call.project !== undefined ? { outputSchema: call.project.schema } : {}),\n },\n submittedAt: new Date(submit.submittedAt).toISOString(),\n expiresAt: new Date(submit.submittedAt + job.spec.keepH * 3_600_000).toISOString(),\n amountAtomic: providerAtomic.toString(),\n ...(submit.authorization !== undefined ? { authorization: submit.authorization } : {}),\n ...(submit.txHash !== undefined ? { txHash: submit.txHash } : {}),\n ...httpStatus,\n state: 'running',\n savedFiles: [],\n // A status URL the agent may open itself: a plain GET.\n ...(target.method === 'GET' ? { statusUrl: target.url } : {}),\n };\n const kept = await writeTake(deps.ctx.dataDir, take).then(\n () => true,\n () => false,\n );\n const deadline = Math.min(\n deps.waitsForJobs === true\n ? Number.POSITIVE_INFINITY\n : (deps.startedAt ?? submit.submittedAt) + MAX_CALL_WAIT_MS,\n submit.submittedAt + job.spec.maxWaitS * 1000,\n );\n const answer = await pollUntil(\n take,\n { deadline, firstWaitMs: job.spec.everyS * 1000 },\n pollDeps(deps),\n );\n return finishTake(take, answer, deps, footer, { kept, parameters: call.parameters });\n}\n\n/**\n * THAT A FAILED JOB WAS PAID AND BROUGHT NOTHING BACK, and what is known of\n * the money: settled when the submit's payment-response named the\n * transaction (AiSpace settles at submit, so a refused prompt is still a paid\n * one), else unknown until the authorization expires.\n */\nfunction paidNothing(amountAtomic: bigint, txHash: string | undefined): string {\n const usd = `$${toMoney(amountAtomic.toString()).usd}`;\n return txHash !== undefined\n ? `It was paid (${usd}, settled in tx ${txHash}) and nothing came back.`\n : `It was paid (${usd}) and nothing came back; whether that payment settles is unknown until its authorization expires.`;\n}\n\n/** What the agent does after a job failed: the money is already accounted. */\nfunction failedNextStep(txHash: string | undefined): string {\n return txHash !== undefined\n ? 'Tell the user it was paid and nothing came back; the payment is in `tenjin payments`. A new call pays again.'\n : '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.';\n}\n\n/** The poll's seams, and who is told of each poll. */\nfunction pollDeps(deps: RequestToolDeps): PollDeps {\n return {\n ...(deps.pollTransport !== undefined ? { transport: deps.pollTransport } : {}),\n ...(deps.payDeps?.destination !== undefined ? { destination: deps.payDeps.destination } : {}),\n ...(deps.now !== undefined ? { now: deps.now } : {}),\n ...(deps.sleep !== undefined ? { sleep: deps.sleep } : {}),\n ...(deps.onPoll !== undefined ? { onPoll: deps.onPoll } : {}),\n };\n}\n\n/** A take's call, rebuilt from its record for the delivery step. */\nfunction callOf(take: JobTake, parameters?: unknown): DeliverCall {\n return {\n capabilityId: take.call.capabilityId,\n provider: take.call.provider,\n media: take.call.media,\n sent: take.call.sent,\n request: { url: take.call.url },\n ...(parameters !== undefined ? { parameters } : {}),\n ...(take.call.outputSchema !== undefined\n ? {\n project: {\n id: take.take > 1 ? `${take.offerId}#${take.take}` : take.offerId,\n schema: take.call.outputSchema,\n },\n }\n : {}),\n };\n}\n\n/**\n * HOW A TAKE ENDED THIS CALL, recorded and said. Done: the last answer is the\n * result, checked against the success rule and saved like any paid result,\n * its files written onto the payment's ledger row. Running: the id that\n * resumes it. Failed or gone: the seller's reason, the money already counted.\n * The record keeps every ending until it expires. The first ending recorded\n * stands: a call whose take another call ended first answers with that ending.\n */\nasync function finishTake(\n take: JobTake,\n answer: PollAnswer,\n deps: RequestToolDeps,\n footer: LookupFooter,\n opts: { kept: boolean; parameters?: unknown },\n): Promise<TakeEnding> {\n const { dataDir } = deps.ctx;\n const providerAtomic = BigInt(take.amountAtomic);\n const call = callOf(take, opts.parameters);\n const shown = {\n provider: take.call.url,\n price: `$${toMoney(providerAtomic.toString()).usd}`,\n };\n // Undefined when the ending could not be written: the take stays running.\n const end = (ending: Partial<JobTake>) =>\n endTake(dataDir, take.offerId, take.take, ending).catch(() => undefined);\n // AN ENDING ANOTHER CALL RECORDED FIRST stands, and is this call's answer.\n const lostTo = async (ended: JobTake): Promise<TakeEnding> => {\n const result = endedResult(ended, { raced: true });\n const status = result.envelope.status as 'fulfilled' | 'unverified' | 'failed';\n await footer.done(status, shown);\n return { result, outcome: { status } };\n };\n if (answer.state === 'done') {\n const current = (await readTake(dataDir, take.offerId, take.take)) ?? take;\n if (current.state !== 'running') return lostTo(current);\n // The row the submit's payment is on.\n const nonce = current.authorization?.nonce;\n let caveat: string | undefined;\n let unverified = false;\n if (take.call.resultSchema !== undefined && answer.bytes === undefined) {\n const check = validateResultBody(take.call.resultSchema, answer.text);\n if (!check.valid || check.unvalidated === true) {\n unverified = true;\n caveat = check.reason ?? 'The result does not satisfy its success schema.';\n }\n }\n const tx = settlementTx({ header: answer.header });\n const delivered = await deliverResult(\n call,\n deps,\n footer,\n {\n status: answer.status,\n ...(answer.bytes !== undefined\n ? { bodyBytes: answer.bytes, contentType: answer.contentType }\n : { bodyText: answer.text }),\n ...(unverified ? { resultUnverified: true } : {}),\n ...(caveat !== undefined ? { resultCaveat: caveat } : {}),\n },\n {\n providerAtomic,\n ...(tx !== undefined ? { txHash: tx } : {}),\n ledger: nonce !== undefined ? { update: nonce } : 'none',\n },\n );\n // A RESULT NOT SAVED HERE IS NOT AN ENDING: the seller still holds it, so\n // the take stays running, its copy is never freed, and a resume fetches\n // it again with nothing more paid.\n if (delivered.unsaved !== undefined) {\n await footer.done('running', shown);\n return {\n outcome: { status: 'running', httpStatus: answer.status },\n result: unsavedResult(take, call, opts.kept, delivered.unsaved),\n };\n }\n const ended = await end({\n state: 'done',\n savedFiles: delivered.savedFiles.slice(0, 16),\n result: keptResult(delivered.result.envelope.result),\n ...(unverified ? { resultUnverified: true } : {}),\n ...(caveat !== undefined ? { resultCaveat: caveat.slice(0, 1_000) } : {}),\n });\n if (ended?.won === false) return lostTo(ended.take);\n // THE SELLER'S COPY IS FREED once ours is on disk, by the call that ended\n // the take: never while the record still says running.\n if (delivered.savedFiles.length > 0 && ended !== undefined) {\n await completeJob({ ...current, submitUrl: take.call.url }, pollDeps(deps));\n }\n return {\n result: withJob(delivered.result, take.offerId),\n outcome: delivered.outcome,\n };\n }\n if (answer.state === 'running') {\n await footer.done('running', shown);\n return {\n outcome: {\n status: 'running',\n ...(take.httpStatus !== undefined ? { httpStatus: take.httpStatus } : {}),\n },\n result: runningResult(take, call, opts.kept, answer.reason),\n };\n }\n const reason = `${\n answer.state === 'expired'\n ? `${take.call.provider} no longer has this job (HTTP ${answer.status}).`\n : `${take.call.provider}: ${answer.reason}.`\n } ${paidNothing(providerAtomic, take.txHash)}`;\n const said = answer.state === 'failed' ? answer.said : undefined;\n const ended = await end({\n state: answer.state,\n reason: reason.slice(0, 1_000),\n ...(said !== undefined ? { said } : {}),\n });\n if (ended?.won === false) return lostTo(ended.take);\n await footer.done('failed', shown);\n return {\n outcome: {\n status: 'failed',\n ...(answer.status !== undefined ? { httpStatus: answer.status } : {}),\n },\n result: withJob(failedResult(take, reason, answer.status, said, opts.parameters), take.offerId),\n };\n}\n\n/** A take that failed, paid: the reason, the seller's own words beside it as\n * untrusted text, and what is known of the money. */\nfunction failedResult(\n take: JobTake,\n reason: string,\n status: number | undefined,\n said: string | undefined,\n parameters?: unknown,\n): RequestToolResult {\n return fail('failed', reason, {\n providerAtomic: BigInt(take.amountAtomic),\n settlement: take.txHash !== undefined ? 'settled' : 'unknown',\n ...(status !== undefined ? { providerStatus: status } : {}),\n ...(said !== undefined ? { providerError: said } : {}),\n request: { method: take.poll.method, url: take.poll.url },\n ...(parameters !== undefined ? { parameters } : {}),\n nextStep: failedNextStep(take.txHash),\n });\n}\n\n/** A take's result names its job, so a set's entries can be told apart. */\nfunction withJob(result: RequestToolResult, offerId: string): RequestToolResult {\n return { ...result, envelope: { ...result.envelope, job: offerId } };\n}\n\n/** What a finished take keeps of the result it handed the agent. */\nfunction keptResult(result: unknown): string {\n const text = typeof result === 'string' ? result : JSON.stringify(result ?? '');\n return text.length <= KEPT_RESULT_CHARS ? text : `${text.slice(0, KEPT_RESULT_CHARS)}…`;\n}\n\n/** The answer for a take still running when this call's wait ran out. */\nfunction runningResult(\n take: JobTake,\n call: DeliverCall,\n kept: boolean,\n note?: string,\n): RequestToolResult {\n const cost = costLines(BigInt(take.amountAtomic));\n const supplier = supplierOf(take.call.url);\n const nextStep = kept\n ? `Call request({job: ${JSON.stringify(take.offerId)}}) in a minute or two; nothing more is paid.`\n : `This machine could not keep the job, so it cannot be resumed here${take.statusUrl !== undefined ? '; check statusUrl for the result' : ''}. Do not call again for this: it would pay again.`;\n return {\n isError: false,\n summary: `Still running at ${supplier} · ${cost.join(' · ')}. ${nextStep}`,\n envelope: {\n status: 'running',\n job: take.offerId,\n ...(take.statusUrl !== undefined ? { statusUrl: take.statusUrl } : {}),\n supplier,\n ...(call.parameters !== undefined ? { parameters: call.parameters } : {}),\n cost,\n ...(note !== undefined ? { note } : {}),\n nextStep,\n providerContentUntrusted: true,\n },\n };\n}\n\n/** A take the seller finished whose result this machine could not save: still\n * running, so a resume fetches it again, with nothing more paid. */\nfunction unsavedResult(\n take: JobTake,\n call: DeliverCall,\n kept: boolean,\n why: string,\n): RequestToolResult {\n const running = runningResult(\n take,\n call,\n kept,\n `The seller finished it and the payment went through, but it could not be saved here (${why}).`,\n );\n const words = unsavedWords(\n `Paid; ${supplierOf(take.call.url)} finished it`,\n why,\n kept ? { job: take.offerId } : { otherwise: String(running.envelope.nextStep) },\n );\n return {\n ...running,\n summary: words.summary,\n envelope: { ...running.envelope, nextStep: words.nextStep },\n };\n}\n\n/**\n * WHAT A FINISHED RESULT THIS MACHINE COULD NOT SAVE SAYS (`deliverResult`'s\n * `unsaved`), one wording for a paid take and a call on the user's own\n * account: who finished it, why it was not saved here, and the way to it.\n * With a kept `job`, a resume fetches it again and nothing more is paid;\n * without one, `otherwise` is the next step.\n */\nexport function unsavedWords(\n finished: string,\n why: string,\n next: { job: string } | { otherwise: string },\n): { said: string; nextStep: string; summary: string } {\n const said = `${finished}, but it could not be saved here (${why}).`;\n const nextStep =\n 'job' in next\n ? `Tell the user why it was not saved, then call request({job: ${JSON.stringify(next.job)}}) to fetch it again; nothing more is paid.`\n : next.otherwise;\n return { said, nextStep, summary: `${said} ${nextStep}` };\n}\n\n/** A take that had already ended when its job was resumed, from its record;\n * `raced`, one another call ended while this one was polling it. */\nfunction endedResult(take: JobTake, opts: { raced?: boolean } = {}): RequestToolResult {\n const cost = costLines(BigInt(take.amountAtomic));\n const supplier = supplierOf(take.call.url);\n const how =\n opts.raced === true\n ? 'another call finished this job first; nothing more was paid'\n : 'already finished; nothing was polled or paid';\n if (take.state === 'done') {\n // Unverified as it was delivered: see `deliverResult`.\n const unverified = take.resultUnverified === true;\n return {\n isError: unverified,\n summary: `${unverified ? 'Unverified result from' : 'Fulfilled by'} ${supplier} · ${cost.join(' · ')} (${how})`,\n envelope: {\n status: unverified ? 'unverified' : 'fulfilled',\n job: take.offerId,\n supplier,\n cost,\n result: take.result ?? '',\n ...(take.savedFiles.length > 0 ? { savedFiles: take.savedFiles } : {}),\n note:\n opts.raced === true\n ? 'Another call finished this job first; this is its result, and nothing more was paid.'\n : 'This job had already finished; nothing was polled or paid.',\n providerContentUntrusted: true,\n ...(unverified && take.resultCaveat !== undefined\n ? { resultCaveat: take.resultCaveat }\n : {}),\n },\n };\n }\n return withJob(\n failedResult(\n take,\n take.reason ??\n `${take.call.provider}: the job ended without a result. ${paidNothing(BigInt(take.amountAtomic), take.txHash)}`,\n undefined,\n take.said,\n ),\n take.offerId,\n );\n}\n\n/**\n * `request({job})`: EVERY UNFINISHED TAKE OF A JOB, polled again from its\n * record, side by side, for up to {@link MAX_CALL_WAIT_MS} (or, where the host\n * waits for jobs, until the job's own `maxWaitS` from its submit, if that is\n * later) and never past the take's own keep time. Nothing is built and\n * nothing is paid. A take that already ended answers from its record. One\n * take answers as itself; several as a set.\n */\nasync function resumeJob(offerId: string, deps: RequestToolDeps): Promise<RequestToolResult> {\n const { dataDir } = deps.ctx;\n // A JOB ON THE USER'S OWN ACCOUNT (plan 37): its follow-up only.\n const accountJob = await readAccountJob(dataDir, offerId);\n if (accountJob !== null) {\n const settings = await resolveContextSettings(deps.ctx);\n return (await import('./accounts/run')).resumeAccountJob(accountJob, deps, {\n ctx: deps.ctx,\n baseUrl: settings.baseUrl,\n acceptsBazaar: settings.experimentalBazaar,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n ...(deps.harness !== undefined ? { harness: deps.harness } : {}),\n });\n }\n const takes = await readTakes(dataDir, offerId);\n if (takes.length === 0) {\n return fail(\n 'needs_input',\n '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.',\n {\n nextStep:\n 'Check `tenjin payments` for what was paid. For a new result, call request({query}); that pays again.',\n },\n );\n }\n const footer = await openLookupFooter(dataDir, { id: offerId });\n await footer.routing();\n const settings = await resolveContextSettings(deps.ctx);\n const startedAt = deps.startedAt ?? (deps.now ?? Date.now)();\n const started = Date.now();\n const ended = await Promise.all(\n takes.map(async (take) => {\n if (take.state !== 'running') {\n return { take, result: endedResult(take), outcome: null };\n }\n const waited = startedAt + MAX_CALL_WAIT_MS;\n const deadline = Math.min(\n deps.waitsForJobs === true\n ? Math.max(waited, Date.parse(take.submittedAt) + take.job.maxWaitS * 1000)\n : waited,\n Date.parse(take.expiresAt),\n );\n const answer = await pollUntil(take, { deadline, firstWaitMs: 0 }, pollDeps(deps));\n const done = await finishTake(take, answer, deps, SILENT_FOOTER, { kept: true });\n return { take, result: done.result, outcome: done.outcome };\n }),\n );\n // The offer's own report, once, for a take that ended in this call: the\n // server keeps the first report it got, and logs this one.\n const changed = ended.find(({ outcome }) => outcome !== null && outcome.status !== 'running');\n if (changed?.outcome) {\n reportOutcome(\n {\n ctx: deps.ctx,\n baseUrl: settings.baseUrl,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n },\n offerId,\n changed.outcome,\n started,\n );\n }\n if (ended.length === 1) {\n const only = ended[0]!.result;\n await footer.done(String(only.envelope.status));\n return only;\n }\n const set = takesResult(\n ended.map(({ take, result }) => ({\n named: { take: take.take },\n result,\n // Paid when the job started: a resume pays nothing more of its own.\n amountAtomic: BigInt(take.amountAtomic),\n })),\n {\n head: `${ended.length} takes of ${takes[0]!.call.provider}`,\n nextStep:\n 'Open each saved file, say which take fits the request best and why, and let the user pick.',\n },\n );\n await footer.done(String(set.envelope.status));\n return set;\n}\n\n/**\n * THE FIELDS THE SPEC PROMISES, AND THE WHOLE BODY ON DISK. A provider body\n * can be far larger than the answer (an Apollo person hit carries the\n * employer's whole organization record), so the model is handed the\n * projection and the path of the full body. The success rule has already run\n * on the full body. Null when the body cannot be cut or the file cannot be\n * written: the whole body is then handed back as before, and the call never\n * fails over it.\n */\nasync function projected(\n dataDir: string,\n project: { id: string; schema: Record<string, unknown> },\n body: string,\n): Promise<{ result: string; fullResultPath: string } | null> {\n const cut = projectBody(project.schema, body);\n if (cut === undefined) return null;\n const fullResultPath = await storeFullResult(dataDir, project.id, body);\n if (fullResultPath === null) return null;\n return { result: JSON.stringify(cut.value), fullResultPath };\n}\n\n/**\n * WHETHER A PAYMENT MAY HAVE BEEN SIGNED, read off the spend gate's own calls\n * rather than off an error. `runPay` reserves before it signs, releases only\n * when nothing was signed, and commits once the authorization has left, so a\n * commit, or a reservation never released, is a payment that may have moved.\n * An error's details cannot say that: a commit that fails to write the spend\n * ledger throws with no amount on it, after the money left.\n */\nfunction watchSigning(inner: SpendAuthorizer): {\n authorizer: SpendAuthorizer;\n mayHaveSigned: () => boolean;\n} {\n let reserved = false;\n let released = false;\n let committed = false;\n return {\n authorizer: {\n policyEnforcement: inner.policyEnforcement,\n authorize: async (req) => {\n const authorization = await inner.authorize(req);\n if (authorization.decision !== 'deny') reserved = true;\n return authorization;\n },\n commit: async (reservationId, amountAtomic, opts) => {\n committed = true;\n await inner.commit(reservationId, amountAtomic, opts);\n },\n release: async (reservationId) => {\n released = true;\n await inner.release(reservationId);\n },\n },\n mayHaveSigned: () => committed || (reserved && !released),\n };\n}\n\n/**\n * WHAT THE SERVER IS TOLD ABOUT A CALL THAT THREW, from the error alone.\n * Money that may have moved is a call that ran, whatever stopped it: `failed`,\n * never `unpaid`. The spend policy keeps its own `needs_approval`. Anything\n * else stopped before a signature, and the reason says which side stopped it:\n * the agent's input, the deal (the live 402 against the spec, or a request\n * this build will not send), the provider's answer, the network, or the\n * wallet. Null for a failure none of those describe, such as a bug here.\n */\nexport function failureOutcome(\n err: unknown,\n facts: {\n /** An amount left, or the spend gate saw a payment that may have. */\n mayHaveMoved: boolean;\n /** The provider refused an input the agent built, before any payment. */\n rejectedInput: boolean;\n },\n): { status: 'failed' | 'needs_approval' } | { status: 'unpaid'; reason: UnpaidReason } | null {\n if (facts.mayHaveMoved) return { status: 'failed' };\n if (!(err instanceof CliError)) return null;\n if (err.code === 'POLICY_REFUSED') return { status: 'needs_approval' };\n const unpaid = (reason: UnpaidReason) => ({ status: 'unpaid' as const, reason });\n if (facts.rejectedInput) return unpaid('input');\n const detail = (err.details ?? {}) as { reason?: unknown; walletUnavailable?: unknown };\n if (\n detail.walletUnavailable === true ||\n detail.reason === 'insufficient_funds' ||\n detail.reason === 'balance_unavailable'\n ) {\n return unpaid('wallet');\n }\n switch (err.code) {\n // REGISTRY_MISMATCH: the live 402 is not the spec's deal, including a\n // varying price over its ceiling. PAYMENT_FAILED before a signature: no\n // entry this wallet can pay, or a price or deal that changed on the\n // re-check. USAGE and REFUSED: a request this build will not send.\n case 'REGISTRY_MISMATCH':\n case 'PAYMENT_FAILED':\n case 'REFUSED':\n case 'USAGE':\n return unpaid('terms');\n // A transport failure or a timeout: no answer came back.\n case 'NETWORK_ERROR':\n return unpaid('unreachable');\n // AN ANSWER THAT WAS NOT A USABLE 402. API_UNREACHABLE from the provider\n // leg always carries one (another status, or a redirect this build will\n // not follow); a transport failure is NETWORK_ERROR. The others: a\n // challenge this build cannot read, or a free body that missed its rule.\n case 'API_UNREACHABLE':\n case 'CONTRACT_MISMATCH':\n case 'CHALLENGE_TOO_LARGE':\n return unpaid('provider');\n default:\n return null;\n }\n}\n\n/** One ledger line for a paid call; the settlement is known only with a tx.\n * `account`: run on the user's own connected account, by its id, which\n * their plan paid; nothing left the balance. */\nexport function paidRecord(\n decision: { capabilityId: string; provider: string; label?: string; via?: 'swap' },\n url: string,\n sent: string,\n amountAtomic: bigint,\n opts: {\n txHash?: string;\n authorization?: SignedAuthorization;\n savedFiles: string[];\n account?: string;\n now?: () => number;\n },\n): PaidRecord {\n return {\n version: 1,\n ts: new Date((opts.now ?? Date.now)()).toISOString(),\n capabilityId: decision.capabilityId,\n provider: decision.provider,\n ...(decision.label !== undefined ? { label: decision.label } : {}),\n // Who the call ran through: Tenjin's own tools, or a connected account.\n source: opts.account ?? BUILT_IN_SOURCE,\n ...(decision.via !== undefined ? { via: decision.via } : {}),\n url,\n sent: recordedSent(sent),\n amountAtomic: amountAtomic.toString(),\n ...(opts.txHash !== undefined ? { txHash: opts.txHash } : {}),\n settlement:\n opts.account !== undefined ? 'account' : opts.txHash !== undefined ? 'settled' : 'unknown',\n savedFiles: opts.savedFiles,\n ...(opts.authorization !== undefined ? { authorization: opts.authorization } : {}),\n };\n}\n\n/** Extensions for the media types a paid lookup plausibly returns; any other\n * type, `text/html` from a seller included, is saved as `.bin`. */\nconst EXTENSIONS: Record<string, string> = {\n 'audio/mpeg': 'mp3',\n 'audio/mp3': 'mp3',\n 'audio/wav': 'wav',\n 'audio/x-wav': 'wav',\n 'audio/wave': 'wav',\n 'audio/ogg': 'ogg',\n 'audio/aac': 'aac',\n 'audio/flac': 'flac',\n 'audio/webm': 'webm',\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/gif': 'gif',\n 'image/webp': 'webp',\n 'image/svg+xml': 'svg',\n 'image/avif': 'avif',\n 'audio/mp4': 'm4a',\n 'audio/x-m4a': 'm4a',\n 'video/quicktime': 'mov',\n 'video/mp4': 'mp4',\n 'video/webm': 'webm',\n 'application/pdf': 'pdf',\n 'application/zip': 'zip',\n 'application/octet-stream': 'bin',\n};\n\nexport function extensionFor(contentType: string): string {\n const type = contentType.split(';')[0]!.trim().toLowerCase();\n return EXTENSIONS[type] ?? 'bin';\n}\n\n/**\n * Write a binary body under the data dir as `<capability>-<timestamp>.<ext>`\n * and say where: the path, the type and the size are what the host needs to\n * use it. The name is built from characters a path segment can always hold.\n *\n * NEVER THROWS. The money has already moved when this runs, and a throw here\n * would reach the failure arm, which reports nothing paid; a file that could\n * not be written is said so beside the amount instead.\n */\nasync function saveBinary(\n dataDir: string,\n capabilityId: string,\n bytes: Uint8Array,\n opts: { contentType: string; now?: () => number; budget?: { leftBytes: number } },\n): Promise<{ savedTo?: string; saveError?: string; contentType: string; bytes: number }> {\n const described = { contentType: opts.contentType, bytes: bytes.byteLength };\n // ONE CALL WRITES AT MOST ITS SHARE: several takes of a video each bring a\n // file home, and the disk is the user's. Taken before the write, given back\n // when it fails.\n if (opts.budget !== undefined && bytes.byteLength > opts.budget.leftBytes) {\n return { saveError: CAP_REACHED, ...described };\n }\n if (opts.budget !== undefined) opts.budget.leftBytes -= bytes.byteLength;\n try {\n const file = await createUniqueFile(\n downloadsDir(dataDir),\n `${capabilityId.slice(0, 80)}-${(opts.now ?? Date.now)()}`,\n extensionFor(opts.contentType),\n );\n try {\n await writeAll(file.handle, bytes);\n } finally {\n await file.handle.close();\n }\n return { savedTo: file.path, ...described };\n } catch (err) {\n if (opts.budget !== undefined) opts.budget.leftBytes += bytes.byteLength;\n return { saveError: err instanceof Error ? err.message : String(err), ...described };\n }\n}\n\nexport type FailStatus = 'failed' | 'needs_approval' | 'needs_input' | 'native';\n\nfunction checkContract(contract: DecisionContract): { status: FailStatus; reason: string } | null {\n const built = contract.request;\n if (built.method !== 'GET' && built.method !== 'POST') {\n return {\n status: 'failed',\n reason: `This build executes GET and POST only, not ${built.method}.`,\n };\n }\n const header = unsafeHeader(built.headers);\n if (header !== null) {\n return {\n status: 'failed',\n reason: `The decision sets a header this build will not send: ${header}`,\n };\n }\n if (built.method === 'GET' && built.body !== undefined) {\n return { status: 'failed', reason: 'The decision puts a body on a GET.' };\n }\n // The arguments are NOT re-validated here. The server binds them against the\n // capability's own schema and builds `request` from the result; this client\n // never re-encodes them, so a second check against a schema the answer no\n // longer carries would be checking a copy of somebody else's rule.\n if (contract.resultSchema !== undefined) {\n try {\n assertResultSchema(contract.resultSchema);\n } catch (err) {\n return {\n status: 'failed',\n reason: `The decision's success rule is unusable: ${String(err)}`,\n };\n }\n }\n try {\n // Parsed above every signature: a URL the paying leg cannot read is a\n // refusal here, never a throw from inside it.\n new URL(built.url);\n } catch {\n return { status: 'failed', reason: 'The decision names a URL this build cannot parse.' };\n }\n return null;\n}\n\n/**\n * The only headers a routing decision may put on the wire. Authentication,\n * transport and payment headers are this client's to set or nobody's, so a\n * decision naming one is refused rather than quietly filtered.\n */\nconst SENDABLE_HEADERS = new Set(['accept', 'content-type']);\n\nfunction unsafeHeader(headers: Record<string, string>): string | null {\n for (const [name, value] of Object.entries(headers)) {\n if (!SENDABLE_HEADERS.has(name.toLowerCase())) return name;\n if (value.length > 1_024 || /[\\r\\n]/.test(value)) return name;\n }\n return null;\n}\n\nfunction supplierOf(url: string): string {\n try {\n return new URL(url).hostname;\n } catch {\n return 'unknown service';\n }\n}\n\n/** The cost line of a call on the user's own account: their plan, never the\n * balance, and not counted in its limits. */\nexport function accountCost(label: string): string[] {\n return [`billed to your ${label} account, not the Tenjin balance`];\n}\n\n/**\n * A RECEIPT FOR A CALL ON THE USER'S ACCOUNT: the account, who paid, and how\n * much came back, counted where the result says (its saved files, or the one\n * list it holds) and named from the spec's own words where they name it (\"the\n * places found\" is places).\n */\nexport function accountReceipt(\n account: { label: string; returns?: string },\n body: unknown,\n savedFiles: readonly string[],\n): string {\n const parts = [account.label, 'your account'];\n if (savedFiles.length > 0) {\n parts.push(`${savedFiles.length} ${savedFiles.length === 1 ? 'file' : 'files'} saved`);\n return parts.join(' · ');\n }\n let value: unknown = body;\n if (typeof body === 'string') {\n try {\n value = JSON.parse(body);\n } catch {\n return parts.join(' · ');\n }\n }\n const lists =\n value !== null && typeof value === 'object' && !Array.isArray(value)\n ? Object.values(value).filter(Array.isArray)\n : [];\n const items = Array.isArray(value) ? value : lists.length === 1 ? lists[0]! : undefined;\n if (items !== undefined) {\n const noun = /^the ([a-z]+s)\\b/.exec(account.returns ?? '')?.[1];\n parts.push(items.length === 1 ? '1 result' : `${items.length} ${noun ?? 'results'}`);\n }\n return parts.join(' · ');\n}\n\n/** ONE COST LINE, because there is one payment: the provider's. */\nexport function costLines(providerAtomic: bigint): string[] {\n return [`provider price ${toMoney(providerAtomic.toString()).usd} USD`];\n}\n\n/**\n * ROUTINE CONTROL OUTCOMES, not failures of this tool. A routing decision was\n * delivered and it says the turn continues somewhere else: with the host's own\n * tools, with a question for the user, or with an approval the user gives.\n * The MCP error flag is for what went WRONG, and raising it on these put a\n * red box in front of the user on the most ordinary answer the router has.\n */\nconst ROUTINE: ReadonlySet<FailStatus> = new Set(['native', 'needs_input', 'needs_approval']);\n\nconst ROUTER_OFF_NEXT_STEP =\n 'Continue with your own tools. Nothing was sent to the router and nothing was bought.';\n\n/**\n * `router.*` for this directory, or why the router is off here, naming the key\n * and the file that set it. A layer that cannot be read is off: a switch the\n * user set must not fail open.\n */\nasync function routerHere(\n deps: RequestToolDeps,\n): Promise<{ settings: RouterSettings } | { off: string }> {\n try {\n const settings = await routerSettings({\n cwd: deps.cwd ?? process.cwd(),\n dataDir: deps.ctx.dataDir,\n });\n if (settings.enabled.value) return { settings };\n return {\n off: `router.enabled is false in ${settings.enabled.path ?? 'the config'}, so the router is off here.`,\n };\n } catch (err) {\n return {\n off: `router.enabled could not be read (${err instanceof Error ? err.message : String(err)}), so the router is off here.`,\n };\n }\n}\n\n/** One short line saying what the host does next, per routine outcome. */\nconst NEXT_STEP: Record<string, string> = {\n native: 'Continue with your own tools. Nothing was bought.',\n needs_input:\n 'Ask the user for the missing detail, then call `request` again with it. Nothing was bought.',\n needs_approval: 'Tell the user what it would cost; nothing was paid.',\n};\n\n/**\n * The four outcomes the target step splits into, each with the step that\n * actually follows from it. The backend's own `nextAction` wins whenever it\n * sent one; this is what a host is told when the code arrives without it.\n */\nconst NEXT_STEP_BY_REASON: Record<string, string> = {\n page_target: 'That URL is the lookup itself; call `request` again with the URL as the query.',\n contextual_url:\n 'The URL was background, not the target; call `request` again with the question as the query.',\n unresolved_intent:\n 'Ask the user for the scope choice or field named above, then call `request` again with it.',\n classifier_failure:\n 'The router could not classify this one and charged nothing. Continue with your own tools, or call `request` once more.',\n};\n\nexport interface FailExtras {\n providerAtomic?: bigint;\n settlement?: string;\n /** Which rule failed, whether the body was JSON, its size and a bounded\n * redacted preview: what tells a parse miss from an HTML error page. */\n diagnosis?: Record<string, unknown>;\n /** The provider's HTTP status on a non-2xx answer. */\n providerStatus?: number;\n /** The start of that answer's body, bounded and redacted. Provider content. */\n providerError?: string;\n /** Why the seller says it did not settle a signed payment, bounded and\n * redacted. Provider content. */\n settlementError?: string;\n /** Where a long job's result will be, as the seller named it. Provider content. */\n statusUrl?: string;\n /** The backend's own stable error code, from a typed non-2xx body. */\n errorCode?: string;\n /** What stopped a non-execute decision, in the backend's own terms. */\n diagnostics?: DecisionDiagnostics;\n /** The backend's plain sentence about the call itself, such as a dead id. */\n note?: string;\n /** Replaces the generic next step, for an outcome this build decided alone. */\n nextStep?: string;\n /** What was sent, or would have been: the bound or built input. */\n parameters?: unknown;\n /** The provider request it went out as. */\n request?: { method: string; url: string };\n /** A plan over the limits, kept for the user's yes: its id, what it buys\n * and its total. */\n quote?: Record<string, unknown>;\n}\n\n/** The headline: calm for a routine outcome, explicit for a real failure. */\nfunction summaryFor(status: FailStatus, reason: string): string {\n if (status === 'native') return `Use your usual tools: ${reason}`;\n if (status === 'needs_input') return `More input needed: ${reason}`;\n if (status === 'needs_approval') return `Needs the user's approval: ${reason}`;\n return `x402 request ${status}: ${reason}`;\n}\n\n/** The backend's own instruction, then the one its reasonCode implies, then the\n * generic one for the outcome. Never empty while any of the three exists. */\nfunction nextStepFor(status: FailStatus, diagnostics: DecisionDiagnostics | undefined): string {\n const fromServer = diagnostics?.nextAction.trim() ?? '';\n if (fromServer.length > 0) return fromServer;\n const byReason =\n diagnostics !== undefined ? NEXT_STEP_BY_REASON[diagnostics.reasonCode] : undefined;\n return byReason ?? NEXT_STEP[status] ?? '';\n}\n\n/**\n * AN OFFER REFUSED BY THE CHECK BEFORE EVERY CALL: nothing was sent, signed\n * or paid, and the agent is told to ask again. Routine (`needs_input`), with\n * the refusal's own code in `reasonCode`.\n */\nexport function settingsFail(refusal: SettingsRefusal): RequestToolResult {\n return fail('needs_input', refusal.reason, {\n diagnostics: {\n reasonCode: refusal.code,\n stage: 'client',\n missing: [],\n nextAction: refusal.nextStep,\n },\n });\n}\n\nexport function fail(\n status: FailStatus,\n reason: string,\n extras: FailExtras = {},\n): RequestToolResult {\n const routine = ROUTINE.has(status);\n const { diagnostics } = extras;\n return {\n isError: !routine,\n summary: summaryFor(status, reason),\n envelope: {\n status,\n reason,\n ...(extras.errorCode !== undefined ? { errorCode: extras.errorCode } : {}),\n ...(extras.quote !== undefined ? { quote: extras.quote } : {}),\n // The status is the fact; the next step is what to do about it. The\n // BACKEND'S own next action wins when it sent one: it knows which field\n // is missing.\n ...(routine || diagnostics !== undefined || extras.nextStep !== undefined\n ? { nextStep: extras.nextStep ?? nextStepFor(status, diagnostics) }\n : {}),\n ...(diagnostics !== undefined\n ? {\n reasonCode: diagnostics.reasonCode,\n stage: diagnostics.stage,\n ...(diagnostics.missing.length > 0 ? { missing: diagnostics.missing } : {}),\n }\n : {}),\n // What LEFT, not what was delivered: an authorization that was\n // transmitted is money at risk whether or not a result came back.\n cost: costLines(extras.providerAtomic ?? 0n),\n ...(extras.note !== undefined ? { note: extras.note } : {}),\n ...(extras.settlement !== undefined ? { settlement: extras.settlement } : {}),\n ...(extras.diagnosis !== undefined ? { diagnosis: extras.diagnosis } : {}),\n ...(extras.providerStatus !== undefined ? { providerStatus: extras.providerStatus } : {}),\n ...(extras.providerError !== undefined ? { providerError: extras.providerError } : {}),\n ...(extras.settlementError !== undefined ? { settlementError: extras.settlementError } : {}),\n ...(extras.statusUrl !== undefined ? { statusUrl: extras.statusUrl } : {}),\n ...(extras.request !== undefined ? { request: extras.request } : {}),\n ...(extras.parameters !== undefined ? { parameters: extras.parameters } : {}),\n providerContentUntrusted: true,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,UAAU;AACnB,SAAS,YAAY;AAgBrB,IAAM,MAAM,KAAK,YAAY,cAAc;AAEpC,IAAM,sBAAsB,KAAK,KAAK;AAE7C,IAAM,gBAAgB,MAAM;AAE5B,IAAM,mBAAmB,iBAAE,aAAa;AAAA,EACtC,SAAS,iBAAE,QAAQ,CAAC;AAAA,EACpB,SAAS,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAAA,EACjC,MAAM;AAAA,EACN,OAAO,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC;AAAA,EACvC,OAAO,iBAAE,QAAQ;AAAA,EACjB,SAAS,iBAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AACxC,CAAC;AAGD,IAAM,SAAS,CAAC,SAAiB,YAC/B,KAAK,SAAS,KAAK,GAA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