tenjin-cli 0.1.0-alpha.0 → 0.1.0-alpha.10

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 (191) hide show
  1. package/NOTICE.md +33 -0
  2. package/README.md +575 -50
  3. package/dist/{_esm-ZH2J4QEH.js → _esm-C5CRWCYU.js} +2 -2
  4. package/dist/_esm-N4KAVXQR.js +881 -0
  5. package/dist/buy-FMDBZ4NY.js +44 -0
  6. package/dist/candidate-7LAELUQD.js +23 -0
  7. package/dist/ccip-RPPPKTJR.js +19 -0
  8. package/dist/{ccip-FXWZDDF5.js → ccip-ZGGWQN4X.js} +6 -5
  9. package/dist/chunk-2GSRYTZS.js +127 -0
  10. package/dist/chunk-2GSRYTZS.js.map +1 -0
  11. package/dist/chunk-2I4QTOLB.js +11 -0
  12. package/dist/chunk-2I4QTOLB.js.map +1 -0
  13. package/dist/chunk-36X2CA3N.js +311 -0
  14. package/dist/chunk-36X2CA3N.js.map +1 -0
  15. package/dist/{chunk-F5DZJLU3.js → chunk-47PP7TAG.js} +1441 -634
  16. package/dist/chunk-47PP7TAG.js.map +1 -0
  17. package/dist/chunk-5JMKIDMM.js +316 -0
  18. package/dist/chunk-5JMKIDMM.js.map +1 -0
  19. package/dist/chunk-5JXAZP7H.js +206 -0
  20. package/dist/chunk-5JXAZP7H.js.map +1 -0
  21. package/dist/chunk-5SE6BJRP.js +135 -0
  22. package/dist/chunk-5SE6BJRP.js.map +1 -0
  23. package/dist/chunk-6BZLSRNU.js +149 -0
  24. package/dist/chunk-6BZLSRNU.js.map +1 -0
  25. package/dist/{chunk-PAAL45FJ.js → chunk-7FK2UN2T.js} +3410 -412
  26. package/dist/chunk-7FK2UN2T.js.map +1 -0
  27. package/dist/chunk-7WDY4AXV.js +14620 -0
  28. package/dist/chunk-7WDY4AXV.js.map +1 -0
  29. package/dist/chunk-A6KCZPNQ.js +83 -0
  30. package/dist/chunk-A6KCZPNQ.js.map +1 -0
  31. package/dist/chunk-AWQ6A4CI.js +341 -0
  32. package/dist/chunk-AWQ6A4CI.js.map +1 -0
  33. package/dist/chunk-BJJ5BQO6.js +162 -0
  34. package/dist/chunk-BJJ5BQO6.js.map +1 -0
  35. package/dist/chunk-BUDHTDKL.js +612 -0
  36. package/dist/chunk-BUDHTDKL.js.map +1 -0
  37. package/dist/chunk-DKQMJTG7.js +188 -0
  38. package/dist/chunk-DKQMJTG7.js.map +1 -0
  39. package/dist/chunk-FKSAUOJU.js +137 -0
  40. package/dist/chunk-FKSAUOJU.js.map +1 -0
  41. package/dist/chunk-GECSWJ7O.js +1645 -0
  42. package/dist/chunk-GECSWJ7O.js.map +1 -0
  43. package/dist/chunk-GSDZRCGF.js +105 -0
  44. package/dist/chunk-GSDZRCGF.js.map +1 -0
  45. package/dist/chunk-JSSIMGQT.js +174 -0
  46. package/dist/chunk-JSSIMGQT.js.map +1 -0
  47. package/dist/chunk-KYH4KPE5.js +1357 -0
  48. package/dist/chunk-KYH4KPE5.js.map +1 -0
  49. package/dist/chunk-KYQVEKP5.js +209 -0
  50. package/dist/chunk-KYQVEKP5.js.map +1 -0
  51. package/dist/chunk-KZAAWQNP.js +6199 -0
  52. package/dist/chunk-KZAAWQNP.js.map +1 -0
  53. package/dist/{chunk-SXQQ2ZSR.js → chunk-M2O56UK7.js} +243 -75
  54. package/dist/chunk-M2O56UK7.js.map +1 -0
  55. package/dist/chunk-MD7WGYYI.js +125 -0
  56. package/dist/chunk-MD7WGYYI.js.map +1 -0
  57. package/dist/chunk-MJZZTKCC.js +323 -0
  58. package/dist/chunk-MJZZTKCC.js.map +1 -0
  59. package/dist/chunk-O6CAUZGY.js +317 -0
  60. package/dist/chunk-O6CAUZGY.js.map +1 -0
  61. package/dist/chunk-P74I3WH4.js +204 -0
  62. package/dist/chunk-P74I3WH4.js.map +1 -0
  63. package/dist/chunk-POF7HPRV.js +145 -0
  64. package/dist/chunk-POF7HPRV.js.map +1 -0
  65. package/dist/chunk-POJRB2AE.js +83 -0
  66. package/dist/chunk-POJRB2AE.js.map +1 -0
  67. package/dist/{chunk-FIYZLITH.js → chunk-PZRAAAY2.js} +107 -18
  68. package/dist/chunk-PZRAAAY2.js.map +1 -0
  69. package/dist/chunk-PZSUWDF2.js +35 -0
  70. package/dist/chunk-PZSUWDF2.js.map +1 -0
  71. package/dist/chunk-QW2Q2KAH.js +27 -0
  72. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  73. package/dist/chunk-R2VLGNFD.js +181 -0
  74. package/dist/chunk-R2VLGNFD.js.map +1 -0
  75. package/dist/{chunk-CPUZRZ2A.js → chunk-RBJPAZFI.js} +25 -170
  76. package/dist/chunk-RBJPAZFI.js.map +1 -0
  77. package/dist/chunk-S5RYMCV6.js +70 -0
  78. package/dist/chunk-S5RYMCV6.js.map +1 -0
  79. package/dist/chunk-SGK2B724.js +67 -0
  80. package/dist/chunk-SGK2B724.js.map +1 -0
  81. package/dist/chunk-STND72DS.js +242 -0
  82. package/dist/chunk-STND72DS.js.map +1 -0
  83. package/dist/chunk-TEL27PR5.js +124 -0
  84. package/dist/chunk-TEL27PR5.js.map +1 -0
  85. package/dist/chunk-TWRYSGAW.js +134 -0
  86. package/dist/chunk-TWRYSGAW.js.map +1 -0
  87. package/dist/{chunk-WOHCAMDQ.js → chunk-U5S527PP.js} +1887 -1029
  88. package/dist/chunk-U5S527PP.js.map +1 -0
  89. package/dist/chunk-UHTVXQ2O.js +140 -0
  90. package/dist/chunk-UHTVXQ2O.js.map +1 -0
  91. package/dist/chunk-UOJRKQTZ.js +213 -0
  92. package/dist/chunk-UOJRKQTZ.js.map +1 -0
  93. package/dist/chunk-V4WWTZHZ.js +233 -0
  94. package/dist/chunk-V4WWTZHZ.js.map +1 -0
  95. package/dist/chunk-VRRLTZ2Q.js +651 -0
  96. package/dist/chunk-VRRLTZ2Q.js.map +1 -0
  97. package/dist/{chunk-TX5T3LKJ.js → chunk-W6R3HAAG.js} +21 -17
  98. package/dist/{chunk-TX5T3LKJ.js.map → chunk-W6R3HAAG.js.map} +1 -1
  99. package/dist/chunk-X3OOVSPX.js +154 -0
  100. package/dist/chunk-X3OOVSPX.js.map +1 -0
  101. package/dist/chunk-XJN5WUKL.js +204 -0
  102. package/dist/chunk-XJN5WUKL.js.map +1 -0
  103. package/dist/chunk-Y7ERTA7D.js +146 -0
  104. package/dist/chunk-Y7ERTA7D.js.map +1 -0
  105. package/dist/chunk-YLYINX2H.js +7806 -0
  106. package/dist/chunk-YLYINX2H.js.map +1 -0
  107. package/dist/chunk-ZQIQ55KK.js +51 -0
  108. package/dist/chunk-ZQIQ55KK.js.map +1 -0
  109. package/dist/chunk-ZUAQRIVP.js +1369 -0
  110. package/dist/chunk-ZUAQRIVP.js.map +1 -0
  111. package/dist/{chunk-3IMLRUZE.js → chunk-ZXTAQYNA.js} +6 -2
  112. package/dist/chunk-ZXTAQYNA.js.map +1 -0
  113. package/dist/{cli-LMHGCZ5S.js → cli-HK2XAWNW.js} +438 -177
  114. package/dist/cli-HK2XAWNW.js.map +1 -0
  115. package/dist/config-LYCHHNAJ.js +26 -0
  116. package/dist/config-LYCHHNAJ.js.map +1 -0
  117. package/dist/dist-U4M6QCKE.js +2842 -0
  118. package/dist/dist-U4M6QCKE.js.map +1 -0
  119. package/dist/doctor-2KPUQURC.js +27 -0
  120. package/dist/doctor-2KPUQURC.js.map +1 -0
  121. package/dist/edit-TST3OCKQ.js +38 -0
  122. package/dist/edit-TST3OCKQ.js.map +1 -0
  123. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js +18 -0
  124. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js.map +1 -0
  125. package/dist/index.js +1 -1
  126. package/dist/inspect-TPTHVPBB.js +35 -0
  127. package/dist/inspect-TPTHVPBB.js.map +1 -0
  128. package/dist/install-PT3XEDJ6.js +1869 -0
  129. package/dist/install-PT3XEDJ6.js.map +1 -0
  130. package/dist/{mine.wasm-GQECMSGN.js → mine.wasm-6PIT3DK6.js} +2 -2
  131. package/dist/outcome-NPNSF2Q7.js +22 -0
  132. package/dist/outcome-NPNSF2Q7.js.map +1 -0
  133. package/dist/publish-XP5SEWST.js +41 -0
  134. package/dist/publish-XP5SEWST.js.map +1 -0
  135. package/dist/read-D4VXRWOG.js +158 -0
  136. package/dist/read-D4VXRWOG.js.map +1 -0
  137. package/dist/run-3IPGEXW7.js +16902 -0
  138. package/dist/run-3IPGEXW7.js.map +1 -0
  139. package/dist/search-YOBD6VDI.js +24 -0
  140. package/dist/search-YOBD6VDI.js.map +1 -0
  141. package/dist/{secp256k1-35YNNB6F.js → secp256k1-XRPVBC6V.js} +5 -4
  142. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  143. package/dist/send-BWNP6WN4.js +223 -0
  144. package/dist/send-BWNP6WN4.js.map +1 -0
  145. package/dist/session-GZEZBOMI.js +88 -0
  146. package/dist/session-GZEZBOMI.js.map +1 -0
  147. package/dist/skill-heal-OK6YALW6.js +85 -0
  148. package/dist/skill-heal-OK6YALW6.js.map +1 -0
  149. package/dist/usdc-4VCDHFWX.js +38 -0
  150. package/dist/usdc-4VCDHFWX.js.map +1 -0
  151. package/dist/viemAdapter-By13KInL-TUQJBMHM.js +14 -0
  152. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  153. package/dist/wallet-5RHDFPN2.js +32 -0
  154. package/dist/wallet-5RHDFPN2.js.map +1 -0
  155. package/dist/wallet-YEGQBWWL.js +42 -0
  156. package/dist/wallet-YEGQBWWL.js.map +1 -0
  157. package/docs/agent-permissions.md +281 -0
  158. package/package.json +26 -17
  159. package/skills/tenjin/SKILL.md +364 -0
  160. package/skills/tenjin-publish/SKILL.md +219 -0
  161. package/skills/tenjin-search/SKILL.md +335 -0
  162. package/dist/chunk-376LHMK2.js +0 -100
  163. package/dist/chunk-376LHMK2.js.map +0 -1
  164. package/dist/chunk-CPUZRZ2A.js.map +0 -1
  165. package/dist/chunk-F5DZJLU3.js.map +0 -1
  166. package/dist/chunk-FIYZLITH.js.map +0 -1
  167. package/dist/chunk-LTTRND4A.js +0 -135
  168. package/dist/chunk-LTTRND4A.js.map +0 -1
  169. package/dist/chunk-PAAL45FJ.js.map +0 -1
  170. package/dist/chunk-QHIEYBLV.js +0 -320
  171. package/dist/chunk-QHIEYBLV.js.map +0 -1
  172. package/dist/chunk-SXQQ2ZSR.js.map +0 -1
  173. package/dist/chunk-WOHCAMDQ.js.map +0 -1
  174. package/dist/chunk-ZPZFPVDN.js +0 -67
  175. package/dist/chunk-ZPZFPVDN.js.map +0 -1
  176. package/dist/cli-LMHGCZ5S.js.map +0 -1
  177. package/dist/config-XVXZ3V2Q.js +0 -206
  178. package/dist/config-XVXZ3V2Q.js.map +0 -1
  179. package/dist/doctor-MVLZRVPU.js +0 -338
  180. package/dist/doctor-MVLZRVPU.js.map +0 -1
  181. package/dist/usdc-OQUOFF6R.js +0 -18
  182. package/dist/wallet-NRKWLKHX.js +0 -153
  183. package/dist/wallet-NRKWLKHX.js.map +0 -1
  184. package/dist/wallet-QUWK2PA4.js +0 -22
  185. /package/dist/{_esm-ZH2J4QEH.js.map → _esm-C5CRWCYU.js.map} +0 -0
  186. /package/dist/{ccip-FXWZDDF5.js.map → _esm-N4KAVXQR.js.map} +0 -0
  187. /package/dist/{chunk-3IMLRUZE.js.map → buy-FMDBZ4NY.js.map} +0 -0
  188. /package/dist/{secp256k1-35YNNB6F.js.map → candidate-7LAELUQD.js.map} +0 -0
  189. /package/dist/{usdc-OQUOFF6R.js.map → ccip-RPPPKTJR.js.map} +0 -0
  190. /package/dist/{wallet-QUWK2PA4.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  191. /package/dist/{mine.wasm-GQECMSGN.js.map → mine.wasm-6PIT3DK6.js.map} +0 -0
@@ -0,0 +1,70 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ a2 as a,
4
+ i2 as i,
5
+ p,
6
+ r,
7
+ t
8
+ } from "./chunk-YLYINX2H.js";
9
+
10
+ // node_modules/.pnpm/@signinwithethereum+siwe@4.2.0_viem@2.55.2_typescript@6.0.3_zod@4.4.3_/node_modules/@signinwithethereum/siwe/dist/viemAdapter-By13KInL.js
11
+ var a2 = /* @__PURE__ */ t({ createViemConfig: () => s });
12
+ var o = [{
13
+ inputs: [{
14
+ name: "_message",
15
+ type: "bytes32"
16
+ }, {
17
+ name: "_signature",
18
+ type: "bytes"
19
+ }],
20
+ name: "isValidSignature",
21
+ outputs: [{
22
+ name: "",
23
+ type: "bytes4"
24
+ }],
25
+ stateMutability: "view",
26
+ type: "function"
27
+ }];
28
+ async function s(e) {
29
+ let a3;
30
+ try {
31
+ a3 = await import("./_esm-N4KAVXQR.js");
32
+ } catch {
33
+ throw new r(i.MISSING_PROVIDER_LIBRARY, "viem installed (npm install viem)", "viem not found");
34
+ }
35
+ let s2 = {
36
+ verifyMessage: async (e2, t2) => a3.recoverMessageAddress({
37
+ message: e2,
38
+ signature: t2
39
+ }),
40
+ hashMessage: (e2) => a3.hashMessage(e2),
41
+ getAddress: (e2) => a3.getAddress(e2)
42
+ };
43
+ if (e?.publicClient) {
44
+ let t2 = e.publicClient;
45
+ s2.checkContractWalletSignature = async (e2, i2, s3, c) => {
46
+ let l = t2.chain?.id;
47
+ if (l == null && t2.getChainId && (l = await t2.getChainId()), l == null) throw new p("EIP-1271/EIP-6492 verification requires a viem publicClient with chain.id or getChainId().");
48
+ if (l !== c) throw new p(`publicClient chainId ${l} does not match message chainId ${c}.`);
49
+ if (t2.verifyMessage) return t2.verifyMessage({
50
+ address: e2,
51
+ message: i2,
52
+ signature: s3
53
+ });
54
+ let u = a3.hashMessage(i2);
55
+ return await t2.readContract({
56
+ address: e2,
57
+ abi: o,
58
+ functionName: "isValidSignature",
59
+ args: [u, s3]
60
+ }) === a;
61
+ };
62
+ }
63
+ return s2;
64
+ }
65
+
66
+ export {
67
+ a2 as a,
68
+ s
69
+ };
70
+ //# sourceMappingURL=chunk-S5RYMCV6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../node_modules/.pnpm/@signinwithethereum+siwe@4.2.0_viem@2.55.2_typescript@6.0.3_zod@4.4.3_/node_modules/@signinwithethereum/siwe/dist/viemAdapter-By13KInL.js"],"sourcesContent":["import { t as e } from \"./rolldown-runtime-CAFD8bLK.js\";\nimport { d as t, o as n, t as r, u as i } from \"./utils-9-kzgPFC.js\";\n//#region lib/viemAdapter.ts\nvar a = /* @__PURE__ */ e({ createViemConfig: () => s }), o = [{\n\tinputs: [{\n\t\tname: \"_message\",\n\t\ttype: \"bytes32\"\n\t}, {\n\t\tname: \"_signature\",\n\t\ttype: \"bytes\"\n\t}],\n\tname: \"isValidSignature\",\n\toutputs: [{\n\t\tname: \"\",\n\t\ttype: \"bytes4\"\n\t}],\n\tstateMutability: \"view\",\n\ttype: \"function\"\n}];\nasync function s(e) {\n\tlet a;\n\ttry {\n\t\ta = await import(\"viem\");\n\t} catch {\n\t\tthrow new i(t.MISSING_PROVIDER_LIBRARY, \"viem installed (npm install viem)\", \"viem not found\");\n\t}\n\tlet s = {\n\t\tverifyMessage: async (e, t) => a.recoverMessageAddress({\n\t\t\tmessage: e,\n\t\t\tsignature: t\n\t\t}),\n\t\thashMessage: (e) => a.hashMessage(e),\n\t\tgetAddress: (e) => a.getAddress(e)\n\t};\n\tif (e?.publicClient) {\n\t\tlet t = e.publicClient;\n\t\ts.checkContractWalletSignature = async (e, i, s, c) => {\n\t\t\tlet l = t.chain?.id;\n\t\t\tif (l == null && t.getChainId && (l = await t.getChainId()), l == null) throw new r(\"EIP-1271/EIP-6492 verification requires a viem publicClient with chain.id or getChainId().\");\n\t\t\tif (l !== c) throw new r(`publicClient chainId ${l} does not match message chainId ${c}.`);\n\t\t\tif (t.verifyMessage) return t.verifyMessage({\n\t\t\t\taddress: e,\n\t\t\t\tmessage: i,\n\t\t\t\tsignature: s\n\t\t\t});\n\t\t\tlet u = a.hashMessage(i);\n\t\t\treturn await t.readContract({\n\t\t\t\taddress: e,\n\t\t\t\tabi: o,\n\t\t\t\tfunctionName: \"isValidSignature\",\n\t\t\t\targs: [u, s]\n\t\t\t}) === n;\n\t\t};\n\t}\n\treturn s;\n}\n//#endregion\nexport { a as n, s as t };\n"],"mappings":";;;;;;;;;;AAGA,IAAIA,KAAoB,kBAAE,EAAE,kBAAkB,MAAM,EAAE,CAAC;AAAvD,IAA0D,IAAI,CAAC;AAAA,EAC9D,QAAQ,CAAC;AAAA,IACR,MAAM;AAAA,IACN,MAAM;AAAA,EACP,GAAG;AAAA,IACF,MAAM;AAAA,IACN,MAAM;AAAA,EACP,CAAC;AAAA,EACD,MAAM;AAAA,EACN,SAAS,CAAC;AAAA,IACT,MAAM;AAAA,IACN,MAAM;AAAA,EACP,CAAC;AAAA,EACD,iBAAiB;AAAA,EACjB,MAAM;AACP,CAAC;AACD,eAAe,EAAE,GAAG;AACnB,MAAIA;AACJ,MAAI;AACH,IAAAA,KAAI,MAAM,OAAO,oBAAM;AAAA,EACxB,QAAQ;AACP,UAAM,IAAI,EAAE,EAAE,0BAA0B,qCAAqC,gBAAgB;AAAA,EAC9F;AACA,MAAIC,KAAI;AAAA,IACP,eAAe,OAAOC,IAAGC,OAAMH,GAAE,sBAAsB;AAAA,MACtD,SAASE;AAAA,MACT,WAAWC;AAAA,IACZ,CAAC;AAAA,IACD,aAAa,CAACD,OAAMF,GAAE,YAAYE,EAAC;AAAA,IACnC,YAAY,CAACA,OAAMF,GAAE,WAAWE,EAAC;AAAA,EAClC;AACA,MAAI,GAAG,cAAc;AACpB,QAAIC,KAAI,EAAE;AACV,IAAAF,GAAE,+BAA+B,OAAOC,IAAGE,IAAGH,IAAG,MAAM;AACtD,UAAI,IAAIE,GAAE,OAAO;AACjB,UAAI,KAAK,QAAQA,GAAE,eAAe,IAAI,MAAMA,GAAE,WAAW,IAAI,KAAK,KAAM,OAAM,IAAI,EAAE,4FAA4F;AAChL,UAAI,MAAM,EAAG,OAAM,IAAI,EAAE,wBAAwB,CAAC,mCAAmC,CAAC,GAAG;AACzF,UAAIA,GAAE,cAAe,QAAOA,GAAE,cAAc;AAAA,QAC3C,SAASD;AAAA,QACT,SAASE;AAAA,QACT,WAAWH;AAAA,MACZ,CAAC;AACD,UAAI,IAAID,GAAE,YAAYI,EAAC;AACvB,aAAO,MAAMD,GAAE,aAAa;AAAA,QAC3B,SAASD;AAAA,QACT,KAAK;AAAA,QACL,cAAc;AAAA,QACd,MAAM,CAAC,GAAGD,EAAC;AAAA,MACZ,CAAC,MAAM;AAAA,IACR;AAAA,EACD;AACA,SAAOA;AACR;","names":["a","s","e","t","i"]}
@@ -0,0 +1,67 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/markdown.ts
4
+ function headingOutline(bodyMd) {
5
+ const headings = [];
6
+ let inFence = false;
7
+ for (const line of bodyMd.split(/\r?\n/)) {
8
+ if (/^\s*(```|~~~)/.test(line)) {
9
+ inFence = !inFence;
10
+ continue;
11
+ }
12
+ if (inFence) continue;
13
+ const m = /^(#{1,6})\s+(.*\S)\s*$/.exec(line);
14
+ if (m && m[1] !== void 0 && m[2] !== void 0) {
15
+ headings.push({ level: m[1].length, text: m[2] });
16
+ }
17
+ }
18
+ return headings;
19
+ }
20
+ function estimateTokens(text) {
21
+ const words = text.split(/\s+/).filter((w) => w.length > 0).length;
22
+ return Math.ceil(words * 1.33);
23
+ }
24
+ function splitSections(bodyMd) {
25
+ const sections = [];
26
+ let heading = null;
27
+ let level = 0;
28
+ let lines = [];
29
+ let inFence = false;
30
+ const push = () => {
31
+ const body = lines.join("\n").trim();
32
+ if (heading === null && body.length === 0) return;
33
+ sections.push({ heading, level, body, estimatedTokens: estimateTokens(body) });
34
+ };
35
+ for (const line of bodyMd.split(/\r?\n/)) {
36
+ if (/^\s*(```|~~~)/.test(line)) inFence = !inFence;
37
+ const m = inFence ? null : /^(#{1,6})\s+(.*\S)\s*$/.exec(line);
38
+ if (m && m[1] !== void 0 && m[2] !== void 0) {
39
+ push();
40
+ heading = m[2].trim();
41
+ level = m[1].length;
42
+ lines = [];
43
+ } else {
44
+ lines.push(line);
45
+ }
46
+ }
47
+ push();
48
+ return sections;
49
+ }
50
+ function selectSections(sections, budgetTokens) {
51
+ const selected = [];
52
+ let spent = 0;
53
+ for (const section of sections) {
54
+ if (selected.length > 0 && spent + section.estimatedTokens > budgetTokens) break;
55
+ selected.push(section);
56
+ spent += section.estimatedTokens;
57
+ if (spent >= budgetTokens) break;
58
+ }
59
+ return selected;
60
+ }
61
+
62
+ export {
63
+ headingOutline,
64
+ splitSections,
65
+ selectSections
66
+ };
67
+ //# sourceMappingURL=chunk-SGK2B724.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/markdown.ts"],"sourcesContent":["/**\n * Deterministic markdown structure helpers for delivery output: the heading\n * outline that replaces the body on stdout, and the `--sections` budgeted\n * selection. No model calls, no scoring; identical input always yields\n * identical output. Split from library.ts so filesystem delivery and text\n * shaping stay separate concerns.\n */\n\nexport interface Heading {\n level: number;\n text: string;\n}\n\n/**\n * Deterministic ATX-heading outline for the stdout summary, never the body, so\n * agent transcripts stay small (spec 10). Skips fenced code blocks so a `#`\n * comment inside a code sample is not mistaken for a heading.\n */\nexport function headingOutline(bodyMd: string): Heading[] {\n const headings: Heading[] = [];\n let inFence = false;\n for (const line of bodyMd.split(/\\r?\\n/)) {\n if (/^\\s*(```|~~~)/.test(line)) {\n inFence = !inFence;\n continue;\n }\n if (inFence) continue;\n const m = /^(#{1,6})\\s+(.*\\S)\\s*$/.exec(line);\n if (m && m[1] !== undefined && m[2] !== undefined) {\n headings.push({ level: m[1].length, text: m[2] });\n }\n }\n return headings;\n}\n\nexport interface MarkdownSection {\n /** Heading text without the leading #s; null for preamble before any heading. */\n heading: string | null;\n level: number;\n body: string;\n estimatedTokens: number;\n}\n\n/** The server's own heuristic: ceil(words x 1.33). A display hint, never a boundary. */\nexport function estimateTokens(text: string): number {\n const words = text.split(/\\s+/).filter((w) => w.length > 0).length;\n return Math.ceil(words * 1.33);\n}\n\n/**\n * Deterministic heading-split of the body for `--sections` delivery: no model\n * calls, no scoring; the same input always splits identically. Fenced code\n * blocks are ignored for heading detection, like headingOutline.\n */\nexport function splitSections(bodyMd: string): MarkdownSection[] {\n const sections: MarkdownSection[] = [];\n let heading: string | null = null;\n let level = 0;\n let lines: string[] = [];\n let inFence = false;\n\n const push = (): void => {\n const body = lines.join('\\n').trim();\n if (heading === null && body.length === 0) return;\n sections.push({ heading, level, body, estimatedTokens: estimateTokens(body) });\n };\n\n for (const line of bodyMd.split(/\\r?\\n/)) {\n if (/^\\s*(```|~~~)/.test(line)) inFence = !inFence;\n const m = inFence ? null : /^(#{1,6})\\s+(.*\\S)\\s*$/.exec(line);\n if (m && m[1] !== undefined && m[2] !== undefined) {\n push();\n heading = m[2].trim();\n level = m[1].length;\n lines = [];\n } else {\n lines.push(line);\n }\n }\n push();\n return sections;\n}\n\n/**\n * Sections in document order until the budget is spent. The first section always\n * ships even when it alone exceeds the budget, so a tiny budget still returns\n * something rather than an empty selection.\n */\nexport function selectSections(\n sections: MarkdownSection[],\n budgetTokens: number,\n): MarkdownSection[] {\n const selected: MarkdownSection[] = [];\n let spent = 0;\n for (const section of sections) {\n if (selected.length > 0 && spent + section.estimatedTokens > budgetTokens) break;\n selected.push(section);\n spent += section.estimatedTokens;\n if (spent >= budgetTokens) break;\n }\n return selected;\n}\n"],"mappings":";;;AAkBO,SAAS,eAAe,QAA2B;AACxD,QAAM,WAAsB,CAAC;AAC7B,MAAI,UAAU;AACd,aAAW,QAAQ,OAAO,MAAM,OAAO,GAAG;AACxC,QAAI,gBAAgB,KAAK,IAAI,GAAG;AAC9B,gBAAU,CAAC;AACX;AAAA,IACF;AACA,QAAI,QAAS;AACb,UAAM,IAAI,yBAAyB,KAAK,IAAI;AAC5C,QAAI,KAAK,EAAE,CAAC,MAAM,UAAa,EAAE,CAAC,MAAM,QAAW;AACjD,eAA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c;AAAA,EAC7B;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,242 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ getUsdcBalance
4
+ } from "./chunk-MJZZTKCC.js";
5
+ import {
6
+ commitLocalWallet,
7
+ createLocalWallet,
8
+ describeWallet,
9
+ parkOutgoingWallet,
10
+ prepareLocalWallet,
11
+ resolvePassphraseForCreate,
12
+ resolveWalletProvider,
13
+ restoreParkedWallet,
14
+ verifyAndPreserveOutgoingWallet
15
+ } from "./chunk-GECSWJ7O.js";
16
+ import {
17
+ walletExistsError,
18
+ walletFileExists
19
+ } from "./chunk-Y7ERTA7D.js";
20
+ import {
21
+ LockTimeoutError,
22
+ withFileLock
23
+ } from "./chunk-FKSAUOJU.js";
24
+ import {
25
+ loadRawConfig,
26
+ resolveSettings,
27
+ toMoney
28
+ } from "./chunk-36X2CA3N.js";
29
+ import {
30
+ walletPath
31
+ } from "./chunk-ZQIQ55KK.js";
32
+ import {
33
+ CliError
34
+ } from "./chunk-PZRAAAY2.js";
35
+
36
+ // src/commands/wallet.ts
37
+ import { mkdir } from "fs/promises";
38
+ import { join } from "path";
39
+ var FUNDING_LINE = "Send USDC on Base. $5 covers ~50 typical resources.";
40
+ var KEY_STORAGE = "encrypted (keystore v3, scrypt)";
41
+ var isWindows = process.platform === "win32";
42
+ async function runWalletCreate(ctx, opts = {}) {
43
+ const {
44
+ address,
45
+ walletPath: path,
46
+ source,
47
+ replaced
48
+ } = await createWalletLocked(ctx.dataDir, opts);
49
+ const warnings = custodyWarnings();
50
+ return {
51
+ data: {
52
+ address,
53
+ walletPath: path,
54
+ provider: "local",
55
+ policyEnforcement: "client-only",
56
+ keyStorage: KEY_STORAGE,
57
+ passphraseSource: source,
58
+ ...replaced !== void 0 ? {
59
+ replaced: {
60
+ address: replaced.address,
61
+ archivedWalletPath: replaced.archivedPath,
62
+ passphrasePreserved: replaced.passphraseLocation,
63
+ ...replaced.unarchivedReason !== void 0 ? { unarchivedReason: replaced.unarchivedReason } : {}
64
+ }
65
+ } : {},
66
+ warnings
67
+ },
68
+ humanLines: [
69
+ `Wallet created: ${address}`,
70
+ `Key stored ${KEY_STORAGE}.`,
71
+ passphraseNote(source, address),
72
+ ...replaced !== void 0 ? replacedNote(replaced, path) : [],
73
+ FUNDING_LINE,
74
+ ...warnings
75
+ ]
76
+ };
77
+ }
78
+ function replacedNote(replaced, activeWalletPath) {
79
+ const passphraseLine = replaced.passphraseLocation === "store" ? `its passphrase is preserved in the OS credential store (service tenjin-cli, account ${replaced.account}).` : replaced.passphraseLocation === "env" ? "its passphrase is TENJIN_WALLET_PASSPHRASE \u2014 keep that value." : replaced.unarchivedReason === "rejected-characters" ? "its passphrase was NOT archived: the macOS keychain writer only stores machine-generated (base64url) passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it." : replaced.unarchivedReason === "no-store" ? "its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it." : "its passphrase was NOT archived: the OS credential store write failed. It exists only where you keep it.";
80
+ return [
81
+ `Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,
82
+ `Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,
83
+ `To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \`mv ${replaced.archivedPath} ${activeWalletPath}\`.`
84
+ ];
85
+ }
86
+ async function createWalletLocked(dir, opts) {
87
+ await mkdir(dir, { recursive: true, mode: 448 });
88
+ const lockPath = join(dir, "wallet.create.lock");
89
+ try {
90
+ return await withFileLock(lockPath, async () => {
91
+ const env = opts.env ?? process.env;
92
+ let source = "env";
93
+ const passphraseFor = async (forAddress) => {
94
+ const resolved = await resolvePassphraseForCreate(
95
+ { env, dir, ...opts.passphrase },
96
+ forAddress
97
+ );
98
+ source = resolved.source;
99
+ return resolved.passphrase;
100
+ };
101
+ if (!await walletFileExists(dir)) {
102
+ const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);
103
+ return { address, walletPath: path, source };
104
+ }
105
+ if (opts.replace !== true) throw walletExistsError(dir);
106
+ const preserved = await verifyAndPreserveOutgoingWallet({
107
+ dir,
108
+ env,
109
+ ...opts.passphrase !== void 0 ? { passphrase: opts.passphrase } : {}
110
+ });
111
+ const prepared = await prepareLocalWallet(passphraseFor);
112
+ const archivedPath = await parkOutgoingWallet(dir, preserved.account);
113
+ try {
114
+ const { address, walletPath: path } = await commitLocalWallet(dir, prepared);
115
+ return { address, walletPath: path, source, replaced: { ...preserved, archivedPath } };
116
+ } catch (err) {
117
+ try {
118
+ await restoreParkedWallet(dir, archivedPath);
119
+ } catch (restoreErr) {
120
+ throw new CliError(
121
+ "INTERNAL",
122
+ "Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.",
123
+ {
124
+ fix: `Your old wallet ${preserved.address} is intact at ${archivedPath} with its passphrase preserved. If a ${walletPath(dir)} now exists, another process wrote it \u2014 move it aside first. Then restore with \`mv ${archivedPath} ${walletPath(dir)}\`.`,
125
+ cause: restoreErr
126
+ }
127
+ );
128
+ }
129
+ throw new CliError(
130
+ "INTERNAL",
131
+ "Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.",
132
+ {
133
+ fix: "Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.",
134
+ cause: err
135
+ }
136
+ );
137
+ }
138
+ });
139
+ } catch (err) {
140
+ if (err instanceof LockTimeoutError) {
141
+ throw new CliError("INTERNAL", err.message, {
142
+ fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,
143
+ cause: err
144
+ });
145
+ }
146
+ throw err;
147
+ }
148
+ }
149
+ function passphraseNote(source, address) {
150
+ const account = address.toLowerCase();
151
+ switch (source) {
152
+ case "keychain":
153
+ return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;
154
+ case "dpapi":
155
+ return `Passphrase saved to a DPAPI-encrypted per-wallet file (passphrase.${account}.dpapi), readable only by you on this Windows machine; signing will be transparent here.`;
156
+ case "secret-service":
157
+ return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;
158
+ case "env":
159
+ return "Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.";
160
+ case "prompt":
161
+ return "Remember your passphrase: it is required to sign and cannot be recovered.";
162
+ }
163
+ }
164
+ async function runWalletShow(ctx, opts = {}) {
165
+ const provider = resolveWalletProvider(ctx, opts);
166
+ const desc = await describeWallet(provider);
167
+ const {
168
+ walletPath: path,
169
+ keyStorage,
170
+ passphraseSource,
171
+ archivedWallets,
172
+ warnings
173
+ } = await provider.diagnostics();
174
+ const humanLines = [`Address: ${desc.address}`, `Key source: ${desc.credentialSource}`];
175
+ if (keyStorage !== void 0) humanLines.push(`Key storage: ${keyStorage}`);
176
+ if (passphraseSource !== void 0) humanLines.push(`Passphrase: ${passphraseSource}`);
177
+ if (archivedWallets !== void 0 && archivedWallets.length > 0) {
178
+ humanLines.push(
179
+ `Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(", ")}`
180
+ );
181
+ }
182
+ humanLines.push(...warnings);
183
+ return {
184
+ data: {
185
+ address: desc.address,
186
+ provider: desc.provider,
187
+ credentialSource: desc.credentialSource,
188
+ policyEnforcement: desc.policyEnforcement,
189
+ ...path !== void 0 ? { walletPath: path } : {},
190
+ ...keyStorage !== void 0 ? { keyStorage } : {},
191
+ ...passphraseSource !== void 0 ? { passphraseSource } : {},
192
+ ...archivedWallets !== void 0 && archivedWallets.length > 0 ? { archivedWallets } : {},
193
+ warnings
194
+ },
195
+ humanLines
196
+ };
197
+ }
198
+ async function runWalletBalance(ctx, opts = {}) {
199
+ const provider = resolveWalletProvider(ctx, opts);
200
+ const desc = await describeWallet(provider);
201
+ const config = await loadRawConfig(ctx.dataDir);
202
+ const rpcUrl = resolveSettings({
203
+ config,
204
+ flags: { baseUrl: ctx.flags.baseUrl },
205
+ env: process.env
206
+ }).rpcUrl.value;
207
+ let atomic;
208
+ try {
209
+ atomic = await getUsdcBalance(desc.address, rpcUrl);
210
+ } catch (err) {
211
+ throw new CliError("RPC_ERROR", `Could not read the USDC balance from ${rpcUrl}.`, {
212
+ fix: "Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.",
213
+ cause: err
214
+ });
215
+ }
216
+ const balance = toMoney(atomic.toString());
217
+ return {
218
+ data: { address: desc.address, balance },
219
+ humanLines: [`Balance: ${balance.usd} USDC on Base`]
220
+ };
221
+ }
222
+ function custodyWarnings() {
223
+ const warnings = [];
224
+ if (hasEnvKey()) {
225
+ warnings.push("TENJIN_WALLET_KEY is set and shadows this file at runtime.");
226
+ }
227
+ if (isWindows) {
228
+ warnings.push("File permissions are not enforced on Windows; the key file is not restricted.");
229
+ }
230
+ return warnings;
231
+ }
232
+ function hasEnvKey() {
233
+ const envKey = process.env.TENJIN_WALLET_KEY;
234
+ return envKey !== void 0 && envKey.length > 0;
235
+ }
236
+
237
+ export {
238
+ runWalletCreate,
239
+ runWalletShow,
240
+ runWalletBalance
241
+ };
242
+ //# sourceMappingURL=chunk-STND72DS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/wallet.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { walletPath } from '../lib/paths';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { toMoney } from '../lib/money';\nimport { getUsdcBalance } from '../lib/usdc';\nimport {\n commitLocalWallet,\n createLocalWallet,\n describeWallet,\n parkOutgoingWallet,\n prepareLocalWallet,\n resolveWalletProvider,\n restoreParkedWallet,\n verifyAndPreserveOutgoingWallet,\n type ArchivedWalletInfo,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { walletExistsError, walletFileExists } from '../lib/wallet/store';\nimport { resolvePassphraseForCreate, type PassphraseSource } from '../lib/wallet/passphrase';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport type { CommandContext, CommandResult } from '../context';\n\nconst FUNDING_LINE = 'Send USDC on Base. $5 covers ~50 typical resources.';\nconst KEY_STORAGE = 'encrypted (keystore v3, scrypt)';\nconst isWindows = process.platform === 'win32';\n\nexport interface WalletCreateOptions {\n /**\n * Explicitly replace the existing active wallet (mirrors the `--yes`-style\n * explicit-flag precedent): the outgoing wallet is ARCHIVED — passphrase\n * verified against its keystore and preserved under its own address, keystore\n * parked beside the new one — never destroyed. Without it, create refuses\n * when a wallet exists. There is always exactly ONE active wallet.\n */\n replace?: boolean;\n /** Test seam for passphrase resolution (keychain exec, TTY prompt, platform). */\n passphrase?: PassphraseOverrides;\n /**\n * The environment TENJIN_WALLET_PASSPHRASE is read from; defaults to\n * process.env. A seam rather than a global read so a caller (and above all a\n * test) can settle the passphrase source WITHOUT mutating the real process\n * environment, which under a parallel runner leaks across whole test files.\n */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runWalletCreate(\n ctx: CommandContext,\n opts: WalletCreateOptions = {},\n): Promise<CommandResult> {\n const {\n address,\n walletPath: path,\n source,\n replaced,\n } = await createWalletLocked(ctx.dataDir, opts);\n\n const warnings = custodyWarnings();\n return {\n data: {\n address,\n walletPath: path,\n provider: 'local',\n policyEnforcement: 'client-only',\n keyStorage: KEY_STORAGE,\n passphraseSource: source,\n ...(replaced !== undefined\n ? {\n replaced: {\n address: replaced.address,\n archivedWalletPath: replaced.archivedPath,\n passphrasePreserved: replaced.passphraseLocation,\n ...(replaced.unarchivedReason !== undefined\n ? { unarchivedReason: replaced.unarchivedReason }\n : {}),\n },\n }\n : {}),\n warnings,\n },\n humanLines: [\n `Wallet created: ${address}`,\n `Key stored ${KEY_STORAGE}.`,\n passphraseNote(source, address),\n ...(replaced !== undefined ? replacedNote(replaced, path) : []),\n FUNDING_LINE,\n ...warnings,\n ],\n };\n}\n\n/** Where the outgoing wallet's funds live, why they remain reachable, and how to restore it. */\nfunction replacedNote(replaced: ArchivedWalletInfo, activeWalletPath: string): string[] {\n const passphraseLine =\n replaced.passphraseLocation === 'store'\n ? `its passphrase is preserved in the OS credential store (service tenjin-cli, account ${replaced.account}).`\n : replaced.passphraseLocation === 'env'\n ? 'its passphrase is TENJIN_WALLET_PASSPHRASE — keep that value.'\n : replaced.unarchivedReason === 'rejected-characters'\n ? 'its passphrase was NOT archived: the macOS keychain writer only stores machine-generated (base64url) passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it.'\n : replaced.unarchivedReason === 'no-store'\n ? 'its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it.'\n : 'its passphrase was NOT archived: the OS credential store write failed. It exists only where you keep it.';\n return [\n `Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,\n `Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,\n `To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \\`mv ${replaced.archivedPath} ${activeWalletPath}\\`.`,\n ];\n}\n\n/**\n * Run the whole create critical section under a cross-process file lock: the\n * existence pre-check, the passphrase generate-and-store, and the no-clobber\n * write. Without the lock these interleave across two concurrent creates — each\n * generates a distinct passphrase and persists it to the OS store BEFORE the\n * exclusive file write, so a different process could win the file while this\n * one's per-address entry names a wallet that never landed. Serializing means\n * the loser blocks until the winner commits, then trips the exists check and\n * exits WALLET_EXISTS having never generated or stored a passphrase. The\n * store-before-write ordering stays (it still guards the single-process crash\n * window), and the exclusive write stays the final authority.\n *\n * The passphrase is resolved inside the prepare step's address callback so the\n * OS-store entry is keyed to the new wallet's own address (issue #32).\n *\n * `--replace` ordering closes the no-active-wallet window: verify-and-preserve\n * the outgoing wallet (no file moves), fully PREPARE the replacement (key,\n * stored passphrase, encrypted keystore — every fallible step) while the old\n * wallet is still active, and only then park the old keystore and commit the\n * new one. A commit failure rolls the park back, so at every exit either the\n * old or the new wallet is the active one.\n */\nasync function createWalletLocked(\n dir: string,\n opts: WalletCreateOptions,\n): Promise<{\n address: string;\n walletPath: string;\n source: PassphraseSource;\n replaced?: ArchivedWalletInfo;\n}> {\n // Ensure the data dir exists so the lock's own mkdir has a parent on a fresh\n // install; the exclusive wallet write below re-ensures it at 0700 regardless.\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = join(dir, 'wallet.create.lock');\n try {\n return await withFileLock(lockPath, async () => {\n const env = opts.env ?? process.env;\n let source: PassphraseSource = 'env';\n const passphraseFor = async (forAddress: string): Promise<string> => {\n const resolved = await resolvePassphraseForCreate(\n { env, dir, ...opts.passphrase },\n forAddress,\n );\n source = resolved.source;\n return resolved.passphrase;\n };\n\n if (!(await walletFileExists(dir))) {\n const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);\n return { address, walletPath: path, source };\n }\n\n if (opts.replace !== true) throw walletExistsError(dir);\n const preserved = await verifyAndPreserveOutgoingWallet({\n dir,\n env,\n ...(opts.passphrase !== undefined ? { passphrase: opts.passphrase } : {}),\n });\n const prepared = await prepareLocalWallet(passphraseFor);\n const archivedPath = await parkOutgoingWallet(dir, preserved.account);\n try {\n const { address, walletPath: path } = await commitLocalWallet(dir, prepared);\n return { address, walletPath: path, source, replaced: { ...preserved, archivedPath } };\n } catch (err) {\n try {\n await restoreParkedWallet(dir, archivedPath);\n } catch (restoreErr) {\n // The no-clobber restore also refuses when a wallet.json appeared out\n // of band (commit EEXIST) — never overwrite it; name both files.\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.',\n {\n fix: `Your old wallet ${preserved.address} is intact at ${archivedPath} with its passphrase preserved. If a ${walletPath(dir)} now exists, another process wrote it — move it aside first. Then restore with \\`mv ${archivedPath} ${walletPath(dir)}\\`.`,\n cause: restoreErr,\n },\n );\n }\n // Old wallet restored as the active one; say so rather than surfacing a\n // raw fs error (or a WALLET_EXISTS whose fix suggests re-running --replace).\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.',\n {\n fix: 'Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.',\n cause: err,\n },\n );\n }\n });\n } catch (err) {\n // A lock timeout is not the user's error; surface it as INTERNAL with the one\n // manual step (there is no auto-steal), keeping the JSON error contract. Every\n // other error — notably the loser's WALLET_EXISTS — propagates unchanged.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\n/** Where the encryption passphrase lives, and what the user must remember. */\nfunction passphraseNote(source: PassphraseSource, address: string): string {\n const account = address.toLowerCase();\n switch (source) {\n case 'keychain':\n return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'dpapi':\n return `Passphrase saved to a DPAPI-encrypted per-wallet file (passphrase.${account}.dpapi), readable only by you on this Windows machine; signing will be transparent here.`;\n case 'secret-service':\n return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'env':\n return 'Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.';\n case 'prompt':\n return 'Remember your passphrase: it is required to sign and cannot be recovered.';\n }\n}\n\nexport async function runWalletShow(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n // Diagnostics are the provider's own: a remote provider reports no local file\n // path or perms warning, so `show` never contaminates a remote wallet's output\n // with a stale local wallet.json's state. keyStorage/passphraseSource are the\n // custody posture reported without decrypting or requiring a passphrase.\n const {\n walletPath: path,\n keyStorage,\n passphraseSource,\n archivedWallets,\n warnings,\n } = await provider.diagnostics();\n\n const humanLines = [`Address: ${desc.address}`, `Key source: ${desc.credentialSource}`];\n if (keyStorage !== undefined) humanLines.push(`Key storage: ${keyStorage}`);\n if (passphraseSource !== undefined) humanLines.push(`Passphrase: ${passphraseSource}`);\n if (archivedWallets !== undefined && archivedWallets.length > 0) {\n // A recovery hint, not a wallet switcher: exactly one wallet is ever active.\n humanLines.push(\n `Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(', ')}`,\n );\n }\n humanLines.push(...warnings);\n\n return {\n data: {\n address: desc.address,\n provider: desc.provider,\n credentialSource: desc.credentialSource,\n policyEnforcement: desc.policyEnforcement,\n ...(path !== undefined ? { walletPath: path } : {}),\n ...(keyStorage !== undefined ? { keyStorage } : {}),\n ...(passphraseSource !== undefined ? { passphraseSource } : {}),\n ...(archivedWallets !== undefined && archivedWallets.length > 0 ? { archivedWallets } : {}),\n warnings,\n },\n humanLines,\n };\n}\n\nexport async function runWalletBalance(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n\n const config = await loadRawConfig(ctx.dataDir);\n const rpcUrl = resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n }).rpcUrl.value;\n\n let atomic: bigint;\n try {\n atomic = await getUsdcBalance(desc.address, rpcUrl);\n } catch (err) {\n throw new CliError('RPC_ERROR', `Could not read the USDC balance from ${rpcUrl}.`, {\n fix: 'Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.',\n cause: err,\n });\n }\n\n const balance = toMoney(atomic.toString());\n return {\n data: { address: desc.address, balance },\n humanLines: [`Balance: ${balance.usd} USDC on Base`],\n };\n}\n\nfunction custodyWarnings(): string[] {\n const warnings: string[] = [];\n if (hasEnvKey()) {\n warnings.push('TENJIN_WALLET_KEY is set and shadows this file at runtime.');\n }\n if (isWindows) {\n warnings.push('File permissions are not enforced on Windows; the key file is not restricted.');\n }\n return warnings;\n}\n\nfunction hasEnvKey(): boolean {\n const envKey = process.env.TENJIN_WALLET_KEY;\n return envKey !== undefined && envKey.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB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AC;AAC5B,MAAI,UAAU,GAAG;AACf,aAAS,KAAK,4DAA4D;AAAA,EAC5E;AACA,MAAI,WAAW;AACb,aAAS,KAAK,+EAA+E;AAAA,EAC/F;AACA,SAAO;AACT;AAEA,SAAS,YAAqB;AAC5B,QAAM,SAAS,QAAQ,IAAI;AAC3B,SAAO,WAAW,UAAa,OAAO,SAAS;AACjD;","names":[]}
@@ -0,0 +1,124 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ UUID_RE,
4
+ newId
5
+ } from "./chunk-36X2CA3N.js";
6
+ import {
7
+ hasCode
8
+ } from "./chunk-2I4QTOLB.js";
9
+ import {
10
+ external_exports,
11
+ writeFileAtomicExclusive
12
+ } from "./chunk-PZRAAAY2.js";
13
+
14
+ // src/lib/candidate-store.ts
15
+ import { mkdir, readFile, readdir, rm, stat } from "fs/promises";
16
+ import { join } from "path";
17
+ var DRAFT_FILE = "draft.md";
18
+ var META_FILE = "meta.json";
19
+ var CandidateMetaSchema = external_exports.object({
20
+ schemaVersion: external_exports.literal(1),
21
+ searchId: external_exports.string(),
22
+ question: external_exports.string().optional(),
23
+ // Fixed-width UTC ISO-8601 (a trailing Z, never an offset): listCandidates
24
+ // sorts newest-first lexicographically on this string, which is only a valid
25
+ // proxy for chronological order when every value is same-zone UTC. z.iso
26
+ // .datetime() rejects offsets and non-datetime strings, pinning that invariant.
27
+ created: external_exports.iso.datetime(),
28
+ /** The repo root the add ran in, or the cwd when not in a repo. */
29
+ sourceProject: external_exports.string()
30
+ });
31
+ function candidatesDir(dataDir) {
32
+ return join(dataDir, "candidates");
33
+ }
34
+ function candidateDir(dataDir, id) {
35
+ return join(candidatesDir(dataDir), id);
36
+ }
37
+ async function createCandidate(dataDir, input) {
38
+ const id = newId();
39
+ const dir = candidateDir(dataDir, id);
40
+ await mkdir(dir, { recursive: true, mode: 448 });
41
+ const draftPath = join(dir, DRAFT_FILE);
42
+ const meta = {
43
+ schemaVersion: 1,
44
+ searchId: input.searchId,
45
+ ...input.question !== void 0 ? { question: input.question } : {},
46
+ created: input.created,
47
+ sourceProject: input.sourceProject
48
+ };
49
+ try {
50
+ await writeFileAtomicExclusive(draftPath, input.draft, { mode: 384, dirMode: 448 });
51
+ await writeFileAtomicExclusive(join(dir, META_FILE), `${JSON.stringify(meta, null, 2)}
52
+ `, {
53
+ mode: 384,
54
+ dirMode: 448
55
+ });
56
+ } catch (err) {
57
+ if (!hasCode(err, "EEXIST")) {
58
+ await rm(dir, { recursive: true, force: true }).catch(() => void 0);
59
+ }
60
+ throw err;
61
+ }
62
+ return { id, meta, dir, draftPath };
63
+ }
64
+ async function readCandidate(dataDir, id) {
65
+ if (!UUID_RE.test(id)) return null;
66
+ const dir = candidateDir(dataDir, id);
67
+ const meta = await readMeta(dir);
68
+ if (meta === null) return null;
69
+ return { id, meta, dir, draftPath: join(dir, DRAFT_FILE) };
70
+ }
71
+ async function listCandidates(dataDir) {
72
+ let entries;
73
+ try {
74
+ entries = await readdir(candidatesDir(dataDir), { withFileTypes: true });
75
+ } catch {
76
+ return [];
77
+ }
78
+ const records = [];
79
+ for (const entry of entries) {
80
+ if (!entry.isDirectory() || !UUID_RE.test(entry.name)) continue;
81
+ const record = await readCandidate(dataDir, entry.name);
82
+ if (record !== null) records.push(record);
83
+ }
84
+ records.sort((a, b) => {
85
+ if (a.meta.created !== b.meta.created) return a.meta.created < b.meta.created ? 1 : -1;
86
+ return a.id < b.id ? 1 : -1;
87
+ });
88
+ return records;
89
+ }
90
+ async function dropCandidate(dataDir, id) {
91
+ if (!UUID_RE.test(id)) return false;
92
+ const dir = candidateDir(dataDir, id);
93
+ try {
94
+ if (!(await stat(dir)).isDirectory()) return false;
95
+ } catch {
96
+ return false;
97
+ }
98
+ await rm(dir, { recursive: true, force: true });
99
+ return true;
100
+ }
101
+ async function readMeta(dir) {
102
+ let raw;
103
+ try {
104
+ raw = await readFile(join(dir, META_FILE), "utf8");
105
+ } catch {
106
+ return null;
107
+ }
108
+ let json;
109
+ try {
110
+ json = JSON.parse(raw);
111
+ } catch {
112
+ return null;
113
+ }
114
+ const parsed = CandidateMetaSchema.safeParse(json);
115
+ return parsed.success ? parsed.data : null;
116
+ }
117
+
118
+ export {
119
+ createCandidate,
120
+ readCandidate,
121
+ listCandidates,
122
+ dropCandidate
123
+ };
124
+ //# sourceMappingURL=chunk-TEL27PR5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/candidate-store.ts"],"sourcesContent":["import { mkdir, readFile, readdir, rm, stat } from 'node:fs/promises';\nimport type { Dirent } from 'node:fs';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { writeFileAtomicExclusive } from './atomic-json';\nimport { hasCode } from './errno';\nimport { newId, UUID_RE } from './ids';\n\n/**\n * The D40 candidate store: publish drafts parked locally that never touch the\n * network and never upload — only a later `tenjin publish --candidate <id>`\n * sends one, under the D38 consent scan. Each candidate is its OWN directory\n * `~/.tenjin/candidates/<id>/` holding the draft markdown plus a meta.json.\n *\n * Custody mirrors the wallet key discipline: the candidates tree is 0700 and\n * every file 0600, written create-once through writeFileAtomicExclusive so a\n * reader sees a complete file or none and a uuid collision is loud, never a\n * silent overwrite. Unlike search-store's single shared ledger, there is no shared\n * mutable file here — a fresh uuid per add means two concurrent adds land in two\n * distinct dirs and cannot contend — so no cross-process lock is needed. The\n * meta.json is written LAST and atomically, making it the commit point: `list`\n * skips any dir whose meta is absent or unreadable, so a torn or half-written\n * add reads as not-yet-there rather than a broken candidate, the same\n * best-effort posture loadSearches takes on a corrupt store. A crash mid-add is\n * cleaned up eagerly (the dir is removed on any write failure), and `drop` can\n * still remove a metaless orphan by id so a leaked draft is never stranded.\n */\n\nconst DRAFT_FILE = 'draft.md';\nconst META_FILE = 'meta.json';\n\nconst CandidateMetaSchema = z.object({\n schemaVersion: z.literal(1),\n searchId: z.string(),\n question: z.string().optional(),\n // Fixed-width UTC ISO-8601 (a trailing Z, never an offset): listCandidates\n // sorts newest-first lexicographically on this string, which is only a valid\n // proxy for chronological order when every value is same-zone UTC. z.iso\n // .datetime() rejects offsets and non-datetime strings, pinning that invariant.\n created: z.iso.datetime(),\n /** The repo root the add ran in, or the cwd when not in a repo. */\n sourceProject: z.string(),\n});\nexport type CandidateMeta = z.infer<typeof CandidateMetaSchema>;\n\nexport interface CandidateRecord {\n id: string;\n meta: CandidateMeta;\n /** Absolute path of the candidate directory. */\n dir: string;\n /** Absolute path of the draft markdown inside the directory. */\n draftPath: string;\n}\n\nexport interface CreateCandidateInput {\n /** The draft markdown, copied verbatim into the candidate. */\n draft: string;\n searchId: string;\n question?: string;\n /** ISO-8601 creation time; the command supplies it via its clock seam. */\n created: string;\n sourceProject: string;\n}\n\nfunction candidatesDir(dataDir: string): string {\n return join(dataDir, 'candidates');\n}\n\nfunction candidateDir(dataDir: string, id: string): string {\n return join(candidatesDir(dataDir), id);\n}\n\n/** Park a draft as a new candidate and return the created record. Both files are\n * written create-once (no-clobber, fsynced) at a fresh uuid path, meta.json\n * last, so the candidate is either fully present to `list`/`read` or absent,\n * never half-there. */\nexport async function createCandidate(\n dataDir: string,\n input: CreateCandidateInput,\n): Promise<CandidateRecord> {\n const id = newId();\n const dir = candidateDir(dataDir, id);\n await mkdir(dir, { recursive: true, mode: 0o700 });\n\n const draftPath = join(dir, DRAFT_FILE);\n const meta: CandidateMeta = {\n schemaVersion: 1,\n searchId: input.searchId,\n ...(input.question !== undefined ? { question: input.question } : {}),\n created: input.created,\n sourceProject: input.sourceProject,\n };\n try {\n // Exclusive (create-or-EEXIST, fsynced) so a uuid collision is loud, not a\n // silent overwrite of an existing candidate, and the crash-durable commit of\n // meta.json is the last, atomic step.\n await writeFileAtomicExclusive(draftPath, input.draft, { mode: 0o600, dirMode: 0o700 });\n await writeFileAtomicExclusive(join(dir, META_FILE), `${JSON.stringify(meta, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n // An EEXIST means something already lived at this fresh-uuid path (a real\n // collision, astronomically unlikely): surface it loudly and NEVER delete\n // what was already there. Any other failure is a partial write of our own\n // fresh dir — remove it so a crash mid-add can't strand a hidden dir holding\n // the (secrets-adjacent) draft that `list` skips and no one can name to `drop`.\n if (!hasCode(err, 'EEXIST')) {\n await rm(dir, { recursive: true, force: true }).catch(() => undefined);\n }\n throw err;\n }\n\n return { id, meta, dir, draftPath };\n}\n\n/** One candidate by id, or null when it is unknown (or the id is malformed, so a\n * stray argument can never traverse out of the store). */\nexport async function readCandidate(dataDir: string, id: string): Promise<CandidateRecord | null> {\n if (!UUID_RE.test(id)) return null;\n const dir = candidateDir(dataDir, id);\n const meta = await readMeta(dir);\n if (meta === null) return null;\n return { id, meta, dir, draftPath: join(dir, DRAFT_FILE) };\n}\n\n/** Every pending candidate, newest first by `created` (no auto-expiry — stale\n * candidates stay visible, D40). Tie-broken on id so the order is total. */\nexport async function listCandidates(dataDir: string): Promise<CandidateRecord[]> {\n let entries: Dirent[];\n try {\n entries = await readdir(candidatesDir(dataDir), { withFileTypes: true });\n } catch {\n return [];\n }\n const records: CandidateRecord[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory() || !UUID_RE.test(entry.name)) continue;\n const record = await readCandidate(dataDir, entry.name);\n if (record !== null) records.push(record);\n }\n records.sort((a, b) => {\n if (a.meta.created !== b.meta.created) return a.meta.created < b.meta.created ? 1 : -1;\n return a.id < b.id ? 1 : -1;\n });\n return records;\n}\n\n/** Discard one candidate by id. Returns false when the id is malformed or no\n * such dir exists, so the command can surface a clean not-found; nothing is\n * ever auto-deleted. Removes the dir even when its meta is absent or corrupt,\n * so a crash-orphaned candidate can still be cleaned up by id (the id is\n * UUID-gated first, so a stray argument can never target a path outside the\n * store). */\nexport async function dropCandidate(dataDir: string, id: string): Promise<boolean> {\n if (!UUID_RE.test(id)) return false;\n const dir = candidateDir(dataDir, id);\n try {\n if (!(await stat(dir)).isDirectory()) return false;\n } catch {\n return false; // no such candidate\n }\n await rm(dir, { recursive: true, force: true });\n return true;\n}\n\n/** Read and validate a candidate's meta.json; null on any absence/corruption. */\nasync function readMeta(dir: string): Promise<CandidateMeta | null> {\n let raw: string;\n try {\n raw = await readFile(join(dir, META_FILE), 'utf8');\n } catch {\n return null;\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return null;\n }\n const parsed = CandidateMetaSchema.safeParse(json);\n return parsed.success ? parsed.data : null;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,OAAO,UAAU,SAAS,IAAI,YAAY;AAEnD,SAAS,YAAY;AA0BrB,IAAM,aAAa;AACnB,IAAM,YAAY;AAElB,IAAM,sBAAsB,iBAAE,OAAO;AAAA,EACnC,eAAe,iBAAE,QAAQ,CAAC;AAAA,EAC1B,UAAU,iBAAE,OAAO;AAAA,EACnB,UAAU,iBAAE,OAAO,EAAE,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,EAK9B,SAAS,iBAAE,IAAI,SAAS;AAAA;AAAA,EAExB,eAAe,iBAAE,OAAO;AAC1B,CAAC;AAsBD,SAAS,cAAc,SAAyB;AAC9C,SAAO,KAAK,SAAS,YAAY;AACnC;AAEA,SAAS,aAAa,SAAiB,IAAoB;AACzD,SAAO,KAAK,cAAc,OAAO,GAAG,EAAE;AACxC;AAMA,eAAsB,gBACpB,SACA,OAC0B;AAC1B,QAAM,KAAK,MAAM;AACjB,QAAM,MAAM,aAAa,SAAS,EAAE;AACpC,QAAM,MAAM,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAEjD,QAAM,YAAY,KAAK,KAAK,UAAU;AACtC,QAAM,OAAsB;AAAA,IAC1B,eAAe;AAAA,IACf,UAAU,MAAM;AAAA,IAChB,GAAI,MAAM,aAAa,SAAY,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;AAAA,IACnE,SAAS,MAAM;AAAA,IACf,eAAe,MAAM;AAAA,EACvB;AACA,MAAI;AAIF,UAAM,yBAAyB,WAAW,MAAM,OAAO,EAAE,M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