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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { FetchJsonFailure, HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\nimport type { Harness } from './names';\n\n/**\n * `POST /api/x402-router`: ONE DECISION PER LOOKUP. On the free path it costs\n * nothing. Inside `tenjin mcp`, while the server answers its paid path, the\n * same body goes to that path through the stock x402 client\n * ({@link DecisionRoute}, `routing-payer.ts`); a call that path cannot take\n * falls back to the free path. The rest of this note describes the free path,\n * which is unchanged.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * The bounded packet travels with the hook request and the backend keeps it\n * against the decision id until that id expires. What this client keeps is\n * each offer's spec, by its id (`specs.ts`).\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\n/** A display name the server gives a capability, sent because this build\n * lists `label`. Shown exactly as given; absent, a surface says\n * {@link UNLABELLED}. */\nconst LabelSchema = z.string().min(1).max(32);\n\n/** What a surface names a lookup whose decision carries no `label`. */\nexport const UNLABELLED = 'Tenjin lookup';\n\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n label: LabelSchema.optional(),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\n/**\n * STRUCTURE, NEVER WORDING. A hint lands in the model's context verbatim, so\n * its shape is checked the way the id's alphabet is: one line, no control\n * characters, and it has to be the call it claims to be, naming the id this\n * same answer carries. A hint that fails any of these is a protocol error and\n * the turn falls back to the generic line; nothing here rewrites a word of a\n * hint that passes. Both offering arms, `execute` and `discovered`, hold it.\n */\nfunction checkHint(decision: { id: string; hint: string }, ctx: z.RefinementCtx): void {\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n}\n\n/**\n * A PAY-PER-CALL SERVICE NOBODY CURATED. When a Tenjin list service does the\n * task the gate picked, or no task fits and a listed x402 service could do the\n * step, the server names that one service: who sells it, where, for how much,\n * and the input it takes. A Tenjin list service arrives here under its catalog\n * id, because this build sends `catalog`. The candidate is the seller's own\n * listing, so every field is data for the host to judge, never an instruction;\n * the host builds the `input` and the tool call pays through the same `runPay`\n * path and caps as a curated lookup.\n */\nconst DiscoveredCandidateSchema = z.strictObject({\n source: z.string().min(1).max(64),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n description: z.string().max(500),\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n network: z.string().min(1).max(64),\n payTo: z.string().min(1).max(200),\n input: z.strictObject({\n location: z.enum(['body', 'query']),\n schema: z.record(z.string(), z.unknown()),\n }),\n});\n\n/** A field name a job reads from an answer or writes into a poll body. */\nconst JobField = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/);\n\n/** A body field whose value names a state: Treza's `status: \"running\"`. */\nconst JobFieldStateSchema = z.strictObject({\n field: JobField,\n values: z.array(z.string().min(1).max(64)).min(1).max(8),\n});\n\n/** A poll body value naming a field of the call's input or of the submit's\n * answer; any other value is sent as written. */\nexport const POLL_REFERENCE = /^\\$(input|result)\\.([A-Za-z_][A-Za-z0-9_]{0,63})$/;\n\n/**\n * HOW A CALL WHOSE SELLER ANSWERS BEFORE THE RESULT IS READY IS FINISHED, sent\n * on a spec only because this build asks for it (`accepts: [\"jobs\"]`): where\n * the status is (a field or header of the submit's answer, or one fixed URL),\n * how a poll is sent, what says it is still running or failed, how often and\n * how long to poll, and how many hours the job can be resumed. `always`: the\n * seller never answers inline. A poll is never signed: the take's one payment\n * is its submit. Every field is the server's: the poll and complete URLs are\n * still checked here against the submit's host (`jobs.ts`).\n */\nexport const JobSchema = z\n .strictObject({\n pollUrl: z.union([\n z\n .strictObject({\n field: JobField.optional(),\n header: z\n .string()\n .regex(/^[A-Za-z0-9-]{1,64}$/)\n .optional(),\n })\n .refine((at) => at.field !== undefined || at.header !== undefined, 'a field or a header'),\n z.strictObject({ fixed: z.string().min(1).max(2_048) }),\n ]),\n /** Sent once like a poll after the result is saved, never after a save\n * that failed: it frees the seller's copy (AiSpace's `/complete`). Its\n * answer is ignored. */\n completeUrl: z.strictObject({ fixed: z.string().min(1).max(2_048) }).optional(),\n pollMethod: z.enum(['GET', 'POST']),\n pollBody: z\n .record(JobField, z.unknown())\n .refine(\n (body) =>\n Object.values(body).every(\n (value) =>\n typeof value !== 'string' || !value.startsWith('$') || POLL_REFERENCE.test(value),\n ),\n 'a $ value is $input.<field> or $result.<field>',\n )\n .optional(),\n running: z.union([\n z.strictObject({ httpStatus: z.array(z.number().int().min(200).max(299)).min(1).max(8) }),\n JobFieldStateSchema,\n ]),\n failed: JobFieldStateSchema.optional(),\n everyS: z.number().int().min(1).max(30),\n maxWaitS: z.number().int().min(1).max(600),\n keepH: z.number().int().min(1).max(48),\n always: z.literal(true).optional(),\n })\n .refine((job) => !job.pollBody || job.pollMethod === 'POST', 'only a POST poll has a body');\nexport type Job = z.infer<typeof JobSchema>;\n\n/**\n * A REQUEST SPEC: the offered service's real contract, sent beside the line only\n * because this build asks for it (`accepts: [\"spec\"]`). The hook stores it by\n * the offer's id; `request({id})` shows it and `request({id, input})` fills its\n * request and pays the provider directly, with no second decision. Every field\n * is the server's, and so is checked like the rest of the answer: the payee and\n * price still meet the live 402 and the spend policy in `runPay`.\n */\nexport const ToolSpecSchema = z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n /** The display name, on a catalog service's spec; a Bazaar spec has none. */\n label: LabelSchema.optional(),\n /** The input field that takes a pending search's query or fetch's URL. */\n holds: z\n .strictObject({\n WebSearch: z.string().min(1).max(64).optional(),\n WebFetch: z.string().min(1).max(64).optional(),\n })\n .optional(),\n /** What a paid result is. `media` means its files (bytes, links or inline\n * base64) are saved locally; absent on a Bazaar spec. */\n output: z.enum(['json', 'text', 'media']).optional(),\n description: z.string().min(1).max(500),\n priceAtomic: z.string().regex(/^\\d+$/),\n priceVaries: z.boolean(),\n maxAmountAtomic: z.string().regex(/^\\d+$/),\n payTo: z.string().min(1).max(200),\n network: z.string().min(1).max(64),\n asset: z.string().min(1).max(200),\n request: z.strictObject({\n method: z.enum(['GET', 'POST']),\n url: z.string().min(1).max(2_048),\n fields: z.record(z.string(), z.enum(['path', 'query', 'body'])),\n location: z.enum(['query', 'body']),\n /** Fixed request headers the catalog decides for this service (a\n * provider's beta opt-in, say), never the agent. The call refuses a name\n * this client signs or sets itself; `accept` and `content-type` stay its own. */\n headers: z\n .record(z.string().min(1).max(64), z.string().min(1).max(1_024))\n .refine((headers) => Object.keys(headers).length <= 8, 'at most 8 headers')\n .optional(),\n }),\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n /** The fields the result promises (type, properties, items, required). The\n * agent is handed only these; the whole body is saved to a file. */\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n /** How a call answered before its result is ready is finished. */\n job: JobSchema.optional(),\n /** A media service that runs several takes of one call: `count` up to `max`. */\n takes: z.strictObject({ max: z.number().int().min(2).max(5) }).optional(),\n});\nexport type ToolSpec = z.infer<typeof ToolSpecSchema>;\n\nexport const OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });\nexport type OfferSpec = z.infer<typeof OfferSpecSchema>;\n\n/** One spec per service the line names: the offer, any other service it\n * lists, and each option of a choice set. */\nconst SpecsSchema = z.array(OfferSpecSchema).min(1).max(8).optional();\n\n/** Words this client shows the model itself, in its own line: one plain line. */\nconst PlainLine = (max: number) =>\n z\n .string()\n .min(1)\n .max(max)\n .refine((text) => !/[\\p{Cc}\\p{Cf}]/u.test(text), 'one plain line');\n\n/**\n * SERVICES THE USER PICKS BETWEEN, OR RUNS ALL OF. Sent only beside a\n * discovered offer, to a build that lists `catalog` in `accepts`. Each option\n * is a real offer: its own id, its own spec in `specs`, and its own one\n * payment, so `request({id, choice})` runs exactly the spec\n * `request({id: option.id})` would. `all` runs every option side by side, one\n * payment each. The set is the server's data: changing it is a deploy there,\n * not a release here. `input` names the open fields the options share, the\n * only ones an `all` call may carry.\n */\nexport const ChoicesSchema = z.strictObject({\n group: PlainLine(64),\n default: PlainLine(64),\n input: z.array(PlainLine(64)).min(1).max(16),\n options: z\n .array(\n z.strictObject({\n key: PlainLine(64),\n label: PlainLine(120),\n strength: PlainLine(300),\n id: IdSchema,\n }),\n )\n .min(2)\n .max(4),\n all: z.strictObject({ totalAtomic: z.string().regex(/^\\d+$/) }),\n});\nexport type Choices = z.infer<typeof ChoicesSchema>;\n\n/** The word that runs every option, so no option may take it as its key. */\nexport const ALL_CHOICES = 'all';\n\n/**\n * A CHOICE NAMES ONLY WHAT THIS ANSWER CARRIES: each key and id once, `all`\n * free for the whole set, a spec for every option, and the default option is\n * the offer this answer's id already names. A set that breaks any of these is\n * a protocol error, and the turn falls back like any unreadable answer.\n */\nfunction checkChoices(\n decision: { id: string; specs?: { id: string }[] | undefined; choices?: Choices | undefined },\n ctx: z.RefinementCtx,\n): void {\n const { choices } = decision;\n if (choices === undefined) return;\n const issue = (message: string) => ctx.addIssue({ code: 'custom', path: ['choices'], message });\n const keys = choices.options.map((option) => option.key);\n const ids = choices.options.map((option) => option.id);\n if (new Set(keys).size !== keys.length) issue('each choice key is named once');\n if (new Set(ids).size !== ids.length) issue('each choice id is named once');\n if (keys.includes(ALL_CHOICES)) issue(`\"${ALL_CHOICES}\" runs every choice, so it is no key`);\n const specIds = new Set((decision.specs ?? []).map((spec) => spec.id));\n if (ids.some((id) => !specIds.has(id))) issue('every choice carries its spec');\n const fallback = choices.options.find((option) => option.key === choices.default);\n if (fallback === undefined) issue('the default is one of the choices');\n else if (fallback.id !== decision.id) issue(\"the default choice is this answer's own offer\");\n}\n\n/** The same answer on both calls: the hook's offer, and the tool's answer\n * when a query with no id found a service nobody curated. */\nconst DiscoveredSchema = z\n .strictObject({\n action: z.literal('discovered'),\n id: IdSchema,\n candidate: DiscoveredCandidateSchema,\n /** THE LINE, FINISHED, as on `execute`: it carries the seller's\n * description and the input it takes. */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n choices: ChoicesSchema.optional(),\n })\n .superRefine(checkHint)\n .superRefine(checkChoices);\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift. The same\n * bound as a discovered line's.\n */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n /**\n * HOW THE OFFER IS DELIVERED, sent because this build lists `fields`.\n * `note` is the free docs lookup before a search, for a client that\n * also lists `note`: the line comes after the search. `augment` is the\n * same offer for a client that does not, with the `augmentUrl` that\n * client fetches. `offer` is every other line. This build shows only a\n * `note` after a search; any other free offer before one, `augment`\n * included, runs silent.\n */\n delivery: z.enum(['offer', 'augment', 'note']).optional(),\n augmentUrl: z.string().url().max(2_048).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n /**\n * A query with no id, answered with the spec of the service the server\n * picked under a fresh `id`: kept like a hook's, and never run in the same\n * call. `hint` is the line, with the skeleton of the next call:\n * `request({id, input: {...}})` with the required fields. `input` is what a\n * router from before the binder's removal still sends on a bound pick: it\n * is accepted so that answer parses, and never read, so it never runs.\n */\n z\n .strictObject({\n action: z.literal('spec'),\n id: IdSchema,\n spec: ToolSpecSchema,\n hint: z.string().min(1).max(2_000),\n input: z.record(z.string(), z.unknown()).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\n/**\n * ONE ROW OF THE TOOL LIST, as the free browse answers it: the tool's id, its\n * display name (a list entry's upstream name runs to 120 characters), what it\n * does, its price as the server writes it, and its kind. Strict like every\n * answer here, with the server's own bounds. The id is the one field the model\n * sends back, so its alphabet is pinned; the text is flattened to one line\n * where it is shown (`tool.ts`).\n */\nconst BrowseRowSchema = z.strictObject({\n id: z\n .string()\n .min(1)\n .max(200)\n .regex(/^[A-Za-z0-9._:-]+$/),\n label: z.string().min(1).max(120),\n does: z.string().min(1).max(500),\n price: z.string().min(1).max(32),\n free: z.boolean(),\n kind: z.string().min(1).max(120),\n});\nexport type BrowseRow = z.infer<typeof BrowseRowSchema>;\n\nconst BrowseResponseSchema = z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n rows: z.array(BrowseRowSchema).max(200),\n});\nexport type BrowseResponse = z.infer<typeof BrowseResponseSchema>;\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool' | 'browse';\n\n/**\n * What this client can act on beyond the curated answers, sent on every call.\n * Each token names one kind of feature this build parses and runs, and the\n * server ignores a token it does not know, so the list only ever grows.\n * `label` takes each catalog service's display name on its spec and both\n * `execute` answers, and the offer line that starts at it. `fields` takes\n * each spec's `holds` and `output`, and the hook `execute`'s `delivery` and\n * `augmentUrl`. `note` asks for `delivery: \"note\"` on the free docs lookup\n * before a search, whose line this build shows after the search, in place of\n * the `augment` an older build fetched. `catalog` takes Tenjin's reviewed\n * list of third-party services as\n * `discovered` offers under their catalog ids, with each spec's `holds` and\n * `output`, and `choices`, a set of options the user picks between or runs\n * all of, beside a discovered offer from a compare group. A build that sends\n * `discovered` in its place gets the same services under their\n * `discovered:tenjin:` ids. `spec` asks for each offered service's request\n * spec beside its line, and for the picked service's spec in place of a\n * decision on a query with no id, which only a build that parses them can\n * take: the decision schemas are strict. `jobs` asks for each spec's `job`,\n * for the services that never answer inline, and for `count` on a media\n * offer's line. `headers` asks for a spec's `request.headers`, the fixed\n * headers the catalog sets on a service's call (a provider's beta opt-in),\n * with the pins those headers unlock: `buildSpecRequest` sends them, and a\n * build without the token is never sent a spec it would refuse as strict.\n * `bazaar` widens discovery to the open Bazaar and is sent only while\n * `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = [\n 'catalog',\n 'spec',\n 'label',\n 'fields',\n 'jobs',\n 'headers',\n 'note',\n];\nexport const BAZAAR_ACCEPT = 'bazaar';\n\n/** The `accepts` this build sends, with the open Bazaar or without it. */\nexport function acceptsFor(bazaar: boolean): string[] {\n return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];\n}\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone. `sessionId` is the harness's own session id, which the\n * server uses only so one session is not offered the same discovered service\n * twice.\n */\nexport function buildHookBody(\n packet: Packet,\n extras: { sessionId?: string; accepts?: readonly string[]; harness?: Harness } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(extras.sessionId !== undefined ? { sessionId: extras.sessionId } : {}),\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n ...(extras.harness !== undefined ? { harness: extras.harness } : {}),\n packet,\n };\n}\n\n/** The exact body the tool call sends. `id` is the offer the query is for,\n * sent only for an offer with no spec kept; `gateHint` is evidence, never\n * authority. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\n gateHint?: GateHint;\n accepts?: readonly string[];\n harness?: Harness;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n ...(request.accepts !== undefined ? { accepts: [...request.accepts] } : {}),\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n };\n}\n\n/** The free browse of the tool list: `browse` is the need, or `\"\"` for every\n * tool by kind. No gate call and no Jev on the server. */\nexport function buildBrowseBody(request: {\n browse: string;\n accepts: readonly string[];\n harness?: Harness;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n browse: request.browse,\n accepts: [...request.accepts],\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n };\n}\n\n/** A browse row's id, answered with that tool's spec under a fresh offer id. */\nexport function buildToolSpecBody(request: {\n tool: string;\n accepts: readonly string[];\n harness?: Harness;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n tool: request.tool,\n accepts: [...request.accepts],\n ...(request.harness !== undefined ? { harness: request.harness } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n return { success: schemaFor(kind).safeParse(value).success };\n}\n\nfunction schemaFor(kind: CallKind) {\n return kind === 'hook'\n ? HookResponseSchema\n : kind === 'tool'\n ? ToolResponseSchema\n : BrowseResponseSchema;\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n /** `experimental.bazaar`: add {@link BAZAAR_ACCEPT}, so a service from the\n * open Bazaar may come back. Off by default: curated and the Tenjin list. */\n acceptsBazaar?: boolean;\n /**\n * The host asking. The server filters out the lookups that host's own tools\n * already do, and nothing else: never payment, limits or the fee. Absent is\n * `claude`, and every production caller sends it.\n */\n harness?: Harness;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n /** The paid path, when `tenjin mcp` takes it: the body goes to `path` and is\n * sent by `send`, which pays the routing fee with the stock x402 client.\n * Absent is the free path. */\n route?: DecisionRoute;\n}\n\n/** How a routing call reaches the paid path. `send` throws\n * {@link RouteSkipped} when it has no paid answer for the call, which then\n * takes the free path. */\nexport interface DecisionRoute {\n path: string;\n send: (url: string, options: HttpRequestOptions) => Promise<HttpResult>;\n /** What this route's calls deposited into the routing channel and the\n * router took, 0n for none: the caller says so once, where it is read. */\n deposited?: () => bigint;\n}\n\n/** The paid path gave this call no answer: the wallet locked, low or over\n * its spend limits, the channel busy, or the payment failed. */\nexport class RouteSkipped extends Error {\n /** `unreached`: the paid call could not reach the router\n * ({@link isUnreachable}), so the free path, on the same host, is not\n * tried and the call reads as that transport failure. */\n constructor(\n readonly why: string,\n readonly unreached?: FetchJsonFailure,\n ) {\n super(`routing fee not paid: ${why}`);\n }\n}\n\n/** Another session's call was in flight on the wallet's routing channel. */\nexport const CHANNEL_BUSY = 'channel_busy';\n/** The server answered no paid path. */\nexport const PAID_PATH_ABSENT = 'paid_path_absent';\n/** The paid call got no answer, a refused payment or a server error. */\nexport const PAYMENT_FAILED = 'payment_failed';\n/** The payment went out and the call's budget ran out before its answer:\n * no fault. `tenjin mcp` lets the request finish, so it is recorded. */\nexport const DEADLINE_AFTER_PAYMENT_SENT = 'deadline_after_payment_sent';\n\nexport type DecisionOutcome<T> =\n /** `freePath`: the paid path skipped the call for this reason and it went\n * to the free path instead, unpaid. */\n | { status: 'decided'; decision: T; freePath?: string }\n /** On the free path nothing was paid and nothing could be, so a failure here\n * costs the turn a routing answer and nothing else. */\n | {\n status: 'failed';\n reason: string;\n errorCode?: string;\n freePath?: string;\n /** The router could not be reached at all ({@link isUnreachable}). */\n unreachable?: true;\n /** No answer came back at all: a transport failure or a timeout. */\n noAnswer?: true;\n }\n /** The paid path gave no answer ({@link RouteSkipped}) and no time was left\n * for the free path: the native tool runs. */\n | { status: 'skipped'; why: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id and answers with\n * each offered service's spec. The tool sends `{ query }`, which the backend\n * answers with the spec of the service its gate picks, or `{ query, id }` for\n * the free docs offer, which has no spec and is bound from the query. Every\n * provider call is built here, from a spec, or for the docs lookup by the\n * backend from the query.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet; sessionId?: string },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n sessionId?: string;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(deps.route?.path ?? ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet, {\n ...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n })\n : buildToolBody({\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n const started = Date.now();\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n let response: HttpResult;\n try {\n response = await (deps.route?.send ?? httpRequest)(url, options);\n } catch (err) {\n if (!(err instanceof RouteSkipped)) throw err;\n if (err.unreached !== undefined) return readDecision(err.unreached, schema);\n const left = options.timeoutMs - (Date.now() - started);\n if (left <= 0) return { status: 'skipped', why: err.why };\n // A CALL THE PAID PATH COULD NOT TAKE STILL ROUTES, on the free path,\n // unpaid, inside what is left of its budget, and says why.\n response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n ...options,\n timeoutMs: left,\n });\n const free = readDecision(response, schema);\n // A failure here ran on what a paid attempt left of the budget, so it says\n // nothing about the router being down: it never starts the backoff.\n if (free.status === 'failed') {\n return {\n status: 'failed',\n reason: free.reason,\n ...(free.errorCode !== undefined ? { errorCode: free.errorCode } : {}),\n // Still no answer, which must not end another call's backoff.\n ...(free.noAnswer === true ? { noAnswer: true as const } : {}),\n freePath: err.why,\n };\n }\n return free.status === 'skipped' ? free : { ...free, freePath: err.why };\n }\n return readDecision(response, schema);\n}\n\n/**\n * THE TWO FREE READS OF THE TOOL LIST. `{browse}` lists the tools that fit a\n * need (or all of them, by kind, for `\"\"`), and `{tool}` answers a browse\n * row's id with that tool's spec under a fresh offer id, exactly as a query\n * with no id is answered. Neither makes a gate call on the server, neither is\n * charged the routing fee, and neither pays anything here, so both always take\n * the free path: `deps.route` is never read.\n */\nexport async function requestBrowse(\n browse: string,\n deps: Omit<DecisionDeps, 'route'>,\n): Promise<DecisionOutcome<BrowseResponse>> {\n return readDecision(\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody: buildBrowseBody({\n browse,\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n BrowseResponseSchema,\n );\n}\n\n/** `{tool}`: a browse row's spec, kept by the caller under the answer's id. */\nexport async function requestToolSpec(\n tool: string,\n deps: Omit<DecisionDeps, 'route'>,\n): Promise<DecisionOutcome<ToolResponse>> {\n return readDecision(\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody: buildToolSpecBody({\n tool,\n accepts: acceptsFor(deps.acceptsBazaar === true),\n harness: deps.harness ?? 'claude',\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n }),\n ToolResponseSchema,\n );\n}\n\n/** Why a call from a spec stopped before anything was signed: the input did\n * not fit, the live terms were not the spec's, the provider answered\n * something else, it could not be reached, or the wallet could not pay. */\nexport type UnpaidReason = 'input' | 'terms' | 'provider' | 'unreachable' | 'wallet';\n\n/** How a call run from a request spec ended, for the server's offer-to-call\n * count. No text: the id, the outcome, the provider's status and the time. */\nexport interface SpecOutcome {\n id: string;\n /** `unpaid`: stopped before anything was signed, which the server never\n * counts as the offer taken. `running`: paid, and the seller was still\n * rendering when the call ended. */\n status: 'fulfilled' | 'unverified' | 'failed' | 'needs_approval' | 'unpaid' | 'running';\n /** On `unpaid` only, where the server requires it. */\n reason?: UnpaidReason;\n httpStatus?: number;\n ms?: number;\n}\n\n/** The outcome report's own deadline: it is telemetry and never holds a result. */\nexport const OUTCOME_TIMEOUT_MS = 3_000;\n\n/**\n * TELL THE SERVER A SPEC WAS USED. The client called and paid the provider\n * itself, so this is the only word the server gets that its offer was taken,\n * or that a call for it stopped before payment and why. Never throws and never\n * waits on anything the caller needs: a lost report costs one count.\n */\nexport async function reportSpecOutcome(\n outcome: SpecOutcome,\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl' | 'harness'>,\n): Promise<void> {\n try {\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildOutcomeBody(outcome, deps.harness ?? 'claude'),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n // Telemetry only.\n }\n}\n\n/** The exact body of an outcome report, pinned to the shared fixtures. */\nexport function buildOutcomeBody(outcome: SpecOutcome, harness?: Harness): Record<string, unknown> {\n return {\n schemaVersion: 1,\n id: outcome.id,\n ...(harness !== undefined ? { harness } : {}),\n status: outcome.status,\n ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),\n ...(outcome.httpStatus !== undefined ? { httpStatus: outcome.httpStatus } : {}),\n ...(outcome.ms !== undefined ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}),\n };\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) {\n return {\n status: 'failed',\n reason: fetchFailureToCliError(response).message,\n ...(isUnreachable(response) ? { unreachable: true as const } : {}),\n ...(response.status === undefined ? { noAnswer: true as const } : {}),\n };\n }\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n\n/** A dropped socket, which a fresh connection usually gets past. */\nconst RESET_CODES = new Set(['ECONNRESET', 'UND_ERR_SOCKET']);\n\n/**\n * A ROUTER THAT CANNOT BE REACHED: the transport named the layer that refused\n * the connection (DNS, TLS, a refused connection, a proxy refusing the tunnel)\n * and no status came back. Never the call's own timeout: that is the gate's\n * few seconds, and a slow decision or a cold start must not take the router\n * away from every session. Never a status, even with a body that failed to\n * read, and never a reset socket, which the free path retries on a fresh one.\n */\nexport function isUnreachable(failure: FetchJsonFailure): boolean {\n return (\n failure.kind === 'network' &&\n failure.status === undefined &&\n failure.transport !== undefined &&\n !RESET_CODES.has(failure.transport.code ?? '')\n );\n}\n"],"mappings":";;;;;;;;;;AA4BO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAA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GAAI,QAAO;AAC9E,QAAM,OAAO,OAAO,YAAY,WAAW,QAAQ,MAAM,GAAG,GAAG,IAAI;AACnE,SAAO,EAAE,MAAM,SAAS,KAAK;AAC/B;AAGA,IAAM,cAAc,oBAAI,IAAI,CAAC,cAAc,gBAAgB,CAAC;AAUrD,SAAS,cAAc,SAAoC;AAChE,SACE,QAAQ,SAAS,aACjB,QAAQ,WAAW,UACnB,QAAQ,cAAc,UACtB,CAAC,YAAY,IAAI,QAAQ,UAAU,QAAQ,EAAE;AAEjD;","names":[]}
|
|
@@ -19,6 +19,7 @@ function launchedByPlugin(env = process.env) {
|
|
|
19
19
|
}
|
|
20
20
|
var HARNESSES = ["claude", "codex"];
|
|
21
21
|
var CODEX_REQUEST_TOOL = `mcp__${MCP_SERVER_NAME}__request`;
|
|
22
|
+
var CODEX_HOOK_TOOL = `mcp__${MCP_SERVER_NAME}__hook`;
|
|
22
23
|
function requestToolName(host = "claude", env = process.env) {
|
|
23
24
|
if (host === "codex") return CODEX_REQUEST_TOOL;
|
|
24
25
|
return launchedByPlugin(env) ? REQUEST_TOOL : LEGACY_REQUEST_TOOL;
|
|
@@ -38,6 +39,8 @@ export {
|
|
|
38
39
|
LEGACY_HOOK_TOOL,
|
|
39
40
|
launchedByPlugin,
|
|
40
41
|
HARNESSES,
|
|
42
|
+
CODEX_REQUEST_TOOL,
|
|
43
|
+
CODEX_HOOK_TOOL,
|
|
41
44
|
requestToolName
|
|
42
45
|
};
|
|
43
|
-
//# sourceMappingURL=chunk-
|
|
46
|
+
//# sourceMappingURL=chunk-MPZUYCAP.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/names.ts"],"sourcesContent":["/**\n * THE NAMES THE HARNESS KNOWS THE ROUTER BY, spelled once. `install` registers\n * the Claude Code plugin {@link PLUGIN_NAME}, whose MCP server is\n * {@link MCP_SERVER_NAME}, and Claude Code names a plugin's tools\n * `mcp__plugin_<plugin>_<server>__<tool>`. The plugin's hooks, the server's own\n * name and every hint line the hooks inject read these, so a rename moves them\n * together.\n *\n * A module of its own because the hooks need the tool name and must not load\n * `install` to get it: their chunk graph is the product's floor.\n */\nexport const PLUGIN_NAME = 'tenjin';\nexport const MCP_SERVER_NAME = 'router';\n/** The marketplace `install` adds from the package, so the plugin id is `tenjin@tenjin`. */\nexport const MARKETPLACE_NAME = 'tenjin';\nexport const PLUGIN_ID = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;\n/** The id Claude Code gives the same plugin loaded from a skills-directory folder. */\nexport const SKILLS_DIR_PLUGIN_ID = `${PLUGIN_NAME}@skills-dir`;\n/** How a plugin's `hooks.json` and `claude mcp` name the plugin's own server. */\nexport const PLUGIN_SERVER = `plugin:${PLUGIN_NAME}:${MCP_SERVER_NAME}`;\nconst TOOL_PREFIX = `mcp__plugin_${PLUGIN_NAME}_${MCP_SERVER_NAME}`;\nexport const REQUEST_TOOL = `${TOOL_PREFIX}__request`;\n/** The tool the plugin's hook legs call, which its own deny hook keeps from the model. */\nexport const PLUGIN_HOOK_TOOL = `${TOOL_PREFIX}__hook`;\n\n/**\n * THE SETTINGS-BASED INSTALL'S NAMES, for its migration and nothing else.\n * Releases up to alpha.26 registered the server as `x402` through `claude mcp\n * add` and wrote seven hook entries and two permission rules into settings.json.\n *\n * SHIM: remove on or after 2026-12-01, the first release cut 30 or more days\n * after the plugin PR 2 ships. Doctor keeps naming an unmigrated machine after.\n */\nexport const LEGACY_MCP_SERVER_NAME = 'x402';\nexport const LEGACY_REQUEST_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__request`;\nexport const LEGACY_HOOK_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__hook`;\n\n/**\n * Is this process one Claude Code launched from the plugin? Claude Code sets\n * `CLAUDE_PLUGIN_ROOT` for a plugin's MCP server and its command hooks\n * (checked on 2.1.296), and not for a server registered in `~/.claude.json`.\n */\nexport function launchedByPlugin(env: NodeJS.ProcessEnv = process.env): boolean {\n const root = env.CLAUDE_PLUGIN_ROOT;\n return typeof root === 'string' && root.length > 0;\n}\n\n/** The agent hosts the router serves, as the CLI names them to the server. */\nexport const HARNESSES = ['claude', 'codex'] as const;\nexport type Harness = (typeof HARNESSES)[number];\n\n/**\n * Codex names an MCP tool `mcp__<server>__<tool>`, and its plugin's server is\n * {@link MCP_SERVER_NAME}, so the grant key and the tool name move together.\n */\nexport const CODEX_REQUEST_TOOL = `mcp__${MCP_SERVER_NAME}__request`;\n\n/**\n * The request tool's name as the host exposes it, so an offer line never names\n * a tool the model does not have. In Claude Code: the plugin's tool for a\n * server the plugin launched, and the `x402` server's tool for one a settings\n * install launched.\n *\n * SHIM: the Claude settings branch goes on or after 2026-12-01 (see\n * {@link LEGACY_MCP_SERVER_NAME}); Claude's name is then always {@link REQUEST_TOOL}.\n */\nexport function requestToolName(\n host: Harness = 'claude',\n env: NodeJS.ProcessEnv = process.env,\n): string {\n if (host === 'codex') return CODEX_REQUEST_TOOL;\n return launchedByPlugin(env) ? REQUEST_TOOL : LEGACY_REQUEST_TOOL;\n}\n"],"mappings":";;;AAWO,IAAM,cAAc;AACpB,IAAM,kBAAkB;AAExB,IAAM,mBAAmB;AACzB,IAAM,YAAY,GAAG,WAAW,IAAI,gBAAgB;AAEpD,IAAM,uBAAuB,GAAG,WAAW;AAE3C,IAAM,gBAAgB,UAAU,WAAW,IAAI,eAAe;AACrE,IAAM,cAAc,eAAe,WAAW,IAAI,eAAe;AAC1D,IAAM,eAAe,GAAG,WAAW;AAEnC,IAAM,mBAAmB,GAAG,WAAW;AAUvC,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB,QAAQ,sBAAsB;AAC1D,IAAM,mBAAmB,QAAQ,sBAAsB;AAOvD,SAAS,iBAAiB,MAAyB,QAAQ,KAAc;AAC9E,QAAM,OAAO,IAAI;AACjB,SAAO,OAAO,SAAS,YAAY,KAAK,SAAS;AACnD;AAGO,IAAM,YAAY,CAAC,UAAU,OAAO;AAOpC,IAAM,qBAAqB,QAAQ,eAAe;
|
|
1
|
+
{"version":3,"sources":["../src/router/names.ts"],"sourcesContent":["/**\n * THE NAMES THE HARNESS KNOWS THE ROUTER BY, spelled once. `install` registers\n * the Claude Code plugin {@link PLUGIN_NAME}, whose MCP server is\n * {@link MCP_SERVER_NAME}, and Claude Code names a plugin's tools\n * `mcp__plugin_<plugin>_<server>__<tool>`. The plugin's hooks, the server's own\n * name and every hint line the hooks inject read these, so a rename moves them\n * together.\n *\n * A module of its own because the hooks need the tool name and must not load\n * `install` to get it: their chunk graph is the product's floor.\n */\nexport const PLUGIN_NAME = 'tenjin';\nexport const MCP_SERVER_NAME = 'router';\n/** The marketplace `install` adds from the package, so the plugin id is `tenjin@tenjin`. */\nexport const MARKETPLACE_NAME = 'tenjin';\nexport const PLUGIN_ID = `${PLUGIN_NAME}@${MARKETPLACE_NAME}`;\n/** The id Claude Code gives the same plugin loaded from a skills-directory folder. */\nexport const SKILLS_DIR_PLUGIN_ID = `${PLUGIN_NAME}@skills-dir`;\n/** How a plugin's `hooks.json` and `claude mcp` name the plugin's own server. */\nexport const PLUGIN_SERVER = `plugin:${PLUGIN_NAME}:${MCP_SERVER_NAME}`;\nconst TOOL_PREFIX = `mcp__plugin_${PLUGIN_NAME}_${MCP_SERVER_NAME}`;\nexport const REQUEST_TOOL = `${TOOL_PREFIX}__request`;\n/** The tool the plugin's hook legs call, which its own deny hook keeps from the model. */\nexport const PLUGIN_HOOK_TOOL = `${TOOL_PREFIX}__hook`;\n\n/**\n * THE SETTINGS-BASED INSTALL'S NAMES, for its migration and nothing else.\n * Releases up to alpha.26 registered the server as `x402` through `claude mcp\n * add` and wrote seven hook entries and two permission rules into settings.json.\n *\n * SHIM: remove on or after 2026-12-01, the first release cut 30 or more days\n * after the plugin PR 2 ships. Doctor keeps naming an unmigrated machine after.\n */\nexport const LEGACY_MCP_SERVER_NAME = 'x402';\nexport const LEGACY_REQUEST_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__request`;\nexport const LEGACY_HOOK_TOOL = `mcp__${LEGACY_MCP_SERVER_NAME}__hook`;\n\n/**\n * Is this process one Claude Code launched from the plugin? Claude Code sets\n * `CLAUDE_PLUGIN_ROOT` for a plugin's MCP server and its command hooks\n * (checked on 2.1.296), and not for a server registered in `~/.claude.json`.\n */\nexport function launchedByPlugin(env: NodeJS.ProcessEnv = process.env): boolean {\n const root = env.CLAUDE_PLUGIN_ROOT;\n return typeof root === 'string' && root.length > 0;\n}\n\n/** The agent hosts the router serves, as the CLI names them to the server. */\nexport const HARNESSES = ['claude', 'codex'] as const;\nexport type Harness = (typeof HARNESSES)[number];\n\n/**\n * Codex names an MCP tool `mcp__<server>__<tool>`, and its plugin's server is\n * {@link MCP_SERVER_NAME}, so the grant key and the tool name move together.\n */\nexport const CODEX_REQUEST_TOOL = `mcp__${MCP_SERVER_NAME}__request`;\n/** The tool the Codex plugin's routing legs call, which its own deny hook keeps from the model. */\nexport const CODEX_HOOK_TOOL = `mcp__${MCP_SERVER_NAME}__hook`;\n\n/**\n * The request tool's name as the host exposes it, so an offer line never names\n * a tool the model does not have. In Claude Code: the plugin's tool for a\n * server the plugin launched, and the `x402` server's tool for one a settings\n * install launched.\n *\n * SHIM: the Claude settings branch goes on or after 2026-12-01 (see\n * {@link LEGACY_MCP_SERVER_NAME}); Claude's name is then always {@link REQUEST_TOOL}.\n */\nexport function requestToolName(\n host: Harness = 'claude',\n env: NodeJS.ProcessEnv = process.env,\n): string {\n if (host === 'codex') return CODEX_REQUEST_TOOL;\n return launchedByPlugin(env) ? REQUEST_TOOL : LEGACY_REQUEST_TOOL;\n}\n"],"mappings":";;;AAWO,IAAM,cAAc;AACpB,IAAM,kBAAkB;AAExB,IAAM,mBAAmB;AACzB,IAAM,YAAY,GAAG,WAAW,IAAI,gBAAgB;AAEpD,IAAM,uBAAuB,GAAG,WAAW;AAE3C,IAAM,gBAAgB,UAAU,WAAW,IAAI,eAAe;AACrE,IAAM,cAAc,eAAe,WAAW,IAAI,eAAe;AAC1D,IAAM,eAAe,GAAG,WAAW;AAEnC,IAAM,mBAAmB,GAAG,WAAW;AAUvC,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB,QAAQ,sBAAsB;AAC1D,IAAM,mBAAmB,QAAQ,sBAAsB;AAOvD,SAAS,iBAAiB,MAAyB,QAAQ,KAAc;AAC9E,QAAM,OAAO,IAAI;AACjB,SAAO,OAAO,SAAS,YAAY,KAAK,SAAS;AACnD;AAGO,IAAM,YAAY,CAAC,UAAU,OAAO;AAOpC,IAAM,qBAAqB,QAAQ,eAAe;AAElD,IAAM,kBAAkB,QAAQ,eAAe;AAW/C,SAAS,gBACd,OAAgB,UAChB,MAAyB,QAAQ,KACzB;AACR,MAAI,SAAS,QAAS,QAAO;AAC7B,SAAO,iBAAiB,GAAG,IAAI,eAAe;AAChD;","names":[]}
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
WALLET_CLASS,
|
|
4
|
+
sessionStartMessage,
|
|
5
|
+
walletClearedSentence
|
|
6
|
+
} from "./chunk-BFDQ4WNW.js";
|
|
7
|
+
import {
|
|
8
|
+
readPassphraseRecord
|
|
9
|
+
} from "./chunk-3AIHRXKO.js";
|
|
10
|
+
import {
|
|
11
|
+
PRIVATE_KEY_RE
|
|
12
|
+
} from "./chunk-X5ZBP3IY.js";
|
|
13
|
+
import {
|
|
14
|
+
hasCode
|
|
15
|
+
} from "./chunk-2I4QTOLB.js";
|
|
16
|
+
import {
|
|
17
|
+
DEFAULT_MAX_AUTO_SPEND
|
|
18
|
+
} from "./chunk-2M2VPI2E.js";
|
|
19
|
+
import {
|
|
20
|
+
DEFAULT_RPC_URL,
|
|
21
|
+
rememberingBalanceReader
|
|
22
|
+
} from "./chunk-WXA2BWTE.js";
|
|
23
|
+
import {
|
|
24
|
+
writeFileAtomic
|
|
25
|
+
} from "./chunk-7WEQQJLG.js";
|
|
26
|
+
import {
|
|
27
|
+
configPath,
|
|
28
|
+
passphraseFilePathFor,
|
|
29
|
+
passphraseRecordPath,
|
|
30
|
+
walletPath
|
|
31
|
+
} from "./chunk-OJNTCYQQ.js";
|
|
32
|
+
|
|
33
|
+
// src/router/alive.ts
|
|
34
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
35
|
+
import { mkdir as mkdir2, readdir as readdir2, readFile as readFile3, rm as rm2, rmdir, stat as stat2, writeFile } from "node:fs/promises";
|
|
36
|
+
import { join as join2 } from "node:path";
|
|
37
|
+
|
|
38
|
+
// src/lib/wallet-facts.ts
|
|
39
|
+
import { readFile, stat } from "node:fs/promises";
|
|
40
|
+
var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
|
|
41
|
+
async function readWalletFacts(dataDir, env) {
|
|
42
|
+
const key = env.TENJIN_WALLET_KEY?.trim() ?? "";
|
|
43
|
+
const envKey = key.length === 0 ? "absent" : PRIVATE_KEY_RE.test(key) ? "valid" : "malformed";
|
|
44
|
+
const passphrase = env.TENJIN_WALLET_PASSPHRASE;
|
|
45
|
+
const envPassphraseSet = passphrase !== void 0 && passphrase.length > 0;
|
|
46
|
+
const { walletFile, address } = await readWalletAddress(dataDir);
|
|
47
|
+
const [walletMtimeMs, sidecarMtimeMs] = await Promise.all([
|
|
48
|
+
mtimeOf(walletPath(dataDir)),
|
|
49
|
+
mtimeOf(passphraseRecordPath(dataDir))
|
|
50
|
+
]);
|
|
51
|
+
let passphraseStore = null;
|
|
52
|
+
let passphraseFileMissing = false;
|
|
53
|
+
if (address !== null) {
|
|
54
|
+
passphraseStore = (await readPassphraseRecord(dataDir, address).catch(() => null))?.store ?? null;
|
|
55
|
+
if (passphraseStore === "file") {
|
|
56
|
+
passphraseFileMissing = await stat(passphraseFilePathFor(address.toLowerCase(), dataDir)).then(() => false).catch((err) => hasCode(err, "ENOENT"));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
envKey,
|
|
61
|
+
walletFile,
|
|
62
|
+
address,
|
|
63
|
+
envPassphraseSet,
|
|
64
|
+
passphraseStore,
|
|
65
|
+
passphraseFileMissing,
|
|
66
|
+
walletMtimeMs,
|
|
67
|
+
sidecarMtimeMs
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function unlockStamp(f) {
|
|
71
|
+
return `${f.walletMtimeMs}:${f.sidecarMtimeMs}`;
|
|
72
|
+
}
|
|
73
|
+
async function readWalletAddress(dataDir) {
|
|
74
|
+
let text;
|
|
75
|
+
try {
|
|
76
|
+
text = await readFile(walletPath(dataDir), "utf8");
|
|
77
|
+
} catch (err) {
|
|
78
|
+
return { walletFile: hasCode(err, "ENOENT") ? "absent" : "unparsable", address: null };
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const record = JSON.parse(text);
|
|
82
|
+
const address = record?.address;
|
|
83
|
+
return typeof address === "string" && ADDRESS_RE.test(address) ? { walletFile: "present", address } : { walletFile: "unparsable", address: null };
|
|
84
|
+
} catch {
|
|
85
|
+
return { walletFile: "unparsable", address: null };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function mtimeOf(path) {
|
|
89
|
+
try {
|
|
90
|
+
return (await stat(path)).mtimeMs;
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// src/router/notice-markers.ts
|
|
97
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
98
|
+
import { mkdir, open, readFile as readFile2, readdir, rename, rm } from "node:fs/promises";
|
|
99
|
+
import { basename, dirname, join } from "node:path";
|
|
100
|
+
var NOTICE_KEEP_MS = 7 * 864e5;
|
|
101
|
+
var CLEARED = "cleared";
|
|
102
|
+
var UNLOCK_CLASS = [
|
|
103
|
+
"no_wallet",
|
|
104
|
+
"wallet_corrupt",
|
|
105
|
+
"env_key_invalid",
|
|
106
|
+
"passphrase_missing",
|
|
107
|
+
"passphrase_wrong",
|
|
108
|
+
"env_passphrase_wrong",
|
|
109
|
+
"keychain_locked",
|
|
110
|
+
"unlock_timeout",
|
|
111
|
+
"wallet_locked"
|
|
112
|
+
];
|
|
113
|
+
function noticesDir(dataDir) {
|
|
114
|
+
return join(dataDir, "router", "notices");
|
|
115
|
+
}
|
|
116
|
+
function sessionHash(sessionId) {
|
|
117
|
+
return createHash("sha256").update(sessionId).digest("hex").slice(0, 32);
|
|
118
|
+
}
|
|
119
|
+
function reasonMarker(dataDir, sessionId, why) {
|
|
120
|
+
const reason = createHash("sha256").update(why).digest("hex").slice(0, 8);
|
|
121
|
+
return join(noticesDir(dataDir), `${sessionHash(sessionId)}-${reason}`);
|
|
122
|
+
}
|
|
123
|
+
function currentPath(dataDir, sessionId) {
|
|
124
|
+
return join(noticesDir(dataDir), `${sessionHash(sessionId)}.current`);
|
|
125
|
+
}
|
|
126
|
+
async function writeCurrent(dataDir, sessionId, now, why) {
|
|
127
|
+
await writeFileAtomic(currentPath(dataDir, sessionId), `${now}
|
|
128
|
+
${why}`, {
|
|
129
|
+
mode: 384,
|
|
130
|
+
dirMode: 448
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
async function noticeFor(dataDir, sessionId, why, now) {
|
|
134
|
+
const created = await createExclusive(reasonMarker(dataDir, sessionId, why), String(now));
|
|
135
|
+
if (!created) return "quiet";
|
|
136
|
+
await writeCurrent(dataDir, sessionId, now, why);
|
|
137
|
+
await pruneNotices(dataDir, now);
|
|
138
|
+
return "tell";
|
|
139
|
+
}
|
|
140
|
+
async function noticeCleared(dataDir, sessionId, now) {
|
|
141
|
+
const text = await readFile2(currentPath(dataDir, sessionId), "utf8").catch(() => null);
|
|
142
|
+
if (text === null) return null;
|
|
143
|
+
const why = text.split("\n")[1] ?? "";
|
|
144
|
+
if (!WALLET_CLASS.has(why)) return null;
|
|
145
|
+
const marker = reasonMarker(dataDir, sessionId, why);
|
|
146
|
+
const claimed = join(
|
|
147
|
+
dirname(marker),
|
|
148
|
+
`.${basename(marker)}.${randomBytes(6).toString("hex")}.claimed`
|
|
149
|
+
);
|
|
150
|
+
try {
|
|
151
|
+
await rename(marker, claimed);
|
|
152
|
+
} catch {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
await rm(claimed, { force: true }).catch(() => void 0);
|
|
156
|
+
await writeCurrent(dataDir, sessionId, now, CLEARED);
|
|
157
|
+
return walletClearedSentence(why);
|
|
158
|
+
}
|
|
159
|
+
async function settleCurrent(dataDir, sessionId, now) {
|
|
160
|
+
await writeCurrent(dataDir, sessionId, now, CLEARED);
|
|
161
|
+
await Promise.all(
|
|
162
|
+
UNLOCK_CLASS.map(
|
|
163
|
+
(why) => rm(reasonMarker(dataDir, sessionId, why), { force: true }).catch(() => void 0)
|
|
164
|
+
)
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
async function pruneNotices(dataDir, now) {
|
|
168
|
+
const dir = noticesDir(dataDir);
|
|
169
|
+
for (const entry of await readdir(dir).catch(() => [])) {
|
|
170
|
+
if (entry.startsWith(".")) continue;
|
|
171
|
+
const path = join(dir, entry);
|
|
172
|
+
const text = await readFile2(path, "utf8").catch(() => "NaN");
|
|
173
|
+
if (text.length === 0) continue;
|
|
174
|
+
const at = Number(text.split("\n")[0]);
|
|
175
|
+
if (!Number.isFinite(at) || now - at > NOTICE_KEEP_MS) await rm(path, { force: true });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function createExclusive(path, body) {
|
|
179
|
+
try {
|
|
180
|
+
await mkdir(join(path, ".."), { recursive: true, mode: 448 });
|
|
181
|
+
const handle = await open(path, "wx", 384);
|
|
182
|
+
try {
|
|
183
|
+
await handle.writeFile(body);
|
|
184
|
+
} finally {
|
|
185
|
+
await handle.close();
|
|
186
|
+
}
|
|
187
|
+
return true;
|
|
188
|
+
} catch (err) {
|
|
189
|
+
if (hasCode(err, "EEXIST")) return false;
|
|
190
|
+
throw err;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// src/router/alive.ts
|
|
195
|
+
var MARKER_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
196
|
+
var STAMP = "plugin-loaded.json";
|
|
197
|
+
var MAX_SESSION_ID = 200;
|
|
198
|
+
function aliveDir(dataDir) {
|
|
199
|
+
return join2(dataDir, "alive");
|
|
200
|
+
}
|
|
201
|
+
function markerName(sessionId) {
|
|
202
|
+
return createHash2("sha256").update(sessionId).digest("hex").slice(0, 32);
|
|
203
|
+
}
|
|
204
|
+
function sessionIdOf(event) {
|
|
205
|
+
if (event === null || typeof event !== "object") return null;
|
|
206
|
+
const id = event.session_id;
|
|
207
|
+
return typeof id === "string" && id.length > 0 && id.length <= MAX_SESSION_ID ? id : null;
|
|
208
|
+
}
|
|
209
|
+
async function runAliveHook(event, opts) {
|
|
210
|
+
const sessionId = sessionIdOf(event);
|
|
211
|
+
const now = opts.now ?? Date.now();
|
|
212
|
+
const dir = aliveDir(opts.dataDir);
|
|
213
|
+
try {
|
|
214
|
+
await mkdir2(dir, { recursive: true, mode: 448 });
|
|
215
|
+
if (sessionId !== null) {
|
|
216
|
+
await writeFile(join2(dir, markerName(sessionId)), `${new Date(now).toISOString()}
|
|
217
|
+
`);
|
|
218
|
+
}
|
|
219
|
+
const stamp = { at: new Date(now).toISOString(), version: opts.version };
|
|
220
|
+
await writeFile(join2(dir, STAMP), `${JSON.stringify(stamp)}
|
|
221
|
+
`);
|
|
222
|
+
await pruneMarkers(dir, now);
|
|
223
|
+
} catch {
|
|
224
|
+
}
|
|
225
|
+
try {
|
|
226
|
+
const reason = await walletAtStart(opts.dataDir, opts.env ?? process.env);
|
|
227
|
+
if (reason === null) return null;
|
|
228
|
+
const { systemMessage, additionalContext } = sessionStartMessage(reason);
|
|
229
|
+
if (sessionId !== null) {
|
|
230
|
+
await noticeFor(opts.dataDir, sessionId, reason, now).catch(() => void 0);
|
|
231
|
+
}
|
|
232
|
+
return {
|
|
233
|
+
systemMessage,
|
|
234
|
+
hookSpecificOutput: { hookEventName: "SessionStart", additionalContext }
|
|
235
|
+
};
|
|
236
|
+
} catch {
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
async function walletAtStart(dataDir, env) {
|
|
241
|
+
const facts = await readWalletFacts(dataDir, env);
|
|
242
|
+
if (facts.envKey !== "absent") return null;
|
|
243
|
+
if (facts.walletFile === "absent") return null;
|
|
244
|
+
if (facts.walletFile === "unparsable") return "wallet_corrupt";
|
|
245
|
+
if (facts.passphraseFileMissing && !facts.envPassphraseSet) return "passphrase_missing";
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
async function pruneMarkers(dir, now) {
|
|
249
|
+
for (const name of await readdir2(dir).catch(() => [])) {
|
|
250
|
+
if (!/^[0-9a-f]{32}$/.test(name)) continue;
|
|
251
|
+
const path = join2(dir, name);
|
|
252
|
+
const s = await stat2(path).catch(() => null);
|
|
253
|
+
if (s !== null && now - s.mtimeMs > MARKER_TTL_MS) await rm2(path, { force: true });
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
async function sessionServedByPlugin(dataDir, event) {
|
|
257
|
+
const sessionId = sessionIdOf(event);
|
|
258
|
+
if (sessionId === null) return false;
|
|
259
|
+
return await stat2(join2(aliveDir(dataDir), markerName(sessionId))).catch(() => null) !== null;
|
|
260
|
+
}
|
|
261
|
+
async function readAliveStamp(dataDir) {
|
|
262
|
+
try {
|
|
263
|
+
const parsed = JSON.parse(await readFile3(join2(aliveDir(dataDir), STAMP), "utf8"));
|
|
264
|
+
if (parsed === null || typeof parsed !== "object") return null;
|
|
265
|
+
const { at, version } = parsed;
|
|
266
|
+
return typeof at === "string" && typeof version === "string" ? { at, version } : null;
|
|
267
|
+
} catch {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
async function removeAliveState(dataDir) {
|
|
272
|
+
const dir = aliveDir(dataDir);
|
|
273
|
+
const existed = await stat2(dir).catch(() => null) !== null;
|
|
274
|
+
if (!existed) return false;
|
|
275
|
+
for (const name of await readdir2(dir).catch(() => [])) {
|
|
276
|
+
if (name === STAMP || /^[0-9a-f]{32}$/.test(name)) await rm2(join2(dir, name), { force: true });
|
|
277
|
+
}
|
|
278
|
+
await rmdir(dir).catch(() => void 0);
|
|
279
|
+
return true;
|
|
280
|
+
}
|
|
281
|
+
var WALLET_READ_MS = 2e3;
|
|
282
|
+
async function walletNotice(dataDir, opts = {}) {
|
|
283
|
+
const wallet = await readJson(walletPath(dataDir));
|
|
284
|
+
const address = typeof wallet?.address === "string" ? wallet.address : void 0;
|
|
285
|
+
if (address === void 0 || !/^0x[0-9a-fA-F]{40}$/.test(address)) return null;
|
|
286
|
+
const config = await readJson(configPath(dataDir));
|
|
287
|
+
const rpcUrl = typeof config?.rpcUrl === "string" ? config.rpcUrl : DEFAULT_RPC_URL;
|
|
288
|
+
const timeoutMs = opts.timeoutMs ?? WALLET_READ_MS;
|
|
289
|
+
const read = rememberingBalanceReader(dataDir, {
|
|
290
|
+
...opts.read !== void 0 ? { read: opts.read } : {}
|
|
291
|
+
});
|
|
292
|
+
const balance = await read(address, rpcUrl, { timeoutMs });
|
|
293
|
+
if (balance === null) return null;
|
|
294
|
+
const cap = BigInt(
|
|
295
|
+
typeof config?.maxAutoSpend === "string" && /^\d{1,30}$/.test(config.maxAutoSpend) ? config.maxAutoSpend : DEFAULT_MAX_AUTO_SPEND
|
|
296
|
+
);
|
|
297
|
+
if (balance > 0n && balance >= cap) return null;
|
|
298
|
+
return `Tenjin balance: $${dollars(balance)}. Ask your agent to add funds to Tenjin.`;
|
|
299
|
+
}
|
|
300
|
+
function dollars(atomic) {
|
|
301
|
+
const fraction = (atomic % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
|
|
302
|
+
return `${atomic / 1000000n}.${fraction.padEnd(2, "0")}`;
|
|
303
|
+
}
|
|
304
|
+
async function readJson(path) {
|
|
305
|
+
try {
|
|
306
|
+
const value = JSON.parse(await readFile3(path, "utf8"));
|
|
307
|
+
return value !== null && typeof value === "object" ? value : null;
|
|
308
|
+
} catch {
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
async function aliveMain(opts) {
|
|
313
|
+
const raw = await (opts.readEvent ?? (() => readStdin(1e3)))().catch(() => "");
|
|
314
|
+
const answer = await runAliveHook(parseEvent(raw), {
|
|
315
|
+
dataDir: opts.dataDir,
|
|
316
|
+
version: opts.version,
|
|
317
|
+
...opts.env !== void 0 ? { env: opts.env } : {}
|
|
318
|
+
});
|
|
319
|
+
const notice = answer === null ? await walletNotice(opts.dataDir).catch(() => null) : null;
|
|
320
|
+
const payload = answer ?? (notice !== null ? { systemMessage: notice } : null);
|
|
321
|
+
if (payload === null) return;
|
|
322
|
+
const out = opts.stdout ?? process.stdout;
|
|
323
|
+
await new Promise((resolve) => {
|
|
324
|
+
try {
|
|
325
|
+
out.write(`${JSON.stringify(payload)}
|
|
326
|
+
`, () => resolve());
|
|
327
|
+
} catch {
|
|
328
|
+
resolve();
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
function parseEvent(raw) {
|
|
333
|
+
try {
|
|
334
|
+
return JSON.parse(raw);
|
|
335
|
+
} catch {
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
function readStdin(timeoutMs) {
|
|
340
|
+
return new Promise((resolve, reject) => {
|
|
341
|
+
const chunks = [];
|
|
342
|
+
let size = 0;
|
|
343
|
+
const timer = setTimeout(() => reject(new Error("no harness event")), timeoutMs);
|
|
344
|
+
process.stdin.on("data", (chunk) => {
|
|
345
|
+
size += chunk.length;
|
|
346
|
+
if (size > 1e6) {
|
|
347
|
+
clearTimeout(timer);
|
|
348
|
+
reject(new Error("harness event too large"));
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
chunks.push(chunk);
|
|
352
|
+
});
|
|
353
|
+
process.stdin.once("end", () => {
|
|
354
|
+
clearTimeout(timer);
|
|
355
|
+
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
356
|
+
});
|
|
357
|
+
process.stdin.once("error", () => {
|
|
358
|
+
clearTimeout(timer);
|
|
359
|
+
reject(new Error("harness event unreadable"));
|
|
360
|
+
});
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
async function markSessionServed(dataDir, event) {
|
|
364
|
+
const sessionId = sessionIdOf(event);
|
|
365
|
+
if (sessionId === null) return;
|
|
366
|
+
const path = join2(aliveDir(dataDir), markerName(sessionId));
|
|
367
|
+
if (await stat2(path).catch(() => null) !== null) return;
|
|
368
|
+
try {
|
|
369
|
+
await mkdir2(aliveDir(dataDir), { recursive: true, mode: 448 });
|
|
370
|
+
await writeFile(path, `${(/* @__PURE__ */ new Date()).toISOString()}
|
|
371
|
+
`);
|
|
372
|
+
} catch {
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export {
|
|
377
|
+
readWalletFacts,
|
|
378
|
+
unlockStamp,
|
|
379
|
+
noticeFor,
|
|
380
|
+
noticeCleared,
|
|
381
|
+
settleCurrent,
|
|
382
|
+
aliveDir,
|
|
383
|
+
runAliveHook,
|
|
384
|
+
walletAtStart,
|
|
385
|
+
sessionServedByPlugin,
|
|
386
|
+
readAliveStamp,
|
|
387
|
+
removeAliveState,
|
|
388
|
+
WALLET_READ_MS,
|
|
389
|
+
walletNotice,
|
|
390
|
+
aliveMain,
|
|
391
|
+
markSessionServed
|
|
392
|
+
};
|
|
393
|
+
//# sourceMappingURL=chunk-NDGZDTSJ.js.map
|