@absol-labs/agent 0.11.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 (350) hide show
  1. package/README.md +42 -50
  2. package/dist/capability/invocation-capability.d.ts +2 -2
  3. package/dist/capability/probe-capability.d.ts +225 -0
  4. package/dist/capability/probe-capability.d.ts.map +1 -0
  5. package/dist/capability/probe-capability.js +248 -0
  6. package/dist/capability/probe-capability.js.map +1 -0
  7. package/dist/cli/args.d.ts +11 -0
  8. package/dist/cli/args.d.ts.map +1 -1
  9. package/dist/cli/args.js +23 -0
  10. package/dist/cli/args.js.map +1 -1
  11. package/dist/cli/commands/claim.js +1 -1
  12. package/dist/cli/commands/claim.js.map +1 -1
  13. package/dist/cli/commands/close.d.ts.map +1 -1
  14. package/dist/cli/commands/close.js +35 -3
  15. package/dist/cli/commands/close.js.map +1 -1
  16. package/dist/cli/commands/invoke.d.ts +2 -0
  17. package/dist/cli/commands/invoke.d.ts.map +1 -1
  18. package/dist/cli/commands/invoke.js +2 -2
  19. package/dist/cli/commands/invoke.js.map +1 -1
  20. package/dist/cli/commands/mcp.d.ts.map +1 -1
  21. package/dist/cli/commands/mcp.js +15 -2
  22. package/dist/cli/commands/mcp.js.map +1 -1
  23. package/dist/cli/commands/open.d.ts.map +1 -1
  24. package/dist/cli/commands/open.js +58 -4
  25. package/dist/cli/commands/open.js.map +1 -1
  26. package/dist/cli/commands/pay.d.ts +19 -0
  27. package/dist/cli/commands/pay.d.ts.map +1 -0
  28. package/dist/cli/commands/pay.js +355 -0
  29. package/dist/cli/commands/pay.js.map +1 -0
  30. package/dist/cli/commands/reclaim-unverified.d.ts.map +1 -1
  31. package/dist/cli/commands/reclaim-unverified.js +3 -2
  32. package/dist/cli/commands/reclaim-unverified.js.map +1 -1
  33. package/dist/cli/commands/reclaim.d.ts +23 -2
  34. package/dist/cli/commands/reclaim.d.ts.map +1 -1
  35. package/dist/cli/commands/reclaim.js +184 -16
  36. package/dist/cli/commands/reclaim.js.map +1 -1
  37. package/dist/cli/commands/refund.d.ts +13 -0
  38. package/dist/cli/commands/refund.d.ts.map +1 -0
  39. package/dist/cli/commands/refund.js +224 -0
  40. package/dist/cli/commands/refund.js.map +1 -0
  41. package/dist/cli/commands/status.d.ts.map +1 -1
  42. package/dist/cli/commands/status.js +10 -1
  43. package/dist/cli/commands/status.js.map +1 -1
  44. package/dist/cli/commands/streams.js +8 -12
  45. package/dist/cli/commands/streams.js.map +1 -1
  46. package/dist/cli/commands/watch.d.ts.map +1 -1
  47. package/dist/cli/commands/watch.js +2 -1
  48. package/dist/cli/commands/watch.js.map +1 -1
  49. package/dist/cli/config.d.ts +44 -26
  50. package/dist/cli/config.d.ts.map +1 -1
  51. package/dist/cli/config.js +88 -38
  52. package/dist/cli/config.js.map +1 -1
  53. package/dist/cli/deps.d.ts +33 -0
  54. package/dist/cli/deps.d.ts.map +1 -1
  55. package/dist/cli/deps.js +37 -1
  56. package/dist/cli/deps.js.map +1 -1
  57. package/dist/cli/errors.d.ts.map +1 -1
  58. package/dist/cli/errors.js +21 -1
  59. package/dist/cli/errors.js.map +1 -1
  60. package/dist/cli/escape-hatch.d.ts +6 -4
  61. package/dist/cli/escape-hatch.d.ts.map +1 -1
  62. package/dist/cli/escape-hatch.js +6 -2
  63. package/dist/cli/escape-hatch.js.map +1 -1
  64. package/dist/cli/listings.d.ts +18 -0
  65. package/dist/cli/listings.d.ts.map +1 -1
  66. package/dist/cli/listings.js +22 -12
  67. package/dist/cli/listings.js.map +1 -1
  68. package/dist/cli/preflight.d.ts +20 -14
  69. package/dist/cli/preflight.d.ts.map +1 -1
  70. package/dist/cli/preflight.js +34 -20
  71. package/dist/cli/preflight.js.map +1 -1
  72. package/dist/cli/privy.d.ts.map +1 -1
  73. package/dist/cli/privy.js +4 -2
  74. package/dist/cli/privy.js.map +1 -1
  75. package/dist/cli/reclaimability.d.ts +82 -0
  76. package/dist/cli/reclaimability.d.ts.map +1 -0
  77. package/dist/cli/reclaimability.js +80 -0
  78. package/dist/cli/reclaimability.js.map +1 -0
  79. package/dist/cli/run.d.ts +2 -1
  80. package/dist/cli/run.d.ts.map +1 -1
  81. package/dist/cli/run.js +40 -11
  82. package/dist/cli/run.js.map +1 -1
  83. package/dist/cli/scan-range.d.ts +2 -2
  84. package/dist/cli/scan-range.js +2 -2
  85. package/dist/cli/status.d.ts +3 -1
  86. package/dist/cli/status.d.ts.map +1 -1
  87. package/dist/cli/status.js +15 -3
  88. package/dist/cli/status.js.map +1 -1
  89. package/dist/cli/wallet.d.ts +1 -1
  90. package/dist/cli/wallet.js +2 -2
  91. package/dist/cli/wallet.js.map +1 -1
  92. package/dist/discovery/rate-band.d.ts +74 -0
  93. package/dist/discovery/rate-band.d.ts.map +1 -0
  94. package/dist/discovery/rate-band.js +114 -0
  95. package/dist/discovery/rate-band.js.map +1 -0
  96. package/dist/escrow-generation.d.ts +81 -0
  97. package/dist/escrow-generation.d.ts.map +1 -0
  98. package/dist/escrow-generation.js +76 -0
  99. package/dist/escrow-generation.js.map +1 -0
  100. package/dist/frameworks/agentkit.d.ts +8 -4
  101. package/dist/frameworks/agentkit.d.ts.map +1 -1
  102. package/dist/frameworks/agentkit.js +27 -10
  103. package/dist/frameworks/agentkit.js.map +1 -1
  104. package/dist/frameworks/eliza.d.ts +3 -3
  105. package/dist/frameworks/eliza.d.ts.map +1 -1
  106. package/dist/frameworks/eliza.js +15 -6
  107. package/dist/frameworks/eliza.js.map +1 -1
  108. package/dist/frameworks/langchain.d.ts.map +1 -1
  109. package/dist/frameworks/langchain.js +8 -0
  110. package/dist/frameworks/langchain.js.map +1 -1
  111. package/dist/gateway/caller-auth-gateway.d.ts +83 -31
  112. package/dist/gateway/caller-auth-gateway.d.ts.map +1 -1
  113. package/dist/gateway/caller-auth-gateway.js +180 -27
  114. package/dist/gateway/caller-auth-gateway.js.map +1 -1
  115. package/dist/gateway/http-server.d.ts +111 -44
  116. package/dist/gateway/http-server.d.ts.map +1 -1
  117. package/dist/gateway/http-server.js +439 -155
  118. package/dist/gateway/http-server.js.map +1 -1
  119. package/dist/gateway/probe-auth.d.ts +112 -0
  120. package/dist/gateway/probe-auth.d.ts.map +1 -0
  121. package/dist/gateway/probe-auth.js +127 -0
  122. package/dist/gateway/probe-auth.js.map +1 -0
  123. package/dist/gateway/signed-rate-bounds.d.ts +51 -0
  124. package/dist/gateway/signed-rate-bounds.d.ts.map +1 -0
  125. package/dist/gateway/signed-rate-bounds.js +94 -0
  126. package/dist/gateway/signed-rate-bounds.js.map +1 -0
  127. package/dist/gateway/x402-opener-mode.d.ts +215 -0
  128. package/dist/gateway/x402-opener-mode.d.ts.map +1 -0
  129. package/dist/gateway/x402-opener-mode.js +639 -0
  130. package/dist/gateway/x402-opener-mode.js.map +1 -0
  131. package/dist/index.d.ts +6 -2
  132. package/dist/index.d.ts.map +1 -1
  133. package/dist/index.js +10 -5
  134. package/dist/index.js.map +1 -1
  135. package/dist/mcp/server.d.ts +52 -1
  136. package/dist/mcp/server.d.ts.map +1 -1
  137. package/dist/mcp/server.js +228 -37
  138. package/dist/mcp/server.js.map +1 -1
  139. package/dist/mcp/x402-tools.d.ts +104 -0
  140. package/dist/mcp/x402-tools.d.ts.map +1 -0
  141. package/dist/mcp/x402-tools.js +434 -0
  142. package/dist/mcp/x402-tools.js.map +1 -0
  143. package/dist/network.d.ts +119 -0
  144. package/dist/network.d.ts.map +1 -0
  145. package/dist/network.js +199 -0
  146. package/dist/network.js.map +1 -0
  147. package/dist/sdk/invoke.d.ts +4 -0
  148. package/dist/sdk/invoke.d.ts.map +1 -1
  149. package/dist/sdk/invoke.js +2 -5
  150. package/dist/sdk/invoke.js.map +1 -1
  151. package/dist/wallet/autonomous-wallet-broker.d.ts +3 -0
  152. package/dist/wallet/autonomous-wallet-broker.d.ts.map +1 -1
  153. package/dist/wallet/autonomous-wallet-broker.js +27 -23
  154. package/dist/wallet/autonomous-wallet-broker.js.map +1 -1
  155. package/dist/wallet/autonomous-wallet-protocol.d.ts +8 -2
  156. package/dist/wallet/autonomous-wallet-protocol.d.ts.map +1 -1
  157. package/dist/wallet/autonomous-wallet-protocol.js +9 -2
  158. package/dist/wallet/autonomous-wallet-protocol.js.map +1 -1
  159. package/dist/wallet/autonomous-wallet.d.ts.map +1 -1
  160. package/dist/wallet/autonomous-wallet.js +3 -2
  161. package/dist/wallet/autonomous-wallet.js.map +1 -1
  162. package/dist/wallet/broker-escrows.d.ts +222 -0
  163. package/dist/wallet/broker-escrows.d.ts.map +1 -0
  164. package/dist/wallet/broker-escrows.js +36 -0
  165. package/dist/wallet/broker-escrows.js.map +1 -0
  166. package/dist/wallet/lifecycle.d.ts +21 -5
  167. package/dist/wallet/lifecycle.d.ts.map +1 -1
  168. package/dist/wallet/lifecycle.js +32 -12
  169. package/dist/wallet/lifecycle.js.map +1 -1
  170. package/dist/wallet/privy-broker-server.d.ts.map +1 -1
  171. package/dist/wallet/privy-broker-server.js +31 -26
  172. package/dist/wallet/privy-broker-server.js.map +1 -1
  173. package/dist/wallet/privy-session-broker.d.ts +14 -5
  174. package/dist/wallet/privy-session-broker.d.ts.map +1 -1
  175. package/dist/wallet/privy-session-broker.js +29 -17
  176. package/dist/wallet/privy-session-broker.js.map +1 -1
  177. package/dist/wallet/privy-session-provider.d.ts +3 -1
  178. package/dist/wallet/privy-session-provider.d.ts.map +1 -1
  179. package/dist/wallet/privy-session-provider.js +5 -3
  180. package/dist/wallet/privy-session-provider.js.map +1 -1
  181. package/dist/wallet/provider.d.ts.map +1 -1
  182. package/dist/wallet/provider.js +15 -8
  183. package/dist/wallet/provider.js.map +1 -1
  184. package/dist/x402/facilitator.d.ts +3 -30
  185. package/dist/x402/facilitator.d.ts.map +1 -1
  186. package/dist/x402/facilitator.js +0 -27
  187. package/dist/x402/facilitator.js.map +1 -1
  188. package/dist/x402-buyer/guarded-fetch.d.ts +51 -0
  189. package/dist/x402-buyer/guarded-fetch.d.ts.map +1 -0
  190. package/dist/x402-buyer/guarded-fetch.js +147 -0
  191. package/dist/x402-buyer/guarded-fetch.js.map +1 -0
  192. package/dist/x402-buyer/index.d.ts +10 -0
  193. package/dist/x402-buyer/index.d.ts.map +1 -0
  194. package/dist/x402-buyer/index.js +10 -0
  195. package/dist/x402-buyer/index.js.map +1 -0
  196. package/dist/x402-buyer/pay.d.ts +135 -0
  197. package/dist/x402-buyer/pay.d.ts.map +1 -0
  198. package/dist/x402-buyer/pay.js +336 -0
  199. package/dist/x402-buyer/pay.js.map +1 -0
  200. package/dist/x402-opener/abi.d.ts +684 -0
  201. package/dist/x402-opener/abi.d.ts.map +1 -0
  202. package/dist/x402-opener/abi.js +880 -0
  203. package/dist/x402-opener/abi.js.map +1 -0
  204. package/dist/x402-opener/facilitator-entry.d.ts +3 -0
  205. package/dist/x402-opener/facilitator-entry.d.ts.map +1 -0
  206. package/dist/x402-opener/facilitator-entry.js +37 -0
  207. package/dist/x402-opener/facilitator-entry.js.map +1 -0
  208. package/dist/x402-opener/facilitator-server.d.ts +180 -0
  209. package/dist/x402-opener/facilitator-server.d.ts.map +1 -0
  210. package/dist/x402-opener/facilitator-server.js +696 -0
  211. package/dist/x402-opener/facilitator-server.js.map +1 -0
  212. package/dist/x402-opener/index.d.ts +14 -0
  213. package/dist/x402-opener/index.d.ts.map +1 -0
  214. package/dist/x402-opener/index.js +14 -0
  215. package/dist/x402-opener/index.js.map +1 -0
  216. package/dist/x402-opener/listing-resolver.d.ts +55 -0
  217. package/dist/x402-opener/listing-resolver.d.ts.map +1 -0
  218. package/dist/x402-opener/listing-resolver.js +125 -0
  219. package/dist/x402-opener/listing-resolver.js.map +1 -0
  220. package/dist/x402-opener/refund-relay.d.ts +240 -0
  221. package/dist/x402-opener/refund-relay.d.ts.map +1 -0
  222. package/dist/x402-opener/refund-relay.js +1240 -0
  223. package/dist/x402-opener/refund-relay.js.map +1 -0
  224. package/dist/x402-opener/relayer-queue.d.ts +14 -0
  225. package/dist/x402-opener/relayer-queue.d.ts.map +1 -0
  226. package/dist/x402-opener/relayer-queue.js +18 -0
  227. package/dist/x402-opener/relayer-queue.js.map +1 -0
  228. package/dist/x402-opener/scheme.d.ts +217 -0
  229. package/dist/x402-opener/scheme.d.ts.map +1 -0
  230. package/dist/x402-opener/scheme.js +749 -0
  231. package/dist/x402-opener/scheme.js.map +1 -0
  232. package/dist/x402-opener/terms.d.ts +105 -0
  233. package/dist/x402-opener/terms.d.ts.map +1 -0
  234. package/dist/x402-opener/terms.js +212 -0
  235. package/dist/x402-opener/terms.js.map +1 -0
  236. package/dist/zktls/reclaim.d.ts +2 -2
  237. package/dist/zktls/t2-delivery-proof.d.ts +6 -6
  238. package/docs/agent-layer.md +3 -2
  239. package/docs/autonomous-privy-wallet.md +188 -0
  240. package/docs/cli.md +184 -31
  241. package/docs/langchain.md +5 -0
  242. package/docs/mcp-reference.md +75 -5
  243. package/docs/probe-capability.md +191 -0
  244. package/docs/quickstart.md +36 -1
  245. package/docs/threat-model.md +20 -0
  246. package/docs/x402.md +628 -595
  247. package/package.json +19 -17
  248. package/src/capability/probe-capability.ts +355 -0
  249. package/src/cli/args.ts +29 -0
  250. package/src/cli/commands/claim.ts +1 -1
  251. package/src/cli/commands/close.ts +36 -3
  252. package/src/cli/commands/invoke.ts +5 -2
  253. package/src/cli/commands/mcp.ts +18 -2
  254. package/src/cli/commands/open.ts +75 -4
  255. package/src/cli/commands/pay.ts +442 -0
  256. package/src/cli/commands/reclaim-unverified.ts +8 -2
  257. package/src/cli/commands/reclaim.ts +252 -14
  258. package/src/cli/commands/refund.ts +277 -0
  259. package/src/cli/commands/status.ts +17 -1
  260. package/src/cli/commands/streams.ts +10 -14
  261. package/src/cli/commands/watch.ts +7 -1
  262. package/src/cli/config.ts +139 -52
  263. package/src/cli/deps.ts +74 -1
  264. package/src/cli/errors.ts +24 -1
  265. package/src/cli/escape-hatch.ts +19 -5
  266. package/src/cli/listings.ts +43 -10
  267. package/src/cli/preflight.ts +36 -21
  268. package/src/cli/privy.ts +4 -2
  269. package/src/cli/reclaimability.ts +154 -0
  270. package/src/cli/run.ts +54 -11
  271. package/src/cli/scan-range.ts +2 -2
  272. package/src/cli/status.ts +14 -1
  273. package/src/cli/wallet.ts +2 -2
  274. package/src/discovery/rate-band.ts +172 -0
  275. package/src/escrow-generation.ts +135 -0
  276. package/src/frameworks/agentkit.ts +45 -11
  277. package/src/frameworks/eliza.ts +27 -5
  278. package/src/frameworks/langchain.ts +14 -0
  279. package/src/gateway/caller-auth-gateway.ts +320 -68
  280. package/src/gateway/http-server.ts +629 -220
  281. package/src/gateway/probe-auth.ts +191 -0
  282. package/src/gateway/signed-rate-bounds.ts +164 -0
  283. package/src/gateway/x402-opener-mode.ts +974 -0
  284. package/src/index.ts +82 -19
  285. package/src/mcp/server.ts +319 -42
  286. package/src/mcp/x402-tools.ts +621 -0
  287. package/src/network.ts +302 -0
  288. package/src/sdk/invoke.ts +6 -5
  289. package/src/wallet/autonomous-wallet-broker.ts +46 -20
  290. package/src/wallet/autonomous-wallet-protocol.ts +11 -2
  291. package/src/wallet/autonomous-wallet.ts +4 -2
  292. package/src/wallet/broker-escrows.ts +66 -0
  293. package/src/wallet/lifecycle.ts +53 -18
  294. package/src/wallet/privy-broker-server.ts +35 -25
  295. package/src/wallet/privy-session-broker.ts +58 -25
  296. package/src/wallet/privy-session-provider.ts +7 -3
  297. package/src/wallet/provider.ts +20 -15
  298. package/src/x402/facilitator.ts +3 -43
  299. package/src/x402-buyer/guarded-fetch.ts +213 -0
  300. package/src/x402-buyer/index.ts +9 -0
  301. package/src/x402-buyer/pay.ts +517 -0
  302. package/src/x402-opener/abi.ts +881 -0
  303. package/src/x402-opener/facilitator-entry.ts +45 -0
  304. package/src/x402-opener/facilitator-server.ts +1014 -0
  305. package/src/x402-opener/index.ts +13 -0
  306. package/src/x402-opener/listing-resolver.ts +202 -0
  307. package/src/x402-opener/refund-relay.ts +1743 -0
  308. package/src/x402-opener/relayer-queue.ts +18 -0
  309. package/src/x402-opener/scheme.ts +1133 -0
  310. package/src/x402-opener/terms.ts +300 -0
  311. package/dist/gateway/x402-mode.d.ts +0 -123
  312. package/dist/gateway/x402-mode.d.ts.map +0 -1
  313. package/dist/gateway/x402-mode.js +0 -212
  314. package/dist/gateway/x402-mode.js.map +0 -1
  315. package/dist/x402/delivery-oracle.d.ts +0 -108
  316. package/dist/x402/delivery-oracle.d.ts.map +0 -1
  317. package/dist/x402/delivery-oracle.js +0 -174
  318. package/dist/x402/delivery-oracle.js.map +0 -1
  319. package/dist/x402/facilitator-server-entry.d.ts +0 -3
  320. package/dist/x402/facilitator-server-entry.d.ts.map +0 -1
  321. package/dist/x402/facilitator-server-entry.js +0 -27
  322. package/dist/x402/facilitator-server-entry.js.map +0 -1
  323. package/dist/x402/facilitator-server.d.ts +0 -73
  324. package/dist/x402/facilitator-server.d.ts.map +0 -1
  325. package/dist/x402/facilitator-server.js +0 -305
  326. package/dist/x402/facilitator-server.js.map +0 -1
  327. package/dist/x402/payment-requirements.d.ts +0 -106
  328. package/dist/x402/payment-requirements.d.ts.map +0 -1
  329. package/dist/x402/payment-requirements.js +0 -138
  330. package/dist/x402/payment-requirements.js.map +0 -1
  331. package/dist/x402/relayer.d.ts +0 -41
  332. package/dist/x402/relayer.d.ts.map +0 -1
  333. package/dist/x402/relayer.js +0 -64
  334. package/dist/x402/relayer.js.map +0 -1
  335. package/dist/x402/resource-index.d.ts +0 -75
  336. package/dist/x402/resource-index.d.ts.map +0 -1
  337. package/dist/x402/resource-index.js +0 -126
  338. package/dist/x402/resource-index.js.map +0 -1
  339. package/dist/x402/verified-delivery-facilitator.d.ts +0 -285
  340. package/dist/x402/verified-delivery-facilitator.d.ts.map +0 -1
  341. package/dist/x402/verified-delivery-facilitator.js +0 -423
  342. package/dist/x402/verified-delivery-facilitator.js.map +0 -1
  343. package/src/gateway/x402-mode.ts +0 -350
  344. package/src/x402/delivery-oracle.ts +0 -285
  345. package/src/x402/facilitator-server-entry.ts +0 -35
  346. package/src/x402/facilitator-server.ts +0 -445
  347. package/src/x402/payment-requirements.ts +0 -231
  348. package/src/x402/relayer.ts +0 -122
  349. package/src/x402/resource-index.ts +0 -228
  350. package/src/x402/verified-delivery-facilitator.ts +0 -744
@@ -23,7 +23,12 @@ import {
23
23
  resolveCliWallet,
24
24
  PRIVATE_KEY_ENV,
25
25
  } from "../wallet.js";
26
- import { resolveListing } from "../listings.js";
26
+ import { resolveListingRecord } from "../listings.js";
27
+ import {
28
+ listingRateBand,
29
+ rateBandRefusal,
30
+ SignedRateBoundsError,
31
+ } from "../../discovery/rate-band.js";
27
32
  import type { CommandContext, CommandSpec } from "../context.js";
28
33
 
29
34
  export const openCommand: CommandSpec = {
@@ -89,14 +94,21 @@ export const openCommand: CommandSpec = {
89
94
  if (account !== null && !dryRun) {
90
95
  // Both balances, before anything is signed. Gas first: a wallet with no
91
96
  // ETH cannot send the approval that the USDC check exists to protect.
92
- await assertCanPayGas(read, account.address);
93
- await assertCanFundStream(read, account.address, budgetUsdc);
97
+ await assertCanPayGas(read, account.address, config.network);
98
+ await assertCanFundStream(
99
+ read,
100
+ account.address,
101
+ budgetUsdc,
102
+ config.network,
103
+ );
94
104
  }
95
105
 
96
106
  const operatorOverride = stringFlag(args, "operator");
97
- const listing = await resolveListing(context, serviceRef, {
107
+ const resolution = await resolveListingRecord(context, serviceRef, {
98
108
  required: operatorOverride === undefined,
99
109
  });
110
+ const listing = resolution.listing;
111
+ await assertRateInSignedBand(context, resolution, ratePerSecondUsdc);
100
112
  const operator = (operatorOverride ?? listing?.operator) as
101
113
  | `0x${string}`
102
114
  | undefined;
@@ -348,6 +360,65 @@ export const openCommand: CommandSpec = {
348
360
  },
349
361
  };
350
362
 
363
+ /**
364
+ * Refuse a `--rate` outside the band the operator SIGNED, before anything is
365
+ * signed or broadcast — dry run included, because the rate is an invalid input
366
+ * for this service exactly like `--rate 0` is.
367
+ *
368
+ * The escrow accepts any non-zero rate; the seller's capability gateway does
369
+ * not, and answers every request on an out-of-band stream with
370
+ * `403 stream-rate-out-of-bounds`. Without this check the CLI locked a buyer's
371
+ * deposit in a stream that could never be served, and said nothing.
372
+ *
373
+ * - Listing found: its signed descriptor is re-verified and the band enforced.
374
+ * A descriptor that does not verify is a refusal (exit 4), never "no band".
375
+ * A legacy binding signs no commercial terms, so there is nothing to enforce.
376
+ * - No listing: only reachable with `--operator`, the CLI's existing,
377
+ * explicit escape hatch for a service the registry cannot vouch for. The
378
+ * check cannot run, so it is skipped LOUDLY rather than silently. Without
379
+ * `--operator` an unreachable registry or a missing listing has already
380
+ * failed the command before this point (`resolveListingRecord`).
381
+ */
382
+ async function assertRateInSignedBand(
383
+ context: CommandContext,
384
+ resolution: Awaited<ReturnType<typeof resolveListingRecord>>,
385
+ ratePerSecondUsdc: bigint,
386
+ ): Promise<void> {
387
+ const { out } = context;
388
+ if (resolution.record === null) {
389
+ out.note(
390
+ resolution.registryUnreachable
391
+ ? "warning: the operator-signed rate band could NOT be checked because the registry is unreachable. If --rate is outside the band the operator signed, the service's gateway will refuse every request while the deposit stays escrowed. Re-run when the registry answers to have it checked."
392
+ : "note: this serviceRef has no verified listing, so there is no operator-signed rate band to check --rate against.",
393
+ );
394
+ return;
395
+ }
396
+ let bounds;
397
+ try {
398
+ bounds = await listingRateBand(resolution.record);
399
+ } catch (error) {
400
+ if (error instanceof SignedRateBoundsError) {
401
+ throw new CliError(
402
+ `the listing's operator-signed rate band could not be verified: ${error.message}`,
403
+ {
404
+ exitCode: 4,
405
+ hint: "nothing was broadcast. The CLI will not open a stream against a rate band it cannot verify.",
406
+ cause: error,
407
+ },
408
+ );
409
+ }
410
+ throw error;
411
+ }
412
+ if (bounds === null) return;
413
+ const refusal = rateBandRefusal(ratePerSecondUsdc, bounds, "--rate");
414
+ if (refusal !== undefined) {
415
+ throw new CliError(refusal, {
416
+ exitCode: 2,
417
+ hint: "pick a --rate inside the signed band (`--units atomic` takes base units; see `metrik discover` for each listing's band).",
418
+ });
419
+ }
420
+ }
421
+
351
422
  /**
352
423
  * What the buyer is actually paying for.
353
424
  *
@@ -0,0 +1,442 @@
1
+ import type { X402PayerSigner } from "@absol-labs/sdk/x402";
2
+
3
+ import {
4
+ DEFAULT_SERVER_MANDATE_TTL_SECONDS,
5
+ parseServerMandateCapsEnv,
6
+ signServerMandate,
7
+ type ServerMandateCaps,
8
+ } from "../../mandates/env.js";
9
+ import {
10
+ booleanFlag,
11
+ integerFlag,
12
+ jsonBodyFlag,
13
+ stringFlag,
14
+ stringFlags,
15
+ } from "../args.js";
16
+ import {
17
+ formatDuration,
18
+ formatUsdc,
19
+ parseAmountUnits,
20
+ parseDurationSeconds,
21
+ parseUsdcAmount,
22
+ } from "../amounts.js";
23
+ import { assertTestnetRpc } from "../config.js";
24
+ import { rpcTransport, type CliX402 } from "../deps.js";
25
+ import { CliError, configError, usageError } from "../errors.js";
26
+ import { usdcFundingHint } from "../../network.js";
27
+ import { isPrivyWalletSource, resolveCliWallet } from "../wallet.js";
28
+ import { hasHeader, parseHeaders } from "./invoke.js";
29
+ import type { X402PostSignatureError } from "../../x402-buyer/pay.js";
30
+ import type { CommandContext, CommandSpec } from "../context.js";
31
+
32
+ /** Default stream window a request-sized mandate allows (one day). */
33
+ const DEFAULT_MAX_DURATION_SECONDS = 86_400;
34
+ /** Longest response body printed in human mode before it is truncated. */
35
+ const MAX_PRINTED_BODY_CHARS = 64 * 1024;
36
+
37
+ export const payCommand: CommandSpec = {
38
+ name: "pay",
39
+ summary:
40
+ "Pay an x402 endpoint into a recoverable escrow stream, under a spend mandate",
41
+ usage:
42
+ 'metrik pay <url> [--json \'{"text":"hi"}\' | --data <body>] [--method POST] [--header "K: V"] --max-amount <usdc> [--max-rate <usdc/s>] [--max-duration <seconds>] [--min-duration <seconds>] [--operator <address>] [--units atomic]',
43
+ flags: [
44
+ "data",
45
+ "json-body",
46
+ "method",
47
+ "header",
48
+ "max-amount",
49
+ "max-rate",
50
+ "max-duration",
51
+ "min-duration",
52
+ "operator",
53
+ "units",
54
+ "allow-legacy-factory",
55
+ ],
56
+ // It moves the payer's USDC (an EIP-3009 authorization the facilitator
57
+ // settles into the escrow). The PAYER broadcasts nothing and needs no gas,
58
+ // but it is a fund-moving command and is gated like one.
59
+ signs: true,
60
+ async run(context: CommandContext): Promise<void> {
61
+ const { args, config, env, out, deps } = context;
62
+ const x402 = requireX402(deps.x402);
63
+ const [urlArg] = args.positionals;
64
+ if (urlArg === undefined) {
65
+ throw usageError("metrik pay requires the <url> of an x402 endpoint");
66
+ }
67
+ const url = parseResourceUrl(urlArg);
68
+ const units = parseAmountUnits(stringFlag(args, "units"));
69
+ const maxAmountRaw = stringFlag(args, "max-amount");
70
+ const maxAmount =
71
+ maxAmountRaw === undefined
72
+ ? undefined
73
+ : parseUsdcAmount(maxAmountRaw, units, "max-amount");
74
+ const maxRateRaw = stringFlag(args, "max-rate");
75
+ const maxRate =
76
+ maxRateRaw === undefined
77
+ ? undefined
78
+ : parseUsdcAmount(maxRateRaw, units, "max-rate");
79
+ const maxDurationRaw = stringFlag(args, "max-duration");
80
+ const maxDuration =
81
+ maxDurationRaw === undefined
82
+ ? undefined
83
+ : parseDurationSeconds(maxDurationRaw);
84
+ const minDuration = integerFlag(args, "min-duration");
85
+ const operator = stringFlag(args, "operator");
86
+ if (operator !== undefined && !/^0x[0-9a-fA-F]{40}$/.test(operator)) {
87
+ throw usageError(`--operator must be an EVM address (got "${operator}")`);
88
+ }
89
+ if (maxAmount !== undefined && maxAmount <= 0n) {
90
+ throw usageError("--max-amount must be greater than zero");
91
+ }
92
+ if (maxRate !== undefined && maxRate <= 0n) {
93
+ throw usageError("--max-rate must be greater than zero");
94
+ }
95
+
96
+ const init = buildRequest(context);
97
+
98
+ // The mandate: an operator-set standing ceiling (METRIK_AGENT_MANDATE_*),
99
+ // or one sized to exactly this payment. Either way it is SIGNED and
100
+ // `checkMandate()` gates the quote before anything is signed for the
101
+ // seller. There is no unbounded path: without standing caps, --max-amount
102
+ // is required.
103
+ const envCaps = parseServerMandateCapsEnv(env);
104
+ if (envCaps === null && maxAmount === undefined) {
105
+ throw usageError(
106
+ "metrik pay needs a spend ceiling: pass --max-amount <usdc> (or configure a standing mandate with METRIK_AGENT_MANDATE_*)",
107
+ "no spend without a mandate: the seller picks the price, so the buyer must cap it. Nothing was sent.",
108
+ );
109
+ }
110
+ const caps = intersectCaps(envCaps, {
111
+ maxAmount,
112
+ maxRate,
113
+ maxDuration,
114
+ operator: operator as `0x${string}` | undefined,
115
+ });
116
+
117
+ const wallet = await resolveCliWallet(env, {
118
+ note: out.note,
119
+ rpcUrl: config.rpcUrl,
120
+ });
121
+ if (isPrivyWalletSource(wallet.source)) {
122
+ throw configError(
123
+ "metrik pay cannot sign with a Privy wallet",
124
+ "an x402 payment is an EIP-3009 TransferWithAuthorization signature, and the Privy broker's typed-data policy allows only an InvocationCapability. Pay with METRIK_AGENT_PRIVATE_KEY or a CDP wallet.",
125
+ );
126
+ }
127
+ const { account } = wallet;
128
+ const read = deps.createReadClient(config);
129
+ await assertTestnetRpc(config, () => read.getChainId());
130
+ // The payer needs USDC only — no gas: the facilitator's relayer submits
131
+ // the authorization. A zero balance is a knowable fact before signing.
132
+ const balance = await read.usdcBalance(account.address).catch(() => null);
133
+ if (balance === 0n) {
134
+ throw new CliError(
135
+ `wallet ${account.address} holds 0 USDC on ${config.network.name}, so it cannot pay`,
136
+ {
137
+ exitCode: 3,
138
+ hint: `${usdcFundingHint(config.network)}, then re-run. (An x402 payer needs USDC only; no gas.)`,
139
+ },
140
+ );
141
+ }
142
+
143
+ const signedMandate = await signServerMandate(account, caps, {
144
+ chainId: config.chainId,
145
+ });
146
+
147
+ out.note(
148
+ `paying ${url} (ceiling ${formatUsdc(maxAmount === undefined ? caps.maxPerStreamUsdc : maxAmount < caps.maxPerStreamUsdc ? maxAmount : caps.maxPerStreamUsdc)}, mandate from ${envCaps === null ? "this command" : "METRIK_AGENT_MANDATE_*"}) …`,
149
+ );
150
+ const result = await payOrExplain(x402, {
151
+ url,
152
+ init,
153
+ signer: account as unknown as X402PayerSigner,
154
+ network: config.network,
155
+ signedMandate,
156
+ spentSoFarUsdc: 0n,
157
+ nowSeconds: deps.nowSeconds(),
158
+ ...(maxAmount === undefined ? {} : { maxAmount }),
159
+ ...(maxRate === undefined ? {} : { maxRatePerSecond: maxRate }),
160
+ ...(minDuration === undefined ? {} : { minDurationSeconds: minDuration }),
161
+ sdkOptions: {
162
+ transport: rpcTransport(config),
163
+ // A LEGACY deployment's factory is refused by the SDK unless the
164
+ // buyer opts in: streams there can still be closed and reclaimed, but
165
+ // nothing new should open on a generation being retired by default.
166
+ ...(booleanFlag(args, "allow-legacy-factory")
167
+ ? { allowLegacyFactory: true }
168
+ : {}),
169
+ },
170
+ });
171
+
172
+ const bodyText = await result.response.text();
173
+ const opener = result.metrikStreamOpener;
174
+ const quote = result.quote;
175
+ out.result({
176
+ paid: result.paid,
177
+ httpStatus: result.response.status,
178
+ contentType: result.response.headers.get("content-type"),
179
+ body: bodyText,
180
+ streamId: opener?.streamId ?? null,
181
+ opener: opener?.opener ?? null,
182
+ refundUrl: opener?.refundUrl ?? null,
183
+ escrow: opener?.escrow ?? null,
184
+ deposit: opener?.deposit ?? null,
185
+ ratePerSecond: opener?.ratePerSecond ?? null,
186
+ expiresAt: opener?.expiresAt ?? null,
187
+ operator: quote?.operator ?? null,
188
+ serviceRef: quote?.serviceRef ?? null,
189
+ minEarnSeconds: quote?.minEarnSeconds ?? null,
190
+ mandateSource: envCaps === null ? "request" : "env",
191
+ refundIsAutomatic: false,
192
+ });
193
+
194
+ if (!result.paid) {
195
+ out.print(
196
+ `The endpoint answered ${result.response.status} without asking for payment; nothing was signed or paid.`,
197
+ );
198
+ out.print(truncate(bodyText));
199
+ return;
200
+ }
201
+ out.print(`Paid. HTTP ${result.response.status}`);
202
+ out.print(truncate(bodyText));
203
+ out.print("");
204
+ if (opener !== null) {
205
+ out.table([
206
+ ["streamId", opener.streamId],
207
+ ["opener", opener.opener],
208
+ ["payer", account.address],
209
+ ...(opener.deposit === null
210
+ ? []
211
+ : ([["deposit", formatUsdc(opener.deposit)]] as const)),
212
+ ...(opener.ratePerSecond === null
213
+ ? []
214
+ : ([
215
+ ["rate", `${formatUsdc(opener.ratePerSecond)} / verified second`],
216
+ ] as const)),
217
+ ...(quote?.minEarnSeconds === null ||
218
+ quote?.minEarnSeconds === undefined
219
+ ? []
220
+ : ([
221
+ [
222
+ "fully earned after",
223
+ `${formatDuration(Number(quote.minEarnSeconds))} of verified delivery`,
224
+ ],
225
+ ] as const)),
226
+ ...(opener.expiresAt === null
227
+ ? []
228
+ : ([
229
+ ["expires", new Date(opener.expiresAt * 1000).toISOString()],
230
+ ] as const)),
231
+ ["refund url", opener.refundUrl ?? "(the seller advertised no relay)"],
232
+ ]);
233
+ out.print("");
234
+ // A stream on another (e.g. legacy) registered escrow is reached by
235
+ // naming that escrow; the CLI defaults to the network's current one.
236
+ const escrowFlag =
237
+ opener.escrow !== null &&
238
+ opener.escrow.toLowerCase() !== config.escrow.toLowerCase()
239
+ ? ` --escrow ${opener.escrow}`
240
+ : "";
241
+ out.print(
242
+ "Refunds are NOT automatic. The seller earns only for verified seconds; whatever is unearned stays in the escrow until someone reclaims it for you:",
243
+ );
244
+ out.print(
245
+ opener.refundUrl === null
246
+ ? ` metrik reclaim ${opener.streamId}${escrowFlag} (anyone may send it; the refund always goes to the payer)`
247
+ : ` metrik refund ${opener.streamId} --refund-url ${opener.refundUrl}${escrowFlag} --close --reclaim`,
248
+ );
249
+ }
250
+ },
251
+ };
252
+
253
+ const minBig = (a: bigint, b: bigint | undefined): bigint =>
254
+ b !== undefined && b < a ? b : a;
255
+
256
+ /**
257
+ * The mandate this command signs: a standing `METRIK_AGENT_MANDATE_*` ceiling
258
+ * INTERSECTED with every flag (the most restrictive value wins), or, with no
259
+ * standing ceiling, one sized to the flags. A flag can only tighten a
260
+ * standing ceiling, never loosen or bypass it; an `--operator` outside a
261
+ * standing allowlist is refused outright.
262
+ */
263
+ export function intersectCaps(
264
+ envCaps: ServerMandateCaps | null,
265
+ flags: {
266
+ readonly maxAmount: bigint | undefined;
267
+ readonly maxRate: bigint | undefined;
268
+ readonly maxDuration: number | undefined;
269
+ readonly operator: `0x${string}` | undefined;
270
+ },
271
+ ): ServerMandateCaps {
272
+ if (envCaps === null) {
273
+ const amount = flags.maxAmount as bigint;
274
+ return {
275
+ maxPerStreamUsdc: amount,
276
+ maxTotalUsdc: amount,
277
+ // No --max-rate: the price is the only cap on how fast the seller can
278
+ // earn it. Reported as minEarnSeconds so the buyer can see it.
279
+ maxRatePerSecondUsdc: flags.maxRate ?? amount,
280
+ maxDurationSeconds: flags.maxDuration ?? DEFAULT_MAX_DURATION_SECONDS,
281
+ allowedOperators: flags.operator === undefined ? [] : [flags.operator],
282
+ ttlSeconds: DEFAULT_SERVER_MANDATE_TTL_SECONDS,
283
+ };
284
+ }
285
+ let allowedOperators = envCaps.allowedOperators;
286
+ if (flags.operator !== undefined) {
287
+ if (
288
+ allowedOperators.length > 0 &&
289
+ !allowedOperators.some(
290
+ (entry) => entry.toLowerCase() === flags.operator?.toLowerCase(),
291
+ )
292
+ ) {
293
+ throw new CliError(
294
+ `--operator ${flags.operator} is not in METRIK_AGENT_MANDATE_ALLOWED_OPERATORS`,
295
+ {
296
+ exitCode: 3,
297
+ hint: "a flag can only narrow the standing mandate, never widen it. Nothing was sent.",
298
+ },
299
+ );
300
+ }
301
+ allowedOperators = [flags.operator];
302
+ }
303
+ return {
304
+ maxPerStreamUsdc: minBig(envCaps.maxPerStreamUsdc, flags.maxAmount),
305
+ maxTotalUsdc: minBig(envCaps.maxTotalUsdc, flags.maxAmount),
306
+ maxRatePerSecondUsdc: minBig(envCaps.maxRatePerSecondUsdc, flags.maxRate),
307
+ maxDurationSeconds:
308
+ flags.maxDuration !== undefined &&
309
+ flags.maxDuration < envCaps.maxDurationSeconds
310
+ ? flags.maxDuration
311
+ : envCaps.maxDurationSeconds,
312
+ allowedOperators,
313
+ ttlSeconds: envCaps.ttlSeconds,
314
+ };
315
+ }
316
+
317
+ function requireX402(x402: CliX402 | undefined): CliX402 {
318
+ if (x402 === undefined) {
319
+ throw new CliError(
320
+ "this CLI build has no x402 dependency wired (CliDependencies.x402)",
321
+ { exitCode: 4 },
322
+ );
323
+ }
324
+ return x402;
325
+ }
326
+
327
+ function parseResourceUrl(raw: string): string {
328
+ let url: URL;
329
+ try {
330
+ url = new URL(raw);
331
+ } catch {
332
+ throw usageError(`<url> must be an absolute http(s) URL (got "${raw}")`);
333
+ }
334
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
335
+ throw usageError(`<url> must be http(s) (got "${url.protocol}")`);
336
+ }
337
+ return url.toString();
338
+ }
339
+
340
+ function buildRequest(context: CommandContext): RequestInit {
341
+ const { args } = context;
342
+ const data = stringFlag(args, "data");
343
+ const jsonValue = jsonBodyFlag(args);
344
+ const jsonAlias = stringFlag(args, "json-body");
345
+ if (jsonValue !== undefined && jsonAlias !== undefined) {
346
+ throw usageError(
347
+ "give the JSON body once: --json <body> or --json-body <body>",
348
+ );
349
+ }
350
+ const jsonBody = jsonValue ?? jsonAlias;
351
+ if (data !== undefined && jsonBody !== undefined) {
352
+ throw usageError("give either --data or --json <body>, not both");
353
+ }
354
+ if (jsonBody !== undefined) {
355
+ try {
356
+ JSON.parse(jsonBody);
357
+ } catch {
358
+ throw usageError("--json <body> must be valid JSON");
359
+ }
360
+ }
361
+ const body = jsonBody ?? data;
362
+ const method = (
363
+ stringFlag(args, "method") ?? (body === undefined ? "GET" : "POST")
364
+ ).toUpperCase();
365
+ const headers = parseHeaders(stringFlags(args, "header"));
366
+ if (jsonBody !== undefined && !hasHeader(headers, "content-type")) {
367
+ headers["content-type"] = "application/json";
368
+ }
369
+ for (const name of Object.keys(headers)) {
370
+ if (name === "payment-signature" || name === "x-payment") {
371
+ throw usageError(
372
+ `do not set the ${name} header: the payment is signed by this command, after the quote passes the mandate`,
373
+ );
374
+ }
375
+ }
376
+ return {
377
+ method,
378
+ headers,
379
+ ...(body === undefined ? {} : { body }),
380
+ };
381
+ }
382
+
383
+ function truncate(text: string): string {
384
+ return text.length <= MAX_PRINTED_BODY_CHARS
385
+ ? text
386
+ : `${text.slice(0, MAX_PRINTED_BODY_CHARS)}\n… (${text.length - MAX_PRINTED_BODY_CHARS} more characters; use --json for the whole body)`;
387
+ }
388
+
389
+ async function payOrExplain(
390
+ x402: CliX402,
391
+ input: Parameters<CliX402["pay"]>[0],
392
+ ): ReturnType<CliX402["pay"]> {
393
+ try {
394
+ return await x402.pay(input);
395
+ } catch (error) {
396
+ throw explainPayFailure(error);
397
+ }
398
+ }
399
+
400
+ /** Map the SDK's and the mandate's typed failures onto CLI exit codes. */
401
+ export function explainPayFailure(error: unknown): unknown {
402
+ if (!(error instanceof Error)) return error;
403
+ switch (error.name) {
404
+ case "X402MandateDeniedError":
405
+ return new CliError(error.message, {
406
+ exitCode: 3,
407
+ hint: "raise --max-amount / --max-rate / --max-duration (or METRIK_AGENT_MANDATE_*) only if you mean to pay that much, that fast, for that long.",
408
+ cause: error,
409
+ });
410
+ case "X402PaymentRefusedError":
411
+ return new CliError(error.message, {
412
+ exitCode: 3,
413
+ hint: /exceeds maxAmount|exceeds maxRatePerSecond/.test(error.message)
414
+ ? "that ceiling is your spend mandate's (--max-amount / --max-rate or METRIK_AGENT_MANDATE_*), handed to the SDK as a second gate. Nothing was signed."
415
+ : "the quote failed one of the SDK's protections (wrong network or token, unknown factory, payTo != factory.predict(terms), not an opener payment, ...). Nothing was signed.",
416
+ cause: error,
417
+ });
418
+ case "X402PostSignatureError": {
419
+ // The signature was handed out: never say "nothing moved" unless the
420
+ // chain proves the authorization can never be used.
421
+ const post = error as X402PostSignatureError;
422
+ const recover =
423
+ post.streamId === null
424
+ ? ""
425
+ : ` Recover the unearned part: metrik refund ${post.streamId} --refund-url <the seller's relay> --close --reclaim (or metrik reclaim ${post.streamId}).`;
426
+ return new CliError(error.message, {
427
+ exitCode: 4,
428
+ hint:
429
+ post.state === "used"
430
+ ? `the money LEFT the payer.${post.streamId === null ? " Its stream could not be identified on-chain; keep this output as evidence (see docs/x402.md)." : ` It is in stream ${post.streamId} (opener ${post.opener}).`}${recover}`
431
+ : post.state === "possibly-used"
432
+ ? "whether the authorization was used could not be established: treat the payment as SPENT and check USDC.authorizationState before paying again (see docs/x402.md)."
433
+ : post.state === "unused-but-valid"
434
+ ? "it has not moved yet, but the seller holds a signature valid until its validBefore: treat it as spent, or cancel it with USDC.cancelAuthorization (needs gas). See docs/x402.md."
435
+ : "the authorization was never used and has expired: nothing moved.",
436
+ cause: error,
437
+ });
438
+ }
439
+ default:
440
+ return error;
441
+ }
442
+ }
@@ -14,6 +14,7 @@ import { writeClientOptions } from "../deps.js";
14
14
  import { isPolicyEnforced, resolveCliWallet } from "../wallet.js";
15
15
  import type { CommandContext, CommandSpec } from "../context.js";
16
16
  import type { CliReadClient } from "../deps.js";
17
+ import { escrowGenerationFor } from "../../escrow-generation.js";
17
18
 
18
19
  /**
19
20
  * The acknowledgement this command will not run without.
@@ -88,7 +89,7 @@ export const reclaimUnverifiedCommand: CommandSpec = {
88
89
  const { account } = wallet;
89
90
  const read = deps.createReadClient(config);
90
91
  await assertTestnetRpc(config, () => read.getChainId());
91
- await assertCanPayGas(read, account.address);
92
+ await assertCanPayGas(read, account.address, config.network);
92
93
 
93
94
  const stream = await read.getStreamV2(streamId);
94
95
  if (stream.reclaimed) {
@@ -107,7 +108,12 @@ export const reclaimUnverifiedCommand: CommandSpec = {
107
108
  // prevent.
108
109
  const grace = await readEscapeGrace(read);
109
110
  const now = await readChainNow(read, deps.nowSeconds());
110
- const window = escapeHatchWindow(stream, grace, now.seconds);
111
+ const window = escapeHatchWindow(
112
+ stream,
113
+ grace,
114
+ now.seconds,
115
+ escrowGenerationFor(config.chainId, config.escrow),
116
+ );
111
117
  if (!window.ready) {
112
118
  throw notReady(streamId, window, now.source);
113
119
  }