tenjin-cli 0.1.0-alpha.15 → 0.1.0-alpha.17

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.
Files changed (278) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +43 -310
  3. package/dist/{_esm-N4KAVXQR.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/{ccip-ZGGWQN4X.js → ccip-7RMRLAGV.js} +4 -4
  5. package/dist/{ccip-RPPPKTJR.js → ccip-NLCSCHKI.js} +5 -5
  6. package/dist/chunk-2BKS2FVE.js +93 -0
  7. package/dist/chunk-2BKS2FVE.js.map +1 -0
  8. package/dist/chunk-2G2WLVHB.js +102 -0
  9. package/dist/chunk-2G2WLVHB.js.map +1 -0
  10. package/dist/chunk-2I4QTOLB.js +11 -0
  11. package/dist/chunk-2I4QTOLB.js.map +1 -0
  12. package/dist/chunk-2JGT3KDW.js +172 -0
  13. package/dist/chunk-2JGT3KDW.js.map +1 -0
  14. package/dist/chunk-2QYORQBF.js +55 -0
  15. package/dist/chunk-2QYORQBF.js.map +1 -0
  16. package/dist/chunk-35M3VITA.js +102 -0
  17. package/dist/chunk-35M3VITA.js.map +1 -0
  18. package/dist/{chunk-KINZ23CV.js → chunk-3AUDA53C.js} +4740 -23
  19. package/dist/chunk-3AUDA53C.js.map +1 -0
  20. package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
  21. package/dist/chunk-56MOAIP5.js.map +1 -0
  22. package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
  23. package/dist/chunk-5QHHRMRA.js +227 -0
  24. package/dist/chunk-5QHHRMRA.js.map +1 -0
  25. package/dist/{chunk-JBIKAAT3.js → chunk-5UDD5VSY.js} +8 -8
  26. package/dist/chunk-5UDD5VSY.js.map +1 -0
  27. package/dist/chunk-7QKHZQKW.js +1680 -0
  28. package/dist/chunk-7QKHZQKW.js.map +1 -0
  29. package/dist/{chunk-ZFJJ3EXC.js → chunk-AR7U7BRG.js} +550 -182
  30. package/dist/chunk-AR7U7BRG.js.map +1 -0
  31. package/dist/chunk-AUKDYPPX.js +130 -0
  32. package/dist/chunk-AUKDYPPX.js.map +1 -0
  33. package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
  34. package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
  35. package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
  36. package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
  37. package/dist/chunk-EGELTSPU.js.map +1 -0
  38. package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-J5INH7WB.js +299 -0
  40. package/dist/chunk-J5INH7WB.js.map +1 -0
  41. package/dist/chunk-JLEF5WHM.js +132 -0
  42. package/dist/chunk-JLEF5WHM.js.map +1 -0
  43. package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
  44. package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
  45. package/dist/chunk-KK4YGYTV.js +808 -0
  46. package/dist/chunk-KK4YGYTV.js.map +1 -0
  47. package/dist/{chunk-CPCX67TI.js → chunk-KUBEYXSO.js} +1076 -1038
  48. package/dist/chunk-KUBEYXSO.js.map +1 -0
  49. package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
  50. package/dist/{chunk-NIKXHWOL.js → chunk-LJ4DMVFI.js} +16 -16
  51. package/dist/chunk-LJ4DMVFI.js.map +1 -0
  52. package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
  53. package/dist/chunk-MEFB5KHA.js.map +1 -0
  54. package/dist/{chunk-HPJGOLTN.js → chunk-MRGADYDD.js} +13 -8
  55. package/dist/chunk-MRGADYDD.js.map +1 -0
  56. package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
  57. package/dist/chunk-N35E6CM2.js.map +1 -0
  58. package/dist/chunk-O4ZNKFRU.js +366 -0
  59. package/dist/chunk-O4ZNKFRU.js.map +1 -0
  60. package/dist/chunk-PDA2BVFY.js +244 -0
  61. package/dist/chunk-PDA2BVFY.js.map +1 -0
  62. package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
  63. package/dist/chunk-QDD2RN7G.js +10238 -0
  64. package/dist/chunk-QDD2RN7G.js.map +1 -0
  65. package/dist/chunk-S2NRVRPF.js +171 -0
  66. package/dist/chunk-S2NRVRPF.js.map +1 -0
  67. package/dist/chunk-TGLKKLQG.js +11 -0
  68. package/dist/chunk-TGLKKLQG.js.map +1 -0
  69. package/dist/chunk-TP4D47BY.js +127 -0
  70. package/dist/chunk-TP4D47BY.js.map +1 -0
  71. package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
  72. package/dist/{chunk-UO22YNY4.js → chunk-U2DZISAH.js} +43 -1
  73. package/dist/chunk-U2DZISAH.js.map +1 -0
  74. package/dist/chunk-WGQVJM56.js +165 -0
  75. package/dist/chunk-WGQVJM56.js.map +1 -0
  76. package/dist/{chunk-OLWTRUTS.js → chunk-WLMJE3GJ.js} +35 -16
  77. package/dist/chunk-WLMJE3GJ.js.map +1 -0
  78. package/dist/chunk-WS4JA6TC.js +137 -0
  79. package/dist/chunk-WS4JA6TC.js.map +1 -0
  80. package/dist/chunk-WXC57XGG.js +29 -0
  81. package/dist/chunk-WXC57XGG.js.map +1 -0
  82. package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
  83. package/dist/chunk-XZOEUYMX.js +1784 -0
  84. package/dist/chunk-XZOEUYMX.js.map +1 -0
  85. package/dist/{cli-KKRKBU5T.js → cli-VHYYYYXM.js} +303 -374
  86. package/dist/cli-VHYYYYXM.js.map +1 -0
  87. package/dist/config-5ADBAAXU.js +42 -0
  88. package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
  89. package/dist/doctor-Q35VQW3S.js +436 -0
  90. package/dist/doctor-Q35VQW3S.js.map +1 -0
  91. package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  92. package/dist/{chunk-KAJZHIQ4.js → fund-GDDPL2BB.js} +81 -24
  93. package/dist/fund-GDDPL2BB.js.map +1 -0
  94. package/dist/hook-command-PBERPRE3.js +763 -0
  95. package/dist/hook-command-PBERPRE3.js.map +1 -0
  96. package/dist/index.js +8 -3
  97. package/dist/index.js.map +1 -1
  98. package/dist/install-OKDKGUXM.js +60 -0
  99. package/dist/install-wallet-SI4LZ73K.js +106 -0
  100. package/dist/install-wallet-SI4LZ73K.js.map +1 -0
  101. package/dist/{run-XYTQ5TWQ.js → mcp-XX3WRQEZ.js} +3766 -10677
  102. package/dist/mcp-XX3WRQEZ.js.map +1 -0
  103. package/dist/paths-P2N4JTDZ.js +49 -0
  104. package/dist/pay-3SYKHKWJ.js +39 -0
  105. package/dist/redact-6W23GGJC.js +15 -0
  106. package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
  107. package/dist/{send-G746D7PQ.js → send-LQRKTEJT.js} +29 -29
  108. package/dist/send-LQRKTEJT.js.map +1 -0
  109. package/dist/{chunk-QZ6ROAJU.js → skill-placement-JMDPSKE6.js} +155 -10
  110. package/dist/skill-placement-JMDPSKE6.js.map +1 -0
  111. package/dist/status-FFC6FO72.js +64 -0
  112. package/dist/status-FFC6FO72.js.map +1 -0
  113. package/dist/status-line-SAXSU6CR.js +87 -0
  114. package/dist/status-line-SAXSU6CR.js.map +1 -0
  115. package/dist/status-line-wiring-L2WYIYBM.js +29 -0
  116. package/dist/tenjin-daemon.mjs +20421 -0
  117. package/dist/tenjin-shim.mjs +251 -0
  118. package/dist/tenjin-vitest-reporter.mjs +49 -0
  119. package/dist/uninstall-OACH27UV.js +147 -0
  120. package/dist/uninstall-OACH27UV.js.map +1 -0
  121. package/dist/{update-R76LHOZW.js → update-4W6EKLGZ.js} +132 -16
  122. package/dist/update-4W6EKLGZ.js.map +1 -0
  123. package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  124. package/dist/wallet-BMEXRR3P.js +32 -0
  125. package/dist/wallet-kdf-worker.mjs +980 -0
  126. package/docs/agent-permissions.md +71 -352
  127. package/docs/safety-model.md +16 -6
  128. package/package.json +8 -7
  129. package/LICENSE +0 -21
  130. package/dist/buy-VIRNSYGN.js +0 -47
  131. package/dist/chunk-2MYQN7HM.js +0 -247
  132. package/dist/chunk-2MYQN7HM.js.map +0 -1
  133. package/dist/chunk-2RF2GIJQ.js +0 -1188
  134. package/dist/chunk-2RF2GIJQ.js.map +0 -1
  135. package/dist/chunk-3GL2Z5QK.js +0 -57
  136. package/dist/chunk-3GL2Z5QK.js.map +0 -1
  137. package/dist/chunk-47PP7TAG.js.map +0 -1
  138. package/dist/chunk-4CQIDQOT.js +0 -167
  139. package/dist/chunk-4CQIDQOT.js.map +0 -1
  140. package/dist/chunk-4KG27W2S.js +0 -614
  141. package/dist/chunk-4KG27W2S.js.map +0 -1
  142. package/dist/chunk-5QQTYWEU.js +0 -199
  143. package/dist/chunk-5QQTYWEU.js.map +0 -1
  144. package/dist/chunk-65DTCCJ7.js +0 -21
  145. package/dist/chunk-65DTCCJ7.js.map +0 -1
  146. package/dist/chunk-A5DKHMUN.js +0 -173
  147. package/dist/chunk-A5DKHMUN.js.map +0 -1
  148. package/dist/chunk-B63XPWQ4.js +0 -246
  149. package/dist/chunk-B63XPWQ4.js.map +0 -1
  150. package/dist/chunk-CAR6FHK6.js +0 -105
  151. package/dist/chunk-CAR6FHK6.js.map +0 -1
  152. package/dist/chunk-CPCX67TI.js.map +0 -1
  153. package/dist/chunk-CQBVCYI2.js +0 -162
  154. package/dist/chunk-CQBVCYI2.js.map +0 -1
  155. package/dist/chunk-DBU5CXBV.js +0 -4731
  156. package/dist/chunk-DBU5CXBV.js.map +0 -1
  157. package/dist/chunk-DHJD77OW.js +0 -81
  158. package/dist/chunk-DHJD77OW.js.map +0 -1
  159. package/dist/chunk-EDZSNPE5.js +0 -35
  160. package/dist/chunk-EDZSNPE5.js.map +0 -1
  161. package/dist/chunk-EFWZPUTC.js +0 -65
  162. package/dist/chunk-EFWZPUTC.js.map +0 -1
  163. package/dist/chunk-EPFL6CTE.js +0 -448
  164. package/dist/chunk-EPFL6CTE.js.map +0 -1
  165. package/dist/chunk-GHLVXVZD.js +0 -142
  166. package/dist/chunk-GHLVXVZD.js.map +0 -1
  167. package/dist/chunk-H3SOOJ2I.js +0 -580
  168. package/dist/chunk-H3SOOJ2I.js.map +0 -1
  169. package/dist/chunk-HPJGOLTN.js.map +0 -1
  170. package/dist/chunk-HRGBS2PA.js +0 -203
  171. package/dist/chunk-HRGBS2PA.js.map +0 -1
  172. package/dist/chunk-ITUXPJIS.js +0 -314
  173. package/dist/chunk-ITUXPJIS.js.map +0 -1
  174. package/dist/chunk-JBIKAAT3.js.map +0 -1
  175. package/dist/chunk-KAJZHIQ4.js.map +0 -1
  176. package/dist/chunk-KINZ23CV.js.map +0 -1
  177. package/dist/chunk-LRYV3SK7.js +0 -235
  178. package/dist/chunk-LRYV3SK7.js.map +0 -1
  179. package/dist/chunk-M2O56UK7.js.map +0 -1
  180. package/dist/chunk-MJZZTKCC.js.map +0 -1
  181. package/dist/chunk-NIKXHWOL.js.map +0 -1
  182. package/dist/chunk-OKDRDT74.js +0 -209
  183. package/dist/chunk-OKDRDT74.js.map +0 -1
  184. package/dist/chunk-OKYSNAS3.js +0 -2144
  185. package/dist/chunk-OKYSNAS3.js.map +0 -1
  186. package/dist/chunk-OLWTRUTS.js.map +0 -1
  187. package/dist/chunk-QQ6ELLSA.js +0 -143
  188. package/dist/chunk-QQ6ELLSA.js.map +0 -1
  189. package/dist/chunk-QZ6ROAJU.js.map +0 -1
  190. package/dist/chunk-R7RSCBI7.js +0 -794
  191. package/dist/chunk-R7RSCBI7.js.map +0 -1
  192. package/dist/chunk-SGK2B724.js +0 -67
  193. package/dist/chunk-SGK2B724.js.map +0 -1
  194. package/dist/chunk-U6VPKMGC.js +0 -390
  195. package/dist/chunk-U6VPKMGC.js.map +0 -1
  196. package/dist/chunk-UHTVXQ2O.js +0 -140
  197. package/dist/chunk-UHTVXQ2O.js.map +0 -1
  198. package/dist/chunk-UO22YNY4.js.map +0 -1
  199. package/dist/chunk-US456VUI.js +0 -149
  200. package/dist/chunk-US456VUI.js.map +0 -1
  201. package/dist/chunk-V44J2MXV.js +0 -400
  202. package/dist/chunk-V44J2MXV.js.map +0 -1
  203. package/dist/chunk-VJQKL3YH.js +0 -216
  204. package/dist/chunk-VJQKL3YH.js.map +0 -1
  205. package/dist/chunk-VJSQSLBM.js +0 -1442
  206. package/dist/chunk-VJSQSLBM.js.map +0 -1
  207. package/dist/chunk-VYOJOX4Z.js +0 -165
  208. package/dist/chunk-VYOJOX4Z.js.map +0 -1
  209. package/dist/chunk-WY2K35OL.js +0 -269
  210. package/dist/chunk-WY2K35OL.js.map +0 -1
  211. package/dist/chunk-ZFJJ3EXC.js.map +0 -1
  212. package/dist/chunk-ZOBNS7CX.js.map +0 -1
  213. package/dist/cli-KKRKBU5T.js.map +0 -1
  214. package/dist/config-JMRUNYE6.js +0 -37
  215. package/dist/discover-B5HF6SHM.js +0 -102
  216. package/dist/discover-B5HF6SHM.js.map +0 -1
  217. package/dist/doctor-ZBG7X66D.js +0 -32
  218. package/dist/edit-PZJIILQE.js +0 -40
  219. package/dist/fund-EUDH5KPA.js +0 -40
  220. package/dist/inspect-QC6WEQPN.js +0 -37
  221. package/dist/install-GNK2W3PI.js +0 -972
  222. package/dist/install-GNK2W3PI.js.map +0 -1
  223. package/dist/outcome-KSGWZHUS.js +0 -24
  224. package/dist/pay-BC4UICPA.js +0 -361
  225. package/dist/pay-BC4UICPA.js.map +0 -1
  226. package/dist/publish-LXWFDIKF.js +0 -42
  227. package/dist/read-JMNUQ56P.js +0 -160
  228. package/dist/read-JMNUQ56P.js.map +0 -1
  229. package/dist/run-XYTQ5TWQ.js.map +0 -1
  230. package/dist/search-TSQAB45E.js +0 -25
  231. package/dist/secp256k1-XRPVBC6V.js.map +0 -1
  232. package/dist/send-G746D7PQ.js.map +0 -1
  233. package/dist/session-JBKWMJ24.js +0 -89
  234. package/dist/session-JBKWMJ24.js.map +0 -1
  235. package/dist/skill-heal-WKD67SLJ.js +0 -92
  236. package/dist/skill-heal-WKD67SLJ.js.map +0 -1
  237. package/dist/skill-placement-RIU4AMC2.js +0 -20
  238. package/dist/skill-placement-RIU4AMC2.js.map +0 -1
  239. package/dist/uninstall-5E263VTS.js +0 -73
  240. package/dist/uninstall-5E263VTS.js.map +0 -1
  241. package/dist/update-R76LHOZW.js.map +0 -1
  242. package/dist/usdc-4VCDHFWX.js +0 -38
  243. package/dist/usdc-4VCDHFWX.js.map +0 -1
  244. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
  245. package/dist/wallet-TQ7D5EQ7.js +0 -41
  246. package/dist/wallet-TQ7D5EQ7.js.map +0 -1
  247. package/dist/wallet-ZAVXWLWP.js +0 -32
  248. package/dist/wallet-ZAVXWLWP.js.map +0 -1
  249. package/docs/command-reference.md +0 -303
  250. package/skills/tenjin/SKILL.md +0 -373
  251. package/skills/tenjin-pay/SKILL.md +0 -76
  252. package/skills/tenjin-publish/SKILL.md +0 -227
  253. package/skills/tenjin-publish/references/maintain.md +0 -39
  254. package/skills/tenjin-search/SKILL.md +0 -154
  255. package/skills/tenjin-search/references/permissions.md +0 -112
  256. /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
  257. /package/dist/{buy-VIRNSYGN.js.map → ccip-7RMRLAGV.js.map} +0 -0
  258. /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
  259. /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
  260. /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
  261. /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
  262. /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  263. /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
  264. /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
  265. /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
  266. /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
  267. /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
  268. /package/dist/{ccip-ZGGWQN4X.js.map → config-5ADBAAXU.js.map} +0 -0
  269. /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
  270. /package/dist/{config-JMRUNYE6.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  271. /package/dist/{doctor-ZBG7X66D.js.map → install-OKDKGUXM.js.map} +0 -0
  272. /package/dist/{edit-PZJIILQE.js.map → paths-P2N4JTDZ.js.map} +0 -0
  273. /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-3SYKHKWJ.js.map} +0 -0
  274. /package/dist/{fund-EUDH5KPA.js.map → redact-6W23GGJC.js.map} +0 -0
  275. /package/dist/{inspect-QC6WEQPN.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
  276. /package/dist/{outcome-KSGWZHUS.js.map → status-line-wiring-L2WYIYBM.js.map} +0 -0
  277. /package/dist/{publish-LXWFDIKF.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
  278. /package/dist/{search-TSQAB45E.js.map → wallet-BMEXRR3P.js.map} +0 -0
@@ -0,0 +1,763 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ isPublicAddress
4
+ } from "./chunk-2G2WLVHB.js";
5
+ import {
6
+ requestToolAccess
7
+ } from "./chunk-S2NRVRPF.js";
8
+ import {
9
+ ROUTER_PATH,
10
+ requestDecision
11
+ } from "./chunk-WGQVJM56.js";
12
+ import "./chunk-5QHHRMRA.js";
13
+ import {
14
+ readSpendSummary,
15
+ spentOf
16
+ } from "./chunk-35M3VITA.js";
17
+ import {
18
+ REQUEST_TOOL
19
+ } from "./chunk-TGLKKLQG.js";
20
+ import {
21
+ mask
22
+ } from "./chunk-7QKHZQKW.js";
23
+ import {
24
+ bindDecision,
25
+ markOffered,
26
+ newCallId,
27
+ noteSession,
28
+ pruneProgress,
29
+ pruneSessions,
30
+ sessionDir,
31
+ wasOffered,
32
+ writeProgress
33
+ } from "./chunk-J5INH7WB.js";
34
+ import {
35
+ routerSettings
36
+ } from "./chunk-TP4D47BY.js";
37
+ import "./chunk-2I4QTOLB.js";
38
+ import {
39
+ resolveContextSettings
40
+ } from "./chunk-PDA2BVFY.js";
41
+ import {
42
+ evaluateSpendPolicy
43
+ } from "./chunk-U2DZISAH.js";
44
+ import {
45
+ external_exports,
46
+ loadRawConfig,
47
+ resolveSettings
48
+ } from "./chunk-AR7U7BRG.js";
49
+ import "./chunk-5UDD5VSY.js";
50
+ import "./chunk-JLEF5WHM.js";
51
+ import "./chunk-2BKS2FVE.js";
52
+ import "./chunk-ZXTAQYNA.js";
53
+
54
+ // src/router/hooks.ts
55
+ import { homedir } from "node:os";
56
+
57
+ // src/router/context.ts
58
+ import { open } from "node:fs/promises";
59
+ import { isIP } from "node:net";
60
+ import { dirname, join } from "node:path";
61
+ var MAX_HISTORY = 6;
62
+ var MAX_PACKET_BYTES = 16 * 1024;
63
+ var MAX_MESSAGE_CHARS = 16e3;
64
+ var MAX_TRANSCRIPT_BYTES = 4e6;
65
+ var MAX_LITERAL_URLS = 8;
66
+ var MAX_LITERAL_URL_CHARS = 2e3;
67
+ var MAX_PENDING_CHARS = 4e3;
68
+ var MAX_OUTCOME_ERROR_CHARS = 1e3;
69
+ var MASK_MARGIN = 4096;
70
+ var URL_RE = /\bhttps?:\/\/[^\s<>"'`)\]]+/gi;
71
+ function literalUrlsIn(text) {
72
+ const found = /* @__PURE__ */ new Set();
73
+ for (const match of text.matchAll(URL_RE)) {
74
+ const candidate = match[0].replace(/[.,;:!?]+$/, "");
75
+ try {
76
+ const normalized = new URL(candidate).toString();
77
+ if (normalized.length <= MAX_LITERAL_URL_CHARS) found.add(normalized);
78
+ } catch {
79
+ continue;
80
+ }
81
+ if (found.size >= MAX_LITERAL_URLS) break;
82
+ }
83
+ return [...found];
84
+ }
85
+ function fit(packet) {
86
+ const size = (value) => Buffer.byteLength(JSON.stringify(value));
87
+ const next = { ...packet, history: packet.history.slice(-MAX_HISTORY) };
88
+ while (next.history.length > 0 && size(next) > MAX_PACKET_BYTES) {
89
+ next.history = next.history.slice(1);
90
+ }
91
+ while (next.literalUrls.length > 0 && size(next) > MAX_PACKET_BYTES) {
92
+ next.literalUrls = next.literalUrls.slice(0, -1);
93
+ }
94
+ while (size(next) > MAX_PACKET_BYTES && next.current.text.length > 1) {
95
+ const over = size(next) - MAX_PACKET_BYTES;
96
+ const keep = Math.max(1, next.current.text.length - Math.max(over, 1));
97
+ next.current = { ...next.current, text: next.current.text.slice(0, keep) };
98
+ }
99
+ return next;
100
+ }
101
+ function seal(packet) {
102
+ const pending = packet.pendingCall;
103
+ const subject = pending === void 0 ? "" : "query" in pending ? pending.query : pending.url;
104
+ const sealedSubject = maskWithin(subject, MAX_PENDING_CHARS);
105
+ const bound = (text) => maskWithin(text, MAX_MESSAGE_CHARS).text;
106
+ const sealedCurrent = maskWithin(packet.current.text, MAX_MESSAGE_CHARS);
107
+ const current = sealedCurrent.text;
108
+ const outcome = packet.nativeOutcome;
109
+ const sealed = fit({
110
+ current: { role: packet.current.role, text: current.length > 0 ? current : "(no task text)" },
111
+ history: packet.history.slice(-MAX_HISTORY).map((message) => ({ role: message.role, text: bound(message.text) })).filter((message) => message.text.length > 0),
112
+ literalUrls: packet.literalUrls.filter((url) => !isLocalTarget(url)).map(mask).filter((url) => url.length <= MAX_LITERAL_URL_CHARS),
113
+ historyStatus: packet.historyStatus,
114
+ ...pending === void 0 ? {} : {
115
+ pendingCall: "query" in pending ? { tool: pending.tool, query: sealedSubject.text } : { tool: pending.tool, url: sealedSubject.text }
116
+ },
117
+ ...outcome === void 0 ? {} : {
118
+ nativeOutcome: {
119
+ ...outcome,
120
+ ...outcome.error !== void 0 ? { error: maskWithin(outcome.error, MAX_OUTCOME_ERROR_CHARS).text } : {}
121
+ }
122
+ }
123
+ });
124
+ return {
125
+ packet: sealed,
126
+ subjectChanged: sealedSubject.changed,
127
+ localTarget: pending !== void 0 && "url" in pending && isLocalTarget(pending.url),
128
+ currentChanged: sealedCurrent.changed,
129
+ localUrl: packet.literalUrls.some(isLocalTarget)
130
+ };
131
+ }
132
+ function maskWithin(text, max) {
133
+ const window = text.slice(0, max + MASK_MARGIN);
134
+ const masked = mask(window);
135
+ const limit = window.length < text.length ? Math.min(max, masked.length - MASK_MARGIN) : max;
136
+ return { text: masked.slice(0, Math.max(0, limit)), changed: masked !== window };
137
+ }
138
+ var LOCAL_NAME = /(?:^|\.)(?:localhost|local)$/i;
139
+ function isLocalTarget(raw) {
140
+ let url;
141
+ try {
142
+ url = new URL(raw);
143
+ } catch {
144
+ return true;
145
+ }
146
+ if (url.protocol !== "http:" && url.protocol !== "https:") return true;
147
+ const host = url.hostname.replace(/^\[|\]$/g, "");
148
+ if (LOCAL_NAME.test(host)) return true;
149
+ return isIP(host) !== 0 && !isPublicAddress(host);
150
+ }
151
+ async function buildPromptPacket(transcriptPath, sessionId, prompt) {
152
+ const trimmed = prompt.trim();
153
+ const text = trimmed.length > 0 ? trimmed : "(empty prompt)";
154
+ const read = await readHistory(transcriptPath, { sessionId });
155
+ return {
156
+ current: { role: "user", text },
157
+ history: read ?? [],
158
+ literalUrls: literalUrlsIn(text),
159
+ historyStatus: read === null ? "unavailable" : "ok"
160
+ };
161
+ }
162
+ async function buildNativePacket(transcriptPath, sessionId, pending, opts = {}) {
163
+ const { agentId, nativeOutcome } = opts;
164
+ const subject = "query" in pending ? pending.query : pending.url;
165
+ const read = await readHistory(transcriptPath, { sessionId });
166
+ const own = agentId === void 0 ? null : await readHistory(subagentTranscriptPath(transcriptPath, sessionId, agentId), {
167
+ sessionId,
168
+ agentId
169
+ });
170
+ const messages = own === null ? read ?? [] : [...read ?? [], ...own];
171
+ const lastUser = messages.map((message, index) => ({ message, index })).filter((entry) => entry.message.role === "user");
172
+ const current = lastUser.at(-1);
173
+ return {
174
+ current: current?.message ?? { role: "user", text: subject },
175
+ history: current === void 0 ? messages : messages.slice(0, current.index),
176
+ literalUrls: literalUrlsIn(`${current?.message.text ?? ""}
177
+ ${subject}`),
178
+ historyStatus: read === null && own === null ? "unavailable" : "ok",
179
+ pendingCall: pending,
180
+ ...nativeOutcome !== void 0 ? { nativeOutcome } : {}
181
+ };
182
+ }
183
+ var PATH_SEGMENT_RE = /^[A-Za-z0-9_-]{1,200}$/;
184
+ function subagentTranscriptPath(transcriptPath, sessionId, agentId) {
185
+ if (transcriptPath === void 0 || transcriptPath.length === 0) return void 0;
186
+ if (!PATH_SEGMENT_RE.test(sessionId) || !PATH_SEGMENT_RE.test(agentId)) return void 0;
187
+ return join(dirname(transcriptPath), sessionId, "subagents", `agent-${agentId}.jsonl`);
188
+ }
189
+ async function readHistory(path, scope) {
190
+ if (path === void 0 || path.length === 0) return null;
191
+ let raw;
192
+ let file;
193
+ try {
194
+ file = await open(path, "r");
195
+ } catch {
196
+ return null;
197
+ }
198
+ try {
199
+ const stat = await file.stat();
200
+ if (!stat.isFile() || stat.size > MAX_TRANSCRIPT_BYTES) return null;
201
+ const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES + 1);
202
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
203
+ if (bytesRead > MAX_TRANSCRIPT_BYTES) return null;
204
+ raw = buffer.subarray(0, bytesRead).toString("utf8");
205
+ } catch {
206
+ return null;
207
+ } finally {
208
+ await file.close();
209
+ }
210
+ try {
211
+ return parseRows(raw, scope);
212
+ } catch {
213
+ return null;
214
+ }
215
+ }
216
+ function parseRows(raw, scope) {
217
+ const { sessionId, agentId } = scope;
218
+ let messages = [];
219
+ for (const line of raw.split("\n")) {
220
+ if (line.trim().length === 0) continue;
221
+ let row;
222
+ try {
223
+ row = JSON.parse(line);
224
+ } catch {
225
+ continue;
226
+ }
227
+ if (row === null || typeof row !== "object" || Array.isArray(row)) continue;
228
+ if (row.type === "system" && row.subtype === "compact_boundary") {
229
+ messages = [];
230
+ continue;
231
+ }
232
+ if (typeof row.sessionId === "string" && row.sessionId !== sessionId) continue;
233
+ if (row.isMeta === true) continue;
234
+ if (agentId === void 0 ? row.isSidechain === true : !ownSidechainRow(row, agentId)) {
235
+ continue;
236
+ }
237
+ if (row.type !== "user" && row.type !== "assistant") continue;
238
+ if (row.sessionId !== sessionId) continue;
239
+ let text;
240
+ try {
241
+ text = textOf(row.message);
242
+ } catch {
243
+ continue;
244
+ }
245
+ if (text.length > 0) messages.push({ role: row.type, text });
246
+ }
247
+ return messages;
248
+ }
249
+ function ownSidechainRow(row, agentId) {
250
+ return row.isSidechain === true && row.agentId === agentId && row.isMeta !== true;
251
+ }
252
+ function textOf(message) {
253
+ if (message === null || typeof message !== "object" || Array.isArray(message)) {
254
+ throw new Error("malformed message");
255
+ }
256
+ const content = message.content;
257
+ if (typeof content === "string") return content;
258
+ if (!Array.isArray(content)) throw new Error("malformed content");
259
+ const parts = [];
260
+ for (const part of content) {
261
+ if (part === null || typeof part !== "object" || typeof part.type !== "string") {
262
+ throw new Error("malformed block");
263
+ }
264
+ const block = part;
265
+ if (block.type !== "text") continue;
266
+ if (typeof block.text !== "string") throw new Error("malformed text block");
267
+ parts.push(block.text);
268
+ }
269
+ return parts.join("\n");
270
+ }
271
+
272
+ // src/router/gate.ts
273
+ var GATE_TIMEOUT_MS = 3500;
274
+
275
+ // src/router/hooks.ts
276
+ var PromptEventSchema = external_exports.object({
277
+ session_id: external_exports.string().min(1).max(200),
278
+ /** The directory the session works in; `router.*` resolves from it. */
279
+ cwd: external_exports.string().optional(),
280
+ transcript_path: external_exports.string().optional(),
281
+ prompt: external_exports.string()
282
+ });
283
+ var NativeCallFields = {
284
+ session_id: external_exports.string().min(1).max(200),
285
+ /** The harness's own path for THIS session: the decision reads the same
286
+ * bounded history the prompt one does, so a restriction the user gave
287
+ * reaches both gates. */
288
+ transcript_path: external_exports.string().optional(),
289
+ tool_name: external_exports.enum(["WebSearch", "WebFetch"]),
290
+ tool_input: external_exports.record(external_exports.string(), external_exports.unknown()),
291
+ /** The harness's id for this one call, shared by its Pre and Post events. */
292
+ tool_use_id: external_exports.string().min(1).max(200).optional(),
293
+ /** Present only inside a subagent, which is the one caller that cannot reach
294
+ * the user to approve a spend. */
295
+ agent_id: external_exports.string().min(1).max(200).optional(),
296
+ /** The subagent's type, which names its definition file. */
297
+ agent_type: external_exports.string().min(1).max(200).optional(),
298
+ cwd: external_exports.string().optional()
299
+ };
300
+ var NativeEventSchema = external_exports.object({
301
+ hook_event_name: external_exports.literal("PreToolUse").optional(),
302
+ ...NativeCallFields
303
+ });
304
+ var ShortfallEventSchema = external_exports.object({
305
+ hook_event_name: external_exports.enum(["PostToolUse", "PostToolUseFailure"]),
306
+ ...NativeCallFields,
307
+ /** PostToolUse only: WebFetch's `{bytes, code, codeText, result, durationMs}`,
308
+ * or WebSearch's `{query, results, durationSeconds, searchCount}`. */
309
+ tool_response: external_exports.unknown().optional(),
310
+ /** PostToolUseFailure only: the failed call's own error, such as
311
+ * `getaddrinfo ENOTFOUND x.test`. */
312
+ error: external_exports.unknown().optional(),
313
+ is_interrupt: external_exports.boolean().optional()
314
+ });
315
+ var DelegationEventSchema = external_exports.object({
316
+ session_id: external_exports.string().min(1).max(200),
317
+ transcript_path: external_exports.string().optional(),
318
+ /** `Task` is the tool's older name; the matcher `install` writes takes both. */
319
+ tool_name: external_exports.enum(["Agent", "Task"]),
320
+ tool_input: external_exports.record(external_exports.string(), external_exports.unknown()),
321
+ cwd: external_exports.string().optional()
322
+ });
323
+ function decodeEvent(raw) {
324
+ const shortfall = ShortfallEventSchema.safeParse(raw);
325
+ if (shortfall.success) {
326
+ return {
327
+ kind: "shortfall",
328
+ eventName: shortfall.data.hook_event_name,
329
+ nativeOutcome: shortfallOf(shortfall.data),
330
+ ...nativeCallOf(shortfall.data)
331
+ };
332
+ }
333
+ const native = NativeEventSchema.safeParse(raw);
334
+ if (native.success) return { kind: "native", ...nativeCallOf(native.data) };
335
+ const delegation = DelegationEventSchema.safeParse(raw);
336
+ if (delegation.success) {
337
+ const input = delegation.data.tool_input;
338
+ return {
339
+ kind: "delegation",
340
+ sessionId: delegation.data.session_id,
341
+ ...optional("transcriptPath", delegation.data.transcript_path),
342
+ task: typeof input.prompt === "string" ? input.prompt : null,
343
+ // With no type the harness runs its general-purpose agent.
344
+ subagentType: typeof input.subagent_type === "string" ? input.subagent_type : "general-purpose",
345
+ toolInput: input,
346
+ ...optional("cwd", delegation.data.cwd)
347
+ };
348
+ }
349
+ const prompt = PromptEventSchema.safeParse(raw);
350
+ if (!prompt.success) return null;
351
+ return {
352
+ kind: "prompt",
353
+ sessionId: prompt.data.session_id,
354
+ ...optional("transcriptPath", prompt.data.transcript_path),
355
+ prompt: prompt.data.prompt,
356
+ ...optional("cwd", prompt.data.cwd)
357
+ };
358
+ }
359
+ function nativeCallOf(event) {
360
+ return {
361
+ sessionId: event.session_id,
362
+ ...optional("transcriptPath", event.transcript_path),
363
+ tool: event.tool_name,
364
+ pending: pendingCallOf(event.tool_name, event.tool_input),
365
+ ...optional("toolUseId", event.tool_use_id),
366
+ ...optional("agentId", event.agent_id),
367
+ ...optional("agentType", event.agent_type),
368
+ ...optional("cwd", event.cwd)
369
+ };
370
+ }
371
+ function optional(key, value) {
372
+ return value === void 0 ? {} : { [key]: value };
373
+ }
374
+ var ACKNOWLEDGEMENTS = /* @__PURE__ */ new Set(["y", "yes", "ok", "okay", "continue", "go", "sure", "thanks"]);
375
+ function promptSkipReason(prompt) {
376
+ const trimmed = prompt.trim();
377
+ if (trimmed.startsWith("/")) return "slash";
378
+ const normalized = trimmed.toLowerCase().replace(/[.!,]+$/, "");
379
+ return ACKNOWLEDGEMENTS.has(normalized) ? "acknowledgement" : null;
380
+ }
381
+ var HINT_SOURCE = "Tenjin router (installed by the user)";
382
+ var BARE_CALL_RE = /(?<![\w$])request\(\{/g;
383
+ function toolNamed(hint) {
384
+ return hint.replace(BARE_CALL_RE, `${REQUEST_TOOL}({`);
385
+ }
386
+ function attributed(hint) {
387
+ return `${HINT_SOURCE}: ${toolNamed(hint)}`;
388
+ }
389
+ function shortfallOffer(tool, hint) {
390
+ return `${HINT_SOURCE}: your ${tool} call came back short. Optional: ${toolNamed(hint)}`;
391
+ }
392
+ var NEAR_EMPTY_BYTES = 64;
393
+ function shortfallOf(event) {
394
+ if (event.hook_event_name === "PostToolUseFailure") {
395
+ if (event.is_interrupt === true) return null;
396
+ const error = typeof event.error === "string" ? event.error.trim() : "";
397
+ return error.length > 0 ? { error } : null;
398
+ }
399
+ const response = event.tool_response;
400
+ if (response === null || typeof response !== "object" || Array.isArray(response)) return null;
401
+ const fields = response;
402
+ if (event.tool_name === "WebFetch") {
403
+ const code = wholeNumber(fields.code, 999);
404
+ const bytes = wholeNumber(fields.bytes, Number.MAX_SAFE_INTEGER);
405
+ const outcome = {
406
+ ...code !== void 0 ? { code } : {},
407
+ ...bytes !== void 0 ? { bytes } : {}
408
+ };
409
+ if (code !== void 0 && isShortStatus(code)) return outcome;
410
+ const success = code === void 0 || code >= 200 && code < 300;
411
+ return success && bytes !== void 0 && bytes < NEAR_EMPTY_BYTES ? outcome : null;
412
+ }
413
+ const results = fields.results;
414
+ if (!Array.isArray(results)) return null;
415
+ const linked = results.some(
416
+ (entry) => entry !== null && typeof entry === "object" && Array.isArray(entry.content) && entry.content.length > 0
417
+ );
418
+ return linked ? null : { error: "Web search returned no results" };
419
+ }
420
+ var SHORT_STATUSES = /* @__PURE__ */ new Set([401, 402, 403, 429]);
421
+ function isShortStatus(code) {
422
+ return SHORT_STATUSES.has(code) || code >= 500 && code <= 599;
423
+ }
424
+ function wholeNumber(value, max) {
425
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max ? value : void 0;
426
+ }
427
+ function delegationOffer(hint) {
428
+ return `${HINT_SOURCE}, optional if your own tools fall short: ${toolNamed(hint)} Your own tools are fine when they are enough.`;
429
+ }
430
+ function resolveBaseUrl(deps, config) {
431
+ if (deps.baseUrl !== void 0) return deps.baseUrl;
432
+ return resolveSettings({ config, flags: {}, env: deps.env ?? process.env }).baseUrl.value;
433
+ }
434
+ async function wouldAutoExecute(decision, deps) {
435
+ try {
436
+ const { policy } = await resolveContextSettings(hookContext(deps));
437
+ const ledger = await readSpendSummary(deps.dataDir, {
438
+ ...deps.now !== void 0 ? { now: deps.now } : {}
439
+ });
440
+ const evaluation = evaluateSpendPolicy(policy, {
441
+ amountAtomic: BigInt(decision.providerPriceAtomic),
442
+ creator: new URL(decision.endpoint).host,
443
+ sessionSpentAtomic: ledger === null ? 0n : spentOf(ledger)
444
+ });
445
+ return evaluation.decision === "allow";
446
+ } catch {
447
+ return false;
448
+ }
449
+ }
450
+ function agentLookup(cwd, deps) {
451
+ return { ...cwd !== void 0 ? { cwd } : {}, homeDir: deps.homeDir ?? homedir() };
452
+ }
453
+ function hookContext(deps) {
454
+ return {
455
+ flags: { json: true, timeout: deps.timeoutMs ?? GATE_TIMEOUT_MS },
456
+ dataDir: deps.dataDir,
457
+ io: { stdout: nullStream(), stderr: nullStream(), isTTY: false }
458
+ };
459
+ }
460
+ async function runPromptHook(raw, deps) {
461
+ const event = decodeEvent(raw);
462
+ if (event?.kind !== "prompt") return { response: null };
463
+ const skipped = promptSkipReason(event.prompt);
464
+ if (skipped !== null) return { response: null, skipped };
465
+ const router = await routerFor(event.cwd, deps);
466
+ if (router === null) return { response: null };
467
+ const sealed = seal(
468
+ scoped(
469
+ await buildPromptPacket(event.transcriptPath, event.sessionId, event.prompt),
470
+ router.settings
471
+ )
472
+ );
473
+ const footer = await openFooter(deps, event.sessionId, "prompt");
474
+ const outcome = await decide(sealed, deps, router.config);
475
+ await footer.close(outcome);
476
+ if (outcome === null) return { response: null };
477
+ if (outcome.action !== "execute") return { response: null, action: outcome.action };
478
+ return { action: "execute", id: outcome.id, ...injection(attributed(outcome.hint)) };
479
+ }
480
+ function injection(line) {
481
+ return {
482
+ response: {
483
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: line }
484
+ }
485
+ };
486
+ }
487
+ async function routeNativeCall(event, pending, deps, nativeOutcome) {
488
+ const router = await routerFor(event.cwd, deps);
489
+ if (router === null) return { offer: null, outcome: { response: null } };
490
+ if (event.agentId !== void 0 && await requestToolAccess(event.agentType, agentLookup(event.cwd, deps)) !== "allowed") {
491
+ return { offer: null, outcome: { response: null, noRequestTool: true } };
492
+ }
493
+ const sealed = seal(
494
+ scoped(
495
+ await buildNativePacket(event.transcriptPath, event.sessionId, pending, {
496
+ ...event.agentId !== void 0 ? { agentId: event.agentId } : {},
497
+ ...nativeOutcome !== void 0 ? { nativeOutcome } : {}
498
+ }),
499
+ router.settings
500
+ )
501
+ );
502
+ const { packet } = sealed;
503
+ if (sealed.localTarget) return { offer: null, outcome: { response: null } };
504
+ if (sealed.subjectChanged) {
505
+ (deps.warn ?? ((line) => process.stderr.write(`${line}
506
+ `)))(
507
+ "tenjin hook: the native call carries a credential-shaped value, so it is not routed"
508
+ );
509
+ return { offer: null, outcome: { response: null } };
510
+ }
511
+ if (packet.historyStatus !== "ok") {
512
+ (deps.warn ?? ((line) => process.stderr.write(`${line}
513
+ `)))(
514
+ "tenjin hook: this session's transcript could not be read, so no paid lookup is offered"
515
+ );
516
+ return { offer: null, outcome: { response: null } };
517
+ }
518
+ const footer = await openFooter(deps, event.sessionId, "search");
519
+ const outcome = await decide(sealed, deps, router.config);
520
+ if (outcome === null || outcome.action !== "execute") {
521
+ await footer.close(outcome);
522
+ return {
523
+ offer: null,
524
+ outcome: { response: null, ...outcome !== null ? { action: outcome.action } : {} }
525
+ };
526
+ }
527
+ if (event.agentId !== void 0 && !await wouldAutoExecute(outcome, deps)) {
528
+ await footer.close(outcome, { withheld: true });
529
+ return { offer: null, outcome: { response: null, action: "execute", withheld: true } };
530
+ }
531
+ await footer.close(outcome);
532
+ return { offer: outcome };
533
+ }
534
+ async function runNativeHook(raw, deps) {
535
+ const event = decodeEvent(raw);
536
+ if (event?.kind !== "native" || event.pending === null) return { response: null };
537
+ const routed = await routeNativeCall(event, event.pending, deps);
538
+ if (routed.offer === null) return routed.outcome;
539
+ if (event.toolUseId !== void 0) {
540
+ await markOffered(deps.dataDir, event.sessionId, event.toolUseId, deps.now?.());
541
+ }
542
+ return {
543
+ response: {
544
+ hookSpecificOutput: {
545
+ hookEventName: "PreToolUse",
546
+ permissionDecision: "deny",
547
+ // THE SERVER'S LINE, attributed and tool-named, and nothing else. It
548
+ // already carries the id and the exact search or URL that was denied.
549
+ permissionDecisionReason: attributed(routed.offer.hint)
550
+ }
551
+ },
552
+ action: "execute",
553
+ id: routed.offer.id
554
+ };
555
+ }
556
+ async function runShortfallHook(raw, deps) {
557
+ const event = decodeEvent(raw);
558
+ if (event?.kind !== "shortfall") return { response: null };
559
+ const { nativeOutcome, pending, eventName } = event;
560
+ if (nativeOutcome === null) return { response: null };
561
+ if (pending === null) return { response: null };
562
+ if (event.toolUseId !== void 0 && await wasOffered(deps.dataDir, event.sessionId, event.toolUseId, deps.now?.())) {
563
+ return { response: null, nativeOutcome, alreadyOffered: true };
564
+ }
565
+ const routed = await routeNativeCall(event, pending, deps, nativeOutcome);
566
+ if (routed.offer === null) return { ...routed.outcome, nativeOutcome };
567
+ return {
568
+ response: {
569
+ hookSpecificOutput: {
570
+ hookEventName: eventName,
571
+ // THE SERVER'S LINE, attributed and framed as the option it is. It
572
+ // already carries the id and the exact search or URL that came back short.
573
+ additionalContext: shortfallOffer(event.tool, routed.offer.hint)
574
+ }
575
+ },
576
+ nativeOutcome,
577
+ action: "execute",
578
+ id: routed.offer.id
579
+ };
580
+ }
581
+ async function runDelegationHook(raw, deps) {
582
+ const event = decodeEvent(raw);
583
+ if (event?.kind !== "delegation") return { response: null };
584
+ const { task } = event;
585
+ if (task === null || task.trim().length === 0) return { response: null };
586
+ const router = await routerFor(event.cwd, deps);
587
+ if (router === null) return { response: null };
588
+ if (await requestToolAccess(event.subagentType, agentLookup(event.cwd, deps)) !== "allowed") {
589
+ return { response: null, noRequestTool: true };
590
+ }
591
+ const sealed = seal(
592
+ scoped(await buildPromptPacket(event.transcriptPath, event.sessionId, task), router.settings)
593
+ );
594
+ if (sealed.localUrl) return { response: null };
595
+ if (sealed.currentChanged) {
596
+ (deps.warn ?? ((line) => process.stderr.write(`${line}
597
+ `)))(
598
+ "tenjin hook: the delegated task carries a credential-shaped value, so it is not routed"
599
+ );
600
+ return { response: null };
601
+ }
602
+ if (sealed.packet.historyStatus !== "ok") return { response: null };
603
+ const footer = await openFooter(deps, event.sessionId, "delegate");
604
+ const outcome = await decide(sealed, deps, router.config);
605
+ if (outcome === null || outcome.action !== "execute") {
606
+ await footer.close(outcome);
607
+ return { response: null, ...outcome !== null ? { action: outcome.action } : {} };
608
+ }
609
+ if (!await wouldAutoExecute(outcome, deps)) {
610
+ await footer.close(outcome, { withheld: true });
611
+ return { response: null, action: "execute", withheld: true };
612
+ }
613
+ await footer.close(outcome);
614
+ return {
615
+ response: {
616
+ hookSpecificOutput: {
617
+ hookEventName: "PreToolUse",
618
+ // The whole input, with one line appended: `updatedInput` replaces it.
619
+ updatedInput: {
620
+ ...event.toolInput,
621
+ prompt: `${task}
622
+
623
+ ${delegationOffer(outcome.hint)}`
624
+ }
625
+ }
626
+ },
627
+ action: "execute",
628
+ id: outcome.id
629
+ };
630
+ }
631
+ async function openFooter(deps, sessionId, operation) {
632
+ const now = () => deps.now?.() ?? Date.now();
633
+ const directory = sessionDir(deps.dataDir, sessionId);
634
+ const callId = newCallId();
635
+ await noteSession(deps.dataDir, sessionId, now());
636
+ await writeProgress(
637
+ directory,
638
+ callId,
639
+ { phase: "routing", operation, outcome: "selecting service" },
640
+ now()
641
+ );
642
+ await pruneProgress(directory, now());
643
+ await pruneSessions(deps.dataDir, now());
644
+ return {
645
+ close: async (decision, opts) => {
646
+ const withheld = opts?.withheld === true;
647
+ await writeProgress(
648
+ directory,
649
+ callId,
650
+ {
651
+ phase: "done",
652
+ operation,
653
+ outcome: withheld ? "native tools (offer needs approval)" : hookOutcome(decision)
654
+ },
655
+ now()
656
+ );
657
+ if (!withheld && decision !== null && decision.action === "execute") {
658
+ await bindDecision(deps.dataDir, sessionId, decision.id, now());
659
+ }
660
+ }
661
+ };
662
+ }
663
+ function hookOutcome(decision) {
664
+ if (decision === null) return "native tools (router unavailable)";
665
+ if (decision.action === "execute") return `paid lookup offered (${decision.provider})`;
666
+ if (decision.action === "native") return "native tools (no x402 payment)";
667
+ return "needs input";
668
+ }
669
+ async function decide({ packet }, deps, config) {
670
+ const baseUrl = resolveBaseUrl(deps, config);
671
+ const warn = deps.warn ?? ((line) => process.stderr.write(`${line}
672
+ `));
673
+ const outcome = await requestDecision(
674
+ "hook",
675
+ { packet },
676
+ {
677
+ ctx: hookContext(deps),
678
+ baseUrl,
679
+ timeoutMs: deps.timeoutMs ?? GATE_TIMEOUT_MS,
680
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
681
+ }
682
+ );
683
+ if (outcome.status === "failed") {
684
+ warn(`tenjin hook: ${baseUrl}${ROUTER_PATH} ${outcome.reason}`);
685
+ return null;
686
+ }
687
+ return outcome.decision.decision;
688
+ }
689
+ function nullStream() {
690
+ return { write: () => true };
691
+ }
692
+ function pendingCallOf(tool, input) {
693
+ const value = tool === "WebSearch" ? input.query : input.url;
694
+ if (typeof value !== "string") return null;
695
+ const subject = value.trim();
696
+ if (subject.length === 0) return null;
697
+ return tool === "WebSearch" ? { tool, query: subject } : { tool, url: subject };
698
+ }
699
+ async function routerFor(cwd, deps) {
700
+ const warn = deps.warn ?? ((line) => process.stderr.write(`${line}
701
+ `));
702
+ try {
703
+ const config = await loadRawConfig(deps.dataDir);
704
+ const settings = await routerSettings(
705
+ { cwd: cwd ?? process.cwd(), dataDir: deps.dataDir, config },
706
+ { warn: (line) => warn(`tenjin hook: ${line}`) }
707
+ );
708
+ return settings.enabled.value ? { settings, config } : null;
709
+ } catch (err) {
710
+ warn(`tenjin hook: ${err instanceof Error ? err.message : String(err)}, so the router is off`);
711
+ return null;
712
+ }
713
+ }
714
+ function scoped(packet, router) {
715
+ return router.context.value === "turn" ? { ...packet, history: [] } : packet;
716
+ }
717
+
718
+ // src/router/hook-command.ts
719
+ var MAX_EVENT_BYTES = 1e6;
720
+ var STDIN_TIMEOUT_MS = 1e3;
721
+ async function runHookCommand(kind, io, deps) {
722
+ let response;
723
+ try {
724
+ const raw = await (deps.readEvent ?? readStdin)();
725
+ const event = JSON.parse(raw);
726
+ const outcome = kind === "prompt" ? await runPromptHook(event, deps) : kind === "native" ? await runNativeHook(event, deps) : kind === "shortfall" ? await runShortfallHook(event, deps) : await runDelegationHook(event, deps);
727
+ response = outcome.response;
728
+ } catch {
729
+ response = null;
730
+ }
731
+ if (response !== null) io.stdout.write(`${JSON.stringify(response)}
732
+ `);
733
+ }
734
+ async function readStdin() {
735
+ return new Promise((resolve, reject) => {
736
+ const chunks = [];
737
+ let size = 0;
738
+ const timer = setTimeout(() => reject(new Error("no harness event")), STDIN_TIMEOUT_MS);
739
+ const done = (value) => {
740
+ clearTimeout(timer);
741
+ resolve(value);
742
+ };
743
+ process.stdin.on("data", (chunk) => {
744
+ size += chunk.length;
745
+ if (size > MAX_EVENT_BYTES) {
746
+ clearTimeout(timer);
747
+ reject(new Error("harness event too large"));
748
+ return;
749
+ }
750
+ chunks.push(chunk);
751
+ });
752
+ process.stdin.once("end", () => done(Buffer.concat(chunks).toString("utf8")));
753
+ process.stdin.once("error", () => {
754
+ clearTimeout(timer);
755
+ reject(new Error("harness event unreadable"));
756
+ });
757
+ });
758
+ }
759
+ export {
760
+ STDIN_TIMEOUT_MS,
761
+ runHookCommand
762
+ };
763
+ //# sourceMappingURL=hook-command-PBERPRE3.js.map