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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (246) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +149 -264
  3. package/dist/{_esm-FEASBWRP.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/alive-3J3CHOQP.js +21 -0
  5. package/dist/{ccip-NQXCEK2U.js → ccip-7RMRLAGV.js} +4 -4
  6. package/dist/{ccip-XR5NE5QK.js → ccip-NLCSCHKI.js} +5 -5
  7. package/dist/chunk-2SNUOHAT.js +75 -0
  8. package/dist/chunk-2SNUOHAT.js.map +1 -0
  9. package/dist/chunk-3O2BQIF6.js +2227 -0
  10. package/dist/chunk-3O2BQIF6.js.map +1 -0
  11. package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
  12. package/dist/chunk-5LJCEMFD.js +12700 -0
  13. package/dist/chunk-5LJCEMFD.js.map +1 -0
  14. package/dist/chunk-6W5GYG3W.js +128 -0
  15. package/dist/chunk-6W5GYG3W.js.map +1 -0
  16. package/dist/chunk-7EKYXMUO.js +7536 -0
  17. package/dist/chunk-7EKYXMUO.js.map +1 -0
  18. package/dist/chunk-7QKHZQKW.js +1680 -0
  19. package/dist/chunk-7QKHZQKW.js.map +1 -0
  20. package/dist/chunk-A36LQPHV.js +29 -0
  21. package/dist/chunk-A36LQPHV.js.map +1 -0
  22. package/dist/chunk-AEG2PXBP.js +192 -0
  23. package/dist/chunk-AEG2PXBP.js.map +1 -0
  24. package/dist/chunk-AKWGE6JQ.js +49 -0
  25. package/dist/chunk-AKWGE6JQ.js.map +1 -0
  26. package/dist/chunk-AWFUPKTM.js +238 -0
  27. package/dist/chunk-AWFUPKTM.js.map +1 -0
  28. package/dist/{chunk-UGX7YPX2.js → chunk-AWQPGIR6.js} +7 -9
  29. package/dist/{chunk-UGX7YPX2.js.map → chunk-AWQPGIR6.js.map} +1 -1
  30. package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
  31. package/dist/chunk-EBVIKMCH.js +108 -0
  32. package/dist/chunk-EBVIKMCH.js.map +1 -0
  33. package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
  34. package/dist/{chunk-S3IGX57D.js → chunk-EL56RW2J.js} +166 -7237
  35. package/dist/chunk-EL56RW2J.js.map +1 -0
  36. package/dist/chunk-HE2MS4QO.js +256 -0
  37. package/dist/chunk-HE2MS4QO.js.map +1 -0
  38. package/dist/{chunk-CYOF7ROH.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-IOODYAXL.js +324 -0
  40. package/dist/chunk-IOODYAXL.js.map +1 -0
  41. package/dist/chunk-JMM6YE7J.js +2174 -0
  42. package/dist/chunk-JMM6YE7J.js.map +1 -0
  43. package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
  44. package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
  45. package/dist/chunk-KHE6L6TD.js +416 -0
  46. package/dist/chunk-KHE6L6TD.js.map +1 -0
  47. package/dist/chunk-KOGZDMHO.js +21 -0
  48. package/dist/chunk-KOGZDMHO.js.map +1 -0
  49. package/dist/chunk-KYFZTGMC.js +237 -0
  50. package/dist/chunk-KYFZTGMC.js.map +1 -0
  51. package/dist/chunk-LFZJM56J.js +159 -0
  52. package/dist/chunk-LFZJM56J.js.map +1 -0
  53. package/dist/chunk-LHHMV4GU.js +27 -0
  54. package/dist/chunk-LHHMV4GU.js.map +1 -0
  55. package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
  56. package/dist/chunk-MEFB5KHA.js.map +1 -0
  57. package/dist/{chunk-NCE5NSN6.js → chunk-N35E6CM2.js} +140 -10
  58. package/dist/chunk-N35E6CM2.js.map +1 -0
  59. package/dist/chunk-NZIP4PA2.js +114 -0
  60. package/dist/chunk-NZIP4PA2.js.map +1 -0
  61. package/dist/chunk-O2FRQ2L2.js +168 -0
  62. package/dist/chunk-O2FRQ2L2.js.map +1 -0
  63. package/dist/chunk-OK2TDZQU.js +404 -0
  64. package/dist/chunk-OK2TDZQU.js.map +1 -0
  65. package/dist/chunk-ORWL5BSN.js +269 -0
  66. package/dist/chunk-ORWL5BSN.js.map +1 -0
  67. package/dist/{chunk-Z6MFJV5Z.js → chunk-OSYTBCUC.js} +850 -499
  68. package/dist/chunk-OSYTBCUC.js.map +1 -0
  69. package/dist/chunk-P7LABKCW.js +90 -0
  70. package/dist/chunk-P7LABKCW.js.map +1 -0
  71. package/dist/chunk-PAYV4XUA.js +151 -0
  72. package/dist/chunk-PAYV4XUA.js.map +1 -0
  73. package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
  74. package/dist/chunk-QUVVWYJW.js +112 -0
  75. package/dist/chunk-QUVVWYJW.js.map +1 -0
  76. package/dist/chunk-RAULEAZ6.js +228 -0
  77. package/dist/chunk-RAULEAZ6.js.map +1 -0
  78. package/dist/chunk-S4SAZ7OD.js +30 -0
  79. package/dist/chunk-S4SAZ7OD.js.map +1 -0
  80. package/dist/chunk-SJLTEINJ.js +117 -0
  81. package/dist/chunk-SJLTEINJ.js.map +1 -0
  82. package/dist/chunk-SPAVAYSW.js +125 -0
  83. package/dist/chunk-SPAVAYSW.js.map +1 -0
  84. package/dist/chunk-TTBKWWTV.js +1605 -0
  85. package/dist/chunk-TTBKWWTV.js.map +1 -0
  86. package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
  87. package/dist/chunk-U6YQ6FRI.js +378 -0
  88. package/dist/chunk-U6YQ6FRI.js.map +1 -0
  89. package/dist/chunk-VFMQTSXG.js +29 -0
  90. package/dist/chunk-VFMQTSXG.js.map +1 -0
  91. package/dist/chunk-VUFAK2LW.js +115 -0
  92. package/dist/chunk-VUFAK2LW.js.map +1 -0
  93. package/dist/chunk-VZGAONSJ.js +194 -0
  94. package/dist/chunk-VZGAONSJ.js.map +1 -0
  95. package/dist/{chunk-OYMYCW7J.js → chunk-WO5BJNIB.js} +682 -53
  96. package/dist/chunk-WO5BJNIB.js.map +1 -0
  97. package/dist/chunk-WVUSXNIE.js +39 -0
  98. package/dist/chunk-WVUSXNIE.js.map +1 -0
  99. package/dist/chunk-XKESD27X.js +10 -0
  100. package/dist/chunk-XKESD27X.js.map +1 -0
  101. package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
  102. package/dist/{chunk-XJIW7USF.js → chunk-YFQOA5AU.js} +118 -9
  103. package/dist/chunk-YFQOA5AU.js.map +1 -0
  104. package/dist/chunk-YHKXNYTB.js +105 -0
  105. package/dist/chunk-YHKXNYTB.js.map +1 -0
  106. package/dist/{cli-SBXI5AMS.js → cli-O5SN7ZJ4.js} +382 -214
  107. package/dist/cli-O5SN7ZJ4.js.map +1 -0
  108. package/dist/config-OJQI27LT.js +45 -0
  109. package/dist/dist-3LOO6M4U.js +2842 -0
  110. package/dist/dist-3LOO6M4U.js.map +1 -0
  111. package/dist/doctor-IQQJHGGM.js +590 -0
  112. package/dist/doctor-IQQJHGGM.js.map +1 -0
  113. package/dist/env-proxy-XL4P73MZ.js +15 -0
  114. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  115. package/dist/fund-WEV6DMTD.js +365 -0
  116. package/dist/fund-WEV6DMTD.js.map +1 -0
  117. package/dist/hook-command-D2P3ILRV.js +32 -0
  118. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  119. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
  120. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  121. package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
  122. package/dist/index.js +21 -2
  123. package/dist/index.js.map +1 -1
  124. package/dist/install-TUCRF32I.js +60 -0
  125. package/dist/install-identity-WHPNMNMQ.js +26 -0
  126. package/dist/install-wallet-MA27FTQ5.js +113 -0
  127. package/dist/install-wallet-MA27FTQ5.js.map +1 -0
  128. package/dist/mcp-QML7ZMPH.js +13427 -0
  129. package/dist/mcp-QML7ZMPH.js.map +1 -0
  130. package/dist/package-LGKYOEPV.js +37 -0
  131. package/dist/package-LGKYOEPV.js.map +1 -0
  132. package/dist/paths-POPTXJO6.js +61 -0
  133. package/dist/paths-POPTXJO6.js.map +1 -0
  134. package/dist/pay-2C2UBBXJ.js +51 -0
  135. package/dist/pay-2C2UBBXJ.js.map +1 -0
  136. package/dist/payments-C44QUFXU.js +106 -0
  137. package/dist/payments-C44QUFXU.js.map +1 -0
  138. package/dist/redact-6W23GGJC.js +15 -0
  139. package/dist/redact-6W23GGJC.js.map +1 -0
  140. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
  141. package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
  142. package/dist/send-KVJX4XIR.js +222 -0
  143. package/dist/send-KVJX4XIR.js.map +1 -0
  144. package/dist/status-S7C3WMSH.js +115 -0
  145. package/dist/status-S7C3WMSH.js.map +1 -0
  146. package/dist/status-line-YR2T5HC4.js +86 -0
  147. package/dist/status-line-YR2T5HC4.js.map +1 -0
  148. package/dist/uninstall-HY6LKIIT.js +149 -0
  149. package/dist/uninstall-HY6LKIIT.js.map +1 -0
  150. package/dist/update-OJV22LR3.js +36 -0
  151. package/dist/update-OJV22LR3.js.map +1 -0
  152. package/dist/usdc-JK4RRFFQ.js +39 -0
  153. package/dist/usdc-JK4RRFFQ.js.map +1 -0
  154. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  155. package/dist/viemAdapter-By13KInL-X2VY6CY3.js.map +1 -0
  156. package/dist/wallet-PD2IMZDU.js +39 -0
  157. package/dist/wallet-PD2IMZDU.js.map +1 -0
  158. package/dist/wallet-kdf-worker.mjs +980 -0
  159. package/docs/agent-permissions.md +180 -0
  160. package/docs/safety-model.md +59 -0
  161. package/docs/troubleshooting.md +13 -0
  162. package/package.json +28 -19
  163. package/LICENSE +0 -21
  164. package/dist/buy-EE6SEXP6.js +0 -1598
  165. package/dist/buy-EE6SEXP6.js.map +0 -1
  166. package/dist/candidate-ERMSYYQZ.js +0 -127
  167. package/dist/candidate-ERMSYYQZ.js.map +0 -1
  168. package/dist/chunk-3OV7E5G5.js +0 -18
  169. package/dist/chunk-3OV7E5G5.js.map +0 -1
  170. package/dist/chunk-4ONXEEQL.js +0 -152
  171. package/dist/chunk-4ONXEEQL.js.map +0 -1
  172. package/dist/chunk-662MSGZB.js +0 -286
  173. package/dist/chunk-662MSGZB.js.map +0 -1
  174. package/dist/chunk-7KUW4MJD.js +0 -59
  175. package/dist/chunk-7KUW4MJD.js.map +0 -1
  176. package/dist/chunk-AWPAWHNX.js +0 -333
  177. package/dist/chunk-AWPAWHNX.js.map +0 -1
  178. package/dist/chunk-DXTQ3CSI.js +0 -171
  179. package/dist/chunk-DXTQ3CSI.js.map +0 -1
  180. package/dist/chunk-ESPNTPQ2.js +0 -207
  181. package/dist/chunk-ESPNTPQ2.js.map +0 -1
  182. package/dist/chunk-FJPLRISB.js +0 -79
  183. package/dist/chunk-FJPLRISB.js.map +0 -1
  184. package/dist/chunk-GO75V3NZ.js +0 -160
  185. package/dist/chunk-GO75V3NZ.js.map +0 -1
  186. package/dist/chunk-JPHG2JW3.js +0 -96
  187. package/dist/chunk-JPHG2JW3.js.map +0 -1
  188. package/dist/chunk-MUBUQVC3.js +0 -67
  189. package/dist/chunk-MUBUQVC3.js.map +0 -1
  190. package/dist/chunk-NCE5NSN6.js.map +0 -1
  191. package/dist/chunk-OYMYCW7J.js.map +0 -1
  192. package/dist/chunk-RY4XKNV3.js +0 -140
  193. package/dist/chunk-RY4XKNV3.js.map +0 -1
  194. package/dist/chunk-S3IGX57D.js.map +0 -1
  195. package/dist/chunk-TLCMMYLY.js +0 -126
  196. package/dist/chunk-TLCMMYLY.js.map +0 -1
  197. package/dist/chunk-UO22YNY4.js +0 -69
  198. package/dist/chunk-UO22YNY4.js.map +0 -1
  199. package/dist/chunk-XHC6FCGZ.js +0 -261
  200. package/dist/chunk-XHC6FCGZ.js.map +0 -1
  201. package/dist/chunk-XJIW7USF.js.map +0 -1
  202. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  203. package/dist/chunk-YN5SHIXQ.js +0 -126
  204. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  205. package/dist/chunk-Z52RA3NC.js +0 -137
  206. package/dist/chunk-Z52RA3NC.js.map +0 -1
  207. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  208. package/dist/cli-SBXI5AMS.js.map +0 -1
  209. package/dist/config-VELDKLHY.js +0 -21
  210. package/dist/doctor-T3KWNNP2.js +0 -20
  211. package/dist/inspect-LMKOXE4Y.js +0 -96
  212. package/dist/inspect-LMKOXE4Y.js.map +0 -1
  213. package/dist/install-LEX3ENQ6.js +0 -387
  214. package/dist/install-LEX3ENQ6.js.map +0 -1
  215. package/dist/lookup-ZPN2Q67N.js +0 -129
  216. package/dist/lookup-ZPN2Q67N.js.map +0 -1
  217. package/dist/outcome-N7TAK6WR.js +0 -66
  218. package/dist/outcome-N7TAK6WR.js.map +0 -1
  219. package/dist/publish-BKBQQAW4.js +0 -1478
  220. package/dist/publish-BKBQQAW4.js.map +0 -1
  221. package/dist/usdc-JIAJW4SV.js +0 -22
  222. package/dist/wallet-CWEMYVIH.js +0 -179
  223. package/dist/wallet-CWEMYVIH.js.map +0 -1
  224. package/dist/wallet-PA54CRBL.js +0 -30
  225. package/skills/tenjin/SKILL.md +0 -199
  226. package/skills/tenjin-publish/SKILL.md +0 -111
  227. package/skills/tenjin-search/SKILL.md +0 -133
  228. /package/dist/{_esm-FEASBWRP.js.map → _esm-CE7KNONL.js.map} +0 -0
  229. /package/dist/{ccip-NQXCEK2U.js.map → alive-3J3CHOQP.js.map} +0 -0
  230. /package/dist/{ccip-XR5NE5QK.js.map → ccip-7RMRLAGV.js.map} +0 -0
  231. /package/dist/{config-VELDKLHY.js.map → ccip-NLCSCHKI.js.map} +0 -0
  232. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
  233. /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
  234. /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
  235. /package/dist/{chunk-CYOF7ROH.js.map → chunk-HPWO4O6S.js.map} +0 -0
  236. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  237. /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
  238. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
  239. /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
  240. /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
  241. /package/dist/{doctor-T3KWNNP2.js.map → config-OJQI27LT.js.map} +0 -0
  242. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
  243. /package/dist/{secp256k1-N3ZHU7LB.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  244. /package/dist/{usdc-JIAJW4SV.js.map → hook-command-D2P3ILRV.js.map} +0 -0
  245. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → install-TUCRF32I.js.map} +0 -0
  246. /package/dist/{wallet-PA54CRBL.js.map → install-identity-WHPNMNMQ.js.map} +0 -0
@@ -0,0 +1,256 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ addressQrLines
4
+ } from "./chunk-ORWL5BSN.js";
5
+ import {
6
+ getUsdcBalance
7
+ } from "./chunk-YFQOA5AU.js";
8
+ import {
9
+ channelCredit
10
+ } from "./chunk-VFMQTSXG.js";
11
+ import {
12
+ commitLocalWallet,
13
+ createLocalWallet,
14
+ describeWallet,
15
+ parkOutgoingWallet,
16
+ prepareLocalWallet,
17
+ resolvePassphraseForCreate,
18
+ resolveWalletProvider,
19
+ restoreParkedWallet,
20
+ verifyAndPreserveOutgoingWallet,
21
+ walletExistsError,
22
+ walletFileExists
23
+ } from "./chunk-OSYTBCUC.js";
24
+ import {
25
+ SUGGESTED_FUND_USD
26
+ } from "./chunk-PAYV4XUA.js";
27
+ import {
28
+ LockTimeoutError,
29
+ withFileLock
30
+ } from "./chunk-MEFB5KHA.js";
31
+ import {
32
+ CliError,
33
+ loadRawConfig,
34
+ resolveSettings,
35
+ toMoney
36
+ } from "./chunk-WO5BJNIB.js";
37
+ import {
38
+ walletPath
39
+ } from "./chunk-SJLTEINJ.js";
40
+
41
+ // src/commands/wallet.ts
42
+ import { mkdir } from "node:fs/promises";
43
+ import { join } from "node:path";
44
+ var FUNDING_LINE = `Fund it with \`tenjin wallet fund ${SUGGESTED_FUND_USD}\`, or send USDC on Base.`;
45
+ var KEY_STORAGE = "encrypted (keystore v3, scrypt)";
46
+ var isWindows = process.platform === "win32";
47
+ async function runWalletCreate(ctx, opts = {}) {
48
+ const {
49
+ address,
50
+ walletPath: path,
51
+ source,
52
+ replaced
53
+ } = await createWalletLocked(ctx.dataDir, opts);
54
+ const warnings = custodyWarnings();
55
+ return {
56
+ data: {
57
+ address,
58
+ walletPath: path,
59
+ provider: "local",
60
+ policyEnforcement: "client-only",
61
+ keyStorage: KEY_STORAGE,
62
+ passphraseSource: source,
63
+ ...replaced !== void 0 ? {
64
+ replaced: {
65
+ address: replaced.address,
66
+ archivedWalletPath: replaced.archivedPath,
67
+ passphrasePreserved: replaced.passphraseLocation,
68
+ ...replaced.unarchivedReason !== void 0 ? { unarchivedReason: replaced.unarchivedReason } : {}
69
+ }
70
+ } : {},
71
+ warnings
72
+ },
73
+ humanLines: [
74
+ `Wallet created: ${address}`,
75
+ `Key stored ${KEY_STORAGE}.`,
76
+ passphraseNote(source, address),
77
+ ...replaced !== void 0 ? replacedNote(replaced, path) : [],
78
+ FUNDING_LINE,
79
+ ...warnings
80
+ ]
81
+ };
82
+ }
83
+ function replacedNote(replaced, activeWalletPath) {
84
+ 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.";
85
+ return [
86
+ `Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,
87
+ `Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,
88
+ `To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \`mv ${replaced.archivedPath} ${activeWalletPath}\`.`
89
+ ];
90
+ }
91
+ async function createWalletLocked(dir, opts) {
92
+ await mkdir(dir, { recursive: true, mode: 448 });
93
+ const lockPath = join(dir, "wallet.create.lock");
94
+ try {
95
+ return await withFileLock(lockPath, async () => {
96
+ const env = opts.env ?? process.env;
97
+ let source = "env";
98
+ const passphraseFor = async (forAddress) => {
99
+ const resolved = await resolvePassphraseForCreate(
100
+ { env, dir, ...opts.passphrase },
101
+ forAddress
102
+ );
103
+ source = resolved.source;
104
+ return resolved.passphrase;
105
+ };
106
+ if (!await walletFileExists(dir)) {
107
+ const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);
108
+ return { address, walletPath: path, source };
109
+ }
110
+ if (opts.replace !== true) throw walletExistsError(dir);
111
+ const preserved = await verifyAndPreserveOutgoingWallet({
112
+ dir,
113
+ env,
114
+ ...opts.passphrase !== void 0 ? { passphrase: opts.passphrase } : {}
115
+ });
116
+ const prepared = await prepareLocalWallet(passphraseFor);
117
+ const archivedPath = await parkOutgoingWallet(dir, preserved.account);
118
+ try {
119
+ const { address, walletPath: path } = await commitLocalWallet(dir, prepared);
120
+ return { address, walletPath: path, source, replaced: { ...preserved, archivedPath } };
121
+ } catch (err) {
122
+ try {
123
+ await restoreParkedWallet(dir, archivedPath);
124
+ } catch (restoreErr) {
125
+ throw new CliError(
126
+ "INTERNAL",
127
+ "Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.",
128
+ {
129
+ 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)}\`.`,
130
+ cause: restoreErr
131
+ }
132
+ );
133
+ }
134
+ throw new CliError(
135
+ "INTERNAL",
136
+ "Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.",
137
+ {
138
+ fix: "Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.",
139
+ cause: err
140
+ }
141
+ );
142
+ }
143
+ });
144
+ } catch (err) {
145
+ if (err instanceof LockTimeoutError) {
146
+ throw new CliError("INTERNAL", err.message, {
147
+ fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,
148
+ cause: err
149
+ });
150
+ }
151
+ throw err;
152
+ }
153
+ }
154
+ function passphraseNote(source, address) {
155
+ const account = address.toLowerCase();
156
+ switch (source) {
157
+ case "keychain":
158
+ return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;
159
+ case "dpapi":
160
+ 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.`;
161
+ case "secret-service":
162
+ return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;
163
+ case "env":
164
+ return "Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.";
165
+ case "prompt":
166
+ return "Remember your passphrase: it is required to sign and cannot be recovered.";
167
+ }
168
+ }
169
+ async function runWalletShow(ctx, opts = {}) {
170
+ const provider = resolveWalletProvider(ctx, opts);
171
+ const desc = await describeWallet(provider);
172
+ const {
173
+ walletPath: path,
174
+ keyStorage,
175
+ passphraseSource,
176
+ archivedWallets,
177
+ warnings
178
+ } = await provider.diagnostics();
179
+ const humanLines = [
180
+ `Address: ${desc.address}`,
181
+ ...opts.qr !== false && ctx.io.isTTY && !ctx.flags.json ? addressQrLines(desc.address, ctx.io.stdout) : [],
182
+ `Key source: ${desc.credentialSource}`
183
+ ];
184
+ if (keyStorage !== void 0) humanLines.push(`Key storage: ${keyStorage}`);
185
+ if (passphraseSource !== void 0) humanLines.push(`Passphrase: ${passphraseSource}`);
186
+ if (archivedWallets !== void 0 && archivedWallets.length > 0) {
187
+ humanLines.push(
188
+ `Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(", ")}`
189
+ );
190
+ }
191
+ humanLines.push(...warnings);
192
+ return {
193
+ data: {
194
+ address: desc.address,
195
+ provider: desc.provider,
196
+ credentialSource: desc.credentialSource,
197
+ policyEnforcement: desc.policyEnforcement,
198
+ ...path !== void 0 ? { walletPath: path } : {},
199
+ ...keyStorage !== void 0 ? { keyStorage } : {},
200
+ ...passphraseSource !== void 0 ? { passphraseSource } : {},
201
+ ...archivedWallets !== void 0 && archivedWallets.length > 0 ? { archivedWallets } : {},
202
+ warnings
203
+ },
204
+ humanLines
205
+ };
206
+ }
207
+ async function runWalletBalance(ctx, opts = {}) {
208
+ const provider = resolveWalletProvider(ctx, opts);
209
+ const desc = await describeWallet(provider);
210
+ const config = await loadRawConfig(ctx.dataDir);
211
+ const rpcUrl = resolveSettings({
212
+ config,
213
+ flags: { baseUrl: ctx.flags.baseUrl },
214
+ env: process.env
215
+ }).rpcUrl.value;
216
+ let atomic;
217
+ try {
218
+ atomic = await getUsdcBalance(desc.address, rpcUrl);
219
+ } catch (err) {
220
+ throw new CliError("RPC_ERROR", `Could not read the USDC balance from ${rpcUrl}.`, {
221
+ fix: "Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.",
222
+ cause: err
223
+ });
224
+ }
225
+ const balance = toMoney(atomic.toString());
226
+ const credit = toMoney(
227
+ (await channelCredit(ctx.dataDir, desc.address).catch(() => 0n)).toString()
228
+ );
229
+ return {
230
+ data: { address: desc.address, balance, routingCredit: credit },
231
+ humanLines: [
232
+ `Balance: ${balance.usd} USDC on Base` + (credit.atomic !== "0" ? ` (+${credit.usd} routing credit)` : "")
233
+ ]
234
+ };
235
+ }
236
+ function custodyWarnings() {
237
+ const warnings = [];
238
+ if (hasEnvKey()) {
239
+ warnings.push("TENJIN_WALLET_KEY is set and shadows this file at runtime.");
240
+ }
241
+ if (isWindows) {
242
+ warnings.push("File permissions are not enforced on Windows; the key file is not restricted.");
243
+ }
244
+ return warnings;
245
+ }
246
+ function hasEnvKey() {
247
+ const envKey = process.env.TENJIN_WALLET_KEY;
248
+ return envKey !== void 0 && envKey.length > 0;
249
+ }
250
+
251
+ export {
252
+ runWalletCreate,
253
+ runWalletShow,
254
+ runWalletBalance
255
+ };
256
+ //# sourceMappingURL=chunk-HE2MS4QO.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 { addressQrLines } from '../lib/qr';\nimport { channelCredit } from '../router/channel-credit';\nimport { SUGGESTED_FUND_USD } from '../router/fee';\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 = `Fund it with \\`tenjin wallet fund ${SUGGESTED_FUND_USD}\\`, or send USDC on Base.`;\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 interface WalletShowOptions extends ResolveWalletProviderOptions {\n /** `--no-qr`: print the address without the QR block at a TTY. */\n qr?: boolean;\n}\n\nexport async function runWalletShow(\n ctx: CommandContext,\n opts: WalletShowOptions = {},\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 = [\n `Address: ${desc.address}`,\n ...(opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(desc.address, ctx.io.stdout)\n : []),\n `Key source: ${desc.credentialSource}`,\n ];\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 // THE ROUTING CREDIT IS STILL THE USER'S: a deposit moved it off the wallet\n // into the routing channel, where the next routing fees draw from it.\n const credit = toMoney(\n (await channelCredit(ctx.dataDir, desc.address).catch(() => 0n)).toString(),\n );\n return {\n data: { address: desc.address, balance, routingCredit: credit },\n humanLines: [\n `Balance: ${balance.usd} USDC on Base` +\n (credit.atomic !== '0' ? ` (+${credit.usd} routing credit)` : ''),\n ],\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,SAAS,YAAY;AA2BrB,IAAM,eAAe,qCAAqC,kBAAkB;AAC5E,IAAM,cAAc;AACpB,IAAM,YAAY,QAAQ,aAAa;AAsBvC,eAAsB,gBACpB,KACA,OAA4B,CAAC,GACL;AACxB,QAAM;AAAA,IACJ;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,EACF,IAAI,MAAM,mBAAmB,IAAI,SAAS,IAAI;AAE9C,QAAM,WAAW,gBAAgB;AACjC,SAAO;AAAA,IACL,MAAM;AAAA,MACJ;AAAA,MACA,YAAY;AAAA,MACZ,UAAU;AAAA,MACV,mBAAmB;AAAA,MACnB,YAAY;AAAA,MACZ,kBAAkB;AAAA,MAClB,GAAI,aAAa,SACb;AAAA,QACE,UAAU;AAAA,UACR,SAAS,SAAS;AAAA,UAClB,oBAAoB,SAAS;AAAA,UAC7B,qBAAqB,SAAS;AAAA,UAC9B,GAAI,SAAS,qBAAqB,SAC9B,EAAE,kBAAkB,SAAS,iBAAiB,IAC9C,CAAC;AAAA,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
7
7
  t
8
- } from "./chunk-HSDCI7OV.js";
8
+ } from "./chunk-XZKD7DIF.js";
9
9
 
10
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
11
  var a2 = /* @__PURE__ */ t({ createViemConfig: () => s });
@@ -28,7 +28,7 @@ var o = [{
28
28
  async function s(e) {
29
29
  let a3;
30
30
  try {
31
- a3 = await import("./_esm-FEASBWRP.js");
31
+ a3 = await import("./_esm-CE7KNONL.js");
32
32
  } catch {
33
33
  throw new r(i.MISSING_PROVIDER_LIBRARY, "viem installed (npm install viem)", "viem not found");
34
34
  }
@@ -67,4 +67,4 @@ export {
67
67
  a2 as a,
68
68
  s
69
69
  };
70
- //# sourceMappingURL=chunk-CYOF7ROH.js.map
70
+ //# sourceMappingURL=chunk-HPWO4O6S.js.map
@@ -0,0 +1,324 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ CliError,
4
+ PRODUCTION_ORIGIN
5
+ } from "./chunk-WO5BJNIB.js";
6
+ import {
7
+ package_default
8
+ } from "./chunk-VUFAK2LW.js";
9
+
10
+ // src/lib/client-meta.ts
11
+ var TENJIN_PRODUCT = `tenjin-cli/${package_default.version}`;
12
+ var TENJIN_PRODUCT_NAME = "tenjin-cli";
13
+ var WEBSEARCH_HOOK_PRODUCT_NAME = "tenjin-websearch-hook";
14
+ var WEBSEARCH_HOOK_PRODUCT = `${WEBSEARCH_HOOK_PRODUCT_NAME}/${package_default.version}`;
15
+ var OWN_PRODUCT_NAMES = [TENJIN_PRODUCT_NAME, WEBSEARCH_HOOK_PRODUCT_NAME];
16
+ var TENJIN_COMMENT = `(+${PRODUCTION_ORIGIN})`;
17
+ var TENJIN_USER_AGENT = `${TENJIN_PRODUCT} ${TENJIN_COMMENT}`;
18
+ var WEBSEARCH_HOOK_USER_AGENT = `${WEBSEARCH_HOOK_PRODUCT} ${TENJIN_COMMENT}`;
19
+ var CALLER_USER_AGENT_ENV = "TENJIN_CALLER_USER_AGENT";
20
+ var USER_AGENT_MAX_LENGTH = 512;
21
+ var PRODUCT_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:\/[!#$%&'*+.^_`|~0-9A-Za-z-]+)?$/;
22
+ var PRINTABLE_ASCII_RE = /^[\x20-\x7e]*$/;
23
+ function composeUserAgent(input = {}) {
24
+ const product = input.product ?? TENJIN_PRODUCT;
25
+ const alone = `${product} ${TENJIN_COMMENT}`;
26
+ const raw = input.caller ?? (input.env ?? process.env)[CALLER_USER_AGENT_ENV];
27
+ const products = callerProducts(raw);
28
+ if (products.length === 0) return alone;
29
+ const composed = `${product} ${products.join(" ")} ${TENJIN_COMMENT}`;
30
+ return composed.length <= USER_AGENT_MAX_LENGTH ? composed : alone;
31
+ }
32
+ function callerProducts(raw) {
33
+ if (raw === void 0 || !PRINTABLE_ASCII_RE.test(raw)) return [];
34
+ const tokens = raw.split(" ").filter((token) => token.length > 0 && !isOwnIdentity(token));
35
+ return tokens.every((token) => PRODUCT_RE.test(token)) ? tokens : [];
36
+ }
37
+ function isOwnIdentity(token) {
38
+ const lower = token.toLowerCase();
39
+ if (lower === TENJIN_COMMENT.toLowerCase()) return true;
40
+ return OWN_PRODUCT_NAMES.some((name) => {
41
+ const own = name.toLowerCase();
42
+ return lower === own || lower.startsWith(`${own}/`);
43
+ });
44
+ }
45
+
46
+ // src/lib/http.ts
47
+ var SHELF_BYPASS_HEADER = "x-vercel-protection-bypass";
48
+ function shelfBypassHeaders(url, bypass) {
49
+ if (bypass === void 0 || bypass.secret.length === 0) return {};
50
+ let origin;
51
+ try {
52
+ origin = new URL(url).origin;
53
+ } catch {
54
+ return {};
55
+ }
56
+ if (origin !== bypass.origin) return {};
57
+ return { [SHELF_BYPASS_HEADER]: bypass.secret };
58
+ }
59
+ function carriesBypassKey(headers) {
60
+ return Object.keys(headers).some((name) => name.toLowerCase() === SHELF_BYPASS_HEADER);
61
+ }
62
+ var INSTALL_ID_HEADER = "tenjin-install-id";
63
+ var tenjinIdentity;
64
+ function setTenjinIdentity(identity) {
65
+ tenjinIdentity = identity;
66
+ }
67
+ async function tenjinIdentityHeaders(url) {
68
+ const identity = tenjinIdentity;
69
+ if (identity === void 0) return {};
70
+ try {
71
+ if (!(await identity.origins()).includes(new URL(url).origin)) return {};
72
+ const id = await identity.installId();
73
+ return id !== void 0 ? { [INSTALL_ID_HEADER]: id } : {};
74
+ } catch {
75
+ return {};
76
+ }
77
+ }
78
+ function applyUserAgent(headers, callerUserAgent) {
79
+ headers.set("user-agent", composeUserAgent({ caller: callerUserAgent }));
80
+ return headers;
81
+ }
82
+ var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
83
+ "sign-in-with-x",
84
+ "payment-signature",
85
+ "x-payment",
86
+ "tenjin-session-delegation"
87
+ ]);
88
+ function carriesSignedMaterial(headers) {
89
+ return Object.keys(headers).some((name) => CREDENTIAL_HEADERS.has(name.toLowerCase()));
90
+ }
91
+ function timeoutFailure(url, timeoutMs) {
92
+ return {
93
+ ok: false,
94
+ kind: "timeout",
95
+ message: `Request to ${url} timed out after ${timeoutMs}ms`
96
+ };
97
+ }
98
+ var MAX_BINARY_BODY_BYTES = 200 * 1024 * 1024;
99
+ async function readCapped(res, max) {
100
+ const declared = Number(res.headers.get("content-length") ?? "0");
101
+ if (Number.isFinite(declared) && declared > max) {
102
+ await res.body?.cancel().catch(() => void 0);
103
+ return null;
104
+ }
105
+ if (res.body === null) return new Uint8Array();
106
+ const reader = res.body.getReader();
107
+ const chunks = [];
108
+ let size = 0;
109
+ for (; ; ) {
110
+ const { done, value } = await reader.read();
111
+ if (done) break;
112
+ size += value.byteLength;
113
+ if (size > max) {
114
+ await reader.cancel().catch(() => void 0);
115
+ return null;
116
+ }
117
+ chunks.push(value);
118
+ }
119
+ return new Uint8Array(Buffer.concat(chunks));
120
+ }
121
+ function isBinaryContentType(contentType) {
122
+ const type = (contentType ?? "").split(";")[0].trim().toLowerCase();
123
+ if (type.length === 0) return false;
124
+ if (type.startsWith("text/")) return false;
125
+ return !/(?:json|xml|javascript|ecmascript|yaml|x-www-form-urlencoded)/.test(type);
126
+ }
127
+ function prepareRequest(url, opts) {
128
+ try {
129
+ let body;
130
+ const merged = new Headers({ ...opts.headers, ...shelfBypassHeaders(url, opts.bypass) });
131
+ if (opts.jsonBody !== void 0) {
132
+ body = JSON.stringify(opts.jsonBody);
133
+ merged.set("content-type", "application/json");
134
+ } else if (opts.rawBody !== void 0) {
135
+ body = opts.rawBody;
136
+ }
137
+ const wantsAccept = opts.method === "POST" || opts.method === "PUT" || body !== void 0;
138
+ if (wantsAccept && !merged.has("accept")) merged.set("accept", "application/json");
139
+ const headers = Object.fromEntries(applyUserAgent(merged, opts.callerUserAgent).entries());
140
+ const signed = carriesSignedMaterial(headers);
141
+ const bypassed = carriesBypassKey(headers);
142
+ return {
143
+ ok: true,
144
+ headers,
145
+ body,
146
+ signed,
147
+ bypassed,
148
+ pinned: signed || bypassed || opts.blockRedirects === true
149
+ };
150
+ } catch (err) {
151
+ return {
152
+ ok: false,
153
+ kind: "network",
154
+ message: `Request to ${url} failed: ${errorMessage(err)}`
155
+ };
156
+ }
157
+ }
158
+ async function httpRequest(url, opts) {
159
+ const doFetch = opts.fetchImpl ?? fetch;
160
+ const controller = new AbortController();
161
+ let timedOut = false;
162
+ const timer = setTimeout(() => {
163
+ timedOut = true;
164
+ controller.abort();
165
+ }, opts.timeoutMs);
166
+ const signal = opts.signal === void 0 ? controller.signal : AbortSignal.any([controller.signal, opts.signal]);
167
+ try {
168
+ const prepared = prepareRequest(url, opts);
169
+ if (!prepared.ok) return prepared;
170
+ const { headers, body, signed, bypassed, pinned } = prepared;
171
+ let res;
172
+ try {
173
+ res = await doFetch(url, {
174
+ method: opts.method ?? "GET",
175
+ headers: opts.anonymous === true ? headers : { ...headers, ...await tenjinIdentityHeaders(url) },
176
+ body,
177
+ signal,
178
+ ...pinned ? { redirect: "manual" } : {}
179
+ });
180
+ } catch (err) {
181
+ if (timedOut) return timeoutFailure(url, opts.timeoutMs);
182
+ if (isHeaderOverflow(err)) return oversizedHeaderFailure(url);
183
+ const transport = transportFailure(err);
184
+ return {
185
+ ok: false,
186
+ kind: "network",
187
+ message: `Request to ${url} failed: ${errorMessage(err)}`,
188
+ ...transport !== void 0 ? { transport } : {}
189
+ };
190
+ }
191
+ const requestId = res.headers.get("x-request-id") ?? void 0;
192
+ if (pinned && res.status >= 300 && res.status < 400) {
193
+ return {
194
+ ok: false,
195
+ kind: "blocked-redirect",
196
+ status: res.status,
197
+ ...requestId !== void 0 ? { requestId } : {},
198
+ message: signed ? `Request to ${url} was redirected (${res.status}) while carrying a signed header; refusing to follow it, because the signature is bound to the configured origin.` : bypassed ? `Request to ${url} was redirected (${res.status}) while carrying the team shelf's bypass key; refusing to follow it, because the key opens only the configured origin.` : `Request to ${url} was redirected (${res.status}); refusing to follow it, because the response must come from the configured origin.`
199
+ };
200
+ }
201
+ let text;
202
+ let bytes;
203
+ try {
204
+ if (opts.binaryBody === true && isBinaryContentType(res.headers.get("content-type") ?? "")) {
205
+ const read = await readCapped(res, opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES);
206
+ if (read === null) {
207
+ return {
208
+ ok: false,
209
+ kind: "network",
210
+ status: res.status,
211
+ ...requestId !== void 0 ? { requestId } : {},
212
+ message: `Request to ${url} returned a file over the ${Math.round((opts.maxBinaryBytes ?? MAX_BINARY_BODY_BYTES) / 1048576)} MB cap; it was not kept.`
213
+ };
214
+ }
215
+ bytes = read;
216
+ text = "";
217
+ } else {
218
+ text = await res.text();
219
+ }
220
+ } catch (err) {
221
+ if (timedOut) {
222
+ return {
223
+ ...timeoutFailure(url, opts.timeoutMs),
224
+ header: (name) => res.headers.get(name) ?? void 0
225
+ };
226
+ }
227
+ return {
228
+ ok: false,
229
+ kind: "network",
230
+ status: res.status,
231
+ ...requestId !== void 0 ? { requestId } : {},
232
+ message: `Request to ${url} failed while reading the response body: ${errorMessage(err)}`
233
+ };
234
+ }
235
+ let json;
236
+ if (text.length > 0) {
237
+ try {
238
+ json = JSON.parse(text);
239
+ } catch {
240
+ json = void 0;
241
+ }
242
+ }
243
+ return {
244
+ ok: true,
245
+ status: res.status,
246
+ header: (name) => res.headers.get(name) ?? void 0,
247
+ json,
248
+ text,
249
+ ...bytes !== void 0 ? { bytes } : {},
250
+ ...requestId !== void 0 ? { requestId } : {}
251
+ };
252
+ } finally {
253
+ clearTimeout(timer);
254
+ }
255
+ }
256
+ function fetchFailureToCliError(failure, opts = {}) {
257
+ const code = failure.kind === "network" || failure.kind === "timeout" ? "NETWORK_ERROR" : failure.kind === "invalid-json" ? "CONTRACT_MISMATCH" : failure.kind === "oversized-header" ? "CHALLENGE_TOO_LARGE" : "API_UNREACHABLE";
258
+ const fix = opts.fix ?? (failure.kind === "oversized-header" ? "Raising `--max-http-header-size` on the node process that runs this CLI would let the header be read; that is an operator decision, not a default this build changes." : void 0);
259
+ return new CliError(code, failure.message, {
260
+ ...fix !== void 0 ? { fix } : {},
261
+ ...opts.details !== void 0 ? { details: opts.details } : {}
262
+ });
263
+ }
264
+ function errorMessage(err) {
265
+ return err instanceof Error ? err.message : String(err);
266
+ }
267
+ function isHeaderOverflow(err) {
268
+ const seen = [err, err?.cause];
269
+ return seen.some((candidate) => {
270
+ if (candidate === null || typeof candidate !== "object") return false;
271
+ const code = candidate.code;
272
+ if (code === "UND_ERR_HEADERS_OVERFLOW" || code === "HPE_HEADER_OVERFLOW") return true;
273
+ const message = candidate.message;
274
+ return typeof message === "string" && /headers overflow|header overflow/i.test(message);
275
+ });
276
+ }
277
+ var DNS_CODES = /* @__PURE__ */ new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_FAIL", "EAI_NODATA", "EAI_NONAME"]);
278
+ var CONNECT_CODES = /* @__PURE__ */ new Set([
279
+ "ECONNREFUSED",
280
+ "ECONNRESET",
281
+ "EHOSTUNREACH",
282
+ "ENETUNREACH",
283
+ "ETIMEDOUT",
284
+ "UND_ERR_CONNECT_TIMEOUT",
285
+ "UND_ERR_SOCKET"
286
+ ]);
287
+ var TLS_CODE = /^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_|SELF_SIGNED_|DEPTH_ZERO_)/;
288
+ var PROXY_REFUSAL = /Proxy response \((\d{3})\)/;
289
+ function transportFailure(err) {
290
+ let link = err;
291
+ for (let depth = 0; depth < 5 && link !== null && typeof link === "object"; depth += 1) {
292
+ const { code, message, cause } = link;
293
+ const proxy = typeof message === "string" ? PROXY_REFUSAL.exec(message) : null;
294
+ if (proxy !== null) return { layer: "proxy", proxyStatus: Number(proxy[1]) };
295
+ if (typeof code === "string") {
296
+ if (DNS_CODES.has(code)) return { layer: "dns", code };
297
+ if (TLS_CODE.test(code)) return { layer: "tls", code };
298
+ if (CONNECT_CODES.has(code)) return { layer: "connect", code };
299
+ }
300
+ link = cause;
301
+ }
302
+ return void 0;
303
+ }
304
+ function oversizedHeaderFailure(url) {
305
+ let origin = url;
306
+ try {
307
+ origin = new URL(url).origin;
308
+ } catch {
309
+ }
310
+ return {
311
+ ok: false,
312
+ kind: "oversized-header",
313
+ message: `${origin} answered with a response header block larger than this process will read. An x402 challenge travels in a header, and a seller that embeds its whole output schema in one can exceed the limit, so the response could not be read.`
314
+ };
315
+ }
316
+
317
+ export {
318
+ composeUserAgent,
319
+ setTenjinIdentity,
320
+ isBinaryContentType,
321
+ httpRequest,
322
+ fetchFailureToCliError
323
+ };
324
+ //# sourceMappingURL=chunk-IOODYAXL.js.map