@priors/mcp 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,12 +21,12 @@ repaying.
21
21
 
22
22
  | tool | what it does | needs the key |
23
23
  |---|---|---|
24
- | `pay_url(url, method?, body?, max_price_usd?, max_borrow_usd?)` | fetch an https URL, pay its x402 402 in USDG if the price is ≤ `max_price_usd` (default **$0.10**); borrows the gap only if `max_borrow_usd` is given. Refuses private and local addresses, never follows a redirect, answers within 45 s, and never signs a second payment for a purchase that is still pending (a new call resends the same one) | yes |
24
+ | `pay_url(url, method?, body?, max_price_usd?, max_borrow_usd?)` | fetch an https URL, pay its x402 402 in USDG if the price is ≤ `max_price_usd` (default **$0.10**); borrows the gap only if `max_borrow_usd` is given. Refuses private and local addresses, never follows a redirect, answers within 45 s, and never signs a second payment for a purchase (the same method, URL and body) that is still pending, until its validBefore plus 60 s (a new call resends the same one, also after a restart, in a new session or from another session of the same wallet: see `PRIORS_STATE_DIR`) | yes |
25
25
  | `wallet_balance(address?)` | USDG and gas ETH of the wallet (or any address) | no (with `address`) |
26
26
  | `credit_status(agent_id?)` | line, drawn, available, backer, record, score, open loans and due dates; on a stock line, the stock tokens behind it, and `available` capped by what the stock vault lets it draw | no (with `agent_id`) |
27
27
  | `stock_assets(symbol?)` | the stock tokens the Priors stock vault accepts: live Chainlink price, whether it lends against each now (or why not: a sharp price move, a multiplier change, a paused or blocked token), loan-to-value | no |
28
28
  | `stock_position(agent_id?)` | the stock tokens behind an agent's stock line: amount, what the vault values them at, loan-to-value, what the line can draw now, any lending hold | no (with `agent_id`) |
29
- | `borrow(amount_usd, days, dry_run?)` | borrow USDG from the line into the wallet; both amounts required; `dry_run` quotes the fee | yes |
29
+ | `borrow(amount_usd, days, dry_run?)` | borrow USDG from the line into the wallet; both amounts required; `dry_run` quotes the fee. A borrow sent whose answer is lost is counted and said to be possibly open (check `credit_status`) | yes |
30
30
  | `repay(loan_id? \| all)` | repay one of the agent's own loans, or all of them earliest due first; another agent's loan is refused | yes |
31
31
  | `score_of(agent_id)` | any agent's on-chain score (0 to 1000) and repayment record, plus its Priors Score v2 and trust rung when published | no |
32
32
  | `find_services(query?)` | services registered with the Priors facilitator that accept USDG (`GET /merchants`), each marked as approved by Priors or self-registered and not reviewed | no |
@@ -50,10 +50,11 @@ dedicated agent wallet holding only what the agent may spend.
50
50
  | `PRIORS_MAX_PRICE_USD` | `1.00` | ceiling on what `pay_url` may be told to pay per call |
51
51
  | `PRIORS_MAX_BORROW_USD` | `25` | ceiling on `borrow` and on `pay_url`'s `max_borrow_usd` |
52
52
  | `PRIORS_MAX_SPEND_USD` | `5` | most `pay_url` may sign in total while the server runs (counted when signed) |
53
- | `PRIORS_MAX_BORROW_TOTAL_USD` | `25` | most `borrow` and `pay_url` may borrow in total while the server runs |
53
+ | `PRIORS_MAX_BORROW_TOTAL_USD` | `25` | most `borrow` and `pay_url` may borrow in total while the server runs (a borrow sent whose answer was lost counts: it may have opened a loan) |
54
54
  | `PRIORS_ALLOW_LOCAL` | off | `1` lets `pay_url` reach `http://localhost` and private addresses (local testing only) |
55
55
  | `PRIORS_SCORE_V2` | `https://priors.trade/api/score-v2` | where `score_of` reads Priors Score v2; `off` shows the on-chain score only |
56
56
  | `PRIORS_STOCK_VAULT` | the bundled deployments file's `stockVault` | the stock vault the stock tools and `credit_status` read |
57
+ | `PRIORS_STATE_DIR` | `~/.local/state/priors-mcp` | where the payments signed and not yet settled are kept (one owner-only file per wallet, never the key, with a short-lived `.lock` beside it while it is written), so a restart, a new session or another session of the same wallet resends them instead of signing again; `off` keeps them in memory only |
57
58
 
58
59
  Contract addresses (pool, lens, registry, USDG) come from `deployments/4663.v2.json`, bundled in the package, and the
59
60
  accepted stock tokens from `deployments/stock-assets.4663.json`. The stock vault's address (live since 2026-09-28)
@@ -68,7 +69,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
68
69
  "mcpServers": {
69
70
  "priors": {
70
71
  "command": "npx",
71
- "args": ["-y", "@priors/mcp@0.2.2"],
72
+ "args": ["-y", "@priors/mcp@0.2.4"],
72
73
  "env": {
73
74
  "PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
74
75
  "PRIORS_AGENT_ID": "1234"
@@ -90,7 +91,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
90
91
  "mcpServers": {
91
92
  "priors": {
92
93
  "command": "npx",
93
- "args": ["-y", "@priors/mcp@0.2.2"],
94
+ "args": ["-y", "@priors/mcp@0.2.4"],
94
95
  "env": {
95
96
  "PRIORS_KEY": "${PRIORS_KEY}",
96
97
  "PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
@@ -100,7 +101,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
100
101
  }
101
102
  ```
102
103
 
103
- or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.2.2`
104
+ or, for your user only: `claude mcp add priors --scope user -e PRIORS_KEY="$PRIORS_KEY" -- npx -y @priors/mcp@0.2.4`
104
105
  (the key is expanded by your shell from the environment; do not paste it on the command line).
105
106
 
106
107
  ## Try it
@@ -9,7 +9,7 @@ if (argv.some((a) => /(^|[^0-9a-fA-F])(0x)?[0-9a-fA-F]{64}($|[^0-9a-fA-F])/.test
9
9
  process.exit(2);
10
10
  }
11
11
  if (argv.includes("--help") || argv.includes("-h")) {
12
- process.stderr.write("priors-mcp: MCP server (stdio) for Priors on Robinhood Chain.\nenv: PRIORS_KEY (wallet key, optional), PRIORS_RPC, PRIORS_AGENT_ID, PRIORS_FACILITATOR, PRIORS_MAX_PRICE_USD, PRIORS_MAX_BORROW_USD, PRIORS_MAX_SPEND_USD, PRIORS_MAX_BORROW_TOTAL_USD, PRIORS_ALLOW_LOCAL, PRIORS_STOCK_VAULT, PRIORS_SCORE_V2\nSee the README for the Claude Desktop / Claude Code config.\n");
12
+ process.stderr.write("priors-mcp: MCP server (stdio) for Priors on Robinhood Chain.\nenv: PRIORS_KEY (wallet key, optional), PRIORS_RPC, PRIORS_AGENT_ID, PRIORS_FACILITATOR, PRIORS_MAX_PRICE_USD, PRIORS_MAX_BORROW_USD, PRIORS_MAX_SPEND_USD, PRIORS_MAX_BORROW_TOTAL_USD, PRIORS_ALLOW_LOCAL, PRIORS_STOCK_VAULT, PRIORS_SCORE_V2, PRIORS_STATE_DIR\nSee the README for the Claude Desktop / Claude Code config.\n");
13
13
  process.exit(0);
14
14
  }
15
15
  if (argv.length > 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@priors/mcp",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "private": false,
5
5
  "description": "MCP server for Priors on Robinhood Chain: pay x402 URLs in USDG, read balances, credit lines and scores, borrow and repay. Key from PRIORS_KEY only.",
6
6
  "type": "module",
@@ -42,7 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@modelcontextprotocol/sdk": "^1.30.1",
45
- "@priors/x402": "0.2.2",
45
+ "@priors/x402": "0.2.4",
46
46
  "ethers": "^6.13.4",
47
47
  "undici": "6.29.0",
48
48
  "zod": "^4.6.5"
package/src/server.mjs CHANGED
@@ -18,7 +18,11 @@
18
18
  // PRIORS_ALLOW_LOCAL "1": pay_url may reach http://localhost and private addresses (testing only)
19
19
  // PRIORS_SCORE_V2 where score_of reads Priors Score v2 (default https://priors.trade/api/score-v2; "off": v1 only)
20
20
  // PRIORS_STOCK_VAULT the stock vault's address (default: deployments/4663.v2.json `stockVault`)
21
- import { readFileSync } from "node:fs";
21
+ // PRIORS_STATE_DIR where signed, unsettled payments are kept across restarts and shared by every session of the
22
+ // wallet (default ~/.local/state/priors-mcp; "off": memory only)
23
+ import { readFileSync, writeFileSync, mkdirSync, renameSync, openSync, closeSync, statSync, rmSync } from "node:fs";
24
+ import { homedir } from "node:os";
25
+ import { join } from "node:path";
22
26
  import { randomBytes } from "node:crypto";
23
27
  import { lookup as dnsLookup } from "node:dns/promises";
24
28
  import { isIP } from "node:net";
@@ -124,7 +128,11 @@ const when = (t) => new Date(Number(t) * 1000).toISOString().replace(".000Z", "Z
124
128
  const tokens = (units, decimals) => (Number.isInteger(decimals) ? ethers.formatUnits(units, decimals).replace(/\.0$/, "") : String(units));
125
129
  /** One line for the stock collateral behind a line (creditStatus.collateral, or a stockPosition). */
126
130
  export function collateralText(c, symbol = c.symbol, decimals = c.decimals) {
127
- const what = symbol ? `${tokens(c.amount, decimals)} ${symbol}` : `${c.amount} base units of ${c.token}`;
131
+ const held = symbol ? `${tokens(c.amount, decimals)} ${symbol}` : `${c.amount} base units of ${c.token}`;
132
+ // after an issuer burn from the vault the position is paid its share (`payout`), which `value` prices
133
+ const what = c.payout !== undefined && c.payout !== null
134
+ ? `${symbol ? `${tokens(c.payout, decimals)} ${symbol}` : `${c.payout} base units of ${c.token}`}, of ${symbol ? tokens(c.amount, decimals) : c.amount} deposited: an issuer burn left the vault short,`
135
+ : held;
128
136
  return `Backed by ${what}${c.value !== null ? ` worth ${usd(c.value)} to the vault` : " (not priced for new loans right now)"}, at ${Number(c.ltvBps) / 100}% loan-to-value: ${usd(c.borrowRoom)} can be drawn now.`
129
137
  + (c.hold ? ` New loans wait: ${c.holdReason || "a lending hold"}.` : "") + (c.closing ? " Closing: no new loans." : "");
130
138
  }
@@ -169,11 +177,12 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
169
177
  const sleep = deps.sleep; // undefined: the library's own
170
178
  const requestTimeoutMs = deps.requestTimeoutMs ?? 15_000;
171
179
  const callBudgetMs = deps.callBudgetMs ?? 45_000; // under the MCP clients' usual 60 s request timeout
172
- // Payments signed and not (yet) counted as paid, by "METHOD url": until validBefore the merchant can still cash
173
- // them, so another pay_url for the same purchase resends that payment instead of signing a second one.
180
+ // Payments signed and not (yet) counted as paid, by purchase (X.purchaseKey: the method, the URL without its fragment,
181
+ // and the body): until validBefore the merchant can still cash them, so another pay_url for the same purchase resends
182
+ // that payment instead of signing a second one.
174
183
  const outstanding = new Map();
175
184
  // One money call at a time (pay_url, borrow, repay): MCP clients may send tool calls concurrently, and each check
176
- // above (an outstanding payment for this URL, the session totals) must see the previous call's result (Codex review).
185
+ // above (an outstanding payment for this purchase, the session totals) must see the previous call's result (Codex review).
177
186
  let moneyQueue = Promise.resolve();
178
187
  // The time budget counts from the call's arrival, not from its turn: a call queued behind a slow one must still answer
179
188
  // before the client gives up (a client timeout hides the "do not retry" answer and invites a retry).
@@ -240,6 +249,70 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
240
249
  // answers a batch that size with HTTP 429, which ethers retries until its 5-minute timeout (stock_assets' ~140 reads).
241
250
  const provider = deps.provider || new ethers.JsonRpcProvider(rpc, ethers.Network.from(X.robinhood.chainId), { staticNetwork: true, cacheTimeout: -1, batchMaxCount: 1 });
242
251
  const wallet = key ? new ethers.Wallet(key, provider) : null;
252
+ // The payments this wallet signed and has not seen settle outlive the process (a restart, or the client closing its
253
+ // session, starts a new one): one file per wallet under PRIORS_STATE_DIR (default ~/.local/state/priors-mcp; "off"
254
+ // disables it), owner-only. It holds signed authorizations, each payable only to the merchant it was sent to, never the key.
255
+ const stateRaw = String(env.PRIORS_STATE_DIR ?? "").trim();
256
+ const stateDir = /^(off|none|false|0)$/i.test(stateRaw) ? null : stateRaw || join(homedir(), ".local", "state", "priors-mcp");
257
+ const stateFile = wallet && stateDir ? join(stateDir, `outstanding-${wallet.address.toLowerCase()}.json`) : null;
258
+ // An entry is { paymentHeaders, validBefore, price (bigint), payTo }: only what this server wrote, never the merchant's
259
+ // own requirement object (its fields are the merchant's to choose). On disk the price is a decimal string; each entry
260
+ // is checked on its own, so one bad entry never costs the others. No reviver.
261
+ const live = (e, nowS) => e.validBefore + X.SKEW_SECONDS > nowS;
262
+ function entryFrom(v) {
263
+ if (!v || typeof v !== "object" || !v.paymentHeaders || typeof v.paymentHeaders !== "object") return null;
264
+ const headers = {};
265
+ 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; }
266
+ const validBefore = Number(v.validBefore);
267
+ if (Object.keys(headers).length === 0 || !Number.isSafeInteger(validBefore) || !/^\d{1,30}$/.test(String(v.price)) || !ethers.isAddress(String(v.payTo))) return null;
268
+ return { paymentHeaders: headers, validBefore, price: BigInt(v.price), payTo: String(v.payTo) };
269
+ }
270
+ function readState() {
271
+ const m = new Map();
272
+ try {
273
+ const obj = JSON.parse(readFileSync(stateFile, "utf8"));
274
+ const nowS = Math.floor(Date.now() / 1000);
275
+ for (const [k, v] of Object.entries(obj && typeof obj === "object" ? obj : {})) { const e = entryFrom(v); if (e && live(e, nowS)) m.set(k, e); }
276
+ } catch (_) { /* no file yet, or unreadable */ }
277
+ return m;
278
+ }
279
+ function writeState(m) {
280
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
281
+ const tmp = `${stateFile}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
282
+ 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 });
283
+ renameSync(tmp, stateFile);
284
+ }
285
+ // Several servers can share one wallet (two sessions, Claude Desktop and Claude Code): every change is a read-modify-write
286
+ // of the file under an exclusive lock file, so no server rewrites the file from its own map and erases another's entries.
287
+ // Best effort: a lock older than 10 s is stale, and after 2 s the write goes ahead without it. Waiting for it delays
288
+ // this call only (an async wait, never a blocking one): the server keeps answering meanwhile. Inside one process the
289
+ // lock is held only across synchronous code, so two calls of this server never contend.
290
+ async function locked(fn) {
291
+ const lock = `${stateFile}.lock`;
292
+ const giveUp = Date.now() + 2000;
293
+ let held = false;
294
+ for (;;) {
295
+ try { closeSync(openSync(lock, "wx", 0o600)); held = true; break; } catch (e) {
296
+ if (e?.code === "ENOENT") { try { mkdirSync(stateDir, { recursive: true, mode: 0o700 }); continue; } catch (_) { break; } }
297
+ if (e?.code !== "EEXIST") break;
298
+ try { if (Date.now() - statSync(lock).mtimeMs > 10_000) { rmSync(lock, { force: true }); continue; } } catch (_) { continue; }
299
+ if (Date.now() > giveUp) break; // never block a payment on the lock
300
+ await new Promise((res) => setTimeout(res, 10));
301
+ }
302
+ }
303
+ try { return fn(); } finally { if (held) rmSync(lock, { force: true }); }
304
+ }
305
+ /** Entries another server wrote since: merged in before any decision to sign. */
306
+ function refresh() { if (stateFile) for (const [k, e] of readState()) if (!outstanding.has(k)) outstanding.set(k, e); }
307
+ async function record(key, e) {
308
+ outstanding.set(key, e);
309
+ if (stateFile) { try { await locked(() => { const m = readState(); m.set(key, e); writeState(m); }); } catch (_) { /* best effort: memory still holds it */ } }
310
+ }
311
+ async function forget(key) {
312
+ outstanding.delete(key);
313
+ if (stateFile) { try { await locked(() => { const m = readState(); if (m.delete(key)) writeState(m); }); } catch (_) { /* best effort */ } }
314
+ }
315
+ refresh();
243
316
  const contracts = C.creditContracts({ runner: provider, addresses: { pool: addresses.pool, lens: addresses.lens, usdg: addresses.usdg, registry: addresses.registry, stockVault: addresses.stockVault || null } });
244
317
 
245
318
  // The chain, behind one facade (tests replace it).
@@ -338,44 +411,65 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
338
411
  let json = false; try { JSON.parse(body); json = true; } catch (_) { /* text */ }
339
412
  init.body = body; init.headers = { "content-type": json ? "application/json" : "text/plain; charset=utf-8" };
340
413
  }
414
+ // The method, the URL without its fragment (url#a and url#b are the same purchase) and the body: another body at the
415
+ // same URL is another purchase, quoted and priced on its own (GHSA-xqp9).
416
+ const purchase = await X.purchaseKey(new Request(u.href, init));
341
417
  const target = new URL(u.href);
342
- target.hash = ""; // a fragment never reaches the merchant: url#a and url#b are the same purchase
343
- const purchase = `${method} ${target.href}`;
418
+ target.hash = "";
419
+ const urlOnly = `${method} ${target.href}`; // the whole key without a body, and every key written before the body was in it
344
420
  const now = Math.floor(Date.now() / 1000);
345
- for (const [k, v] of outstanding) if (v.validBefore <= now) outstanding.delete(k);
421
+ // Kept for the payer's clock-skew margin past validBefore: the chain's clock may be behind this machine's.
422
+ for (const [k, v] of outstanding) if (!live(v, now)) outstanding.delete(k); // the file drops them on its next write
423
+ refresh(); // a payment another server of this wallet (another session) signed for this purchase is resent, not signed again
424
+ // SHORTCUT: two sessions of one wallet paying the same URL in the same instant (between this read and the other's
425
+ // onSigned, about one 402 round trip) can still both sign: onSigned records a payment, it cannot veto one. Ceiling:
426
+ // one extra payment of at most max_price_usd to the merchant the user chose, counted in each session's cap (the
427
+ // P-15 class, Low). Upgrade trigger: a report of it, or agents running pay_url concurrently on one wallet: reserve
428
+ // the purchase in the file under the lock before the 402 request, or derive the EIP-3009 nonce per purchase.
346
429
  const lines = [];
347
430
  const prior = outstanding.get(purchase);
431
+ // A payment kept without its body (by an earlier version, or for a call without one) cannot be matched to a call with
432
+ // a body: resending it could serve another purchase, signing could pay this one twice. Nothing is done until it expires.
433
+ const unmatched = !prior && purchase !== urlOnly ? outstanding.get(urlOnly) : undefined;
434
+ if (unmatched) {
435
+ const until = when(unmatched.validBefore + X.SKEW_SECONDS);
436
+ 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.`);
437
+ }
348
438
  let r;
439
+ let signedPrice = null; // what the payer checked and signed, never a merchant field read again here
349
440
  if (prior) {
350
441
  // A payment for this purchase is already out and still cashable: send that same one, never a second.
351
442
  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);
352
- r = { ...r, requirement: prior.requirement, paid: r.response.ok ? prior.price : 0n, borrowed: 0n, signed: prior, resent: true, ...(r.response.ok ? { settlement: settlementOf(r.response) } : {}) };
443
+ 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) } : {}) };
444
+ signedPrice = prior.price;
353
445
  lines.push("No new payment was signed: the same signed payment was sent again.");
354
446
  } else {
355
447
  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.`);
356
448
  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).`);
357
449
  let agentId;
358
450
  if (maxBorrow > 0n) { agentId = await resolveAgent(); await needController(agentId); }
359
- 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 } : {}) });
451
+ 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 } : {}),
452
+ // Counted when signed, at the price the payer checked and signed (a v1 requirement's `amount` is the merchant's text).
453
+ onSigned: async (s) => { signedPrice = s.price; session.spent += s.price; await record(purchase, { paymentHeaders: s.paymentHeaders, validBefore: s.validBefore, price: s.price, payTo: s.requirement.payTo }); } });
360
454
  try { r = await payer.pay(url, init); } catch (e) {
361
455
  // What the error carries was done: a loan taken and a payment signed are counted, whatever failed after.
362
456
  if (e?.borrowed > 0n) session.borrowed += e.borrowed;
457
+ // A borrow sent whose answer was lost may have mined (GHSA-v9xj): counted above, and said, never "nothing done".
458
+ 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.`);
363
459
  if (e?.signed) {
364
- const price = BigInt(e.requirement.amount ?? e.requirement.maxAmountRequired);
365
- session.spent += price;
366
- outstanding.set(purchase, { ...e.signed, requirement: e.requirement, price });
367
- const until = when(e.signed.validBefore);
368
- 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 URL 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.` : ""}`);
460
+ if (signedPrice === null) { signedPrice = maxPrice; session.spent += maxPrice; await record(purchase, { ...e.signed, price: maxPrice, payTo: e.requirement.payTo }); } // not reached: onSigned ran
461
+ const price = signedPrice;
462
+ const until = when(e.signed.validBefore + X.SKEW_SECONDS);
463
+ 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.` : ""}`);
369
464
  }
370
465
  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.` : "";
371
466
  if (e?.name === "TimeoutError" || e?.name === "AbortError") throw new ToolError(`${method} ${u.href} did not answer in time. Nothing was signed or paid.${loan}`);
372
467
  if (loan) throw new ToolError(`${explain(e)}.${loan}`);
373
468
  throw e;
374
469
  }
375
- if (r.signed) {
376
- const price = BigInt(r.requirement.amount ?? r.requirement.maxAmountRequired);
377
- session.spent += price; // counted when signed: the merchant can cash it whether or not it says so
378
- if (r.paid === 0n) outstanding.set(purchase, { ...r.signed, requirement: r.requirement, price });
470
+ if (r.signed && signedPrice === null) { // not reached: onSigned counted and recorded it
471
+ signedPrice = maxPrice; session.spent += maxPrice;
472
+ if (r.paid === 0n) await record(purchase, { ...r.signed, price: maxPrice, payTo: r.requirement.payTo });
379
473
  }
380
474
  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.`); }
381
475
  else if (r.requirement) lines.push("Nothing was borrowed.");
@@ -383,12 +477,12 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
383
477
  const status = r.timedOut ? "no answer in time" : r.transportError ? "the connection was lost" : `HTTP ${r.response.status}`;
384
478
  if (!r.requirement) lines.unshift(`No payment was asked for: ${method} ${u.href} answered ${status}. Nothing was paid.`);
385
479
  else if (r.paid > 0n) {
386
- outstanding.delete(purchase);
480
+ await forget(purchase);
387
481
  const tx = r.settlement?.transaction;
388
482
  lines.unshift(`Paid ${usd(r.paid)}${r.x402Version ? ` (x402 v${r.x402Version})` : ""} to ${r.requirement.payTo} for ${method} ${u.href}: ${status}.${tx ? (TX_RE.test(String(tx)) ? ` Settlement tx ${tx}.` : " (The merchant's settlement id is not a transaction hash; not shown.)") : ""}`);
389
483
  } else {
390
- const until = when(r.signed.validBefore);
391
- lines.unshift(`A payment of ${usd(BigInt(r.requirement.amount ?? r.requirement.maxAmountRequired))} to ${r.requirement.payTo} was signed and sent (${status}), and the merchant may still settle it until ${until}, so do NOT call pay_url again for this URL before ${until}; check wallet_balance. A later call for this URL only resends this same payment.`);
484
+ const until = when(r.signed.validBefore + X.SKEW_SECONDS);
485
+ lines.unshift(`A payment of ${usd(signedPrice)} to ${r.requirement.payTo} was signed and sent (${status}), and 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. A later call for this purchase only resends this same payment.`);
392
486
  }
393
487
  const loc = r.response.status >= 300 && r.response.status < 400 ? r.response.headers.get("location") : null;
394
488
  if (loc) lines.push(`The server redirected (not followed): ${fenced(oneLine(loc, 500), "redirect target")}`);
@@ -526,7 +620,15 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
526
620
  await needController(id);
527
621
  const q = await credit.quote(id, amount, term);
528
622
  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.`;
529
- const r = await credit.borrow(id, amount, term);
623
+ let r;
624
+ try { r = await credit.borrow(id, amount, term); } catch (e) {
625
+ // sent, and its answer lost: it may have mined, so it is counted and said (GHSA-v9xj)
626
+ if (e?.unconfirmed) {
627
+ session.borrowed += e.borrowed > 0n ? e.borrowed : amount;
628
+ throw new ToolError(`A borrow of ${usd(amount)} for agent #${id} 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 before borrowing again, and repay it with the repay tool before its due date.`);
629
+ }
630
+ throw e;
631
+ }
530
632
  session.borrowed += r.principal;
531
633
  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}.`;
532
634
  }));