@absol-labs/agent 0.10.0 → 0.12.0-rc.1

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 (331) hide show
  1. package/README.md +106 -30
  2. package/dist/capability/invocation-capability.d.ts +20 -8
  3. package/dist/capability/invocation-capability.d.ts.map +1 -1
  4. package/dist/capability/invocation-capability.js.map +1 -1
  5. package/dist/capability/probe-capability.d.ts +225 -0
  6. package/dist/capability/probe-capability.d.ts.map +1 -0
  7. package/dist/capability/probe-capability.js +248 -0
  8. package/dist/capability/probe-capability.js.map +1 -0
  9. package/dist/cli/args.d.ts +11 -0
  10. package/dist/cli/args.d.ts.map +1 -1
  11. package/dist/cli/args.js +23 -0
  12. package/dist/cli/args.js.map +1 -1
  13. package/dist/cli/commands/claim.d.ts.map +1 -1
  14. package/dist/cli/commands/claim.js +21 -5
  15. package/dist/cli/commands/claim.js.map +1 -1
  16. package/dist/cli/commands/close.d.ts.map +1 -1
  17. package/dist/cli/commands/close.js +51 -7
  18. package/dist/cli/commands/close.js.map +1 -1
  19. package/dist/cli/commands/invoke.d.ts +2 -0
  20. package/dist/cli/commands/invoke.d.ts.map +1 -1
  21. package/dist/cli/commands/invoke.js +3 -2
  22. package/dist/cli/commands/invoke.js.map +1 -1
  23. package/dist/cli/commands/mcp.d.ts.map +1 -1
  24. package/dist/cli/commands/mcp.js +15 -2
  25. package/dist/cli/commands/mcp.js.map +1 -1
  26. package/dist/cli/commands/open.d.ts.map +1 -1
  27. package/dist/cli/commands/open.js +121 -15
  28. package/dist/cli/commands/open.js.map +1 -1
  29. package/dist/cli/commands/pay.d.ts +19 -0
  30. package/dist/cli/commands/pay.d.ts.map +1 -0
  31. package/dist/cli/commands/pay.js +355 -0
  32. package/dist/cli/commands/pay.js.map +1 -0
  33. package/dist/cli/commands/reclaim-unverified.d.ts.map +1 -1
  34. package/dist/cli/commands/reclaim-unverified.js +15 -6
  35. package/dist/cli/commands/reclaim-unverified.js.map +1 -1
  36. package/dist/cli/commands/reclaim.d.ts +23 -2
  37. package/dist/cli/commands/reclaim.d.ts.map +1 -1
  38. package/dist/cli/commands/reclaim.js +200 -21
  39. package/dist/cli/commands/reclaim.js.map +1 -1
  40. package/dist/cli/commands/refund.d.ts +13 -0
  41. package/dist/cli/commands/refund.d.ts.map +1 -0
  42. package/dist/cli/commands/refund.js +224 -0
  43. package/dist/cli/commands/refund.js.map +1 -0
  44. package/dist/cli/commands/status.d.ts.map +1 -1
  45. package/dist/cli/commands/status.js +10 -1
  46. package/dist/cli/commands/status.js.map +1 -1
  47. package/dist/cli/commands/streams.js +9 -13
  48. package/dist/cli/commands/streams.js.map +1 -1
  49. package/dist/cli/commands/watch.d.ts.map +1 -1
  50. package/dist/cli/commands/watch.js +2 -1
  51. package/dist/cli/commands/watch.js.map +1 -1
  52. package/dist/cli/config.d.ts +44 -26
  53. package/dist/cli/config.d.ts.map +1 -1
  54. package/dist/cli/config.js +88 -38
  55. package/dist/cli/config.js.map +1 -1
  56. package/dist/cli/deps.d.ts +86 -7
  57. package/dist/cli/deps.d.ts.map +1 -1
  58. package/dist/cli/deps.js +102 -16
  59. package/dist/cli/deps.js.map +1 -1
  60. package/dist/cli/errors.d.ts.map +1 -1
  61. package/dist/cli/errors.js +21 -1
  62. package/dist/cli/errors.js.map +1 -1
  63. package/dist/cli/escape-hatch.d.ts +6 -4
  64. package/dist/cli/escape-hatch.d.ts.map +1 -1
  65. package/dist/cli/escape-hatch.js +6 -2
  66. package/dist/cli/escape-hatch.js.map +1 -1
  67. package/dist/cli/listings.d.ts +18 -0
  68. package/dist/cli/listings.d.ts.map +1 -1
  69. package/dist/cli/listings.js +22 -12
  70. package/dist/cli/listings.js.map +1 -1
  71. package/dist/cli/preflight.d.ts +20 -14
  72. package/dist/cli/preflight.d.ts.map +1 -1
  73. package/dist/cli/preflight.js +34 -20
  74. package/dist/cli/preflight.js.map +1 -1
  75. package/dist/cli/privy.d.ts +83 -0
  76. package/dist/cli/privy.d.ts.map +1 -0
  77. package/dist/cli/privy.js +232 -0
  78. package/dist/cli/privy.js.map +1 -0
  79. package/dist/cli/reclaimability.d.ts +82 -0
  80. package/dist/cli/reclaimability.d.ts.map +1 -0
  81. package/dist/cli/reclaimability.js +80 -0
  82. package/dist/cli/reclaimability.js.map +1 -0
  83. package/dist/cli/run.d.ts +2 -1
  84. package/dist/cli/run.d.ts.map +1 -1
  85. package/dist/cli/run.js +40 -11
  86. package/dist/cli/run.js.map +1 -1
  87. package/dist/cli/scan-range.d.ts +2 -2
  88. package/dist/cli/scan-range.js +2 -2
  89. package/dist/cli/spend-policy.d.ts +60 -0
  90. package/dist/cli/spend-policy.d.ts.map +1 -0
  91. package/dist/cli/spend-policy.js +65 -0
  92. package/dist/cli/spend-policy.js.map +1 -0
  93. package/dist/cli/status.d.ts +3 -1
  94. package/dist/cli/status.d.ts.map +1 -1
  95. package/dist/cli/status.js +15 -3
  96. package/dist/cli/status.js.map +1 -1
  97. package/dist/cli/wallet.d.ts +109 -40
  98. package/dist/cli/wallet.d.ts.map +1 -1
  99. package/dist/cli/wallet.js +109 -44
  100. package/dist/cli/wallet.js.map +1 -1
  101. package/dist/discovery/rate-band.d.ts +74 -0
  102. package/dist/discovery/rate-band.d.ts.map +1 -0
  103. package/dist/discovery/rate-band.js +114 -0
  104. package/dist/discovery/rate-band.js.map +1 -0
  105. package/dist/escrow-generation.d.ts +81 -0
  106. package/dist/escrow-generation.d.ts.map +1 -0
  107. package/dist/escrow-generation.js +76 -0
  108. package/dist/escrow-generation.js.map +1 -0
  109. package/dist/frameworks/agentkit.d.ts +8 -4
  110. package/dist/frameworks/agentkit.d.ts.map +1 -1
  111. package/dist/frameworks/agentkit.js +27 -10
  112. package/dist/frameworks/agentkit.js.map +1 -1
  113. package/dist/frameworks/eliza.d.ts +3 -3
  114. package/dist/frameworks/eliza.d.ts.map +1 -1
  115. package/dist/frameworks/eliza.js +15 -6
  116. package/dist/frameworks/eliza.js.map +1 -1
  117. package/dist/frameworks/langchain.d.ts.map +1 -1
  118. package/dist/frameworks/langchain.js +8 -0
  119. package/dist/frameworks/langchain.js.map +1 -1
  120. package/dist/gateway/caller-auth-gateway.d.ts +91 -4
  121. package/dist/gateway/caller-auth-gateway.d.ts.map +1 -1
  122. package/dist/gateway/caller-auth-gateway.js +184 -7
  123. package/dist/gateway/caller-auth-gateway.js.map +1 -1
  124. package/dist/gateway/http-server.d.ts +121 -1
  125. package/dist/gateway/http-server.d.ts.map +1 -1
  126. package/dist/gateway/http-server.js +474 -5
  127. package/dist/gateway/http-server.js.map +1 -1
  128. package/dist/gateway/probe-auth.d.ts +112 -0
  129. package/dist/gateway/probe-auth.d.ts.map +1 -0
  130. package/dist/gateway/probe-auth.js +127 -0
  131. package/dist/gateway/probe-auth.js.map +1 -0
  132. package/dist/gateway/signed-rate-bounds.d.ts +51 -0
  133. package/dist/gateway/signed-rate-bounds.d.ts.map +1 -0
  134. package/dist/gateway/signed-rate-bounds.js +94 -0
  135. package/dist/gateway/signed-rate-bounds.js.map +1 -0
  136. package/dist/gateway/x402-opener-mode.d.ts +215 -0
  137. package/dist/gateway/x402-opener-mode.d.ts.map +1 -0
  138. package/dist/gateway/x402-opener-mode.js +639 -0
  139. package/dist/gateway/x402-opener-mode.js.map +1 -0
  140. package/dist/index.d.ts +11 -5
  141. package/dist/index.d.ts.map +1 -1
  142. package/dist/index.js +15 -5
  143. package/dist/index.js.map +1 -1
  144. package/dist/mandates/env.d.ts +3 -2
  145. package/dist/mandates/env.d.ts.map +1 -1
  146. package/dist/mandates/env.js +3 -2
  147. package/dist/mandates/env.js.map +1 -1
  148. package/dist/mcp/server.d.ts +100 -0
  149. package/dist/mcp/server.d.ts.map +1 -1
  150. package/dist/mcp/server.js +719 -39
  151. package/dist/mcp/server.js.map +1 -1
  152. package/dist/mcp/service-invoker.d.ts +97 -0
  153. package/dist/mcp/service-invoker.d.ts.map +1 -0
  154. package/dist/mcp/service-invoker.js +167 -0
  155. package/dist/mcp/service-invoker.js.map +1 -0
  156. package/dist/mcp/x402-tools.d.ts +104 -0
  157. package/dist/mcp/x402-tools.d.ts.map +1 -0
  158. package/dist/mcp/x402-tools.js +434 -0
  159. package/dist/mcp/x402-tools.js.map +1 -0
  160. package/dist/network.d.ts +119 -0
  161. package/dist/network.d.ts.map +1 -0
  162. package/dist/network.js +199 -0
  163. package/dist/network.js.map +1 -0
  164. package/dist/sdk/invoke.d.ts +23 -4
  165. package/dist/sdk/invoke.d.ts.map +1 -1
  166. package/dist/sdk/invoke.js +71 -10
  167. package/dist/sdk/invoke.js.map +1 -1
  168. package/dist/wallet/autonomous-wallet-broker.d.ts +3 -0
  169. package/dist/wallet/autonomous-wallet-broker.d.ts.map +1 -1
  170. package/dist/wallet/autonomous-wallet-broker.js +27 -23
  171. package/dist/wallet/autonomous-wallet-broker.js.map +1 -1
  172. package/dist/wallet/autonomous-wallet-protocol.d.ts +8 -2
  173. package/dist/wallet/autonomous-wallet-protocol.d.ts.map +1 -1
  174. package/dist/wallet/autonomous-wallet-protocol.js +9 -2
  175. package/dist/wallet/autonomous-wallet-protocol.js.map +1 -1
  176. package/dist/wallet/autonomous-wallet.d.ts.map +1 -1
  177. package/dist/wallet/autonomous-wallet.js +3 -2
  178. package/dist/wallet/autonomous-wallet.js.map +1 -1
  179. package/dist/wallet/broker-escrows.d.ts +222 -0
  180. package/dist/wallet/broker-escrows.d.ts.map +1 -0
  181. package/dist/wallet/broker-escrows.js +36 -0
  182. package/dist/wallet/broker-escrows.js.map +1 -0
  183. package/dist/wallet/lifecycle.d.ts +21 -5
  184. package/dist/wallet/lifecycle.d.ts.map +1 -1
  185. package/dist/wallet/lifecycle.js +32 -12
  186. package/dist/wallet/lifecycle.js.map +1 -1
  187. package/dist/wallet/privy-broker-server.d.ts.map +1 -1
  188. package/dist/wallet/privy-broker-server.js +31 -26
  189. package/dist/wallet/privy-broker-server.js.map +1 -1
  190. package/dist/wallet/privy-session-broker.d.ts +14 -5
  191. package/dist/wallet/privy-session-broker.d.ts.map +1 -1
  192. package/dist/wallet/privy-session-broker.js +29 -17
  193. package/dist/wallet/privy-session-broker.js.map +1 -1
  194. package/dist/wallet/privy-session-provider.d.ts +3 -1
  195. package/dist/wallet/privy-session-provider.d.ts.map +1 -1
  196. package/dist/wallet/privy-session-provider.js +5 -3
  197. package/dist/wallet/privy-session-provider.js.map +1 -1
  198. package/dist/wallet/provider.d.ts.map +1 -1
  199. package/dist/wallet/provider.js +15 -8
  200. package/dist/wallet/provider.js.map +1 -1
  201. package/dist/x402/facilitator.d.ts +42 -17
  202. package/dist/x402/facilitator.d.ts.map +1 -1
  203. package/dist/x402/facilitator.js +49 -33
  204. package/dist/x402/facilitator.js.map +1 -1
  205. package/dist/x402-buyer/guarded-fetch.d.ts +51 -0
  206. package/dist/x402-buyer/guarded-fetch.d.ts.map +1 -0
  207. package/dist/x402-buyer/guarded-fetch.js +147 -0
  208. package/dist/x402-buyer/guarded-fetch.js.map +1 -0
  209. package/dist/x402-buyer/index.d.ts +10 -0
  210. package/dist/x402-buyer/index.d.ts.map +1 -0
  211. package/dist/x402-buyer/index.js +10 -0
  212. package/dist/x402-buyer/index.js.map +1 -0
  213. package/dist/x402-buyer/pay.d.ts +135 -0
  214. package/dist/x402-buyer/pay.d.ts.map +1 -0
  215. package/dist/x402-buyer/pay.js +336 -0
  216. package/dist/x402-buyer/pay.js.map +1 -0
  217. package/dist/x402-opener/abi.d.ts +684 -0
  218. package/dist/x402-opener/abi.d.ts.map +1 -0
  219. package/dist/x402-opener/abi.js +880 -0
  220. package/dist/x402-opener/abi.js.map +1 -0
  221. package/dist/x402-opener/facilitator-entry.d.ts +3 -0
  222. package/dist/x402-opener/facilitator-entry.d.ts.map +1 -0
  223. package/dist/x402-opener/facilitator-entry.js +37 -0
  224. package/dist/x402-opener/facilitator-entry.js.map +1 -0
  225. package/dist/x402-opener/facilitator-server.d.ts +180 -0
  226. package/dist/x402-opener/facilitator-server.d.ts.map +1 -0
  227. package/dist/x402-opener/facilitator-server.js +696 -0
  228. package/dist/x402-opener/facilitator-server.js.map +1 -0
  229. package/dist/x402-opener/index.d.ts +14 -0
  230. package/dist/x402-opener/index.d.ts.map +1 -0
  231. package/dist/x402-opener/index.js +14 -0
  232. package/dist/x402-opener/index.js.map +1 -0
  233. package/dist/x402-opener/listing-resolver.d.ts +55 -0
  234. package/dist/x402-opener/listing-resolver.d.ts.map +1 -0
  235. package/dist/x402-opener/listing-resolver.js +125 -0
  236. package/dist/x402-opener/listing-resolver.js.map +1 -0
  237. package/dist/x402-opener/refund-relay.d.ts +240 -0
  238. package/dist/x402-opener/refund-relay.d.ts.map +1 -0
  239. package/dist/x402-opener/refund-relay.js +1240 -0
  240. package/dist/x402-opener/refund-relay.js.map +1 -0
  241. package/dist/x402-opener/relayer-queue.d.ts +14 -0
  242. package/dist/x402-opener/relayer-queue.d.ts.map +1 -0
  243. package/dist/x402-opener/relayer-queue.js +18 -0
  244. package/dist/x402-opener/relayer-queue.js.map +1 -0
  245. package/dist/x402-opener/scheme.d.ts +217 -0
  246. package/dist/x402-opener/scheme.d.ts.map +1 -0
  247. package/dist/x402-opener/scheme.js +749 -0
  248. package/dist/x402-opener/scheme.js.map +1 -0
  249. package/dist/x402-opener/terms.d.ts +105 -0
  250. package/dist/x402-opener/terms.d.ts.map +1 -0
  251. package/dist/x402-opener/terms.js +212 -0
  252. package/dist/x402-opener/terms.js.map +1 -0
  253. package/dist/zktls/reclaim.d.ts +2 -2
  254. package/docs/agent-layer.md +13 -8
  255. package/docs/autonomous-privy-wallet.md +188 -0
  256. package/docs/cli.md +342 -53
  257. package/docs/langchain.md +5 -0
  258. package/docs/mcp-hosted.md +4 -3
  259. package/docs/mcp-reference.md +245 -0
  260. package/docs/probe-capability.md +191 -0
  261. package/docs/quickstart.md +54 -5
  262. package/docs/threat-model.md +24 -3
  263. package/docs/x402.md +681 -0
  264. package/package.json +19 -6
  265. package/src/capability/invocation-capability.ts +17 -1
  266. package/src/capability/probe-capability.ts +355 -0
  267. package/src/cli/args.ts +29 -0
  268. package/src/cli/commands/claim.ts +31 -5
  269. package/src/cli/commands/close.ts +56 -7
  270. package/src/cli/commands/invoke.ts +6 -2
  271. package/src/cli/commands/mcp.ts +18 -2
  272. package/src/cli/commands/open.ts +151 -14
  273. package/src/cli/commands/pay.ts +442 -0
  274. package/src/cli/commands/reclaim-unverified.ts +24 -6
  275. package/src/cli/commands/reclaim.ts +274 -19
  276. package/src/cli/commands/refund.ts +277 -0
  277. package/src/cli/commands/status.ts +17 -1
  278. package/src/cli/commands/streams.ts +11 -15
  279. package/src/cli/commands/watch.ts +7 -1
  280. package/src/cli/config.ts +139 -52
  281. package/src/cli/deps.ts +189 -25
  282. package/src/cli/errors.ts +24 -1
  283. package/src/cli/escape-hatch.ts +19 -5
  284. package/src/cli/listings.ts +43 -10
  285. package/src/cli/preflight.ts +36 -21
  286. package/src/cli/privy.ts +398 -0
  287. package/src/cli/reclaimability.ts +154 -0
  288. package/src/cli/run.ts +54 -11
  289. package/src/cli/scan-range.ts +2 -2
  290. package/src/cli/spend-policy.ts +139 -0
  291. package/src/cli/status.ts +14 -1
  292. package/src/cli/wallet.ts +189 -58
  293. package/src/discovery/rate-band.ts +172 -0
  294. package/src/escrow-generation.ts +135 -0
  295. package/src/frameworks/agentkit.ts +45 -11
  296. package/src/frameworks/eliza.ts +27 -5
  297. package/src/frameworks/langchain.ts +14 -0
  298. package/src/gateway/caller-auth-gateway.ts +336 -13
  299. package/src/gateway/http-server.ts +690 -7
  300. package/src/gateway/probe-auth.ts +191 -0
  301. package/src/gateway/signed-rate-bounds.ts +164 -0
  302. package/src/gateway/x402-opener-mode.ts +974 -0
  303. package/src/index.ts +112 -14
  304. package/src/mandates/env.ts +3 -2
  305. package/src/mcp/server.ts +973 -44
  306. package/src/mcp/service-invoker.ts +285 -0
  307. package/src/mcp/x402-tools.ts +621 -0
  308. package/src/network.ts +302 -0
  309. package/src/sdk/invoke.ts +96 -17
  310. package/src/wallet/autonomous-wallet-broker.ts +46 -20
  311. package/src/wallet/autonomous-wallet-protocol.ts +11 -2
  312. package/src/wallet/autonomous-wallet.ts +4 -2
  313. package/src/wallet/broker-escrows.ts +66 -0
  314. package/src/wallet/lifecycle.ts +53 -18
  315. package/src/wallet/privy-broker-server.ts +35 -25
  316. package/src/wallet/privy-session-broker.ts +58 -25
  317. package/src/wallet/privy-session-provider.ts +7 -3
  318. package/src/wallet/provider.ts +20 -15
  319. package/src/x402/facilitator.ts +85 -46
  320. package/src/x402-buyer/guarded-fetch.ts +213 -0
  321. package/src/x402-buyer/index.ts +9 -0
  322. package/src/x402-buyer/pay.ts +517 -0
  323. package/src/x402-opener/abi.ts +881 -0
  324. package/src/x402-opener/facilitator-entry.ts +45 -0
  325. package/src/x402-opener/facilitator-server.ts +1014 -0
  326. package/src/x402-opener/index.ts +13 -0
  327. package/src/x402-opener/listing-resolver.ts +202 -0
  328. package/src/x402-opener/refund-relay.ts +1743 -0
  329. package/src/x402-opener/relayer-queue.ts +18 -0
  330. package/src/x402-opener/scheme.ts +1133 -0
  331. package/src/x402-opener/terms.ts +300 -0
@@ -0,0 +1,398 @@
1
+ import {
2
+ custom,
3
+ isAddress,
4
+ getAddress,
5
+ type Account,
6
+ type Transport,
7
+ } from "viem";
8
+
9
+ import {
10
+ AutonomousWalletError,
11
+ EncryptedFileCredentialStore,
12
+ HttpAutonomousWalletBroker,
13
+ METRIK_AUTONOMOUS_WALLET_BROKER_URL,
14
+ METRIK_WALLET_ENCRYPTION_KEY_ENV,
15
+ createAutonomousWalletProvider,
16
+ createDefaultAutonomousWalletStore,
17
+ type AutonomousWalletCredentialStore,
18
+ type AutonomousWalletRecord,
19
+ } from "../wallet/autonomous-wallet.js";
20
+ import { createPrivySessionProvider } from "../wallet/privy-session-provider.js";
21
+ import { PRIVY_BROKER_CHAIN_ID } from "../wallet/privy-session-broker.js";
22
+ import { defaultNetwork } from "../network.js";
23
+ import {
24
+ createPrivyEmbeddedAccount,
25
+ type PrivyEip1193Provider,
26
+ } from "../wallet/provider.js";
27
+ import { configError } from "./errors.js";
28
+
29
+ /**
30
+ * The CLI's two Privy wallet shapes.
31
+ *
32
+ * Privy differs from the private-key and CDP paths in ONE structural way: the
33
+ * account it yields has no local `signTransaction`. It signs and broadcasts by
34
+ * sending `eth_sendTransaction` / `eth_signTypedData_v4` to a provider, so the
35
+ * viem wallet client's TRANSPORT must be that provider rather than a plain HTTP
36
+ * RPC. That is the whole difference, and it is what `transport` below carries.
37
+ *
38
+ * Neither shape puts a wallet key on this machine. The signing key lives at
39
+ * Privy; the broker holds the Privy authorization key. What the CLI holds is
40
+ * either a short-lived session token (`session`) or a P-256 authorization key
41
+ * in the host credential store (`autonomous`) — a key that authorizes a
42
+ * policy-bounded request, not a key that can move funds by itself.
43
+ */
44
+ export type PrivyCliWalletSource = "privy-autonomous" | "privy-session";
45
+
46
+ /** The store key naming the agent-owned wallet in the host credential store. */
47
+ export const PRIVY_WALLET_KEY_ENV = "METRIK_AGENT_PRIVY_WALLET_KEY";
48
+ /** Broker base URL. Optional for `autonomous`, REQUIRED for `session`. */
49
+ export const PRIVY_BROKER_URL_ENV = "METRIK_AGENT_PRIVY_BROKER_URL";
50
+ /** A scoped session token minted by the broker's `POST /v1/sessions`. */
51
+ export const PRIVY_SESSION_TOKEN_ENV = "METRIK_AGENT_PRIVY_SESSION_TOKEN";
52
+ /** The embedded wallet address the session is bound to. */
53
+ export const PRIVY_ADDRESS_ENV = "METRIK_AGENT_PRIVY_ADDRESS";
54
+ /** The PUBLIC Privy app id. Not a secret — the broker serves it at `/v1/config`. */
55
+ export const PRIVY_APP_ID_ENV = "METRIK_AGENT_PRIVY_APP_ID";
56
+
57
+ /** Every variable either Privy shape reads. Named in errors, never printed. */
58
+ export const PRIVY_ENV_VARS = [
59
+ PRIVY_WALLET_KEY_ENV,
60
+ PRIVY_BROKER_URL_ENV,
61
+ PRIVY_SESSION_TOKEN_ENV,
62
+ PRIVY_ADDRESS_ENV,
63
+ PRIVY_APP_ID_ENV,
64
+ ] as const;
65
+
66
+ /** The variables the user-owned session shape needs, all of them. */
67
+ export const PRIVY_SESSION_ENV_VARS = [
68
+ PRIVY_BROKER_URL_ENV,
69
+ PRIVY_SESSION_TOKEN_ENV,
70
+ PRIVY_ADDRESS_ENV,
71
+ PRIVY_APP_ID_ENV,
72
+ ] as const;
73
+
74
+ /**
75
+ * The spend ceiling a broker enforces server-side, read from `GET /v1/config`.
76
+ *
77
+ * These are the SAME numbers the broker checks `openStream` against
78
+ * (`deposit <= maxTotalUsdc`, `ratePerSecond <= maxRatePerSecondUsdc`,
79
+ * `duration <= maxDurationSeconds`), which is why the CLI can use them to
80
+ * refuse an over-ceiling hire locally instead of paying gas to learn a knowable
81
+ * fact. It reads them rather than hardcoding them: the ceiling belongs to the
82
+ * broker, and a copy in this file would be a second source of truth that goes
83
+ * stale silently.
84
+ */
85
+ export interface PrivySpendPolicy {
86
+ readonly brokerUrl: string;
87
+ readonly chainId: number;
88
+ readonly maxTotalUsdc: bigint;
89
+ readonly maxRatePerSecondUsdc: bigint;
90
+ readonly maxDurationSeconds: number;
91
+ }
92
+
93
+ /** Reads a broker's public policy. No credential is sent; nothing secret is served. */
94
+ export async function fetchPrivySpendPolicy(
95
+ brokerUrl: string,
96
+ fetchImpl: typeof fetch = fetch,
97
+ ): Promise<PrivySpendPolicy> {
98
+ const base = brokerUrl.replace(/\/$/, "");
99
+ const response = await fetchImpl(`${base}/v1/config`, {
100
+ headers: { accept: "application/json" },
101
+ }).catch((error: unknown) => {
102
+ throw configError(
103
+ `the Privy broker at ${base} did not answer its public policy`,
104
+ `${describe(error)} The CLI reads GET /v1/config to know the ceiling your wallet is capped at; without it, it cannot tell you before broadcasting whether a hire fits.`,
105
+ );
106
+ });
107
+ const body = (await response.json().catch(() => null)) as Record<
108
+ string,
109
+ unknown
110
+ > | null;
111
+ if (!response.ok || body === null) {
112
+ throw configError(
113
+ `the Privy broker at ${base} rejected the public policy read (${response.status})`,
114
+ );
115
+ }
116
+ const chainId = Number(body.chainId);
117
+ const maxTotalUsdc = asBigint(body.maxTotalUsdcAtomic);
118
+ const maxRatePerSecondUsdc = asBigint(body.maxRatePerSecondAtomic);
119
+ const maxDurationSeconds = Number(body.maxDurationSeconds);
120
+ if (
121
+ !Number.isSafeInteger(chainId) ||
122
+ maxTotalUsdc === null ||
123
+ maxRatePerSecondUsdc === null ||
124
+ !Number.isSafeInteger(maxDurationSeconds)
125
+ ) {
126
+ throw configError(
127
+ `the Privy broker at ${base} returned a policy this CLI cannot read`,
128
+ "expected chainId, maxTotalUsdcAtomic, maxRatePerSecondAtomic and maxDurationSeconds.",
129
+ );
130
+ }
131
+ return {
132
+ brokerUrl: base,
133
+ chainId,
134
+ maxTotalUsdc,
135
+ maxRatePerSecondUsdc,
136
+ maxDurationSeconds,
137
+ };
138
+ }
139
+
140
+ function asBigint(value: unknown): bigint | null {
141
+ if (typeof value === "bigint") return value;
142
+ if (typeof value === "number" && Number.isSafeInteger(value))
143
+ return BigInt(value);
144
+ if (typeof value === "string" && /^[0-9]+$/.test(value)) return BigInt(value);
145
+ return null;
146
+ }
147
+
148
+ export interface ResolvedPrivyCliWallet {
149
+ readonly source: PrivyCliWalletSource;
150
+ /** A JSON-RPC account: `signTypedData` works, `signTransaction` does not exist. */
151
+ readonly account: Account;
152
+ /** The provider-as-transport. Without this every write goes to a plain RPC and fails. */
153
+ readonly transport: Transport;
154
+ /** One line naming the wallet's origin. Safe to print: no credential in it. */
155
+ readonly description: string;
156
+ /** Reads the broker ceiling this wallet is capped at. Bound to its broker URL. */
157
+ readonly readSpendPolicy: () => Promise<PrivySpendPolicy>;
158
+ }
159
+
160
+ export interface ResolvePrivyCliWalletOptions {
161
+ /** `--rpc-url`, so a Privy wallet's READS use the same endpoint as everything else. */
162
+ readonly rpcUrl?: string;
163
+ readonly note?: (line: string) => void;
164
+ /** Test seam. Defaults to the real credential store selected from `env`. */
165
+ readonly store?: AutonomousWalletCredentialStore;
166
+ /** Test seam for the broker HTTP contract. */
167
+ readonly fetchImpl?: typeof fetch;
168
+ }
169
+
170
+ /**
171
+ * Resolves a Privy wallet from the environment, or `null` when no Privy
172
+ * variable is set at all.
173
+ *
174
+ * A PARTIALLY configured Privy setup is an error, not a `null` — "you set the
175
+ * session token but not the address" and "you configured no Privy wallet" are
176
+ * different facts, and rendering the first as the second sends the reader
177
+ * looking in the wrong place. This mirrors the CDP path exactly.
178
+ */
179
+ export async function resolvePrivyCliWallet(
180
+ env: NodeJS.ProcessEnv,
181
+ options: ResolvePrivyCliWalletOptions = {},
182
+ ): Promise<ResolvedPrivyCliWallet | null> {
183
+ const walletKey = read(env, PRIVY_WALLET_KEY_ENV);
184
+ const brokerUrl = read(env, PRIVY_BROKER_URL_ENV);
185
+ const sessionToken = read(env, PRIVY_SESSION_TOKEN_ENV);
186
+ const address = read(env, PRIVY_ADDRESS_ENV);
187
+ const appId = read(env, PRIVY_APP_ID_ENV);
188
+
189
+ if (
190
+ walletKey === null &&
191
+ brokerUrl === null &&
192
+ sessionToken === null &&
193
+ address === null &&
194
+ appId === null
195
+ ) {
196
+ return null;
197
+ }
198
+
199
+ if (walletKey !== null) {
200
+ if (sessionToken !== null) {
201
+ options.note?.(
202
+ `warning: both ${PRIVY_WALLET_KEY_ENV} and ${PRIVY_SESSION_TOKEN_ENV} are set; using the agent-owned wallet named by ${PRIVY_WALLET_KEY_ENV}. Unset it to sign with the session token.`,
203
+ );
204
+ }
205
+ return await resolveAutonomous(walletKey, brokerUrl, env, options);
206
+ }
207
+
208
+ const missing = PRIVY_SESSION_ENV_VARS.filter(
209
+ (name) => read(env, name) === null,
210
+ );
211
+ if (missing.length > 0) {
212
+ throw configError(
213
+ `the Privy wallet is partially configured: ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not set`,
214
+ `a Privy wallet is configured one of two ways: set ${PRIVY_WALLET_KEY_ENV} to the store key of an agent-owned wallet you provisioned with provisionMetrikAutonomousWallet(), or set all of ${PRIVY_SESSION_ENV_VARS.join(", ")} for a broker session. Set the missing one${missing.length === 1 ? "" : "s"}, or unset the others to use a different wallet.`,
215
+ );
216
+ }
217
+
218
+ return resolveSession({
219
+ brokerUrl: brokerUrl as string,
220
+ sessionToken: sessionToken as string,
221
+ address: address as string,
222
+ appId: appId as string,
223
+ ...(options.rpcUrl === undefined ? {} : { rpcUrl: options.rpcUrl }),
224
+ ...(options.fetchImpl === undefined
225
+ ? {}
226
+ : { fetchImpl: options.fetchImpl }),
227
+ });
228
+ }
229
+
230
+ async function resolveAutonomous(
231
+ walletKey: string,
232
+ brokerUrlOverride: string | null,
233
+ env: NodeJS.ProcessEnv,
234
+ options: ResolvePrivyCliWalletOptions,
235
+ ): Promise<ResolvedPrivyCliWallet> {
236
+ const store = options.store ?? selectCredentialStore(env);
237
+ let record: AutonomousWalletRecord | null;
238
+ try {
239
+ record = await store.load(walletKey);
240
+ } catch (error) {
241
+ throw configError(
242
+ `could not read the agent-owned Privy wallet "${walletKey}" from the credential store`,
243
+ `${describe(error)} On a headless host the OS credential store is often unavailable; set ${METRIK_WALLET_ENCRYPTION_KEY_ENV} to use the encrypted-file store instead.`,
244
+ );
245
+ }
246
+ if (record === null) {
247
+ throw configError(
248
+ `no agent-owned Privy wallet is stored under the key "${walletKey}"`,
249
+ `the CLI never provisions a wallet on your behalf — a fund-moving command is the wrong place to mint one. Provision it once with provisionMetrikAutonomousWallet({ storeKey: "${walletKey}" }) (see docs/autonomous-privy-wallet.md), then re-run this command.`,
250
+ );
251
+ }
252
+ if (record.walletId === undefined || record.address === undefined) {
253
+ throw configError(
254
+ `the agent-owned Privy wallet "${walletKey}" was never finished provisioning`,
255
+ "the local key exists but the broker never returned a wallet id and address. Re-run provisionMetrikAutonomousWallet() with the same store key — it retries with the same key and idempotency nonce.",
256
+ );
257
+ }
258
+
259
+ const brokerUrl = brokerUrlOverride ?? record.brokerUrl;
260
+ if (brokerUrlOverride !== null && brokerUrlOverride !== record.brokerUrl) {
261
+ options.note?.(
262
+ `note: ${PRIVY_BROKER_URL_ENV} (${brokerUrlOverride}) overrides the broker this wallet was provisioned against (${record.brokerUrl}); only a broker holding this wallet's Privy authorization key can authorize it.`,
263
+ );
264
+ }
265
+
266
+ let broker: HttpAutonomousWalletBroker;
267
+ try {
268
+ broker = new HttpAutonomousWalletBroker(brokerUrl, {
269
+ ...(options.fetchImpl === undefined
270
+ ? {}
271
+ : { fetchImpl: options.fetchImpl }),
272
+ });
273
+ } catch (error) {
274
+ throw configError(
275
+ `the autonomous wallet broker URL is not usable: ${describe(error)}`,
276
+ `set ${PRIVY_BROKER_URL_ENV} to an HTTPS broker you control (the default is ${METRIK_AUTONOMOUS_WALLET_BROKER_URL}).`,
277
+ );
278
+ }
279
+
280
+ const provider = createAutonomousWalletProvider({
281
+ wallet: record,
282
+ broker,
283
+ ...(options.rpcUrl === undefined ? {} : { rpcUrl: options.rpcUrl }),
284
+ ...(options.fetchImpl === undefined
285
+ ? {}
286
+ : { fetchImpl: options.fetchImpl }),
287
+ });
288
+ const account = await embeddedAccount(provider, record.appId, record.address);
289
+
290
+ return {
291
+ source: "privy-autonomous",
292
+ account,
293
+ transport: custom(provider),
294
+ description: `${record.address} (agent-owned Privy wallet "${walletKey}" via ${brokerUrl})`,
295
+ readSpendPolicy: async () =>
296
+ await fetchPrivySpendPolicy(
297
+ brokerUrl,
298
+ options.fetchImpl ?? globalThis.fetch.bind(globalThis),
299
+ ),
300
+ };
301
+ }
302
+
303
+ function resolveSession(input: {
304
+ readonly brokerUrl: string;
305
+ readonly sessionToken: string;
306
+ readonly address: string;
307
+ readonly appId: string;
308
+ readonly rpcUrl?: string;
309
+ readonly fetchImpl?: typeof fetch;
310
+ }): Promise<ResolvedPrivyCliWallet> {
311
+ if (!isAddress(input.address)) {
312
+ throw configError(
313
+ `${PRIVY_ADDRESS_ENV} must be a 0x-prefixed 20-byte address`,
314
+ );
315
+ }
316
+ const address = getAddress(input.address);
317
+ let provider: PrivyEip1193Provider;
318
+ try {
319
+ provider = createPrivySessionProvider({
320
+ brokerUrl: input.brokerUrl,
321
+ sessionToken: input.sessionToken,
322
+ address,
323
+ ...(input.rpcUrl === undefined ? {} : { rpcUrl: input.rpcUrl }),
324
+ ...(input.fetchImpl === undefined ? {} : { fetchImpl: input.fetchImpl }),
325
+ });
326
+ } catch (error) {
327
+ throw configError(
328
+ `the Privy session broker URL is not usable: ${describe(error)}`,
329
+ `set ${PRIVY_BROKER_URL_ENV} to the HTTPS broker that minted ${PRIVY_SESSION_TOKEN_ENV}. A session token is only valid against the broker that issued it.`,
330
+ );
331
+ }
332
+ return embeddedAccount(provider, input.appId, address).then((account) => ({
333
+ source: "privy-session" as const,
334
+ account,
335
+ transport: custom(provider),
336
+ description: `${address} (Privy broker session via ${input.brokerUrl})`,
337
+ readSpendPolicy: async () =>
338
+ await fetchPrivySpendPolicy(
339
+ input.brokerUrl,
340
+ input.fetchImpl ?? globalThis.fetch.bind(globalThis),
341
+ ),
342
+ }));
343
+ }
344
+
345
+ /**
346
+ * Wraps a provider in the package's existing Privy EOA adapter.
347
+ *
348
+ * Both CLI providers answer `eth_chainId` and `eth_accounts` locally, so the
349
+ * adapter's session assertion is a pure local consistency check here — no
350
+ * network call happens while the wallet is being resolved.
351
+ */
352
+ async function embeddedAccount(
353
+ provider: PrivyEip1193Provider,
354
+ appId: string,
355
+ address: `0x${string}`,
356
+ ): Promise<Account> {
357
+ try {
358
+ return await createPrivyEmbeddedAccount({
359
+ appId,
360
+ address,
361
+ provider,
362
+ chainId: PRIVY_BROKER_CHAIN_ID,
363
+ });
364
+ } catch (error) {
365
+ throw configError(
366
+ `the Privy wallet could not be prepared: ${describe(error)}`,
367
+ `check ${PRIVY_ENV_VARS.join(", ")}. Metrik Privy wallets are on the broker's network only (${defaultNetwork().name}, chain ${PRIVY_BROKER_CHAIN_ID}).`,
368
+ );
369
+ }
370
+ }
371
+
372
+ /**
373
+ * The credential store the autonomous wallet was provisioned into.
374
+ *
375
+ * Selection mirrors `provisionMetrikAutonomousWallet`'s documented options:
376
+ * setting `METRIK_WALLET_ENCRYPTION_KEY` means the encrypted-file store (the
377
+ * durable option for a headless host), otherwise the host OS store. Picking a
378
+ * different store than provisioning used simply finds no record, and the
379
+ * "no wallet is stored under this key" error above says so.
380
+ */
381
+ function selectCredentialStore(
382
+ env: NodeJS.ProcessEnv,
383
+ ): AutonomousWalletCredentialStore {
384
+ if (read(env, METRIK_WALLET_ENCRYPTION_KEY_ENV) !== null) {
385
+ return new EncryptedFileCredentialStore({ env });
386
+ }
387
+ return createDefaultAutonomousWalletStore();
388
+ }
389
+
390
+ function read(env: NodeJS.ProcessEnv, name: string): string | null {
391
+ const value = env[name];
392
+ return value === undefined || value.length === 0 ? null : value;
393
+ }
394
+
395
+ function describe(error: unknown): string {
396
+ if (error instanceof AutonomousWalletError) return error.message;
397
+ return error instanceof Error ? error.message : String(error);
398
+ }
@@ -0,0 +1,154 @@
1
+ import type { StreamV2 } from "@absol-labs/sdk";
2
+
3
+ import { formatDuration } from "./amounts.js";
4
+ import { formatTimestamp, readChainNow } from "./escape-hatch.js";
5
+ import { settlementCoverage } from "./status.js";
6
+ import type { CliReadClient } from "./deps.js";
7
+
8
+ /**
9
+ * Why a proof-based reclaim cannot go through right now, read from chain state
10
+ * rather than decoded out of a revert.
11
+ *
12
+ * `metrik reclaim` used to learn this only by sending the simulation and
13
+ * reading what came back. That works exactly as well as the endpoint's revert
14
+ * data does, and on the public Base Sepolia RPC it frequently does not work at
15
+ * all: an already-reclaimed stream, a stream that is still running, and a
16
+ * stream whose stop time is not checkpointed yet ALL came back as
17
+ *
18
+ * reclaim simulation failed: Execution reverted for an unknown reason.
19
+ *
20
+ * Three different situations, three completely different next actions — you
21
+ * already have the money / close it first / wait ~20 seconds — and one message
22
+ * that distinguishes none of them. Worse, the retry loop keys off the same
23
+ * undecoded revert, so the wait that this command advertises never engaged.
24
+ *
25
+ * Every one of these conditions is a pure function of state the CLI already
26
+ * reads elsewhere (`getStreamV2`, `latestCheckpointCheckedAt`, the chain clock,
27
+ * and {@link settlementCoverage}, which `metrik status` has always used to
28
+ * decide the same question). So the condition is named from that state, before
29
+ * a transaction is built, the way `reclaim-unverified` has always named
30
+ * "already reclaimed". No revert data required.
31
+ */
32
+ export type ReclaimBlocker =
33
+ /** `AlreadyReclaimed()` / `NothingToReclaim()`: the money is already back. */
34
+ | { readonly kind: "reclaimed" }
35
+ /** `StreamNotReclaimable()`: neither closed nor expired, so the clock runs. */
36
+ | {
37
+ readonly kind: "running";
38
+ readonly expiresAt: number;
39
+ readonly secondsRemaining: number;
40
+ }
41
+ /**
42
+ * `SettlementWindowOpen()`: the stream has stopped but no checkpoint reaches
43
+ * its stop time yet. The ONLY one of the three that is a wait rather than a
44
+ * refusal — the oracle publishes roughly every 15-22s.
45
+ */
46
+ | {
47
+ readonly kind: "awaiting-checkpoint";
48
+ readonly stopAt: number;
49
+ readonly coveredUpTo: number | null;
50
+ };
51
+
52
+ /**
53
+ * The blocker implied by this state, or `null` when nothing in the state blocks
54
+ * a reclaim. Pure, so every branch is testable without an RPC — the same reason
55
+ * {@link settlementCoverage} is.
56
+ *
57
+ * Order matters and follows the escrow: a reclaimed stream is terminal, a
58
+ * running stream cannot be reclaimed at any settlement state, and only then
59
+ * does checkpoint coverage decide.
60
+ */
61
+ export function classifyReclaimBlocker(
62
+ stream: Pick<StreamV2, "status" | "closedAt" | "expiresAt" | "reclaimed">,
63
+ latestCheckpointCheckedAt: number | null,
64
+ nowSeconds: number,
65
+ ): ReclaimBlocker | null {
66
+ if (stream.reclaimed) return { kind: "reclaimed" };
67
+ if (stream.status !== "closed" && nowSeconds < stream.expiresAt) {
68
+ return {
69
+ kind: "running",
70
+ expiresAt: stream.expiresAt,
71
+ secondsRemaining: stream.expiresAt - nowSeconds,
72
+ };
73
+ }
74
+ const coverage = settlementCoverage(
75
+ stream,
76
+ latestCheckpointCheckedAt,
77
+ nowSeconds,
78
+ );
79
+ if (coverage.pending && coverage.stopAt !== null) {
80
+ return {
81
+ kind: "awaiting-checkpoint",
82
+ stopAt: coverage.stopAt,
83
+ coveredUpTo: coverage.coveredUpTo,
84
+ };
85
+ }
86
+ return null;
87
+ }
88
+
89
+ /**
90
+ * Read the state the classifier needs and name the blocker.
91
+ *
92
+ * **Fails open.** A read that does not answer returns `null` — "nothing known
93
+ * to block this" — never a refusal. Refusing to return a buyer's money because
94
+ * a load-balanced endpoint would not answer a view call is the one outcome this
95
+ * command must never produce; the transaction itself remains the authority.
96
+ */
97
+ export async function readReclaimBlocker(
98
+ read: Pick<
99
+ CliReadClient,
100
+ "getStreamV2" | "latestCheckpointCheckedAt" | "latestBlockTimestamp"
101
+ >,
102
+ streamId: `0x${string}`,
103
+ fallbackNowSeconds: number,
104
+ ): Promise<ReclaimBlocker | null> {
105
+ const stream = await read.getStreamV2(streamId).catch(() => null);
106
+ if (stream === null) return null;
107
+ const now = await readChainNow(read, fallbackNowSeconds);
108
+ const latestCheckpointCheckedAt = await read
109
+ .latestCheckpointCheckedAt()
110
+ .catch(() => null);
111
+ return classifyReclaimBlocker(stream, latestCheckpointCheckedAt, now.seconds);
112
+ }
113
+
114
+ /**
115
+ * The refusal for a blocker that will not clear on its own, as message + hint.
116
+ *
117
+ * `awaiting-checkpoint` has no entry here on purpose: it clears by itself, so
118
+ * it is narrated by {@link describeAwaitingCheckpoint} and waited out, never
119
+ * raised as an error.
120
+ */
121
+ export function describeTerminalBlocker(
122
+ blocker: ReclaimBlocker,
123
+ streamId: `0x${string}`,
124
+ ): { readonly message: string; readonly hint: string } | null {
125
+ if (blocker.kind === "reclaimed") {
126
+ return {
127
+ message:
128
+ "this stream has already been reclaimed — there is nothing left to take back",
129
+ hint: `check where it went: metrik status ${streamId}`,
130
+ };
131
+ }
132
+ if (blocker.kind === "running") {
133
+ return {
134
+ message: `the stream is still running, so there is nothing to reclaim yet — the meter stops at ${formatTimestamp(
135
+ blocker.expiresAt,
136
+ )}, in ${formatDuration(blocker.secondsRemaining)}`,
137
+ hint: `stop the clock first — \`metrik close ${streamId}\`, or re-run this command with --close-first — or wait for it to expire. (If you closed it moments ago, the RPC endpoint may not have caught up yet: re-run this command.)`,
138
+ };
139
+ }
140
+ return null;
141
+ }
142
+
143
+ /** The wait, named: what stopped, how far the oracle has published. */
144
+ export function describeAwaitingCheckpoint(
145
+ blocker: Extract<ReclaimBlocker, { kind: "awaiting-checkpoint" }>,
146
+ ): string {
147
+ const covered =
148
+ blocker.coveredUpTo === null
149
+ ? "how far the oracle has published could not be read"
150
+ : `the oracle has published only to ${formatTimestamp(blocker.coveredUpTo)}`;
151
+ return `the stream stopped at ${formatTimestamp(
152
+ blocker.stopAt,
153
+ )} and ${covered}. Reclaim reverts until a checkpoint reaches the stop time — the oracle publishes roughly every 15-22s, so this waits.`;
154
+ }
package/src/cli/run.ts CHANGED
@@ -1,16 +1,27 @@
1
- import { assertKnownFlags, booleanFlag, parseArgs } from "./args.js";
1
+ import {
2
+ assertKnownFlags,
3
+ booleanFlag,
4
+ jsonOutputRequested,
5
+ parseArgs,
6
+ } from "./args.js";
2
7
  import {
3
8
  CONFIG_FLAGS,
4
9
  GLOBAL_FLAGS,
5
- TESTNET_CHAIN_IDS,
10
+ CLI_NETWORK_POLICY,
6
11
  resolveConfig,
7
12
  } from "./config.js";
13
+ import { describeAllowedNetworks } from "../network.js";
8
14
  import { CliError, describeError, usageError } from "./errors.js";
9
15
  import { createPrinter, type CliStreams } from "./output.js";
10
16
  import { startHeartbeat } from "./progress.js";
11
17
  import { defaultCliDependencies, type CliDependencies } from "./deps.js";
12
18
  import { packageVersion } from "./version.js";
13
- import { CDP_ENV_VARS, PRIVATE_KEY_ENV } from "./wallet.js";
19
+ import {
20
+ CDP_ENV_VARS,
21
+ PRIVATE_KEY_ENV,
22
+ PRIVY_SESSION_ENV_VARS,
23
+ PRIVY_WALLET_KEY_ENV,
24
+ } from "./wallet.js";
14
25
  import type { CommandSpec } from "./context.js";
15
26
 
16
27
  import { claimCommand } from "./commands/claim.js";
@@ -19,15 +30,39 @@ import { discoverCommand } from "./commands/discover.js";
19
30
  import { invokeCommand } from "./commands/invoke.js";
20
31
  import { mcpCommand } from "./commands/mcp.js";
21
32
  import { openCommand } from "./commands/open.js";
33
+ import { payCommand } from "./commands/pay.js";
22
34
  import { reclaimCommand } from "./commands/reclaim.js";
35
+ import { refundCommand } from "./commands/refund.js";
23
36
  import { reclaimUnverifiedCommand } from "./commands/reclaim-unverified.js";
24
37
  import { statusCommand } from "./commands/status.js";
25
38
  import { streamsCommand } from "./commands/streams.js";
26
39
  import { watchCommand } from "./commands/watch.js";
27
40
 
41
+ /**
42
+ * Every wallet source, named in the order they are resolved. Privy shipped in
43
+ * 0.11.0 as resolution step 3 and worked, but appeared in no user-facing text
44
+ * at all — so the only way to learn the CLI could use it was to read the
45
+ * source or the docs. An external reviewer running the published package
46
+ * concluded it did not exist.
47
+ */
48
+ const WALLET_SOURCES =
49
+ `${PRIVATE_KEY_ENV}, ${CDP_ENV_VARS.join(" + ")}, ` +
50
+ `or ${PRIVY_WALLET_KEY_ENV} (Privy; or a broker session via ${PRIVY_SESSION_ENV_VARS.join(" + ")}).`;
51
+
52
+ /**
53
+ * Said in the help, not only discovered at runtime. `claim` is the OPERATOR's
54
+ * side and a Privy broker policy allowlists BUYER actions only, so a Privy
55
+ * wallet cannot sign one — the broker refuses, and the client cannot raise its
56
+ * own ceiling. The command already warns when it runs; someone choosing a
57
+ * wallet needs it before that.
58
+ */
59
+ const PRIVY_CLAIM_NOTE =
60
+ "`metrik claim` does NOT work on a Privy wallet: the broker's transaction allowlist is buyer-only. Claim with the operator's own key.";
61
+
28
62
  /**
29
63
  * The command surface, in the order the product loop runs:
30
- * discover -> open -> invoke -> watch/status -> close -> reclaim, then the
64
+ * discover -> open (or pay, over x402) -> invoke -> watch/status -> close ->
65
+ * reclaim (or refund, through an x402 seller's gasless relay), then the
31
66
  * operator's own redemption (`claim`) and the buyer's last-resort exit
32
67
  * (`reclaim-unverified`). `streams` (which of them are mine?) sits inside that
33
68
  * loop; `mcp` (run the same loop from an MCP host) sits after it.
@@ -35,12 +70,14 @@ import { watchCommand } from "./commands/watch.js";
35
70
  export const COMMANDS: readonly CommandSpec[] = [
36
71
  discoverCommand,
37
72
  openCommand,
73
+ payCommand,
38
74
  statusCommand,
39
75
  streamsCommand,
40
76
  watchCommand,
41
77
  invokeCommand,
42
78
  closeCommand,
43
79
  reclaimCommand,
80
+ refundCommand,
44
81
  reclaimUnverifiedCommand,
45
82
  claimCommand,
46
83
  mcpCommand,
@@ -69,7 +106,7 @@ export async function runCli(options: RunCliOptions): Promise<number> {
69
106
  let json = false;
70
107
  try {
71
108
  const args = parseArgs(options.argv);
72
- json = booleanFlag(args, "json");
109
+ json = jsonOutputRequested(args);
73
110
  const out = createPrinter(streams, json);
74
111
 
75
112
  // `--version` is checked before the bare-invocation help branch: `metrik
@@ -160,12 +197,13 @@ export function renderHelp(commandName?: string): string {
160
197
  ...(command.signs
161
198
  ? [
162
199
  "",
163
- `Broadcasts a transaction. Requires a wallet in the environment: ${PRIVATE_KEY_ENV}, or ${CDP_ENV_VARS.join(" + ")}.`,
200
+ `Broadcasts a transaction. Requires a wallet in the environment: ${WALLET_SOURCES}`,
201
+ ...(command.name === "claim" ? [PRIVY_CLAIM_NOTE] : []),
164
202
  ]
165
203
  : command.requiresKey === true
166
204
  ? [
167
205
  "",
168
- `Broadcasts nothing, but signs an off-chain EIP-712 capability, so it requires a wallet in the environment: ${PRIVATE_KEY_ENV}, or ${CDP_ENV_VARS.join(" + ")}.`,
206
+ `Broadcasts nothing, but signs an off-chain EIP-712 capability, so it requires a wallet in the environment: ${WALLET_SOURCES}`,
169
207
  ]
170
208
  : []),
171
209
  ].join("\n");
@@ -194,16 +232,21 @@ export function renderHelp(commandName?: string): string {
194
232
  " --json machine-readable output on stdout",
195
233
  " --help this text, or `metrik <command> --help`",
196
234
  "",
197
- "Settlement flags (all default to Metrik's Base Sepolia deployment):",
198
- " --chain-id --rpc-url --escrow --usdc --oracle-url --registry-url",
235
+ "Settlement flags (all default to the selected network's registry entry):",
236
+ " --network --chain-id --rpc-url --escrow --usdc --oracle-url --registry-url",
237
+ " --network takes a registry id, chain id or CAIP-2 id (env METRIK_NETWORK).",
199
238
  "",
200
239
  "Wallet (read from the environment only; never accepted as a flag):",
201
- ` ${PRIVATE_KEY_ENV} a Base Sepolia test key. Checked first.`,
240
+ ` ${PRIVATE_KEY_ENV} a testnet key. Checked first.`,
202
241
  ` ${CDP_ENV_VARS.join(", ")}`,
203
242
  " a Coinbase CDP Server Wallet v2 account. Used when no private key is set.",
243
+ ` ${PRIVY_WALLET_KEY_ENV}`,
244
+ " a Privy wallet you provisioned, reached through a broker. Checked third.",
245
+ ` A broker session instead: ${PRIVY_SESSION_ENV_VARS.join(", ")}.`,
246
+ ` ${PRIVY_CLAIM_NOTE}`,
204
247
  " A credential on the command line lands in shell history; these never are.",
205
248
  "",
206
- `TESTNET ONLY: this CLI refuses any chain outside ${TESTNET_CHAIN_IDS.join(", ")} (Base Sepolia),`,
249
+ `TESTNET ONLY: this CLI refuses any chain outside the registered testnets: ${describeAllowedNetworks(CLI_NETWORK_POLICY)},`,
207
250
  "and re-checks the chain id the RPC actually serves before signing. There is no override.",
208
251
  ].join("\n");
209
252
  }