@priors/mcp 0.14.1 → 0.16.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.
@@ -8,11 +8,12 @@
8
8
  // bond: USDG approve, deposit], registry approve(market, id), list
9
9
  // market_cancel cancel, on the market and/or on V2's v1
10
10
  // market_buy [USDG approve(market, exactly the price)], buy with the listing's nonce, the URI's hash and the
11
- // market's own record pin
11
+ // market's own record pin; [claim on the agent's lease before and after]
12
12
  // market_bid (V2) [USDG approve(spender, exactly what all open bids take)], bid
13
13
  // market_bid_any (V2) [the same approve], bidAny on the hub's list for an origin, checked against its root
14
14
  // market_cancel_bid (V2) cancelBid ×1-10, then the reserve trimmed to what is left
15
- // market_accept (V2) [the two cancels], [the bond], registry approve(market, id), acceptBid with minNet exact
15
+ // market_accept (V2) [the two cancels], [the bond], registry approve(market, id), acceptBid with minNet exact;
16
+ // [claim on the agent's lease before and after]
16
17
  //
17
18
  // sdk/market-plan.mjs (./market-plan.mjs here, a byte-for-byte copy) checks every rule of the contract on reads taken at
18
19
  // one block before anything is signed; each step is then simulated just before it is signed, and before each later step
@@ -21,6 +22,15 @@
21
22
  // (deployments/4663.agent-market-v2.json when it is there, else 4663.agent-market.json), confirmed on chain at the first
22
23
  // market call of the process; there is no address setting, so no page or model can steer an approval elsewhere.
23
24
  //
25
+ // Renting: once the package carries AgentLease's record (deployments/4663.agent-lease.json, beside V2's; none before
26
+ // the lease is deployed), its address is confirmed with the market (the lease's market() is V2), and market_buy and
27
+ // market_accept claim on the lease before and after the change of hands while a lease is stored on the agent, as every
28
+ // change of hands on Priors does (docs/AGENT-LEASE.md, the client rule): each day's rent then goes to whoever held the
29
+ // agent when it ended. The claim after is sent once the change of hands is mined, with nothing read or planned again
30
+ // (a claim with nothing stored returns 0); one that can't be sent, or doesn't go through, leaves the change as it is,
31
+ // and the answer says so, a retry's from the market record too. Without the record every tool, read and answer is as
32
+ // before.
33
+ //
24
34
  // What keeps a planted instruction from costing the wallet: selling is off unless PRIORS_MARKET_SELL allows the agent,
25
35
  // never the agent the server acts for (PRIORS_AGENT_ID), never under PRIORS_MARKET_MIN_SELL_USD; a buy or a bid is held
26
36
  // to PRIORS_MAX_MARKET_USD, all of the wallet's open bids to PRIORS_MAX_BIDS_USD, and buys, bids and listing bonds
@@ -39,10 +49,17 @@ import { z } from "zod";
39
49
  import * as M from "./market-plan.mjs";
40
50
  import { LISTING_RULES, LISTING_WORDS } from "./market-abi.mjs";
41
51
  import { MARKET_V2_IFACE, bidView, proofOf, idsRootOf, inRoot } from "./market-bids.mjs";
52
+ import { leaseView } from "./agent-lease.mjs";
42
53
  import { dailyLedger, ledgerOwners } from "./daily.mjs";
43
54
 
44
55
  const V1_TOOLS = ["market_agent", "market_list", "market_cancel", "market_buy"];
45
56
  const V2_TOOLS = [...V1_TOOLS, "market_bid", "market_bid_any", "market_cancel_bid", "market_accept"];
57
+ /** The claims on the lease around a change of hands (market-plan's bracket): the change itself is the last step that
58
+ * isn't one. */
59
+ const CLAIMS = new Set(["claimBefore", "claimAfter"]);
60
+ const mainStep = (steps, stage = (x) => x.step) => [...steps].reverse().find((x) => !CLAIMS.has(stage(x))) || steps[steps.length - 1];
61
+ /** The change of hands of each tool that claims around one, as the claims' words name it ("tx .. before the buy"). */
62
+ const CHANGE = Object.freeze({ market_buy: "the buy", market_accept: "the sale" });
46
63
  const HEX32 = /^0x[0-9a-fA-F]{64}$/;
47
64
  const lc = (a) => String(a).toLowerCase();
48
65
  const same = (a, b) => a != null && b != null && lc(a) === lc(b);
@@ -107,14 +124,19 @@ export function marketSettings(env, { looksLikeKey, stateDir }) {
107
124
  };
108
125
  }
109
126
 
127
+ /** A record in this package's deployments/, parsed, or null when it isn't there. */
128
+ const packageRecord = (f) => { const u = new URL(`../deployments/${f}`, import.meta.url); return existsSync(u) ? JSON.parse(readFileSync(u, "utf8")) : null; };
110
129
  /** The market this package knows (8.3): V2 once deployments/4663.agent-market-v2.json is in it, with v1 as its
111
- * `previous`; else v1. { kind, market, previous, adapters } (the NFT adapters that hold agents no market sells). */
112
- export function marketRecord() {
113
- const read = (f) => { const u = new URL(`../deployments/${f}`, import.meta.url); return existsSync(u) ? JSON.parse(readFileSync(u, "utf8")) : null; };
114
- const v1 = read("4663.agent-market.json"), v2 = read("4663.agent-market-v2.json"), op = read("origin-platforms.4663.json");
130
+ * `previous`; else v1. { kind, market, previous, adapters } (the NFT adapters that hold agents no market sells), and
131
+ * `lease` once deployments/4663.agent-lease.json is in it too (AgentLease, written by its deploy: `agentLease`, and
132
+ * `market`, which must be V2's). A lease record beside v1 alone, or naming another market, stops the start. `read`: a
133
+ * test's records by file name. */
134
+ export function marketRecord(read = packageRecord) {
135
+ const v1 = read("4663.agent-market.json"), v2 = read("4663.agent-market-v2.json"), op = read("origin-platforms.4663.json"), leaseRec = read("4663.agent-lease.json");
115
136
  const adapters = (op && Array.isArray(op.adapters) ? op.adapters : []).filter(isAddr).map(lc);
116
137
  const v2At = v2 && (v2.agentMarketV2 || v2.agentMarket || v2.market);
117
- if (isAddr(v2At)) return { kind: "v2", market: lc(v2At), previous: v1 && isAddr(v1.agentMarket) ? lc(v1.agentMarket) : null, adapters };
138
+ if (leaseRec && (!isAddr(v2At) || !isAddr(leaseRec.agentLease) || !same(leaseRec.market, v2At))) throw new Error("this package's AgentLease record (deployments/4663.agent-lease.json) doesn't name a lease of its AgentMarketV2 (deployments/4663.agent-market-v2.json)");
139
+ if (isAddr(v2At)) return { kind: "v2", market: lc(v2At), previous: v1 && isAddr(v1.agentMarket) ? lc(v1.agentMarket) : null, adapters, ...(leaseRec ? { lease: lc(leaseRec.agentLease) } : {}) };
118
140
  if (!v1 || !isAddr(v1.agentMarket)) throw new Error("this package has no AgentMarket record (deployments/4663.agent-market.json)");
119
141
  return { kind: "v1", market: lc(v1.agentMarket), previous: null, adapters };
120
142
  }
@@ -140,6 +162,8 @@ export function marketInstructions(s, kind) {
140
162
  export function registerMarketTools(ctx) {
141
163
  const { tool, serial, needWallet, wallet, provider, fetchImpl, credit, locked, stateDir, withinTime, ToolError, callBudgetMs, settings: S, record: REC, addresses } = ctx;
142
164
  const pollMs = ctx.pollMs ?? 1000;
165
+ // the USDG payments signed and not settled yet still need (pay_url's, as stock_buy and save keep it back)
166
+ const heldForPayments = typeof ctx.heldForPayments === "function" ? ctx.heldForPayments : () => 0n;
143
167
  const fail = (t) => new ToolError(t);
144
168
  /** A kind's words, with a value the refusal didn't carry: the sentence that names it dropped, or the step's own. */
145
169
  const words = (kind, vars, role) => {
@@ -165,14 +189,16 @@ export function registerMarketTools(ctx) {
165
189
  const call = M.aggregateCall(reads);
166
190
  return M.aggregateOut(await withinTime(provider.call({ to: call.to, data: call.data, blockTag }), left()));
167
191
  }
168
- // the market, confirmed once a process (8.3): a failed read is tried again at the next call
192
+ // the market, confirmed once a process (8.3), with the package's lease when it has one: a failed read is tried again
193
+ // at the next call
169
194
  let kindCache = null;
170
195
  async function marketOf(left) {
171
196
  if (kindCache) return kindCache;
172
197
  let c;
173
- try { const reads = M.kindReads(REC.market); c = M.readsOut(reads, await multicall(reads, "latest", left)); } catch (e) { throw refuse("unread"); }
174
- const k = M.marketKindOf(c, { market: REC.market, record: { registry: addresses.registry, usdg: addresses.usdg } });
198
+ try { const reads = M.kindReads(REC.market, REC.lease); c = M.readsOut(reads, await multicall(reads, "latest", left)); } catch (e) { throw refuse("unread"); }
199
+ const k = M.marketKindOf(c, { market: REC.market, record: { registry: addresses.registry, usdg: addresses.usdg }, lease: REC.lease });
175
200
  if (k.error === "unread") throw refuse("unread");
201
+ if (k.error === "unknownLease") throw refuse("unknownLease", { lease: ethers.getAddress(REC.lease) });
176
202
  if (k.error || k.kind !== REC.kind || (k.kind === "v2" && REC.previous && !same(k.addr.previous, REC.previous))) throw refuse("unknownMarket", { market: ethers.getAddress(REC.market) });
177
203
  kindCache = k;
178
204
  return k;
@@ -297,9 +323,10 @@ export function registerMarketTools(ctx) {
297
323
  /**
298
324
  * 2. At each market call: settle the step an earlier call sent (8.7). Pending, or not known to the node while its
299
325
  * nonce is unused: TX_UNCONFIRMED, nothing new is sent. Mined: marked; once every step of it is settled it joins
300
- * `done`, answered again for a retry of the same call for 10 minutes from now. Another server's call still between its
301
- * steps: OTHER_SESSION. This server's own (it ended: one call of a server runs at a time), and one that sent nothing,
302
- * hold nothing.
326
+ * `done`, answered again for a retry of the same call for 10 minutes from now, as does a buy or an accept whose every
327
+ * step but the claim on the lease after it is mined (that claim mined or not, the answer says which). Another
328
+ * server's call still between its steps: OTHER_SESSION. This server's own (it ended: one call of a server runs at a
329
+ * time), and one that sent nothing, hold nothing.
303
330
  */
304
331
  async function settleRecord(T) {
305
332
  let r = readRec();
@@ -321,12 +348,21 @@ export function registerMarketTools(ctx) {
321
348
  }
322
349
  // mined steps: their receipts, for the answer of the call that sent them
323
350
  for (const s of steps) if (s.state === "mined" && !rcs.has(s.hash)) { const seen = await lookupTx(s.hash, T.end); if (seen && seen.state === "mined") rcs.set(s.hash, seen.rc); }
324
- const finished = op.steps.length > 0 && steps.length === op.plan.length && steps.every((s) => s.state === "mined");
325
- // a call of another server, still between its steps: never overtaken
326
- if (!finished && steps.length && steps.every((s) => s.state === "mined") && op.by !== SESSION && Date.now() - op.at * 1000 < 2 * callBudgetMs) throw fail(`Another session of this wallet is running ${op.tool} now. ${NOTHING} Call again in a minute.`);
327
- const k = kindCache, at = nowS();
328
- const made = k ? steps.filter((s) => s.state === "mined").flatMap((s) => (rcs.get(s.hash) ? bidMadeIn(rcs.get(s.hash), k, wallet.address).map((id) => ({ id, block: Number(BigInt(rcs.get(s.hash).blockNumber)), at })) : [])) : [];
329
- const answer = finished ? `${cap1(stageWords(steps[steps.length - 1].stage, op.id))} went through (tx ${steps.map((s) => s.hash).join(", ")})${made.length ? `: bid #${made.map((b) => b.id).join(", #")}` : ""}.` : null;
351
+ const n = op.plan.length, mined = (s) => s.state === "mined";
352
+ // a call of another server, still between its steps: never overtaken (its claim on the lease after the change of
353
+ // hands included, while it may still send it)
354
+ if (steps.length && steps.length < n && steps.every(mined) && op.by !== SESSION && Date.now() - op.at * 1000 < 2 * callBudgetMs) throw fail(`Another session of this wallet is running ${op.tool} now. ${NOTHING} Call again in a minute.`);
355
+ // the claim on the lease after a change of hands is best effort (execute): once every step before it is mined the
356
+ // change went through, whether that claim then landed, was dropped or reverted ("failed"), or was never sent
357
+ // ("unsent")
358
+ const claimLeft = op.plan[n - 1] === "claimAfter" && steps.length >= n - 1 && steps.slice(0, n - 1).every(mined);
359
+ const finished = op.steps.length > 0 && ((steps.length === n && steps.every(mined)) || claimLeft);
360
+ const missed = !claimLeft || (steps.length === n && mined(steps[n - 1])) ? null : steps.length < n ? "unsent" : "failed";
361
+ const k = kindCache, at = nowS(), ok = steps.filter(mined);
362
+ const made = k ? ok.flatMap((s) => (rcs.get(s.hash) ? bidMadeIn(rcs.get(s.hash), k, wallet.address).map((id) => ({ id, block: Number(BigInt(rcs.get(s.hash).blockNumber)), at })) : [])) : [];
363
+ // named by its change of hands, not the claim on the lease after it: the steps mined, and the claims' line when the
364
+ // claim after didn't go through
365
+ const answer = finished ? `${cap1(stageWords(mainStep(steps, (x) => x.stage).stage, op.id))} went through (tx ${ok.map((s) => s.hash).join(", ")})${made.length ? `: bid #${made.map((b) => b.id).join(", #")}` : ""}.${missed ? ` ${claimsWords(ok.map((s) => ({ step: s.stage, hash: s.hash })), { leased: true }, op.id, CHANGE[op.tool], missed).join(" ")}` : ""}` : null;
330
366
  try { r = await writeRec({ op: null, done: [...r.done, ...(answer ? [{ tool: op.tool, key: op.key, at, answer }] : [])], bids: [...r.bids, ...made] }, r.rev); } catch (e) {
331
367
  if (e?.code === "OTHER_SESSION") throw fail(`another session of this wallet changed its market record just now. ${NOTHING} Call again in a minute.`);
332
368
  throw fail(`the market record (${recFile}) could not be written (${e?.message || e}). ${NOTHING} Fix PRIORS_STATE_DIR, then call again.`);
@@ -366,6 +402,8 @@ export function registerMarketTools(ctx) {
366
402
  if (stage === "bidAny") return "the bid on an origin's agents";
367
403
  if (stage.startsWith("cancelBid:")) return `the cancel of bid #${stage.slice(10)}`;
368
404
  if (stage === "accept") return `the accept of a bid for ${a}`;
405
+ if (stage === "claimBefore") return `the claim on ${a}'s lease before it changes hands`;
406
+ if (stage === "claimAfter") return `the claim on ${a}'s lease after it changed hands`;
369
407
  return stage;
370
408
  }
371
409
  /** What a step already mined leaves standing, said when a call stops after it. */
@@ -384,10 +422,12 @@ export function registerMarketTools(ctx) {
384
422
  // ceilings, about 1.25 times each step's gas on an anvil fork of chain 4663 at block 99,412,584 (2026-10-27: v1 list
385
423
  // 316,483, buy 282,356, cancel 49,272; V2 list 326,793, bid 242,570, bidAny 133,439, cancelBid 36,028 to 38,892,
386
424
  // acceptBid 319,757; the registry's approve 53,244, USDG's 57,964); InviteBondV2's deposit, not measured there, keeps
387
- // first_line's ceiling for InviteBond's. Each step is estimated again before it is signed. Ceiling: a chain or
425
+ // first_line's ceiling for InviteBond's. AgentLease's claim isn't deployed, so not measured: it pays at most three
426
+ // transfers (the holder at the last payout, the owner now, the fee), and 20 of them are to fit the gas gate's 3M a
427
+ // call, so 250,000 leaves room. Each step is estimated again before it is signed. Ceiling: a chain or
388
428
  // contract change that makes a step cost more. Upgrade trigger: a call that stops on gas after its first step.
389
429
  const GAS = { cancelOldPrev: 65_000n, cancelOld: 65_000n, cancel: 65_000n, cancelPrev: 65_000n, bondApprove: 75_000n, bond: 400_000n, approve: 70_000n, list: 410_000n,
390
- approveUsdg: 75_000n, buy: 360_000n, approveReserve: 75_000n, bid: 305_000n, bidAny: 170_000n, cancelBid: 50_000n, accept: 400_000n };
430
+ approveUsdg: 75_000n, buy: 360_000n, approveReserve: 75_000n, bid: 305_000n, bidAny: 170_000n, cancelBid: 50_000n, accept: 400_000n, claimBefore: 250_000n, claimAfter: 250_000n };
391
431
  const gasOf = (stage) => GAS[stage.startsWith("cancelBid:") ? "cancelBid" : stage] ?? 300_000n;
392
432
  async function feeNow(T, tail) {
393
433
  let fee;
@@ -494,8 +534,11 @@ export function registerMarketTools(ctx) {
494
534
  // the steps that take USDG from the wallet or raise what its bids may take: keep back is checked again before each
495
535
  const TAKES = new Set(["buy", "bid", "bidAny", "approveReserve", "bond"]);
496
536
  const ledger = wallet ? dailyLedger({ stateDir: join(stateDir, "market"), owners: ledgerOwners(String(S.agentId), wallet.address), caps: { signed: S.dayCap, borrowed: null } }) : null;
497
- /** 6. What the agent's open loans owe stays in the wallet (its savings count): `out` is what this call takes. */
498
- async function keepBack(c, out, T) {
537
+ /** 6. What the agent's open loans owe stays in the wallet (its savings count): `out` is what this call takes. USDG
538
+ * this wallet's open bids can still take (what it approved to the bids' spender, c.reserve) and USDG payments signed
539
+ * and not settled yet still need are not there to repay them (GHSA-m2h8-m55f-9j66): `bids` false for a bid, whose
540
+ * `out` already is the reserve of all its open bids. */
541
+ async function keepBack(c, out, T, bids = true) {
499
542
  const a = c.selfAgent;
500
543
  if (a == null) throw refuse("unread");
501
544
  if (BigInt(a.activeLoans) === 0n) return;
@@ -506,8 +549,12 @@ export function registerMarketTools(ctx) {
506
549
  } catch (_) { throw refuse("unread"); }
507
550
  let saved = 0n;
508
551
  try { if (typeof credit.savedOf === "function") saved = BigInt(await withinTime(credit.savedOf(wallet.address), Math.min(5000, T.left()))); } catch (_) { saved = 0n; }
509
- const left = BigInt(c.cash) + saved - out;
510
- if (left < owed) throw refuse("keepBack", { self: S.agentId, owed, due: due ? M.dayText(due) : "soon", left: left > 0n ? left : 0n });
552
+ let held = 0n;
553
+ try { held = BigInt(heldForPayments() || 0n); } catch (_) { held = 0n; }
554
+ if (bids && c.reserve != null) held += BigInt(c.reserve);
555
+ const left = BigInt(c.cash) + saved - out - held;
556
+ const vars = { self: S.agentId, owed, due: due ? M.dayText(due) : "soon", left: left > 0n ? left : 0n, held };
557
+ if (left < owed) throw refuse(held > 0n ? "keepBackHeld" : "keepBack", vars);
511
558
  }
512
559
  /** 7. The day's count, reserved before anything is sent (the market's own ledger). */
513
560
  function reserveDay(want) {
@@ -525,10 +572,11 @@ export function registerMarketTools(ctx) {
525
572
 
526
573
  /**
527
574
  * Steps 2 to 12 for one write tool. `o`: { name, role, args, id, me, dry, read (the snapshot's options, from the
528
- * record), plan (s, k, first) => a plan (first: the first plan, null for it), check (plan, s, rec) => throws a
529
- * refusal of the first plan, facts (plan, s) => lines for dry_run, keep (plan) => what leaves the wallet (keep back;
530
- * null: nothing), day (plan) => the day's reservation, counted (step, plan) => what a broadcast step counts, done
531
- * (ctx) => the answer }.
575
+ * record), plan (s, k, first, T, sent) => a plan (first: the first plan, null for it; sent: the steps mined so far),
576
+ * check (plan, s, rec) => throws a refusal of the first plan, facts (plan, s) => lines for dry_run, keep (plan) =>
577
+ * what leaves the wallet (keep back; null: nothing), day (plan) => the day's reservation, counted (step, plan) =>
578
+ * what a broadcast step counts, done (ctx) => the answer (ctx.missed: "time" when the call's time left no room for
579
+ * the claim on the lease after the change of hands, "failed" when it didn't go through, else null) }.
532
580
  */
533
581
  async function execute(o, deadline) {
534
582
  const T = timing(deadline), me = o.me;
@@ -547,7 +595,7 @@ export function registerMarketTools(ctx) {
547
595
  if (plan.error) throw refuse(plan.error, varsOf(plan, o), o.role);
548
596
  if (o.check) o.check(plan, s, rec);
549
597
  const out = o.keep ? o.keep(plan) : null;
550
- if (out != null) await keepBack(s.c, out, T);
598
+ if (out != null) await keepBack(s.c, out, T, o.role !== "bid");
551
599
  const stepsAll = plan.steps;
552
600
  const calls = stepsAll.map((st) => ({ step: st, ...M.stepCalls(st, { addr: k.addr, id: o.id, now: s.now, ...plan }), what: stageWords(st, o.id, plan) }));
553
601
  if (o.dry) {
@@ -555,16 +603,26 @@ export function registerMarketTools(ctx) {
555
603
  structured: { tool: o.name, dryRun: true, agentId: o.id == null ? null : String(o.id), calls: calls.map((c) => ({ step: c.step, to: lc(c.to), data: c.data })) } };
556
604
  }
557
605
  const day = reserveDay(o.day ? o.day(plan) : 0n);
558
- let counted = 0n;
606
+ // what the steps sent count (o.counted), and the step being sent with the plan it was sent on: a step whose answer
607
+ // is lost may still land, so it adds what it alone counts (an approval nothing, a buy its price); the steps mined
608
+ // before it stay counted (GHSA-m2h8-m55f-9j66, GHSA-pg36-8pmq-5p4v: a later plan of the same call, read once the bond
609
+ // was mined, carries no bond, so its day was no measure of what the call spent)
610
+ let counted = 0n, inFlight = null;
559
611
  try {
560
612
  await gasCheck(stepsAll, calls[0], T);
561
613
  const opBase = { tool: o.name, key, at: nowS(), plan: stepsAll, id: o.id == null ? null : String(o.id), by: SESSION };
562
614
  rec = { ...rec, op: null };
563
615
  const sent = [];
564
616
  const first = plan;
565
- let steps = stepsAll;
617
+ let steps = stepsAll, missed = null;
566
618
  while (steps.length) {
567
- if (sent.length) {
619
+ const step = steps[0];
620
+ // the claim on the lease after a change of hands: the change is mined, so nothing is read or planned again (a
621
+ // claim with nothing stored returns 0); one the call's time leaves no room for, or that doesn't go through,
622
+ // leaves the change as it is, and the answer says so
623
+ const after = step === "claimAfter";
624
+ if (after && T.end - Date.now() < stepMs) { missed = "time"; break; }
625
+ if (sent.length && !after) {
568
626
  // 10.1: read everything again at the latest block and plan again; the rest and the terms must be the same
569
627
  let again;
570
628
  try { s = await snapshot(k, await o.read(rec, k, T, sent), T.left); again = await o.plan(s, k, first, T, sent); } catch (e) {
@@ -575,25 +633,37 @@ export function registerMarketTools(ctx) {
575
633
  if (why) throw fail(`Sent ${sentWords(sent, o)}, then stopped. ${cap1(why)} ${NOTHING_MORE}${standing(sent[sent.length - 1].step)}`);
576
634
  plan = again;
577
635
  }
578
- const step = steps[0];
579
636
  // 6 again, on the new reads, before a later step that takes USDG or raises what the bids may take: USDG
580
637
  // that left the wallet since the first read (another session's pay_url, an autopay pull) counts
581
638
  const out2 = sent.length && o.keep && TAKES.has(step) ? o.keep(plan) : null;
582
639
  if (out2 != null) {
583
- try { await keepBack(s.c, out2, T); } catch (e) {
640
+ try { await keepBack(s.c, out2, T, o.role !== "bid"); } catch (e) {
584
641
  throw fail(`Sent ${sentWords(sent, o)}, then stopped. ${e instanceof ToolError ? e.message.replace(/ Nothing was signed or sent\.$/, "") : M.planWords("unread")} ${NOTHING_MORE}${standing(sent[sent.length - 1].step)}`);
585
642
  }
586
643
  }
587
644
  const call = M.stepCalls(step, { addr: k.addr, id: o.id, now: s.now, ...plan });
588
- const r = await sendStep({ step, call, o: { id: o.id, vars: { ...o.vars, id: o.id }, ...plan }, rec, opBase, sent, T, role: o.role });
645
+ let r;
646
+ inFlight = { step, plan };
647
+ try { r = await sendStep({ step, call, o: { id: o.id, vars: { ...o.vars, id: o.id }, ...plan }, rec, opBase, sent, T, role: o.role }); } catch (e) {
648
+ // a claim after that was sent and not seen yet stays in the record as any step does (TX_UNCONFIRMED)
649
+ if (!after || !(e instanceof ToolError) || /^TX_UNCONFIRMED/.test(e.message)) throw e;
650
+ inFlight = null;
651
+ missed = "failed";
652
+ // the record as the step left it (one mined and reverted is kept so), while its op is still this call's: the
653
+ // answer below is then kept for a retry; another session's op is never written over
654
+ try { const cur = readRec(); if (cur.op && cur.op.by === SESSION && cur.op.key === key && cur.op.at === opBase.at) rec = cur; } catch (_) { /* settled next time */ }
655
+ break;
656
+ }
657
+ inFlight = null;
589
658
  counted += o.counted ? o.counted(step, plan) : 0n;
590
659
  rec = r.rec;
591
660
  sent.push({ step, hash: r.hash, rc: r.rc, o: plan });
592
661
  steps = steps.slice(1);
593
662
  }
594
- // 11. read back: the market's event in the final receipt, and the chain now
663
+ // 11. read back: the market's event in the change of hands' receipt (the final one, but for a claim on the lease
664
+ // after it), and the chain now
595
665
  const last = sent[sent.length - 1];
596
- const answer = await o.done({ k, sent, plan, first, events: eventsOf(last.rc, k), T, s });
666
+ const answer = await o.done({ k, sent, plan, first, events: eventsOf(mainStep(sent).rc, k), T, s, missed });
597
667
  const made = bidMadeIn(last.rc, k, me).map((id) => ({ id, block: Number(BigInt(last.rc.blockNumber)), at: nowS() }));
598
668
  // the record's bids: those bidOf last showed closed, and those this call cancelled, are dropped
599
669
  const gone = new Set(sent.filter((x) => x.step.startsWith("cancelBid:")).map((x) => x.step.slice(10)));
@@ -603,7 +673,7 @@ export function registerMarketTools(ctx) {
603
673
  } catch (e) {
604
674
  // what a step that was broadcast counts stays counted, its answer lost or not (a sent step may still land)
605
675
  const unconfirmed = e instanceof ToolError && /^TX_UNCONFIRMED/.test(e.message);
606
- if (unconfirmed && o.counted) counted = o.day ? o.day(plan) : counted;
676
+ if (unconfirmed && o.counted && inFlight) counted += o.counted(inFlight.step, inFlight.plan);
607
677
  // a call that stopped with every step it sent settled leaves nothing in flight: the next call isn't held by it
608
678
  if (!unconfirmed && rec && rec.op && rec.op.steps.every((x) => x.state !== "sent")) {
609
679
  try { await writeRec({ op: null, done: rec.done, bids: rec.bids }, rec.rev); } catch (_) { /* settled next time */ }
@@ -629,6 +699,30 @@ export function registerMarketTools(ctx) {
629
699
  const ceiling = (amount) => { if (amount > S.maxMarket) throw refuse("ceiling", { amount, max: S.maxMarket }); };
630
700
  const sellerWords = (p) => `${amt(p.price)} USDG. Fee ${amt(p.fee)}.${p.share > 0n ? ` Builder share ${amt(p.share)}.` : ""}`;
631
701
  const holdNow = (c) => { const t = Number(c.soldAt ?? 0); return t === 0 ? 0 : t + LISTING_RULES.holdS; };
702
+
703
+ /* ---- the lease's claims around a change of hands (only where the package records AgentLease) ---- */
704
+ /** A later plan's part of market-plan's bracket: the first plan's, and whether the claim before was sent. */
705
+ const claimsOf = (first, sent = []) => ({ leased: !!(first && first.leased), claimed: sent.some((x) => x.step === "claimBefore") });
706
+ /** The lease that runs on the agent `c` read, as every surface says it ("Run by 0x12..ab until 30 Nov"), or null. */
707
+ const runOf = (c, now) => (c && c.lease ? leaseView(c.lease, { nowS: now }) : null);
708
+ /** What a buyer of a rented agent gets (the seam's Sell words, LEASE_WORDS.sell, say the same to a seller). */
709
+ const RENTED = "A buyer gets it with the lease and the rent of each day that ends after the sale.";
710
+ /** dry_run's line for a plan with the claims (`what`: CHANGE's): the lease that runs, and the claims. */
711
+ const leaseFacts = (p, s, id, what) => {
712
+ if (!p.leased) return [];
713
+ const run = runOf(s.c, s.now);
714
+ return [`${run ? `${run.words}. ${RENTED} ` : ""}A claim on its lease comes before ${what} and after it, so each day ended goes to whoever held #${id} when it ended; the claims cost this wallet gas only.`];
715
+ };
716
+ /** The answer's line on the claims once the change of hands is mined (`what`: CHANGE's; `missed`: execute's, "time"
717
+ * for a claim after the call's time left no room for and "failed" for one that didn't go through, or the record's
718
+ * settling, "unsent" for one never sent and "failed" for one dropped or reverted). */
719
+ const claimsWords = (sent, first, id, what, missed) => {
720
+ if (!first.leased) return [];
721
+ const b = sent.find((x) => x.step === "claimBefore"), a = sent.find((x) => x.step === "claimAfter");
722
+ const said = [b && `tx ${b.hash} before ${what}`, a && `tx ${a.hash} after it`].filter(Boolean).join(", ");
723
+ const miss = missed === "time" ? "The claim after it wasn't sent: this call's time ran out." : missed === "unsent" ? "The claim after it wasn't sent." : missed ? "The claim after it didn't go through." : "";
724
+ return [[said ? `Claims on its lease: ${said}.` : "", miss && `${miss} The lease's next claim, by anyone, records #${id}'s new holder.`].filter(Boolean).join(" ")];
725
+ };
632
726
  const agentIdIn = z.number().int().nonnegative().describe("The agent's ERC-8004 id on Robinhood Chain.");
633
727
  const dryRun = z.boolean().optional().describe("true: read and plan, list the transactions in order, send nothing.");
634
728
  const daysIn = z.number().int().min(1).max(30).optional().describe("How long it stands, 1 to 30 days. Default 7.");
@@ -638,7 +732,7 @@ export function registerMarketTools(ctx) {
638
732
  /* ---- market_agent ---- */
639
733
  tool("market_agent", {
640
734
  title: "Read an agent on the market",
641
- description: `Read one agent on Priors' agent market (AgentMarket${kind === "v2" ? "V2" : ""} on Robinhood Chain), from the chain: who holds it (and whether that is this wallet), its listing (the asking price, the fee, what the seller gets, until when${kind === "v2" ? "; also its listing on the older market" : ""}), its 14-day hold, whether its treasury line goes with it and the bond a buyer locks, and whether this server may sell it.${kind === "v2" ? " With its open bids from Priors' hub, each read again on chain: the bid id, the price, what the owner gets, the maker's pins and, for a bid on an origin, the proof market_accept takes." : ""} Read-only.`,
735
+ description: `Read one agent on Priors' agent market (AgentMarket${kind === "v2" ? "V2" : ""} on Robinhood Chain), from the chain: who holds it (and whether that is this wallet)${REC.lease ? ", who runs it under a lease and until when (a buyer gets it with the lease)" : ""}, its listing (the asking price, the fee, what the seller gets, until when${kind === "v2" ? "; also its listing on the older market" : ""}), its 14-day hold, whether its treasury line goes with it and the bond a buyer locks, and whether this server may sell it.${kind === "v2" ? " With its open bids from Priors' hub, each read again on chain: the bid id, the price, what the owner gets, the maker's pins and, for a bid on an origin, the proof market_accept takes." : ""} Read-only.`,
642
736
  inputSchema: { agent_id: agentIdIn },
643
737
  annotations: { readOnlyHint: true, openWorldHint: true },
644
738
  }, async ({ agent_id }) => {
@@ -654,6 +748,11 @@ export function registerMarketTools(ctx) {
654
748
  if (c.owner == null) throw fail(c.failed.owner === "reverted" ? `#${id} isn't an agent on Robinhood Chain's registry.` : M.planWords("unread"));
655
749
  const lines = [], data = { agentId: String(id), market: ethers.getAddress(k.addr.market), kind: k.kind, owner: c.owner, yours: same(c.owner, me), listing: null, previousListing: null, holdUntil: null, line: null, bond: null, sell: null, bids: [] };
656
750
  lines.push(`#${id} is held by ${ethers.getAddress(c.owner)}${same(c.owner, me) ? " (this wallet)" : ""}.`);
751
+ // the lease that runs on it, where the package records AgentLease: an address and a date, as for every agent (a
752
+ // lease that couldn't be read is said, as market_buy and market_accept wait for it)
753
+ const run = k.addr.lease ? runOf(c, s.now) : null;
754
+ if (run) { data.runBy = { by: run.by, until: run.until }; lines.push(`${run.words}. ${RENTED}`); }
755
+ else if (k.addr.lease && c.lease == null) lines.push(`Whether #${id} is rented couldn't be read just now.`);
657
756
  const a = c.agent, follows = a && BigInt(a.sponsor) !== 0n && c.followed === true, lent = a ? BigInt(a.delegatedIn) : 0n;
658
757
  const shares = k.shares && c.builder && isAddr(c.builder.to) ? { to: c.builder.to, bps: BigInt(c.builder.bps) } : null;
659
758
  const view = (l, where) => {
@@ -694,6 +793,8 @@ export function registerMarketTools(ctx) {
694
793
  for (const item of hubBids) {
695
794
  const b = c.bids.get(String(item.bid));
696
795
  if (!b || !isAddr(b.maker) || Number(b.expiry) <= s.now || (item.by && !same(item.by, b.maker))) continue;
796
+ // a bid made before the agent's builder share was set: no accept can take it (BuilderAfterBid)
797
+ if (M.takesBid(c, String(item.bid), k.shares) === false) continue;
697
798
  const mk = c.makers.get(lc(b.maker)) || {};
698
799
  if (mk.cash == null || mk.reserve == null || BigInt(mk.cash) < BigInt(b.price) || BigInt(mk.reserve) < BigInt(b.price)) continue;
699
800
  let proof = [];
@@ -775,7 +876,7 @@ export function registerMarketTools(ctx) {
775
876
  /* ---- market_buy ---- */
776
877
  tool("market_buy", {
777
878
  title: "Buy an agent",
778
- description: `Buy an agent listed on Priors' agent market from this wallet's USDG, at its asking price, only if that is at most max_price_usd (required, no default): an approval of exactly the price when the USDG approved is short, then buy, pinned to the listing it read (its nonce, the agent's file and its record), so a listing changed meanwhile is refused on chain. The agent comes with its on-chain record, and a treasury line comes with it (lock your own bond before it borrows); its agent wallet is cleared by the transfer. Held to PRIORS_MAX_MARKET_USD (${amt(S.maxMarket)} USDG) a buy and PRIORS_MAX_MARKET_DAY_USD a day, only agents with PRIORS_MARKET_MIN_REPAID repaid loans or more, and never leaving less USDG (savings included) than agent #${S.agentId}'s open loans owe. Moves real money: state the agent, the price and the fee to the user and get their go-ahead first; dry_run: true lists the transactions without sending. Needs ETH for gas.`,
879
+ description: `Buy an agent listed on Priors' agent market from this wallet's USDG, at its asking price, only if that is at most max_price_usd (required, no default): an approval of exactly the price when the USDG approved is short, then buy, pinned to the listing it read (its nonce, the agent's file and its record), so a listing changed meanwhile is refused on chain.${REC.lease ? " A rented agent comes with its lease: while a lease is stored on it, a claim on the lease comes before and after the buy, so each day's rent goes to whoever held the agent when the day ended (gas only)." : ""} The agent comes with its on-chain record, and a treasury line comes with it (lock your own bond before it borrows); its agent wallet is cleared by the transfer. Held to PRIORS_MAX_MARKET_USD (${amt(S.maxMarket)} USDG) a buy and PRIORS_MAX_MARKET_DAY_USD a day, only agents with PRIORS_MARKET_MIN_REPAID repaid loans or more, and never leaving less USDG (savings included) than agent #${S.agentId}'s open loans owe. Moves real money: state the agent, the price and the fee to the user and get their go-ahead first; dry_run: true lists the transactions without sending. Needs ETH for gas.`,
779
880
  inputSchema: { agent_id: agentIdIn, max_price_usd: z.number().positive().describe("The most to pay, in US dollars of USDG (required)."), dry_run: dryRun },
780
881
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
781
882
  }, serial(async ({ agent_id, max_price_usd, dry_run = false }, deadline) => {
@@ -785,16 +886,16 @@ export function registerMarketTools(ctx) {
785
886
  return execute({
786
887
  name: "market_buy", role: "buy", args: { agent_id, max_price_usd }, id, me, dry: dry_run, vars: { max },
787
888
  read: async () => ({ id, me, self: S.agentId }),
788
- plan: (s, k, first) => M.buyPlan(s.c, { addr: k.addr, me, now: s.now, maxPrice: max, seen: first ? first.pins : null, minRecord: S.minRepaid, shares: k.shares }),
889
+ plan: (s, k, first, T, sent) => M.buyPlan(s.c, { addr: k.addr, me, now: s.now, maxPrice: max, seen: first ? first.pins : null, minRecord: S.minRepaid, shares: k.shares, ...claimsOf(first, sent) }),
789
890
  changed: (p, f) => (p.pins.recordHash !== f.pins.recordHash ? M.planWords("recordMoved", { id }) : p.pins.nonce !== f.pins.nonce || p.pins.price !== f.pins.price ? M.planWords("relisted", { id, price: p.listing.price }) : "Its terms changed since the first read."),
790
891
  keep: (p) => p.listing.price, day: (p) => p.listing.price, counted: (step, p) => (step === "buy" ? p.listing.price : 0n),
791
- facts: (p) => [`Buys #${id} for ${amt(p.listing.price)} USDG from ${ethers.getAddress(p.listing.seller)}. Fee ${amt(p.fee)}.${p.share > 0n ? ` Builder share ${amt(p.share)}.` : ""} The seller gets ${amt(p.net)}.`, ...(p.follows ? [`Its ${amt(p.line)} USDG line from the treasury comes with it.${p.bond > 0n ? ` Lock your own ${amt(p.bond)} USDG bond before it borrows.` : ""}`] : [])],
792
- done: async ({ k, sent, plan, events, T }) => {
793
- const txs = sent.map((x) => x.hash), buyTx = txs[txs.length - 1];
892
+ facts: (p, s) => [`Buys #${id} for ${amt(p.listing.price)} USDG from ${ethers.getAddress(p.listing.seller)}. Fee ${amt(p.fee)}.${p.share > 0n ? ` Builder share ${amt(p.share)}.` : ""} The seller gets ${amt(p.net)}.`, ...(p.follows ? [`Its ${amt(p.line)} USDG line from the treasury comes with it.${p.bond > 0n ? ` Lock your own ${amt(p.bond)} USDG bond before it borrows.` : ""}`] : []), ...leaseFacts(p, s, id, CHANGE.market_buy)],
893
+ done: async ({ k, sent, plan, first, events, T, missed }) => {
894
+ const txs = sent.map((x) => x.hash), buyTx = mainStep(sent).hash, approval = sent.find((x) => x.step === "approveUsdg");
794
895
  const ev = events.find((e) => e.name === "Sold" && BigInt(e.args.agentId) === id && same(e.args.buyer, me));
795
896
  const cash = await usdgOf(me, T.left);
796
897
  if (!ev) return { text: `${cap1(stageWords("buy", id))} was mined (tx ${buyTx}), but its receipt carries no Sold event from the market for #${id} and this wallet. ${NOTHING_MORE} market_agent shows who holds it.`, structured: { tool: "market_buy", agentId: String(id), txs, bought: null } };
797
- const lines = [`Bought #${id}. Tx ${buyTx}${txs.length > 1 ? ` (approval ${txs[0]})` : ""}. #${id} is this wallet's now, with its record.${cash != null ? ` This wallet holds ${amt(cash)} USDG now.` : ""}`];
898
+ const lines = [`Bought #${id}. Tx ${buyTx}${approval ? ` (approval ${approval.hash})` : ""}. #${id} is this wallet's now, with its record.${cash != null ? ` This wallet holds ${amt(cash)} USDG now.` : ""}`, ...claimsWords(sent, first, id, CHANGE.market_buy, missed)];
798
899
  if (plan.follows && plan.line > 0n) lines.push(`Its ${amt(plan.line)} USDG line from the treasury came with it. Lock your own ${amt(plan.bond || LISTING_RULES.bond)} USDG bond before it borrows.`);
799
900
  lines.push("Its agent wallet was cleared by the transfer. Run `priors-mcp link-wallet` to set one.");
800
901
  return { text: lines.join("\n"), structured: { tool: "market_buy", agentId: String(id), txs, bought: true, owner: me, usdg: cash == null ? null : amt(cash), line: plan.follows ? amt(plan.line) : null, bond: plan.bond > 0n ? amt(plan.bond) : null } };
@@ -906,7 +1007,7 @@ export function registerMarketTools(ctx) {
906
1007
  /* ---- market_cancel_bid ---- */
907
1008
  tool("market_cancel_bid", {
908
1009
  title: "Cancel a bid",
909
- description: "Cancel this wallet's bid bid_id on Priors' agent market, or with all: true every open bid of this wallet (the ones this server made and the ones Priors' hub shows, at most 10 a call), then set the bids' approval down to what the bids left still take. Each cancel is its own transaction from this wallet; never paused. dry_run: true lists the transactions without sending. Needs ETH for gas.",
1010
+ description: "Cancel this wallet's bid bid_id on Priors' agent market, or with all: true every open bid of this wallet (the ones this server made and the ones Priors' hub shows, at most 10 a call), then set the bids' approval down to what the bids left still take (left as it is while Priors' hub doesn't answer, since bids made elsewhere can't be counted then; with all: true and no open bid, an approval left standing is set to 0). Each cancel is its own transaction from this wallet; never paused. dry_run: true lists the transactions without sending. Needs ETH for gas.",
910
1011
  inputSchema: { bid_id: z.number().int().positive().optional().describe("The bid to cancel."), all: z.boolean().optional().describe("true: every open bid of this wallet, at most 10 a call."), dry_run: dryRun },
911
1012
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
912
1013
  }, serial(async ({ bid_id, all = false, dry_run = false }, deadline) => {
@@ -914,28 +1015,41 @@ export function registerMarketTools(ctx) {
914
1015
  if ((bid_id == null) === !all) throw fail(`Give bid_id, or all: true. ${NOTHING}`);
915
1016
  const me = lc(wallet.address);
916
1017
  let targets = bid_id != null ? [String(bid_id)] : null;
1018
+ // the hub's list of this wallet's bids not read (once in a call, for the whole call): bids made elsewhere (Go mode,
1019
+ // the board, another machine) are then unknown, so the bids' approval is never set down, which would leave them
1020
+ // unfunded (GHSA-m2h8-m55f-9j66)
1021
+ let hubDown = false;
1022
+ const keptWords = (x) => `Priors' hub didn't answer, so bids this wallet made elsewhere can't be counted: the bids' approval was left at ${amt(x)} USDG.`;
917
1023
  return execute({
918
1024
  name: "market_cancel_bid", role: "cancelBid", args: { bid_id, all }, id: null, me, dry: dry_run, vars: { bidId: bid_id == null ? null : String(bid_id) }, replay: false,
919
- read: async (rec, k, T) => { const b = await myBids(rec, T); return { me, bidIds: [...new Set([...b.ids, ...(targets || [])])] }; },
1025
+ read: async (rec, k, T) => { const b = await myBids(rec, T); hubDown = hubDown || b.hubDown; return { me, bidIds: [...new Set([...b.ids, ...(targets || [])])] }; },
920
1026
  plan: (s, k, first, T, sent = []) => {
921
1027
  const done = sent.filter((x) => x.step.startsWith("cancelBid:")).map((x) => x.step.slice(10));
922
1028
  const mine = [...s.c.bids.keys()];
923
1029
  if (!targets) {
924
1030
  targets = mine.filter((b) => { const x = s.c.bids.get(b); return x && same(x.maker, me) && Number(x.expiry) > s.now; }).sort((a, b) => Number(BigInt(a) - BigInt(b))).slice(0, 10);
1031
+ // no open bid, and an approval left standing (bids that ran out or were taken): set down to 0, the hub's list read
1032
+ if (!targets.length && !hubDown && s.c.reserve != null && BigInt(s.c.reserve) > 0n) return { steps: ["approveReserve"], reserve: 0n, reserveAfter: 0n, trimOnly: true, pins: { reserveAfter: "0" } };
925
1033
  if (!targets.length) return { error: "noBids" };
926
1034
  }
927
1035
  const left = targets.filter((b) => !done.includes(b));
928
1036
  if (!left.length) {
929
1037
  const reserveAfter = first ? first.reserveAfter : 0n;
930
- return { steps: s.c.reserve != null && BigInt(s.c.reserve) > reserveAfter ? ["approveReserve"] : [], reserve: reserveAfter, reserveAfter, pins: first.pins };
1038
+ return { steps: s.c.reserve != null && BigInt(s.c.reserve) > reserveAfter ? ["approveReserve"] : [], reserve: reserveAfter, reserveAfter, kept: first.kept, pins: first.pins };
931
1039
  }
932
1040
  const p = M.cancelBidPlan(s.c, { me, now: s.now, bidIds: left, myBids: mine });
933
- return p.error ? { ...p, bidId: p.bidId ? BigInt(p.bidId) : null } : { ...p, pins: { reserveAfter: String(p.reserveAfter) } };
1041
+ if (p.error) return { ...p, bidId: p.bidId ? BigInt(p.bidId) : null };
1042
+ if (hubDown && s.c.reserve != null) {
1043
+ const r = BigInt(s.c.reserve);
1044
+ return { ...p, steps: p.steps.filter((x) => x !== "approveReserve"), reserveAfter: r, reserve: r, kept: true, pins: { reserveAfter: String(r) } };
1045
+ }
1046
+ return { ...p, pins: { reserveAfter: String(p.reserveAfter) } };
934
1047
  },
935
- facts: (p) => [`Cancels ${p.steps.filter((x) => x.startsWith("cancelBid:")).map((x) => `bid #${x.slice(10)}`).join(", ")}.${p.steps.includes("approveReserve") ? ` Then sets the bids' approval down to ${amt(p.reserveAfter)} USDG.` : ""}`],
1048
+ facts: (p) => [p.trimOnly ? `No open bid to cancel. Sets the bids' approval down to 0 USDG.` : `Cancels ${p.steps.filter((x) => x.startsWith("cancelBid:")).map((x) => `bid #${x.slice(10)}`).join(", ")}.${p.steps.includes("approveReserve") ? ` Then sets the bids' approval down to ${amt(p.reserveAfter)} USDG.` : ""}${p.kept ? ` ${keptWords(p.reserveAfter)}` : ""}`],
936
1049
  done: async ({ sent, plan, events, k, T }) => {
937
1050
  const txs = sent.map((x) => x.hash), cancelled = sent.filter((x) => x.step.startsWith("cancelBid:")).map((x) => x.step.slice(10));
938
- return { text: `Cancelled bid${cancelled.length > 1 ? "s" : ""} #${cancelled.join(", #")}. Tx ${txs.join(", ")}. ${reserveLine(plan.reserveAfter).replace(/\.$/, " now.")}`, structured: { tool: "market_cancel_bid", txs, cancelled, reserve: amt(plan.reserveAfter) } };
1051
+ if (plan.trimOnly) return { text: `No open bid to cancel; set the bids' approval down to 0 USDG. Tx ${txs.join(", ")}.`, structured: { tool: "market_cancel_bid", txs, cancelled, reserve: amt(0n) } };
1052
+ return { text: `Cancelled bid${cancelled.length > 1 ? "s" : ""} #${cancelled.join(", #")}. Tx ${txs.join(", ")}. ${plan.kept ? keptWords(plan.reserveAfter) : reserveLine(plan.reserveAfter).replace(/\.$/, " now.")}`, structured: { tool: "market_cancel_bid", txs, cancelled, reserve: amt(plan.reserveAfter), ...(plan.kept ? { hubDown: true } : {}) } };
939
1053
  },
940
1054
  }, deadline);
941
1055
  }));
@@ -946,7 +1060,7 @@ export function registerMarketTools(ctx) {
946
1060
  const bondWords = (bond, id, done = false) => (bond > 0n ? (done ? ` This wallet's ${amt(bond)} USDG bond stays on #${id}'s line, at stake for it, until its new owner bonds, and then comes back.` : ` Before it, this wallet's ${amt(bond)} USDG bond goes on its line. The bond stays on #${id} after the sale, at stake for that line, until its new owner bonds, and then comes back.`) : "");
947
1061
  tool("market_accept", {
948
1062
  title: "Accept a bid",
949
- description: `Accept bid bid_id for agent agent_id, which this wallet holds: the agent goes to the bid's maker at once, and this wallet gets the price less the fee and any builder share set on the agent (market_agent shows each open bid, its id and, for a bid on an origin, its proof). The steps, each its own transaction from this wallet: cancel this wallet's own dormant listing of it first (approving would bring it back), InviteBondV2's bond when its treasury line needs one, the registry's approval of this one agent to the market, then acceptBid with what this wallet gets pinned exactly. A proof given is checked against the bid's list, never trusted; without one it is built from Priors' hub's list, checked against the bid's root. Only agents PRIORS_MARKET_SELL allows, never the agent this server acts for (PRIORS_AGENT_ID), never leaving less than PRIORS_MARKET_MIN_SELL_USD (${amt(S.minSell)} USDG) after the fee and any builder share. Moves an agent: state the bid, the price, the fee, any bond and what this wallet gets to the user and get their go-ahead first; dry_run: true lists the transactions without sending. Needs ETH for gas.`,
1063
+ description: `Accept bid bid_id for agent agent_id, which this wallet holds: the agent goes to the bid's maker at once, and this wallet gets the price less the fee and any builder share set on the agent (market_agent shows each open bid, its id and, for a bid on an origin, its proof). The steps, each its own transaction from this wallet: cancel this wallet's own dormant listing of it first (approving would bring it back), InviteBondV2's bond when its treasury line needs one, the registry's approval of this one agent to the market, then acceptBid with what this wallet gets pinned exactly.${REC.lease ? " A rented agent goes with its lease: while a lease is stored on it, a claim on the lease comes before and after, so each day's rent goes to whoever held the agent when the day ended (gas only)." : ""} A proof given is checked against the bid's list, never trusted; without one it is built from Priors' hub's list, checked against the bid's root. Only agents PRIORS_MARKET_SELL allows, never the agent this server acts for (PRIORS_AGENT_ID), never leaving less than PRIORS_MARKET_MIN_SELL_USD (${amt(S.minSell)} USDG) after the fee and any builder share. Moves an agent: state the bid, the price, the fee, any bond and what this wallet gets to the user and get their go-ahead first; dry_run: true lists the transactions without sending. Needs ETH for gas.`,
950
1064
  inputSchema: { bid_id: z.number().int().positive().describe("The bid to accept."), agent_id: agentIdIn, proof: z.array(z.string().regex(/^0x[0-9a-fA-F]{64}$/)).max(32).optional().describe("For a bid on an origin: the proof that the agent is in its list, as market_agent shows it."), dry_run: dryRun },
951
1065
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
952
1066
  }, serial(async ({ bid_id, agent_id, proof, dry_run = false }, deadline) => {
@@ -957,7 +1071,7 @@ export function registerMarketTools(ctx) {
957
1071
  return execute({
958
1072
  name: "market_accept", role: "accept", args: { bid_id, agent_id, proof }, id, me, dry: dry_run, vars: { bidId },
959
1073
  read: async () => ({ id, me, self: S.agentId, bidIds: [bidId] }),
960
- plan: async (s, k, first, T) => {
1074
+ plan: async (s, k, first, T, sent) => {
961
1075
  const b = s.c.bids.get(bidId);
962
1076
  if (b && isAddr(b.maker) && b.any && pr == null) {
963
1077
  const got = await originSet(`root=${lc(b.target)}`, T.left);
@@ -966,18 +1080,20 @@ export function registerMarketTools(ctx) {
966
1080
  pr = proofOf(got.set.ids, String(id));
967
1081
  if (pr == null) return { error: "notInBid" };
968
1082
  }
969
- const p = M.acceptPlan(s.c, { addr: k.addr, me, now: s.now, bidId, id, proof: pr || [], shares: k.shares });
1083
+ const p = M.acceptPlan(s.c, { addr: k.addr, me, now: s.now, bidId, id, proof: pr || [], shares: k.shares, ...claimsOf(first, sent) });
970
1084
  if (!p.error && p.net < S.minSell) return { error: "floorNet", net: p.net, floor: S.minSell, and: p.share > 0n ? " and the builder share" : "" };
971
1085
  return p;
972
1086
  },
973
1087
  changed: (p, f) => (p.pins && f.pins && p.pins.minNet !== f.pins.minNet ? M.planWords("fee", {}, "accept") : "the bid or the agent changed since the first read."),
974
1088
  keep: (p) => (p.bond > 0n ? p.bond : null), day: (p) => p.bond, counted: (step, p) => (step === "bond" ? p.bond : 0n),
975
- facts: (p) => [`Accepts bid #${bidId} for #${id}: ${ethers.getAddress(p.maker)} pays ${amt(p.price)} USDG. Fee ${amt(p.fee)}.${p.share > 0n ? ` Builder share ${amt(p.share)}.` : ""} This wallet gets ${amt(p.net)}, and #${id} goes to them at once.${bondWords(p.bond, id)}`],
976
- done: async ({ sent, plan, first, events, T }) => {
1089
+ facts: (p, s) => [`Accepts bid #${bidId} for #${id}: ${ethers.getAddress(p.maker)} pays ${amt(p.price)} USDG. Fee ${amt(p.fee)}.${p.share > 0n ? ` Builder share ${amt(p.share)}.` : ""} This wallet gets ${amt(p.net)}, and #${id} goes to them at once.${bondWords(p.bond, id)}`, ...leaseFacts(p, s, id, CHANGE.market_accept)],
1090
+ done: async ({ sent, plan, first, events, T, missed }) => {
977
1091
  const txs = sent.map((x) => x.hash), ev = events.find((e) => e.name === "BidTaken" && BigInt(e.args.agentId) === id && same(e.args.seller, me) && String(e.args.bidId) === bidId);
1092
+ // the accept, and its steps before it but the claim on the lease (said on its own line, with the one after)
1093
+ const acc = mainStep(sent), before = sent.slice(0, sent.indexOf(acc)).filter((x) => !CLAIMS.has(x.step));
978
1094
  const cash = await usdgOf(me, T.left);
979
- if (!ev) return { text: `${cap1(stageWords("accept", id))} was mined (tx ${txs[txs.length - 1]}), but its receipt carries no BidTaken event for #${id} and bid #${bidId}. ${NOTHING_MORE} market_agent shows who holds it.`, structured: { tool: "market_accept", agentId: String(id), bid: bidId, txs, accepted: null } };
980
- return { text: `Accepted bid #${bidId}. #${id} went to ${ethers.getAddress(ev.args.maker)}. Tx ${txs[txs.length - 1]}${txs.length > 1 ? ` (before it: ${sent.slice(0, -1).map((x) => `${stageWords(x.step, id, x.o)} ${x.hash}`).join(", ")})` : ""}.${cash != null ? ` This wallet holds ${amt(cash)} USDG now.` : ""}${sent.some((x) => x.step === "bond") ? bondWords(first.bond, id, true) : ""}`,
1095
+ if (!ev) return { text: `${cap1(stageWords("accept", id))} was mined (tx ${acc.hash}), but its receipt carries no BidTaken event for #${id} and bid #${bidId}. ${NOTHING_MORE} market_agent shows who holds it.`, structured: { tool: "market_accept", agentId: String(id), bid: bidId, txs, accepted: null } };
1096
+ return { text: [`Accepted bid #${bidId}. #${id} went to ${ethers.getAddress(ev.args.maker)}. Tx ${acc.hash}${before.length ? ` (before it: ${before.map((x) => `${stageWords(x.step, id, x.o)} ${x.hash}`).join(", ")})` : ""}.${cash != null ? ` This wallet holds ${amt(cash)} USDG now.` : ""}${sent.some((x) => x.step === "bond") ? bondWords(first.bond, id, true) : ""}`, ...claimsWords(sent, first, id, CHANGE.market_accept, missed)].join("\n"),
981
1097
  structured: { tool: "market_accept", agentId: String(id), bid: bidId, txs, accepted: true, to: lc(ev.args.maker), usdg: cash == null ? null : amt(cash) } };
982
1098
  },
983
1099
  }, deadline);