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,171 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ MCP_SERVER_NAME,
4
+ REQUEST_TOOL
5
+ } from "./chunk-TGLKKLQG.js";
6
+
7
+ // src/router/agent-tools.ts
8
+ import { readdir, readFile } from "node:fs/promises";
9
+ import { dirname, join, resolve } from "node:path";
10
+ var MCP_INHERITING_BUILTINS = /* @__PURE__ */ new Set([
11
+ "general-purpose",
12
+ "Explore",
13
+ "Plan"
14
+ ]);
15
+ var MAX_AGENT_FILE_BYTES = 256 * 1024;
16
+ var TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;
17
+ async function requestToolAccess(agentType, lookup) {
18
+ if (agentType === void 0 || !TYPE_RE.test(agentType)) return "unknown";
19
+ try {
20
+ const text = await findDefinition(agentType, lookup);
21
+ if (text !== null) return accessOf(text);
22
+ return MCP_INHERITING_BUILTINS.has(agentType) ? "allowed" : "unknown";
23
+ } catch {
24
+ return "unknown";
25
+ }
26
+ }
27
+ function accessOf(definition) {
28
+ const frontmatter = frontmatterOf(definition);
29
+ if (frontmatter === null) return "unknown";
30
+ const disallowed = listField(frontmatter, "disallowedTools");
31
+ if (disallowed !== void 0 && disallowed.some(namesRequestTool)) return "excluded";
32
+ const tools = listField(frontmatter, "tools");
33
+ if (tools === void 0) return "allowed";
34
+ return tools.some(namesRequestTool) ? "allowed" : "excluded";
35
+ }
36
+ function namesRequestTool(tool) {
37
+ if (tool === REQUEST_TOOL || tool === `mcp__${MCP_SERVER_NAME}`) return true;
38
+ return tool.endsWith("*") && REQUEST_TOOL.startsWith(tool.slice(0, -1));
39
+ }
40
+ async function agentsWithoutRequestTool(lookup) {
41
+ const found = [];
42
+ const seen = /* @__PURE__ */ new Set();
43
+ for (const directory of agentDirs(lookup)) {
44
+ for (const { name, text } of await definitionsIn(directory)) {
45
+ const type = nameOf(text) ?? name;
46
+ if (seen.has(type)) continue;
47
+ seen.add(type);
48
+ if (accessOf(text) === "excluded") found.push(type);
49
+ }
50
+ }
51
+ return found.sort();
52
+ }
53
+ async function findDefinition(agentType, lookup) {
54
+ for (const directory of agentDirs(lookup)) {
55
+ const text = await definitionIn(directory, agentType);
56
+ if (text !== null) return text;
57
+ }
58
+ const colon = agentType.indexOf(":");
59
+ if (colon > 0) {
60
+ const plugin = agentType.slice(0, colon);
61
+ const agent = agentType.slice(colon + 1);
62
+ for (const root of await pluginRoots(plugin, lookup.homeDir)) {
63
+ const text = await definitionIn(join(root, "agents"), agent);
64
+ if (text !== null) return text;
65
+ }
66
+ }
67
+ return null;
68
+ }
69
+ function agentDirs(lookup) {
70
+ const dirs = [];
71
+ if (lookup.cwd !== void 0 && lookup.cwd.length > 0) {
72
+ let current = resolve(lookup.cwd);
73
+ for (; ; ) {
74
+ dirs.push(join(current, ".claude", "agents"));
75
+ const parent = dirname(current);
76
+ if (parent === current) break;
77
+ current = parent;
78
+ }
79
+ }
80
+ const user = join(resolve(lookup.homeDir), ".claude", "agents");
81
+ return [...dirs.filter((d) => d !== user), user];
82
+ }
83
+ async function definitionIn(directory, agentType) {
84
+ const direct = await readBounded(join(directory, `${agentType}.md`));
85
+ if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;
86
+ for (const { text } of await definitionsIn(directory)) {
87
+ if (nameOf(text) === agentType) return text;
88
+ }
89
+ return null;
90
+ }
91
+ async function definitionsIn(directory) {
92
+ let names;
93
+ try {
94
+ names = (await readdir(directory)).filter((n) => n.endsWith(".md")).slice(0, 200);
95
+ } catch {
96
+ return [];
97
+ }
98
+ const out = [];
99
+ for (const file of names) {
100
+ const text = await readBounded(join(directory, file));
101
+ if (text !== null) out.push({ name: file.slice(0, -3), text });
102
+ }
103
+ return out;
104
+ }
105
+ async function pluginRoots(plugin, homeDir) {
106
+ const raw = await readBounded(join(homeDir, ".claude", "plugins", "installed_plugins.json"));
107
+ if (raw === null) return [];
108
+ const parsed = JSON.parse(raw);
109
+ const roots = [];
110
+ for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {
111
+ if (key.split("@")[0] !== plugin || !Array.isArray(entries)) continue;
112
+ for (const entry of entries) {
113
+ const path = entry.installPath;
114
+ if (typeof path === "string" && path.length > 0) roots.push(path);
115
+ }
116
+ }
117
+ return roots;
118
+ }
119
+ async function readBounded(path) {
120
+ try {
121
+ const text = await readFile(path, "utf8");
122
+ return text.length > MAX_AGENT_FILE_BYTES ? null : text;
123
+ } catch {
124
+ return null;
125
+ }
126
+ }
127
+ function frontmatterOf(text) {
128
+ const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
129
+ const open = lines.findIndex((l) => l.trim().length > 0);
130
+ if (open === -1 || lines[open]?.trim() !== "---") return null;
131
+ const end = lines.findIndex((l, i) => i > open && l.trim() === "---");
132
+ return end === -1 ? null : lines.slice(open + 1, end);
133
+ }
134
+ function nameOf(text) {
135
+ const frontmatter = frontmatterOf(text);
136
+ if (frontmatter === null) return null;
137
+ const line = frontmatter.find((l) => /^name\s*:/.test(l));
138
+ const value = line === void 0 ? "" : unquote(line.slice(line.indexOf(":") + 1).trim());
139
+ return value.length > 0 ? value : null;
140
+ }
141
+ function listField(frontmatter, key) {
142
+ const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\s*:`).test(l));
143
+ if (index === -1) return void 0;
144
+ const line = frontmatter[index];
145
+ const inline = line.slice(line.indexOf(":") + 1).trim();
146
+ if (inline.length > 0) {
147
+ const body = inline.startsWith("[") && inline.endsWith("]") ? inline.slice(1, -1) : inline;
148
+ return body.split(",").map((part) => unquote(part.trim())).filter((part) => part.length > 0);
149
+ }
150
+ const items = [];
151
+ for (const next of frontmatter.slice(index + 1)) {
152
+ const item = /^\s+-\s*(.*)$/.exec(next);
153
+ if (item === null) {
154
+ if (next.trim().length === 0) continue;
155
+ break;
156
+ }
157
+ const value = unquote(item[1].trim());
158
+ if (value.length > 0) items.push(value);
159
+ }
160
+ return items;
161
+ }
162
+ function unquote(value) {
163
+ const quoted = /^(['"])(.*)\1$/.exec(value);
164
+ return quoted === null ? value : quoted[2];
165
+ }
166
+
167
+ export {
168
+ requestToolAccess,
169
+ agentsWithoutRequestTool
170
+ };
171
+ //# sourceMappingURL=chunk-S2NRVRPF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/agent-tools.ts"],"sourcesContent":["import { readdir, readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { MCP_SERVER_NAME, REQUEST_TOOL } from './names';\n\n/**\n * CAN THIS SUBAGENT CALL `request` AT ALL? An offer to an agent whose definition\n * leaves the tool out is a line it cannot act on, and a router call spent to\n * write it. Claude Code defines a custom agent in a Markdown file whose\n * frontmatter may carry `tools:` (an allowlist) and `disallowedTools:`; this\n * reads that, and nothing else, and never writes to it.\n *\n * ONLY `allowed` IS ACTED ON. A subagent is redirected or offered a lookup\n * only when this KNOWS it can make the call: a definition whose tools cover\n * the request tool (or that has no `tools:` and so inherits everything), or a\n * built-in in {@link MCP_INHERITING_BUILTINS}. Every other built-in, and any\n * type with no definition this can find or read, is `unknown`, and `unknown`\n * gets no router call: `claude-code-guide` ships with Bash, Read, WebFetch and\n * WebSearch and no MCP tools, and denying its WebFetch would strand it exactly\n * as #377 reported.\n *\n * WHERE A DEFINITION LIVES, in the harness's own precedence: the project's\n * `.claude/agents` (from `cwd` up to the filesystem root, nearest first), then\n * `~/.claude/agents`, then an installed plugin's `agents/` for a `plugin:agent`\n * type. A file is found by its name first and by its frontmatter `name:`\n * second, because the type is the `name:` and the file name only usually\n * matches it.\n */\n\nexport type RequestToolAccess = 'allowed' | 'excluded' | 'unknown';\n\n/**\n * The built-in agent types that have no definition file and still inherit MCP\n * tools, so can call `mcp__x402__request`. From Claude Code's own Agent tool\n * listing (2.1.28x): `general-purpose` has every tool, and `Explore` and `Plan`\n * exclude only editing and agent tools, never MCP. Built-ins with a fixed tool\n * list, such as `claude-code-guide` (Bash, Read, WebFetch, WebSearch) and\n * `statusline-setup` (Read, Edit), are deliberately absent.\n */\nexport const MCP_INHERITING_BUILTINS: ReadonlySet<string> = new Set([\n 'general-purpose',\n 'Explore',\n 'Plan',\n]);\n\nexport interface AgentLookup {\n cwd?: string;\n homeDir: string;\n}\n\nconst MAX_AGENT_FILE_BYTES = 256 * 1024;\nconst TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;\n\nexport async function requestToolAccess(\n agentType: string | undefined,\n lookup: AgentLookup,\n): Promise<RequestToolAccess> {\n if (agentType === undefined || !TYPE_RE.test(agentType)) return 'unknown';\n try {\n const text = await findDefinition(agentType, lookup);\n if (text !== null) return accessOf(text);\n return MCP_INHERITING_BUILTINS.has(agentType) ? 'allowed' : 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n/** What one definition's frontmatter says about the request tool. */\nexport function accessOf(definition: string): RequestToolAccess {\n const frontmatter = frontmatterOf(definition);\n if (frontmatter === null) return 'unknown';\n const disallowed = listField(frontmatter, 'disallowedTools');\n if (disallowed !== undefined && disallowed.some(namesRequestTool)) return 'excluded';\n const tools = listField(frontmatter, 'tools');\n if (tools === undefined) return 'allowed';\n return tools.some(namesRequestTool) ? 'allowed' : 'excluded';\n}\n\n/**\n * Does one `tools:` or `disallowedTools:` entry cover the request tool? The\n * tool itself, the bare server, or any `*`-suffixed pattern the tool's name\n * starts with: `*`, `mcp__*`, `mcp__x402__*` and every prefix between.\n */\nfunction namesRequestTool(tool: string): boolean {\n if (tool === REQUEST_TOOL || tool === `mcp__${MCP_SERVER_NAME}`) return true;\n return tool.endsWith('*') && REQUEST_TOOL.startsWith(tool.slice(0, -1));\n}\n\n/**\n * Every custom agent this project and this user define whose tools leave the\n * request tool out, for `doctor` to name. Plugin agents are not listed: their\n * files are not the user's to edit.\n */\nexport async function agentsWithoutRequestTool(lookup: AgentLookup): Promise<string[]> {\n const found: string[] = [];\n const seen = new Set<string>();\n for (const directory of agentDirs(lookup)) {\n for (const { name, text } of await definitionsIn(directory)) {\n const type = nameOf(text) ?? name;\n if (seen.has(type)) continue;\n seen.add(type);\n if (accessOf(text) === 'excluded') found.push(type);\n }\n }\n return found.sort();\n}\n\nasync function findDefinition(agentType: string, lookup: AgentLookup): Promise<string | null> {\n for (const directory of agentDirs(lookup)) {\n const text = await definitionIn(directory, agentType);\n if (text !== null) return text;\n }\n const colon = agentType.indexOf(':');\n if (colon > 0) {\n const plugin = agentType.slice(0, colon);\n const agent = agentType.slice(colon + 1);\n for (const root of await pluginRoots(plugin, lookup.homeDir)) {\n const text = await definitionIn(join(root, 'agents'), agent);\n if (text !== null) return text;\n }\n }\n return null;\n}\n\nfunction agentDirs(lookup: AgentLookup): string[] {\n const dirs: string[] = [];\n if (lookup.cwd !== undefined && lookup.cwd.length > 0) {\n let current = resolve(lookup.cwd);\n for (;;) {\n dirs.push(join(current, '.claude', 'agents'));\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n }\n const user = join(resolve(lookup.homeDir), '.claude', 'agents');\n // The user's directory is also an ancestor of most projects; it counts once,\n // in its own place in the order.\n return [...dirs.filter((d) => d !== user), user];\n}\n\nasync function definitionIn(directory: string, agentType: string): Promise<string | null> {\n const direct = await readBounded(join(directory, `${agentType}.md`));\n if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;\n for (const { text } of await definitionsIn(directory)) {\n if (nameOf(text) === agentType) return text;\n }\n return null;\n}\n\nasync function definitionsIn(directory: string): Promise<{ name: string; text: string }[]> {\n let names: string[];\n try {\n names = (await readdir(directory)).filter((n) => n.endsWith('.md')).slice(0, 200);\n } catch {\n return [];\n }\n const out: { name: string; text: string }[] = [];\n for (const file of names) {\n const text = await readBounded(join(directory, file));\n if (text !== null) out.push({ name: file.slice(0, -3), text });\n }\n return out;\n}\n\n/** Install paths `installed_plugins.json` records for `<plugin>@<marketplace>`. */\nasync function pluginRoots(plugin: string, homeDir: string): Promise<string[]> {\n const raw = await readBounded(join(homeDir, '.claude', 'plugins', 'installed_plugins.json'));\n if (raw === null) return [];\n const parsed = JSON.parse(raw) as { plugins?: Record<string, unknown> };\n const roots: string[] = [];\n for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {\n if (key.split('@')[0] !== plugin || !Array.isArray(entries)) continue;\n for (const entry of entries) {\n const path = (entry as { installPath?: unknown }).installPath;\n if (typeof path === 'string' && path.length > 0) roots.push(path);\n }\n }\n return roots;\n}\n\nasync function readBounded(path: string): Promise<string | null> {\n try {\n const text = await readFile(path, 'utf8');\n return text.length > MAX_AGENT_FILE_BYTES ? null : text;\n } catch {\n return null;\n }\n}\n\nfunction frontmatterOf(text: string): string[] | null {\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n return end === -1 ? null : lines.slice(open + 1, end);\n}\n\nfunction nameOf(text: string): string | null {\n const frontmatter = frontmatterOf(text);\n if (frontmatter === null) return null;\n const line = frontmatter.find((l) => /^name\\s*:/.test(l));\n const value = line === undefined ? '' : unquote(line.slice(line.indexOf(':') + 1).trim());\n return value.length > 0 ? value : null;\n}\n\n/**\n * A top-level list field in the three spellings agent files use: `a, b, c`,\n * `[a, b]`, or a block of `- a` lines. `undefined` when the key is absent.\n */\nfunction listField(frontmatter: string[], key: string): string[] | undefined {\n const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\\\s*:`).test(l));\n if (index === -1) return undefined;\n const line = frontmatter[index]!;\n const inline = line.slice(line.indexOf(':') + 1).trim();\n if (inline.length > 0) {\n const body = inline.startsWith('[') && inline.endsWith(']') ? inline.slice(1, -1) : inline;\n return body\n .split(',')\n .map((part) => unquote(part.trim()))\n .filter((part) => part.length > 0);\n }\n const items: string[] = [];\n for (const next of frontmatter.slice(index + 1)) {\n const item = /^\\s+-\\s*(.*)$/.exec(next);\n if (item === null) {\n if (next.trim().length === 0) continue;\n break;\n }\n const value = unquote(item[1]!.trim());\n if (value.length > 0) items.push(value);\n }\n return items;\n}\n\nfunction unquote(value: string): string {\n const quoted = /^(['\"])(.*)\\1$/.exec(value);\n return quoted ===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AAC;AACzB,aAAW,QAAQ,YAAY,MAAM,QAAQ,CAAC,GAAG;AAC/C,UAAM,OAAO,gBAAgB,KAAK,IAAI;AACtC,QAAI,SAAS,MAAM;AACjB,UAAI,KAAK,KAAK,EAAE,WAAW,EAAG;AAC9B;AAAA,IACF;AACA,UAAM,QAAQ,QAAQ,KAAK,CAAC,EAAG,KAAK,CAAC;AACrC,QAAI,MAAM,SAAS,EAAG,OAAM,KAAK,KAAK;AAAA,EACxC;AACA,SAAO;AACT;AAEA,SAAS,QAAQ,OAAuB;AACtC,QAAM,SAAS,iBAAiB,KAAK,KAAK;AAC1C,SAAO,WAAW,OAAO,QAAQ,OAAO,CAAC;AAC3C;","names":[]}
@@ -0,0 +1,11 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/router/names.ts
4
+ var MCP_SERVER_NAME = "x402";
5
+ var REQUEST_TOOL = `mcp__${MCP_SERVER_NAME}__request`;
6
+
7
+ export {
8
+ MCP_SERVER_NAME,
9
+ REQUEST_TOOL
10
+ };
11
+ //# sourceMappingURL=chunk-TGLKKLQG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/names.ts"],"sourcesContent":["/**\n * THE NAMES THE HARNESS KNOWS THE ROUTER BY, spelled once. `install` registers\n * the MCP server under {@link MCP_SERVER_NAME}, and Claude Code exposes its tool\n * as {@link REQUEST_TOOL}; the permission rule, the server's own name and every\n * hint line the hooks inject all read these, so a rename moves them together.\n *\n * A module of its own because the hooks need the tool name and must not load\n * `install` to get it: their chunk graph is the product's floor.\n */\nexport const MCP_SERVER_NAME = 'x402';\nexport const REQUEST_TOOL = `mcp__${MCP_SERVER_NAME}__request`;\n"],"mappings":";;;AASO,IAAM,kBAAkB;AACxB,IAAM,eAAe,QAAQ,eAAe;","names":[]}
@@ -0,0 +1,127 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ findAllProjectFiles,
4
+ findNearestProjectFiles,
5
+ mainWorktreeOf,
6
+ ownedCandidates,
7
+ projectRoot
8
+ } from "./chunk-PDA2BVFY.js";
9
+ import {
10
+ CONFIG_DEFAULTS,
11
+ loadRawConfig,
12
+ parseRouterLayer
13
+ } from "./chunk-AR7U7BRG.js";
14
+ import {
15
+ CliError
16
+ } from "./chunk-JLEF5WHM.js";
17
+ import {
18
+ configPath
19
+ } from "./chunk-2BKS2FVE.js";
20
+
21
+ // src/router/settings.ts
22
+ import { readFile } from "node:fs/promises";
23
+ import { homedir } from "node:os";
24
+ import { join, resolve } from "node:path";
25
+ var PROJECT_ROUTER_FILE = join(".tenjin", "config.json");
26
+ var LOCAL_ROUTER_FILE = join(".tenjin", "config.local.json");
27
+ async function routerSettings(input, deps = {}) {
28
+ const globalPath = configPath(input.dataDir);
29
+ const global = (input.config ?? await loadRawConfig(input.dataDir)).router;
30
+ let enabled = {
31
+ value: CONFIG_DEFAULTS.router.enabled,
32
+ source: "default"
33
+ };
34
+ let context = {
35
+ value: CONFIG_DEFAULTS.router.context,
36
+ source: "default"
37
+ };
38
+ if (global?.enabled !== void 0) {
39
+ enabled = { value: global.enabled, source: "file", path: globalPath };
40
+ }
41
+ if (global?.context !== void 0) {
42
+ context = { value: global.context, source: "file", path: globalPath };
43
+ }
44
+ for (const { source, path, layer } of await projectLayers(input, deps)) {
45
+ if (layer.enabled !== void 0 && (layer.enabled === false || enabled.value)) {
46
+ enabled = { value: layer.enabled, source, path };
47
+ }
48
+ if (layer.context !== void 0 && (layer.context === "turn" || context.value === "session")) {
49
+ context = { value: layer.context, source, path };
50
+ }
51
+ }
52
+ return { enabled, context };
53
+ }
54
+ var ROUTER_FILES = [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE];
55
+ async function projectLayers(input, deps) {
56
+ const { levels, gitRoot } = await findAllProjectFiles(input.cwd, ROUTER_FILES, {
57
+ ...deps,
58
+ // $HOME/.tenjin is the global scope, not a project.
59
+ homeIsProject: false
60
+ });
61
+ const main = gitRoot === null ? null : await mainWorktreeOf(gitRoot, deps.homeDir);
62
+ const outer = main === null ? [] : [{ dir: main, found: await ownedCandidates(main, ROUTER_FILES, deps) }];
63
+ const layers = [];
64
+ for (const { dir, found } of [...outer, ...levels.reverse()]) {
65
+ if (resolve(dir, ".tenjin") === resolve(input.dataDir)) continue;
66
+ for (const path of found) {
67
+ const file = await readProjectRouterFile(path);
68
+ if (file === null) continue;
69
+ layers.push({
70
+ source: path === join(dir, LOCAL_ROUTER_FILE) ? "local" : "project",
71
+ path,
72
+ layer: file.layer
73
+ });
74
+ }
75
+ }
76
+ return layers;
77
+ }
78
+ var ABSENT = /* @__PURE__ */ new Set(["ENOENT", "ENOTDIR"]);
79
+ async function readProjectRouterFile(path) {
80
+ let raw;
81
+ try {
82
+ raw = await readFile(path, "utf8");
83
+ } catch (err) {
84
+ if (ABSENT.has(String(err.code))) return null;
85
+ throw invalid(path, "could not be read", err);
86
+ }
87
+ let json;
88
+ try {
89
+ json = JSON.parse(raw);
90
+ } catch (err) {
91
+ throw invalid(path, "is not valid JSON", err);
92
+ }
93
+ const layer = parseRouterLayer(json, path);
94
+ return { json, layer };
95
+ }
96
+ async function projectRouterPath(input, deps = {}) {
97
+ const home = deps.homeDir ?? homedir();
98
+ const hit = await findNearestProjectFiles(input.cwd, [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE], {
99
+ ...deps,
100
+ warn: () => void 0,
101
+ homeIsProject: false
102
+ });
103
+ const dir = hit?.dir ?? await projectRoot(input.cwd, home);
104
+ if (dir === home) {
105
+ throw new CliError(
106
+ "USAGE",
107
+ "Your home directory is not a project: its .tenjin is the global config.",
108
+ {
109
+ fix: "Run it from inside the project, or drop --project to set it for this machine."
110
+ }
111
+ );
112
+ }
113
+ return join(dir, input.local ? LOCAL_ROUTER_FILE : PROJECT_ROUTER_FILE);
114
+ }
115
+ function invalid(path, what, cause) {
116
+ return new CliError("CONFIG_INVALID", `Config at ${path} ${what}`, {
117
+ fix: `Fix ${path}, or delete it.`,
118
+ ...cause !== void 0 ? { cause } : {}
119
+ });
120
+ }
121
+
122
+ export {
123
+ routerSettings,
124
+ readProjectRouterFile,
125
+ projectRouterPath
126
+ };
127
+ //# sourceMappingURL=chunk-TP4D47BY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/settings.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport {\n CONFIG_DEFAULTS,\n loadRawConfig,\n parseRouterLayer,\n type PartialConfig,\n type RouterContext,\n type RouterLayer,\n} from '../lib/config';\nimport { CliError } from '../lib/errors';\nimport { configPath } from '../lib/paths';\nimport {\n findAllProjectFiles,\n findNearestProjectFiles,\n mainWorktreeOf,\n ownedCandidates,\n projectRoot,\n type ProjectWalkDeps,\n} from '../lib/settings';\n\n/**\n * THE ONE READER OF THE ROUTER'S OWN KEYS, `router.enabled` and\n * `router.context`. Both hooks, the `request` tool, doctor, the status line and\n * `tenjin config` call {@link routerSettings} first, and nothing reads a router\n * key any other way.\n *\n * THE LAYERS: the default, `~/.tenjin/config.json`, then EVERY\n * `.tenjin/config.json` and `config.local.json` from the working directory up\n * to the git root, and in a linked git worktree the main checkout's pair too.\n * No environment variable.\n *\n * EVERY LAYER IS A FLOOR. `enabled` is false when any layer says false, and\n * `context` is `turn` when any layer says turn; a key a file leaves out\n * inherits, and a looser value is not read. So a file a cloned repository\n * carries cannot undo `tenjin config set router.enabled false` on this\n * machine, a package in a monorepo cannot undo its root, and a\n * `config.local.json` a repository commits anyway cannot undo the committed\n * one. Both keys fail toward less data sent, and no project file has a spend\n * key to loosen. The source reported is the nearest layer at the value.\n *\n * ONE PARSER. The global block is the one `loadRawConfig` already validated,\n * and a project file goes through `parseRouterLayer` from the same schema.\n */\n\n/** The committed project file and the personal one beside it. */\nexport const PROJECT_ROUTER_FILE = join('.tenjin', 'config.json');\nexport const LOCAL_ROUTER_FILE = join('.tenjin', 'config.local.json');\n\nexport type RouterSource = 'default' | 'file' | 'project' | 'local';\n\nexport interface RouterSetting<T> {\n value: T;\n source: RouterSource;\n /** The file that set it; absent for the default. */\n path?: string;\n}\n\nexport interface RouterSettings {\n enabled: RouterSetting<boolean>;\n context: RouterSetting<RouterContext>;\n}\n\nexport interface RouterSettingsInput {\n /** The directory the harness is working in. */\n cwd: string;\n /** The data dir whose `config.json` is the global layer. */\n dataDir: string;\n /** That file, when the caller has already loaded it; read here otherwise. */\n config?: PartialConfig;\n}\n\nexport async function routerSettings(\n input: RouterSettingsInput,\n deps: ProjectWalkDeps = {},\n): Promise<RouterSettings> {\n const globalPath = configPath(input.dataDir);\n const global = (input.config ?? (await loadRawConfig(input.dataDir))).router;\n let enabled: RouterSetting<boolean> = {\n value: CONFIG_DEFAULTS.router.enabled,\n source: 'default',\n };\n let context: RouterSetting<RouterContext> = {\n value: CONFIG_DEFAULTS.router.context,\n source: 'default',\n };\n if (global?.enabled !== undefined) {\n enabled = { value: global.enabled, source: 'file', path: globalPath };\n }\n if (global?.context !== undefined) {\n context = { value: global.context, source: 'file', path: globalPath };\n }\n\n for (const { source, path, layer } of await projectLayers(input, deps)) {\n // Every layer is a floor: a value looser than the one so far is not read.\n if (layer.enabled !== undefined && (layer.enabled === false || enabled.value)) {\n enabled = { value: layer.enabled, source, path };\n }\n if (layer.context !== undefined && (layer.context === 'turn' || context.value === 'session')) {\n context = { value: layer.context, source, path };\n }\n }\n return { enabled, context };\n}\n\nconst ROUTER_FILES = [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE];\n\n/**\n * Every project layer, outermost first so the nearest one at a value is the\n * one reported: the main checkout's pair when this is a linked worktree, then\n * each directory from the git root down to `cwd`, its project file before its\n * personal one.\n */\nasync function projectLayers(\n input: RouterSettingsInput,\n deps: ProjectWalkDeps,\n): Promise<{ source: 'project' | 'local'; path: string; layer: RouterLayer }[]> {\n const { levels, gitRoot } = await findAllProjectFiles(input.cwd, ROUTER_FILES, {\n ...deps,\n // $HOME/.tenjin is the global scope, not a project.\n homeIsProject: false,\n });\n const main = gitRoot === null ? null : await mainWorktreeOf(gitRoot, deps.homeDir);\n const outer =\n main === null ? [] : [{ dir: main, found: await ownedCandidates(main, ROUTER_FILES, deps) }];\n const layers = [];\n for (const { dir, found } of [...outer, ...levels.reverse()]) {\n // A data dir kept inside a project is the global file, already read.\n if (resolve(dir, '.tenjin') === resolve(input.dataDir)) continue;\n for (const path of found) {\n const file = await readProjectRouterFile(path);\n if (file === null) continue;\n layers.push({\n source: path === join(dir, LOCAL_ROUTER_FILE) ? ('local' as const) : ('project' as const),\n path,\n layer: file.layer,\n });\n }\n }\n return layers;\n}\n\nconst ABSENT = new Set(['ENOENT', 'ENOTDIR']);\n\n/**\n * One project file: its whole JSON, for a writer that keeps sibling keys, and\n * its router layer through the one parser. Null when there is no file.\n */\nexport async function readProjectRouterFile(\n path: string,\n): Promise<{ json: Record<string, unknown>; layer: RouterLayer } | null> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (ABSENT.has(String((err as { code?: unknown }).code))) return null;\n throw invalid(path, 'could not be read', err);\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw invalid(path, 'is not valid JSON', err);\n }\n const layer = parseRouterLayer(json, path);\n return { json: json as Record<string, unknown>, layer };\n}\n\n/**\n * Where `tenjin config set --project [--local]` writes from `cwd`: beside the\n * layer {@link routerSettings} already reads there, else at the git root, else\n * in `cwd`. Never in $HOME, whose `.tenjin/config.json` is the global file.\n */\nexport async function projectRouterPath(\n input: { cwd: string; local: boolean },\n deps: ProjectWalkDeps = {},\n): Promise<string> {\n const home = deps.homeDir ?? homedir();\n const hit = await findNearestProjectFiles(input.cwd, [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE], {\n ...deps,\n warn: () => undefined,\n homeIsProject: false,\n });\n const dir = hit?.dir ?? (await projectRoot(input.cwd, home));\n if (dir === home) {\n throw new CliError(\n 'USAGE',\n 'Your home directory is not a project: its .tenjin is the global config.',\n {\n fix: 'Run it from inside the project, or drop --project to set it for this machine.',\n },\n );\n }\n return join(dir, input.local ? LOCAL_ROUTER_FILE : PROJECT_ROUTER_FILE);\n}\n\nfunction invalid(path: string, what: string, cause?: unknown): CliError {\n return new CliError('CONFIG_INVALID', `Config at ${path} ${what}`, {\n fix: `Fix ${path}, or delete it.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AA6CvB,IAAM,sBAAsB,KAAK,WAAW,aAAa;AACzD,IAAM,oBAAoB,KAAK,WAAW,mBAAmB;AAyBpE,eAAsB,eACpB,OACA,OAAwB,CAAC,GACA;AACzB,QAAM,aAAa,WAAW,MAAM,OAAO;AAC3C,QAAM,UAAU,MAAM,UAAW,MAAM,cAAc,MAAM,OAAO,GAAI;AACtE,MAAI,UAAkC;AAAA,IACpC,OAAO,gBAAgB,OAAO;AAAA,IAC9B,QAAQ;AAAA,EACV;AACA,MAAI,UAAwC;AAAA,IAC1C,OAAO,gBAAgB,OAAO;AAAA,IAC9B,QAAQ;AAAA,EACV;AACA,MAAI,QAAQ,YAAY,QAAW;AACjC,cAAU,EAAE,OAAO,OAAO,SAAS,QAAQ,QAAQ,MAAM,WAAW;AAAA,EACtE;AACA,MAAI,QAAQ,YAAY,QAAW;AACjC,cAAU,EAAE,OAAO,OAAO,SAAS,QAAQ,QAAQ,MAAM,WAAW;AAAA,EACtE;AAEA,aAAW,EAAE,QAAQ,MAAM,MAAM,KAAK,MAAM,cAAc,OAAO,IAAI,GAAG;AAEtE,QAAI,MAAM,YAAY,WAAc,MAAM,YAAY,SAAS,QAAQ,QAAQ;AAC7E,gBAAU,EAAE,OAAO,MAAM,SAAS,QAAQ,KAAK;AAAA,IACjD;AACA,QAAI,MAAM,YAAY,WAAc,MAAM,YAAY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9C;AACA,MAAI;AACJ,MAAI;AACF,WAAO,KAAK,MAAM,GAAG;AAAA,EACvB,SAAS,KAAK;AACZ,UAAM,QAAQ,MAAM,qBAAqB,GAAG;AAAA,EAC9C;AACA,QAAM,QAAQ,iBAAiB,MAAM,IAAI;AACzC,SAAO,EAAE,MAAuC,MAAM;AACxD;AAOA,eAAsB,kBACpB,OACA,OAAwB,CAAC,GACR;AACjB,QAAM,OAAO,KAAK,WAAW,QAAQ;AACrC,QAAM,MAAM,MAAM,wBAAwB,MAAM,KAAK,CAAC,qBAAqB,iBAAiB,GAAG;AAAA,IAC7F,GAAG;AAAA,IACH,MAAM,MAAM;AAAA,IACZ,eAAe;AAAA,EACjB,CAAC;AACD,QAAM,MAAM,KAAK,OAAQ,MAAM,YAAY,MAAM,KAAK,IAAI;AAC1D,MAAI,QAAQ,MAAM;AAChB,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,QACE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACA,SAAO,KAAK,KAAK,MAAM,QAAQ,oBAAoB,mBAAmB;AACxE;AAEA,SAAS,QAAQ,MAAc,MAAc,OAA2B;AACtE,SAAO,IAAI,SAAS,kBAAkB,aAAa,IAAI,IAAI,IAAI,IAAI;AAAA,IACjE,KAAK,OAAO,IAAI;AAAA,IAChB,GAAI,UAAU,SAAY,EAAE,MAAM,IAAI,CAAC;AAAA,EACzC,CAAC;AACH;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  keccak_256
4
- } from "./chunk-XJN5WUKL.js";
4
+ } from "./chunk-KG3D7FIF.js";
5
5
 
6
6
  // node_modules/.pnpm/abitype@1.2.3_typescript@6.0.3_zod@3.25.76/node_modules/abitype/dist/esm/version.js
7
7
  var version = "1.2.3";
@@ -5630,7 +5630,7 @@ async function call(client, args) {
5630
5630
  if (isAbortError(err))
5631
5631
  throw err;
5632
5632
  const data2 = getRevertErrorData(err);
5633
- const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-ZGGWQN4X.js");
5633
+ const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await import("./ccip-7RMRLAGV.js");
5634
5634
  if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to)
5635
5635
  return {
5636
5636
  data: await offchainLookup2(client, { data: data2, requestOptions, to })
@@ -6196,4 +6196,4 @@ export {
6196
6196
  ccipRequest,
6197
6197
  call
6198
6198
  };
6199
- //# sourceMappingURL=chunk-KZAAWQNP.js.map
6199
+ //# sourceMappingURL=chunk-TTNESUPQ.js.map
@@ -1,4 +1,44 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ CliError
4
+ } from "./chunk-JLEF5WHM.js";
5
+
6
+ // src/lib/money.ts
7
+ var USDC_DECIMALS = 6;
8
+ function parseUsdToAtomic(input) {
9
+ const trimmed = input.trim();
10
+ if (!/^\d+(\.\d+)?$/.test(trimmed)) {
11
+ throw new CliError("USAGE", `Invalid USD amount: ${JSON.stringify(input)}`, {
12
+ fix: "Pass a non-negative decimal like 0.25 or 5."
13
+ });
14
+ }
15
+ const [whole, frac = ""] = trimmed.split(".");
16
+ if (frac.length > USDC_DECIMALS) {
17
+ throw new CliError(
18
+ "USAGE",
19
+ `USD amount ${JSON.stringify(input)} has more than 6 decimal places`,
20
+ {
21
+ fix: "USDC supports at most 6 decimal places (micro-dollars)."
22
+ }
23
+ );
24
+ }
25
+ const atomic = BigInt(`${whole}${frac.padEnd(USDC_DECIMALS, "0")}`);
26
+ return atomic.toString();
27
+ }
28
+ function atomicToUsd(atomic) {
29
+ const trimmed = atomic.trim();
30
+ if (!/^\d+$/.test(trimmed)) {
31
+ throw new CliError("INTERNAL", `Malformed atomic amount: ${JSON.stringify(atomic)}`);
32
+ }
33
+ const value = BigInt(trimmed);
34
+ const base = 10n ** BigInt(USDC_DECIMALS);
35
+ const whole = value / base;
36
+ const frac = (value % base).toString().padStart(USDC_DECIMALS, "0").replace(/0+$/, "");
37
+ return frac.length > 0 ? `${whole}.${frac}` : whole.toString();
38
+ }
39
+ function toMoney(atomic) {
40
+ return { atomic, usd: atomicToUsd(atomic) };
41
+ }
2
42
 
3
43
  // src/lib/policy.ts
4
44
  function normCreator(value) {
@@ -63,7 +103,9 @@ function parseConfirmPolicy(stored) {
63
103
  }
64
104
 
65
105
  export {
106
+ parseUsdToAtomic,
107
+ toMoney,
66
108
  evaluateSpendPolicy,
67
109
  parseConfirmPolicy
68
110
  };
69
- //# sourceMappingURL=chunk-UO22YNY4.js.map
111
+ //# sourceMappingURL=chunk-U2DZISAH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/money.ts","../src/lib/policy.ts"],"sourcesContent":["import { CliError } from './errors';\nimport { ATOMIC_RE } from './ids';\nimport type { Money } from '../schemas';\n\n/** USDC is a 6-decimal token; one dollar is 1_000_000 atomic units. */\nconst USDC_DECIMALS = 6;\n\n/**\n * Decimal USD at the CLI edge -> atomic USDC string (O1). Accepts \"0\", \"0.25\",\n * \"5\"; rejects negatives, non-numeric input, and more than 6 decimal places as\n * USAGE so a fat-fingered amount fails loudly instead of truncating money.\n * String math throughout — a float would lose precision at the 6th decimal.\n */\nexport function parseUsdToAtomic(input: string): string {\n const trimmed = input.trim();\n if (!/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n throw new CliError('USAGE', `Invalid USD amount: ${JSON.stringify(input)}`, {\n fix: 'Pass a non-negative decimal like 0.25 or 5.',\n });\n }\n const [whole, frac = ''] = trimmed.split('.');\n if (frac.length > USDC_DECIMALS) {\n throw new CliError(\n 'USAGE',\n `USD amount ${JSON.stringify(input)} has more than 6 decimal places`,\n {\n fix: 'USDC supports at most 6 decimal places (micro-dollars).',\n },\n );\n }\n const atomic = BigInt(`${whole}${frac.padEnd(USDC_DECIMALS, '0')}`);\n return atomic.toString();\n}\n\n/**\n * Atomic USDC string -> decimal USD string, trailing zeros trimmed (\"250000\" ->\n * \"0.25\", \"5000000\" -> \"5\", \"0\" -> \"0\"). Throws INTERNAL on a malformed atomic\n * value: atomic strings come from validated config or on-chain reads, so a bad\n * one is a bug, not user input.\n */\nexport function atomicToUsd(atomic: string): string {\n const trimmed = atomic.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new CliError('INTERNAL', `Malformed atomic amount: ${JSON.stringify(atomic)}`);\n }\n const value = BigInt(trimmed);\n const base = 10n ** BigInt(USDC_DECIMALS);\n const whole = value / base;\n const frac = (value % base).toString().padStart(USDC_DECIMALS, '0').replace(/0+$/, '');\n return frac.length > 0 ? `${whole}.${frac}` : whole.toString();\n}\n\n/**\n * Whether an atomic price would actually cost something: true paid, false free,\n * null when the string is not an atomic amount at all and so cannot answer.\n *\n * A Tenjin piece may be priced at zero and is then delivered by `read` with no\n * payment, so \"there is a price field\" and \"there is a purchase to make\" are\n * different questions. The third state is not decoration: only the wire schema\n * enforces ATOMIC_RE, and the local search store types `price` as a bare string,\n * so a hand-edited or half-written entry can hold \"-1\" or \"0.1\". Those must not\n * read as \"free\", or corrupt local data would start refusing honest reports.\n * Never throws, which is why the check is a regex and not a BigInt compare.\n *\n * Matched against the RAW string, with no trimming. The contract carries the\n * canonical form and nothing else, so \" 0 \" did not come off the wire; padding is\n * evidence the value was edited, and normalizing it away would launder a corrupt\n * entry into a confident \"free\" and hand back the false refusal this avoids.\n */\nexport function isPaidPrice(atomic: string): boolean | null {\n if (!ATOMIC_RE.test(atomic)) return null;\n return /[1-9]/.test(atomic);\n}\n\n/** Dual-form money object for machine output. */\nexport function toMoney(atomic: string): Money {\n return { atomic, usd: atomicToUsd(atomic) };\n}\n\n/**\n * Canonical USD for human COPY (a price a person reads): always at least two\n * decimals (\"0.10\", \"5.00\"), keeping any finer precision below a cent\n * (\"0.000001\"). Distinct from `atomicToUsd`, which trims to the shortest exact\n * form for machine output; use this only where a dollar amount is shown to a human.\n */\nexport function formatUsdDisplay(atomic: string): string {\n const [whole, frac = ''] = atomicToUsd(atomic).split('.');\n return `${whole}.${frac.padEnd(2, '0')}`;\n}\n","/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\n/** How a `confirm` gate is configured (parsed from the stored config string). */\nexport type ConfirmPolicy = { mode: 'always' } | { mode: 'above'; thresholdAtomic: bigint };\n\nexport interface SpendPolicy {\n /** Amounts at or below this auto-approve WITHOUT a prompt (still subject to the\n * confirm gate below). Default 0 → nothing auto-approves. */\n maxAutoSpendAtomic: bigint;\n /** Rolling local ceiling on cumulative session spend. 0 = disabled (no ceiling). */\n sessionBudgetAtomic: bigint;\n /** When a human confirmation is requested. */\n confirm: ConfirmPolicy;\n /** Creators (handle or 0x-address, lowercased) auto-payment is restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\n/**\n * `duplicate_in_flight` is the one reason this pure evaluator never returns: it\n * is a fact about the ledger (an identical request already holds a reservation\n * in this turn), so the authorizer raises it. It lives in the union because\n * every caller renders a decision's reason from one vocabulary.\n */\nexport type PolicyReason =\n | 'within_policy'\n | 'duplicate_in_flight'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always'\n | 'above_confirm_threshold';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/**\n * Evaluate one spend against the policy. Hard gates run first (price cap →\n * allowlist → session budget); only if all pass is the confirm gate consulted. A\n * spend at or below `maxAutoSpend` that the confirm policy would not prompt for is\n * the only `allow`; everything else within the hard gates is `confirm`.\n */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (policy.sessionBudgetAtomic > 0n) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'confirm',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; confirmation required.`,\n };\n }\n\n if (policy.confirm.mode === 'always') {\n return {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'confirm policy is \"always\"; confirmation required.',\n };\n }\n\n if (req.amountAtomic > policy.confirm.thresholdAtomic) {\n return {\n decision: 'confirm',\n reason: 'above_confirm_threshold',\n message: `Price ${req.amountAtomic} is above the confirm threshold ${policy.confirm.thresholdAtomic}; confirmation required.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n\n/** Parse the stored `confirm` config value (\"always\" | \"above:<atomic>\"). */\nexport function parseConfirmPolicy(stored: string): ConfirmPolicy {\n if (stored === 'always') return { mode: 'always' };\n const m = /^above:(\\d+)$/.exec(stored);\n if (m && m[1] !== undefined) return { mode: 'above', thresholdAtomic: BigInt(m[1]) };\n // The config schema already constrains this; a malformed value here is a bug,\n // so fail closed to the safest interpretation rather than throwing mid-buy.\n return { mode: 'always' };\n}\n"],"mappings":";;;;;;AAKA,IAAM,gBAAgB;AAQf,SAAS,iBAAiB,OAAuB;AACtD,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,gBAAgB,KAAK,OAAO,GAAG;AAClC,UAAM,IAAI,SAAS,SAAS,uBAAuB,KAAK,UAAU,KAAK,CAAC,IAAI;AAAA,MAC1E,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,QAAM,CAAC,OAAO,OAAO,EAAE,IAAI,QAAQ,MAAM,GAAG;AAC5C,MAAI,KAAK,SAAS,eAAe;AAC/B,UAAM,IAAI;AAAA,MACR;AAAA,MACA,cAAc,KAAK,UAAU,KAAK,CAAC;AAAA,MACnC;AAAA,QACE,KAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACA,QAAM,SAAS,OAAO,GAAG,KAAK,GAAG,KAAK,OAAO,eAAe,GAAG,CAAC,EAAE;AAClE,SAAO,OAAO,SAAS;AACzB;AAQO,SAAS,YAAY,QAAwB;AAClD,QAAM,UAAU,OAAO,KAAK;AAC5B,MAAI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;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,oBAAoB;AAChD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,0BAA0B,OAAO,kBAAkB;AAAA,IACvF;AAAA,EACF;AAEA,MAAI,OAAO,QAAQ,SAAS,UAAU;AACpC,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS;AAAA,IACX;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,QAAQ,iBAAiB;AACrD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,mCAAmC,OAAO,QAAQ,eAAe;AAAA,IACrG;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;AAGO,SAAS,mBAAmB,QAA+B;AAChE,MAAI,WAAW,SAAU,QAAO,EAAE,MAAM,SAAS;AACjD,QAAM,IAAI,gBAAgB,KAAK,MAAM;AACrC,MAAI,KAAK,EAAE,CAAC,MAAM,OAAW,QAAO,EAAE,MAAM,SAAS,iBAAiB,OAAO,EAAE,CAAC,CAAC,EAAE;AAGnF,SAAO,EAAE,MAAM,SAAS;AAC1B;","names":[]}
@@ -0,0 +1,165 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ fetchFailureToCliError,
4
+ httpRequest
5
+ } from "./chunk-5QHHRMRA.js";
6
+ import {
7
+ external_exports
8
+ } from "./chunk-AR7U7BRG.js";
9
+
10
+ // src/router/decision.ts
11
+ var ROUTER_PATH = "/api/x402-router";
12
+ var RequestSchema = external_exports.object({
13
+ url: external_exports.string().min(1).max(16384),
14
+ method: external_exports.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]),
15
+ headers: external_exports.record(external_exports.string(), external_exports.string()),
16
+ body: external_exports.string().max(256 * 1024).optional()
17
+ });
18
+ var ContractSchema = external_exports.object({
19
+ /** Flat, for display and for the result check; never re-encoded into a call:
20
+ * the server built `request` from them and this client sends that verbatim. */
21
+ arguments: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
22
+ resultSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
23
+ request: RequestSchema
24
+ });
25
+ var DiagnosticsSchema = external_exports.object({
26
+ reasonCode: external_exports.string().min(1).max(64),
27
+ stage: external_exports.string().min(1).max(32),
28
+ missing: external_exports.array(external_exports.string().max(200)).max(60),
29
+ nextAction: external_exports.string().max(500)
30
+ });
31
+ var IdSchema = external_exports.string().regex(/^[A-Za-z0-9_-]{8,64}$/).describe(
32
+ "The turn id, an OPAQUE HANDLE: it is the one piece of server text this client puts in a model-facing line, so the alphabet is pinned here rather than escaped later."
33
+ );
34
+ var RefusedSchema = external_exports.strictObject({
35
+ reason: external_exports.string().max(2e3).optional(),
36
+ diagnostics: DiagnosticsSchema
37
+ });
38
+ var CapabilityFields = {
39
+ capabilityId: external_exports.string().min(1).max(200),
40
+ category: external_exports.string().min(1).max(64),
41
+ /** The service's own name, not the x402 reseller in front of it. */
42
+ provider: external_exports.string().min(1).max(120),
43
+ capabilityDescription: external_exports.string().min(1).max(500),
44
+ /** What the provider charges, atomic USDC. The `request` tool refuses a live
45
+ * 402 above it; `gateSpend` still caps the amount actually signed. */
46
+ providerPriceAtomic: external_exports.string().regex(/^\d+$/)
47
+ };
48
+ var HookDecisionSchema = external_exports.discriminatedUnion("action", [
49
+ external_exports.strictObject({
50
+ action: external_exports.literal("execute"),
51
+ id: IdSchema,
52
+ ...CapabilityFields,
53
+ /** The x402 URL a lookup would pay, for the line the server writes. */
54
+ endpoint: external_exports.string().min(1).max(2048),
55
+ /** What to pass in `query`, in the service's own terms. */
56
+ usage: external_exports.string().min(1).max(300),
57
+ /**
58
+ * THE LINE, FINISHED. The server writes it with the real id in it and, on a
59
+ * native call, the exact search or URL that was denied. The client injects
60
+ * it and composes nothing, which is why there is no hint builder here any
61
+ * more: two sides writing the same sentence is how they drift.
62
+ */
63
+ hint: external_exports.string().min(1).max(1e3)
64
+ }).superRefine((decision, ctx) => {
65
+ if (/[\p{Cc}\p{Cf}]/u.test(decision.hint)) {
66
+ ctx.addIssue({ code: "custom", path: ["hint"], message: "a hint is one plain line" });
67
+ }
68
+ if (!decision.hint.includes("request({")) {
69
+ ctx.addIssue({ code: "custom", path: ["hint"], message: "a hint names the call to make" });
70
+ }
71
+ if (!decision.hint.includes(decision.id)) {
72
+ ctx.addIssue({
73
+ code: "custom",
74
+ path: ["hint"],
75
+ message: "a hint carries this answer's own id"
76
+ });
77
+ }
78
+ }),
79
+ RefusedSchema.extend({ action: external_exports.literal("native") }),
80
+ RefusedSchema.extend({ action: external_exports.literal("needs_input") })
81
+ ]);
82
+ var ToolDecisionSchema = external_exports.discriminatedUnion("action", [
83
+ external_exports.strictObject({
84
+ action: external_exports.literal("execute"),
85
+ ...CapabilityFields,
86
+ contract: ContractSchema
87
+ }),
88
+ RefusedSchema.extend({ action: external_exports.literal("native") }),
89
+ RefusedSchema.extend({ action: external_exports.literal("needs_input") })
90
+ ]);
91
+ function envelope(decision) {
92
+ return external_exports.strictObject({
93
+ schemaVersion: external_exports.literal(1),
94
+ routerVersion: external_exports.string().min(1).max(64),
95
+ decision,
96
+ /** A plain sentence about the CALL, such as an id that had expired. Never a
97
+ * failure: the decision beside it ran anyway. */
98
+ note: external_exports.string().max(500).optional(),
99
+ jev: external_exports.object({ calls: external_exports.number(), latencyMs: external_exports.number() }).optional()
100
+ });
101
+ }
102
+ var HookResponseSchema = envelope(HookDecisionSchema);
103
+ var ToolResponseSchema = envelope(ToolDecisionSchema);
104
+ function buildHookBody(packet) {
105
+ return { schemaVersion: 1, packet };
106
+ }
107
+ function buildToolBody(request) {
108
+ return {
109
+ schemaVersion: 1,
110
+ query: request.query,
111
+ ...request.id !== void 0 ? { id: request.id } : {},
112
+ ...request.gateHint !== void 0 ? { gateHint: request.gateHint } : {}
113
+ };
114
+ }
115
+ async function requestDecision(kind, request, deps) {
116
+ const url = new URL(ROUTER_PATH, deps.baseUrl).toString();
117
+ const options = {
118
+ method: "POST",
119
+ timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,
120
+ blockRedirects: true,
121
+ jsonBody: kind === "hook" ? buildHookBody(request.packet) : buildToolBody({
122
+ query: request.query,
123
+ ...request.id !== void 0 ? { id: request.id } : {},
124
+ ...request.gateHint !== void 0 ? { gateHint: request.gateHint } : {}
125
+ }),
126
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
127
+ };
128
+ return readDecision(
129
+ await httpRequest(url, options),
130
+ kind === "hook" ? HookResponseSchema : ToolResponseSchema
131
+ );
132
+ }
133
+ function readDecision(response, schema) {
134
+ if (!response.ok) return { status: "failed", reason: fetchFailureToCliError(response).message };
135
+ if (response.status < 200 || response.status >= 300) {
136
+ const named = errorOf(response.json);
137
+ return {
138
+ status: "failed",
139
+ // The backend's own code and message, never a bare status line: a typed
140
+ // refusal the host could act on was arriving as "answered 400".
141
+ reason: named === null ? `The router endpoint answered ${response.status}.` : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,
142
+ ...named !== null ? { errorCode: named.code } : {}
143
+ };
144
+ }
145
+ const parsed = schema.safeParse(response.json);
146
+ if (!parsed.success) {
147
+ return { status: "failed", reason: "The router returned a decision this build cannot read." };
148
+ }
149
+ return { status: "decided", decision: parsed.data };
150
+ }
151
+ function errorOf(body) {
152
+ if (body === null || typeof body !== "object") return null;
153
+ const error = body.error;
154
+ if (error === null || typeof error !== "object") return null;
155
+ const { code, message } = error;
156
+ if (typeof code !== "string" || code.length === 0 || code.length > 64) return null;
157
+ const text = typeof message === "string" ? message.slice(0, 500) : "";
158
+ return { code, message: text };
159
+ }
160
+
161
+ export {
162
+ ROUTER_PATH,
163
+ requestDecision
164
+ };
165
+ //# sourceMappingURL=chunk-WGQVJM56.js.map