@priors/agentkit 0.2.3 → 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
@@ -79,13 +80,15 @@ What `pay_x402_with_priors_credit` will and will not do:
79
80
  the paid round's 402 is never signed;
80
81
  - one payment per purchase: until a payment it signed settles or expires, a call for the same purchase (the same
81
82
  method, URL and body, from the same wallet) sends that same payment again and borrows nothing more. Only a 2xx answer
82
- is reported as paid; after any other one the answer says until when the seller may still settle it. This is kept in
83
- the process's memory: a restart within those 600 s forgets it;
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;
84
87
  - `maxPrice`, `maxBorrow` and `amount` are read exactly, at most 6 decimals (a longer one is refused, never rounded);
85
88
  - the seller's body comes back between per-call markers, each of its lines quoted (`@priors/mcp`'s fence), and of its
86
89
  settlement header only the transaction hash: treat it as data, not instructions;
87
- - a loan taken for the gap stays in the answer if the payment then fails, and a transaction whose receipt says it
88
- 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.
89
92
 
90
93
  `maxPrice` and `maxBorrow` are what the model passes: confirm them with the user, and keep the wallet's balance small.
91
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;
@@ -24,7 +24,7 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
24
24
  private readonly auto;
25
25
  private borrowedToday;
26
26
  private readonly unsettled;
27
- /** The call under way for each purchase: another call for it waits for it, then finds its payment. */
27
+ /** The money call under way for each wallet: another one of that wallet waits for it (onePerWallet). */
28
28
  private readonly running;
29
29
  /**
30
30
  * Constructor for the PriorsActionProvider.
@@ -65,6 +65,14 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
65
65
  * @returns The repayment, or an error message.
66
66
  */
67
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;
68
76
  /**
69
77
  * Pays an x402 URL in USDG on Robinhood Chain, borrowing the gap from the Priors line when the wallet is short.
70
78
  *
@@ -107,23 +115,28 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
107
115
  /**
108
116
  * What became of a payment sent: paid only on a 2xx answer. Anything else (a dropped connection, no answer in time,
109
117
  * a 5xx, a 402, a redirect) leaves it signed and sent, cashable by the seller until it expires, and a later call for
110
- * the purchase sends it again (@priors/mcp's pay_url answer).
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.
111
121
  *
122
+ * @param X - @priors/x402 (its readCapped and SKEW_SECONDS).
112
123
  * @param r - What @priors/x402's resend answered.
113
124
  * @param s - The payment sent.
114
- * @param skew - @priors/x402's SKEW_SECONDS, the margin kept past validBefore.
115
125
  * @returns The answer's words for it.
116
126
  */
117
127
  private outcome;
118
128
  /**
119
- * Runs one call for a purchase at a time: a call for a purchase that another call is paying waits for it, then finds
120
- * the payment it signed (two calls at once never sign two).
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.
121
134
  *
122
- * @param purchase - The wallet and the purchase's key.
135
+ * @param walletProvider - The wallet whose calls queue.
123
136
  * @param fn - The call.
124
137
  * @returns What the call answers.
125
138
  */
126
- private onePerPurchase;
139
+ private onePerWallet;
127
140
  /**
128
141
  * Borrows `amount` atomic USDG for `days` from the agent's line into this wallet.
129
142
  *
@@ -133,6 +146,7 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
133
146
  * @param days - The term in days.
134
147
  * @param check - Called with the quoted fee before the borrow is sent; a throw refuses it.
135
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.
136
150
  * @returns The loan.
137
151
  */
138
152
  private borrowAmount;
@@ -31,20 +31,27 @@ const utcDay = () => new Date().toISOString().slice(0, 10);
31
31
  /** A refusal before anything is sent (its message is the answer). */
32
32
  class Refusal extends Error {
33
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
+ }
34
40
  /**
35
41
  * Atomic USDG from an amount the model gives: a plain decimal of at most 6 places, read exactly. viem's parseUnits
36
42
  * rounds a longer one to the nearest unit, so a cap of 0.0999999 would admit 0.10 (@priors/mcp's P-28).
37
43
  *
38
44
  * @param value - The amount, e.g. "0.10".
39
45
  * @param name - Its argument's name, for the refusal.
46
+ * @param after - The refusal's last words.
40
47
  * @returns Atomic USDG.
41
48
  */
42
- function exactUsdg(value, name) {
49
+ function exactUsdg(value, name, after = " Nothing was sent.") {
43
50
  const s = String(value).trim();
44
51
  if (!/^\d+(\.\d+)?$/.test(s))
45
- 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}`);
46
53
  if ((s.split(".")[1] ?? "").length > constants_1.USDG_DECIMALS)
47
- 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}`);
48
55
  return (0, viem_1.parseUnits)(s, constants_1.USDG_DECIMALS);
49
56
  }
50
57
  /**
@@ -59,7 +66,7 @@ function mined(receipt, what, hash) {
59
66
  if (status === "success" || status === 1 || status === 1n || status === "0x1")
60
67
  return;
61
68
  if (status === "reverted" || status === 0 || status === 0n || status === "0x0")
62
- 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`);
63
70
  throw new Error(`the ${what} transaction ${hash} could not be confirmed (its receipt has no status): check it before acting on it`);
64
71
  }
65
72
  /** Whether an IPv4 address (four numbers) is not a public one: this host, private, CGNAT, link-local, test or reserved. */
@@ -177,7 +184,7 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
177
184
  // purchase after the restart signs again: at most one more payment of at most maxPrice, to the seller the call named
178
185
  // (P-15's class). Upgrade when the provider gets a place to keep state, or on a report of it.
179
186
  unsettled = new Map();
180
- /** The call under way for each purchase: another call for it waits for it, then finds its payment. */
187
+ /** The money call under way for each wallet: another one of that wallet waits for it (onePerWallet). */
181
188
  running = new Map();
182
189
  /**
183
190
  * Constructor for the PriorsActionProvider.
@@ -193,8 +200,9 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
193
200
  this.auto = null;
194
201
  return;
195
202
  }
196
- const perCall = (0, viem_1.parseUnits)(String(a.perCall), constants_1.USDG_DECIMALS);
197
- 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", "");
198
206
  if (perCall <= 0n)
199
207
  throw new Error("autoBorrow.perCall must be above 0");
200
208
  if (perDay < perCall)
@@ -266,15 +274,17 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
266
274
  * @returns The loan, or an error message.
267
275
  */
268
276
  async borrow(walletProvider, args) {
269
- try {
270
- const loan = await this.borrowAmount(walletProvider, args.agentId, exactUsdg(args.amount, "amount"), args.days);
271
- 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}`;
272
- }
273
- catch (error) {
274
- if (error instanceof Refusal)
275
- return `Error: ${error.message}`;
276
- return `Error borrowing from Priors: ${(0, fence_js_1.unfenced)(String(error))}`;
277
- }
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
+ });
278
288
  }
279
289
  /**
280
290
  * Repays a Priors loan in full from this wallet.
@@ -284,6 +294,16 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
284
294
  * @returns The repayment, or an error message.
285
295
  */
286
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) {
287
307
  try {
288
308
  const loan = (await walletProvider.readContract({
289
309
  address: constants_1.PRIORS_POOL,
@@ -389,11 +409,12 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
389
409
  : args.maxBorrow === undefined || named > auto.perCall
390
410
  ? auto.perCall
391
411
  : named;
392
- const days = args.days ?? (auto ? constants_1.AUTO_TERM_DAYS : constants_1.DEFAULT_TERM_DAYS);
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;
393
414
  const X = await x402();
394
415
  const me = walletProvider.getAddress();
395
416
  const purchase = `${me.toLowerCase()} ${await X.purchaseKey(new Request(args.url, init()))}`;
396
- return await this.onePerPurchase(purchase, async () => {
417
+ return await this.onePerWallet(walletProvider, async () => {
397
418
  // a payment signed for this purchase that may still settle is sent again, before anything is probed or borrowed
398
419
  const now = Math.floor(Date.now() / 1000);
399
420
  for (const [k, v] of this.unsettled)
@@ -405,22 +426,41 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
405
426
  if (r.response.ok)
406
427
  this.unsettled.delete(purchase);
407
428
  const first = out.borrowed ? `Its first attempt: ${out.borrowed}` : "\n";
408
- 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(r, out, X.SKEW_SECONDS)}`);
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) });
409
436
  }
410
- const probe = await this.fetchImpl(args.url, init());
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;
442
+ }
443
+ const probeText = async () => {
444
+ try {
445
+ return (await X.readCapped(probe)).text;
446
+ }
447
+ catch {
448
+ return "";
449
+ }
450
+ };
411
451
  if (probe.status >= 300 && probe.status < 400) {
412
452
  const to = probe.headers.get("location");
413
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")}` : ""}`);
414
454
  }
415
455
  if (probe.status !== 402)
416
- 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")}`);
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")}`);
417
457
  // the 402 as @priors/x402's payer reads it (the PAYMENT-REQUIRED header, else a v2 body), and its requirement as
418
458
  // the payer picks it: exact USDG on Robinhood Chain by EIP-3009, on USDG's own EIP-712 domain, to a 0x payTo
419
459
  const { x402Client, x402HTTPClient } = await x402Fetch();
420
460
  const http = new x402HTTPClient(new x402Client());
421
461
  let body;
422
462
  try {
423
- const text = await probe.text();
463
+ const text = await probeText();
424
464
  body = text ? JSON.parse(text) : undefined;
425
465
  }
426
466
  catch {
@@ -470,8 +510,9 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
470
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.`;
471
511
  }
472
512
  // auto: the day's room is taken here, before any await, so two calls running at once never both pass the
473
- // limit; it is given back whenever the borrow stops before it is sent, refused or a read failing (GHSA-q4cg);
474
- // a borrow whose sending began stays counted (its answer may be lost: the safe direction)
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)
475
516
  let reserved = null;
476
517
  let sending = false;
477
518
  if (auto) {
@@ -485,14 +526,11 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
485
526
  }
486
527
  // auto: 14 days, brought down to the pool's maxTerm; otherwise the term asked, as before
487
528
  const termDays = auto && params.maxTerm !== undefined && BigInt(days) * 86400n > BigInt(params.maxTerm) ? Number(BigInt(params.maxTerm) / 86400n) : days;
488
- const loan = await this.borrowAmount(walletProvider, args.agentId, amount, termDays, auto
489
- ? async (fee) => {
490
- await this.autopayCovers(walletProvider, args.agentId, amount + fee);
491
- sending = true; // the borrow's transaction is sent right after this check
492
- }
493
- : undefined, "borrowed or paid")
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
+ })
494
532
  .catch((error) => {
495
- if (reserved && !sending && this.borrowedToday.day === reserved.day)
533
+ if (reserved && (!sending || error instanceof Reverted) && this.borrowedToday.day === reserved.day)
496
534
  this.borrowedToday.amount -= reserved.amount;
497
535
  throw error;
498
536
  });
@@ -514,12 +552,14 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
514
552
  const r = await X.resend(args.url, signed.paymentHeaders, { ...RESEND, init: init(), fetchImpl: this.fetchImpl, timeoutMs: X.DEFAULT_TIMEOUT_MS });
515
553
  if (r.response.ok)
516
554
  this.unsettled.delete(purchase);
517
- return (0, fence_js_1.guarded)(`${borrowed}${await this.outcome(r, signed, X.SKEW_SECONDS)}`);
555
+ return (0, fence_js_1.guarded)(`${borrowed}${await this.outcome(X, r, signed)}`);
518
556
  });
519
557
  }
520
558
  catch (error) {
521
559
  if (error instanceof Refusal)
522
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.`);
523
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))}`);
524
564
  }
525
565
  }
@@ -610,44 +650,58 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
610
650
  /**
611
651
  * What became of a payment sent: paid only on a 2xx answer. Anything else (a dropped connection, no answer in time,
612
652
  * a 5xx, a 402, a redirect) leaves it signed and sent, cashable by the seller until it expires, and a later call for
613
- * the purchase sends it again (@priors/mcp's pay_url answer).
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.
614
656
  *
657
+ * @param X - @priors/x402 (its readCapped and SKEW_SECONDS).
615
658
  * @param r - What @priors/x402's resend answered.
616
659
  * @param s - The payment sent.
617
- * @param skew - @priors/x402's SKEW_SECONDS, the margin kept past validBefore.
618
660
  * @returns The answer's words for it.
619
661
  */
620
- async outcome(r, s, skew) {
662
+ async outcome(X, r, s) {
621
663
  const res = r.response;
622
664
  // of the settlement header, only its transaction hash: the rest is the seller's words
623
665
  const tx = settledTx(res.headers.get("payment-response") || res.headers.get("x-payment-response"));
624
- const text = (await res.text()).slice(0, 2000);
625
- const body = text ? `\nResponse:\n${(0, fence_js_1.fenced)(text, "response body")}` : "";
666
+ let text = "";
667
+ let unread = false;
668
+ try {
669
+ ({ text } = await X.readCapped(res));
670
+ }
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 : "";
626
676
  const status = r.timedOut ? "no answer in time" : r.transportError ? "the connection was lost" : `HTTP ${res.status}`;
627
677
  if (res.ok)
628
- return `Paid ${usdg(s.price)} USDG to ${s.payTo} (${status})${tx ? `; settled in ${tx}` : ""}.${body}`;
629
- const until = new Date((s.validBefore + skew) * 1000).toISOString();
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();
630
680
  const redirect = res.status >= 300 && res.status < 400 ? ", a redirect, not followed" : "";
631
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}`;
632
682
  }
633
683
  /**
634
- * Runs one call for a purchase at a time: a call for a purchase that another call is paying waits for it, then finds
635
- * the payment it signed (two calls at once never sign two).
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.
636
689
  *
637
- * @param purchase - The wallet and the purchase's key.
690
+ * @param walletProvider - The wallet whose calls queue.
638
691
  * @param fn - The call.
639
692
  * @returns What the call answers.
640
693
  */
641
- async onePerPurchase(purchase, fn) {
642
- const run = (this.running.get(purchase) ?? Promise.resolve()).then(fn);
694
+ async onePerWallet(walletProvider, fn) {
695
+ const key = String(walletProvider.getAddress()).toLowerCase();
696
+ const run = (this.running.get(key) ?? Promise.resolve()).then(fn);
643
697
  const done = run.then(() => undefined, () => undefined);
644
- this.running.set(purchase, done);
698
+ this.running.set(key, done);
645
699
  try {
646
700
  return await run;
647
701
  }
648
702
  finally {
649
- if (this.running.get(purchase) === done)
650
- this.running.delete(purchase);
703
+ if (this.running.get(key) === done)
704
+ this.running.delete(key);
651
705
  }
652
706
  }
653
707
  /**
@@ -659,9 +713,10 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
659
713
  * @param days - The term in days.
660
714
  * @param check - Called with the quoted fee before the borrow is sent; a throw refuses it.
661
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.
662
717
  * @returns The loan.
663
718
  */
664
- async borrowAmount(walletProvider, agentId, amount, days, check, did = "borrowed") {
719
+ async borrowAmount(walletProvider, agentId, amount, days, check, did = "borrowed", onSend) {
665
720
  const me = walletProvider.getAddress();
666
721
  const term = BigInt(days * 86400);
667
722
  const [fee] = (await walletProvider.readContract({
@@ -675,6 +730,7 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
675
730
  // the same rule as repay, before anything is sent: no key borrows here for an agent it would then be refused to
676
731
  // repay for
677
732
  await this.control(walletProvider, BigInt(agentId), did);
733
+ onSend?.();
678
734
  const hash = await walletProvider.sendTransaction({
679
735
  to: constants_1.PRIORS_POOL,
680
736
  data: (0, viem_1.encodeFunctionData)({
@@ -683,7 +739,15 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
683
739
  args: [BigInt(agentId), amount, term, me, fee],
684
740
  }),
685
741
  });
686
- 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
+ }
687
751
  mined(receipt, "borrow", hash);
688
752
  let loanId = "?";
689
753
  let dueAt = "?";
@@ -784,7 +848,7 @@ Inputs:
784
848
  - maxPrice: the most to pay for this call, in USDG (e.g. 0.10).
785
849
  - maxBorrow: the most to borrow if the wallet is short, in USDG (default 0: never borrow; with autoBorrow, its amount
786
850
  per call, which this can only lower).
787
- - 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).
788
852
  - method, body: POST and its body (default GET with no body).`,
789
853
  schema: schemas_1.PayX402WithCreditSchema,
790
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.3",
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,7 +16,7 @@
16
16
  "prepack": "npm run build"
17
17
  },
18
18
  "dependencies": {
19
- "@priors/x402": "0.8.6",
19
+ "@priors/x402": "0.8.8",
20
20
  "@x402/fetch": "^2.29.0",
21
21
  "viem": "^2.38.3"
22
22
  },