@priors/mcp 0.2.11 → 0.6.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/src/server.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // @priors/mcp: an MCP server that lets an AI assistant pay x402 URLs in USDG on Robinhood Chain and run a Priors
2
- // credit line. Tools: pay_url, wallet_balance, credit_status, stock_assets, stock_position, borrow, repay, score_of,
3
- // find_services.
2
+ // credit line, with the agent's spare USDG saved in a Morpho vault. Tools: pay_url, wallet_balance, credit_status,
3
+ // stock_assets, stock_position, borrow, repay, score_of, find_services, savings, save, unsave, autopay_on, autopay_off,
4
+ // and PT-USDG (Pendle's principal token for USDG): pt_quote, pt_position, pt_buy, pt_sell, pt_redeem.
4
5
  //
5
6
  // The private key comes from the environment (PRIORS_KEY) only. It is never read from argv, never logged, and never
6
7
  // part of any tool result or error: every text this server returns passes through `redact()`, which removes the key
@@ -18,8 +19,23 @@
18
19
  // PRIORS_ALLOW_LOCAL "1": pay_url may reach http://localhost and private addresses (testing only)
19
20
  // PRIORS_SCORE_V2 where score_of reads Priors Score v2 (default https://priors.trade/api/score-v2; "off": v1 only)
20
21
  // PRIORS_STOCK_VAULT the stock vault's address (default: deployments/4663.v2.json `stockVault`)
22
+ // PRIORS_SAVINGS_VAULT the USDG vault savings go to (default Steakhouse USDG on Morpho). "off" stops save and the
23
+ // automatic top-ups; savings and unsave keep working on the default vault, so saved money can
24
+ // always come out
25
+ // PRIORS_MAX_SAVE_USD most one save call may move into the vault (default 50)
26
+ // PRIORS_MAX_SAVE_TOTAL_USD most save may move in total while the server runs (default 200)
27
+ // PRIORS_AUTOREPAY AutoRepay v2's address (default: deployments/4663.v2.json `autoRepay`; none until it is
28
+ // deployed: autopay_on and autopay_off then say so). AutoRepay v1 (retired) is refused
29
+ // PRIORS_V5, PRIORS_V5_ROOT SeatVaultV5's address and its root's agent id (default: deployments/4663.v2.json
30
+ // `seatVaultV5`, `seatVaultV5AgentId`; none until V5 is deployed): a borrow on a V5 line
31
+ // refreshes it first (owner, or this key 24 h after V5 recorded it with noteDelegate)
32
+ // PRIORS_MAX_AUTOPAY_USD the most autopay_on enrolls per loan (default 25, the stage 0 cap)
33
+ // PRIORS_AUTOPAY_RESERVE "off": pay_url no longer keeps back what Autopay loans pull in the next 24 h (default on)
21
34
  // PRIORS_STATE_DIR where signed, unsettled payments are kept across restarts and shared by every session of the
22
35
  // wallet (default ~/.local/state/priors-mcp; "off": memory only)
36
+ // PRIORS_PT "off": no PT-USDG tool (default on: the market is Pendle's, live on Robinhood Chain)
37
+ // PRIORS_MAX_PT_USD most USDG one pt_buy may spend (default 50); sales and redemptions only turn PT back into USDG
38
+ // PRIORS_MAX_PT_TOTAL_USD most USDG pt_buy may spend in total while the server runs (default 200)
23
39
  import { readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, statSync, rmSync } from "node:fs";
24
40
  import { homedir } from "node:os";
25
41
  import { isAbsolute, join } from "node:path";
@@ -31,17 +47,21 @@ import { fetch as undiciFetch, Agent } from "undici";
31
47
  import { ethers } from "ethers";
32
48
  import { z } from "zod";
33
49
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
50
+ // PT-USDG: byte-for-byte copies of the repository's sdk/pt-usdg.mjs and sdk/pendle-pt.mjs (the calls the SDK, the
51
+ // hosted MCP and the gas gate's check share), with their deployments/pendle.4663.json and pt-usdg.4663.json beside
52
+ // this package's other records (scripts/test-packages.mjs fails on any drift).
53
+ import * as P from "./pt-usdg.mjs";
34
54
 
35
55
  // @priors/x402 when installed from npm; the sibling package in the monorepo otherwise.
36
56
  async function loadX402() {
37
57
  try {
38
- return { X: await import("@priors/x402"), C: await import("@priors/x402/credit") };
58
+ return { X: await import("@priors/x402"), C: await import("@priors/x402/credit"), S: await import("@priors/x402/savings"), A: await import("@priors/x402/autopay") };
39
59
  } catch (e) {
40
60
  if (e?.code !== "ERR_MODULE_NOT_FOUND" || !String(e.message).includes("@priors/x402")) throw e;
41
- return { X: await import("../../x402/index.mjs"), C: await import("../../x402/src/credit.mjs") };
61
+ return { X: await import("../../x402/index.mjs"), C: await import("../../x402/src/credit.mjs"), S: await import("../../x402/src/savings.mjs"), A: await import("../../x402/src/autopay.mjs") };
42
62
  }
43
63
  }
44
- const { X, C } = await loadX402();
64
+ const { X, C, S, A } = await loadX402();
45
65
 
46
66
  export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
47
67
  const ADDRESSES = JSON.parse(readFileSync(new URL("../deployments/4663.v2.json", import.meta.url), "utf8"));
@@ -179,7 +199,27 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
179
199
  // Per-call caps alone let a model (or a page steering it) spend the wallet a dollar at a time: these bound the process.
180
200
  const spendCap = envDollars(env, "PRIORS_MAX_SPEND_USD", 5);
181
201
  const borrowTotalCap = envDollars(env, "PRIORS_MAX_BORROW_TOTAL_USD", 25);
182
- const session = { spent: 0n, borrowed: 0n };
202
+ const maxSaveCeiling = envDollars(env, "PRIORS_MAX_SAVE_USD", 50);
203
+ const saveTotalCap = envDollars(env, "PRIORS_MAX_SAVE_TOTAL_USD", 200);
204
+ // Savings (Morpho). "off" stops new saving and the automatic top-ups, never the way out: savings and unsave then read
205
+ // the default vault. The setting's value is never echoed (a key pasted into it must not reach the model).
206
+ const savingsRaw = String(env.PRIORS_SAVINGS_VAULT ?? "").trim();
207
+ const savingsOff = /^(off|false|0|no|none)$/i.test(savingsRaw);
208
+ const savingsVault = savingsOff || savingsRaw === "" ? S.DEFAULT_SAVINGS_VAULT : savingsRaw;
209
+ const savingsProblem = ethers.isAddress(savingsVault) ? null
210
+ : looksLikeKey(savingsRaw) ? "PRIORS_SAVINGS_VAULT holds what looks like a private key, not a vault address: take it out of that variable and restart the server"
211
+ : "PRIORS_SAVINGS_VAULT is not a 0x address: fix it and restart the server";
212
+ const autoSavings = !savingsOff && !savingsProblem;
213
+ // Autopay: the agent's wallet approves AutoRepay and enrolls; the keeper repays in the
214
+ // window. The cap per loan is bounded by this server (stage 0: $25); pay_url keeps back what Autopay loans pull soon.
215
+ const maxAutopayCap = envDollars(env, "PRIORS_MAX_AUTOPAY_USD", 25);
216
+ const reserveOn = !/^(off|false|0|no)$/i.test(String(env.PRIORS_AUTOPAY_RESERVE ?? "").trim());
217
+ // PT-USDG (Pendle's principal token for USDG, maturing 2027-03-25): on unless PRIORS_PT=off. Buys are capped per call
218
+ // and per process like save; a sale or a redemption turns the wallet's own PT back into USDG and has no cap.
219
+ const ptOn = !/^(off|false|0|no|none)$/i.test(String(env.PRIORS_PT ?? "").trim());
220
+ const maxPtCeiling = envDollars(env, "PRIORS_MAX_PT_USD", 50);
221
+ const ptTotalCap = envDollars(env, "PRIORS_MAX_PT_TOTAL_USD", 200);
222
+ const session = { spent: 0n, borrowed: 0n, saved: 0n, ptBought: 0n };
183
223
  const allowLocal = env.PRIORS_ALLOW_LOCAL === "1";
184
224
  const lookup = deps.lookup || ((host) => dnsLookup(host, { all: true }));
185
225
  const sleep = deps.sleep; // undefined: the library's own
@@ -194,10 +234,21 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
194
234
  let moneyQueue = Promise.resolve();
195
235
  // The time budget counts from the call's arrival, not from its turn: a call queued behind a slow one must still answer
196
236
  // before the client gives up (a client timeout hides the "do not retry" answer and invites a retry).
237
+ // A savings withdrawal sent by a top-up that ran out of time, still in flight: every money call waits for it (at
238
+ // most until its own deadline), so none sends a second withdrawal or borrows for money that is on its way. The hold
239
+ // ends when the withdrawal settles, or after HOLD_MAX_MS whatever happens (a dropped transaction can't lock the queue).
240
+ let hold = null;
241
+ const HOLD_MAX_MS = deps.holdMaxMs ?? 120_000;
197
242
  const serial = (fn) => (args) => {
198
243
  const deadline = Date.now() + callBudgetMs;
199
- const run = moneyQueue.then(() => {
200
- if (Date.now() >= deadline - Math.min(1000, callBudgetMs / 10)) throw new ToolError("another payment call was still running and this one ran out of time before it could start. Nothing was signed or paid: try again.");
244
+ const margin = Math.min(1000, callBudgetMs / 10);
245
+ const run = moneyQueue.then(async () => {
246
+ if (hold) {
247
+ const h = hold;
248
+ await Promise.race([h, new Promise((ok) => setTimeout(ok, Math.max(0, deadline - margin - Date.now())).unref?.())]);
249
+ if (hold === h) throw new ToolError("a savings withdrawal from an earlier call is still in flight. Nothing was done: check the savings tool and try again in a minute.");
250
+ }
251
+ if (Date.now() >= deadline - margin) throw new ToolError("another payment call was still running and this one ran out of time before it could start. Nothing was signed or paid: try again.");
201
252
  return fn(args, deadline);
202
253
  });
203
254
  moneyQueue = run.catch(() => {});
@@ -228,7 +279,11 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
228
279
  for (const n of ["PAYMENT-RESPONSE", "X-PAYMENT-RESPONSE"]) { const h = res.headers.get(n); if (h) { try { return JSON.parse(Buffer.from(h, "base64").toString("utf8")); } catch (_) { /* not ours to read */ } } }
229
280
  return undefined;
230
281
  };
231
- const addresses = { ...ADDRESSES, ...(env.PRIORS_STOCK_VAULT ? { stockVault: env.PRIORS_STOCK_VAULT } : {}), ...(deps.addresses || {}) };
282
+ const addresses = { ...ADDRESSES, ...(env.PRIORS_STOCK_VAULT ? { stockVault: env.PRIORS_STOCK_VAULT } : {}),
283
+ ...(env.PRIORS_V5 ? { seatVaultV5: env.PRIORS_V5 } : {}), ...(env.PRIORS_V5_ROOT ? { seatVaultV5AgentId: env.PRIORS_V5_ROOT } : {}), ...(deps.addresses || {}) };
284
+ // SeatVaultV5, when known: both its address and its root's agent id, or neither (L-05: a borrow on its line refreshes it)
285
+ const v5 = addresses.seatVaultV5 && ethers.isAddress(String(addresses.seatVaultV5)) && /^[1-9][0-9]*$/.test(String(addresses.seatVaultV5AgentId ?? ""))
286
+ ? { v5: ethers.getAddress(String(addresses.seatVaultV5)), v5Root: BigInt(addresses.seatVaultV5AgentId) } : { v5: null, v5Root: null };
232
287
 
233
288
  // Everything returned passes through here. The key is cut with or without 0x, in any case, and with separators between
234
289
  // its digits (spaced, split over lines, dashed, JSON-quoted chunks). A private RPC URL is cut whole and by its parts
@@ -268,17 +323,20 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
268
323
  if (stateHome && !/^(off|none|false|0)$/i.test(stateHome) && !isAbsolute(stateHome)) throw new Error(`PRIORS_STATE_DIR must be an absolute path (or start with ~/), not "${stateRaw}"`);
269
324
  const stateDir = /^(off|none|false|0)$/i.test(stateRaw) ? null : stateHome || join(homedir(), ".local", "state", "priors-mcp");
270
325
  const stateFile = wallet && stateDir ? join(stateDir, `outstanding-${wallet.address.toLowerCase()}.json`) : null;
271
- // An entry is { paymentHeaders, validBefore, price (bigint), payTo }: only what this server wrote, never the merchant's
272
- // own requirement object (its fields are the merchant's to choose). On disk the price is a decimal string; each entry
273
- // is checked on its own, so one bad entry never costs the others. No reviver.
326
+ // An entry is { paymentHeaders, validBefore, price, payTo, borrowed, loanId }: only what this server wrote, never the
327
+ // merchant's requirement object (its fields are the merchant's to choose). On disk the amounts are decimal strings;
328
+ // each entry is checked on its own, so one bad entry never costs the others. No reviver.
274
329
  const live = (e, nowS) => e.validBefore + X.SKEW_SECONDS > nowS;
330
+ const DEC = /^\d{1,30}$/;
275
331
  function entryFrom(v) {
276
332
  if (!v || typeof v !== "object" || !v.paymentHeaders || typeof v.paymentHeaders !== "object") return null;
277
333
  const headers = {};
278
334
  for (const [k, x] of Object.entries(v.paymentHeaders)) { if (!/^(payment-signature|x-payment)$/i.test(k) || typeof x !== "string") return null; headers[k] = x; }
279
335
  const validBefore = Number(v.validBefore);
280
- if (Object.keys(headers).length === 0 || !Number.isSafeInteger(validBefore) || !/^\d{1,30}$/.test(String(v.price)) || !ethers.isAddress(String(v.payTo))) return null;
281
- return { paymentHeaders: headers, validBefore, price: BigInt(v.price), payTo: String(v.payTo) };
336
+ if (Object.keys(headers).length === 0 || !Number.isSafeInteger(validBefore) || !DEC.test(String(v.price)) || !ethers.isAddress(String(v.payTo))) return null;
337
+ const borrowed = DEC.test(String(v.borrowed ?? "0")) ? BigInt(v.borrowed ?? "0") : 0n;
338
+ const loanId = v.loanId !== null && v.loanId !== undefined && DEC.test(String(v.loanId)) ? BigInt(v.loanId) : null;
339
+ return { paymentHeaders: headers, validBefore, price: BigInt(v.price), payTo: String(v.payTo), borrowed, loanId };
282
340
  }
283
341
  function readState() {
284
342
  const m = new Map();
@@ -292,14 +350,15 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
292
350
  function writeState(m) {
293
351
  mkdirSync(stateDir, { recursive: true, mode: 0o700 });
294
352
  const tmp = `${stateFile}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
295
- writeFileSync(tmp, JSON.stringify(Object.fromEntries([...m].map(([k, e]) => [k, { paymentHeaders: e.paymentHeaders, validBefore: e.validBefore, price: String(e.price), payTo: e.payTo }]))), { mode: 0o600 });
353
+ const out = Object.fromEntries([...m].map(([k, e]) => [k, { paymentHeaders: e.paymentHeaders, validBefore: e.validBefore, price: String(e.price), payTo: e.payTo, borrowed: String(e.borrowed || 0n), loanId: e.loanId === null || e.loanId === undefined ? null : String(e.loanId) }]));
354
+ writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 });
296
355
  renameSync(tmp, stateFile);
297
356
  }
298
- // Several servers can share one wallet (two sessions, Claude Desktop and Claude Code): every change is a read-modify-write
299
- // of the file under an exclusive lock file, so no server rewrites the file from its own map and erases another's entries.
300
- // Best effort: a lock older than 10 s is stale, and after 2 s the write goes ahead without it. Waiting for it delays
301
- // this call only (an async wait, never a blocking one): the server keeps answering meanwhile. Inside one process the
302
- // lock is held only across synchronous code, so two calls of this server never contend.
357
+ // Several servers can share one wallet (two sessions, Claude Desktop and Claude Code): every change is a
358
+ // read-modify-write of the file under an exclusive lock file, so no server rewrites it from its own map and erases
359
+ // another's entries. Best effort: a lock older than 10 s is stale, and after 2 s the write goes ahead without it.
360
+ // Waiting for it delays this call only (an async wait, never a blocking one): the server keeps answering meanwhile.
361
+ // Inside one process the lock is held only across synchronous code, so two calls of this server never contend.
303
362
  async function locked(fn) {
304
363
  const lock = `${stateFile}.lock`;
305
364
  const giveUp = Date.now() + 2000;
@@ -309,13 +368,13 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
309
368
  if (e?.code === "ENOENT") { try { mkdirSync(stateDir, { recursive: true, mode: 0o700 }); continue; } catch (_) { break; } }
310
369
  if (e?.code !== "EEXIST") break;
311
370
  try { if (Date.now() - statSync(lock).mtimeMs > 10_000) { rmSync(lock, { force: true }); continue; } } catch (_) { continue; }
312
- if (Date.now() > giveUp) break; // never block a payment on the lock
371
+ if (Date.now() > giveUp) break;
313
372
  await new Promise((res) => setTimeout(res, 10));
314
373
  }
315
374
  }
316
375
  try { return fn(); } finally { if (held) rmSync(lock, { force: true }); }
317
376
  }
318
- /** Entries another server wrote since: merged in before any decision to sign. */
377
+ /** Entries another server of this wallet wrote since: merged in before any decision to sign. */
319
378
  function refresh() { if (stateFile) for (const [k, e] of readState()) if (!outstanding.has(k)) outstanding.set(k, e); }
320
379
  /** Kept on file before the payment leaves; a failure throws, and the payer then does not send it (own audit: a
321
380
  * record silently lost made a restart or another session sign again). */
@@ -342,7 +401,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
342
401
  if (stateFile) { try { await locked(() => { const m = readState(); if (same(m.get(key)) && m.delete(key)) writeState(m); }); } catch (_) { /* best effort */ } }
343
402
  }
344
403
  refresh();
345
- const contracts = C.creditContracts({ runner: provider, addresses: { pool: addresses.pool, lens: addresses.lens, usdg: addresses.usdg, registry: addresses.registry, stockVault: addresses.stockVault || null } });
404
+ const contracts = C.creditContracts({ runner: provider, addresses: { pool: addresses.pool, lens: addresses.lens, usdg: addresses.usdg, registry: addresses.registry, stockVault: addresses.stockVault || null, seatVaultV5: v5.v5, seatVaultV5AgentId: v5.v5Root } });
346
405
 
347
406
  // The chain, behind one facade (tests replace it).
348
407
  const credit = deps.credit || {
@@ -356,7 +415,69 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
356
415
  loanAgent: async (loanId) => (await contracts.pool.getLoan(loanId)).agentId,
357
416
  isController: (id, addr) => contracts.pool.isController(id, addr),
358
417
  agentsOf: (addr) => discoverAgents(addr),
418
+ loanDue: async (loanId) => { const l = await contracts.pool.getLoan(loanId); return Number(l.status) === 1 ? l.principal + l.fee : null; },
419
+ // savings: the vault is checked (a contract, asset = USDG) once, on first use
420
+ savingsOf: async (addr) => S.savingsOf(await savingsC(), addr),
421
+ savedOf: async (addr) => { const c = await savingsC(); const sh = await c.vault.balanceOf(addr); return sh === 0n ? 0n : c.vault.previewRedeem(sh); },
422
+ save: async (amount) => S.save(await savingsC(), wallet, amount),
423
+ unsave: async (o) => S.unsave(await savingsC(), wallet, o),
424
+ topUp: async (need, o) => S.topUpFromSavings(await savingsC(), wallet, need, o),
359
425
  };
426
+ let savingsCache = null;
427
+ function needSavings() { if (savingsProblem) throw new ToolError(savingsProblem); }
428
+ function savingsC() {
429
+ needSavings();
430
+ if (!savingsCache) savingsCache = S.savingsContracts({ runner: provider, vault: savingsVault, usdg: addresses.usdg }).catch((e) => { savingsCache = null; throw e; });
431
+ return savingsCache;
432
+ }
433
+ /** A read that may be slow (savedNote): at most `ms`. */
434
+ const withinTime = (p, ms) => Promise.race([p, new Promise((_, no) => setTimeout(() => no(new ToolError("timed out")), ms).unref?.())]);
435
+ const SAVINGS_WAIT_MS = 30_000;
436
+ /**
437
+ * A top-up bounded by the call's own deadline (at most 30 s). When time runs out it is stopped before it sends
438
+ * anything; if a withdrawal was already sent, the answer says so (`pending`: the payer then neither borrows nor
439
+ * signs) and the next money call waits for that withdrawal to settle.
440
+ */
441
+ function topUpWithin(need, deadline) {
442
+ const ac = new AbortController();
443
+ const o = { signal: ac.signal };
444
+ const ms = Math.max(1_000, Math.min(SAVINGS_WAIT_MS, (deadline ?? Infinity) - Date.now() - 2_000));
445
+ const p = credit.topUp(need, o);
446
+ return new Promise((resolve, reject) => {
447
+ const t = setTimeout(() => {
448
+ ac.abort();
449
+ if (o.sent || o.sending) {
450
+ const h = Promise.race([p.then(() => {}, () => {}), new Promise((ok) => setTimeout(ok, HOLD_MAX_MS).unref?.())]).then(() => { if (hold === h) hold = null; });
451
+ hold = h;
452
+ reject(Object.assign(new ToolError(`a savings withdrawal${o.sent ? ` (tx ${o.sent})` : ""} was sent and has not confirmed within ${Math.round(ms / 1000)} s; it may still land (the savings tool shows it)`), { pending: true }));
453
+ } else reject(new ToolError(`the savings step took longer than ${Math.round(ms / 1000)} s and was stopped before it sent anything`));
454
+ }, ms);
455
+ t.unref?.();
456
+ p.then((r) => { clearTimeout(t); resolve(r); }, (e) => { clearTimeout(t); reject(e); });
457
+ });
458
+ }
459
+ function savingsFailure(e) {
460
+ const m = explain(e);
461
+ if (e?.pending || e?.code === "UNCONFIRMED") return `${m}.`;
462
+ return `Could not check or use savings (${/insufficient funds|gas required exceeds|intrinsic gas|NO_GAS/i.test(m) ? "the wallet has no ETH to pay the withdrawal's gas" : m}); went on with the wallet's balance.`;
463
+ }
464
+ /** What a top-up did, as lines for the answer: taken out, still saved but stuck, or why it failed. */
465
+ function savingsLines(r, lines) {
466
+ if (!r) return;
467
+ if (r.error) { lines.push(savingsFailure(r.error)); return; }
468
+ if (r.withdrawn > 0n) lines.push(`Took ${usd(r.withdrawn)} out of savings first${r.inKind ? " (from the vault's other markets, in one transaction)" : ""}${r.hash ? ` (tx ${r.hash})` : ""}.`);
469
+ if (r.short > 0n && r.saved > r.withdrawn) lines.push(`${usd(r.saved - r.withdrawn)} is still saved but the vault could not pay it out right now (its liquidity is lent out); went on with the wallet's balance.`);
470
+ }
471
+ /** Before a repayment: take what the wallet is short of `need` (a value or a function) out of savings. Never fails the call. */
472
+ async function fromSavings(needOf, lines, deadline) {
473
+ if (!autoSavings || typeof credit.topUp !== "function") return;
474
+ try {
475
+ const need = typeof needOf === "function" ? await needOf() : needOf;
476
+ if (need === null || need === undefined) return;
477
+ if (wallet && typeof credit.balances === "function" && (await credit.balances(wallet.address)).usdg >= need) return; // covered: the vault is not touched
478
+ savingsLines(await topUpWithin(need, deadline), lines);
479
+ } catch (e) { lines.push(savingsFailure(e)); }
480
+ }
360
481
 
361
482
  // The registry is not enumerable: find identities minted to `addr` since the v2 deploy, keep what it owns. Only a mint
362
483
  // counts: anyone can transfer an identity with an open loan to this wallet, and `repay` would then pay it (own audit).
@@ -391,7 +512,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
391
512
 
392
513
  function needWallet(action) {
393
514
  if (keyProblem) throw new ToolError(`${action} needs a wallet, but ${keyProblem}. Fix PRIORS_KEY in the MCP server's environment.`);
394
- if (!wallet) throw new ToolError(`${action} moves money and needs a wallet: set PRIORS_KEY in the MCP server's environment (never pass a key as a tool argument or on the command line). Read-only tools (wallet_balance with an address, credit_status, stock_assets, stock_position, score_of, find_services) work without it.`);
515
+ if (!wallet) throw new ToolError(`${action} moves money and needs a wallet: set PRIORS_KEY in the MCP server's environment (never pass a key as a tool argument or on the command line). Read-only tools (wallet_balance and savings with an address, credit_status, stock_assets, stock_position, score_of, find_services) work without it.`);
395
516
  return wallet;
396
517
  }
397
518
  async function needController(id) {
@@ -402,6 +523,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
402
523
  const failure = (t) => ({ content: [{ type: "text", text: redact(t) }], isError: true });
403
524
  const explain = (e) => {
404
525
  if (e instanceof ToolError) return e.message;
526
+ if (e?.name === "SavingsError") return `${e.message} [${e.code}]`;
405
527
  if (e?.name === "PayError") return `${e.message} [${e.code}]`;
406
528
  if (e?.name === "ZodError") return `invalid arguments: ${e.message}`;
407
529
  const m = e?.shortMessage || e?.message || String(e);
@@ -409,8 +531,47 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
409
531
  return m;
410
532
  };
411
533
 
534
+ // ---- Autopay: the chain, behind one facade (tests replace it) ----
535
+ const autoRepayRaw = String(env.PRIORS_AUTOREPAY ?? addresses.autoRepay ?? "").trim();
536
+ const autoRepayProblem = autoRepayRaw && !ethers.isAddress(autoRepayRaw) ? (looksLikeKey(autoRepayRaw) ? "PRIORS_AUTOREPAY holds what looks like a private key, not an address: take it out of that variable and restart the server" : "PRIORS_AUTOREPAY is not a 0x address: fix it and restart the server") : null;
537
+ let autopayCache = null;
538
+ const autopayC = () => (autopayCache ||= A.autopayContracts({ runner: provider, address: autoRepayRaw, registry: addresses.registry, usdg: addresses.usdg, savingsVault: savingsProblem ? null : savingsVault, pool: addresses.pool }));
539
+ const autopay = deps.autopay !== undefined ? deps.autopay : autoRepayRaw && !autoRepayProblem ? {
540
+ status: (walletAddr, id) => A.autopayStatus(autopayC(), walletAddr, id),
541
+ on: (id, o) => A.autopayOn(autopayC(), wallet, id, o),
542
+ off: (id, o) => A.autopayOff(autopayC(), wallet, id, o),
543
+ } : null;
544
+ function needAutopay() {
545
+ if (autoRepayProblem) throw new ToolError(autoRepayProblem);
546
+ if (!autopay) throw new ToolError("Autopay isn't deployed yet: no AutoRepay address is known to this server (PRIORS_AUTOREPAY, or deployments/4663.v2.json `autoRepay` in a later version). Repay loans with the repay tool before their due date.");
547
+ return autopay;
548
+ }
549
+ /** What pay_url keeps back: what the wallet's Autopay plan pulls for loans whose window opens in the next 24 h. A
550
+ * failed read keeps nothing back (the payment goes on as before) and is never an error. */
551
+ async function autopayReserve() {
552
+ if (!reserveOn || !autopay || !wallet) return 0n;
553
+ try {
554
+ const id = await resolveAgent();
555
+ return A.autopayReserve(await withinTime(autopay.status(wallet.address, id), 10_000));
556
+ } catch (_) { return 0n; }
557
+ }
558
+ /** Autopay lines for credit_status: the wallet's plan, its budget, the next loan it pays, a shortfall. */
559
+ async function autopayLines(id) {
560
+ if (!autopay || !wallet) return [];
561
+ let st;
562
+ try { st = await withinTime(autopay.status(wallet.address, id), 10_000); } catch (e) { return [`Autopay: couldn't read it (${explain(e)}).`]; }
563
+ 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."];
564
+ 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."];
565
+ 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."];
566
+ 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.` : ""}`];
567
+ 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)}).`);
568
+ if (st.short) out.push(st.short.overCap ? `Loan #${st.short.loanId} is above the Autopay limit. Raise the limit with autopay_on, or repay it by hand.` : `This wallet won't cover its autopay of loan #${st.short.loanId}: ${usd(st.short.need)} is needed by then and ${usd(st.short.have)} can be pulled. Add USDG to this wallet, approve more with autopay_on, or repay by hand.`);
569
+ if (st.budget < st.plan.cap) out.push("The budget left is under one loan's limit: call autopay_on again to approve more.");
570
+ return out;
571
+ }
572
+
412
573
  const server = new McpServer({ name: "priors", version: VERSION }, {
413
- instructions: "Priors on Robinhood Chain (chain 4663): pay x402-priced URLs in USDG, and run the agent's Priors credit line. Tools that move money (pay_url, borrow, repay) act immediately on mainnet: state the amounts to the user and get their go-ahead first. Amounts are in US dollars of USDG.",
574
+ instructions: `Priors on Robinhood Chain (chain 4663): pay x402-priced URLs in USDG, and run the agent's Priors credit line. Tools that move money (pay_url, borrow, repay, save, unsave, autopay_on, autopay_off${ptOn ? ", pt_buy, pt_sell, pt_redeem" : ""}) act immediately on mainnet: state the amounts to the user and get their go-ahead first. Spare USDG can be saved in a Morpho vault (save); pay_url and repay take it back out when the wallet is short, before any borrowing.${ptOn ? ` PT-USDG (Pendle's principal token for USDG, redeemable 1:1 for USDG on ${P.PT_USDG.maturity.slice(0, 10)}) can be bought, sold and redeemed through Pendle's router (pt_quote, pt_position first).` : ""} Amounts are in US dollars of USDG.`,
414
575
  });
415
576
  const tool = (name, config, handler) => server.registerTool(name, config, async (args) => {
416
577
  try { return text(await handler(args || {})); } catch (e) { return failure(explain(e)); }
@@ -426,9 +587,10 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
426
587
  body: z.string().max(100_000).optional().describe("Request body (not for GET). Sent as application/json when it parses as JSON, else text/plain."),
427
588
  max_price_usd: z.number().positive().optional().describe("Most to pay for this one call, in US dollars. Default 0.10."),
428
589
  max_borrow_usd: z.number().nonnegative().optional().describe("Most to borrow from the Priors line if the wallet is short, in US dollars. Default 0: never borrow."),
590
+ use_savings: z.boolean().optional().describe("Default true: once the price is known, if the wallet holds less, first take the difference out of the agent's savings, before any borrowing."),
429
591
  },
430
592
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
431
- }, serial(async ({ url, method = "GET", body, max_price_usd, max_borrow_usd }, deadline) => {
593
+ }, serial(async ({ url, method = "GET", body, max_price_usd, max_borrow_usd, use_savings = true }, deadline) => {
432
594
  const signer = needWallet("pay_url");
433
595
  const u = await checkTarget(url);
434
596
  if (method === "GET" && body !== undefined) throw new ToolError("A GET request cannot carry a body: use POST (or another method) with body.");
@@ -466,43 +628,51 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
466
628
  throw new ToolError(`A payment of ${usd(unmatched.price)} to ${unmatched.payTo} for ${urlOnly} was signed earlier and kept without its request body (by an earlier version of this server, or for a call without a body), and the merchant may still settle it until ${until}. It cannot be told apart from this purchase, so nothing was signed: do NOT call pay_url again for this URL before ${until}; check wallet_balance.`);
467
629
  }
468
630
  let r;
469
- let signedPrice = null; // what the payer checked and signed, never a merchant field read again here
631
+ let signedPrice = null; // what the payer checked and signed; never a merchant field read again here
470
632
  if (prior) {
471
633
  // A payment for this purchase is already out and still cashable: send that same one, never a second.
472
634
  r = await X.createPayer({ signer, fetchImpl: payFetch, pendingRetries: 2, maxSleepMs: 10_000, timeoutMs: requestTimeoutMs, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), ...(sleep ? { sleep } : {}) }).resend(url, prior.paymentHeaders, init);
473
635
  r = { ...r, requirement: { payTo: prior.payTo }, paid: r.response.ok ? prior.price : 0n, borrowed: 0n, signed: prior, resent: true, ...(r.response.ok ? { settlement: settlementOf(r.response) } : {}) };
474
636
  signedPrice = prior.price;
475
637
  lines.push("No new payment was signed: the same signed payment was sent again.");
638
+ if (prior.borrowed > 0n) lines.push(`The first attempt at this purchase borrowed ${usd(prior.borrowed)}${prior.loanId !== null && prior.loanId !== undefined ? ` as loan #${prior.loanId}` : ""}: repay it with the repay tool.`);
476
639
  } else {
477
640
  if (session.spent + maxPrice > spendCap) throw new ToolError(`this would bring what pay_url may sign in this session to ${usd(session.spent + maxPrice)}, above ${usd(spendCap)} (PRIORS_MAX_SPEND_USD). ${usd(session.spent)} was signed so far; the user can raise the limit and restart the server.`);
478
641
  if (maxBorrow > 0n && session.borrowed + maxBorrow > borrowTotalCap) throw new ToolError(`this could bring what is borrowed in this session to ${usd(session.borrowed + maxBorrow)}, above ${usd(borrowTotalCap)} (PRIORS_MAX_BORROW_TOTAL_USD).`);
479
642
  let agentId;
480
643
  if (maxBorrow > 0n) { agentId = await resolveAgent(); await needController(agentId); }
481
- const payer = X.createPayer({ signer, maxPrice, maxBorrow, fetchImpl: payFetch, pendingRetries: 2, maxSleepMs: 10_000, timeoutMs: requestTimeoutMs, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), ...(sleep ? { sleep } : {}), ...(maxBorrow > 0n ? { pool: addresses.pool, agentId } : {}),
644
+ // The agent's own savings before a loan: once the 402 names the price, only what the wallet is short of.
645
+ const topUp = use_savings && autoSavings && typeof credit.topUp === "function" ? (need) => topUpWithin(need, deadline) : undefined;
646
+ const payer = X.createPayer({ signer, maxPrice, maxBorrow, fetchImpl: payFetch, pendingRetries: 2, maxSleepMs: 10_000, timeoutMs: requestTimeoutMs, signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())), ...(sleep ? { sleep } : {}), ...(maxBorrow > 0n ? { pool: addresses.pool, agentId, ...v5 } : {}), ...(topUp ? { topUp } : {}), ...(reserveOn && autopay ? { reserve: autopayReserve } : {}),
482
647
  // Recorded, then counted, when signed, at the price the payer checked and signed (a v1 requirement's `amount` is the
483
648
  // merchant's text). A record that cannot be kept throws, and the payer does not send the payment.
484
- onSigned: async (s) => { await record(purchase, { paymentHeaders: s.paymentHeaders, validBefore: s.validBefore, price: s.price, payTo: s.requirement.payTo }); signedPrice = s.price; session.spent += s.price; } });
649
+ onSigned: async (s) => { await record(purchase, { paymentHeaders: s.paymentHeaders, validBefore: s.validBefore, price: s.price, payTo: s.requirement.payTo, borrowed: s.borrowed || 0n, loanId: s.loanId ?? null }); signedPrice = s.price; session.spent += s.price; } });
485
650
  try { r = await payer.pay(url, init); } catch (e) {
651
+ // What savings did before the failure is part of the answer, whatever failed after.
652
+ const sv = []; savingsLines(e?.savings, sv);
653
+ const note = sv.length ? ` ${sv.join(" ")}` : "";
486
654
  // What the error carries was done: a loan taken and a payment signed are counted, whatever failed after.
487
655
  if (e?.borrowed > 0n) session.borrowed += e.borrowed;
488
656
  // A borrow sent whose answer was lost may have mined (GHSA-v9xj): counted above, and said, never "nothing done".
489
- if (e?.unconfirmed) throw new ToolError(`A borrow of ${usd(e.borrowed)} was sent${e.hash ? ` (tx ${e.hash})` : ""} and its answer was lost (${explain(e.cause ?? e)}), so it may have opened a loan: check credit_status, and repay it with the repay tool before its due date. Nothing was signed or paid.`);
657
+ if (e?.unconfirmed) throw new ToolError(`A borrow of ${usd(e.borrowed)} was sent${e.hash ? ` (tx ${e.hash})` : ""} and its answer was lost (${explain(e.cause ?? e)}), so it may have opened a loan: check credit_status, and repay it with the repay tool before its due date. Nothing was signed or paid.${note}`);
490
658
  if (e?.signed) {
491
- if (signedPrice === null) { signedPrice = maxPrice; session.spent += maxPrice; await recordSent(purchase, { ...e.signed, price: maxPrice, payTo: e.requirement.payTo }); } // not reached: onSigned ran
659
+ // onSigned ran before the payment left; should it not have, count the most this call could sign
660
+ if (signedPrice === null) { signedPrice = maxPrice; session.spent += maxPrice; await recordSent(purchase, { ...e.signed, price: maxPrice, payTo: e.requirement.payTo, borrowed: e.borrowed || 0n, loanId: e.loanId ?? null }); }
492
661
  const price = signedPrice;
493
662
  const until = when(e.signed.validBefore + X.SKEW_SECONDS);
494
- throw new ToolError(`A payment of ${usd(price)} to ${e.requirement.payTo} was signed, then the request failed (${explain(e)}). The merchant may still settle it until ${until}, so do NOT call pay_url again for this purchase (the same method, URL and body) before ${until}; check wallet_balance.${e.borrowed > 0n ? ` Borrowed ${usd(e.borrowed)}${e.loanId !== null ? ` as loan #${e.loanId}` : ""}: repay it with the repay tool.` : ""}`);
663
+ throw new ToolError(`A payment of ${usd(price)} to ${e.requirement.payTo} was signed, then the request failed (${explain(e)}). The merchant may still settle it until ${until}, so do NOT call pay_url again for this purchase (the same method, URL and body) before ${until}; check wallet_balance.${e.borrowed > 0n ? ` Borrowed ${usd(e.borrowed)}${e.loanId !== null ? ` as loan #${e.loanId}` : ""}: repay it with the repay tool.` : ""}${note}`);
495
664
  }
496
665
  const loan = e?.borrowed > 0n ? ` ${usd(e.borrowed)} was borrowed${e.loanId !== null ? ` as loan #${e.loanId}` : ""} before it failed: repay it with the repay tool.` : "";
497
666
  if (e?.code === "NOT_RECORDED" && e.cause?.code === "OTHER_SESSION") { outstanding.set(purchase, e.cause.prior); throw new ToolError(`Another session of this wallet signed a payment of ${usd(e.cause.prior.price)} for this purchase a moment ago, and it may still settle until ${when(e.cause.prior.validBefore + X.SKEW_SECONDS)}. Nothing was sent from this call and no payment of its own is out: calling pay_url again resends that same payment, never a new one.${loan}`); }
498
- if (e?.code === "NOT_RECORDED") throw new ToolError(`A payment was signed but could not be written to PRIORS_STATE_DIR (${explain(e.cause ?? e)}), so it was not sent and nothing can be settled. Fix that directory, or set PRIORS_STATE_DIR=off to keep payments in this process's memory only, then call again.${loan}`);
499
- if (e?.name === "TimeoutError" || e?.name === "AbortError") throw new ToolError(`${method} ${u.href} did not answer in time. Nothing was signed or paid.${loan}`);
500
- if (loan) throw new ToolError(`${explain(e)}.${loan}`);
667
+ if (e?.code === "NOT_RECORDED") throw new ToolError(`A payment was signed but could not be written to PRIORS_STATE_DIR (${explain(e.cause ?? e)}), so it was not sent and nothing can be settled. Fix that directory, or set PRIORS_STATE_DIR=off to keep payments in this process's memory only, then call again.${loan}${note}`);
668
+ if (e?.name === "TimeoutError" || e?.name === "AbortError") throw new ToolError(`${method} ${u.href} did not answer in time. Nothing was signed or paid.${loan}${note}`);
669
+ if (loan || note) throw new ToolError(`${explain(e)}.${loan}${note}`);
501
670
  throw e;
502
671
  }
503
- if (r.signed && signedPrice === null) { // not reached: onSigned counted and recorded it
672
+ savingsLines(r.savings, lines);
673
+ if (r.signed && signedPrice === null) { // onSigned counted and recorded it; should it not have, the most this call could sign
504
674
  signedPrice = maxPrice; session.spent += maxPrice;
505
- if (r.paid === 0n) await recordSent(purchase, { ...r.signed, price: maxPrice, payTo: r.requirement.payTo });
675
+ if (r.paid === 0n) await recordSent(purchase, { ...r.signed, price: maxPrice, payTo: r.requirement.payTo, borrowed: r.borrowed || 0n, loanId: r.loanId ?? null });
506
676
  }
507
677
  if (r.borrowed > 0n) { session.borrowed += r.borrowed; lines.push(`Borrowed ${usd(r.borrowed)} from the Priors line for agent #${agentId}${r.loanId !== null ? ` as loan #${r.loanId}` : ""}${r.dueAt ? `, due ${when(r.dueAt)}` : ""}. Repay it with the repay tool before then.`); }
508
678
  else if (r.requirement) lines.push("Nothing was borrowed.");
@@ -536,13 +706,13 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
536
706
  if (!addr) throw new ToolError("No wallet is configured (PRIORS_KEY is not set): pass an address to check.");
537
707
  if (!ethers.isAddress(addr)) throw new ToolError(`not an address: ${clean(addr, 80)}`);
538
708
  const b = await credit.balances(ethers.getAddress(addr));
539
- return `${b.address}${wallet && ethers.getAddress(addr) === wallet.address ? " (this server's wallet)" : ""} holds ${usd(b.usdg)} and ${ethers.formatEther(b.native)} ETH for gas on Robinhood Chain.`;
709
+ return `${b.address}${wallet && ethers.getAddress(addr) === wallet.address ? " (this server's wallet)" : ""} holds ${usd(b.usdg)} and ${ethers.formatEther(b.native)} ETH for gas on Robinhood Chain.${await savedNote(b.address)}`;
540
710
  });
541
711
 
542
712
  // ---- credit_status -------------------------------------------------------------------------------------------
543
713
  tool("credit_status", {
544
714
  title: "Priors credit line of an agent",
545
- description: "Show a Priors agent's credit line on Robinhood Chain: who backs it, the line, what is drawn and available, its repayment record, score and open loans with due dates. agent_id defaults to the configured wallet's agent. Read-only.",
715
+ description: "Show a Priors agent's credit line on Robinhood Chain: who backs it, the line, what is drawn and available, its repayment record, score and open loans with due dates, and (for the configured wallet) its Autopay: on or off, the limit per loan, the budget left, the next loan it repays and any shortfall. agent_id defaults to the configured wallet's agent. Read-only.",
546
716
  inputSchema: { agent_id: z.number().int().nonnegative().optional().describe("Priors (ERC-8004) agent id; default: the configured wallet's agent.") },
547
717
  annotations: { readOnlyHint: true, openWorldHint: true },
548
718
  }, async ({ agent_id }) => {
@@ -558,6 +728,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
558
728
  ];
559
729
  if (s.openLoans.length === 0) lines.push("Open loans: none.");
560
730
  for (const l of s.openLoans) lines.push(`Open loan #${l.loanId}: ${usd(l.principal)} + fee ${usd(l.fee)} = ${usd(l.due)}, due ${when(l.dueAt)}${Date.now() / 1000 > l.dueAt ? " (PAST DUE: repay now)" : ""}.`);
731
+ lines.push(...(await autopayLines(id)));
561
732
  return lines.join("\n");
562
733
  });
563
734
 
@@ -652,7 +823,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
652
823
  const id = await resolveAgent();
653
824
  await needController(id);
654
825
  const q = await credit.quote(id, amount, term);
655
- if (dry_run) return `Quote for agent #${id}: borrow ${usd(amount)} for ${days} days, fee ${usd(q.fee)}, ${usd(q.due)} due at the end. Nothing was borrowed.`;
826
+ if (dry_run) return `Quote for agent #${id}: borrow ${usd(amount)} for ${days} days, fee ${usd(q.fee)}, ${usd(q.due)} due at the end. Nothing was borrowed.${await savedNote(wallet.address)}`;
656
827
  let r;
657
828
  try { r = await credit.borrow(id, amount, term); } catch (e) {
658
829
  // sent, and its answer lost: it may have mined, so it is counted and said (GHSA-v9xj)
@@ -663,20 +834,23 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
663
834
  throw e;
664
835
  }
665
836
  session.borrowed += r.principal;
666
- return `Borrowed ${usd(r.principal)} for agent #${id}${r.loanId !== null ? ` as loan #${r.loanId}` : ""}: fee ${usd(r.fee)}, so ${usd(r.principal + r.fee)} is due${r.dueAt ? ` by ${when(r.dueAt)}` : ""}. The USDG is in ${wallet.address}. Tx ${r.hash}.`;
837
+ const v5Note = r.v5Refreshed ? " Its SeatVaultV5 line was refreshed first." : r.v5Noted ? ` SeatVaultV5 recorded this key now (tx ${r.v5Noted}): it can raise the line itself 24 hours from now.` : "";
838
+ return `Borrowed ${usd(r.principal)} for agent #${id}${r.loanId !== null ? ` as loan #${r.loanId}` : ""}: fee ${usd(r.fee)}, so ${usd(r.principal + r.fee)} is due${r.dueAt ? ` by ${when(r.dueAt)}` : ""}. The USDG is in ${wallet.address}. Tx ${r.hash}.${v5Note}`;
667
839
  }));
668
840
 
669
841
  // ---- repay ---------------------------------------------------------------------------------------------------
670
842
  tool("repay", {
671
843
  title: "Repay Priors loans",
672
- description: "Repay the agent's own Priors loans in full (principal + fee) from the configured wallet's USDG; a loan of another agent is refused. Give either loan_id for one loan, or all: true to repay every open loan, earliest due first, as far as the balance covers. Moves real money: state the amounts (credit_status lists them) to the user first.",
844
+ description: "Repay the agent's own Priors loans in full (principal + fee) from the configured wallet's USDG; a loan of another agent is refused. Give either loan_id for one loan, or all: true to repay every open loan, earliest due first, as far as the balance covers. Moves real money: state the amounts (credit_status lists them) to the user and get their go-ahead first.",
673
845
  inputSchema: {
674
846
  loan_id: z.number().int().nonnegative().optional().describe("The loan to repay."),
675
847
  all: z.boolean().optional().describe("true: repay every open loan of the agent, earliest due first."),
848
+ use_savings: z.boolean().optional().describe("Default true: if the wallet holds less than what is due, first take the difference out of the agent's savings."),
676
849
  },
677
850
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
678
- }, serial(async ({ loan_id, all }) => {
851
+ }, serial(async ({ loan_id, all, use_savings = true }, deadline) => {
679
852
  needWallet("repay");
853
+ const pre = [];
680
854
  if ((loan_id === undefined) === (all !== true)) throw new ToolError("Give exactly one of loan_id or all: true.");
681
855
  // Only the loans of an agent this wallet controls: the pool lets anyone repay any loan, and this wallet's USDG is
682
856
  // not for others. PRIORS_AGENT_ID alone is not proof: a stale or mistyped id would point at someone else's agent.
@@ -685,22 +859,271 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
685
859
  if (loan_id !== undefined) {
686
860
  const owner = BigInt(await credit.loanAgent(BigInt(loan_id)));
687
861
  if (owner !== id) throw new ToolError(`loan #${loan_id} belongs to agent #${owner}, not to agent #${id}. This tool only repays the configured agent's own loans.`);
688
- const r = await credit.repay(BigInt(loan_id));
689
- return `Repaid loan #${r.loanId} of agent #${r.agentId}: ${usd(r.paid)} (principal + fee). Tx ${r.hash}.`;
862
+ // the due is read inside the savings step: a failed read there never stops the repayment
863
+ if (use_savings) await fromSavings(() => credit.loanDue(BigInt(loan_id)), pre, deadline);
864
+ let r;
865
+ try { r = await credit.repay(BigInt(loan_id)); } catch (e) {
866
+ if (pre.length) throw new ToolError(`${pre.join(" ")} Then the repayment failed: ${explain(e)}`);
867
+ throw e;
868
+ }
869
+ return [...pre, `Repaid loan #${r.loanId} of agent #${r.agentId}: ${usd(r.paid)} (principal + fee). Tx ${r.hash}.`].join("\n");
690
870
  }
691
871
  const s = await credit.status(id);
692
872
  if (s.openLoans.length === 0) return `Agent #${id} has no open loan. Nothing was repaid.`;
873
+ if (use_savings) await fromSavings(s.openLoans.reduce((a, l) => a + l.due, 0n), pre, deadline);
693
874
  const done = [], left = [];
694
875
  let stop = null;
695
876
  for (const l of s.openLoans) {
696
877
  if (stop) { left.push(l); continue; }
697
878
  try { const r = await credit.repay(l.loanId); done.push(`loan #${r.loanId}: ${usd(r.paid)}, tx ${r.hash}`); } catch (e) { stop = explain(e); left.push(l); }
698
879
  }
699
- const out = [done.length ? `Repaid for agent #${id}:\n- ${done.join("\n- ")}` : `Nothing was repaid for agent #${id}.`];
880
+ const out = [...pre, done.length ? `Repaid for agent #${id}:\n- ${done.join("\n- ")}` : `Nothing was repaid for agent #${id}.`];
700
881
  if (left.length) out.push(`Still open: ${left.map((l) => `#${l.loanId} (${usd(l.due)} due ${when(l.dueAt)})`).join(", ")}.${stop ? ` Stopped because: ${stop}` : ""}`);
701
882
  return out.join("\n");
702
883
  }));
703
884
 
885
+ // ---- autopay_on / autopay_off ---------------------------------------------------------------------------------
886
+ // Autopay: the agent's own wallet approves AutoRepay for a budget (4 x the limit, never unlimited)
887
+ // and enrolls; Priors' keeper (or anyone) then repays each loan in the 6 hours before it is due, from this wallet,
888
+ // while it holds enough. Two plain transactions from the wallet (its own ETH pays the gas).
889
+ tool("autopay_on", {
890
+ title: "Turn on Autopay (repay loans on time from this wallet)",
891
+ description: "Turn on Autopay for the configured agent: this wallet approves AutoRepay for a USDG budget (4 x the limit per loan) and enrolls, so each Priors loan is repaid from this wallet (then its savings, if chosen) in the 6 hours before it is due, by Priors' keeper or anyone, with no call per loan, while the wallet holds enough. It makes an on-time repayment more likely; it is not a promise. Call it again to change the limit or approve more budget when it runs low. Moves real allowances: state the limit and the budget to the user and get their go-ahead once. Needs ETH for gas.",
892
+ inputSchema: {
893
+ cap_usd: z.number().positive().optional().describe("Most it repays per loan, in US dollars. Default: the line plus a 30-day fee, at most this server's ceiling (PRIORS_MAX_AUTOPAY_USD, default 25)."),
894
+ use_savings: z.boolean().optional().describe("Also take from the wallet's savings when its USDG is short. Default: on when the wallet has savings."),
895
+ late: z.boolean().optional().describe("Default true: also repay in the 3-day grace period after the due date (late, but no default)."),
896
+ budget_usd: z.number().positive().optional().describe("The allowance to approve, in US dollars. Default 4 x the limit."),
897
+ },
898
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
899
+ }, serial(async ({ cap_usd, use_savings, late = true, budget_usd }) => {
900
+ needWallet("autopay_on");
901
+ const ap = needAutopay();
902
+ const id = await resolveAgent();
903
+ await needController(id);
904
+ let cap = cap_usd !== undefined ? dollars(cap_usd, "cap_usd") : null;
905
+ if (cap === null) { const st = await credit.status(id); cap = A.defaultCap(st.line, maxAutopayCap); }
906
+ if (cap === 0n) throw new ToolError("cap_usd must be above zero");
907
+ if (cap > maxAutopayCap) throw new ToolError(`cap_usd ${X.formatUsdg(cap)} is above this server's Autopay ceiling of ${usd(maxAutopayCap)} (PRIORS_MAX_AUTOPAY_USD).`);
908
+ const budget = budget_usd !== undefined ? dollars(budget_usd, "budget_usd") : cap * A.BUDGET_LOANS;
909
+ if (budget < cap) throw new ToolError("budget_usd must cover at least one loan's limit.");
910
+ let useSavings = use_savings;
911
+ if (useSavings === undefined) { try { useSavings = autoSavings && (await credit.savedOf(wallet.address)) > 0n; } catch (_) { useSavings = false; } }
912
+ if (useSavings && savingsProblem) throw new ToolError(savingsProblem);
913
+ const r = await ap.on(id, { cap, useSavings, late, budget, ceiling: maxAutopayCap });
914
+ return `Autopay is on for agent #${id}: each loan up to ${usd(r.cap)} is repaid from ${wallet.address}${useSavings ? ", then its savings," : ""} in the 6 hours before it is due${late ? ", and in the grace period if it is late" : ""}, while the wallet holds enough. Budget approved: ${usd(r.budget)}; call autopay_on again to approve more when it runs low. credit_status shows the next loan it pays.${r.hashes.length ? ` Tx ${r.hashes.join(", ")}.` : ""}`;
915
+ }));
916
+
917
+ tool("autopay_off", {
918
+ title: "Turn off Autopay",
919
+ description: "Turn off Autopay for the configured agent: AutoRepay stops repaying its loans from this wallet at once. With clear_budget: true, also set this wallet's allowances to AutoRepay to 0. Loans must then be repaid with the repay tool before their due date.",
920
+ inputSchema: { clear_budget: z.boolean().optional().describe("true: also set the allowances to AutoRepay to 0.") },
921
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
922
+ }, serial(async ({ clear_budget = false }) => {
923
+ needWallet("autopay_off");
924
+ const ap = needAutopay();
925
+ const id = await resolveAgent();
926
+ const r = await ap.off(id, { clearBudget: clear_budget });
927
+ return `Autopay is off for agent #${id}: AutoRepay no longer repays its loans from ${wallet.address}${clear_budget ? ", and its allowances to AutoRepay are 0" : ""}. Repay open loans with the repay tool before their due date.${r.hashes.length ? ` Tx ${r.hashes.join(", ")}.` : ""}`;
928
+ }));
929
+
930
+ // ---- savings / save / unsave ----------------------------------------------------------------------------------
931
+ // Spare USDG kept in a Morpho vault (Steakhouse USDG by default) and taken back out when the agent pays or repays
932
+ // (pay_url and repay take from savings before borrowing). The agent's own money: Priors never holds it, and the
933
+ // vault's risk is the agent's. savings and unsave work even with PRIORS_SAVINGS_VAULT=off, so saved money can come out.
934
+ /** " It also has X saved ..." for an address, or "" (never fails the calling tool). */
935
+ async function savedNote(addr) {
936
+ if (savingsProblem || typeof credit.savedOf !== "function") return "";
937
+ try {
938
+ const v = await withinTime(credit.savedOf(addr), 5_000);
939
+ if (!(v > 0n)) return "";
940
+ if (!wallet || ethers.getAddress(addr) !== wallet.address) return ` It also has ${usd(v)} saved in the savings vault.`;
941
+ return ` It also has ${usd(v)} saved in the savings vault (the savings tool shows it; ${autoSavings ? "pay_url and repay use it before borrowing" : "savings are off on this server, so pay_url and repay don't use it; unsave takes it out"}).`;
942
+ } catch (_) { return ""; }
943
+ }
944
+ const RISK = "Savings earn the vault's rate, which moves with Morpho's markets; the vault's risk (its curator's markets and settings, a loss in a market) is the saver's, and Priors never holds the money.";
945
+ tool("savings", {
946
+ title: "Savings in the Morpho vault",
947
+ description: "Show how much USDG an address has saved in the savings vault (Steakhouse USDG on Morpho by default), what the vault can pay out to it right now, and the USDG in its wallet. Defaults to the configured wallet. Read-only.",
948
+ inputSchema: { address: z.string().optional().describe("0x address to check; default: the configured wallet.") },
949
+ annotations: { readOnlyHint: true, openWorldHint: true },
950
+ }, async ({ address }) => {
951
+ const addr = address ?? wallet?.address;
952
+ if (!addr) throw new ToolError("No wallet is configured (PRIORS_KEY is not set): pass an address to check.");
953
+ if (!ethers.isAddress(addr)) throw new ToolError(`not an address: ${clean(addr, 80)}`);
954
+ needSavings();
955
+ const s = await credit.savingsOf(ethers.getAddress(addr));
956
+ const reach = s.reachable ?? s.withdrawable;
957
+ const out = [`${s.owner} has ${usd(s.saved)} saved in vault ${s.vault} and ${usd(s.wallet)} in its wallet.`];
958
+ if (s.saved > 0n) {
959
+ out.push(reach >= s.saved ? "All of it can come out right now (unsave)." : `${usd(reach)} can come out right now${reach > s.withdrawable ? ` (${usd(s.withdrawable)} by a normal withdrawal, the rest from the vault's other markets; unsave does both)` : ""}; ${usd(s.saved - reach)} can't until the vault's markets have liquidity again.`);
960
+ }
961
+ if (savingsOff) out.push("Savings are off on this server: no new saving and no automatic top-ups; unsave still works.");
962
+ out.push(RISK);
963
+ return out.join(" ");
964
+ });
965
+
966
+ tool("save", {
967
+ title: "Save spare USDG in the Morpho vault",
968
+ description: "Move USDG from the configured wallet into the savings vault (Steakhouse USDG on Morpho by default), where it earns the vault's rate (which moves with its markets) until the agent needs it; pay_url and repay take it back out automatically when the wallet is short. Moves real money into a third-party vault, whose risk the agent carries: state the amount to the user and get their go-ahead first. Keep enough in the wallet for loans coming due and payments expected soon. Needs ETH for gas.",
969
+ inputSchema: { amount_usd: z.number().positive().describe("How much to save, in US dollars of USDG.") },
970
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
971
+ }, serial(async ({ amount_usd }) => {
972
+ needSavings();
973
+ if (savingsOff) throw new ToolError("Savings are off on this server (PRIORS_SAVINGS_VAULT=off): save is disabled. The savings and unsave tools still work.");
974
+ needWallet("save");
975
+ const amount = dollars(amount_usd, "amount_usd");
976
+ if (amount === 0n) throw new ToolError("amount_usd must be above zero");
977
+ if (amount > maxSaveCeiling) throw new ToolError(`amount_usd ${X.formatUsdg(amount)} is above this server's ceiling of ${usd(maxSaveCeiling)} per save (PRIORS_MAX_SAVE_USD).`);
978
+ if (session.saved + amount > saveTotalCap) throw new ToolError(`this would bring what save moved in this session to ${usd(session.saved + amount)}, above ${usd(saveTotalCap)} (PRIORS_MAX_SAVE_TOTAL_USD).`);
979
+ // Payments signed and not yet settled still need their USDG in the wallet: never save it away from under them.
980
+ const nowS = Math.floor(Date.now() / 1000);
981
+ refresh(); // another session's pending payments need their USDG too
982
+ const reserved = [...outstanding.values()].filter((v) => live(v, nowS)).reduce((a, v) => a + v.price, 0n);
983
+ if (reserved > 0n) {
984
+ const b = await credit.balances(wallet.address);
985
+ if (b.usdg < amount + reserved) throw new ToolError(`${usd(reserved)} of the wallet's USDG is held for signed payments that have not settled yet; at most ${usd(b.usdg > reserved ? b.usdg - reserved : 0n)} can be saved now.`);
986
+ }
987
+ let r;
988
+ try { r = await credit.save(amount); } catch (e) {
989
+ if (e?.code === "UNCONFIRMED") session.saved += amount; // it may have landed: counted, so a retry can't pass the cap
990
+ throw e;
991
+ }
992
+ session.saved += r.amount;
993
+ let after = "";
994
+ try { const s = await credit.savingsOf(wallet.address); after = ` Now ${usd(s.saved)} saved, ${usd(s.wallet)} left in the wallet.`; } catch (_) { after = " (The balances could not be read just now: check the savings tool.)"; }
995
+ return `Saved ${usd(r.amount)} in vault ${r.vault || savingsVault}. Tx ${r.hash}.${after}`;
996
+ }));
997
+
998
+ tool("unsave", {
999
+ title: "Take USDG out of savings",
1000
+ description: "Move USDG from the savings vault back into the configured wallet: amount_usd, or all: true for everything. When the vault's normal withdrawal cannot pay it all, it takes the rest from the vault's other markets in the same transaction (only where that costs no penalty). Refused before any transaction when even that cannot pay the amount. Moves the agent's own money back to its own wallet; state the amount to the user and get their go-ahead first. Needs ETH for gas.",
1001
+ inputSchema: {
1002
+ amount_usd: z.number().positive().optional().describe("How much to take out, in US dollars of USDG."),
1003
+ all: z.boolean().optional().describe("true: take everything out."),
1004
+ },
1005
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
1006
+ }, serial(async ({ amount_usd, all }) => {
1007
+ needSavings();
1008
+ needWallet("unsave");
1009
+ if ((amount_usd === undefined) === (all !== true)) throw new ToolError("Give exactly one of amount_usd or all: true.");
1010
+ const r = await credit.unsave(all ? { all: true } : { amount: dollars(amount_usd, "amount_usd") });
1011
+ let after = "";
1012
+ try { const s = await credit.savingsOf(wallet.address); after = ` Now ${usd(s.saved)} saved, ${usd(s.wallet)} in the wallet.`; } catch (_) { after = " (The balances could not be read just now: check the savings tool.)"; }
1013
+ return `Took ${usd(r.amount)} out of savings${r.inKind ? " (part of it from the vault's other markets, in one transaction)" : ""}. Tx ${r.hash}.${after}`;
1014
+ }));
1015
+
1016
+ // ---- PT-USDG: pt_quote / pt_position / pt_buy / pt_sell / pt_redeem ---------------------------------------------
1017
+ // Pendle's principal token for USDG (the markets of deployments/pendle.4663.json: the active one, maturing 2027-03-25
1018
+ // today, and any earlier one kept for redemption): bought with USDG, sold for USDG before maturity and redeemed 1:1 from it, through Pendle's router, with the calls sdk/pt-usdg.mjs builds (an approval of exactly the
1019
+ // trade's amount, then the router call paying the wallet itself, with a minimum out). Like borrow and save, this server
1020
+ // signs and sends them from the configured wallet (its own ETH pays the gas), one money call at a time; dry_run
1021
+ // returns the calls without sending. The chain, behind one facade (tests replace it).
1022
+ if (ptOn) {
1023
+ const pt = deps.pt || {
1024
+ quote: (o) => P.ptQuote(provider, o),
1025
+ position: (addr) => P.ptPosition(provider, addr),
1026
+ trade: (kind, o) => ({ buy: P.ptBuy, sell: P.ptSell, redeem: P.ptRedeem })[kind](provider, o),
1027
+ };
1028
+ const nf = (x) => Number(x).toLocaleString("en-US", { maximumFractionDigits: 6 });
1029
+ const capText = (u) => `${X.formatUsdg(u)} USDG`;
1030
+ const termsLine = (q) => (q.matured ? `PT-USDG matured on ${q.maturity.slice(0, 10)}: it redeems 1:1 for USDG.` : `PT-USDG trades at ${q.price.toFixed(6)} USDG and redeems 1:1 for USDG on ${q.maturity.slice(0, 10)} (${q.daysToMaturity} days): a fixed ${q.impliedApyText} a year to maturity, at the oracle's spot rate.`);
1031
+ // the wallet's PT of other listed markets (an earlier, redeem-only one): each with what to do with it
1032
+ const otherLines = (p) => (p.markets || []).filter((m) => m.token !== p.token && m.balance != null && m.balance > 0n).map((m) => (m.matured
1033
+ ? `It also holds ${nf(m.balanceText)} PT-USDG of the market that matured on ${m.maturity.slice(0, 10)} (token ${m.token}): it redeems 1:1 for USDG now (pt_redeem with market ${m.market}).`
1034
+ : `It also holds ${nf(m.balanceText)} PT-USDG of an earlier market (token ${m.token}): it redeems 1:1 for USDG from ${m.maturity.slice(0, 10)}.`));
1035
+ const listingLine = (l) => (!l ? "The stock vault's listing could not be read just now."
1036
+ : l.backsLines ? `The Priors stock vault takes PT-USDG behind an agent's line now, at up to ${l.ltvBps / 100}% of its value (all PT-USDG lines share one ${capText(l.lineCap)} cap): deposit it with the SDK's openPtLine(agentId, amount) or in Go mode's Backing tab.`
1037
+ : l.listed ? "The Priors stock vault lists PT-USDG but takes no new line on it now (disabled, or the shared cap is used up)."
1038
+ : `The Priors stock vault does not list PT-USDG yet. Once it does, PT-USDG backs an agent's line (planned: up to ${l.planned.ltvBps / 100}% of its value, one ${capText(BigInt(l.planned.lineCap))} cap for all PT-USDG lines).`);
1039
+ const slippage = z.number().int().min(0).max(500).optional().describe("Slippage margin in basis points under the quote, 0 to 500. Default 100 (1%), 10 for a redemption.");
1040
+ const ptAmount = z.union([z.number().positive().max(10_000_000), z.literal("all")]).describe('PT-USDG, e.g. 25.5, or "all" for the wallet\'s whole balance.');
1041
+ const dryRun = z.boolean().optional().describe("true: only quote and list the calls, send nothing.");
1042
+ const asked = (e) => new ToolError(clean(e?.shortMessage || e?.message || String(e), 300));
1043
+ const callsText = (b) => b.calls.map((c, i) => `${i + 1}. ${c.what}: to ${c.to}, data ${c.data}`).join("\n");
1044
+ const minLine = (b) => `The router call names a minimum out of ${nf(b.quote.minOutText)} ${b.quote.tokenOut} (the quote ${nf(b.quote.expectedOutText)}, less ${b.quote.slippageBps / 100}%): it reverts rather than fill worse. The quote is the oracle's spot rate, before the trade's own price impact.`;
1045
+
1046
+ tool("pt_quote", {
1047
+ title: "Quote a PT-USDG trade",
1048
+ description: "Quote buying PT-USDG (Pendle's principal token for USDG on Robinhood Chain, redeemable 1:1 for USDG at its maturity) 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 a buyer locks in. Read-only.",
1049
+ inputSchema: { side: z.enum(["buy", "sell", "redeem"]).describe("buy: USDG in, PT-USDG out. sell: PT-USDG in, USDG out, before maturity. redeem: PT-USDG in, USDG out 1:1, from maturity."), amount: z.number().positive().max(10_000_000).describe("USDG to spend (buy), or PT-USDG to sell or redeem."), slippage_bps: slippage },
1050
+ annotations: { readOnlyHint: true, openWorldHint: true },
1051
+ }, async ({ side, amount, slippage_bps }) => {
1052
+ let q;
1053
+ try { q = await pt.quote({ side, amount, slippageBps: slippage_bps }); } catch (e) { throw asked(e); }
1054
+ return [termsLine(q), `${nf(q.amountInText)} ${q.tokenIn} -> about ${nf(q.expectedOutText)} ${q.tokenOut} (at least ${nf(q.minOutText)} with a ${q.slippageBps / 100}% margin).`,
1055
+ side === "buy" ? `Held to maturity it pays ${nf(q.atMaturityText)} USDG, ${nf(q.fixedGainText)} USDG more than it costs.` : "",
1056
+ `pt_${side} ${side === "buy" ? `spends it from this server's wallet (at most ${capText(maxPtCeiling)} a call, PRIORS_MAX_PT_USD)` : "sends it from this server's wallet"}; dry_run: true lists the calls first.`].filter(Boolean).join("\n");
1057
+ });
1058
+
1059
+ tool("pt_position", {
1060
+ title: "A wallet's PT-USDG",
1061
+ description: "Show a wallet's PT-USDG on Robinhood Chain: its balance, what it is worth now at the oracle's spot rate, what it pays at maturity, the days left and the fixed APY to maturity; and whether the Priors stock vault takes PT-USDG behind an agent's line. Defaults to the configured wallet; any address works without a key. Read-only.",
1062
+ inputSchema: { address: z.string().optional().describe("0x address to check; default: the configured wallet.") },
1063
+ annotations: { readOnlyHint: true, openWorldHint: true },
1064
+ }, async ({ address }) => {
1065
+ const addr = address ?? wallet?.address;
1066
+ if (!addr) throw new ToolError("No wallet is configured (PRIORS_KEY is not set): pass an address to check.");
1067
+ if (!ethers.isAddress(addr)) throw new ToolError(`not an address: ${clean(addr, 80)}`);
1068
+ let p;
1069
+ try { p = await pt.position(ethers.getAddress(addr)); } catch (e) { throw asked(e); }
1070
+ return [`${p.account}${wallet && p.account === wallet.address ? " (this server's wallet)" : ""} holds ${nf(p.balanceText)} PT-USDG${p.balance > 0n ? `, worth ${nf(p.valueText)} USDG now and ${nf(p.atMaturityText)} USDG at maturity` : ""}.`, termsLine(p), ...otherLines(p), listingLine(p.listing)].join("\n");
1071
+ });
1072
+
1073
+ /** One trade from the configured wallet: the SDK's calls, sent in order (each simulated, then waited for). */
1074
+ async function ptTrade(kind, amount, slippage_bps, dry_run, market) {
1075
+ const signer = needWallet(`pt_${kind}`);
1076
+ let units = null;
1077
+ if (kind === "buy") {
1078
+ units = dollars(amount, "amount_usdg");
1079
+ if (units === 0n) throw new ToolError("amount_usdg must be above zero");
1080
+ if (units > maxPtCeiling) throw new ToolError(`amount_usdg ${X.formatUsdg(units)} is above this server's ceiling of ${usd(maxPtCeiling)} per buy (PRIORS_MAX_PT_USD).`);
1081
+ if (!dry_run && session.ptBought + units > ptTotalCap) throw new ToolError(`this would bring what pt_buy spent in this session to ${usd(session.ptBought + units)}, above ${usd(ptTotalCap)} (PRIORS_MAX_PT_TOTAL_USD).`);
1082
+ }
1083
+ const o = { account: signer.address, amount: units ?? amount, slippageBps: slippage_bps, ...(market ? { market } : {}) };
1084
+ if (dry_run) {
1085
+ let b;
1086
+ try { b = await pt.trade(kind, o); } catch (e) { throw asked(e); }
1087
+ return [termsLine(b.quote), `Nothing was sent. From ${b.account}, ${b.calls.length} call${b.calls.length > 1 ? "s" : ""} in order:`, callsText(b), minLine(b), ...b.warnings.map((w) => `Note: ${w}.`)].join("\n");
1088
+ }
1089
+ // what left the wallet is counted even when the answer is lost: a send that started may have landed
1090
+ const sent = [];
1091
+ const counting = { getAddress: async () => signer.address, sendTransaction: async (tx) => { const r = await signer.sendTransaction(tx); sent.push(r.hash); return r; } };
1092
+ if (units !== null) session.ptBought += units;
1093
+ let r;
1094
+ try { r = await pt.trade(kind, { ...o, wallet: counting }); } catch (e) {
1095
+ if (sent.length === 0 && units !== null) session.ptBought -= units;
1096
+ if (sent.length) throw new ToolError(`${sent.length} transaction${sent.length > 1 ? "s were" : " was"} sent (${sent.join(", ")}), then: ${clean(e?.shortMessage || e?.message || String(e), 300)}. Check pt_position and wallet_balance before trying again.`);
1097
+ throw asked(e);
1098
+ }
1099
+ const done = kind === "buy" ? `Bought about ${nf(r.quote.expectedOutText)} PT-USDG (at least ${nf(r.quote.minOutText)}) with ${usd(units)}`
1100
+ : kind === "sell" ? `Sold ${nf(r.quote.amountInText)} PT-USDG for about ${nf(r.quote.expectedOutText)} USDG (at least ${nf(r.quote.minOutText)})`
1101
+ : `Redeemed ${nf(r.quote.amountInText)} PT-USDG for ${nf(r.quote.expectedOutText)} USDG`;
1102
+ return [`${done}, from and to ${r.account}. Tx ${r.hashes.join(", ")}.`, kind === "buy" ? termsLine(r.quote) : "", ...r.warnings.filter((w) => !/sponsorship/.test(w)).map((w) => `Note: ${w}.`)].filter(Boolean).join("\n");
1103
+ }
1104
+
1105
+ tool("pt_buy", {
1106
+ title: "Buy PT-USDG with USDG",
1107
+ 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.`,
1108
+ inputSchema: { amount_usdg: z.number().positive().describe("USDG to spend, in US dollars (required, no default)."), slippage_bps: slippage, dry_run: dryRun },
1109
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
1110
+ }, serial(async ({ amount_usdg, slippage_bps, dry_run }) => ptTrade("buy", amount_usdg, slippage_bps, dry_run)));
1111
+
1112
+ tool("pt_sell", {
1113
+ title: "Sell PT-USDG for USDG",
1114
+ 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.",
1115
+ inputSchema: { amount_pt: ptAmount, slippage_bps: slippage, dry_run: dryRun },
1116
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
1117
+ }, serial(async ({ amount_pt, slippage_bps, dry_run }) => ptTrade("sell", amount_pt, slippage_bps, dry_run)));
1118
+
1119
+ tool("pt_redeem", {
1120
+ title: "Redeem PT-USDG for USDG",
1121
+ description: `Redeem the configured wallet's PT-USDG for USDG 1:1, from its maturity (${P.PT_USDG.maturity.slice(0, 10)}) on, through Pendle's router: an approval of exactly that PT-USDG, then the redemption to this wallet. By default the PT of the oldest matured market the wallet holds (an earlier market's included); \`market\` names one (pt_position lists them). Before maturity it says to sell instead. State the amount to the user and get their go-ahead first; dry_run: true lists the calls without sending. Needs ETH for gas.`,
1122
+ inputSchema: { amount_pt: ptAmount, slippage_bps: slippage, dry_run: dryRun, market: z.string().regex(/^0x[0-9a-fA-F]{40}$/).optional().describe("Optional: the market (or its PT) to redeem, as pt_position lists it. Default: the oldest matured market the wallet holds PT of.") },
1123
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
1124
+ }, serial(async ({ amount_pt, slippage_bps, dry_run, market }) => ptTrade("redeem", amount_pt, slippage_bps, dry_run, market)));
1125
+ }
1126
+
704
1127
  // ---- find_services -------------------------------------------------------------------------------------------
705
1128
  tool("find_services", {
706
1129
  title: "Find services that accept USDG",