@priors/mcp 0.18.0 → 0.18.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # @priors/mcp changelog
2
2
 
3
+ ## 0.18.2 (2026-11-06)
4
+
5
+ - **The state file's lock is never taken from a running server by a clock** (GHSA-wqww-vjpx-w8mq, reported by
6
+ @JasmeJun). A lock was judged abandoned by its file time against this process's clock, so after a clock step (NTP, a
7
+ resumed VM), or on a file server whose clock is behind, a lock held for milliseconds was taken, two servers of one
8
+ wallet wrote at once, and an unsettled payment's entry could be lost; another session, or a restart, then signed that
9
+ purchase again. The lock now names its holder and is removed only by it, and is taken over only when that holder, on
10
+ this host, has ended, or once this server has seen it unchanged for 10 s. After 2 s the write still goes ahead
11
+ without it, as before.
12
+ - **`pt_buy` and `pt_sell` hold the trade to the quote the user agreed to** (GHSA-3fwm-95gh-5xh4, reported by
13
+ @SanjilVinsmoke): `min_out_pt` and `min_out_usdg`, such as `pt_quote`'s "at least". A fresh quote under it is refused
14
+ before anything is signed; otherwise the router call names the larger of it and the fresh quote's own minimum, never a
15
+ lower one. Without it, the minimum came from the fresh quote alone, so a trade could fill below the quote the user
16
+ agreed to (never below the oracle's rate at its own block less the slippage).
17
+
18
+ ## 0.18.1 (2026-11-05)
19
+
20
+ On @priors/x402 0.8.8 (a plan whose AutoRepay epoch could not be read, below).
21
+
22
+ - **A bid made while Priors' hub does not answer never sets the bids' approval down, and counts it** (GHSA-mc89-r73h-33vv,
23
+ reported by @sonson0910; only with `PRIORS_MARKET` on). With the hub's list of this wallet's bids unread, `market_bid`
24
+ and `market_bid_any` planned from this server's own record alone: an approval standing above `PRIORS_MAX_BIDS_USD`
25
+ (bids made in Go mode, on the board or on another machine) was set down to the new bid's price, leaving those bids
26
+ unfunded (0.16.0 had fixed the same in `market_cancel_bid`), and an approval under it was neither counted against
27
+ `PRIORS_MAX_BIDS_USD` nor kept back from the agent's open loans. With the hub down, the approval standing now counts
28
+ with the new bid: it is only ever raised, a bid that would pass `PRIORS_MAX_BIDS_USD` with it is refused before
29
+ anything is signed (try again once the hub answers), and keep back counts it.
30
+ - **Auto-borrow never borrows on a plan whose AutoRepay epoch could not be read** (GHSA-mc89-r73h-33vv): with
31
+ `@priors/x402` 0.8.7, a failed `epochOf` read made a plan set before the agent's key or owner changed, which
32
+ AutoRepayV2 never pays, read as current. The borrow is refused now ("AutoRepay's epoch ... could not be read just
33
+ now"), and `credit_status` says the same.
34
+
3
35
  ## 0.18.0 (2026-11-04)
4
36
 
5
37
  - `line_key_status` and `line_key_spend` (only with `PRIORS_LINE_KEY=on`, off by default; docs/LINE-KEY.md in the
package/README.md CHANGED
@@ -44,8 +44,8 @@ repaying.
44
44
  | `find_services(query?)` | services registered with the Priors facilitator that accept USDG (`GET /merchants`): the ones Priors approved, and the ones under review whose own endpoint passed the facilitator's 402 check, marked so; hidden or unchecked ones are not listed | no |
45
45
  | `pt_quote(side, amount, slippage_bps?)` | quote buying PT-USDG with USDG, selling it before maturity or redeeming it after: what comes out at the oracle's spot rate, the minimum a trade would name, the days to maturity and the fixed APY to maturity | no |
46
46
  | `pt_position(address?)` | the wallet's (or any address's) PT-USDG: balance, what it is worth now, what it pays at maturity, and whether the Priors stock vault takes PT-USDG behind a line yet | no (with `address`) |
47
- | `pt_buy(amount_usdg, slippage_bps?, dry_run?)` | buy PT-USDG with the wallet's USDG through Pendle's router (at most `PRIORS_MAX_PT_USD` per call, `PRIORS_MAX_PT_TOTAL_USD` per run), keeping back what payments signed and not settled yet still need; `dry_run` lists the calls; needs ETH for gas | yes |
48
- | `pt_sell(amount_pt \| "all", slippage_bps?, dry_run?)` | sell the wallet's PT-USDG for USDG at the market, before maturity; needs ETH for gas | yes |
47
+ | `pt_buy(amount_usdg, slippage_bps?, min_out_pt?, dry_run?)` | buy PT-USDG with the wallet's USDG through Pendle's router (at most `PRIORS_MAX_PT_USD` per call, `PRIORS_MAX_PT_TOTAL_USD` per run), keeping back what payments signed and not settled yet still need; `min_out_pt` (`pt_quote`'s "at least", the quote the user agreed to): a fresh quote under it is refused before anything is signed, and the swap names the larger of it and the fresh quote's own minimum; `dry_run` lists the calls; needs ETH for gas | yes |
48
+ | `pt_sell(amount_pt \| "all", slippage_bps?, min_out_usdg?, dry_run?)` | sell the wallet's PT-USDG for USDG at the market, before maturity; `min_out_usdg` holds the sale to the quote the user agreed to, as `min_out_pt` does a buy; needs ETH for gas | yes |
49
49
  | `pt_redeem(amount_pt \| "all", slippage_bps?, dry_run?)` | redeem the wallet's PT-USDG for USDG 1:1, from maturity (2027-03-25) on; needs ETH for gas | yes |
50
50
  | `pt_buy_and_deposit(amount_usdg, agent_id?, include_held?, slippage_bps?, dry_run?)` | only with `PRIORS_PT_ONESTEP=on` (below): buy PT-USDG with the wallet's USDG and deposit it, with the PT-USDG the wallet already holds (unless `include_held` is false), behind the agent's line on the Priors stock vault, which opens the line, in one call: four transactions (the exact USDG approval, the buy with its minimum out, the exact PT-USDG approval to the vault, the vault's open with this wallet's pool consent). The wallet must own the agent, and the agent must have no open stock line; checked before the first is signed. `pt_buy`'s caps apply; `dry_run` lists the calls; needs ETH for gas | yes |
51
51
  | `fund_base(amount_usd, max_borrow_usd?)` | only with Base on (below): move USDG to USDC in the same address on Base through Across, keeping back what Autopay and signed payments need, borrowing the gap only with `max_borrow_usd`; needs ETH for gas | yes |
@@ -134,7 +134,7 @@ nothing changes: no tool, no sentence in the instructions, and none of the setti
134
134
  | `market_list` | the cancel of its own listing while the market isn't approved (approving would bring it back at its old price; on V2 also its own listing on the older market), InviteBondV2's bond when the treasury line lends with none (an approval of exactly the bond, then the deposit), the registry's approval of this one agent, then `list` |
135
135
  | `market_cancel` | `cancel`, here and on the older market; any agent, always: it only stops a sale |
136
136
  | `market_buy` | an approval of exactly the price when the USDG approved is short, then `buy`, pinned to the listing read (its nonce, the agent's file, its record) |
137
- | `market_bid` | an approval to the bids' spender of exactly what all of this wallet's open bids take, when it is short or above `PRIORS_MAX_BIDS_USD`, then `bid` |
137
+ | `market_bid` | an approval to the bids' spender of exactly what all of this wallet's open bids take, when it is short or above `PRIORS_MAX_BIDS_USD` (while Priors' hub doesn't answer, the approval standing plus the bid, only ever raised: bids made elsewhere can't be counted then), then `bid` |
138
138
  | `market_bid_any` | the same approval, then `bidAny` on the origin's list from Priors' hub, its ids checked against its root first. The root proves only that the list is the hub's: any agent on it can be sold to this wallet, so the answer names the list and its first ids, and the bid asks at least 1 repaid loan unless `min_repaid` says otherwise |
139
139
  | `market_cancel_bid` | `cancelBid` for one bid, or `all` (at most 10 a call), then the approval set down to what the bids left take (left as it is while Priors' hub doesn't answer, since bids made elsewhere can't be counted then; with `all` and no open bid, an approval left standing is set to 0) |
140
140
  | `market_accept` | the cancels and the bond as `market_list` (the bond stays on the agent after the sale until its new owner bonds), the registry's approval, then `acceptBid` with what this wallet gets pinned exactly; a bid made before the agent's builder share was set, which the market refuses, is refused before anything is sent |
@@ -388,7 +388,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
388
388
  "mcpServers": {
389
389
  "priors": {
390
390
  "command": "npx",
391
- "args": ["-y", "@priors/mcp@0.18.0"],
391
+ "args": ["-y", "@priors/mcp@0.18.2"],
392
392
  "env": {
393
393
  "PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
394
394
  "PRIORS_AGENT_ID": "1234"
@@ -410,7 +410,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
410
410
  "mcpServers": {
411
411
  "priors": {
412
412
  "command": "npx",
413
- "args": ["-y", "@priors/mcp@0.18.0"],
413
+ "args": ["-y", "@priors/mcp@0.18.2"],
414
414
  "env": {
415
415
  "PRIORS_KEY": "${PRIORS_KEY}",
416
416
  "PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
@@ -423,7 +423,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
423
423
  or, for your user only, from a macOS or Linux terminal:
424
424
 
425
425
  ```sh
426
- (read -rs PRIORS_KEY && umask 077 && mkdir -p ~/.config/priors && rm -f ~/.config/priors/agent.key && printf '%s\n' "$PRIORS_KEY" > ~/.config/priors/agent.key) && claude mcp add priors --scope user -- sh -c 'read -r PRIORS_KEY < "$1" && export PRIORS_KEY && exec npx -y @priors/mcp@0.18.0' priors-mcp ~/.config/priors/agent.key
426
+ (read -rs PRIORS_KEY && umask 077 && mkdir -p ~/.config/priors && rm -f ~/.config/priors/agent.key && printf '%s\n' "$PRIORS_KEY" > ~/.config/priors/agent.key) && claude mcp add priors --scope user -- sh -c 'read -r PRIORS_KEY < "$1" && export PRIORS_KEY && exec npx -y @priors/mcp@0.18.2' priors-mcp ~/.config/priors/agent.key
427
427
  ```
428
428
 
429
429
  It waits for the key without showing it (paste it, then Enter), saves it in a file only you can read, and gives Claude
@@ -504,7 +504,7 @@ to approve a borrow; this package, with the key, pays for APIs. With borrowing o
504
504
  approves each loan in Priors' Go mode. ElizaOS (`@elizaos/plugin-mcp`):
505
505
 
506
506
  ```ts
507
- "priors-wallet": { type: "stdio", command: "npx", args: ["-y", "@priors/mcp@0.18.0"],
507
+ "priors-wallet": { type: "stdio", command: "npx", args: ["-y", "@priors/mcp@0.18.2"],
508
508
  env: { PRIORS_KEY_FILE: "/home/agent/.config/priors/agent-7311.key", PRIORS_AGENT_ID: "7311",
509
509
  PRIORS_MAX_BORROW_USD: "0", PRIORS_MAX_BORROW_DAY_USD: "0", PRIORS_MAX_SPEND_DAY_USD: "1", PRIORS_MAX_PRICE_USD: "0.10",
510
510
  PRIORS_PAY_HOSTS: "api.example.com" } }
@@ -516,7 +516,7 @@ OpenClaw (`mcp.servers`, JSON5) takes the same `command`, `args` and `env`; Herm
516
516
  mcp_servers:
517
517
  priors-wallet:
518
518
  command: npx
519
- args: ["-y", "@priors/mcp@0.18.0"]
519
+ args: ["-y", "@priors/mcp@0.18.2"]
520
520
  env:
521
521
  PRIORS_KEY_FILE: /home/agent/.config/priors/agent-7311.key
522
522
  PRIORS_AGENT_ID: "7311"
@@ -543,7 +543,7 @@ key proves it is there: it signs the ERC-8004 identity registry's `AgentWalletSe
543
543
  agent's).
544
544
 
545
545
  ```sh
546
- PRIORS_KEY_FILE=~/.config/priors/agent-7311.key npx -y @priors/mcp@0.18.0 link-wallet --agent 7311
546
+ PRIORS_KEY_FILE=~/.config/priors/agent-7311.key npx -y @priors/mcp@0.18.2 link-wallet --agent 7311
547
547
  ```
548
548
 
549
549
  It reads the registry's EIP-712 domain and refuses to sign for any other, takes the owner from the chain (`--owner`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@priors/mcp",
3
3
  "mcpName": "io.github.priors-agents/priors",
4
- "version": "0.18.0",
4
+ "version": "0.18.2",
5
5
  "private": false,
6
6
  "description": "MCP server for Priors on Robinhood Chain: pay x402 URLs in USDG, read balances, credit lines and scores, borrow and repay, and buy, sell and redeem PT-USDG. Key from PRIORS_KEY_FILE (a file only you can read) or PRIORS_KEY, never the command line.",
7
7
  "type": "module",
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@modelcontextprotocol/sdk": "^1.30.1",
48
- "@priors/x402": "0.8.7",
48
+ "@priors/x402": "0.8.8",
49
49
  "ethers": "^6.13.4",
50
50
  "undici": "6.29.1",
51
51
  "viem": "^2.56.9",
@@ -556,6 +556,18 @@ function reserveOf(c, { ids, me, now, except = [], extra = 0n }) {
556
556
  }
557
557
  return sum;
558
558
  }
559
+ /** A new bid's reserve (`extra` on top of the open bids in `ids`), and what an over-limit refusal says. With Priors' hub
560
+ * down (`hubDown`), the bids this wallet made elsewhere (Go mode, the board, another machine) are unknown, and the
561
+ * approval standing (c.reserve) may fund them: the bid counts on top of it, so it is never set down (P-55's rule) and
562
+ * the limit and keep back see it (P-54's) (GHSA-mc89-r73h-33vv). `standing`: the approval as the call first read it,
563
+ * when it plans again after its own approval (which then stands for this bid too). */
564
+ function newReserve(c, { ids, me, now, extra, hubDown, maxReserve, standing: first = null }) {
565
+ const known = reserveOf(c, { ids, me, now, extra });
566
+ if (known == null) return { error: "unread" };
567
+ const standing = first ?? big(c.reserve), reserve = hubDown && standing + extra > known ? standing + extra : known;
568
+ if (reserve > big(maxReserve)) return { error: "over", reserve, max: big(maxReserve), ...(hubDown ? { down: true, standing } : {}) };
569
+ return { reserve, ...(hubDown ? { standing } : {}) };
570
+ }
559
571
  /** The terms both bids check first, in the contract's order: the pause, the wallet's standing, the price, the days. */
560
572
  function bidTerms(c, { me, now, price, days, expiry }) {
561
573
  if (unread(c.paused, c.custodian, c.refused, c.marked, c.cash, c.reserve, c.feeBps, c.minFee)) return { error: "unread" };
@@ -576,9 +588,12 @@ function bidTerms(c, { me, now, price, days, expiry }) {
576
588
  * market stops doesn't count, as bid() takes the bid then), "short" (`short`, `cash`), "over" (`reserve`, `max`)), or
577
589
  * { steps ("approveReserve": the reserve set to exactly what all its open bids and this one take, when the allowance
578
590
  * is under it or above `maxReserve`; "bid"), reserve, price, expiry, uriHash (only as its file is now: the URI's bytes
579
- * hashed here, with `sameFile`), minRepaid, minLine, fee, share, net (what the owner gets now), pins }.
591
+ * hashed here, with `sameFile`), minRepaid, minLine, fee, share, net (what the owner gets now), pins }. `hubDown`:
592
+ * Priors' hub didn't answer, so `myBids` lacks the bids made elsewhere: the reserve is at least the approval standing
593
+ * plus this bid ("over" then carries `down` and `standing`), and the approval is never set down (newReserve); the plan
594
+ * keeps that `standing`, which its call passes back when it plans again after its own approval.
580
595
  */
581
- export function bidPlan(c, { addr, me, id, now, price, days, expiry = null, sameFile = true, minRepaid = 0n, minLine = 0n, myBids = [], maxReserve, minRecord = 0n, adapters = [], shares = false }) {
596
+ export function bidPlan(c, { addr, me, id, now, price, days, expiry = null, sameFile = true, minRepaid = 0n, minLine = 0n, myBids = [], maxReserve, minRecord = 0n, adapters = [], shares = false, hubDown = false, standing = null }) {
582
597
  c = c || {};
583
598
  const t = bidTerms(c, { me, now, price, days, expiry });
584
599
  if (t.error) return t;
@@ -597,15 +612,15 @@ export function bidPlan(c, { addr, me, id, now, price, days, expiry = null, same
597
612
  if (!k.error) return { error: "listed", price: l.price };
598
613
  }
599
614
  if (big(c.cash) < t.p) return { error: "short", short: t.p - big(c.cash), cash: big(c.cash) };
600
- const reserve = reserveOf(c, { ids: myBids, me, now, extra: t.p });
601
- if (reserve == null) return { error: "unread" };
602
- if (reserve > big(maxReserve)) return { error: "over", reserve, max: big(maxReserve) };
615
+ const nr = newReserve(c, { ids: myBids, me, now, extra: t.p, hubDown, maxReserve, standing });
616
+ if (nr.error) return nr;
617
+ const { reserve } = nr;
603
618
  const bi = builderIn(c, shares);
604
619
  if (bi.error) return bi;
605
620
  const { fee, share, net } = netOf(t.p, { ...feesOf(c), builder: bi.builder, seller: c.owner });
606
621
  const uriHash = sameFile ? lc(ethers.keccak256(ethers.toUtf8Bytes(c.uri))) : ZERO32;
607
622
  const r = big(c.reserve), mr = big(minRepaid), ml = big(minLine);
608
- return { steps: [...(r < reserve || r > big(maxReserve) ? ["approveReserve"] : []), "bid"], reserve, price: t.p, expiry: t.e, uriHash, minRepaid: mr, minLine: ml, fee, share, net,
623
+ return { steps: [...(r < reserve || r > big(maxReserve) ? ["approveReserve"] : []), "bid"], reserve, ...(nr.standing != null ? { standing: nr.standing } : {}), price: t.p, expiry: t.e, uriHash, minRepaid: mr, minLine: ml, fee, share, net,
609
624
  pins: { id: big(id), price: t.p, expiry: t.e, uriHash, minRepaid: mr, minLine: ml } };
610
625
  }
611
626
  /**
@@ -613,9 +628,9 @@ export function bidPlan(c, { addr, me, id, now, price, days, expiry = null, same
613
628
  * first (its ids don't make its root: the index's answer is refused), "count" (1 to 20, at most the list's size: `max`),
614
629
  * then bidPlan's terms, "short" (price × count), "over"; else { steps ("approveReserve", "bidAny"), reserve, price,
615
630
  * total, count, root, expiry, minRepaid, minLine, fee, net (what an owner gets now; no share is known before an agent
616
- * is), pins }.
631
+ * is), pins }. `hubDown` as bidPlan's.
617
632
  */
618
- export function bidAnyPlan(c, { me, now, set, count, price, days, expiry = null, minRepaid = 0n, minLine = 0n, myBids = [], maxReserve }) {
633
+ export function bidAnyPlan(c, { me, now, set, count, price, days, expiry = null, minRepaid = 0n, minLine = 0n, myBids = [], maxReserve, hubDown = false, standing = null }) {
619
634
  c = c || {};
620
635
  let root;
621
636
  try { root = set && Array.isArray(set.ids) && set.ids.length ? idsRootOf(set.ids) : null; } catch (_) { root = null; }
@@ -626,12 +641,12 @@ export function bidAnyPlan(c, { me, now, set, count, price, days, expiry = null,
626
641
  if (t.error) return t;
627
642
  const total = t.p * BigInt(count);
628
643
  if (big(c.cash) < total) return { error: "short", short: total - big(c.cash), cash: big(c.cash) };
629
- const reserve = reserveOf(c, { ids: myBids, me, now, extra: total });
630
- if (reserve == null) return { error: "unread" };
631
- if (reserve > big(maxReserve)) return { error: "over", reserve, max: big(maxReserve) };
644
+ const nr = newReserve(c, { ids: myBids, me, now, extra: total, hubDown, maxReserve, standing });
645
+ if (nr.error) return nr;
646
+ const { reserve } = nr;
632
647
  const { fee, net } = netOf(t.p, feesOf(c));
633
648
  const r = big(c.reserve), mr = big(minRepaid), ml = big(minLine);
634
- return { steps: [...(r < reserve || r > big(maxReserve) ? ["approveReserve"] : []), "bidAny"], reserve, price: t.p, total, count, root, expiry: t.e, minRepaid: mr, minLine: ml, fee, net,
649
+ return { steps: [...(r < reserve || r > big(maxReserve) ? ["approveReserve"] : []), "bidAny"], reserve, ...(nr.standing != null ? { standing: nr.standing } : {}), price: t.p, total, count, root, expiry: t.e, minRepaid: mr, minLine: ml, fee, net,
635
650
  pins: { root, count, price: t.p, expiry: t.e, minRepaid: mr, minLine: ml } };
636
651
  }
637
652
  /**
@@ -816,6 +831,7 @@ export const PLAN_WORDS = Object.freeze({
816
831
  ceiling: "This could take {amount} USDG, above this server's limit of {max} USDG for one buy or bid. The user can raise PRIORS_MAX_MARKET_USD.",
817
832
  day: "This would bring today's buys and bids for agent #{self} and this wallet to {total} USDG, above {cap} USDG a day. {used} USDG was counted today, and the limit starts again at 00:00 UTC.",
818
833
  bidsOver: "Your open bids would take up to {reserve} USDG, above this server's limit of {max} USDG. Cancel a bid, then bid.",
834
+ bidsOverDown: "Priors' hub didn't answer, so bids this wallet made elsewhere can't be counted, and the bids' approval, which may fund them, stands at {standing} USDG: with this bid, all open bids could take up to {reserve} USDG, above this server's limit of {max} USDG. Try again once the hub answers.",
819
835
  dupBid: "This wallet made bid #{bidId} on the same terms in the last 10 minutes, and it is still open. To bid again, cancel it with market_cancel_bid, then bid.",
820
836
  record: "#{id} has {m} repaid loan{s}. This server buys and bids only on agents with {n} or more.",
821
837
  // money
@@ -912,6 +912,7 @@ export function registerMarketTools(ctx) {
912
912
  return { ids: [...new Set([...myBidIds(rec), ...(fromHub || [])])], hubDown: fromHub === null };
913
913
  }
914
914
  const reserveLine = (x) => `Your bids can take up to ${amt(x)} USDG from this wallet.`;
915
+ const downLine = " Priors' hub didn't answer, so bids this wallet made elsewhere can't be listed: the approval standing, which may fund them, is counted in it with this bid, and never set down.";
915
916
  tool("market_bid", {
916
917
  title: "Bid on an agent",
917
918
  description: `Bid price_usd on one agent on Priors' agent market (AgentMarketV2): the agent's owner can accept it at any time until it ends, and the agent then comes to this wallet at once. The USDG stays in this wallet until then: one approval to the bids' spender, set to exactly what all of this wallet's open bids take, covers every bid. Its pins, Go mode's defaults: same_file (default true: only as its file is now), min_repaid (default its repaid loans now, never under PRIORS_MARKET_MIN_REPAID), min_line_usd (default its treasury line when it lends). Held to PRIORS_MAX_MARKET_USD (${amt(S.maxMarket)} USDG) a bid, PRIORS_MAX_BIDS_USD (${amt(S.maxBids)} USDG) for all open bids, PRIORS_MAX_MARKET_DAY_USD a day, and agent #${S.agentId}'s open loans. Refused when it is listed at or below the bid (buy it instead). Commits real money: state the agent, the price, the fee and what the owner gets to the user and get their go-ahead first; dry_run: true lists the transactions without sending. Needs ETH for gas.`,
@@ -932,8 +933,9 @@ export function registerMarketTools(ctx) {
932
933
  const follows = BigInt(a.sponsor) !== 0n && s.c.followed === true, lent = BigInt(a.delegatedIn);
933
934
  const minRepaid = first ? first.minRepaid : (() => { const r = min_repaid != null ? BigInt(min_repaid) : BigInt(a.loansRepaid); return r < S.minRepaid ? S.minRepaid : r; })();
934
935
  const minLine = first ? first.minLine : min_line_usd != null ? units(min_line_usd, "min_line_usd") : follows && lent > 0n ? lent : 0n;
935
- const p = M.bidPlan(s.c, { addr: k.addr, me, id, now: s.now, price, days, expiry: first ? first.expiry : null, sameFile: same_file, minRepaid, minLine, myBids: [...s.c.bids.keys()], maxReserve: S.maxBids, minRecord: S.minRepaid, adapters: REC.adapters, shares: k.shares });
936
- return p.error === "over" ? { ...p, error: "bidsOver" } : p;
936
+ // the hub down: the approval standing counts with this bid, and is never set down (GHSA-mc89-r73h-33vv)
937
+ const p = M.bidPlan(s.c, { addr: k.addr, me, id, now: s.now, price, days, expiry: first ? first.expiry : null, sameFile: same_file, minRepaid, minLine, myBids: [...s.c.bids.keys()], maxReserve: S.maxBids, minRecord: S.minRepaid, adapters: REC.adapters, shares: k.shares, hubDown, standing: first ? first.standing : null });
938
+ return p.error === "over" ? { ...p, error: p.down ? "bidsOverDown" : "bidsOver" } : p;
937
939
  },
938
940
  // a retry whose terms differ only in days (or whose answer was lost and its settling is past the replay) is a
939
941
  // second bid on chain: refused while the record's stands
@@ -943,7 +945,7 @@ export function registerMarketTools(ctx) {
943
945
  },
944
946
  changed: (p, f) => (p.pins.uriHash !== f.pins.uriHash ? M.planWords("fileMoved", { id }) : "Its terms changed since the first read."),
945
947
  keep: (p) => p.reserve, day: (p) => p.price, counted: (step, p) => (step === "bid" ? p.price : 0n),
946
- facts: (p) => [`Bids on #${id}: ${amt(p.price)} USDG. Fee ${amt(p.fee)}.${p.share > 0n ? ` Builder share ${amt(p.share)}.` : ""} The owner gets ${amt(p.net)}. Until ${M.dayText(p.expiry)}.`, `${reserveLine(p.reserve)}${hubDown ? " Priors' hub didn't answer, so bids this wallet made elsewhere aren't counted in it." : ""}`],
948
+ facts: (p) => [`Bids on #${id}: ${amt(p.price)} USDG. Fee ${amt(p.fee)}.${p.share > 0n ? ` Builder share ${amt(p.share)}.` : ""} The owner gets ${amt(p.net)}. Until ${M.dayText(p.expiry)}.`, `${reserveLine(p.reserve)}${hubDown ? downLine : ""}`],
947
949
  done: async ({ k, sent, plan, events, T }) => {
948
950
  const txs = sent.map((x) => x.hash), ev = events.find((e) => e.name === "BidMade" && same(e.args.maker, me) && BigInt(e.args.agentId) === id);
949
951
  if (!ev) return { text: `${cap1(stageWords("bid", id))} was mined (tx ${txs[txs.length - 1]}), but its receipt carries no BidMade event for #${id} from this wallet. ${NOTHING_MORE} market_agent shows its bids.`, structured: { tool: "market_bid", agentId: String(id), txs, bid: null } };
@@ -985,13 +987,13 @@ export function registerMarketTools(ctx) {
985
987
  return execute({
986
988
  name: "market_bid_any", role: "bid", args: { origin, count, price_usd, days, min_repaid, min_line_usd }, id: null, me, dry: dry_run, vars: { price, max: S.maxBids },
987
989
  read: async (rec, k, T) => { const b = await myBids(rec, T); hubDown = b.hubDown; return { me, self: S.agentId, bidIds: b.ids }; },
988
- plan: (s, k, first) => { const p = M.bidAnyPlan(s.c, { me, now: s.now, set, count, price, days, expiry: first ? first.expiry : null, minRepaid, minLine, myBids: [...s.c.bids.keys()], maxReserve: S.maxBids }); return p.error === "over" ? { ...p, error: "bidsOver" } : p; },
990
+ plan: (s, k, first) => { const p = M.bidAnyPlan(s.c, { me, now: s.now, set, count, price, days, expiry: first ? first.expiry : null, minRepaid, minLine, myBids: [...s.c.bids.keys()], maxReserve: S.maxBids, hubDown, standing: first ? first.standing : null }); return p.error === "over" ? { ...p, error: p.down ? "bidsOverDown" : "bidsOver" } : p; },
989
991
  check: (p, s, rec) => {
990
992
  const dup = recentBid(rec, s.c, s.now, (x) => x.any && lc(x.target) === lc(p.root) && BigInt(x.price) === p.price && BigInt(x.minRepaid) === p.minRepaid && BigInt(x.minLine) === p.minLine);
991
993
  if (dup) throw refuse("dupBid", { bidId: BigInt(dup) }, "bid");
992
994
  },
993
995
  keep: (p) => p.reserve, day: (p) => p.total, counted: (step, p) => (step === "bidAny" ? p.total : 0n),
994
- facts: (p) => [`Bids on any of ${listWords}: ${amt(p.price)} USDG each, up to ${count}. Fee ${amt(p.fee)}. An owner gets ${amt(p.net)}, less any builder share on its agent. Until ${M.dayText(p.expiry)}.${recordWords}`, `${reserveLine(p.reserve)}${hubDown ? " Priors' hub didn't answer, so bids this wallet made elsewhere aren't counted in it." : ""}`],
996
+ facts: (p) => [`Bids on any of ${listWords}: ${amt(p.price)} USDG each, up to ${count}. Fee ${amt(p.fee)}. An owner gets ${amt(p.net)}, less any builder share on its agent. Until ${M.dayText(p.expiry)}.${recordWords}`, `${reserveLine(p.reserve)}${hubDown ? downLine : ""}`],
995
997
  done: async ({ sent, plan, events }) => {
996
998
  const txs = sent.map((x) => x.hash), ev = events.find((e) => e.name === "BidAnyMade" && same(e.args.maker, me) && lc(e.args.root) === set.root);
997
999
  if (!ev) return { text: `${cap1(stageWords("bidAny", null))} was mined (tx ${txs[txs.length - 1]}), but its receipt carries no BidAnyMade event from this wallet. ${NOTHING_MORE}`, structured: { tool: "market_bid_any", txs, bid: null } };
package/src/server.mjs CHANGED
@@ -121,8 +121,8 @@
121
121
  // or http for localhost only, no credentials, query or fragment
122
122
  // With both on, PRIORS_AGENT_ID and PRIORS_STATE_DIR are required: a buy leaves what that agent's open loans owe, and
123
123
  // the zap's 5 buys and 5 sales a UTC day are counted there for the agent and the wallet.
124
- import { readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, statSync, rmSync, existsSync, realpathSync, lstatSync, readlinkSync } from "node:fs";
125
- import { homedir } from "node:os";
124
+ import { readFileSync, writeFileSync, mkdirSync, renameSync, statSync, rmSync, existsSync, realpathSync, lstatSync, readlinkSync, linkSync } from "node:fs";
125
+ import { homedir, hostname } from "node:os";
126
126
  import { isAbsolute, join } from "node:path";
127
127
  import { randomBytes } from "node:crypto";
128
128
  import { createRequire } from "node:module";
@@ -674,23 +674,58 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
674
674
  }
675
675
  // Several servers can share one wallet (two sessions, Claude Desktop and Claude Code): every change is a
676
676
  // read-modify-write of the file under an exclusive lock file, so no server rewrites it from its own map and erases
677
- // another's entries. Best effort: a lock older than 10 s is stale, and after 2 s the write goes ahead without it.
677
+ // another's entries. Best effort: after 2 s the write goes ahead without it.
678
678
  // Waiting for it delays this call only (an async wait, never a blocking one): the server keeps answering meanwhile.
679
679
  // Inside one process the lock is held only across synchronous code, so two calls of this server never contend.
680
+ // The lock names its holder (this host, its pid, a random token), written as it is made, and only that holder removes
681
+ // it. No clock says a lock was abandoned (GHSA-wqww-vjpx-w8mq): its file time against this process's clock read a lock
682
+ // milliseconds old as one over 10 s old after a clock step (NTP, a resumed VM) or on a file server whose clock is
683
+ // behind, so a second server took it and wrote at the same time, one erasing the other's entry, and the first then
684
+ // removed the second's lock. A lock is taken over only when its holder is a process of this host no longer running,
685
+ // or once this process has seen that same lock for 10 s of its own monotonic clock, over its calls (a holder stopped
686
+ // that long, a pid reused, another host's lock, the empty lock of a server before this rule).
687
+ const lockHost = hostname();
688
+ let lockSeen = null; // the lock this process last found held, and when (performance.now()) it first found it
689
+ const running = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e?.code === "EPERM"; } };
690
+ /** The lock at `path`: which one it is (its file and its token, never its time against a clock), and whether its
691
+ * holder is a process of this host no longer running (in this process a lock never outlives a call). Throws if none. */
692
+ function lockAt(path) {
693
+ const st = statSync(path);
694
+ let h = null;
695
+ try { h = JSON.parse(readFileSync(path, "utf8")); } catch (_) { /* empty: being written, or an older server's */ }
696
+ const pid = Number(h?.pid);
697
+ return { id: `${st.dev}:${st.ino}:${st.mtimeMs}:${h?.token ?? ""}`, gone: h?.host === lockHost && Number.isSafeInteger(pid) && pid > 0 && (pid === process.pid || !running(pid)) };
698
+ }
699
+ /** Moves the lock `id` aside and removes it. If what moved is another lock by then (a server that took it over first
700
+ * and made its own), it is put back, unless a third took the name meanwhile: as sdk/tx-record.mjs's lockKey. */
701
+ function takeOver(path, id) {
702
+ const aside = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.stale`;
703
+ try { renameSync(path, aside); } catch (e) { return e?.code === "ENOENT"; }
704
+ try { if (lockAt(aside).id !== id) linkSync(aside, path); } catch (_) { /* a third took the name */ }
705
+ rmSync(aside, { force: true });
706
+ return true;
707
+ }
680
708
  async function locked(fn) {
681
709
  const lock = `${stateFile}.lock`;
682
- const giveUp = Date.now() + 2000;
710
+ const token = randomBytes(12).toString("hex");
711
+ const start = performance.now();
683
712
  let held = false;
684
713
  for (;;) {
685
- try { closeSync(openSync(lock, "wx", 0o600)); held = true; break; } catch (e) {
714
+ try { writeFileSync(lock, JSON.stringify({ host: lockHost, pid: process.pid, token }), { flag: "wx", mode: 0o600 }); held = true; break; } catch (e) {
686
715
  if (e?.code === "ENOENT") { try { mkdirSync(stateDir, { recursive: true, mode: 0o700 }); continue; } catch (_) { break; } }
687
716
  if (e?.code !== "EEXIST") break;
688
- try { if (Date.now() - statSync(lock).mtimeMs > 10_000) { rmSync(lock, { force: true }); continue; } } catch (_) { continue; }
689
- if (Date.now() > giveUp) break;
717
+ let now;
718
+ try { now = lockAt(lock); } catch (_) { continue; } // released meanwhile
719
+ const t = performance.now();
720
+ if (lockSeen?.id !== now.id) lockSeen = { id: now.id, at: t };
721
+ if ((now.gone || t - lockSeen.at >= 10_000) && takeOver(lock, now.id)) continue;
722
+ if (t - start > 2000) break;
690
723
  await new Promise((res) => setTimeout(res, 10));
691
724
  }
692
725
  }
693
- try { return fn(); } finally { if (held) rmSync(lock, { force: true }); }
726
+ try { return fn(); } finally {
727
+ if (held) { try { if (JSON.parse(readFileSync(lock, "utf8")).token === token) rmSync(lock, { force: true }); } catch (_) { /* gone, or not ours */ } }
728
+ }
694
729
  }
695
730
  /** Entries another server of this wallet wrote since: merged in before any decision to sign. */
696
731
  function refresh() { if (stateFile) for (const [k, e] of readState()) if (!outstanding.has(k)) outstanding.set(k, e); }
@@ -1125,6 +1160,8 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
1125
1160
  throw no(`agent #${id}'s declared wallet is its owner's own address (this wallet), and AutoRepay never repays from that address under a wallet plan, so no plan covers the loan. Declare a key of the agent's own as its wallet (the registry's setAgentWallet) and turn Autopay on from that key`);
1126
1161
  }
1127
1162
  if (!st.plan.on) throw no("Autopay is off for this wallet");
1163
+ // null: AutoRepay's epoch unread, so a plan set before the agent's key or owner changed can't be told apart (GHSA-mc89)
1164
+ if (st.plan.current === null) throw no(`AutoRepay's epoch for agent #${id} could not be read just now, so whether this wallet's plan still pays can't be told (one set before the agent's key or owner changed pays nothing); try again in a moment`);
1128
1165
  if (!st.plan.current) throw no("this wallet's Autopay plan was set under an earlier owner or key of the agent, so it pays nothing now");
1129
1166
  if (st.held) throw no("Autopay is on hold for this wallet");
1130
1167
  if (st.paused) throw no(`Autopay is paused by the Safe until ${when(st.paused.until)}`);
@@ -1141,6 +1178,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
1141
1178
  if (!st.declared) return ["Autopay: off. This wallet is not the agent's declared wallet, so it can't repay the agent's loans through AutoRepay."];
1142
1179
  if (st.ownerIsWallet) return [`Autopay: off. The agent's declared wallet is its owner's own address (this wallet), and AutoRepay never repays from that address under a wallet plan${st.plan.on ? ", so the plan this wallet set pays nothing" : ""}. Declare a key of the agent's own as its wallet (setAgentWallet) and turn Autopay on from that key, or repay by hand before the due date.`];
1143
1180
  if (!st.plan.on) return ["Autopay: off. autopay_on turns it on: this wallet then repays each loan a few hours before it is due, if it holds enough."];
1181
+ if (st.plan.current === null) return ["Autopay: on, but AutoRepay's epoch for the agent couldn't be read just now, so whether the plan still pays can't be told (one set before the agent's key or owner changed pays nothing). Ask again in a moment."];
1144
1182
  if (!st.plan.current) return [st.plan.stale ? "Autopay: the plan was set before the agent's key or owner changed, so it pays nothing now. Call autopay_on again." : "Autopay: the plan was set under an earlier owner of the agent, so it pays nothing now. Call autopay_on again."];
1145
1183
  const out = [`Autopay: on, from this wallet${st.plan.useSavings ? " (then its savings)" : ""}; limit ${usd(st.plan.cap)} per loan, budget left ${usd(st.budget)}${st.plan.late ? "; also in the grace period" : ""}.${st.held ? " On hold: it pays nothing until resumed." : ""}${st.paused ? ` Paused by the Safe until ${when(st.paused.until)}: repay by hand before the due date.` : ""}`];
1146
1184
  if (st.next) out.push(`Next autopay: loan #${st.next.loanId}, ${usd(st.next.due)}, from ${when(st.next.opens)} (due ${when(st.next.dueAt)}).`);
@@ -2052,7 +2090,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2052
2090
 
2053
2091
  /** One trade from the configured wallet: the SDK's calls, sent in order (each simulated, then waited for). `count` is
2054
2092
  * serial's: a buy's amount counts against PRIORS_MAX_PT_TOTAL_USD from its check until the call ends. */
2055
- async function ptTrade(kind, amount, slippage_bps, dry_run, market, count) {
2093
+ async function ptTrade(kind, amount, slippage_bps, dry_run, market, count, floor) {
2056
2094
  const signer = needWallet(`pt_${kind}`);
2057
2095
  let units = null;
2058
2096
  if (kind === "buy") {
@@ -2065,6 +2103,17 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2065
2103
  if (!dry_run) count("ptBought", units);
2066
2104
  }
2067
2105
  const o = { account: signer.address, amount: units ?? amount, slippageBps: slippage_bps, ...(market ? { market } : {}) };
2106
+ // the least the caller holds the trade to (pt_quote's or a dry_run's "at least", the quote the user agreed to): a
2107
+ // fresh quote under it is refused before anything is signed, and the router call names the larger of it and the
2108
+ // fresh quote's own minimum, never a lower one (GHSA-3fwm-95gh-5xh4, as stock_buy's min_out)
2109
+ if (floor !== undefined) {
2110
+ const what = kind === "buy" ? "min_out_pt" : "min_out_usdg";
2111
+ const least = dollars(floor, what);
2112
+ let b;
2113
+ try { b = await pt.trade(kind, o); } catch (e) { throw asked(e); }
2114
+ if (b.quote.expectedOut < least) throw new ToolError(`pt_${kind} refused: the price moved: a fresh quote gives ${nf(b.quote.expectedOutText)} ${b.quote.tokenOut}, under the ${nf(ethers.formatUnits(least, 6))} ${b.quote.tokenOut} asked for at least (${what}). Nothing was signed or sent: quote it again (pt_quote) and ask the user.`);
2115
+ o.minOut = b.quote.minOut > least ? b.quote.minOut : least;
2116
+ }
2068
2117
  if (dry_run) {
2069
2118
  let b;
2070
2119
  try { b = await pt.trade(kind, o); } catch (e) { throw asked(e); }
@@ -2109,16 +2158,16 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
2109
2158
  tool("pt_buy", {
2110
2159
  title: "Buy PT-USDG with USDG",
2111
2160
  description: `Buy PT-USDG (Pendle's principal token for USDG, redeemable 1:1 for USDG on ${P.PT_USDG.maturity.slice(0, 10)}) with the configured wallet's USDG, through Pendle's router: an approval of exactly that USDG, then the swap, paying the PT-USDG to this wallet with a minimum out. Held to maturity it pays a fixed amount of USDG; sold earlier, it gets the market's rate then, which can be lower. Moves real money: quote it (pt_quote), state the amount and what it buys to the user and get their go-ahead first; dry_run: true lists the calls without sending. Needs ETH for gas.`,
2112
- inputSchema: { amount_usdg: z.number().positive().describe("USDG to spend, in US dollars (required, no default)."), slippage_bps: slippage, dry_run: dryRun },
2161
+ inputSchema: { amount_usdg: z.number().positive().describe("USDG to spend, in US dollars (required, no default)."), slippage_bps: slippage, min_out_pt: z.number().positive().optional().describe("The least PT-USDG to accept, e.g. pt_quote's \"at least\": a fresh quote under it is refused before anything is signed."), dry_run: dryRun },
2113
2162
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
2114
- }, serial(async ({ amount_usdg, slippage_bps, dry_run }, _deadline, count) => ptTrade("buy", amount_usdg, slippage_bps, dry_run, undefined, count)));
2163
+ }, serial(async ({ amount_usdg, slippage_bps, min_out_pt, dry_run }, _deadline, count) => ptTrade("buy", amount_usdg, slippage_bps, dry_run, undefined, count, min_out_pt)));
2115
2164
 
2116
2165
  tool("pt_sell", {
2117
2166
  title: "Sell PT-USDG for USDG",
2118
2167
  description: "Sell the configured wallet's PT-USDG for USDG at the market, before maturity, through Pendle's router: an approval of exactly that PT-USDG, then the swap, paying the USDG to this wallet with a minimum out. Moves real money: quote it (pt_quote), state the amount to the user and get their go-ahead first; dry_run: true lists the calls without sending. Needs ETH for gas.",
2119
- inputSchema: { amount_pt: ptAmount, slippage_bps: slippage, dry_run: dryRun },
2168
+ inputSchema: { amount_pt: ptAmount, slippage_bps: slippage, min_out_usdg: z.number().positive().optional().describe("The least USDG to accept, e.g. pt_quote's \"at least\": a fresh quote under it is refused before anything is signed."), dry_run: dryRun },
2120
2169
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
2121
- }, serial(async ({ amount_pt, slippage_bps, dry_run }) => ptTrade("sell", amount_pt, slippage_bps, dry_run)));
2170
+ }, serial(async ({ amount_pt, slippage_bps, min_out_usdg, dry_run }) => ptTrade("sell", amount_pt, slippage_bps, dry_run, undefined, undefined, min_out_usdg)));
2122
2171
 
2123
2172
  tool("pt_redeem", {
2124
2173
  title: "Redeem PT-USDG for USDG",