@priors/agentkit 0.2.2 → 0.2.4

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.
package/README.md CHANGED
@@ -43,8 +43,9 @@ priorsActionProvider(undefined, { autoBorrow: { perCall: "5", perDay: "10", host
43
43
 
44
44
  With it, `pay_x402_with_priors_credit` borrows the gap on its own when the wallet is short, for the listed hosts only.
45
45
  There is no default host: `hosts` names each one, exactly (here `models.example` stands for the model API you choose).
46
- The limits are `perCall` USDG a call and `perDay` USDG a UTC day in the process, for 14 days (or the pool's maximum
47
- term). It borrows only while this wallet's Autopay (AutoRepay v2) covers the new loan: the wallet is the agent's
46
+ The limits are `perCall` USDG a call and `perDay` USDG a UTC day in the process (each read exactly, at most 6 decimals),
47
+ for 14 days whatever term the model names (or the pool's maximum term). It borrows only while this wallet's Autopay
48
+ (AutoRepay v2) covers the new loan: the wallet is the agent's
48
49
  declared wallet, the plan is on under the agent's current owner, not held or paused, its limit per loan and its USDG
49
50
  approval cover the loan's due. Otherwise nothing is borrowed or paid, and the answer says to turn Autopay on. The
50
51
  wallet must be a key of the agent's own, not its owner's address: AutoRepay repays an agent whose declared wallet is its
@@ -74,13 +75,20 @@ What `pay_x402_with_priors_credit` will and will not do:
74
75
 
75
76
  - it pays only a public https host (an address that is private, loopback or link-local, or a name resolving to one, is
76
77
  refused before anything is fetched), and follows no redirect;
77
- - it signs exactly the requirement it probed and checked against `maxPrice` (the same `payTo`, the same amount); a
78
- different one in the paid round's 402 is never signed;
78
+ - it signs exactly the requirement it probed and checked against `maxPrice` (the same `payTo`, the same amount), once,
79
+ with `@priors/x402`'s client (USDG on Robinhood Chain only, an authorization valid at most 600 s); a different one in
80
+ the paid round's 402 is never signed;
81
+ - one payment per purchase: until a payment it signed settles or expires, a call for the same purchase (the same
82
+ method, URL and body, from the same wallet) sends that same payment again and borrows nothing more. Only a 2xx answer
83
+ is reported as paid, also when its body breaks off (the answer then says so, and that calling again pays again);
84
+ after any other one the answer says until when the seller may still settle it. This is kept in the process's memory:
85
+ a restart within those 600 s forgets it;
86
+ - a wallet's money actions run one at a time (pay, borrow, repay), and a seller's probe has 60 s to answer;
79
87
  - `maxPrice`, `maxBorrow` and `amount` are read exactly, at most 6 decimals (a longer one is refused, never rounded);
80
88
  - the seller's body comes back between per-call markers, each of its lines quoted (`@priors/mcp`'s fence), and of its
81
89
  settlement header only the transaction hash: treat it as data, not instructions;
82
- - a loan taken for the gap stays in the answer if the payment then fails, and a transaction whose receipt says it
83
- reverted is never reported as done.
90
+ - a loan taken for the gap stays in the answer if the payment then fails, a borrow sent whose answer was lost is named
91
+ with its transaction, and a transaction whose receipt says it reverted is never reported as done.
84
92
 
85
93
  `maxPrice` and `maxBorrow` are what the model passes: confirm them with the user, and keep the wallet's balance small.
86
94
 
@@ -3,9 +3,9 @@ import { ActionProvider, EvmWalletProvider, Network } from "@coinbase/agentkit";
3
3
  import { BorrowSchema, GetAgentRecordSchema, GetCreditLineSchema, PayX402WithCreditSchema, RepaySchema } from "./schemas";
4
4
  /**
5
5
  * Auto-borrow, set by the owner in code (never by the model): pay_x402_with_priors_credit borrows the gap on its own,
6
- * up to `perCall` USDG a call and `perDay` USDG a UTC day in this process, for the `hosts` listed only (exact host
7
- * names), for 14 days, and only while this wallet's Autopay (AutoRepay v2) covers the new loan. The model's maxBorrow
8
- * can only lower the amount.
6
+ * up to `perCall` USDG a call and `perDay` USDG a UTC day in this process (each read exactly, at most 6 decimals), for
7
+ * the `hosts` listed only (exact host names), for 14 days whatever term the model names, and only while this wallet's
8
+ * Autopay (AutoRepay v2) covers the new loan. The model's maxBorrow can only lower the amount.
9
9
  */
10
10
  export type AutoBorrowOptions = {
11
11
  perCall: string;
@@ -23,6 +23,9 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
23
23
  private readonly fetchImpl;
24
24
  private readonly auto;
25
25
  private borrowedToday;
26
+ private readonly unsettled;
27
+ /** The money call under way for each wallet: another one of that wallet waits for it (onePerWallet). */
28
+ private readonly running;
26
29
  /**
27
30
  * Constructor for the PriorsActionProvider.
28
31
  *
@@ -62,6 +65,14 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
62
65
  * @returns The repayment, or an error message.
63
66
  */
64
67
  repay(walletProvider: EvmWalletProvider, args: z.infer<typeof RepaySchema>): Promise<string>;
68
+ /**
69
+ * repay_priors_loan's work, run as the wallet's one money call (onePerWallet).
70
+ *
71
+ * @param walletProvider - The wallet provider.
72
+ * @param args - The loan id, and optionally its agent id.
73
+ * @returns The repayment, or an error message.
74
+ */
75
+ private repayLoan;
65
76
  /**
66
77
  * Pays an x402 URL in USDG on Robinhood Chain, borrowing the gap from the Priors line when the wallet is short.
67
78
  *
@@ -102,12 +113,30 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
102
113
  */
103
114
  supportsNetwork: (network: Network) => boolean;
104
115
  /**
105
- * The x402 v2 `exact` requirement for USDG on Robinhood Chain, from the 402's header or body.
116
+ * What became of a payment sent: paid only on a 2xx answer. Anything else (a dropped connection, no answer in time,
117
+ * a 5xx, a 402, a redirect) leaves it signed and sent, cashable by the seller until it expires, and a later call for
118
+ * the purchase sends it again (@priors/mcp's pay_url answer). A body that fails mid-read (a reset, or the request's
119
+ * time bound firing during a long answer) is said, never an error that hides the payment (@priors/mcp's issue #19,
120
+ * GHSA-87h5): once paid, the purchase is complete, so a call again for it pays again.
121
+ *
122
+ * @param X - @priors/x402 (its readCapped and SKEW_SECONDS).
123
+ * @param r - What @priors/x402's resend answered.
124
+ * @param s - The payment sent.
125
+ * @returns The answer's words for it.
126
+ */
127
+ private outcome;
128
+ /**
129
+ * Runs a wallet's money calls (pay, borrow, repay) one at a time, as @priors/x402's createPayer queues its payments
130
+ * and @priors/mcp runs its money calls: two calls at once on a short wallet would each read the balance short and each
131
+ * borrow, both passing auto-borrow's Autopay check on an approval that covers one loan (GHSA-482p F3, GHSA-87h5). A
132
+ * call for a purchase another call is paying waits for it, then finds its payment while that may still settle; once
133
+ * it is paid (a 2xx), the purchase is complete and a call for it is a new one.
106
134
  *
107
- * @param probe - The 402 response.
108
- * @returns The requirement, or null.
135
+ * @param walletProvider - The wallet whose calls queue.
136
+ * @param fn - The call.
137
+ * @returns What the call answers.
109
138
  */
110
- private usdgRequirement;
139
+ private onePerWallet;
111
140
  /**
112
141
  * Borrows `amount` atomic USDG for `days` from the agent's line into this wallet.
113
142
  *
@@ -117,6 +146,7 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
117
146
  * @param days - The term in days.
118
147
  * @param check - Called with the quoted fee before the borrow is sent; a throw refuses it.
119
148
  * @param did - What did not happen when the borrow is refused ("borrowed", "borrowed or paid").
149
+ * @param onSend - Called once every check has passed, right before the borrow's transaction is sent.
120
150
  * @returns The loan.
121
151
  */
122
152
  private borrowAmount;
@@ -14,33 +14,44 @@ const node_dns_1 = require("node:dns");
14
14
  const node_net_1 = require("node:net");
15
15
  const zod_1 = require("zod");
16
16
  const viem_1 = require("viem");
17
- const fetch_1 = require("@x402/fetch");
18
- const client_1 = require("@x402/evm/exact/client");
19
17
  const agentkit_1 = require("@coinbase/agentkit");
20
18
  const schemas_1 = require("./schemas");
21
19
  const constants_1 = require("./constants");
22
20
  // @priors/mcp's data fence, sdk/fence.mjs copied byte for byte (test/provider.test.cjs checks the copy)
23
21
  const fence_js_1 = require("./fence.js");
22
+ // @priors/x402's payer pieces (the purchase's identity, the resend of a signed payment, the USDG client) and the x402
23
+ // client they run on: ES modules, loaded with import() from this CommonJS package
24
+ const x402 = () => import("@priors/x402");
25
+ const x402Fetch = () => import("@x402/fetch");
26
+ /** A paid request's resends while its seller answers "settlement pending", as @priors/mcp's pay_url sends them. */
27
+ const RESEND = { retries: 2, maxSleepMs: 10_000 };
24
28
  const usdg = (atomic) => (0, viem_1.formatUnits)(atomic, constants_1.USDG_DECIMALS);
25
29
  const sameAddress = (a, b) => String(a).toLowerCase() === b.toLowerCase();
26
30
  const utcDay = () => new Date().toISOString().slice(0, 10);
27
31
  /** A refusal before anything is sent (its message is the answer). */
28
32
  class Refusal extends Error {
29
33
  }
34
+ /** A transaction mined and reverted: the chain shows it moved nothing. */
35
+ class Reverted extends Error {
36
+ }
37
+ /** A borrow sent whose answer was lost: it may have opened a loan (its message says so, with its transaction). */
38
+ class Unconfirmed extends Error {
39
+ }
30
40
  /**
31
41
  * Atomic USDG from an amount the model gives: a plain decimal of at most 6 places, read exactly. viem's parseUnits
32
42
  * rounds a longer one to the nearest unit, so a cap of 0.0999999 would admit 0.10 (@priors/mcp's P-28).
33
43
  *
34
44
  * @param value - The amount, e.g. "0.10".
35
45
  * @param name - Its argument's name, for the refusal.
46
+ * @param after - The refusal's last words.
36
47
  * @returns Atomic USDG.
37
48
  */
38
- function exactUsdg(value, name) {
49
+ function exactUsdg(value, name, after = " Nothing was sent.") {
39
50
  const s = String(value).trim();
40
51
  if (!/^\d+(\.\d+)?$/.test(s))
41
- throw new Refusal(`${name} must be a plain amount of USDG, such as 0.10. Nothing was sent.`);
52
+ throw new Refusal(`${name} must be a plain amount of USDG, such as 0.10.${after}`);
42
53
  if ((s.split(".")[1] ?? "").length > constants_1.USDG_DECIMALS)
43
- throw new Refusal(`${name} ${s} has more than ${constants_1.USDG_DECIMALS} decimals, and USDG counts in millionths: give at most 6 decimals. Nothing was sent.`);
54
+ throw new Refusal(`${name} ${s} has more than ${constants_1.USDG_DECIMALS} decimals, and USDG counts in millionths: give at most 6 decimals.${after}`);
44
55
  return (0, viem_1.parseUnits)(s, constants_1.USDG_DECIMALS);
45
56
  }
46
57
  /**
@@ -55,7 +66,7 @@ function mined(receipt, what, hash) {
55
66
  if (status === "success" || status === 1 || status === 1n || status === "0x1")
56
67
  return;
57
68
  if (status === "reverted" || status === 0 || status === 0n || status === "0x0")
58
- throw new Error(`the ${what} transaction ${hash} reverted on chain: it moved nothing`);
69
+ throw new Reverted(`the ${what} transaction ${hash} reverted on chain: it moved nothing`);
59
70
  throw new Error(`the ${what} transaction ${hash} could not be confirmed (its receipt has no status): check it before acting on it`);
60
71
  }
61
72
  /** Whether an IPv4 address (four numbers) is not a public one: this host, private, CGNAT, link-local, test or reserved. */
@@ -164,6 +175,17 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
164
175
  fetchImpl;
165
176
  auto;
166
177
  borrowedToday = { day: "", amount: 0n };
178
+ // One signature per purchase (GHSA-pr4v), @priors/x402's rule (createPayer's unsettled payments, @priors/mcp's
179
+ // outstanding ones): a payment this provider signed for a wallet's purchase (the method, the URL as the seller reads
180
+ // it and the body: @priors/x402's purchaseKey) and has not seen settle is sent again by a later call for that
181
+ // purchase, never signed again, until it expires.
182
+ // SHORTCUT: kept in this process's memory, as createPayer keeps it (@priors/mcp adds its PRIORS_STATE_DIR file). A
183
+ // restart while such a payment may still settle (at most 600 s, plus SKEW_SECONDS) forgets it, and a call for the same
184
+ // purchase after the restart signs again: at most one more payment of at most maxPrice, to the seller the call named
185
+ // (P-15's class). Upgrade when the provider gets a place to keep state, or on a report of it.
186
+ unsettled = new Map();
187
+ /** The money call under way for each wallet: another one of that wallet waits for it (onePerWallet). */
188
+ running = new Map();
167
189
  /**
168
190
  * Constructor for the PriorsActionProvider.
169
191
  *
@@ -178,8 +200,9 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
178
200
  this.auto = null;
179
201
  return;
180
202
  }
181
- const perCall = (0, viem_1.parseUnits)(String(a.perCall), constants_1.USDG_DECIMALS);
182
- const perDay = (0, viem_1.parseUnits)(String(a.perDay), constants_1.USDG_DECIMALS);
203
+ // read exactly, as the model's amounts are: a limit is never rounded up to the next unit (RT-4's rule)
204
+ const perCall = exactUsdg(String(a.perCall), "autoBorrow.perCall", "");
205
+ const perDay = exactUsdg(String(a.perDay), "autoBorrow.perDay", "");
183
206
  if (perCall <= 0n)
184
207
  throw new Error("autoBorrow.perCall must be above 0");
185
208
  if (perDay < perCall)
@@ -251,15 +274,17 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
251
274
  * @returns The loan, or an error message.
252
275
  */
253
276
  async borrow(walletProvider, args) {
254
- try {
255
- const loan = await this.borrowAmount(walletProvider, args.agentId, exactUsdg(args.amount, "amount"), args.days);
256
- return `Borrowed ${usdg(loan.amount)} USDG from agent #${args.agentId}'s Priors line: loan #${loan.loanId}, fee ${usdg(loan.fee)} USDG, due ${loan.dueAt}. Transaction: ${loan.hash}`;
257
- }
258
- catch (error) {
259
- if (error instanceof Refusal)
260
- return `Error: ${error.message}`;
261
- return `Error borrowing from Priors: ${(0, fence_js_1.unfenced)(String(error))}`;
262
- }
277
+ return this.onePerWallet(walletProvider, async () => {
278
+ try {
279
+ const loan = await this.borrowAmount(walletProvider, args.agentId, exactUsdg(args.amount, "amount"), args.days);
280
+ return `Borrowed ${usdg(loan.amount)} USDG from agent #${args.agentId}'s Priors line: loan #${loan.loanId}, fee ${usdg(loan.fee)} USDG, due ${loan.dueAt}. Transaction: ${loan.hash}`;
281
+ }
282
+ catch (error) {
283
+ if (error instanceof Refusal || error instanceof Unconfirmed)
284
+ return `Error: ${error.message}`;
285
+ return `Error borrowing from Priors: ${(0, fence_js_1.unfenced)(String(error))}`;
286
+ }
287
+ });
263
288
  }
264
289
  /**
265
290
  * Repays a Priors loan in full from this wallet.
@@ -269,6 +294,16 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
269
294
  * @returns The repayment, or an error message.
270
295
  */
271
296
  async repay(walletProvider, args) {
297
+ return this.onePerWallet(walletProvider, () => this.repayLoan(walletProvider, args));
298
+ }
299
+ /**
300
+ * repay_priors_loan's work, run as the wallet's one money call (onePerWallet).
301
+ *
302
+ * @param walletProvider - The wallet provider.
303
+ * @param args - The loan id, and optionally its agent id.
304
+ * @returns The repayment, or an error message.
305
+ */
306
+ async repayLoan(walletProvider, args) {
272
307
  try {
273
308
  const loan = (await walletProvider.readContract({
274
309
  address: constants_1.PRIORS_POOL,
@@ -374,96 +409,157 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
374
409
  : args.maxBorrow === undefined || named > auto.perCall
375
410
  ? auto.perCall
376
411
  : named;
377
- const days = args.days ?? (auto ? constants_1.AUTO_TERM_DAYS : constants_1.DEFAULT_TERM_DAYS);
378
- const probe = await this.fetchImpl(args.url, init());
379
- if (probe.status >= 300 && probe.status < 400) {
380
- const to = probe.headers.get("location");
381
- return (0, fence_js_1.guarded)(`The URL answered a redirect (HTTP ${probe.status}), not followed: nothing was paid.${to ? `\n${(0, fence_js_1.fenced)(to.slice(0, 500), "redirect target")}` : ""}`);
382
- }
383
- if (probe.status !== 402)
384
- return (0, fence_js_1.guarded)(`No payment asked (HTTP ${probe.status}). Response:\n${(0, fence_js_1.fenced)((await probe.text()).slice(0, 2000), "response body")}`);
385
- const requirement = await this.usdgRequirement(probe);
386
- if (!requirement)
387
- return "Error: the URL asks for no USDG payment on Robinhood Chain (x402 exact).";
388
- const price = BigInt(requirement.amount ?? "0");
389
- if (price > maxPrice)
390
- return `Error: the URL asks ${usdg(price)} USDG, above maxPrice ${args.maxPrice}. Nothing was paid.`;
412
+ // auto-borrow's term is the owner's (14 days, brought down to the pool's maxTerm below), never the model's days
413
+ const days = auto ? constants_1.AUTO_TERM_DAYS : args.days ?? constants_1.DEFAULT_TERM_DAYS;
414
+ const X = await x402();
391
415
  const me = walletProvider.getAddress();
392
- const balance = (await walletProvider.readContract({
393
- address: constants_1.USDG,
394
- abi: viem_1.erc20Abi,
395
- functionName: "balanceOf",
396
- args: [me],
397
- }));
398
- if (balance < price) {
399
- const params = (await walletProvider.readContract({
400
- address: constants_1.PRIORS_POOL,
401
- abi: constants_1.POOL_ABI,
402
- functionName: "getParams",
403
- }));
404
- const gap = price - balance;
405
- const amount = gap > params.minLoan ? gap : params.minLoan;
406
- if (auto && !autoHere)
407
- return `Error: the wallet holds ${usdg(balance)} USDG, short of ${usdg(price)}, and auto-borrow borrows only to pay ${[...auto.hosts].join(", ")}. Nothing was borrowed or paid.`;
408
- if (amount > maxBorrow) {
409
- return `Error: the wallet holds ${usdg(balance)} USDG, short of ${usdg(price)}; borrowing ${usdg(amount)} (the pool's minimum loan is ${usdg(params.minLoan)}) is above ${auto ? `the most this call may borrow, ${usdg(maxBorrow)}` : `maxBorrow ${args.maxBorrow || "0"}`}. Nothing was paid.`;
416
+ const purchase = `${me.toLowerCase()} ${await X.purchaseKey(new Request(args.url, init()))}`;
417
+ return await this.onePerWallet(walletProvider, async () => {
418
+ // a payment signed for this purchase that may still settle is sent again, before anything is probed or borrowed
419
+ const now = Math.floor(Date.now() / 1000);
420
+ for (const [k, v] of this.unsettled)
421
+ if (v.validBefore + X.SKEW_SECONDS <= now)
422
+ this.unsettled.delete(k);
423
+ const out = this.unsettled.get(purchase);
424
+ if (out) {
425
+ const r = await X.resend(args.url, out.paymentHeaders, { ...RESEND, init: init(), fetchImpl: this.fetchImpl, timeoutMs: X.DEFAULT_TIMEOUT_MS });
426
+ if (r.response.ok)
427
+ this.unsettled.delete(purchase);
428
+ const first = out.borrowed ? `Its first attempt: ${out.borrowed}` : "\n";
429
+ return (0, fence_js_1.guarded)(`No new payment was signed: the payment of ${usdg(out.price)} USDG to ${out.payTo} signed earlier for this purchase was sent again. ${first}${await this.outcome(X, r, out)}`);
430
+ }
431
+ // the probe has a time bound of its own, as the payer's (DEFAULT_TIMEOUT_MS), its body included: the wallet's
432
+ // other money calls wait for this one
433
+ let probe;
434
+ try {
435
+ probe = await this.fetchImpl(args.url, { ...init(), signal: AbortSignal.timeout(X.DEFAULT_TIMEOUT_MS) });
410
436
  }
411
- // auto: the day's room is taken here, before any await, so two calls running at once never both pass the
412
- // limit; it is given back whenever the borrow stops before it is sent, refused or a read failing (GHSA-q4cg);
413
- // a borrow whose sending began stays counted (its answer may be lost: the safe direction)
414
- let reserved = null;
415
- let sending = false;
416
- if (auto) {
417
- const today = utcDay();
418
- if (this.borrowedToday.day !== today)
419
- this.borrowedToday = { day: today, amount: 0n };
420
- if (this.borrowedToday.amount + amount > auto.perDay)
421
- return `Error: the wallet holds ${usdg(balance)} USDG, short of ${usdg(price)}, and auto-borrow's limit of ${usdg(auto.perDay)} USDG a day has ${usdg(auto.perDay - this.borrowedToday.amount)} left in this process, less than ${usdg(amount)}. Nothing was borrowed or paid.`;
422
- this.borrowedToday.amount += amount;
423
- reserved = { day: today, amount };
437
+ catch (error) {
438
+ const name = error?.name;
439
+ if (name === "TimeoutError" || name === "AbortError")
440
+ return `Error: ${host} did not answer within ${X.DEFAULT_TIMEOUT_MS / 1000} s. Nothing was signed or paid.`;
441
+ throw error;
424
442
  }
425
- // auto: 14 days, brought down to the pool's maxTerm; otherwise the term asked, as before
426
- const termDays = auto && params.maxTerm !== undefined && BigInt(days) * 86400n > BigInt(params.maxTerm) ? Number(BigInt(params.maxTerm) / 86400n) : days;
427
- const loan = await this.borrowAmount(walletProvider, args.agentId, amount, termDays, auto
428
- ? async (fee) => {
429
- await this.autopayCovers(walletProvider, args.agentId, amount + fee);
430
- sending = true; // the borrow's transaction is sent right after this check
443
+ const probeText = async () => {
444
+ try {
445
+ return (await X.readCapped(probe)).text;
431
446
  }
432
- : undefined, "borrowed or paid")
433
- .catch((error) => {
434
- if (reserved && !sending && this.borrowedToday.day === reserved.day)
435
- this.borrowedToday.amount -= reserved.amount;
436
- throw error;
437
- });
438
- borrowed = `Borrowed ${usdg(loan.amount)} USDG first: loan #${loan.loanId}, fee ${usdg(loan.fee)}, due ${loan.dueAt} (transaction ${loan.hash}). ${auto ? "Auto-borrow: Autopay repays it from this wallet in its window, the last hours before it is due; keep its due in the wallet by then." : "Repay it with repay_priors_loan before then."}\n`;
439
- }
440
- // the payment signed is the requirement probed (and checked against maxPrice, and borrowed for): the paid
441
- // round's own 402 is asked again, and anything it names but that, another payTo or another amount, is never signed
442
- const payTo = String(requirement.payTo);
443
- const client = new fetch_1.x402Client()
444
- .register(constants_1.ROBINHOOD_NETWORK, new client_1.ExactEvmScheme(walletProvider.toSigner()))
445
- .registerPolicy((_version, reqs) => reqs.filter(r => {
446
- const q = r;
447
- return (q.scheme === "exact" &&
448
- q.network === constants_1.ROBINHOOD_NETWORK &&
449
- sameAddress(q.asset, constants_1.USDG) &&
450
- sameAddress(q.payTo, payTo) &&
451
- /^\d+$/.test(String(q.amount)) &&
452
- BigInt(String(q.amount)) === price);
453
- }));
454
- const paid = await (0, fetch_1.wrapFetchWithPayment)(this.fetchImpl, client)(args.url, init());
455
- // of the settlement header, only its transaction hash: the rest is the seller's words
456
- const tx = settledTx(paid.headers.get("payment-response") || paid.headers.get("x-payment-response"));
457
- const body = `Response:\n${(0, fence_js_1.fenced)((await paid.text()).slice(0, 2000), "response body")}`;
458
- if (paid.status === 402)
459
- return (0, fence_js_1.guarded)(`${borrowed}The payment of ${usdg(price)} USDG to ${payTo} was signed but not accepted (HTTP 402): nothing shows it was paid.\n${body}`);
460
- if (paid.status >= 300 && paid.status < 400)
461
- return (0, fence_js_1.guarded)(`${borrowed}The payment of ${usdg(price)} USDG to ${payTo} was signed, and the URL answered a redirect (HTTP ${paid.status}), not followed${tx ? `; settled in ${tx}` : ": it may still settle"}.`);
462
- return (0, fence_js_1.guarded)(`${borrowed}Paid ${usdg(price)} USDG to ${payTo} (HTTP ${paid.status})${tx ? `; settled in ${tx}` : ""}.\n${body}`);
447
+ catch {
448
+ return "";
449
+ }
450
+ };
451
+ if (probe.status >= 300 && probe.status < 400) {
452
+ const to = probe.headers.get("location");
453
+ return (0, fence_js_1.guarded)(`The URL answered a redirect (HTTP ${probe.status}), not followed: nothing was paid.${to ? `\n${(0, fence_js_1.fenced)(to.slice(0, 500), "redirect target")}` : ""}`);
454
+ }
455
+ if (probe.status !== 402)
456
+ return (0, fence_js_1.guarded)(`No payment asked (HTTP ${probe.status}). Response:\n${(0, fence_js_1.fenced)((await probeText()).slice(0, 2000), "response body")}`);
457
+ // the 402 as @priors/x402's payer reads it (the PAYMENT-REQUIRED header, else a v2 body), and its requirement as
458
+ // the payer picks it: exact USDG on Robinhood Chain by EIP-3009, on USDG's own EIP-712 domain, to a 0x payTo
459
+ const { x402Client, x402HTTPClient } = await x402Fetch();
460
+ const http = new x402HTTPClient(new x402Client());
461
+ let body;
462
+ try {
463
+ const text = await probeText();
464
+ body = text ? JSON.parse(text) : undefined;
465
+ }
466
+ catch {
467
+ body = undefined;
468
+ }
469
+ let required;
470
+ try {
471
+ required = http.getPaymentRequiredResponse(n => probe.headers.get(n), body);
472
+ }
473
+ catch {
474
+ required = body && body.x402Version === 2 && Array.isArray(body.accepts) ? body : null;
475
+ }
476
+ const requirement = required && required.x402Version === 2 ? X.pickV2Requirement(required.accepts, constants_1.USDG) : null;
477
+ if (!required || !requirement)
478
+ return "Error: the URL asks for no USDG payment on Robinhood Chain (x402 v2 exact, EIP-3009).";
479
+ const price = BigInt(requirement.amount);
480
+ if (price > maxPrice)
481
+ return `Error: the URL asks ${usdg(price)} USDG, above maxPrice ${args.maxPrice}. Nothing was paid.`;
482
+ const payTo = String(requirement.payTo);
483
+ // the client that signs (@priors/x402's createUsdgClient): USDG on Robinhood Chain only, at most the probed price,
484
+ // an authorization valid at most 600 s; asked before anything is borrowed whether it signs this requirement
485
+ // (@priors/x402's GHSA-f35g: a refusal at signing time must never come after a loan)
486
+ const client = X.createUsdgClient({ signer: walletProvider.toSigner(), maxPrice: price, asset: constants_1.USDG });
487
+ try {
488
+ client.selectPaymentRequirements(2, [requirement]);
489
+ }
490
+ catch {
491
+ return "Error: x402 would not sign the requirement this URL asks for. Nothing was borrowed or paid.";
492
+ }
493
+ const balance = (await walletProvider.readContract({
494
+ address: constants_1.USDG,
495
+ abi: viem_1.erc20Abi,
496
+ functionName: "balanceOf",
497
+ args: [me],
498
+ }));
499
+ if (balance < price) {
500
+ const params = (await walletProvider.readContract({
501
+ address: constants_1.PRIORS_POOL,
502
+ abi: constants_1.POOL_ABI,
503
+ functionName: "getParams",
504
+ }));
505
+ const gap = price - balance;
506
+ const amount = gap > params.minLoan ? gap : params.minLoan;
507
+ if (auto && !autoHere)
508
+ return `Error: the wallet holds ${usdg(balance)} USDG, short of ${usdg(price)}, and auto-borrow borrows only to pay ${[...auto.hosts].join(", ")}. Nothing was borrowed or paid.`;
509
+ if (amount > maxBorrow) {
510
+ return `Error: the wallet holds ${usdg(balance)} USDG, short of ${usdg(price)}; borrowing ${usdg(amount)} (the pool's minimum loan is ${usdg(params.minLoan)}) is above ${auto ? `the most this call may borrow, ${usdg(maxBorrow)}` : `maxBorrow ${args.maxBorrow || "0"}`}. Nothing was paid.`;
511
+ }
512
+ // auto: the day's room is taken here, before any await, so two calls running at once never both pass the
513
+ // limit; it is given back whenever the borrow stops before it is sent, refused or a read failing, the
514
+ // controller check's included (GHSA-q4cg, GHSA-87h5), and when it is mined and reverts (it moved nothing:
515
+ // GHSA-mc89); a borrow whose sending began and whose answer is lost stays counted (the safe direction)
516
+ let reserved = null;
517
+ let sending = false;
518
+ if (auto) {
519
+ const today = utcDay();
520
+ if (this.borrowedToday.day !== today)
521
+ this.borrowedToday = { day: today, amount: 0n };
522
+ if (this.borrowedToday.amount + amount > auto.perDay)
523
+ return `Error: the wallet holds ${usdg(balance)} USDG, short of ${usdg(price)}, and auto-borrow's limit of ${usdg(auto.perDay)} USDG a day has ${usdg(auto.perDay - this.borrowedToday.amount)} left in this process, less than ${usdg(amount)}. Nothing was borrowed or paid.`;
524
+ this.borrowedToday.amount += amount;
525
+ reserved = { day: today, amount };
526
+ }
527
+ // auto: 14 days, brought down to the pool's maxTerm; otherwise the term asked, as before
528
+ const termDays = auto && params.maxTerm !== undefined && BigInt(days) * 86400n > BigInt(params.maxTerm) ? Number(BigInt(params.maxTerm) / 86400n) : days;
529
+ const loan = await this.borrowAmount(walletProvider, args.agentId, amount, termDays, auto ? (fee) => this.autopayCovers(walletProvider, args.agentId, amount + fee) : undefined, "borrowed or paid", () => {
530
+ sending = true; // right before the borrow's transaction is sent, every check passed
531
+ })
532
+ .catch((error) => {
533
+ if (reserved && (!sending || error instanceof Reverted) && this.borrowedToday.day === reserved.day)
534
+ this.borrowedToday.amount -= reserved.amount;
535
+ throw error;
536
+ });
537
+ borrowed = `Borrowed ${usdg(loan.amount)} USDG first: loan #${loan.loanId}, fee ${usdg(loan.fee)}, due ${loan.dueAt} (transaction ${loan.hash}). ${auto ? "Auto-borrow: Autopay repays it from this wallet in its window, the last hours before it is due; keep its due in the wallet by then." : "Repay it with repay_priors_loan before then."}\n`;
538
+ }
539
+ // the one signature for this purchase: the requirement probed (checked against maxPrice, and borrowed for), kept
540
+ // before it leaves, and from then on only sent again (@priors/x402's resend: once the payment may be out, a
541
+ // dropped connection or a timeout is an answer, never an error that loses it)
542
+ const payload = await client.createPaymentPayload({ ...required, accepts: [requirement] });
543
+ const validBefore = Number(payload.payload.authorization?.validBefore);
544
+ const signed = {
545
+ paymentHeaders: http.encodePaymentSignatureHeader(payload),
546
+ validBefore: Number.isSafeInteger(validBefore) ? validBefore : now + X.MAX_VALIDITY_SECONDS,
547
+ price,
548
+ payTo,
549
+ borrowed,
550
+ };
551
+ this.unsettled.set(purchase, signed);
552
+ const r = await X.resend(args.url, signed.paymentHeaders, { ...RESEND, init: init(), fetchImpl: this.fetchImpl, timeoutMs: X.DEFAULT_TIMEOUT_MS });
553
+ if (r.response.ok)
554
+ this.unsettled.delete(purchase);
555
+ return (0, fence_js_1.guarded)(`${borrowed}${await this.outcome(X, r, signed)}`);
556
+ });
463
557
  }
464
558
  catch (error) {
465
559
  if (error instanceof Refusal)
466
560
  return (0, fence_js_1.guarded)(`${borrowed}Error: ${error.message}`);
561
+ if (error instanceof Unconfirmed)
562
+ return (0, fence_js_1.guarded)(`Error: ${error.message} Nothing was signed or paid.`);
467
563
  return (0, fence_js_1.guarded)(`${borrowed}Error paying ${(0, fence_js_1.unfenced)(args.url)} with Priors credit: ${(0, fence_js_1.unfenced)(String(error))}`);
468
564
  }
469
565
  }
@@ -552,35 +648,61 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
552
648
  */
553
649
  supportsNetwork = (network) => network.protocolFamily === "evm" && String(network.chainId) === constants_1.ROBINHOOD_CHAIN_ID;
554
650
  /**
555
- * The x402 v2 `exact` requirement for USDG on Robinhood Chain, from the 402's header or body.
651
+ * What became of a payment sent: paid only on a 2xx answer. Anything else (a dropped connection, no answer in time,
652
+ * a 5xx, a 402, a redirect) leaves it signed and sent, cashable by the seller until it expires, and a later call for
653
+ * the purchase sends it again (@priors/mcp's pay_url answer). A body that fails mid-read (a reset, or the request's
654
+ * time bound firing during a long answer) is said, never an error that hides the payment (@priors/mcp's issue #19,
655
+ * GHSA-87h5): once paid, the purchase is complete, so a call again for it pays again.
556
656
  *
557
- * @param probe - The 402 response.
558
- * @returns The requirement, or null.
657
+ * @param X - @priors/x402 (its readCapped and SKEW_SECONDS).
658
+ * @param r - What @priors/x402's resend answered.
659
+ * @param s - The payment sent.
660
+ * @returns The answer's words for it.
559
661
  */
560
- async usdgRequirement(probe) {
561
- let accepts = [];
562
- const header = probe.headers.get("payment-required");
563
- if (header) {
564
- try {
565
- accepts = JSON.parse(Buffer.from(header, "base64").toString("utf8")).accepts ?? [];
566
- }
567
- catch {
568
- accepts = [];
569
- }
662
+ async outcome(X, r, s) {
663
+ const res = r.response;
664
+ // of the settlement header, only its transaction hash: the rest is the seller's words
665
+ const tx = settledTx(res.headers.get("payment-response") || res.headers.get("x-payment-response"));
666
+ let text = "";
667
+ let unread = false;
668
+ try {
669
+ ({ text } = await X.readCapped(res));
570
670
  }
571
- if (!accepts.length) {
572
- try {
573
- accepts = (await probe.clone().json()).accepts ?? [];
574
- }
575
- catch {
576
- accepts = [];
577
- }
671
+ catch {
672
+ unread = true;
673
+ }
674
+ const lost = "\nThe response body could not be read completely (the connection failed while it was sent).";
675
+ const body = text ? `\nResponse:\n${(0, fence_js_1.fenced)(text.slice(0, 2000), "response body")}` : unread ? lost : "";
676
+ const status = r.timedOut ? "no answer in time" : r.transportError ? "the connection was lost" : `HTTP ${res.status}`;
677
+ if (res.ok)
678
+ return `Paid ${usdg(s.price)} USDG to ${s.payTo} (${status})${tx ? `; settled in ${tx}` : ""}.${body}${unread ? " This does not undo the payment, and calling again for this purchase pays again: ask the seller for the result instead." : ""}`;
679
+ const until = new Date((s.validBefore + X.SKEW_SECONDS) * 1000).toISOString();
680
+ const redirect = res.status >= 300 && res.status < 400 ? ", a redirect, not followed" : "";
681
+ return `The payment of ${usdg(s.price)} USDG to ${s.payTo} was signed and sent (${status}${redirect}), and the seller may still settle it until ${until}${tx ? ` (it names ${tx})` : ""}: do NOT call pay_x402_with_priors_credit again for this purchase (the same method, URL and body) before then. A later call for it sends this same payment again, never a new one.${body}`;
682
+ }
683
+ /**
684
+ * Runs a wallet's money calls (pay, borrow, repay) one at a time, as @priors/x402's createPayer queues its payments
685
+ * and @priors/mcp runs its money calls: two calls at once on a short wallet would each read the balance short and each
686
+ * borrow, both passing auto-borrow's Autopay check on an approval that covers one loan (GHSA-482p F3, GHSA-87h5). A
687
+ * call for a purchase another call is paying waits for it, then finds its payment while that may still settle; once
688
+ * it is paid (a 2xx), the purchase is complete and a call for it is a new one.
689
+ *
690
+ * @param walletProvider - The wallet whose calls queue.
691
+ * @param fn - The call.
692
+ * @returns What the call answers.
693
+ */
694
+ async onePerWallet(walletProvider, fn) {
695
+ const key = String(walletProvider.getAddress()).toLowerCase();
696
+ const run = (this.running.get(key) ?? Promise.resolve()).then(fn);
697
+ const done = run.then(() => undefined, () => undefined);
698
+ this.running.set(key, done);
699
+ try {
700
+ return await run;
701
+ }
702
+ finally {
703
+ if (this.running.get(key) === done)
704
+ this.running.delete(key);
578
705
  }
579
- return (accepts.find(r => r.scheme === "exact" &&
580
- r.network === constants_1.ROBINHOOD_NETWORK &&
581
- sameAddress(r.asset, constants_1.USDG) &&
582
- /^\d+$/.test(String(r.amount)) &&
583
- /^0x[0-9a-fA-F]{40}$/.test(String(r.payTo))) ?? null);
584
706
  }
585
707
  /**
586
708
  * Borrows `amount` atomic USDG for `days` from the agent's line into this wallet.
@@ -591,9 +713,10 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
591
713
  * @param days - The term in days.
592
714
  * @param check - Called with the quoted fee before the borrow is sent; a throw refuses it.
593
715
  * @param did - What did not happen when the borrow is refused ("borrowed", "borrowed or paid").
716
+ * @param onSend - Called once every check has passed, right before the borrow's transaction is sent.
594
717
  * @returns The loan.
595
718
  */
596
- async borrowAmount(walletProvider, agentId, amount, days, check, did = "borrowed") {
719
+ async borrowAmount(walletProvider, agentId, amount, days, check, did = "borrowed", onSend) {
597
720
  const me = walletProvider.getAddress();
598
721
  const term = BigInt(days * 86400);
599
722
  const [fee] = (await walletProvider.readContract({
@@ -607,6 +730,7 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
607
730
  // the same rule as repay, before anything is sent: no key borrows here for an agent it would then be refused to
608
731
  // repay for
609
732
  await this.control(walletProvider, BigInt(agentId), did);
733
+ onSend?.();
610
734
  const hash = await walletProvider.sendTransaction({
611
735
  to: constants_1.PRIORS_POOL,
612
736
  data: (0, viem_1.encodeFunctionData)({
@@ -615,7 +739,15 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
615
739
  args: [BigInt(agentId), amount, term, me, fee],
616
740
  }),
617
741
  });
618
- const receipt = await walletProvider.waitForTransactionReceipt(hash);
742
+ // sent: an answer lost from here on may hide a loan, so it is said with its transaction, never a bare error (P-18's
743
+ // rule, GHSA-87h5)
744
+ let receipt;
745
+ try {
746
+ receipt = await walletProvider.waitForTransactionReceipt(hash);
747
+ }
748
+ catch (error) {
749
+ throw new Unconfirmed(`the borrow of ${usdg(amount)} USDG was sent (transaction ${hash}) and its answer was lost (${(0, fence_js_1.unfenced)(String(error))}), so it may have opened a loan: check that transaction before calling again, and repay the loan with repay_priors_loan before its due date.`);
750
+ }
619
751
  mined(receipt, "borrow", hash);
620
752
  let loanId = "?";
621
753
  let dueAt = "?";
@@ -707,7 +839,8 @@ This tool fetches a URL that charges per call with x402 (HTTP 402) and pays it i
707
839
  wallet, with GET, or with POST and a body (an OpenAI-style chat completion, for one). If the wallet is short of the
708
840
  price, it first borrows the gap from the agent's Priors line, only when maxBorrow covers it, or, when the provider was
709
841
  set up with autoBorrow, on its own within the owner's limits while Autopay covers the loan. Real money: confirm the URL,
710
- the price and the most to borrow with the user first.
842
+ the price and the most to borrow with the user first. It signs one payment per purchase: while a payment it signed may
843
+ still settle, a call for the same purchase (the same method, URL and body) sends that payment again, never a new one.
711
844
 
712
845
  Inputs:
713
846
  - url: the https URL.
@@ -715,7 +848,7 @@ Inputs:
715
848
  - maxPrice: the most to pay for this call, in USDG (e.g. 0.10).
716
849
  - maxBorrow: the most to borrow if the wallet is short, in USDG (default 0: never borrow; with autoBorrow, its amount
717
850
  per call, which this can only lower).
718
- - days: the term of a loan taken for the gap (default 7; 14 with autoBorrow).
851
+ - days: the term of a loan taken for the gap (default 7; with autoBorrow always 14, the owner's setting).
719
852
  - method, body: POST and its body (default GET with no body).`,
720
853
  schema: schemas_1.PayX402WithCreditSchema,
721
854
  }),
package/dist/schemas.js CHANGED
@@ -43,7 +43,7 @@ exports.PayX402WithCreditSchema = zod_1.z
43
43
  .positive()
44
44
  .max(90)
45
45
  .optional()
46
- .describe("Term of a loan taken for the gap (default 7, or 14 with the provider's autoBorrow)"),
46
+ .describe("Term of a loan taken for the gap (default 7); with the provider's autoBorrow always 14, the owner's setting"),
47
47
  method: zod_1.z
48
48
  .enum(["GET", "POST"])
49
49
  .optional()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@priors/agentkit",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Priors action provider for Coinbase AgentKit: pay x402 APIs in USDG on Robinhood Chain and borrow the gap from an ERC-8004 agent's Priors credit line, repay, and read another agent's repayment record before paying it.",
5
5
  "license": "MIT",
6
6
  "author": "Priors <contact@priors.trade>",
@@ -16,8 +16,8 @@
16
16
  "prepack": "npm run build"
17
17
  },
18
18
  "dependencies": {
19
- "@x402/evm": "^2.7.0",
20
- "@x402/fetch": "^2.7.0",
19
+ "@priors/x402": "0.8.8",
20
+ "@x402/fetch": "^2.29.0",
21
21
  "viem": "^2.38.3"
22
22
  },
23
23
  "peerDependencies": {
@@ -29,5 +29,5 @@
29
29
  "typescript": "^5.9.0",
30
30
  "zod": "^3.25.0"
31
31
  },
32
- "engines": { "node": ">=18" }
32
+ "engines": { "node": ">=20" }
33
33
  }