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/paid.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { appendFile, mkdir, open, readFile, rm, type FileHandle } from 'node:fs/promises';\nimport { request as httpRequest, type IncomingMessage } from 'node:http';\nimport { request as httpsRequest } from 'node:https';\nimport type { LookupFunction } from 'node:net';\nimport { dirname, join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { resolvePublicDestination, type DestinationOptions } from '../lib/destination';\nimport { hasCode } from '../lib/errno';\nimport { withFileLock } from '../lib/lock';\nimport { downloadsDir, paidLedgerPath } from '../lib/paths';\nimport { mask } from '../lib/redact';\nimport { USDC_ADDRESS } from '../lib/usdc-balance';\nimport { releaseUnchargedExposure } from '../lib/wallet/spend';\n\n/**\n * WHAT A PAID ROUTER CALL BOUGHT, KEPT ON THIS MACHINE. One JSON line per paid\n * call in `~/.tenjin/paid/ledger.jsonl`: who was paid, for what, how much, the\n * settlement it carried and the files it saved. A direct `tenjin pay` the\n * seller did not deliver on is a line too. It is the user's own record\n * and the receipt `tenjin payments reconcile` resolves an unknown settlement\n * against. Nothing here can fail a lookup: every write swallows its own error.\n */\n\n/** `account`: run on the user's own connected account, which their plan\n * pays; nothing left the balance, so there is nothing to settle. */\nexport type Settlement = 'settled' | 'unknown' | 'not_charged' | 'account';\n\n/** The EIP-3009 authorization that was signed, enough to ask the token later\n * whether it was used. */\nexport interface SignedAuthorization {\n from: string;\n nonce: string;\n /** Unix seconds; after it the authorization can no longer be used. */\n validBefore: string;\n}\n\nexport interface PaidRecord {\n version: 1;\n ts: string;\n capabilityId: string;\n provider: string;\n /** The service's display name, when its decision or spec carried one. */\n label?: string;\n /** Who the call ran through: `tenjin` for Tenjin's own tools, or the id of\n * the connected account that ran it (plan 37). Rows from before have none\n * and read as `tenjin`. */\n source?: string;\n /** `swap`: the call answered a native search or fetch in place, which\n * nobody was asked about separately. */\n via?: 'swap';\n url: string;\n /** The input or query sent, masked and cut to {@link MAX_SENT_CHARS}. */\n sent: string;\n amountAtomic: string;\n txHash?: string;\n settlement: Settlement;\n savedFiles: string[];\n authorization?: SignedAuthorization;\n /** When reconcile last asked the chain about it, so a slow or rate-limited\n * RPC is not asked about the same record on every lookup. */\n lastCheckedAt?: string;\n /** The offer id of a job on the user's own account: its one row, kept from\n * when its billing call may have billed and finished in place. */\n job?: string;\n /** `unknown`: a call on the user's own account that may have billed it,\n * with no result to show it did: still running, failed after the\n * account's job started, or answered with the account's own error. Usage\n * and payments say it may have charged, and never count it as billed.\n * Absent: the account ran it. */\n charge?: 'unknown';\n}\n\nexport const MAX_SENT_CHARS = 4_096;\n\n/**\n * A JSON value with every object key and string leaf masked on its own. The\n * mask anchors on word boundaries, which a serialized string hides: after an\n * escaped `\\n` a key reads as `nsk-ant-…`, one word, and passes.\n */\nexport function maskDeep(value: unknown): unknown {\n if (typeof value === 'string') return mask(value);\n if (Array.isArray(value)) return value.map(maskDeep);\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n mask(key),\n maskDeep(entry),\n ]),\n );\n }\n return value;\n}\n\n/** The input or query as it is recorded: secrets masked, then cut. */\nexport function recordedSent(sent: string): string {\n return mask(sent).slice(0, MAX_SENT_CHARS);\n}\n\nexport async function appendPaidRecord(dataDir: string, record: PaidRecord): Promise<void> {\n try {\n const path = paidLedgerPath(dataDir);\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n // Under the lock reconcile rewrites with, so an append is never lost to it.\n await withFileLock(`${path}.lock`, () =>\n appendFile(path, `${JSON.stringify(record)}\\n`, { mode: 0o600 }),\n );\n } catch {\n // The record is the user's convenience; the lookup already happened.\n }\n}\n\n/**\n * A JOB'S ROW, FINISHED IN PLACE. A paid call whose seller was still working\n * is recorded when it is paid, so a crash mid-poll loses no row; the files the\n * job later saved, and the settlement its last answer named, are written onto\n * that same row, found by its authorization's nonce, under the lock reconcile\n * rewrites with. One payment, one row. Never throws.\n */\nexport async function updatePaidRecord(\n dataDir: string,\n nonce: string,\n patch: { savedFiles?: string[]; txHash?: string },\n): Promise<void> {\n try {\n const path = paidLedgerPath(dataDir);\n const key = nonce.toLowerCase();\n await withFileLock(`${path}.lock`, async () => {\n const current = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n let found = false;\n const lines = current.map(({ line, record }) => {\n if (record?.authorization?.nonce.toLowerCase() !== key) return line;\n found = true;\n return JSON.stringify({\n ...record,\n ...(patch.savedFiles !== undefined ? { savedFiles: patch.savedFiles } : {}),\n ...(patch.txHash !== undefined && record.settlement === 'unknown'\n ? { txHash: patch.txHash, settlement: 'settled' }\n : {}),\n });\n });\n if (found) {\n await writeFileAtomic(path, lines.map((line) => `${line}\\n`).join(''), { mode: 0o600 });\n }\n });\n } catch {\n // The record is the user's convenience; the lookup already happened.\n }\n}\n\n/**\n * A JOB ON THE USER'S OWN ACCOUNT, ONE ROW (plan 37). It is written once its\n * billing call may have billed (still running, failed, or answered with the\n * account's own error), its charge `unknown`, so usage and payments show it\n * as may have charged; a later write for the same job that delivered (the\n * resumed job) finishes that row in place, with the files it saved and its\n * charge no longer unknown, under the lock reconcile rewrites with. Never\n * throws.\n */\nexport async function recordAccountRow(\n dataDir: string,\n record: PaidRecord & { job: string },\n): Promise<void> {\n try {\n const path = paidLedgerPath(dataDir);\n await mkdir(dirname(path), { recursive: true, mode: 0o700 });\n await withFileLock(`${path}.lock`, async () => {\n const current = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const kept = current\n .map(({ record: row }) => row)\n .find((row): row is PaidRecord => row?.job === record.job);\n if (kept === undefined) {\n await appendFile(path, `${JSON.stringify(record)}\\n`, { mode: 0o600 });\n return;\n }\n // Still unknown, or already finished with nothing to add: unchanged.\n if (record.charge !== undefined) return;\n if (kept.charge === undefined && record.savedFiles.length === 0) return;\n const lines = current.map(({ line, record: row }) => {\n if (row?.job !== record.job) return line;\n const finished: PaidRecord = {\n ...row,\n ...(record.savedFiles.length > 0 ? { savedFiles: record.savedFiles } : {}),\n };\n delete finished.charge;\n return JSON.stringify(finished);\n });\n await writeFileAtomic(path, lines.map((line) => `${line}\\n`).join(''), { mode: 0o600 });\n });\n } catch {\n // The record is the user's convenience; the lookup already happened.\n }\n}\n\n/** `authorizationState(address,bytes32)`: the first four bytes of its keccak-256. */\nconst AUTHORIZATION_STATE_SELECTOR = '0xe94a0102';\nconst WORD_RE = /^0x[0-9a-fA-F]{64}$/;\n/** How many unknown settlements one pass asks the chain about. */\nexport const MAX_RECONCILE_CHECKS = 3;\n/** How long a record the chain could not answer for waits before it is asked\n * about again by the lookup-time pass. */\nexport const RECHECK_MS = 10 * 60_000;\nconst RECONCILE_TIMEOUT_MS = 1_500;\n\n/**\n * Whether USDC on Base has used this authorization: true once a facilitator\n * settled it, false while it has not. Null when the RPC could not say.\n */\nexport async function authorizationUsed(\n authorization: SignedAuthorization,\n rpcUrl: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number; blockTag?: string } = {},\n): Promise<boolean | null> {\n const result = await rpcCall(\n rpcUrl,\n 'eth_call',\n [\n {\n to: USDC_ADDRESS,\n data: `${AUTHORIZATION_STATE_SELECTOR}${authorization.from.slice(2).toLowerCase().padStart(64, '0')}${authorization.nonce.slice(2).toLowerCase()}`,\n },\n opts.blockTag ?? 'latest',\n ],\n opts,\n );\n if (typeof result !== 'string' || !WORD_RE.test(result)) return null;\n return BigInt(result) !== 0n;\n}\n\n/**\n * The chain's own clock: the latest block's number and timestamp (seconds).\n * Expiry is decided against it, not this machine's clock, and the state is\n * read at that same block: a node that lags, or a clock running ahead, then\n * agrees with itself. Null when the RPC could not say.\n */\nexport async function latestBlock(\n rpcUrl: string,\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number } = {},\n): Promise<{ tag: string; timestamp: number } | null> {\n const result = await rpcCall(rpcUrl, 'eth_getBlockByNumber', ['latest', false], opts);\n if (result === null || typeof result !== 'object') return null;\n const { number, timestamp } = result as { number?: unknown; timestamp?: unknown };\n if (typeof number !== 'string' || !/^0x[0-9a-fA-F]+$/.test(number)) return null;\n if (typeof timestamp !== 'string' || !/^0x[0-9a-fA-F]+$/.test(timestamp)) return null;\n return { tag: number, timestamp: Number(BigInt(timestamp)) };\n}\n\nasync function rpcCall(\n rpcUrl: string,\n method: string,\n params: unknown[],\n opts: { fetchImpl?: typeof fetch; timeoutMs?: number },\n): Promise<unknown> {\n try {\n const res = await (opts.fetchImpl ?? fetch)(rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),\n signal: AbortSignal.timeout(opts.timeoutMs ?? RECONCILE_TIMEOUT_MS),\n });\n if (!res.ok) return null;\n return ((await res.json()) as { result?: unknown } | null)?.result ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface ReconcileOutcome {\n /** Records asked about in this pass. */\n checked: number;\n /** The authorization was used: the amount was charged. */\n settled: number;\n /** It expired unused: nothing was charged. */\n notCharged: number;\n /** Still unknown: not yet expired, no authorization on record, or the RPC\n * could not answer. */\n unknown: number;\n /** What the not-charged payments gave back to today's automatic budget. */\n releasedAtomic: string;\n}\n\n/**\n * RESOLVE \"SETTLEMENT UNKNOWN\" FROM THE CHAIN. A paid call whose seller never\n * confirmed settlement leaves a record marked `unknown`. Once the chain's\n * latest block is past its authorization's `validBefore`, the token's own\n * `authorizationState(from, nonce)` read AT THAT BLOCK is final: used means\n * charged, unused means it can never be charged, since no later block can\n * carry it. This machine's clock only decides whether the chain is worth\n * asking. At most `max` records are asked about per pass, and\n * a record the RPC cannot answer for stays unknown, stamped `lastCheckedAt`,\n * and is not asked about again for `recheckMs`.\n *\n * The chain is asked outside the lock; the file is re-read and rewritten under\n * it, so an append made meanwhile is kept.\n */\nexport async function reconcilePayments(\n dataDir: string,\n opts: {\n rpcUrl: string;\n fetchImpl?: typeof fetch;\n now?: () => number;\n max?: number;\n timeoutMs?: number;\n /** Defaults to {@link RECHECK_MS}; the command passes 0. */\n recheckMs?: number;\n },\n): Promise<ReconcileOutcome> {\n const path = paidLedgerPath(dataDir);\n const now = (opts.now ?? Date.now)();\n const records = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const open = records.filter(\n (entry): entry is { line: string; record: PaidRecord } =>\n entry.record !== null && entry.record.settlement === 'unknown',\n );\n const recheckMs = opts.recheckMs ?? RECHECK_MS;\n const due = open.filter(\n ({ record }) =>\n record.authorization !== undefined &&\n Number(record.authorization.validBefore) * 1_000 < now &&\n (record.lastCheckedAt === undefined || now - Date.parse(record.lastCheckedAt) >= recheckMs),\n );\n const answers = new Map<string, Settlement>();\n const asked = new Set<string>();\n let checked = 0;\n const rpc = {\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n };\n const block = due.length > 0 ? await latestBlock(opts.rpcUrl, rpc) : null;\n for (const { record } of due.slice(0, opts.max ?? MAX_RECONCILE_CHECKS)) {\n // Not past validBefore on the chain yet: not asked, and not stamped.\n if (block !== null && Number(record.authorization!.validBefore) >= block.timestamp) continue;\n checked += 1;\n asked.add(record.authorization!.nonce);\n if (block === null) continue;\n const used = await authorizationUsed(record.authorization!, opts.rpcUrl, {\n ...rpc,\n blockTag: block.tag,\n });\n if (used !== null) answers.set(record.authorization!.nonce, used ? 'settled' : 'not_charged');\n }\n // NOT CHARGED GIVES THE DAILY BUDGET BACK FIRST: exactly that payment's\n // exposure, by its nonce, while it is still inside the window that counted\n // it. Only then is the record marked; a release that could not be written\n // leaves it unknown, and the next pass asks again. A second release of the\n // same nonce finds nothing, so a retry never gives back twice.\n let releasedAtomic = 0n;\n for (const [nonce, answer] of [...answers]) {\n if (answer !== 'not_charged') continue;\n const released = await releaseUnchargedExposure(dataDir, nonce, {\n ...(opts.now !== undefined ? { now: opts.now } : {}),\n });\n if (released === null) answers.delete(nonce);\n else releasedAtomic += released;\n }\n if (asked.size > 0) {\n await withFileLock(`${path}.lock`, async () => {\n const current = parseLedger(await readFile(path, 'utf8').catch(() => ''));\n const lines = current.map(({ line, record }) => {\n const nonce =\n record?.settlement === 'unknown' && record.authorization !== undefined\n ? record.authorization.nonce\n : undefined;\n if (nonce === undefined || !asked.has(nonce)) return line;\n const answer = answers.get(nonce);\n const stamp = new Date(now).toISOString();\n return JSON.stringify(\n answer === undefined\n ? { ...record, lastCheckedAt: stamp }\n : { ...record, settlement: answer, lastCheckedAt: stamp, reconciledAt: stamp },\n );\n });\n await writeFileAtomic(path, lines.map((line) => `${line}\\n`).join(''), { mode: 0o600 });\n });\n }\n const settled = [...answers.values()].filter((value) => value === 'settled').length;\n return {\n checked,\n settled,\n notCharged: answers.size - settled,\n unknown: open.length - answers.size,\n releasedAtomic: releasedAtomic.toString(),\n };\n}\n\n/** Every paid record in the ledger, oldest first; a line that is not one is skipped. */\nexport async function readPaidRecords(dataDir: string): Promise<PaidRecord[]> {\n const raw = await readFile(paidLedgerPath(dataDir), 'utf8').catch(() => '');\n return parseLedger(raw).flatMap(({ record }) => (record === null ? [] : [record]));\n}\n\n/** Every line, and the record it holds when it is one; other lines ride along. */\nfunction parseLedger(raw: string): { line: string; record: PaidRecord | null }[] {\n return raw\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line) => {\n try {\n const value = JSON.parse(line) as PaidRecord;\n return { line, record: value !== null && value.version === 1 ? value : null };\n } catch {\n return { line, record: null };\n }\n });\n}\n\n/** The media a paid result links to, by the extension its path ends in. */\nconst MEDIA_EXTENSIONS = new Set([\n 'png',\n 'jpg',\n 'jpeg',\n 'webp',\n 'gif',\n 'svg',\n 'mp3',\n 'wav',\n 'm4a',\n 'ogg',\n 'mp4',\n 'webm',\n 'mov',\n]);\nexport const MAX_MEDIA_FILES = 5;\nexport const MAX_MEDIA_BYTES = 200 * 1024 * 1024;\nexport const MEDIA_TIMEOUT_MS = 60_000;\nconst MAX_REDIRECTS = 3;\nconst URL_RE = /https:\\/\\/[^\\s\"'<>\\\\]+/g;\n\n/** Every https URL in the result whose path ends in a media extension, in\n * order and without repeats, at most {@link MAX_MEDIA_FILES}. */\nexport function mediaUrlsIn(result: string, limit = MAX_MEDIA_FILES): string[] {\n const found: string[] = [];\n for (const match of result.matchAll(URL_RE)) {\n if (found.length >= limit) break;\n let url: URL;\n try {\n url = new URL(match[0]);\n } catch {\n continue;\n }\n const ext = url.pathname.split('.').pop()?.toLowerCase() ?? '';\n if (!url.pathname.includes('.') || !MEDIA_EXTENSIONS.has(ext)) continue;\n if (!found.includes(url.toString())) found.push(url.toString());\n }\n return found;\n}\n\n/** One GET the media download makes, connected to the address it validated. */\nexport interface PinnedTarget {\n url: URL;\n /** The address `resolvePublicDestination` checked; the socket goes here. */\n address: string;\n family: 4 | 6;\n}\n\nexport interface MediaResponse {\n status: number;\n location?: string;\n contentLength?: number;\n body: AsyncIterable<Uint8Array>;\n /** Drop the connection without reading the rest. */\n discard: () => void;\n}\n\nexport type MediaTransport = (target: PinnedTarget, signal: AbortSignal) => Promise<MediaResponse>;\n\nexport interface MediaDeps {\n /** Test seam; production connects with {@link pinnedGet}. */\n transport?: MediaTransport;\n destination?: DestinationOptions;\n now?: () => number;\n timeoutMs?: number;\n maxBytes?: number;\n /** What the call may still write, shared by every file it saves, side by\n * side or not: charged as each chunk is written, so a download still in\n * flight holds only what it wrote. A chunk that would take it below zero\n * stops that file, and a file that is not kept gives its bytes back. */\n budget?: { leftBytes: number };\n}\n\n/**\n * CONNECT TO THE ADDRESS THAT WAS CHECKED. `fetch` resolves the name again on\n * its own, so a host answering publicly to the check and privately a moment\n * later (DNS rebinding) would get the request. `node:https` with a `lookup`\n * that hands back the one validated address closes that: the socket goes to\n * it, and TLS still verifies the certificate against the URL's own host name.\n */\nexport const pinnedGet: MediaTransport = async (target, signal) => {\n const res = await pinnedHttp(target, { method: 'GET' }, signal);\n const length = Number(res.headers['content-length']);\n const location = res.headers.location;\n return {\n status: res.statusCode ?? 0,\n ...(typeof location === 'string' ? { location } : {}),\n ...(Number.isFinite(length) ? { contentLength: length } : {}),\n body: res,\n discard: () => res.destroy(),\n };\n};\n\n/**\n * ONE REQUEST ON THE PINNED SOCKET, the one every request to a host this CLI\n * checked goes out on: a media download (above), a job's poll (`jobs.ts`)\n * and every connected-account request to a host the router or a server named\n * (`accounts/fetch.ts`). HTTPS, but for the plain `http` the account check\n * takes to a loopback address alone. No redirect is followed; the caller sees\n * the 3xx and checks the next hop.\n */\nexport function pinnedHttp(\n target: PinnedTarget,\n request: { method: string; headers?: Record<string, string>; body?: string | Uint8Array },\n signal: AbortSignal,\n): Promise<IncomingMessage> {\n const send = target.url.protocol === 'http:' ? httpRequest : httpsRequest;\n return new Promise((resolve, reject) => {\n const req = send(\n target.url,\n {\n method: request.method,\n ...(request.headers !== undefined ? { headers: request.headers } : {}),\n signal,\n lookup: pinnedLookup(target),\n },\n resolve,\n );\n req.on('error', reject);\n req.end(request.body);\n });\n}\n\n/** A `lookup` that answers every name with the one validated address. */\nexport function pinnedLookup(target: Pick<PinnedTarget, 'address' | 'family'>): LookupFunction {\n return ((_host: string, options: { all?: boolean }, callback: LookupCallback) => {\n if (options.all === true) {\n callback(null, [{ address: target.address, family: target.family }]);\n } else {\n callback(null, target.address, target.family);\n }\n }) as unknown as LookupFunction;\n}\n\ntype LookupCallback = (\n err: Error | null,\n address: string | { address: string; family: number }[],\n family?: number,\n) => void;\n\n/** A file the budget left too little room for. */\nconst CAPPED = Symbol('capped');\n/** A file a later try could save: the network, the file's server or this\n * disk failed, not a rule of ours. */\nconst FAILED = Symbol('failed');\n\n/**\n * Download each URL into the downloads dir, one at a time, each under its own\n * size cap and deadline, every hop of a redirect validated and connected to\n * the address it validated. Returns the paths that were written, whether the\n * budget left a file too little room (`capped`), and whether a download\n * failed in a way a later try could get past (`failed`); a later call could\n * save either. A URL that fails is skipped and never fails the call.\n */\nexport async function saveMedia(\n dataDir: string,\n stem: string,\n urls: string[],\n deps: MediaDeps = {},\n): Promise<{ saved: string[]; capped: boolean; failed: boolean }> {\n const saved: string[] = [];\n let capped = false;\n let failed = false;\n for (const [index, url] of urls.entries()) {\n const path = await saveOne(dataDir, `${stem}-${index + 1}`, url, deps);\n if (path === CAPPED) capped = true;\n else if (path === FAILED) failed = true;\n else if (path !== null) saved.push(path);\n }\n return { saved, capped, failed };\n}\n\n/** Statuses a later try could get past: the server, not the link, failed. */\nconst RETRYABLE_STATUS = new Set([408, 429]);\n\nasync function saveOne(\n dataDir: string,\n stem: string,\n raw: string,\n deps: MediaDeps,\n): Promise<string | typeof CAPPED | typeof FAILED | null> {\n const transport = deps.transport ?? pinnedGet;\n const cap = deps.maxBytes ?? MAX_MEDIA_BYTES;\n const { budget } = deps;\n if (budget !== undefined && budget.leftBytes <= 0) return CAPPED;\n // What this file has taken from the call's budget, given back unless kept.\n let charged = 0;\n let kept = false;\n // Stopped by the call's budget, not by the file's own cap.\n let capped = false;\n // Stopped by a rule of ours (an address, the file's cap), which no later\n // try gets past.\n let refused = false;\n const signal = AbortSignal.timeout(deps.timeoutMs ?? MEDIA_TIMEOUT_MS);\n let target = raw;\n let path: string | null = null;\n try {\n let res: MediaResponse | null = null;\n for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {\n const pinned = await resolvePublicDestination(target, deps.destination ?? {}).catch(\n (err: unknown) => {\n refused = true;\n throw err;\n },\n );\n res = await transport(pinned, signal);\n if (res.status < 300 || res.status >= 400 || res.location === undefined) break;\n res.discard();\n target = new URL(res.location, target).toString();\n res = null;\n }\n if (res === null || res.status < 200 || res.status >= 300) {\n res?.discard();\n const status = res?.status ?? 0;\n return status >= 500 || RETRYABLE_STATUS.has(status) ? FAILED : null;\n }\n const declared = res.contentLength ?? 0;\n if (declared > cap) {\n res.discard();\n return null;\n }\n if (budget !== undefined && declared > budget.leftBytes) {\n res.discard();\n return CAPPED;\n }\n const ext = new URL(target).pathname.split('.').pop()?.toLowerCase() ?? 'bin';\n const file = await createUniqueFile(\n downloadsDir(dataDir),\n `${stem}-${(deps.now ?? Date.now)()}`,\n MEDIA_EXTENSIONS.has(ext) ? ext : 'bin',\n );\n path = file.path;\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 refused = true;\n throw new Error('media over the size cap');\n }\n // Charged before the write, in the same turn as the check, so files\n // saving side by side can never write past the call's cap between\n // them.\n if (budget !== undefined) {\n if (chunk.byteLength > budget.leftBytes) {\n res.discard();\n capped = true;\n throw new Error(\"media over the call's download cap\");\n }\n budget.leftBytes -= chunk.byteLength;\n charged += chunk.byteLength;\n }\n await writeAll(file.handle, chunk);\n }\n } finally {\n await file.handle.close();\n }\n kept = true;\n return path;\n } catch {\n if (path !== null) await rm(path, { force: true }).catch(() => undefined);\n return capped ? CAPPED : refused ? null : FAILED;\n } finally {\n if (budget !== undefined && !kept) budget.leftBytes += charged;\n }\n}\n\n/**\n * EVERY BYTE, OR A THROW. `FileHandle.write` may write fewer bytes than it was\n * handed and says so only in `bytesWritten`; a caller that ignores it saves a\n * file with a hole in it. A write that makes no progress is an error.\n */\nexport async function writeAll(\n handle: Pick<FileHandle, 'write'>,\n bytes: Uint8Array,\n): Promise<void> {\n let offset = 0;\n while (offset < bytes.byteLength) {\n const { bytesWritten } = await handle.write(bytes, offset, bytes.byteLength - offset);\n if (bytesWritten <= 0) throw new Error('the file write made no progress');\n offset += bytesWritten;\n }\n}\n\n/**\n * A NEW FILE, NEVER ANOTHER CALL'S. The name is the stem plus a random suffix,\n * created with an exclusive flag, so two lookups finishing in the same\n * millisecond each get their own file; a clash is retried with a new suffix.\n */\nexport async function createUniqueFile(\n directory: string,\n stem: string,\n ext: string,\n): Promise<{ path: string; handle: FileHandle }> {\n await mkdir(directory, { recursive: true });\n const safe = stem.replace(/[^A-Za-z0-9_-]+/g, '-').slice(0, 100) || 'lookup';\n for (let attempt = 0; ; attempt += 1) {\n const path = join(directory, `${safe}-${randomBytes(4).toString('hex')}.${ext}`);\n try {\n return { path, handle: await open(path, 'wx', 0o600) };\n } catch (err) {\n if (attempt >= 4 || !hasCode(err, 'EEXIST')) throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,YAAY,OAAO,MAAM,UAAU,UAA2B;AACvE,SAAS,WAAW,mBAAyC;AAC7D,SAAS,WAAW,oBAAoB;AAExC,SAAS,SAAS,YAAY;AAoEvB,IAAM,iBAAiB;AAOvB,SAAS,SAAS,OAAyB;AAChD,MAAI,OAAO,UAAU,SAAU,QAAO,KAAK,KAAK;AAChD,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,QAAQ;AACnD,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO,OAAO;AAAA,MACZ,OAAO,QAAQ,KAAgC,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM;AAAA,QACrE,KAAK,GAAG;AAAA,QACR,SAAS,KAAK;AAAA,MAChB,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,aAAa,MAAsB;AACjD,SAAO,KAAK,IAAI,EAAE,MAAM,GAAG,cAAc;AAC3C;AAEA,eAAsB,iBAAiB,SAAiB,QAAmC;AACzF,MAAI;AACF,UAAM,OAAO,eAAe,OAAO;AACnC,UAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAE3D,UAAM;AAAA,MAAa,GAAG,IAAI;AAAA,MAAS,MACjC,WAAW,MAAM,GAAG,KAAK,UAAU,MAAM,CAAC;AAAA,GAAM,EAAE,MAAM,IAAM,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AC,KAAM,QAAO,aAAa;AAAA,EACzD;AACF;AAOA,eAAsB,SACpB,QACA,OACe;AACf,MAAI,SAAS;AACb,SAAO,SAAS,MAAM,YAAY;AAChC,UAAM,EAAE,aAAa,IAAI,MAAM,OAAO,MAAM,OAAO,QAAQ,MAAM,aAAa,MAAM;AACpF,QAAI,gBAAgB,EAAG,OAAM,IAAI,MAAM,iCAAiC;AACxE,cAAU;AAAA,EACZ;AACF;AAOA,eAAsB,iBACpB,WACA,MACA,KAC+C;AAC/C,QAAM,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;AAC1C,QAAM,OAAO,KAAK,QAAQ,oBAAoB,GAAG,EAAE,MAAM,GAAG,GAAG,KAAK;AACpE,WAAS,UAAU,KAAK,WAAW,GAAG;AACpC,UAAM,OAAO,KAAK,WAAW,GAAG,IAAI,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,IAAI,GAAG,EAAE;AAC/E,QAAI;AACF,aAAO,EAAE,MAAM,QAAQ,MAAM,KAAK,MAAM,MAAM,GAAK,EAAE;AAAA,IACvD,SAAS,KAAK;AACZ,UAAI,WAAW,KAAK,CAAC,QAAQ,KAAK,QAAQ,EAAG,OAAM;AAAA,IACrD;AAAA,EACF;AACF;","names":["open"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/alive.ts","../src/lib/wallet-facts.ts","../src/router/notice-markers.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { mkdir, readdir, readFile, rm, rmdir, stat, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { DEFAULT_MAX_AUTO_SPEND, loadRawConfig, type PartialConfig } from '../lib/config';\nimport { walletPath } from '../lib/paths';\nimport { DEFAULT_RPC_URL, readUsdcBalanceWithFallback } from '../lib/usdc-balance';\nimport { readWalletFacts } from '../lib/wallet-facts';\nimport { noticeFor } from './notice-markers';\nimport { routerSettings } from './settings';\nimport { sessionStartMessage } from './wallet-reasons';\n\n/**\n * THE PLUGIN SAYS IT IS HERE. While a machine carries both the plugin and the\n * settings install it replaces, every event would run two sets of routing legs\n * and offer the same lookup twice. The plugin's `SessionStart` entry runs\n * `tenjin hook alive` before any other event of the session, and it writes:\n *\n * - a per-session marker, which every leg a settings install launched checks\n * first, staying silent in a session the plugin serves;\n * - a per-machine stamp, the proof the guarded migration waits for: the plugin\n * has loaded in a real session on this machine at least once, so the\n * settings install can be removed without leaving the machine unrouted.\n *\n * Outside `progress/`, whose files are pruned after ten minutes. Markers are\n * pruned here after a week, which outlasts any session that still matters.\n *\n * SHIM: the per-session check goes on or after 2026-12-01, the first release\n * cut 30 or more days after the plugin PR 2 ships; the stamp stays for doctor.\n *\n * It also says, once, when the wallet's FILES already show it cannot sign in\n * this session ({@link walletAtStart}). That is a file fact, not a verdict:\n * `alive` never unlocks, never execs, never reads a keychain and never replays\n * what a router saw (Q4). Everything else waits for the router's first notice.\n * Its one network call is the balance read behind {@link walletNotice}, at\n * most once a day and bounded at 2 s, through the env proxy it sets up then.\n */\n\nconst MARKER_TTL_MS = 7 * 24 * 60 * 60 * 1000;\nconst STAMP = 'plugin-loaded.json';\n/** When the balance was last read for the notice ({@link walletNotice}). */\nconst BALANCE_NOTICE_FILE = 'balance-notice.json';\n/** A session id names a file only through its hash, so any string is safe. */\nconst MAX_SESSION_ID = 200;\n\nexport function aliveDir(dataDir: string): string {\n return join(dataDir, 'alive');\n}\n\nfunction markerName(sessionId: string): string {\n return createHash('sha256').update(sessionId).digest('hex').slice(0, 32);\n}\n\nfunction sessionIdOf(event: unknown): string | null {\n if (event === null || typeof event !== 'object') return null;\n const id = (event as { session_id?: unknown }).session_id;\n return typeof id === 'string' && id.length > 0 && id.length <= MAX_SESSION_ID ? id : null;\n}\n\nexport interface AliveStamp {\n at: string;\n /** The CLI version whose plugin loaded. */\n version: string;\n}\n\n/** What a `SessionStart` hook prints when the wallet cannot sign: one line for\n * the person, one for the model. */\nexport interface AliveAnswer {\n systemMessage: string;\n hookSpecificOutput: { hookEventName: 'SessionStart'; additionalContext: string };\n}\n\n/**\n * The `alive` leg: marker, stamp, prune, then the wallet's files. It prints\n * only when the wallet file is unreadable or the saved passphrase file is gone\n * (with TENJIN_WALLET_PASSPHRASE unset), because a `SessionStart` hook's stdout\n * is added to the session's context and nothing else there is definite before\n * a router has tried to unlock; everything else waits for the router's first\n * notice. The answer carries the person's fix in `systemMessage` and the\n * model's `agentFix` in `additionalContext` (B1), and the reason's notice\n * marker is written so the session's first prompt leg does not say it again.\n * ({@link aliveMain} adds the balance notice as JSON when there is no answer.)\n * It never fails the session: every error is swallowed, and gives null.\n */\nexport async function runAliveHook(\n event: unknown,\n opts: { dataDir: string; version: string; now?: number; env?: NodeJS.ProcessEnv },\n): Promise<AliveAnswer | null> {\n const sessionId = sessionIdOf(event);\n const now = opts.now ?? Date.now();\n const dir = aliveDir(opts.dataDir);\n try {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n if (sessionId !== null) {\n await writeFile(join(dir, markerName(sessionId)), `${new Date(now).toISOString()}\\n`);\n }\n const stamp: AliveStamp = { at: new Date(now).toISOString(), version: opts.version };\n await writeFile(join(dir, STAMP), `${JSON.stringify(stamp)}\\n`);\n await pruneMarkers(dir, now);\n } catch {\n // A marker that could not be written costs only a duplicate offer.\n }\n try {\n const reason = await walletAtStart(opts.dataDir, opts.env ?? process.env);\n if (reason === null) return null;\n const { systemMessage, additionalContext } = sessionStartMessage(reason);\n if (sessionId !== null) {\n await noticeFor(opts.dataDir, sessionId, reason, now).catch(() => undefined);\n }\n return {\n systemMessage,\n hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext },\n };\n } catch {\n return null;\n }\n}\n\n/**\n * WHAT THE FILES ALONE SAY AT SESSION START, and only what is definite (Q4).\n * Filesystem only: one wallet.json read, the sidecar read and a few stats; no\n * exec, no keychain, no scrypt, and never the router's unlock-state, so it\n * cannot repeat a verdict that has since changed. In order:\n *\n * - a TENJIN_WALLET_KEY (valid or not) shadows the file, and whether it works\n * is the router's to report: null;\n * - no wallet.json: null, never `no_wallet`, because the person may have\n * installed with `--no-wallet` on purpose;\n * - a wallet.json nothing can read: `wallet_corrupt`;\n * - the sidecar names the file store, its `.plain` file is gone, and\n * TENJIN_WALLET_PASSPHRASE is unset: `passphrase_missing`;\n * - anything else: null.\n */\nexport async function walletAtStart(\n dataDir: string,\n env: NodeJS.ProcessEnv,\n): Promise<'wallet_corrupt' | 'passphrase_missing' | null> {\n const facts = await readWalletFacts(dataDir, env);\n if (facts.envKey !== 'absent') return null;\n if (facts.walletFile === 'absent') return null;\n if (facts.walletFile === 'unparsable') return 'wallet_corrupt';\n if (facts.passphraseFileMissing && !facts.envPassphraseSet) return 'passphrase_missing';\n return null;\n}\n\nasync function pruneMarkers(dir: string, now: number): Promise<void> {\n for (const name of await readdir(dir).catch(() => [] as string[])) {\n if (!/^[0-9a-f]{32}$/.test(name)) continue;\n const path = join(dir, name);\n const s = await stat(path).catch(() => null);\n if (s !== null && now - s.mtimeMs > MARKER_TTL_MS) await rm(path, { force: true });\n }\n}\n\n/** Has the plugin's `alive` leg marked this session? False on any doubt. */\nexport async function sessionServedByPlugin(dataDir: string, event: unknown): Promise<boolean> {\n const sessionId = sessionIdOf(event);\n if (sessionId === null) return false;\n return (await stat(join(aliveDir(dataDir), markerName(sessionId))).catch(() => null)) !== null;\n}\n\n/** The machine's stamp, or null when the plugin has never loaded here. */\nexport async function readAliveStamp(dataDir: string): Promise<AliveStamp | null> {\n try {\n const parsed = JSON.parse(await readFile(join(aliveDir(dataDir), STAMP), 'utf8')) as unknown;\n if (parsed === null || typeof parsed !== 'object') return null;\n const { at, version } = parsed as { at?: unknown; version?: unknown };\n return typeof at === 'string' && typeof version === 'string' ? { at, version } : null;\n } catch {\n return null;\n }\n}\n\n/** `uninstall`: the markers, the stamp and the notice record, and nothing else under the data dir. */\nexport async function removeAliveState(dataDir: string): Promise<boolean> {\n const dir = aliveDir(dataDir);\n const existed = (await stat(dir).catch(() => null)) !== null;\n if (!existed) return false;\n for (const name of await readdir(dir).catch(() => [] as string[])) {\n if (name === STAMP || name === BALANCE_NOTICE_FILE || /^[0-9a-f]{32}$/.test(name))\n await rm(join(dir, name), { force: true });\n }\n // Only when empty: a file somebody else put there keeps the folder.\n await rmdir(dir).catch(() => undefined);\n return true;\n}\n\n/** How long the leg waits on a balance read before it says nothing. */\nexport const WALLET_READ_MS = 2_000;\n\n/** The balance is read for the notice at most once in this long, across sessions. */\nexport const BALANCE_NOTICE_EVERY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * THE BALANCE, SAID TO THE PERSON AT THE START OF A SESSION while it is under\n * the per-call limit: the leg's `systemMessage`, which Claude Code shows the\n * user and never the model, on every surface and without the mod. The read\n * behind it is one bounded balance read, at most once a day\n * (`balance-notice.json`), so the notice is too: a reminder at every session\n * start gets Tenjin uninstalled. Null when there is no wallet, a\n * TENJIN_WALLET_KEY shadows wallet.json, the router is off, the balance was\n * read in the last day, it could not be read in time, or it holds at least the\n * per-call limit.\n */\nexport async function walletNotice(\n dataDir: string,\n opts: {\n /** The session's directory, whose project layers `router.enabled` reads too. */\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n read?: typeof readUsdcBalanceWithFallback;\n timeoutMs?: number;\n now?: () => number;\n } = {},\n): Promise<string | null> {\n const env = opts.env ?? process.env;\n // The env key, valid or not, shadows wallet.json as in {@link walletAtStart}:\n // the file's address is not the wallet that pays, so it is never read for.\n if ((env.TENJIN_WALLET_KEY?.trim() ?? '') !== '') return null;\n const now = (opts.now ?? Date.now)();\n const noticePath = join(aliveDir(dataDir), BALANCE_NOTICE_FILE);\n const last = (await readJson(noticePath))?.at;\n if (typeof last === 'number' && now >= last && now - last < BALANCE_NOTICE_EVERY_MS) return null;\n const wallet = await readJson(walletPath(dataDir));\n const address = typeof wallet?.address === 'string' ? wallet.address : undefined;\n if (address === undefined || !/^0x[0-9a-fA-F]{40}$/.test(address)) return null;\n // `router.enabled` as every hook reads it, for the session's directory: off,\n // or a config that cannot be read, and nothing is read or said, nor recorded.\n let config: PartialConfig;\n try {\n config = await loadRawConfig(dataDir);\n const router = await routerSettings(\n { cwd: opts.cwd ?? process.cwd(), dataDir, config },\n { warn: () => undefined },\n );\n if (!router.enabled.value) return null;\n } catch {\n return null;\n }\n // A read that cannot record itself is not made: unrecorded, it would\n // come back at every session start.\n try {\n await mkdir(aliveDir(dataDir), { recursive: true, mode: 0o700 });\n await writeFile(noticePath, JSON.stringify({ at: now }), { mode: 0o600 });\n } catch {\n return null;\n }\n const rpcUrl = config.rpcUrl ?? DEFAULT_RPC_URL;\n const timeoutMs = opts.timeoutMs ?? WALLET_READ_MS;\n const read = opts.read ?? readThroughEnvProxy(env);\n const balance = await read(address, rpcUrl, { timeoutMs });\n if (balance === null) return null;\n // The per-call limit as the spend policy reads it: the file's, else the default.\n const cap = BigInt(config.maxAutoSpend ?? DEFAULT_MAX_AUTO_SPEND);\n if (balance > 0n && balance >= cap) return null;\n // Only the person reads it, inside the session: they say so, the agent runs it.\n return `Tenjin balance $${dollars(balance)} · low. Say \"add funds\" when you're ready.`;\n}\n\n/**\n * The balance read, through the proxy the environment names. The bin entry\n * sets that proxy up only after this leg has exited, and here only a read that\n * is due loads it, so a session start with nothing to read pays nothing for it.\n */\nfunction readThroughEnvProxy(env: NodeJS.ProcessEnv): typeof readUsdcBalanceWithFallback {\n return async (address, rpcUrl, opts) => {\n (await import('../lib/env-proxy')).useEnvProxy(env);\n return readUsdcBalanceWithFallback(address, rpcUrl, opts);\n };\n}\n\n/** `$0.00`, `$0.10`, `$0.007`: whole cents keep two decimals. */\nfunction dollars(atomic: bigint): string {\n const fraction = (atomic % 1_000_000n).toString().padStart(6, '0').replace(/0+$/, '');\n return `${atomic / 1_000_000n}.${fraction.padEnd(2, '0')}`;\n}\n\nasync function readJson(path: string): Promise<Record<string, unknown> | null> {\n try {\n const value: unknown = JSON.parse(await readFile(path, 'utf8'));\n return value !== null && typeof value === 'object' ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The command form's entry, read off stdin: `tenjin hook alive`. It writes the\n * answer, when there is one, as one JSON line and WAITS for the write to land:\n * on macOS stdout to a pipe is asynchronous, and `src/index.ts` calls\n * `process.exit(0)` right after this returns, which would drop it. With no\n * answer from the wallet's files, it prints the balance notice\n * ({@link walletNotice}) as a JSON `systemMessage`, which Claude Code shows the\n * user; plain text would be added to the session's context. A wallet that\n * cannot sign is told that, never to add funds.\n */\nexport async function aliveMain(opts: {\n dataDir: string;\n version: string;\n env?: NodeJS.ProcessEnv;\n /** Test seams: the harness event and the stream the answer goes to. */\n readEvent?: () => Promise<string>;\n stdout?: Pick<NodeJS.WritableStream, 'write'>;\n}): Promise<void> {\n const raw = await (opts.readEvent ?? (() => readStdin(1_000)))().catch(() => '');\n const event = parseEvent(raw);\n const answer = await runAliveHook(event, {\n dataDir: opts.dataDir,\n version: opts.version,\n ...(opts.env !== undefined ? { env: opts.env } : {}),\n });\n const cwd = cwdOf(event);\n const notice =\n answer === null\n ? await walletNotice(opts.dataDir, {\n ...(cwd !== null ? { cwd } : {}),\n ...(opts.env !== undefined ? { env: opts.env } : {}),\n }).catch(() => null)\n : null;\n const payload = answer ?? (notice !== null ? { systemMessage: notice } : null);\n if (payload === null) return;\n const out = opts.stdout ?? process.stdout;\n await new Promise<void>((resolve) => {\n try {\n out.write(`${JSON.stringify(payload)}\\n`, () => resolve());\n } catch {\n resolve();\n }\n });\n}\n\nfunction parseEvent(raw: string): unknown {\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n}\n\n/** The session's directory, as the harness event names it. */\nfunction cwdOf(event: unknown): string | null {\n if (event === null || typeof event !== 'object') return null;\n const cwd = (event as { cwd?: unknown }).cwd;\n return typeof cwd === 'string' && cwd.length > 0 ? cwd : null;\n}\n\nfunction readStdin(timeoutMs: number): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n const timer = setTimeout(() => reject(new Error('no harness event')), timeoutMs);\n process.stdin.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (size > 1_000_000) {\n clearTimeout(timer);\n reject(new Error('harness event too large'));\n return;\n }\n chunks.push(chunk);\n });\n process.stdin.once('end', () => {\n clearTimeout(timer);\n resolve(Buffer.concat(chunks).toString('utf8'));\n });\n process.stdin.once('error', () => {\n clearTimeout(timer);\n reject(new Error('harness event unreadable'));\n });\n });\n}\n\n/**\n * A plugin leg marks its own session too, for a session that loaded the plugin\n * without a `SessionStart` (a `/reload-plugins` mid-session): from the next\n * event on, the settings install's legs there stay silent. A stat when the\n * marker is already there.\n */\nexport async function markSessionServed(dataDir: string, event: unknown): Promise<void> {\n const sessionId = sessionIdOf(event);\n if (sessionId === null) return;\n const path = join(aliveDir(dataDir), markerName(sessionId));\n if ((await stat(path).catch(() => null)) !== null) return;\n try {\n await mkdir(aliveDir(dataDir), { recursive: true, mode: 0o700 });\n await writeFile(path, `${new Date().toISOString()}\\n`);\n } catch {\n // Costs only a duplicate offer.\n }\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { hasCode } from './errno';\nimport { readPassphraseRecord } from './passphrase-record';\nimport { passphraseFilePathFor, passphraseRecordPath, walletPath } from './paths';\nimport { PRIVATE_KEY_RE, type DurableStore } from './wallet-unlock';\nimport { ADDRESS_RE } from './ids';\n\n/**\n * WHAT THE FILES SAY ABOUT THE WALLET, without unlocking it. The hooks, `alive`\n * and the routing payer's memo need to know \"is there a wallet, is it readable,\n * where was its passphrase saved, and did any of that change\" on every prompt,\n * and none of them may load the wallet layer (`src/router/dist-chunks.test.ts`)\n * or pay for a keychain read or an scrypt to find out.\n *\n * So this reads only: wallet.json's cleartext address, the sidecar, two or three\n * `stat`s, and the environment. It never execs and never throws; anything it\n * cannot read is reported as the fact it is (`unparsable`, null), and deciding\n * what that means is `src/router/eligibility.ts`'s job.\n */\nexport interface WalletFacts {\n /** TENJIN_WALLET_KEY trimmed vs PRIVATE_KEY_RE; whitespace-only = absent. */\n envKey: 'absent' | 'valid' | 'malformed';\n /** unparsable = unreadable, bad JSON, or no valid address. */\n walletFile: 'present' | 'absent' | 'unparsable';\n /** Cleartext top-level address of wallet.json. */\n address: string | null;\n envPassphraseSet: boolean;\n /** Sidecar entry for `address`. */\n passphraseStore: DurableStore | null;\n /** Sidecar says 'file' and the .plain file is absent. */\n passphraseFileMissing: boolean;\n walletMtimeMs: number | null;\n sidecarMtimeMs: number | null;\n}\n\n/** The same address test `hooks.ts` applies to wallet.json's cleartext field. */\n\n/**\n * Read {@link WalletFacts} for `dataDir` under `env`. Never rejects.\n *\n * `envKey` runs the exact test `loadCredential` (src/lib/wallet/local.ts)\n * runs, through the one shared {@link PRIVATE_KEY_RE}, so a key these facts\n * call valid is one the signer accepts. The env passphrase counts as set only\n * when non-empty, as the passphrase resolver treats it.\n */\nexport async function readWalletFacts(\n dataDir: string,\n env: NodeJS.ProcessEnv,\n): Promise<WalletFacts> {\n const key = env.TENJIN_WALLET_KEY?.trim() ?? '';\n const envKey: WalletFacts['envKey'] =\n key.length === 0 ? 'absent' : PRIVATE_KEY_RE.test(key) ? 'valid' : 'malformed';\n const passphrase = env.TENJIN_WALLET_PASSPHRASE;\n const envPassphraseSet = passphrase !== undefined && passphrase.length > 0;\n\n const { walletFile, address } = await readWalletAddress(dataDir);\n const [walletMtimeMs, sidecarMtimeMs] = await Promise.all([\n mtimeOf(walletPath(dataDir)),\n mtimeOf(passphraseRecordPath(dataDir)),\n ]);\n\n let passphraseStore: DurableStore | null = null;\n let passphraseFileMissing = false;\n if (address !== null) {\n passphraseStore =\n (await readPassphraseRecord(dataDir, address).catch(() => null))?.store ?? null;\n if (passphraseStore === 'file') {\n // Only a definite ENOENT is \"missing\". Any other stat failure says\n // nothing about whether the file is there, so it claims nothing.\n passphraseFileMissing = await stat(passphraseFilePathFor(address.toLowerCase(), dataDir))\n .then(() => false)\n .catch((err: unknown) => hasCode(err, 'ENOENT'));\n }\n }\n\n return {\n envKey,\n walletFile,\n address,\n envPassphraseSet,\n passphraseStore,\n passphraseFileMissing,\n walletMtimeMs,\n sidecarMtimeMs,\n };\n}\n\n/** `${walletMtimeMs}:${sidecarMtimeMs}`, the stamp the payer memo compares. */\nexport function unlockStamp(f: Pick<WalletFacts, 'walletMtimeMs' | 'sidecarMtimeMs'>): string {\n return `${f.walletMtimeMs}:${f.sidecarMtimeMs}`;\n}\n\n/** wallet.json's state and cleartext address. ENOENT is absent; any other\n * failure to read or understand it is unparsable. */\nasync function readWalletAddress(\n dataDir: string,\n): Promise<Pick<WalletFacts, 'walletFile' | 'address'>> {\n let text: string;\n try {\n text = await readFile(walletPath(dataDir), 'utf8');\n } catch (err) {\n return { walletFile: hasCode(err, 'ENOENT') ? 'absent' : 'unparsable', address: null };\n }\n try {\n const record: unknown = JSON.parse(text);\n const address = (record as { address?: unknown } | null)?.address;\n return typeof address === 'string' && ADDRESS_RE.test(address)\n ? { walletFile: 'present', address }\n : { walletFile: 'unparsable', address: null };\n } catch {\n return { walletFile: 'unparsable', address: null };\n }\n}\n\nasync function mtimeOf(path: string): Promise<number | null> {\n try {\n return (await stat(path)).mtimeMs;\n } catch {\n return null;\n }\n}\n","import { randomBytes } from 'node:crypto';\nimport { mkdir, open, readFile, rename, rm } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport { hasCode } from '../lib/errno';\nimport type { UnlockReason } from '../lib/wallet-unlock';\nimport { WALLET_CLASS, walletClearedSentence } from './wallet-reasons';\nimport { sha256Hex } from '../lib/hash';\nimport { PRIVATE, sweep, writePrivate } from './store-files';\n\n/**\n * WHAT A SESSION HAS ALREADY BEEN TOLD, on disk, because every hook leg is its\n * own process (or a fresh call into `tenjin mcp`) and none of them remembers\n * the last. Under `<dataDir>/router/notices`:\n *\n * <sha32> the old once-per-session marker ({@link firstNoticeFor})\n * <sha32>-<sha8> told this session this reason ({@link noticeFor})\n * <sha32>.current `${at}\\n${why}`: the reason told last, or `cleared`\n *\n * `<sha32>` is the first 32 hex of sha256(session id) and `<sha8>` the first 8\n * of sha256(reason), so neither a session id nor a reason ever names a file.\n *\n * Once per (session, reason), with a clear line. A wallet that\n * goes from \"no passphrase\" to \"wrong passphrase\" is news twice; the same\n * reason on every prompt is news once. Once a paid call succeeds after a\n * wallet-class reason was told, the session hears paid routing recovered, once\n * ({@link noticeCleared}), and the reason's marker goes with it, so a relapse is\n * told again.\n *\n * Every file's FIRST line is the time it was written, and pruning reads only\n * that line, so old markers, new ones and `.current` all age out the same way:\n * a week after they were last written.\n *\n * Hook-safe: node, `./store-files`, `lib/errno` and the reason strings.\n */\n\n/** How long a session's notice marker is kept. */\nconst NOTICE_KEEP_MS = 7 * 86_400_000;\n\n/** What `.current` says once the reason told last has been cleared. */\nconst CLEARED = 'cleared';\n\n/** Every reason {@link settleCurrent} clears: the unlock reasons and the\n * unclassified fallback, all of which \"Tenjin wallet unlocked.\" answers. */\nconst UNLOCK_CLASS: ReadonlyArray<UnlockReason | 'wallet_locked'> = [\n 'no_wallet',\n 'wallet_corrupt',\n 'env_key_invalid',\n 'passphrase_missing',\n 'passphrase_wrong',\n 'env_passphrase_wrong',\n 'keychain_locked',\n 'unlock_timeout',\n 'wallet_locked',\n];\n\nfunction noticesDir(dataDir: string): string {\n return join(dataDir, 'router', 'notices');\n}\n\nfunction sessionHash(sessionId: string): string {\n return sha256Hex(sessionId, 32);\n}\n\nfunction reasonMarker(dataDir: string, sessionId: string, why: string): string {\n const reason = sha256Hex(why, 8);\n return join(noticesDir(dataDir), `${sessionHash(sessionId)}-${reason}`);\n}\n\nfunction currentPath(dataDir: string, sessionId: string): string {\n return join(noticesDir(dataDir), `${sessionHash(sessionId)}.current`);\n}\n\n/** Record the reason told last (or `cleared`), atomically: two legs at once\n * leave one whole answer, never a torn one. */\nasync function writeCurrent(\n dataDir: string,\n sessionId: string,\n now: number,\n why: string,\n): Promise<void> {\n await writePrivate(currentPath(dataDir, sessionId), `${now}\\n${why}`);\n}\n\n/**\n * 'tell' ONCE PER (SESSION, REASON): the first caller creates the marker,\n * records `why` as the reason told last, and gets 'tell'; every later caller\n * for the same pair gets 'quiet'. A new reason is a new marker, so it is told.\n * Rejects only on an I/O failure other than \"already there\"; callers treat\n * that as quiet.\n */\nexport async function noticeFor(\n dataDir: string,\n sessionId: string,\n why: string,\n now: number,\n): Promise<'tell' | 'quiet'> {\n const created = await createExclusive(reasonMarker(dataDir, sessionId, why), String(now));\n if (!created) return 'quiet';\n await writeCurrent(dataDir, sessionId, now, why);\n await pruneNotices(dataDir, now);\n return 'tell';\n}\n\n/**\n * THE CLEAR LINE, only after a completed signed routing payment: paid routing\n * is working again when the reason told last was wallet-class, else null.\n * A free answer or background deposit alone must not call this.\n *\n * CLAIM BY UNLINK. Two legs can finish paid calls at once and both read the\n * same `.current`; only the one that takes that reason's marker away returns\n * the sentence, so it is said once. Removing the marker is also what lets the\n * reason be told again if the wallet relapses. The take is a rename to a name\n * of this caller's own, then a remove: two concurrent `unlink`s of one path\n * were both seen to succeed on macOS, and a rename of one source has exactly\n * one winner.\n */\nexport async function noticeCleared(\n dataDir: string,\n sessionId: string,\n now: number,\n): Promise<string | null> {\n const text = await readFile(currentPath(dataDir, sessionId), 'utf8').catch(() => null);\n if (text === null) return null;\n const why = text.split('\\n')[1] ?? '';\n if (!WALLET_CLASS.has(why)) return null;\n const marker = reasonMarker(dataDir, sessionId, why);\n const claimed = join(\n dirname(marker),\n `.${basename(marker)}.${randomBytes(6).toString('hex')}.claimed`,\n );\n try {\n await rename(marker, claimed);\n } catch {\n // Another leg claimed it (ENOENT), or it cannot be touched: say nothing.\n return null;\n }\n await rm(claimed, { force: true }).catch(() => undefined);\n await writeCurrent(dataDir, sessionId, now, CLEARED);\n return walletClearedSentence(why);\n}\n\n/**\n * The router's wallet news already said `Tenjin wallet unlocked.` on this\n * session's leg: mark the reason told last as cleared, so a later paid call\n * does not say it twice, and drop the markers of every unlock reason, so a\n * relapse is told again.\n */\nexport async function settleCurrent(\n dataDir: string,\n sessionId: string,\n now: number,\n): Promise<void> {\n await writeCurrent(dataDir, sessionId, now, CLEARED);\n await Promise.all(\n UNLOCK_CLASS.map((why) =>\n rm(reasonMarker(dataDir, sessionId, why), { force: true }).catch(() => undefined),\n ),\n );\n}\n\n/**\n * TRUE ONCE PER SESSION: the first caller for a session id creates its marker\n * and gets true; every later one gets false. Each marker holds the time it was\n * made, and those older than a week go on the way past, so the directory does\n * not grow with every session ever run.\n */\nexport async function firstNoticeFor(\n dataDir: string,\n sessionId: string,\n now: number,\n): Promise<boolean> {\n const created = await createExclusive(\n join(noticesDir(dataDir), sessionHash(sessionId)),\n String(now),\n );\n if (created) await pruneNotices(dataDir, now);\n return created;\n}\n\n/**\n * Remove every notice file whose first line is not a time, or is a time more\n * than a week before `now`. Only the first line: `.current` carries its reason\n * on the second, and must age like any marker rather than look malformed.\n *\n * Skipped: a dot-file (another leg's `.current` mid-rename) and an empty file\n * (another leg's marker between its exclusive create and its write), so a prune\n * never pulls a file out from under a writer.\n */\nasync function pruneNotices(dataDir: string, now: number): Promise<void> {\n await sweep(noticesDir(dataDir), async (name, path) => {\n if (name.startsWith('.')) return false;\n const text = await readFile(path, 'utf8').catch(() => 'NaN');\n if (text.length === 0) return false;\n const at = Number(text.split('\\n')[0]);\n return !Number.isFinite(at) || now - at > NOTICE_KEEP_MS;\n });\n}\n\n/** Create `path` holding `body`, only if it is not already there: true when\n * this call made it, false on EEXIST, and any other failure rethrown. */\nexport async function createExclusive(path: string, body: string): Promise<boolean> {\n try {\n await mkdir(join(path, '..'), { recursive: true, mode: PRIVATE.dirMode });\n const handle = await open(path, 'wx', PRIVATE.mode);\n try {\n await handle.writeFile(body);\n } finally {\n await handle.close();\n }\n return true;\n } catch (err) {\n if (hasCode(err, 'EEXIST')) return false;\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,SAAAA,QAAO,SAAS,YAAAC,WAAU,MAAAC,KAAI,OAAO,QAAAC,OAAM,i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aAAO,KAAK,KAAK;AAAA,IACnB,CAAC;AACD,YAAQ,MAAM,KAAK,OAAO,MAAM;AAC9B,mBAAa,KAAK;AAClB,cAAQ,OAAO,OAAO,MAAM,EAAE,SAAS,MAAM,CAAC;AAAA,IAChD,CAAC;AACD,YAAQ,MAAM,KAAK,SAAS,MAAM;AAChC,mBAAa,KAAK;AAClB,aAAO,IAAI,MAAM,0BAA0B,CAAC;AAAA,IAC9C,CAAC;AAAA,EACH,CAAC;AACH;AAQA,eAAsB,kBAAkB,SAAiB,OAA+B;AACtF,QAAM,YAAY,YAAY,KAAK;AACnC,MAAI,cAAc,KAAM;AACxB,QAAM,OAAOJ,MAAK,SAAS,OAAO,GAAG,WAAW,SAAS,CAAC;AAC1D,MAAK,MAAME,MAAK,IAAI,EAAE,MAAM,MAAM,IAAI,MAAO,KAAM;AACnD,MAAI;AACF,UAAMD,OAAM,SAAS,OAAO,GAAG,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAC/D,UAAM,UAAU,MAAM,IAAG,oBAAI,KAAK,GAAE,YAAY,CAAC;AAAA,CAAI;AAAA,EACvD,QAAQ;AAAA,EAER;AACF;","names":["mkdir","readFile","rm","stat","join","readFile","readFile","join","mkdir","stat","rm","readFile"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { isLoopbackHost } from '../lib/destination';\nimport { fetchFailureToCliError, httpRequest, MAX_BINARY_BODY_BYTES } from '../lib/http';\nimport type { FetchJsonFailure, HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\nimport type { Harness } from './names';\nimport {\n BUILT_IN_SOURCE,\n SETTINGS_ACCEPT,\n SettingsHashSchema,\n TargetIdSchema,\n type WireSettings,\n} from './settings-wire';\n\n/**\n * ONE ROUTING PATH, ONE DECISION PER LOOKUP. Every routing call, the hook's\n * and the `request` tool's, goes to the paid route ({@link ROUTE_PAID_PATH}).\n * Inside `tenjin mcp` the payer sends it through the stock x402 client and\n * pays the routing fee its 402 quotes ({@link DecisionRoute},\n * `routing-payer.ts`); a call it cannot pay is skipped, with no request to any\n * other route. One whose channel needs a deposit waits for the payer's\n * background top-up inside its budget first. The free route ({@link ROUTER_PATH}) keeps only what stays free:\n * browse, a browse row's spec and the outcome report.\n *\n * The backend answers with what it would do and what the provider charges,\n * and the provider is paid by `runPay`, from a spec, under the local spend\n * policy. The bounded packet travels with the hook request and the backend\n * keeps it against the decision id until that id expires. What this client\n * keeps is each offer's spec, by its id (`specs.ts`).\n */\n\n/** The free route: browse, a browse row's spec, and the outcome report. */\nexport const ROUTER_PATH = '/api/x402-router';\n/** The paid route, behind x402: every routing call. */\nexport const ROUTE_PAID_PATH = '/api/x402-router/route';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, and a non-execute with no diagnostics\n * parsed with nothing to act on. Each of those is drift the shared fixtures\n * exist to catch, so each is a parse failure that names itself.\n *\n * A TOLERANT READER, AND ONLY THAT (RFC 9413). A field this build does not\n * know is dropped, never a failure: a server that adds one reaches every\n * released client without a release or a deploy order. A field it does know\n * keeps its type, its bounds and its checks, and a job's `pollUrl` or\n * `running` naming the keys of both its arms is still refused (an answer's\n * own arms are told apart by `action`). An offer that a client\n * must understand to run says so in `requires` ({@link withoutUnmet}).\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.object({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\n/** A display name the server gives a capability, sent because this build\n * lists `label`. Shown exactly as given; absent, a surface says\n * {@link UNLABELLED}. */\nconst LabelSchema = z.string().min(1).max(32);\n\n/** What a surface names a lookup whose decision carries no `label`. */\nexport const UNLABELLED = 'Tenjin lookup';\n\n/**\n * WHAT AN OFFER NEEDS THIS CLIENT TO UNDERSTAND, in the `accepts` vocabulary,\n * on an offering answer or on any spec: a must-understand list, like JWS\n * `crit` (RFC 7515 §4.1.11). The tolerant reader drops a field it does not\n * know, which is right for a field a client may ignore and wrong for one that\n * changes what a call is (a header it must send, a new kind of payment). Such\n * an offer names that feature here, and a build without it skips that offer\n * alone, by name, rather than run it half understood ({@link withoutUnmet}).\n * The same bounds as `accepts`, with the alphabet pinned: a token is named\n * in the model's text when its offer is skipped.\n */\nconst RequiresSchema = z\n .array(z.string().regex(/^[a-z][a-z0-9_-]{0,31}$/))\n .max(16)\n .optional();\n\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n label: LabelSchema.optional(),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n requires: RequiresSchema,\n};\n\n/**\n * STRUCTURE, NEVER WORDING. A hint lands in the model's context verbatim, so\n * its shape is checked the way the id's alphabet is: one line, no control\n * characters, and it has to be the call it claims to be, naming the id this\n * same answer carries. A hint that fails any of these is a protocol error and\n * the turn falls back to the generic line; nothing here rewrites a word of a\n * hint that passes. Both offering arms, `execute` and `discovered`, hold it.\n */\nfunction checkHint(decision: { id: string; hint: string }, ctx: z.RefinementCtx): void {\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n}\n\n/**\n * A PAY-PER-CALL SERVICE NOBODY CURATED. When a Tenjin list service does the\n * task the gate picked, or no task fits and a listed x402 service could do the\n * step, the server names that one service: who sells it, where, for how much,\n * and the input it takes. A Tenjin list service arrives here under its catalog\n * id, because this build sends `catalog`. The candidate is the seller's own\n * listing, so every field is data for the host to judge, never an instruction;\n * the host builds the `input` and the tool call pays through the same `runPay`\n * path and caps as a curated lookup.\n */\nconst DiscoveredCandidateSchema = z.object({\n source: z.string().min(1).max(64),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n description: z.string().max(500),\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n network: z.string().min(1).max(64),\n payTo: z.string().min(1).max(200),\n input: z.object({\n location: z.enum(['body', 'query']),\n schema: z.record(z.string(), z.unknown()),\n }),\n});\n\n/** A key that belongs to another arm of the same union. The tolerant reader\n * drops a key it does not know; this one it knows, so an object naming the\n * keys of both arms is refused rather than read as whichever arm is first. */\nconst OtherArm = z.never().optional();\n\n/** A field name a job reads from an answer or writes into a poll body. */\nconst JobField = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/);\n\n/** A body field whose value names a state: Treza's `status: \"running\"`. */\nconst JobFieldStateSchema = z.object({\n field: JobField,\n values: z.array(z.string().min(1).max(64)).min(1).max(8),\n});\n\n/** A poll body value naming a field of the call's input or of the submit's\n * answer; any other value is sent as written. */\nexport const POLL_REFERENCE = /^\\$(input|result)\\.([A-Za-z_][A-Za-z0-9_]{0,63})$/;\n\n/**\n * HOW A CALL WHOSE SELLER ANSWERS BEFORE THE RESULT IS READY IS FINISHED, sent\n * on a spec only because this build asks for it (`accepts: [\"jobs\"]`): where\n * the status is (a field or header of the submit's answer, or one fixed URL),\n * how a poll is sent, what says it is still running or failed, how often and\n * how long to poll, and how many hours the job can be resumed. `always`: the\n * seller never answers inline. A poll is never signed: the take's one payment\n * is its submit. Every field is the server's: the poll and complete URLs are\n * still checked here against the submit's host (`jobs.ts`).\n */\nexport const JobSchema = z\n .object({\n pollUrl: z.union([\n z\n .object({\n field: JobField.optional(),\n header: z\n .string()\n .regex(/^[A-Za-z0-9-]{1,64}$/)\n .optional(),\n fixed: OtherArm,\n })\n .refine((at) => at.field !== undefined || at.header !== undefined, 'a field or a header'),\n z.object({ fixed: z.string().min(1).max(2_048), field: OtherArm, header: OtherArm }),\n ]),\n /** Sent once like a poll after the result is saved, never after a save\n * that failed: it frees the seller's copy (AiSpace's `/complete`). Its\n * answer is ignored. */\n completeUrl: z.object({ fixed: z.string().min(1).max(2_048) }).optional(),\n pollMethod: z.enum(['GET', 'POST']),\n pollBody: z\n .record(JobField, z.unknown())\n .refine(\n (body) =>\n Object.values(body).every(\n (value) =>\n typeof value !== 'string' || !value.startsWith('$') || POLL_REFERENCE.test(value),\n ),\n 'a $ value is $input.<field> or $result.<field>',\n )\n .optional(),\n running: z.union([\n z.object({\n httpStatus: z.array(z.number().int().min(200).max(299)).min(1).max(8),\n field: OtherArm,\n values: OtherArm,\n }),\n JobFieldStateSchema.extend({ httpStatus: OtherArm }),\n ]),\n failed: JobFieldStateSchema.optional(),\n everyS: z.number().int().min(1).max(30),\n maxWaitS: z.number().int().min(1).max(600),\n keepH: z.number().int().min(1).max(48),\n always: z.literal(true).optional(),\n })\n .refine((job) => !job.pollBody || job.pollMethod === 'POST', 'only a POST poll has a body');\nexport type Job = z.infer<typeof JobSchema>;\n\n/** A spec's `timeoutS` ceiling: the paid leg's own (`MAX_PAID_LEG_TIMEOUT_MS`\n * in `commands/pay.ts`), so no spec can hold a call longer than a seller's\n * 402 already may. */\nexport const MAX_SPEC_TIMEOUT_S = 120;\n\n/**\n * A REQUEST SPEC: the offered service's real contract, sent beside the line only\n * because this build asks for it (`accepts: [\"spec\"]`). The hook stores it by\n * the offer's id; `request({id})` shows it and `request({id, input})` fills its\n * request and pays the provider directly, with no second decision. Every field\n * is the server's, and so is checked like the rest of the answer: the payee and\n * price still meet the live 402 and the spend policy in `runPay`.\n */\nexport const ToolSpecSchema = z.object({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n /** The display name, on a catalog service's spec; a Bazaar spec has none. */\n label: LabelSchema.optional(),\n /** The input field that takes a pending search's query or fetch's URL. */\n holds: z\n .object({\n WebSearch: z.string().min(1).max(64).optional(),\n WebFetch: z.string().min(1).max(64).optional(),\n })\n .optional(),\n /** What a paid result is. `media` means its files (bytes, links or inline\n * base64) are saved locally; absent on a Bazaar spec. */\n output: z.enum(['json', 'text', 'media']).optional(),\n description: z.string().min(1).max(500),\n priceAtomic: z.string().regex(/^\\d+$/),\n priceVaries: z.boolean(),\n maxAmountAtomic: z.string().regex(/^\\d+$/),\n payTo: z.string().min(1).max(200),\n network: z.string().min(1).max(64),\n asset: z.string().min(1).max(200),\n request: z.object({\n method: z.enum(['GET', 'POST']),\n url: z.string().min(1).max(2_048),\n fields: z.record(z.string(), z.enum(['path', 'query', 'body'])),\n location: z.enum(['query', 'body']),\n /** Fixed request headers the catalog decides for this service (a\n * provider's beta opt-in, say), never the agent. The call refuses a name\n * this client signs or sets itself; `accept` and `content-type` stay its own. */\n headers: z\n .record(z.string().min(1).max(64), z.string().min(1).max(1_024))\n .refine((headers) => Object.keys(headers).length <= 8, 'at most 8 headers')\n .optional(),\n }),\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n /** The fields the result promises (type, properties, items, required). The\n * agent is handed only these; the whole body is saved to a file. */\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n /** How a call answered before its result is ready is finished. */\n job: JobSchema.optional(),\n /** A media service that runs several takes of one call: `count` up to `max`. */\n takes: z.object({ max: z.number().int().min(2).max(5) }).optional(),\n requires: RequiresSchema,\n /** The provider call's own deadline in seconds: the unpaid probe's, and\n * the least the paid leg waits. Absent, the CLI's `--timeout`. */\n timeoutS: z.number().int().min(1).max(MAX_SPEC_TIMEOUT_S).optional(),\n /** The largest file the call may bring back, in bytes: a binary result,\n * and each file a media result links to, though not yet a job's polled\n * result. Absent, and at most, the {@link MAX_BINARY_BODY_BYTES} every\n * call had. */\n maxBytes: z.number().int().min(1).max(MAX_BINARY_BODY_BYTES).optional(),\n});\nexport type ToolSpec = z.infer<typeof ToolSpecSchema>;\n\nexport const OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });\nexport type OfferSpec = z.infer<typeof OfferSpecSchema>;\n\n/** One spec per service the line names: the offer, any other service it\n * lists, and each option of a choice set. */\nconst SpecsSchema = z.array(OfferSpecSchema).min(1).max(8).optional();\n\n/*\n * A SERVICE ON A CONNECTED ACCOUNT (plan 37), with the bounds tenjin's\n * `wire.ts` holds it to: one MCP tool call this client makes on the user's\n * own account, which the user's plan pays. Sent only to a build that lists\n * `mcp`, and only for an account its `settings.sources` names. It carries no\n * URL, no credential and no price: this client calls the server it connected\n * for `source`, so no answer can send a user's token anywhere else.\n */\n\n/** The `accepts` token for a call on a connected account. */\nexport const MCP_ACCEPT = 'mcp';\n\n/** A connected account's id, which this client keeps its sign-in under: the\n * vault `sources/<id>.json` and the OS-store account `source:<id>:<folder>`.\n * Narrower than a target id, so no file system, shell or keychain command\n * line reads it as anything else. */\nexport const ACCOUNT_ID = /^[a-z0-9][a-z0-9-]{0,47}$/;\n\n/** Whether `id` is an account's: never the built-in source, which is never\n * connected. */\nexport function isAccountId(id: string): boolean {\n return ACCOUNT_ID.test(id) && id !== BUILT_IN_SOURCE;\n}\n\n/** A tool name as the MCP specification bounds it. */\nexport const McpToolSchema = z.string().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/);\n\n/** The most an account call, its follow-up included, may serialize to. */\nexport const ACCOUNT_CALL_MAX_BYTES = 8 * 1024;\n\n/** How a tool's answer is read: its `structuredContent`; the JSON its text\n * items hold, joined in order; or its content items as they come. */\nexport const ACCOUNT_RESULTS = ['structured', 'json-text', 'content'] as const;\n\nconst RESULT_PATH = '[A-Za-z_][A-Za-z0-9_]{0,63}(?:\\\\.[A-Za-z_][A-Za-z0-9_]{0,63}){0,3}';\n/** An argument value that is exactly `{field}` is that input field's value, of\n * its own JSON type; one that is exactly `{result.<path>}`, in a follow-up\n * only, is the value at that path in the first call's result. Every other\n * value is sent as written: that is how a map pins a tool's settings. */\nexport const INPUT_PLACEHOLDER = /^\\{([A-Za-z_][A-Za-z0-9_]{0,63})\\}$/;\nexport const RESULT_PLACEHOLDER = new RegExp(`^\\\\{result\\\\.(${RESULT_PATH})\\\\}$`);\n\n/** A value at a path of a tool's result, and the values that mean a state. */\nconst AccountStateSchema = z.object({\n path: z.string().regex(new RegExp(`^${RESULT_PATH}$`)),\n values: z.array(z.string().min(1).max(64)).min(1).max(8),\n});\n\nconst AccountCallFields = {\n tool: McpToolSchema,\n /** The tool's `arguments`, a template (above). */\n args: z.record(z.string(), z.unknown()),\n result: z.enum(ACCOUNT_RESULTS),\n};\n\n/** A status call, sent every `everyS` seconds until its own result leaves\n * `running`; `failed` ends the call. `maxWaitS` counts from the first call. */\nconst AccountPollSchema = z.object({\n ...AccountCallFields,\n running: AccountStateSchema,\n failed: AccountStateSchema.optional(),\n everyS: z.number().int().min(1).max(30),\n maxWaitS: z.number().int().min(1).max(600),\n});\n\n/** The follow-up that fetches the result, when the first call does not hold\n * it: always, or only `when` the first result is in that state. The call\n * that bills is sent once and never again because its job is still running;\n * only `poll` repeats. */\nconst AccountStepSchema = z.object({\n when: AccountStateSchema.optional(),\n poll: AccountPollSchema.optional(),\n ...AccountCallFields,\n});\n\nexport const AccountCallSchema = z.object({\n ...AccountCallFields,\n next: AccountStepSchema.optional(),\n});\nexport type AccountCall = z.infer<typeof AccountCallSchema>;\n\nconst AccountSpecFields = z.object({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n label: LabelSchema.optional(),\n holds: z\n .object({\n WebSearch: z.string().min(1).max(64).optional(),\n WebFetch: z.string().min(1).max(64).optional(),\n })\n .optional(),\n output: z.enum(['json', 'text', 'media']).optional(),\n description: z.string().min(1).max(500),\n /** The connected account the call runs on: this client attaches the\n * credential it holds for it, and only while it is connected here. */\n source: z.string().regex(ACCOUNT_ID),\n /** The call on the account, in place of a paid spec's price and request. */\n mcp: AccountCallSchema,\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n requires: RequiresSchema,\n // A paid spec's own keys: an object naming them is no account spec.\n priceAtomic: OtherArm,\n request: OtherArm,\n payTo: OtherArm,\n});\n\n/** Every string in a template that is exactly a placeholder. */\nfunction placeholders(value: unknown): string[] {\n if (typeof value === 'string')\n return INPUT_PLACEHOLDER.test(value) || RESULT_PLACEHOLDER.test(value) ? [value] : [];\n if (Array.isArray(value)) return value.flatMap(placeholders);\n if (value && typeof value === 'object') return Object.values(value).flatMap(placeholders);\n return [];\n}\n\nfunction accountSpecProblems(spec: z.infer<typeof AccountSpecFields>, ctx: z.RefinementCtx): void {\n const issue = (message: string, path: (string | number)[]) =>\n ctx.addIssue({ code: 'custom', message, path });\n const { mcp } = spec;\n if (spec.source === BUILT_IN_SOURCE)\n issue(`an account service is never on ${BUILT_IN_SOURCE}`, ['source']);\n if (!(spec.requires ?? []).includes(MCP_ACCEPT))\n issue(`an account spec requires ${MCP_ACCEPT}`, ['requires']);\n if (Buffer.byteLength(JSON.stringify(mcp), 'utf8') > ACCOUNT_CALL_MAX_BYTES)\n issue(`the call must serialize to at most ${ACCOUNT_CALL_MAX_BYTES} bytes`, ['mcp']);\n // The first call bills, so a poll or follow-up never sends it again.\n if (mcp.next?.poll?.tool === mcp.tool)\n issue('the poll never repeats the call that bills', ['mcp', 'next', 'poll', 'tool']);\n if (mcp.next?.tool === mcp.tool)\n issue('the follow-up never repeats the call that bills', ['mcp', 'next', 'tool']);\n const properties = spec.input.properties;\n const fields = new Set(\n properties && typeof properties === 'object' ? Object.keys(properties) : [],\n );\n const calls: [(string | number)[], Record<string, unknown>, boolean][] = [\n [['mcp', 'args'], mcp.args, false],\n ];\n if (mcp.next?.poll) calls.push([['mcp', 'next', 'poll', 'args'], mcp.next.poll.args, true]);\n if (mcp.next) calls.push([['mcp', 'next', 'args'], mcp.next.args, true]);\n for (const [path, args, followUp] of calls)\n for (const value of placeholders(args)) {\n const field = INPUT_PLACEHOLDER.exec(value)?.[1];\n if (field === undefined && !followUp) issue('only a follow-up reads the first result', path);\n if (field !== undefined && !fields.has(field))\n issue(`${value} names no field of the input`, path);\n }\n}\n\n/** An account service's spec, as a lookup's `spec` answer carries it. */\nexport const AccountSpecSchema = AccountSpecFields.superRefine(accountSpecProblems);\nexport type AccountSpec = z.infer<typeof AccountSpecSchema>;\n\n/** An account service's spec under the offer id the agent calls it with. */\nexport const AccountOfferSpecSchema = AccountSpecFields.extend({ id: IdSchema }).superRefine(\n accountSpecProblems,\n);\nexport type AccountOfferSpec = z.infer<typeof AccountOfferSpecSchema>;\n\n/** Any spec an offer id can hold: paid from the balance, or a call on an account. */\nexport type AnyOfferSpec = OfferSpec | AccountOfferSpec;\n\nexport const isAccountSpec = <T extends object>(spec: T): spec is T & AccountSpec =>\n 'mcp' in spec && 'source' in spec;\n\n/** The specs on an `execute`, whose lead may be an account service's. */\nconst ExecuteSpecsSchema = z\n .array(z.union([OfferSpecSchema, AccountOfferSpecSchema]))\n .min(1)\n .max(8)\n .optional();\n\n/** Words this client shows the model itself, in its own line: one plain line. */\nconst PlainLine = (max: number) =>\n z\n .string()\n .min(1)\n .max(max)\n .refine((text) => !/[\\p{Cc}\\p{Cf}]/u.test(text), 'one plain line');\n\n/**\n * SERVICES THE USER PICKS BETWEEN, OR RUNS ALL OF. Sent only beside a\n * discovered offer, to a build that lists `catalog` in `accepts`. Each option\n * is a real offer: its own id, its own spec in `specs`, and its own one\n * payment, so `request({id, choice})` runs exactly the spec\n * `request({id: option.id})` would. `all` runs every option side by side, one\n * payment each. The set is the server's data: changing it is a deploy there,\n * not a release here. `input` names the open fields the options share, the\n * only ones an `all` call may carry.\n */\nexport const ChoicesSchema = z.object({\n group: PlainLine(64),\n default: PlainLine(64),\n input: z.array(PlainLine(64)).min(1).max(16),\n options: z\n .array(\n z.object({\n key: PlainLine(64),\n label: PlainLine(120),\n strength: PlainLine(300),\n id: IdSchema,\n }),\n )\n .min(2)\n .max(4),\n all: z.object({ totalAtomic: z.string().regex(/^\\d+$/) }),\n});\nexport type Choices = z.infer<typeof ChoicesSchema>;\n\n/** The word that runs every option, so no option may take it as its key. */\nexport const ALL_CHOICES = 'all';\n\n/**\n * A CHOICE NAMES ONLY WHAT THIS ANSWER CARRIES: each key and id once, `all`\n * free for the whole set, a spec for every option, and the default option is\n * the offer this answer's id already names. A set that breaks any of these is\n * a protocol error, and the turn falls back like any unreadable answer.\n */\nfunction checkChoices(\n decision: { id: string; specs?: { id: string }[] | undefined; choices?: Choices | undefined },\n ctx: z.RefinementCtx,\n): void {\n const { choices } = decision;\n if (choices === undefined) return;\n const issue = (message: string) => ctx.addIssue({ code: 'custom', path: ['choices'], message });\n const keys = choices.options.map((option) => option.key);\n const ids = choices.options.map((option) => option.id);\n if (new Set(keys).size !== keys.length) issue('each choice key is named once');\n if (new Set(ids).size !== ids.length) issue('each choice id is named once');\n if (keys.includes(ALL_CHOICES)) issue(`\"${ALL_CHOICES}\" runs every choice, so it is no key`);\n const specIds = new Set((decision.specs ?? []).map((spec) => spec.id));\n if (ids.some((id) => !specIds.has(id))) issue('every choice carries its spec');\n const fallback = choices.options.find((option) => option.key === choices.default);\n if (fallback === undefined) issue('the default is one of the choices');\n else if (fallback.id !== decision.id) issue(\"the default choice is this answer's own offer\");\n}\n\n/** One call's input, serialized, bounded as the server bounds it. */\nexport const MAX_INPUT_BYTES = 16 * 1024;\n\n/**\n * THE NATIVE CALL'S OWN INPUT, on a hook answer for a pending WebSearch or\n * WebFetch to a client that sends `settings`, only while the user turned on\n * automatic use and the pick fits its provider scope: the offer id to run\n * and the complete input the server built from that call's own query or URL\n * through the spec's `holds`. Run unchanged in the native call's place,\n * through the ordinary executor and the check before every call, or not at\n * all; never edited, merged or parsed here (`swap.ts`).\n */\nexport const BoundSchema = z.object({\n id: IdSchema,\n input: z\n .record(z.string(), z.unknown())\n .refine(\n (input) => Buffer.byteLength(JSON.stringify(input), 'utf8') <= MAX_INPUT_BYTES,\n `bound input must serialize to at most ${MAX_INPUT_BYTES} bytes`,\n ),\n});\nexport type Bound = z.infer<typeof BoundSchema>;\n\n/** The same answer on both calls: the hook's offer, and the tool's answer\n * when a query with no id found a service nobody curated. */\nconst DiscoveredSchema = z\n .object({\n action: z.literal('discovered'),\n id: IdSchema,\n candidate: DiscoveredCandidateSchema,\n /** THE LINE, FINISHED, as on `execute`: it carries the seller's\n * description and the input it takes. */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n choices: ChoicesSchema.optional(),\n requires: RequiresSchema,\n bound: BoundSchema.optional(),\n })\n .superRefine(checkHint)\n .superRefine(checkChoices);\n\n/**\n * AN ACCOUNT LEAD IS OFFERED ALONE, as a service this client runs on its own\n * connection: no endpoint, no balance price, in place of a native call only\n * through `bound` as any lead. Every other `execute` is as it always was, with\n * the URL it pays.\n */\nfunction checkExecute(\n decision: {\n id: string;\n capabilityId: string;\n providerPriceAtomic: string;\n endpoint?: string | undefined;\n specs?: AnyOfferSpec[] | undefined;\n delivery?: 'offer' | 'augment' | 'note' | undefined;\n augmentUrl?: string | undefined;\n },\n ctx: z.RefinementCtx,\n): void {\n const issue = (message: string, path: (string | number)[]) =>\n ctx.addIssue({ code: 'custom', message, path });\n const specs = decision.specs ?? [];\n const lead = specs.find(({ id }) => id === decision.id);\n if (!lead || !isAccountSpec(lead)) {\n if (specs.some((spec) => isAccountSpec(spec)))\n issue('an account service is only ever the lead', ['specs']);\n if (decision.endpoint === undefined) issue('an execute names the URL it pays', ['endpoint']);\n return;\n }\n if (specs.length > 1) issue('an account lead is offered alone', ['specs']);\n if (decision.endpoint !== undefined)\n issue('an account lead names no endpoint: this client calls its own account', ['endpoint']);\n if (decision.capabilityId !== lead.capabilityId)\n issue('the listing names the lead', ['capabilityId']);\n if (decision.providerPriceAtomic !== '0')\n issue('the balance pays an account lead nothing', ['providerPriceAtomic']);\n if (decision.delivery === 'augment' || decision.augmentUrl !== undefined)\n issue('an account lead is an offer', ['delivery']);\n}\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .object({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. An\n * account lead has none: this client calls the account it connected. */\n endpoint: z.string().min(1).max(2_048).optional(),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift. The same\n * bound as a discovered line's.\n */\n hint: z.string().min(1).max(2_000),\n specs: ExecuteSpecsSchema,\n /**\n * HOW THE OFFER IS DELIVERED, sent because this build lists `fields`.\n * `note` is the free docs lookup before a search, for a client that\n * also lists `note`: the line comes after the search. `augment` is the\n * same offer for a client that does not, with the `augmentUrl` that\n * client fetches. `offer` is every other line. This build shows only a\n * `note` after a search; any other free offer before one, `augment`\n * included, runs silent.\n */\n delivery: z.enum(['offer', 'augment', 'note']).optional(),\n augmentUrl: z.string().url().max(2_048).optional(),\n bound: BoundSchema.optional(),\n })\n .superRefine(checkHint)\n .superRefine(checkExecute),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.object({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n /**\n * A query with no id, answered with the spec of the service the server\n * picked under a fresh `id`: kept like a hook's, and never run in the same\n * call. `hint` is the line, with the skeleton of the next call:\n * `request({id, input: {...}})` with the required fields. What it needs\n * this client to understand is its spec's `requires`.\n */\n z\n .object({\n action: z.literal('spec'),\n id: IdSchema,\n spec: z.union([ToolSpecSchema, AccountSpecSchema]),\n hint: z.string().min(1).max(2_000),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.object({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n /**\n * The request's own settings hash, verbatim, on an answer the server\n * decided under the user's rules (to a client that lists `settings` in\n * `accepts`). The check before every call compares it with the rules\n * saved now (`settings-check.ts`); it names a rule set and authorizes\n * nothing.\n */\n settingsHash: SettingsHashSchema.optional(),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\n/**\n * ONE ROW OF THE TOOL LIST, as the free browse answers it: the tool's id, its\n * display name (a list entry's upstream name runs to 120 characters), what it\n * does, its price as the server writes it, and its kind. Read like every\n * answer here, with the server's own bounds. The id is the one field the model\n * sends back, so its alphabet is pinned; the text is flattened to one line\n * where it is shown (`tool.ts`).\n */\nconst BrowseRowSchema = z.object({\n id: z\n .string()\n .min(1)\n .max(200)\n .regex(/^[A-Za-z0-9._:-]+$/),\n label: z.string().min(1).max(120),\n does: z.string().min(1).max(500),\n price: z.string().min(1).max(32),\n free: z.boolean(),\n kind: z.string().min(1).max(120),\n});\nexport type BrowseRow = z.infer<typeof BrowseRowSchema>;\n\nconst BrowseResponseSchema = z.object({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n rows: z.array(BrowseRowSchema).max(200),\n});\nexport type BrowseResponse = z.infer<typeof BrowseResponseSchema>;\n\nconst Labelled = { id: TargetIdSchema, label: z.string().min(1).max(120) };\n\n/** How an account signs in: `oauth` is the MCP sign-in, `key` a pasted key\n * sent as `Authorization: <keyScheme> <key>`. */\nexport const SIGN_IN = ['oauth', 'key'] as const;\nexport type SignIn = (typeof SIGN_IN)[number];\nexport const KEY_SCHEMES = ['Bearer', 'Key'] as const;\nexport type KeyScheme = (typeof KEY_SCHEMES)[number];\n\n/** Where a connected account is called. A user's token goes here, so it is\n * https, with no credentials, query, fragment or trailing slash to make it\n * another server or carry anything else. One the user typed (`typed`) may\n * also be http on this machine (`localhost`, 127.0.0.0/8, `[::1]`); the\n * router's never is. */\nexport function isAccountUrl(value: string, opts: { typed?: boolean } = {}): boolean {\n const url = URL.canParse(value) ? new URL(value) : undefined;\n return (\n url !== undefined &&\n (url.protocol === 'https:' ||\n (opts.typed === true && url.protocol === 'http:' && isLoopbackHost(url.hostname))) &&\n !url.username &&\n !url.password &&\n !value.includes('?') &&\n !value.includes('#') &&\n !value.endsWith('/')\n );\n}\n\nconst twice = (keys: readonly string[]) => new Set(keys).size !== keys.length;\n\n/**\n * HOW THIS CLIENT CONNECTS AN ACCOUNT, on a source row of the identities read\n * because this build lists `mcp`: its MCP server, the sign-ins it takes, how a\n * pasted key is sent, and every tool its maps call, which the free\n * connect-time `tools/list` must hold for those maps to run on this machine.\n * `tenjin` never has one.\n */\nexport const ConnectableSchema = z\n .object({\n mcpUrl: z\n .string()\n .max(2_048)\n .refine(\n (value) => isAccountUrl(value),\n 'an https URL with no credentials, query, fragment or trailing slash',\n ),\n signIn: z.array(z.enum(SIGN_IN)).min(1).max(2),\n keyScheme: z.enum(KEY_SCHEMES).optional(),\n expectTools: z.array(McpToolSchema).min(1).max(64),\n })\n .superRefine((connectable, ctx) => {\n const issue = (message: string, path: string[]) =>\n ctx.addIssue({ code: 'custom', message, path });\n if (twice(connectable.signIn)) issue('each sign-in is listed once', ['signIn']);\n if (connectable.signIn.includes('key') !== (connectable.keyScheme !== undefined))\n issue('a key sign-in says how the key is sent, and only it does', ['keyScheme']);\n if (twice(connectable.expectTools)) issue('each tool is listed once', ['expectTools']);\n });\nexport type Connectable = z.infer<typeof ConnectableSchema>;\n\n/**\n * EVERY ID A SETTING CAN NAME, free: the categories with their tasks, the\n * tasks, providers, sellers, services (with the task, providers and seller\n * each is identified by) and sources, each with its label. `tenjin config`\n * resolves a typed name against it and names saved rules by it; it never\n * decides with it. Built by the server from its catalog, with no gate, no\n * model and no payment. Read tolerantly like every answer here.\n */\nconst IdentitiesResponseSchema = z.object({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n categories: z.array(z.object({ ...Labelled, tasks: z.array(TargetIdSchema).max(256) })).max(256),\n /** `speed`: a task the speed preference changes (it has a speed criterion). */\n tasks: z\n .array(\n z.object({\n ...Labelled,\n category: TargetIdSchema.optional(),\n speed: z.literal(true).optional(),\n }),\n )\n .max(1_024),\n providers: z.array(z.object(Labelled)).max(2_048),\n sellers: z.array(z.object(Labelled)).max(2_048),\n services: z\n .array(\n z.object({\n ...Labelled,\n task: TargetIdSchema.optional(),\n providers: z.array(TargetIdSchema).max(16),\n seller: TargetIdSchema.optional(),\n }),\n )\n .max(4_096),\n /** `connectable`, for a build that lists `mcp`: an account this client can\n * connect, never `tenjin`. */\n sources: z\n .array(\n z\n .object({ ...Labelled, connectable: ConnectableSchema.optional() })\n .refine(\n ({ id, connectable }) => connectable === undefined || isAccountId(id),\n 'only an account id is connectable, never tenjin',\n ),\n )\n .max(64),\n});\nexport type IdentitiesResponse = z.infer<typeof IdentitiesResponseSchema>;\n\n/** A hook answer reread from disk (`decided.ts`), held to the same schema as\n * the router's: anything else reads as absent. */\nexport function parseHookResponse(value: unknown): HookResponse | undefined {\n const parsed = HookResponseSchema.safeParse(value);\n return parsed.success ? parsed.data : undefined;\n}\n\n/** The identities read reread from disk (`identities.ts`), held to the same\n * schema as the router's answer: anything else reads as absent. */\nexport function parseIdentities(value: unknown): IdentitiesResponse | undefined {\n const parsed = IdentitiesResponseSchema.safeParse(value);\n return parsed.success ? parsed.data : undefined;\n}\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** The reason code of an offer this build skipped for a feature it lacks. */\nexport const REQUIRES_UNMET = 'requires_unmet';\n\n/** An offer skipped for features this build lacks, named by its id. */\nexport interface SkippedOffer {\n id: string;\n missing: string[];\n}\n\n/**\n * A BACKSTOP, NOT A FILTER. The server sends only `requires` tokens a client\n * lists in `accepts`, so a client meets an unmet one only when that rule was\n * broken, and then it fails safe. A spec whose `requires` names a feature this\n * build lacks is dropped. When the answer's line names what was dropped (the\n * answer's own offer, through its `requires`, its own spec or a `spec`\n * answer's spec; another spec whose id the line carries; or any option of its\n * choice set), the line can no longer be shown as written, so the whole\n * answer becomes a `native` that names the missing features: a named skip,\n * never a guess. A dropped spec the line does not name is only dropped.\n */\nexport function withoutUnmet<T extends HookDecision | ToolDecision>(\n decision: T,\n): { decision: T; skipped: SkippedOffer[] } {\n if (decision.action === 'native' || decision.action === 'needs_input') {\n return { decision, skipped: [] };\n }\n const specs = 'specs' in decision ? (decision.specs ?? []) : [];\n const own = [\n ...unmetRequires('requires' in decision ? decision.requires : undefined),\n ...(decision.action === 'spec' ? unmetRequires(decision.spec.requires) : []),\n ...('id' in decision ? unmetRequires(specs.find((s) => s.id === decision.id)?.requires) : []),\n ];\n if (own.length > 0) {\n const missing = [...new Set(own)];\n const id = 'id' in decision ? decision.id : decision.capabilityId;\n return { decision: unmetRefusal(missing) as T, skipped: [{ id, missing }] };\n }\n const skipped = specs.flatMap((spec) => {\n const missing = unmetRequires(spec.requires);\n return missing.length > 0 ? [{ id: spec.id, missing }] : [];\n });\n if (skipped.length === 0) return { decision, skipped };\n const options = new Set(\n decision.action === 'discovered' ? (decision.choices?.options ?? []).map((o) => o.id) : [],\n );\n const hint = 'hint' in decision ? decision.hint : '';\n if (skipped.some((s) => options.has(s.id) || hint.includes(s.id))) {\n const missing = [...new Set(skipped.flatMap((s) => s.missing))];\n return { decision: unmetRefusal(missing) as T, skipped };\n }\n const gone = new Set(skipped.map((s) => s.id));\n return {\n decision: { ...decision, specs: specs.filter((spec) => !gone.has(spec.id)) } as T,\n skipped,\n };\n}\n\nfunction unmetRefusal(missing: string[]) {\n const named = missing.map((token) => `\\`${token}\\``).join(', ');\n return {\n action: 'native' as const,\n reason: `This offer needs ${named}, which this build of tenjin-cli does not have, so it was skipped and no provider was paid.`,\n diagnostics: {\n reasonCode: REQUIRES_UNMET,\n stage: 'client',\n missing,\n nextAction:\n 'Use your own tools for this one. A newer tenjin-cli (`tenjin update`) can run it.',\n },\n };\n}\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool' | 'browse';\n\n/**\n * What this client can act on beyond the curated answers, sent on every call.\n * Each token names one kind of feature this build parses and runs, and the\n * server ignores a token it does not know, so the list only ever grows.\n * `label` takes each catalog service's display name on its spec and both\n * `execute` answers, and the offer line that starts at it. `fields` takes\n * each spec's `holds` and `output`, and the hook `execute`'s `delivery` and\n * `augmentUrl`. `note` asks for `delivery: \"note\"` on the free docs lookup\n * before a search, whose line this build shows after the search, in place of\n * the `augment` an older build fetched. `catalog` takes Tenjin's reviewed\n * list of third-party services as\n * `discovered` offers under their catalog ids, with each spec's `holds` and\n * `output`, and `choices`, a set of options the user picks between or runs\n * all of, beside a discovered offer from a compare group. A build that sends\n * `discovered` in its place gets the same services under their\n * `discovered:tenjin:` ids. `spec` asks for each offered service's request\n * spec beside its line, and for the picked service's spec in place of a\n * decision on a query with no id, which only a build that runs them can\n * take. `jobs` asks for each spec's `job`,\n * for the services that never answer inline, and for `count` on a media\n * offer's line. `headers` asks for a spec's `request.headers`, the fixed\n * headers the catalog sets on a service's call (a provider's beta opt-in),\n * with the pins those headers unlock: `buildSpecRequest` sends them. A build\n * without a token would drop the field as unknown, so a spec that cannot run\n * without it lists the token in `requires`. `tolerant` says this build reads\n * every answer as a tolerant reader and honors `requires` ({@link withoutUnmet}).\n * Once the server reads it (tenjin R2), it sends a new field, `requires`\n * included, only to a client that lists it, and today's shape to one that\n * does not, which is every release from before it and reads strictly. `bazaar` widens discovery to the open\n * Bazaar and is sent only while `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = [\n 'catalog',\n 'spec',\n 'label',\n 'fields',\n 'jobs',\n 'headers',\n 'note',\n 'tolerant',\n];\nexport const BAZAAR_ACCEPT = 'bazaar';\nexport const FREE_QUERY_ACCEPT = 'free-query';\n\n/** Every feature this build has, which a `requires` list is read against:\n * `bazaar` included, which it runs whether or not it asks for one. */\nconst CLIENT_FEATURES: ReadonlySet<string> = new Set([\n ...CLIENT_ACCEPTS,\n BAZAAR_ACCEPT,\n FREE_QUERY_ACCEPT,\n SETTINGS_ACCEPT,\n MCP_ACCEPT,\n]);\n\n/** The features a `requires` list names that this build lacks; none when it\n * has them all. */\nexport function unmetRequires(requires: readonly string[] | undefined): string[] {\n return (requires ?? []).filter((token) => !CLIENT_FEATURES.has(token));\n}\n\n/** The `accepts` this build sends, with the open Bazaar or without it, and\n * `settings` beside the `settings` field, which every production routing\n * call carries (also when the user has no rules). `mcp` rides with it: a\n * call on a connected account is offered only for an account the\n * settings' `sources` names, so it means nothing without them. It takes a\n * spec whose call is an MCP tool call on that account, the `execute` that\n * offers one with no `endpoint`, `connectable` on the identities read, and\n * the `{refused}` re-ask ({@link requestRefused}). */\nexport function acceptsFor(bazaar: boolean, settings = false): string[] {\n return [\n ...CLIENT_ACCEPTS,\n ...(bazaar ? [BAZAAR_ACCEPT] : []),\n ...(settings ? [SETTINGS_ACCEPT, MCP_ACCEPT] : []),\n ];\n}\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route ignores a field it does not know (the tolerant\n * contract), so a new optional field reaches a server that predates it as\n * nothing at all.\n *\n * `improve: true` rides only while the person has turned on \"Help improve\n * routing\" (`router.improve`): the server then keeps this call's sealed packet\n * beside its decision row, with no expiry, until they turn it off. Absent, it\n * keeps nothing past the id's 15 minutes.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone. `sessionId` is the harness's own session id, which the\n * server uses only so one session is not offered the same discovered service\n * twice.\n */\nexport function buildHookBody(\n packet: Packet,\n extras: {\n sessionId?: string;\n accepts?: readonly string[];\n harness?: Harness;\n improve?: boolean;\n budgetMs?: number;\n settings?: WireSettings;\n } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(extras.sessionId !== undefined ? { sessionId: extras.sessionId } : {}),\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n ...(extras.harness !== undefined ? { harness: extras.harness } : {}),\n ...(extras.budgetMs !== undefined ? { budgetMs: extras.budgetMs } : {}),\n packet,\n ...(extras.improve === true ? { improve: true } : {}),\n // A SIBLING OF THE PACKET, never inside it: the packet is what the\n // server's model reads, and the user's settings are for code alone.\n ...(extras.settings !== undefined ? { settings: extras.settings } : {}),\n };\n}\n\n/** The exact body the tool call sends. `id` is the offer the query is for,\n * sent only for an offer with no spec kept; `gateHint` is evidence, never\n * authority; `improve` as on the hook body. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\n gateHint?: GateHint;\n accepts?: readonly string[];\n harness?: Harness;\n improve?: boolean;\n settings?: WireSettings;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n ...(request.accepts !== undefined ? { accepts: [...request.accepts] } : {}),\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n ...(request.improve === true ? { improve: true } : {}),\n ...(request.settings !== undefined ? { settings: request.settings } : {}),\n };\n}\n\n/**\n * THE RE-ASK AFTER AN ACCOUNT REFUSED (plan 37, review round 1): the usual\n * envelope with `refused`, the id of the offer the account refused, and no\n * query. The server routes that offer's own turn again with the account left\n * out for this one answer, under the settings sent, and answers as it answers\n * a query: an offer, or native.\n */\nexport function buildRefusedBody(request: {\n refused: string;\n accepts: readonly string[];\n harness?: Harness;\n settings?: WireSettings;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n refused: request.refused,\n accepts: [...request.accepts],\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n ...(request.settings !== undefined ? { settings: request.settings } : {}),\n };\n}\n\n/** The free browse of the tool list: `browse` is the need, or `\"\"` for every\n * tool by kind. No gate call and no Jev on the server. */\nexport function buildBrowseBody(request: {\n browse: string;\n accepts: readonly string[];\n harness?: Harness;\n settings?: WireSettings;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n browse: request.browse,\n accepts: [...request.accepts],\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n ...(request.settings !== undefined ? { settings: request.settings } : {}),\n };\n}\n\n/** A browse row's spec, or a query bound to that selected free tool. */\nexport function buildToolSpecBody(request: {\n tool: string;\n query?: string;\n accepts: readonly string[];\n harness?: Harness;\n settings?: WireSettings;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n tool: request.tool,\n ...(request.query !== undefined ? { query: request.query } : {}),\n accepts: [...request.accepts],\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n ...(request.settings !== undefined ? { settings: request.settings } : {}),\n };\n}\n\n/** The free identities read: every id a setting can name. No settings and\n * no harness ride on it: its answer is the same for every client. */\nexport function buildIdentitiesBody(): Record<string, unknown> {\n return { schemaVersion: 1, identities: true, accepts: acceptsFor(false, true) };\n}\n\n/**\n * THE PAID ROUTE'S `warm` CALL, a channel deposit's carrier. The payer's\n * background top-up sends it and nothing else does: the batch-settlement spec\n * has no deposit-only payload, so the deposit rides a paid request the server\n * answers in code, with no gate and nothing stored, and settles at $0.\n */\nexport function buildWarmBody(\n extras: { accepts?: readonly string[]; harness?: Harness } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n warm: true,\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n ...(extras.harness !== undefined ? { harness: extras.harness } : {}),\n };\n}\n\n/** The `warm` answer, read tolerantly like every answer: no decision. */\nconst WarmResponseSchema = z.object({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n warm: z.literal(true),\n});\n\n/** Whether a body is the `warm` answer. A router without the form answers\n * anything else: a 400 for an unknown field, or a decision. */\nexport function isWarmAnswer(body: unknown): boolean {\n return WarmResponseSchema.safeParse(body).success;\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(\n kind: CallKind,\n value: unknown,\n): { success: boolean; data?: unknown } {\n const parsed = schemaFor(kind).safeParse(value);\n return parsed.success ? { success: true, data: parsed.data } : { success: false };\n}\n\nfunction schemaFor(kind: CallKind) {\n return kind === 'hook'\n ? HookResponseSchema\n : kind === 'tool'\n ? ToolResponseSchema\n : BrowseResponseSchema;\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n /** `experimental.bazaar`: add {@link BAZAAR_ACCEPT}, so a service from the\n * open Bazaar may come back. Off by default: curated and the Tenjin list. */\n acceptsBazaar?: boolean;\n /**\n * The host asking. Automatic routing avoids services the host already covers;\n * explicit browsing and selection retain every runnable service. Absent is\n * `claude`, and every production caller sends it.\n */\n harness?: Harness;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n /** The payer, inside `tenjin mcp`: it sends the call and pays the routing\n * fee with the stock x402 client. Absent, the call goes unpaid. */\n route?: DecisionRoute;\n /** `router.improve`: the person turned on \"Help improve routing\", so the\n * call says `improve: true`. Off by default. */\n improve?: boolean;\n /**\n * The user's settings as the wire carries them, resolved from the global\n * file on every call (`routerSettings`) and never cached: sent with\n * `settings` in `accepts` on every routing form. Absent only in tests and\n * the free identities read.\n */\n settings?: WireSettings;\n}\n\n/** One decision's payment transport; do not share it between concurrent decisions.\n * `send` throws {@link RouteSkipped} when it has\n * no usable answer for the call, which then is skipped, or read as the\n * transport failure it carries in `unreached`. */\nexport interface DecisionRoute {\n send: (url: string, options: HttpRequestOptions) => Promise<HttpResult>;\n /** What this route's own calls deposited into the routing channel and the\n * router took (only on a router with no `warm` form), 0n for none: the\n * caller says so once, where it is read. */\n deposited?: () => bigint;\n /** What the payer's background top-ups deposited since this was last\n * read, 0n for none, and taken by the read. Only a hook leg reads it, so\n * the person is told, in its `systemMessage`. */\n toppedUp?: () => bigint;\n /** The most recent call completed a signed routing payment successfully.\n * Free answers, background top-ups and payments still settling do not count. */\n paid?: () => boolean;\n}\n\n/** The paid route gave this call no answer: the wallet locked, low or over\n * its spend limits, the fee quoted above the ceiling, the channel busy or\n * being topped up, or the payment failed. */\nexport class RouteSkipped extends Error {\n /** `unreached`: the paid call could not reach the router\n * ({@link isUnreachable}), so the call reads as that transport failure.\n * `quotedAtomic`: the fee the router quoted, when the payer read one.\n * `answered`: the router answered a request of this call (its 402, say). */\n readonly unreached: FetchJsonFailure | undefined;\n readonly quotedAtomic: bigint | undefined;\n readonly answered: boolean;\n constructor(\n readonly why: string,\n opts: { unreached?: FetchJsonFailure; quotedAtomic?: bigint; answered?: boolean } = {},\n ) {\n super(`routing fee not paid: ${why}`);\n this.unreached = opts.unreached;\n this.quotedAtomic = opts.quotedAtomic;\n this.answered = opts.answered === true;\n }\n}\n\n/** Another session's call was in flight on the wallet's routing channel. */\nexport const CHANNEL_BUSY = 'channel_busy';\n/** The paid call got no answer, a refused payment or a server error. */\nexport const PAYMENT_FAILED = 'payment_failed';\n/** The payment went out and the call's budget ran out before its answer:\n * no fault. `tenjin mcp` lets the request finish, so it is recorded. */\nexport const DEADLINE_AFTER_PAYMENT_SENT = 'deadline_after_payment_sent';\n/** The route asked for the fee, and this call had no payer to pay it. */\nexport const NO_PAYER = 'no_payer';\n/** The channel needed a deposit, and this process's background top-up did\n * not land inside the call's budget: no fault. The next call pays from it if\n * it lands, or gets its refusal if it was refused. */\nexport const TOPPING_UP = 'topping_up';\n/** The background top-up got no usable answer: the router rate-limited it,\n * or no connection reached it. No fault, as on any routing call, and never\n * the machine-wide unreachable pause: the call it served reached the router.\n * The top-up is tried again after its backoff. */\nexport const TOP_UP_UNAVAILABLE = 'top_up_unavailable';\n/** The channel needed a deposit, which only the background top-up makes, and\n * this process's could not make it now (another session's top-up of the same\n * wallet is in flight, or the channel was busy): no fault. */\nexport const DEPOSIT_DEFERRED = 'deposit_deferred';\n\nexport type DecisionOutcome<T> =\n /** `skipped`: offers in it this build cannot run, already taken out\n * ({@link withoutUnmet}). */\n | { status: 'decided'; decision: T; skipped?: SkippedOffer[] }\n /** No routing answer: the turn goes without one. */\n | {\n status: 'failed';\n reason: string;\n errorCode?: string;\n /** The router could not be reached at all ({@link isUnreachable}). */\n unreachable?: true;\n /** No answer came back at all: a transport failure or a timeout. */\n noAnswer?: true;\n }\n /** The routing fee was not paid ({@link RouteSkipped}, {@link NO_PAYER}):\n * nothing was routed, and the native tool runs. `quotedAtomic`: the fee\n * the router quoted, when the payer read one. `answered`: the router\n * answered first, so it is reachable. */\n | { status: 'skipped'; why: string; quotedAtomic?: bigint; answered?: true };\n\n/**\n * ONE ROUTING CALL, IN TWO FORMS, ON THE PAID ROUTE. The hook sends\n * `{ packet }`: the backend runs the gate, and on `execute` stores that packet\n * under an id and answers with each offered service's spec. The tool sends\n * `{ query }`, which the backend answers with the spec of the service its gate\n * picks, or `{ query, id }` for the free docs offer, which has no spec and is\n * bound from the query. Every provider call is built here, from a spec, or for\n * the docs lookup by the backend from the query.\n *\n * ONE REQUEST, PAID OR SKIPPED. A call the payer cannot pay is `skipped` at\n * once: no second request, on any route. With no payer the call goes unpaid,\n * and a route that asks for the fee (a 402) is a skip with {@link NO_PAYER};\n * a route that charges nothing (the fee off, in development) answers it.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet; sessionId?: string },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n sessionId?: string;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(ROUTE_PAID_PATH, deps.baseUrl).toString();\n const timeoutMs = deps.timeoutMs ?? deps.ctx.flags.timeout;\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet, {\n ...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true, deps.settings !== undefined),\n harness: deps.harness ?? 'claude',\n improve: deps.improve === true,\n budgetMs: Math.min(5_000, Math.max(0, timeoutMs)),\n ...(deps.settings !== undefined ? { settings: deps.settings } : {}),\n })\n : buildToolBody({\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true, deps.settings !== undefined),\n harness: deps.harness ?? 'claude',\n improve: deps.improve === true,\n ...(deps.settings !== undefined ? { settings: deps.settings } : {}),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n return kind === 'hook'\n ? sendPaid(url, options, HookResponseSchema, deps)\n : sendPaid(url, options, ToolResponseSchema, deps);\n}\n\n/**\n * `{refused}` ON THE PAID ROUTE, paid or skipped like a query\n * ({@link requestDecision}), and answered the same way: an offer, or native.\n * It needs `mcp`, which rides with the settings.\n */\nexport async function requestRefused(\n refused: string,\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>> {\n const url = new URL(ROUTE_PAID_PATH, deps.baseUrl).toString();\n return sendPaid(\n url,\n {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody: buildRefusedBody({\n refused,\n accepts: acceptsFor(deps.acceptsBazaar === true, deps.settings !== undefined),\n harness: deps.harness ?? 'claude',\n ...(deps.settings !== undefined ? { settings: deps.settings } : {}),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n },\n ToolResponseSchema,\n deps,\n );\n}\n\n/** One request on the paid route: sent by the payer, or unpaid with none. */\nasync function sendPaid<R extends HookResponse | ToolResponse>(\n url: string,\n options: HttpRequestOptions,\n schema: z.ZodType<R>,\n deps: Pick<DecisionDeps, 'route'>,\n): Promise<DecisionOutcome<R>> {\n let response: HttpResult;\n try {\n response = await (deps.route?.send ?? httpRequest)(url, options);\n } catch (err) {\n if (!(err instanceof RouteSkipped)) throw err;\n if (err.unreached !== undefined) return readOffer(err.unreached, schema);\n return {\n status: 'skipped',\n why: err.why,\n ...(err.quotedAtomic !== undefined ? { quotedAtomic: err.quotedAtomic } : {}),\n ...(err.answered ? { answered: true as const } : {}),\n };\n }\n if (deps.route === undefined && response.ok && response.status === 402) {\n return { status: 'skipped', why: NO_PAYER, answered: true };\n }\n return readOffer(response, schema);\n}\n\n/**\n * THE TWO FREE READS OF THE TOOL LIST. `{browse}` lists the tools that fit a\n * need (or all of them, by kind, for `\"\"`), and `{tool}` answers a browse\n * row's id with that tool's spec under a fresh offer id, exactly as a query\n * with no id is answered. Neither makes a gate call on the server, neither is\n * charged the routing fee, and neither pays anything here, so both always take\n * the free route: `deps.route` is never read.\n */\nexport async function requestBrowse(\n browse: string,\n deps: Omit<DecisionDeps, 'route'>,\n): Promise<DecisionOutcome<BrowseResponse>> {\n return readDecision(\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody: buildBrowseBody({\n browse,\n accepts: acceptsFor(deps.acceptsBazaar === true, deps.settings !== undefined),\n harness: deps.harness ?? 'claude',\n ...(deps.settings !== undefined ? { settings: deps.settings } : {}),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n BrowseResponseSchema,\n );\n}\n\n/** `{tool}` reads a spec; `{tool, query}` binds a free lookup without paid routing. */\nexport async function requestToolSpec(\n tool: string,\n deps: Omit<DecisionDeps, 'route'>,\n query?: string,\n): Promise<DecisionOutcome<ToolResponse>> {\n return readOffer(\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody: buildToolSpecBody({\n tool,\n ...(query !== undefined ? { query } : {}),\n accepts: [\n ...acceptsFor(deps.acceptsBazaar === true, deps.settings !== undefined),\n FREE_QUERY_ACCEPT,\n ],\n harness: deps.harness ?? 'claude',\n ...(deps.settings !== undefined ? { settings: deps.settings } : {}),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n ToolResponseSchema,\n );\n}\n\n/**\n * EVERY ID A SETTING CAN NAME, ALWAYS FREE: no gate, no model, no payment, so\n * it takes the free route whatever `deps.route` says. `tenjin config` resolves\n * a typed name against it before it writes anything.\n */\nexport async function requestIdentities(\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl' | 'timeoutMs'>,\n): Promise<DecisionOutcome<IdentitiesResponse>> {\n return readDecision(\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody: buildIdentitiesBody(),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n IdentitiesResponseSchema,\n );\n}\n\n/** Why a call from a spec stopped before anything was signed: the input did\n * not fit, the live terms were not the spec's, the provider answered\n * something else, it could not be reached, or the wallet could not pay. */\nexport type UnpaidReason = 'input' | 'terms' | 'provider' | 'unreachable' | 'wallet';\n\n/** How a call run from a request spec ended, for the server's offer-to-call\n * count. No text: the id, the outcome, the provider's status and the time. */\nexport interface SpecOutcome {\n id: string;\n /** `unpaid`: stopped before anything was signed, which the server never\n * counts as the offer taken. `running`: paid, and the seller was still\n * rendering when the call ended. */\n status: 'fulfilled' | 'unverified' | 'failed' | 'needs_approval' | 'unpaid' | 'running';\n /** On `unpaid` only, where the server requires it. */\n reason?: UnpaidReason;\n httpStatus?: number;\n ms?: number;\n /** The path that made the call, when it was not an ordinary request:\n * `swap`, a native search or fetch answered in place. */\n via?: 'swap';\n}\n\n/**\n * Why a shown offer was never taken. `expired`: its 15 minutes ran out with no\n * `request` call naming it. `native_after_offer`: the same agent in the same\n * session made a native WebSearch or WebFetch call while it was still untaken.\n */\nexport type IgnoredReason = 'expired' | 'native_after_offer';\n\n/** An offer the host was shown and did not take: its id and why, no text. */\nexport interface IgnoredOutcome {\n id: string;\n status: 'ignored';\n reason: IgnoredReason;\n}\n\n/** The outcome report's own deadline: it is telemetry and never holds a result. */\nexport const OUTCOME_TIMEOUT_MS = 3_000;\n\n/**\n * TELL THE SERVER A SPEC WAS USED. The client called and paid the provider\n * itself, so this is the only word the server gets that its offer was taken,\n * or that a call for it stopped before payment and why, or that it was shown\n * and never taken. Never throws and never waits on anything the caller needs:\n * a lost report costs one count.\n */\nexport async function reportSpecOutcome(\n outcome: SpecOutcome | IgnoredOutcome,\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl' | 'harness'>,\n): Promise<void> {\n try {\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildOutcomeBody(outcome, deps.harness ?? 'claude'),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n // Telemetry only.\n }\n}\n\n/**\n * The exact body of an outcome report, pinned to the shared fixtures. Built\n * field by field, so it NEVER CARRIES `result`: a paid call that ran is not a\n * call that helped, and the useful rate comes from labelled samples, not from\n * this client's say-so. The server keeps reading `result` from custom setups.\n */\nexport function buildOutcomeBody(\n outcome: SpecOutcome | IgnoredOutcome,\n harness?: Harness,\n): Record<string, unknown> {\n const spec: Partial<SpecOutcome> = outcome.status === 'ignored' ? {} : outcome;\n return {\n schemaVersion: 1,\n id: outcome.id,\n ...(harness !== undefined ? { harness } : {}),\n status: outcome.status,\n ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),\n ...(spec.httpStatus !== undefined ? { httpStatus: spec.httpStatus } : {}),\n ...(spec.ms !== undefined ? { ms: Math.max(0, Math.round(spec.ms)) } : {}),\n ...(spec.via !== undefined ? { via: spec.via } : {}),\n };\n}\n\n/**\n * The `forget` form, pinned to the shared fixture: delete every packet the\n * server kept for this install. The install is the `tenjin-install-id` header\n * the transport already sends to Tenjin's origins, so the body names nothing.\n */\nexport function buildForgetBody(): Record<string, unknown> {\n return { schemaVersion: 1, forget: 'samples' };\n}\n\n/**\n * ASK THE SERVER TO DELETE WHAT \"HELP IMPROVE ROUTING\" KEPT, on the free\n * route, under the outcome report's short deadline. Never throws: the answer\n * is whether it was done, or why not, for the caller to say.\n */\nexport async function requestForget(\n deps: Pick<DecisionDeps, 'baseUrl' | 'fetchImpl'>,\n): Promise<{ ok: true } | { ok: false; reason: string }> {\n try {\n const response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildForgetBody(),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n if (!response.ok) return { ok: false, reason: fetchFailureToCliError(response).message };\n if (response.status >= 200 && response.status < 300) return { ok: true };\n return { ok: false, reason: `the router endpoint answered ${response.status}` };\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) };\n }\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason.\n if (!response.ok) {\n return {\n status: 'failed',\n reason: fetchFailureToCliError(response).message,\n ...(isUnreachable(response) ? { unreachable: true as const } : {}),\n ...(response.status === undefined ? { noAnswer: true as const } : {}),\n };\n }\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** A hook or tool answer, read, with each offer this build cannot run taken\n * out ({@link withoutUnmet}). */\nfunction readOffer<R extends HookResponse | ToolResponse>(\n response: HttpResult,\n schema: z.ZodType<R>,\n): DecisionOutcome<R> {\n const read = readDecision(response, schema);\n if (read.status !== 'decided') return read;\n const { decision, skipped } = withoutUnmet(read.decision.decision);\n return {\n ...read,\n decision: { ...read.decision, decision },\n ...(skipped.length > 0 ? { skipped } : {}),\n };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n\n/** A dropped socket, which a fresh connection usually gets past. */\nconst RESET_CODES = new Set(['ECONNRESET', 'UND_ERR_SOCKET']);\n\n/**\n * A ROUTER THAT CANNOT BE REACHED: the transport named the layer that refused\n * the connection (DNS, TLS, a refused connection, a proxy refusing the tunnel)\n * and no status came back. Never the call's own timeout: that is the gate's\n * few seconds, and a slow decision or a cold start must not take the router\n * away from every session. Never a status, even with a body that failed to\n * read, and never a reset socket, which a fresh connection usually gets past.\n */\nexport function isUnreachable(failure: FetchJsonFailure): boolean {\n return (\n failure.kind === 'network' &&\n failure.status === undefined &&\n failure.transport !== undefined &&\n !RESET_CODES.has(failure.transport.code ?? '')\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiCO,IAAM,cAAc;AAEpB,IAAM,kBAAkB;AAO/B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAAA,EACxC,MAAM,iBACH,OAAO,EACP,IAAI,MAAM,IAAI,EACd,SAAS;AACd,CAAC;AAED,IAAM,iBAAiB,iBAAE,OAAO;AAAA;AAAA;AAAA,EAG9B,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACtD,cAAc,iBAAE,OAAO,iB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