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/codex-install.ts","../src/lib/codex-trust.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport pkg from '../../package.json';\nimport { persistRouterDefaults } from '../commands/config';\nimport { versionFreeEntry } from '../commands/update';\nimport type { WalletDeps, WalletOutcome } from '../commands/install-wallet';\nimport { autoUpdateLine } from '../lib/auto-update';\nimport { resolveCodex } from '../lib/codex-bin';\nimport { loadRawConfig } from '../lib/config';\nimport { CliError } from '../lib/errors';\nimport { atLeast } from '../lib/version-order';\nimport { runtimeDir, tilde } from '../lib/paths';\nimport { hasRuntime } from '../lib/runtime-layout';\nimport type { RuntimeSetup, setupRuntime } from '../lib/runtime';\nimport type { CommandContext, CommandResult } from '../context';\nimport {\n at,\n CODEX_MARKETPLACE,\n CODEX_PLUGIN,\n codexHookRows,\n codexVersion,\n listCodexHooks,\n readCodexConfig,\n type CodexHookRows,\n WEB_VERIFIED_VERSION,\n} from './codex-host';\nimport { resolveContextSettings } from '../lib/settings';\nimport {\n approveLimits,\n assertPluginInstallation,\n continuationCommand,\n requireRuntime,\n defaultRuntime,\n effectiveLimits,\n namedLimits,\n NOTHING_TO_REFRESH,\n runtimeData,\n runtimeLines,\n walletLines,\n CAPABILITY_LINES,\n DISCLOSURE,\n receiptTail,\n spendStepFor,\n type QuestionStep,\n type RouterInstallDeps,\n} from './install';\nimport { EVENT_LABEL, rowsOf, trustCodexHooks, type ListedHook } from '../lib/codex-trust';\nimport { readInstalledHosts, withNote } from './hosts';\nimport { CODEX_MCP_HOOKS_VERSION, renderCodexHooks } from './plugin-files';\nimport { shownLimits } from './spend-question';\nimport { fundStep, type FundingDeps } from './install-funding';\nimport { underAgentHarness } from '../lib/session';\nimport { SUGGESTED_FUND_USD } from './fee';\n\n/**\n * `tenjin install|uninstall|doctor` for Codex. Codex's own commands do\n * every plugin write: `codex plugin marketplace add` and `codex plugin add`\n * copy the plugin from Tenjin's runtime, `~/.tenjin/runtime/codex`, which\n * install sets up as the Claude install does, or from this package's\n * `dist/hosts/codex` where there is none. The plugin's own `PermissionRequest`\n * hook allows the request tool, so install writes no Codex config: the\n * wallet, the spend defaults and the plugin. User scope only.\n */\n\nexport interface CodexArgs {\n project?: boolean;\n yes?: boolean;\n noWallet?: boolean;\n /** `--max-auto-spend`: the per-call limit, at least 0.25 USD. */\n maxAutoSpend?: string;\n /** `--session-budget`: the daily limit in USD, or none. */\n sessionBudget?: string;\n}\n\nexport interface CodexRun {\n code: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface CodexSetupDeps\n extends WalletDeps, FundingDeps, Pick<RouterInstallDeps, 'promptLimits' | 'promptAmount'> {\n /** One `codex` command, recorded in tests. */\n run?: (args: string[]) => Promise<CodexRun>;\n /** Codex's merged config (`config/read`), or null when it could not be read. */\n config?: () => Promise<unknown>;\n /** Codex's hook list (`hooks/list`). */\n hooks?: () => Promise<unknown>;\n version?: () => Promise<string | null>;\n /** The marketplace folder without a runtime, by default this package's `dist/hosts/codex`. */\n hostsDir?: string | null;\n isInteractive?: boolean;\n homeDir?: string;\n /** Sets up Tenjin's runtime for this build; tests inject it, production runs `setupRuntime`. */\n runtime?: (o: Parameters<typeof setupRuntime>[0]) => Promise<RuntimeSetup>;\n /** Trusts the listed rows through Codex's app server; tests inject it. */\n trust?: typeof trustCodexHooks;\n}\n\nconst RUN_TIMEOUT_MS = 30_000;\n\nfunction runCodex(args: string[]): Promise<CodexRun> {\n const codex = resolveCodex();\n if (codex === null) {\n return Promise.resolve({ code: 127, stdout: '', stderr: 'codex was not found on PATH' });\n }\n return new Promise((resolve) => {\n execFile(\n codex.cmd,\n [...codex.prefix, ...args],\n { timeout: RUN_TIMEOUT_MS, maxBuffer: 4_000_000, windowsHide: true },\n (err, stdout, stderr) => {\n const code = err === null ? 0 : typeof err.code === 'number' ? err.code : 127;\n resolve({ code, stdout: String(stdout), stderr: String(stderr) });\n },\n );\n });\n}\n\n/** This package's `dist/hosts/codex`, by its version-free path under pnpm. */\nexport async function codexHostsDir(\n moduleDir: string = dirname(fileURLToPath(import.meta.url)),\n): Promise<string | null> {\n const catalog = join(moduleDir, 'hosts', 'codex', '.agents', 'plugins', 'marketplace.json');\n const stable = versionFreeEntry(catalog) ?? catalog;\n if ((await stat(stable).catch(() => null))?.isFile() !== true) return null;\n return dirname(dirname(dirname(stable)));\n}\n\nfunction failed(step: string, out: CodexRun): CliError {\n const detail = (out.stderr || out.stdout).trim().split('\\n')[0] ?? '';\n return new CliError('REFUSED', `\\`codex ${step}\\` failed${detail ? `: ${detail}` : ''}.`, {\n fix: 'Check that Codex CLI is installed and on PATH (`codex --version`), then re-run.',\n });\n}\n\n/**\n * The runtime's Codex marketplace, when the runtime has one: a `kept` older\n * runtime may predate it.\n */\nfunction runtimeHosts(rt: RuntimeSetup): string | null {\n if (rt.state !== 'active' && rt.state !== 'current' && rt.state !== 'kept') return null;\n const hosts = join(rt.root, 'codex');\n return existsSync(join(hosts, '.agents', 'plugins', 'marketplace.json')) ? hosts : null;\n}\n\n/**\n * `registered` is the folder Codex's config names for the `tenjin`\n * marketplace. Codex keeps one marketplace by that name, so one added from\n * another folder (the package's, before the runtime) is removed first.\n */\nasync function addPlugin(\n run: (args: string[]) => Promise<CodexRun>,\n hosts: string | null,\n registered: unknown,\n previousEnabled: boolean,\n restoreRuntime?: () => Promise<void>,\n): Promise<void> {\n let removed = false;\n let added = false;\n const moved =\n typeof registered === 'string' && hosts !== null && resolve(registered) !== resolve(hosts);\n try {\n if (hosts === null)\n throw new CliError('UPDATE_FAILED', 'The verified runtime carries no Codex plugin folder.');\n if (moved) {\n const old = await run(['plugin', 'marketplace', 'remove', CODEX_MARKETPLACE]);\n removed = old.code === 0;\n }\n const market = await run(['plugin', 'marketplace', 'add', hosts, '--json']);\n if (market.code !== 0) throw failed('plugin marketplace add', market);\n added = true;\n const plugin = await run(['plugin', 'add', CODEX_PLUGIN, '--json']);\n if (plugin.code !== 0) throw failed('plugin add', plugin);\n } catch (error) {\n try {\n await restoreRuntime?.();\n const restore = async (args: string[]): Promise<void> => {\n const out = await run(args);\n if (out.code !== 0) throw failed(args.join(' '), out);\n };\n if (added && (moved || typeof registered !== 'string')) {\n await restore(['plugin', 'marketplace', 'remove', CODEX_MARKETPLACE]);\n }\n if (moved && (removed || added) && typeof registered === 'string') {\n await restore(['plugin', 'marketplace', 'add', registered, '--json']);\n }\n if (previousEnabled && (removed || added)) {\n await restore(['plugin', 'add', CODEX_PLUGIN, '--json']);\n }\n } catch {\n throw new CliError(\n 'UPDATE_FAILED',\n 'Codex plugin registration failed and the previous registration could not be fully restored.',\n {\n fix: 'Run tenjin install --harness codex again. Your payment keys and funds were kept.',\n cause: error,\n },\n );\n }\n throw error;\n }\n}\n\nconst TRUST_STEP =\n 'Open Codex, run /hooks and trust the five Tenjin hooks, then start a new session.';\n/** What a person reads when this Codex cannot run the plugin's routing hooks. */\nconst CODEX_TOO_OLD = `Routing in Codex needs Codex ${CODEX_MCP_HOOKS_VERSION} or later, so Tenjin left its Codex plugin as it was. Ask your agent to update Codex.`;\n/** What a person reads when an install or update turned the hooks on itself. */\nconst NEW_SESSION_STEP = 'Start a new Codex session: Codex reads hooks when a session starts.';\n\n/**\n * ONE OF THE PLUGIN'S OWN HOOKS, as `hooks/list` lists it: our plugin's hooks\n * file, and at that event, group and position exactly the handler this build\n * renders (an `mcp_tool` leg into `router`/`hook`, the deny, or the allow).\n * Anything else in the list, another plugin's row or a row that moved, is not\n * ours to trust.\n */\nexport function ownCodexRow(row: ListedHook): boolean {\n if (row.pluginId !== CODEX_PLUGIN) return false;\n if (typeof row.sourcePath !== 'string' || !/[\\\\/]hooks[\\\\/]hooks\\.json$/.test(row.sourcePath)) {\n return false;\n }\n const at = /:([a-z_]+):(\\d+):(\\d+)$/.exec(typeof row.key === 'string' ? row.key : '');\n if (at === null) return false;\n const event = Object.keys(EVENT_LABEL).find((e) => EVENT_LABEL[e] === at[1]);\n const group = (renderCodexHooks().hooks[event ?? ''] as Record<string, unknown>[] | undefined)?.[\n Number(at[2])\n ] as { matcher?: string; hooks: Record<string, unknown>[] } | undefined;\n const want = group?.hooks[Number(at[3])];\n if (group === undefined || want === undefined) return false;\n if ((row.matcher ?? null) !== (group.matcher ?? null)) return false;\n return want.type === 'mcp_tool'\n ? row.handlerType === 'mcpTool' && row.server === want.server && row.tool === want.tool\n : row.handlerType === 'command' &&\n (row.command === want.command || row.command === want.commandWindows);\n}\n\n/**\n * TURNS THE PLUGIN'S HOOKS ON, as installing a Claude Code plugin does:\n * through `lib/codex-trust.ts`, which echoes back the `currentHash` Codex\n * reports for each of our rows and verifies them trusted. A row the person\n * turned off in `/hooks` (the allow hook's opt-out) stays off. False when\n * Codex lists none of our rows or any step fails: the person then reviews\n * them in `/hooks`.\n */\nasync function trustPlugin(deps: CodexSetupDeps): Promise<boolean> {\n const list = await (deps.hooks ?? (() => listCodexHooks(process.cwd(), 5_000)))();\n const ours = rowsOf(list).filter(ownCodexRow);\n if (ours.length === 0) return false;\n const keys = ours\n .filter(\n (r) => r.enabled !== false && r.trustStatus !== 'trusted' && r.trustStatus !== 'managed',\n )\n .map((r) => r.key as string);\n const result = await (deps.trust ?? trustCodexHooks)(\n deps.homeDir ?? homedir(),\n keys,\n ownCodexRow,\n );\n return result.ok;\n}\n\n/** What `tenjin update` says about Codex, in person-facing words with no command. */\nexport const CODEX_REFRESH_LINES = {\n done: \"Tenjin updated its Codex hooks. They run in Codex's next new session.\",\n review:\n \"Tenjin updated its Codex hooks but could not turn them on. Open /hooks in Codex and approve Tenjin's hooks so routing works.\",\n old: CODEX_TOO_OLD,\n failed:\n 'Tenjin could not update its Codex hooks. Ask your agent to run the Tenjin doctor for Codex.',\n} as const;\n\n/**\n * A bare `install --refresh` with the Codex refresh beside it: the Codex one\n * runs whatever Claude Code's did. Only Claude Code's \"nothing to refresh\"\n * (a Codex-only machine) gives way to a Codex line; any other Claude Code\n * failure stands, so `tenjin update` still reports it with its fix.\n */\nexport async function alongsideCodexRefresh(\n claude: () => Promise<CommandResult>,\n codex: () => Promise<string | undefined>,\n): Promise<CommandResult> {\n let out: CommandResult;\n try {\n out = await claude();\n } catch (err) {\n const line = await codex();\n const nothing = err instanceof CliError && err.message.startsWith(NOTHING_TO_REFRESH);\n if (line === undefined || !nothing) throw err;\n return { data: { notices: [line] }, humanLines: [line] };\n }\n return withNote(out, await codex());\n}\n\n/**\n * THE CODEX REFRESH `tenjin update` RUNS, in the new build (`install\n * --refresh`). Only where Codex already has the Tenjin plugin with the\n * command legs of an older build: it re-adds the plugin from the same folder,\n * which replaces Codex's copy, then turns the new hooks on (`trustPlugin`).\n * It never installs the plugin anywhere it was not, never asks, and never\n * throws: what happened is one line, or nothing.\n */\nexport async function refreshCodexPlugin(\n ctx: CommandContext,\n deps: CodexSetupDeps = {},\n): Promise<string | undefined> {\n try {\n const version = await (deps.version ?? codexVersion)();\n if (version === null) {\n const recorded = (await readInstalledHosts(ctx.dataDir))?.includes('codex') === true;\n return recorded ? CODEX_REFRESH_LINES.failed : undefined;\n }\n const rows = codexHookRows(\n await (deps.hooks ?? (() => listCodexHooks(process.cwd(), 5_000)))(),\n );\n if (rows.state === 'absent') return undefined;\n if (rows.state === 'unknown') return CODEX_REFRESH_LINES.failed;\n if (rows.routing !== 'free') return undefined;\n if (!atLeast(version, CODEX_MCP_HOOKS_VERSION)) return CODEX_REFRESH_LINES.old;\n const runtimeCodex = join(runtimeDir(ctx.dataDir), 'codex');\n const hosts = existsSync(join(runtimeCodex, '.agents', 'plugins', 'marketplace.json'))\n ? runtimeCodex\n : deps.hostsDir === undefined\n ? await codexHostsDir()\n : deps.hostsDir;\n const config = await (deps.config ?? (() => readCodexConfig(process.cwd(), 3_000)))();\n await addPlugin(\n deps.run ?? runCodex,\n hosts,\n at(config, 'marketplaces', CODEX_MARKETPLACE, 'source'),\n at(config, 'plugins', CODEX_PLUGIN, 'enabled') === true,\n );\n return (await trustPlugin(deps)) ? CODEX_REFRESH_LINES.done : CODEX_REFRESH_LINES.review;\n } catch {\n return CODEX_REFRESH_LINES.failed;\n }\n}\n\nfunction userScopeOnly(args: CodexArgs): void {\n if (args.project === true) {\n throw new CliError('USAGE', 'The Codex plugin installs for your user only; omit --project.');\n }\n}\n\nexport async function runCodexInstall(\n args: CodexArgs,\n ctx: CommandContext,\n deps: CodexSetupDeps = {},\n): Promise<CommandResult> {\n userScopeOnly(args);\n const run = deps.run ?? runCodex;\n const home = deps.homeDir ?? homedir();\n assertPluginInstallation(ctx.dataDir, home, deps.env ?? process.env);\n const config = await loadRawConfig(ctx.dataDir);\n const named = namedLimits(args);\n const humanOutput = ctx.flags.json === true ? false : (deps.isInteractive ?? ctx.io.isTTY);\n const canPrompt = humanOutput && (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n // The Claude install's spend model: `--yes` takes the defaults, the two\n // amount flags set the person's own, and a terminal asks once, before any\n // write, only when the file names neither limit. With no answer nothing is\n // written, the defaults hold, and the question goes to whoever ran it.\n const answered = args.yes === true || named.keys.length > 0;\n const unasked = config.maxAutoSpend === undefined && config.sessionBudget === undefined;\n const limits =\n named.keys.length > 0\n ? { ...shownLimits(config), ...named.limits }\n : args.yes === true\n ? shownLimits(config)\n : canPrompt && unasked\n ? await approveLimits(deps)\n : {};\n const rt = await (deps.runtime ?? defaultRuntime)({\n dataDir: ctx.dataDir,\n home,\n env: deps.env ?? process.env,\n version: pkg.version,\n moduleDir: dirname(fileURLToPath(import.meta.url)),\n refresh: false,\n });\n requireRuntime(rt);\n const { resolveWallet } = await import('../commands/install-wallet');\n const wallet: WalletOutcome = await resolveWallet(\n ctx,\n deps,\n args.noWallet === true ? 'flag' : undefined,\n false,\n );\n const spend = await persistRouterDefaults(ctx.dataDir, false, limits, named.keys);\n const fromRuntime = runtimeHosts(rt);\n const hosts =\n rt.state === 'skipped'\n ? deps.hostsDir === undefined\n ? await codexHostsDir()\n : deps.hostsDir\n : fromRuntime;\n // A Codex too old to run `mcp_tool` hooks keeps whatever copy it has: the\n // new hooks would be skipped, or the file refused. An unknown build installs.\n const version = await (deps.version ?? codexVersion)();\n const tooOld = version !== null && !atLeast(version, CODEX_MCP_HOOKS_VERSION);\n let next: string = CODEX_TOO_OLD;\n if (!tooOld) {\n const codexConfig = await (deps.config ?? (() => readCodexConfig(process.cwd(), 3_000)))();\n await addPlugin(\n run,\n hosts,\n at(codexConfig, 'marketplaces', CODEX_MARKETPLACE, 'source'),\n at(codexConfig, 'plugins', CODEX_PLUGIN, 'enabled') === true,\n rt.restore,\n );\n next = (await trustPlugin(deps).catch(() => false)) ? NEW_SESSION_STEP : TRUST_STEP;\n }\n\n // Read back after the write, as the Claude install does.\n const settings = await resolveContextSettings(ctx);\n const { policy } = settings;\n const effective = effectiveLimits(policy);\n // Run again by the agent in Codex, a bare install finds Codex itself.\n const install = [\n `${continuationCommand(rt)} install`,\n ...(args.noWallet ? ['--no-wallet'] : []),\n ].join(' ');\n const spendAsk: QuestionStep | undefined =\n !canPrompt && !answered && unasked ? spendStepFor(install) : undefined;\n const asksAgent = !canPrompt && underAgentHarness(deps.env ?? process.env);\n const funding =\n !tooOld && (asksAgent || canPrompt) && spendAsk === undefined\n ? await (deps.funding ?? fundStep)(\n wallet,\n settings.rpcUrl,\n deps,\n `${continuationCommand(rt)} fund ${SUGGESTED_FUND_USD}`,\n )\n : undefined;\n const nextSteps = [\n ...(spendAsk !== undefined ? [spendAsk] : []),\n ...(funding?.step !== undefined ? [funding.step] : []),\n ];\n if (asksAgent && nextSteps.length > 0)\n next = `Follow the instructions in nextSteps, then ${next}`;\n return {\n data: {\n plugin: CODEX_PLUGIN,\n wallet,\n spend: { ...spend, effective },\n runtime: runtimeData(rt),\n nextSteps,\n disclosure: DISCLOSURE,\n ...(funding?.warning !== undefined ? { fundingWarning: funding.warning } : {}),\n next,\n },\n humanLines: [\n tooOld\n ? `Tenjin keeps its earlier Codex setup until Codex is updated (${version}).`\n : 'Tenjin is installed for Codex.',\n ...(tooOld ? [] : CAPABILITY_LINES.map((line) => ` ${line}`)),\n ...runtimeLines(ctx, rt, home, true),\n ...walletLines(ctx, wallet, 'Codex'),\n ...(funding?.warning !== undefined ? [funding.warning] : []),\n ...(spendAsk !== undefined\n ? [\n ` Ask the person in this session: ${spendAsk.question}`,\n ...spendAsk.options.map(\n (o) => ` ${o.label}${o.recommended ? ' (recommended)' : ''}: ${o.command}`,\n ),\n ]\n : []),\n ],\n humanTail: receiptTail(ctx, policy, next),\n };\n}\n\nexport async function runCodexUninstall(\n args: CodexArgs,\n _ctx: CommandContext,\n deps: CodexSetupDeps = {},\n): Promise<CommandResult> {\n userScopeOnly(args);\n const run = deps.run ?? runCodex;\n const removed = await run(['plugin', 'remove', CODEX_PLUGIN, '--json']);\n if (removed.code !== 0) throw failed('plugin remove', removed);\n // Absent already is the state uninstall wants.\n await run(['plugin', 'marketplace', 'remove', CODEX_MARKETPLACE]);\n return {\n data: { removed: CODEX_PLUGIN, marketplace: CODEX_MARKETPLACE },\n humanLines: [\n `Codex plugin ${CODEX_PLUGIN} and its marketplace removed. The wallet and Claude setup are kept.`,\n ],\n };\n}\n\nconst PLUGIN_LINE: Record<CodexHookRows['state'], string> = {\n trusted: 'installed, its hooks on and trusted',\n review: `installed, its hooks need review. ${TRUST_STEP}`,\n absent: 'not installed or turned off. Run `tenjin install --harness codex`',\n unknown: \"could not read Codex's hook list\",\n};\n\n/**\n * What the plugin's hooks and server run, from the folder Codex's config names\n * for the marketplace: information only. Nothing when Codex names none, or\n * names another folder on a machine with no runtime to move to.\n */\nfunction runsFrom(ctx: CommandContext, deps: CodexSetupDeps, source: unknown): string | null {\n if (typeof source !== 'string') return null;\n const home = deps.homeDir ?? homedir();\n const hosts = join(runtimeDir(ctx.dataDir), 'codex');\n if (resolve(source) === resolve(hosts)) return `Tenjin's runtime (${tilde(hosts, home)})`;\n if (!hasRuntime(ctx.dataDir, home)) return null;\n return \"`tenjin` from your PATH; run `tenjin install --harness codex` to move it to Tenjin's runtime\";\n}\n\nconst ROUTING_LINE: Record<CodexHookRows['routing'], string> = {\n paid: 'its routing hooks call the router MCP server, which pays the routing fee under your wallet spend limits',\n free: 'its routing hooks are commands from an older build, which cannot pay the routing fee, so they offer nothing. Run `tenjin update` or `tenjin install --harness codex` to replace them',\n unknown: \"could not read how Codex runs the plugin's routing hooks\",\n};\n\n/**\n * Reads Codex's view of the plugin and writes nothing. Routing compatibility\n * is read the same way, with nothing paid or sent: the legs must be `mcp_tool`\n * hooks into the plugin's server (`codexHookRows`), and the Codex build must\n * run them ({@link CODEX_MCP_HOOKS_VERSION}).\n */\nexport async function runCodexDoctor(\n args: CodexArgs,\n ctx: CommandContext,\n deps: CodexSetupDeps = {},\n): Promise<CommandResult> {\n userScopeOnly(args);\n const [list, config, version] = await Promise.all([\n (deps.hooks ?? (() => listCodexHooks(process.cwd(), 5_000)))(),\n (deps.config ?? (() => readCodexConfig(process.cwd(), 3_000)))(),\n (deps.version ?? codexVersion)(),\n ]);\n const hooks = codexHookRows(list);\n // With its allow hook off, `approval_policy = \"never\"` refuses the tool.\n const refused = hooks.allowOff && at(config, 'approval_policy') === 'never';\n // An unknown build is not failed on: only a known older one cannot run the legs.\n const tooOld = version !== null && !atLeast(version, CODEX_MCP_HOOKS_VERSION);\n const routing = hooks.state === 'absent' ? null : hooks.routing;\n // Command legs from an older build warn without failing: `tenjin update`\n // replaces them, and Codex still runs the rest of the plugin.\n const ok = hooks.state === 'trusted' && !refused && routing !== 'unknown' && !tooOld;\n const runs = runsFrom(ctx, deps, at(config, 'marketplaces', CODEX_MARKETPLACE, 'source'));\n const auto = hasRuntime(ctx.dataDir, deps.homeDir ?? homedir())\n ? autoUpdateLine(runtimeDir(ctx.dataDir))\n : null;\n const lines = [\n `Setup: ${ok && routing !== 'free' ? 'ready for Codex' : 'needs attention'}.`,\n 'Current Codex session: not verified by this check.',\n 'Paid routing: wallet and funds not checked.',\n '',\n `Codex plugin: ${PLUGIN_LINE[hooks.state]}`,\n `Request tool: ${refused ? 'refused: its allow hook is off in /hooks and approval_policy is never' : hooks.allowOff ? 'asks before each call (its allow hook is off in /hooks)' : 'allowed by its plugin hook, under your wallet spend limits'}`,\n ...(routing !== null\n ? [`${routing === 'free' ? '! ' : ''}Routing: ${ROUTING_LINE[routing]}`]\n : []),\n tooOld\n ? `Codex build: ${version}, which cannot run the plugin's routing hooks. Update Codex to ${CODEX_MCP_HOOKS_VERSION} or later`\n : `Codex build: ${version ?? 'unknown'} (web hooks last captured on ${WEB_VERIFIED_VERSION}; information only)`,\n ...(runs !== null ? [`Codex plugin runs: ${runs}`] : []),\n ...(auto !== null ? [auto] : []),\n ];\n const data = {\n plugin: CODEX_PLUGIN,\n hooks: hooks.state,\n allowOff: hooks.allowOff,\n routing,\n version,\n ok,\n };\n if (!ok) {\n throw new CliError('REFUSED', 'The Codex plugin is not ready.', {\n details: data,\n fix: lines.join('\\n'),\n });\n }\n return { data, humanLines: lines };\n}\n","import { withAppServer } from './codex-app-server';\nimport { isRecord } from './guards';\n\n/**\n * The one write that makes the hook handlers this CLI registered run: `install`\n * needs to move them from \"the file exists\" to \"the harness will run it\".\n *\n * Codex gates a handler on `[hooks.state]` in `$CODEX_HOME/config.toml`: a row keyed\n * `\"<source path>:<event_snake>:<group>:<handler>\"` carrying `enabled` and a\n * `trusted_hash`, and the handler runs only when it is enabled and that hash\n * still matches the one Codex recomputes from the file.\n *\n * TRUSTING IS PART OF INSTALLING, and it goes through Codex's own supported\n * path: read the rows and their `currentHash` from `hooks/list`, upsert those\n * keys through `config/batchWrite`, then list again and require them back\n * trusted. That is the same call the `/hooks` browser makes, and it matches\n * Claude Code's contract that installing a hook activates it, rather than\n * reporting success over a loop that cannot run.\n *\n * WHAT STAYS FORBIDDEN, and the distinction is the whole of the boundary:\n *\n * - COMPUTING a `trusted_hash`. The value is a normalized, TOML-projected,\n * canonical-JSON form private to Codex's build. We only ever echo back the\n * `currentHash` Codex itself just reported, so trust cannot outlive the\n * bytes Codex hashed. A hash of our own would be an assertion about a file\n * Codex has not read.\n * - Trusting a row we did not generate. Every key is matched against the\n * complete handler identity this install wrote: our source file, our\n * command, our event and index. Another tool's entry in the same file is\n * never touched.\n * - Reporting success on a partial result. Listing, writing and verifying all\n * have to land, or the install fails and says which step did not.\n */\n\n/** Codex's snake-case event labels, in the order its `hooks.state` keys use. */\nexport const EVENT_LABEL: Readonly<Record<string, string>> = {\n PreToolUse: 'pre_tool_use',\n PermissionRequest: 'permission_request',\n PostToolUse: 'post_tool_use',\n PreCompact: 'pre_compact',\n PostCompact: 'post_compact',\n SessionStart: 'session_start',\n SessionEnd: 'session_end',\n UserPromptSubmit: 'user_prompt_submit',\n SubagentStart: 'subagent_start',\n SubagentStop: 'subagent_stop',\n Stop: 'stop',\n Interrupt: 'interrupt',\n};\n\n/** One handler as `hooks/list` reports it; every field optional, since this is\n * another program's wire format and a missing one means \"cannot tell\". */\nexport interface ListedHook {\n [field: string]: unknown;\n key?: unknown;\n enabled?: unknown;\n trustStatus?: unknown;\n sourcePath?: unknown;\n currentHash?: unknown;\n command?: unknown;\n}\n\nexport interface TrustProbeOptions {\n env?: NodeJS.ProcessEnv;\n /** How long to wait for the app server. Past it the attempt fails at `list`. */\n timeoutMs?: number;\n /** Seam for tests: answer requests directly instead of spawning an app\n * server. `undefined` from it means the same as no reply. */\n connect?: (method: string, params: unknown) => Promise<unknown>;\n}\n\n/**\n * An install has a person waiting, so the app server gets a few seconds and no\n * more. A slow answer reads as \"could not ask\", never as a verdict.\n */\nconst PROBE_MS = 8_000;\n\n/** The handler rows out of a `hooks/list` result, flattened across its cwds. */\nexport function rowsOf(result: unknown): ListedHook[] {\n if (!isRecord(result) || !Array.isArray(result.data)) return [];\n const out: ListedHook[] = [];\n for (const group of result.data) {\n if (!isRecord(group) || !Array.isArray(group.hooks)) continue;\n for (const hook of group.hooks) if (isRecord(hook)) out.push(hook as ListedHook);\n }\n return out;\n}\n\n/** What one trust attempt did, in the terms `install` reports it. */\nexport interface TrustResult {\n ok: boolean;\n /** Keys Codex confirmed enabled and trusted on the verifying read. */\n trusted: string[];\n /** Which step did not complete, on a failure. */\n failedAt?: 'list' | 'write' | 'verify';\n /** One line naming what went wrong, for the operator. */\n reason?: string;\n}\n\n/**\n * Trust exactly the handlers this install wrote, and prove it.\n *\n * THREE ROUND TRIPS, ALL REQUIRED. List to learn the hashes Codex computed for\n * OUR rows; upsert only those keys; list again and require the same keys back\n * with the same hashes, enabled and trusted. The verifying read is the point:\n * a write that returned without error still has not been shown to have taken\n * effect, and an install that skipped this could report success over a loop\n * that will not run, which is the failure this whole change exists to end.\n *\n * `ownedBy` is the second half of \"only our rows\". The keys already come from\n * the file we wrote, but a key is a path and two indices; this also requires\n * the listed handler's command to be the one we generated, so a row that moved\n * under our key is left alone rather than trusted on its position.\n */\nexport async function trustCodexHooks(\n home: string,\n keys: readonly string[],\n ownedBy: (row: ListedHook) => boolean,\n opts: TrustProbeOptions = {},\n): Promise<TrustResult> {\n const env = opts.env ?? process.env;\n const timeoutMs = opts.timeoutMs ?? PROBE_MS;\n if (keys.length === 0) return { ok: true, trusted: [] };\n\n const run = async (\n request: (method: string, params: unknown) => Promise<unknown>,\n ): Promise<TrustResult> => {\n const before = await request('hooks/list', { cwds: [] });\n if (before === undefined) {\n return {\n ok: false,\n trusted: [],\n failedAt: 'list' as const,\n reason: 'hooks/list did not answer',\n };\n }\n const wanted = new Set(keys);\n const mine = rowsOf(before).filter(\n (r) => typeof r.key === 'string' && wanted.has(r.key) && ownedBy(r),\n );\n if (mine.length !== keys.length) {\n return {\n ok: false,\n trusted: [],\n failedAt: 'list' as const,\n reason: `Codex listed ${mine.length} of the ${keys.length} entries this install wrote`,\n };\n }\n // Only the rows we generated, each carrying the hash Codex just reported\n // for it. `upsert` leaves every other row in `hooks.state` untouched.\n const value: Record<string, { trusted_hash: string; enabled: true }> = {};\n for (const row of mine) {\n const hash = typeof row.currentHash === 'string' ? row.currentHash : null;\n if (hash === null) {\n return {\n ok: false,\n trusted: [],\n failedAt: 'list' as const,\n reason: 'Codex reported an entry with no currentHash',\n };\n }\n value[row.key as string] = { trusted_hash: hash, enabled: true };\n }\n const wrote = await request('config/batchWrite', {\n edits: [{ keyPath: 'hooks.state', value, mergeStrategy: 'upsert' }],\n reloadUserConfig: true,\n });\n if (wrote === undefined) {\n return {\n ok: false,\n trusted: [],\n failedAt: 'write' as const,\n reason: 'config/batchWrite was refused',\n };\n }\n\n // VERIFY. Same keys, same hashes, enabled and trusted, read back from the\n // binary rather than inferred from a write that did not error.\n const after = await request('hooks/list', { cwds: [] });\n if (after === undefined) {\n return {\n ok: false,\n trusted: [],\n failedAt: 'verify' as const,\n reason: 'the verifying hooks/list did not answer',\n };\n }\n const confirmed = rowsOf(after).filter(\n (r) =>\n typeof r.key === 'string' &&\n wanted.has(r.key) &&\n ownedBy(r) &&\n r.enabled !== false &&\n (r.trustStatus === 'trusted' || r.trustStatus === 'managed') &&\n r.currentHash === value[r.key]?.trusted_hash,\n );\n if (confirmed.length !== keys.length) {\n return {\n ok: false,\n trusted: confirmed.map((r) => r.key as string),\n failedAt: 'verify' as const,\n reason: `Codex confirmed ${confirmed.length} of ${keys.length} entries as trusted after the write`,\n };\n }\n return { ok: true, trusted: confirmed.map((r) => r.key as string) };\n };\n\n const outcome =\n opts.connect !== undefined\n ? await run(opts.connect)\n : await withAppServer(home, env, timeoutMs, run);\n\n return (\n outcome ?? {\n ok: false,\n trusted: [],\n failedAt: 'list',\n reason: 'the codex app server could not be reached',\n }\n );\n}\n"],"mappings":";;;;;;;;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@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/doctor.ts","../src/router/eligibility-check.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, realpath, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join, posix, resolve, win32 } from 'node:path';\nimport pkg from '../../package.json';\nimport { autoUpdateLine } from '../lib/auto-update';\nimport { MAX_AUTO_SPEND_FLOOR_ATOMIC } from '../lib/config';\nimport { hasCode } from '../lib/errno';\nimport { CliError } from '../lib/errors';\nimport { toMoney } from '../lib/money';\nimport { isDefaultDataDir, launcherDir, realOr, runtimeDir, samePath, tilde } from '../lib/paths';\nimport { readRuntimeState, runtimeBuild, type RuntimeState } from '../lib/runtime-layout';\nimport { resolveContextSettings } from '../lib/settings';\nimport { isNewer } from '../lib/update-check';\nimport type { WalletProvider } from '../lib/wallet';\nimport { createLocalProvider, type PassphraseOverrides } from '../lib/wallet/local';\nimport { describeStoreLocation } from '../lib/wallet/passphrase';\nimport { walletFileExists } from '../lib/wallet/store';\nimport type { SigningSource, UnlockReason } from '../lib/wallet-unlock';\nimport type { CommandContext, CommandResult } from '../context';\nimport { agentsWithoutRequestTool } from './agent-tools';\nimport { readAliveStamp, type AliveStamp } from './alive';\nimport {\n CLAUDE_CODE_FLOOR,\n findClaudeBinary,\n jsonList,\n readClaudeCode,\n runClaude,\n type ClaudeBinary,\n type ClaudeCodeState,\n} from './claude-cli';\nimport { claudeInstallAt, settingsInstallPaths } from './claude-install';\nimport { isDefiniteBlock } from './eligibility';\nimport { checkEligibility, type Eligibility, type EligibilityInput } from './eligibility-check';\nimport { SUGGESTED_FUND_USD, unpaid, usd } from './fee';\nimport { NEW_SESSION_STEP, pluginProof, projectInstallHere } from './install';\nimport { inspectLegacyInstall, type LegacyInstall } from './legacy-install';\nimport { routerSettings, type RouterSettings } from './settings';\nimport { MARKETPLACE_NAME, MCP_SERVER_NAME, PLUGIN_ID, PLUGIN_SERVER, REQUEST_TOOL } from './names';\nimport { LAUNCHER_MARKER, PLUGIN_DIR, RUNTIME_MISSING_FIX } from './plugin-files';\nimport { folderState, readPluginListing, type PluginScope } from './plugin-registration';\nimport { probeRouter, type RouterCheck } from './reachability';\nimport {\n mcpServersState,\n readProcessSnapshot,\n RECONNECT_FIX,\n type InstalledAt,\n type ListMcpProcesses,\n type ListProcesses,\n type ProcessSnapshot,\n} from './mcp-processes';\nimport { clearRouterMemo, readRouterMemo, type RouterMemo } from './router-memo';\nimport {\n liveObservations,\n readObservations,\n servedObservations,\n type RouterObservation,\n} from './router-observation';\nimport {\n KEYCHAIN_LOCKED_FIX,\n NO_SESSION_CHECKED,\n REPAIR_CLAUSE,\n UNKNOWN_DETAIL,\n WALLET_REASONS,\n} from './wallet-reasons';\n\n/** Collect Claude Code setup, payment eligibility and session evidence without a paid task. */\n\nexport type { RouterCheck };\n\nexport interface RouterDoctorDeps {\n homeDir?: string;\n cwd?: string;\n /** Check the project install, as `install --project` registered it. Absent,\n * a project install in `cwd` is found ({@link projectInstallHere}). */\n project?: boolean;\n env?: NodeJS.ProcessEnv;\n /** Finds the `claude` binary; tests inject one. */\n findClaude?: (env: NodeJS.ProcessEnv) => ClaudeBinary | null;\n fetchImpl?: typeof fetch;\n /** Node's own version, for the floor check. */\n nodeVersion?: string;\n /** This user's running routers and Claude Code processes; tests inject them. */\n listProcesses?: ListProcesses;\n /** This user's running `tenjin mcp` processes alone (the older seam); tests inject them. */\n listMcpProcesses?: ListMcpProcesses;\n /** When this build was installed; tests inject it. */\n installedAt?: InstalledAt;\n now?: () => number;\n /** The one eligibility check doctor makes; tests inject it. Defaults to {@link checkEligibility}. */\n eligibility?: (input: EligibilityInput) => Promise<Eligibility>;\n /** What the running `tenjin mcp` processes wrote about themselves; tests inject it. */\n readObservations?: (dataDir: string) => Promise<RouterObservation[]>;\n /** Whether a pid is alive, when `ps` could not run; tests inject it. */\n isAlive?: (pid: number) => boolean;\n /**\n * Passphrase-resolution seam for the wallet's verify (keychain exec,\n * platform). Tests MUST set it, or inject `eligibility`, before a verify can\n * run: without it, a wallet's verify reads the developer's own keychain.\n */\n walletPassphrase?: PassphraseOverrides;\n /** Where Claude Code starts the router from, read from the plugin it loads; tests inject it. */\n readLaunch?: (binary: ClaudeBinary | null) => Promise<PluginLaunch | null>;\n /** Runs `<command> <entry> --version` as Claude Code would, with no shell; tests inject it. */\n runVersion?: (command: string, entry: string) => Promise<VersionRun>;\n /** The first `tenjin` on PATH and what it is; tests inject it. */\n pathTenjin?: () => Promise<PathTenjin | null>;\n /** This machine's platform when Tenjin pins no Node for it, else null; tests inject it. */\n unpinnedPlatform?: () => Promise<string | null>;\n}\n\n/** The plugin's `router` server as Claude Code will start it. */\nexport interface PluginLaunch {\n /** The marketplace folder, or the plugin folder of the folder fallback. */\n path: string;\n source: 'marketplace' | 'folder';\n /** Null when the folder holds no `router` server to read: its `.mcp.json` is gone or names none. */\n command: string | null;\n /** Its first argument, `${CLAUDE_PLUGIN_ROOT}` expanded; null when it has none. */\n entry: string | null;\n /**\n * The plugin's `.mcp.json` is not there at all: the folder Claude Code loads\n * was deleted (an npm prefix a Node upgrade took, or the runtime), so\n * nothing can start the router from it.\n */\n missing?: true;\n}\n\nexport interface VersionRun {\n code: number | null;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n}\n\nexport interface PathTenjin {\n path: string;\n /** A launcher Tenjin wrote. */\n marked: boolean;\n version: string | null;\n /** A build that hands a terminal run to Tenjin's runtime (its package carries `tenjinRuntime`). */\n handsOff: boolean;\n /** No `tenjin-cli` package was identified behind it (a Volta or pnpm shim, or another program). */\n unknown?: true;\n}\n\nconst NODE_FLOOR = 22;\n\n/**\n * How Claude Code starts the router, which picks the fixes that fit:\n * Tenjin's runtime; the `node` on its PATH where `tenjin install` can move it\n * to the runtime; or that PATH where it cannot, on a platform Tenjin pins no\n * Node for or under a data dir of its own (decisions 15 and 18).\n */\ntype Layout = 'runtime' | 'path' | 'path-only';\n\n/** The line the PATH layout's fixes end with, where the runtime can end the dependence they describe. */\nconst moveToRuntime = (layout: Layout): string =>\n layout === 'path' ? ' Or run `tenjin install` to move Tenjin to its own runtime.' : '';\n\n/**\n * The stamp row's fix: a new session first, since a reload never stamps. On\n * the PATH layout, then the Node Claude Code runs; a running Claude Code keeps\n * the PATH it started with, so a new window is not enough there.\n */\nfunction stampFix(layout: Layout): string {\n const first =\n \"Start a new Claude Code session and run `tenjin doctor` again: `/reload-plugins` does not run the plugin's `SessionStart`, so only a new session writes the stamp.\";\n return layout !== 'runtime'\n ? `${first} If it still warns, run \\`node --version\\` in that session's shell: Claude Code starts the plugin with the Node on its own PATH, and it must be 22 or newer. After installing or updating Node, quit Claude Code fully, then start a new session.${moveToRuntime(layout)}`\n : first;\n}\n\nexport async function runRouterDoctor(\n ctx: CommandContext,\n deps: RouterDoctorDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n const cwd = deps.cwd ?? process.cwd();\n // WITHOUT THE FLAG, THE INSTALL THIS DIRECTORY HOLDS: a project install\n // found here is the one a session here runs, so it is the one checked.\n const project = deps.project ?? (await projectInstallHere(cwd, home, env));\n // From the directory doctor runs in, which is the one a session there would use.\n const router = await routerSettings(\n { cwd, dataDir: ctx.dataDir },\n deps.homeDir !== undefined ? { homeDir: deps.homeDir } : {},\n ).catch((err: unknown) => (err instanceof Error ? err : new Error(String(err))));\n const settings = await resolveContextSettings(ctx);\n const claude = await readClaudeCode(env, cwd, deps.findClaude ?? findClaudeBinary);\n const scope: PluginScope = project ? 'local' : 'user';\n const paths = settingsInstallPaths(project, env, home, cwd);\n const legacy = await inspectLegacyInstall(paths.settingsPath, paths.mcpFile);\n // The processes and what the routers saw, read first: before `claude mcp\n // get` (serverCheck) starts a `tenjin mcp` of its own. That router serves no\n // hook, so it never reads as a session, and nothing it does reaches this\n // snapshot either.\n const [{ snapshot, installed }, observations] = await Promise.all([\n readProcessSnapshot(deps),\n (deps.readObservations ?? readObservations)(ctx.dataDir).catch(() => [] as RouterObservation[]),\n ]);\n const live = servedObservations(\n liveObservations(observations, snapshot?.routers ?? null, deps.isAlive),\n );\n\n // Only the default profile owns plugin registration and a private runtime.\n const runtime = isDefaultDataDir(ctx.dataDir, home);\n const root = runtimeDir(ctx.dataDir);\n const state = runtime ? readRuntimeState(root) : null;\n const launch = await (\n deps.readLaunch ?? ((binary) => readPluginLaunch(binary, { env, home, cwd, scope }))\n )(claude.binary).catch(() => null);\n // A platform Tenjin pins no Node for never gets a runtime.\n const unpinned = runtime ? await (deps.unpinnedPlatform ?? thisPlatformUnpinned)() : null;\n // Which fixes fit: the ones that blame the `node` on Claude Code's PATH only\n // when that is what starts the plugin, read from the folder Claude Code\n // loads. One under `runtime/claude` whose files are gone is the runtime's.\n // A folder that no longer holds the plugin is no PATH's fault, whichever it is.\n const fromPath =\n launch === null\n ? state === null\n : launch.command === null\n ? !(await pluginGone(launch, root))\n : launch.command === 'node';\n const layout: Layout = !fromPath\n ? 'runtime'\n : runtime && unpinned === null\n ? 'path'\n : 'path-only';\n\n const checks: RouterCheck[] = [nodeCheck(deps.nodeVersion ?? process.version)];\n checks.push(claudeCodeCheck(claude));\n const plugin = await pluginCheck(claude, {\n scope,\n env,\n home,\n cwd,\n dataDir: ctx.dataDir,\n legacy,\n installed,\n snapshot,\n live,\n layout,\n });\n checks.push(plugin.check);\n if (plugin.registered && runtime) {\n const onPath = state !== null ? await (deps.pathTenjin ?? (() => findPathTenjin(env)))() : null;\n checks.push(\n await runtimeCheck({ launch, state, root, home, env, project, onPath, unpinned, deps }),\n );\n const old = pathTenjinCheck(onPath, home);\n if (old !== null) checks.push(old);\n }\n if (plugin.registered && claude.binary !== null) {\n const serving = live.find(\n (o) =>\n o.harness === 'claude' &&\n o.launchedByPlugin &&\n o.cliVersion === pkg.version &&\n resolve(o.cwd) === resolve(cwd),\n );\n checks.push(\n serving !== undefined\n ? {\n name: 'router server',\n status: 'ok',\n required: true,\n detail: `${PLUGIN_SERVER} is serving a Claude Code session in this directory (pid ${serving.pid})`,\n }\n : await serverCheck(claude.binary, env, cwd, layout),\n );\n }\n if (legacy.present || legacy.unreadable !== undefined) {\n checks.push(await migrationCheck(legacy, claude, ctx.dataDir, env, cwd));\n }\n checks.push(routingCheck(router));\n checks.push(\n mcpServersState(snapshot?.routers ?? null, installed, pkg.version, RECONNECT_FIX).check,\n );\n checks.push(spendCheck(settings.policy.maxAutoSpendAtomic, settings.policy.sessionBudgetAtomic));\n checks.push(experimentalCheck(settings.experimentalBazaar));\n\n let host: string | null;\n try {\n host = new URL(settings.baseUrl).host;\n } catch {\n // The router check below names the bad base URL and its fix.\n host = null;\n }\n const e = await shellEligibility(ctx, deps, env, {\n policy: settings.policy,\n rpcUrl: settings.rpcUrl,\n host: host ?? '',\n });\n checks.push(host === null ? UNPARSED_BASE_URL_ROW : routingFeeRow(e, host));\n checks.push(walletRow(e, ctx.dataDir));\n checks.push(sessionRow(e, live, pkg.version));\n const now = deps.now?.() ?? Date.now();\n const probe = await probeRouter(settings.baseUrl, {\n timeoutMs: ctx.flags.timeout,\n env,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n // A probe the router answered ends the routing legs' backoff at once: ok,\n // or a warning about its 402 (a quote above the ceiling, or one this CLI\n // cannot read).\n if (probe.status !== 'fail') {\n await clearRouterMemo(ctx.dataDir, 'unreachable', settings.baseUrl);\n checks.push(probe);\n } else {\n checks.push(\n withBackoff(\n probe,\n await readRouterMemo(ctx.dataDir, 'unreachable', settings.baseUrl, now),\n now,\n ),\n );\n }\n const agents = await subagentsCheck(cwd, home);\n if (agents !== null) checks.push(agents);\n\n const failure = checks.find((c) => c.status === 'fail' && c.required);\n const data = {\n checks,\n dataDir: ctx.dataDir,\n baseUrl: settings.baseUrl,\n scope,\n settingsPath: paths.settingsPath,\n session: { observed: live },\n eligibility: {\n canSign: e.canSign,\n canPayRouting: e.canPayRouting,\n savedSign: e.savedSign,\n balanceAtomic: e.balanceAtomic?.toString() ?? null,\n creditAtomic: e.creditAtomic?.toString() ?? null,\n },\n };\n if (failure !== undefined) {\n // REFUSED, the exit-3 class: a machine this command found unready is\n // understood and refused, not a runtime failure of the command itself.\n throw new CliError('REFUSED', failure.detail, {\n ...(failure.fix !== undefined ? { fix: failure.fix } : {}),\n details: data,\n });\n }\n // Information only, above the summary: how the last background update ended.\n const lines = doctorLines(checks);\n const auto = state !== null ? autoUpdateLine(root) : null;\n if (auto !== null) lines.splice(lines.length - 1, 0, auto);\n return { data, humanLines: lines };\n}\n\n/** The routing-fee row when there is no host to check it against. */\nconst UNPARSED_BASE_URL_ROW: RouterCheck = {\n name: 'routing fee',\n status: 'warn',\n required: false,\n detail: 'not checked, because the base URL is not a URL',\n checked: false,\n};\n\n/** `env` without TENJIN_WALLET_PASSPHRASE: what a Claude Code started without it would see. */\nfunction withoutEnvPassphrase(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const rest = { ...env };\n delete rest.TENJIN_WALLET_PASSPHRASE;\n return rest;\n}\n\n/**\n * The wallet as this shell would open it: `resolveWalletProvider`'s provider,\n * built from doctor's own env (so a test's env, not the runner's, decides).\n * Nothing here prompts: `verify` forces `isTTY: false` and keeps its 5 s read\n * deadline, and `describe` never needs a passphrase.\n */\nfunction walletProviderFor(\n ctx: CommandContext,\n env: NodeJS.ProcessEnv,\n overrides: PassphraseOverrides | undefined,\n): WalletProvider {\n return createLocalProvider({\n dir: ctx.dataDir,\n env,\n passphrase: { ...overrides, isTTY: ctx.io.isTTY ? undefined : false },\n });\n}\n\n/**\n * The one eligibility check, for the wallet, routing-fee and session rows.\n * Never rejects: a check that throws reads as \"could not check\" on every row\n * it feeds, never as ok and never as a block.\n *\n * Saved passphrase first: with TENJIN_WALLET_PASSPHRASE set, `verifySaved`\n * asks what install's signing check asks first: does the keychain or the file\n * open the wallet without the variable?\n * So a correct variable that a store also holds reports that store, and the\n * session row can say whether a Claude Code started without it could sign.\n */\nasync function shellEligibility(\n ctx: CommandContext,\n deps: RouterDoctorDeps,\n env: NodeJS.ProcessEnv,\n s: { policy: EligibilityInput['policy']; rpcUrl: string; host: string },\n): Promise<Eligibility> {\n try {\n const keySet = (env.TENJIN_WALLET_KEY ?? '').trim().length > 0;\n const provider =\n keySet || (await walletFileExists(ctx.dataDir))\n ? walletProviderFor(ctx, env, deps.walletPassphrase)\n : null;\n const passphraseSet = (env.TENJIN_WALLET_PASSPHRASE ?? '').length > 0;\n return await (deps.eligibility ?? checkEligibility)({\n dataDir: ctx.dataDir,\n env,\n policy: s.policy,\n rpcUrl: s.rpcUrl,\n host: s.host,\n timeoutMs: ctx.flags.timeout,\n provider,\n ...(provider !== null && passphraseSet\n ? {\n verifySaved: () =>\n walletProviderFor(ctx, withoutEnvPassphrase(env), deps.walletPassphrase).verify?.() ??\n Promise.resolve(undefined),\n }\n : {}),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n const failed = {\n status: 'unknown' as const,\n reason: 'check_failed',\n detail: UNKNOWN_DETAIL['check_failed']!,\n };\n return {\n address: null,\n source: null,\n canSign: failed,\n canPayRouting: failed,\n savedSign: null,\n balanceAtomic: null,\n creditAtomic: null,\n describeError: null,\n };\n }\n}\n\n/** Installation, payment readiness and session evidence are separate claims. */\nexport function doctorLines(checks: RouterCheck[]): string[] {\n const act = checks.filter((c) => c.status !== 'ok' && c.checked !== false).length;\n const unchecked = checks.filter((c) => c.checked === false).length;\n const allPass = checks.every((c) => c.status === 'ok');\n const plugin = checks.find((c) => c.name === 'plugin');\n const runtimeUnchecked = checks.some((c) => c.name === 'runtime' && c.checked === false);\n const setup =\n plugin === undefined\n ? 'not checked'\n : plugin.status !== 'ok' || checks.some((c) => c.required && c.status !== 'ok')\n ? 'needs attention'\n : runtimeUnchecked\n ? 'not verified'\n : 'ready';\n const payment = checks.filter((c) => ['routing', 'routing fee', 'router'].includes(c.name));\n const paid =\n checks.some((c) => c.required && c.status !== 'ok' && c.checked !== false) ||\n payment.some((c) => c.status !== 'ok' && c.checked !== false)\n ? 'unavailable'\n : !runtimeUnchecked && payment.length === 3 && payment.every((c) => c.status === 'ok')\n ? 'ready on this machine'\n : 'not checked';\n const session = checks.find((c) => c.name === 'claude session');\n return [\n `Setup: ${setup}.`,\n `Paid routing: ${paid}.`,\n `Claude Code session: ${session?.status === 'ok' ? 'Tenjin observed; wallet unlocked' : session !== undefined && session.checked !== false ? 'needs attention' : 'not verified'}.`,\n '',\n ...checks.flatMap((c) => [\n `${c.status === 'ok' ? 'ok ' : c.status === 'warn' ? 'warn' : 'fail'} ${c.name}: ${c.detail}`,\n ...(c.status !== 'ok' && c.fix !== undefined ? [` fix: ${c.fix}`] : []),\n ]),\n allPass\n ? `${checks.length} checks, all pass.`\n : `${checks.length} checks, ${act} to act on${unchecked > 0 ? `, ${unchecked} not checked` : ''}.`,\n ];\n}\n\n/**\n * The routing legs' backoff, named on a router line whose probe failed too.\n * It ends by itself after its minute, or when a probe here reaches the router.\n */\nfunction withBackoff(check: RouterCheck, memo: RouterMemo | null, now: number): RouterCheck {\n if (memo === null) return check;\n const left = Math.max(1, Math.ceil((memo.until - now) / 1000));\n return {\n ...check,\n status: check.status === 'ok' ? 'warn' : check.status,\n detail: `${check.detail}; routing calls skip the router for ${left}s more, after one did not reach it`,\n };\n}\n\n/**\n * INFORMATIONAL, NEVER A FAILURE. A custom agent whose `tools:` leave the\n * request tool out is a choice its author may have meant, so this names those\n * agents and the one line that would change it, and counts as passing. It is\n * absent when there is nothing to name. The files are only read.\n */\nasync function subagentsCheck(cwd: string, homeDir: string): Promise<RouterCheck | null> {\n const excluded = await agentsWithoutRequestTool({ cwd, homeDir }, REQUEST_TOOL);\n if (excluded.length === 0) return null;\n return {\n name: 'subagents',\n status: 'ok',\n required: false,\n detail: `${excluded.join(', ')} ${excluded.length === 1 ? 'is' : 'are'} offered no paid lookups: add ${REQUEST_TOOL} to tools: to allow paid lookups there`,\n };\n}\n\nfunction nodeCheck(version: string): RouterCheck {\n const major = Number(/^v(\\d+)/.exec(version)?.[1] ?? '0');\n return major >= NODE_FLOOR\n ? { name: 'node', status: 'ok', required: true, detail: version }\n : {\n name: 'node',\n status: 'fail',\n required: true,\n detail: `${version} is below the Node ${NODE_FLOOR} floor.`,\n fix: `Install Node ${NODE_FLOOR} or newer, then re-run \\`tenjin doctor\\`.`,\n };\n}\n\n/** Claude Code's version against the plugin's floor. */\nfunction claudeCodeCheck(claude: ClaudeCodeState): RouterCheck {\n const name = 'claude code';\n if (claude.binary === null) {\n return {\n name,\n status: 'warn',\n required: false,\n detail:\n 'no claude binary on PATH or in CLAUDE_CODE_EXECPATH, so the plugin was checked from its folder only',\n fix: 'Run `tenjin doctor` from a Claude Code session, where CLAUDE_CODE_EXECPATH names the binary.',\n };\n }\n if (claude.version === null) {\n return {\n name,\n status: 'warn',\n required: false,\n detail: `${claude.binary.path} did not report a version`,\n };\n }\n if (!claude.meetsFloor) {\n return {\n name,\n status: 'fail',\n required: true,\n detail: `Claude Code ${claude.version} is older than ${CLAUDE_CODE_FLOOR}, which the Tenjin plugin needs`,\n ...(claude.fix !== undefined ? { fix: claude.fix } : {}),\n };\n }\n return {\n name,\n status: 'ok',\n required: true,\n detail: `${claude.version}${claude.binary.source === 'execpath' ? ' (from CLAUDE_CODE_EXECPATH)' : ''}`,\n };\n}\n\ninterface PluginContext {\n scope: PluginScope;\n env: NodeJS.ProcessEnv;\n home: string;\n cwd: string;\n dataDir: string;\n legacy: LegacyInstall;\n /** When this build was installed, for {@link pluginStart}. */\n installed: number | null;\n snapshot: ProcessSnapshot | null;\n /** The live observations that served a session. */\n live: RouterObservation[];\n /** How Claude Code starts the plugin, for the fixes that fit. */\n layout: Layout;\n}\n\n/** Whether a session has started the plugin at this version, as {@link pluginStart} tells it. */\nexport type PluginStart = 'proven' | 'pending' | 'did-not-start' | 'unknown';\n\n/**\n * The fix when a Claude Code started since this install did not start the\n * plugin: the `node` on its PATH on that layout, else a new session and then\n * the reinstall that rebuilds the runtime.\n */\nfunction didNotStartFix(layout: Layout): string {\n return layout !== 'runtime'\n ? `Claude Code starts the plugin with the \\`node\\` on its own PATH, which must be 22 or newer: run \\`node --version\\` in the shell it starts from, then quit Claude Code fully and start a new session.${moveToRuntime(layout)}`\n : `Start a new Claude Code session. If Tenjin still does not start: ${RUNTIME_MISSING_FIX}`;\n}\n\n/**\n * Has a session started the plugin at this version? First match wins:\n *\n * 1. `proven`: the `alive` stamp is at or above `version`; or a router that\n * served a Claude session runs `version`; or a plugin router under a\n * Claude Code started at or after this install.\n * 2. `unknown`: no stamp, and no process list to look at (`ps` could not run).\n * 3. `did-not-start`: a Claude Code started at or after this install is\n * running and none of the above holds. Its plugin never came up: most\n * often the `node` on Claude Code's own PATH is too old.\n * 4. `pending`: nothing has started since the install; the next session will.\n *\n * Pure: the caller reads the stamp, the snapshot and the observations.\n */\nexport function pluginStart(i: {\n version: string;\n stamp: AliveStamp | null;\n installed: number | null;\n snapshot: ProcessSnapshot | null;\n live: RouterObservation[];\n}): PluginStart {\n const since = (startedAt: number | null): boolean =>\n i.installed !== null && startedAt !== null && startedAt >= i.installed;\n if (i.stamp !== null && !isNewer(i.version, i.stamp.version)) return 'proven';\n if (servedObservations(i.live).some((o) => o.cliVersion === i.version)) return 'proven';\n if (\n i.snapshot?.routers.some(\n (r) => r.kind === 'plugin' && r.underClaude !== false && since(r.startedAt),\n ) === true\n ) {\n return 'proven';\n }\n if (i.snapshot === null && i.stamp === null) return 'unknown';\n if (i.snapshot?.claude.some((c) => since(c.startedAt)) === true) return 'did-not-start';\n return 'pending';\n}\n\n/** Does any of `paths` name the same directory as `dir`, links resolved? */\nasync function sameDirAsAny(paths: string[], dir: string): Promise<boolean> {\n const here = await realOr(dir);\n for (const path of paths) if ((await realOr(path)) === here) return true;\n return false;\n}\n\n/**\n * The plugin: listed and enabled at this CLI's version and stamped by a\n * session at it, or, with no binary to ask, its folder and the `alive` stamp. A machine that still has a\n * settings install of an earlier release warns rather than fails.\n */\nasync function pluginCheck(\n claude: ClaudeCodeState,\n c: PluginContext,\n): Promise<{ check: RouterCheck; registered: boolean }> {\n const name = 'plugin';\n const missing = (detail: string): { check: RouterCheck; registered: boolean } => ({\n registered: false,\n check: c.legacy.present\n ? {\n name,\n status: 'warn',\n required: false,\n detail: `${detail}; the settings install of an earlier release is still here`,\n fix: claude.meetsFloor\n ? `Run \\`tenjin install${c.scope === 'local' ? ' --project' : ''}\\` to move this machine to the plugin.`\n : `Run \\`claude update\\`, then \\`tenjin install${c.scope === 'local' ? ' --project' : ''}\\` to move this machine to the plugin.`,\n }\n : {\n name,\n status: 'fail',\n required: true,\n detail,\n fix: `Run \\`tenjin install${c.scope === 'local' ? ' --project' : ''}\\`.`,\n },\n });\n if (claude.binary !== null) {\n const listing = await readPluginListing(claude.binary, c.env, c.cwd);\n if (!listing.read) {\n return {\n registered: false,\n check: {\n name,\n status: 'warn',\n required: false,\n detail: \"Claude Code's plugin list could not be read, so the plugin was not checked\",\n fix: 'Run `tenjin doctor` again in a moment.',\n },\n };\n }\n if (listing.id === null) return missing(`${PLUGIN_ID} is not installed in Claude Code`);\n if (!listing.enabled) {\n // A PROJECT INSTALL MADE ELSEWHERE is listed from here as disabled.\n // Enabling it here is not the fix: it was meant for that project, and\n // there it is checked.\n if (listing.projects.length > 0 && !(await sameDirAsAny(listing.projects, c.cwd))) {\n return {\n registered: false,\n check: {\n name,\n status: 'fail',\n required: true,\n detail: `${listing.id} is installed for ${listing.projects.join(', ')} only, so nothing is routed from ${c.cwd}`,\n fix: `To check that install, run \\`tenjin doctor\\` from ${listing.projects[0]}.`,\n },\n };\n }\n return {\n registered: false,\n check: {\n name,\n status: 'fail',\n required: true,\n detail: `${listing.id} is installed but disabled, so no lookup is routed`,\n fix: `Run \\`claude plugin enable ${listing.id} --scope ${listing.scope ?? 'user'}\\`, then ${NEW_SESSION_STEP}.`,\n },\n };\n }\n if (listing.version !== pkg.version) {\n return {\n registered: true,\n check: {\n name,\n status: 'warn',\n required: false,\n detail: `${listing.id} is enabled at ${listing.version ?? 'an unknown version'}, and this CLI is ${pkg.version}`,\n fix: 'Run `tenjin install --refresh` to register this version.',\n },\n };\n }\n // Claude Code's own environment shows only in a real session: the `alive`\n // stamp its SessionStart leg writes, a router it started, or its absence\n // from a Claude Code started since. Doctor's PATH may find a Node that\n // Claude Code's does not.\n const stamp = await readAliveStamp(c.dataDir);\n const start = pluginStart({\n version: pkg.version,\n stamp,\n installed: c.installed,\n snapshot: c.snapshot,\n live: c.live,\n });\n const at = `${listing.id} ${pkg.version}`;\n const last = stamp !== null ? ` (last ${stamp.version}, at ${stamp.at})` : '';\n return {\n registered: true,\n check:\n start === 'proven'\n ? {\n name,\n status: 'ok',\n required: true,\n detail: `${at} enabled, and a session has started it`,\n }\n : start === 'pending'\n ? {\n name,\n status: 'ok',\n required: true,\n detail: `${at} enabled; the next Claude Code session starts it`,\n }\n : start === 'unknown'\n ? {\n name,\n status: 'warn',\n required: false,\n checked: false,\n detail: `${at} is enabled; whether a session has started it at this version could not be checked${last}`,\n fix: stampFix(c.layout),\n }\n : {\n name,\n status: 'warn',\n required: false,\n detail: `${at} is enabled, and the Claude Code started since this install has not started it${last}`,\n fix: didNotStartFix(c.layout),\n },\n };\n }\n const folder = await folderState(c.scope, c.env, c.home, c.cwd);\n if (folder.state === 'foreign') {\n return {\n registered: false,\n check: {\n name,\n status: 'fail',\n required: true,\n detail: `${folder.path} is there and is not a folder this CLI wrote, so the plugin cannot be written`,\n fix: `Move ${folder.path} aside, then run \\`tenjin install\\` again.`,\n },\n };\n }\n if (folder.state === 'ours') {\n const stamp = await readAliveStamp(c.dataDir);\n const start = pluginStart({\n version: pkg.version,\n stamp,\n installed: c.installed,\n snapshot: c.snapshot,\n live: c.live,\n });\n return {\n registered: true,\n check:\n start === 'proven'\n ? {\n name,\n status: 'ok',\n required: true,\n detail:\n stamp !== null\n ? `the plugin folder at ${folder.path} loaded, last at ${stamp.at}`\n : `the plugin folder at ${folder.path} is loaded, and a session has started it`,\n }\n : start === 'pending'\n ? {\n name,\n status: 'ok',\n required: true,\n detail: `the plugin folder is at ${folder.path}; the next Claude Code session starts it`,\n }\n : start === 'unknown'\n ? {\n name,\n status: 'warn',\n required: false,\n checked: false,\n detail: `the plugin folder is at ${folder.path}; whether a session has loaded it could not be checked`,\n fix: `To load it, ${NEW_SESSION_STEP}.`,\n }\n : {\n name,\n status: 'warn',\n required: false,\n detail: `the plugin folder is at ${folder.path}, and the Claude Code started since this install has not loaded it`,\n fix: didNotStartFix(c.layout),\n },\n };\n }\n if (await claudeInstallAt(c.scope, c.env, c.home, c.cwd, ['record'])) {\n return {\n registered: true,\n check: {\n name,\n status: 'warn',\n required: false,\n detail: `${PLUGIN_ID} is registered, and there is no claude binary here to check it`,\n fix: 'Run `tenjin doctor` from a Claude Code session to check it.',\n },\n };\n }\n return missing(`${PLUGIN_ID} is not registered`);\n}\n\n/**\n * The plugin's `router` server, through `claude mcp get`, which starts it the\n * way a session would and reports whether it answered. `claude mcp get` runs\n * with doctor's own environment, so it starts `node` from doctor's PATH, not\n * the PATH a running Claude Code started with: a connected server here does\n * not prove a session can start it. The `plugin` row's `alive` stamp is the\n * proof from a real session.\n */\nasync function serverCheck(\n binary: ClaudeBinary,\n env: NodeJS.ProcessEnv,\n cwd: string,\n layout: Layout,\n): Promise<RouterCheck> {\n const name = 'router server';\n const run = await runClaude(binary, ['mcp', 'get', PLUGIN_SERVER], {\n env,\n cwd,\n timeoutMs: 45_000,\n });\n const status = /Status:\\s*(.+)/.exec(run.stdout)?.[1]?.trim();\n if (\n run.code === 0 &&\n status !== undefined &&\n /connected/i.test(status) &&\n !/fail/i.test(status)\n ) {\n return { name, status: 'ok', required: true, detail: `${PLUGIN_SERVER} connected` };\n }\n return {\n name,\n status: 'fail',\n required: true,\n detail: `${PLUGIN_SERVER} did not connect${status !== undefined ? `: ${status.slice(0, 200)}` : ''}`,\n fix:\n layout !== 'runtime'\n ? `Quit Claude Code fully (from the tray, or sign out and in), then start a new session: the plugin starts the CLI with \\`node\\` from the PATH Claude Code started with, so a Claude Code opened before Node was installed cannot find it.${moveToRuntime(layout)}`\n : didNotStartFix(layout),\n };\n}\n\n/**\n * WHERE CLAUDE CODE STARTS THE ROUTER FROM: the `tenjin` marketplace's folder\n * as `claude plugin marketplace list` names it, or the folder fallback's, and\n * the `router` server in its `.mcp.json`. Never `installed_plugins.json`,\n * whose `installPath` goes stale once the marketplace is repointed.\n */\nexport async function readPluginLaunch(\n binary: ClaudeBinary | null,\n c: { env: NodeJS.ProcessEnv; home: string; cwd: string; scope: PluginScope },\n): Promise<PluginLaunch | null> {\n let found: { path: string; source: PluginLaunch['source']; plugin: string } | null = null;\n if (binary !== null) {\n const out = await runClaude(binary, ['plugin', 'marketplace', 'list', '--json'], {\n env: c.env,\n cwd: c.cwd,\n });\n const row = (out.code === 0 ? jsonList(out.stdout) : null)?.find(\n (m) => m.name === MARKETPLACE_NAME,\n );\n if (typeof row?.path === 'string') {\n found = { path: row.path, source: 'marketplace', plugin: join(row.path, PLUGIN_DIR) };\n }\n }\n if (found === null) {\n const folder = await folderState(c.scope, c.env, c.home, c.cwd);\n if (folder.state === 'ours')\n found = { path: folder.path, source: 'folder', plugin: folder.path };\n }\n if (found === null) return null;\n // A folder Claude Code still loads from, with its files gone (the runtime\n // deleted, or the npm prefix a Node upgrade took), is said as that: where\n // it loads from is known, and empty.\n let missing = false;\n const mcp = (await readFile(join(found.plugin, '.mcp.json'), 'utf8')\n .then((text) => JSON.parse(text) as unknown)\n .catch((err: unknown) => {\n missing = hasCode(err, 'ENOENT') || hasCode(err, 'ENOTDIR');\n return null;\n })) as {\n mcpServers?: Record<string, { command?: unknown; args?: unknown }>;\n } | null;\n const none = {\n path: found.path,\n source: found.source,\n command: null,\n entry: null,\n ...(missing ? { missing: true as const } : {}),\n };\n const server = mcp?.mcpServers?.[MCP_SERVER_NAME];\n if (typeof server?.command !== 'string') return none;\n const first = Array.isArray(server.args) ? server.args[0] : undefined;\n const entry =\n typeof first === 'string'\n ? resolve(first.split('${CLAUDE_PLUGIN_ROOT}').join(found.plugin))\n : null;\n return { path: found.path, source: found.source, command: server.command, entry };\n}\n\n/** `<command> <entry> --version`, in exec form: a `.cmd` is never spawned. */\nfunction runVersion(command: string, entry: string): Promise<VersionRun> {\n return new Promise((done) => {\n execFile(\n command,\n [entry, '--version'],\n { shell: false, timeout: 15_000, windowsHide: true },\n (err, stdout, stderr) => {\n const failure = err as\n (NodeJS.ErrnoException & { killed?: boolean; code?: unknown }) | null;\n done({\n code: failure === null ? 0 : typeof failure.code === 'number' ? failure.code : null,\n stdout: String(stdout),\n stderr: String(stderr),\n timedOut: failure?.killed === true,\n });\n },\n );\n });\n}\n\n/** Why Tenjin pins no Node for this machine, or null where it pins one. */\nasync function thisPlatformUnpinned(): Promise<string | null> {\n const { runningGlibc, unpinnedPlatform } = await import('../lib/runtime-fetch');\n const platform = process.platform;\n return unpinnedPlatform(platform, process.arch, platform === 'linux' ? runningGlibc() : null);\n}\n\n/** Is the folder Claude Code loads Tenjin's `runtime/claude`, whether or not its files are there? */\nasync function inRuntimeFolder(launch: PluginLaunch, root: string): Promise<boolean> {\n return launch.source === 'marketplace' && samePath(launch.path, join(root, 'claude'));\n}\n\n/**\n * Does the folder Claude Code loads hold no plugin at all: `runtime/claude`\n * with no router to read, or any folder whose `.mcp.json` is gone? Either\n * way the router cannot start, and only a reinstall puts it back.\n */\nasync function pluginGone(launch: PluginLaunch, root: string): Promise<boolean> {\n return (\n launch.command === null && (launch.missing === true || (await inRuntimeFolder(launch, root)))\n );\n}\n\nconst exists = async (path: string): Promise<boolean> =>\n (await stat(path).catch(() => null)) !== null;\n\n/**\n * THE RUNTIME CLAUDE CODE STARTS, by what the plugin's `.mcp.json` names:\n *\n * - `runtime/claude` with no router to read, or any folder whose `.mcp.json`\n * is gone (the runtime deleted, or the npm prefix a Node upgrade took):\n * Claude Code cannot start the router (the one required failure);\n * - a marketplace outside `runtime/claude` while a runtime exists: an older\n * build moved it back (warn);\n * - an older npm installation on an unsupported platform (warn, with no retry);\n * - `node` from PATH: no runtime, so a Node upgrade or `npm rm -g` stops it\n * (warn);\n * - an absolute Node or entry that is not there, or that does not run: Claude\n * Code cannot start the router (the one required failure, where `router\n * server` fails too);\n * - otherwise ok, and the launcher a terminal needs is checked with it.\n */\nasync function runtimeCheck(i: {\n launch: PluginLaunch | null;\n state: RuntimeState | null;\n root: string;\n home: string;\n env: NodeJS.ProcessEnv;\n project: boolean;\n onPath: PathTenjin | null;\n /** This platform, when Tenjin pins no Node for it. */\n unpinned: string | null;\n deps: RouterDoctorDeps;\n}): Promise<RouterCheck> {\n const name = 'runtime';\n const flag = i.project ? ' --project' : '';\n const t = (p: string) => tilde(p, i.home);\n const failFix =\n RUNTIME_MISSING_FIX +\n (i.project\n ? ' For a project-only installation, pass `--project` to the installer from that project folder.'\n : '');\n const { launch } = i;\n const unread: RouterCheck = {\n name,\n status: 'warn',\n required: false,\n checked: false,\n detail: \"where Claude Code starts Tenjin from could not be read from the plugin's .mcp.json\",\n };\n if (launch === null) return unread;\n if (await pluginGone(launch, i.root)) {\n return {\n name,\n status: 'fail',\n required: true,\n detail: `Claude Code loads Tenjin from ${t(launch.path)}, which no longer holds its plugin, so the router cannot start`,\n fix: failFix,\n };\n }\n if (\n i.state !== null &&\n launch.source === 'marketplace' &&\n !(await samePath(launch.path, join(i.root, 'claude')))\n ) {\n return {\n name,\n status: 'warn',\n required: false,\n detail: `Claude Code loads Tenjin from ${t(launch.path)}, not Tenjin's runtime: an older tenjin-cli build registered it there`,\n fix: `Run \\`tenjin install${flag}\\`, then start a new Claude Code session.`,\n };\n }\n if (launch.command === null) return unread;\n if (launch.command === 'node' && i.unpinned !== null) {\n const from = launch.entry !== null ? ` at ${t(dirname(launch.entry))}` : '';\n return {\n name,\n status: 'warn',\n required: false,\n detail: `This older installation runs from npm's copy${from}; this platform (${i.unpinned}) does not support Tenjin's private runtime`,\n fix: 'Use macOS, Windows or glibc Linux 2.28+ on x64/arm64. This installation was left unchanged.',\n };\n }\n if (launch.command === 'node') {\n const from = launch.entry !== null ? `, from ${t(dirname(launch.entry))}` : '';\n return {\n name,\n status: 'warn',\n required: false,\n detail: `Claude Code starts Tenjin with the \\`node\\` on its PATH${from}, so a Node upgrade or \\`npm rm -g tenjin-cli\\` stops it`,\n fix: `Run \\`tenjin install${flag}\\` to move it to Tenjin's own runtime.`,\n };\n }\n const missing = [launch.command, ...(launch.entry !== null ? [launch.entry] : [])];\n const gone: string[] = [];\n for (const p of missing) if (!(await exists(p))) gone.push(t(p));\n if (launch.entry === null || gone.length > 0) {\n return {\n name,\n status: 'fail',\n required: true,\n detail:\n launch.entry === null\n ? `Claude Code starts Tenjin with ${t(launch.command)} and no entry script, so the router cannot start`\n : `Claude Code starts Tenjin with ${gone.join(' and ')}, which ${gone.length === 1 ? 'is' : 'are'} not there, so the router cannot start`,\n fix: failFix,\n };\n }\n const shown = `${t(launch.command)} ${t(launch.entry)} --version`;\n const run = await (i.deps.runVersion ?? runVersion)(launch.command, launch.entry);\n if (run.timedOut) {\n return {\n name,\n status: 'warn',\n required: false,\n checked: false,\n detail: `\\`${shown}\\` did not answer within 15 s`,\n };\n }\n if (run.code !== 0) {\n const said = (run.stderr || run.stdout).trim().slice(0, 200);\n return {\n name,\n status: 'fail',\n required: true,\n detail: `\\`${shown}\\` exited ${run.code ?? 'without a code'}${said.length > 0 ? `: ${said}` : ''}, so the router cannot start`,\n fix: failFix,\n };\n }\n const nodeVersion =\n /[\\\\/]node[\\\\/](\\d+\\.\\d+\\.\\d+)[\\\\/]/.exec(launch.command)?.[1] ??\n i.state?.current.node ??\n 'unknown';\n const from = runtimeBuild(dirname(launch.entry))?.root ?? i.root;\n const detail = `Claude Code starts tenjin ${run.stdout.trim()} on Node ${nodeVersion} from ${t(from)}`;\n // THE LAUNCHER A TERMINAL NEEDS once npm's copy is gone.\n const platform = process.platform;\n const launcher = join(launcherDir(i.home), platform === 'win32' ? 'tenjin.cmd' : 'tenjin');\n if (!(await exists(launcher))) {\n return {\n name,\n status: 'warn',\n required: false,\n detail: `${detail}; ${t(launcher)} is missing, so a terminal does not find Tenjin's \\`tenjin\\``,\n fix: `Run \\`tenjin install${flag}\\` to write it.`,\n };\n }\n // Off PATH is only worth a row when the terminal finds no `tenjin` at all: npm's\n // copy hands off to the runtime, and an old one gets its own row below.\n if (i.onPath === null && !launcherOnPath(launcherDir(i.home), i.env, platform)) {\n const { pathLine } = await import('../lib/runtime-launchers');\n return {\n name,\n status: 'warn',\n required: false,\n detail: `${detail}; ${t(launcherDir(i.home))} is not on your PATH, so a terminal does not find \\`tenjin\\` there`,\n fix: pathLine(i.env, i.home, platform),\n };\n }\n return {\n name,\n status: 'ok',\n required: true,\n detail: `${detail}; tenjin on PATH: ${t(i.onPath?.path ?? launcher)}`,\n };\n}\n\n/** Is `dir` on this environment's PATH, compared as `writeLaunchers` compares it? */\nfunction launcherOnPath(dir: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform): boolean {\n const p = platform === 'win32' ? win32 : posix;\n const norm = (value: string) => {\n const full = p.resolve(value).replace(/[\\\\/]+$/, '');\n return platform === 'win32' ? full.toLowerCase() : full;\n };\n const raw = (platform === 'win32' ? (env.Path ?? env.PATH) : env.PATH) ?? '';\n return raw\n .split(p.delimiter)\n .filter((entry) => entry.length > 0)\n .some((entry) => norm(entry) === norm(dir));\n}\n\n/**\n * THE FIRST `tenjin` ON PATH, and the package behind it: the nearest\n * `tenjin-cli` package above its realpath (npm's POSIX link), or\n * `node_modules/tenjin-cli` beside it (npm's Windows shim). A launcher Tenjin\n * wrote needs no package. One with no package identified (a Volta or pnpm\n * shim) is still the one a terminal runs, marked `unknown`. Null when there\n * is none.\n */\nexport async function findPathTenjin(\n env: NodeJS.ProcessEnv,\n platform: NodeJS.Platform = process.platform,\n): Promise<PathTenjin | null> {\n const raw = (platform === 'win32' ? (env.Path ?? env.PATH) : env.PATH) ?? '';\n const delimiter = platform === 'win32' ? win32.delimiter : posix.delimiter;\n const name = platform === 'win32' ? 'tenjin.cmd' : 'tenjin';\n for (const dir of raw.split(delimiter).filter((d) => d.length > 0)) {\n const path = join(dir, name);\n if ((await stat(path).catch(() => null))?.isFile() !== true) continue;\n const body = await readFile(path, 'utf8').catch(() => '');\n if (body.includes(LAUNCHER_MARKER))\n return { path, marked: true, version: null, handsOff: true };\n let root: string | null;\n if (platform === 'win32') root = join(dir, 'node_modules', 'tenjin-cli');\n else {\n const { packageRootOf } = await import('../lib/runtime-place');\n root = packageRootOf(dirname(await realpath(path).catch(() => path)));\n }\n // The first one on PATH is what a terminal runs, identified or not.\n const unknown = { path, marked: false, version: null, handsOff: false, unknown: true } as const;\n if (root === null) return unknown;\n const manifest = await readFile(join(root, 'package.json'), 'utf8')\n .then((t) => JSON.parse(t) as { name?: unknown; version?: unknown; tenjinRuntime?: unknown })\n .catch(() => null);\n if (manifest?.name !== 'tenjin-cli') return unknown;\n return {\n path,\n marked: false,\n version: typeof manifest.version === 'string' ? manifest.version : null,\n handsOff: manifest.tenjinRuntime !== undefined,\n };\n }\n return null;\n}\n\n/** An older npm copy a terminal runs instead of Tenjin's runtime, named; nothing else. */\nfunction pathTenjinCheck(found: PathTenjin | null, home: string): RouterCheck | null {\n if (found === null || found.marked || found.handsOff || found.unknown === true) return null;\n return {\n name: 'tenjin on PATH',\n status: 'warn',\n required: false,\n detail: `\\`tenjin\\` in a terminal runs tenjin-cli ${found.version ?? '(unknown version)'} at ${tilde(found.path, home)}, an older build that does not hand off to Tenjin's runtime`,\n fix: 'Remove it with `npm uninstall -g tenjin-cli` using the Node that installed it, or upgrade it with `npm i -g tenjin-cli@latest`.',\n };\n}\n\n/**\n * A settings install of an earlier release: what is left, and whether the\n * next `tenjin install` or `tenjin update` removes it. Never a failure, and\n * never written here.\n */\nasync function migrationCheck(\n legacy: LegacyInstall,\n claude: ClaudeCodeState,\n dataDir: string,\n env: NodeJS.ProcessEnv,\n cwd: string,\n): Promise<RouterCheck> {\n const name = 'settings install';\n if (legacy.unreadable !== undefined) {\n return { name, status: 'warn', required: false, detail: legacy.unreadable };\n }\n const parts = [\n ...(legacy.events.length > 0 ? [`hook entries (${legacy.events.join(', ')})`] : []),\n ...(legacy.allowRule || legacy.denyRule ? ['permission rules'] : []),\n ...(legacy.statusLine === 'ours' || legacy.statusLine === 'composed' ? ['a status line'] : []),\n ...(legacy.mcp === 'ok' ? ['the x402 MCP server'] : []),\n ];\n const found = `${parts.join(', ')} from an earlier release in ${legacy.settingsPath}`;\n const lookalikes =\n legacy.lookalikes.length > 0\n ? `; not Tenjin's and left alone: ${legacy.lookalikes.join(', ')}`\n : '';\n const proof = await pluginProof(claude, dataDir, env, cwd);\n return proof.proven\n ? {\n name,\n status: 'warn',\n required: false,\n detail: `${found}, ready to remove: the plugin has loaded here${lookalikes}`,\n fix: 'Run `tenjin install --refresh` to remove it.',\n }\n : {\n name,\n status: 'warn',\n required: false,\n detail: `${found}, kept until the plugin loads: ${proof.reason}${lookalikes}`,\n fix: claude.meetsFloor\n ? `To load the plugin, ${NEW_SESSION_STEP}; the next \\`tenjin install\\` or \\`tenjin update\\` then removes the old entries.`\n : 'Run `claude update`, then `tenjin install`: until then the old entries stay.',\n };\n}\n\n/**\n * WIRED BUT SWITCHED OFF is a choice, not a fault, so it warns and names the\n * file that made it.\n */\nfunction routingCheck(router: RouterSettings | Error): RouterCheck {\n const name = 'routing';\n if (router instanceof Error) {\n return {\n name,\n status: 'warn',\n required: false,\n detail: `the router is off here: ${router.message}`,\n fix: 'Fix or delete that file.',\n };\n }\n if (!router.enabled.value) {\n const file = router.enabled.path ?? 'the config';\n return {\n name,\n status: 'warn',\n required: false,\n detail: `router.enabled is false in ${file}, so nothing is routed from this directory`,\n fix:\n router.enabled.source === 'file'\n ? 'Run `tenjin config set router.enabled true` to route again.'\n : `Remove router.enabled from ${file} to route here again.`,\n };\n }\n return { name, status: 'ok', required: false, detail: 'on' };\n}\n\n/** The unlock reasons a routing-fee row words from WALLET_REASONS, with the person's fix. */\nconst UNLOCK_WHY: ReadonlySet<string> = new Set([\n 'wallet_corrupt',\n 'env_key_invalid',\n 'passphrase_missing',\n 'passphrase_wrong',\n 'env_passphrase_wrong',\n 'keychain_locked',\n 'wallet_locked',\n]);\n\n/**\n * The routing fee as the next paid call would meet it: `canPayRouting`, the\n * verdict the payer and the hooks reach on the same facts, in fee.ts's words.\n * Never a failure: a call the fee cannot pay is skipped, and the native tools\n * run.\n *\n * - ready: ok, with the fee's terms; whether the router's live quote is\n * within the ceiling is the router check's to say;\n * - blocked by money or policy: today's `unpaid` detail, and today's fix\n * (`fixes[why]`, else fee.ts's own);\n * - blocked because the wallet cannot sign: the WALLET_REASONS fragment and\n * the verdict's PERSON fix, never `agentFix`: doctor is read by a person;\n * - unknown (a balance or a keychain that did not answer): \"could not check\",\n * never ok, never a fix.\n */\nexport function routingFeeRow(e: Pick<Eligibility, 'canPayRouting'>, host: string): RouterCheck {\n const name = 'routing fee';\n const v = e.canPayRouting;\n if (v.status === 'unknown') {\n return {\n name,\n status: 'warn',\n required: false,\n checked: false,\n detail: `could not check: ${v.detail}`,\n };\n }\n if (v.status === 'ready') {\n return {\n name,\n status: 'ok',\n required: false,\n detail: 'can cover the standard fee',\n };\n }\n const why = v.reason;\n if (UNLOCK_WHY.has(why)) {\n return {\n name,\n status: 'warn',\n required: false,\n detail: WALLET_REASONS[why as keyof typeof WALLET_REASONS].reason,\n fix: v.fix,\n };\n }\n const u = unpaid(why);\n const fixes: Record<string, string> = {\n no_wallet: `Run \\`tenjin wallet create\\`, then \\`tenjin fund ${SUGGESTED_FUND_USD}\\`.`,\n limit_below_deposit: `Raise it with \\`tenjin config set maxAutoSpend ${usd(MAX_AUTO_SPEND_FLOOR_ATOMIC)}\\`.`,\n budget_reached:\n 'Room comes back when the daily budget resets, or raise it with `tenjin config set sessionBudget <usd>`.',\n not_allowlisted: `Add ${host} to allowlistCreators, or clear the allowlist.`,\n };\n return {\n name,\n status: 'warn',\n required: false,\n detail: why === 'wallet_low' ? 'balance too low for the standard fee' : (u?.reason ?? v.detail),\n fix: fixes[why] ?? u?.fix ?? v.fix,\n };\n}\n\n/** INFORMATIONAL: which experiment is on, in one line. Either state passes. */\nfunction experimentalCheck(bazaar: boolean): RouterCheck {\n return {\n name: 'experimental',\n status: 'ok',\n required: false,\n detail: bazaar\n ? 'list: on; bazaar: on (experimental): the router may also suggest unreviewed sellers from the open x402 Bazaar'\n : 'list: on; bazaar: off (experimental): `tenjin config set experimental.bazaar on` to add the open x402 Bazaar',\n };\n}\n\n/**\n * The two limits: the daily budget is the control, the per-call ceiling the\n * runaway guard. A per-call limit an earlier release left below the deposit shows\n * on the routing-fee row, which names the deposit it refuses.\n */\nfunction spendCheck(maxAutoSpendAtomic: bigint, sessionBudgetAtomic: bigint | null): RouterCheck {\n if (sessionBudgetAtomic === 0n) {\n return {\n name: 'spend',\n status: 'fail',\n required: true,\n detail: 'The daily budget is 0, so positive payments are refused even with --yes.',\n fix: 'Choose a daily budget with `tenjin config set sessionBudget <usd|none>`.',\n };\n }\n if (maxAutoSpendAtomic === 0n) {\n return {\n name: 'spend',\n status: 'fail',\n required: true,\n detail: 'maxAutoSpend is 0, so every lookup needs approval and none can pay',\n fix: `Raise it with \\`tenjin config set maxAutoSpend ${usd(MAX_AUTO_SPEND_FLOOR_ATOMIC)}\\`.`,\n };\n }\n const budget =\n sessionBudgetAtomic === null\n ? 'no daily budget limit'\n : `${toMoney(sessionBudgetAtomic.toString()).usd} USD daily budget, shared across chats`;\n return {\n name: 'spend',\n status: sessionBudgetAtomic === null ? 'warn' : 'ok',\n required: false,\n detail: `automatic approval up to ${toMoney(maxAutoSpendAtomic.toString()).usd} USD a call, ${budget}`,\n ...(sessionBudgetAtomic === null\n ? { fix: 'Set one with `tenjin config set sessionBudget 1.00`.' }\n : {}),\n };\n}\n\n/** Where a ready wallet's passphrase (or key) came from, as the wallet row says it;\n * the passphrase file under `dataDir`, which `TENJIN_DATA_DIR` moves. */\nfunction signedFrom(source: SigningSource, address: string, dataDir: string): string {\n switch (source) {\n case 'keychain':\n return 'macOS keychain';\n case 'secret-service':\n return 'Linux keyring';\n case 'dpapi':\n return 'DPAPI file';\n case 'file':\n return `passphrase file ${describeStoreLocation('file', address.toLowerCase(), dataDir)}`;\n case 'key-env':\n return 'TENJIN_WALLET_KEY in this shell';\n case 'passphrase-env':\n return 'TENJIN_WALLET_PASSPHRASE in this shell';\n case 'legacy':\n return 'legacy keychain entry';\n }\n}\n\n/** The unlock reasons a wallet row warns about with the WALLET_REASONS person fix. */\nconst WARN_UNLOCK: ReadonlySet<string> = new Set<UnlockReason>([\n 'passphrase_missing',\n 'passphrase_wrong',\n 'env_passphrase_wrong',\n 'wallet_corrupt',\n]);\n\n/**\n * The wallet row: can this shell's wallet sign, and with what?\n *\n * No wallet, a wallet.json `describe` cannot read, and an invalid\n * TENJIN_WALLET_KEY fail as required. A wallet that is there but cannot be\n * unlocked only warns: the native tools still run, and the fix is a person's,\n * never `agentFix`, never \"set TENJIN_WALLET_PASSPHRASE\" and never the\n * plaintext file. A check that could not answer is said as not checked.\n */\nexport function walletRow(e: Eligibility, dataDir: string): RouterCheck {\n const name = 'wallet';\n const sign = e.canSign;\n if (e.describeError !== null && e.describeError !== undefined) {\n const err = e.describeError;\n return {\n name,\n status: 'fail',\n required: true,\n detail: err instanceof CliError ? err.message : String(err),\n ...(err instanceof CliError && err.fix !== undefined ? { fix: err.fix } : {}),\n };\n }\n if (sign.status === 'blocked' && sign.reason === 'no_wallet') {\n return {\n name,\n status: 'fail',\n required: true,\n detail: 'no wallet on this machine, so nothing can pay',\n fix: `Run \\`tenjin wallet create\\`, then \\`tenjin fund ${SUGGESTED_FUND_USD}\\`.`,\n };\n }\n if (sign.status === 'blocked' && sign.reason === 'env_key_invalid') {\n return { name, status: 'fail', required: true, detail: sign.detail, fix: sign.fix };\n }\n const address = e.address ?? 'the wallet';\n if (sign.status === 'ready') {\n if (sign.warning !== undefined) {\n return {\n name,\n status: 'warn',\n required: false,\n detail: `${address} unlocks with the saved passphrase; TENJIN_WALLET_PASSPHRASE is set but wrong`,\n fix: 'Remove it from this shell and your shell profile: `unset TENJIN_WALLET_PASSPHRASE`.',\n };\n }\n return {\n name,\n status: 'ok',\n required: true,\n detail:\n sign.source !== undefined\n ? `${address} unlocks without a prompt (${signedFrom(sign.source, address, dataDir)})`\n : `${address} unlocks without a prompt`,\n };\n }\n if (sign.status === 'blocked') {\n const fix = WARN_UNLOCK.has(sign.reason)\n ? WALLET_REASONS[sign.reason as keyof typeof WALLET_REASONS].fix\n : sign.fix;\n return {\n name,\n status: 'warn',\n required: false,\n detail: `${address} cannot be unlocked: ${sign.detail}`,\n fix,\n };\n }\n return {\n name,\n status: 'warn',\n required: false,\n checked: false,\n detail: `could not check whether ${address} unlocks: ${sign.detail}`,\n ...(sign.reason === 'keychain_locked' ? { fix: KEYCHAIN_LOCKED_FIX } : {}),\n };\n}\n\n/** The repair fix: the person saves the passphrase where every Claude Code can read it. */\nconst SAVE_FOR_EVERY_SESSION_FIX = `Run \\`tenjin wallet repair\\` yourself to save the passphrase where every Claude Code can read it ${REPAIR_CLAUSE}.`;\n\n/** `HH:MM`, local time, for a router's start. */\nfunction clock(ms: number): string {\n return new Date(ms).toTimeString().slice(0, 5);\n}\n\n/**\n * The `claude session` row: what the router a running Claude Code started saw\n * when it tried to unlock this wallet, read from the observation it wrote.\n * Doctor's own shell is not that session: its environment, its PATH and its\n * keychain answer can all differ, which is the whole point of this row.\n *\n * Only a router that has served a Claude hook counts: one started by\n * `claude mcp get` or `list`, a Codex one, or one prewarmed with no hook\n * served yet, is not \"the running Claude session\" and is ignored.\n *\n * With none, the row says what this shell alone can say, and is not checked,\n * except in the one case it can say more: this shell signs only through\n * TENJIN_WALLET_PASSPHRASE and the saved stores definitely do not open the\n * wallet, so a Claude Code started without the variable cannot unlock it. An\n * unknown saved-store answer (a locked keychain) makes no such claim.\n *\n * Never a failure, and never routing-fee wording: the routing-fee row says\n * that.\n */\nexport function sessionRow(\n shell: Eligibility,\n live: RouterObservation[],\n version: string = pkg.version,\n): RouterCheck {\n const name = 'claude session';\n // At this version first, then the most recent: the router the next lookup most likely meets.\n const served = [...servedObservations(live)].sort(\n (a, b) =>\n Number(b.cliVersion === version) - Number(a.cliVersion === version) ||\n b.startedAt - a.startedAt,\n );\n if (served.length === 0) {\n const shellReady = shell.canSign.status === 'ready' && shell.canPayRouting.status === 'ready';\n const detail = shellReady ? NO_SESSION_CHECKED : 'no running Claude session checked';\n if (\n shell.source === 'passphrase-env' &&\n shell.savedSign !== null &&\n isDefiniteBlock(shell.savedSign)\n ) {\n return {\n name,\n status: 'warn',\n required: false,\n detail: `${detail}, and a Claude Code started without TENJIN_WALLET_PASSPHRASE cannot unlock the wallet`,\n fix: SAVE_FOR_EVERY_SESSION_FIX,\n };\n }\n return {\n name,\n status: 'warn',\n required: false,\n checked: false,\n detail,\n ...(shell.source === 'key-env'\n ? { fix: 'Start Claude Code from a shell that sets TENJIN_WALLET_KEY.' }\n : {}),\n };\n }\n\n const blocked = served.find((o) => o.sign.status === 'blocked');\n if (blocked !== undefined) {\n const reason = blocked.sign.reason ?? '';\n const wallet = Object.prototype.hasOwnProperty.call(WALLET_REASONS, reason)\n ? WALLET_REASONS[reason as keyof typeof WALLET_REASONS]\n : undefined;\n const detail = blocked.sign.detail ?? wallet?.reason ?? reason;\n const fix = wallet?.fix ?? blocked.sign.fix;\n return {\n name,\n status: 'warn',\n required: false,\n detail: `the router Claude Code started (pid ${blocked.pid}) cannot unlock the wallet: ${detail}`,\n ...(fix !== undefined ? { fix } : {}),\n };\n }\n\n const here = shell.address?.toLowerCase() ?? null;\n const other = served.find(\n (o) => o.address !== null && here !== null && o.address.toLowerCase() !== here,\n );\n if (other !== undefined) {\n return {\n name,\n status: 'warn',\n required: false,\n detail: `Claude Code's router uses ${other.address}, this shell ${shell.address}`,\n };\n }\n\n const waiting = served.find((o) => o.sign.status !== 'ready');\n if (waiting !== undefined) {\n const why =\n waiting.sign.status === 'pending'\n ? 'it has not tried to unlock yet'\n : (waiting.sign.detail ??\n UNKNOWN_DETAIL[waiting.sign.reason ?? ''] ??\n UNKNOWN_DETAIL['check_failed']!);\n return {\n name,\n status: 'warn',\n required: false,\n checked: false,\n detail: `could not check whether the router Claude Code started (pid ${waiting.pid}) unlocks the wallet: ${why}`,\n };\n }\n\n const o = served[0]!;\n return {\n name,\n status: 'ok',\n required: false,\n detail: `the router Claude Code started (pid ${o.pid}, since ${clock(o.startedAt)}, v${o.cliVersion}) unlocked ${o.address ?? shell.address ?? 'the wallet'}`,\n };\n}\n","import { evaluateSpendPolicy, type SpendPolicy } from '../lib/policy';\nimport { readSpendSummary, spentOf } from '../lib/spend-ledger';\nimport { readUsdcBalance } from '../lib/usdc-balance';\nimport { describeWallet } from '../lib/wallet';\nimport type { WalletProvider, WalletVerification } from '../lib/wallet/provider';\nimport { readWalletFacts, type WalletFacts } from '../lib/wallet-facts';\nimport type { SigningSource } from '../lib/wallet-unlock';\nimport { channelCredit } from './channel-credit';\nimport {\n canPayRouting,\n canSign as canSignFrom,\n signFromVerification,\n type SignVerdict,\n type Verdict,\n} from './eligibility';\nimport {\n CHANNEL_DEPOSIT_ATOMIC,\n feeRefusal,\n LEGACY_ROUTING_QUOTE_ATOMIC,\n MAX_CHANNEL_DEPOSIT_ATOMIC,\n refusedWhy,\n routingDepositAtomic,\n} from './fee';\nimport { UNKNOWN_DETAIL } from './wallet-reasons';\n\n/**\n * The whole eligibility picture for one shell, for `tenjin doctor`: gather the\n * facts with real I/O (wallet files, a no-prompt verify, the spend ledger, the\n * routing channel, the chain balance), then decide with the pure rules in\n * `eligibility.ts`, so doctor agrees with the payer and the hooks.\n *\n * Not hook-safe: it loads the wallet layer and the x402 channel storage, so\n * only doctor imports it.\n */\nexport interface EligibilityInput {\n dataDir: string;\n env: NodeJS.ProcessEnv;\n policy: SpendPolicy;\n rpcUrl: string;\n /** The router's host (the creator a deposit pays). */\n host: string;\n timeoutMs: number;\n /** null when there is no wallet file and no TENJIN_WALLET_KEY. */\n provider: WalletProvider | null;\n /** Verify with TENJIN_WALLET_PASSPHRASE removed from the env. Called first, only when the variable is set\n * and TENJIN_WALLET_KEY is not valid. Doctor supplies it; absent means a single verify. */\n verifySaved?: () => Promise<WalletVerification | undefined>;\n fetchImpl?: typeof fetch;\n readBalance?: (\n address: string,\n rpcUrl: string,\n o: { timeoutMs: number; fetchImpl?: typeof fetch },\n ) => Promise<bigint | null>;\n readCredit?: (dataDir: string, address: string) => Promise<bigint>;\n readSpent?: (dataDir: string) => Promise<bigint>;\n}\n\nexport interface Eligibility {\n address: string | null;\n source: SigningSource | null;\n warning?: string;\n canSign: SignVerdict;\n canPayRouting: Verdict;\n /** The verdict with TENJIN_WALLET_PASSPHRASE removed (verifySaved). null when it was not run. */\n savedSign: SignVerdict | null;\n balanceAtomic: bigint | null;\n creditAtomic: bigint | null;\n /** What describeWallet(provider) rejected with (a corrupt wallet.json, an invalid key), which doctor fails as\n * required. null when describe succeeded or there is no provider. */\n describeError: unknown | null;\n}\n\n/** An unknown verdict worded from UNKNOWN_DETAIL. */\nfunction unknownSign(reason: 'check_failed' | 'not_checked'): SignVerdict {\n return { status: 'unknown', reason, detail: UNKNOWN_DETAIL[reason]! };\n}\n\n/** The spent total the deposit is evaluated against: the ledger as an\n * authorization would see it, and nothing for an absent one. */\nasync function defaultReadSpent(dataDir: string): Promise<bigint> {\n const ledger = await readSpendSummary(dataDir);\n return ledger === null ? 0n : spentOf(ledger);\n}\n\n/**\n * Check what this shell's wallet can do. Never rejects: every step that can\n * fail is caught and becomes an unknown or a null, and the balance is read\n * even when signing is blocked (the address is cleartext, and \"locked AND\n * empty\" is two things to fix, not one).\n */\nexport async function checkEligibility(input: EligibilityInput): Promise<Eligibility> {\n let facts: WalletFacts | null = null;\n try {\n facts = await readWalletFacts(input.dataDir, input.env);\n return await check(input, facts);\n } catch {\n const failed = unknownSign('check_failed');\n return {\n address: facts?.address ?? null,\n source: null,\n canSign: failed,\n canPayRouting: failed,\n savedSign: null,\n balanceAtomic: null,\n creditAtomic: null,\n describeError: null,\n };\n }\n}\n\nasync function check(input: EligibilityInput, facts: WalletFacts): Promise<Eligibility> {\n const { provider } = input;\n let address = facts.address;\n let describeError: unknown | null = null;\n if (provider !== null) {\n try {\n address = (await describeWallet(provider)).address;\n } catch (err) {\n // Kept for doctor, which fails it as required.\n describeError = err;\n }\n }\n\n const { sign, savedSign } = await signing(input, facts, describeError);\n const source = sign.status === 'ready' ? (sign.source ?? null) : null;\n\n const [spent, creditAtomic, balanceAtomic] = await Promise.all([\n (input.readSpent ?? defaultReadSpent)(input.dataDir).catch(() => null),\n address === null\n ? Promise.resolve(null)\n : (input.readCredit ?? channelCredit)(input.dataDir, address).catch(() => null),\n address === null\n ? Promise.resolve(null)\n : (input.readBalance ?? readUsdcBalance)(address, input.rpcUrl, {\n timeoutMs: input.timeoutMs,\n ...(input.fetchImpl !== undefined ? { fetchImpl: input.fetchImpl } : {}),\n }).catch(() => null),\n ]);\n\n // Doctor has no live SDK quote; estimate the announced target and the\n // router's fixed quote using the same liquidity policy as the deposit strategy.\n const depositAtomic = routingDepositAtomic({\n suggestedAtomic: CHANNEL_DEPOSIT_ATOMIC,\n neededAtomic: LEGACY_ROUTING_QUOTE_ATOMIC,\n balanceAtomic,\n perCallAtomic: input.policy.maxAutoSpendAtomic,\n maxAtomic: MAX_CHANNEL_DEPOSIT_ATOMIC,\n });\n const deposit = evaluateSpendPolicy(input.policy, {\n mode: 'automatic',\n amountAtomic: depositAtomic,\n creator: input.host,\n sessionSpentAtomic: spent ?? 0n,\n });\n const routing = canPayRouting({\n // No quote to go on here: the router's fixed quote.\n feeRefusal: feeRefusal(input.policy, input.host, LEGACY_ROUTING_QUOTE_ATOMIC),\n sign,\n creditAtomic,\n depositRefusal: deposit.decision === 'allow' ? null : refusedWhy(deposit.reason),\n depositAtomic,\n balanceAtomic,\n });\n\n return {\n address,\n source,\n ...(sign.status === 'ready' && sign.warning !== undefined ? { warning: sign.warning } : {}),\n canSign: sign,\n canPayRouting: routing,\n savedSign,\n balanceAtomic,\n creditAtomic,\n describeError,\n };\n}\n\n/**\n * The sign verdict, and the saved-passphrase verdict beside it.\n *\n * Saved passphrase first: with TENJIN_WALLET_PASSPHRASE set, `verifySaved`\n * asks whether the keychain or file opens the wallet without the variable, so\n * a passphrase both hold is reported as that store, not as\n * `passphrase-env`, and doctor can say whether a Claude Code started without\n * the variable could sign. The full verify still runs after it, because only\n * the full env can see that the variable is wrong (ready with a warning).\n */\nasync function signing(\n input: EligibilityInput,\n facts: WalletFacts,\n describeError: unknown | null,\n): Promise<{ sign: SignVerdict; savedSign: SignVerdict | null }> {\n const { provider } = input;\n if (facts.envKey === 'malformed') {\n return {\n sign: canSignFrom({ envKey: 'malformed', walletFile: facts.walletFile }),\n savedSign: null,\n };\n }\n if (provider === null) {\n return { sign: canSignFrom({ envKey: 'absent', walletFile: 'absent' }), savedSign: null };\n }\n if (describeError !== null) return { sign: unknownSign('check_failed'), savedSign: null };\n\n let savedSign: SignVerdict | null = null;\n if (facts.envPassphraseSet && facts.envKey !== 'valid' && input.verifySaved !== undefined) {\n savedSign = await input\n .verifySaved()\n .then((v) => signFromVerification(v))\n .catch(() => unknownSign('check_failed'));\n }\n\n let full: SignVerdict;\n if (provider.verify === undefined) {\n full = unknownSign('not_checked');\n } else {\n full = await provider\n .verify()\n .then((v) => signFromVerification(v))\n .catch(() => unknownSign('check_failed'));\n }\n\n let sign = full;\n if (full.status === 'ready') {\n const source: SigningSource | undefined =\n facts.envKey === 'valid'\n ? 'key-env'\n : savedSign?.status === 'ready'\n ? savedSign.source\n : full.source;\n sign = {\n status: 'ready',\n ...(source !== undefined ? { source } : {}),\n ...(full.warning !== undefined ? { warning: full.warning } : {}),\n };\n } else if (\n facts.envPassphraseSet &&\n full.status === 'blocked' &&\n full.reason === 'passphrase_missing'\n ) {\n // A set variable is a passphrase source, so \"none reachable\" is not definite.\n sign = unknownSign('not_checked');\n }\n return { sign, savedSign };\n}\n"],"mappings":";;;;;;;;;;;;;;;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AC,MAAM,EAAE,UAAU,cAAc,EAAE,WAAW,MAAM,WAAW,YAAY;AAAA,EAC7J;AACF;","names":["check","from","o"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/device-name.ts","../src/commands/fund.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { hostname } from 'node:os';\n\n/**\n * THIS COMPUTER'S NAME, for the fund page to show (\"Tenjin on Ada's MacBook\n * Pro\"), so a person paying can see which machine the link is for. Display\n * only: the server signs it into the link and stores nothing.\n *\n * macOS asks `scutil --get ComputerName`, the name System Settings shows,\n * because `os.hostname()` there is the network name (`adas-mbp.local`).\n * Windows and Linux report the hostname, which is often one the machine made\n * up (`DESKTOP-7F3K2LQ`, `ip-172-31-5-10`, a container id): those read as noise\n * on a payment page, so they are left out and the page says just \"tenjin\". A\n * trailing `.local` is dropped, controls and anything past 64 characters are\n * cut, and nothing here ever throws: a fund link never fails over its label.\n */\n\n/** Hostnames a machine or a cloud gives itself, never a name a person chose. */\nconst GENERATED_HOSTNAME = [\n /^(desktop|laptop|win)-[a-z0-9]{5,}$/i, // Windows' default names\n /^ip-\\d{1,3}-\\d{1,3}-\\d{1,3}-\\d{1,3}\\b/i, // AWS\n /^[0-9a-f]{12}([0-9a-f]{52})?$/i, // a Docker container id\n /^codespaces-[0-9a-z]+$/i, // GitHub Codespaces\n /^(localhost|\\d{1,3}(\\.\\d{1,3}){3})(\\.localdomain)?$/i,\n];\n\nconst MAX_DEVICE_NAME = 64;\nconst SCUTIL = '/usr/sbin/scutil';\nconst SCUTIL_TIMEOUT_MS = 1_000;\n\nexport interface DeviceNameDeps {\n platform?: NodeJS.Platform;\n /** `scutil --get ComputerName`'s output, or null when it failed. */\n computerName?: () => Promise<string | null>;\n hostname?: () => string;\n}\n\nexport async function deviceName(deps: DeviceNameDeps = {}): Promise<string | undefined> {\n try {\n const platform = deps.platform ?? process.platform;\n const fromMac = platform === 'darwin' ? await (deps.computerName ?? macComputerName)() : null;\n const named = clean(fromMac ?? '');\n if (named !== undefined) return named;\n const host = clean((deps.hostname ?? hostname)());\n return host !== undefined && GENERATED_HOSTNAME.some((re) => re.test(host)) ? undefined : host;\n } catch {\n return undefined;\n }\n}\n\n/** Printable, trimmed, without `.local`, at most 64 characters; undefined when nothing is left. */\nexport function clean(raw: string): string | undefined {\n const printable = raw\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x1f\\x7f-\\x9f\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069\\ufeff]/g, '')\n .trim()\n .replace(/\\.local$/i, '')\n .trim();\n const capped = [...printable].slice(0, MAX_DEVICE_NAME).join('').trim();\n return capped.length > 0 ? capped : undefined;\n}\n\nfunction macComputerName(): Promise<string | null> {\n return new Promise((resolve) => {\n execFile(\n SCUTIL,\n ['--get', 'ComputerName'],\n { timeout: SCUTIL_TIMEOUT_MS, windowsHide: true },\n (err, stdout) => resolve(err === null ? String(stdout) : null),\n );\n });\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { deviceName as readDeviceName } from '../lib/device-name';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { liveLine, type LiveLine } from '../lib/live-line';\nimport { buildSiwxHeader, SIWX_CHAIN_ID, SIWX_HEADER } from '../lib/siwx';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n type TenjinSigner,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitWriteNotice, paint, style } from '../lib/output';\nimport { addressQrLines, textQrLines } from '../lib/qr';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { underAgentHarness } from '../lib/session';\nimport { SUGGESTED_FUND_USD } from '../router/fee';\nimport {\n dollars,\n forgetLink,\n inFlight,\n LINK_LIFETIME_MS,\n readLinkStatus,\n recallLink,\n rememberLink,\n STATUS_GRACE_MS,\n tokenExpiry,\n tokenOf,\n watchFunding,\n type LinkStatus,\n type RememberedLink,\n type WatchEnd,\n} from './fund-watch';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin fund` (and `tenjin wallet fund`): add funds to THIS wallet in the\n * browser. The CLI signs a SIWX proof with the wallet's own key and asks the\n * Tenjin backend for a checkout link for that same address (the server refuses\n * any other address). The link is the Tenjin /fund page, with a short-lived\n * token in the URL fragment, or a Coinbase-hosted checkout. The money moves\n * entirely on the provider's side and the link grants no spending power over\n * the wallet. A hosted link is single-use, expires in ~5 minutes and is bound\n * to this machine's public IP at mint time.\n *\n * At a terminal it then watches: the link's payment status from the server\n * and the balance, on one status line, until the money lands\n * (`fund-watch.ts`). `--usdc` shows the address to send USDC to instead,\n * and watches the same way.\n */\n\n/** The hosted Coinbase checkout host, one of the two hosts a returned link may use. */\nconst COINBASE_CHECKOUT_HOST = 'pay.coinbase.com';\n/** A hosted Coinbase link's own lifetime. */\nconst HOSTED_LIFETIME_MS = 5 * 60_000;\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/**\n * The only hosts a returned link may point at; anything else is refused unopened.\n * The first is the host of the pinned origin (the Tenjin /fund page), so it\n * follows the origin if that is ever re-pointed.\n */\nconst ALLOWED_CHECKOUT_HOSTS: readonly string[] = [\n new URL(FUND_ORIGIN).host,\n COINBASE_CHECKOUT_HOST,\n];\n/** Matches the server's presetAmount bound (the fund link route's body schema). */\nconst MAX_PRESET_USD = 100_000;\n/** The link route's bounds on `need`. */\nconst NEED_LABEL_MAX = 60;\nconst NEED_PRICE_MAX_USD = 100;\n/** How long the balance read before a mint may take: it never holds the link up for long. */\nconst BASELINE_TIMEOUT_MS = 4_000;\n/**\n * A payment started on a link this recent, with the balance not yet up, is\n * one on its way: a rerun waits on it rather than opening a second checkout.\n */\nconst DUPLICATE_WINDOW_MS = 15 * 60_000;\n/** How long `--usdc` watches for a transfer. */\nconst USDC_WAIT_MS = 15 * 60_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline (or the link's expiry) won. None establishes the payment status;\n * `status` carries what the page reported, when it did.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\n/** Where a fund link was asked for, as the fund page is told. */\nexport type FundSource = 'install' | 'agent' | 'terminal';\n\nexport interface FundNeed {\n label: string;\n priceUsd: number;\n}\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to the checkout. */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** The environment the agent-harness and browser checks read; defaults to the process's. */\n env?: NodeJS.ProcessEnv;\n /** `--no-qr`: no QR code, even where no browser can open. */\n qr?: boolean;\n /** Watch for the payment after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n /** `--usdc`: the address and a QR to send USDC to, no checkout. */\n usdc?: boolean;\n /** `--for` and `--price`: the paid call the money is for, shown on the page. */\n forLabel?: string;\n priceUsd?: string;\n /** Overrides the derived source; install passes `install`. */\n source?: FundSource;\n /** The \"Add funds to Tenjin\" title and balance; install has its own heading. */\n header?: boolean;\n /** Printed after \"Stopped watching\" on Ctrl-C: install's limits, next step and disclosure. */\n onStopLines?: readonly string[];\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n deviceName?: () => Promise<string | undefined>;\n /** One key from the person, for the expired link's `r` / `q`; null when nobody can answer. */\n readKey?: (keys: readonly string[]) => Promise<string | null>;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n pollIntervalMs?: number;\n /** Bounds the whole wait, in place of the link's expiry plus its grace. */\n pollTimeoutMs?: number;\n /** The status line's stream behavior, for tests. */\n live?: LiveLine;\n platform?: NodeJS.Platform;\n}\n\ninterface Issued {\n url: string;\n token?: string;\n expiresAt: number;\n hosted: boolean;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n const need = parseNeed(opts.forLabel, opts.priceUsd);\n const env = opts.env ?? process.env;\n const now = opts.now ?? Date.now;\n const human = ctx.io.isTTY && !ctx.flags.json;\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const rpcUrl = settings.rpcUrl.value;\n const readBalance = () => balanceOrUndefined(address, rpcUrl);\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting: the\n // envelope carrying the link is written only after runFund returns, and an\n // agent waits with `tenjin balance --wait` in the background instead.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n const live = opts.live ?? liveLine(ctx.io.stderr);\n const err = ctx.io.stderr;\n const say = (line = '') => err.write(`${line}\\n`);\n const dim = (text: string) => style('dim', text, err);\n\n if (opts.usdc === true) {\n return fundByUsdc(ctx, { address, readBalance, human, shouldWait, live, say, dim, opts });\n }\n\n // Read the balance BEFORE minting, every time: it is the baseline the wait\n // and a later `tenjin balance --wait` measure an arrival from, and what the\n // header shows. A slow or failed read only costs those, never the link.\n const startBalance = await withTimeout(readBalance(), BASELINE_TIMEOUT_MS);\n\n if (human && opts.header !== false) {\n say();\n say(` ${style('bold', 'Add funds to Tenjin', err)}`);\n say();\n if (startBalance !== undefined) say(` Balance ${dollars(startBalance)}`);\n }\n\n // A PAYMENT ALREADY ON ITS WAY is waited on, never doubled: a rerun while\n // money is landing is exactly how a second top-up happens.\n const prior = await recallLink(ctx.dataDir, address, now());\n const onItsWay =\n prior !== null && now() - prior.issuedAt < DUPLICATE_WINDOW_MS\n ? await paymentOnItsWay(prior, startBalance, opts.fetchImpl)\n : undefined;\n\n const source: FundSource = opts.source ?? (underAgentHarness(env) ? 'agent' : 'terminal');\n // Unlocked only to mint: waiting on a payment already on its way needs no\n // key, and a fresh link after it expires unlocks then.\n let signer: TenjinSigner | undefined;\n const mint = async (): Promise<Issued> => {\n signer ??= await provider.getSigner();\n const url = await mintLink(ctx, signer, address, {\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n ...(need !== undefined ? { need } : {}),\n source,\n deviceName: await (opts.deviceName ?? readDeviceName)().catch(() => undefined),\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n });\n const token = tokenOf(url);\n const hosted = new URL(url).host === COINBASE_CHECKOUT_HOST;\n const issuedAt = now();\n const expiresAt =\n (token !== undefined ? tokenExpiry(token) : undefined) ??\n issuedAt + (hosted ? HOSTED_LIFETIME_MS : LINK_LIFETIME_MS);\n // Every link is remembered, a hosted one too: its starting balance is what\n // a later `tenjin balance --wait` measures an arrival from. Only a Tenjin\n // link has a token, so only it has a status to follow.\n await rememberLink(ctx.dataDir, {\n version: 1,\n address: address.toLowerCase(),\n url,\n ...(token !== undefined ? { token } : {}),\n issuedAt,\n expiresAt,\n ...(startBalance !== undefined ? { startBalanceAtomic: startBalance.toString() } : {}),\n });\n return { url, ...(token !== undefined ? { token } : {}), expiresAt, hosted };\n };\n\n let link: Issued =\n onItsWay !== undefined\n ? {\n // On its way means it had a token, so it is a Tenjin link with a url.\n url: prior!.url!,\n ...(prior!.token !== undefined ? { token: prior!.token } : {}),\n expiresAt: prior!.expiresAt,\n hosted: false,\n }\n : await mint();\n\n // The link goes out on EVERY surface and before any waiting: the stdout\n // envelope that also carries it is written only after this function\n // returns. Off a terminal these are write-notices (stderr, no TTY or --json\n // gate); stdout stays exactly one JSON object. The link prints whole on\n // every path: a person who copies it into another browser needs the token\n // in its fragment, which can only fund this wallet and expires with the link.\n if (!human) {\n emitWriteNotice(\n ctx.io,\n `${onItsWay !== undefined ? 'Payment on its way, from' : 'Checkout'}: ${link.url}`,\n );\n emitWriteNotice(\n ctx.io,\n link.hosted\n ? 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network).'\n : 'The link expires in about 10 minutes.',\n );\n }\n\n // An explicitly requested funding command can open under an agent harness\n // even without a terminal. The opener is resolved by absolute path and\n // ignores BROWSER (lib/open-url.ts), so an agent host cannot route the link\n // into its embedded view.\n const willOpen =\n onItsWay === undefined && opts.open !== false && (ctx.io.isTTY || underAgentHarness(env));\n const show = async (issued: Issued): Promise<boolean> => {\n const browser = browserAvailable(env, opts.platform ?? process.platform);\n const opened = willOpen && browser ? await (opts.openUrl ?? openInBrowser)(issued.url) : false;\n if (!human) return opened;\n if (onItsWay !== undefined) {\n say();\n say(' A payment is already on its way.');\n say(` ${dim(issued.url)}`);\n } else if (opened) {\n say(' Checkout opened in your browser');\n say(` ${dim(issued.url)}`);\n } else if (!willOpen) {\n say(' Checkout open this link to pay:');\n say(` ${issued.url}`);\n } else {\n // No browser here (SSH, no display) or it would not open: a phone\n // camera opens the same page, the same flow.\n const qr = opts.qr !== false ? textQrLines(issued.url, err) : [];\n say();\n if (qr.length > 0) {\n say(\n browser\n ? \" Couldn't open a browser. Scan to pay on your phone:\"\n : ' No browser on this machine. Scan to pay on your phone:',\n );\n for (const line of qr) say(` ${line}`);\n say(` or open ${issued.url}`);\n } else {\n say(\n browser\n ? \" Couldn't open a browser. Open this link to pay:\"\n : ' No browser on this machine. Open this link to pay:',\n );\n say(` ${issued.url}`);\n }\n }\n say();\n return opened;\n };\n let opened = await show(link);\n\n let pollStatus: FundPollStatus = 'skipped';\n let end: WatchEnd | undefined;\n if (shouldWait && startBalance === undefined) pollStatus = 'unavailable';\n if (shouldWait && startBalance !== undefined) {\n const stopInterrupt = human ? onInterrupt(live, say, opts.onStopLines) : () => undefined;\n try {\n for (;;) {\n end = await watchFunding({\n startBalance,\n readBalance,\n ...(link.token !== undefined ? { token: link.token } : {}),\n expiresAt: link.expiresAt,\n deadline:\n opts.pollTimeoutMs !== undefined\n ? now() + opts.pollTimeoutMs\n : link.expiresAt + STATUS_GRACE_MS,\n view: 'checkout',\n ...(human ? { live } : {}),\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n ...(opts.sleep !== undefined ? { sleep: opts.sleep } : {}),\n ...(opts.pollIntervalMs !== undefined ? { intervalMs: opts.pollIntervalMs } : {}),\n now,\n });\n if (end.kind !== 'expired' || !human) break;\n // AN EXPIRED LINK, at a terminal: say whether money moved, then offer\n // a fresh link. Nothing was charged on it, unless the page could not\n // report (no status), where the payment may still be landing.\n live.warn(\n end.statusKnown\n ? 'The checkout link expired. Nothing was charged.'\n : 'The checkout link expired.',\n );\n if (!end.statusKnown) say(' If you paid, it still lands; `tenjin balance` shows it.');\n const ask = opts.readKey ?? (process.stdin.isTTY ? readKey : undefined);\n if (ask === undefined) break;\n say(` ${style('bold', 'r', err)} new link ${style('bold', 'q', err)} stop`);\n const key = await ask(['r', 'q']);\n if (key !== 'r') break;\n say();\n link = await mint();\n opened = await show(link);\n }\n } finally {\n stopInterrupt();\n live.stop();\n }\n pollStatus = end.kind === 'arrived' ? 'arrived' : 'timed-out';\n }\n\n const arrived = end?.kind === 'arrived' ? end : undefined;\n if (arrived !== undefined) await forgetLink(ctx.dataDir);\n const status: LinkStatus | undefined = end?.status ?? onItsWay;\n const balanceAtomic = arrived?.balance ?? startBalance;\n const amount = preset !== undefined ? String(preset) : SUGGESTED_FUND_USD;\n return {\n data: {\n address,\n checkoutUrl: link.url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: arrived !== undefined,\n pollStatus,\n ...(status !== undefined ? { status: status.state } : {}),\n ...(onItsWay !== undefined ? { paymentInFlight: true } : {}),\n // The link expired and this round's status read said no payment is on it.\n ...(end?.kind === 'expired' && end.statusKnown ? { nothingCharged: true } : {}),\n source,\n ...(need !== undefined ? { need } : {}),\n nextStep:\n arrived !== undefined\n ? 'Funds confirmed. Continue the original task; funding does not require another restart.'\n : agentNextStep({\n opened,\n amount,\n inFlight: onItsWay !== undefined,\n ...(need ? { need } : {}),\n }),\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n ...(arrived !== undefined ? { added: toMoney(arrived.added.toString()) } : {}),\n },\n humanLines: humanEnding(ctx.io, pollStatus, end, arrived?.balance),\n };\n}\n\n/** What a person reads last: the balance and what follows. */\nfunction humanEnding(\n io: CommandContext['io'],\n pollStatus: FundPollStatus,\n end: WatchEnd | undefined,\n balance: bigint | undefined,\n): string[] {\n if (pollStatus === 'arrived' && balance !== undefined) {\n return [\n '',\n ` Balance ${paint(io, 'bold', dollars(balance))}`,\n ' You can close the browser tab.',\n ];\n }\n if (pollStatus === 'unavailable') {\n return [\n \" Couldn't read your balance to watch for the payment. The link still works,\",\n ' and `tenjin balance` shows the payment once it lands.',\n ];\n }\n if (pollStatus === 'skipped') {\n return [' `tenjin balance --wait` tells you when the payment lands.'];\n }\n if (end?.kind === 'expired') {\n return ['', ' Run `tenjin fund` for a fresh link when you are ready.'];\n }\n return [\n '',\n \" The payment hasn't reached your balance yet. It still can:\",\n ' `tenjin balance --wait` watches for it.',\n ];\n}\n\n/**\n * THE AGENT'S NEXT STEP after a link it did not wait on: say what the money is\n * for, wait in the background, carry on when it lands. It never asks the\n * person to come back and type that they are done.\n */\nfunction agentNextStep(o: {\n opened: boolean;\n amount: string;\n inFlight: boolean;\n need?: FundNeed;\n}): string {\n const wait =\n 'run `tenjin balance --wait` in the background, with the same Tenjin executable and shell as this command (in Claude Code, as a background Bash command, so you are woken when it exits), and continue the task when it exits: exit 0 means the funds arrived, and its output says how much. If it exits without funds, say once that nothing arrived and nothing went wrong, and continue without paid tools.';\n if (o.inFlight) {\n return `A payment for this machine is already on its way, so no second checkout was opened; do not open another. Tell the person in one sentence, then ${wait} Never ask the person to type \"done\" or to tell you when the money arrives.`;\n }\n const what =\n o.need !== undefined\n ? `what the money is for (${o.need.label}, $${o.need.priceUsd} a call)`\n : 'what the money is for (the paid tool you wanted and its price, if there is one)';\n const where = o.opened\n ? `that checkout is open in their browser with $${o.amount} filled in`\n : `that checkout is ready with $${o.amount} filled in, and show checkoutUrl as a clickable link`;\n return `Tell the person in one or two sentences ${what} and ${where}. Then ${wait} Never ask the person to type \"done\" or to tell you when they have paid. Ask about adding funds at most once per session: if they decline, carry on without paid tools and do not offer again. Do not open another checkout unless they ask for a new link.`;\n}\n\n/**\n * `--usdc`: the address to send USDC to, its safety rule first, and a QR of\n * the plain address. Nothing is minted and no key is unlocked; the wait is\n * the balance alone.\n */\nasync function fundByUsdc(\n ctx: CommandContext,\n c: {\n address: string;\n readBalance: () => Promise<bigint | undefined>;\n human: boolean;\n shouldWait: boolean;\n live: LiveLine;\n say: (line?: string) => void;\n dim: (text: string) => string;\n opts: FundOptions;\n },\n): Promise<CommandResult> {\n const { address, human, say, dim, opts } = c;\n const now = opts.now ?? Date.now;\n const warning = \"Only USDC, only on the Base network. Anything else can't be recovered.\";\n const check = `starts ${address.slice(0, 6)} · ends ${address.slice(-4)}`;\n // Read the balance BEFORE the handoff, waiting or not: it is what this wait\n // and a later `tenjin balance --wait` measure an arrival from, so a transfer\n // that lands before that wait starts still counts. Bounded off the wait, as\n // for a checkout, so it never holds up the agent's envelope.\n const startBalance = c.shouldWait\n ? await c.readBalance()\n : await withTimeout(c.readBalance(), BASELINE_TIMEOUT_MS);\n // Remembered with no url and no token: `tenjin fund` finds no status to\n // follow, so it never reads this as a checkout on its way. A live checkout\n // link with a token is kept instead: replacing it would hide a card payment\n // still landing from the next `tenjin fund`, which would open a second\n // checkout. Its starting balance drops to this reading when that is lower\n // or it has none (its own read failed, or money was spent since), so\n // `tenjin balance --wait` counts a transfer that lands before it starts,\n // and a card payment still rises above it.\n if (startBalance !== undefined) {\n const prior = await recallLink(ctx.dataDir, address, now());\n if (prior?.token === undefined) {\n const issuedAt = now();\n await rememberLink(ctx.dataDir, {\n version: 1,\n address: address.toLowerCase(),\n issuedAt,\n expiresAt: issuedAt + USDC_WAIT_MS,\n startBalanceAtomic: startBalance.toString(),\n });\n } else if (\n prior.startBalanceAtomic === undefined ||\n startBalance < BigInt(prior.startBalanceAtomic)\n ) {\n await rememberLink(ctx.dataDir, { ...prior, startBalanceAtomic: startBalance.toString() });\n }\n }\n if (human) {\n const err = ctx.io.stderr;\n say();\n say(` ${style('bold', 'Send USDC to add funds', ctx.io.stderr)}`);\n say();\n say(` ${style('yellow', warning, err)}`);\n say();\n say(` ${style('bold', address, err)}`);\n say(` ${dim(check)}`);\n const qr = opts.qr !== false ? addressQrLines(address, err) : [];\n if (qr.length > 0) {\n say();\n for (const line of qr) say(` ${line}`);\n }\n say();\n } else {\n emitWriteNotice(ctx.io, `Send USDC to ${address} (${check}).`);\n emitWriteNotice(ctx.io, warning);\n }\n\n let end: WatchEnd | undefined;\n let pollStatus: FundPollStatus = c.shouldWait ? 'unavailable' : 'skipped';\n if (c.shouldWait && startBalance !== undefined) {\n const stopInterrupt = human ? onInterrupt(c.live, say, opts.onStopLines) : () => undefined;\n try {\n end = await watchFunding({\n startBalance,\n readBalance: c.readBalance,\n deadline: now() + (opts.pollTimeoutMs ?? USDC_WAIT_MS),\n view: 'usdc',\n ...(human ? { live: c.live } : {}),\n ...(opts.sleep !== undefined ? { sleep: opts.sleep } : {}),\n ...(opts.pollIntervalMs !== undefined ? { intervalMs: opts.pollIntervalMs } : {}),\n now,\n });\n } finally {\n stopInterrupt();\n c.live.stop();\n }\n pollStatus = end.kind === 'arrived' ? 'arrived' : 'timed-out';\n }\n const arrived = end?.kind === 'arrived' ? end : undefined;\n if (arrived !== undefined) await forgetLink(ctx.dataDir);\n const balanceAtomic = arrived?.balance ?? startBalance;\n return {\n data: {\n address,\n usdc: true,\n funded: arrived !== undefined,\n pollStatus,\n nextStep:\n arrived !== undefined\n ? 'Funds confirmed. Continue the original task; funding does not require another restart.'\n : `Give the person the address exactly as printed, with the rule \"${warning}\" Then run \\`tenjin balance --wait\\` in the background (in Claude Code, as a background Bash command) and continue the task when it exits. Never ask the person to type \"done\".`,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n ...(arrived !== undefined ? { added: toMoney(arrived.added.toString()) } : {}),\n },\n humanLines:\n arrived !== undefined\n ? ['', ` Balance ${paint(ctx.io, 'bold', dollars(arrived.balance))}`]\n : pollStatus === 'skipped'\n ? [' `tenjin balance --wait` says when it arrives.']\n : ['', ' Nothing has arrived yet. `tenjin balance --wait` keeps watching.'],\n };\n}\n\n/**\n * The prior link's payment status when it shows money on its way: `paying`,\n * or `paid` with the balance not yet above where it was when that link was\n * issued. Undefined otherwise, when the status cannot be read, or for a hosted\n * link or a `--usdc` handoff, which have no status to read.\n */\nasync function paymentOnItsWay(\n prior: RememberedLink,\n balance: bigint | undefined,\n fetchImpl: typeof fetch | undefined,\n): Promise<LinkStatus | undefined> {\n if (prior.token === undefined) return undefined;\n const read = await readLinkStatus(prior.token, {\n ...(fetchImpl !== undefined ? { fetchImpl } : {}),\n });\n if (!('status' in read) || !inFlight(read.status)) return undefined;\n if (balance !== undefined && prior.startBalanceAtomic !== undefined) {\n return balance > BigInt(prior.startBalanceAtomic) ? undefined : read.status;\n }\n // No balance to compare: only a payment still in progress is certain to be pending.\n return read.status.state === 'paying' ? read.status : undefined;\n}\n\n/** POST /api/fund/link with the wallet's SIWX proof: the checkout URL, validated. */\nasync function mintLink(\n ctx: CommandContext,\n signer: TenjinSigner,\n address: string,\n extra: {\n presetAmount?: number;\n need?: FundNeed;\n source: FundSource;\n deviceName: string | undefined;\n fetchImpl?: typeof fetch;\n },\n): Promise<string> {\n const siwxHeader = await buildSiwxHeader(signer, {\n baseUrl: FUND_ORIGIN,\n chainId: SIWX_CHAIN_ID,\n });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n // `deviceName`, `source` and `need` are display context for the page; a\n // server without them ignores them (its body schema is not strict).\n jsonBody: {\n address,\n ...(extra.presetAmount !== undefined ? { presetAmount: extra.presetAmount } : {}),\n ...(extra.deviceName !== undefined ? { deviceName: extra.deviceName } : {}),\n source: extra.source,\n ...(extra.need !== undefined ? { need: extra.need } : {}),\n },\n };\n const res = await httpRequest(`${FUND_ORIGIN}/api/fund/link`, {\n ...request,\n ...(extra.fetchImpl !== undefined ? { fetchImpl: extra.fetchImpl } : {}),\n });\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n return checkoutUrlFrom(res.status, res.json);\n}\n\n/**\n * Is there a browser on this machine a person is sitting at? Not over SSH,\n * and not on a Linux or BSD desktop with no display server.\n */\nexport function browserAvailable(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): boolean {\n const set = (v: string | undefined) => typeof v === 'string' && v.length > 0;\n if (set(env.SSH_CONNECTION) || set(env.SSH_CLIENT) || set(env.SSH_TTY)) return false;\n if (platform === 'darwin' || platform === 'win32') return true;\n return set(env.DISPLAY) || set(env.WAYLAND_DISPLAY);\n}\n\n/**\n * Ctrl-C while watching: clear the status line, say that checkout carries on,\n * print what the caller still owes the person (install's next step), then let\n * the signal end the process as it always did. Returns the remover.\n */\nfunction onInterrupt(\n live: LiveLine,\n say: (line?: string) => void,\n after: readonly string[] = [],\n): () => void {\n const handler = () => {\n live.stop();\n say();\n say(\" Stopped watching. This doesn't cancel checkout: `tenjin balance` shows the\");\n say(' payment once it lands.');\n for (const line of after) say(line);\n process.removeListener('SIGINT', handler);\n process.kill(process.pid, 'SIGINT');\n };\n process.on('SIGINT', handler);\n return () => process.removeListener('SIGINT', handler);\n}\n\n/** One key from the terminal, in raw mode; Ctrl-C and Escape read as `q`. */\nasync function readKey(keys: readonly string[]): Promise<string | null> {\n const stdin = process.stdin;\n if (!stdin.isTTY) return null;\n return new Promise((resolve) => {\n const wasRaw = stdin.isRaw;\n stdin.setRawMode(true);\n stdin.resume();\n const onData = (chunk: Buffer) => {\n const key = chunk.toString('utf8').toLowerCase();\n const answer = key === '\\x03' || key === '\\x1b' ? 'q' : keys.includes(key) ? key : null;\n if (answer === null) return;\n stdin.removeListener('data', onData);\n stdin.setRawMode(wasRaw);\n stdin.pause();\n resolve(answer);\n };\n stdin.on('data', onData);\n });\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin fund 5',\n });\n }\n return n;\n}\n\n/** `--for` and `--price`, together or not at all, within the link route's bounds. */\nexport function parseNeed(\n label: string | undefined,\n price: string | undefined,\n): FundNeed | undefined {\n if (label === undefined && price === undefined) return undefined;\n const example = 'Example: tenjin fund 5 --for \"X post read\" --price 0.006';\n if (label === undefined || price === undefined) {\n throw new CliError('USAGE', '--for and --price go together.', { fix: example });\n }\n const trimmed = label\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x1f\\x7f-\\x9f\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n .trim();\n if (trimmed.length === 0 || [...trimmed].length > NEED_LABEL_MAX) {\n throw new CliError('USAGE', `--for takes a label of 1 to ${NEED_LABEL_MAX} characters.`, {\n fix: example,\n });\n }\n const n = Number(price);\n if (\n !/^\\d+(\\.\\d+)?$/.test(price.trim()) ||\n !Number.isFinite(n) ||\n n <= 0 ||\n n > NEED_PRICE_MAX_USD\n ) {\n throw new CliError(\n 'USAGE',\n `--price takes the call's price in USD, above 0 and at most ${NEED_PRICE_MAX_USD}.`,\n { fix: example },\n );\n }\n return { label: trimmed, priceUsd: n };\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on one of the two\n * allowed hosts (the Tenjin origin or Coinbase's checkout) before anything else\n * sees it: a compromised or misconfigured server must not be able to steer the\n * user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (\n parsed !== undefined &&\n parsed.protocol === 'https:' &&\n ALLOWED_CHECKOUT_HOSTS.includes(parsed.host)\n ) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https on ${ALLOWED_CHECKOUT_HOSTS.join(' or ')}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Adding funds is not available in your region yet.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', \"Your computer's clock is off, so Tenjin could not sign in.\", {\n fix: \"Set your computer's clock right in its system settings, then run `tenjin fund` again.\",\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'Too many tries. Nothing was charged.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError('API_UNREACHABLE', 'Adding funds is down right now. Nothing was charged.', {\n fix: 'Retry later.',\n });\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(address: string, rpcUrl: string): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/** `p`, or undefined once `ms` has passed. */\nasync function withTimeout<T>(p: Promise<T | undefined>, ms: number): Promise<T | undefined> {\n let timer: NodeJS.Timeout | undefined;\n const late = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), ms);\n timer.unref();\n });\n try {\n return await Promise.race([p, late]);\n } finally {\n clearTimeout(timer);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AAiBzB,IAAM,qBAAqB;AAAA,EACzB;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AACF;AAEA,IAAM,kBAAkB;AACxB,IAAM,SAAS;AACf,IAAM,oBAAoB;AAS1B,eAAsB,WAAW,OAAuB,CAAC,GAAgC;AACvF,MAAI;AACF,UAAM,WAAW,KAAK,YAAY,QAAQ;AAC1C,UAAM,UAAU,aAAa,WAAW,OAAO,KAAK,gBAAgB,iBAAiB,IAAI;AACzF,UAAM,QAAQ,MAAM,WAAW,EAAE;AACjC,QAAI,UAAU,OAAW,QAAO;AAChC,UAAM,OAAO,OAAO,KAAK,YAAY,UAAU,CA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