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 @@
1
+ {"version":3,"sources":["../src/router/hooks.ts","../src/router/context.ts","../src/router/gate.ts","../src/router/hook-command.ts"],"sourcesContent":["import { homedir } from 'node:os';\nimport { z } from 'zod';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport type { PartialConfig } from '../lib/config';\nimport { evaluateSpendPolicy } from '../lib/policy';\nimport { resolveContextSettings } from '../lib/settings';\nimport { readSpendSummary, spentOf } from '../lib/spend-ledger';\nimport type { CommandContext } from '../context';\nimport {\n buildNativePacket,\n buildPromptPacket,\n seal,\n type NativeOutcome,\n type Packet,\n type PendingCall,\n type Sealed,\n} from './context';\nimport { requestDecision, ROUTER_PATH, type HookDecision } from './decision';\nimport { GATE_TIMEOUT_MS } from './gate';\nimport { REQUEST_TOOL } from './names';\nimport { requestToolAccess, type AgentLookup } from './agent-tools';\nimport {\n bindDecision,\n markOffered,\n newCallId,\n noteSession,\n pruneProgress,\n pruneSessions,\n sessionDir,\n wasOffered,\n writeProgress,\n} from './progress';\nimport { routerSettings, type RouterSettings } from './settings';\n\n/**\n * The four hook handlers. Between them they do exactly three things: build and\n * seal the packet, ask for one free decision, and say one thing back to the\n * harness.\n *\n * NOTHING ELSE IS IN REACH FROM HERE. No wallet, no signer, no payment SDK, no\n * MCP server: a dist test asserts the chunk graph, because the hooks run on\n * every prompt and after every native search, and their cost is the product's\n * floor.\n * The decision is free, so nothing on this path can spend anything either.\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; anyone\n * 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\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}\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: 'shortfall';\n eventName: 'PostToolUse' | 'PostToolUseFailure';\n /** What the harness reported, when it was a shortfall; null means none. */\n nativeOutcome: NativeOutcome | 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` and\n * `subagent_type`), `tool_use_id`, `agent_id`, `agent_type`, `cwd`,\n * `tool_response` 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 ...nativeCallOf(shortfall.data),\n };\n }\n const native = NativeEventSchema.safeParse(raw);\n if (native.success) return { kind: 'native', ...nativeCallOf(native.data) };\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 sessionId: event.session_id,\n ...optional('transcriptPath', event.transcript_path),\n tool: event.tool_name,\n pending: pendingCallOf(event.tool_name, event.tool_input),\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\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';\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 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(hint: string): string {\n return hint.replace(BARE_CALL_RE, `${REQUEST_TOOL}({`);\n}\n\n/** The server's line as the prompt hint and the redirect both carry it. */\nfunction attributed(hint: string): string {\n return `${HINT_SOURCE}: ${toolNamed(hint)}`;\n}\n\n/** Where the offer sits after the free tool came back short. */\nfunction shortfallOffer(tool: 'WebSearch' | 'WebFetch', hint: string): string {\n return `${HINT_SOURCE}: your ${tool} call came back short. Optional: ${toolNamed(hint)}`;\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 * - 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 */\nexport function shortfallOf(event: {\n hook_event_name: 'PostToolUse' | 'PostToolUseFailure';\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 return success && bytes !== undefined && bytes < NEAR_EMPTY_BYTES ? outcome : 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 /** 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 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}\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/**\n * A SUBAGENT IS OFFERED ONLY WHAT IT CAN PAY FOR ALONE. It cannot reach the\n * user, so an offer that would stop on `needs_approval` is a dead end; the\n * parent can still make that lookup itself. This asks the question `request`\n * will: the same settings, the same session ledger and the same policy\n * evaluation, with the provider's host as the creator the way `pay` names it.\n * Only `allow`, a spend that would auto-execute, is worth the line. It\n * reserves nothing, and the amount actually signed is still `gateSpend`'s to\n * cap. Anything that cannot be read shows no offer.\n */\nasync function wouldAutoExecute(\n decision: { providerPriceAtomic: string; endpoint: string },\n deps: HookDeps,\n): Promise<boolean> {\n try {\n const { policy } = await resolveContextSettings(hookContext(deps));\n const ledger = await readSpendSummary(deps.dataDir, {\n ...(deps.now !== undefined ? { now: deps.now } : {}),\n });\n const evaluation = evaluateSpendPolicy(policy, {\n amountAtomic: BigInt(decision.providerPriceAtomic),\n creator: new URL(decision.endpoint).host,\n sessionSpentAtomic: ledger === null ? 0n : spentOf(ledger),\n });\n return evaluation.decision === 'allow';\n } catch {\n return false;\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}\n\n/**\n * `tenjin hook prompt` (UserPromptSubmit). One free decision from the user's\n * own words. Only an `execute` gets a line: the server's hint, attributed.\n * `native`, `needs_input` and a decision that 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 */\nexport async function runPromptHook(raw: unknown, deps: HookDeps): Promise<PromptHookOutcome> {\n const event = decodeEvent(raw);\n if (event?.kind !== 'prompt') return { response: null };\n const skipped = promptSkipReason(event.prompt);\n if (skipped !== null) return { response: null, skipped };\n const router = await routerFor(event.cwd, deps);\n if (router === null) return { response: null };\n\n const sealed = seal(\n scoped(\n await buildPromptPacket(event.transcriptPath, event.sessionId, event.prompt),\n router.settings,\n ),\n );\n const footer = await openFooter(deps, event.sessionId, 'prompt');\n const outcome = await decide(sealed, deps, router.config);\n await footer.close(outcome);\n if (outcome === null) return { response: null };\n if (outcome.action !== 'execute') return { response: null, action: outcome.action };\n return { action: 'execute', id: outcome.id, ...injection(attributed(outcome.hint)) };\n}\n\nfunction injection(line: string): { response: unknown } {\n return {\n response: {\n hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: line },\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: a subagent spend that would need approval. */\n withheld?: true;\n /** No router call at all: the subagent is not known to have the request tool. */\n noRequestTool?: 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}\n\ntype ExecuteDecision = Extract<HookDecision, { action: 'execute' }>;\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 free 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.\n */\nasync function routeNativeCall(\n event: NativeCall,\n pending: PendingCall,\n deps: HookDeps,\n nativeOutcome?: NativeOutcome,\n): Promise<{ offer: ExecuteDecision } | { offer: null; outcome: NativeHookOutcome }> {\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 // 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 // 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 = seal(\n scoped(\n await buildNativePacket(event.transcriptPath, event.sessionId, pending, {\n ...(event.agentId !== undefined ? { agentId: event.agentId } : {}),\n ...(nativeOutcome !== undefined ? { nativeOutcome } : {}),\n }),\n router.settings,\n ),\n );\n const { packet } = sealed;\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 { offer: null, outcome: { response: 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 (deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`)))(\n 'tenjin hook: the native call carries a credential-shaped value, so it is not routed',\n );\n return { offer: null, outcome: { response: 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 (packet.historyStatus !== 'ok') {\n (deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`)))(\n \"tenjin hook: this session's transcript could not be read, so no paid lookup is offered\",\n );\n return { offer: null, outcome: { response: null } };\n }\n const footer = await openFooter(deps, event.sessionId, 'search');\n const outcome = await decide(sealed, deps, router.config);\n if (outcome === null || outcome.action !== 'execute') {\n await footer.close(outcome);\n return {\n offer: null,\n outcome: { response: null, ...(outcome !== null ? { action: outcome.action } : {}) },\n };\n }\n if (event.agentId !== undefined && !(await wouldAutoExecute(outcome, deps))) {\n await footer.close(outcome, { withheld: true });\n return { offer: null, outcome: { response: null, action: 'execute', withheld: true } };\n }\n await footer.close(outcome);\n return { offer: outcome };\n}\n\n/**\n * `tenjin hook native` (PreToolUse on `WebSearch|WebFetch`). PER-LOOKUP\n * ROUTING BEFORE THE CALL, exactly as main: a clear `execute` denies the native\n * call with the server's hint as the reason, carrying the id so the redirected\n * call runs the decision just made. Anything else, including silence, a slow\n * backend and a `needs_input`, lets the call run with 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.\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 */\nexport async function runNativeHook(raw: unknown, deps: HookDeps): Promise<NativeHookOutcome> {\n const event = decodeEvent(raw);\n if (event?.kind !== 'native' || event.pending === null) return { response: null };\n const routed = await routeNativeCall(event, event.pending, deps);\n if (routed.offer === null) return routed.outcome;\n if (event.toolUseId !== undefined) {\n await markOffered(deps.dataDir, event.sessionId, event.toolUseId, deps.now?.());\n }\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n permissionDecision: 'deny',\n // THE SERVER'S LINE, attributed and tool-named, and nothing else. It\n // already carries the id and the exact search or URL that was denied.\n permissionDecisionReason: attributed(routed.offer.hint),\n },\n },\n action: 'execute',\n id: routed.offer.id,\n };\n}\n\n/**\n * `tenjin hook shortfall` (PostToolUse and PostToolUseFailure on\n * `WebSearch|WebFetch`). THE FREE TOOL HAS ALREADY RUN, and a result that is\n * fine ends here: no router call, no footer, no added latency. Only a clear\n * shortfall ({@link shortfallOf}) asks for one free decision, with what the\n * harness reported riding in the packet as `nativeOutcome`, and only an\n * `execute` says anything. A call the pre-call arm already redirected is not\n * offered on again.\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 = decodeEvent(raw);\n if (event?.kind !== 'shortfall') return { response: null };\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(deps.dataDir, event.sessionId, event.toolUseId, deps.now?.()))\n ) {\n return { response: null, nativeOutcome, alreadyOffered: true };\n }\n const routed = await routeNativeCall(event, pending, deps, nativeOutcome);\n if (routed.offer === null) return { ...routed.outcome, nativeOutcome };\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),\n },\n },\n nativeOutcome,\n action: 'execute',\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 * `tenjin hook agent` (PreToolUse on `Agent|Task`). The one moment a subagent's\n * whole assignment is visible: its task prompt IS the current message, and the\n * parent's own turn is the history, so the router decides on exactly what the\n * subagent will do. On a clear `execute` the offer is appended to that task as\n * one optional line, which reaches the subagent as part of its instructions\n * from its parent, before it starts. Anything else is 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 = decodeEvent(raw);\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 // 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 = seal(\n scoped(await buildPromptPacket(event.transcriptPath, event.sessionId, task), router.settings),\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 const footer = await openFooter(deps, event.sessionId, 'delegate');\n const outcome = await decide(sealed, deps, router.config);\n if (outcome === null || outcome.action !== 'execute') {\n await footer.close(outcome);\n return { response: null, ...(outcome !== null ? { action: outcome.action } : {}) };\n }\n if (!(await wouldAutoExecute(outcome, deps))) {\n await footer.close(outcome, { withheld: true });\n return { response: null, action: 'execute', 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: 'execute',\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 an `execute`\n * also leaves the id-to-session binding the tool resolves its progress through.\n */\nasync function openFooter(\n deps: HookDeps,\n sessionId: string,\n operation: 'prompt' | 'search' | 'delegate',\n): Promise<{\n close: (decision: HookDecision | null, opts?: { withheld?: boolean }) => Promise<void>;\n}> {\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 return {\n close: async (decision, opts) => {\n const withheld = opts?.withheld === true;\n await writeProgress(\n directory,\n callId,\n {\n phase: 'done',\n operation,\n outcome: withheld ? 'native tools (offer needs approval)' : hookOutcome(decision),\n },\n now(),\n );\n if (!withheld && decision !== null && decision.action === 'execute') {\n await bindDecision(deps.dataDir, sessionId, decision.id, now());\n }\n },\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. */\nfunction hookOutcome(decision: HookDecision | null): string {\n if (decision === null) return 'native tools (router unavailable)';\n if (decision.action === 'execute') return `paid lookup offered (${decision.provider})`;\n if (decision.action === 'native') return 'native tools (no x402 payment)';\n return 'needs input';\n}\n\n/** One free decision, with the hook's own deadline and its own silence. It\n * takes what {@link seal} returns rather than a bare packet, so a call site\n * that skips the mask does not typecheck. */\nasync function decide(\n { packet }: Sealed,\n deps: HookDeps,\n config: PartialConfig,\n): Promise<HookDecision | null> {\n const baseUrl = resolveBaseUrl(deps, config);\n const warn = deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`));\n const outcome = await requestDecision(\n 'hook',\n { packet },\n {\n ctx: hookContext(deps),\n baseUrl,\n timeoutMs: deps.timeoutMs ?? GATE_TIMEOUT_MS,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n },\n );\n if (outcome.status === 'failed') {\n warn(`tenjin hook: ${baseUrl}${ROUTER_PATH} ${outcome.reason}`);\n return null;\n }\n return outcome.decision.decision;\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\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/**\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(\n cwd: string | undefined,\n deps: HookDeps,\n): Promise<{ settings: RouterSettings; config: PartialConfig } | 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 return settings.enabled.value ? { settings, config } : null;\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 * `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","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';\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 (another\n * session, a subagent sidechain, a compaction boundary, malformed rows, an\n * oversized file) is reported as `unavailable` rather than partially believed,\n * and the user's turn is never blocked by any of that. 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;\nconst MAX_TRANSCRIPT_BYTES = 4_000_000;\nconst MAX_LITERAL_URLS = 8;\nconst MAX_LITERAL_URL_CHARS = 2_000;\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\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 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}\n\n/** The pending native call, INSIDE the packet: the gate request is a strict\n * object with exactly `schemaVersion`, `source` and `packet`. */\nexport type PendingCall = { tool: 'WebSearch'; query: string } | { tool: 'WebFetch'; url: string };\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 }\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\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`, `history`, `literalUrls` and 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): Sealed {\n const pending = packet.pendingCall;\n const subject = pending === undefined ? '' : 'query' in pending ? pending.query : pending.url;\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 outcome = packet.nativeOutcome;\n const sealed = fit({\n current: { role: packet.current.role, text: current.length > 0 ? current : '(no task text)' },\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: packet.literalUrls\n .filter((url) => !isLocalTarget(url))\n .map(mask)\n .filter((url) => url.length <= MAX_LITERAL_URL_CHARS),\n historyStatus: packet.historyStatus,\n ...(pending === undefined\n ? {}\n : {\n pendingCall:\n 'query' in pending\n ? { tool: pending.tool, query: sealedSubject.text }\n : { tool: pending.tool, url: sealedSubject.text },\n }),\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\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 * A packet for a caller that has no conversation to send: the query itself is\n * the current message, because the server's message text is `min(1)` and an\n * empty one is a 400 after the routing fee has already settled.\n */\nexport function packetForText(text: string): Packet {\n const bounded = text.trim().slice(0, MAX_MESSAGE_CHARS);\n return fit({\n current: { role: 'user', text: bounded.length > 0 ? bounded : '(no task text)' },\n history: [],\n literalUrls: literalUrlsIn(bounded),\n historyStatus: 'unavailable',\n });\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): Promise<Packet> {\n const trimmed = prompt.trim();\n const text = trimmed.length > 0 ? trimmed : '(empty prompt)';\n const read = await readHistory(transcriptPath, { sessionId });\n return {\n current: { role: 'user', text },\n history: read ?? [],\n literalUrls: literalUrlsIn(text),\n historyStatus: read === null ? 'unavailable' : 'ok',\n };\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 } = {},\n): Promise<Packet> {\n const { agentId, nativeOutcome } = opts;\n const subject = 'query' in pending ? pending.query : pending.url;\n const read = await readHistory(transcriptPath, { sessionId });\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\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: current?.message ?? { role: 'user', text: subject },\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}\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 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() || stat.size > MAX_TRANSCRIPT_BYTES) return 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 raw = buffer.subarray(0, bytesRead).toString('utf8');\n } catch {\n return null;\n } finally {\n await file.close();\n }\n try {\n return parseRows(raw, scope);\n } catch {\n return null;\n }\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 if (text.length > 0) messages.push({ role: row.type, text });\n }\n return messages;\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","/**\n * THE HOOK'S TIME BUDGET, which is the only thing this module still owns.\n *\n * There is no separate gate call any more: the hook asks `POST\n * /api/x402-router` for the one free decision, and the backend answers as soon\n * as the native-versus-paid question is settled, binding whatever it chose in\n * the background. What used to live here, the `/prepare` client and the\n * category-shaped hint validator, went with that second round trip.\n */\n\n/**\n * The hook's whole budget is 5 s (the timeout `install` writes). Stdin waits up\n * to 1 s of it, so the decision gets 3.5 s and the two together still leave\n * 500 ms for node's boot and the transcript read; `wire.test.ts` pins the sum.\n * The expected wait is about 1 s: the backend answers on the gate question and\n * binds afterwards.\n *\n * AN ABORT HERE IS A LOST HINT, not a lost turn. The hook falls back to one\n * line telling the model to call `request` with its own query, and the tool\n * makes the decision instead. One of four live prompts was swallowed at a 1.5 s\n * abort against a backend measured at 0.4 to 0.5 s, so this holds the slack the\n * harness budget was already leaving unused.\n */\nexport const GATE_TIMEOUT_MS = 3_500;\n","import {\n runDelegationHook,\n runNativeHook,\n runPromptHook,\n runShortfallHook,\n type HookDeps,\n} from './hooks';\nimport type { Io } from '../lib/output';\n\n/**\n * `tenjin hook prompt`, `native`, `shortfall` and `agent`. The harness writes\n * its event on stdin and reads a JSON object (or nothing) from stdout, so these\n * commands\n * bypass the CLI's envelope entirely. They never fail the turn: a stdin that\n * never arrives, an unreadable event or a handler that throws all exit 0 with\n * an empty stdout, which the harness reads as \"no opinion\".\n */\n\nconst MAX_EVENT_BYTES = 1_000_000;\n/** One fifth of the hook's 5 s budget, leaving the gate its 3.5 s; `wire.test.ts`\n * pins the sum against the timeout `install` writes. The harness writes its\n * event immediately, so this wait is a liveness check rather than a budget to\n * spend: every second it holds is a second the gate does not get. */\nexport const STDIN_TIMEOUT_MS = 1_000;\n\nexport type HookKind = 'prompt' | 'native' | 'shortfall' | 'agent';\n\nexport interface HookCommandDeps extends HookDeps {\n /** Test seam for the harness event; production reads stdin. */\n readEvent?: () => Promise<string>;\n}\n\nexport async function runHookCommand(kind: HookKind, io: Io, deps: HookCommandDeps): Promise<void> {\n let response: unknown;\n try {\n const raw = await (deps.readEvent ?? readStdin)();\n const event: unknown = JSON.parse(raw);\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 : await runDelegationHook(event, deps);\n response = outcome.response;\n } catch {\n response = null;\n }\n if (response !== null) io.stdout.write(`${JSON.stringify(response)}\\n`);\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,eAAe;;;ACAxB,SAAS,YAAY;AACrB,SAAS,YAAY;AACrB,SAAS,SAAS,YAAY;AAwBvB,IAAM,cAAc;AACpB,IAAM,mBAAmB,KAAK;AAG9B,IAAM,oBAAoB;AACjC,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB;AACzB,IAAM,wBAAwB;AAC9B,IAAM,oBAAoB;AAE1B,IAAM,0BAA0B;AAEhC,IAAM,cAAc;AAmCpB,IAAM,SAAS;AAER,SAAS,cAAc,MAAwB;AACpD,QAAM,QAAQ,oBAAI,IAAY;AAC9B,aAAW,SAAS,KAAK,SAAS,MAAM,GAAG;AACzC,UAAM,YAAY,MAAM,CAAC,EAAE,QAAQ,cAAc,EAAE;AACnD,QAAI;AACF,YAAM,aAAa,IAAI,IAAI,SAAS,EAAE,SAAS;AAC/C,UAAI,WAAW,UAAU,sBAAuB,OAAM,IAAI,UAAU;AAAA,IACtE,QAAQ;AACN;AAAA,IACF;AACA,QAAI,MAAM,QAAQ,iBAAkB;AAAA,EACtC;AACA,SAAO,CAAC,GAAG,KAAK;AAClB;AAYO,SAAS,IAAI,QAAwB;AAC1C,QAAM,OAAO,CAAC,UAA0B,OAAO,WAAW,KAAK,UAAU,KAAK,CAAC;AAC/E,QAAM,OAAe,EAAE,GAAG,QAAQ,SAAS,OAAO,QAAQ,MAAM,CAAC,WAAW,EAAE;AAK9E,SAAO,KAAK,QAAQ,SAAS,KAAK,KAAK,IAAI,IAAI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QAAiB,KAAK,MAAM,GAAG;AACrC,UAAM,UACJ,SAAS,WACL,MAAM,cAAc,OAAO,IAAI,IAC/B,SAAS,WACP,MAAM,cAAc,OAAO,IAAI,IAC/B,SAAS,cACP,MAAM,iBAAiB,OAAO,IAAI,IAClC,MAAM,kBAAkB,OAAO,IAAI;AAC7C,eAAW,QAAQ;AAAA,EACrB,QAAQ;AACN,eAAW;AAAA,EACb;AACA,MAAI,aAAa,KAAM,IAAG,OAAO,MAAM,GAAG,KAAK,UAAU,QAAQ,CAAC;AAAA,CAAI;AACxE;AAEA,eAAe,YAA6B;AAC1C,SAAO,IAAI,QAAQ,CAAC,SAAS,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,cAAQ,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":[]}
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
3
3
 
4
4
  // src/index.ts
5
- var MIN_NODE_MAJOR = 22;
5
+ var MIN_NODE_MAJOR = 24;
6
6
  var nodeMajor = Number.parseInt(process.versions.node.split(".")[0] ?? "", 10);
7
7
  if (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {
8
8
  const envelope = {
@@ -12,7 +12,7 @@ if (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {
12
12
  error: {
13
13
  code: "NODE_UNSUPPORTED",
14
14
  message: `Tenjin CLI requires Node ${MIN_NODE_MAJOR} or newer (found ${process.versions.node}).`,
15
- fix: "Install Node 22 or newer"
15
+ fix: "Install Node 24 or newer"
16
16
  }
17
17
  };
18
18
  process.stdout.write(`${JSON.stringify(envelope, null, 2)}
@@ -21,6 +21,11 @@ if (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {
21
21
  `);
22
22
  process.exit(1);
23
23
  }
24
- var { main } = await import("./cli-KKRKBU5T.js");
24
+ if (process.argv.length === 3 && process.argv[2] === "status-line") {
25
+ const { statusLineMain } = await import("./status-line-SAXSU6CR.js");
26
+ await statusLineMain();
27
+ process.exit(0);
28
+ }
29
+ var { main } = await import("./cli-VHYYYYXM.js");
25
30
  process.exit(await main(process.argv.slice(2)));
26
31
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n// Bin entry. The Node version guard runs BEFORE importing anything else — no\n// static imports above it — so an out-of-support runtime gets one JSON error\n// envelope plus a human stderr line instead of a syntax/parse crash from a\n// lazily-loaded module written in newer syntax. Kept in conservative syntax.\nconst MIN_NODE_MAJOR = 22;\n\nconst nodeMajor = Number.parseInt(process.versions.node.split('.')[0] ?? '', 10);\n\nif (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {\n const envelope = {\n schemaVersion: 1,\n command: 'preflight',\n ok: false,\n error: {\n code: 'NODE_UNSUPPORTED',\n message: `Tenjin CLI requires Node ${MIN_NODE_MAJOR} or newer (found ${process.versions.node}).`,\n fix: 'Install Node 22 or newer',\n },\n };\n process.stdout.write(`${JSON.stringify(envelope, null, 2)}\\n`);\n process.stderr.write(`error: Node ${MIN_NODE_MAJOR}+ required, found ${process.versions.node}\\n`);\n process.exit(1);\n}\n\nconst { main } = await import('./cli');\nprocess.exit(await main(process.argv.slice(2)));\n\n// Marks this file a module so top-level await is legal; emits nothing.\nexport {};\n"],"mappings":";;;;AAKA,IAAM,iBAAiB;AAEvB,IAAM,YAAY,OAAO,SAAS,QAAQ,SAAS,KAAK,MAAM,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE;AAE/E,IAAI,OAAO,MAAM,SAAS,KAAK,YAAY,gBAAgB;AACzD,QAAM,WAAW;AAAA,IACf,eAAe;AAAA,IACf,SAAS;AAAA,IACT,IAAI;AAAA,IACJ,OAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS,4BAA4B,cAAc,oBAAoB,QAAQ,SAAS,IAAI;AAAA,MAC5F,KAAK;AAAA,IACP;AAAA,EACF;AACA,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,CAAC;AAAA,CAAI;AAC7D,UAAQ,OAAO,MAAM,eAAe,cAAc,qBAAqB,QAAQ,SAAS,IAAI;AAAA,CAAI;AAChG,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAM,EAAE,KAAK,IAAI,MAAM,OAAO,mBAAO;AACrC,QAAQ,KAAK,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\n// Bin entry. The Node version guard runs BEFORE importing anything else — no\n// static imports above it — so an out-of-support runtime gets one JSON error\n// envelope plus a human stderr line instead of a syntax/parse crash from a\n// lazily-loaded module written in newer syntax. Kept in conservative syntax.\nconst MIN_NODE_MAJOR = 24;\n\nconst nodeMajor = Number.parseInt(process.versions.node.split('.')[0] ?? '', 10);\n\nif (Number.isNaN(nodeMajor) || nodeMajor < MIN_NODE_MAJOR) {\n const envelope = {\n schemaVersion: 1,\n command: 'preflight',\n ok: false,\n error: {\n code: 'NODE_UNSUPPORTED',\n message: `Tenjin CLI requires Node ${MIN_NODE_MAJOR} or newer (found ${process.versions.node}).`,\n fix: 'Install Node 24 or newer',\n },\n };\n process.stdout.write(`${JSON.stringify(envelope, null, 2)}\\n`);\n process.stderr.write(`error: Node ${MIN_NODE_MAJOR}+ required, found ${process.versions.node}\\n`);\n process.exit(1);\n}\n\n// THE STATUS LINE NEVER LOADS THE CLI. Claude Code runs it once a second for as\n// long as a session is open, and commander, zod and the command tree are parse\n// cost it has no use for. Only the bare invocation is diverted; `--help` and\n// every flag fall through to the command tree, which registers it like any verb.\nif (process.argv.length === 3 && process.argv[2] === 'status-line') {\n const { statusLineMain } = await import('./router/status-line');\n await statusLineMain();\n process.exit(0);\n}\n\nconst { main } = await import('./cli');\nprocess.exit(await main(process.argv.slice(2)));\n\n// Marks this file a module so top-level await is legal; emits nothing.\nexport {};\n"],"mappings":";;;;AAKA,IAAM,iBAAiB;AAEvB,IAAM,YAAY,OAAO,SAAS,QAAQ,SAAS,KAAK,MAAM,GAAG,EAAE,CAAC,KAAK,IAAI,EAAE;AAE/E,IAAI,OAAO,MAAM,SAAS,KAAK,YAAY,gBAAgB;AACzD,QAAM,WAAW;AAAA,IACf,eAAe;AAAA,IACf,SAAS;AAAA,IACT,IAAI;AAAA,IACJ,OAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS,4BAA4B,cAAc,oBAAoB,QAAQ,SAAS,IAAI;AAAA,MAC5F,KAAK;AAAA,IACP;AAAA,EACF;AACA,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,CAAC;AAAA,CAAI;AAC7D,UAAQ,OAAO,MAAM,eAAe,cAAc,qBAAqB,QAAQ,SAAS,IAAI;AAAA,CAAI;AAChG,UAAQ,KAAK,CAAC;AAChB;AAMA,IAAI,QAAQ,KAAK,WAAW,KAAK,QAAQ,KAAK,CAAC,MAAM,eAAe;AAClE,QAAM,EAAE,eAAe,IAAI,MAAM,OAAO,2BAAsB;AAC9D,QAAM,eAAe;AACrB,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAM,EAAE,KAAK,IAAI,MAAM,OAAO,mBAAO;AACrC,QAAQ,KAAK,MAAM,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC;","names":[]}
@@ -0,0 +1,60 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ ALLOW_RULE,
4
+ DELEGATION_MATCHER,
5
+ DISCLOSURE,
6
+ HOOK_TIMEOUT_SECONDS,
7
+ MCP_ADD_COMMAND,
8
+ NATIVE_MATCHER,
9
+ classifyMcpEntry,
10
+ mcpAddCommand,
11
+ mcpRemoveCommand,
12
+ mcpScope,
13
+ readMcpEntry,
14
+ routerHookPlan,
15
+ routerSettingsPath,
16
+ runRouterInstall,
17
+ statusLineProblems
18
+ } from "./chunk-O4ZNKFRU.js";
19
+ import {
20
+ MCP_SERVER_NAME
21
+ } from "./chunk-TGLKKLQG.js";
22
+ import "./chunk-WLMJE3GJ.js";
23
+ import "./chunk-KK4YGYTV.js";
24
+ import "./chunk-WXC57XGG.js";
25
+ import "./chunk-2QYORQBF.js";
26
+ import "./chunk-MEFB5KHA.js";
27
+ import "./chunk-TP4D47BY.js";
28
+ import "./chunk-WS4JA6TC.js";
29
+ import "./chunk-2I4QTOLB.js";
30
+ import "./chunk-PDA2BVFY.js";
31
+ import "./chunk-U2DZISAH.js";
32
+ import "./chunk-AR7U7BRG.js";
33
+ import "./chunk-2JGT3KDW.js";
34
+ import {
35
+ pruneHooks
36
+ } from "./chunk-XZOEUYMX.js";
37
+ import "./chunk-5UDD5VSY.js";
38
+ import "./chunk-JLEF5WHM.js";
39
+ import "./chunk-2BKS2FVE.js";
40
+ import "./chunk-ZXTAQYNA.js";
41
+ export {
42
+ ALLOW_RULE,
43
+ DELEGATION_MATCHER,
44
+ DISCLOSURE,
45
+ HOOK_TIMEOUT_SECONDS,
46
+ MCP_ADD_COMMAND,
47
+ MCP_SERVER_NAME,
48
+ NATIVE_MATCHER,
49
+ classifyMcpEntry,
50
+ mcpAddCommand,
51
+ mcpRemoveCommand,
52
+ mcpScope,
53
+ pruneHooks,
54
+ readMcpEntry,
55
+ routerHookPlan,
56
+ routerSettingsPath,
57
+ runRouterInstall,
58
+ statusLineProblems
59
+ };
60
+ //# sourceMappingURL=install-OKDKGUXM.js.map
@@ -0,0 +1,106 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ runWalletCreate
4
+ } from "./chunk-LJ4DMVFI.js";
5
+ import "./chunk-56MOAIP5.js";
6
+ import {
7
+ describeWallet,
8
+ resolveWalletProvider,
9
+ walletFileExists
10
+ } from "./chunk-KUBEYXSO.js";
11
+ import "./chunk-AUKDYPPX.js";
12
+ import "./chunk-35M3VITA.js";
13
+ import "./chunk-AWQPGIR6.js";
14
+ import "./chunk-N35E6CM2.js";
15
+ import "./chunk-JRGFKVAZ.js";
16
+ import "./chunk-5IEP5EGE.js";
17
+ import "./chunk-EGELTSPU.js";
18
+ import "./chunk-KG3D7FIF.js";
19
+ import "./chunk-RBJPAZFI.js";
20
+ import "./chunk-BPMWXTFX.js";
21
+ import "./chunk-WLMJE3GJ.js";
22
+ import {
23
+ confirmChoice
24
+ } from "./chunk-2QYORQBF.js";
25
+ import "./chunk-MEFB5KHA.js";
26
+ import "./chunk-2I4QTOLB.js";
27
+ import "./chunk-U2DZISAH.js";
28
+ import "./chunk-AR7U7BRG.js";
29
+ import {
30
+ CliError
31
+ } from "./chunk-JLEF5WHM.js";
32
+ import "./chunk-2BKS2FVE.js";
33
+ import "./chunk-ZXTAQYNA.js";
34
+
35
+ // src/commands/install-wallet.ts
36
+ var WALLET_QUESTION = "Create a wallet now?";
37
+ function walletFix(reason) {
38
+ switch (reason) {
39
+ case "no-passphrase-store":
40
+ return "No OS credential store is available to hold the wallet passphrase. Set TENJIN_WALLET_PASSPHRASE and re-run `tenjin install`, or run `tenjin wallet create` in a terminal to enter one.";
41
+ case "create-failed":
42
+ return "Fix the reported problem, then run `tenjin wallet create`.";
43
+ case "dry-run":
44
+ case "flag":
45
+ return "Create one with `tenjin wallet create`.";
46
+ }
47
+ }
48
+ function walletValue(w) {
49
+ if (w.status === "existing") return `${w.address} (existing)`;
50
+ if (w.status === "created") return `${w.address}, $0 - fund with: tenjin wallet fund`;
51
+ if (w.status === "skipped") return `none (${w.reason}) - ${w.fix}`;
52
+ return "none - create with: tenjin wallet create";
53
+ }
54
+ async function resolveWallet(ctx, deps, skipReason, canPrompt) {
55
+ const exists = await (deps.walletExists ?? walletFileExists)(ctx.dataDir);
56
+ if (exists) {
57
+ return {
58
+ status: "existing",
59
+ address: await (deps.walletAddress ?? existingWalletAddress)(ctx)
60
+ };
61
+ }
62
+ if (skipReason !== void 0) {
63
+ return { status: "skipped", reason: skipReason, fix: walletFix(skipReason) };
64
+ }
65
+ if (canPrompt) {
66
+ const confirm = deps.confirmWallet ?? defaultConfirm;
67
+ if (!await confirm(WALLET_QUESTION)) return { status: "declined" };
68
+ }
69
+ try {
70
+ const create = deps.createWallet ?? ((c) => defaultCreateWallet(c, deps.walletPassphrase, deps.env));
71
+ return { status: "created", address: await create(ctx) };
72
+ } catch (err) {
73
+ const reason = isNoPassphraseError(err) ? "no-passphrase-store" : "create-failed";
74
+ return {
75
+ status: "skipped",
76
+ reason,
77
+ fix: walletFix(reason),
78
+ ...reason === "create-failed" ? { warning: `The wallet could not be created: ${errorText(err)}` } : {}
79
+ };
80
+ }
81
+ }
82
+ function isNoPassphraseError(err) {
83
+ return err instanceof CliError && err.code === "USAGE" && err.message.includes("No wallet passphrase is available");
84
+ }
85
+ function errorText(err) {
86
+ return err instanceof Error ? err.message : String(err);
87
+ }
88
+ async function existingWalletAddress(ctx) {
89
+ return (await describeWallet(resolveWalletProvider(ctx))).address;
90
+ }
91
+ async function defaultCreateWallet(ctx, passphrase, env) {
92
+ const result = await runWalletCreate(ctx, {
93
+ ...passphrase !== void 0 ? { passphrase } : {},
94
+ ...env !== void 0 ? { env } : {}
95
+ });
96
+ return result.data.address;
97
+ }
98
+ function defaultConfirm(label) {
99
+ return confirmChoice(label, true);
100
+ }
101
+ export {
102
+ WALLET_QUESTION,
103
+ resolveWallet,
104
+ walletValue
105
+ };
106
+ //# sourceMappingURL=install-wallet-SI4LZ73K.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/install-wallet.ts"],"sourcesContent":["import { CliError } from '../lib/errors';\nimport { confirmChoice } from '../lib/clack';\nimport { describeWallet, resolveWalletProvider } from '../lib/wallet';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport { walletFileExists } from '../lib/wallet/store';\nimport { runWalletCreate } from './wallet';\nimport type { CommandContext } from '../context';\n\n/**\n * The wallet step `tenjin install` runs: keep the wallet this machine has, or\n * create one. Shared by the router install and the shelf install so the two\n * can never disagree about when a wallet is made or what a skip tells you.\n */\n\n/** The wallet question's literal copy. */\nexport const WALLET_QUESTION = 'Create a wallet now?';\n\n/** The seams the wallet step reads; every one defaults to the real thing. */\nexport interface WalletDeps {\n env?: NodeJS.ProcessEnv;\n /** \"Create a wallet now?\"; defaults to the clack confirm (default yes). */\n confirmWallet?: (label: string) => Promise<boolean>;\n /** Does a wallet already exist? Defaults to walletFileExists(dataDir). */\n walletExists?: (dataDir: string) => Promise<boolean>;\n /** An existing wallet's address. Defaults to the local provider. */\n walletAddress?: (ctx: CommandContext) => Promise<string>;\n /** Create a wallet and return its address. Defaults to runWalletCreate. */\n createWallet?: (ctx: CommandContext) => Promise<string>;\n /**\n * Passphrase-resolution seam forwarded to `wallet create`. Tests MUST set it\n * (or `createWallet`): without it a headless run creates a real wallet, and\n * on macOS that writes to the developer's own login keychain.\n */\n walletPassphrase?: PassphraseOverrides;\n}\n\n/**\n * Why no wallet was created, when none was.\n *\n * `no-passphrase-store` is the one that matters: this machine has no OS\n * credential store that would hold a generated passphrase, and no\n * `TENJIN_WALLET_PASSPHRASE`. There is no fallback here BY DESIGN. A passphrase\n * written to a plain file beside the keystore it unlocks is not a passphrase, so\n * the run creates nothing and says so loudly with both remedies.\n */\nexport type WalletSkipReason = 'no-passphrase-store' | 'create-failed' | 'dry-run' | 'flag';\n\n/**\n * How the wallet step resolved, so rendering stays separate from prompting.\n *\n * `declined` (an answer) and `skipped` (no answer, with a reason) are kept apart\n * deliberately: an install that could not create a key is a different state from\n * one the operator told not to, and only the first needs a remedy.\n */\nexport interface WalletOutcome {\n status: 'existing' | 'created' | 'declined' | 'skipped';\n address?: string;\n /** Only ever set on `skipped`. */\n reason?: WalletSkipReason;\n /** The exact command that changes this outcome, mirroring the CliError contract. */\n fix?: string;\n /** The underlying failure, for a `create-failed` skip. */\n warning?: string;\n}\n\n/** The remedy for each skip, so no skipped state is ever a dead end. */\nfunction walletFix(reason: WalletSkipReason): string {\n switch (reason) {\n case 'no-passphrase-store':\n return 'No OS credential store is available to hold the wallet passphrase. Set TENJIN_WALLET_PASSPHRASE and re-run `tenjin install`, or run `tenjin wallet create` in a terminal to enter one.';\n case 'create-failed':\n return 'Fix the reported problem, then run `tenjin wallet create`.';\n case 'dry-run':\n case 'flag':\n return 'Create one with `tenjin wallet create`.';\n }\n}\n\nexport function walletValue(w: WalletOutcome): string {\n if (w.status === 'existing') return `${w.address} (existing)`;\n if (w.status === 'created') return `${w.address}, $0 - fund with: tenjin wallet fund`;\n if (w.status === 'skipped') return `none (${w.reason}) - ${w.fix}`;\n return 'none - create with: tenjin wallet create';\n}\n\n/**\n * The wallet decision. A wallet is now created BY DEFAULT on both paths, because\n * the loop this command exists to set up does not close without one: `buy` needs\n * a funded key and publish-on-MISS needs a key to sign the write, so a walletless\n * install is a setup that stops at the first useful thing the agent tries.\n *\n * The headless path is the change. It creates without asking, using the\n * passphrase policy `resolvePassphraseForCreate` already enforces: an explicit\n * `TENJIN_WALLET_PASSPHRASE`, else a strong generated passphrase written to the\n * platform's OS credential store and verified by reading it back. When neither is\n * available it creates NOTHING and reports `skipped: no-passphrase-store` with\n * both remedies. There is deliberately no plain-file fallback: a passphrase\n * sitting next to the keystore it unlocks protects nothing, and an install is\n * never the right place to invent one.\n *\n * A creation failure never fails the install. The skills, hooks and permissions\n * this run just wired are all useful without a wallet, so the failure is reported\n * loudly and the command still succeeds.\n */\nexport async function resolveWallet(\n ctx: CommandContext,\n deps: WalletDeps,\n skipReason: 'dry-run' | 'flag' | undefined,\n canPrompt: boolean,\n): Promise<WalletOutcome> {\n const exists = await (deps.walletExists ?? walletFileExists)(ctx.dataDir);\n if (exists) {\n return {\n status: 'existing',\n address: await (deps.walletAddress ?? existingWalletAddress)(ctx),\n };\n }\n if (skipReason !== undefined) {\n return { status: 'skipped', reason: skipReason, fix: walletFix(skipReason) };\n }\n\n // Interactive keeps the question (default yes); headless has nobody to ask and\n // takes the default rather than treating silence as a no.\n if (canPrompt) {\n const confirm = deps.confirmWallet ?? defaultConfirm;\n if (!(await confirm(WALLET_QUESTION))) return { status: 'declined' };\n }\n\n try {\n const create =\n deps.createWallet ??\n ((c: CommandContext) => defaultCreateWallet(c, deps.walletPassphrase, deps.env));\n return { status: 'created', address: await create(ctx) };\n } catch (err) {\n // The one failure with a real remedy: no env passphrase and no OS store, so\n // resolvePassphraseForCreate refused rather than encrypt with a passphrase\n // that has no durable copy. Anything else is reported as itself.\n const reason: WalletSkipReason = isNoPassphraseError(err)\n ? 'no-passphrase-store'\n : 'create-failed';\n return {\n status: 'skipped',\n reason,\n fix: walletFix(reason),\n ...(reason === 'create-failed'\n ? { warning: `The wallet could not be created: ${errorText(err)}` }\n : {}),\n };\n }\n}\n\n/** Is this the passphrase layer refusing because no durable store could serve? */\nfunction isNoPassphraseError(err: unknown): boolean {\n return (\n err instanceof CliError &&\n err.code === 'USAGE' &&\n err.message.includes('No wallet passphrase is available')\n );\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nasync function existingWalletAddress(ctx: CommandContext): Promise<string> {\n return (await describeWallet(resolveWalletProvider(ctx))).address;\n}\n\nasync function defaultCreateWallet(\n ctx: CommandContext,\n passphrase?: PassphraseOverrides,\n env?: NodeJS.ProcessEnv,\n): Promise<string> {\n const result = await runWalletCreate(ctx, {\n ...(passphrase !== undefined ? { passphrase } : {}),\n ...(env !== undefined ? { env } : {}),\n });\n return (result.data as { address: string }).address;\n}\n\n/** The shared confirm, defaulting to YES (setup ergonomics); cancel reads as no. */\nfunction defaultConfirm(label: string): Promise<boolean> {\n return confirmChoice(label, true);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,IAAM,kBAAkB;AAmD/B,SAAS,UAAU,QAAkC;AACnD,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,EACX;AACF;AAEO,SAAS,YAAY,GAA0B;AACpD,MAAI,EAAE,WAAW,WAAY,QAAO,GAAG,EAAE,OAAO;AAChD,MAAI,EAAE,WAAW,UAAW,QAAO,GAAG,EAAE,OAAO;AAC/C,MAAI,EAAE,WAAW,UAAW,QAAO,SAAS,EAAE,MAAM,OAAO,EAAE,GAAG;AAChE,SAAO;AACT;AAqBA,eAAsB,cACpB,KACA,MACA,YACA,WACwB;AACxB,QAAM,SAAS,OAAO,KAAK,gBAAgB,kBAAkB,IAAI,OAAO;AACxE,MAAI,QAAQ;AACV,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SAAS,OAAO,KAAK,iBAAiB,uBAAuB,GAAG;AAAA,IAClE;AAAA,EACF;AACA,MAAI,eAAe,QAAW;AAC5B,WAAO,EAAE,QAAQ,WAAW,QAAQ,YAAY,KAAK,UAAU,UAAU,EAAE;AAAA,EAC7E;AAIA,MAAI,WAAW;AACb,UAAM,UAAU,KAA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