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

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 (267) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +41 -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-25TJPVBF.js +353 -0
  7. package/dist/chunk-25TJPVBF.js.map +1 -0
  8. package/dist/chunk-2BKS2FVE.js +93 -0
  9. package/dist/chunk-2BKS2FVE.js.map +1 -0
  10. package/dist/chunk-2QYORQBF.js +55 -0
  11. package/dist/chunk-2QYORQBF.js.map +1 -0
  12. package/dist/{chunk-NIKXHWOL.js → chunk-2U5ZVEV3.js} +16 -16
  13. package/dist/chunk-2U5ZVEV3.js.map +1 -0
  14. package/dist/{chunk-HPJGOLTN.js → chunk-3AJS6LLN.js} +13 -8
  15. package/dist/chunk-3AJS6LLN.js.map +1 -0
  16. package/dist/{chunk-KINZ23CV.js → chunk-3AUDA53C.js} +4740 -23
  17. package/dist/chunk-3AUDA53C.js.map +1 -0
  18. package/dist/{chunk-MJZZTKCC.js → chunk-56MOAIP5.js} +5 -10
  19. package/dist/chunk-56MOAIP5.js.map +1 -0
  20. package/dist/{chunk-U5S527PP.js → chunk-5IEP5EGE.js} +3 -3
  21. package/dist/chunk-5X4SZ5BF.js +227 -0
  22. package/dist/chunk-5X4SZ5BF.js.map +1 -0
  23. package/dist/chunk-7WEQQJLG.js +68 -0
  24. package/dist/chunk-7WEQQJLG.js.map +1 -0
  25. package/dist/{chunk-7FK2UN2T.js → chunk-AWQPGIR6.js} +65 -67
  26. package/dist/{chunk-7FK2UN2T.js.map → chunk-AWQPGIR6.js.map} +1 -1
  27. package/dist/{chunk-ZFJJ3EXC.js → chunk-BBVUVBUO.js} +516 -185
  28. package/dist/chunk-BBVUVBUO.js.map +1 -0
  29. package/dist/{chunk-JBIKAAT3.js → chunk-BFFM2WFK.js} +8 -8
  30. package/dist/chunk-BFFM2WFK.js.map +1 -0
  31. package/dist/{chunk-KYQVEKP5.js → chunk-BPMWXTFX.js} +8 -8
  32. package/dist/chunk-DMZZLPZN.js +205 -0
  33. package/dist/chunk-DMZZLPZN.js.map +1 -0
  34. package/dist/{chunk-47PP7TAG.js → chunk-EGELTSPU.js} +1356 -1356
  35. package/dist/chunk-EGELTSPU.js.map +1 -0
  36. package/dist/chunk-GULLJQXA.js +698 -0
  37. package/dist/chunk-GULLJQXA.js.map +1 -0
  38. package/dist/{chunk-S5RYMCV6.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-HVRC33OL.js +174 -0
  40. package/dist/chunk-HVRC33OL.js.map +1 -0
  41. package/dist/{chunk-W6R3HAAG.js → chunk-JRGFKVAZ.js} +2 -2
  42. package/dist/{chunk-XJN5WUKL.js → chunk-KG3D7FIF.js} +2 -2
  43. package/dist/chunk-L3PVMIYQ.js +10328 -0
  44. package/dist/chunk-L3PVMIYQ.js.map +1 -0
  45. package/dist/{chunk-QW2Q2KAH.js → chunk-LHHMV4GU.js} +2 -2
  46. package/dist/{chunk-ZOBNS7CX.js → chunk-MEFB5KHA.js} +4 -18
  47. package/dist/chunk-MEFB5KHA.js.map +1 -0
  48. package/dist/{chunk-M2O56UK7.js → chunk-N35E6CM2.js} +293 -163
  49. package/dist/chunk-N35E6CM2.js.map +1 -0
  50. package/dist/chunk-OCBHUHWB.js +69 -0
  51. package/dist/chunk-OCBHUHWB.js.map +1 -0
  52. package/dist/chunk-OIM4HLN6.js +1405 -0
  53. package/dist/chunk-OIM4HLN6.js.map +1 -0
  54. package/dist/{chunk-VYOJOX4Z.js → chunk-OJLYNM4Z.js} +54 -33
  55. package/dist/chunk-OJLYNM4Z.js.map +1 -0
  56. package/dist/{chunk-POJRB2AE.js → chunk-POUWHWID.js} +2 -2
  57. package/dist/chunk-PZEN5PHN.js +285 -0
  58. package/dist/chunk-PZEN5PHN.js.map +1 -0
  59. package/dist/chunk-SKAHDQH7.js +1785 -0
  60. package/dist/chunk-SKAHDQH7.js.map +1 -0
  61. package/dist/{chunk-KZAAWQNP.js → chunk-TTNESUPQ.js} +3 -3
  62. package/dist/chunk-U5DXNFJC.js +137 -0
  63. package/dist/chunk-U5DXNFJC.js.map +1 -0
  64. package/dist/chunk-USS336NF.js +165 -0
  65. package/dist/chunk-USS336NF.js.map +1 -0
  66. package/dist/{chunk-UO22YNY4.js → chunk-WH7OWT6G.js} +49 -1
  67. package/dist/chunk-WH7OWT6G.js.map +1 -0
  68. package/dist/chunk-WXC57XGG.js +29 -0
  69. package/dist/chunk-WXC57XGG.js.map +1 -0
  70. package/dist/{chunk-YLYINX2H.js → chunk-XZKD7DIF.js} +3 -3
  71. package/dist/{chunk-CPCX67TI.js → chunk-YEETV6IW.js} +1079 -1039
  72. package/dist/chunk-YEETV6IW.js.map +1 -0
  73. package/dist/{chunk-OLWTRUTS.js → chunk-YJHHCWM3.js} +35 -16
  74. package/dist/chunk-YJHHCWM3.js.map +1 -0
  75. package/dist/{cli-KKRKBU5T.js → cli-M3XCSOU6.js} +289 -374
  76. package/dist/cli-M3XCSOU6.js.map +1 -0
  77. package/dist/config-MXOX7XDR.js +41 -0
  78. package/dist/{dist-U4M6QCKE.js → dist-3LOO6M4U.js} +10 -10
  79. package/dist/doctor-LU4YIZWM.js +349 -0
  80. package/dist/doctor-LU4YIZWM.js.map +1 -0
  81. package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  82. package/dist/{chunk-KAJZHIQ4.js → fund-A54P2QFK.js} +80 -24
  83. package/dist/fund-A54P2QFK.js.map +1 -0
  84. package/dist/hook-command-U6KWPEDQ.js +377 -0
  85. package/dist/hook-command-U6KWPEDQ.js.map +1 -0
  86. package/dist/index.js +8 -3
  87. package/dist/index.js.map +1 -1
  88. package/dist/install-XUM2XSHW.js +53 -0
  89. package/dist/install-wallet-QIOFORTX.js +105 -0
  90. package/dist/install-wallet-QIOFORTX.js.map +1 -0
  91. package/dist/{run-XYTQ5TWQ.js → mcp-HJC2PLRV.js} +3727 -10670
  92. package/dist/mcp-HJC2PLRV.js.map +1 -0
  93. package/dist/paths-P2N4JTDZ.js +49 -0
  94. package/dist/pay-SBXZEPEP.js +37 -0
  95. package/dist/redact-46ZHF2NH.js +17 -0
  96. package/dist/{secp256k1-XRPVBC6V.js → secp256k1-ZZZT2CAX.js} +3 -3
  97. package/dist/{send-G746D7PQ.js → send-ASD2ZXJD.js} +28 -29
  98. package/dist/send-ASD2ZXJD.js.map +1 -0
  99. package/dist/{chunk-QZ6ROAJU.js → skill-placement-NFVHY6A3.js} +157 -11
  100. package/dist/skill-placement-NFVHY6A3.js.map +1 -0
  101. package/dist/status-T2SDB57A.js +63 -0
  102. package/dist/status-T2SDB57A.js.map +1 -0
  103. package/dist/status-line-CGPUSDMC.js +71 -0
  104. package/dist/status-line-CGPUSDMC.js.map +1 -0
  105. package/dist/status-line-wiring-BYPHTYZE.js +30 -0
  106. package/dist/tenjin-daemon.mjs +20060 -0
  107. package/dist/tenjin-shim.mjs +251 -0
  108. package/dist/tenjin-vitest-reporter.mjs +49 -0
  109. package/dist/uninstall-FKYZHAM3.js +144 -0
  110. package/dist/uninstall-FKYZHAM3.js.map +1 -0
  111. package/dist/{update-R76LHOZW.js → update-ANJ2AOTN.js} +133 -16
  112. package/dist/update-ANJ2AOTN.js.map +1 -0
  113. package/dist/{viemAdapter-By13KInL-TUQJBMHM.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  114. package/dist/wallet-PWAHVKWW.js +31 -0
  115. package/dist/wallet-kdf-worker.mjs +980 -0
  116. package/docs/agent-permissions.md +65 -354
  117. package/docs/safety-model.md +16 -6
  118. package/package.json +8 -7
  119. package/LICENSE +0 -21
  120. package/dist/buy-VIRNSYGN.js +0 -47
  121. package/dist/chunk-2MYQN7HM.js +0 -247
  122. package/dist/chunk-2MYQN7HM.js.map +0 -1
  123. package/dist/chunk-2RF2GIJQ.js +0 -1188
  124. package/dist/chunk-2RF2GIJQ.js.map +0 -1
  125. package/dist/chunk-3GL2Z5QK.js +0 -57
  126. package/dist/chunk-3GL2Z5QK.js.map +0 -1
  127. package/dist/chunk-47PP7TAG.js.map +0 -1
  128. package/dist/chunk-4CQIDQOT.js +0 -167
  129. package/dist/chunk-4CQIDQOT.js.map +0 -1
  130. package/dist/chunk-4KG27W2S.js +0 -614
  131. package/dist/chunk-4KG27W2S.js.map +0 -1
  132. package/dist/chunk-5QQTYWEU.js +0 -199
  133. package/dist/chunk-5QQTYWEU.js.map +0 -1
  134. package/dist/chunk-65DTCCJ7.js +0 -21
  135. package/dist/chunk-65DTCCJ7.js.map +0 -1
  136. package/dist/chunk-A5DKHMUN.js +0 -173
  137. package/dist/chunk-A5DKHMUN.js.map +0 -1
  138. package/dist/chunk-B63XPWQ4.js +0 -246
  139. package/dist/chunk-B63XPWQ4.js.map +0 -1
  140. package/dist/chunk-CAR6FHK6.js +0 -105
  141. package/dist/chunk-CAR6FHK6.js.map +0 -1
  142. package/dist/chunk-CPCX67TI.js.map +0 -1
  143. package/dist/chunk-CQBVCYI2.js +0 -162
  144. package/dist/chunk-CQBVCYI2.js.map +0 -1
  145. package/dist/chunk-DBU5CXBV.js +0 -4731
  146. package/dist/chunk-DBU5CXBV.js.map +0 -1
  147. package/dist/chunk-DHJD77OW.js +0 -81
  148. package/dist/chunk-DHJD77OW.js.map +0 -1
  149. package/dist/chunk-EDZSNPE5.js +0 -35
  150. package/dist/chunk-EDZSNPE5.js.map +0 -1
  151. package/dist/chunk-EFWZPUTC.js +0 -65
  152. package/dist/chunk-EFWZPUTC.js.map +0 -1
  153. package/dist/chunk-EPFL6CTE.js +0 -448
  154. package/dist/chunk-EPFL6CTE.js.map +0 -1
  155. package/dist/chunk-GHLVXVZD.js +0 -142
  156. package/dist/chunk-GHLVXVZD.js.map +0 -1
  157. package/dist/chunk-H3SOOJ2I.js +0 -580
  158. package/dist/chunk-H3SOOJ2I.js.map +0 -1
  159. package/dist/chunk-HPJGOLTN.js.map +0 -1
  160. package/dist/chunk-HRGBS2PA.js +0 -203
  161. package/dist/chunk-HRGBS2PA.js.map +0 -1
  162. package/dist/chunk-ITUXPJIS.js +0 -314
  163. package/dist/chunk-ITUXPJIS.js.map +0 -1
  164. package/dist/chunk-JBIKAAT3.js.map +0 -1
  165. package/dist/chunk-KAJZHIQ4.js.map +0 -1
  166. package/dist/chunk-KINZ23CV.js.map +0 -1
  167. package/dist/chunk-LRYV3SK7.js +0 -235
  168. package/dist/chunk-LRYV3SK7.js.map +0 -1
  169. package/dist/chunk-M2O56UK7.js.map +0 -1
  170. package/dist/chunk-MJZZTKCC.js.map +0 -1
  171. package/dist/chunk-NIKXHWOL.js.map +0 -1
  172. package/dist/chunk-OKDRDT74.js +0 -209
  173. package/dist/chunk-OKDRDT74.js.map +0 -1
  174. package/dist/chunk-OKYSNAS3.js +0 -2144
  175. package/dist/chunk-OKYSNAS3.js.map +0 -1
  176. package/dist/chunk-OLWTRUTS.js.map +0 -1
  177. package/dist/chunk-QQ6ELLSA.js +0 -143
  178. package/dist/chunk-QQ6ELLSA.js.map +0 -1
  179. package/dist/chunk-QZ6ROAJU.js.map +0 -1
  180. package/dist/chunk-R7RSCBI7.js +0 -794
  181. package/dist/chunk-R7RSCBI7.js.map +0 -1
  182. package/dist/chunk-SGK2B724.js +0 -67
  183. package/dist/chunk-SGK2B724.js.map +0 -1
  184. package/dist/chunk-U6VPKMGC.js +0 -390
  185. package/dist/chunk-U6VPKMGC.js.map +0 -1
  186. package/dist/chunk-UHTVXQ2O.js +0 -140
  187. package/dist/chunk-UHTVXQ2O.js.map +0 -1
  188. package/dist/chunk-UO22YNY4.js.map +0 -1
  189. package/dist/chunk-US456VUI.js +0 -149
  190. package/dist/chunk-US456VUI.js.map +0 -1
  191. package/dist/chunk-V44J2MXV.js +0 -400
  192. package/dist/chunk-V44J2MXV.js.map +0 -1
  193. package/dist/chunk-VJQKL3YH.js +0 -216
  194. package/dist/chunk-VJQKL3YH.js.map +0 -1
  195. package/dist/chunk-VJSQSLBM.js +0 -1442
  196. package/dist/chunk-VJSQSLBM.js.map +0 -1
  197. package/dist/chunk-VYOJOX4Z.js.map +0 -1
  198. package/dist/chunk-WY2K35OL.js +0 -269
  199. package/dist/chunk-WY2K35OL.js.map +0 -1
  200. package/dist/chunk-ZFJJ3EXC.js.map +0 -1
  201. package/dist/chunk-ZOBNS7CX.js.map +0 -1
  202. package/dist/cli-KKRKBU5T.js.map +0 -1
  203. package/dist/config-JMRUNYE6.js +0 -37
  204. package/dist/discover-B5HF6SHM.js +0 -102
  205. package/dist/discover-B5HF6SHM.js.map +0 -1
  206. package/dist/doctor-ZBG7X66D.js +0 -32
  207. package/dist/edit-PZJIILQE.js +0 -40
  208. package/dist/fund-EUDH5KPA.js +0 -40
  209. package/dist/inspect-QC6WEQPN.js +0 -37
  210. package/dist/install-GNK2W3PI.js +0 -972
  211. package/dist/install-GNK2W3PI.js.map +0 -1
  212. package/dist/outcome-KSGWZHUS.js +0 -24
  213. package/dist/pay-BC4UICPA.js +0 -361
  214. package/dist/pay-BC4UICPA.js.map +0 -1
  215. package/dist/publish-LXWFDIKF.js +0 -42
  216. package/dist/read-JMNUQ56P.js +0 -160
  217. package/dist/read-JMNUQ56P.js.map +0 -1
  218. package/dist/run-XYTQ5TWQ.js.map +0 -1
  219. package/dist/search-TSQAB45E.js +0 -25
  220. package/dist/secp256k1-XRPVBC6V.js.map +0 -1
  221. package/dist/send-G746D7PQ.js.map +0 -1
  222. package/dist/session-JBKWMJ24.js +0 -89
  223. package/dist/session-JBKWMJ24.js.map +0 -1
  224. package/dist/skill-heal-WKD67SLJ.js +0 -92
  225. package/dist/skill-heal-WKD67SLJ.js.map +0 -1
  226. package/dist/skill-placement-RIU4AMC2.js +0 -20
  227. package/dist/skill-placement-RIU4AMC2.js.map +0 -1
  228. package/dist/uninstall-5E263VTS.js +0 -73
  229. package/dist/uninstall-5E263VTS.js.map +0 -1
  230. package/dist/update-R76LHOZW.js.map +0 -1
  231. package/dist/usdc-4VCDHFWX.js +0 -38
  232. package/dist/usdc-4VCDHFWX.js.map +0 -1
  233. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +0 -1
  234. package/dist/wallet-TQ7D5EQ7.js +0 -41
  235. package/dist/wallet-TQ7D5EQ7.js.map +0 -1
  236. package/dist/wallet-ZAVXWLWP.js +0 -32
  237. package/dist/wallet-ZAVXWLWP.js.map +0 -1
  238. package/docs/command-reference.md +0 -303
  239. package/skills/tenjin/SKILL.md +0 -373
  240. package/skills/tenjin-pay/SKILL.md +0 -76
  241. package/skills/tenjin-publish/SKILL.md +0 -227
  242. package/skills/tenjin-publish/references/maintain.md +0 -39
  243. package/skills/tenjin-search/SKILL.md +0 -154
  244. package/skills/tenjin-search/references/permissions.md +0 -112
  245. /package/dist/{_esm-N4KAVXQR.js.map → _esm-CE7KNONL.js.map} +0 -0
  246. /package/dist/{buy-VIRNSYGN.js.map → ccip-7RMRLAGV.js.map} +0 -0
  247. /package/dist/{ccip-RPPPKTJR.js.map → ccip-NLCSCHKI.js.map} +0 -0
  248. /package/dist/{chunk-U5S527PP.js.map → chunk-5IEP5EGE.js.map} +0 -0
  249. /package/dist/{chunk-KYQVEKP5.js.map → chunk-BPMWXTFX.js.map} +0 -0
  250. /package/dist/{chunk-S5RYMCV6.js.map → chunk-HPWO4O6S.js.map} +0 -0
  251. /package/dist/{chunk-W6R3HAAG.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  252. /package/dist/{chunk-XJN5WUKL.js.map → chunk-KG3D7FIF.js.map} +0 -0
  253. /package/dist/{chunk-QW2Q2KAH.js.map → chunk-LHHMV4GU.js.map} +0 -0
  254. /package/dist/{chunk-POJRB2AE.js.map → chunk-POUWHWID.js.map} +0 -0
  255. /package/dist/{chunk-KZAAWQNP.js.map → chunk-TTNESUPQ.js.map} +0 -0
  256. /package/dist/{chunk-YLYINX2H.js.map → chunk-XZKD7DIF.js.map} +0 -0
  257. /package/dist/{ccip-ZGGWQN4X.js.map → config-MXOX7XDR.js.map} +0 -0
  258. /package/dist/{dist-U4M6QCKE.js.map → dist-3LOO6M4U.js.map} +0 -0
  259. /package/dist/{config-JMRUNYE6.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  260. /package/dist/{doctor-ZBG7X66D.js.map → install-XUM2XSHW.js.map} +0 -0
  261. /package/dist/{edit-PZJIILQE.js.map → paths-P2N4JTDZ.js.map} +0 -0
  262. /package/dist/{ethersCompat-Df4a6QIZ-WHYKB6HA.js.map → pay-SBXZEPEP.js.map} +0 -0
  263. /package/dist/{fund-EUDH5KPA.js.map → redact-46ZHF2NH.js.map} +0 -0
  264. /package/dist/{inspect-QC6WEQPN.js.map → secp256k1-ZZZT2CAX.js.map} +0 -0
  265. /package/dist/{outcome-KSGWZHUS.js.map → status-line-wiring-BYPHTYZE.js.map} +0 -0
  266. /package/dist/{publish-LXWFDIKF.js.map → viemAdapter-By13KInL-X2VY6CY3.js.map} +0 -0
  267. /package/dist/{search-TSQAB45E.js.map → wallet-PWAHVKWW.js.map} +0 -0
@@ -0,0 +1,137 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ hasCode
4
+ } from "./chunk-WH7OWT6G.js";
5
+ import {
6
+ CliError
7
+ } from "./chunk-OCBHUHWB.js";
8
+
9
+ // src/lib/skills-source.ts
10
+ import { existsSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ var SKILL_NAMES = ["tenjin-search", "tenjin-publish", "tenjin"];
13
+ var OPTIONAL_PAY_SKILL = "tenjin-pay";
14
+ var OPTIONAL_SKILL_NAMES = [OPTIONAL_PAY_SKILL];
15
+ var PACKAGED_SKILL_NAMES = [...SKILL_NAMES, ...OPTIONAL_SKILL_NAMES];
16
+ var SENTINEL = join("tenjin", "SKILL.md");
17
+ function resolveSkillsSource(startDir) {
18
+ let dir = startDir;
19
+ for (let i = 0; i < 8; i += 1) {
20
+ const candidate = join(dir, "skills");
21
+ if (existsSync(join(candidate, SENTINEL))) return candidate;
22
+ const parent = dirname(dir);
23
+ if (parent === dir) break;
24
+ dir = parent;
25
+ }
26
+ throw new CliError("INTERNAL", "Could not locate the packaged Tenjin skills directory", {
27
+ fix: "Reinstall tenjin-cli; the published package must ship the skills/ directory (files array).",
28
+ details: { startDir }
29
+ });
30
+ }
31
+
32
+ // src/lib/skill-wiring.ts
33
+ import { existsSync as existsSync2, statSync } from "node:fs";
34
+ import { constants, open } from "node:fs/promises";
35
+ import { delimiter, join as join2 } from "node:path";
36
+ var HOSTED_SKILL_NAME = "tenjin";
37
+ function skillsDirsFor(home) {
38
+ return [join2(home, ".claude", "skills"), join2(home, ".agents", "skills")];
39
+ }
40
+ function harnessTargetDir(home, harness) {
41
+ if (harness === "claude") return join2(home, ".claude", "skills");
42
+ return join2(home, ".agents", "skills");
43
+ }
44
+ function harnessFlagFor(home, dir) {
45
+ if (dir === join2(home, ".claude", "skills")) return "claude";
46
+ return "codex";
47
+ }
48
+ function harnessDetectedBy(home, harness, which) {
49
+ const reasons = [];
50
+ if (existsSync2(join2(home, `.${harness}`))) reasons.push("home-dir");
51
+ if (which(harness)) reasons.push("binary");
52
+ return reasons;
53
+ }
54
+ function detectHarnesses(home, which) {
55
+ return {
56
+ claude: harnessDetectedBy(home, "claude", which).length > 0,
57
+ codex: harnessDetectedBy(home, "codex", which).length > 0
58
+ };
59
+ }
60
+ function harnessReads(home, dir, present) {
61
+ if (harnessFlagFor(home, dir) === "claude") return present.claude;
62
+ return present.codex;
63
+ }
64
+ function harnessRequested(home, dir, requested) {
65
+ return requested.some((h) => harnessTargetDir(home, h) === dir);
66
+ }
67
+ function harnessInPlay(home, dir, present, requested) {
68
+ if (requested.length > 0) return harnessRequested(home, dir, requested);
69
+ return harnessReads(home, dir, present);
70
+ }
71
+ function onPath(bin, env) {
72
+ const raw = env.PATH ?? "";
73
+ const exts = process.platform === "win32" ? ["", ...(env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter((e) => e.length > 0)] : [""];
74
+ for (const part of raw.split(delimiter)) {
75
+ if (part.length === 0) continue;
76
+ for (const ext of exts) {
77
+ if (isFile(join2(part, bin + ext))) return true;
78
+ }
79
+ }
80
+ return false;
81
+ }
82
+ function isFile(p) {
83
+ try {
84
+ return statSync(p).isFile();
85
+ } catch {
86
+ return false;
87
+ }
88
+ }
89
+ async function readSkillFile(path) {
90
+ let handle;
91
+ try {
92
+ handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
93
+ } catch (err) {
94
+ if (hasCode(err, "ENOENT")) return { kind: "absent" };
95
+ return { kind: "unreadable", err };
96
+ }
97
+ try {
98
+ if (!(await handle.stat()).isFile()) return { kind: "not-regular" };
99
+ return { kind: "ok", bytes: await handle.readFile() };
100
+ } catch (err) {
101
+ return { kind: "unreadable", err };
102
+ } finally {
103
+ await handle.close().catch(() => void 0);
104
+ }
105
+ }
106
+ function skillFrontmatterName(skillMd) {
107
+ const frontmatter = extractFrontmatter(skillMd);
108
+ if (frontmatter === null) return null;
109
+ for (const line of frontmatter) {
110
+ const m = /^name:\s*(.+?)\s*$/.exec(line);
111
+ if (m !== null) return (m[1] ?? "").replace(/^["']|["']$/g, "");
112
+ }
113
+ return null;
114
+ }
115
+ function extractFrontmatter(text) {
116
+ const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
117
+ const open2 = lines.findIndex((l) => l.trim().length > 0);
118
+ if (open2 === -1 || lines[open2]?.trim() !== "---") return null;
119
+ const end = lines.findIndex((l, i) => i > open2 && l.trim() === "---");
120
+ if (end === -1) return null;
121
+ return lines.slice(open2 + 1, end);
122
+ }
123
+
124
+ export {
125
+ SKILL_NAMES,
126
+ OPTIONAL_PAY_SKILL,
127
+ resolveSkillsSource,
128
+ HOSTED_SKILL_NAME,
129
+ skillsDirsFor,
130
+ harnessTargetDir,
131
+ detectHarnesses,
132
+ harnessInPlay,
133
+ onPath,
134
+ readSkillFile,
135
+ skillFrontmatterName
136
+ };
137
+ //# sourceMappingURL=chunk-U5DXNFJC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/skills-source.ts","../src/lib/skill-wiring.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * The packaged skills `install` copies into every target harness. All three go to\n * every target: `tenjin` (the zero-install curriculum, works with no CLI),\n * `tenjin-search` and `tenjin-publish` (thin CLI adapters). Order is the install\n * order and the human-render order.\n */\nexport const SKILL_NAMES = ['tenjin-search', 'tenjin-publish', 'tenjin'] as const;\nexport type SkillName = (typeof SKILL_NAMES)[number];\n\n/**\n * OPTIONAL skills ship in the package but are PRESENT only while their gate is\n * on, and are never required for a directory to count as wired: tenjin-pay\n * exists exactly while the `bazaarPay` toggle does (lib/skill-placement). The\n * heal and doctor cover them when present, exactly like everything else whose\n * presence is the operator's consent.\n */\nexport const OPTIONAL_PAY_SKILL = 'tenjin-pay';\nexport const OPTIONAL_SKILL_NAMES = [OPTIONAL_PAY_SKILL] as const;\nexport type OptionalSkillName = (typeof OPTIONAL_SKILL_NAMES)[number];\n\n/** Every skill directory this package ships, gated or not, in install order. */\nexport const PACKAGED_SKILL_NAMES = [...SKILL_NAMES, ...OPTIONAL_SKILL_NAMES] as const;\n\n/**\n * Every file a packaged skill ships, per skill, as a path relative to the skill\n * directory.\n *\n * DECLARED rather than discovered, because `uninstall` needs it on a machine\n * where the packaged source may be gone or unreadable, and \"remove exactly the\n * files this package wrote\" is not a question it can answer by listing the\n * operator's directory — everything else in there is theirs. `install` still\n * copies the real tree; a test pins this list against it, so a new reference\n * file that nobody declares fails the build rather than becoming litter no\n * uninstall can reclaim.\n *\n * The OPTIONAL skills are declared here for the same reason the required ones\n * are: `uninstall` reclaims a tenjin-pay directory whatever `bazaarPay` says at\n * the time, so a gate flipped back off cannot strand the files it wrote.\n */\nexport const SHIPPED_SKILL_FILES: Record<SkillName | OptionalSkillName, readonly string[]> = {\n 'tenjin-search': ['SKILL.md', 'references/permissions.md'],\n 'tenjin-publish': ['SKILL.md', 'references/maintain.md'],\n tenjin: ['SKILL.md'],\n 'tenjin-pay': ['SKILL.md'],\n};\n\n// A `skills/` directory is the real one iff it holds `tenjin/SKILL.md`; a bare\n// `skills/` created for some other reason up the tree can't false-positive.\nconst SENTINEL = join('tenjin', 'SKILL.md');\n\n/**\n * Locate the packaged `skills/` directory by walking up from `startDir`. This has\n * to work in two layouts from one resolver: a global npm install where the module\n * lives in `dist/` with `skills/` a sibling (the `files` array ships it), and a\n * repo/source run where the module is under `src/` and `skills/` sits at the repo\n * root. Walking up until a `skills/` with the sentinel appears covers both without\n * hard-coding either depth. Sync (existsSync) on purpose: this is one-shot path\n * resolution at command start, the same shape as `require.resolve`.\n */\nexport function resolveSkillsSource(startDir: string): string {\n let dir = startDir;\n for (let i = 0; i < 8; i += 1) {\n const candidate = join(dir, 'skills');\n if (existsSync(join(candidate, SENTINEL))) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new CliError('INTERNAL', 'Could not locate the packaged Tenjin skills directory', {\n fix: 'Reinstall tenjin-cli; the published package must ship the skills/ directory (files array).',\n details: { startDir },\n });\n}\n","import { existsSync, statSync } from 'node:fs';\nimport { constants, open } from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport { hasCode } from './errno';\nimport { delimiter, join } from 'node:path';\nimport { SKILL_NAMES } from './skills-source';\nimport type { SkillName } from './skills-source';\nimport type { Harness } from '../adapters/types';\n\n/**\n * CLI_SKILL_NAMES are the thin adapter skills (roadmap C1), both required for the\n * CLI to be usable from a harness; HOSTED_SKILL_NAME is the zero-install\n * curriculum mirror (roadmap G4), typed as their complement so a rename in\n * skills-source.ts is a compile error here rather than a silently-always-false\n * `cliSkillsWired`.\n */\nexport const CLI_SKILL_NAMES = [\n 'tenjin-search',\n 'tenjin-publish',\n] as const satisfies readonly SkillName[];\nexport type CliSkillName = (typeof CLI_SKILL_NAMES)[number];\nexport type HostedSkillName = Exclude<SkillName, CliSkillName>;\nexport const HOSTED_SKILL_NAME: HostedSkillName = 'tenjin';\n\nexport type NotInvocableReason = 'disabled' | 'unreadable';\n\nexport interface SkillWiring {\n name: string;\n present: boolean;\n /** Undefined when absent. False means on disk yet never surfaced to the model. */\n modelInvocable?: boolean;\n reason?: NotInvocableReason;\n}\n\n/**\n * One directory's verdict. `shadowed` and `partial` are actionable; `hosted-only`\n * is a working zero-install machine, not a defect; `empty` is not a Tenjin dir.\n */\nexport type DirState = 'empty' | 'hosted-only' | 'partial' | 'shadowed' | 'wired';\n\nexport interface HarnessWiring {\n dir: string;\n exists: boolean;\n skills: SkillWiring[];\n state: DirState;\n}\n\n/** Every skills directory a harness on this machine reads. */\nexport function skillsDirsFor(home: string): string[] {\n return [join(home, '.claude', 'skills'), join(home, '.agents', 'skills')];\n}\n\n/** The skills directory a real harness reads. */\nexport function harnessTargetDir(home: string, harness: Harness): string {\n if (harness === 'claude') return join(home, '.claude', 'skills');\n return join(home, '.agents', 'skills');\n}\n\n/**\n * The `--harness` value that targets `dir`. A Claude-only machine never targets\n * ~/.agents/skills by default, so a bare `tenjin install` cannot clear a problem\n * found there.\n */\nexport function harnessFlagFor(home: string, dir: string): Harness {\n if (dir === join(home, '.claude', 'skills')) return 'claude';\n return 'codex';\n}\n\n/**\n * Why we think `harness` is on this machine: its home dir (~/.claude, ~/.codex) and\n * its binary on PATH. Single-sourced so `install` picks its targets and `doctor`\n * decides which directories MUST be wired from the same two probes — a directory no\n * harness here reads is a leftover, not a defect.\n */\nexport function harnessDetectedBy(\n home: string,\n harness: Harness,\n which: (bin: string) => boolean,\n): string[] {\n const reasons: string[] = [];\n if (existsSync(join(home, `.${harness}`))) reasons.push('home-dir');\n if (which(harness)) reasons.push('binary');\n return reasons;\n}\n\nexport interface HarnessPresence {\n claude: boolean;\n codex: boolean;\n}\n\nexport function detectHarnesses(home: string, which: (bin: string) => boolean): HarnessPresence {\n return {\n claude: harnessDetectedBy(home, 'claude', which).length > 0,\n codex: harnessDetectedBy(home, 'codex', which).length > 0,\n };\n}\n\n/**\n * Does a harness ON THIS MACHINE read `dir`? Claude Code reads ~/.claude/skills and\n * Codex reads ~/.agents/skills, so a wired .agents does NOT make Claude Code wired:\n * the question has to be asked per directory.\n */\nexport function harnessReads(home: string, dir: string, present: HarnessPresence): boolean {\n if (harnessFlagFor(home, dir) === 'claude') return present.claude;\n return present.codex;\n}\n\n/**\n * Did the last settled install selection name `dir` on purpose? Detection is a\n * current machine fact; `requested` is the operator's answer and outranks it.\n */\nexport function harnessRequested(\n home: string,\n dir: string,\n requested: readonly Harness[],\n): boolean {\n return requested.some((h) => harnessTargetDir(home, h) === dir);\n}\n\n/**\n * Is `dir` this machine's business at all? Once the operator has settled an install\n * selection, that answer is authoritative. Detection is only the fallback for homes\n * that predate the selection record. `harnessPresent` remains a separate detection\n * fact for reporting.\n */\nexport function harnessInPlay(\n home: string,\n dir: string,\n present: HarnessPresence,\n requested: readonly Harness[],\n): boolean {\n if (requested.length > 0) return harnessRequested(home, dir, requested);\n return harnessReads(home, dir, present);\n}\n\n/**\n * Is `bin` a real executable file on PATH? Gates on statSync().isFile() so a\n * same-named DIRECTORY on PATH never false-positives as the binary, and probes the\n * PATHEXT extensions on win32 where the real binary is `claude.cmd`/`claude.exe`\n * rather than a bare `claude`.\n */\nexport function onPath(bin: string, env: NodeJS.ProcessEnv): boolean {\n const raw = env.PATH ?? '';\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of raw.split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (isFile(join(part, bin + ext))) return true;\n }\n }\n return false;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nexport async function readHarnessWiring(dir: string): Promise<HarnessWiring> {\n const exists = existsSync(dir);\n const skills: SkillWiring[] = [];\n for (const name of SKILL_NAMES) skills.push(await readSkillWiring(dir, name));\n return { dir, exists, skills, state: classify(skills) };\n}\n\nexport async function readAllWiring(home: string): Promise<HarnessWiring[]> {\n const out: HarnessWiring[] = [];\n for (const dir of skillsDirsFor(home)) out.push(await readHarnessWiring(dir));\n return out;\n}\n\nfunction classify(skills: SkillWiring[]): DirState {\n const cli = CLI_SKILL_NAMES.map((n) => skills.find((s) => s.name === n)).filter(\n (s) => s?.present === true,\n );\n if (cli.length === 0) return skills.some((s) => s.present) ? 'hosted-only' : 'empty';\n if (cli.some((s) => s?.modelInvocable === false)) return 'shadowed';\n return cli.length === CLI_SKILL_NAMES.length ? 'wired' : 'partial';\n}\n\n/**\n * What reading a SKILL.md found. A skill path is operator-controlled, so it is not\n * necessarily a file at all.\n */\nexport type SkillFileRead =\n | { kind: 'ok'; bytes: Buffer }\n | { kind: 'absent' }\n | { kind: 'not-regular' }\n | { kind: 'unreadable'; err: unknown };\n\n/**\n * Read a SKILL.md through ONE descriptor, and only when it is a regular file.\n *\n * `readFile` on a FIFO blocks until a writer appears, and on a character device it\n * streams without end; neither call fails, so no error handling reaches them. A\n * pipe at a wired SKILL.md path hung `tenjin doctor` and `tenjin install` past\n * SIGTERM. Opening non-blocking returns immediately whatever the node type is,\n * `fstat` on that descriptor says what it actually is, and only a regular file is\n * read. Checking the pathname and then reading the pathname would let the two\n * answer about different files.\n *\n * O_NONBLOCK does not exist on Windows, where it degrades to 0; FIFOs are not a\n * meaningful case there.\n */\nexport async function readSkillFile(path: string): Promise<SkillFileRead> {\n let handle: FileHandle;\n try {\n handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', err };\n }\n try {\n if (!(await handle.stat()).isFile()) return { kind: 'not-regular' };\n return { kind: 'ok', bytes: await handle.readFile() };\n } catch (err) {\n return { kind: 'unreadable', err };\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\nasync function readSkillWiring(dir: string, name: string): Promise<SkillWiring> {\n const read = await readSkillFile(join(dir, name, 'SKILL.md'));\n if (read.kind === 'absent') return { name, present: false };\n // A pipe or a device is there, but it is not a skill and must never be read as\n // one; `unreadable` is the state that already describes \"present, unusable\".\n if (read.kind !== 'ok')\n return { name, present: true, modelInvocable: false, reason: 'unreadable' };\n const text = read.bytes.toString('utf8');\n if (isModelInvocationDisabled(text)) {\n return { name, present: true, modelInvocable: false, reason: 'disabled' };\n }\n return { name, present: true, modelInvocable: true };\n}\n\n/** YAML 1.1 truthy spellings a harness frontmatter parser may accept. */\nconst YAML_TRUE = /^(?:true|yes|on)$/i;\n\n/**\n * Deliberately not a general YAML parse: only the leading `---` block is read,\n * because this repo's own skills discuss the key in prose and a whole-file match\n * would call a working skill disabled.\n */\nexport function isModelInvocationDisabled(skillMd: string): boolean {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return false;\n return frontmatter.some((line) => {\n const m = /^disable-model-invocation:\\s*(.+?)\\s*$/.exec(line.trim());\n if (m === null) return false;\n // Strip an inline `# comment` and optional quotes before testing truthiness.\n const value = (m[1] ?? '').replace(/\\s+#.*$/, '').replace(/^[\"']|[\"']$/g, '');\n return YAML_TRUE.test(value);\n });\n}\n\n/**\n * The `name:` a SKILL.md declares in its leading frontmatter, or null when it\n * declares none. It is what a harness registers the skill AS, so it is also the\n * cheapest evidence that a file at one of our paths is one of ours: the\n * unattended self-heal refuses to overwrite a same-named third-party skill.\n */\nexport function skillFrontmatterName(skillMd: string): string | null {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return null;\n for (const line of frontmatter) {\n const m = /^name:\\s*(.+?)\\s*$/.exec(line);\n if (m !== null) return (m[1] ?? '').replace(/^[\"']|[\"']$/g, '');\n }\n return null;\n}\n\nfunction extractFrontmatter(text: string): string[] | null {\n // Tolerate a UTF-8 BOM, CRLF, and leading blank lines before the opening fence.\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 if (end === -1) return null;\n return lines.slice(open + 1, end);\n}\n\nexport function cliSkillsWired(wiring: HarnessWiring): boolean {\n return wiring.state === 'wired';\n}\n\nexport function missingCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter(\n (name) => wiring.skills.find((x) => x.name === name)?.present !== true,\n );\n}\n\nexport function shadowedCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter((name) => {\n const s = wiring.skills.find((x) => x.name === name);\n return s?.present === true && s.modelInvocable === false;\n });\n}\n\nexport function anyTenjinSkill(wiring: HarnessWiring): boolean {\n return wiring.state !== 'empty';\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,SAAS,YAAY;AASvB,IAAM,cAAc,CAAC,iBAAiB,kBAAkB,QAAQ;AAUhE,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB,CAAC,kBAAkB;AAIhD,IAAM,uBAAuB,CAAC,GAAG,aAAa,GAAG,oBAAoB;AA2B5E,IAAM,WAAW,KAAK,UAAU,UAAU;AAWnC,SAAS,oBAAoB,UAA0B;AAC5D,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG;AAC7B,UAAM,YAAY,KAAK,KAAK,QAAQ;AACpC,QAAI,WAAW,KAAK,WAAW,QAAQ,CAAC,EAAG,QAAO;AAClD,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAAK;AACpB,UAAM;AAAA,EACR;AACA,QAAM,IAAI,SAA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,KAAM,QAAO;AACjC,aAAW,QAAQ,aAAa;AAC9B,UAAM,IAAI,qBAAqB,KAAK,IAAI;AACxC,QAAI,MAAM,KAAM,SAAQ,EAAE,CAAC,KAAK,IAAI,QAAQ,gBAAgB,EAAE;AAAA,EAChE;AACA,SAAO;AACT;AAEA,SAAS,mBAAmB,MAA+B;AAEzD,QAAM,QAAQ,KAAK,QAAQ,WAAW,EAAE,EAAE,MAAM,OAAO;AACvD,QAAME,QAAO,MAAM,UAAU,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC;AACvD,MAAIA,UAAS,MAAM,MAAMA,KAAI,GAAG,KAAK,MAAM,MAAO,QAAO;AACzD,QAAM,MAAM,MAAM,UAAU,CAAC,GAAG,MAAM,IAAIA,SAAQ,EAAE,KAAK,MAAM,KAAK;AACpE,MAAI,QAAQ,GAAI,QAAO;AACvB,SAAO,MAAM,MAAMA,QAAO,GAAG,GAAG;AAClC;","names":["existsSync","join","join","existsSync","open"]}
@@ -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-5X4SZ5BF.js";
6
+ import {
7
+ external_exports
8
+ } from "./chunk-BBVUVBUO.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. DISPLAY ONLY: the amount actually
45
+ * signed is what `gateSpend` caps. */
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-USS336NF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\n\n/**\n * `POST /api/x402-router`: ONE FREE DECISION PER LOOKUP.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * NOTHING IS STORED LOCALLY. The bounded packet travels with the request and\n * the backend keeps it against the decision id until that id expires, which is\n * how `request({query})` reaches the same calibrated input with no session\n * file, no timestamp latch and no guess about which window this process serves.\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. DISPLAY ONLY: the amount actually\n * signed is what `gateSpend` caps. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift.\n */\n hint: z.string().min(1).max(1_000),\n })\n .superRefine((decision, ctx) => {\n // STRUCTURE, NEVER WORDING. This line lands in the model's context\n // verbatim, so the shape is checked the way the id's alphabet is: one\n // line, no control characters, and it has to be the call it claims to be,\n // naming the id this same answer carries. A hint that fails any of these\n // is a protocol error and the turn falls back to the generic line; nothing\n // here rewrites a word of a hint that passes.\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n }),\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool';\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone.\n */\nexport function buildHookBody(packet: Packet): Record<string, unknown> {\n return { schemaVersion: 1, packet };\n}\n\n/** The exact body the tool call sends. `id` is the turn whose packet decides\n * with this query; `gateHint` is evidence, never authority. */\nexport function buildToolBody(request: {\n query: string;\n id?: string;\n gateHint?: GateHint;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n query: request.query,\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n return { success: schema.safeParse(value).success };\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n}\n\nexport type DecisionOutcome<T> =\n | { status: 'decided'; decision: T }\n /** Nothing was paid and nothing could be: the endpoint is free, so a failure\n * here costs the turn a routing answer and nothing else. */\n | { status: 'failed'; reason: string; errorCode?: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id. The tool sends\n * `{ query, id? }`: the backend makes THE decision from that query plus the\n * packet it stored, and answers with the contract to run.\n *\n * The tool never sends a packet of its own. The turn's context lives on the\n * backend against the id, and the query the model wrote is what the routing\n * corpus is calibrated against: 55 of 56 for query plus packet, 53 of 56 for\n * the raw prompt, measured on jev-1.13.0.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet)\n : buildToolBody({\n query: request.query as string,\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n return readDecision(\n await httpRequest(url, options),\n kind === 'hook' ? HookResponseSchema : ToolResponseSchema,\n );\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) return { status: 'failed', reason: fetchFailureToCliError(response).message };\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n"],"mappings":";;;;;;;;;;AAuBO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAAA,EACxC,MAAM,iBACH,OAAO,EACP,IAAI,MAAM,IAAI,EACd,SAAS;AACd,CAAC;AAED,IAAM,iBAAiB,iBAAE,OAAO;AAAA;AAAA;AAAA,EAG9B,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACtD,cAAc,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACzD,SAAS;AACX,CAAC;AAQD,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACjC,YAAY,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAAA,EACpC,OAAO,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAAA,EAC/B,SAAS,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AAA;AAAA;AAAA,MAGR,QACE,UAAU,OACN,gCAAgC,SAAS,MAAM,MAC/C,gCAAgC,SAAS,MAAM,KAAK,MAAM,IAAI,MAAM,MAAM,OAAO;AAAA,MACvF,GAAI,UAAU,OAAO,EAAE,WAAW,MAAM,KAAK,IAAI,CAAC;AAAA,IACpD;AAAA,EACF;AACA,QAAM,SAAS,OAAO,UAAU,SAAS,IAAI;AAC7C,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,EAAE,QAAQ,UAAU,QAAQ,yDAAyD;AAAA,EAC9F;AACA,SAAO,EAAE,QAAQ,WAAW,UAAU,OAAO,KAAmB;AAClE;AAIA,SAAS,QAAQ,MAAyD;AACxE,MAAI,SAAS,QAAQ,OAAO,SAAS,SAAU,QAAO;AACtD,QAAM,QAAS,KAA6B;AAC5C,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AACxD,QAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,MAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAS,GAAI,QAAO;AAC9E,QAAM,OAAO,OAAO,YAAY,WAAW,QAAQ,MAAM,GAAG,GAAG,IAAI;AACnE,SAAO,EAAE,MAAM,SAAS,KAAK;AAC/B;","names":[]}
@@ -1,4 +1,49 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ CliError
4
+ } from "./chunk-OCBHUHWB.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
+ }
42
+
43
+ // src/lib/errno.ts
44
+ function hasCode(err, code) {
45
+ return typeof err === "object" && err !== null && "code" in err && err.code === code;
46
+ }
2
47
 
3
48
  // src/lib/policy.ts
4
49
  function normCreator(value) {
@@ -63,7 +108,10 @@ function parseConfirmPolicy(stored) {
63
108
  }
64
109
 
65
110
  export {
111
+ hasCode,
112
+ parseUsdToAtomic,
113
+ toMoney,
66
114
  evaluateSpendPolicy,
67
115
  parseConfirmPolicy
68
116
  };
69
- //# sourceMappingURL=chunk-UO22YNY4.js.map
117
+ //# sourceMappingURL=chunk-WH7OWT6G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/money.ts","../src/lib/errno.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 * True when `err` is a Node system error carrying the given `code` (ENOENT,\n * EEXIST, …). One definition so the fs-error checks scattered across the wallet\n * store, config loader, and session cache stay identical.\n */\nexport function hasCode(err: unknown, code: string): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code?: unknown }).code === code\n );\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"],"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,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,29 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/permissions.ts
4
+ var PUBLISH_MODE_ALLOWLIST = [
5
+ {
6
+ rule: "Bash(tenjin publish:*)",
7
+ command: "tenjin publish",
8
+ note: "PUBLISHES PUBLICLY under your identity, and is cleared only while publish.mode is auto or full-auto: the mode is the consent, and the harness prompt would ask for it twice. Three things it clears that the free tier never did. It OPENS THE KEYSTORE: publish always resolves a signer, and with no usable session it mints one at read+write scope, which is strictly broader than the read-only key `tenjin read` mints to recover an owned piece. It publishes the contents of ANY REGULAR LOCAL FILE the agent can read, gated only by the heuristic scan. And it is a PREFIX rule, so it pins the verb and not the flags: `--base-url` rides it (see the flag caveat), and `--yes` is an ordinary flag on the same verb that clears exactly the WARN findings auto stopped on, so a re-run collapses auto into full-auto with nobody asked. The local scan is warn-only now and every finding routes through the same consent flow this mode already governs; what still refuses a publish outright is the SERVER\u2019s ingest gate (vendor tokens, private keys, seed phrases, DB passwords, bearer headers), which no mode and no flag clears. The skills hold the rest of that line. Set publish.mode back to review and the rule is retracted."
9
+ },
10
+ {
11
+ rule: "Bash(tenjin edit:*)",
12
+ command: "tenjin edit",
13
+ note: "Updates posts your wallet ALREADY OWNS: reprices, refreshes an as-of date, repairs an answer card, and flips status both ways, so it CAN PROMOTE A DRAFT TO PUBLISHED under this same gate (promotion re-runs the block-tier secret scan over the stored body). Owner-scoped on both legs (GET and PUT /api/posts/<id> are signed and owner-only), spends nothing, moves no keys, and mints no new posts: a narrower blast radius than the publish rule beside it, though promotion means existing drafts can go public. It rides the same mode for the same reason: edit runs the identical publish.mode consent gate in the CLI (lib/consent.ts needsConfirmation), so a mode that publishes unattended and then cannot fix its own post\u2019s price is the asymmetry the mode exists to remove. It opens the keystore on the same terms as the publish rule beside it, and takes the same prefix-rule caveats. Removed by the same return to review."
14
+ }
15
+ ];
16
+ function modeGatedAllowlist(mode) {
17
+ return mode === "review" ? [] : PUBLISH_MODE_ALLOWLIST.map((e) => ({ ...e }));
18
+ }
19
+ var PERMISSIONS_DOC_URL = "https://github.com/BackTrackCo/tenjin-agent/blob/main/docs/agent-permissions.md";
20
+ function modeGatedPointer(mode, missing, remedy = "tenjin install") {
21
+ if (modeGatedAllowlist(mode).length === 0 || missing.length === 0) return null;
22
+ return `publish.mode=${mode} also needs ${missing.join(" and ")} in your harness allowlist, or it will prompt anyway; \`${remedy}\` writes them.`;
23
+ }
24
+
25
+ export {
26
+ PERMISSIONS_DOC_URL,
27
+ modeGatedPointer
28
+ };
29
+ //# sourceMappingURL=chunk-WXC57XGG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/permissions.ts"],"sourcesContent":["/**\n * The recommended HARNESS permission allowlist: the exact rule lines an operator\n * pastes into Claude Code (or an equivalent harness) so auto mode stops denying\n * the free Tenjin verbs, and so the one paying verb is cleared deliberately\n * rather than by accident.\n *\n * This is a HARNESS-side allowlist (which shell commands the agent may run at\n * all). It is NOT the CLI's spend policy and shares nothing with it: the shipped\n * `allowlistCreators` config key gates WHO you may pay, this file gates WHICH\n * COMMANDS the harness will run without a prompt. The two are deliberately kept\n * apart in name and in code — clearing `Bash(tenjin buy:*)` here never raises a\n * spend cap. That is a claim about this file, NOT a claim that the spend policy\n * stops an allowlisted `buy`: `--yes` is an ordinary flag on an allowlisted verb\n * and `confirmSpend` returns true on it before any TTY check\n * (src/commands/buy.ts), so under CONFIG_DEFAULTS nothing denies. See\n * OPT_IN_ALLOWLIST's note for the walk-through.\n *\n * These are static, shipped constants on purpose: there is NO config key for\n * them. An operator-editable \"which commands may run\" list stored next to the\n * spend policy would be a second, weaker copy of a control the harness already\n * owns, and a CLI that could widen its own permission grant is exactly the shape\n * this file exists to avoid.\n *\n * Scope: `tenjin mcp` exposes the same command cores over MCP, where the harness\n * gates TOOLS, not Bash lines. These rules say nothing about that surface, which\n * is why `tenjin mcp` is itself never recommended here: clearing it would route\n * around every rule below. MCP_CAVEAT names the tools to leave gated for an\n * operator who runs the server anyway.\n *\n * LIMIT OF A PREFIX RULE, read this before adding an entry: the rule constrains\n * the VERB and nothing else. `addGlobalFlags` (src/cli.ts) puts `--json`,\n * `--timeout`, and `--base-url` on every leaf command, so every rule below also\n * clears `--base-url <url>` in trailing position. `--base-url` is validated as a\n * URL and nothing more, and it wins settings precedence, so it re-points the\n * trust boundary itself: the `search` question goes to that host, `doctor` probes\n * it, and `assertOnBaseOrigin` only checks that a resource URL shares an origin\n * with the CONFIGURED base, so an attacker-controlled pair satisfies the pin. No\n * prefix syntax expresses \"this verb but not that flag\", so the mitigation is\n * disclosure rather than a narrower rule: FLAG_CAVEAT rides the `--json` payload\n * and docs/agent-permissions.md, every human surface points at that page, and the\n * skills tell the agent never to pass `--base-url` on an allowlisted verb. Pinning\n * the paying path to a constant origin instead is the real fix and is an\n * x402/payments-semantics change, tracked separately.\n */\n\nimport type { PublishMode } from './config';\n\n/** One pasteable allowlist rule plus why it is safe (or what it costs). */\nexport interface AllowlistEntry {\n /** The exact line to add to the harness permission allowlist. */\n rule: string;\n /** The verb it clears. */\n command: string;\n /** Why it is safe to pre-clear, or what the operator is opting into. */\n note: string;\n}\n\n/** A verb deliberately kept OUT of the recommended allowlist, and why. */\nexport interface ExcludedVerb {\n command: string;\n reason: string;\n}\n\n/**\n * FREE verbs: they CANNOT SPEND. That is the whole definition of this tier, and\n * it is deliberately narrower than the older \"no wallet, no signing, no\n * payment\" — which stopped being true the moment `read` gained the ability to\n * recover an owned piece. `read` signs, with a P-256 delegation, and mints one\n * with a wallet signature when none is live; what it cannot do is produce the\n * secp256k1/EIP-712 signature a payment authorization needs (wrong curve), which\n * is test-pinned by its import graph never reaching the payment module. Money\n * stays out of reach; a signature, and the keystore access behind minting one,\n * no longer do, so the tier says what it means. `doctor` decrypts locally to\n * check the wallet still opens.\n *\n * What the tier does NOT claim, because it is not true: that the read scope\n * limits what a leaked delegation is worth. Scope is enforced only on the request\n * shape that carries both a session signature and the delegation header; the same\n * delegation replayed as a plain `SIGN-IN-WITH-X` takes a different server path\n * where no scope logic runs. So a session file is a wallet-derived credential\n * with the authority of the wallet behind it, and the mitigations that actually\n * hold are the ones in this repo: it is 0600, short-lived (≤24h, server-clamped),\n * bound to the origin it was minted for, and never presented off that origin.\n * Treat \"read is allowlisted\" as \"read may transmit that credential to the\n * configured origin\", and see FLAG_CAVEAT for why the configured origin is not\n * automatically the one you configured.\n *\n * Not all of them are read-only, and the difference is disclosed rather than\n * papered over — `search` POSTs the (generalized, anonymous) question off-machine\n * and records it locally, `outcome` POSTs a report that moves the marketplace's\n * reuse signal (both unauthenticated remote writes), and `read` writes locally,\n * saving a delivered piece to the library, and `doctor` decrypts the keystore\n * locally to check it opens. Pre-clearing them is defensible because they cost\n * nothing and none of it leaves the machine; calling them read-only to justify it\n * would not be.\n *\n * Rules are PREFIX rules: `Bash(tenjin search:*)` clears commands that start with\n * `tenjin search` and nothing else. The narrow `wallet show` / `wallet balance` /\n * The `config get` form is deliberate: a `Bash(tenjin wallet:*)`\n * or `Bash(tenjin config:*)` rule would silently swallow `wallet create` and\n * `config set`, and `config set` can raise the spend caps.\n *\n * Two known gaps, both fail-closed (denied, never wrongly allowed):\n * - Bare `tenjin config` (runConfigList) is as read-only as `config get`, but no\n * prefix rule reaches it without also covering `config set`, so it stays out.\n * Use `tenjin config get <key>`, which is a different supported command rather\n * than a reworded one.\n * - Group-level flag forms like `tenjin wallet --json show` are not covered.\n * Put global flags AFTER the leaf verb (`tenjin wallet show --json`); the\n * CLI parses either, and only the trailing form matches these rules.\n */\nexport const ALWAYS_SAFE_ALLOWLIST: readonly AllowlistEntry[] = [\n {\n rule: 'Bash(tenjin search:*)',\n command: 'tenjin search',\n note:\n 'Free anonymous marketplace search. No wallet, no signing, no payment. ' +\n 'Not read-only: it POSTs the generalized question off-machine and records ' +\n 'the search locally.',\n },\n {\n rule: 'Bash(tenjin wallet fund:*)',\n command: 'tenjin wallet fund',\n note:\n 'Owner call (2026-08-12): free on both surfaces, because the command just opens the ' +\n 'fund modal. Minting moves no money: the destination is server-pinned to the wallet ' +\n 'that signed, the CLI refuses any checkout host but pay.coinbase.com, and payment ' +\n 'happens behind Coinbase\\u2019s own human gate. The usual --base-url caveat does not ' +\n 'apply: fund is pinned to the production origin and takes no override from flag, ' +\n 'env, or config.',\n },\n {\n rule: 'Bash(tenjin inspect:*)',\n command: 'tenjin inspect',\n note: 'Free pre-purchase card and preview. Never signs, never pays, never saves.',\n },\n {\n rule: 'Bash(tenjin read:*)',\n command: 'tenjin read',\n note:\n 'Free-only delivery: free pieces, local-library re-reads, and pieces this ' +\n 'wallet already owns. Cannot spend: the payment module is absent from its ' +\n 'import graph, and the key it signs with is a P-256 delegation, the wrong ' +\n 'curve to authorize a payment. OPENS THE KEYSTORE (one wallet signature) ' +\n 'when an owned piece is not on this machine and no session key is live, ' +\n 'minting the same ≤24h read-scoped delegation `publish` and `edit` mint; ' +\n 'every later owned read reuses it and asks for nothing. TRANSMITS A ' +\n 'CREDENTIAL: that wallet-derived delegation goes to the server on a cold ' +\n '402. It is minted and presented only for the origin of the piece being ' +\n 'read, and never for a second origin while one for another is cached, ' +\n 'which is what bounds a stray `--base-url`; no scope on it limits what a ' +\n 'holder could do with it. Not read-only: a freshly delivered piece is ' +\n 'saved to the library.',\n },\n {\n rule: 'Bash(tenjin outcome:*)',\n command: 'tenjin outcome',\n note:\n 'Free honest outcome report on a past search. No wallet, no payment. ' +\n 'Not read-only: it POSTs a report that moves the marketplace reuse signal.',\n },\n {\n rule: 'Bash(tenjin doctor:*)',\n command: 'tenjin doctor',\n note:\n 'Local environment and API reachability diagnostics. Decrypts the wallet ' +\n 'locally to check it still opens; signs nothing and sends nothing.',\n },\n {\n rule: 'Bash(tenjin wallet show:*)',\n command: 'tenjin wallet show',\n note: 'Prints the wallet address and key source. Never prints the key.',\n },\n {\n rule: 'Bash(tenjin wallet balance:*)',\n command: 'tenjin wallet balance',\n note: 'Read-only USDC balance query on Base.',\n },\n {\n rule: 'Bash(tenjin config get:*)',\n command: 'tenjin config get',\n note:\n 'Reads one effective config value. `config set` is excluded on purpose. ' +\n 'Note `config get rpcUrl` returns your RPC URL, which commonly embeds a ' +\n 'provider API key: no wallet secret, but a credential-adjacent read.',\n },\n];\n\n/**\n * The verbs offered as EXPLICIT opt-in lines rather than shipped in the safe set:\n * the one that spends, and the one that opens the keystore.\n *\n * Read the buy note carefully before pasting the line: on the DEFAULT config this\n * rule authorizes unattended spending up to the wallet balance. Walking\n * evaluateSpendPolicy (lib/policy.ts) against CONFIG_DEFAULTS with an agent that\n * passes `--yes` (which this repo's own skill snippet offers):\n * - `maxPriceAtomic` is unset unless the agent chooses to pass `--max-price`;\n * - `allowlistCreators` is empty, so the creator gate is off;\n * - `sessionBudget` is '0', which `if (policy.sessionBudgetAtomic > 0n)` reads\n * as DISABLED, not as a zero ceiling;\n * - `maxAutoSpend` '0' and `confirm` 'always' both land on `confirm`, and\n * `confirmSpend` returns true on `--yes` before any TTY check.\n * Nothing denies. Note the asymmetry that makes the pair read safer than it is:\n * `maxAutoSpend: '0'` means \"auto-approve nothing\" while `sessionBudget: '0'`\n * means \"no ceiling at all\".\n */\nexport const OPT_IN_ALLOWLIST: readonly AllowlistEntry[] = [\n {\n rule: 'Bash(tenjin buy:*)',\n command: 'tenjin buy',\n note:\n 'SPENDS USDC on Base, unrefundably. This authorizes UNATTENDED purchases: ' +\n '`--yes` is an ordinary flag on the same allowlisted verb and it clears the ' +\n 'confirm gate, so on the default config nothing stops a spend up to your ' +\n 'wallet balance. Set a real ceiling first with ' +\n '`tenjin config set maxAutoSpend <usd>` and ' +\n '`tenjin config set sessionBudget <usd>` (sessionBudget 0 means NO ceiling, ' +\n 'not a zero one). This line never raises a spend cap by itself, but do not ' +\n 'read that as a human being on every purchase. Fund small.',\n },\n {\n rule: 'Bash(tenjin pay:*)',\n command: 'tenjin pay',\n note:\n 'SPENDS USDC on Base, unrefundably, at ANY x402 endpoint the origin gate ' +\n 'allows: the configured base URL always, and with `bazaarPay` on, ' +\n 'registry-listed foreign sellers too. The same spend policy and `--yes` ' +\n 'caveat as the buy line apply, and unlike `buy` there is no library ' +\n 'dedupe: a looping agent pays on every call. Set maxAutoSpend and ' +\n 'sessionBudget first, and leave `bazaarPay` off unless you mean it.',\n },\n];\n\n/**\n * The one rule that is neither always-safe nor a standing opt-in: it exists only\n * while `publish.mode` is `auto` or `full-auto`.\n *\n * The mode IS the consent. An operator who set auto has already said a clean\n * publish should proceed without asking; leaving the harness prompt in front of\n * it asks the same question a second time, in a place the mode cannot answer,\n * and the agent that hits it does the only safe thing and stops. That was the\n * observed failure: a session ran `tenjin config get publish.mode` mid-publish to\n * discover it had permission it had already been given (#161).\n *\n * NOT part of {@link recommendedRules}, and not a tier an operator picks from.\n * There is no line to paste and no flag that adds it: `install` writes it when\n * the mode it just settled is auto or full-auto, takes it back when the mode is\n * review, and `uninstall` reclaims it like every other rule this CLI wrote.\n */\nexport const PUBLISH_MODE_ALLOWLIST: readonly AllowlistEntry[] = [\n {\n rule: 'Bash(tenjin publish:*)',\n command: 'tenjin publish',\n note:\n 'PUBLISHES PUBLICLY under your identity, and is cleared only while publish.mode is ' +\n 'auto or full-auto: the mode is the consent, and the harness prompt would ask for it ' +\n 'twice. Three things it clears that the free tier never did. It OPENS THE KEYSTORE: ' +\n 'publish always resolves a signer, and with no usable session it mints one at ' +\n 'read+write scope, which is strictly broader than the read-only key `tenjin read` ' +\n 'mints to recover an owned piece. It publishes the contents ' +\n 'of ANY REGULAR LOCAL FILE the agent can read, gated only by the heuristic scan. And it is a ' +\n 'PREFIX rule, so it pins the verb and not the flags: `--base-url` rides it (see the ' +\n 'flag caveat), and `--yes` is an ordinary flag on the same verb that clears exactly ' +\n 'the WARN findings auto stopped on, so a re-run collapses auto into full-auto with ' +\n 'nobody asked. The local scan is warn-only now and every finding routes through the ' +\n 'same consent flow this mode already governs; what still refuses a publish outright is ' +\n 'the SERVER’s ingest gate (vendor tokens, private keys, seed phrases, DB passwords, ' +\n 'bearer headers), which no mode and no flag clears. The skills hold the rest of that ' +\n 'line. Set publish.mode back to review and the rule is retracted.',\n },\n {\n rule: 'Bash(tenjin edit:*)',\n command: 'tenjin edit',\n note:\n 'Updates posts your wallet ALREADY OWNS: reprices, refreshes an as-of date, repairs an ' +\n 'answer card, and flips status both ways, so it CAN PROMOTE A DRAFT TO PUBLISHED under ' +\n 'this same gate (promotion re-runs the block-tier secret scan over the stored body). ' +\n 'Owner-scoped on both legs (GET and PUT /api/posts/<id> are signed and owner-only), ' +\n 'spends nothing, moves no keys, and mints no new posts: a narrower blast radius than ' +\n 'the publish rule beside it, though promotion means existing drafts can go public. It ' +\n 'rides the same mode for the same reason: edit runs the identical publish.mode consent ' +\n 'gate in the CLI (lib/consent.ts needsConfirmation), so a mode that publishes ' +\n 'unattended and then cannot fix its own post\\u2019s price is the asymmetry the mode ' +\n 'exists to remove. It opens the keystore on the same terms as the publish rule beside ' +\n 'it, and takes the same prefix-rule caveats. Removed by the same return to review.',\n },\n];\n\n/** The mode-gated rules in effect for `mode`; empty on review. */\nexport function modeGatedAllowlist(mode: PublishMode): AllowlistEntry[] {\n return mode === 'review' ? [] : PUBLISH_MODE_ALLOWLIST.map((e) => ({ ...e }));\n}\n\n/**\n * Verbs that must NEVER appear in the recommended allowlist, with the reason each\n * one is a human decision. `tenjin wallet send` is the wallet escape hatch\n * (tenjin-agent #40) and heads this list: it moves USDC to an arbitrary address,\n * outside the spend policy that bounds `buy`. Naming it here is load-bearing even\n * in versions where the verb does not exist yet — the exclusion ships before the\n * verb does.\n *\n * `tenjin publish` stays on this list under its own terms: nothing RECOMMENDS it,\n * and no line here or on the doc page adds it. {@link PUBLISH_MODE_ALLOWLIST} is\n * not a recommendation — it is what one specific operator choice already means.\n */\nexport const NEVER_ALLOWLISTED: readonly ExcludedVerb[] = [\n {\n command: 'tenjin wallet send',\n reason:\n 'Moves USDC out of the wallet to an arbitrary address (the escape hatch, #40). ' +\n 'Irreversible and not bounded by the buy spend policy. Always a human decision.',\n },\n {\n command: 'tenjin publish',\n reason:\n 'Puts your content on a public marketplace under your identity. Never pre-cleared by the ' +\n 'free tier or an opt-in line: the only thing that clears it is `publish.mode` auto or ' +\n 'full-auto, which is the same human decision said once instead of twice (see ' +\n 'PUBLISH_MODE_ALLOWLIST). Back on review, `install` takes the rule away again.',\n },\n {\n command: 'tenjin edit',\n reason:\n 'Write-capable despite the no-flag form reading as a pure show: it edits live posts ' +\n 'and answer cards under your identity, and moves prices. A prefix rule pins the verb, ' +\n 'not the flags, so no rule can clear the read half without clearing the write half. ' +\n 'Never pre-cleared as a recommendation: like `tenjin publish`, the only thing that ' +\n 'clears it is `publish.mode` auto or full-auto, whose consent gate it already shares ' +\n '(see PUBLISH_MODE_ALLOWLIST). Back on review, `install` takes the rule away again.',\n },\n {\n command: 'tenjin delete',\n reason:\n 'Destroys a published piece. It is the one write verb `publish.mode` deliberately does NOT ' +\n 'carry: the mode is consent to publish, and reading it as consent to destroy would let one ' +\n 'decision authorize a different, irreversible one. So no mode ever clears this rule, and ' +\n 'the CLI confirms on every run regardless — a prefix rule here would only remove the ' +\n 'harness prompt in front of a command that asks its own question anyway. Reach for ' +\n '`tenjin edit --status draft` when the piece should come down reversibly.',\n },\n {\n command: 'tenjin wallet create',\n reason: 'Creates the payment credential; a stray run is a wallet you did not mean to have.',\n },\n {\n command: 'tenjin config set',\n reason:\n 'Can raise maxAutoSpend / sessionBudget / confirm, i.e. widen the agent’s own spend policy — ' +\n 'and, through shelfBypassSecret + baseUrl, put the machine in team mode, where a publish ' +\n 'skips the scan’s warn tier (except secret-assignment, and hex32-value, the warn form a ' +\n 'block-tier check demotes to) and prices at 0. It also writes ' +\n 'publish.ackServerWarnings on, the most direct consent-loosening write on this verb: ' +\n 'it lets one --yes cover the marketplace’s own scan findings, which no payload had ' +\n 'rendered when that yes was given.',\n },\n {\n command: 'tenjin install',\n reason: 'Writes into harness config and skills directories.',\n },\n {\n command: 'tenjin mcp',\n reason:\n 'Long-running server that re-exposes every command core over stdio; ' +\n 'clearing it would indirectly clear everything above.',\n },\n {\n command: 'tenjin update',\n reason:\n 'Replaces the tenjin binary the agent then runs, with whatever npm serves ' +\n 'next. Which build an agent executes is an operator decision, not something ' +\n 'a rule pre-clears. `--check` only reports, but a prefix rule pins the verb, ' +\n 'not the flags.',\n },\n];\n\n/**\n * The flag-surface caveat. A prefix rule pins the verb, never the flags, and the\n * flag that matters is `--base-url`: it is accepted on every leaf, validated only\n * as a URL, and it wins settings precedence, so it moves the destination of every\n * allowlisted verb. Printed with the rules everywhere they are printed, because\n * an operator who only reads the verb list would never learn it.\n */\nexport const FLAG_CAVEAT: readonly string[] = [\n 'Caveat: a prefix rule pins the VERB, not the flags. Every line above also clears',\n '`--base-url <url>` on that verb, which re-points where the question, the probe, the',\n 'session key `read` mints and presents, and (for buy) the signature and payment go.',\n 'Signed and credential-bearing traffic is NOT confined to the paying verb: `read` is in',\n 'the safe tier and both mints a wallet-derived delegation and transmits it, which is why',\n 'that delegation is bound to the origin it was minted for and refused elsewhere.',\n 'Allowlist these verbs only if you are content for the agent to choose the destination',\n 'host, and set the base URL in config instead of letting it be an argument. The skills',\n 'tell agents never to pass --base-url on an allowlisted verb, but that is a convention,',\n 'not an enforced boundary.',\n 'This covers the two rules your publish.mode carries as well, and bites hardest there:',\n '`tenjin publish --base-url <host>` is cleared by default on auto, and it signs against',\n 'the host it is given.',\n];\n\n/**\n * The MCP caveat. `tenjin mcp` is never recommended as a Bash rule, but an\n * operator who registers the server anyway is on a different permission surface\n * (tools, not command strings) where three excluded verbs come back.\n */\nexport const MCP_CAVEAT: readonly string[] = [\n 'Note the asymmetry: publish.mode writes the Bash rules for `publish` and `edit`, and',\n 'deliberately does not touch the MCP tool grants below. The mode is a CLI-side consent',\n 'gate, and nothing reads it on the MCP surface, so clearing those tools would hand out',\n 'the same authority with none of the same gate. Aligning the two is tracked separately.',\n 'Running the local MCP server (`tenjin mcp`) instead? That is a different permission',\n 'surface: the harness gates TOOLS there, and these Bash rules do not apply. Leave',\n '`mcp__tenjin__tenjin_publish`, `mcp__tenjin__tenjin_edit`,',\n '`mcp__tenjin__tenjin_delete`, and `mcp__tenjin__tenjin_wallet` gated. `tenjin_buy` is',\n 'the same opt-in decision as the buy line above. `tenjin_delete` is the one whose own',\n 'core still confirms even if you clear it: it never reads publish.mode.',\n];\n\n/** The machine shape emitted by `tenjin doctor --json` and `tenjin install --json`. */\nexport interface RecommendedPermissions {\n alwaysSafe: AllowlistEntry[];\n optIn: AllowlistEntry[];\n neverAllowlisted: ExcludedVerb[];\n /**\n * Rules the CURRENT publish.mode carries, empty on review. Separate from the\n * three tiers above because it is not a recommendation to weigh: it is what\n * this machine's mode already means, so a consumer that renders it beside the\n * others would be offering a choice that has been made.\n */\n modeGated: AllowlistEntry[];\n /**\n * Whether any harness on THIS machine can carry the rules above. They are\n * `Bash(...)` lines, Claude Code's grammar; a reader that took this payload\n * for a description of a Codex-only machine concluded `publish.mode=auto`\n * was in force while Codex was rejecting `tenjin publish` before the CLI ran\n * (tenjin-agent#342). The document still ships for a harness you have not\n * installed yet, so check this before treating any rule below as granted.\n */\n effective: boolean;\n /** Caveats that qualify the rules above; never omit them when rendering. */\n caveats: { flags: string[]; mcp: string[] };\n}\n\n/**\n * `mode` defaults to the shipped `review`, i.e. no mode-gated rules.\n * `effective` defaults to FALSE, so a caller that has not established such a\n * harness cannot have the payload claim one by omission.\n */\nexport function recommendedPermissions(\n mode: PublishMode = 'review',\n effective = false,\n): RecommendedPermissions {\n return {\n alwaysSafe: ALWAYS_SAFE_ALLOWLIST.map((e) => ({ ...e })),\n optIn: OPT_IN_ALLOWLIST.map((e) => ({ ...e })),\n neverAllowlisted: NEVER_ALLOWLISTED.map((e) => ({ ...e })),\n modeGated: modeGatedAllowlist(mode),\n effective,\n caveats: { flags: [...FLAG_CAVEAT], mcp: [...MCP_CAVEAT] },\n };\n}\n\n/** Every rule this module recommends adding (safe + opt-in). */\nexport function recommendedRules(): string[] {\n return [...ALWAYS_SAFE_ALLOWLIST, ...OPT_IN_ALLOWLIST].map((e) => e.rule);\n}\n\n/**\n * The permission caveats' one home. `doctor` used to print the whole thing —\n * nine rules, both opt-in notes, every exclusion, the flag caveat and the MCP\n * caveat, ~60 lines ahead of the check list it was actually run for. No doctor\n * command in the wider ecosystem carries security prose, and an operator reading\n * a wall of it in a terminal cannot paste from it, search it, or link a colleague\n * to a section. The page can do all three, so it is where the caveats live and\n * where every human surface points; `--json` still carries them as data\n * (`recommendedPermissions`), which is what an agent reads.\n */\nexport const PERMISSIONS_DOC_URL =\n 'https://github.com/BackTrackCo/tenjin-agent/blob/main/docs/agent-permissions.md';\n\n/**\n * The rules the current mode is missing, or null when it needs none. This one\n * DOES name them: they are not a tier to weigh and paste, they\n * are lines that should already be in the operator's settings file, and an\n * operator whose agent is being prompted for work the mode said not to ask about\n * needs to see exactly which rules are missing.\n *\n * CONSULTS THE MACHINE. Rendering from the mode alone told operators to add\n * rules their settings file already had, and named a remedy that in one case\n * would not have written anything — a nag that is wrong twice over on a line\n * whose whole job is to prevent an agent stalling on a prompt (#161).\n */\nexport function modeGatedPointer(\n mode: PublishMode,\n /** The mode-gated rules this machine is actually MISSING. Empty renders nothing. */\n missing: readonly string[],\n /**\n * The command that would fix it. `tenjin install` for the ordinary case; a\n * mode coming from TENJIN_PUBLISH_MODE needs `config set` instead, because\n * install resolves the mode from the global file and would write nothing.\n */\n remedy = 'tenjin install',\n): string | null {\n if (modeGatedAllowlist(mode).length === 0 || missing.length === 0) return null;\n return `publish.mode=${mode} also needs ${missing.join(' and ')} in your harness allowlist, or it will prompt anyway; \\`${remedy}\\` writes them.`;\n}\n"],"mappings":";;;AAyPO,IAAM,yBAAoD;AAAA,EAC/D;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAeJ;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,MACE;AAAA,EAWJ;AACF;AAGO,SAAS,mBAAmB,MAAqC;AACtE,SAAO,SAAS,WAAW,CAAC,IAAI,uBAAuB,IAAI,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE;AAC9E;AAwLO,IAAM,sBACX;AAcK,SAAS,iBACd,MAEA,SAMA,SAAS,kBACM;AACf,MAAI,mBAAmB,IAAI,EAAE,WAAW,KAAK,QAAQ,WAAW,EAAG,QAAO;AAC1E,SAAO,gBAAgB,IAAI,eAAe,QAAQ,KAAK,OAAO,CAAC,2DAA2D,MAAM;AAClI;","names":[]}
@@ -1,10 +1,10 @@
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
  import {
6
6
  bytesToHex
7
- } from "./chunk-KYQVEKP5.js";
7
+ } from "./chunk-BPMWXTFX.js";
8
8
  import {
9
9
  __commonJS,
10
10
  __require,
@@ -7803,4 +7803,4 @@ export {
7803
7803
  p2 as p,
7804
7804
  m2 as m
7805
7805
  };
7806
- //# sourceMappingURL=chunk-YLYINX2H.js.map
7806
+ //# sourceMappingURL=chunk-XZKD7DIF.js.map