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
@@ -0,0 +1,204 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ Hash,
4
+ abytes,
5
+ aexists,
6
+ anumber,
7
+ aoutput,
8
+ clean,
9
+ createHasher,
10
+ rotlBH,
11
+ rotlBL,
12
+ rotlSH,
13
+ rotlSL,
14
+ split,
15
+ swap32IfBE,
16
+ toBytes,
17
+ u32
18
+ } from "./chunk-KYQVEKP5.js";
19
+
20
+ // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js
21
+ var _0n = BigInt(0);
22
+ var _1n = BigInt(1);
23
+ var _2n = BigInt(2);
24
+ var _7n = BigInt(7);
25
+ var _256n = BigInt(256);
26
+ var _0x71n = BigInt(113);
27
+ var SHA3_PI = [];
28
+ var SHA3_ROTL = [];
29
+ var _SHA3_IOTA = [];
30
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
31
+ [x, y] = [y, (2 * x + 3 * y) % 5];
32
+ SHA3_PI.push(2 * (5 * y + x));
33
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
34
+ let t = _0n;
35
+ for (let j = 0; j < 7; j++) {
36
+ R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
37
+ if (R & _2n)
38
+ t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
39
+ }
40
+ _SHA3_IOTA.push(t);
41
+ }
42
+ var IOTAS = split(_SHA3_IOTA, true);
43
+ var SHA3_IOTA_H = IOTAS[0];
44
+ var SHA3_IOTA_L = IOTAS[1];
45
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
46
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
47
+ function keccakP(s, rounds = 24) {
48
+ const B = new Uint32Array(5 * 2);
49
+ for (let round = 24 - rounds; round < 24; round++) {
50
+ for (let x = 0; x < 10; x++)
51
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
52
+ for (let x = 0; x < 10; x += 2) {
53
+ const idx1 = (x + 8) % 10;
54
+ const idx0 = (x + 2) % 10;
55
+ const B0 = B[idx0];
56
+ const B1 = B[idx0 + 1];
57
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
58
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
59
+ for (let y = 0; y < 50; y += 10) {
60
+ s[x + y] ^= Th;
61
+ s[x + y + 1] ^= Tl;
62
+ }
63
+ }
64
+ let curH = s[2];
65
+ let curL = s[3];
66
+ for (let t = 0; t < 24; t++) {
67
+ const shift = SHA3_ROTL[t];
68
+ const Th = rotlH(curH, curL, shift);
69
+ const Tl = rotlL(curH, curL, shift);
70
+ const PI = SHA3_PI[t];
71
+ curH = s[PI];
72
+ curL = s[PI + 1];
73
+ s[PI] = Th;
74
+ s[PI + 1] = Tl;
75
+ }
76
+ for (let y = 0; y < 50; y += 10) {
77
+ for (let x = 0; x < 10; x++)
78
+ B[x] = s[y + x];
79
+ for (let x = 0; x < 10; x++)
80
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
81
+ }
82
+ s[0] ^= SHA3_IOTA_H[round];
83
+ s[1] ^= SHA3_IOTA_L[round];
84
+ }
85
+ clean(B);
86
+ }
87
+ var Keccak = class _Keccak extends Hash {
88
+ // NOTE: we accept arguments in bytes instead of bits here.
89
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
90
+ super();
91
+ this.pos = 0;
92
+ this.posOut = 0;
93
+ this.finished = false;
94
+ this.destroyed = false;
95
+ this.enableXOF = false;
96
+ this.blockLen = blockLen;
97
+ this.suffix = suffix;
98
+ this.outputLen = outputLen;
99
+ this.enableXOF = enableXOF;
100
+ this.rounds = rounds;
101
+ anumber(outputLen);
102
+ if (!(0 < blockLen && blockLen < 200))
103
+ throw new Error("only keccak-f1600 function is supported");
104
+ this.state = new Uint8Array(200);
105
+ this.state32 = u32(this.state);
106
+ }
107
+ clone() {
108
+ return this._cloneInto();
109
+ }
110
+ keccak() {
111
+ swap32IfBE(this.state32);
112
+ keccakP(this.state32, this.rounds);
113
+ swap32IfBE(this.state32);
114
+ this.posOut = 0;
115
+ this.pos = 0;
116
+ }
117
+ update(data) {
118
+ aexists(this);
119
+ data = toBytes(data);
120
+ abytes(data);
121
+ const { blockLen, state } = this;
122
+ const len = data.length;
123
+ for (let pos = 0; pos < len; ) {
124
+ const take = Math.min(blockLen - this.pos, len - pos);
125
+ for (let i = 0; i < take; i++)
126
+ state[this.pos++] ^= data[pos++];
127
+ if (this.pos === blockLen)
128
+ this.keccak();
129
+ }
130
+ return this;
131
+ }
132
+ finish() {
133
+ if (this.finished)
134
+ return;
135
+ this.finished = true;
136
+ const { state, suffix, pos, blockLen } = this;
137
+ state[pos] ^= suffix;
138
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
139
+ this.keccak();
140
+ state[blockLen - 1] ^= 128;
141
+ this.keccak();
142
+ }
143
+ writeInto(out) {
144
+ aexists(this, false);
145
+ abytes(out);
146
+ this.finish();
147
+ const bufferOut = this.state;
148
+ const { blockLen } = this;
149
+ for (let pos = 0, len = out.length; pos < len; ) {
150
+ if (this.posOut >= blockLen)
151
+ this.keccak();
152
+ const take = Math.min(blockLen - this.posOut, len - pos);
153
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
154
+ this.posOut += take;
155
+ pos += take;
156
+ }
157
+ return out;
158
+ }
159
+ xofInto(out) {
160
+ if (!this.enableXOF)
161
+ throw new Error("XOF is not possible for this instance");
162
+ return this.writeInto(out);
163
+ }
164
+ xof(bytes) {
165
+ anumber(bytes);
166
+ return this.xofInto(new Uint8Array(bytes));
167
+ }
168
+ digestInto(out) {
169
+ aoutput(out, this);
170
+ if (this.finished)
171
+ throw new Error("digest() was already called");
172
+ this.writeInto(out);
173
+ this.destroy();
174
+ return out;
175
+ }
176
+ digest() {
177
+ return this.digestInto(new Uint8Array(this.outputLen));
178
+ }
179
+ destroy() {
180
+ this.destroyed = true;
181
+ clean(this.state);
182
+ }
183
+ _cloneInto(to) {
184
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
185
+ to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
186
+ to.state32.set(this.state32);
187
+ to.pos = this.pos;
188
+ to.posOut = this.posOut;
189
+ to.finished = this.finished;
190
+ to.rounds = rounds;
191
+ to.suffix = suffix;
192
+ to.outputLen = outputLen;
193
+ to.enableXOF = enableXOF;
194
+ to.destroyed = this.destroyed;
195
+ return to;
196
+ }
197
+ };
198
+ var gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
199
+ var keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
200
+
201
+ export {
202
+ keccak_256
203
+ };
204
+ //# sourceMappingURL=chunk-XJN5WUKL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/sha3.ts"],"sourcesContent":["/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher, createXOFer, Hash,\n swap32IfBE,\n toBytes, u32,\n type CHash, type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = [];\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s: Uint32Array, rounds: number = 24): void {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++) B[x] = s[y + x];\n for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n\n/** Keccak sponge function. */\nexport class Keccak extends Hash<Keccak> implements HashXOF<Keccak> {\n protected state: Uint8Array;\n protected pos = 0;\n protected posOut = 0;\n protected finished = false;\n protected state32: Uint32Array;\n protected destroyed = false;\n\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen) this.keccak();\n }\n return this;\n }\n protected finish(): void {\n if (this.finished) return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n protected writeInto(out: Uint8Array): Uint8Array {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len; ) {\n if (this.posOut >= blockLen) this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out: Uint8Array): Uint8Array {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF) throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes: number): Uint8Array {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array): Uint8Array {\n aoutput(out, this);\n if (this.finished) throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to?: Keccak): Keccak {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\n\nconst gen = (suffix: number, blockLen: number, outputLen: number) =>\n createHasher(() => new Keccak(blockLen, suffix, outputLen));\n\n/** SHA3-224 hash function. */\nexport const sha3_224: CHash = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256: CHash = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384: CHash = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512: CHash = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n\n/** keccak-224 hash function. */\nexport const keccak_224: CHash = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256: CHash = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384: CHash = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512: CHash = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n createXOFer<HashXOF<Keccak>, ShakeOpts>(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n );\n\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwBA,IAAM,MAAM,OAAO,CAAC;AACpB,IAAM,MAAM,OAAO,CAAC;AACpB,IAAM,MAAM,OAAO,CAAC;AACpB,IAAM,MAAM,OAAO,CAAC;AACpB,IAAM,QAAQ,OAAO,GAAG;AACxB,IAAM,SAAS,OAAO,GAAI;AAC1B,IAAM,UAAoB,C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,GAAM,KAAK,MAAM,CAAC,GAAE;","names":[]}
@@ -0,0 +1,149 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ fetchRead
4
+ } from "./chunk-ZE7KOO7A.js";
5
+ import {
6
+ headingOutline
7
+ } from "./chunk-SGK2B724.js";
8
+ import {
9
+ resolveResourceRef
10
+ } from "./chunk-6UY2UQMY.js";
11
+ import {
12
+ sanitizeForTerminal
13
+ } from "./chunk-IB63U6BM.js";
14
+ import {
15
+ resolveContextSettings
16
+ } from "./chunk-JTYIX6OD.js";
17
+ import {
18
+ toMoney
19
+ } from "./chunk-ALUNME53.js";
20
+
21
+ // src/commands/inspect.ts
22
+ async function runInspect(args, ctx, deps = {}) {
23
+ const settings = await resolveContextSettings(ctx);
24
+ const ref = await resolveResourceRef(args.ref, ctx.dataDir, settings.baseUrl);
25
+ const result = await fetchRead(ref.url, {
26
+ timeoutMs: ctx.flags.timeout,
27
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
28
+ });
29
+ if (result.kind === "entitled") {
30
+ const body = result.body;
31
+ return {
32
+ data: {
33
+ url: ref.url,
34
+ resourceId: body.id,
35
+ access: "free",
36
+ title: body.title,
37
+ price: toMoney(body.price),
38
+ headings: headingOutline(body.bodyMd),
39
+ // The free/owned half of the verb split (#42): delivery here costs nothing,
40
+ // so point at the free-only verb, not at the paying one. Machine consumers
41
+ // read this; the human line below says the same thing.
42
+ nextCommand: `tenjin read ${ref.url}`
43
+ },
44
+ humanLines: [
45
+ `${sanitizeForTerminal(body.title)}, free (${body.price} atomic). Read it with \`tenjin read ${sanitizeForTerminal(ref.url)}\`.`
46
+ ]
47
+ };
48
+ }
49
+ if (result.kind === "payment_required") {
50
+ const requirement = result.paymentRequired.accepts[0];
51
+ const price = requirement !== void 0 ? toMoney(requirement.amount) : void 0;
52
+ const card = result.preview.card;
53
+ return {
54
+ data: {
55
+ url: ref.url,
56
+ ...ref.resourceId !== void 0 ? { resourceId: ref.resourceId } : {},
57
+ access: "paid",
58
+ ...price !== void 0 ? { price } : {},
59
+ payment: requirement !== void 0 ? {
60
+ scheme: requirement.scheme,
61
+ network: requirement.network,
62
+ asset: requirement.asset,
63
+ payTo: requirement.payTo,
64
+ amount: requirement.amount
65
+ } : void 0,
66
+ // The card stays where the wire puts it, inside `preview`, and is emitted
67
+ // exactly once: it is the largest object in this envelope, and a second
68
+ // hoisted copy would double every inspect payload to save one key of
69
+ // depth.
70
+ preview: result.preview,
71
+ ...result.cardError === true ? { cardError: true } : {},
72
+ // Paid and unowned: this one really does cost money, so it keeps pointing at
73
+ // `buy`. `tenjin read` would refuse it with exit 3.
74
+ nextCommand: `tenjin buy ${ref.url}`
75
+ },
76
+ humanLines: [
77
+ `Paid resource${price !== void 0 ? `, ${price.usd} USD (${price.atomic} atomic)` : ""}.`,
78
+ ...cardLines(card),
79
+ // Three distinct states behind an absent card, and they call for three
80
+ // different actions: the piece attests nothing (a signal, judge on that),
81
+ // the server could not load a card it has (transient, retry), or this CLI
82
+ // could not parse what arrived (a client-side bug or server drift). Only
83
+ // the last is ours. `cardUnavailable` is server-sent and never rides
84
+ // alongside a card, so it is only worth saying when there is no card.
85
+ ...card === void 0 && result.preview.cardUnavailable === true ? ["The piece has a card the server could not load; retry later."] : [],
86
+ ...result.cardError === true ? [
87
+ "The server sent an answer card this CLI could not parse; judging on price and preview only."
88
+ ] : [],
89
+ "This is the pre-purchase card; run `tenjin buy` to pay and read (`tenjin read` refuses paid pieces)."
90
+ ]
91
+ };
92
+ }
93
+ return {
94
+ data: {
95
+ url: ref.url,
96
+ access: "entitled",
97
+ message: result.message,
98
+ nextCommand: `tenjin read ${ref.url}`
99
+ },
100
+ humanLines: [
101
+ `${sanitizeForTerminal(result.message)} Read it with \`tenjin read ${sanitizeForTerminal(ref.url)}\`.`
102
+ ]
103
+ };
104
+ }
105
+ var CARD_BOUNDS = {
106
+ list: 10 * 200 + 9 * 2,
107
+ appliesTo: 8 * (32 + 1 + 20 * 120 + 19 * 2) + 7 * 2,
108
+ prose: 500,
109
+ cadence: 120,
110
+ // artifactType and temporalMode are open strings on the wire, so the composed
111
+ // freshness line gets a bound of its own rather than trusting them.
112
+ freshness: 200
113
+ };
114
+ var CLIP_MARKER = "...";
115
+ function cardLine(label, value, max) {
116
+ if (value === null) return [];
117
+ const text = sanitizeForTerminal(value).trim();
118
+ if (text.length === 0) return [];
119
+ return [`${label}: ${text.length > max ? `${text.slice(0, max)}${CLIP_MARKER}` : text}`];
120
+ }
121
+ function cardLines(card) {
122
+ if (card === void 0) return [];
123
+ const list = (items) => items.length > 0 ? items.join("; ") : null;
124
+ const appliesTo = Object.entries(card.appliesTo).map(
125
+ ([key, values]) => `${key}=${values.join(", ")}`
126
+ );
127
+ return [
128
+ ...cardLine("Answers", list(card.questionsAnswered), CARD_BOUNDS.list),
129
+ ...cardLine("Tasks", list(card.tasksSupported), CARD_BOUNDS.list),
130
+ ...cardLine("Applies to", list(appliesTo), CARD_BOUNDS.appliesTo),
131
+ ...cardLine("Scope", card.scope, CARD_BOUNDS.prose),
132
+ ...cardLine("Excludes", card.exclusions, CARD_BOUNDS.prose),
133
+ ...cardLine("Freshness", freshness(card), CARD_BOUNDS.freshness),
134
+ ...cardLine("Provenance", card.provenanceSummary, CARD_BOUNDS.prose),
135
+ ...cardLine("Method", card.methodologySummary, CARD_BOUNDS.prose),
136
+ ...cardLine("Maintenance", card.maintenanceCadence, CARD_BOUNDS.cadence)
137
+ ];
138
+ }
139
+ function freshness(card) {
140
+ const parts = [card.artifactType, card.temporalMode].filter((s) => s.trim().length > 0);
141
+ if (card.asOf !== null) parts.push(`as of ${card.asOf}`);
142
+ if (card.validUntil !== null) parts.push(`valid until ${card.validUntil}`);
143
+ return parts.join(", ");
144
+ }
145
+
146
+ export {
147
+ runInspect
148
+ };
149
+ //# sourceMappingURL=chunk-XWHXX2BI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/inspect.ts"],"sourcesContent":["import { resolveResourceRef } from '../lib/resource-ref';\nimport { resolveContextSettings } from '../lib/settings';\nimport { fetchRead, type PreviewCard } from '../lib/read-client';\nimport { toMoney } from '../lib/money';\nimport { headingOutline } from '../lib/markdown';\nimport { sanitizeForTerminal } from '../lib/output';\nimport type { CommandContext, CommandResult } from '../context';\n\n/**\n * `tenjin inspect <resource-url-or-id>`, fetch the pre-purchase answer card /\n * preview from the read route's 402 body WITHOUT paying (spec 10). A free\n * resource returns 200 with the whole body; a paid one returns the leak-safe\n * preview plus the advertised price/network, and the answer card when the piece\n * carries one. Never signs, never pays, never saves.\n *\n * The card is the depth half of the search/inspect split: search v2 candidates are\n * lean, so this free call is where an agent gets what it answers, what it applies\n * to, what it excludes, and how it is dated, before spending anything.\n */\n\nexport interface InspectArgs {\n ref: string;\n}\n\nexport interface InspectDeps {\n fetchImpl?: typeof fetch;\n}\n\nexport async function runInspect(\n args: InspectArgs,\n ctx: CommandContext,\n deps: InspectDeps = {},\n): Promise<CommandResult> {\n const settings = await resolveContextSettings(ctx);\n const ref = await resolveResourceRef(args.ref, ctx.dataDir, settings.baseUrl);\n\n const result = await fetchRead(ref.url, {\n timeoutMs: ctx.flags.timeout,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n if (result.kind === 'entitled') {\n // Free (or already-entitled) resource: the body is readable now, no payment.\n const body = result.body;\n return {\n data: {\n url: ref.url,\n resourceId: body.id,\n access: 'free',\n title: body.title,\n price: toMoney(body.price),\n headings: headingOutline(body.bodyMd),\n // The free/owned half of the verb split (#42): delivery here costs nothing,\n // so point at the free-only verb, not at the paying one. Machine consumers\n // read this; the human line below says the same thing.\n nextCommand: `tenjin read ${ref.url}`,\n },\n humanLines: [\n `${sanitizeForTerminal(body.title)}, free (${body.price} atomic). Read it with \\`tenjin read ${sanitizeForTerminal(ref.url)}\\`.`,\n ],\n };\n }\n\n if (result.kind === 'payment_required') {\n const requirement = result.paymentRequired.accepts[0];\n const price = requirement !== undefined ? toMoney(requirement.amount) : undefined;\n const card = result.preview.card;\n return {\n data: {\n url: ref.url,\n ...(ref.resourceId !== undefined ? { resourceId: ref.resourceId } : {}),\n access: 'paid',\n ...(price !== undefined ? { price } : {}),\n payment:\n requirement !== undefined\n ? {\n scheme: requirement.scheme,\n network: requirement.network,\n asset: requirement.asset,\n payTo: requirement.payTo,\n amount: requirement.amount,\n }\n : undefined,\n // The card stays where the wire puts it, inside `preview`, and is emitted\n // exactly once: it is the largest object in this envelope, and a second\n // hoisted copy would double every inspect payload to save one key of\n // depth.\n preview: result.preview,\n ...(result.cardError === true ? { cardError: true } : {}),\n // Paid and unowned: this one really does cost money, so it keeps pointing at\n // `buy`. `tenjin read` would refuse it with exit 3.\n nextCommand: `tenjin buy ${ref.url}`,\n },\n humanLines: [\n `Paid resource${price !== undefined ? `, ${price.usd} USD (${price.atomic} atomic)` : ''}.`,\n ...cardLines(card),\n // Three distinct states behind an absent card, and they call for three\n // different actions: the piece attests nothing (a signal, judge on that),\n // the server could not load a card it has (transient, retry), or this CLI\n // could not parse what arrived (a client-side bug or server drift). Only\n // the last is ours. `cardUnavailable` is server-sent and never rides\n // alongside a card, so it is only worth saying when there is no card.\n ...(card === undefined && result.preview.cardUnavailable === true\n ? ['The piece has a card the server could not load; retry later.']\n : []),\n ...(result.cardError === true\n ? [\n 'The server sent an answer card this CLI could not parse; judging on price and preview only.',\n ]\n : []),\n 'This is the pre-purchase card; run `tenjin buy` to pay and read (`tenjin read` refuses paid pieces).',\n ],\n };\n }\n\n // already_purchased without a payment header is unexpected; report it plainly.\n // Owned means delivery is free, so this branch points at `read` too.\n return {\n data: {\n url: ref.url,\n access: 'entitled',\n message: result.message,\n nextCommand: `tenjin read ${ref.url}`,\n },\n humanLines: [\n `${sanitizeForTerminal(result.message)} Read it with \\`tenjin read ${sanitizeForTerminal(ref.url)}\\`.`,\n ],\n };\n}\n\n/**\n * Per-line caps for the rendered card, each derived from the server's write-time\n * bound for that field, so a VALID card is never clipped: the two lists are 10\n * items x 200 chars joined with '; '; appliesTo is 8 keys (<=32 chars) x 20\n * values x 120 chars; the prose fields have a 500-char column bound and cadence\n * 120. Exceeding one means a server that broke its own bounds.\n *\n * When that happens the clip is MARKED. A silently shortened claim reads as a\n * whole one, and \"applies to Postgres 14, 15\" is a different promise from\n * \"applies to Postgres 14, 15, 16\". The `--json` payload stays verbatim either\n * way, because that copy is what an agent decides a non-refundable purchase on.\n */\nconst CARD_BOUNDS = {\n list: 10 * 200 + 9 * 2,\n appliesTo: 8 * (32 + 1 + 20 * 120 + 19 * 2) + 7 * 2,\n prose: 500,\n cadence: 120,\n // artifactType and temporalMode are open strings on the wire, so the composed\n // freshness line gets a bound of its own rather than trusting them.\n freshness: 200,\n} as const;\n\nconst CLIP_MARKER = '...';\n\nfunction cardLine(label: string, value: string | null, max: number): string[] {\n if (value === null) return [];\n const text = sanitizeForTerminal(value).trim();\n if (text.length === 0) return [];\n return [`${label}: ${text.length > max ? `${text.slice(0, max)}${CLIP_MARKER}` : text}`];\n}\n\n/**\n * The answer card off the 402 body, as human lines. This is the depth half of the\n * search/inspect split: search v2 returns lean hits, and the card an agent judges\n * fit on arrives here, for free. Empty when the piece carries no card, so an\n * uncarded inspect renders exactly as it did before.\n */\nfunction cardLines(card: PreviewCard | undefined): string[] {\n if (card === undefined) return [];\n const list = (items: string[]): string | null => (items.length > 0 ? items.join('; ') : null);\n const appliesTo = Object.entries(card.appliesTo).map(\n ([key, values]) => `${key}=${values.join(', ')}`,\n );\n return [\n ...cardLine('Answers', list(card.questionsAnswered), CARD_BOUNDS.list),\n ...cardLine('Tasks', list(card.tasksSupported), CARD_BOUNDS.list),\n ...cardLine('Applies to', list(appliesTo), CARD_BOUNDS.appliesTo),\n ...cardLine('Scope', card.scope, CARD_BOUNDS.prose),\n ...cardLine('Excludes', card.exclusions, CARD_BOUNDS.prose),\n ...cardLine('Freshness', freshness(card), CARD_BOUNDS.freshness),\n ...cardLine('Provenance', card.provenanceSummary, CARD_BOUNDS.prose),\n ...cardLine('Method', card.methodologySummary, CARD_BOUNDS.prose),\n ...cardLine('Maintenance', card.maintenanceCadence, CARD_BOUNDS.cadence),\n ];\n}\n\n/** Type, temporal mode and the two dates on one line: they answer the single\n * question a buyer asks of freshness, which is whether this is still true here.\n *\n * Both labels are open strings on the wire, so an empty one is dropped rather\n * than joined: otherwise the line leads with a comma and reads as a rendering\n * bug. All four empty yields '', and cardLine then omits the line entirely. */\nfunction freshness(card: PreviewCard): string {\n const parts = [card.artifactType, card.temporalMode].filter((s) => s.trim().length > 0);\n if (card.asOf !== null) parts.push(`as of ${card.asOf}`);\n if (card.validUntil !== null) parts.push(`valid until ${card.validUntil}`);\n return parts.join(', ');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsB,WACpB,MACA,KACA,OAAoB,CAAC,GACG;AACxB,QAAM,WAAW,MAAM,uBAAuB,GAAG;AACjD,QAAM,MAAM,MAAM,mBAAmB,KAAK,KAAK,IAAI,SAAS,SAAS,OAAO;AAE5E,QAAM,SAAS,MAAM,UAAU,IAAI,KAAK;AAAA,IACtC,WAAW,IAAI,MAAM;AAAA,IACrB,GAAI,KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,EACtE,CAAC;AAED,MAAI,OAAO,SAAS,YAAY;AAE9B,UAAM,OAAO,OAAO;AACpB,WAAO;AAAA,MACL,MAAM;AAAA,QACJ,KAAK,IAAI;AAAA,QACT,YAAY,KAAK;AAAA,QACjB,QAAQ;AAAA,QACR,OAAO,KAAK;AAAA,QACZ,OAAO,QAAQ,KAAK,KAAK;AAAA,QACzB,UAAU,eAAe,KAAK,MAAM;AAAA;AAAA;AAAA;AAAA,QAIpC,aAAa,eAAe,IAAI,GAAG;AAAA,MACrC;AAAA,MACA,YAAY;AAAA,QACV,GAAG,oBAAoB,KAAK,KAAK,CAAC,WAAW,KAAK,KAAK,wCAAwC,oBAAoB,IA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,YAAY,YAAY,KAAK;AAAA,IAC1D,GAAG,SAAS,aAAa,UAAU,IAAI,GAAG,YAAY,SAAS;AAAA,IAC/D,GAAG,SAAS,cAAc,KAAK,mBAAmB,YAAY,KAAK;AAAA,IACnE,GAAG,SAAS,UAAU,KAAK,oBAAoB,YAAY,KAAK;AAAA,IAChE,GAAG,SAAS,eAAe,KAAK,oBAAoB,YAAY,OAAO;AAAA,EACzE;AACF;AAQA,SAAS,UAAU,MAA2B;AAC5C,QAAM,QAAQ,CAAC,KAAK,cAAc,KAAK,YAAY,EAAE,OAAO,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC;AACtF,MAAI,KAAK,SAAS,KAAM,OAAM,KAAK,SAAS,KAAK,IAAI,EAAE;AACvD,MAAI,KAAK,eAAe,KAAM,OAAM,KAAK,eAAe,KAAK,UAAU,EAAE;AACzE,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
@@ -1,12 +1,15 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
- writeFileAtomicExclusive
4
- } from "./chunk-ZPZFPVDN.js";
3
+ walletPath
4
+ } from "./chunk-ZQIQ55KK.js";
5
+ import {
6
+ hasCode
7
+ } from "./chunk-2I4QTOLB.js";
5
8
  import {
6
9
  CliError,
7
10
  external_exports,
8
- walletPath
9
- } from "./chunk-YG2DO46P.js";
11
+ writeFileAtomicExclusive
12
+ } from "./chunk-PZRAAAY2.js";
10
13
 
11
14
  // src/lib/wallet/store.ts
12
15
  import { readFile, stat } from "fs/promises";
@@ -24,8 +27,9 @@ var KeystoreV3Schema = external_exports.object({
24
27
  id: external_exports.string(),
25
28
  version: external_exports.literal(3)
26
29
  });
30
+ var WALLET_SCHEMA_VERSION = 2;
27
31
  var WalletRecordSchema = external_exports.object({
28
- schemaVersion: external_exports.literal(2),
32
+ schemaVersion: external_exports.literal(WALLET_SCHEMA_VERSION),
29
33
  provider: external_exports.literal("local"),
30
34
  address: external_exports.string().regex(ADDRESS_RE, "expected a 0x-prefixed 20-byte address"),
31
35
  keystore: KeystoreV3Schema,
@@ -72,6 +76,16 @@ async function readWalletRecord(dir) {
72
76
  }
73
77
  );
74
78
  }
79
+ const newer = newerSchemaVersion(json);
80
+ if (newer !== null) {
81
+ throw new CliError(
82
+ "CONTRACT_MISMATCH",
83
+ `The wallet file at ${path} was written by a newer tenjin-cli (wallet schema v${newer}; this build reads v${WALLET_SCHEMA_VERSION}).`,
84
+ {
85
+ fix: "Upgrade with `npm i -g tenjin-cli`. Do not delete or recreate the wallet: the newer CLI still reads this one, and the funds are on the address it holds."
86
+ }
87
+ );
88
+ }
75
89
  const parsed = WalletRecordSchema.safeParse(json);
76
90
  if (!parsed.success) {
77
91
  throw new CliError(
@@ -85,6 +99,13 @@ async function readWalletRecord(dir) {
85
99
  }
86
100
  return parsed.data;
87
101
  }
102
+ function walletExistsError(dir, cause) {
103
+ const path = walletPath(dir);
104
+ return new CliError("WALLET_EXISTS", `A wallet already exists at ${path}.`, {
105
+ fix: `Run \`tenjin wallet create --replace\` to archive it and create a new one: its keystore is parked beside the new wallet and its passphrase stays preserved in the OS credential store (service tenjin-cli, account = its address), so its funds remain reachable. That passphrase is unrecoverable \u2014 never delete the credential-store entry, or the wallet's funds are stranded.`,
106
+ ...cause !== void 0 ? { cause } : {}
107
+ });
108
+ }
88
109
  async function writeWalletRecord(dir, record) {
89
110
  const validated = WalletRecordSchema.parse(record);
90
111
  const path = walletPath(dir);
@@ -95,15 +116,15 @@ async function writeWalletRecord(dir, record) {
95
116
  dirMode: 448
96
117
  });
97
118
  } catch (err) {
98
- if (hasCode(err, "EEXIST")) {
99
- throw new CliError("WALLET_EXISTS", `A wallet already exists at ${path}.`, {
100
- fix: `Keys are non-recoverable; move it aside first (e.g. \`mv ${path} ${path}.bak\`) to create a new one.`,
101
- cause: err
102
- });
103
- }
119
+ if (hasCode(err, "EEXIST")) throw walletExistsError(dir, err);
104
120
  throw err;
105
121
  }
106
122
  }
123
+ function newerSchemaVersion(json) {
124
+ if (typeof json !== "object" || json === null) return null;
125
+ const v = json.schemaVersion;
126
+ return typeof v === "number" && Number.isInteger(v) && v > WALLET_SCHEMA_VERSION ? v : null;
127
+ }
107
128
  function isPreEncryptionRecord(json) {
108
129
  if (typeof json !== "object" || json === null) return false;
109
130
  const rec = json;
@@ -112,15 +133,14 @@ function isPreEncryptionRecord(json) {
112
133
  function isNotFound(err) {
113
134
  return hasCode(err, "ENOENT");
114
135
  }
115
- function hasCode(err, code) {
116
- return typeof err === "object" && err !== null && "code" in err && err.code === code;
117
- }
118
136
 
119
137
  export {
120
138
  PRIVATE_KEY_RE,
139
+ WALLET_SCHEMA_VERSION,
121
140
  walletFileExists,
122
141
  walletFileMode,
123
142
  readWalletRecord,
143
+ walletExistsError,
124
144
  writeWalletRecord
125
145
  };
126
- //# sourceMappingURL=chunk-DXPYFVKG.js.map
146
+ //# sourceMappingURL=chunk-Y7ERTA7D.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/wallet/store.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport * as Keystore from 'ox/Keystore';\nimport { CliError } from '../errors';\nimport { writeFileAtomicExclusive } from '../atomic-json';\nimport { hasCode } from '../errno';\nimport { walletPath } from '../paths';\n\n/** A 0x-prefixed 32-byte hex private key (case-insensitive). */\nexport const PRIVATE_KEY_RE = /^0x[0-9a-f]{64}$/i;\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n\n/**\n * The at-rest shape of a Keystore v3 document (Web3 Secret Storage). Validated\n * structurally on read so an obviously-corrupt keystore fails as\n * WALLET_INVALID_KEY before we ever ask for a passphrase; the real integrity\n * check is the keystore's own MAC, verified by ox at decrypt time. `kdfparams`\n * stays an open object because scrypt and pbkdf2 carry different fields and only\n * ox needs to interpret them.\n */\nconst KeystoreV3Schema = z.object({\n crypto: z.object({\n cipher: z.literal('aes-128-ctr'),\n ciphertext: z.string(),\n cipherparams: z.object({ iv: z.string() }),\n kdf: z.enum(['scrypt', 'pbkdf2']),\n kdfparams: z.record(z.string(), z.unknown()),\n mac: z.string(),\n }),\n id: z.string(),\n version: z.literal(3),\n});\n\n/** The wallet-record schema this build writes and reads. Anything higher on disk\n * was written by a newer CLI; see `readWalletRecord`. */\nexport const WALLET_SCHEMA_VERSION = 2;\n\n/**\n * The persisted wallet record (schema v2). The private key is NEVER stored in\n * cleartext: `keystore` is a Keystore v3 document (scrypt + AES-128-CTR) and the\n * key is recovered only by decrypting it with the wallet passphrase. `address`\n * stays top-level in cleartext ON PURPOSE so `show`/`balance` keep working\n * without a passphrase; signing decrypts, and so does `doctor` when it can reach\n * a passphrase without prompting. The `provider`\n * discriminator keeps the schema from implying every future wallet embeds a\n * keystore. Validated on read (a corrupt file is WALLET_INVALID_KEY, never a\n * silent partial parse).\n */\nexport const WalletRecordSchema = z.object({\n schemaVersion: z.literal(WALLET_SCHEMA_VERSION),\n provider: z.literal('local'),\n address: z.string().regex(ADDRESS_RE, 'expected a 0x-prefixed 20-byte address'),\n keystore: KeystoreV3Schema,\n createdAt: z.string(),\n});\nexport type WalletRecord = Omit<z.infer<typeof WalletRecordSchema>, 'keystore'> & {\n keystore: Keystore.Keystore;\n};\n\nexport async function walletFileExists(dir: string): Promise<boolean> {\n return (await walletFileMode(dir)) !== null;\n}\n\n/** File permission bits (`mode & 0o777`), or null when the wallet file is absent. */\nexport async function walletFileMode(dir: string): Promise<number | null> {\n try {\n return (await stat(walletPath(dir))).mode & 0o777;\n } catch (err) {\n if (isNotFound(err)) return null;\n throw err;\n }\n}\n\n/** Read + validate the wallet record; null when absent, WALLET_INVALID_KEY when corrupt. */\nexport async function readWalletRecord(dir: string): Promise<WalletRecord | null> {\n const path = walletPath(dir);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNotFound(err)) return null;\n throw new CliError('WALLET_INVALID_KEY', `Could not read the wallet file at ${path}.`, {\n fix: `Check file permissions on ${path}.`,\n cause: err,\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new CliError('WALLET_INVALID_KEY', `The wallet file at ${path} is not valid JSON.`, {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n cause: err,\n });\n }\n // A pre-encryption record (schema v1 stored the raw key). There is no in-place\n // migration: the old key must be swept and a fresh encrypted wallet created.\n if (isPreEncryptionRecord(json)) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} predates encrypted storage.`,\n {\n fix: `Move ${path} aside and run \\`tenjin wallet create\\`; sweep any funds from the old address first.`,\n },\n );\n }\n // A NEWER CLI's record is a downgrade, not a corruption, and must be caught\n // BEFORE the generic parse failure below: that failure says to move the file\n // aside and run `wallet create`, which on a downgrade abandons a funded wallet.\n // CONTRACT_MISMATCH is the API layer's code for a schema version skew.\n const newer = newerSchemaVersion(json);\n if (newer !== null) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The wallet file at ${path} was written by a newer tenjin-cli (wallet schema v${newer}; this build reads v${WALLET_SCHEMA_VERSION}).`,\n {\n fix: 'Upgrade with `npm i -g tenjin-cli`. Do not delete or recreate the wallet: the newer CLI still reads this one, and the funds are on the address it holds.',\n },\n );\n }\n const parsed = WalletRecordSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} is not a valid wallet record.`,\n {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n details: parsed.error.issues,\n },\n );\n }\n return parsed.data as WalletRecord;\n}\n\n/**\n * The one WALLET_EXISTS error, shared by the create pre-check and the exclusive\n * write's race loser so the two surfaces can never drift apart.\n */\nexport function walletExistsError(dir: string, cause?: unknown): CliError {\n const path = walletPath(dir);\n return new CliError('WALLET_EXISTS', `A wallet already exists at ${path}.`, {\n fix: `Run \\`tenjin wallet create --replace\\` to archive it and create a new one: its keystore is parked beside the new wallet and its passphrase stays preserved in the OS credential store (service tenjin-cli, account = its address), so its funds remain reachable. That passphrase is unrecoverable — never delete the credential-store entry, or the wallet's funds are stranded.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n\n/**\n * Persist a validated record at 0600 in a 0700 dir, NO-CLOBBER. The exclusive\n * write — not an earlier existence check — is the authority: two concurrent\n * `create` runs can both pass a pre-check, but only one can win the atomic\n * commit; the loser surfaces as WALLET_EXISTS instead of silently overwriting\n * (and losing) a non-recoverable key.\n */\nexport async function writeWalletRecord(dir: string, record: WalletRecord): Promise<void> {\n const validated = WalletRecordSchema.parse(record);\n const path = walletPath(dir);\n try {\n await writeFileAtomicExclusive(path, `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n if (hasCode(err, 'EEXIST')) throw walletExistsError(dir, err);\n throw err;\n }\n}\n\n/** The schema version of a record from a future CLI, or null when this build reads it. */\nfunction newerSchemaVersion(json: unknown): number | null {\n if (typeof json !== 'object' || json === null) return null;\n const v = (json as Record<string, unknown>).schemaVersion;\n // Integral only: `2.5` is not a schema we will ship, and calling it \"from the\n // future\" would send the operator into an upgrade loop. Integrality rather than\n // SAFE integrality, because an absurd-but-whole version is still a version, and\n // the alternative branch tells them to move the wallet aside and recreate it.\n return typeof v === 'number' && Number.isInteger(v) && v > WALLET_SCHEMA_VERSION ? v : null;\n}\n\n/** A cleartext-key record from before encrypted storage: schema v1 or a bare `privateKey`. */\nfunction isPreEncryptionRecord(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) return false;\n const rec = json as Record<string, unknown>;\n return rec.schemaVersion === 1 || 'privateKey' in rec;\n}\n\nfunction isNotFound(err: unknown): boolean {\n return hasCode(err, 'ENOENT');\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,UAAU,YAAY;AASxB,IAAM,iBAAiB;AAC9B,IAAM,aAAa;AAUnB,IAAM,mBAAmB,iBAAE,OAAO;AAAA,EAChC,QAAQ,iBAAE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