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/agent-tools.ts","../src/router/router-memo.ts"],"sourcesContent":["import { readdir, readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { LEGACY_MCP_SERVER_NAME, LEGACY_REQUEST_TOOL, requestToolName } from './names';\n\n/**\n * CAN THIS SUBAGENT CALL `request` AT ALL? An offer to an agent whose definition\n * leaves the tool out is a line it cannot act on, and a router call spent to\n * write it. Claude Code defines a custom agent in a Markdown file whose\n * frontmatter may carry `tools:` (an allowlist) and `disallowedTools:`; this\n * reads that, and nothing else, and never writes to it.\n *\n * ONLY `allowed` IS ACTED ON. A subagent is redirected or offered a lookup\n * only when this KNOWS it can make the call: a definition whose tools cover\n * the request tool (or that has no `tools:` and so inherits everything), or a\n * built-in in {@link MCP_INHERITING_BUILTINS}. Every other built-in, and any\n * type with no definition this can find or read, is `unknown`, and `unknown`\n * gets no router call: `claude-code-guide` ships with Bash, Read, WebFetch and\n * WebSearch and no MCP tools, and denying its WebFetch would strand it.\n *\n * WHERE A DEFINITION LIVES, in the harness's own precedence: the project's\n * `.claude/agents` (from `cwd` up to the filesystem root, nearest first), then\n * `~/.claude/agents`, then an installed plugin's `agents/` for a `plugin:agent`\n * type. A file is found by its name first and by its frontmatter `name:`\n * second, because the type is the `name:` and the file name only usually\n * matches it.\n */\n\nexport type RequestToolAccess = 'allowed' | 'excluded' | 'unknown';\n\n/**\n * The built-in agent types that have no definition file and still inherit MCP\n * tools, so can call the request tool. From Claude Code's own Agent tool\n * listing (2.1.28x): `general-purpose` has every tool, and `Explore` and `Plan`\n * exclude only editing and agent tools, never MCP. Built-ins with a fixed tool\n * list, such as `claude-code-guide` (Bash, Read, WebFetch, WebSearch) and\n * `statusline-setup` (Read, Edit), are deliberately absent.\n */\nexport const MCP_INHERITING_BUILTINS: ReadonlySet<string> = new Set([\n 'general-purpose',\n 'Explore',\n 'Plan',\n]);\n\nexport interface AgentLookup {\n cwd?: string;\n homeDir: string;\n}\n\nconst MAX_AGENT_FILE_BYTES = 256 * 1024;\nconst TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;\n\nexport async function requestToolAccess(\n agentType: string | undefined,\n lookup: AgentLookup,\n tool: string = requestToolName(),\n): Promise<RequestToolAccess> {\n if (agentType === undefined || !TYPE_RE.test(agentType)) return 'unknown';\n try {\n const text = await findDefinition(agentType, lookup);\n if (text !== null) return accessOf(text, tool);\n return MCP_INHERITING_BUILTINS.has(agentType) ? 'allowed' : 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n/**\n * What one definition's frontmatter says about the request tool, named as the\n * leg's harness exposes it (`tool`).\n *\n * THE OLD NAME, AFTER THE RENAME. An agent whose `tools:` names only\n * `mcp__x402__request` cannot call the plugin's tool, so it counts as excluded\n * and doctor names the new name to add. One whose `disallowedTools:` names the\n * old tool or server meant to keep paid lookups out, so it stays excluded.\n * SHIM: the old-name branch goes on or after 2026-12-01.\n */\nexport function accessOf(definition: string, tool: string = requestToolName()): RequestToolAccess {\n const frontmatter = frontmatterOf(definition);\n if (frontmatter === null) return 'unknown';\n const disallowed = listField(frontmatter, 'disallowedTools');\n if (\n disallowed !== undefined &&\n disallowed.some((entry) => namesRequestTool(entry, tool) || namesLegacyTool(entry))\n ) {\n return 'excluded';\n }\n const tools = listField(frontmatter, 'tools');\n if (tools === undefined) return 'allowed';\n return tools.some((entry) => namesRequestTool(entry, tool)) ? 'allowed' : 'excluded';\n}\n\n/**\n * Does one `tools:` or `disallowedTools:` entry cover the request tool? The\n * tool itself, its bare server (`mcp__plugin_tenjin_router`), or any\n * `*`-suffixed pattern the tool's name starts with: `*`, `mcp__*`,\n * `mcp__plugin_tenjin_router__*` and every prefix between.\n */\nfunction namesRequestTool(entry: string, tool: string): boolean {\n if (entry === tool || entry === tool.replace(/__request$/, '')) return true;\n return entry.endsWith('*') && tool.startsWith(entry.slice(0, -1));\n}\n\n/** The settings install's tool or server, by literal or wildcard. */\nfunction namesLegacyTool(entry: string): boolean {\n return namesRequestTool(entry, LEGACY_REQUEST_TOOL) || entry === `mcp__${LEGACY_MCP_SERVER_NAME}`;\n}\n\n/**\n * Every custom agent this project and this user define whose tools leave the\n * request tool out, for `doctor` to name. Plugin agents are not listed: their\n * files are not the user's to edit.\n */\nexport async function agentsWithoutRequestTool(\n lookup: AgentLookup,\n tool: string = requestToolName(),\n): Promise<string[]> {\n const found: string[] = [];\n const seen = new Set<string>();\n for (const directory of agentDirs(lookup)) {\n for (const { name, text } of await definitionsIn(directory)) {\n const type = nameOf(text) ?? name;\n if (seen.has(type)) continue;\n seen.add(type);\n if (accessOf(text, tool) === 'excluded') found.push(type);\n }\n }\n return found.sort();\n}\n\nasync function findDefinition(agentType: string, lookup: AgentLookup): Promise<string | null> {\n for (const directory of agentDirs(lookup)) {\n const text = await definitionIn(directory, agentType);\n if (text !== null) return text;\n }\n const colon = agentType.indexOf(':');\n if (colon > 0) {\n const plugin = agentType.slice(0, colon);\n const agent = agentType.slice(colon + 1);\n for (const root of await pluginRoots(plugin, lookup.homeDir)) {\n const text = await definitionIn(join(root, 'agents'), agent);\n if (text !== null) return text;\n }\n }\n return null;\n}\n\nfunction agentDirs(lookup: AgentLookup): string[] {\n const dirs: string[] = [];\n if (lookup.cwd !== undefined && lookup.cwd.length > 0) {\n let current = resolve(lookup.cwd);\n for (;;) {\n dirs.push(join(current, '.claude', 'agents'));\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n }\n const user = join(resolve(lookup.homeDir), '.claude', 'agents');\n // The user's directory is also an ancestor of most projects; it counts once,\n // in its own place in the order.\n return [...dirs.filter((d) => d !== user), user];\n}\n\nasync function definitionIn(directory: string, agentType: string): Promise<string | null> {\n const direct = await readBounded(join(directory, `${agentType}.md`));\n if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;\n for (const { text } of await definitionsIn(directory)) {\n if (nameOf(text) === agentType) return text;\n }\n return null;\n}\n\nasync function definitionsIn(directory: string): Promise<{ name: string; text: string }[]> {\n let names: string[];\n try {\n names = (await readdir(directory)).filter((n) => n.endsWith('.md')).slice(0, 200);\n } catch {\n return [];\n }\n const out: { name: string; text: string }[] = [];\n for (const file of names) {\n const text = await readBounded(join(directory, file));\n if (text !== null) out.push({ name: file.slice(0, -3), text });\n }\n return out;\n}\n\n/** Install paths `installed_plugins.json` records for `<plugin>@<marketplace>`. */\nasync function pluginRoots(plugin: string, homeDir: string): Promise<string[]> {\n const raw = await readBounded(join(homeDir, '.claude', 'plugins', 'installed_plugins.json'));\n if (raw === null) return [];\n const parsed = JSON.parse(raw) as { plugins?: Record<string, unknown> };\n const roots: string[] = [];\n for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {\n if (key.split('@')[0] !== plugin || !Array.isArray(entries)) continue;\n for (const entry of entries) {\n const path = (entry as { installPath?: unknown }).installPath;\n if (typeof path === 'string' && path.length > 0) roots.push(path);\n }\n }\n return roots;\n}\n\nasync function readBounded(path: string): Promise<string | null> {\n try {\n const text = await readFile(path, 'utf8');\n return text.length > MAX_AGENT_FILE_BYTES ? null : text;\n } catch {\n return null;\n }\n}\n\nfunction frontmatterOf(text: string): string[] | null {\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n return end === -1 ? null : lines.slice(open + 1, end);\n}\n\nfunction nameOf(text: string): string | null {\n const frontmatter = frontmatterOf(text);\n if (frontmatter === null) return null;\n const line = frontmatter.find((l) => /^name\\s*:/.test(l));\n const value = line === undefined ? '' : unquote(line.slice(line.indexOf(':') + 1).trim());\n return value.length > 0 ? value : null;\n}\n\n/**\n * A top-level list field in the three spellings agent files use: `a, b, c`,\n * `[a, b]`, or a block of `- a` lines. `undefined` when the key is absent.\n */\nfunction listField(frontmatter: string[], key: string): string[] | undefined {\n const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\\\s*:`).test(l));\n if (index === -1) return undefined;\n const line = frontmatter[index]!;\n const inline = line.slice(line.indexOf(':') + 1).trim();\n if (inline.length > 0) {\n const body = inline.startsWith('[') && inline.endsWith(']') ? inline.slice(1, -1) : inline;\n return body\n .split(',')\n .map((part) => unquote(part.trim()))\n .filter((part) => part.length > 0);\n }\n const items: string[] = [];\n for (const next of frontmatter.slice(index + 1)) {\n const item = /^\\s+-\\s*(.*)$/.exec(next);\n if (item === null) {\n if (next.trim().length === 0) continue;\n break;\n }\n const value = unquote(item[1]!.trim());\n if (value.length > 0) items.push(value);\n }\n return items;\n}\n\nfunction unquote(value: string): string {\n const quoted = /^(['\"])(.*)\\1$/.exec(value);\n return quoted === null ? value : quoted[2]!;\n}\n","import { randomBytes } from 'node:crypto';\nimport { readFile, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomicExclusive } from '../lib/atomic-json';\nimport { hasCode } from '../lib/errno';\nimport { sha256Hex } from '../lib/hash';\nimport { PRIVATE, writePrivate } from './store-files';\n\n/**\n * ONE MEMO FOR \"DO NOT ASK THE ROUTER YET\", per machine and per router origin,\n * in the data dir, so every hook leg and every `tenjin mcp` process reads the\n * same answer:\n *\n * - `unreachable`: a routing leg's call could not reach the router (DNS, TLS,\n * a refused connection, a proxy refusing the tunnel; see `isUnreachable`). For\n * {@link UNREACHABLE_BACKOFF_MS} every leg skips the router and the native\n * tool runs at once, instead of each prompt and search waiting out the gate.\n * Doctor's probe ends it early when it reaches the router.\n * - `topping-up`: a `tenjin mcp` process is topping up the wallet's routing\n * channel in the background ({@link TOPPING_UP_MEMO_MS}), so another one on\n * the same wallet does not send a second deposit. One memo per wallet, which\n * one process at a time claims ({@link claimRouterMemo}).\n * - `warm-absent`: the router answered the background top-up's `warm` call\n * with a 2xx that is not the `warm` answer, or a 3xx or 4xx other than a\n * 402 or 429 (an older server answers 400), so it has no `warm` form. For\n * {@link WARM_ABSENT_MS} a deposit rides the next paid call, as it did\n * before the form existed. A 402, 429, 5xx or no answer backs off instead.\n *\n * A memo is a file written atomically and read with the clock: one older than\n * its window, or dated in the future, reads as absent, so nothing cleans up\n * after it. An unreadable file reads as absent too: the cost of a lost memo is\n * one more call to the router.\n */\nexport type RouterMemoKind = 'unreachable' | 'topping-up' | 'warm-absent';\n\nexport interface RouterMemo {\n /** When it was written, in epoch ms. */\n at: number;\n /** When it ends, in epoch ms. */\n until: number;\n /** What happened, for doctor. */\n detail?: string;\n}\n\n/** How long routing legs skip a router that did not answer. */\nexport const UNREACHABLE_BACKOFF_MS = 60_000;\n/** How long another process's top-up holds this one's off at most: the\n * top-up's own budget (`TOP_UP_TIMEOUT_MS`, 15 s), a deposit still out after\n * it (`DETACHED_CEILING_MS`, 15 s) and some. Its holder ends it sooner. */\nexport const TOPPING_UP_MEMO_MS = 35_000;\n/** How long a router without the `warm` form gets deposits on the next paid\n * call instead, before the top-up tries `warm` again. */\nexport const WARM_ABSENT_MS = 60 * 60_000;\n\n/** `scope` gives each wallet a memo of its own, under the same origin. */\nfunction memoPath(dataDir: string, kind: RouterMemoKind, baseUrl: string, scope?: string): string {\n const origin = new URL(baseUrl).origin;\n const key = sha256Hex(scope === undefined ? origin : `${origin}\\n${scope}`, 16);\n return join(dataDir, 'router-memo', `${kind}-${key}.json`);\n}\n\n/** The memo in the file, whatever its window, or null. Never throws, not\n * even on a base URL that does not parse. */\nasync function readMemoFile(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n scope?: string,\n): Promise<RouterMemo | null> {\n try {\n const raw = JSON.parse(\n await readFile(memoPath(dataDir, kind, baseUrl, scope), 'utf8'),\n ) as unknown;\n if (raw === null || typeof raw !== 'object') return null;\n const { at, until, detail } = raw as Record<string, unknown>;\n if (typeof at !== 'number' || typeof until !== 'number') return null;\n return { at, until, ...(typeof detail === 'string' ? { detail } : {}) };\n } catch {\n return null;\n }\n}\n\n/** The memo in force at `now`, or null. Never throws. */\nexport async function readRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n now: number,\n scope?: string,\n): Promise<RouterMemo | null> {\n const memo = await readMemoFile(dataDir, kind, baseUrl, scope);\n return memo === null || memo.at > now || memo.until <= now ? null : memo;\n}\n\n/** Starts a memo of `ttlMs` from `now`. Never throws. */\nexport async function writeRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n memo: { now: number; ttlMs: number; detail?: string },\n): Promise<void> {\n const body: RouterMemo = {\n at: memo.now,\n until: memo.now + memo.ttlMs,\n ...(memo.detail !== undefined ? { detail: memo.detail.slice(0, 300) } : {}),\n };\n try {\n await writePrivate(memoPath(dataDir, kind, baseUrl), `${JSON.stringify(body)}\\n`);\n } catch {\n // Best effort: a memo that did not land costs one more call.\n }\n}\n\n/** Ends a memo before its window does. Never throws. */\nexport async function clearRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n scope?: string,\n): Promise<void> {\n try {\n await rm(memoPath(dataDir, kind, baseUrl, scope), { force: true });\n } catch {\n // Best effort: the window ends it anyway.\n }\n}\n\n/**\n * A MEMO ONLY ONE PROCESS HOLDS. It is created whole and exclusively, so of\n * two processes claiming at once exactly one wins. One past its window, or\n * unreadable, was left by a process that died holding it: it is removed and\n * claimed once more. One dated after this claim's `now` is a contender's that\n * read the clock a moment later and is held, unless it is a whole window\n * ahead (the clock went back). The claim's token, its `detail`, is what\n * {@link releaseRouterMemo} checks, so a holder never ends another's claim.\n * The token, or null when another process holds it. Never throws: a claim the\n * file system refuses outright counts as this call's, as before claims existed.\n */\nexport async function claimRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n memo: { now: number; ttlMs: number; scope?: string },\n): Promise<string | null> {\n const path = memoPath(dataDir, kind, baseUrl, memo.scope);\n const token = randomBytes(8).toString('hex');\n const body: RouterMemo = { at: memo.now, until: memo.now + memo.ttlMs, detail: token };\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n await writeFileAtomicExclusive(path, `${JSON.stringify(body)}\\n`, PRIVATE);\n return token;\n } catch (err) {\n if (!hasCode(err, 'EEXIST')) return token;\n }\n const held = await readMemoFile(dataDir, kind, baseUrl, memo.scope);\n if (held !== null && held.until > memo.now && held.at <= memo.now + memo.ttlMs) return null;\n await rm(path, { force: true }).catch(() => undefined);\n }\n return null;\n}\n\n/** Ends this claim, unless another process's has replaced it. Never throws. */\nexport async function releaseRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n claim: { token: string; now: number; scope?: string },\n): Promise<void> {\n const held = await readRouterMemo(dataDir, kind, baseUrl, claim.now, claim.scope);\n if (held?.detail === claim.token) await clearRouterMemo(dataDir, kind, baseUrl, claim.scope);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,gBAAgB;AAClC,SAAS,SAAS,MAAM,eAAe;AAoChC,IAAM,0BAA+C,oBAAI,IAAI;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,IAAM,uBAAuB,MAAM;AACnC,IAAM,UAAU;AAEhB,eAAsB,kBACpB,WACA,QACA,OAAe,gBAAgB,GACH;AAC5B,MAAI,cAAc,UAAa,CAAC,QAAQ,KAAK,SAAS,EAAG,QAAO;AAChE,MAAI;AACF,UAAM,OAAO,MAAM,eAAe,WAAW,MAAM;AACnD,QAAI,SAAS,KAAM,QAAO,SAAS,MAAM,IAAI;AAC7C,WAAO,wBAAwB,IAAI,SAAS,IAAI,YAAY;AAAA,EAC9D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAYO,SAAS,SAAS,YAAoB,OAAe,gBAAgB,GAAsB;AAChG,QAAM,cA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M,KAAK;AAChF,MAAI,MAAM,WAAW,MAAM,MAAO,OAAM,gBAAgB,SAAS,MAAM,SAAS,MAAM,KAAK;AAC7F;","names":["readFile","join","join","readFile"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/client-meta.ts","../src/lib/http.ts"],"sourcesContent":["import pkg from '../../package.json';\nimport { PRODUCTION_ORIGIN } from './production-origin';\n\n/**\n * The RFC 9110 product token naming this CLI. It leads every User-Agent\n * because the server's `parseUserAgentProduct()` attributes on the first\n * product only, and the CLI is what sent the request.\n */\nexport const TENJIN_PRODUCT = `tenjin-cli/${pkg.version}`;\n\n/** The product name alone, which identifies a copy of us in a handoff. */\nexport const TENJIN_PRODUCT_NAME = 'tenjin-cli';\n\n/** The product an earlier build's WebSearch hook led with; a handoff may still carry it. */\nexport const WEBSEARCH_HOOK_PRODUCT_NAME = 'tenjin-websearch-hook';\n\n/** Every identity of ours a handoff may carry, which composition drops rather\n * than duplicate. */\nexport const OWN_PRODUCT_NAMES = [TENJIN_PRODUCT_NAME, WEBSEARCH_HOOK_PRODUCT_NAME];\n\n/**\n * The identifying comment. It rides last so a caller's products keep their\n * order, and stripping it recovers the caller's sequence from a composed field.\n */\nexport const TENJIN_COMMENT = `(+${PRODUCTION_ORIGIN})`;\n\n/**\n * The CLI's identity on every HTTP request, sent as `User-Agent` from the\n * shared transport (`http.ts`).\n */\nexport const TENJIN_USER_AGENT = `${TENJIN_PRODUCT} ${TENJIN_COMMENT}`;\n\n/** The handoff seam for an agent that launches the CLI as a subprocess. */\nexport const CALLER_USER_AGENT_ENV = 'TENJIN_CALLER_USER_AGENT';\n\n/** The server's bound: a longer field is discarded whole, never truncated. */\nexport const USER_AGENT_MAX_LENGTH = 512;\n\n/**\n * One RFC 9110 product: a token, optionally `/token`. The handoff accepts only\n * a sequence of these, no comments or free text, which keeps user, wallet,\n * session and machine identifiers out structurally rather than by blocklist.\n */\nexport const PRODUCT_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+)?$/;\n\n/** Printable ASCII, the only range the server parses; also excludes CR/LF/tab. */\nexport const PRINTABLE_ASCII_RE = /^[\\x20-\\x7e]*$/;\n\nexport interface ComposeUserAgentInput {\n /** A caller's product sequence, passed programmatically; wins over the env. */\n caller?: string | undefined;\n /** Environment seam; defaults to `process.env`. */\n env?: NodeJS.ProcessEnv;\n}\n\n/**\n * Compose the field the transport sends: the Tenjin product, the caller's\n * products in order, then the Tenjin comment. The handoff is self-reported\n * telemetry; nothing here or on the server may use it for entitlement, spend\n * or trust.\n *\n * Idempotent: our own product and comment are dropped from the caller value\n * before the rebuild, so re-composing a composed field (a retry, an agent\n * re-exporting its env) never adds a second `tenjin-cli` token.\n *\n * Rejection is total: a non-printable, non-product or overlong handoff is\n * omitted whole, because truncating a product token would mint a false one.\n */\nexport function composeUserAgent(input: ComposeUserAgentInput = {}): string {\n const raw = input.caller ?? (input.env ?? process.env)[CALLER_USER_AGENT_ENV];\n const products = callerProducts(raw);\n if (products.length === 0) return TENJIN_USER_AGENT;\n const composed = `${TENJIN_PRODUCT} ${products.join(' ')} ${TENJIN_COMMENT}`;\n return composed.length <= USER_AGENT_MAX_LENGTH ? composed : TENJIN_USER_AGENT;\n}\n\n/** The caller's products, or none at all when any part of the handoff is unusable. */\nfunction callerProducts(raw: string | undefined): string[] {\n if (raw === undefined || !PRINTABLE_ASCII_RE.test(raw)) return [];\n // Printable ASCII leaves the space as the only whitespace, so it is the only\n // separator a product sequence can have.\n const tokens = raw.split(' ').filter((token) => token.length > 0 && !isOwnIdentity(token));\n return tokens.every((token) => PRODUCT_RE.test(token)) ? tokens : [];\n}\n\n/**\n * Our own identity inside a caller value, matched case-insensitively: a copy\n * of ours in any casing is still a duplicate identity.\n */\nfunction isOwnIdentity(token: string): boolean {\n const lower = token.toLowerCase();\n // Lower both sides, so a constant that gains a capital still matches.\n if (lower === TENJIN_COMMENT.toLowerCase()) return true;\n return OWN_PRODUCT_NAMES.some((name) => {\n const own = name.toLowerCase();\n return lower === own || lower.startsWith(`${own}/`);\n });\n}\n","import { CliError } from './errors';\nimport { composeUserAgent } from './client-meta';\n\n/**\n * Vercel's \"Protection Bypass for Automation\" header: a door key to someone's\n * protected deployment. This client never sets it, and neither an operator's\n * `-H` nor a spec may (see {@link isReservedRequestHeader}): a request that\n * carried one would hand the key to whatever host it went to.\n */\nconst PROTECTION_BYPASS_HEADER = 'x-vercel-protection-bypass';\n\n/** The anonymous install id: a random UUID minted once per data dir. */\nexport const INSTALL_ID_HEADER = 'tenjin-install-id';\n\n/**\n * Who is using the router, for Tenjin's own request telemetry: an anonymous\n * install id, random and tied to nothing but the data dir.\n *\n * The transport decides where it goes, from the REQUEST URL, so a call site\n * cannot send it to a provider by believing it is talking to Tenjin. `pay` runs over this transport\n * to third-party sellers, and none of them gets the header.\n *\n * Process-wide rather than a per-call option because it is not a per-call\n * decision: every request to Tenjin carries it, and threading it through forty\n * call sites is forty chances to forget one. Set only by the process entry (the\n * CLI's `index.ts`), so an in-process test that never sets it sends exactly\n * what it always did.\n *\n * Redirects are left to the request's usual transport: an unpinned request\n * follows them as `fetch` does, headers and all. Tenjin's origins redirect only\n * to Tenjin's own hosts, and the id is not a credential, so it is not worth the\n * redirect pin signed headers get.\n */\nexport interface TenjinIdentity {\n /** The origins that are Tenjin's own for this process. */\n origins: () => Promise<readonly string[]>;\n /** The install id; absent when it could not be read or created. */\n installId: () => Promise<string | undefined>;\n}\n\nlet tenjinIdentity: TenjinIdentity | undefined;\n\nexport function setTenjinIdentity(identity: TenjinIdentity | undefined): void {\n tenjinIdentity = identity;\n}\n\n/**\n * The telemetry headers for `url`, or nothing. NEVER THROWS: a data dir that\n * cannot be read costs the request its telemetry and nothing else.\n */\nexport async function tenjinIdentityHeaders(url: string): Promise<Record<string, string>> {\n const identity = tenjinIdentity;\n if (identity === undefined) return {};\n try {\n if (!(await identity.origins()).includes(new URL(url).origin)) return {};\n const id = await identity.installId();\n return id !== undefined ? { [INSTALL_ID_HEADER]: id } : {};\n } catch {\n return {};\n }\n}\n\n/**\n * The one place the identity is written for anything that can import it; the\n * transport funnels its Headers through it, so a second entry point on this\n * side cannot ship without it. `.set` on a Headers\n * object is what makes this total: a caller header spelled `User-Agent` in any\n * case lands in the same slot and is overwritten, never duplicated, so a\n * call-specific header cannot erase the composed field or add a second one.\n */\nfunction applyUserAgent(headers: Headers, callerUserAgent?: string): Headers {\n headers.set('user-agent', composeUserAgent({ caller: callerUserAgent }));\n return headers;\n}\n\n/**\n * A failed request, tagged by class so the caller maps it deliberately:\n * `network`/`timeout` (never reached the server or no answer), `blocked-redirect`\n * (a 3xx a pinned request may not follow), `oversized-header` (a response\n * header block too large to read).\n */\nexport interface FetchJsonFailure {\n ok: false;\n kind: 'network' | 'timeout' | 'blocked-redirect' | 'oversized-header';\n status?: number;\n requestId?: string;\n message: string;\n /**\n * On `network`: the layer the error chain names, when it names one. The\n * origin never answered, so a caller that blames it (or its base URL) gives\n * the wrong fix. See {@link transportFailure}.\n */\n transport?: TransportFailure;\n /**\n * On a `timeout` that came after the response headers did (`httpRequest`\n * only): a case-insensitive lookup over them. A seller can name where a long\n * job's result will be with its first byte, and only the body ran out of time.\n */\n header?: (name: string) => string | undefined;\n}\n\n/** Which layer refused a request that never reached the origin. */\nexport interface TransportFailure {\n layer: 'proxy' | 'dns' | 'tls' | 'connect';\n /** The socket's own error code, for every layer but `proxy`. */\n code?: string;\n /** What the proxy answered to `CONNECT`, for `proxy` only. */\n proxyStatus?: number;\n}\n\n/**\n * Header names that carry wallet-signed material.\n *\n * A request bearing any of these must NEVER follow a redirect: nothing signed\n * may leave for a host the request did not name, and `fetch`'s default\n * `redirect: 'follow'` re-sends request headers verbatim to the new host (Node\n * strips only `Authorization`). A 3xx anywhere on the signed origin would\n * therefore hand a signature BOUND TO THAT DOMAIN to whoever `Location` points\n * at, replayable against it for the signature's lifetime.\n *\n * Detected by header NAME rather than by a caller-supplied \"this is signed\" flag\n * so the protection cannot be forgotten at a call site: attaching the credential\n * is what arms it. Matched case-insensitively. Kept as literals so the base\n * transport keeps its single dependency; `http.test.ts` pins them against the\n * real constants in `lib/siwx` and the x402 payment headers.\n *\n * Both wallet-signed families this CLI sends are here: the SIWX auth header,\n * and the x402 payment header (`payment-signature` for x402 v2, plus\n * `x-payment`, the v1 spelling `@x402/core` can emit, as drift insurance).\n * `tenjin-session-delegation` is a reusable SIWX signature this client no\n * longer sends; it stays so a spec can never set it.\n */\nconst CREDENTIAL_HEADERS = new Set([\n 'sign-in-with-x',\n 'payment-signature',\n 'x-payment',\n 'tenjin-session-delegation',\n]);\n\nfunction carriesSignedMaterial(headers: Record<string, string>): boolean {\n return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));\n}\n\n/**\n * A request header name an operator may not set: the wallet-signed material\n * above, a deployment-protection bypass key, this install's identity, and the\n * x402 payment namespace. Kept beside the set so the two cannot drift.\n */\nexport function isReservedRequestHeader(name: string): boolean {\n const lowered = name.toLowerCase();\n return (\n CREDENTIAL_HEADERS.has(lowered) ||\n lowered === PROTECTION_BYPASS_HEADER ||\n lowered === INSTALL_ID_HEADER ||\n lowered.startsWith('payment-') ||\n lowered.startsWith('x-payment')\n );\n}\n\n/** One header name, as RFC 9110 spells a token. */\nconst HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n/** Names the transport or the body encoding own. */\nconst TRANSPORT_HEADERS = new Set(['host', 'content-length', 'content-type', 'user-agent']);\n\n/**\n * Why a request header someone else names (an operator's `-H`, a catalog\n * spec) cannot ride a paid request, or null when it can: `name` for a name\n * that is not a token or a value that is empty, `reserved` for a name this\n * client signs or sets itself or the transport owns, `value` for a value over\n * 1,024 characters or one that spans lines. `ownContentType` lets the caller\n * name `content-type`, for a body this client does not encode.\n */\nexport function requestHeaderProblem(\n name: string,\n value: string,\n ownContentType = false,\n): 'name' | 'reserved' | 'value' | null {\n if (!HEADER_NAME.test(name) || value.length === 0) return 'name';\n const lowered = name.toLowerCase();\n const contentType = ownContentType && lowered === 'content-type';\n if (isReservedRequestHeader(lowered) || (TRANSPORT_HEADERS.has(lowered) && !contentType)) {\n return 'reserved';\n }\n if (value.length > 1_024 || /[\\r\\n]/.test(value)) return 'value';\n return null;\n}\n\nfunction timeoutFailure(url: string, timeoutMs: number): FetchJsonFailure {\n return {\n ok: false,\n kind: 'timeout',\n message: `Request to ${url} timed out after ${timeoutMs}ms`,\n };\n}\n\n/**\n * A full HTTP round trip that surfaces the STATUS, headers, and best-effort JSON\n * body for ANY status: the pay flow needs the body on a 402, and the router's\n * calls need a 4xx validation envelope. It never throws on a transport or\n * protocol failure: it returns the discriminated FetchJsonFailure so callers\n * map each class uniformly. `fetchImpl` is injectable so tests never touch the\n * network.\n */\nexport interface HttpRequestOptions {\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n timeoutMs: number;\n headers?: Record<string, string>;\n /**\n * INTERNAL. A caller's own product sequence, composed BEHIND the CLI's\n * identity (see `composeUserAgent`). The package ships a `bin` and no\n * `exports` map, so this is not a supported seam for code outside this repo:\n * the documented handoff is the `TENJIN_CALLER_USER_AGENT` environment\n * variable, which is what a subprocess launcher sets and what this falls back\n * to. Kept as an option so an in-repo caller can pass a value the environment\n * does not carry.\n */\n callerUserAgent?: string;\n /** A JSON body (POST); serialized with a content-type header set automatically. */\n jsonBody?: unknown;\n /**\n * A body the CALLER already encoded, sent byte for byte with no content-type\n * of this transport's choosing: the router's provider leg is handed a request\n * the server built, and re-encoding it would make the bytes signed for and\n * the bytes sent two different things. The caller's own `headers` carry the\n * content type. Ignored when `jsonBody` is set.\n */\n rawBody?: string;\n fetchImpl?: typeof fetch;\n /**\n * Refuse redirects even when the request carries no signed header. For a\n * caller whose response becomes a durable local artifact, following a\n * cross-origin redirect would let another host's bytes be recorded as if the\n * origin asked for served them. Off by default, so other requests keep normal\n * transport.\n */\n blockRedirects?: boolean;\n /**\n * Keep a binary body as bytes. A sound, an image or any other non-text\n * payload decoded as text is corrupted, so with this set a response whose\n * content type is not text ({@link isBinaryContentType}) comes back with\n * `bytes` and an empty `text`. The router's provider leg sets it; every other\n * caller reads text as before.\n */\n binaryBody?: boolean;\n /** The cap on such a body; over it the response is a failure, never a\n * buffer that grows without bound. Defaults to {@link MAX_BINARY_BODY_BYTES}. */\n maxBinaryBytes?: number;\n /**\n * Send no install id, and mint none. For a request that checks the network\n * rather than uses Tenjin (the reachability probe), so it never counts as an\n * install in request telemetry.\n */\n anonymous?: boolean;\n}\n\n/** The same cap the router's linked-media download uses. */\nexport const MAX_BINARY_BODY_BYTES = 200 * 1024 * 1024;\n\n/** A body cap as a person reads it: whole MB, or bytes under one. */\nfunction capText(bytes: number): string {\n return bytes >= 1_048_576 ? `${Math.round(bytes / 1_048_576)} MB` : `${bytes}-byte`;\n}\n\n/**\n * The body's bytes, read chunk by chunk and abandoned the moment they pass\n * `max`; null over the cap. A declared length over it is refused unread.\n */\nasync function readCapped(res: Response, max: number): Promise<Uint8Array | null> {\n const declared = Number(res.headers.get('content-length') ?? '0');\n if (Number.isFinite(declared) && declared > max) {\n await res.body?.cancel().catch(() => undefined);\n return null;\n }\n if (res.body === null) return new Uint8Array();\n const reader = res.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > max) {\n await reader.cancel().catch(() => undefined);\n return null;\n }\n chunks.push(value);\n }\n return new Uint8Array(Buffer.concat(chunks));\n}\n\n/**\n * A content type whose body is not text: anything that is not `text/*` and\n * not a JSON, XML, JavaScript, YAML or form type. An absent header is text, as\n * it always was here.\n */\nexport function isBinaryContentType(contentType: string | undefined): boolean {\n const type = (contentType ?? '').split(';')[0]!.trim().toLowerCase();\n if (type.length === 0) return false;\n if (type.startsWith('text/')) return false;\n return !/(?:json|xml|javascript|ecmascript|yaml|x-www-form-urlencoded)/.test(type);\n}\n\nexport interface HttpResponse {\n ok: true;\n status: number;\n /** Case-insensitive header lookup over the response. */\n header(name: string): string | undefined;\n /** Parsed JSON body, or undefined when the body was empty or not JSON. */\n json: unknown;\n /** The raw body text; what a non-JSON endpoint actually said (`pay` delivers it). */\n text: string;\n /** The body's bytes, only for a binary body read with `binaryBody`; `text`\n * is then empty. */\n bytes?: Uint8Array;\n requestId?: string;\n}\n\nexport type HttpResult = HttpResponse | FetchJsonFailure;\n\n/** The wire form of one request: what to send, and whether it may follow a redirect. */\ninterface PreparedRequest {\n ok: true;\n headers: Record<string, string>;\n body: string | undefined;\n signed: boolean;\n pinned: boolean;\n}\n\n/**\n * Assemble the request and DERIVE its redirect decision from the headers that\n * were actually built, in one place and one pass. The redirect flags are\n * returned rather than assigned, so they have no value until the headers do:\n * there is no state in which `pinned` is readable but not yet computed, which\n * is what would let a signed request follow a 3xx to another host. Anything\n * that refuses here (`new Headers` throws on a malformed caller header) becomes\n * the same discriminated failure a dead socket does, because this transport\n * documents a returned failure for every refusal, not an exception.\n */\nfunction prepareRequest(url: string, opts: HttpRequestOptions): PreparedRequest | FetchJsonFailure {\n try {\n let body: string | undefined;\n const merged = new Headers(opts.headers ?? {});\n if (opts.jsonBody !== undefined) {\n body = JSON.stringify(opts.jsonBody);\n merged.set('content-type', 'application/json');\n } else if (opts.rawBody !== undefined) {\n body = opts.rawBody;\n }\n const wantsAccept =\n opts.method === 'POST' ||\n opts.method === 'PUT' ||\n opts.method === 'PATCH' ||\n body !== undefined;\n if (wantsAccept && !merged.has('accept')) merged.set('accept', 'application/json');\n // An `accept`/`content-type` set here wins the slot regardless of how a\n // caller cased its own copy.\n const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());\n\n // Signed requests opt out of redirect following entirely; see CREDENTIAL_HEADERS.\n // A caller can also pin an unsigned request (blockRedirects) when the\n // response it gets back becomes a durable local record.\n const signed = carriesSignedMaterial(headers);\n return {\n ok: true,\n headers,\n body,\n signed,\n pinned: signed || opts.blockRedirects === true,\n };\n } catch (err) {\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n };\n }\n}\n\nexport async function httpRequest(url: string, opts: HttpRequestOptions): Promise<HttpResult> {\n const doFetch = opts.fetchImpl ?? fetch;\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, opts.timeoutMs);\n try {\n const prepared = prepareRequest(url, opts);\n if (!prepared.ok) return prepared;\n const { headers, body, signed, pinned } = prepared;\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method: opts.method ?? 'GET',\n headers:\n opts.anonymous === true ? headers : { ...headers, ...(await tenjinIdentityHeaders(url)) },\n body,\n signal: controller.signal,\n ...(pinned ? { redirect: 'manual' as const } : {}),\n });\n } catch (err) {\n if (timedOut) return timeoutFailure(url, opts.timeoutMs);\n if (isHeaderOverflow(err)) return oversizedHeaderFailure(url);\n const transport = transportFailure(err);\n return {\n ok: false,\n kind: 'network',\n message: `Request to ${url} failed: ${errorMessage(err)}`,\n ...(transport !== undefined ? { transport } : {}),\n };\n }\n\n const requestId = res.headers.get('x-request-id') ?? undefined;\n\n // Fail CLOSED on a redirect the request was not allowed to follow. This\n // returns a failure rather than the 3xx response so no caller can mistake an\n // unfollowed redirect for a normal status and retry it by hand.\n if (pinned && res.status >= 300 && res.status < 400) {\n return {\n ok: false,\n kind: 'blocked-redirect',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: signed\n ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; ` +\n 'refusing to follow it, because the signature is bound to the configured origin.'\n : `Request to ${url} was redirected (${res.status}); ` +\n 'refusing to follow it, because the response must come from the configured origin.',\n };\n }\n // Read the raw text once; parse best-effort. A non-JSON body (empty 202, an\n // HTML error page) yields `undefined` rather than a thrown parse, because a\n // 402/409 caller keys off the STATUS and only some statuses carry JSON.\n let text: string;\n let bytes: Uint8Array | undefined;\n try {\n if (opts.binaryBody === true && isBinaryContentType(res.headers.get('content-type') ?? '')) {\n const read = await readCapped(res, opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES);\n if (read === null) {\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} returned a file over the ${capText(opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES)} cap; it was not kept.`,\n };\n }\n bytes = read;\n text = '';\n } else {\n text = await res.text();\n }\n } catch (err) {\n if (timedOut) {\n return {\n ...timeoutFailure(url, opts.timeoutMs),\n header: (name) => res.headers.get(name) ?? undefined,\n };\n }\n return {\n ok: false,\n kind: 'network',\n status: res.status,\n ...(requestId !== undefined ? { requestId } : {}),\n message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`,\n };\n }\n let json: unknown;\n if (text.length > 0) {\n try {\n json = JSON.parse(text);\n } catch {\n json = undefined;\n }\n }\n return {\n ok: true,\n status: res.status,\n header: (name) => res.headers.get(name) ?? undefined,\n json,\n text,\n ...(bytes !== undefined ? { bytes } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n };\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport interface FailureToCliErrorOptions {\n fix?: string;\n details?: unknown;\n}\n\n/**\n * Normalize a fetch failure into the CLI error contract: network/timeout are a\n * NETWORK_ERROR, an oversized header block is CHALLENGE_TOO_LARGE, and a\n * blocked redirect is API_UNREACHABLE. Callers that need a check-specific code\n * build their own CliError; this is the default the rest lean on.\n */\nexport function fetchFailureToCliError(\n failure: FetchJsonFailure,\n opts: FailureToCliErrorOptions = {},\n): CliError {\n const code =\n failure.kind === 'network' || failure.kind === 'timeout'\n ? 'NETWORK_ERROR'\n : failure.kind === 'oversized-header'\n ? 'CHALLENGE_TOO_LARGE'\n : 'API_UNREACHABLE';\n // The one failure with a remedy nobody can apply from inside the process, so\n // it names the operator's knob rather than suggesting a retry.\n // The knob, with no claim about payment: a caller that knows its leg passes\n // its own `fix` and says what happened to the money there.\n const fix =\n opts.fix ??\n (failure.kind === 'oversized-header'\n ? 'Raising `--max-http-header-size` on the node process that runs this CLI would let the header be read; that is an operator decision, not a default this build changes.'\n : undefined);\n return new CliError(code, failure.message, {\n ...(fix !== undefined ? { fix } : {}),\n ...(opts.details !== undefined ? { details: opts.details } : {}),\n });\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Does this transport failure mean the response HEADERS were too big for this\n * process to read?\n *\n * Node caps them at 16 KiB unless `--max-http-header-size` says otherwise, and\n * an x402 challenge is a header: a seller that embeds its whole output schema\n * in one can exceed the cap on its own (AnyAPI's is 52 KB, measured\n * 2026-09-22). undici then aborts the request and the generic path reported\n * `fetch failed` with no status and nothing naming the cause, which reads as\n * \"the endpoint is down\" for a seller that is answering perfectly.\n *\n * The message is undici's, matched on its stable text and on the code it\n * attaches; the CAUSE is the one that carries either, so both are checked.\n */\nfunction isHeaderOverflow(err: unknown): boolean {\n const seen = [err, (err as { cause?: unknown } | null)?.cause];\n return seen.some((candidate) => {\n if (candidate === null || typeof candidate !== 'object') return false;\n const code = (candidate as { code?: unknown }).code;\n if (code === 'UND_ERR_HEADERS_OVERFLOW' || code === 'HPE_HEADER_OVERFLOW') return true;\n const message = (candidate as { message?: unknown }).message;\n return typeof message === 'string' && /headers overflow|header overflow/i.test(message);\n });\n}\n\nconst DNS_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'EAI_FAIL', 'EAI_NODATA', 'EAI_NONAME']);\nconst CONNECT_CODES = new Set([\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'ETIMEDOUT',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\nconst TLS_CODE = /^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_|SELF_SIGNED_|DEPTH_ZERO_)/;\n/** undici's text when a proxy answers `CONNECT` with anything but 200. */\nconst PROXY_REFUSAL = /Proxy response \\((\\d{3})\\)/;\n\n/**\n * The layer a `fetch failed` came from, read down the `cause` chain. fetch\n * wraps the real error twice: a proxy refusing the tunnel is\n * `TypeError: fetch failed`, then `Request was cancelled.`, then undici's\n * `UND_ERR_ABORTED` with the proxy's status in its message (Node 24.18,\n * measured 2026-10-05). Undefined when no link names a layer.\n */\nexport function transportFailure(err: unknown): TransportFailure | undefined {\n let link: unknown = err;\n for (let depth = 0; depth < 5 && link !== null && typeof link === 'object'; depth += 1) {\n const { code, message, cause } = link as { code?: unknown; message?: unknown; cause?: unknown };\n const proxy = typeof message === 'string' ? PROXY_REFUSAL.exec(message) : null;\n if (proxy !== null) return { layer: 'proxy', proxyStatus: Number(proxy[1]) };\n if (typeof code === 'string') {\n if (DNS_CODES.has(code)) return { layer: 'dns', code };\n if (TLS_CODE.test(code)) return { layer: 'tls', code };\n if (CONNECT_CODES.has(code)) return { layer: 'connect', code };\n }\n link = cause;\n }\n return undefined;\n}\n\n/**\n * The named refusal for that case. NOT a `network` failure: nothing is wrong\n * with the connection, and a caller that retries gets the same 52 KB again.\n *\n * SAYS NOTHING ABOUT PAYMENT. This transport serves the unpaid probe and the\n * paid retry alike and cannot tell them apart, so a message asserting either\n * way is wrong on one of them: it read as \"nothing was sent\" on a leg where a\n * signed authorization had already left. The leg adds that sentence, because\n * the leg is what knows; see `runPay`.\n */\nfunction oversizedHeaderFailure(url: string): FetchJsonFailure {\n let origin = url;\n try {\n origin = new URL(url).origin;\n } catch {\n // Keep the raw string; this is a diagnostic, not a destination.\n }\n return {\n ok: false,\n kind: 'oversized-header',\n message:\n `${origin} answered with a response header block larger than this process will read. ` +\n 'An x402 challenge travels in a header, and a seller that embeds its whole output ' +\n 'schema in one can exceed the limit, so the response could not be read.',\n };\n}\n"],"mappings":";;;;;;;;;;;;AAQO,IAAM,iBAAiB,cAAc,gBAAI,OAAO;AAGhD,IAAM,sBAAsB;AAG5B,IAAM,8BAA8B;AAIpC,IAAM,oBAAoB,CAAC,qBAAqB,2BAA2B;AAM3E,IAAM,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AACT;AAYA,SAAS,uBAAuB,KAA+B;AAC7D,MAAI,SAAS;AACb,MAAI;AACF,aAAS,IAAI,IAAI,GAAG,EAAE;AAAA,EACxB,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SACE,GAAG,MAAM;AAAA,EAGb;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/fee.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { MAX_AUTO_SPEND_FLOOR_ATOMIC } from '../lib/config';\nimport { atomicToUsd, formatUsdDisplay } from '../lib/money';\nimport { evaluateSpendPolicy, type PolicyReason, type SpendPolicy } from '../lib/policy';\nimport {\n DEPOSIT_DEFERRED,\n NO_PAYER,\n TOP_UP_UNAVAILABLE,\n TOPPING_UP,\n type DecisionRoute,\n} from './decision';\nimport { agentFixFor, WALLET_REASONS } from './wallet-reasons';\n\n/**\n * THE ROUTING FEE, WITHOUT ANYTHING THAT PAYS. Every routing call goes to the\n * paid route and pays the fee its 402 quotes over x402 `batch-settlement`, and\n * the stock SDK client in `tenjin mcp` does all of it (`routing-payer.ts`).\n * Nothing else pays it: a call without that payer is skipped when the route\n * asks for it.\n *\n * THE SERVER QUOTES, THIS CLIENT CAPS. The fee is the server's to set, so no\n * fee amount lives here: only the ceiling a quote must not pass, like\n * EIP-1559's `maxFeePerGas`, and the spend limits that bound it beside that.\n *\n * Hook-safe: `tenjin hook` loads this module, and its chunk graph stays free\n * of the wallet and the x402 SDK (`dist-chunks.test.ts`).\n */\n\n/**\n * THE ROUTING FEE CEILING, atomic USDC ($0.25): the most one routing answer\n * pays, and the most one routing deposit holds ({@link MAX_CHANNEL_DEPOSIT_ATOMIC}).\n * The router quotes each answer its own fee, usually far below this; a quote\n * at or below it is paid inside the spend limits, and one above it is not\n * paid at all ({@link FEE_ABOVE_CEILING}). It is a limit, not a price.\n */\nexport const ROUTING_FEE_CEILING_ATOMIC = 250_000n;\n/**\n * THE ROUTER'S FIXED QUOTE ($0.003), which it still offers beside a per-answer\n * quote for the CLIs released before per-answer quotes. This client pays it\n * only when it is the 402's only routing offer (`routing-quote.ts`). An\n * estimate with no 402 in hand (doctor's funded-enough check, the fund line\n * under an empty wallet) sizes from it.\n */\nexport const LEGACY_ROUTING_QUOTE_ATOMIC = 3_000n;\n/** The skip reason for a quote above {@link ROUTING_FEE_CEILING_ATOMIC}. */\nexport const FEE_ABOVE_CEILING = 'fee_above_ceiling';\n/** The deposit hint ($0.05) when a 402 carries no `extra.minDeposit`: the\n * production server's own, and the one doctor sizes from with no 402. */\nexport const CHANNEL_DEPOSIT_ATOMIC = 50_000n;\n/** Tenjin's maximum deposit per top-up ($0.25), independent of the SDK's larger bound. */\nexport const MAX_CHANNEL_DEPOSIT_ATOMIC = 250_000n;\n/** Keep this much USDC outside the routing channel for provider payments. */\nexport const ROUTING_WALLET_RESERVE_ATOMIC = 10_000n;\n/** Buffered top-up for a wallet that cannot fit the normal SDK target. */\nexport const SMALL_CHANNEL_DEPOSIT_ATOMIC = 10_000n;\n/** Below ten cents liquid, use the small deposit even when the buffer fits. */\nexport const SMALL_WALLET_THRESHOLD_ATOMIC = 100_000n;\n\n/** Use the SDK target when it fits at ten cents or more; otherwise use the\n * small target, raised for a larger voucher deficit. Shrink to the balance\n * above the reserve; zero refuses less than the deficit. Null is doctor's estimate. */\nexport function routingDepositAtomic(o: {\n suggestedAtomic: bigint;\n neededAtomic: bigint;\n balanceAtomic: bigint | null;\n perCallAtomic: bigint;\n maxAtomic: bigint;\n}): bigint {\n const least = (a: bigint, b: bigint) => (b < a ? b : a);\n const target = least(least(o.suggestedAtomic, o.perCallAtomic), o.maxAtomic);\n if (o.balanceAtomic === null) return target;\n if (\n o.balanceAtomic >= SMALL_WALLET_THRESHOLD_ATOMIC &&\n o.balanceAtomic >= target + ROUTING_WALLET_RESERVE_ATOMIC\n )\n return target;\n const smaller = least(\n target,\n o.neededAtomic > SMALL_CHANNEL_DEPOSIT_ATOMIC ? o.neededAtomic : SMALL_CHANNEL_DEPOSIT_ATOMIC,\n );\n const available = o.balanceAtomic - ROUTING_WALLET_RESERVE_ATOMIC;\n const amount = least(smaller, available);\n return amount > 0n && amount >= o.neededAtomic ? amount : 0n;\n}\n\n/**\n * The top-up every \"add funds\" hint names, in USD: the checkout's Apple\n * Pay and Google Pay minimum, which covers the routing deposit and a few\n * hundred lookups. `tenjin fund` sends it to the checkout as a preset.\n */\nexport const SUGGESTED_FUND_USD = '5';\n/** The funding line a new wallet is told, after `tenjin wallet create`. */\nexport const FUNDING_LINE = `Add funds with \\`tenjin fund ${SUGGESTED_FUND_USD}\\`, or send USDC from a crypto wallet with \\`tenjin fund --usdc\\`.`;\n/** The funding line under a balance of exactly $0, in `tenjin balance` and `tenjin status`. */\nexport const FUND_COMMAND_LINE = 'Add funds with `tenjin fund`, or ask your agent.';\n\n/** The most a fund link's `need` may name as its price (the link route's bound). */\nconst NEED_PRICE_MAX_ATOMIC = 100_000_000n;\n/** A `--for` label: the link route takes 1 to 60 characters. */\nconst NEED_LABEL_MAX = 60;\n\n/**\n * THE COMMAND THAT OPENS CHECKOUT FOR ONE WAITING CALL: `tenjin fund 5 --for\n * \"X post read\" --price 0.006`, so the checkout page says what the money is\n * for. The amount is the suggested top-up, or the price in whole dollars when\n * that is more. The label keeps only characters that are inert inside double\n * quotes in any shell.\n */\nexport function fundForCommand(label: string, priceAtomic: bigint): string {\n const wholePrice = (priceAtomic + 999_999n) / 1_000_000n;\n const amount =\n wholePrice > BigInt(SUGGESTED_FUND_USD) ? wholePrice.toString() : SUGGESTED_FUND_USD;\n const safe = [\n ...label\n .replace(/[^\\p{L}\\p{N} .,:'()/+&-]/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim(),\n ]\n .slice(0, NEED_LABEL_MAX)\n .join('')\n .trim();\n const named =\n safe.length > 0 && priceAtomic > 0n && priceAtomic <= NEED_PRICE_MAX_ATOMIC\n ? ` --for \"${safe}\" --price ${atomicToUsd(priceAtomic.toString())}`\n : '';\n return `tenjin fund ${amount}${named}`;\n}\n\n/**\n * A PAID CALL REFUSED FOR LOW FUNDS, said with what the money is for: \"This X\n * post read costs $0.006, more than your Tenjin balance. Ask the person once\n * to add funds; on yes, run `tenjin fund 5 --for \"X post read\" --price\n * 0.006`.\" That command opens checkout with the call named on the page. A\n * service with no display label is named by its provider (\"A call to\n * BlockRun costs …\").\n */\nexport function shortOfFunds(o: {\n label?: string | undefined;\n provider: string;\n priceAtomic: bigint;\n}): string {\n const subject = o.label !== undefined ? `This ${o.label}` : `A call to ${o.provider}`;\n return `${subject} costs $${usd(o.priceAtomic)}, more than your Tenjin balance. Ask the person once to add funds; on yes, run \\`${fundForCommand(o.label ?? o.provider, o.priceAtomic)}\\`.`;\n}\n/** The spend ledger key a deposit's exposure is recorded under, before its id. */\nexport const ROUTING_DEPOSIT_KEY = 'routing-deposit:';\n\n/** A spend refusal, as the reason the call was not paid. */\nconst REFUSED: Partial<Record<PolicyReason, string>> = {\n not_allowlisted: 'not_allowlisted',\n session_budget_exceeded: 'budget_reached',\n above_auto_spend: 'limit_below_deposit',\n};\n\n/** The reason a spend refusal leaves a routing call unpaid. */\nexport function refusedWhy(reason: PolicyReason): string {\n return REFUSED[reason] ?? reason;\n}\n\n/**\n * THE DEPOSIT IS THE SPEND. It meets the whole policy once, the day's budget\n * included, when the SDK's `depositStrategy` reserves it. Each fee paid from\n * it then gets only the per-payment checks, at the amount quoted: the per-call\n * limit, the creator allowlist (the router's host) and an explicit zero daily\n * limit. It is never refused for the day's running total, which the deposit\n * already consumed. Null when those checks allow the fee.\n */\nexport function feeRefusal(policy: SpendPolicy, host: string, feeAtomic: bigint): string | null {\n const evaluation = evaluateSpendPolicy(\n { ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },\n { mode: 'automatic', amountAtomic: feeAtomic, creator: host, sessionSpentAtomic: 0n },\n );\n return evaluation.decision === 'allow' ? null : refusedWhy(evaluation.reason);\n}\n\n/** The payer's route for a call to the router at `baseUrl`. `tenjin mcp`\n * passes its payer's; absent, a call goes unpaid. */\nexport type RouteFor = (baseUrl: string) => DecisionRoute;\n\n/**\n * WHY A CALL WAS NOT PAID, for the user: the reason and the fix, keyed by the\n * payer's skip reason (or `no_payer`, when the route asked for the fee and\n * nothing could pay it). Null for a reason that is no fault and needs no\n * fix: another session's call on the channel, or a call queued past its own\n * budget, or a payment still out when the call's\n * budget ran out (it finishes in the background), or an unlock that did not\n * finish inside the call's budget (it keeps running, and the next call gets\n * its answer), or a balance read before a deposit that failed or ran out of\n * time (nothing was signed or sent), or a deposit the background top-up has\n * not made yet.\n *\n * THE WALLET'S OWN REASONS ARE `WALLET_REASONS`, spread in rather than written\n * twice, so a notice names the same cause in the same words as doctor. They\n * carry the PERSON `fix`, never `agentFix`: this sentence goes in the hook's\n * `systemMessage`, which the harness shows the person (B1, decision 15), and a\n * fix that names `tenjin wallet repair` says it asks in their own terminal.\n */\nconst WALLET_UNPAID: Record<string, { reason: string; fix: string }> = Object.fromEntries(\n Object.entries(WALLET_REASONS).map(([key, { reason, fix }]) => [key, { reason, fix }]),\n);\nconst UNPAID: Record<string, { reason: string; fix: string }> = {\n wallet_low: {\n // The least a wallet routes with ({@link routingDepositAtomic}): the\n // reserve kept for provider payments plus a deposit of one fixed quote,\n // $0.013. A dearer answer needs more, so the line says \"at least\".\n reason: `the wallet holds less than Tenjin needs to set aside for routing (at least $${usd(ROUTING_WALLET_RESERVE_ATOMIC + LEGACY_ROUTING_QUOTE_ATOMIC)})`,\n fix: `Add funds with \\`tenjin fund ${SUGGESTED_FUND_USD}\\`.`,\n },\n ...WALLET_UNPAID,\n // A SPEND LIMIT IS NEVER A FUNDING PROBLEM: adding money cannot help, so\n // these never point at checkout. They say the balance is not the cause and\n // name the setting that is.\n limit_below_deposit: {\n reason: 'the per-call spend limit cannot cover the routing fee or its deposit',\n fix: `Your balance is fine; this is the per-call limit. Raise it with \\`tenjin config set maxAutoSpend ${usd(MAX_AUTO_SPEND_FLOOR_ATOMIC)}\\`.`,\n },\n budget_reached: {\n reason: \"today's spend limit is used up\",\n fix: 'Your balance is fine, and adding funds would not help. The limit frees up as the 24 hours pass, or raise it with `tenjin config set sessionBudget <usd>`.',\n },\n not_allowlisted: {\n reason: 'allowlistCreators does not include the router',\n fix: 'Run `tenjin doctor`.',\n },\n payment_failed: {\n reason: 'the routing payment failed',\n fix: 'Run `tenjin doctor`.',\n },\n [FEE_ABOVE_CEILING]: {\n reason: 'the router asks more per call than this install agreed to pay',\n fix: 'Your usual tools still work.',\n },\n [NO_PAYER]: {\n reason: 'the router charges it, and this session cannot pay it',\n fix: 'Run `tenjin doctor`.',\n },\n};\nconst NO_FAULT = new Set([\n 'channel_busy',\n 'busy',\n 'no_call',\n 'deadline_after_payment_sent',\n 'unlock_timeout',\n 'balance_unreadable',\n TOPPING_UP,\n DEPOSIT_DEFERRED,\n TOP_UP_UNAVAILABLE,\n]);\n\n/** The reason and fix for an unpaid call, or null when it needs no word. */\nexport function unpaid(why: string): { reason: string; fix: string } | null {\n if (NO_FAULT.has(why)) return null;\n return UNPAID[why] ?? UNPAID['payment_failed']!;\n}\n\n/**\n * The deposit notice, on the next hook after a background top-up or on the\n * routing call that carried it. Each fee is the router's own quote, and the\n * deposit counts toward spend limits once, when it is sent ({@link feeRefusal}).\n */\nexport function depositSentence(amountAtomic: bigint): string {\n return `Tenjin set aside $${usd(amountAtomic)} for routing. It counts toward your spend limits.`;\n}\n\n/**\n * What a call the wallet could not fund says. Routing has not stopped: an\n * answer that needs no payment can still come, so the line says only that\n * this answer went unpaid, and opens no checkout (explicit balance, payment\n * and doctor results keep `unpaid().fix`).\n */\nexport const WALLET_LOW_SENTENCE =\n 'Your balance was too low for this routing fee. Free routing still works.';\n\n/**\n * The one line the user sees, once per session and reason, when a call was not\n * paid. Its reader picks the fix (B1): the person's by default; for the model\n * (the `request` tool's text) a wallet unlock reason's `agentFix`, which asks\n * the person to act and never for the passphrase, and any other reason's own.\n * A quote above the ceiling names the price quoted, when the payer read one.\n */\n/**\n * A spend limit, as the person reads it in chat: their agent raises it, so they\n * never get a command they did not type. The agent reader keeps the command.\n */\nconst PERSON_FIX: Partial<Record<string, string>> = {\n limit_below_deposit:\n 'Your balance is fine; this is the per-call limit. Ask your agent to raise it.',\n budget_reached:\n 'Your balance is fine, and adding funds would not help. The limit frees up as the 24 hours pass, or ask your agent to raise it.',\n};\n\nexport function unpaidSentence(\n why: string,\n reader: 'person' | 'agent' = 'person',\n quotedAtomic?: bigint,\n): string | null {\n const u = unpaid(why);\n if (u === null) return null;\n if (why === 'wallet_low') return WALLET_LOW_SENTENCE;\n const fix = reader === 'agent' ? agentFixFor(why, u.fix) : (PERSON_FIX[why] ?? u.fix);\n const reason =\n why === FEE_ABOVE_CEILING && quotedAtomic !== undefined\n ? `the router quoted $${usd(quotedAtomic)} a call, more than this install agreed to pay`\n : u.reason;\n return `Tenjin could not pay the routing fee (${reason}). Free routing still works. ${fix}`;\n}\n\nconst ADDRESS_RE = /^0x[0-9a-f]{40}$/;\n\n/** One wallet's folder: the SDK's file storage for its routing channel\n * (`client/<channelId>.json`). */\nexport function payerDir(dataDir: string, payer: string): string {\n const name = payer.toLowerCase();\n if (!ADDRESS_RE.test(name)) throw new Error(`not a wallet address: ${payer}`);\n return join(dataDir, 'router', 'fee', name);\n}\n\n/** Atomic USDC as dollars with at least two decimals, never a float. */\nexport function usd(atomic: bigint): string {\n return formatUsdDisplay(atomic.toString());\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY;AAmCd,IAAM,6BAA6B;AAQnC,IAAM,8BAA8B;AAEpC,IAAM,oBAAoB;AAG1B,IAAM,yBAAyB;AAE/B,IAAM,6BAA6B;AAEnC,IAAM,gCAAgC;AAEtC,IAAM,+BAA+B;AAErC,IAAM,gCAAgC;AAKtC,SAAS,qBAAqB,GAM1B;AACT,QAAM,QAAQ,CAAC,GAAW,MAAe,IAAI,IAAI,IA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AI;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGM,SAAS,OAAO,KAAqD;AAC1E,MAAI,SAAS,IAAI,GAAG,EAAG,QAAO;AAC9B,SAAO,OAAO,GAAG,KAAK,OAAO,gBAAgB;AAC/C;AAOO,SAAS,gBAAgB,cAA8B;AAC5D,SAAO,qBAAqB,IAAI,YAAY,CAAC;AAC/C;AAQO,IAAM,sBACX;AAaF,IAAM,aAA8C;AAAA,EAClD,qBACE;AAAA,EACF,gBACE;AACJ;AAEO,SAAS,eACd,KACA,SAA6B,UAC7B,cACe;AACf,QAAM,IAAI,OAAO,GAAG;AACpB,MAAI,MAAM,KAAM,QAAO;AACvB,MAAI,QAAQ,aAAc,QAAO;AACjC,QAAM,MAAM,WAAW,UAAU,YAAY,KAAK,EAAE,GAAG,IAAK,WAAW,GAAG,KAAK,EAAE;AACjF,QAAM,SACJ,QAAQ,qBAAqB,iBAAiB,SAC1C,sBAAsB,IAAI,YAAY,CAAC,kDACvC,EAAE;AACR,SAAO,yCAAyC,MAAM,gCAAgC,GAAG;AAC3F;AAEA,IAAM,aAAa;AAIZ,SAAS,SAAS,SAAiB,OAAuB;AAC/D,QAAM,OAAO,MAAM,YAAY;AAC/B,MAAI,CAAC,WAAW,KAAK,IAAI,EAAG,OAAM,IAAI,MAAM,yBAAyB,KAAK,EAAE;AAC5E,SAAO,KAAK,SAAS,UAAU,OAAO,IAAI;AAC5C;AAGO,SAAS,IAAI,QAAwB;AAC1C,SAAO,iBAAiB,OAAO,SAAS,CAAC;AAC3C;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/names.ts"],"sourcesContent":["/**\n * THE NAMES THE HARNESS KNOWS THE ROUTER BY, spelled once. `install` registers\n * the Claude Code plugin {@link PLUGIN_NAME}, whose MCP server is\n * {@link MCP_SERVER_NAME}, and Claude Code names a plugin's tools\n * `mcp__plugin_<plugin>_<server>__<tool>`. The plugin's hooks, the server's own\n * name and every hint line the hooks inject read these, so a rename moves them\n * together.\n *\n * A module of its own because the hooks need the tool name and must not load\n * `install` to get it: their chunk graph is the product's floor.\n */\nexport const PLUGIN_NAME = 'tenjin';\nexport const MCP_SERVER_NAME = 'router';\n/** The marketplace `install` adds from the package, so the plugin id is `tenjin@tenjin`. */\nexport const MARKETPLACE_NAME = 'tenjin';\nexport const PLUGIN_ID = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;\n/** The id Claude Code gives the same plugin loaded from a skills-directory folder. */\nexport const SKILLS_DIR_PLUGIN_ID = `${PLUGIN_NAME}@skills-dir`;\n/** How a plugin's `hooks.json` and `claude mcp` name the plugin's own server. */\nexport const PLUGIN_SERVER = `plugin:${PLUGIN_NAME}:${MCP_SERVER_NAME}`;\nconst TOOL_PREFIX = `mcp__plugin_${PLUGIN_NAME}_${MCP_SERVER_NAME}`;\nexport const REQUEST_TOOL = `${TOOL_PREFIX}__request`;\n/** The tool the plugin's hook legs call, which its own deny hook keeps from the model. */\nexport const PLUGIN_HOOK_TOOL = `${TOOL_PREFIX}__hook`;\n\n/**\n * The settings-based install's names, for its migration and nothing else.\n * Older releases registered the server as `x402` through `claude mcp add` and\n * wrote seven hook entries and two permission rules into settings.json.\n *\n * SHIM: remove on or after 2026-12-01, the first release cut 30 or more days\n * after the plugin PR 2 ships. Doctor keeps naming an unmigrated machine after.\n */\nexport const LEGACY_MCP_SERVER_NAME = 'x402';\nexport const LEGACY_REQUEST_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__request`;\nexport const LEGACY_HOOK_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__hook`;\n\n/**\n * Is this process one Claude Code launched from the plugin? Claude Code sets\n * `CLAUDE_PLUGIN_ROOT` for a plugin's MCP server and its command hooks\n * (checked on 2.1.296), and not for a server registered in `~/.claude.json`.\n */\nexport function launchedByPlugin(env: NodeJS.ProcessEnv = process.env): boolean {\n const root = env.CLAUDE_PLUGIN_ROOT;\n return typeof root === 'string' && root.length > 0;\n}\n\n/** The agent hosts the router serves, as the CLI names them to the server. */\nexport const HARNESSES = ['claude', 'codex'] as const;\nexport type Harness = (typeof HARNESSES)[number];\n\n/**\n * Codex names an MCP tool `mcp__<server>__<tool>`, and its plugin's server is\n * {@link MCP_SERVER_NAME}, so the grant key and the tool name move together.\n */\nexport const CODEX_REQUEST_TOOL = `mcp__${MCP_SERVER_NAME}__request`;\n/** The tool the Codex plugin's routing legs call, which its own deny hook keeps from the model. */\nexport const CODEX_HOOK_TOOL = `mcp__${MCP_SERVER_NAME}__hook`;\n\n/**\n * The request tool's name as the host exposes it, so an offer line never names\n * a tool the model does not have. In Claude Code: the plugin's tool for a\n * server the plugin launched, and the `x402` server's tool for one a settings\n * install launched.\n *\n * SHIM: the Claude settings branch goes on or after 2026-12-01 (see\n * {@link LEGACY_MCP_SERVER_NAME}); Claude's name is then always {@link REQUEST_TOOL}.\n */\nexport function requestToolName(\n host: Harness = 'claude',\n env: NodeJS.ProcessEnv = process.env,\n): string {\n if (host === 'codex') return CODEX_REQUEST_TOOL;\n return launchedByPlugin(env) ? REQUEST_TOOL : LEGACY_REQUEST_TOOL;\n}\n"],"mappings":";;;AAWO,IAAM,cAAc;AACpB,IAAM,kBAAkB;AAExB,IAAM,mBAAmB;AACzB,IAAM,YAAY,GAAG,WAAW,IAAI,gBAAgB;AAEpD,IAAM,uBAAuB,GAAG,WAAW;AAE3C,IAAM,gBAAgB,UAAU,WAAW,IAAI,eAAe;AACrE,IAAM,cAAc,eAAe,WAAW,IAAI,eAAe;AAC1D,IAAM,eAAe,GAAG,WAAW;AAEnC,IAAM,mBAAmB,GAAG,WAAW;AAUvC,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB,QAAQ,sBAAsB;AAC1D,IAAM,mBAAmB,QAAQ,sBAAsB;AAOvD,SAAS,iBAAiB,MAAyB,QAAQ,KAAc;AAC9E,QAAM,OAAO,IAAI;AACjB,SAAO,OAAO,SAAS,YAAY,KAAK,SAAS;AACnD;AAGO,IAAM,YAAY,CAAC,UAAU,OAAO;AAOpC,IAAM,qBAAqB,QAAQ,eAAe;AAElD,IAAM,kBAAkB,QAAQ,eAAe;AAW/C,SAAS,gBACd,OAAgB,UAChB,MAAyB,QAAQ,KACzB;AACR,MAAI,SAAS,QAAS,QAAO;AAC7B,SAAO,iBAAiB,GAAG,IAAI,eAAe;AAChD;","names":[]}
|