@priors/agentkit 0.2.4 → 0.3.0

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
@@ -38,16 +38,26 @@ Then hand `agentKit` to your framework as usual (`getVercelAITools(agentKit)`, `
38
38
  **Inference on credit (0.2.0).** Give the provider `autoBorrow`, set by you in code, never by the model:
39
39
 
40
40
  ```ts
41
- priorsActionProvider(undefined, { autoBorrow: { perCall: "5", perDay: "10", hosts: ["models.example"] } })
41
+ priorsActionProvider(undefined, { autoBorrow: { perCall: "5", perDay: "10", hosts: ["models.example"], agents: [437] } })
42
42
  ```
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
+ Its limits and checks hold `borrow_from_priors` too: while `autoBorrow` is set, a borrow the model asks for is at most
46
+ `perCall`, counts in `perDay` with the pay action's own borrows, and is sent only while Autopay covers the loan.
45
47
  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 (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
+ `agents` lists every agent whose loans this wallet's Autopay repays: AutoRepay pays each agent's plan on a wallet from
49
+ that wallet's one USDG approval, so the Autopay check below counts the open loans of every listed agent whose plan the
50
+ wallet holds, and auto-borrow borrows only for a listed agent. Without `agents` it borrows nothing: an `autoBorrow`
51
+ written before `agents` existed borrows nothing until it lists its agent. The limits are `perCall` USDG a call and `perDay` USDG a UTC day (each read
52
+ exactly, at most 6 decimals), for 14 days whatever term the model names (or the pool's maximum term, and 10 days on a
53
+ SeatVaultV5 line, below). The day counts what the pool lent the agent since 00:00 UTC,
54
+ every loan of the agent whoever took it, as well as this provider's own auto-borrows, so a restart does not start the
55
+ day again (0.2.5); if those loans cannot be read, nothing is borrowed. A borrow another process sent that is not mined
56
+ yet is not seen, and after a restart a provider that auto-borrows for several agents counts each agent's loans only. It borrows only while this wallet's Autopay
48
57
  (AutoRepay v2) covers the new loan: the wallet is the agent's
49
58
  declared wallet, the plan is on under the agent's current owner, not held or paused, its limit per loan and its USDG
50
- approval cover the loan's due. Otherwise nothing is borrowed or paid, and the answer says to turn Autopay on. The
59
+ approval cover the loan's due, with the open loans of every agent in `agents` whose plan the wallet holds. Otherwise
60
+ nothing is borrowed or paid, and the answer says to turn Autopay on. The
51
61
  wallet must be a key of the agent's own, not its owner's address: AutoRepay repays an agent whose declared wallet is its
52
62
  owner (what registering it leaves) under the owner's plan only, so auto-borrow refuses that wallet. Autopay
53
63
  then repays the loan in its window. The model's `maxBorrow` can only lower the amount. A chat completion is one call
@@ -62,28 +72,39 @@ OpenAI-style request as JSON (sent with POST), `maxPrice` the most to pay for th
62
72
  | `get_priors_agent_record` | reads an agent's repayment record: loans repaid, late repayments, defaults, score | no |
63
73
  | `get_priors_credit_line` | reads an agent's line: size, drawn, available | no |
64
74
  | `pay_x402_with_priors_credit` | pays an x402 URL in USDG, at most `maxPrice`, with GET or with POST and a `body`; if the wallet is short, first borrows the gap (at least the pool's minimum loan, 5 USDG today) when `maxBorrow` covers it, or, with `autoBorrow`, on its own within its limits | yes |
65
- | `borrow_from_priors` | borrows USDG from the agent's line into the wallet | yes |
66
- | `repay_priors_loan` | repays a loan in full; approves exactly what is due | yes |
75
+ | `borrow_from_priors` | borrows USDG from the agent's line into the wallet; with `autoBorrow`, within its limits and only while Autopay covers the loan | yes |
76
+ | `repay_priors_loan` | repays a loan in full; approves exactly what is due; a repay or approval whose answer was lost is named with its transaction | yes |
67
77
 
68
78
  Only the agent's owner or its registry wallet can borrow against or repay its line, as in `@priors/mcp`: the wallet
69
79
  must control the agent at the pool and be its current owner or its declared ERC-8004 wallet (a pool delegate named by
70
- the owner alone is not enough), and `repay_priors_loan` pays only a loan the agent's current owner took. A loan more
80
+ the owner alone is not enough), and `repay_priors_loan` pays only a loan the agent's current owner took.
81
+
82
+ On a line backed by SeatVaultV5 (root #8762), every borrow keeps V5's rules, as `@priors/x402` does: V5 lends for at
83
+ most 10 days, so auto-borrow's 14 days are brought down to 10 and a `borrow_from_priors` over 10 days is refused before
84
+ anything is sent; before the borrow the line is refreshed (V5's `refresh`, a transaction), since V5 raises the pool's
85
+ vouch only then; and V5 lends to a key other than the agent's owner only from 24 hours after it recorded that key. The
86
+ first borrow from such a key records it (V5's `noteDelegate`, a transaction) and borrows nothing, and the answer says
87
+ from when it can: auto-borrow, which never borrows from the owner's address, so needs the agent's key recorded with V5
88
+ a day before. A loan more
71
89
  than three days late can be marked defaulted, which ends the agent's record on Priors. The reads use Priors' public
72
90
  API, no key.
73
91
 
74
92
  What `pay_x402_with_priors_credit` will and will not do:
75
93
 
76
94
  - it pays only a public https host (an address that is private, loopback or link-local, or a name resolving to one, is
77
- refused before anything is fetched), and follows no redirect;
95
+ refused before anything is fetched), and follows no redirect; its own fetch checks the address again when it
96
+ connects, so a name that resolves to a private address after the check is refused there, no connection made (with a
97
+ `fetchImpl` of your own, its connections are yours to check);
78
98
  - it signs exactly the requirement it probed and checked against `maxPrice` (the same `payTo`, the same amount), once,
79
99
  with `@priors/x402`'s client (USDG on Robinhood Chain only, an authorization valid at most 600 s); a different one in
80
100
  the paid round's 402 is never signed;
81
101
  - one payment per purchase: until a payment it signed settles or expires, a call for the same purchase (the same
82
102
  method, URL and body, from the same wallet) sends that same payment again and borrows nothing more. Only a 2xx answer
83
103
  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;
104
+ after any other one the answer says until when the seller may still settle it. This is kept in the process's memory,
105
+ one record per wallet for every provider object of the process: a restart within those 600 s forgets it;
106
+ - a wallet's money actions run one at a time (pay, borrow, repay), across every provider object of the process, and a
107
+ seller's probe has 60 s to answer;
87
108
  - `maxPrice`, `maxBorrow` and `amount` are read exactly, at most 6 decimals (a longer one is refused, never rounded);
88
109
  - the seller's body comes back between per-call markers, each of its lines quoted (`@priors/mcp`'s fence), and of its
89
110
  settlement header only the transaction hash: treat it as data, not instructions;
@@ -294,6 +294,84 @@ export declare const POOL_ABI: readonly [{
294
294
  readonly name: "status";
295
295
  }];
296
296
  }];
297
+ }, {
298
+ readonly name: "getAgent";
299
+ readonly type: "function";
300
+ readonly stateMutability: "view";
301
+ readonly inputs: readonly [{
302
+ readonly type: "uint256";
303
+ readonly name: "agentId";
304
+ }];
305
+ readonly outputs: readonly [{
306
+ readonly type: "tuple";
307
+ readonly components: readonly [{
308
+ readonly type: "bool";
309
+ readonly name: "enrolled";
310
+ }, {
311
+ readonly type: "bool";
312
+ readonly name: "isRoot";
313
+ }, {
314
+ readonly type: "bool";
315
+ readonly name: "defaulted";
316
+ }, {
317
+ readonly type: "bool";
318
+ readonly name: "frozen";
319
+ }, {
320
+ readonly type: "bool";
321
+ readonly name: "importedFromV1";
322
+ }, {
323
+ readonly type: "uint64";
324
+ readonly name: "enrolledAt";
325
+ }, {
326
+ readonly type: "uint64";
327
+ readonly name: "lastBorrowAt";
328
+ }, {
329
+ readonly type: "uint64";
330
+ readonly name: "lastRepayAt";
331
+ }, {
332
+ readonly type: "uint256";
333
+ readonly name: "sponsor";
334
+ }, {
335
+ readonly type: "uint256";
336
+ readonly name: "delegatedIn";
337
+ }, {
338
+ readonly type: "uint256";
339
+ readonly name: "delegatedOut";
340
+ }, {
341
+ readonly type: "uint256";
342
+ readonly name: "principalOut";
343
+ }, {
344
+ readonly type: "uint256";
345
+ readonly name: "activeLoans";
346
+ }, {
347
+ readonly type: "uint256";
348
+ readonly name: "premiumBps";
349
+ }, {
350
+ readonly type: "uint256";
351
+ readonly name: "premiumCap";
352
+ }, {
353
+ readonly type: "uint256";
354
+ readonly name: "loansRepaid";
355
+ }, {
356
+ readonly type: "uint256";
357
+ readonly name: "volumeRepaid";
358
+ }, {
359
+ readonly type: "uint256";
360
+ readonly name: "feesPaid";
361
+ }, {
362
+ readonly type: "uint256";
363
+ readonly name: "recourseHonored";
364
+ }, {
365
+ readonly type: "uint256";
366
+ readonly name: "childrenDefaulted";
367
+ }, {
368
+ readonly type: "uint256";
369
+ readonly name: "qualifiedRepaid";
370
+ }, {
371
+ readonly type: "uint256";
372
+ readonly name: "dollarSecondsRepaid";
373
+ }];
374
+ }];
297
375
  }, {
298
376
  readonly name: "Borrowed";
299
377
  readonly type: "event";
@@ -323,5 +401,48 @@ export declare const POOL_ABI: readonly [{
323
401
  readonly name: "to";
324
402
  }];
325
403
  }];
404
+ /** SeatVaultV5 (deployments/4663.v2.json `seatVaultV5`, root identity `seatVaultV5AgentId`), a root that backs lines
405
+ * with its owner's $PRIORS. It vouches nothing at a line's open and raises the pool's vouch only on `refresh`, by the
406
+ * agent's owner or by the pool delegate it recorded (`noteDelegate`, anyone may send it) at least 24 h before; its
407
+ * canBorrow, which the pool asks at every borrow, refuses a term over 10 days (C.MAX_LOAN_TERM, a constant) and any
408
+ * caller but the owner until 24 h after it recorded that key (@priors/x402's v5BeforeBorrow). */
409
+ export declare const SEAT_VAULT_V5: "0xC999014C6218EC41f0aE412d49AE8f2aA4c539fD";
410
+ export declare const SEAT_VAULT_V5_ROOT = 8762n;
411
+ export declare const V5_MAX_TERM_DAYS = 10;
412
+ export declare const V5_DELEGATE_WAIT_S = 86400;
413
+ export declare const V5_ABI: readonly [{
414
+ readonly name: "refresh";
415
+ readonly type: "function";
416
+ readonly stateMutability: "nonpayable";
417
+ readonly inputs: readonly [{
418
+ readonly type: "uint256";
419
+ readonly name: "id";
420
+ }];
421
+ readonly outputs: readonly [];
422
+ }, {
423
+ readonly name: "noteDelegate";
424
+ readonly type: "function";
425
+ readonly stateMutability: "nonpayable";
426
+ readonly inputs: readonly [{
427
+ readonly type: "uint256";
428
+ readonly name: "id";
429
+ }];
430
+ readonly outputs: readonly [];
431
+ }, {
432
+ readonly name: "delegateOf";
433
+ readonly type: "function";
434
+ readonly stateMutability: "view";
435
+ readonly inputs: readonly [{
436
+ readonly type: "uint256";
437
+ readonly name: "id";
438
+ }];
439
+ readonly outputs: readonly [{
440
+ readonly type: "address";
441
+ readonly name: "who";
442
+ }, {
443
+ readonly type: "uint64";
444
+ readonly name: "at";
445
+ }];
446
+ }];
326
447
  /** Loan status 1 is active in CreditPoolV2. */
327
448
  export declare const LOAN_ACTIVE = 1;
package/dist/constants.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LOAN_ACTIVE = exports.POOL_ABI = exports.AUTOREPAY_ABI = exports.REGISTRY_ABI = exports.AUTOREPAY = exports.REGISTRY = exports.AUTO_TERM_DAYS = exports.DEFAULT_TERM_DAYS = exports.PRIORS_API = exports.USDG_DECIMALS = exports.USDG = exports.PRIORS_POOL = exports.ROBINHOOD_NETWORK = exports.ROBINHOOD_CHAIN_ID = void 0;
3
+ exports.LOAN_ACTIVE = exports.V5_ABI = exports.V5_DELEGATE_WAIT_S = exports.V5_MAX_TERM_DAYS = exports.SEAT_VAULT_V5_ROOT = exports.SEAT_VAULT_V5 = exports.POOL_ABI = exports.AUTOREPAY_ABI = exports.REGISTRY_ABI = exports.AUTOREPAY = exports.REGISTRY = exports.AUTO_TERM_DAYS = exports.DEFAULT_TERM_DAYS = exports.PRIORS_API = exports.USDG_DECIMALS = exports.USDG = exports.PRIORS_POOL = exports.ROBINHOOD_NETWORK = exports.ROBINHOOD_CHAIN_ID = void 0;
4
4
  const viem_1 = require("viem");
5
5
  /** Robinhood Chain, where Priors' pool and USDG live. */
6
6
  exports.ROBINHOOD_CHAIN_ID = "4663";
@@ -39,7 +39,22 @@ exports.POOL_ABI = (0, viem_1.parseAbi)([
39
39
  "function loansOf(uint256 agentId) view returns (uint256[])",
40
40
  "function isController(uint256 agentId, address who) view returns (bool)",
41
41
  "function getLoan(uint256 loanId) view returns ((uint256 agentId, uint256 sponsorId, uint256 principal, uint256 fee, uint256 sponsorCut, uint256 reserveCut, uint256 premium, address owner, uint64 issuedAt, uint64 dueAt, uint64 defaultableAt, uint64 minScoreTerm, uint64 closedAt, uint8 status))",
42
+ "function getAgent(uint256 agentId) view returns ((bool enrolled, bool isRoot, bool defaulted, bool frozen, bool importedFromV1, uint64 enrolledAt, uint64 lastBorrowAt, uint64 lastRepayAt, uint256 sponsor, uint256 delegatedIn, uint256 delegatedOut, uint256 principalOut, uint256 activeLoans, uint256 premiumBps, uint256 premiumCap, uint256 loansRepaid, uint256 volumeRepaid, uint256 feesPaid, uint256 recourseHonored, uint256 childrenDefaulted, uint256 qualifiedRepaid, uint256 dollarSecondsRepaid))",
42
43
  "event Borrowed(uint256 indexed loanId, uint256 indexed agentId, uint256 indexed sponsorId, uint256 principal, uint256 fee, uint64 dueAt, address to)",
43
44
  ]);
45
+ /** SeatVaultV5 (deployments/4663.v2.json `seatVaultV5`, root identity `seatVaultV5AgentId`), a root that backs lines
46
+ * with its owner's $PRIORS. It vouches nothing at a line's open and raises the pool's vouch only on `refresh`, by the
47
+ * agent's owner or by the pool delegate it recorded (`noteDelegate`, anyone may send it) at least 24 h before; its
48
+ * canBorrow, which the pool asks at every borrow, refuses a term over 10 days (C.MAX_LOAN_TERM, a constant) and any
49
+ * caller but the owner until 24 h after it recorded that key (@priors/x402's v5BeforeBorrow). */
50
+ exports.SEAT_VAULT_V5 = "0xC999014C6218EC41f0aE412d49AE8f2aA4c539fD";
51
+ exports.SEAT_VAULT_V5_ROOT = 8762n;
52
+ exports.V5_MAX_TERM_DAYS = 10;
53
+ exports.V5_DELEGATE_WAIT_S = 86_400;
54
+ exports.V5_ABI = (0, viem_1.parseAbi)([
55
+ "function refresh(uint256 id)",
56
+ "function noteDelegate(uint256 id)",
57
+ "function delegateOf(uint256 id) view returns (address who, uint64 at)",
58
+ ]);
44
59
  /** Loan status 1 is active in CreditPoolV2. */
45
60
  exports.LOAN_ACTIVE = 1;
@@ -3,14 +3,21 @@ 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 (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.
6
+ * up to `perCall` USDG a call and `perDay` USDG a UTC day (each read exactly, at most 6 decimals), for the `hosts` listed
7
+ * only (exact host names), for 14 days whatever term the model names, and only while this wallet's Autopay (AutoRepay
8
+ * v2) covers the new loan. The model's maxBorrow can only lower the amount. The day counts what the pool lent the agent
9
+ * since 00:00 UTC, every loan of the agent whoever took it, as well as this process's own auto-borrows, so a restart
10
+ * does not start the day again (GHSA-j679). While it is set, the same limits and Autopay check hold borrow_from_priors,
11
+ * on the same count. `agents` lists the ERC-8004 ids whose loans the wallet's Autopay repays: AutoRepayV2
12
+ * pulls every agent's plan on a wallet from that wallet's one approval, so the check counts the open loans of each one
13
+ * listed whose plan the wallet holds, and auto-borrow borrows only for a listed agent; without it, auto-borrow
14
+ * borrows nothing.
9
15
  */
10
16
  export type AutoBorrowOptions = {
11
17
  perCall: string;
12
18
  perDay: string;
13
19
  hosts: string[];
20
+ agents?: number[];
14
21
  };
15
22
  export type PriorsOptions = {
16
23
  autoBorrow?: AutoBorrowOptions;
@@ -23,16 +30,23 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
23
30
  private readonly fetchImpl;
24
31
  private readonly auto;
25
32
  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;
29
33
  /**
30
34
  * Constructor for the PriorsActionProvider.
31
35
  *
32
- * @param fetchImpl - The fetch used for Priors' API and the x402 URLs (injectable for tests).
36
+ * @param fetchImpl - The fetch used for Priors' API and the x402 URLs. By default the provider's own (guardedFetch),
37
+ * whose connections check the addresses they resolve; one given here is used as it is, its connections the caller's
38
+ * to check (tests give their sellers here).
33
39
  * @param options - `autoBorrow` (off unless given): see AutoBorrowOptions.
34
40
  */
35
41
  constructor(fetchImpl?: typeof fetch, options?: PriorsOptions);
42
+ /**
43
+ * Why auto-borrow does not borrow for `agentId`: autoBorrow.agents is not set, or does not list it; null
44
+ * when it may.
45
+ *
46
+ * @param agentId - The agent id.
47
+ * @returns The refusal's words, or null.
48
+ */
49
+ private unlisted;
36
50
  /**
37
51
  * Reads an agent's Priors repayment record.
38
52
  *
@@ -84,14 +98,35 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
84
98
  /**
85
99
  * Auto-borrow's condition, read before the borrow is sent: this wallet is the agent's declared wallet, its Autopay
86
100
  * plan is on and set under the agent's current owner and key, not held or paused, its limit per loan is at least
87
- * `due`, and its USDG approval to AutoRepay covers `due` on top of the agent's open loans it already repays (those
88
- * within its limit), as @priors/mcp's check. Throws a Refusal saying what to turn on otherwise.
101
+ * `due`, and its USDG approval to AutoRepay covers `due` on top of the open loans it already repays: those of every
102
+ * agent in autoBorrow.agents whose plan on this wallet is on, each within its plan's limit. Throws a
103
+ * Refusal saying what to turn on otherwise.
89
104
  *
90
105
  * @param walletProvider - The wallet provider.
91
106
  * @param agentId - The agent id.
92
107
  * @param due - The new loan's principal plus fee, atomic USDG.
93
108
  */
94
109
  private autopayCovers;
110
+ /**
111
+ * Auto-borrow's day limit as the pool records the day (GHSA-j679): `amount` more on top of what the pool lent agent
112
+ * `agentId` since 00:00 UTC of `day` must stay within `perDay`. Every loan of the agent issued that day counts, whoever
113
+ * took it (the pool records the agent and its owner, not the key that borrowed), so a restart, or another process of
114
+ * this wallet, starts the day where the pool is; that can only lower auto-borrow's room. A read that fails, or a loan
115
+ * whose record does not read as one, refuses (nothing is sent). The pool lists an agent's loans oldest first
116
+ * (CreditPoolV2 appends each in borrow), so they are read from the newest back to the first one issued before the day.
117
+ *
118
+ * SHORTCUT: what the pool shows: a borrow another process sent and the chain has not mined yet is not seen, and after a
119
+ * restart a provider that auto-borrows for several agents counts each agent's own loans only (its count across agents
120
+ * starts again). Upgrade when the provider gets a place to keep state (@priors/mcp's daily ledger under
121
+ * PRIORS_STATE_DIR), or on a report of either.
122
+ *
123
+ * @param walletProvider - The wallet provider.
124
+ * @param agentId - The agent id.
125
+ * @param amount - The borrow about to be sent, atomic USDG.
126
+ * @param perDay - The owner's limit a UTC day, atomic USDG.
127
+ * @param day - The UTC day the borrow counts in (YYYY-MM-DD).
128
+ */
129
+ private dayRoom;
95
130
  /**
96
131
  * Before this wallet's money moves for agent `agentId` (a borrow into it, a repayment from it), @priors/mcp's rule
97
132
  * (needController, GHSA-9pw7): the wallet controls the agent at the pool AND is its current owner or its declared
@@ -137,6 +172,21 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
137
172
  * @returns What the call answers.
138
173
  */
139
174
  private onePerWallet;
175
+ /**
176
+ * borrow_from_priors with autoBorrow set: the owner's limits hold the model's own borrow as they
177
+ * hold the pay action's. At most `perCall`; counted in `perDay` on the same count, this process's (taken before any
178
+ * await, given back when the borrow stops before it is sent or reverts, as the pay action's) and the pool's day
179
+ * (dayRoom); and only while Autopay covers the loan (autopayCovers). A manual borrow so uses up the day's room the pay
180
+ * action has, and a balance it funds stays within the limits whoever spends it. The term is the model's `days`.
181
+ *
182
+ * @param walletProvider - The wallet provider.
183
+ * @param agentId - The agent id.
184
+ * @param amount - Atomic USDG.
185
+ * @param days - The term in days.
186
+ * @param auto - The owner's autoBorrow limits.
187
+ * @returns The loan.
188
+ */
189
+ private borrowHeld;
140
190
  /**
141
191
  * Borrows `amount` atomic USDG for `days` from the agent's line into this wallet.
142
192
  *
@@ -145,10 +195,28 @@ export declare class PriorsActionProvider extends ActionProvider<EvmWalletProvid
145
195
  * @param amount - Atomic USDG.
146
196
  * @param days - The term in days.
147
197
  * @param check - Called with the quoted fee before the borrow is sent; a throw refuses it.
198
+ * On a SeatVaultV5 line, V5's rules before anything is sent, as @priors/x402's v5BeforeBorrow: a term
199
+ * over V5's 10 days is brought down to them when `fit` (auto-borrow's own term), else refused; then the key step
200
+ * (v5Ready).
201
+ *
148
202
  * @param did - What did not happen when the borrow is refused ("borrowed", "borrowed or paid").
149
203
  * @param onSend - Called once every check has passed, right before the borrow's transaction is sent.
204
+ * @param fit - Whether the term is the provider's own (auto-borrow's), brought down to V5's longest on its line.
150
205
  * @returns The loan.
151
206
  */
152
207
  private borrowAmount;
208
+ /**
209
+ * SeatVaultV5's key rule before a borrow on its line, as @priors/x402's v5BeforeBorrow: V5 lends only to
210
+ * the agent's owner, or to the pool delegate it recorded (noteDelegate) from 24 hours after. The owner's key, or one
211
+ * recorded that long ago, raises the pool's vouch to the line V5 allows now (refresh: V5 vouches nothing until then),
212
+ * and the borrow follows. A key V5 has not recorded is recorded now (control() has found this wallet controls the
213
+ * agent, so it is the pool's delegate) and, like one recorded under 24 hours ago, borrows nothing: the Refusal says
214
+ * from when it can. Each transaction's receipt is checked, a lost answer said with its transaction.
215
+ *
216
+ * @param walletProvider - The wallet provider.
217
+ * @param agentId - The agent id.
218
+ * @param did - What did not happen when refused ("borrowed", "borrowed or paid").
219
+ */
220
+ private v5Ready;
153
221
  }
154
222
  export declare const priorsActionProvider: (fetchImpl?: typeof fetch, options?: PriorsOptions) => PriorsActionProvider;
@@ -12,6 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.priorsActionProvider = exports.PriorsActionProvider = void 0;
13
13
  const node_dns_1 = require("node:dns");
14
14
  const node_net_1 = require("node:net");
15
+ const undici_1 = require("undici");
15
16
  const zod_1 = require("zod");
16
17
  const viem_1 = require("viem");
17
18
  const agentkit_1 = require("@coinbase/agentkit");
@@ -125,13 +126,46 @@ function privateAddress(ip) {
125
126
  }
126
127
  return true;
127
128
  }
129
+ /** The error code a connection refused by guardedFetch's lookup carries. */
130
+ const EPRIVATE = "EPRIVATE";
131
+ /**
132
+ * The provider's own fetch: every connection checks again the addresses it resolves, as @priors/mcp's
133
+ * guardedFetch does, so a name that answered a public address to publicHost and a private one when fetch connects (DNS
134
+ * rebinding) is refused there, before any byte is sent. IP literals skip DNS; publicHost refuses the private ones.
135
+ *
136
+ * @returns A fetch over undici whose connect lookup refuses any private, loopback or link-local address.
137
+ */
138
+ function guardedFetch() {
139
+ const lookup = (hostname, options, cb) => (0, node_dns_1.lookup)(hostname, { ...(options || {}), all: true }, (err, addrs) => {
140
+ if (err)
141
+ return cb(err);
142
+ const list = Array.isArray(addrs) ? addrs : [{ address: String(addrs), family: (0, node_net_1.isIP)(String(addrs)) }];
143
+ const bad = list.find(a => privateAddress(a.address));
144
+ if (bad || !list.length)
145
+ return cb(Object.assign(new Error(`${hostname} resolves to a private or local address (${bad?.address ?? "none"})`), { code: EPRIVATE, address: bad?.address }));
146
+ return options?.all ? cb(null, list) : cb(null, list[0].address, list[0].family);
147
+ });
148
+ const dispatcher = new undici_1.Agent({ connect: { lookup: lookup } });
149
+ return (async (input, init) => {
150
+ const r = input instanceof Request ? input : new Request(input, init);
151
+ const body = r.body ? await r.arrayBuffer() : undefined;
152
+ const headers = [];
153
+ r.headers.forEach((value, name) => headers.push([name, value]));
154
+ return (0, undici_1.fetch)(r.url, { method: r.method, headers, body, redirect: r.redirect, signal: r.signal, dispatcher });
155
+ });
156
+ }
157
+ let defaultFetch = null;
158
+ /** The private address a connection was refused for by guardedFetch, from fetch's error, or null. */
159
+ function refusedAtConnect(error) {
160
+ const cause = error?.cause;
161
+ return cause?.code === EPRIVATE ? String(cause.address ?? "none") : null;
162
+ }
128
163
  /**
129
164
  * Refuses, before anything is fetched, a URL whose host is a private, loopback or link-local address, a local name, or a
130
165
  * name that resolves to one (@priors/mcp's P-3): the provider fetches what the model names and hands the answer back.
131
- *
132
- * SHORTCUT: the name is resolved here and again by fetch when it connects, so a DNS answer that turns private between
133
- * the two (rebinding) is not caught. Upgrade when the provider fetches with credentials or reads private answers back:
134
- * a dispatcher whose connect lookup applies this same check, as @priors/x402 does.
166
+ * With the provider's own fetch, the connection checks the addresses it resolves again (guardedFetch), so a DNS answer
167
+ * that turns private between this check and the connection is refused there; this check is the clear
168
+ * refusal first.
135
169
  *
136
170
  * @param url - The URL to be fetched.
137
171
  */
@@ -167,6 +201,20 @@ function settledTx(header) {
167
201
  return null;
168
202
  }
169
203
  }
204
+ // One record per wallet for the whole process, shared by every provider object: two objects for one wallet
205
+ // (two AgentKit instances on one wallet provider, or two providers in one) keep one record of its signed payments and
206
+ // one queue of its money calls, as the README says ("from the same wallet ... in the process's memory").
207
+ // One signature per purchase (GHSA-pr4v), @priors/x402's rule (createPayer's unsettled payments, @priors/mcp's
208
+ // outstanding ones): a payment signed for a wallet's purchase (the method, the URL as the seller reads it and the body:
209
+ // @priors/x402's purchaseKey, keyed with the wallet's address) and not seen settled is sent again by a later call for
210
+ // that purchase, never signed again, until it expires.
211
+ // SHORTCUT: kept in this process's memory, as createPayer keeps it (@priors/mcp adds its PRIORS_STATE_DIR file). A
212
+ // restart while such a payment may still settle (at most 600 s, plus SKEW_SECONDS) forgets it, and a call for the same
213
+ // purchase after the restart signs again: at most one more payment of at most maxPrice, to the seller the call named
214
+ // (P-15's class). Upgrade when the provider gets a place to keep state, or on a report of it.
215
+ const unsettled = new Map();
216
+ /** The money call under way for each wallet: another one of that wallet, from any provider object, waits for it. */
217
+ const running = new Map();
170
218
  /**
171
219
  * PriorsActionProvider gives an agent on Robinhood Chain a USDG credit line from Priors: pay an x402 URL and borrow
172
220
  * the gap when the wallet is short, borrow and repay, and read another agent's repayment record before paying it.
@@ -174,25 +222,20 @@ function settledTx(header) {
174
222
  class PriorsActionProvider extends agentkit_1.ActionProvider {
175
223
  fetchImpl;
176
224
  auto;
225
+ // what this provider borrowed today under autoBorrow (its auto-borrows, and borrow_from_priors's), sent or
226
+ // about to be: the borrows the pool does not list yet. The pool's own record of the agent's loans today is read before
227
+ // each of them too (dayRoom), so a restart starts from it; another provider object of the process waits for this
228
+ // one's calls on the same wallet (onePerWallet), so the pool shows it those mined.
177
229
  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();
189
230
  /**
190
231
  * Constructor for the PriorsActionProvider.
191
232
  *
192
- * @param fetchImpl - The fetch used for Priors' API and the x402 URLs (injectable for tests).
233
+ * @param fetchImpl - The fetch used for Priors' API and the x402 URLs. By default the provider's own (guardedFetch),
234
+ * whose connections check the addresses they resolve; one given here is used as it is, its connections the caller's
235
+ * to check (tests give their sellers here).
193
236
  * @param options - `autoBorrow` (off unless given): see AutoBorrowOptions.
194
237
  */
195
- constructor(fetchImpl = (input, init) => globalThis.fetch(input, init), options = {}) {
238
+ constructor(fetchImpl = (defaultFetch ??= guardedFetch()), options = {}) {
196
239
  super("priors", []);
197
240
  this.fetchImpl = fetchImpl;
198
241
  const a = options.autoBorrow;
@@ -210,7 +253,25 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
210
253
  const hosts = (a.hosts ?? []).map(h => String(h).trim().toLowerCase());
211
254
  if (!hosts.length || hosts.some(h => !/^[a-z0-9.-]+(:\d{1,5})?$/.test(h)))
212
255
  throw new Error("autoBorrow.hosts must list the host names it may borrow to pay, e.g. [\"models.example\"]");
213
- this.auto = { perCall, perDay, hosts: new Set(hosts) };
256
+ const agents = a.agents;
257
+ if (agents !== undefined && (!Array.isArray(agents) || !agents.length || agents.some(id => typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0)))
258
+ throw new Error("autoBorrow.agents must list the ERC-8004 ids whose loans this wallet's Autopay repays, e.g. [437]");
259
+ this.auto = { perCall, perDay, hosts: new Set(hosts), agents: agents ? agents.map(BigInt) : null };
260
+ }
261
+ /**
262
+ * Why auto-borrow does not borrow for `agentId`: autoBorrow.agents is not set, or does not list it; null
263
+ * when it may.
264
+ *
265
+ * @param agentId - The agent id.
266
+ * @returns The refusal's words, or null.
267
+ */
268
+ unlisted(agentId) {
269
+ const agents = this.auto?.agents;
270
+ if (!agents)
271
+ return "auto-borrow borrows only for the agents listed in autoBorrow.agents, which is not set: list there every agent whose loans this wallet's Autopay repays (each plan on this wallet is paid from its one approval), e.g. agents: [437].";
272
+ if (!agents.includes(BigInt(agentId)))
273
+ return `auto-borrow borrows only for the agents listed in autoBorrow.agents (${agents.map(id => `#${id}`).join(", ")}), and agent #${agentId} is not one.`;
274
+ return null;
214
275
  }
215
276
  /**
216
277
  * Reads an agent's Priors repayment record.
@@ -276,7 +337,10 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
276
337
  async borrow(walletProvider, args) {
277
338
  return this.onePerWallet(walletProvider, async () => {
278
339
  try {
279
- const loan = await this.borrowAmount(walletProvider, args.agentId, exactUsdg(args.amount, "amount"), args.days);
340
+ const amount = exactUsdg(args.amount, "amount");
341
+ const loan = this.auto
342
+ ? await this.borrowHeld(walletProvider, args.agentId, amount, args.days, this.auto)
343
+ : await this.borrowAmount(walletProvider, args.agentId, amount, args.days);
280
344
  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
345
  }
282
346
  catch (error) {
@@ -346,7 +410,15 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
346
410
  args: [constants_1.PRIORS_POOL, due],
347
411
  }),
348
412
  });
349
- mined(await walletProvider.waitForTransactionReceipt(approve), "USDG approval", approve);
413
+ // sent: a lost answer is said with its transaction, as the borrow's (RT-5's rule)
414
+ let approved;
415
+ try {
416
+ approved = await walletProvider.waitForTransactionReceipt(approve);
417
+ }
418
+ catch (error) {
419
+ throw new Unconfirmed(`the USDG approval of ${usdg(due)} USDG for loan #${args.loanId}'s repay was sent (transaction ${approve}) and its answer was lost (${(0, fence_js_1.unfenced)(String(error))}), so it may have gone through. The repay was not sent: nothing was repaid. Check that transaction before calling again.`);
420
+ }
421
+ mined(approved, "USDG approval", approve);
350
422
  }
351
423
  const hash = await walletProvider.sendTransaction({
352
424
  to: constants_1.PRIORS_POOL,
@@ -356,11 +428,18 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
356
428
  args: [BigInt(args.loanId), loan.agentId, due],
357
429
  }),
358
430
  });
359
- mined(await walletProvider.waitForTransactionReceipt(hash), "repay", hash);
431
+ let receipt;
432
+ try {
433
+ receipt = await walletProvider.waitForTransactionReceipt(hash);
434
+ }
435
+ catch (error) {
436
+ throw new Unconfirmed(`the repay of loan #${args.loanId} (${usdg(due)} USDG) was sent (transaction ${hash}) and its answer was lost (${(0, fence_js_1.unfenced)(String(error))}), so it may have repaid the loan: check that transaction before calling again.`);
437
+ }
438
+ mined(receipt, "repay", hash);
360
439
  return `Repaid Priors loan #${args.loanId}: ${usdg(due)} USDG. Transaction: ${hash}`;
361
440
  }
362
441
  catch (error) {
363
- if (error instanceof Refusal)
442
+ if (error instanceof Refusal || error instanceof Unconfirmed)
364
443
  return `Error: ${error.message}`;
365
444
  return `Error repaying loan #${args.loanId}: ${(0, fence_js_1.unfenced)(String(error))}`;
366
445
  }
@@ -417,14 +496,14 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
417
496
  return await this.onePerWallet(walletProvider, async () => {
418
497
  // a payment signed for this purchase that may still settle is sent again, before anything is probed or borrowed
419
498
  const now = Math.floor(Date.now() / 1000);
420
- for (const [k, v] of this.unsettled)
499
+ for (const [k, v] of unsettled)
421
500
  if (v.validBefore + X.SKEW_SECONDS <= now)
422
- this.unsettled.delete(k);
423
- const out = this.unsettled.get(purchase);
501
+ unsettled.delete(k);
502
+ const out = unsettled.get(purchase);
424
503
  if (out) {
425
504
  const r = await X.resend(args.url, out.paymentHeaders, { ...RESEND, init: init(), fetchImpl: this.fetchImpl, timeoutMs: X.DEFAULT_TIMEOUT_MS });
426
505
  if (r.response.ok)
427
- this.unsettled.delete(purchase);
506
+ unsettled.delete(purchase);
428
507
  const first = out.borrowed ? `Its first attempt: ${out.borrowed}` : "\n";
429
508
  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
509
  }
@@ -438,6 +517,9 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
438
517
  const name = error?.name;
439
518
  if (name === "TimeoutError" || name === "AbortError")
440
519
  return `Error: ${host} did not answer within ${X.DEFAULT_TIMEOUT_MS / 1000} s. Nothing was signed or paid.`;
520
+ const at = refusedAtConnect(error);
521
+ if (at !== null)
522
+ return `Error: ${host} resolved to a private, loopback or link-local address when connecting (${at}), after it resolved to a public one when checked: refused, no connection made. Nothing was fetched or paid.`;
441
523
  throw error;
442
524
  }
443
525
  const probeText = async () => {
@@ -506,13 +588,18 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
506
588
  const amount = gap > params.minLoan ? gap : params.minLoan;
507
589
  if (auto && !autoHere)
508
590
  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.`;
591
+ const unlisted = auto ? this.unlisted(args.agentId) : null;
592
+ if (unlisted)
593
+ return `Error: the wallet holds ${usdg(balance)} USDG, short of ${usdg(price)}, and ${unlisted} Nothing was borrowed or paid.`;
509
594
  if (amount > maxBorrow) {
510
595
  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
596
  }
512
597
  // auto: the day's room is taken here, before any await, so two calls running at once never both pass the
513
598
  // limit; it is given back whenever the borrow stops before it is sent, refused or a read failing, the
514
599
  // 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)
600
+ // GHSA-mc89); a borrow whose sending began and whose answer is lost stays counted (the safe direction).
601
+ // Before it is sent, what the pool lent the agent today is checked against the same limit (dayRoom), so a
602
+ // restart, which starts this count at 0, does not start the day again (GHSA-j679)
516
603
  let reserved = null;
517
604
  let sending = false;
518
605
  if (auto) {
@@ -520,15 +607,22 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
520
607
  if (this.borrowedToday.day !== today)
521
608
  this.borrowedToday = { day: today, amount: 0n };
522
609
  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.`;
610
+ 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, after what this process borrowed today, less than ${usdg(amount)}. Nothing was borrowed or paid.`;
524
611
  this.borrowedToday.amount += amount;
525
612
  reserved = { day: today, amount };
526
613
  }
527
- // auto: 14 days, brought down to the pool's maxTerm; otherwise the term asked, as before
614
+ const day = reserved?.day ?? "";
615
+ // auto: 14 days, brought down to the pool's maxTerm (and on a SeatVaultV5 line to its 10 days, borrowAmount);
616
+ // otherwise the term asked, as before
528
617
  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", () => {
618
+ const loan = await this.borrowAmount(walletProvider, args.agentId, amount, termDays, auto
619
+ ? async (fee) => {
620
+ await this.autopayCovers(walletProvider, args.agentId, amount + fee);
621
+ await this.dayRoom(walletProvider, args.agentId, amount, auto.perDay, day);
622
+ }
623
+ : undefined, "borrowed or paid", () => {
530
624
  sending = true; // right before the borrow's transaction is sent, every check passed
531
- })
625
+ }, !!auto)
532
626
  .catch((error) => {
533
627
  if (reserved && (!sending || error instanceof Reverted) && this.borrowedToday.day === reserved.day)
534
628
  this.borrowedToday.amount -= reserved.amount;
@@ -548,10 +642,10 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
548
642
  payTo,
549
643
  borrowed,
550
644
  };
551
- this.unsettled.set(purchase, signed);
645
+ unsettled.set(purchase, signed);
552
646
  const r = await X.resend(args.url, signed.paymentHeaders, { ...RESEND, init: init(), fetchImpl: this.fetchImpl, timeoutMs: X.DEFAULT_TIMEOUT_MS });
553
647
  if (r.response.ok)
554
- this.unsettled.delete(purchase);
648
+ unsettled.delete(purchase);
555
649
  return (0, fence_js_1.guarded)(`${borrowed}${await this.outcome(X, r, signed)}`);
556
650
  });
557
651
  }
@@ -566,8 +660,9 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
566
660
  /**
567
661
  * Auto-borrow's condition, read before the borrow is sent: this wallet is the agent's declared wallet, its Autopay
568
662
  * plan is on and set under the agent's current owner and key, not held or paused, its limit per loan is at least
569
- * `due`, and its USDG approval to AutoRepay covers `due` on top of the agent's open loans it already repays (those
570
- * within its limit), as @priors/mcp's check. Throws a Refusal saying what to turn on otherwise.
663
+ * `due`, and its USDG approval to AutoRepay covers `due` on top of the open loans it already repays: those of every
664
+ * agent in autoBorrow.agents whose plan on this wallet is on, each within its plan's limit. Throws a
665
+ * Refusal saying what to turn on otherwise.
571
666
  *
572
667
  * @param walletProvider - The wallet provider.
573
668
  * @param agentId - The agent id.
@@ -604,18 +699,63 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
604
699
  throw no("Autopay is paused by the Safe");
605
700
  if (BigInt(cap) < due)
606
701
  throw no(`Autopay's limit is ${usdg(BigInt(cap))} USDG per loan`);
607
- // what the agent's open loans already need from that approval: each active loan within the plan's limit
608
- const ids = (await walletProvider.readContract({ address: constants_1.PRIORS_POOL, abi: constants_1.POOL_ABI, functionName: "loansOf", args: [id] }));
702
+ // what the open loans already need from that approval: AutoRepayV2 keeps a plan per wallet and agent and
703
+ // pulls each from the wallet's one approval, so every agent of autoBorrow.agents whose plan on this wallet is on
704
+ // counts, each of its active loans within its plan's limit (unlisted() has refused an agent not listed)
609
705
  let owed = 0n;
610
- for (const loanId of ids) {
611
- const l = (await walletProvider.readContract({ address: constants_1.PRIORS_POOL, abi: constants_1.POOL_ABI, functionName: "getLoan", args: [loanId] }));
612
- const loanDue = BigInt(l.principal) + BigInt(l.fee);
613
- if (Number(l.status) === constants_1.LOAN_ACTIVE && loanDue <= BigInt(cap))
614
- owed += loanDue;
706
+ for (const other of this.auto?.agents ?? [id]) {
707
+ const [otherCap, , otherOn] = other === id ? plan : (await read(constants_1.AUTOREPAY, constants_1.AUTOREPAY_ABI, "planOf", [me, other]));
708
+ if (!otherOn)
709
+ continue;
710
+ const ids = (await walletProvider.readContract({ address: constants_1.PRIORS_POOL, abi: constants_1.POOL_ABI, functionName: "loansOf", args: [other] }));
711
+ for (const loanId of ids) {
712
+ const l = (await walletProvider.readContract({ address: constants_1.PRIORS_POOL, abi: constants_1.POOL_ABI, functionName: "getLoan", args: [loanId] }));
713
+ const loanDue = BigInt(l.principal) + BigInt(l.fee);
714
+ if (Number(l.status) === constants_1.LOAN_ACTIVE && loanDue <= BigInt(otherCap))
715
+ owed += loanDue;
716
+ }
615
717
  }
616
718
  if (BigInt(allowance) < owed + due)
617
719
  throw no(`Autopay may pull ${usdg(BigInt(allowance))} USDG from this wallet, and its open loans already need ${usdg(owed)} USDG`);
618
720
  }
721
+ /**
722
+ * Auto-borrow's day limit as the pool records the day (GHSA-j679): `amount` more on top of what the pool lent agent
723
+ * `agentId` since 00:00 UTC of `day` must stay within `perDay`. Every loan of the agent issued that day counts, whoever
724
+ * took it (the pool records the agent and its owner, not the key that borrowed), so a restart, or another process of
725
+ * this wallet, starts the day where the pool is; that can only lower auto-borrow's room. A read that fails, or a loan
726
+ * whose record does not read as one, refuses (nothing is sent). The pool lists an agent's loans oldest first
727
+ * (CreditPoolV2 appends each in borrow), so they are read from the newest back to the first one issued before the day.
728
+ *
729
+ * SHORTCUT: what the pool shows: a borrow another process sent and the chain has not mined yet is not seen, and after a
730
+ * restart a provider that auto-borrows for several agents counts each agent's own loans only (its count across agents
731
+ * starts again). Upgrade when the provider gets a place to keep state (@priors/mcp's daily ledger under
732
+ * PRIORS_STATE_DIR), or on a report of either.
733
+ *
734
+ * @param walletProvider - The wallet provider.
735
+ * @param agentId - The agent id.
736
+ * @param amount - The borrow about to be sent, atomic USDG.
737
+ * @param perDay - The owner's limit a UTC day, atomic USDG.
738
+ * @param day - The UTC day the borrow counts in (YYYY-MM-DD).
739
+ */
740
+ async dayRoom(walletProvider, agentId, amount, perDay, day) {
741
+ const id = BigInt(agentId);
742
+ let lent = 0n;
743
+ try {
744
+ const start = BigInt(Date.parse(`${day}T00:00:00Z`) / 1000);
745
+ const ids = (await walletProvider.readContract({ address: constants_1.PRIORS_POOL, abi: constants_1.POOL_ABI, functionName: "loansOf", args: [id] }));
746
+ for (let i = ids.length - 1; i >= 0; i--) {
747
+ const l = (await walletProvider.readContract({ address: constants_1.PRIORS_POOL, abi: constants_1.POOL_ABI, functionName: "getLoan", args: [ids[i]] }));
748
+ if (BigInt(l.issuedAt) < start)
749
+ break;
750
+ lent += BigInt(l.principal);
751
+ }
752
+ }
753
+ catch (error) {
754
+ throw new Refusal(`auto-borrow's day limit could not be checked: agent #${agentId}'s loans of today could not be read from the pool (${(0, fence_js_1.unfenced)(String(error))}). Nothing was borrowed or paid.`);
755
+ }
756
+ if (lent + amount > perDay)
757
+ throw new Refusal(`auto-borrow's limit of ${usdg(perDay)} USDG a day has ${usdg(lent < perDay ? perDay - lent : 0n)} left: the pool lent agent #${agentId} ${usdg(lent)} USDG since 00:00 UTC (every loan of the agent today counts, whoever took it, so a restart does not start the day again), less than ${usdg(amount)}. Nothing was borrowed or paid.`);
758
+ }
619
759
  /**
620
760
  * Before this wallet's money moves for agent `agentId` (a borrow into it, a repayment from it), @priors/mcp's rule
621
761
  * (needController, GHSA-9pw7): the wallet controls the agent at the pool AND is its current owner or its declared
@@ -693,15 +833,62 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
693
833
  */
694
834
  async onePerWallet(walletProvider, fn) {
695
835
  const key = String(walletProvider.getAddress()).toLowerCase();
696
- const run = (this.running.get(key) ?? Promise.resolve()).then(fn);
836
+ const run = (running.get(key) ?? Promise.resolve()).then(fn);
697
837
  const done = run.then(() => undefined, () => undefined);
698
- this.running.set(key, done);
838
+ running.set(key, done);
699
839
  try {
700
840
  return await run;
701
841
  }
702
842
  finally {
703
- if (this.running.get(key) === done)
704
- this.running.delete(key);
843
+ if (running.get(key) === done)
844
+ running.delete(key);
845
+ }
846
+ }
847
+ /**
848
+ * borrow_from_priors with autoBorrow set: the owner's limits hold the model's own borrow as they
849
+ * hold the pay action's. At most `perCall`; counted in `perDay` on the same count, this process's (taken before any
850
+ * await, given back when the borrow stops before it is sent or reverts, as the pay action's) and the pool's day
851
+ * (dayRoom); and only while Autopay covers the loan (autopayCovers). A manual borrow so uses up the day's room the pay
852
+ * action has, and a balance it funds stays within the limits whoever spends it. The term is the model's `days`.
853
+ *
854
+ * @param walletProvider - The wallet provider.
855
+ * @param agentId - The agent id.
856
+ * @param amount - Atomic USDG.
857
+ * @param days - The term in days.
858
+ * @param auto - The owner's autoBorrow limits.
859
+ * @returns The loan.
860
+ */
861
+ async borrowHeld(walletProvider, agentId, amount, days, auto) {
862
+ const held = (why) => new Refusal(`autoBorrow is set, so borrow_from_priors is held to its limits and checks: ${why}`);
863
+ const unlisted = this.unlisted(agentId);
864
+ if (unlisted)
865
+ throw held(`${unlisted} Nothing was borrowed.`);
866
+ if (amount > auto.perCall)
867
+ throw held(`${usdg(amount)} USDG is above autoBorrow's limit of ${usdg(auto.perCall)} USDG a call. Nothing was borrowed.`);
868
+ const today = utcDay();
869
+ if (this.borrowedToday.day !== today)
870
+ this.borrowedToday = { day: today, amount: 0n };
871
+ if (this.borrowedToday.amount + amount > auto.perDay)
872
+ throw held(`autoBorrow's limit of ${usdg(auto.perDay)} USDG a day has ${usdg(auto.perDay - this.borrowedToday.amount)} left, after what this process borrowed today, less than ${usdg(amount)}. Nothing was borrowed.`);
873
+ this.borrowedToday.amount += amount;
874
+ let sending = false;
875
+ try {
876
+ return await this.borrowAmount(walletProvider, agentId, amount, days, async (fee) => {
877
+ try {
878
+ await this.autopayCovers(walletProvider, agentId, amount + fee);
879
+ await this.dayRoom(walletProvider, agentId, amount, auto.perDay, today);
880
+ }
881
+ catch (error) {
882
+ throw error instanceof Refusal ? held(error.message) : error;
883
+ }
884
+ }, "borrowed", () => {
885
+ sending = true; // right before the borrow's transaction is sent, every check passed
886
+ });
887
+ }
888
+ catch (error) {
889
+ if ((!sending || error instanceof Reverted) && this.borrowedToday.day === today)
890
+ this.borrowedToday.amount -= amount;
891
+ throw error;
705
892
  }
706
893
  }
707
894
  /**
@@ -712,12 +899,29 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
712
899
  * @param amount - Atomic USDG.
713
900
  * @param days - The term in days.
714
901
  * @param check - Called with the quoted fee before the borrow is sent; a throw refuses it.
902
+ * On a SeatVaultV5 line, V5's rules before anything is sent, as @priors/x402's v5BeforeBorrow: a term
903
+ * over V5's 10 days is brought down to them when `fit` (auto-borrow's own term), else refused; then the key step
904
+ * (v5Ready).
905
+ *
715
906
  * @param did - What did not happen when the borrow is refused ("borrowed", "borrowed or paid").
716
907
  * @param onSend - Called once every check has passed, right before the borrow's transaction is sent.
908
+ * @param fit - Whether the term is the provider's own (auto-borrow's), brought down to V5's longest on its line.
717
909
  * @returns The loan.
718
910
  */
719
- async borrowAmount(walletProvider, agentId, amount, days, check, did = "borrowed", onSend) {
911
+ async borrowAmount(walletProvider, agentId, amount, days, check, did = "borrowed", onSend, fit = false) {
720
912
  const me = walletProvider.getAddress();
913
+ const line = (await walletProvider.readContract({
914
+ address: constants_1.PRIORS_POOL,
915
+ abi: constants_1.POOL_ABI,
916
+ functionName: "getAgent",
917
+ args: [BigInt(agentId)],
918
+ }));
919
+ const v5 = BigInt(line.sponsor) === constants_1.SEAT_VAULT_V5_ROOT;
920
+ if (v5 && days > constants_1.V5_MAX_TERM_DAYS) {
921
+ if (!fit)
922
+ throw new Refusal(`agent #${agentId}'s line is on SeatVaultV5, which lends for at most ${constants_1.V5_MAX_TERM_DAYS} days: a term of ${days} days would be refused on chain (BorrowBlockedByBacker), so nothing was ${did}. Borrow for ${constants_1.V5_MAX_TERM_DAYS} days or less.`);
923
+ days = constants_1.V5_MAX_TERM_DAYS;
924
+ }
721
925
  const term = BigInt(days * 86400);
722
926
  const [fee] = (await walletProvider.readContract({
723
927
  address: constants_1.PRIORS_POOL,
@@ -730,6 +934,8 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
730
934
  // the same rule as repay, before anything is sent: no key borrows here for an agent it would then be refused to
731
935
  // repay for
732
936
  await this.control(walletProvider, BigInt(agentId), did);
937
+ if (v5)
938
+ await this.v5Ready(walletProvider, agentId, did);
733
939
  onSend?.();
734
940
  const hash = await walletProvider.sendTransaction({
735
941
  to: constants_1.PRIORS_POOL,
@@ -767,6 +973,51 @@ class PriorsActionProvider extends agentkit_1.ActionProvider {
767
973
  }
768
974
  return { amount, fee, hash, loanId, dueAt };
769
975
  }
976
+ /**
977
+ * SeatVaultV5's key rule before a borrow on its line, as @priors/x402's v5BeforeBorrow: V5 lends only to
978
+ * the agent's owner, or to the pool delegate it recorded (noteDelegate) from 24 hours after. The owner's key, or one
979
+ * recorded that long ago, raises the pool's vouch to the line V5 allows now (refresh: V5 vouches nothing until then),
980
+ * and the borrow follows. A key V5 has not recorded is recorded now (control() has found this wallet controls the
981
+ * agent, so it is the pool's delegate) and, like one recorded under 24 hours ago, borrows nothing: the Refusal says
982
+ * from when it can. Each transaction's receipt is checked, a lost answer said with its transaction.
983
+ *
984
+ * @param walletProvider - The wallet provider.
985
+ * @param agentId - The agent id.
986
+ * @param did - What did not happen when refused ("borrowed", "borrowed or paid").
987
+ */
988
+ async v5Ready(walletProvider, agentId, did) {
989
+ const me = walletProvider.getAddress();
990
+ const id = BigInt(agentId);
991
+ const send = async (functionName, lost) => {
992
+ const hash = await walletProvider.sendTransaction({ to: constants_1.SEAT_VAULT_V5, data: (0, viem_1.encodeFunctionData)({ abi: constants_1.V5_ABI, functionName, args: [id] }) });
993
+ let receipt;
994
+ try {
995
+ receipt = await walletProvider.waitForTransactionReceipt(hash);
996
+ }
997
+ catch (error) {
998
+ throw new Unconfirmed(lost(hash, error));
999
+ }
1000
+ mined(receipt, `SeatVaultV5 ${functionName}`, hash);
1001
+ return hash;
1002
+ };
1003
+ const owner = String(await walletProvider.readContract({ address: constants_1.REGISTRY, abi: constants_1.REGISTRY_ABI, functionName: "ownerOf", args: [id] }));
1004
+ if (!sameAddress(owner, me)) {
1005
+ const [who, at] = (await walletProvider.readContract({ address: constants_1.SEAT_VAULT_V5, abi: constants_1.V5_ABI, functionName: "delegateOf", args: [id] }));
1006
+ const now = Math.floor(Date.now() / 1000);
1007
+ const recorded = sameAddress(who, me);
1008
+ if (!recorded || now < Number(at) + constants_1.V5_DELEGATE_WAIT_S) {
1009
+ const from = (s) => new Date(s * 1000).toISOString();
1010
+ let noted = "";
1011
+ if (!recorded) {
1012
+ const readyAt = from(now + constants_1.V5_DELEGATE_WAIT_S);
1013
+ const hash = await send("noteDelegate", (h, e) => `agent #${agentId}'s line is on SeatVaultV5: V5's record of this key (noteDelegate) was sent (transaction ${h}) and its answer was lost (${(0, fence_js_1.unfenced)(String(e))}), so it may have recorded it; then this key can borrow from ${readyAt}. Nothing was ${did}.`);
1014
+ noted = ` (recorded now, transaction ${hash})`;
1015
+ }
1016
+ throw new Refusal(`agent #${agentId}'s line is on SeatVaultV5, which lends only to the agent's owner, or to the agent's key from 24 hours after V5 recorded it${noted}: this key can borrow from ${from(recorded ? Number(at) + constants_1.V5_DELEGATE_WAIT_S : now + constants_1.V5_DELEGATE_WAIT_S)}. Nothing was ${did}.`);
1017
+ }
1018
+ }
1019
+ await send("refresh", (h, e) => `agent #${agentId}'s line is on SeatVaultV5: its refresh was sent (transaction ${h}) and its answer was lost (${(0, fence_js_1.unfenced)(String(e))}), so it may have raised the line. The borrow was not sent: nothing was ${did}.`);
1020
+ }
770
1021
  }
771
1022
  exports.PriorsActionProvider = PriorsActionProvider;
772
1023
  __decorate([
@@ -808,7 +1059,9 @@ must be repaid (principal and fee) before its due date, or the agent's record en
808
1059
  Inputs:
809
1060
  - agentId: the agent's ERC-8004 id; this wallet must be its owner or its registry wallet.
810
1061
  - amount: USDG to borrow, e.g. 1.5 (at least the pool's minimum loan).
811
- - days: the loan term in days (default 7).`,
1062
+ - days: the loan term in days (default 7; at most 10 on a SeatVaultV5 line).
1063
+ When the provider was set up with autoBorrow, this borrow is held to the owner's limits too (its amount per call and per
1064
+ day, counted with the pay action's own borrows), and only while Autopay covers the loan.`,
812
1065
  schema: schemas_1.BorrowSchema,
813
1066
  }),
814
1067
  __metadata("design:type", Function),
@@ -848,7 +1101,8 @@ Inputs:
848
1101
  - maxPrice: the most to pay for this call, in USDG (e.g. 0.10).
849
1102
  - maxBorrow: the most to borrow if the wallet is short, in USDG (default 0: never borrow; with autoBorrow, its amount
850
1103
  per call, which this can only lower).
851
- - days: the term of a loan taken for the gap (default 7; with autoBorrow always 14, the owner's setting).
1104
+ - days: the term of a loan taken for the gap (default 7; with autoBorrow always 14, the owner's setting, or 10 on a
1105
+ SeatVaultV5 line).
852
1106
  - method, body: POST and its body (default GET with no body).`,
853
1107
  schema: schemas_1.PayX402WithCreditSchema,
854
1108
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@priors/agentkit",
3
- "version": "0.2.4",
3
+ "version": "0.3.0",
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>",
@@ -18,6 +18,7 @@
18
18
  "dependencies": {
19
19
  "@priors/x402": "0.8.8",
20
20
  "@x402/fetch": "^2.29.0",
21
+ "undici": "6.29.1",
21
22
  "viem": "^2.38.3"
22
23
  },
23
24
  "peerDependencies": {