tenjin-cli 0.1.0-alpha.33 → 0.1.0-alpha.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE.md +110 -0
- package/README.md +87 -81
- package/dist/{_esm-BIN7VY2L.js → _esm-2KST7HQ7.js} +7 -7
- package/dist/alive-5TV22PNF.js +51 -0
- package/dist/auth-XI7BJFLW.js +47 -0
- package/dist/{auto-update-Y24UL56V.js → auto-update-7L24KDWA.js} +4 -5
- package/dist/balance-DFHC6XEU.js +71 -0
- package/dist/{ccip-DHDFKTQV.js → ccip-HOW3DZYF.js} +4 -4
- package/dist/chunk-24XKUN2S.js +202 -0
- package/dist/chunk-24XKUN2S.js.map +1 -0
- package/dist/chunk-2L7TDGLV.js +56 -0
- package/dist/chunk-2L7TDGLV.js.map +1 -0
- package/dist/{chunk-C2Q76BVM.js → chunk-2U7H35IP.js} +29 -7
- package/dist/chunk-2U7H35IP.js.map +1 -0
- package/dist/chunk-2W4DQQUU.js +176 -0
- package/dist/chunk-2W4DQQUU.js.map +1 -0
- package/dist/{chunk-LRW6S53P.js → chunk-34SAECKZ.js} +35 -11
- package/dist/chunk-34SAECKZ.js.map +1 -0
- package/dist/{chunk-2I4QTOLB.js → chunk-3MZ7DYRO.js} +1 -1
- package/dist/chunk-3MZ7DYRO.js.map +1 -0
- package/dist/{chunk-RVPYTUP4.js → chunk-3Y2EHT4F.js} +13 -9
- package/dist/chunk-3Y2EHT4F.js.map +1 -0
- package/dist/chunk-3Y6BHIN6.js +169 -0
- package/dist/chunk-3Y6BHIN6.js.map +1 -0
- package/dist/{chunk-4K7TQHNP.js → chunk-3YPL6T3P.js} +17 -33
- package/dist/chunk-3YPL6T3P.js.map +1 -0
- package/dist/{chunk-E7SW44LM.js → chunk-44MVIRZH.js} +121 -6
- package/dist/chunk-44MVIRZH.js.map +1 -0
- package/dist/chunk-45MMSBHA.js +321 -0
- package/dist/chunk-45MMSBHA.js.map +1 -0
- package/dist/{chunk-3FMZGI7I.js → chunk-4CE6TMI5.js} +1 -1
- package/dist/chunk-4CE6TMI5.js.map +1 -0
- package/dist/{chunk-QXP3Z3JN.js → chunk-4MBCJFY4.js} +35 -3
- package/dist/chunk-4MBCJFY4.js.map +1 -0
- package/dist/chunk-4TPL54KW.js +227 -0
- package/dist/chunk-4TPL54KW.js.map +1 -0
- package/dist/chunk-54ELBTKE.js +1615 -0
- package/dist/chunk-54ELBTKE.js.map +1 -0
- package/dist/{chunk-NDGZDTSJ.js → chunk-5F4OB5B3.js} +115 -57
- package/dist/chunk-5F4OB5B3.js.map +1 -0
- package/dist/chunk-5HN4KVQU.js +3348 -0
- package/dist/chunk-5HN4KVQU.js.map +1 -0
- package/dist/{chunk-ZDZERB6L.js → chunk-5J4E5GYI.js} +572 -407
- package/dist/chunk-5J4E5GYI.js.map +1 -0
- package/dist/{chunk-ZNNXRNFD.js → chunk-5N4GGUBN.js} +48 -6
- package/dist/chunk-5N4GGUBN.js.map +1 -0
- package/dist/chunk-5USBZ2MU.js +58 -0
- package/dist/chunk-5USBZ2MU.js.map +1 -0
- package/dist/chunk-64WOMNYR.js +183 -0
- package/dist/chunk-64WOMNYR.js.map +1 -0
- package/dist/{chunk-ILNIZ5I2.js → chunk-65RS4LQS.js} +1825 -1715
- package/dist/chunk-65RS4LQS.js.map +1 -0
- package/dist/{chunk-IE7P2BZE.js → chunk-6QMDUDF2.js} +3 -3
- package/dist/{chunk-IADZOXKN.js → chunk-7SLOTLO7.js} +19 -697
- package/dist/chunk-7SLOTLO7.js.map +1 -0
- package/dist/{chunk-WFSPCCVW.js → chunk-7V25UAQO.js} +99 -99
- package/dist/{chunk-WFSPCCVW.js.map → chunk-7V25UAQO.js.map} +1 -1
- package/dist/chunk-BGA4DO5M.js +719 -0
- package/dist/chunk-BGA4DO5M.js.map +1 -0
- package/dist/chunk-BVP7YK2J.js +706 -0
- package/dist/chunk-BVP7YK2J.js.map +1 -0
- package/dist/chunk-C265QIMJ.js +83 -0
- package/dist/chunk-C265QIMJ.js.map +1 -0
- package/dist/{chunk-XQJXNMSB.js → chunk-CRG54LEB.js} +1 -1
- package/dist/chunk-CRG54LEB.js.map +1 -0
- package/dist/{chunk-KG3D7FIF.js → chunk-CZJOMUBP.js} +2 -2
- package/dist/{chunk-36RVGZNY.js → chunk-D6M3ZK66.js} +22 -39
- package/dist/chunk-D6M3ZK66.js.map +1 -0
- package/dist/{chunk-3UCIG4TG.js → chunk-DI4QAGRZ.js} +1 -11
- package/dist/chunk-DI4QAGRZ.js.map +1 -0
- package/dist/{chunk-JKKAIPTU.js → chunk-DIH2G3YG.js} +47 -10
- package/dist/chunk-DIH2G3YG.js.map +1 -0
- package/dist/chunk-DJ36BM62.js +78 -0
- package/dist/chunk-DJ36BM62.js.map +1 -0
- package/dist/chunk-DTEWAVNE.js +114 -0
- package/dist/chunk-DTEWAVNE.js.map +1 -0
- package/dist/chunk-F2KJAJ7T.js +13 -0
- package/dist/chunk-F2KJAJ7T.js.map +1 -0
- package/dist/{chunk-BF4XHEQK.js → chunk-F3QPGYOY.js} +6 -6
- package/dist/chunk-F3QPGYOY.js.map +1 -0
- package/dist/{chunk-3GNJXKIT.js → chunk-F43CV6UC.js} +2 -2
- package/dist/{chunk-J57UC3DD.js → chunk-FKVJKLPI.js} +3 -3
- package/dist/{chunk-V2LQLN5H.js → chunk-FYFHH7V5.js} +59 -8
- package/dist/{chunk-V2LQLN5H.js.map → chunk-FYFHH7V5.js.map} +1 -1
- package/dist/chunk-GAJC4BQZ.js +1096 -0
- package/dist/chunk-GAJC4BQZ.js.map +1 -0
- package/dist/{chunk-DOQGNFHM.js → chunk-GH5UKMZD.js} +2 -12
- package/dist/{chunk-DOQGNFHM.js.map → chunk-GH5UKMZD.js.map} +1 -1
- package/dist/{chunk-WYXUQGOL.js → chunk-HAZAN4UM.js} +7 -6
- package/dist/chunk-HAZAN4UM.js.map +1 -0
- package/dist/chunk-HI5XQOX2.js +393 -0
- package/dist/chunk-HI5XQOX2.js.map +1 -0
- package/dist/chunk-HKGUKAQW.js +488 -0
- package/dist/chunk-HKGUKAQW.js.map +1 -0
- package/dist/{chunk-SO3XRZPX.js → chunk-HPRVFJPM.js} +6 -6
- package/dist/{chunk-L6JEXB3E.js → chunk-HQR4BWKX.js} +3 -131
- package/dist/chunk-HQR4BWKX.js.map +1 -0
- package/dist/chunk-HZKANST2.js +177 -0
- package/dist/chunk-HZKANST2.js.map +1 -0
- package/dist/{chunk-UUGOUOVT.js → chunk-I557SAOM.js} +8 -2
- package/dist/chunk-I557SAOM.js.map +1 -0
- package/dist/{chunk-TC2WZLSC.js → chunk-IGLWLH73.js} +8 -7
- package/dist/chunk-IGLWLH73.js.map +1 -0
- package/dist/chunk-ILWCKCOI.js +58 -0
- package/dist/chunk-ILWCKCOI.js.map +1 -0
- package/dist/{chunk-2GP3HRYK.js → chunk-INSIW65E.js} +182 -182
- package/dist/{chunk-MPZUYCAP.js → chunk-IULCDMVG.js} +12 -1
- package/dist/chunk-IULCDMVG.js.map +1 -0
- package/dist/{chunk-INTFHMU4.js → chunk-IVNSUAVC.js} +25 -26
- package/dist/chunk-IVNSUAVC.js.map +1 -0
- package/dist/chunk-JDQZCREI.js +87 -0
- package/dist/chunk-JDQZCREI.js.map +1 -0
- package/dist/chunk-JHFFUVON.js +1050 -0
- package/dist/chunk-JHFFUVON.js.map +1 -0
- package/dist/{chunk-RL5UUDT4.js → chunk-JNUKLSMZ.js} +3 -3
- package/dist/chunk-JTILUN4W.js +2933 -0
- package/dist/chunk-JTILUN4W.js.map +1 -0
- package/dist/{chunk-OJNTCYQQ.js → chunk-JTX3BUDK.js} +37 -53
- package/dist/chunk-JTX3BUDK.js.map +1 -0
- package/dist/{chunk-X5ZBP3IY.js → chunk-JUUBBBY5.js} +2 -2
- package/dist/chunk-JUUBBBY5.js.map +1 -0
- package/dist/chunk-JWAK7JQB.js +15 -0
- package/dist/chunk-JWAK7JQB.js.map +1 -0
- package/dist/{chunk-UXZONNEQ.js → chunk-K5KNGC4I.js} +34 -31
- package/dist/chunk-K5KNGC4I.js.map +1 -0
- package/dist/chunk-KAQ4Q3TO.js +135 -0
- package/dist/chunk-KAQ4Q3TO.js.map +1 -0
- package/dist/chunk-KFVJYLVL.js +125 -0
- package/dist/chunk-KFVJYLVL.js.map +1 -0
- package/dist/chunk-KGUE5AVX.js +69 -0
- package/dist/chunk-KGUE5AVX.js.map +1 -0
- package/dist/{chunk-FVIGCDSV.js → chunk-KLDMLWXT.js} +11 -85
- package/dist/chunk-KLDMLWXT.js.map +1 -0
- package/dist/chunk-KNKDMTHU.js +453 -0
- package/dist/chunk-KNKDMTHU.js.map +1 -0
- package/dist/chunk-LDA6TAYQ.js +95 -0
- package/dist/chunk-LDA6TAYQ.js.map +1 -0
- package/dist/chunk-LWSSIZOY.js +347 -0
- package/dist/chunk-LWSSIZOY.js.map +1 -0
- package/dist/{chunk-ZURZHELF.js → chunk-MAHNZA6C.js} +158 -41
- package/dist/chunk-MAHNZA6C.js.map +1 -0
- package/dist/chunk-MEWZCIA6.js +220 -0
- package/dist/chunk-MEWZCIA6.js.map +1 -0
- package/dist/{chunk-2SNUOHAT.js → chunk-MEZJ3I63.js} +49 -1
- package/dist/chunk-MEZJ3I63.js.map +1 -0
- package/dist/chunk-MJDO4EXD.js +353 -0
- package/dist/chunk-MJDO4EXD.js.map +1 -0
- package/dist/chunk-NJA6NT3A.js +6595 -0
- package/dist/chunk-NJA6NT3A.js.map +1 -0
- package/dist/{chunk-LHHMV4GU.js → chunk-NVSKJPRC.js} +1 -1
- package/dist/{chunk-LHHMV4GU.js.map → chunk-NVSKJPRC.js.map} +1 -1
- package/dist/{chunk-4YOZGGTZ.js → chunk-OC7K2DVZ.js} +5 -5
- package/dist/chunk-OC7K2DVZ.js.map +1 -0
- package/dist/chunk-ODRPASFP.js +2078 -0
- package/dist/chunk-ODRPASFP.js.map +1 -0
- package/dist/chunk-OJJFANO6.js +133 -0
- package/dist/chunk-OJJFANO6.js.map +1 -0
- package/dist/{chunk-JNJWBTU2.js → chunk-OQWPRFAC.js} +332 -882
- package/dist/chunk-OQWPRFAC.js.map +1 -0
- package/dist/chunk-P4I7BFNJ.js +11 -0
- package/dist/chunk-P4I7BFNJ.js.map +1 -0
- package/dist/{chunk-SNNSAGMT.js → chunk-P6YQWIT2.js} +4058 -4039
- package/dist/chunk-P6YQWIT2.js.map +1 -0
- package/dist/{chunk-JRGFKVAZ.js → chunk-PETQ5WEA.js} +2 -2
- package/dist/{chunk-HMWYAUA6.js → chunk-Q6RSJCXB.js} +29 -69
- package/dist/chunk-Q6RSJCXB.js.map +1 -0
- package/dist/{chunk-U3IKUGRP.js → chunk-QKEUKBRK.js} +17 -23
- package/dist/chunk-QKEUKBRK.js.map +1 -0
- package/dist/{chunk-2RWB7RKE.js → chunk-QKYUCITR.js} +174 -5814
- package/dist/chunk-QKYUCITR.js.map +1 -0
- package/dist/chunk-QQDPRTLP.js +127 -0
- package/dist/chunk-QQDPRTLP.js.map +1 -0
- package/dist/chunk-QQYCYAKI.js +79 -0
- package/dist/chunk-QQYCYAKI.js.map +1 -0
- package/dist/chunk-R4KDH477.js +1064 -0
- package/dist/chunk-R4KDH477.js.map +1 -0
- package/dist/chunk-R5TR2DIK.js +119 -0
- package/dist/chunk-R5TR2DIK.js.map +1 -0
- package/dist/chunk-R62PKTAG.js +66 -0
- package/dist/chunk-R62PKTAG.js.map +1 -0
- package/dist/{chunk-BFDQ4WNW.js → chunk-RFZA7PSM.js} +4 -5
- package/dist/chunk-RFZA7PSM.js.map +1 -0
- package/dist/chunk-RGCPELQN.js +219 -0
- package/dist/chunk-RGCPELQN.js.map +1 -0
- package/dist/chunk-RGVCOG2S.js +910 -0
- package/dist/chunk-RGVCOG2S.js.map +1 -0
- package/dist/chunk-SOLNJ3AZ.js +209 -0
- package/dist/chunk-SOLNJ3AZ.js.map +1 -0
- package/dist/chunk-TFT2X7SH.js +77 -0
- package/dist/chunk-TFT2X7SH.js.map +1 -0
- package/dist/chunk-TUCKEEXE.js +2 -0
- package/dist/chunk-TVWCLUBI.js +293 -0
- package/dist/chunk-TVWCLUBI.js.map +1 -0
- package/dist/chunk-U4TRWSVE.js +78 -0
- package/dist/chunk-U4TRWSVE.js.map +1 -0
- package/dist/chunk-UIB33QQP.js +379 -0
- package/dist/chunk-UIB33QQP.js.map +1 -0
- package/dist/chunk-V6GIVALQ.js +1889 -0
- package/dist/chunk-V6GIVALQ.js.map +1 -0
- package/dist/chunk-VHXCPXUS.js +366 -0
- package/dist/chunk-VHXCPXUS.js.map +1 -0
- package/dist/{chunk-HGZEPQUT.js → chunk-VU6GMWF6.js} +17 -8
- package/dist/chunk-VU6GMWF6.js.map +1 -0
- package/dist/chunk-VWZYE3NC.js +8415 -0
- package/dist/chunk-VWZYE3NC.js.map +1 -0
- package/dist/{chunk-AGMVASXZ.js → chunk-W2GXIARJ.js} +88 -11
- package/dist/chunk-W2GXIARJ.js.map +1 -0
- package/dist/chunk-W4G3K3V7.js +288 -0
- package/dist/chunk-W4G3K3V7.js.map +1 -0
- package/dist/chunk-W74LJ5OT.js +588 -0
- package/dist/chunk-W74LJ5OT.js.map +1 -0
- package/dist/chunk-W7ELYLYK.js +233 -0
- package/dist/chunk-W7ELYLYK.js.map +1 -0
- package/dist/{chunk-BPMWXTFX.js → chunk-WFZX352D.js} +7 -7
- package/dist/chunk-WXA3WTPF.js +20 -0
- package/dist/chunk-WXA3WTPF.js.map +1 -0
- package/dist/chunk-XRGFH7FI.js +454 -0
- package/dist/chunk-XRGFH7FI.js.map +1 -0
- package/dist/chunk-XSCGUO2U.js +330 -0
- package/dist/chunk-XSCGUO2U.js.map +1 -0
- package/dist/chunk-XWROSMI5.js +1039 -0
- package/dist/chunk-XWROSMI5.js.map +1 -0
- package/dist/chunk-Y2EXZ47H.js +40 -0
- package/dist/chunk-Y2EXZ47H.js.map +1 -0
- package/dist/chunk-YJGEVBKZ.js +47 -0
- package/dist/chunk-YJGEVBKZ.js.map +1 -0
- package/dist/{chunk-6CMM6YCB.js → chunk-YWWMISDY.js} +2 -2
- package/dist/{chunk-WXA2BWTE.js → chunk-ZCT5DJ3G.js} +2 -48
- package/dist/chunk-ZCT5DJ3G.js.map +1 -0
- package/dist/chunk-ZEYA2WWX.js +982 -0
- package/dist/chunk-ZEYA2WWX.js.map +1 -0
- package/dist/chunk-ZRC7Z5X3.js +82 -0
- package/dist/chunk-ZRC7Z5X3.js.map +1 -0
- package/dist/{chunk-3AIHRXKO.js → chunk-ZS7JIUJ3.js} +12 -10
- package/dist/chunk-ZS7JIUJ3.js.map +1 -0
- package/dist/{clack-EZ7TDWQU.js → clack-Q4RNC5VE.js} +2 -6
- package/dist/{claude-cli-2YKABJJZ.js → claude-cli-GIIHOBGT.js} +4 -2
- package/dist/claude-install-BAUSJMW3.js +64 -0
- package/dist/{cli-E36SPKBW.js → cli-QY4KKA3D.js} +632 -150
- package/dist/cli-QY4KKA3D.js.map +1 -0
- package/dist/client-3YQKORVK.js +710 -0
- package/dist/client-3YQKORVK.js.map +1 -0
- package/dist/{codex-event-ZO2GEFE6.js → codex-event-EUTCAOTQ.js} +3 -5
- package/dist/{codex-host-KECJVTA2.js → codex-host-ZON3S6HU.js} +7 -7
- package/dist/{codex-install-HQZDGFXW.js → codex-install-HZV2DOAB.js} +242 -88
- package/dist/codex-install-HZV2DOAB.js.map +1 -0
- package/dist/config-QZOBMTEL.js +57 -0
- package/dist/config-names-Z5NZD5R2.js +224 -0
- package/dist/config-names-Z5NZD5R2.js.map +1 -0
- package/dist/config-rules-YOYHS6YL.js +55 -0
- package/dist/config-subagents-WQV2ZAD5.js +362 -0
- package/dist/config-subagents-WQV2ZAD5.js.map +1 -0
- package/dist/connect-YDWTYU4B.js +1020 -0
- package/dist/connect-YDWTYU4B.js.map +1 -0
- package/dist/core-0a66n3e7-TTP554XV.js +127 -0
- package/dist/core-0a66n3e7-TTP554XV.js.map +1 -0
- package/dist/core-0bmnpbz2-C2JIRVZO.js +10790 -0
- package/dist/core-0bmnpbz2-C2JIRVZO.js.map +1 -0
- package/dist/core-9je8ee1j-74DGHWPV.js +30 -0
- package/dist/core-9je8ee1j-74DGHWPV.js.map +1 -0
- package/dist/core-wadgcjfh-TSZFQZGH.js +666 -0
- package/dist/core-wadgcjfh-TSZFQZGH.js.map +1 -0
- package/dist/core-zg882d22-LKV5DZYW.js +37 -0
- package/dist/core-zg882d22-LKV5DZYW.js.map +1 -0
- package/dist/decision-QSKHOGCO.js +145 -0
- package/dist/{doctor-I6XQEKWD.js → doctor-ZWJXRD75.js} +162 -148
- package/dist/doctor-ZWJXRD75.js.map +1 -0
- package/dist/{env-proxy-R6ZMLQTT.js → env-proxy-XLSLHBKQ.js} +2 -2
- package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js → ethersCompat-Df4a6QIZ-K3DMHR6Y.js} +5 -5
- package/dist/explicit-ME2NRADQ.js +371 -0
- package/dist/explicit-ME2NRADQ.js.map +1 -0
- package/dist/flush-stdio-NYIJ3QXT.js +18 -0
- package/dist/fund-VF7TLDJH.js +722 -0
- package/dist/fund-VF7TLDJH.js.map +1 -0
- package/dist/hook-command-VZ27MGWO.js +49 -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/hook-data.ts +152 -0
- package/dist/hosts/claude/tenjin/hooks/hooks.json +7 -0
- package/dist/hosts/claude/tenjin/hooks/model-viewer.tsx +2987 -0
- package/dist/hosts/claude/tenjin/hooks/register.tsx +527 -56
- package/dist/hosts/claude/tenjin/skills/tenjin-pay/SKILL.md +14 -4
- package/dist/hosts/claude/tenjin/types/index.d.ts +144 -1
- package/dist/{hosts-DVQJ32QC.js → hosts-3EMTVM4H.js} +7 -6
- package/dist/index.js +18 -15
- package/dist/index.js.map +1 -1
- package/dist/install-ZA7L2UF3.js +115 -0
- package/dist/install-funding-JDGYTF72.js +30 -0
- package/dist/install-identity-FFAYEFLX.js +30 -0
- package/dist/{install-wallet-5M4OTYLX.js → install-wallet-2SFOVE3Q.js} +68 -53
- package/dist/install-wallet-2SFOVE3Q.js.map +1 -0
- package/dist/mcp-36S6MK3C.js +67642 -0
- package/dist/mcp-36S6MK3C.js.map +1 -0
- package/dist/new-install-5L4GY3LN.js +51 -0
- package/dist/{package-IJFGMWEV.js → package-BONDXSV3.js} +2 -2
- package/dist/{passphrase-IFTDS3CU.js → passphrase-T4ULBN4M.js} +16 -12
- package/dist/{paths-XCSAKISU.js → paths-O2KDWZ76.js} +18 -28
- package/dist/pay-CMV5KL74.js +74 -0
- package/dist/{payments-HFPPWHTV.js → payments-Z6UBZL4Z.js} +36 -26
- package/dist/payments-Z6UBZL4Z.js.map +1 -0
- package/dist/reclaim-subagent-credit-ABSF67SJ.js +105 -0
- package/dist/reclaim-subagent-credit-ABSF67SJ.js.map +1 -0
- package/dist/{redact-D7ASVWKL.js → redact-LOTHE5TS.js} +2 -8
- package/dist/redact-LOTHE5TS.js.map +1 -0
- package/dist/routing-quote-AHLAREXR.js +40 -0
- package/dist/routing-quote-AHLAREXR.js.map +1 -0
- package/dist/run-JH7ELYAM.js +88 -0
- package/dist/run-JH7ELYAM.js.map +1 -0
- package/dist/runtime-2GX4ALJP.js +410 -0
- package/dist/runtime-2GX4ALJP.js.map +1 -0
- package/dist/runtime-activate-IDQ2NCSP.js +39 -0
- package/dist/runtime-activate-IDQ2NCSP.js.map +1 -0
- package/dist/{runtime-fetch-ZSSSK72Y.js → runtime-fetch-6LOBHBEN.js} +4 -4
- package/dist/runtime-fetch-6LOBHBEN.js.map +1 -0
- package/dist/runtime-launchers-YAPKCBHV.js +31 -0
- package/dist/runtime-launchers-YAPKCBHV.js.map +1 -0
- package/dist/{runtime-layout-WIDILZ6K.js → runtime-layout-QHZQJV7C.js} +5 -4
- package/dist/runtime-layout-QHZQJV7C.js.map +1 -0
- package/dist/runtime-place-4POL4KK4.js +37 -0
- package/dist/runtime-place-4POL4KK4.js.map +1 -0
- package/dist/runtime-provenance-MNJGVBV2.js +12 -0
- package/dist/runtime-provenance-MNJGVBV2.js.map +1 -0
- package/dist/{secp256k1-ZZZT2CAX.js → secp256k1-N5P2GVGF.js} +3 -3
- package/dist/secp256k1-N5P2GVGF.js.map +1 -0
- package/dist/{send-GCVEAQKL.js → send-ELXFKEKY.js} +35 -32
- package/dist/send-ELXFKEKY.js.map +1 -0
- package/dist/status-FXUFWJDM.js +404 -0
- package/dist/status-FXUFWJDM.js.map +1 -0
- package/dist/{status-line-OPCXDHL2.js → status-line-IH5JBWBC.js} +51 -43
- package/dist/status-line-IH5JBWBC.js.map +1 -0
- package/dist/streamableHttp-CP2ZQBIK.js +768 -0
- package/dist/streamableHttp-CP2ZQBIK.js.map +1 -0
- package/dist/{uninstall-BAWRBXXQ.js → uninstall-LJZUKM4D.js} +76 -76
- package/dist/uninstall-LJZUKM4D.js.map +1 -0
- package/dist/update-EUIX72IX.js +68 -0
- package/dist/update-EUIX72IX.js.map +1 -0
- package/dist/usage-EKDC7LUC.js +180 -0
- package/dist/usage-EKDC7LUC.js.map +1 -0
- package/dist/{usdc-VG4CIOUK.js → usdc-YIHK2OMC.js} +8 -12
- package/dist/usdc-YIHK2OMC.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-DOFTEIJV.js → viemAdapter-By13KInL-PRLSIESK.js} +5 -5
- package/dist/viemAdapter-By13KInL-PRLSIESK.js.map +1 -0
- package/dist/wallet-HSW757W6.js +80 -0
- package/dist/wallet-HSW757W6.js.map +1 -0
- package/dist/wallet-kdf-worker.mjs +1433 -818
- package/docs/agent-permissions.md +88 -155
- package/docs/router-reference.md +236 -0
- package/docs/safety-model.md +31 -33
- package/docs/subagents-internals.md +97 -0
- package/docs/subagents.md +348 -0
- package/docs/troubleshooting.md +10 -6
- package/package.json +12 -8
- package/scripts/installers/install.sh +7 -1
- package/dist/alive-GSOWKUOY.js +0 -38
- package/dist/chunk-2I4QTOLB.js.map +0 -1
- package/dist/chunk-2M2VPI2E.js +0 -560
- package/dist/chunk-2M2VPI2E.js.map +0 -1
- package/dist/chunk-2RWB7RKE.js.map +0 -1
- package/dist/chunk-2SNUOHAT.js.map +0 -1
- package/dist/chunk-3623BLPV.js +0 -184
- package/dist/chunk-3623BLPV.js.map +0 -1
- package/dist/chunk-36RVGZNY.js.map +0 -1
- package/dist/chunk-3AIHRXKO.js.map +0 -1
- package/dist/chunk-3FMZGI7I.js.map +0 -1
- package/dist/chunk-3UCIG4TG.js.map +0 -1
- package/dist/chunk-4K7TQHNP.js.map +0 -1
- package/dist/chunk-4LMUQMBH.js +0 -29
- package/dist/chunk-4LMUQMBH.js.map +0 -1
- package/dist/chunk-4USCZ2NI.js +0 -228
- package/dist/chunk-4USCZ2NI.js.map +0 -1
- package/dist/chunk-4YOZGGTZ.js.map +0 -1
- package/dist/chunk-62KNUYWD.js +0 -111
- package/dist/chunk-62KNUYWD.js.map +0 -1
- package/dist/chunk-A5GKIG5O.js +0 -2037
- package/dist/chunk-A5GKIG5O.js.map +0 -1
- package/dist/chunk-AGMVASXZ.js.map +0 -1
- package/dist/chunk-BF4XHEQK.js.map +0 -1
- package/dist/chunk-BFDQ4WNW.js.map +0 -1
- package/dist/chunk-C2Q76BVM.js.map +0 -1
- package/dist/chunk-CEXSOI5R.js +0 -808
- package/dist/chunk-CEXSOI5R.js.map +0 -1
- package/dist/chunk-E7SW44LM.js.map +0 -1
- package/dist/chunk-EDJWHDDL.js +0 -33
- package/dist/chunk-EDJWHDDL.js.map +0 -1
- package/dist/chunk-FVIGCDSV.js.map +0 -1
- package/dist/chunk-GTTUCOPD.js +0 -105
- package/dist/chunk-GTTUCOPD.js.map +0 -1
- package/dist/chunk-HDPUXS3Z.js +0 -122
- package/dist/chunk-HDPUXS3Z.js.map +0 -1
- package/dist/chunk-HGGWCP7W.js +0 -120
- package/dist/chunk-HGGWCP7W.js.map +0 -1
- package/dist/chunk-HGZEPQUT.js.map +0 -1
- package/dist/chunk-HMWYAUA6.js.map +0 -1
- package/dist/chunk-IADZOXKN.js.map +0 -1
- package/dist/chunk-ILNIZ5I2.js.map +0 -1
- package/dist/chunk-INTFHMU4.js.map +0 -1
- package/dist/chunk-JKKAIPTU.js.map +0 -1
- package/dist/chunk-JNJWBTU2.js.map +0 -1
- package/dist/chunk-KM7RY2ZS.js +0 -246
- package/dist/chunk-KM7RY2ZS.js.map +0 -1
- package/dist/chunk-KOGZDMHO.js +0 -21
- package/dist/chunk-KOGZDMHO.js.map +0 -1
- package/dist/chunk-L6JEXB3E.js.map +0 -1
- package/dist/chunk-LRW6S53P.js.map +0 -1
- package/dist/chunk-LXAYUOXI.js +0 -511
- package/dist/chunk-LXAYUOXI.js.map +0 -1
- package/dist/chunk-MEFB5KHA.js +0 -59
- package/dist/chunk-MEFB5KHA.js.map +0 -1
- package/dist/chunk-MPZUYCAP.js.map +0 -1
- package/dist/chunk-NDGZDTSJ.js.map +0 -1
- package/dist/chunk-OJNTCYQQ.js.map +0 -1
- package/dist/chunk-P3LFTKE7.js +0 -58
- package/dist/chunk-P3LFTKE7.js.map +0 -1
- package/dist/chunk-QXP3Z3JN.js.map +0 -1
- package/dist/chunk-RVPYTUP4.js.map +0 -1
- package/dist/chunk-SNNSAGMT.js.map +0 -1
- package/dist/chunk-TC2WZLSC.js.map +0 -1
- package/dist/chunk-TKPF35W6.js +0 -29
- package/dist/chunk-TKPF35W6.js.map +0 -1
- package/dist/chunk-U3IKUGRP.js.map +0 -1
- package/dist/chunk-UUGOUOVT.js.map +0 -1
- package/dist/chunk-UXZONNEQ.js.map +0 -1
- package/dist/chunk-WXA2BWTE.js.map +0 -1
- package/dist/chunk-WYXUQGOL.js.map +0 -1
- package/dist/chunk-X5ZBP3IY.js.map +0 -1
- package/dist/chunk-XKESD27X.js +0 -10
- package/dist/chunk-XKESD27X.js.map +0 -1
- package/dist/chunk-XQJXNMSB.js.map +0 -1
- package/dist/chunk-Y527D4TV.js +0 -56
- package/dist/chunk-Y527D4TV.js.map +0 -1
- package/dist/chunk-ZDZERB6L.js.map +0 -1
- package/dist/chunk-ZNNXRNFD.js.map +0 -1
- package/dist/chunk-ZURZHELF.js.map +0 -1
- package/dist/cli-E36SPKBW.js.map +0 -1
- package/dist/codex-install-HQZDGFXW.js.map +0 -1
- package/dist/config-HY2E4GGW.js +0 -55
- package/dist/doctor-I6XQEKWD.js.map +0 -1
- package/dist/fund-2QRO7OJL.js +0 -378
- package/dist/fund-2QRO7OJL.js.map +0 -1
- package/dist/hook-command-2UBCSZG6.js +0 -43
- package/dist/install-ILUX5C4A.js +0 -107
- package/dist/install-identity-TZKGY6LQ.js +0 -31
- package/dist/install-wallet-5M4OTYLX.js.map +0 -1
- package/dist/mcp-LE4DUS22.js +0 -14127
- package/dist/mcp-LE4DUS22.js.map +0 -1
- package/dist/pay-WCG3IH4R.js +0 -55
- package/dist/payments-HFPPWHTV.js.map +0 -1
- package/dist/plugin-registration-PZFI5GZW.js +0 -68
- package/dist/runtime-UZOKSUZX.js +0 -1321
- package/dist/runtime-UZOKSUZX.js.map +0 -1
- package/dist/send-GCVEAQKL.js.map +0 -1
- package/dist/status-HCVAOCN7.js +0 -150
- package/dist/status-HCVAOCN7.js.map +0 -1
- package/dist/status-line-OPCXDHL2.js.map +0 -1
- package/dist/uninstall-BAWRBXXQ.js.map +0 -1
- package/dist/update-CACXLQLR.js +0 -56
- package/dist/wallet-QL4UUXEZ.js +0 -55
- /package/dist/{_esm-BIN7VY2L.js.map → _esm-2KST7HQ7.js.map} +0 -0
- /package/dist/{alive-GSOWKUOY.js.map → alive-5TV22PNF.js.map} +0 -0
- /package/dist/{auto-update-Y24UL56V.js.map → auth-XI7BJFLW.js.map} +0 -0
- /package/dist/{ccip-DHDFKTQV.js.map → auto-update-7L24KDWA.js.map} +0 -0
- /package/dist/{clack-EZ7TDWQU.js.map → balance-DFHC6XEU.js.map} +0 -0
- /package/dist/{claude-cli-2YKABJJZ.js.map → ccip-HOW3DZYF.js.map} +0 -0
- /package/dist/{chunk-IE7P2BZE.js.map → chunk-6QMDUDF2.js.map} +0 -0
- /package/dist/{chunk-KG3D7FIF.js.map → chunk-CZJOMUBP.js.map} +0 -0
- /package/dist/{chunk-3GNJXKIT.js.map → chunk-F43CV6UC.js.map} +0 -0
- /package/dist/{chunk-J57UC3DD.js.map → chunk-FKVJKLPI.js.map} +0 -0
- /package/dist/{chunk-SO3XRZPX.js.map → chunk-HPRVFJPM.js.map} +0 -0
- /package/dist/{chunk-2GP3HRYK.js.map → chunk-INSIW65E.js.map} +0 -0
- /package/dist/{chunk-RL5UUDT4.js.map → chunk-JNUKLSMZ.js.map} +0 -0
- /package/dist/{chunk-JRGFKVAZ.js.map → chunk-PETQ5WEA.js.map} +0 -0
- /package/dist/{codex-event-ZO2GEFE6.js.map → chunk-TUCKEEXE.js.map} +0 -0
- /package/dist/{chunk-BPMWXTFX.js.map → chunk-WFZX352D.js.map} +0 -0
- /package/dist/{chunk-6CMM6YCB.js.map → chunk-YWWMISDY.js.map} +0 -0
- /package/dist/{codex-host-KECJVTA2.js.map → clack-Q4RNC5VE.js.map} +0 -0
- /package/dist/{config-HY2E4GGW.js.map → claude-cli-GIIHOBGT.js.map} +0 -0
- /package/dist/{env-proxy-R6ZMLQTT.js.map → claude-install-BAUSJMW3.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-X6YZWAML.js.map → codex-event-EUTCAOTQ.js.map} +0 -0
- /package/dist/{hook-command-2UBCSZG6.js.map → codex-host-ZON3S6HU.js.map} +0 -0
- /package/dist/{hosts-DVQJ32QC.js.map → config-QZOBMTEL.js.map} +0 -0
- /package/dist/{install-ILUX5C4A.js.map → config-rules-YOYHS6YL.js.map} +0 -0
- /package/dist/{install-identity-TZKGY6LQ.js.map → decision-QSKHOGCO.js.map} +0 -0
- /package/dist/{package-IJFGMWEV.js.map → env-proxy-XLSLHBKQ.js.map} +0 -0
- /package/dist/{passphrase-IFTDS3CU.js.map → ethersCompat-Df4a6QIZ-K3DMHR6Y.js.map} +0 -0
- /package/dist/{paths-XCSAKISU.js.map → flush-stdio-NYIJ3QXT.js.map} +0 -0
- /package/dist/{pay-WCG3IH4R.js.map → hook-command-VZ27MGWO.js.map} +0 -0
- /package/dist/{plugin-registration-PZFI5GZW.js.map → hosts-3EMTVM4H.js.map} +0 -0
- /package/dist/{redact-D7ASVWKL.js.map → install-ZA7L2UF3.js.map} +0 -0
- /package/dist/{runtime-fetch-ZSSSK72Y.js.map → install-funding-JDGYTF72.js.map} +0 -0
- /package/dist/{runtime-layout-WIDILZ6K.js.map → install-identity-FFAYEFLX.js.map} +0 -0
- /package/dist/{secp256k1-ZZZT2CAX.js.map → new-install-5L4GY3LN.js.map} +0 -0
- /package/dist/{update-CACXLQLR.js.map → package-BONDXSV3.js.map} +0 -0
- /package/dist/{usdc-VG4CIOUK.js.map → passphrase-T4ULBN4M.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-DOFTEIJV.js.map → paths-O2KDWZ76.js.map} +0 -0
- /package/dist/{wallet-QL4UUXEZ.js.map → pay-CMV5KL74.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/hooks.ts","../src/router/context.ts","../src/router/codex-history.ts","../src/router/decided.ts","../src/router/fetch-result.ts","../src/router/own-urls.ts","../src/router/hook-command.ts"],"sourcesContent":["import { homedir } from 'node:os';\nimport { z } from 'zod';\nimport { loadRawConfig, resolveExperimentalBazaar, resolveSettings } from '../lib/config';\nimport type { PartialConfig } from '../lib/config';\nimport { toMoney } from '../lib/money';\nimport { evaluateSpendPolicy } from '../lib/policy';\nimport { resolveContextSettings } from '../lib/settings';\nimport { readSpendSummary, spentOf } from '../lib/spend-ledger';\nimport { readWalletFacts } from '../lib/wallet-facts';\nimport type { CommandContext } from '../context';\nimport {\n buildNativePacket,\n buildPromptPacket,\n isHandback,\n seal,\n type NativeOutcome,\n type Packet,\n type PendingCall,\n type Sealed,\n} from './context';\nimport { storeAccountOffer, storeChoices, storeLabel, storeSpecs } from './specs';\nimport {\n isAccountSpec,\n requestDecision,\n REQUIRES_UNMET,\n ROUTE_PAID_PATH,\n type AccountOfferSpec,\n type AnyOfferSpec,\n type Bound,\n type HookDecision,\n type HookResponse,\n type OfferSpec,\n} from './decision';\nimport { accountLacks } from './accounts/presence';\nimport { keepDecided, takeDecided, type Decided } from './decided';\nimport { canSign, type SignVerdict } from './eligibility';\nimport { depositSentence, unpaidSentence, type RouteFor } from './fee';\nimport { termsNotice } from './terms-notice';\nimport { noticeCleared, noticeFor } from './notice-markers';\nimport { agentFixFor } from './wallet-reasons';\nimport { readsAsEmptyPage, savedPdfOf } from './fetch-result';\nimport { GATE_TIMEOUT_MS, UNPAID_GATE_TIMEOUT_MS } from './gate';\nimport {\n clearRouterMemo,\n readRouterMemo,\n UNREACHABLE_BACKOFF_MS,\n writeRouterMemo,\n} from './router-memo';\nimport { requestToolName, type Harness } from './names';\nimport { codexRouterEvent, codexSession } from './codex-event';\nimport { requestToolAccess, type AgentLookup } from './agent-tools';\nimport {\n bindDecision,\n claimRedirect,\n markHandedBack,\n markOffered,\n promptOfferKey,\n type OfferedTerms,\n newCallId,\n claimNote,\n markNoted,\n noteOf,\n noteSession,\n pruneProgress,\n pruneSessions,\n redirectClaimed,\n sessionDir,\n wasOffered,\n writeProgress,\n} from './progress';\nimport { routerSettings, type RouterSettings, type WireState } from './settings';\nimport { hashRefusal } from './settings-check';\nimport { claimIgnored, noteShown, offerScope, reportIgnored } from './untaken';\nimport { ownHostsFor } from './own-urls';\n\n/**\n * The six hook handlers. Between them they do exactly three things: build and\n * seal the packet, ask for one routing decision, and say one thing back to the\n * harness. Before an `execute` is shown where nobody can approve it, they also\n * read the wallet's local signing facts (`readWalletFacts`, `spendShortfall`).\n * A free offer on a search keeps its line on disk for after the search\n * (`markNoted`), and every shown offer is kept until it is taken, so one that\n * is ignored is reported once (`untaken.ts`); those are the only other things\n * they touch.\n *\n * NOTHING ELSE IS IN REACH FROM HERE. No wallet module, no signer, no payment\n * SDK, no viem, no MCP server: a dist test asserts the chunk graph, because the\n * hooks run on every prompt and after every native search, and their cost is\n * the product's floor.\n * Every routing call goes to the paid route. These handlers run inside\n * `tenjin mcp`, behind the plugins' `mcp_tool` hook entries: that process\n * passes its payer as {@link HookDeps.route}, and the payer, not this file,\n * signs and pays (`routing-payer.ts`). The `tenjin hook <kind>` command form\n * runs none of them (`hook-command.ts`).\n *\n * EVERY FAILURE IS SILENT. A backend that is down, slow or answering nonsense\n * leaves the prompt and the native result unchanged; the cause goes to\n * stderr. The user's turn is never blocked by this.\n *\n * A DENY ONLY WHERE IT CAN BE ACTED ON. The pre-call arm redirects a native\n * call the router routes, as every release has, because a note beside the call\n * was followed 0 times in 11 where the redirect is followed. But a denied\n * WebFetch stranded every subagent that could not reach `request`\n * (tenjin-agent#377), so a subagent is denied only when it is known to have\n * the tool (`requestToolAccess`) and the spend would auto-execute from a wallet\n * that can cover it; anyone else's call runs free. No arm ever returns `allow`: that would skip the user's own permission\n * rules for the call.\n */\n\nconst PromptEventSchema = z.object({\n session_id: z.string().min(1).max(200),\n /** The directory the session works in; `router.*` resolves from it. */\n cwd: z.string().optional(),\n transcript_path: z.string().optional(),\n prompt: z.string(),\n});\n\n/** What both native arms read: the call, whose it is, and where it runs. */\nconst NativeCallFields = {\n session_id: z.string().min(1).max(200),\n /** The harness's own path for THIS session: the decision reads the same\n * bounded history the prompt one does, so a restriction the user gave\n * reaches both gates. */\n transcript_path: z.string().optional(),\n tool_name: z.enum(['WebSearch', 'WebFetch']),\n tool_input: z.record(z.string(), z.unknown()),\n /** The harness's id for this one call, shared by its Pre and Post events. */\n tool_use_id: z.string().min(1).max(200).optional(),\n /** Present only inside a subagent, which is the one caller that cannot reach\n * the user to approve a spend. */\n agent_id: z.string().min(1).max(200).optional(),\n /** The subagent's type, which names its definition file. */\n agent_type: z.string().min(1).max(200).optional(),\n cwd: z.string().optional(),\n};\n\nconst NativeEventSchema = z.object({\n hook_event_name: z.literal('PreToolUse').optional(),\n ...NativeCallFields,\n});\n\nconst ShortfallEventSchema = z.object({\n hook_event_name: z.enum(['PostToolUse', 'PostToolUseFailure']),\n ...NativeCallFields,\n /** PostToolUse only: WebFetch's `{bytes, code, codeText, result, durationMs}`,\n * or WebSearch's `{query, results, durationSeconds, searchCount}`. */\n tool_response: z.unknown().optional(),\n /** PostToolUseFailure only: the failed call's own error, such as\n * `getaddrinfo ENOTFOUND x.test`. */\n error: z.unknown().optional(),\n is_interrupt: z.boolean().optional(),\n});\n\n/** Before the host asks the user: its questions and their options. */\nconst AskEventSchema = z.object({\n hook_event_name: z.literal('PreToolUse').optional(),\n ...NativeCallFields,\n tool_name: z.literal('AskUserQuestion'),\n});\n\n/** After the user answered: `tool_response` is `{questions, answers,\n * annotations}`, `answers` keyed by each question's text. */\nconst AnswerEventSchema = z.object({\n hook_event_name: z.literal('PostToolUse'),\n session_id: z.string().min(1).max(200),\n transcript_path: z.string().optional(),\n tool_name: z.literal('AskUserQuestion'),\n tool_input: z.record(z.string(), z.unknown()),\n tool_response: z.unknown().optional(),\n cwd: z.string().optional(),\n});\n\nconst DelegationEventSchema = z.object({\n session_id: z.string().min(1).max(200),\n transcript_path: z.string().optional(),\n /** `Task` is the tool's older name; the matcher `install` writes takes both. */\n tool_name: z.enum(['Agent', 'Task']),\n tool_input: z.record(z.string(), z.unknown()),\n cwd: z.string().optional(),\n});\n\n/** A native call as every arm past {@link decodeEvent} reads it. */\nexport interface NativeCall {\n sessionId: string;\n transcriptPath?: string;\n tool: 'WebSearch' | 'WebFetch';\n /** The search or URL, or null when the call carries none. */\n pending: PendingCall | null;\n toolUseId?: string;\n /** Present only inside a subagent. */\n agentId?: string;\n agentType?: string;\n cwd?: string;\n /** A Codex `webrun` call's input without `pending`, when anything else is in it. */\n rest?: Record<string, unknown>;\n /** Every search and URL in the call, `pending` first; absent means `pending` alone. */\n targets?: PendingCall[];\n}\n\n/** One hook event, as this file uses it. */\nexport type HookEvent =\n | { kind: 'prompt'; sessionId: string; transcriptPath?: string; prompt: string; cwd?: string }\n | ({ kind: 'native' } & NativeCall)\n | ({\n kind: 'ask';\n /** The questions and their options, joined; null when there are none. */\n pending: PendingCall | null;\n } & Omit<NativeCall, 'tool' | 'pending'>)\n | {\n kind: 'answer';\n sessionId: string;\n transcriptPath?: string;\n /** The user's answers, joined; null when there are none. */\n answers: string | null;\n cwd?: string;\n }\n | ({\n kind: 'shortfall';\n eventName: 'PostToolUse' | 'PostToolUseFailure';\n /** What the harness reported, when it was a shortfall; null means none. */\n nativeOutcome: NativeOutcome | null;\n /** The user's Esc or an abort cut the call (`is_interrupt`). */\n interrupted?: true;\n /** Where a WebFetch saved the PDF it fetched ({@link savedPdfOf}); null\n * for anything else. */\n savedPdf: string | null;\n } & NativeCall)\n | {\n kind: 'delegation';\n sessionId: string;\n transcriptPath?: string;\n /** `tool_input.prompt`: the subagent's whole task. */\n task: string | null;\n subagentType: string;\n /** The whole tool input, echoed back with the task changed. */\n toolInput: Record<string, unknown>;\n cwd?: string;\n };\n\n/**\n * THE ONLY READER OF A HARNESS FIELD. `session_id`, `transcript_path`,\n * `prompt`, `tool_name`, `tool_input` (its `query`, `url`, `prompt`,\n * `subagent_type` and `questions`), `tool_use_id`, `agent_id`, `agent_type`,\n * `cwd`, `tool_response` (and its `answers`) and `error` are Claude Code's names; everything past this\n * function reads {@link HookEvent}, so a second harness is a second decoder\n * rather than a change to each arm. `null` is an event no arm handles.\n */\nexport function decodeEvent(raw: unknown): HookEvent | null {\n const shortfall = ShortfallEventSchema.safeParse(raw);\n if (shortfall.success) {\n return {\n kind: 'shortfall',\n eventName: shortfall.data.hook_event_name,\n nativeOutcome: shortfallOf(shortfall.data),\n ...(shortfall.data.is_interrupt === true ? { interrupted: true as const } : {}),\n savedPdf: savedPdfIn(shortfall.data),\n ...nativeCallOf(shortfall.data),\n };\n }\n const native = NativeEventSchema.safeParse(raw);\n if (native.success) return { kind: 'native', ...nativeCallOf(native.data) };\n const answer = AnswerEventSchema.safeParse(raw);\n if (answer.success) {\n return {\n kind: 'answer',\n sessionId: answer.data.session_id,\n ...optional('transcriptPath', answer.data.transcript_path),\n answers: answersOf(answer.data.tool_response, answer.data.tool_input),\n ...optional('cwd', answer.data.cwd),\n };\n }\n const ask = AskEventSchema.safeParse(raw);\n if (ask.success) {\n const question = questionOf(ask.data.tool_input);\n return {\n kind: 'ask',\n ...callFieldsOf(ask.data),\n pending: question === null ? null : { tool: 'AskUserQuestion', question },\n };\n }\n const delegation = DelegationEventSchema.safeParse(raw);\n if (delegation.success) {\n const input = delegation.data.tool_input;\n return {\n kind: 'delegation',\n sessionId: delegation.data.session_id,\n ...optional('transcriptPath', delegation.data.transcript_path),\n task: typeof input.prompt === 'string' ? input.prompt : null,\n // With no type the harness runs its general-purpose agent.\n subagentType:\n typeof input.subagent_type === 'string' ? input.subagent_type : 'general-purpose',\n toolInput: input,\n ...optional('cwd', delegation.data.cwd),\n };\n }\n const prompt = PromptEventSchema.safeParse(raw);\n if (!prompt.success) return null;\n return {\n kind: 'prompt',\n sessionId: prompt.data.session_id,\n ...optional('transcriptPath', prompt.data.transcript_path),\n prompt: prompt.data.prompt,\n ...optional('cwd', prompt.data.cwd),\n };\n}\n\nfunction nativeCallOf(\n event: Omit<z.infer<typeof NativeEventSchema>, 'hook_event_name'>,\n): NativeCall {\n return {\n ...callFieldsOf(event),\n tool: event.tool_name,\n pending: pendingCallOf(event.tool_name, event.tool_input),\n };\n}\n\n/** Whose call it is and where it runs, the same for every tool. */\nfunction callFieldsOf(event: {\n session_id: string;\n transcript_path?: string | undefined;\n tool_use_id?: string | undefined;\n agent_id?: string | undefined;\n agent_type?: string | undefined;\n cwd?: string | undefined;\n}): Omit<NativeCall, 'tool' | 'pending'> {\n return {\n sessionId: event.session_id,\n ...optional('transcriptPath', event.transcript_path),\n ...optional('toolUseId', event.tool_use_id),\n ...optional('agentId', event.agent_id),\n ...optional('agentType', event.agent_type),\n ...optional('cwd', event.cwd),\n };\n}\n\n/**\n * THE HOST'S OWN WORDS BEFORE IT ASKS: each question, then each option's label\n * and description, in the order the host wrote them. Not cut here: seal()\n * masks it first and bounds it after, as it does a search.\n */\nfunction questionOf(input: Record<string, unknown>): string | null {\n const questions = Array.isArray(input.questions) ? input.questions : [];\n const parts: string[] = [];\n for (const entry of questions) {\n if (entry === null || typeof entry !== 'object') continue;\n const { question, options } = entry as { question?: unknown; options?: unknown };\n if (typeof question === 'string' && question.trim().length > 0) parts.push(question.trim());\n for (const option of Array.isArray(options) ? options : []) {\n if (option === null || typeof option !== 'object') continue;\n const { label, description } = option as { label?: unknown; description?: unknown };\n if (typeof label !== 'string' || label.trim().length === 0) continue;\n parts.push(\n typeof description === 'string' && description.trim().length > 0\n ? `${label.trim()}: ${description.trim()}`\n : label.trim(),\n );\n }\n }\n const joined = parts.join(' ');\n return joined.length > 0 ? joined : null;\n}\n\n/** The user's answers, one per line, from the tool's response, or from its\n * input where a harness puts them there instead. */\nfunction answersOf(response: unknown, input: Record<string, unknown>): string | null {\n for (const holder of [response, input]) {\n if (holder === null || typeof holder !== 'object' || Array.isArray(holder)) continue;\n const answers = (holder as { answers?: unknown }).answers;\n if (answers === null || typeof answers !== 'object' || Array.isArray(answers)) continue;\n const texts = Object.values(answers as Record<string, unknown>)\n .filter((value): value is string => typeof value === 'string')\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n if (texts.length > 0) return texts.join('\\n');\n }\n return null;\n}\n\n/** WebFetch's `result`, when it names the PDF it saved whole. */\nfunction savedPdfIn(event: z.infer<typeof ShortfallEventSchema>): string | null {\n if (event.hook_event_name !== 'PostToolUse' || event.tool_name !== 'WebFetch') return null;\n const response = event.tool_response;\n if (response === null || typeof response !== 'object' || Array.isArray(response)) return null;\n const result = (response as { result?: unknown }).result;\n return typeof result === 'string' ? savedPdfOf(result, event.session_id) : null;\n}\n\nfunction optional<K extends string>(key: K, value: string | undefined): Partial<Record<K, string>> {\n return value === undefined ? {} : ({ [key]: value } as Record<K, string>);\n}\n\n/** Acknowledgements that cannot be a lookup; `install` never gates them. */\nconst ACKNOWLEDGEMENTS = new Set(['y', 'yes', 'ok', 'okay', 'continue', 'go', 'sure', 'thanks']);\n\nexport type PromptSkip = 'slash' | 'acknowledgement' | 'handback';\n\n/**\n * Prompts that cannot need a lookup, decided locally with no network call. Any\n * OTHER short prompt still goes to the backend: `2^1000`, a bare URL and a task\n * typed without spaces can all need one, and a computation has no later\n * WebSearch or WebFetch hook to recover a skipped classification.\n */\nexport function promptSkipReason(prompt: string): PromptSkip | null {\n const trimmed = prompt.trim();\n // A hand-back from the harness or another agent ({@link isHandback}).\n if (isHandback(trimmed)) return 'handback';\n if (trimmed.startsWith('/')) return 'slash';\n const normalized = trimmed.toLowerCase().replace(/[.!,]+$/, '');\n return ACKNOWLEDGEMENTS.has(normalized) ? 'acknowledgement' : null;\n}\n\n/**\n * EVERY LINE SAYS WHERE IT CAME FROM AND NAMES THE REAL TOOL. An unattributed\n * line asking for a call the model cannot find by that name reads like an\n * injection, and a subagent looking for `request` in its tool list finds\n * nothing. So each line opens with its source, and the server's `request({`\n * becomes the name the harness actually exposes, from the one place `install`\n * registers it. The server's words are otherwise untouched: this client names\n * no provider and no price of its own.\n */\nexport const HINT_SOURCE = 'Tenjin router (installed by the user)';\n\nconst BARE_CALL_RE = /(?<![\\w$])request\\(\\{/g;\n\nexport function toolNamed(\n hint: string,\n host: Harness = 'claude',\n env: NodeJS.ProcessEnv = process.env,\n): string {\n return hint.replace(BARE_CALL_RE, `${requestToolName(host, env)}({`);\n}\n\n/** The server's line as the prompt hint and the redirect both carry it. */\nfunction attributed(hint: string, host: Harness): string {\n return `${HINT_SOURCE}: ${toolNamed(hint, host)}`;\n}\n\n/** This client's one sentence on a redirect: the promise {@link runNativeHook} keeps. */\nconst ONE_BLOCK =\n 'If this does not cover it, make your own call again: you will not be redirected twice in a row for the same search or URL.';\n\n/** The same promise, for a question the ask arm redirected. */\nconst ONE_BLOCK_QUESTION =\n 'If this does not cover it, ask your question again: you will not be redirected twice in a row for the same question.';\n\n/** The free line after WebFetch saved a PDF its summary could not read. */\nfunction savedPdfHint(path: string): string {\n return `${HINT_SOURCE}: WebFetch's summary cannot read a PDF, but it saved this one whole to ${path}. Read that file for its text, free (pass pages, such as \"1-10\", for a long one).`;\n}\n\n/** Where the offer sits after the free tool came back short. */\nfunction shortfallOffer(tool: 'WebSearch' | 'WebFetch', hint: string, host: Harness): string {\n return `${HINT_SOURCE}: your ${tool} call came back short. Optional: ${toolNamed(hint, host)}`;\n}\n\n/** Where a free lookup noted before a search sits, once the search has run. */\nfunction noteLine(line: string, host: Harness): string {\n return `${HINT_SOURCE}: your WebSearch call ran. Optional: ${toolNamed(line, host)}`;\n}\n\n/**\n * A WebFetch body smaller than this is empty for any purpose a reader has. The\n * smallest real page measured, example.com (a heading and two sentences),\n * reports 559 bytes; a 404 and x.com's blocked read both report 0. Sixty-four\n * bytes has no room for one sentence of content, so nothing a person would\n * call a page falls under it.\n */\nexport const NEAR_EMPTY_BYTES = 64;\n\n/**\n * DID THE FREE TOOL FALL SHORT, decided from the harness's own report and\n * nothing else: no model, no network call. Only clear signals count, and\n * everything else is `null`, which means the router is never asked:\n *\n * - a failed call (PostToolUseFailure), unless the user interrupted it;\n * - WebFetch refused or failing upstream: 401, 402, 403, 429 or any 5xx. A\n * 404 or 410 is not one: a page that is missing is missing for a paid\n * reader too;\n * - WebFetch answering 2xx, or no code, with under {@link NEAR_EMPTY_BYTES};\n * - WebFetch answering 2xx, or no code, whose summary says the page had no\n * main content (`reason: 'no_main_content'`, {@link readsAsEmptyPage}): a\n * JavaScript app's title, a video page's footer. Both are 200s with tens of\n * kilobytes, so the size never caught them;\n * - WebSearch answering with no result links at all.\n *\n * A search that returned unrelated links is NOT one: it looks exactly like a\n * good search from here, and guessing would put the router on every call.\n * Nor is a PDF WebFetch saved whole: its summary fails, but `Read` opens the\n * file for free ({@link savedPdfOf}).\n */\nexport function shortfallOf(event: {\n hook_event_name: 'PostToolUse' | 'PostToolUseFailure';\n session_id: string;\n tool_name: 'WebSearch' | 'WebFetch';\n tool_response?: unknown;\n error?: unknown;\n is_interrupt?: boolean;\n}): NativeOutcome | null {\n if (event.hook_event_name === 'PostToolUseFailure') {\n if (event.is_interrupt === true) return null;\n // Neither masked nor cut here: seal() does both, in that order.\n const error = typeof event.error === 'string' ? event.error.trim() : '';\n return error.length > 0 ? { error } : null;\n }\n const response = event.tool_response;\n if (response === null || typeof response !== 'object' || Array.isArray(response)) return null;\n const fields = response as Record<string, unknown>;\n if (event.tool_name === 'WebFetch') {\n const code = wholeNumber(fields.code, 999);\n const bytes = wholeNumber(fields.bytes, Number.MAX_SAFE_INTEGER);\n const outcome = {\n ...(code !== undefined ? { code } : {}),\n ...(bytes !== undefined ? { bytes } : {}),\n };\n if (code !== undefined && isShortStatus(code)) return outcome;\n const success = code === undefined || (code >= 200 && code < 300);\n if (!success) return null;\n if (bytes !== undefined && bytes < NEAR_EMPTY_BYTES) return outcome;\n const result = typeof fields.result === 'string' ? fields.result : '';\n // A PDF it saved is read for free (`runShortfallHook`), never paid for.\n if (savedPdfOf(result, event.session_id) !== null) return null;\n return readsAsEmptyPage(result) ? { ...outcome, reason: 'no_main_content' } : null;\n }\n const results = fields.results;\n if (!Array.isArray(results)) return null;\n const linked = results.some(\n (entry) =>\n entry !== null &&\n typeof entry === 'object' &&\n Array.isArray((entry as { content?: unknown }).content) &&\n (entry as { content: unknown[] }).content.length > 0,\n );\n return linked ? null : { error: 'Web search returned no results' };\n}\n\n/** The statuses a paid reader can get past: auth walls, paywalls, bot blocks,\n * rate limits and upstream failures. Every other 4xx is the page's answer. */\nconst SHORT_STATUSES = new Set([401, 402, 403, 429]);\n\nfunction isShortStatus(code: number): boolean {\n return SHORT_STATUSES.has(code) || (code >= 500 && code <= 599);\n}\n\nfunction wholeNumber(value: unknown, max: number): number | undefined {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= max\n ? value\n : undefined;\n}\n\nfunction delegationOffer(hint: string): string {\n return `${HINT_SOURCE}, optional if your own tools fall short: ${toolNamed(hint)} Your own tools are fine when they are enough.`;\n}\n\nexport interface HookDeps {\n dataDir: string;\n /** The host whose event this is, Claude Code when absent. */\n harness?: Harness;\n /** Overrides the resolved base URL entirely; tests point it at a local stub. */\n baseUrl?: string;\n /** The environment the base URL precedence reads `TENJIN_BASE_URL` from. */\n env?: NodeJS.ProcessEnv;\n /** Requests for routing decisions and free documentation. */\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n now?: () => number;\n /** Where `~/.claude` is, for the user's agent definitions; tests point it\n * at a scratch directory. */\n homeDir?: string;\n /**\n * Where a silent failure says why. The harness keeps hook stderr in its log,\n * so one line there is the difference between \"the feature is off\" and \"the\n * router answered 401 at this URL\". Never stdout: that is the harness's\n * protocol channel.\n */\n warn?: (line: string) => void;\n /** The payer's route, passed by `tenjin mcp`. Absent, a call goes unpaid,\n * and a router that asks for the fee skips it. */\n route?: RouteFor;\n /** A line for the user beside this leg's answer (`runHookKind` puts it in\n * the hook's `systemMessage`). */\n notice?: (line: string) => void;\n /**\n * Inside `tenjin mcp`: the payer's in-memory sign verdict (what its last\n * unlock said, no I/O). Absent (a caller with no payer, which cannot\n * unlock), it is decided from the wallet's files alone ({@link spendShortfall}).\n */\n signer?: () => SignVerdict;\n /**\n * Inside `tenjin mcp`, called only for an event with a valid session_id:\n * marks the session served (B2) and returns this leg's one-time wallet\n * lines. `ack()` runs once the response carrying them is built; only then\n * are they marked delivered (and awaiting_confirmation cleared).\n */\n walletNews?: (sessionId: string) => Promise<WalletNews>;\n}\n\n/**\n * One leg's one-time wallet lines, CLAIMED for that leg: a leg running at the\n * same time is not handed them. `ack()` marks them delivered once the response\n * carrying them is built; `release()` hands them back for the next leg when\n * the leg failed before answering.\n */\nexport interface WalletNews {\n lines: string[];\n /**\n * The reason a still-locked line in `lines` names, if any. The leg marks it\n * told for the session, so the fee notice for the same reason stays quiet\n * (once per session and reason).\n */\n told?: string;\n ack: () => Promise<void>;\n release: () => void;\n}\n\n/**\n * The CLI's ONE precedence, not a second copy of it: flag, then\n * `TENJIN_BASE_URL`, then the config file, then the production default. The\n * hook read the file alone, so a session pointed somewhere by the environment\n * had its prompts routed against whatever the file said instead; on a machine\n * whose file named a protected deployment that was a 401, and a 401 is silence.\n */\nfunction resolveBaseUrl(deps: HookDeps, config: PartialConfig): string {\n if (deps.baseUrl !== undefined) return deps.baseUrl;\n return resolveSettings({ config, flags: {}, env: deps.env ?? process.env }).baseUrl.value;\n}\n\n/** The decision's deadline, bounded by the hook timeout. */\nfunction gateDeadline(deps: HookDeps): number {\n return (\n (deps.now?.() ?? Date.now()) +\n (deps.timeoutMs ?? (deps.route ? GATE_TIMEOUT_MS : UNPAID_GATE_TIMEOUT_MS))\n );\n}\n\n/**\n * WHY THE PAID CALL WOULD NOT RUN ON ITS OWN, in the footer's words, or null\n * when it would. Every line that points at `request` where nobody can approve\n * asks this first: a subagent cannot reach the user, and the main agent's\n * pre-call deny and prompt hint send it to a call that has to run rather than\n * to the free tools that would have answered. Two things stop that call:\n *\n * - THE SPEND POLICY, asked the way `request` will ask it: the same settings,\n * the same session ledger and the same evaluation, with the provider's host\n * as the creator the way `pay` names it. Only `allow` runs alone. Nothing is\n * reserved, and the amount actually signed is still `gateSpend`'s to cap.\n * - A WALLET THAT CANNOT SIGN. Inside `tenjin mcp` that is the payer's own\n * verdict ({@link HookDeps.signer}); with no payer, which cannot unlock,\n * it is `canSign` over the wallet's files alone (`readWalletFacts`):\n * no wallet and no key, a malformed TENJIN_WALLET_KEY, a wallet.json nobody\n * can read, or the saved passphrase file gone while TENJIN_WALLET_PASSPHRASE\n * is unset. Approval cannot unlock a wallet mid-session, so this one\n * withholds discovered offers too ({@link vetOffer}, Q3), and it wins over\n * the policy's `needs_approval` for any price above zero. Its note rides\n * in `additionalContext`, so it carries the model's `agentFix` (B1).\n *\n * Unknown signers still offer. Neither offers nor signing depend on a balance\n * RPC: the facilitator checks funds when it verifies a payment.\n *\n * Exported for its tests: a sign-blocked note is never shown in an offer\n * ({@link vetOffer} withholds it), so they read it here.\n */\nexport async function spendShortfall(\n decision: { providerPriceAtomic: string; endpoint: string },\n deps: HookDeps,\n _deadline: number,\n): Promise<Shortfall | null> {\n const price = `$${toMoney(decision.providerPriceAtomic).usd}`;\n const approval = (detail: string): Shortfall => ({\n withheld: 'offer needs approval',\n note: `Note: ${price} ${detail}; request will pay nothing and return needs_approval with what it costs.`,\n });\n let policy: Shortfall | null;\n try {\n const settings = await resolveContextSettings(hookContext(deps));\n const ledger = await readSpendSummary(deps.dataDir, {\n ...(deps.now !== undefined ? { now: deps.now } : {}),\n });\n const evaluation = evaluateSpendPolicy(settings.policy, {\n amountAtomic: BigInt(decision.providerPriceAtomic),\n creator: new URL(decision.endpoint).host,\n sessionSpentAtomic: ledger === null ? 0n : spentOf(ledger),\n });\n policy =\n evaluation.decision !== 'allow'\n ? approval(\n evaluation.reason === 'above_auto_spend'\n ? `is above this machine's automatic per-call limit ($${toMoney(settings.policy.maxAutoSpendAtomic.toString()).usd})`\n : \"needs approval under this machine's spend limits\",\n )\n : null;\n } catch {\n policy = approval(\"needs approval under this machine's spend limits\");\n }\n // A free call pays nothing, so it needs nothing from the wallet: one that\n // cannot sign, or no wallet at all (`--no-wallet`), never withholds it.\n if (BigInt(decision.providerPriceAtomic) === 0n) return policy;\n const facts = await readWalletFacts(deps.dataDir, deps.env ?? process.env);\n const sign = deps.signer?.() ?? canSign(facts);\n // A wallet that definitely cannot sign is said before the policy's\n // `needs_approval` (Q3): approving an over-cap call cannot unlock it\n // mid-session, so even a discovered offer is withheld.\n if (sign.status === 'blocked') return cannotSign(sign);\n return policy;\n}\n\n/** The Shortfall of a wallet that definitely cannot sign; {@link vetOffer} always withholds it. */\nfunction cannotSign(v: { reason: string; detail: string; fix: string }): Shortfall {\n return {\n withheld: 'wallet cannot sign',\n note: `Note: Tenjin's wallet cannot pay for this (${v.detail}); ${agentFixFor(v.reason, v.fix)}`,\n signBlocked: true,\n };\n}\n\n/** Why a paid call would not run on its own: the footer's words, and the\n * sentence a discovered offer carries instead of being withheld.\n * `signBlocked` marks a wallet that definitely cannot sign, which no\n * approval fixes mid-session. */\nexport interface Shortfall {\n withheld: string;\n note: string;\n signBlocked?: true;\n}\n\n/**\n * AN OFFER, OR WHY IT IS NOT SHOWN. A curated offer the paid call could not\n * make good on alone is withheld, as it always was. A DISCOVERED one is not\n * withheld where someone can ask the user: it is the only line naming a\n * service that can do the step, so it is shown with one sentence saying the\n * call needs approval or funds; its `needs_approval` result names the\n * `approve` call, which is the asking, so the host never asks first. Where\n * nobody can ask (a subagent's call, a delegated task) it is withheld like\n * any other. A wallet that definitely cannot sign withholds every offer,\n * discovered ones included (Q3): asking the user cannot unlock it mid-session.\n *\n * An offer that is shown can still list OTHER services beside its own: a Tenjin\n * list menu, or an alternative after a curated line. One priced over the cap\n * gets a sentence saying so ({@link overCapNote}), so the host picks one that\n * runs rather than one that stops on `needs_approval`.\n */\nasync function vetOffer<T extends OfferDecision>(\n offer: T,\n deps: HookDeps,\n deadline: number,\n canAskUser: boolean,\n): Promise<{ offer: T; withheld?: undefined } | { withheld: string }> {\n // THE USER'S OWN PLAN PAYS an account's call: nothing for the spend policy\n // or the wallet to check, and it is offered alone. One whose call this\n // account was found to lack when it was connected is left out, rather than\n // leading its task and failing when called: the hook stays silent.\n const lead = accountLeadOf(offer);\n if (lead !== undefined) {\n if (await accountLacks(deps.dataDir, lead)) return { withheld: 'account lacks this job' };\n return { offer };\n }\n const terms = termsOf(offer);\n if (terms.endpoint === undefined) return { withheld: 'no endpoint to pay' };\n const shortfall = await spendShortfall({ ...terms, endpoint: terms.endpoint }, deps, deadline);\n if (shortfall === null) {\n const note = await overCapNote(offer, deps, canAskUser);\n return { offer: note === null ? offer : { ...offer, hint: `${offer.hint} ${note}` } };\n }\n if (offer.action === 'discovered' && canAskUser && shortfall.signBlocked !== true) {\n return { offer: { ...offer, hint: `${offer.hint} ${shortfall.note}` } };\n }\n return { withheld: shortfall.withheld };\n}\n\n/**\n * The other services an offer names, by price in atomic USDC: every spec\n * beside the offer's own (its line and its specs name the same ids). A price\n * is a field, never the line's prose: an offer with no specs names none.\n */\nfunction listedPrices(offer: OfferDecision): bigint[] {\n return (offer.specs ?? [])\n .filter((spec) => spec.id !== offer.id)\n .flatMap((spec) => (isAccountSpec(spec) ? [] : [BigInt(spec.priceAtomic)]));\n}\n\n/** A listed price as a line quotes one: dollars with at least two decimals. */\nfunction listedUsd(atomic: bigint): string {\n const [whole, fraction = ''] = toMoney(atomic.toString()).usd.split('.');\n return `${whole}.${fraction.padEnd(2, '0')}`;\n}\n\n/**\n * ONE SENTENCE FOR A LISTED SERVICE OVER THE AUTO-SPEND CAP, or null. The offer\n * itself already fits (it passed {@link spendShortfall}), so a price over the\n * cap here is another entry: People Data Labs at $0.28 beside a $0.005 email\n * finder, under a $0.25 cap, was picked and refused. Quiet when the offer\n * names no such price or the settings cannot be read.\n */\nasync function overCapNote(\n offer: OfferDecision,\n deps: HookDeps,\n canAskUser: boolean,\n): Promise<string | null> {\n const listed = listedPrices(offer);\n if (listed.length === 0) return null;\n let cap: bigint;\n try {\n cap = (await resolveContextSettings(hookContext(deps))).policy.maxAutoSpendAtomic;\n } catch {\n return null;\n }\n const over = [...new Set(listed.filter((atomic) => atomic > cap).map(listedUsd))];\n if (over.length === 0) return null;\n const prices = over.map((usd) => `$${usd}`).join(' and ');\n const which = over.length > 1 ? 'those services' : 'that service';\n return (\n `Note: ${prices} ${over.length > 1 ? 'are' : 'is'} above this machine's automatic per-call limit ` +\n `($${toMoney(cap.toString()).usd}), so request returns needs_approval for ${which}; ` +\n (canAskUser ? 'prefer one within the limit.' : 'use one within the limit.')\n );\n}\n\nfunction agentLookup(cwd: string | undefined, deps: HookDeps): AgentLookup {\n return { ...(cwd !== undefined ? { cwd } : {}), homeDir: deps.homeDir ?? homedir() };\n}\n\n/** The context the hook's own library calls run in: JSON, silent, no TTY. */\nfunction hookContext(deps: HookDeps): CommandContext {\n return {\n flags: { json: true, timeout: deps.timeoutMs ?? GATE_TIMEOUT_MS },\n dataDir: deps.dataDir,\n io: { stdout: nullStream(), stderr: nullStream(), isTTY: false },\n };\n}\n\nexport interface PromptHookOutcome {\n /** What the harness is told, or null for \"nothing to say\". */\n response: unknown | null;\n skipped?: PromptSkip;\n action?: HookDecision['action'];\n /** The turn id, for the smoke to correlate against. */\n id?: string;\n /** An `execute` whose hint was not shown: the paid call would not run on its\n * own, for want of approval or of funds. */\n withheld?: true;\n}\n\n/**\n * The prompt leg (UserPromptSubmit), run by `tenjin mcp`'s `hook` tool. One\n * routing decision from the user's\n * own words. Only an offer (`execute`, or a `discovered` service) gets a line:\n * the server's hint, attributed. `native`, `needs_input` and a decision that\n * failed or timed out are silence:\n * a turn with no lookup carries nothing extra, and `decide` has already written\n * any failure cause to stderr.\n *\n * THE HINT ASKS FOR A CALL THAT HAS TO RUN. Over the cap or past the budget,\n * `request` answers `needs_approval`, and a model sent there stops to ask the\n * user where its free tools would have done: so a curated line is shown only\n * when the paid call would auto-execute, the same rule the pre-call deny\n * follows. A discovered line is shown anyway, with a sentence saying it needs\n * approval or funds ({@link vetOffer}): it may be the only service for the step.\n */\nexport async function runPromptHook(raw: unknown, deps: HookDeps): Promise<PromptHookOutcome> {\n const event = eventOf(raw, deps);\n if (event?.kind !== 'prompt') return { response: null };\n return offerOnUserText(event, event.prompt, 'UserPromptSubmit', deps);\n}\n\n/**\n * The answer leg (PostToolUse on `AskUserQuestion`), run by `tenjin mcp`'s\n * `hook` tool. THE USER JUST ANSWERED, which is a user turn in all but name: an\n * answer like \"I can get an API key\" is exactly when a pay-per-call service\n * would do instead. So it is routed the way a prompt is, with the answers as\n * the current message and the session's history before them, and an offer is\n * added beside the answers the host reads next. Anything else is no output at\n * all.\n */\nexport async function runAnswerHook(raw: unknown, deps: HookDeps): Promise<PromptHookOutcome> {\n const event = eventOf(raw, deps);\n if (event?.kind !== 'answer' || event.answers === null) return { response: null };\n return offerOnUserText(event, event.answers, 'PostToolUse', deps);\n}\n\n/** The prompt route, for any text that is the user's own words this turn. */\nasync function offerOnUserText(\n event: { sessionId: string; transcriptPath?: string; cwd?: string },\n text: string,\n hookEventName: 'UserPromptSubmit' | 'PostToolUse',\n deps: HookDeps,\n): Promise<PromptHookOutcome> {\n const skipped = promptSkipReason(text);\n if (skipped !== null) return { response: null, skipped };\n const router = await routerFor(event.cwd, deps);\n if (router === null) return { response: null };\n await sweepUntaken(deps, router);\n\n const sealed = await sealHere(\n await buildPromptPacket(event.transcriptPath, event.sessionId, text, hostOf(deps)),\n router,\n event.cwd,\n deps,\n );\n const footer = await openFooter(deps, event.sessionId, 'prompt', {});\n const deadline = gateDeadline(deps);\n const outcome = await decide(sealed, deps, router, event.sessionId, deadline, footer);\n if (!isOffer(outcome)) {\n await footer.close(outcome);\n return {\n ...injection(hookEventName),\n ...(outcome !== null ? { action: outcome.action } : {}),\n };\n }\n const vetted = await vetOffer(outcome, deps, deadline, true);\n if (vetted.withheld !== undefined) {\n await footer.close(outcome, { withheld: vetted.withheld });\n return { ...injection(hookEventName), action: outcome.action, withheld: true };\n }\n await footer.close(outcome);\n if (hookEventName === 'UserPromptSubmit') {\n // The mod draws `Tenjin offered <label>` under this prompt from this record.\n await markOffered(\n deps.dataDir,\n localSession(event.sessionId, deps),\n promptOfferKey(text),\n offeredTerms(vetted.offer),\n deps.now?.(),\n );\n }\n return {\n action: outcome.action,\n id: outcome.id,\n ...injection(hookEventName, attributed(vetted.offer.hint, hostOf(deps))),\n };\n}\n\n/** The lines this leg adds to the agent's context, or no answer when there are none. */\nfunction injection(\n hookEventName: 'UserPromptSubmit' | 'PostToolUse',\n ...lines: (string | undefined)[]\n): { response: unknown } {\n const said = lines.filter((line) => line !== undefined);\n if (said.length === 0) return { response: null };\n return {\n response: { hookSpecificOutput: { hookEventName, additionalContext: said.join('\\n\\n') } },\n };\n}\n\n/** What either native arm reports about itself; `response` is all the harness sees. */\nexport interface NativeHookOutcome {\n response: unknown | null;\n action?: HookDecision['action'];\n id?: string;\n /** An `execute` whose offer was not shown: the paid call would not run on\n * its own, for want of approval or of funds. */\n withheld?: true;\n /** No router call at all: the subagent is not known to have the request tool. */\n noRequestTool?: true;\n /** No redirect: this agent was already redirected on this same search or\n * URL. Found before the router was asked there is no `action`; only a\n * parallel copy that lost the claim after its decision carries one. */\n alreadyRedirected?: true;\n /** A free offer, which the pre-call arm never redirects: the call runs. */\n free?: true;\n /** And its line is kept, for the after-call arm to show once the search ran. */\n noted?: true;\n}\n\nexport interface ShortfallHookOutcome extends NativeHookOutcome {\n /** What the harness reported, when it was a shortfall; absent means the\n * router was never asked. */\n nativeOutcome?: NativeOutcome;\n /** The pre-call arm already redirected this very call, so nothing more is said. */\n alreadyOffered?: true;\n /** The pre-call arm noted a free lookup on this call, and its line was\n * shown. Never a shortfall offer as well. */\n noted?: true;\n /** WebFetch saved a PDF whole, and the agent was pointed at it, free. */\n savedPdf?: true;\n}\n\ntype ExecuteDecision = Extract<HookDecision, { action: 'execute' }>;\n\n/**\n * AN ANSWER THAT OFFERS SOMETHING: a curated capability (`execute`), a\n * service on the user's own account (an `execute` led by one), or a\n * pay-per-call service the server found for a step nothing curated serves\n * (`discovered`). Each carries an id and a finished line, and every hook\n * shows them in the same place, under the same rules; only one the balance\n * pays meets the spend check.\n */\ntype OfferDecision = Extract<HookDecision, { action: 'execute' | 'discovered' }>;\n\nfunction isOffer(decision: HookDecision | null): decision is OfferDecision {\n return decision?.action === 'execute' || decision?.action === 'discovered';\n}\n\n/**\n * AN OFFER LED BY A SERVICE ON THE USER'S CONNECTED ACCOUNT (plan 37): no\n * URL, nothing the balance pays, and Tenjin's own route for the job beside\n * it, which a refusal offers. The server sends one only for an account this\n * machine's settings name, alone, with `bound` when it can run in place of the\n * native call it holds. Its lead's own spec, or undefined: an\n * answer that parsed carries an account spec only as its lead\n * (`checkExecute`), so this is the whole test.\n */\nfunction accountLeadOf(decision: HookDecision | null): AccountOfferSpec | undefined {\n if (decision?.action !== 'execute') return undefined;\n const lead = (decision.specs ?? []).find(({ id }) => id === decision.id);\n return lead !== undefined && isAccountSpec(lead) ? lead : undefined;\n}\n\n/** {@link accountLeadOf}, as a test that narrows the decision. */\nconst isAccountOffer = (decision: HookDecision | null): decision is ExecuteDecision =>\n accountLeadOf(decision) !== undefined;\n\n/** What the spend check and the footer read, for any kind of offer. An\n * account's has no URL, and costs the balance nothing. */\nfunction termsOf(offer: OfferDecision): {\n provider: string;\n providerPriceAtomic: string;\n endpoint?: string;\n} {\n if (offer.action === 'execute') return offer;\n const { candidate } = offer;\n return {\n provider: candidate.provider,\n providerPriceAtomic: candidate.providerPriceAtomic,\n endpoint: candidate.url,\n };\n}\n\n/** A free curated offer: nothing to pay, so nothing for the spend policy or\n * the wallet. A discovered service is never one: it is always a sale. */\nfunction isFree(offer: OfferDecision): offer is ExecuteDecision {\n return offer.action === 'execute' && offer.providerPriceAtomic === '0' && !isAccountOffer(offer);\n}\n\n/**\n * THE ONE ROUTE BOTH NATIVE ARMS TAKE, before the call and after it: the\n * agent's tool list, the packet from the right transcript, one routing decision,\n * and the subagent spend rule. An `execute` that survives all of it comes back\n * as `offer`; everything else is the reason there is none. `repeated` is the\n * pre-call arm's one-block rule, asked only of an offer that would be shown;\n * `redirected` is its read half, asked before the router is, so a retry the\n * arm would only withhold costs no decision and writes no offer row.\n * `passFree` is the pre-call arm's too: a free offer comes back marked `free`\n * before the spend policy, the wallet or `repeated` is asked, since it is\n * never a redirect, and the arm closes its footer: noted when it kept the\n * offer's line for the after-call arm, withheld when it did not.\n */\nasync function routeNativeCall(\n event: Omit<NativeCall, 'tool' | 'pending'>,\n pending: PendingCall,\n deps: HookDeps,\n opts: {\n nativeOutcome?: NativeOutcome;\n repeated?: () => Promise<boolean>;\n redirected?: () => Promise<boolean>;\n passFree?: boolean;\n operation?: 'prompt' | 'search';\n /** False where a discovered offer must be affordable as it stands: the\n * call it would replace is the one way to reach the user. */\n canAskUser?: boolean;\n /** The pre-call arm's: this is a native call, so an offer this agent was\n * shown and has not taken was ignored for it. */\n native?: boolean;\n /** The answer the swap already got for this very call ({@link\n * decideSwap}): used as the router's answer, so one search is never\n * decided, or charged a routing fee, twice. */\n recorded?: Decided;\n } = {},\n): Promise<\n | { offer: OfferDecision; free?: undefined }\n | { offer: ExecuteDecision; free: true; close: (noted: boolean) => Promise<void> }\n | { offer: null; outcome: NativeHookOutcome }\n> {\n const { nativeOutcome, repeated } = opts;\n // OFF MEANS NOTHING ABOUT THE TURN IS READ: the switch comes before the\n // agent lookup and the transcript, for both native arms.\n const router = await routerFor(event.cwd, deps);\n if (router === null) return { offer: null, outcome: { response: null } };\n await sweepUntaken(\n deps,\n router,\n opts.native === true\n ? offerScope(localSession(event.sessionId, deps), event.agentId)\n : undefined,\n );\n // A SUBAGENT IS ROUTED ONLY WHEN IT IS KNOWN TO HAVE THE TOOL: redirecting\n // or offering to one that cannot make the call strands it (#377). Decided\n // before the router is asked, so an unknown one costs nothing.\n if (\n event.agentId !== undefined &&\n (await requestToolAccess(event.agentType, agentLookup(event.cwd, deps))) !== 'allowed'\n ) {\n return { offer: null, outcome: { response: null, noRequestTool: true } };\n }\n // ALREADY REDIRECTED HERE: the retry the one-block rule lets run. Asking the\n // router first cost a gate decision and wrote an offer row nobody saw, about\n // 45% of an active session's rows. The claim after the decision still\n // settles two parallel copies of one call.\n if (opts.redirected !== undefined && (await opts.redirected())) {\n const footer = await openFooter(deps, event.sessionId, opts.operation ?? 'search', event);\n await footer.close(null, { withheld: 'already redirected once' });\n return { offer: null, outcome: { response: null, alreadyRedirected: true } };\n }\n const { recorded } = opts;\n const sealed =\n recorded === undefined\n ? await sealNative(event, pending, router, deps, nativeOutcome)\n : undefined;\n if (sealed === null) return { offer: null, outcome: { response: null } };\n const footer = await openFooter(deps, event.sessionId, opts.operation ?? 'search', event);\n const deadline = gateDeadline(deps);\n const outcome =\n sealed !== undefined\n ? await decide(sealed, deps, router, event.sessionId, deadline, footer)\n : fromRecorded(recorded!, router, footer, deps);\n if (!isOffer(outcome)) {\n await footer.close(outcome);\n return {\n offer: null,\n outcome: { response: null, ...(outcome !== null ? { action: outcome.action } : {}) },\n };\n }\n if (opts.passFree === true && isFree(outcome)) {\n const close = (noted: boolean) =>\n footer.close(outcome, noted ? { noted: true } : { withheld: 'free lookup, call runs' });\n return { offer: outcome, free: true, close };\n }\n const vetted = await vetOffer(\n outcome,\n deps,\n deadline,\n event.agentId === undefined && opts.canAskUser !== false,\n );\n if (vetted.withheld !== undefined) {\n await footer.close(outcome, { withheld: vetted.withheld });\n return { offer: null, outcome: { response: null, action: outcome.action, withheld: true } };\n }\n if (repeated !== undefined && (await repeated())) {\n await footer.close(outcome, { withheld: 'already redirected once' });\n return {\n offer: null,\n outcome: { response: null, action: outcome.action, alreadyRedirected: true },\n };\n }\n await footer.close(outcome);\n return { offer: vetted.offer };\n}\n\n/**\n * THE PACKET FOR A NATIVE CALL, sealed, or null when nothing may be asked\n * about it. Shared by both native arms and the swap ({@link decideSwap}).\n */\nasync function sealNative(\n event: Omit<NativeCall, 'tool' | 'pending'>,\n pending: PendingCall,\n router: RouterHere,\n deps: HookDeps,\n nativeOutcome?: NativeOutcome,\n): Promise<Sealed | null> {\n const warn = deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`));\n // THE USER'S WORDS COME WITH IT. Building this from the tool argument alone\n // made the search string the whole conversation, so \"native tools only, no\n // paid services\" never reached this gate. Inside a subagent, its own task\n // comes first: see `buildNativePacket`.\n const sealed = await sealHere(\n await buildNativePacket(event.transcriptPath, event.sessionId, pending, {\n ...(event.agentId !== undefined ? { agentId: event.agentId } : {}),\n ...(nativeOutcome !== undefined ? { nativeOutcome } : {}),\n harness: hostOf(deps),\n }),\n router,\n event.cwd,\n deps,\n );\n // A LOCAL TARGET ONLY EVER HAS A NATIVE ANSWER, so asking costs a round trip\n // and sends the conversation for nothing.\n if (sealed.localTarget) return null;\n // A CREDENTIAL IN THE SEARCH OR URL NEVER LEAVES. Sending it masked would put\n // the mask into the hint the server writes from it, and the model would call\n // the provider with the mask. The call stays native.\n if (sealed.subjectChanged) {\n warn('tenjin hook: the native call carries a credential-shaped value, so it is not routed');\n return null;\n }\n // AND WHEN THEY CANNOT BE READ, NOTHING IS OFFERED. An offer routed on the\n // tool argument alone is how an instruction the user gave this turn gets\n // overruled by a decision that never saw it.\n if (sealed.packet.historyStatus !== 'ok') {\n warn(\"tenjin hook: this session's transcript could not be read, so no paid lookup is offered\");\n return null;\n }\n return sealed;\n}\n\n/** The swap's kept answer, as this leg's own: its unpaid fee said again, and\n * held to the rules saved now like a fresh one. */\nfunction fromRecorded(\n recorded: Decided,\n router: RouterHere,\n footer: {\n unpaid: (why: string) => void;\n answered: (answer: Pick<HookResponse, 'settingsHash'>) => void;\n },\n deps: HookDeps,\n): HookDecision | null {\n if (recorded.unpaid !== undefined) footer.unpaid(recorded.unpaid);\n const { answer } = recorded;\n if (answer === null) return null;\n const warn = deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`));\n if (!decidedUnder(answer, router, warn)) return null;\n footer.answered(answer);\n return answer.decision;\n}\n\n/** What the swap's decision came to: the call to run in the native call's\n * place, or why the call goes back to the host's own flow. */\nexport type SwapDecision =\n | { handback: string }\n | {\n offer: OfferDecision;\n /** The offer id and complete input the router built, run unchanged. */\n bound: Bound;\n /** The spec `bound` fills, as the hook keeps it: a paid one, or a\n * service on the user's connected account. */\n spec: AnyOfferSpec;\n tool: 'WebSearch' | 'WebFetch';\n /**\n * Claims every search or URL of the call for the main agent, as a\n * redirect does, and marks the call answered in place. False when a\n * claim is already held: the call then goes back and runs natively.\n */\n claim: () => Promise<boolean>;\n /** After a claim, the call goes back after all: its mark no longer says\n * it was answered in place, so the mod draws the native call. */\n unmark: () => Promise<void>;\n };\n\n/**\n * THE SWAP'S DECISION, for a host that can answer a WebSearch or WebFetch in\n * place (`router.nativeReplacement: when-routed`, the Claude Code mod). The\n * same route the pre-call hook takes: the switch, the transcript, the hook\n * body (so the gate's confidence floor applies), the user's settings and the\n * spend check. On top of it, only an answer that carries `bound` (the offer\n * id and the complete input the router built from this call's own search or\n * URL, sent only while automatic use is on and the pick fits its provider\n * scope) can run in place. The input is never built, parsed or edited here.\n *\n * Anything else HANDS THE CALL BACK, and the answer is kept for it\n * ({@link keepDecided}): the pre-call hook then offers from it, as it would\n * have, without asking again. An over-limit price hands back too, so its\n * offer takes the ordinary approval path. The main agent only: a subagent's\n * call takes the ordinary route.\n */\nexport async function decideSwap(raw: unknown, deps: HookDeps): Promise<SwapDecision> {\n if (hostOf(deps) !== 'claude') return { handback: 'this host cannot run a pick in place' };\n const event = decodeEvent(raw);\n if (event?.kind !== 'native' || event.pending === null || event.toolUseId === undefined) {\n return { handback: 'not a search or fetch Tenjin routes' };\n }\n const { pending, toolUseId } = event;\n if (pending.tool !== 'WebSearch' && pending.tool !== 'WebFetch') {\n return { handback: 'not a search or fetch Tenjin routes' };\n }\n if (event.agentId !== undefined) return { handback: 'a subagent call' };\n // THE SWITCH, READ NOW from the global file alone: a project file cannot\n // turn it on, and turning it off applies to the very next call.\n const router = await routerFor(event.cwd, deps);\n if (router === null) return { handback: 'Tenjin is off here' };\n if (router.settings.nativeReplacement.mode !== 'when-routed')\n return { handback: 'automatic use is off' };\n const tool = pending.tool;\n const session = localSession(event.sessionId, deps);\n const target = redirectTarget(pending);\n const targets = [...new Set((event.targets ?? [pending]).map(redirectTarget))];\n // A RETRY OF A CALL ALREADY ROUTED runs natively, as after a redirect.\n for (const t of targets) {\n if (await redirectClaimed(deps.dataDir, session, undefined, t, deps.now?.())) {\n return { handback: 'already routed once' };\n }\n }\n const sealed = await sealNative(event, pending, router, deps);\n if (sealed === null) return { handback: 'not routed' };\n const footer = await openFooter(deps, event.sessionId, 'search', event);\n const deadline = gateDeadline(deps);\n let kept: Decided = { answer: null };\n const outcome = await decide(sealed, deps, router, event.sessionId, deadline, {\n unpaid: (why) => {\n kept = { ...kept, unpaid: why };\n footer.unpaid(why);\n },\n answered: (answer) => {\n kept = { ...kept, answer };\n footer.answered(answer);\n },\n });\n await keepDecided(deps.dataDir, session, toolUseId, target, kept, deps.now?.());\n const back = async (why: string): Promise<SwapDecision> => {\n await footer.close(outcome, isOffer(outcome) ? { withheld: why } : undefined);\n return { handback: why };\n };\n if (!isOffer(outcome)) return back('no paid lookup fits');\n const { bound } = outcome;\n const spec = bound === undefined ? undefined : outcome.specs?.find(({ id }) => id === bound.id);\n // NOTHING TO RUN AS IT STANDS: no `bound` (automatic use off at the router,\n // a pick outside its provider scope, an input it could not fill), no spec\n // for it to fill, a free docs lookup, or a choice for the user to make.\n if (\n bound === undefined ||\n spec === undefined ||\n isFree(outcome) ||\n (outcome.action === 'discovered' && outcome.choices !== undefined)\n ) {\n return back('no input to run in place');\n }\n // ONLY A CALL THAT WOULD RUN ON ITS OWN: over a limit, or a wallet that\n // cannot pay, goes back to the offer, whose request asks for approval.\n const vetted = await vetOffer(outcome, deps, deadline, false);\n if (vetted.withheld !== undefined) return back(vetted.withheld);\n // Kept like a shown offer's: the spec `request({id, input})` runs, with the\n // settings hash its answer echoed.\n await footer.close(outcome);\n const now = () => deps.now?.() ?? Date.now();\n const terms = { ...offeredTerms(outcome), swap: true as const };\n return {\n offer: outcome,\n bound,\n spec,\n tool,\n claim: async () => {\n if (!(await claimRedirect(deps.dataDir, session, undefined, target, now()))) return false;\n await Promise.all(\n targets\n .filter((t) => t !== target)\n .map((t) => claimRedirect(deps.dataDir, session, undefined, t, now())),\n );\n await markOffered(deps.dataDir, session, toolUseId, terms, now());\n return true;\n },\n unmark: () => markHandedBack(deps.dataDir, session, toolUseId, now()),\n };\n}\n\n/**\n * The native leg (PreToolUse on `WebSearch|WebFetch`), run by `tenjin mcp`'s\n * `hook` tool. PER-LOOKUP ROUTING BEFORE THE CALL, exactly as main: a clear\n * offer denies the native call with the server's hint as the reason, carrying\n * the id so the redirected call runs the decision just made. Anything else,\n * including silence, a slow backend and a `needs_input`, lets the call run with\n * no output at all.\n *\n * WHAT IS NEW is who can be denied. A subagent not known to have the request\n * tool, or whose spend would need an approval it cannot ask for, is never\n * redirected: `routeNativeCall` answers without an offer, and its\n * call runs free. Neither is the main agent when the paid call would stop on\n * `needs_approval` or its wallet cannot cover the price: its free call runs,\n * and the after-call arm can still offer.\n *\n * A redirect leaves a mark under the call's `tool_use_id`, so the after-call\n * arm never offers on that same call.\n *\n * NEVER REDIRECTED TWICE FOR ONE TARGET. A redirect claims its exact search or\n * URL for this agent first ({@link claimRedirect}). A call on a target this\n * agent was already redirected on runs without asking the router at all\n * ({@link redirectClaimed}), however its lookup went and whatever other calls\n * ran in between; a parallel copy that got past that check loses the claim\n * after its decision and runs too. Parallel calls each hold their own claim,\n * so none can spend another's. Any other target gets its own redirect.\n *\n * A FREE OFFER IS NEVER A REDIRECT. Denying a search for the free docs lookup\n * sent the agent on a detour, and round a loop when the docs missed. The call\n * runs with no output and no redirect claim. On a WebSearch with\n * `delivery: \"note\"` the server's line is kept, once per query per agent in\n * five minutes, and the after-call arm shows it once the search has run; its\n * footer closes as a shown offer, so the lookup the agent may call resolves to\n * this session, but its untaken record waits for the after-call arm to show\n * it. Any other free offer, and any WebFetch, just runs: the server owns which\n * offer is a note.\n */\nexport async function runNativeHook(raw: unknown, deps: HookDeps): Promise<NativeHookOutcome> {\n const event = eventOf(raw, deps);\n if (event?.kind !== 'native' || event.pending === null) return { response: null };\n const target = redirectTarget(event.pending);\n // A batch is blocked at most once: the redirect claims every search and URL\n // in it, and a call naming any claimed one runs.\n const targets = [...new Set((event.targets ?? [event.pending]).map(redirectTarget))];\n const session = localSession(event.sessionId, deps);\n const claim = (t: string) => claimRedirect(deps.dataDir, session, event.agentId, t, deps.now?.());\n // THE SWAP HANDED THIS CALL BACK: its answer stands, and is not asked for again.\n const recorded =\n event.toolUseId !== undefined && event.agentId === undefined\n ? await takeDecided(deps.dataDir, session, event.toolUseId, target, deps.now?.())\n : undefined;\n const routed = await routeNativeCall(event, event.pending, deps, {\n ...(recorded !== undefined ? { recorded } : {}),\n passFree: true,\n native: true,\n repeated: async () => {\n if (!(await claim(target))) return true;\n await Promise.all(targets.filter((t) => t !== target).map(claim));\n return false;\n },\n redirected: async () => {\n for (const t of targets) {\n if (await redirectClaimed(deps.dataDir, session, event.agentId, t, deps.now?.())) {\n return true;\n }\n }\n return false;\n },\n });\n if (routed.offer === null) return routed.outcome;\n if (routed.free === true) {\n const { pending, toolUseId } = event;\n const now = deps.now?.() ?? Date.now();\n const { id, hint } = routed.offer;\n // Only a search the harness gave an id can be matched to its after-call event.\n const noted =\n pending.tool === 'WebSearch' &&\n routed.offer.delivery === 'note' &&\n toolUseId !== undefined &&\n (await claimNote(deps.dataDir, session, event.agentId, pending.query, now)) &&\n (await markNoted(\n deps.dataDir,\n session,\n toolUseId,\n { offerId: id, line: hint, ids: offeredIds(routed.offer) },\n now,\n ));\n await routed.close(noted);\n return {\n response: null,\n action: 'execute',\n id: routed.offer.id,\n free: true,\n ...(noted ? { noted: true as const } : {}),\n };\n }\n if (event.toolUseId !== undefined) {\n await markOffered(\n deps.dataDir,\n session,\n event.toolUseId,\n offeredTerms(routed.offer),\n deps.now?.(),\n );\n }\n return redirect(\n routed.offer,\n hostOf(deps),\n event.rest === undefined ? ONE_BLOCK : `${ONE_BLOCK} ${restSentence(event.rest)}`,\n );\n}\n\n/**\n * The deny blocked the whole Codex call: the rest of it, exactly as written,\n * to run again natively.\n */\nfunction restSentence(rest: Record<string, unknown>): string {\n return `Nothing else in this web.run call ran either; to run the rest as written, call web.run again with exactly ${JSON.stringify(rest)}`;\n}\n\n/** What the offer record keeps of a redirect: the offer's id, its label, from\n * its decision or else its own spec, and its price. */\nfunction offeredTerms(offer: OfferDecision): OfferedTerms {\n const label =\n (offer.action === 'execute' ? offer.label : undefined) ??\n offer.specs?.find((spec) => spec.id === offer.id)?.label;\n return {\n offerId: offer.id,\n ...(label !== undefined ? { label } : {}),\n // An account's call costs the balance nothing: no price to show.\n ...(isAccountOffer(offer) ? {} : { priceAtomic: termsOf(offer).providerPriceAtomic }),\n };\n}\n\n/**\n * Deny the call once with the server's line: the redirect both pre-call arms\n * make, after `routeNativeCall` has claimed its target ({@link claimRedirect}).\n */\nfunction redirect(offer: OfferDecision, host: Harness, oneBlock = ONE_BLOCK): NativeHookOutcome {\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n permissionDecision: 'deny',\n // THE SERVER'S LINE, attributed and tool-named, then this client's one\n // sentence. The line already carries the id and the exact search, URL\n // or question that was denied.\n permissionDecisionReason: `${attributed(offer.hint, host)} ${oneBlock}`,\n },\n },\n action: offer.action,\n id: offer.id,\n };\n}\n\n/**\n * The ask leg (PreToolUse on `AskUserQuestion`), run by `tenjin mcp`'s `hook`\n * tool. THE HOST IS ABOUT TO ASK THE USER FOR SOMETHING, often an API key or an\n * account for a one-off step, which is the moment a pay-per-call service could\n * answer instead. The questions and their options ride as the pending call, and\n * an offer denies the question once with the server's line: never twice for the\n * same question, and a free offer never denies anything. The host can ask\n * again, and that question runs.\n *\n * AN OFFER THE CALL COULD NOT MAKE GOOD ON ALONE NEVER TAKES THE QUESTION'S\n * PLACE. Elsewhere a discovered offer over the cap is shown\n * with a note that the call needs approval or funds; here the question IS\n * the asking, so denying it for a call that cannot run alone strands the\n * turn. Any shortfall, curated or discovered, withholds the offer and the\n * question runs.\n */\nexport async function runAskHook(raw: unknown, deps: HookDeps): Promise<NativeHookOutcome> {\n const event = eventOf(raw, deps);\n if (event?.kind !== 'ask' || event.pending === null) return { response: null };\n // The question itself is the target, claimed exactly as a search or a URL is.\n const target = redirectTarget(event.pending);\n const routed = await routeNativeCall(event, event.pending, deps, {\n passFree: true,\n operation: 'prompt',\n canAskUser: false,\n repeated: async () =>\n !(await claimRedirect(deps.dataDir, event.sessionId, event.agentId, target, deps.now?.())),\n redirected: () =>\n redirectClaimed(deps.dataDir, event.sessionId, event.agentId, target, deps.now?.()),\n });\n if (routed.offer === null) return routed.outcome;\n if (routed.free === true) {\n await routed.close(false);\n return { response: null, action: routed.offer.action, id: routed.offer.id, free: true };\n }\n if (event.toolUseId !== undefined) {\n await markOffered(\n deps.dataDir,\n localSession(event.sessionId, deps),\n event.toolUseId,\n offeredTerms(routed.offer),\n deps.now?.(),\n );\n }\n return redirect(routed.offer, hostOf(deps), ONE_BLOCK_QUESTION);\n}\n\n/**\n * The shortfall leg (PostToolUse and PostToolUseFailure on\n * `WebSearch|WebFetch`), run by `tenjin mcp`'s `hook` tool. THE FREE TOOL HAS\n * ALREADY RUN, and a result that is fine ends here: no router call, no footer,\n * no added latency. Only a clear shortfall ({@link shortfallOf}) asks for one\n * routing decision, with what the harness reported riding in the packet as\n * `nativeOutcome`, and only an offer (`execute` or `discovered`) says anything.\n * A call the pre-call arm already redirected is not offered on again. Two lines\n * ask the router nothing: a PDF WebFetch saved whole, where the agent is\n * pointed at the file, and a noted search.\n *\n * A SEARCH THE PRE-CALL ARM NOTED A FREE LOOKUP ON gets that line now, read\n * from disk, framed as the option it is, under this event's own name, and the\n * router is not asked: the note already names the service it picked for this\n * search, so a call shows one line at most, and its untaken record is kept\n * here, where it is shown (`untaken.ts`). An interrupted call gets nothing,\n * since the agent never read a result for it to follow.\n *\n * A server that does not know `nativeOutcome` yet refuses the packet; that is\n * a failed decision like any other, so the hook stays silent.\n */\nexport async function runShortfallHook(\n raw: unknown,\n deps: HookDeps,\n): Promise<ShortfallHookOutcome> {\n const event = eventOf(raw, deps);\n if (event?.kind !== 'shortfall') return { response: null };\n const note =\n event.toolUseId === undefined\n ? null\n : await noteOf(\n deps.dataDir,\n localSession(event.sessionId, deps),\n event.toolUseId,\n deps.now?.(),\n );\n if (note !== null) {\n if (event.interrupted === true) return { response: null };\n await noteShown(\n deps.dataDir,\n {\n id: note.offerId,\n ids: note.ids ?? [],\n harness: hostOf(deps),\n scope: offerScope(localSession(event.sessionId, deps), event.agentId),\n },\n deps.now?.(),\n );\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: event.eventName,\n additionalContext: noteLine(note.line, hostOf(deps)),\n },\n },\n action: 'execute',\n id: note.offerId,\n noted: true,\n };\n }\n if (event.savedPdf !== null) return await pointAtSavedPdf(event, event.savedPdf, deps);\n return offerOnShortfall(event, deps);\n}\n\n/**\n * A PDF WEBFETCH SAVED IS READ FOR FREE. Its summary was handed the compressed\n * bytes and says it cannot parse them, but the harness saved the file whole,\n * and `Read` returns every page. So the line says that, and the router is\n * never asked: a paid reader would only fetch the same file again. Silent when\n * `router.enabled` is off, like every other line this hook writes.\n */\nasync function pointAtSavedPdf(\n event: Extract<HookEvent, { kind: 'shortfall' }>,\n path: string,\n deps: HookDeps,\n): Promise<ShortfallHookOutcome> {\n if ((await routerFor(event.cwd, deps)) === null) return { response: null };\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: event.eventName,\n additionalContext: savedPdfHint(path),\n },\n },\n savedPdf: true,\n };\n}\n\n/** The shortfall route itself: ask about a call that came back short, once. */\nasync function offerOnShortfall(\n event: Extract<HookEvent, { kind: 'shortfall' }>,\n deps: HookDeps,\n): Promise<ShortfallHookOutcome> {\n const { nativeOutcome, pending, eventName } = event;\n if (nativeOutcome === null) return { response: null };\n if (pending === null) return { response: null };\n if (\n event.toolUseId !== undefined &&\n (await wasOffered(\n deps.dataDir,\n localSession(event.sessionId, deps),\n event.toolUseId,\n deps.now?.(),\n ))\n ) {\n return { response: null, nativeOutcome, alreadyOffered: true };\n }\n const routed = await routeNativeCall(event, pending, deps, { nativeOutcome });\n if (routed.offer === null) {\n return { ...routed.outcome, nativeOutcome };\n }\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: eventName,\n // THE SERVER'S LINE, attributed and framed as the option it is. It\n // already carries the id and the exact search or URL that came back short.\n additionalContext: shortfallOffer(event.tool, routed.offer.hint, hostOf(deps)),\n },\n },\n nativeOutcome,\n action: routed.offer.action,\n id: routed.offer.id,\n };\n}\n\nexport interface DelegationHookOutcome {\n response: unknown | null;\n action?: HookDecision['action'];\n id?: string;\n withheld?: true;\n noRequestTool?: true;\n}\n\n/**\n * The agent leg (PreToolUse on `Agent|Task`), run by `tenjin mcp`'s `hook`\n * tool. The one moment a subagent's whole assignment is visible: its task\n * prompt IS the current message, and the parent's own turn is the history, so\n * the router decides on exactly what the subagent will do. On a clear offer, it\n * is appended to that task as one optional line, which reaches the subagent as\n * part of its instructions from its parent, before it starts. Anything else is\n * no output at all.\n *\n * The subagent will be the payer, so the same auto-execute rule applies here.\n */\nexport async function runDelegationHook(\n raw: unknown,\n deps: HookDeps,\n): Promise<DelegationHookOutcome> {\n const event = eventOf(raw, deps);\n if (event?.kind !== 'delegation') return { response: null };\n const { task } = event;\n if (task === null || task.trim().length === 0) return { response: null };\n const router = await routerFor(event.cwd, deps);\n if (router === null) return { response: null };\n await sweepUntaken(deps, router);\n // The subagent this task goes to is the one that would have to make the\n // call, so the same rule: only a type known to have the tool is offered. With\n // no type the harness runs its general-purpose agent, which inherits it.\n if ((await requestToolAccess(event.subagentType, agentLookup(event.cwd, deps))) !== 'allowed') {\n return { response: null, noRequestTool: true };\n }\n const sealed = await sealHere(\n await buildPromptPacket(event.transcriptPath, event.sessionId, task, hostOf(deps), {\n delegated: true,\n }),\n router,\n event.cwd,\n deps,\n );\n // The native hook's two rules, with the task as the subject: a task the mask\n // would change is not sent, since the offer is written back into it, and a\n // task naming a local target only ever has a native answer.\n if (sealed.localUrl) return { response: null };\n if (sealed.currentChanged) {\n (deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`)))(\n 'tenjin hook: the delegated task carries a credential-shaped value, so it is not routed',\n );\n return { response: null };\n }\n // The native hook's rule, for the same reason: a delegation routed without\n // the user's words could offer what they just ruled out.\n if (sealed.packet.historyStatus !== 'ok') return { response: null };\n // Only the subagent could take this offer, so no native call here ignores it.\n const footer = await openFooter(deps, event.sessionId, 'delegate', null);\n const deadline = gateDeadline(deps);\n const outcome = await decide(sealed, deps, router, event.sessionId, deadline, footer);\n if (!isOffer(outcome)) {\n await footer.close(outcome);\n return { response: null, ...(outcome !== null ? { action: outcome.action } : {}) };\n }\n // The subagent will make the call and cannot ask the user, so nothing it\n // could not pay for alone is offered to it.\n const vetted = await vetOffer(outcome, deps, deadline, false);\n if (vetted.withheld !== undefined) {\n await footer.close(outcome, { withheld: vetted.withheld });\n return { response: null, action: outcome.action, withheld: true };\n }\n await footer.close(outcome);\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n // The whole input, with one line appended: `updatedInput` replaces it.\n updatedInput: {\n ...event.toolInput,\n prompt: `${task}\\n\\n${delegationOffer(outcome.hint)}`,\n },\n },\n },\n action: outcome.action,\n id: outcome.id,\n };\n}\n\n/**\n * THE HOOK STAGE, WHICH IS THE ONE THE DEMO OPENS WITH. The decision is in\n * flight for about a second, and at a one-second refresh a state that is\n * written and then erased inside that second is a state nobody ever sees. So\n * the record is not cleared: `selecting service` is REPLACED by what the\n * decision turned out to be, and that outcome holds the line until the next\n * state arrives or its hold runs out.\n *\n * Display only. Every write inside swallows its own failure, and a shown offer\n * also leaves the id-to-session binding the tool resolves its progress through,\n * the request specs the line names, which the tool reads by id, and its\n * untaken record (`untaken.ts`), scoped to `shownTo`: the agent whose native\n * call would ignore it, or null for a delegated task's. A noted line is not\n * shown yet, so it gets no untaken record here: the after-call arm keeps one\n * when it shows the line.\n */\nasync function openFooter(\n deps: HookDeps,\n sessionId: string,\n operation: 'prompt' | 'search' | 'delegate',\n shownTo: { agentId?: string } | null,\n): Promise<{\n /** Why this call's routing fee was not paid, when it was not. */\n unpaid: (why: string) => void;\n /** The router's answer, whose settings hash is kept with its specs. */\n answered: (answer: Pick<HookResponse, 'settingsHash'>) => void;\n /** `withheld` is why an `execute` was not shown, in the footer's words;\n * `noted` is a free line the after-call arm shows once the search has run. */\n close: (\n decision: HookDecision | null,\n opts?: { withheld?: string; noted?: true },\n ) => Promise<void>;\n}> {\n sessionId = localSession(sessionId, deps);\n const now = (): number => deps.now?.() ?? Date.now();\n const directory = sessionDir(deps.dataDir, sessionId);\n const callId = newCallId();\n await noteSession(deps.dataDir, sessionId, now());\n await writeProgress(\n directory,\n callId,\n { phase: 'routing', operation, outcome: 'selecting service' },\n now(),\n );\n await pruneProgress(directory, now());\n // The root, not just this session: a directory per session ever opened would\n // eventually be more than the resolver can scan.\n await pruneSessions(deps.dataDir, now());\n let unpaid: string | undefined;\n let settingsHash: string | undefined;\n return {\n unpaid: (why) => {\n unpaid = why;\n },\n answered: (answer) => {\n settingsHash = answer.settingsHash;\n },\n close: async (decision, opts) => {\n const withheld = opts?.withheld;\n await writeProgress(\n directory,\n callId,\n {\n phase: 'done',\n operation,\n outcome:\n withheld !== undefined ? `native tools (${withheld})` : hookOutcome(decision, unpaid),\n },\n now(),\n );\n if (withheld === undefined && isOffer(decision)) {\n await bindDecision(deps.dataDir, sessionId, decision.id, now());\n if (opts?.noted !== true) {\n await noteShown(\n deps.dataDir,\n {\n id: decision.id,\n ids: offeredIds(decision),\n harness: hostOf(deps),\n ...(shownTo !== null ? { scope: offerScope(sessionId, shownTo.agentId) } : {}),\n },\n now(),\n );\n }\n // The line is shown, so the specs of the services it names are what\n // `request({id, input})` runs and `request({id})` shows, and its\n // choice set is what `request({id, choice})` picks from.\n // Each with the settings hash its answer echoed: what the check before\n // every call holds the offer to.\n const lead = accountLeadOf(decision);\n if (lead !== undefined) {\n await storeAccountOffer(deps.dataDir, lead, settingsHash);\n } else {\n const specs: readonly AnyOfferSpec[] = decision.specs ?? [];\n await storeSpecs(\n deps.dataDir,\n specs.filter((spec): spec is OfferSpec => !isAccountSpec(spec)),\n settingsHash,\n );\n }\n // A free lookup has no spec to name its row: its label is kept instead.\n if (isFree(decision) && decision.label !== undefined) {\n await storeLabel(deps.dataDir, decision.id, decision.label);\n }\n if (decision.action === 'discovered' && decision.choices !== undefined) {\n await storeChoices(deps.dataDir, decision.id, {\n choices: decision.choices,\n hint: decision.hint,\n });\n }\n }\n },\n };\n}\n\n/** Every id an offer's line names: its own, each spec's and each choice's. */\nfunction offeredIds(offer: OfferDecision): string[] {\n return [\n offer.id,\n ...(offer.specs ?? []).map((spec) => spec.id),\n ...(offer.action === 'discovered' ? (offer.choices?.options ?? []).map((o) => o.id) : []),\n ];\n}\n\n/**\n * ONE ROUTED LEG REPORTS WHAT WAS IGNORED SINCE THE LAST ONE: every offer\n * past its 15 minutes and, with `nativeScope` (a native call about to run),\n * every offer that same agent still holds. The claim is a few local file\n * operations, made before this leg can show an offer of its own; the reports\n * go without being waited on, so a slow router never holds the turn.\n */\nasync function sweepUntaken(\n deps: HookDeps,\n router: RouterHere,\n nativeScope?: string,\n): Promise<void> {\n const claimed = await claimIgnored(deps.dataDir, {\n now: deps.now?.() ?? Date.now(),\n ...(nativeScope !== undefined ? { nativeScope } : {}),\n });\n if (claimed.length === 0) return;\n void reportIgnored(claimed, {\n ctx: hookContext(deps),\n baseUrl: resolveBaseUrl(deps, router.config),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n}\n\n/** What the gate decided, in the footer's own words. A silent backend is not a\n * blank line: the turn runs on native tools and the footer says which. A\n * routing fee that was not paid (`wallet_low`, `no_payer` and the rest) is\n * named as such, never passed off as the router choosing native tools. */\nexport function hookOutcome(decision: HookDecision | null, unpaid?: string): string {\n if (isAccountOffer(decision)) return `account lookup offered (${decision.provider})`;\n if (isOffer(decision)) return `paid lookup offered (${termsOf(decision).provider})`;\n if (unpaid !== undefined && (decision === null || decision.action === 'native')) {\n // `fee unpaid: <reason>` fits the record's 40 characters for every reason.\n return `fee unpaid: ${unpaid}`;\n }\n if (decision === null) return 'native tools (router unavailable)';\n // An offer this build skipped is not the router choosing native tools.\n if (decision.action === 'native' && decision.diagnostics.reasonCode === REQUIRES_UNMET) {\n return 'native tools (offer needs newer tenjin)';\n }\n if (decision.action === 'native') return 'native tools (router chose native)';\n return 'needs input';\n}\n\n/** The one routing call, its packet SEALED (masked and bounded): a path that\n * skips the mask does not typecheck. It goes to the paid route, whose fee\n * the payer in `tenjin mcp` pays; a call it cannot pay is skipped (after\n * waiting for the background top-up when its channel needs a deposit), the\n * native tool runs, and the first such call in a session tells the user why\n * and what fixes it.\n *\n * BACKOFF: a call that could not reach the router starts the machine's\n * `unreachable` memo, and for its minute every leg skips the call and the\n * native tool runs at once, rather than each one waiting out the gate. It\n * ends after its minute, or when `tenjin doctor` reaches the router. */\nasync function decide(\n { packet }: Sealed,\n deps: HookDeps,\n router: RouterHere,\n sessionId: string,\n deadline: number,\n footer: {\n unpaid: (why: string) => void;\n answered: (answer: HookResponse) => void;\n },\n): Promise<HookDecision | null> {\n const { config } = router;\n const baseUrl = resolveBaseUrl(deps, config);\n const warn = deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`));\n const now = deps.now?.() ?? Date.now();\n const backoff = await readRouterMemo(deps.dataDir, 'unreachable', baseUrl, now);\n if (backoff !== null) {\n const left = Math.ceil((backoff.until - now) / 1000);\n warn(`tenjin hook: ${baseUrl} did not answer a moment ago, so the native tool runs (${left}s)`);\n return null;\n }\n const route = deps.route?.(baseUrl);\n const outcome = await requestDecision(\n 'hook',\n { packet, sessionId },\n {\n ctx: hookContext(deps),\n baseUrl,\n acceptsBazaar: resolveExperimentalBazaar(config).value === 'on',\n harness: hostOf(deps),\n improve: router.settings.improve.value,\n timeoutMs: Math.max(0, deadline - now),\n // THE SAVED RULES RIDE BESIDE THE PACKET on every call, read for this\n // event: `routerFor` already refused rules this build cannot read.\n settings: router.wire.settings,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n ...(route !== undefined ? { route } : {}),\n },\n );\n for (const { id, missing } of outcome.status === 'decided' ? (outcome.skipped ?? []) : []) {\n warn(\n `tenjin hook: offer ${id} needs ${missing.join(', ')}, which this build lacks, so it was skipped`,\n );\n }\n // New routing terms are told once, on the first paid-path call after an update.\n if (route !== undefined && deps.notice !== undefined) {\n const terms = await termsNotice(deps.dataDir);\n if (terms !== null) deps.notice(terms);\n }\n // A deposit sets funds aside; the user would otherwise see it only as spend.\n // A background top-up's is said here alone, never in a tool's result, so the\n // person reads it.\n const deposited = (route?.deposited?.() ?? 0n) + (route?.toppedUp?.() ?? 0n);\n if (deposited > 0n) deps.notice?.(depositSentence(deposited));\n if (outcome.status === 'skipped') {\n // The router answered (its 402, say) before the skip: it is reachable.\n if (outcome.answered === true) await clearRouterMemo(deps.dataDir, 'unreachable', baseUrl);\n footer.unpaid(outcome.why);\n await tellOnce(deps, sessionId, outcome.why, now, outcome.quotedAtomic);\n warn(`tenjin hook: the routing fee was not paid (${outcome.why}), so the native tool runs`);\n return null;\n }\n // ONLY A COMPLETED SIGNED PAYMENT establishes paid routing recovered.\n // A free decision, or a background deposit, proves no such recovery.\n if (outcome.status === 'decided' && route?.paid?.() === true) {\n const cleared = await noticeCleared(deps.dataDir, sessionId, now).catch(() => null);\n if (cleared !== null) deps.notice?.(cleared);\n }\n if (outcome.status === 'failed' && outcome.unreachable === true) {\n await writeRouterMemo(deps.dataDir, 'unreachable', baseUrl, {\n now: deps.now?.() ?? Date.now(),\n ttlMs: UNREACHABLE_BACKOFF_MS,\n detail: outcome.reason,\n });\n } else if (\n outcome.status === 'decided' ||\n (outcome.status === 'failed' && outcome.noAnswer !== true)\n ) {\n // Only an answer ends it: a concurrent call that timed out, or got no\n // answer for any other reason, leaves another call's backoff in place.\n await clearRouterMemo(deps.dataDir, 'unreachable', baseUrl);\n }\n if (outcome.status === 'failed') {\n warn(`tenjin hook: ${baseUrl}${ROUTE_PAID_PATH} ${outcome.reason}`);\n return null;\n }\n if (!decidedUnder(outcome.decision, router, warn)) return null;\n footer.answered(outcome.decision);\n return outcome.decision.decision;\n}\n\n/**\n * AN ANSWER DECIDED UNDER OTHER RULES OFFERS NOTHING: its hash names other\n * rules than the ones saved now, or it echoed none while the user has rules,\n * so it came from a router that did not apply them. Its offer would only be\n * refused when it ran (`settings-check.ts`).\n */\nfunction decidedUnder(\n answer: Pick<HookResponse, 'settingsHash'>,\n router: RouterHere,\n warn: (line: string) => void,\n): boolean {\n if (hashRefusal(router.wire, answer.settingsHash) === null) return true;\n warn(\n 'tenjin hook: the router did not confirm it applied your Tenjin settings, so no lookup is offered',\n );\n return false;\n}\n\n/**\n * ONE LINE FOR THE USER, ONCE PER SESSION AND REASON, when a call could not\n * pay the routing fee for a reason the user can fix: the reason and the fix,\n * in the hook's `systemMessage`. Never on every call, and never in place of\n * routing. A different reason later in the session is news again (a missing\n * passphrase repaired into a wrong one), the same one is not.\n */\nasync function tellOnce(\n deps: HookDeps,\n sessionId: string,\n why: string,\n now: number,\n quotedAtomic?: bigint,\n) {\n const sentence = unpaidSentence(why, 'person', quotedAtomic);\n if (sentence === null || deps.notice === undefined) return;\n const told = await noticeFor(deps.dataDir, sessionId, why, now).catch(() => 'quiet' as const);\n if (told === 'tell') deps.notice(sentence);\n}\n\n/** The hooks write their own protocol answer on stdout and nothing else. */\nfunction nullStream(): NodeJS.WritableStream {\n return { write: () => true } as unknown as NodeJS.WritableStream;\n}\n\n/**\n * What one redirect is for: the search as the agent wrote it, or the URL as\n * `URL` parses it, so a retry that differs only in how the URL is spelled is\n * still the same call.\n */\nfunction redirectTarget(pending: PendingCall): string {\n if (pending.tool === 'WebSearch') return `WebSearch ${pending.query}`;\n if (pending.tool === 'AskUserQuestion') return `AskUserQuestion ${pending.question}`;\n let url = pending.url;\n try {\n url = new URL(url).toString();\n } catch {\n // Not a URL the parser takes: the agent's own spelling is the target.\n }\n return `WebFetch ${url}`;\n}\n\nfunction pendingCallOf(\n tool: 'WebSearch' | 'WebFetch',\n input: Record<string, unknown>,\n): PendingCall | null {\n const value = tool === 'WebSearch' ? input.query : input.url;\n if (typeof value !== 'string') return null;\n // Not cut here: seal() masks the subject first and bounds it after, so a\n // token crossing the bound is seen whole by the mask.\n const subject = value.trim();\n if (subject.length === 0) return null;\n return tool === 'WebSearch' ? { tool, query: subject } : { tool, url: subject };\n}\n\n/** `router.*` for one event's directory, the `settings` field every call\n * sends (only ever readable rules), and the global config it read. */\ninterface RouterHere {\n settings: RouterSettings;\n wire: Extract<WireState, { status: 'ok' }>;\n config: PartialConfig;\n}\n\n/**\n * `router.*` for the event's directory with the global config it came from,\n * which is read ONCE per event and also names the base URL; null when the\n * router is off there. FIRST, before any packet is built: `router.enabled\n * false` means nothing about this turn is read for the router or leaves the\n * machine. A config that cannot be read is off too, since a switch the user\n * set must not fail open.\n */\nasync function routerFor(cwd: string | undefined, deps: HookDeps): Promise<RouterHere | null> {\n const warn = deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`));\n try {\n const config = await loadRawConfig(deps.dataDir);\n const settings = await routerSettings(\n { cwd: cwd ?? process.cwd(), dataDir: deps.dataDir, config },\n { warn: (line) => warn(`tenjin hook: ${line}`) },\n );\n if (!settings.enabled.value) return null;\n // RULES THIS BUILD CANNOT READ ROUTE NOTHING: no rule is guessed, and no\n // turn is routed without them. `tenjin config` shows the problem.\n if (settings.wire.status === 'invalid') {\n warn(\n `tenjin hook: your Tenjin settings can't be read (${settings.wire.problem}), so nothing is routed`,\n );\n return null;\n }\n return { settings, wire: settings.wire, config };\n } catch (err) {\n warn(`tenjin hook: ${err instanceof Error ? err.message : String(err)}, so the router is off`);\n return null;\n }\n}\n\n/**\n * The packet as it leaves: scoped to `router.context`, then sealed, with the\n * links on the user's own hosts named (`own-urls.ts`), read only when it has\n * a link at all.\n */\nasync function sealHere(\n packet: Packet,\n router: RouterHere,\n cwd: string | undefined,\n deps: HookDeps,\n): Promise<Sealed> {\n const inScope = scoped(packet, router.settings);\n const ownHosts = await ownHostsFor(inScope, cwd ?? process.cwd(), hostOf(deps), deps.homeDir);\n return seal(inScope, ownHosts.length > 0 ? { ownHosts } : {});\n}\n\n/**\n * `router.context turn`: the current turn and nothing before it. `current` is\n * kept (the prompt, the latest user message on a native call, the task on a\n * delegation) so an instruction given this turn still reaches the gate;\n * `historyStatus` is left as read, so a call whose turn could not be found is\n * still offered nothing.\n */\nfunction scoped(packet: Packet, router: RouterSettings): Packet {\n return router.context.value === 'turn' ? { ...packet, history: [] } : packet;\n}\n\nfunction hostOf(deps: HookDeps): Harness {\n return deps.harness ?? 'claude';\n}\n\n/** The harness's event in the arms' shape, from that harness's own decoder. */\nfunction eventOf(raw: unknown, deps: HookDeps): HookEvent | null {\n return hostOf(deps) === 'codex' ? codexRouterEvent(raw) : decodeEvent(raw);\n}\n\n/** Where this session's local state lives; a Codex session never shares Claude's. */\nfunction localSession(sessionId: string, deps: HookDeps): string {\n return hostOf(deps) === 'codex' ? codexSession(sessionId) : sessionId;\n}\n","import { open } from 'node:fs/promises';\nimport { isIP } from 'node:net';\nimport { dirname, join } from 'node:path';\nimport { isPublicAddress } from '../lib/destination';\nimport { mask } from '../lib/redact';\nimport { parseCodexHistory } from './codex-history';\nimport type { Harness } from './names';\n\n/**\n * The bounded conversation packet the router's gate and paid decision read.\n *\n * WHAT GOES IN IT: ordinary user and assistant text from the CURRENT session\n * only (and, for a subagent's own native call, that one subagent's rows), at\n * most {@link MAX_HISTORY} prior messages and at most {@link MAX_PACKET_BYTES}\n * in total, oldest dropped first. The builders below choose the text;\n * {@link seal} masks and bounds it, and is the only way a packet reaches the\n * wire. Tool results are excluded: a tool result is other people's content,\n * and a packet that carried it would be a channel from a fetched page into a\n * routing decision.\n *\n * WHAT NEVER HAPPENS: a transcript this reader cannot vouch for is reported\n * as `unavailable` rather than partially believed, and the user's turn is\n * never blocked by any of that. Another session's rows, a subagent sidechain,\n * malformed rows and everything before a compaction boundary are skipped row\n * by row. A file over {@link MAX_TRANSCRIPT_BYTES} is read from its tail\n * ({@link readTail}), where this turn's own words are. Adapted from the draft\n * auto-mode experiment (PR #369 `context.ts`), whose 48,000-character reader\n * this tightens.\n */\n\nexport const MAX_HISTORY = 6;\nexport const MAX_PACKET_BYTES = 16 * 1024;\n/** Every bound here is the server's own (tenjin `lib/x402-router/wire.ts`). A\n * packet this side lets through and that side refuses is a paid 400. */\nexport const MAX_MESSAGE_CHARS = 16_000;\n/** How much of a transcript is read: all of a smaller one, the last this many\n * bytes of a larger one. A long working session passes 4 MB in a day. */\nconst MAX_TRANSCRIPT_BYTES = 4_000_000;\nconst MAX_LITERAL_URLS = 8;\nconst MAX_LITERAL_URL_CHARS = 2_000;\n/** The server's caps on `current.quoted`: blocks, each one a message's size. */\nconst MAX_QUOTED = 8;\nconst MAX_PENDING_CHARS = 4_000;\n/** The server's cap on a native outcome's error text. */\nconst MAX_OUTCOME_ERROR_CHARS = 1_000;\n/** Scanned past each bound: longer than any secret shape the mask knows. */\nconst MASK_MARGIN = 4_096;\n\nexport type PacketRole = 'user' | 'assistant';\nexport interface PacketMessage {\n role: PacketRole;\n text: string;\n /**\n * On `current` only: blocks the harness marked as pasted, moved out of\n * `text` so the text is the user's own words ({@link splitPasted}).\n */\n quoted?: string[];\n}\n\nexport type HistoryStatus = 'ok' | 'unavailable';\n\nexport interface Packet {\n current: PacketMessage;\n history: PacketMessage[];\n /** Absolute http(s) URLs written literally in the current message. */\n literalUrls: string[];\n /**\n * The entries of `literalUrls` the host can open with its own tools: links\n * on the host of the current repository's git remote, and the harness's own\n * links ({@link SealOptions}). Absent when there are none.\n */\n ownUrls?: string[];\n historyStatus: HistoryStatus;\n pendingCall?: PendingCall;\n /** How the free tool already fared on `pendingCall`, sent only when it fell\n * short. Never without `pendingCall`: the server refuses it alone. */\n nativeOutcome?: NativeOutcome;\n}\n\n/** What the harness reported about a native call that came back short: its\n * status and size (WebFetch), or the error a failed call carried. At least one\n * field, always; the server's schema is the same strict object. */\nexport interface NativeOutcome {\n code?: number;\n bytes?: number;\n error?: string;\n /** Why a call whose status and size look fine still came back short. */\n reason?: NativeShortfallReason;\n}\n\n/**\n * The client's own reading of a native result, named where the code and the\n * size say nothing. `no_main_content`: WebFetch answered 2xx with a full body,\n * and its summary says the page was empty, only a title, navigation or a\n * footer, or needed JavaScript it did not run (a script-rendered app, a video\n * page) (`readsAsEmptyPage`). The server picks the reader from the URL.\n */\nexport type NativeShortfallReason = 'no_main_content';\n\n/** The pending native call, INSIDE the packet: the gate request is a strict\n * object with exactly `schemaVersion`, `source` and `packet`. An\n * `AskUserQuestion` carries the host's own question and its options, joined. */\nexport type PendingCall =\n | { tool: 'WebSearch'; query: string }\n | { tool: 'WebFetch'; url: string }\n | { tool: 'AskUserQuestion'; question: string };\n\n/** The one string a pending call is about: its search, its URL or its question. */\nexport function subjectOf(pending: PendingCall): string {\n return 'query' in pending ? pending.query : 'url' in pending ? pending.url : pending.question;\n}\n\n/** The same call about a different subject, of the same kind. */\nfunction withSubject(pending: PendingCall, subject: string): PendingCall {\n if ('query' in pending) return { tool: pending.tool, query: subject };\n if ('url' in pending) return { tool: pending.tool, url: subject };\n return { tool: pending.tool, question: subject };\n}\n\nconst URL_RE = /\\bhttps?:\\/\\/[^\\s<>\"'`)\\]]+/gi;\n\nexport function literalUrlsIn(text: string): string[] {\n const found = new Set<string>();\n for (const match of text.matchAll(URL_RE)) {\n const candidate = match[0].replace(/[.,;:!?]+$/, '');\n try {\n const normalized = new URL(candidate).toString();\n if (normalized.length <= MAX_LITERAL_URL_CHARS) found.add(normalized);\n } catch {\n continue;\n }\n if (found.size >= MAX_LITERAL_URLS) break;\n }\n return [...found];\n}\n\n/**\n * Bring the packet inside the server's caps: oldest history first, then the\n * current message itself, measured on the WHOLE packet rather than on the two\n * message lists, because `literalUrls` and a pending call are bytes too.\n *\n * EXPORTED BECAUSE ATTACHING ANYTHING RE-OPENS THE QUESTION. A packet this\n * returned at exactly the cap is over it the moment a caller adds a field, and\n * the server refuses rather than truncates, so every caller that adds one runs\n * this again on what it is actually going to send.\n */\nexport function fit(packet: Packet): Packet {\n const size = (value: Packet): number => Buffer.byteLength(JSON.stringify(value));\n const next: Packet = { ...packet, history: packet.history.slice(-MAX_HISTORY) };\n // In order of what is cheapest to lose. History first: a prior turn is\n // context. Then the literal URLs, which are a convenience the server can\n // re-derive from the text. The current message LAST, because it is the task\n // itself, and only down to one character, so a packet is never empty.\n while (next.history.length > 0 && size(next) > MAX_PACKET_BYTES) {\n next.history = next.history.slice(1);\n }\n while (next.literalUrls.length > 0 && size(next) > MAX_PACKET_BYTES) {\n next.literalUrls = next.literalUrls.slice(0, -1);\n // `ownUrls` names entries of `literalUrls`, so it loses what that loses.\n const own = next.ownUrls?.filter((url) => next.literalUrls.includes(url)) ?? [];\n if (own.length > 0) next.ownUrls = own;\n else delete next.ownUrls;\n }\n // Then what the user pasted, last block first: it is context for the task,\n // and the task is the user's own words.\n while ((next.current.quoted?.length ?? 0) > 0 && size(next) > MAX_PACKET_BYTES) {\n const quoted = next.current.quoted!.slice(0, -1);\n const { role, text } = next.current;\n next.current = quoted.length > 0 ? { role, text, quoted } : { role, text };\n }\n while (size(next) > MAX_PACKET_BYTES && next.current.text.length > 1) {\n const over = size(next) - MAX_PACKET_BYTES;\n const keep = Math.max(1, next.current.text.length - Math.max(over, 1));\n next.current = { ...next.current, text: next.current.text.slice(0, keep) };\n }\n return next;\n}\n\n/** What {@link seal} is told beside the packet. */\nexport interface SealOptions {\n /**\n * The hosts whose links the host opens with its own tools: the current\n * repository's git remotes, and the harness's own (`own-urls.ts`). Each\n * sealed literal URL on one of them is also listed in `ownUrls`.\n */\n ownHosts?: readonly string[];\n}\n\nexport interface Sealed {\n packet: Packet;\n /** The mask changed the pending call's search or URL. */\n subjectChanged: boolean;\n /** The pending WebFetch targets this machine or a private network. */\n localTarget: boolean;\n /** The mask changed the current message. */\n currentChanged: boolean;\n /** A literal URL in the packet targets this machine or a private network. */\n localUrl: boolean;\n}\n\n/**\n * THE ONE OUTBOUND CHOKEPOINT. Every string that leaves in a hook packet is\n * masked here, `current` and its `quoted` blocks, `history`, `literalUrls` and\n * the pending call alike,\n * and only then bounded ({@link maskWithin}): a secret cut in half by a bound\n * before the mask no longer matches its row, and its first half would leave. The server stores\n * the packet against the id, so a secret here is a secret in its database.\n *\n * It also says what the caller must not send at all. A masked subject would\n * become the query the server writes into its hint, and a local or private\n * target can only ever be answered natively; both run unrouted.\n */\nexport function seal(packet: Packet, opts: SealOptions = {}): Sealed {\n const pending = packet.pendingCall;\n const subject = pending === undefined ? '' : subjectOf(pending);\n const sealedSubject = maskWithin(subject, MAX_PENDING_CHARS);\n const bound = (text: string): string => maskWithin(text, MAX_MESSAGE_CHARS).text;\n const sealedCurrent = maskWithin(packet.current.text, MAX_MESSAGE_CHARS);\n const current = sealedCurrent.text;\n const quoted = (packet.current.quoted ?? [])\n .slice(0, MAX_QUOTED)\n .map(bound)\n .filter((block) => block.length > 0);\n const outcome = packet.nativeOutcome;\n const literalUrls = packet.literalUrls\n .filter((url) => !isLocalTarget(url))\n .map(mask)\n .filter((url) => url.length <= MAX_LITERAL_URL_CHARS);\n const ownHosts = new Set((opts.ownHosts ?? []).map((host) => host.toLowerCase()));\n const ownUrls = literalUrls\n .filter((url) => ownHosts.has(hostnameOf(url)))\n .slice(0, MAX_LITERAL_URLS);\n const sealed = fit({\n current: {\n role: packet.current.role,\n text: current.length > 0 ? current : '(no task text)',\n ...(quoted.length > 0 ? { quoted } : {}),\n },\n history: packet.history\n .slice(-MAX_HISTORY)\n .map((message) => ({ role: message.role, text: bound(message.text) }))\n .filter((message) => message.text.length > 0),\n literalUrls,\n ...(ownUrls.length > 0 ? { ownUrls } : {}),\n historyStatus: packet.historyStatus,\n ...(pending === undefined ? {} : { pendingCall: withSubject(pending, sealedSubject.text) }),\n ...(outcome === undefined\n ? {}\n : {\n nativeOutcome: {\n ...outcome,\n ...(outcome.error !== undefined\n ? { error: maskWithin(outcome.error, MAX_OUTCOME_ERROR_CHARS).text }\n : {}),\n },\n }),\n });\n return {\n packet: sealed,\n subjectChanged: sealedSubject.changed,\n localTarget: pending !== undefined && 'url' in pending && isLocalTarget(pending.url),\n currentChanged: sealedCurrent.changed,\n localUrl: packet.literalUrls.some(isLocalTarget),\n };\n}\n\n/**\n * MASKED, THEN BOUNDED, over a window: the mask scans what can be sent plus a\n * margin longer than any secret shape, so its cost is bounded however large\n * the input, and a secret crossing `max` is seen whole before the cut. A PEM\n * block that opens inside the window is masked to the window's end. When the\n * window itself cut the text, the last `MASK_MARGIN` characters of its masked\n * form are never sent either: a secret cut at the window's edge can sit there\n * after earlier masks shortened the text, and must not leave in part.\n */\nfunction maskWithin(text: string, max: number): { text: string; changed: boolean } {\n const window = text.slice(0, max + MASK_MARGIN);\n const masked = mask(window);\n const limit = window.length < text.length ? Math.min(max, masked.length - MASK_MARGIN) : max;\n return { text: masked.slice(0, Math.max(0, limit)), changed: masked !== window };\n}\n\n/** A URL's host as `URL` names it, lowercase; empty for one that does not parse. */\nfunction hostnameOf(raw: string): string {\n try {\n return new URL(raw).hostname.toLowerCase();\n } catch {\n return '';\n }\n}\n\nconst LOCAL_NAME = /(?:^|\\.)(?:localhost|local)$/i;\n\n/**\n * A URL no public service can fetch: another scheme, a `localhost` or `.local`\n * name, or a literal address that is not public (loopback, private,\n * link-local, IPv6 ULA and the other reserved ranges `isPublicAddress` knows).\n * A string that does not parse as a URL is not a public target either.\n */\nfunction isLocalTarget(raw: string): boolean {\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n return true;\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return true;\n const host = url.hostname.replace(/^\\[|\\]$/g, '');\n if (LOCAL_NAME.test(host)) return true;\n return isIP(host) !== 0 && !isPublicAddress(host);\n}\n\n/**\n * Build the packet for one user prompt. `transcriptPath` is the harness's own\n * path for this session; an absent or unusable one yields `unavailable`. The\n * result is neither masked nor bounded: {@link seal} does both.\n */\nexport async function buildPromptPacket(\n transcriptPath: string | undefined,\n sessionId: string,\n prompt: string,\n harness: Harness = 'claude',\n opts: { delegated?: boolean; agentId?: string } = {},\n): Promise<Packet> {\n const trimmed = prompt.trim();\n const text = trimmed.length > 0 ? trimmed : '(empty prompt)';\n const session = await readHistory(transcriptPath, { sessionId, harness });\n // A subagent's prompt belongs to its own task: its transcript follows the session's,\n // as for a subagent's tool call (see buildNativePacket). One that cannot be read\n // leaves the session's history alone.\n const own =\n opts.agentId === undefined || harness === 'codex' || session === null\n ? null\n : await readHistory(subagentTranscriptPath(transcriptPath, sessionId, opts.agentId), {\n sessionId,\n agentId: opts.agentId,\n });\n const read = own === null ? session : [...session!, ...own];\n // A delegated task is the agent's words, so no harness mark is read in it.\n const current: PacketMessage = { role: 'user', text };\n return {\n current: opts.delegated === true ? current : withPasted(current, harness),\n history: read ?? [],\n literalUrls: literalUrlsIn(text),\n historyStatus: read === null ? 'unavailable' : 'ok',\n };\n}\n\n/**\n * WHAT THE USER PASTED IS NOT WHAT THEY ASKED. A block the harness itself\n * marks as pasted goes to `quoted`, apart from the user's own words. Only a\n * harness's own mark counts: nothing is guessed from what the text looks\n * like, and a message the move would leave empty, or that carries a mark this\n * reader cannot account for, stays as it was.\n *\n * WHICH HARNESS MARKS A PASTE (read 2026-11-01). Claude Code, in the terminal\n * and the desktop app's Code tab, wraps each paste in the prompt in\n * `<pasted_content id=\"<4 hex>\">` and `</pasted_content id=\"<the same id>\">`,\n * each tag on its own line, with any tag text inside the paste escaped\n * (`<\\pasted_content`): {@link splitClaudePastes}. Not every paste is wrapped\n * (Claude Code decides), and an unwrapped one stays in the text. Codex's\n * terminal expands its `[Pasted Content N chars]` placeholder inline with no\n * mark. The Codex desktop app (0.162 to 0.164) saves a long paste as a file\n * and writes the message as its own sections: `# Files pasted by the user:`,\n * one `## \"<the paste's opening…>\": <file>` line per paste, and the user's\n * words after `## My request:`. Those opening lines are the blocks moved here,\n * without the local path.\n */\nexport function splitPasted(\n text: string,\n harness: Harness,\n): { text: string; quoted: string[] } | null {\n if (harness === 'claude') return splitClaudePastes(text);\n const lines = text.split('\\n');\n const start = lines.indexOf(PASTED_HEADER);\n const request = lines.indexOf(REQUEST_HEADER, start + 1);\n if (start === -1 || request === -1) return null;\n // The section runs to the next of the app's top-level headers, or the request.\n const after = lines.slice(start + 1, request).findIndex((line) => line.startsWith('# '));\n const end = after === -1 ? request : start + 1 + after;\n const quoted: string[] = [];\n for (const line of lines.slice(start + 1, end)) {\n if (line.trim().length === 0) continue;\n const entry = PASTED_ENTRY.exec(line);\n // A line the app's own shape does not explain: nothing is moved.\n if (entry === null) return null;\n quoted.push(entry[1]!);\n }\n const words = lines\n .slice(request + 1)\n .join('\\n')\n .trim();\n if (quoted.length === 0 || words.length === 0) return null;\n // With no other section of the app's beside it, the text is the words alone.\n const others = [...lines.slice(0, start), ...lines.slice(end, request)].join('\\n').trim();\n const rest = [lines.slice(0, start).join('\\n').trim(), lines.slice(end).join('\\n').trim()]\n .filter((part) => part.length > 0)\n .join('\\n\\n');\n return { text: others.length === 0 ? words : rest, quoted };\n}\n\n/** Claude Code's paste tags, as its own reader takes them: the id is 4 hex. */\nconst CLAUDE_OPEN = /<pasted_content id=\"([0-9a-f]{4})\">\\n/g;\nconst CLAUDE_TAG = /<\\/?pasted_content\\b/g;\n\n/**\n * Claude Code's wrapped pastes, read the way Claude Code reads them back: each\n * block runs from its opening line to the closing tag with the same id, and\n * up to two newlines on either side belong to the block. Any tag the pairs do\n * not account for (an unclosed block, a closing tag alone, an id that is not\n * one, the tag text typed in the user's own words) leaves the message as it is.\n */\nfunction splitClaudePastes(text: string): { text: string; quoted: string[] } | null {\n const words: string[] = [];\n const quoted: string[] = [];\n const tags: number[] = [];\n let from = 0;\n for (const open of text.matchAll(CLAUDE_OPEN)) {\n if (open.index < from) return null;\n const close = `\\n</pasted_content id=\"${open[1]!}\">`;\n const bodyAt = open.index + open[0].length;\n const closeAt = text.indexOf(close, bodyAt - 1);\n if (closeAt === -1) return null;\n let start = open.index;\n for (let n = 0; n < 2 && start > from && text[start - 1] === '\\n'; n++) start--;\n let end = closeAt + close.length;\n tags.push(open.index, closeAt + 1);\n for (let n = 0; n < 2 && text[end] === '\\n'; n++) end++;\n words.push(text.slice(from, start));\n quoted.push(text.slice(bodyAt, Math.max(bodyAt, closeAt)));\n from = end;\n }\n words.push(text.slice(from));\n // Every tag in the text is one of the pairs just read, or nothing is moved.\n const every = [...text.matchAll(CLAUDE_TAG)].map((tag) => tag.index);\n if (quoted.length === 0 || every.length !== tags.length) return null;\n if (!every.every((at, i) => at === tags[i])) return null;\n const rest = words\n .map((part) => part.trim())\n .filter((part) => part.length > 0)\n .join('\\n');\n if (rest.length === 0 || quoted.every((block) => block.trim().length === 0)) return null;\n return { text: rest, quoted };\n}\n\nconst PASTED_HEADER = '# Files pasted by the user:';\nconst REQUEST_HEADER = '## My request:';\n/** `## \"<the paste's opening>\": <the file it was saved to>`. */\nconst PASTED_ENTRY = /^## \"(.+)\": \\S.*$/;\n\n/**\n * The message, with any harness-marked paste moved to `quoted`; unchanged\n * when it holds more blocks than the server takes, so none is dropped. Only\n * `current` has a `quoted`: a history message keeps its paste in its text.\n */\nfunction withPasted(message: PacketMessage, harness: Harness): PacketMessage {\n const pasted = splitPasted(message.text, harness);\n if (pasted === null || pasted.quoted.length > MAX_QUOTED) return message;\n return { role: message.role, ...pasted };\n}\n\n/**\n * Build the packet for a native call, before it runs or after it came back\n * short. The same reader as a prompt packet, with tool results excluded, and\n * the same {@link seal} before it is sent.\n *\n * THE USER'S WORDS ARE WHAT CARRY THEIR AUTHORITY. Building this packet from\n * the tool argument alone made the search string the entire conversation, so a\n * turn that said \"native tools only, no paid services\" reached the prompt gate\n * and never reached this one: the same session could then be redirected to a\n * paid provider on a bare URL. Reading the transcript at the hook event is not\n * session guessing; the harness hands this hook the path to its own session.\n *\n * The call rides INSIDE the packet as `pendingCall`, with how it fared beside\n * it as `nativeOutcome`: the shape the route takes, pinned by\n * `wire-hook-request-native-shortfall.json`.\n */\nexport async function buildNativePacket(\n transcriptPath: string | undefined,\n sessionId: string,\n pending: PendingCall,\n opts: { agentId?: string; nativeOutcome?: NativeOutcome; harness?: Harness } = {},\n): Promise<Packet> {\n const { agentId, nativeOutcome, harness = 'claude' } = opts;\n const subject = subjectOf(pending);\n const read = await readHistory(transcriptPath, { sessionId, harness });\n // A SUBAGENT'S CALL BELONGS TO ITS OWN TASK. The harness hands every\n // subagent hook the PARENT's transcript, whose latest user message is not\n // what this subagent was asked to do, so two subagents with different\n // assignments sent the same packet (tenjin-agent#377). Its own transcript\n // opens with the delegated task; the parent's messages stay in front of it\n // as history, which is how a restriction the user gave the parent still\n // reaches this call. A subagent file that cannot be read is today's\n // behaviour, not a refusal.\n const own =\n agentId === undefined || harness === 'codex'\n ? null\n : await readHistory(subagentTranscriptPath(transcriptPath, sessionId, agentId), {\n sessionId,\n agentId,\n });\n const messages = own === null ? (read ?? []) : [...(read ?? []), ...own];\n // The most recent user message is the turn this call belongs to; everything\n // before it is context. With no transcript the call speaks for itself, which\n // is what this hook did before it could read one.\n const lastUser = messages\n .map((message, index) => ({ message, index }))\n .filter((entry) => entry.message.role === 'user');\n const current = lastUser.at(-1);\n return {\n current:\n current === undefined\n ? { role: 'user', text: subject }\n : withPasted(current.message, harness),\n history: current === undefined ? messages : messages.slice(0, current.index),\n literalUrls: literalUrlsIn(`${current?.message.text ?? ''}\\n${subject}`),\n historyStatus: read === null && own === null ? 'unavailable' : 'ok',\n pendingCall: pending,\n ...(nativeOutcome !== undefined ? { nativeOutcome } : {}),\n };\n}\n\n/** Both ids become path segments, so anything but an opaque token is refused. */\nconst PATH_SEGMENT_RE = /^[A-Za-z0-9_-]{1,200}$/;\n\n/**\n * Where the harness keeps one subagent's transcript: beside the parent's\n * `<session>.jsonl`, under `<session>/subagents/agent-<agent_id>.jsonl`\n * (Claude Code 2.1.x). `undefined` when either id could not be a path segment.\n */\nexport function subagentTranscriptPath(\n transcriptPath: string | undefined,\n sessionId: string,\n agentId: string,\n): string | undefined {\n if (transcriptPath === undefined || transcriptPath.length === 0) return undefined;\n if (!PATH_SEGMENT_RE.test(sessionId) || !PATH_SEGMENT_RE.test(agentId)) return undefined;\n return join(dirname(transcriptPath), sessionId, 'subagents', `agent-${agentId}.jsonl`);\n}\n\n/**\n * Whose rows a transcript read admits: the session's own, or with `agentId`,\n * exactly one subagent's sidechain and no other.\n */\ninterface RowScope {\n sessionId: string;\n agentId?: string;\n /** Codex's rollout file has its own rows and its own ownership check. */\n harness?: Harness;\n}\n\n/** `null` means \"cannot be vouched for\"; an empty array is a genuinely fresh session. */\nasync function readHistory(\n path: string | undefined,\n scope: RowScope,\n): Promise<PacketMessage[] | null> {\n if (path === undefined || path.length === 0) return null;\n let raw: string;\n let tail: boolean;\n let file;\n try {\n file = await open(path, 'r');\n } catch {\n return null;\n }\n try {\n const stat = await file.stat();\n if (!stat.isFile()) return null;\n tail = stat.size > MAX_TRANSCRIPT_BYTES;\n const read = tail ? await readTail(file, stat.size) : await readHead(file);\n if (read === null) return null;\n raw = read;\n } catch {\n return null;\n } finally {\n await file.close();\n }\n try {\n // A Codex tail has lost the rollout's ownership header, so it is unavailable.\n if (scope.harness === 'codex') return tail ? null : parseCodexHistory(raw, scope.sessionId);\n const messages = parseRows(raw, scope);\n // A TAIL MUST HOLD THE TURN. The latest user message is the newest of\n // them, so a tail with any user message holds this turn's; one with none\n // is a single turn longer than the window, whose instruction was cut off.\n if (tail && !messages.some((message) => message.role === 'user')) {\n // Except a subagent's: its one turn is the delegated task, the first\n // user row at the head of its file. Dropping the file instead put the\n // parent's latest message in that task's place.\n if (scope.agentId === undefined) return null;\n const task = await firstUserRow(path, scope);\n return task === null ? null : [task, ...messages];\n }\n return messages;\n } catch {\n return null;\n }\n}\n\n/** The first user message in a transcript's leading {@link MAX_TRANSCRIPT_BYTES}. */\nasync function firstUserRow(path: string, scope: RowScope): Promise<PacketMessage | null> {\n const file = await open(path, 'r');\n try {\n const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);\n const window = buffer.subarray(0, bytesRead);\n // Whole lines only: a row cut at the window's end is not read.\n const end = window.lastIndexOf(0x0a);\n if (end === -1) return null;\n const rows = parseRows(window.subarray(0, end).toString('utf8'), scope);\n return rows.find((message) => message.role === 'user') ?? null;\n } finally {\n await file.close();\n }\n}\n\ntype TranscriptFile = Awaited<ReturnType<typeof open>>;\n\n/** All of a transcript within the bound; null if it grew past it meanwhile. */\nasync function readHead(file: TranscriptFile): Promise<string | null> {\n const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES + 1);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);\n if (bytesRead > MAX_TRANSCRIPT_BYTES) return null;\n return buffer.subarray(0, bytesRead).toString('utf8');\n}\n\n/**\n * THE LAST {@link MAX_TRANSCRIPT_BYTES} OF A LONGER TRANSCRIPT, from the first\n * line that starts inside them: the one byte before the window is read too,\n * so a window that opens on a line boundary keeps its first line, and one\n * that opens mid-line drops the fragment. Cutting after a newline never\n * splits a UTF-8 character. Null when the window holds no line start at all.\n */\nasync function readTail(file: TranscriptFile, size: number): Promise<string | null> {\n const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES + 1);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, size - buffer.length);\n const window = buffer.subarray(0, bytesRead);\n const newline = window.indexOf(0x0a);\n return newline === -1 ? null : window.subarray(newline + 1).toString('utf8');\n}\n\n/**\n * TOLERANT BY ROW, STRICT BY CONTENT. Every rule below still holds about what\n * may enter a packet: no other session's text, no subagent's, no tool results.\n * What changed is the blast radius of one bad row. Rejecting the whole\n * transcript over a compaction boundary or a sidechain line meant the native\n * hook routed on the tool argument alone, which is exactly how a current-turn\n * \"native tools only\" instruction went missing from the decision it was about.\n *\n * A compaction boundary is not a reason to read nothing: the rows after it are\n * the live context, so the collected messages start again there.\n */\nfunction parseRows(raw: string, scope: RowScope): PacketMessage[] {\n const { sessionId, agentId } = scope;\n let messages: PacketMessage[] = [];\n for (const line of raw.split('\\n')) {\n if (line.trim().length === 0) continue;\n let row: Record<string, unknown>;\n try {\n row = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue; // One unreadable line is one line, not the conversation.\n }\n if (row === null || typeof row !== 'object' || Array.isArray(row)) continue;\n // Everything before the boundary belongs to a context that was summarized\n // away; what follows is the turn in play.\n if (row.type === 'system' && row.subtype === 'compact_boundary') {\n messages = [];\n continue;\n }\n // Never ours to read: another window's rows and a subagent's are skipped\n // rather than allowed to void the file.\n if (typeof row.sessionId === 'string' && row.sessionId !== sessionId) continue;\n // Harness meta rows (a skill body, a command caveat) are not the user's words.\n if (row.isMeta === true) continue;\n // A subagent read admits that one sidechain and nothing else; the harness's\n // own reminders in it are not the task. Every other read admits none.\n if (agentId === undefined ? row.isSidechain === true : !ownSidechainRow(row, agentId)) {\n continue;\n }\n if (row.type !== 'user' && row.type !== 'assistant') continue;\n if (row.sessionId !== sessionId) continue;\n let text: string;\n try {\n text = textOf(row.message);\n } catch {\n continue; // A row this build cannot read contributes nothing, and no more.\n }\n // Nor is what the harness writes back into the user's turn (tenjin-agent#401).\n if (row.type === 'user' && harnessUserRow(row, text)) continue;\n if (text.length > 0) messages.push({ role: row.type, text });\n }\n return messages;\n}\n\n/** Output of a local command, as the harness wraps it into a user row. */\nconst LOCAL_COMMAND_OUTPUT = /^\\s*<local-command-(?:stdout|stderr)>/;\n\n/**\n * A turn the harness or another agent wrote, not the user: a background task\n * finishing, a subagent's hand-back or a teammate's message, a message from\n * another session. It hands work back; it asks for none, and routing it offers\n * a lookup nobody requested. The prompt hook skips these and the transcript\n * reader drops them, from this one list.\n */\nconst HANDBACK_PREFIXES = [\n '<task-notification>',\n '<agent-message',\n '<teammate-message',\n '<cross-session-message',\n 'Another Claude session sent a message',\n];\n\nexport function isHandback(text: string): boolean {\n const trimmed = text.trimStart();\n return HANDBACK_PREFIXES.some((prefix) => trimmed.startsWith(prefix));\n}\n\n/** The `origin.kind` of a user row another agent or the harness wrote. */\nconst HARNESS_ORIGINS = new Set(['task-notification', 'peer']);\n\n/**\n * A `type: \"user\"` row the user never typed. The harness writes these without\n * `isMeta`: a background task finishing (`origin.kind: \"task-notification\"`),\n * a subagent's hand-back or another session's message (`origin.kind: \"peer\"`,\n * text `Another Claude session sent a message:` then `<agent-message …>`), and\n * a local command's output (`<local-command-stdout>`). None is the user's\n * words, and none can become `current`: a hand-back read as this turn put a\n * subagent's report in place of the user's own instruction. A\n * `<command-name>` row stays: that is the command the user did type.\n */\nfunction harnessUserRow(row: Record<string, unknown>, text: string): boolean {\n const origin = row.origin;\n if (\n origin !== null &&\n typeof origin === 'object' &&\n HARNESS_ORIGINS.has((origin as { kind?: unknown }).kind as string)\n ) {\n return true;\n }\n return isHandback(text) || LOCAL_COMMAND_OUTPUT.test(text);\n}\n\nfunction ownSidechainRow(row: Record<string, unknown>, agentId: string): boolean {\n return row.isSidechain === true && row.agentId === agentId && row.isMeta !== true;\n}\n\n/** Ordinary text blocks only; a tool result contributes nothing. */\nfunction textOf(message: unknown): string {\n if (message === null || typeof message !== 'object' || Array.isArray(message)) {\n throw new Error('malformed message');\n }\n const content = (message as { content?: unknown }).content;\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) throw new Error('malformed content');\n const parts: string[] = [];\n for (const part of content) {\n if (\n part === null ||\n typeof part !== 'object' ||\n typeof (part as { type?: unknown }).type !== 'string'\n ) {\n throw new Error('malformed block');\n }\n const block = part as { type: string; text?: unknown };\n if (block.type !== 'text') continue;\n if (typeof block.text !== 'string') throw new Error('malformed text block');\n parts.push(block.text);\n }\n return parts.join('\\n');\n}\n","import type { PacketMessage } from './context';\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** CLI 0.154.0's completed conversation items, not synthetic response_item\n * prompts or tool output. Unknown ownership/compaction means unavailable. */\nexport function parseCodexHistory(raw: string, session: string): PacketMessage[] | null {\n const messages: PacketMessage[] = [];\n const seen = new Set<string>();\n let owned = false;\n for (const line of raw.split('\\n')) {\n if (!line.trim()) continue;\n let row: unknown;\n try {\n row = JSON.parse(line);\n } catch {\n return null;\n }\n if (!record(row) || !record(row.payload)) continue;\n const p = row.payload;\n if (row.type === 'session_meta') {\n if (\n owned ||\n p.id !== session ||\n p.session_id !== session ||\n p.thread_source !== 'user' ||\n p.parent_thread_id != null\n )\n return null;\n owned = true;\n continue;\n }\n if (!owned) return null;\n // Compaction has not been qualified. Never resurrect pre-compaction\n // restrictions or assume that an unrecognized summary is user text.\n if (\n row.type === 'compacted' ||\n p.type === 'context_compacted' ||\n p.type === 'compaction' ||\n p.type === 'compaction_completed'\n )\n return null;\n if (row.type !== 'event_msg' || p.type !== 'item_completed') continue;\n if (p.thread_id !== session || !record(p.item)) return null;\n const item = p.item;\n if (item.type === 'ContextCompaction' || item.type === 'Compaction') return null;\n const user = item.type === 'UserMessage';\n if (!user && !(item.type === 'AgentMessage' && item.phase === 'final_answer')) continue;\n if (typeof item.id !== 'string' || !Array.isArray(item.content)) return null;\n if (seen.has(item.id)) continue;\n seen.add(item.id);\n const text = item.content\n .filter(record)\n .filter((b) => b.type === (user ? 'text' : 'Text') && typeof b.text === 'string')\n .map((b) => b.text as string)\n .join('\\n');\n if (text.trim()) messages.push({ role: user ? 'user' : 'assistant', text });\n }\n return owned && messages.some((m) => m.role === 'user') ? messages : null;\n}\n","import { rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { sha256Hex } from '../lib/hash';\nimport { parseHookResponse, type HookResponse } from './decision';\nimport { DECIDED_PREFIX, sessionDir } from './progress';\nimport { readJsonFile, writePrivate } from './store-files';\n\n/**\n * ONE SEARCH, ONE DECISION. With automatic use on, the swap asks the router\n * about a native search or fetch before the host's pre-call hook runs. When it\n * hands the call back (no `bound` input, a pick outside the automatic scope, a\n * price over the limit), the pre-call hook offers from that same answer\n * instead of asking, and paying for, a second one. The answer is kept here,\n * under the session and the harness's own `tool_use_id`, with the exact\n * search or URL it was made for, its settings hash included; a different\n * target, a stale record or one that does not parse is read as absent.\n *\n * Hook-safe: node, zod (through `decision.ts`) and `store-files.ts` only.\n * Every failure is \"absent\": a lost record costs one more decision, never a\n * wrong one.\n */\n\n/** Long enough for the host to run its pre-call hook after the swap answered. */\nconst DECIDED_TTL_MS = 60_000;\n\n/** The router's answer runs to a few hundred kilobytes at most. */\nconst MAX_DECIDED_BYTES = 1024 * 1024;\n\nfunction decidedPath(dataDir: string, sessionId: string, toolUseId: string): string {\n return join(sessionDir(dataDir, sessionId), `${DECIDED_PREFIX}${sha256Hex(toolUseId)}.json`);\n}\n\n/** What the swap decided for one call. */\nexport interface Decided {\n /** The router's whole answer: null when it gave none. */\n answer: HookResponse | null;\n /** Why the routing fee was not paid, when it was not (`fee_required`, ...). */\n unpaid?: string;\n}\n\n/** Keep the answer the swap got for this call. */\nexport async function keepDecided(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n target: string,\n { answer, unpaid }: Decided,\n now = Date.now(),\n): Promise<void> {\n try {\n await writePrivate(\n decidedPath(dataDir, sessionId, toolUseId),\n JSON.stringify({ version: 1, at: now, target, answer, unpaid }),\n );\n } catch {\n // Lost: the pre-call hook decides again.\n }\n}\n\n/**\n * The answer kept for this call and target, taken once: the record is removed\n * as it is read, so a retry of the same call is decided afresh. `undefined`\n * when none is kept; an `answer` of null is a kept \"the router gave none\".\n */\nexport async function takeDecided(\n dataDir: string,\n sessionId: string,\n toolUseId: string,\n target: string,\n now = Date.now(),\n): Promise<Decided | undefined> {\n const path = decidedPath(dataDir, sessionId, toolUseId);\n const row = await readJsonFile(path, MAX_DECIDED_BYTES);\n if (row === null) return undefined;\n await rm(path, { force: true }).catch(() => undefined);\n if (row.version !== 1 || typeof row.at !== 'number' || row.target !== target) return undefined;\n if (now - row.at > DECIDED_TTL_MS || row.at > now + DECIDED_TTL_MS) return undefined;\n const unpaid = typeof row.unpaid === 'string' ? { unpaid: row.unpaid } : {};\n if (row.answer === null) return { answer: null, ...unpaid };\n const answer = parseHookResponse(row.answer);\n return answer === undefined ? undefined : { answer, ...unpaid };\n}\n","/**\n * WHAT A WEBFETCH RESULT SAYS ABOUT THE PAGE IT READ. WebFetch does not hand\n * back the page: `result` is a small model's answer to the agent's prompt,\n * written from the page's text. So a page that came back as a shell (a\n * JavaScript app's title, a video page's footer) still answers 200 with tens\n * of kilobytes, and the only place that says nothing was there is that\n * answer's own opening.\n *\n * Read deterministically, with no model and no network call, from the opening\n * alone, where the summarizer says what it was given. Every pattern names the\n * WHOLE page as empty or as page furniture only (a title, navigation, a\n * footer) or as needing JavaScript. \"The page does not mention X\" is the page\n * answering, not a shell, and matches nothing here. Over 682 recorded 2xx\n * WebFetch results these match the eight shells among them and nothing else;\n * `fixtures/harness/claude-WebFetch-results.json` keeps those eight and the\n * near misses a looser rule would take.\n */\n\n/** Where the summarizer says what it was given: its first few sentences. */\nconst OPENING_CHARS = 600;\n\n/** The page as a whole, as the summarizer refers to it. */\nconst PAGE = String.raw`(?:web ?page|page|site|content|excerpt)`;\n/** \"only shows\", \"contains only\", and their kin, in either order. */\nconst ONLY = String.raw`(?:only (?:shows?|contains?|includes?|consists? of|has|displays?)|(?:shows?|contains?|includes?|consists? of|has|displays?) only)`;\n/** Page furniture: what every page has and no page is about. A title counts\n * alone, not as the first of \"the title and abstract\". */\nconst FURNITURE = String.raw`(?:navigation|nav (?:bar|links|menu)|footer|legal links|boilerplate|loading (?:screen|spinner|indicator|message)|title\\b(?!\\s*(?:,|and\\b|&)))`;\n/** Within one sentence: no full stop, no line break. */\nconst SAME_SENTENCE = (max: number): string => String.raw`[^.\\n]{0,${max}}?`;\n\nconst EMPTY_PAGE_PATTERNS: readonly RegExp[] = [\n // \"the web page content provided is empty\", \"\\\"Web page content:\\\" appears to be empty\"\n new RegExp(\n String.raw`\\b(?:web ?page|page) content\\b${SAME_SENTENCE(40)}\\b(?:is|was|appears to be|seems to be) (?:entirely |completely )?empty\\b`,\n 'i',\n ),\n // \"I don't see any web page content provided\"\n /\\b(?:don't|do not|can't|cannot) see any (?:web ?page |page )?content\\b/i,\n // \"the webpage content provided only shows YouTube's footer navigation\",\n // \"contains only navigation elements, footer links\", \"only contains a title\"\n new RegExp(\n String.raw`\\b${PAGE}\\b${SAME_SENTENCE(60)}\\b${ONLY}\\b${SAME_SENTENCE(80)}\\b${FURNITURE}`,\n 'i',\n ),\n // \"The only information shown is \\\"Uniswap Interface,\\\" ... a page title or header\"\n new RegExp(\n String.raw`\\bthe only (?:information|content|text|thing)s? (?:shown|present|visible|available|provided|included)\\b${SAME_SENTENCE(120)}\\b${FURNITURE}`,\n 'i',\n ),\n // \"looks like a shell\", \"appears to be an empty app shell\"\n /\\b(?:looks like|appears to be|seems to be|is (?:just|only|merely)) an? (?:(?:empty|javascript|js|html|page|app|application|loading) ){0,2}(?:shell|skeleton)\\b/i,\n // A page that needs the JavaScript the fetch did not run: React's own\n // noscript line is \"You need to enable JavaScript to run this app.\"\n /\\benable JavaScript\\b/i,\n /\\bJavaScript (?:is )?(?:required|disabled|must be enabled)\\b/i,\n new RegExp(String.raw`\\b${PAGE}\\b${SAME_SENTENCE(60)}\\b(?:requires?|needs?) JavaScript\\b`, 'i'),\n // PyPI's script-less fallback: \"A required part of this site couldn't load\".\n /\\b(?:site|page) (?:couldn't|could not) load\\b/i,\n];\n\n/**\n * True when the summarizer says the page it was given had no main content:\n * empty, only a title, navigation or footer, or a script-rendered shell.\n */\nexport function readsAsEmptyPage(result: string): boolean {\n const opening = result.slice(0, OPENING_CHARS);\n return EMPTY_PAGE_PATTERNS.some((pattern) => pattern.test(opening));\n}\n\n/**\n * The note Claude Code appends as the result's last line when the body was\n * binary: `[Binary content (application/pdf, 2.1MB) also saved to <path>]`.\n */\nconst SAVED_PDF_RE =\n /\\n\\[Binary content \\(application\\/pdf, [^)\\n]{1,24}\\) also saved to ([^\\]\\n]+)\\]\\s*$/;\n/** How WebFetch names the file it saved, in `<session id>/tool-results`. */\nconst SAVED_PDF_NAME_RE = /[\\\\/]([^\\\\/]+)[\\\\/]tool-results[\\\\/]webfetch-\\d+-[a-z0-9]+\\.pdf$/i;\nconst PARENT_SEGMENT_RE = /(?:^|[\\\\/])\\.\\.(?:[\\\\/]|$)/;\n\n/**\n * Where WebFetch saved the PDF it fetched, or null. Its summary cannot read a\n * PDF (it is handed the compressed bytes: arxiv.org/pdf/1706.03762 came back\n * as \"a corrupted or binary PDF file that I cannot parse\"), but the file it\n * saved is whole, and `Read` parses its pages for free.\n *\n * Trusted only as the result's LAST line, only for a file named the way\n * WebFetch names one, and only in this session's own `tool-results`, so a\n * summary quoting a page that says otherwise cannot point the agent at any\n * other file, another session's included.\n */\nexport function savedPdfOf(result: string, sessionId: string): string | null {\n const path = SAVED_PDF_RE.exec(result)?.[1];\n if (path === undefined || PARENT_SEGMENT_RE.test(path)) return null;\n return SAVED_PDF_NAME_RE.exec(path)?.[1] === sessionId ? path : null;\n}\n","import { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { pathExists, projectRoot } from '../lib/settings';\nimport type { Packet } from './context';\nimport type { Harness } from './names';\n\n/**\n * THE USER'S OWN LINKS, which the host opens with its own tools: a pull\n * request on the forge this repository pushes to, a claude.ai artifact. A\n * paid page reader is not the answer to one, so the packet names them\n * (`ownUrls`) for the server's gate to keep page reading off them.\n *\n * Two sources. The hosts of the git remotes of the repository the hook's\n * working directory is in, read from its git config file and nothing else (no\n * `git` process): an ssh alias or an `insteadOf` rewrite is not resolved, and\n * a repository with no remote has none. And the harness's own link hosts:\n * claude.ai for Claude Code. Codex has none listed: no host is clearly its own\n * and open to its own tools.\n *\n * READ ONLY WHEN THE TURN HAS A LINK, and silent on any failure: a turn with\n * no literal URL costs nothing, and one that cannot be read names none.\n */\n\nconst HARNESS_HOSTS: Record<Harness, readonly string[]> = { claude: ['claude.ai'], codex: [] };\n\n/** Past this a git config is not one this reader trusts to be small. */\nconst MAX_CONFIG_BYTES = 64 * 1024;\n\n/** The hosts `seal` lists links on in `ownUrls`, for this packet. */\nexport async function ownHostsFor(\n packet: Packet,\n cwd: string,\n harness: Harness,\n homeDir: string = homedir(),\n): Promise<string[]> {\n if (packet.literalUrls.length === 0) return [];\n return [...(await remoteHosts(cwd, homeDir)), ...HARNESS_HOSTS[harness]];\n}\n\n/** The hosts of every remote of the repository `cwd` is in; none outside one. Never throws. */\nexport async function remoteHosts(cwd: string, homeDir: string = homedir()): Promise<string[]> {\n try {\n const root = await projectRoot(cwd, homeDir);\n const dotGit = join(root, '.git');\n if (!(await pathExists(dotGit))) return [];\n const path = await configPath(dotGit);\n if ((await stat(path)).size > MAX_CONFIG_BYTES) return [];\n return remoteHostsIn(await readFile(path, 'utf8'));\n } catch {\n return [];\n }\n}\n\n/**\n * The config file behind a `.git`: in it for a checkout, and for a linked\n * worktree or a submodule (a `.git` file naming its gitdir) in the shared\n * repository its `commondir` names, else in that gitdir.\n */\nasync function configPath(dotGit: string): Promise<string> {\n if ((await stat(dotGit)).isDirectory()) return join(dotGit, 'config');\n const line = /^gitdir:\\s*(.+?)\\s*$/m.exec(await readFile(dotGit, 'utf8'));\n if (line === null) throw new Error('not a gitdir file');\n const gitdir = resolve(dotGit, '..', line[1]!);\n const common = await readFile(join(gitdir, 'commondir'), 'utf8').then(\n (text) => resolve(gitdir, text.trim()),\n () => gitdir,\n );\n return join(common, 'config');\n}\n\n/** Each `url` under a `[remote \"…\"]` section, as the host it names. */\nexport function remoteHostsIn(config: string): string[] {\n const hosts = new Set<string>();\n let inRemote = false;\n for (const raw of config.split('\\n')) {\n const line = raw.trim();\n if (line.startsWith('[')) {\n inRemote = /^\\[remote\\s+\"[^\"]*\"\\]$/.test(line);\n continue;\n }\n const url = inRemote ? /^url\\s*=\\s*\"?([^\"]+?)\"?\\s*$/.exec(line)?.[1] : undefined;\n const host = url === undefined ? null : hostOfRemote(url);\n if (host !== null) hosts.add(host);\n }\n return [...hosts];\n}\n\n/** `scheme://[user@]host[:port]/path`, or git's scp form `[user@]host:path`. */\nfunction hostOfRemote(remote: string): string | null {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(remote)) {\n try {\n const host = new URL(remote).hostname.toLowerCase();\n return host.length > 0 ? host : null;\n } catch {\n return null;\n }\n }\n const scp = /^(?:[^@/]+@)?([^:/\\\\]+):(?!\\/\\/)/.exec(remote);\n return scp?.[1] !== undefined && scp[1].includes('.') ? scp[1].toLowerCase() : null;\n}\n","import {\n runAnswerHook,\n runAskHook,\n runDelegationHook,\n runNativeHook,\n runPromptHook,\n runShortfallHook,\n type HookDeps,\n} from './hooks';\nimport type { Io } from '../lib/output';\nimport { sessionServedByPlugin } from './alive';\nimport type { HookKind } from './hook-tool';\nimport { launchedByPlugin } from './names';\nimport { firstNoticeFor, noticeFor, settleCurrent } from './notice-markers';\nimport { WALLET_UNLOCKED } from './wallet-reasons';\n\n/**\n * `tenjin hook prompt`, `native`, `shortfall`, `agent`, `ask` and `answer`:\n * THE COMMAND FORM, KEPT AS A STUB. Both plugins route through the `hook`\n * tool of `tenjin mcp` ({@link runHookKind}), the one process that holds the\n * wallet and pays the routing fee every routing call costs. A command entry\n * is a hand-written one, a settings install's or a plugin copy from an older\n * build, which cannot pay, so it routes nothing: it tells the person once per\n * session to ask their agent to set Tenjin up again, in the `systemMessage`\n * the harness shows them (Codex too), and says nothing after that, nor in a\n * Claude Code session the plugin serves. Deleting the commands would leave\n * such a setup failing silently.\n *\n * The harness writes its event on stdin and reads a JSON object (or nothing)\n * from stdout, so these commands bypass the CLI's envelope entirely. They\n * never fail the turn: a stdin that never arrives, an unreadable event or a\n * failure all exit 0 with an empty stdout, which the harness reads as \"no\n * opinion\".\n */\n\nconst MAX_EVENT_BYTES = 1_000_000;\n/** The stub's wait for its event: the harness writes it at once, so this is\n * a liveness check, and the stub calls nothing after it. */\nconst STDIN_TIMEOUT_MS = 1_000;\n\nexport type { HookKind };\n\n/** What a command entry says, once per session. The person is never handed a\n * command: their agent runs install, which names a Claude Code update first\n * where the plugin needs one (a settings install below 2.1.287 is kept). */\nexport const STALE_HOOK_LINE =\n \"Tenjin's hooks in this setup are from an older version and no longer route; your usual tools still work. \" +\n 'Ask your agent to set Tenjin up again, updating Claude Code or Codex first if Tenjin needs a newer one.';\n\nexport interface HookCommandDeps extends Pick<HookDeps, 'dataDir' | 'harness' | 'now'> {\n /** Test seam for the harness event; production reads stdin. */\n readEvent?: () => Promise<string>;\n /** Test seam for this process's environment. */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runHookCommand(io: Io, deps: HookCommandDeps): Promise<void> {\n let response: unknown = null;\n try {\n const event = JSON.parse(await (deps.readEvent ?? readStdin)()) as unknown;\n // An entry an older settings install wrote stays silent in a session the\n // plugin serves (see `alive.ts`). SHIM: goes on or after 2026-12-01.\n if (\n deps.harness !== 'codex' &&\n !launchedByPlugin(deps.env) &&\n (await sessionServedByPlugin(deps.dataDir, event))\n ) {\n return;\n }\n const sessionId = sessionIdOf(event);\n if (sessionId === null) return;\n // The session's once-per-session marker under `router/notices/`, which\n // builds up to alpha.31 also wrote for their unpaid-fee notice: a session\n // one of those told already hears nothing more. It leaves the reason told\n // last (`noticeFor`'s `.current`) to the wallet notices that read it.\n if (await firstNoticeFor(deps.dataDir, sessionId, deps.now?.() ?? Date.now())) {\n response = { systemMessage: STALE_HOOK_LINE };\n }\n } catch {\n response = null;\n }\n if (response !== null) io.stdout.write(`${JSON.stringify(response)}\\n`);\n}\n\n/** A session id as the hook schemas take one: a string of 1 to 200 characters. */\nfunction sessionIdOf(event: unknown): string | null {\n if (event === null || typeof event !== 'object') return null;\n const id = (event as { session_id?: unknown }).session_id;\n return typeof id === 'string' && id.length > 0 && id.length <= 200 ? id : null;\n}\n\n/**\n * ONE HOOK EVENT, by kind, to its handler; the harness's answer or null. The\n * `hook` tool of `tenjin mcp` runs it for each routing leg.\n *\n * THE ROUTER'S WALLET NEWS (B2, decision 14). Inside `tenjin mcp`,\n * {@link HookDeps.walletNews} hands this leg the one-time wallet lines\n * (\"Tenjin wallet unlocked.\", a still-locked line, a wrong-variable warning),\n * and only for an event carrying a session id: that call is what marks the\n * router as serving a session, and a leg without one must not. The lines ride in `systemMessage` beside the\n * leg's own notices, and are acknowledged only once the response carrying them\n * is built: a leg that throws releases them instead of acking, so the next\n * leg offers them again rather than losing them. A leg running at the same\n * time is never handed lines another leg holds.\n */\nexport async function runHookKind(\n kind: HookKind,\n event: unknown,\n hookDeps: HookDeps,\n): Promise<unknown | null> {\n const notices = new Set<string>();\n const deps: HookDeps = { ...hookDeps, notice: (line) => notices.add(line) };\n const sessionId = sessionIdOf(event);\n const news =\n sessionId !== null && hookDeps.walletNews !== undefined\n ? await hookDeps.walletNews(sessionId).catch(() => null)\n : null;\n for (const line of news?.lines ?? []) notices.add(line);\n let response: unknown | null;\n try {\n if (sessionId !== null && news?.lines.includes(WALLET_UNLOCKED) === true) {\n // Said here already: a paid call later in this session must not say it\n // again, and a relapse must be told again.\n await settleCurrent(hookDeps.dataDir, sessionId, hookDeps.now?.() ?? Date.now()).catch(\n () => undefined,\n );\n }\n if (sessionId !== null && news?.told !== undefined) {\n // The still-locked line is this session's notice for that reason: the\n // fee notice on this leg (or a later one) must not repeat it.\n await noticeFor(hookDeps.dataDir, sessionId, news.told, hookDeps.now?.() ?? Date.now()).catch(\n () => undefined,\n );\n }\n const outcome =\n kind === 'prompt'\n ? await runPromptHook(event, deps)\n : kind === 'native'\n ? await runNativeHook(event, deps)\n : kind === 'shortfall'\n ? await runShortfallHook(event, deps)\n : kind === 'ask'\n ? await runAskHook(event, deps)\n : kind === 'answer'\n ? await runAnswerHook(event, deps)\n : await runDelegationHook(event, deps);\n response = withNotices(outcome.response, notices);\n } catch (err) {\n // No answer carries the lines: the next leg is offered them again.\n news?.release();\n throw err;\n }\n if (news !== null) await news.ack().catch(() => undefined);\n return response;\n}\n\n/** The handler's answer with this leg's notices in `systemMessage`, which the\n * harness shows to the user whatever the event; the answer alone when none. */\nfunction withNotices(response: unknown, notices: Set<string>): unknown | null {\n if (notices.size === 0) return response;\n const systemMessage = [...notices].join('\\n');\n return response === null || typeof response !== 'object'\n ? { systemMessage }\n : { ...response, systemMessage };\n}\n\nasync function readStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n const timer = setTimeout(() => reject(new Error('no harness event')), STDIN_TIMEOUT_MS);\n const done = (value: string): void => {\n clearTimeout(timer);\n resolve(value);\n };\n process.stdin.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (size > MAX_EVENT_BYTES) {\n clearTimeout(timer);\n reject(new Error('harness event too large'));\n return;\n }\n chunks.push(chunk);\n });\n process.stdin.once('end', () => done(Buffer.concat(chunks).toString('utf8')));\n process.stdin.once('error', () => {\n clearTimeout(timer);\n reject(new Error('harness event unreadable'));\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAAA,gBAAe;;;ACAxB,SAAS,YAAY;AACrB,SAAS,YAAY;AACrB,SAAS,SAAS,YAAY;;;ACA9B,SAAS,OAAO,OAAkD;AAChE,SAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAIO,SAAS,kBAAkB,KAAa,SAAyC;AACtF,QAAM,WAA4B,CAAC;AACnC,QAAM,OAAO,oBAAI,IAAY;AAC7B,MAAI,QAAQ;AACZ,aAAW,QAAQ,IAAI,MAAM,IAAI,GAAG;AAClC,QAAI,CAAC,KAAK,KAAK,EAAG;AAClB,QAAI;AACJ,QAAI;AACF,YAAM,KAAK,MAAM,IAAI;AAAA,IACvB,QAAQ;AACN,aAAO;AAAA,IACT;AACA,QAAI,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,IAAI,OAAO,EAAG;AAC1C,UAAM,IAAI,IAAI;AACd,QAAI,IAAI,SAAS,gBAAgB;AAC/B,UACE,SACA,EAAE,OAAO,WACT,EAAE,eAAe,WACjB,EAAE,kBAAkB,UACpB,EAAE,oBAAoB;AAEtB,eAAO;AACT,cAAQ;AACR;AAAA,IACF;AACA,QAAI,CAAC,MAAO,QAAO;AAGnB,QACE,IAAI,SAAS,eACb,EAAE,SAAS,uBACX,EAAE,SAAS,gBACX,EAAE,SAAS;AAEX,aAAO;AACT,QAAI,IAAI,SAAS,eAAe,EAAE,SAAS,iBAAkB;AAC7D,QAAI,EAAE,cAAc,WAAW,CAAC,OAAO,EAAE,IAAI,EAAG,QAAO;AACvD,UAAM,OAAO,EAAE;AACf,QAAI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AmB,SAAsC;AAC5E,MAAI,QAAQ,SAAS,EAAG,QAAO;AAC/B,QAAM,gBAAgB,CAAC,GAAG,OAAO,EAAE,KAAK,IAAI;AAC5C,SAAO,aAAa,QAAQ,OAAO,aAAa,WAC5C,EAAE,cAAc,IAChB,EAAE,GAAG,UAAU,cAAc;AACnC;AAEA,eAAe,YAA6B;AAC1C,SAAO,IAAI,QAAQ,CAACC,UAAS,WAAW;AACtC,UAAM,SAAmB,CAAC;AAC1B,QAAI,OAAO;AACX,UAAM,QAAQ,WAAW,MAAM,OAAO,IAAI,MAAM,kBAAkB,CAAC,GAAG,gBAAgB;AACtF,UAAM,OAAO,CAAC,UAAwB;AACpC,mBAAa,KAAK;AAClB,MAAAA,SAAQ,KAAK;AAAA,IACf;AACA,YAAQ,MAAM,GAAG,QAAQ,CAAC,UAAkB;AAC1C,cAAQ,MAAM;AACd,UAAI,OAAO,iBAAiB;AAC1B,qBAAa,KAAK;AAClB,eAAO,IAAI,MAAM,yBAAyB,CAAC;AAC3C;AAAA,MACF;AACA,aAAO,KAAK,KAAK;AAAA,IACnB,CAAC;AACD,YAAQ,MAAM,KAAK,OAAO,MAAM,KAAK,OAAO,OAAO,MAAM,EAAE,SAAS,MAAM,CAAC,CAAC;AAC5E,YAAQ,MAAM,KAAK,SAAS,MAAM;AAChC,mBAAa,KAAK;AAClB,aAAO,IAAI,MAAM,0BAA0B,CAAC;AAAA,IAC9C,CAAC;AAAA,EACH,CAAC;AACH;","names":["homedir","open","stat","join","join","join","join","homedir","footer","resolve"]}
|
|
@@ -1,22 +1,60 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
isNewer,
|
|
4
|
-
parseVersion
|
|
5
|
-
} from "./chunk-EDJWHDDL.js";
|
|
6
2
|
import {
|
|
7
3
|
defaultDataDir,
|
|
4
|
+
isDefaultDataDir,
|
|
8
5
|
runtimeDir
|
|
9
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-JTX3BUDK.js";
|
|
10
7
|
|
|
11
8
|
// src/lib/runtime-layout.ts
|
|
12
9
|
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
13
10
|
import { homedir } from "node:os";
|
|
14
11
|
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
15
12
|
import { fileURLToPath } from "node:url";
|
|
13
|
+
|
|
14
|
+
// src/lib/version-order.ts
|
|
15
|
+
var VERSION_RE = /^(\d+)\.(\d+)\.(\d+)(?:-alpha\.(\d+))?$/;
|
|
16
|
+
function parseVersion(raw) {
|
|
17
|
+
const m = VERSION_RE.exec(raw);
|
|
18
|
+
if (m === null) return null;
|
|
19
|
+
const [, major, minor, patch, alpha] = m;
|
|
20
|
+
if (major === void 0 || minor === void 0 || patch === void 0) return null;
|
|
21
|
+
return {
|
|
22
|
+
major: Number(major),
|
|
23
|
+
minor: Number(minor),
|
|
24
|
+
patch: Number(patch),
|
|
25
|
+
alpha: alpha !== void 0 ? Number(alpha) : null
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function isNewer(candidate, current) {
|
|
29
|
+
const a = parseVersion(candidate);
|
|
30
|
+
const b = parseVersion(current);
|
|
31
|
+
if (a === null || b === null) return false;
|
|
32
|
+
if (a.major !== b.major) return a.major > b.major;
|
|
33
|
+
if (a.minor !== b.minor) return a.minor > b.minor;
|
|
34
|
+
if (a.patch !== b.patch) return a.patch > b.patch;
|
|
35
|
+
if (a.alpha === null) return b.alpha !== null;
|
|
36
|
+
if (b.alpha === null) return false;
|
|
37
|
+
return a.alpha > b.alpha;
|
|
38
|
+
}
|
|
39
|
+
function atLeast(version, floor) {
|
|
40
|
+
const parts = (v) => (v.split(/[-+]/)[0] ?? "").split(".").map((n) => Number.parseInt(n, 10));
|
|
41
|
+
const have = parts(version);
|
|
42
|
+
for (const [i, least] of parts(floor).entries()) {
|
|
43
|
+
const part = have[i] ?? 0;
|
|
44
|
+
if (!Number.isFinite(part)) return false;
|
|
45
|
+
if (part !== least) return part > least;
|
|
46
|
+
}
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/lib/runtime-layout.ts
|
|
16
51
|
var NODE_VERSION_RE = /^\d+\.\d+\.\d+$/;
|
|
17
52
|
function runtimeStatePath(root) {
|
|
18
53
|
return join(root, "state.json");
|
|
19
54
|
}
|
|
55
|
+
function hasRuntime(dataDir, home) {
|
|
56
|
+
return isDefaultDataDir(dataDir, home) && existsSync(runtimeStatePath(runtimeDir(dataDir)));
|
|
57
|
+
}
|
|
20
58
|
function pointer(raw) {
|
|
21
59
|
if (typeof raw !== "object" || raw === null) return null;
|
|
22
60
|
const { cli, node } = raw;
|
|
@@ -101,7 +139,11 @@ function markLive(moduleDir, pid = process.pid) {
|
|
|
101
139
|
}
|
|
102
140
|
|
|
103
141
|
export {
|
|
142
|
+
parseVersion,
|
|
143
|
+
isNewer,
|
|
144
|
+
atLeast,
|
|
104
145
|
runtimeStatePath,
|
|
146
|
+
hasRuntime,
|
|
105
147
|
readRuntimeState,
|
|
106
148
|
nodeBinPath,
|
|
107
149
|
versionDir,
|
|
@@ -110,4 +152,4 @@ export {
|
|
|
110
152
|
handoffTarget,
|
|
111
153
|
markLive
|
|
112
154
|
};
|
|
113
|
-
//# sourceMappingURL=chunk-
|
|
155
|
+
//# sourceMappingURL=chunk-5N4GGUBN.js.map
|