tenjin-cli 0.1.0-alpha.1 → 0.1.0-alpha.11

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 (193) hide show
  1. package/NOTICE.md +33 -0
  2. package/README.md +596 -79
  3. package/dist/{_esm-ZH2J4QEH.js → _esm-C5CRWCYU.js} +2 -2
  4. package/dist/_esm-N4KAVXQR.js +881 -0
  5. package/dist/buy-THMVOPUH.js +44 -0
  6. package/dist/ccip-RPPPKTJR.js +19 -0
  7. package/dist/{ccip-UCLT5VOW.js → ccip-ZGGWQN4X.js} +6 -5
  8. package/dist/chunk-2I4QTOLB.js +11 -0
  9. package/dist/chunk-2I4QTOLB.js.map +1 -0
  10. package/dist/chunk-2SDUV6MQ.js +352 -0
  11. package/dist/chunk-2SDUV6MQ.js.map +1 -0
  12. package/dist/chunk-3GSZUADW.js +199 -0
  13. package/dist/chunk-3GSZUADW.js.map +1 -0
  14. package/dist/{chunk-BRJHUQSY.js → chunk-47PP7TAG.js} +908 -812
  15. package/dist/chunk-47PP7TAG.js.map +1 -0
  16. package/dist/chunk-4NTZETIL.js +158 -0
  17. package/dist/chunk-4NTZETIL.js.map +1 -0
  18. package/dist/chunk-4TCU3YRD.js +130 -0
  19. package/dist/chunk-4TCU3YRD.js.map +1 -0
  20. package/dist/chunk-6BGYHARE.js +14620 -0
  21. package/dist/chunk-6BGYHARE.js.map +1 -0
  22. package/dist/chunk-6UY2UQMY.js +213 -0
  23. package/dist/chunk-6UY2UQMY.js.map +1 -0
  24. package/dist/{chunk-IPOWB3G3.js → chunk-7FK2UN2T.js} +3515 -507
  25. package/dist/chunk-7FK2UN2T.js.map +1 -0
  26. package/dist/chunk-ALUNME53.js +306 -0
  27. package/dist/chunk-ALUNME53.js.map +1 -0
  28. package/dist/{chunk-EXBMF5X7.js → chunk-CNUXRXI2.js} +526 -79
  29. package/dist/chunk-CNUXRXI2.js.map +1 -0
  30. package/dist/chunk-E6YOODH7.js +913 -0
  31. package/dist/chunk-E6YOODH7.js.map +1 -0
  32. package/dist/chunk-EDVI7RRD.js +317 -0
  33. package/dist/chunk-EDVI7RRD.js.map +1 -0
  34. package/dist/chunk-FKSAUOJU.js +137 -0
  35. package/dist/chunk-FKSAUOJU.js.map +1 -0
  36. package/dist/chunk-GKV6VZSZ.js +125 -0
  37. package/dist/chunk-GKV6VZSZ.js.map +1 -0
  38. package/dist/chunk-GUUAYR3K.js +175 -0
  39. package/dist/chunk-GUUAYR3K.js.map +1 -0
  40. package/dist/chunk-IAFYUFIC.js +1408 -0
  41. package/dist/chunk-IAFYUFIC.js.map +1 -0
  42. package/dist/chunk-IB63U6BM.js +185 -0
  43. package/dist/chunk-IB63U6BM.js.map +1 -0
  44. package/dist/chunk-IXTENA2H.js +235 -0
  45. package/dist/chunk-IXTENA2H.js.map +1 -0
  46. package/dist/chunk-JTYIX6OD.js +161 -0
  47. package/dist/chunk-JTYIX6OD.js.map +1 -0
  48. package/dist/chunk-KYQVEKP5.js +209 -0
  49. package/dist/chunk-KYQVEKP5.js.map +1 -0
  50. package/dist/chunk-KZAAWQNP.js +6199 -0
  51. package/dist/chunk-KZAAWQNP.js.map +1 -0
  52. package/dist/{chunk-T4LKNY7T.js → chunk-M2O56UK7.js} +225 -70
  53. package/dist/chunk-M2O56UK7.js.map +1 -0
  54. package/dist/chunk-MJZZTKCC.js +323 -0
  55. package/dist/chunk-MJZZTKCC.js.map +1 -0
  56. package/dist/chunk-NUF2PKJO.js +207 -0
  57. package/dist/chunk-NUF2PKJO.js.map +1 -0
  58. package/dist/chunk-O25VWJCG.js +1357 -0
  59. package/dist/chunk-O25VWJCG.js.map +1 -0
  60. package/dist/chunk-OCN27NJV.js +612 -0
  61. package/dist/chunk-OCN27NJV.js.map +1 -0
  62. package/dist/chunk-OZHJ3FLR.js +105 -0
  63. package/dist/chunk-OZHJ3FLR.js.map +1 -0
  64. package/dist/chunk-P74I3WH4.js +204 -0
  65. package/dist/chunk-P74I3WH4.js.map +1 -0
  66. package/dist/chunk-POJRB2AE.js +83 -0
  67. package/dist/chunk-POJRB2AE.js.map +1 -0
  68. package/dist/{chunk-YG2DO46P.js → chunk-PZRAAAY2.js} +107 -22
  69. package/dist/chunk-PZRAAAY2.js.map +1 -0
  70. package/dist/chunk-PZSUWDF2.js +35 -0
  71. package/dist/chunk-PZSUWDF2.js.map +1 -0
  72. package/dist/chunk-QW2Q2KAH.js +27 -0
  73. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  74. package/dist/{chunk-CUWUHTIL.js → chunk-RBJPAZFI.js} +16 -202
  75. package/dist/chunk-RBJPAZFI.js.map +1 -0
  76. package/dist/chunk-RSBN67PA.js +152 -0
  77. package/dist/chunk-RSBN67PA.js.map +1 -0
  78. package/dist/chunk-S5RYMCV6.js +70 -0
  79. package/dist/chunk-S5RYMCV6.js.map +1 -0
  80. package/dist/chunk-SFGXAZ3M.js +316 -0
  81. package/dist/chunk-SFGXAZ3M.js.map +1 -0
  82. package/dist/chunk-SGK2B724.js +67 -0
  83. package/dist/chunk-SGK2B724.js.map +1 -0
  84. package/dist/chunk-TDDN5GXR.js +145 -0
  85. package/dist/chunk-TDDN5GXR.js.map +1 -0
  86. package/dist/{chunk-LPRVHM7P.js → chunk-U5S527PP.js} +1655 -114
  87. package/dist/chunk-U5S527PP.js.map +1 -0
  88. package/dist/chunk-UFPJBS4C.js +242 -0
  89. package/dist/chunk-UFPJBS4C.js.map +1 -0
  90. package/dist/chunk-UHTVXQ2O.js +140 -0
  91. package/dist/chunk-UHTVXQ2O.js.map +1 -0
  92. package/dist/chunk-UY6CGULW.js +83 -0
  93. package/dist/chunk-UY6CGULW.js.map +1 -0
  94. package/dist/chunk-VWY3U732.js +674 -0
  95. package/dist/chunk-VWY3U732.js.map +1 -0
  96. package/dist/{chunk-Q53IYV2G.js → chunk-W6R3HAAG.js} +20 -17
  97. package/dist/{chunk-Q53IYV2G.js.map → chunk-W6R3HAAG.js.map} +1 -1
  98. package/dist/chunk-XJN5WUKL.js +204 -0
  99. package/dist/chunk-XJN5WUKL.js.map +1 -0
  100. package/dist/chunk-XWHXX2BI.js +149 -0
  101. package/dist/chunk-XWHXX2BI.js.map +1 -0
  102. package/dist/{chunk-DXPYFVKG.js → chunk-Y7ERTA7D.js} +35 -15
  103. package/dist/chunk-Y7ERTA7D.js.map +1 -0
  104. package/dist/chunk-YLYINX2H.js +7806 -0
  105. package/dist/chunk-YLYINX2H.js.map +1 -0
  106. package/dist/chunk-ZE7KOO7A.js +233 -0
  107. package/dist/chunk-ZE7KOO7A.js.map +1 -0
  108. package/dist/chunk-ZQIQ55KK.js +51 -0
  109. package/dist/chunk-ZQIQ55KK.js.map +1 -0
  110. package/dist/{chunk-3IMLRUZE.js → chunk-ZXTAQYNA.js} +6 -2
  111. package/dist/{cli-WA65NP4Y.js → cli-Y2HBOSGK.js} +437 -175
  112. package/dist/cli-Y2HBOSGK.js.map +1 -0
  113. package/dist/config-WDGMZKHU.js +26 -0
  114. package/dist/config-WDGMZKHU.js.map +1 -0
  115. package/dist/dist-U4M6QCKE.js +2842 -0
  116. package/dist/dist-U4M6QCKE.js.map +1 -0
  117. package/dist/doctor-CSIWKWM2.js +27 -0
  118. package/dist/doctor-CSIWKWM2.js.map +1 -0
  119. package/dist/edit-E7N6F3OY.js +38 -0
  120. package/dist/edit-E7N6F3OY.js.map +1 -0
  121. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js +18 -0
  122. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js.map +1 -0
  123. package/dist/fund-OKK627GL.js +38 -0
  124. package/dist/fund-OKK627GL.js.map +1 -0
  125. package/dist/index.js +1 -1
  126. package/dist/inspect-573WHEV4.js +35 -0
  127. package/dist/inspect-573WHEV4.js.map +1 -0
  128. package/dist/install-SQAYMNQC.js +1134 -0
  129. package/dist/install-SQAYMNQC.js.map +1 -0
  130. package/dist/{mine.wasm-GQECMSGN.js → mine.wasm-6PIT3DK6.js} +2 -2
  131. package/dist/outcome-W3KYGF23.js +22 -0
  132. package/dist/outcome-W3KYGF23.js.map +1 -0
  133. package/dist/publish-N5U4XYVA.js +40 -0
  134. package/dist/publish-N5U4XYVA.js.map +1 -0
  135. package/dist/read-PJ7Z6UGF.js +158 -0
  136. package/dist/read-PJ7Z6UGF.js.map +1 -0
  137. package/dist/run-FSO3MMXN.js +16883 -0
  138. package/dist/run-FSO3MMXN.js.map +1 -0
  139. package/dist/search-ZWOP4EGK.js +23 -0
  140. package/dist/search-ZWOP4EGK.js.map +1 -0
  141. package/dist/{secp256k1-BEZS642W.js → secp256k1-XRPVBC6V.js} +5 -4
  142. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  143. package/dist/send-F34ZDXDZ.js +223 -0
  144. package/dist/send-F34ZDXDZ.js.map +1 -0
  145. package/dist/session-4N4ZT3AH.js +88 -0
  146. package/dist/session-4N4ZT3AH.js.map +1 -0
  147. package/dist/skill-heal-XBEK272G.js +85 -0
  148. package/dist/skill-heal-XBEK272G.js.map +1 -0
  149. package/dist/uninstall-BTKPHPDL.js +68 -0
  150. package/dist/uninstall-BTKPHPDL.js.map +1 -0
  151. package/dist/usdc-4VCDHFWX.js +38 -0
  152. package/dist/usdc-4VCDHFWX.js.map +1 -0
  153. package/dist/viemAdapter-By13KInL-TUQJBMHM.js +14 -0
  154. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  155. package/dist/wallet-UL4P2JRO.js +42 -0
  156. package/dist/wallet-UL4P2JRO.js.map +1 -0
  157. package/dist/wallet-WJ6UP5OU.js +32 -0
  158. package/dist/wallet-WJ6UP5OU.js.map +1 -0
  159. package/docs/agent-permissions.md +294 -0
  160. package/package.json +25 -18
  161. package/skills/tenjin/SKILL.md +364 -0
  162. package/skills/tenjin-publish/SKILL.md +232 -0
  163. package/skills/tenjin-search/SKILL.md +341 -0
  164. package/dist/chunk-BRJHUQSY.js.map +0 -1
  165. package/dist/chunk-CUWUHTIL.js.map +0 -1
  166. package/dist/chunk-DXPYFVKG.js.map +0 -1
  167. package/dist/chunk-EXBMF5X7.js.map +0 -1
  168. package/dist/chunk-EZROUI5U.js +0 -135
  169. package/dist/chunk-EZROUI5U.js.map +0 -1
  170. package/dist/chunk-IPOWB3G3.js.map +0 -1
  171. package/dist/chunk-LPRVHM7P.js.map +0 -1
  172. package/dist/chunk-T4LKNY7T.js.map +0 -1
  173. package/dist/chunk-YBMMV4Y4.js +0 -51
  174. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  175. package/dist/chunk-YG2DO46P.js.map +0 -1
  176. package/dist/chunk-ZPZFPVDN.js +0 -67
  177. package/dist/chunk-ZPZFPVDN.js.map +0 -1
  178. package/dist/cli-WA65NP4Y.js.map +0 -1
  179. package/dist/config-CEFTL5ZL.js +0 -164
  180. package/dist/config-CEFTL5ZL.js.map +0 -1
  181. package/dist/doctor-3QBYN46N.js +0 -338
  182. package/dist/doctor-3QBYN46N.js.map +0 -1
  183. package/dist/usdc-44R6XZF2.js +0 -18
  184. package/dist/wallet-ELBTBMXO.js +0 -20
  185. package/dist/wallet-XD576HF3.js +0 -173
  186. package/dist/wallet-XD576HF3.js.map +0 -1
  187. /package/dist/{_esm-ZH2J4QEH.js.map → _esm-C5CRWCYU.js.map} +0 -0
  188. /package/dist/{ccip-UCLT5VOW.js.map → _esm-N4KAVXQR.js.map} +0 -0
  189. /package/dist/{chunk-3IMLRUZE.js.map → buy-THMVOPUH.js.map} +0 -0
  190. /package/dist/{secp256k1-BEZS642W.js.map → ccip-RPPPKTJR.js.map} +0 -0
  191. /package/dist/{usdc-44R6XZF2.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  192. /package/dist/{wallet-ELBTBMXO.js.map → chunk-ZXTAQYNA.js.map} +0 -0
  193. /package/dist/{mine.wasm-GQECMSGN.js.map → mine.wasm-6PIT3DK6.js.map} +0 -0
@@ -1,4 +1,34 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ PRIVATE_KEY_RE,
4
+ WALLET_SCHEMA_VERSION,
5
+ readWalletRecord,
6
+ walletFileMode,
7
+ writeWalletRecord
8
+ } from "./chunk-Y7ERTA7D.js";
9
+ import {
10
+ emitNotice
11
+ } from "./chunk-IB63U6BM.js";
12
+ import {
13
+ evaluateSpendPolicy,
14
+ withFileLock
15
+ } from "./chunk-FKSAUOJU.js";
16
+ import {
17
+ archivedWalletPath,
18
+ passphraseBlobPath,
19
+ passphraseBlobPathFor,
20
+ spendLedgerPath,
21
+ walletPath
22
+ } from "./chunk-ZQIQ55KK.js";
23
+ import {
24
+ hasCode
25
+ } from "./chunk-2I4QTOLB.js";
26
+ import {
27
+ CliError,
28
+ external_exports,
29
+ fsyncDir,
30
+ writeFileAtomic
31
+ } from "./chunk-PZRAAAY2.js";
2
32
  import {
3
33
  hashAuthorization,
4
34
  hashMessage,
@@ -7,16 +37,16 @@ import {
7
37
  publicKeyToAddress,
8
38
  serializeSignature,
9
39
  serializeTransaction
10
- } from "./chunk-T4LKNY7T.js";
40
+ } from "./chunk-M2O56UK7.js";
11
41
  import {
12
42
  hmac,
13
43
  secp256k1,
14
44
  sha256
15
- } from "./chunk-Q53IYV2G.js";
45
+ } from "./chunk-W6R3HAAG.js";
16
46
  import {
17
47
  InvalidAddressError,
18
- concat3 as concat,
19
- from2 as from,
48
+ concat2 as concat,
49
+ from,
20
50
  hexToBytes,
21
51
  isAddress,
22
52
  isEqual,
@@ -24,10 +54,10 @@ import {
24
54
  keccak256,
25
55
  numberToHex,
26
56
  random,
27
- slice3 as slice,
57
+ slice2 as slice,
28
58
  toHex,
29
59
  toHex2
30
- } from "./chunk-BRJHUQSY.js";
60
+ } from "./chunk-47PP7TAG.js";
31
61
  import {
32
62
  ahash,
33
63
  anumber,
@@ -39,21 +69,10 @@ import {
39
69
  rotl,
40
70
  swap32IfBE,
41
71
  u32
42
- } from "./chunk-CUWUHTIL.js";
43
- import {
44
- PRIVATE_KEY_RE,
45
- readWalletRecord,
46
- walletFileMode,
47
- writeWalletRecord
48
- } from "./chunk-DXPYFVKG.js";
49
- import {
50
- writeFileAtomic
51
- } from "./chunk-ZPZFPVDN.js";
52
- import {
53
- CliError,
54
- passphraseBlobPath,
55
- walletPath
56
- } from "./chunk-YG2DO46P.js";
72
+ } from "./chunk-KYQVEKP5.js";
73
+
74
+ // src/lib/wallet/local.ts
75
+ import { link, readdir, unlink as unlink2 } from "fs/promises";
57
76
 
58
77
  // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/pbkdf2.js
59
78
  function pbkdf2Init(hash, _password, _salt, _opts) {
@@ -754,20 +773,35 @@ function defineKey(key, options) {
754
773
  // src/lib/wallet/passphrase.ts
755
774
  import { execFile } from "child_process";
756
775
  import { randomBytes } from "crypto";
757
- import { readFile } from "fs/promises";
776
+ import { readFile, unlink } from "fs/promises";
758
777
  var KEYCHAIN_SERVICE = "tenjin-cli";
759
- var KEYCHAIN_ACCOUNT = "wallet";
778
+ var LEGACY_ACCOUNT = "wallet";
779
+ var ACCOUNT_ADDRESS_RE = /^0x[0-9a-f]{40}$/;
760
780
  var BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
761
- var defaultExec = (file, args, stdin) => new Promise((resolve, reject) => {
762
- const child = execFile(file, args, { encoding: "utf8" }, (err, stdout, stderr) => {
763
- if (err) reject(err);
764
- else resolve({ stdout, stderr });
765
- });
766
- if (stdin !== void 0) {
767
- child.stdin?.on("error", () => void 0);
768
- child.stdin?.end(stdin);
781
+ function walletStoreAccount(address) {
782
+ const account = address.toLowerCase();
783
+ if (!ACCOUNT_ADDRESS_RE.test(account)) {
784
+ throw new CliError("INTERNAL", `Not a valid wallet address for passphrase storage: ${address}`);
769
785
  }
770
- });
786
+ return account;
787
+ }
788
+ function defaultExecFor(timeoutMs) {
789
+ return (file, args, stdin) => new Promise((resolve, reject) => {
790
+ const child = execFile(
791
+ file,
792
+ args,
793
+ { encoding: "utf8", ...timeoutMs !== void 0 ? { timeout: timeoutMs } : {} },
794
+ (err, stdout, stderr) => {
795
+ if (err) reject(err);
796
+ else resolve({ stdout, stderr });
797
+ }
798
+ );
799
+ if (stdin !== void 0) {
800
+ child.stdin?.on("error", () => void 0);
801
+ child.stdin?.end(stdin);
802
+ }
803
+ });
804
+ }
771
805
  function storeFor(deps) {
772
806
  switch (deps.platform ?? process.platform) {
773
807
  case "darwin":
@@ -780,13 +814,22 @@ function storeFor(deps) {
780
814
  return null;
781
815
  }
782
816
  }
783
- async function resolvePassphrase(deps) {
817
+ async function resolvePassphrase(deps, address) {
784
818
  const fromEnv = envPassphrase(deps.env);
785
819
  if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
786
820
  const store = storeFor(deps);
787
821
  if (store !== null) {
788
- const fromStore = await store.read();
789
- if (fromStore !== null) return { passphrase: fromStore, source: store.source };
822
+ const account = walletStoreAccount(address);
823
+ const own = await store.read(account);
824
+ if (own !== null) return { passphrase: own, source: store.source };
825
+ const legacy = await store.read(LEGACY_ACCOUNT);
826
+ if (legacy !== null) {
827
+ return {
828
+ passphrase: legacy,
829
+ source: store.source,
830
+ migrateLegacy: () => migrateLegacyEntry(store, account, legacy)
831
+ };
832
+ }
790
833
  }
791
834
  if (canPrompt(deps)) {
792
835
  const entered = await promptOf(deps)("Wallet passphrase: ");
@@ -795,13 +838,29 @@ async function resolvePassphrase(deps) {
795
838
  }
796
839
  throw noPassphraseError();
797
840
  }
798
- async function resolvePassphraseForCreate(deps) {
841
+ async function migrateLegacyEntry(store, account, passphrase) {
842
+ if (!await store.store(account, passphrase)) return false;
843
+ if (await store.read(account) !== passphrase) return false;
844
+ await store.remove(LEGACY_ACCOUNT);
845
+ return true;
846
+ }
847
+ async function storePassphraseForWallet(deps, address, passphrase) {
848
+ const store = storeFor(deps);
849
+ if (store === null) return "no-store";
850
+ const account = walletStoreAccount(address);
851
+ if (await store.read(account) === passphrase) return "stored";
852
+ if (store.storable !== void 0 && !store.storable(passphrase)) return "rejected-characters";
853
+ if (!await store.store(account, passphrase)) return "store-failed";
854
+ return await store.read(account) === passphrase ? "stored" : "store-failed";
855
+ }
856
+ async function resolvePassphraseForCreate(deps, address) {
799
857
  const fromEnv = envPassphrase(deps.env);
800
858
  if (fromEnv !== null) return { passphrase: fromEnv, source: "env" };
801
859
  const store = storeFor(deps);
802
860
  if (store !== null) {
861
+ const account = walletStoreAccount(address);
803
862
  const generated = randomBytes(32).toString("base64url");
804
- if (await store.store(generated)) {
863
+ if (await store.store(account, generated) && await store.read(account) === generated) {
805
864
  return { passphrase: generated, source: store.source };
806
865
  }
807
866
  }
@@ -824,17 +883,17 @@ async function resolvePassphraseForCreate(deps) {
824
883
  throw noPassphraseError();
825
884
  }
826
885
  function keychainStore(deps) {
827
- const exec = deps.exec ?? defaultExec;
886
+ const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
828
887
  return {
829
888
  source: "keychain",
830
- async read() {
889
+ async read(account) {
831
890
  try {
832
891
  const { stdout } = await exec("security", [
833
892
  "find-generic-password",
834
893
  "-s",
835
894
  KEYCHAIN_SERVICE,
836
895
  "-a",
837
- KEYCHAIN_ACCOUNT,
896
+ account,
838
897
  "-w"
839
898
  ]);
840
899
  return trimmedNonEmpty(stdout);
@@ -842,16 +901,28 @@ function keychainStore(deps) {
842
901
  return null;
843
902
  }
844
903
  },
845
- async store(passphrase) {
846
- if (!BASE64URL_RE.test(passphrase)) return false;
904
+ // The one backend that interpolates into a command line, so only base64url
905
+ // values pass; escaping is NOT a safe alternative (backslash bites even
906
+ // inside single quotes there).
907
+ storable: (passphrase) => BASE64URL_RE.test(passphrase),
908
+ async store(account, passphrase) {
909
+ if (!BASE64URL_RE.test(passphrase) || !BASE64URL_RE.test(account)) return false;
847
910
  try {
848
- const command = `add-generic-password -U -s ${KEYCHAIN_SERVICE} -a ${KEYCHAIN_ACCOUNT} -w '${passphrase}'
911
+ const command = `add-generic-password -s ${KEYCHAIN_SERVICE} -a ${account} -w '${passphrase}'
849
912
  `;
850
913
  await exec("security", ["-i"], command);
851
914
  return true;
852
915
  } catch {
853
916
  return false;
854
917
  }
918
+ },
919
+ async remove(account) {
920
+ try {
921
+ await exec("security", ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", account]);
922
+ return true;
923
+ } catch {
924
+ return false;
925
+ }
855
926
  }
856
927
  };
857
928
  }
@@ -873,14 +944,14 @@ function powershellArgs(script) {
873
944
  return ["-NoProfile", "-NonInteractive", "-Command", script];
874
945
  }
875
946
  function dpapiStore(deps) {
876
- const exec = deps.exec ?? defaultExec;
877
- const blobPath = passphraseBlobPath(deps.dir);
947
+ const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
948
+ const blobPathFor = (account) => account === LEGACY_ACCOUNT ? passphraseBlobPath(deps.dir) : passphraseBlobPathFor(account, deps.dir);
878
949
  return {
879
950
  source: "dpapi",
880
- async read() {
951
+ async read(account) {
881
952
  let blob;
882
953
  try {
883
- blob = await readFile(blobPath, "utf8");
954
+ blob = await readFile(blobPathFor(account), "utf8");
884
955
  } catch {
885
956
  return null;
886
957
  }
@@ -896,7 +967,7 @@ function dpapiStore(deps) {
896
967
  return null;
897
968
  }
898
969
  },
899
- async store(passphrase) {
970
+ async store(account, passphrase) {
900
971
  try {
901
972
  const { stdout } = await exec(
902
973
  "powershell.exe",
@@ -905,7 +976,15 @@ function dpapiStore(deps) {
905
976
  );
906
977
  const blob = stdout.replace(/\r?\n$/, "").trim();
907
978
  if (blob.length === 0) return false;
908
- await writeFileAtomic(blobPath, blob, { mode: 384 });
979
+ await writeFileAtomic(blobPathFor(account), blob, { mode: 384 });
980
+ return true;
981
+ } catch {
982
+ return false;
983
+ }
984
+ },
985
+ async remove(account) {
986
+ try {
987
+ await unlink(blobPathFor(account));
909
988
  return true;
910
989
  } catch {
911
990
  return false;
@@ -914,34 +993,34 @@ function dpapiStore(deps) {
914
993
  };
915
994
  }
916
995
  function secretServiceStore(deps) {
917
- const exec = deps.exec ?? defaultExec;
996
+ const exec = deps.exec ?? defaultExecFor(deps.timeoutMs);
918
997
  return {
919
998
  source: "secret-service",
920
- async read() {
999
+ async read(account) {
921
1000
  try {
922
1001
  const { stdout } = await exec("secret-tool", [
923
1002
  "lookup",
924
1003
  "service",
925
1004
  KEYCHAIN_SERVICE,
926
1005
  "account",
927
- KEYCHAIN_ACCOUNT
1006
+ account
928
1007
  ]);
929
1008
  return trimmedNonEmpty(stdout);
930
1009
  } catch {
931
1010
  return null;
932
1011
  }
933
1012
  },
934
- async store(passphrase) {
1013
+ async store(account, passphrase) {
935
1014
  try {
936
1015
  await exec(
937
1016
  "secret-tool",
938
1017
  [
939
1018
  "store",
940
- "--label=tenjin-cli-wallet",
1019
+ `--label=tenjin-cli wallet ${account}`,
941
1020
  "service",
942
1021
  KEYCHAIN_SERVICE,
943
1022
  "account",
944
- KEYCHAIN_ACCOUNT
1023
+ account
945
1024
  ],
946
1025
  passphrase
947
1026
  );
@@ -949,6 +1028,14 @@ function secretServiceStore(deps) {
949
1028
  } catch {
950
1029
  return false;
951
1030
  }
1031
+ },
1032
+ async remove(account) {
1033
+ try {
1034
+ await exec("secret-tool", ["clear", "service", KEYCHAIN_SERVICE, "account", account]);
1035
+ return true;
1036
+ } catch {
1037
+ return false;
1038
+ }
952
1039
  }
953
1040
  };
954
1041
  }
@@ -1022,12 +1109,13 @@ function promptHidden(label) {
1022
1109
  // src/lib/wallet/local.ts
1023
1110
  var isWindows = process.platform === "win32";
1024
1111
  var KEY_STORAGE = "encrypted (keystore v3, scrypt)";
1112
+ var STORE_READ_TIMEOUT_MS = 5e3;
1025
1113
  var signerCache = /* @__PURE__ */ new Map();
1026
1114
  function createLocalProvider(deps) {
1027
1115
  return {
1028
1116
  id: "local",
1029
1117
  async describe() {
1030
- const cred = resolveCredentialOrThrow(await loadCredential(deps));
1118
+ const cred = await credentialOrThrow(deps);
1031
1119
  return {
1032
1120
  // A file credential's address is stored cleartext and returned as-is —
1033
1121
  // no decryption. An env credential derives (and thereby validates) its
@@ -1039,19 +1127,89 @@ function createLocalProvider(deps) {
1039
1127
  };
1040
1128
  },
1041
1129
  async getSigner() {
1042
- const cred = resolveCredentialOrThrow(await loadCredential(deps));
1130
+ const cred = await credentialOrThrow(deps);
1043
1131
  const account = await accountForSigning(cred, deps);
1044
1132
  return {
1045
1133
  address: account.address,
1046
1134
  signMessage: (args) => account.signMessage({ message: args.message }),
1047
- signTypedData: (args) => account.signTypedData(args)
1135
+ signTypedData: (args) => account.signTypedData(args),
1136
+ signTransaction: (tx) => account.signTransaction(tx)
1048
1137
  };
1049
1138
  },
1050
1139
  diagnostics() {
1051
1140
  return localWalletDiagnostics(deps);
1141
+ },
1142
+ verify() {
1143
+ return verifyLocalWallet(deps);
1052
1144
  }
1053
1145
  };
1054
1146
  }
1147
+ async function verifyLocalWallet(deps) {
1148
+ const cred = await loadCredential(deps);
1149
+ if (cred === null) return { status: "unverified", detail: "there is no credential to verify" };
1150
+ if (cred.source === "env") {
1151
+ accountFromKey(cred.key, "env");
1152
+ return { status: "verified", detail: "TENJIN_WALLET_KEY derives a valid signing key" };
1153
+ }
1154
+ const account = walletStoreAccount(cred.address);
1155
+ let resolved;
1156
+ try {
1157
+ resolved = await resolvePassphrase(
1158
+ {
1159
+ env: deps.env,
1160
+ dir: deps.dir,
1161
+ ...deps.passphrase,
1162
+ isTTY: false,
1163
+ timeoutMs: STORE_READ_TIMEOUT_MS
1164
+ },
1165
+ cred.address
1166
+ );
1167
+ } catch {
1168
+ return {
1169
+ status: "unverified",
1170
+ detail: "no passphrase is reachable without prompting, so the keystore was not opened"
1171
+ };
1172
+ }
1173
+ let key;
1174
+ try {
1175
+ const derived = await toKeyAsync(cred.keystore, { password: resolved.passphrase });
1176
+ key = decrypt(cred.keystore, derived);
1177
+ } catch {
1178
+ if (resolved.migrateLegacy !== void 0) {
1179
+ return {
1180
+ status: "broken",
1181
+ detail: `the keystore cannot be decrypted: the only stored passphrase is ${legacyOrigin(resolved.source)}, which does not open it`,
1182
+ fix: `That passphrase likely belongs to a wallet created later. Set TENJIN_WALLET_PASSPHRASE to this wallet's own passphrase, or restore ${passphraseOrigin(resolved.source, account)}.`
1183
+ };
1184
+ }
1185
+ const escape = resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not open it; set it to the correct passphrase" : `The passphrase from ${passphraseOrigin(resolved.source, account)} does not open it; set TENJIN_WALLET_PASSPHRASE to the correct passphrase`;
1186
+ return {
1187
+ status: "broken",
1188
+ detail: `the keystore cannot be decrypted with the passphrase from ${passphraseOrigin(resolved.source, account)}`,
1189
+ fix: `${escape}. Without it the key is unrecoverable and this address can no longer sign or publish.`
1190
+ };
1191
+ }
1192
+ if (privateKeyToAccount(key).address.toLowerCase() !== account) {
1193
+ return {
1194
+ status: "broken",
1195
+ detail: `the decrypted key does not derive the wallet file's stored address ${cred.address}`,
1196
+ fix: "The wallet file may be tampered. Move it aside, then run `tenjin wallet create` for a fresh key or set TENJIN_WALLET_KEY to use the intended one."
1197
+ };
1198
+ }
1199
+ return {
1200
+ status: "verified",
1201
+ detail: `keystore decrypts with the passphrase from ${passphraseOrigin(resolved.source, account)}`
1202
+ };
1203
+ }
1204
+ function passphraseOrigin(source, account) {
1205
+ if (source === "env") return "TENJIN_WALLET_PASSPHRASE";
1206
+ if (source === "prompt") return "the prompt";
1207
+ if (source === "dpapi") return `the DPAPI-protected passphrase file for ${account}`;
1208
+ return `the OS credential store (service tenjin-cli, account ${account})`;
1209
+ }
1210
+ function legacyOrigin(source) {
1211
+ return source === "dpapi" ? "the legacy shared DPAPI passphrase file (passphrase.dpapi)" : 'the legacy shared entry (service tenjin-cli, account "wallet")';
1212
+ }
1055
1213
  async function localWalletDiagnostics(deps) {
1056
1214
  const mode = await walletFileMode(deps.dir);
1057
1215
  const fileExists = mode !== null;
@@ -1072,18 +1230,133 @@ async function localWalletDiagnostics(deps) {
1072
1230
  }
1073
1231
  }
1074
1232
  const passphraseSource = deps.env.TENJIN_WALLET_PASSPHRASE !== void 0 && deps.env.TENJIN_WALLET_PASSPHRASE.length > 0 ? "TENJIN_WALLET_PASSPHRASE" : void 0;
1233
+ const archivedWallets = await listArchivedWallets(deps.dir);
1075
1234
  return {
1076
1235
  ...fileExists ? { walletPath: path, keyStorage: KEY_STORAGE } : {},
1077
1236
  ...fileExists && passphraseSource !== void 0 ? { passphraseSource } : {},
1237
+ ...archivedWallets.length > 0 ? { archivedWallets } : {},
1078
1238
  warnings
1079
1239
  };
1080
1240
  }
1081
- async function createLocalWallet(dir, passphrase) {
1241
+ var ARCHIVED_WALLET_RE = /^wallet\.(0x[0-9a-f]{40})\.json\.bak$/;
1242
+ async function listArchivedWallets(dir) {
1243
+ let names;
1244
+ try {
1245
+ names = await readdir(dir);
1246
+ } catch {
1247
+ return [];
1248
+ }
1249
+ return names.map((name) => ARCHIVED_WALLET_RE.exec(name)?.[1]).filter((address) => address !== void 0).sort();
1250
+ }
1251
+ async function prepareLocalWallet(passphrase) {
1082
1252
  const key = generatePrivateKey();
1083
1253
  const address = privateKeyToAccount(key).address;
1084
- const keystore = await encryptToKeystore(key, passphrase);
1085
- await writeWalletRecord(dir, walletRecord(address, keystore));
1086
- return { address, walletPath: walletPath(dir) };
1254
+ const resolved = typeof passphrase === "string" ? passphrase : await passphrase(address);
1255
+ const keystore = await encryptToKeystore(key, resolved);
1256
+ return { address, record: walletRecord(address, keystore) };
1257
+ }
1258
+ async function commitLocalWallet(dir, prepared) {
1259
+ await writeWalletRecord(dir, prepared.record);
1260
+ return { address: prepared.address, walletPath: walletPath(dir) };
1261
+ }
1262
+ async function createLocalWallet(dir, passphrase) {
1263
+ return commitLocalWallet(dir, await prepareLocalWallet(passphrase));
1264
+ }
1265
+ async function verifyAndPreserveOutgoingWallet(deps) {
1266
+ const record = await readWalletRecord(deps.dir);
1267
+ if (record === null) {
1268
+ throw new CliError("WALLET_MISSING", "No wallet found to archive.", {
1269
+ fix: "Run `tenjin wallet create` without --replace."
1270
+ });
1271
+ }
1272
+ const address = record.address;
1273
+ const account = walletStoreAccount(address);
1274
+ const passphraseDeps = { env: deps.env, dir: deps.dir, ...deps.passphrase };
1275
+ const resolved = await resolvePassphrase(passphraseDeps, address);
1276
+ let key;
1277
+ try {
1278
+ const derived = await toKeyAsync(record.keystore, { password: resolved.passphrase });
1279
+ key = decrypt(record.keystore, derived);
1280
+ } catch (err) {
1281
+ const escape = resolved.source === "prompt" ? "Retry and enter that wallet's correct passphrase at the prompt, or set TENJIN_WALLET_PASSPHRASE to it" : resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not decrypt it; set it to the correct passphrase" : `Set TENJIN_WALLET_PASSPHRASE to its passphrase, or fix its OS credential store entry (service tenjin-cli, account ${account})`;
1282
+ throw new CliError(
1283
+ "REFUSED",
1284
+ `Cannot verify the passphrase of the existing wallet ${address}; --replace refused.`,
1285
+ {
1286
+ fix: `Replacing now could strand that wallet's funds. ${escape}, then retry.`,
1287
+ cause: err
1288
+ }
1289
+ );
1290
+ }
1291
+ if (privateKeyToAccount(key).address.toLowerCase() !== account) {
1292
+ throw new CliError(
1293
+ "REFUSED",
1294
+ `The wallet file's stored address ${address} does not match its key; --replace refused.`,
1295
+ { fix: "The wallet file may be tampered. Resolve that before replacing it." }
1296
+ );
1297
+ }
1298
+ if (resolved.source === "env") {
1299
+ return { address, account, passphraseLocation: "env" };
1300
+ }
1301
+ if (resolved.migrateLegacy !== void 0) {
1302
+ if (!await resolved.migrateLegacy()) {
1303
+ throw new CliError(
1304
+ "REFUSED",
1305
+ `Could not archive the existing wallet's passphrase under its own address; --replace refused.`,
1306
+ {
1307
+ fix: `The passphrase currently lives only in the legacy shared slot (service tenjin-cli, account "wallet"), and copying it to account ${account} failed. Retry, or check OS credential store access.`
1308
+ }
1309
+ );
1310
+ }
1311
+ return { address, account, passphraseLocation: "store" };
1312
+ }
1313
+ if (resolved.source === "prompt") {
1314
+ const outcome = await storePassphraseForWallet(passphraseDeps, address, resolved.passphrase);
1315
+ return outcome === "stored" ? { address, account, passphraseLocation: "store" } : { address, account, passphraseLocation: "unarchived", unarchivedReason: outcome };
1316
+ }
1317
+ return { address, account, passphraseLocation: "store" };
1318
+ }
1319
+ async function parkOutgoingWallet(dir, account) {
1320
+ const src = walletPath(dir);
1321
+ const dst = archivedWalletPath(account, dir);
1322
+ try {
1323
+ await link(src, dst);
1324
+ } catch (err) {
1325
+ if (hasCode(err, "EEXIST")) {
1326
+ throw new CliError("REFUSED", `An archived wallet already exists at ${dst}.`, {
1327
+ fix: `Move ${dst} aside, then retry \`tenjin wallet create --replace\`. Nothing has moved; the current wallet is still active.`,
1328
+ cause: err
1329
+ });
1330
+ }
1331
+ throw new CliError("INTERNAL", `Could not park the outgoing keystore at ${dst}.`, {
1332
+ fix: `Nothing has moved; the current wallet is still active at ${src}. Fix the underlying filesystem error and retry.`,
1333
+ cause: err
1334
+ });
1335
+ }
1336
+ try {
1337
+ await unlink2(src);
1338
+ } catch (err) {
1339
+ await unlink2(dst).catch(() => void 0);
1340
+ throw new CliError(
1341
+ "INTERNAL",
1342
+ `Could not clear the active wallet slot ${src} while parking the outgoing wallet.`,
1343
+ {
1344
+ fix: "The previous wallet is still active and nothing was lost. Fix the underlying filesystem error (on Windows, close any process holding the wallet file open) and retry.",
1345
+ cause: err
1346
+ }
1347
+ );
1348
+ }
1349
+ await syncWalletDir(dir);
1350
+ return dst;
1351
+ }
1352
+ async function restoreParkedWallet(dir, archivedPath) {
1353
+ await link(archivedPath, walletPath(dir));
1354
+ await unlink2(archivedPath).catch(() => void 0);
1355
+ await syncWalletDir(dir);
1356
+ }
1357
+ async function syncWalletDir(dir) {
1358
+ if (isWindows) return;
1359
+ await fsyncDir(dir);
1087
1360
  }
1088
1361
  async function loadCredential(deps) {
1089
1362
  const envKey = deps.env.TENJIN_WALLET_KEY;
@@ -1106,18 +1379,32 @@ async function accountForSigning(cred, deps) {
1106
1379
  if (cred.source === "env") return accountFromKey(cred.key, "env");
1107
1380
  const cached = signerCache.get(cred.keystore.id);
1108
1381
  if (cached !== void 0) return cached;
1109
- const { passphrase } = await resolvePassphrase({
1110
- env: deps.env,
1111
- dir: deps.dir,
1112
- ...deps.passphrase
1113
- });
1382
+ const resolved = await resolvePassphrase(
1383
+ {
1384
+ env: deps.env,
1385
+ dir: deps.dir,
1386
+ ...deps.passphrase
1387
+ },
1388
+ cred.address
1389
+ );
1114
1390
  let key;
1115
1391
  try {
1116
- const derived = await toKeyAsync(cred.keystore, { password: passphrase });
1392
+ const derived = await toKeyAsync(cred.keystore, { password: resolved.passphrase });
1117
1393
  key = decrypt(cred.keystore, derived);
1118
1394
  } catch (err) {
1395
+ if (resolved.migrateLegacy !== void 0) {
1396
+ throw new CliError(
1397
+ "WALLET_INVALID_KEY",
1398
+ 'The legacy shared passphrase entry (service tenjin-cli, account "wallet") does not decrypt this wallet.',
1399
+ {
1400
+ fix: "That entry likely belongs to a different wallet created later and was left untouched. If you know this wallet's passphrase, set TENJIN_WALLET_PASSPHRASE to it (a store-served passphrase is never re-asked at a prompt).",
1401
+ cause: err
1402
+ }
1403
+ );
1404
+ }
1405
+ const escape = resolved.source === "env" ? "TENJIN_WALLET_PASSPHRASE is set but does not decrypt it; set it to the correct passphrase" : resolved.source === "prompt" ? "Retry and enter the correct passphrase at the prompt, or set TENJIN_WALLET_PASSPHRASE to it" : `The OS credential store entry (service tenjin-cli, account ${cred.address.toLowerCase()}) does not decrypt it; set TENJIN_WALLET_PASSPHRASE to the correct passphrase`;
1119
1406
  throw new CliError("WALLET_INVALID_KEY", "Could not decrypt the wallet keystore.", {
1120
- fix: "Check the passphrase: TENJIN_WALLET_PASSPHRASE, the macOS keychain (service tenjin-cli), or the one you enter when prompted.",
1407
+ fix: `${escape}.`,
1121
1408
  cause: err
1122
1409
  });
1123
1410
  }
@@ -1131,6 +1418,7 @@ async function accountForSigning(cred, deps) {
1131
1418
  }
1132
1419
  );
1133
1420
  }
1421
+ if (resolved.migrateLegacy !== void 0) await resolved.migrateLegacy();
1134
1422
  signerCache.set(cred.keystore.id, account);
1135
1423
  return account;
1136
1424
  }
@@ -1148,17 +1436,18 @@ async function encryptToKeystore(key, passphrase) {
1148
1436
  const [derivedKey, opts] = await scryptAsync2({ password: passphrase });
1149
1437
  return encrypt2(key, derivedKey, opts);
1150
1438
  }
1151
- function resolveCredentialOrThrow(cred) {
1152
- if (cred === null) {
1153
- throw new CliError("WALLET_MISSING", "No wallet found.", {
1154
- fix: "Run `tenjin wallet create` to create one."
1155
- });
1156
- }
1157
- return cred;
1439
+ async function credentialOrThrow(deps) {
1440
+ const cred = await loadCredential(deps);
1441
+ if (cred !== null) return cred;
1442
+ const archived = await listArchivedWallets(deps.dir);
1443
+ const hint = archived.length > 0 ? ` Archived wallets exist (${archived.join(", ")}); restore one with \`mv ${archivedWalletPath("<address>", deps.dir)} ${walletPath(deps.dir)}\`.` : "";
1444
+ throw new CliError("WALLET_MISSING", "No wallet found.", {
1445
+ fix: `Run \`tenjin wallet create\` to create one.${hint}`
1446
+ });
1158
1447
  }
1159
1448
  function walletRecord(address, keystore) {
1160
1449
  return {
1161
- schemaVersion: 2,
1450
+ schemaVersion: WALLET_SCHEMA_VERSION,
1162
1451
  provider: "local",
1163
1452
  address,
1164
1453
  keystore,
@@ -1166,10 +1455,160 @@ function walletRecord(address, keystore) {
1166
1455
  };
1167
1456
  }
1168
1457
 
1458
+ // src/lib/wallet/spend.ts
1459
+ import { mkdir, readFile as readFile2 } from "fs/promises";
1460
+ import { randomUUID } from "crypto";
1461
+ var DEFAULT_WINDOW_MS = 864e5;
1462
+ var RESERVATION_TTL_MS = 6e5;
1463
+ var ReservationSchema = external_exports.object({
1464
+ id: external_exports.string(),
1465
+ amountAtomic: external_exports.string().regex(/^\d+$/),
1466
+ atMs: external_exports.number()
1467
+ });
1468
+ var LedgerSchema = external_exports.object({
1469
+ schemaVersion: external_exports.literal(2),
1470
+ windowStartMs: external_exports.number(),
1471
+ committedAtomic: external_exports.string().regex(/^\d+$/),
1472
+ reservations: external_exports.array(ReservationSchema)
1473
+ });
1474
+ function emptyLedger(nowMs) {
1475
+ return { schemaVersion: 2, windowStartMs: nowMs, committedAtomic: "0", reservations: [] };
1476
+ }
1477
+ function createLocalSpendAuthorizer(deps) {
1478
+ const windowMs = deps.windowMs ?? DEFAULT_WINDOW_MS;
1479
+ const now = deps.now ?? Date.now;
1480
+ const path = spendLedgerPath(deps.dir);
1481
+ const lockPath = `${path}.lock`;
1482
+ let warnedCorrupt = false;
1483
+ const freshen = (ledger, nowMs) => {
1484
+ if (ledger === null || nowMs - ledger.windowStartMs >= windowMs) return emptyLedger(nowMs);
1485
+ return {
1486
+ ...ledger,
1487
+ reservations: ledger.reservations.filter((r) => nowMs - r.atMs < RESERVATION_TTL_MS)
1488
+ };
1489
+ };
1490
+ const spentOf = (ledger) => ledger.reservations.reduce(
1491
+ (sum, r) => sum + BigInt(r.amountAtomic),
1492
+ BigInt(ledger.committedAtomic)
1493
+ );
1494
+ const persist = async (ledger) => {
1495
+ await writeFileAtomic(path, `${JSON.stringify(ledger, null, 2)}
1496
+ `, {
1497
+ mode: 384,
1498
+ dirMode: 448
1499
+ });
1500
+ };
1501
+ async function withLedger(fn) {
1502
+ await mkdir(deps.dir, { recursive: true, mode: 448 });
1503
+ return withFileLock(lockPath, async () => {
1504
+ const nowMs = now();
1505
+ const read = await readLedger(path);
1506
+ if (read.corrupt !== void 0 && !warnedCorrupt) {
1507
+ warnedCorrupt = true;
1508
+ deps.onCorrupt?.(read.corrupt);
1509
+ }
1510
+ const ledger = freshen(read.ledger, nowMs);
1511
+ return fn(ledger, nowMs);
1512
+ });
1513
+ }
1514
+ return {
1515
+ policyEnforcement: "client-only",
1516
+ async authorize(req) {
1517
+ return withLedger(async (ledger) => {
1518
+ const sessionSpentAtomic = spentOf(ledger);
1519
+ const evaluation = evaluateSpendPolicy(deps.policy, {
1520
+ amountAtomic: req.amountAtomic,
1521
+ creator: req.creator,
1522
+ ...req.maxPriceAtomic !== void 0 ? { maxPriceAtomic: req.maxPriceAtomic } : {},
1523
+ sessionSpentAtomic
1524
+ });
1525
+ const base = {
1526
+ ...evaluation,
1527
+ amountAtomic: req.amountAtomic,
1528
+ sessionSpentAtomic,
1529
+ sessionBudgetAtomic: deps.policy.sessionBudgetAtomic,
1530
+ policyEnforcement: "client-only"
1531
+ };
1532
+ if (evaluation.decision === "deny" || deps.policy.sessionBudgetAtomic === 0n) {
1533
+ return base;
1534
+ }
1535
+ const reservation = {
1536
+ id: randomUUID(),
1537
+ amountAtomic: req.amountAtomic.toString(),
1538
+ atMs: now()
1539
+ };
1540
+ await persist({ ...ledger, reservations: [...ledger.reservations, reservation] });
1541
+ return { ...base, reservationId: reservation.id };
1542
+ });
1543
+ },
1544
+ async commit(reservationId, amountAtomic) {
1545
+ await withLedger(async (ledger) => {
1546
+ const reservation = reservationId !== void 0 ? ledger.reservations.find((r) => r.id === reservationId) : void 0;
1547
+ const settled = reservation !== void 0 ? BigInt(reservation.amountAtomic) : amountAtomic;
1548
+ await persist({
1549
+ ...ledger,
1550
+ committedAtomic: (BigInt(ledger.committedAtomic) + settled).toString(),
1551
+ reservations: reservationId !== void 0 ? ledger.reservations.filter((r) => r.id !== reservationId) : ledger.reservations
1552
+ });
1553
+ });
1554
+ },
1555
+ async release(reservationId) {
1556
+ if (reservationId === void 0) return;
1557
+ await withLedger(async (ledger) => {
1558
+ if (!ledger.reservations.some((r) => r.id === reservationId)) return;
1559
+ await persist({
1560
+ ...ledger,
1561
+ reservations: ledger.reservations.filter((r) => r.id !== reservationId)
1562
+ });
1563
+ });
1564
+ }
1565
+ };
1566
+ }
1567
+ async function readLedger(path) {
1568
+ let raw;
1569
+ try {
1570
+ raw = await readFile2(path, "utf8");
1571
+ } catch (err) {
1572
+ if (hasCode(err, "ENOENT")) return { ledger: null };
1573
+ return { ledger: null, corrupt: err instanceof Error ? err.message : String(err) };
1574
+ }
1575
+ let json;
1576
+ try {
1577
+ json = JSON.parse(raw);
1578
+ } catch {
1579
+ return { ledger: null, corrupt: "not valid JSON" };
1580
+ }
1581
+ const parsed = LedgerSchema.safeParse(json);
1582
+ if (parsed.success) return { ledger: parsed.data };
1583
+ const issue = parsed.error.issues[0];
1584
+ const field = issue?.path.join(".");
1585
+ const message = issue?.message ?? "schema mismatch";
1586
+ return {
1587
+ ledger: null,
1588
+ corrupt: field !== void 0 && field.length > 0 ? `${field}: ${message}` : message
1589
+ };
1590
+ }
1591
+
1169
1592
  // src/lib/wallet/index.ts
1170
1593
  function resolveWalletProvider(ctx, opts = {}) {
1171
1594
  if (opts.provider !== void 0) return opts.provider;
1172
- return createLocalProvider({ dir: ctx.dataDir, env: process.env });
1595
+ return createLocalProvider({
1596
+ dir: ctx.dataDir,
1597
+ env: process.env,
1598
+ passphrase: { ...opts.passphrase, isTTY: ctx.io.isTTY ? void 0 : false }
1599
+ });
1600
+ }
1601
+ function resolveSpendAuthorizer(ctx, policy, opts = {}) {
1602
+ if (opts.authorizer !== void 0) return opts.authorizer;
1603
+ return createLocalSpendAuthorizer({
1604
+ dir: ctx.dataDir,
1605
+ policy,
1606
+ onCorrupt: (reason) => emitNotice(
1607
+ ctx.io,
1608
+ `spend ledger at ${spendLedgerPath(ctx.dataDir)} was unreadable (${reason}); spending window restarted`,
1609
+ { json: ctx.flags.json }
1610
+ )
1611
+ });
1173
1612
  }
1174
1613
  async function describeWallet(provider) {
1175
1614
  try {
@@ -1186,8 +1625,16 @@ async function describeWallet(provider) {
1186
1625
 
1187
1626
  export {
1188
1627
  resolvePassphraseForCreate,
1628
+ verifyLocalWallet,
1629
+ prepareLocalWallet,
1630
+ commitLocalWallet,
1189
1631
  createLocalWallet,
1632
+ verifyAndPreserveOutgoingWallet,
1633
+ parkOutgoingWallet,
1634
+ restoreParkedWallet,
1635
+ createLocalSpendAuthorizer,
1190
1636
  resolveWalletProvider,
1637
+ resolveSpendAuthorizer,
1191
1638
  describeWallet
1192
1639
  };
1193
1640
  /*! Bundled license information:
@@ -1195,4 +1642,4 @@ export {
1195
1642
  @noble/ciphers/esm/utils.js:
1196
1643
  (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
1197
1644
  */
1198
- //# sourceMappingURL=chunk-EXBMF5X7.js.map
1645
+ //# sourceMappingURL=chunk-CNUXRXI2.js.map