@priors/mcp 0.20.1 → 0.21.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/books.mjs ADDED
@@ -0,0 +1,231 @@
1
+ // The books of one agent, and the treasury's rules that need no chain (docs/AGENT-TREASURY-SPEC.md, sections 2 and 3):
2
+ // what it holds, what it owes, what it earns and its record, each figure with where it comes from and when. Pure, with
3
+ // no import: the data Worker's GET /api/agent/<id>/books builds the books from what it reads (data-worker/books.mjs),
4
+ // and @priors/mcp's treasury tools from their own reads (packages/mcp/src/books.mjs is this file byte for byte;
5
+ // scripts/test-books.mjs checks it). Nothing here signs, sends or reads.
6
+ //
7
+ // Amounts are decimal strings in the token's own units ("12.5"), values decimal strings in USDG (6 decimals), so no
8
+ // figure goes through a float. A token with no Chainlink feed is shown by its amount with no value, never as a zero; a
9
+ // price is "fresh" by the stock vault's own rule (freshPrice), and a stale one still values the token, marked stale.
10
+ // `holds.noValue` counts what is shown by amount only.
11
+ // [treasury-audit] Version 2 (the audit of 2026-11-26, docs/handoff/2026-11-26-treasury-audit-fixes.md): what it holds is its paying
12
+ // wallet's alone, the wallet it declared in the ERC-8004 registry (setAgentWallet proves it by that wallet's own
13
+ // signature), and only while no other agent shares that wallet (as its owner, or as its paying wallet too); any other
14
+ // wallet (its owner's, or a shared one) is shown apart, with how many agents it serves, out of every total and of its
15
+ // holdings over what it owes now; with no paying wallet declared, or one shared, that figure is null and `why` says so
16
+ // (T5). The board row's figures carry the index's own time (`rowAt`), each token is held to its own age rule, and a
17
+ // total built on a stale price says how many of its figures are (T6). A failed read of the Base float is named (T8).
18
+ // "Cover" is the word for what a backer's stake does: the books say holdings over what it owes now (T9).
19
+ // [/treasury-audit]
20
+
21
+ export const BOOKS_V = 2;
22
+ /** The tokens a treasury holds in step 1: the short-term treasury fund token only (SGOV, a Robinhood stock token). */
23
+ export const TREASURY_SYMBOLS = Object.freeze(["SGOV"]);
24
+ /** The stock vault's price ages for SGOV (ops/2026-10-12-rwa-batch.json, src/StockVault.sol): 26 h while the market
25
+ * trades, never older than 4 days. */
26
+ export const SESSION_MAX_AGE_S = 26 * 3600;
27
+ export const MAX_AGE_S = 4 * 86400;
28
+ const USDG_DECIMALS = 6;
29
+
30
+ /** The stock vault's freshness rule (src/StockVault.sol _fresh), for a feed that sleeps on weekends: at most `session`
31
+ * old, or the week's last price (published on a Friday or Saturday, UTC) until Tuesday 06:00 UTC; never older than
32
+ * `maxAge`, never from the future. `updatedAt` and `now` in seconds. */
33
+ export function freshPrice(updatedAt, now, { maxAge = MAX_AGE_S, session = SESSION_MAX_AGE_S } = {}) {
34
+ const at = Number(updatedAt), t = Number(now);
35
+ if (!Number.isFinite(at) || !Number.isFinite(t) || at <= 0 || at > t) return false;
36
+ const age = t - at;
37
+ if (age > maxAge) return false;
38
+ if (age <= session) return true;
39
+ const day = Math.floor(at / 86400);
40
+ const weekday = (day + 4) % 7; // 0 Sunday ... 5 Friday, 6 Saturday (1 January 1970 was a Thursday)
41
+ if (weekday < 5) return false;
42
+ const tuesday = day + (weekday === 5 ? 4 : 3);
43
+ return t < tuesday * 86400 + 6 * 3600;
44
+ }
45
+
46
+ const big = (v) => {
47
+ if (v == null || v === "") return 0n;
48
+ if (typeof v === "bigint") return v;
49
+ const s = String(v).trim();
50
+ if (!/^-?[0-9]+$/.test(s)) throw new Error(`books: not a whole number of units: ${s}`);
51
+ return BigInt(s);
52
+ };
53
+
54
+ /** `units` with `decimals` as a plain decimal string, trailing zeros cut ("12.5", "0", "-3.25"). */
55
+ export function fmtUnits(units, decimals) {
56
+ const u = big(units), d = Number(decimals);
57
+ const neg = u < 0n, a = neg ? -u : u;
58
+ const s = a.toString().padStart(d + 1, "0");
59
+ const whole = s.slice(0, s.length - d), frac = d ? s.slice(s.length - d).replace(/0+$/, "") : "";
60
+ return `${neg ? "-" : ""}${whole}${frac ? `.${frac}` : ""}`;
61
+ }
62
+
63
+ /** USDG units (6 decimals) of `amount` token units at a Chainlink `answer` with `feedDecimals`. */
64
+ export function valueOf(amount, answer, decimals, feedDecimals) {
65
+ return (big(amount) * big(answer) * 10n ** BigInt(USDG_DECIMALS)) / (10n ** BigInt(decimals) * 10n ** BigInt(feedDecimals));
66
+ }
67
+
68
+ const lc = (a) => String(a || "").toLowerCase();
69
+ const isAddr = (a) => /^0x[0-9a-fA-F]{40}$/.test(String(a || ""));
70
+
71
+ /** A ratio of two unit amounts as a decimal string with two places ("1.25"), null when the divisor is 0. */
72
+ function ratio(a, b) {
73
+ const x = big(a), y = big(b);
74
+ if (y === 0n) return null;
75
+ const r = (x * 100n + y / 2n) / y;
76
+ return fmtUnits(r, 2);
77
+ }
78
+
79
+ /**
80
+ * The books of agent `f.agentId` from facts already read:
81
+ * now seconds; the time the books are for
82
+ * rowAt seconds; when the board index its row comes from was built (the index's timestamp); null when unknown
83
+ * row the board's row for the agent (data-worker/board.mjs boardIndex): owner, defaulted, frozen and line
84
+ * { limit, drawn, available, source, sponsor, collateral } in USDG units; null when the agent is unknown
85
+ * score its published Score v2 (sdk/score-v2.mjs: score, rung, rungName, detail { incomeUsdg, receiptsUsdg,
86
+ * receiptPayers, distinctPayers }); null when there is none
87
+ * loans its open loans as the pool reads them ({ owed, loans: [{ loanId, due, dueAt }] }, units); null unread
88
+ * wallets [{ address, role: "declared" | "owner", agents }]: its paying wallet (the one it declared in the
89
+ * registry) and its owner's, once each (one address given twice is one wallet, "declared", its owner's
90
+ * too); `agents`: how many agents on the board that wallet serves, as owner or paying wallet, this one
91
+ * counted (1 when not given)
92
+ * payingUnread true when the registry's answer for its paying wallet was not read
93
+ * balances { [wallet, lower case]: { usdg, tokens: { [token, lower case]: units } } | null (unread) }
94
+ * assets the priced stock tokens: [{ symbol, name, token, decimals, feedDecimals, answer, updatedAt, maxAge }]
95
+ * (maxAge: the oldest its price may be, in seconds; MAX_AGE_S when not given)
96
+ * unpriced the stock tokens with no feed: [{ symbol, name, token, decimals }]
97
+ * pt PT-USDG: { symbol, token, decimals, feedDecimals, answer, updatedAt, maxAge } | null
98
+ * base its paying wallet's float on Base: { address, usdc, at } | { address, unread, failed } (failed: a read
99
+ * that failed, named in `unread`) | null (not asked)
100
+ * Returns { v, agentId, at, rowAt, owner, defaulted, frozen, wallets: [{ address, role, owner, agents, counted }], holds:
101
+ * { usdg, treasury, stocks, pt, vault, base, value, noValue, stale, treasuryShare }, apart: [{ address, role, agents,
102
+ * usdg, value, stale }], owes, earns, record, holdsOverOwed: { ratio, why }, unread } (see the spec, section 2): `holds`
103
+ * is its paying wallet's (usdg and value null when none counts), `apart` each wallet that doesn't count, with what it
104
+ * holds at feed value (its tokens with no feed not read), and `why` is null, "none-declared", "shared" or "unread".
105
+ */
106
+ export function booksOf(f) {
107
+ const now = Number(f.now);
108
+ const row = f.row || null;
109
+ // [treasury-audit] T5: each wallet once, the paying wallet counted only while no other agent shares it
110
+ const ownerOf = row && isAddr(row.owner) ? lc(row.owner) : null;
111
+ const wallets = [];
112
+ for (const w of f.wallets || []) {
113
+ if (!isAddr(w.address)) continue;
114
+ const agents = Number.isSafeInteger(w.agents) && w.agents > 0 ? w.agents : 1;
115
+ const had = wallets.find((x) => lc(x.address) === lc(w.address));
116
+ if (had) { if (w.role === "declared") had.role = "declared"; else had.owner = true; if (agents > had.agents) had.agents = agents; continue; }
117
+ wallets.push({ address: w.address, role: w.role === "declared" ? "declared" : "owner", owner: w.role !== "declared" || lc(w.address) === ownerOf, agents, counted: false });
118
+ }
119
+ const paying = wallets.find((w) => w.role === "declared") || null;
120
+ if (paying && paying.agents <= 1) paying.counted = true;
121
+ const unread = [];
122
+ if (!paying && f.payingUnread) unread.push("its paying wallet");
123
+ const bal = (w) => (f.balances && Object.prototype.hasOwnProperty.call(f.balances, lc(w.address)) ? f.balances[lc(w.address)] : undefined);
124
+ for (const w of wallets) if (!bal(w)) unread.push(`the balances of ${w.address}`);
125
+ // T6: each token's price held to its own age rule (the vault's maxAge for it), and the stale ones counted
126
+ const freshOf = (a) => freshPrice(a.updatedAt, now, { maxAge: Number(a.maxAge) > 0 ? Number(a.maxAge) : MAX_AGE_S });
127
+ /** What one wallet's balances `b` hold: its USDG, the treasury and the other stock tokens (priced ones at their feed,
128
+ * fresh or marked stale; unpriced ones by amount), PT-USDG at its feed (1e18 = par), and their value. */
129
+ function holdingsOf(b) {
130
+ const units = (t) => big((b.tokens || {})[lc(t)]);
131
+ const usdg = big(b.usdg);
132
+ const treasury = [], stocks = [];
133
+ let held = usdg, noValue = 0, stale = 0, pt = null;
134
+ for (const a of f.assets || []) {
135
+ const u = units(a.token);
136
+ if (u === 0n) continue;
137
+ const priced = a.answer != null && big(a.answer) > 0n;
138
+ const value = priced ? valueOf(u, a.answer, a.decimals, a.feedDecimals) : null;
139
+ if (value != null) held += value; else noValue++;
140
+ const item = {
141
+ symbol: a.symbol, name: a.name || a.symbol, amount: fmtUnits(u, a.decimals),
142
+ value: value == null ? null : fmtUnits(value, USDG_DECIMALS), valuedAt: priced ? Number(a.updatedAt) : null,
143
+ fresh: priced ? freshOf(a) : null,
144
+ };
145
+ if (item.fresh === false) stale++;
146
+ (TREASURY_SYMBOLS.includes(a.symbol) ? treasury : stocks).push(item);
147
+ }
148
+ for (const x of f.unpriced || []) {
149
+ const u = units(x.token);
150
+ if (u === 0n) continue;
151
+ noValue++;
152
+ stocks.push({ symbol: x.symbol, name: x.name || x.symbol, amount: fmtUnits(u, x.decimals), value: null, valuedAt: null, fresh: null });
153
+ }
154
+ if (f.pt) {
155
+ const u = units(f.pt.token);
156
+ if (u > 0n) {
157
+ const priced = f.pt.answer != null && big(f.pt.answer) > 0n;
158
+ const value = priced ? valueOf(u, f.pt.answer, f.pt.decimals, f.pt.feedDecimals) : null;
159
+ if (value != null) held += value; else noValue++;
160
+ pt = { symbol: f.pt.symbol || "PT-USDG", amount: fmtUnits(u, f.pt.decimals), value: value == null ? null : fmtUnits(value, USDG_DECIMALS), valuedAt: priced ? Number(f.pt.updatedAt) : null, fresh: priced ? freshOf(f.pt) : null };
161
+ if (pt.fresh === false) stale++;
162
+ }
163
+ }
164
+ return { usdg, treasury, stocks, pt, held, noValue, stale };
165
+ }
166
+ const mine = paying && paying.counted ? bal(paying) : undefined;
167
+ const h = mine ? holdingsOf(mine) : null;
168
+ let held = h ? h.held : 0n;
169
+ // [/treasury-audit]
170
+ // the tokens in the stock vault behind its line (the board row's collateral), at the vault's own value: shown, and out
171
+ // of its totals, since they are pledged to its line and the totals are what is not (T9)
172
+ let vault = null;
173
+ const col = row && row.line && row.line.collateral;
174
+ if (col && col.amount != null) {
175
+ vault = { symbol: col.symbol, amount: fmtUnits(col.amount, col.decimals), value: col.value == null ? null : fmtUnits(col.value, USDG_DECIMALS), ltvBps: col.ltvBps == null ? null : Number(col.ltvBps), hold: col.hold ? String(col.hold) : null };
176
+ }
177
+ // its paying wallet's USDC float on Base (an externally owned wallet only); a read that failed is named (T8)
178
+ let base = null;
179
+ if (f.base) {
180
+ if (f.base.unread) { base = { wallet: f.base.address, unread: String(f.base.unread) }; if (f.base.failed) unread.push("its float on Base"); }
181
+ else { base = { wallet: f.base.address, usdc: fmtUnits(f.base.usdc, 6), at: Number(f.base.at) }; held += big(f.base.usdc); }
182
+ }
183
+ const treasuryValue = h ? h.treasury.reduce((a, t) => a + (t.value == null ? 0n : unitsOf(t.value)), 0n) : 0n;
184
+
185
+ // what it owes: its line, what is drawn, and each open loan's principal and fee
186
+ const line = row && row.line ? row.line : null;
187
+ let owes = null;
188
+ if (line) {
189
+ owes = {
190
+ line: fmtUnits(line.limit || 0, USDG_DECIMALS), drawn: fmtUnits(line.drawn || 0, USDG_DECIMALS), available: fmtUnits(line.available || 0, USDG_DECIMALS),
191
+ source: line.source == null ? null : String(line.source), sponsor: line.sponsor == null ? null : Number(line.sponsor),
192
+ loans: f.loans ? f.loans.loans.map((l) => ({ loanId: String(l.loanId), due: fmtUnits(l.due, USDG_DECIMALS), dueAt: Number(l.dueAt) })) : null,
193
+ owed: f.loans ? fmtUnits(f.loans.owed, USDG_DECIMALS) : null,
194
+ };
195
+ }
196
+ if (!f.loans) unread.push("its open loans");
197
+ // what it earns: the 30-day x402 income Score v2 counts, and the receipts and payers behind it
198
+ const d = f.score && f.score.detail ? f.score.detail : null;
199
+ const n = (v) => (v == null || !Number.isFinite(Number(v)) ? null : Number(v));
200
+ const earns = d ? { days: 30, incomeUsdg: n(d.incomeUsdg), receiptsUsdg: n(d.receiptsUsdg), payers: n(d.receiptPayers), distinctPayers: n(d.distinctPayers) } : null;
201
+ const record = f.score ? { score: n(f.score.score), rung: n(f.score.rung), rungName: f.score.rungName == null ? null : String(f.score.rungName) } : null;
202
+ // [treasury-audit] its holdings over what it owes now (not pledged to its line), its paying wallet's alone, and the
203
+ // treasury's share of what it holds (T5, T9); every wallet that doesn't count, apart, with what it holds
204
+ const owed = f.loans ? big(f.loans.owed) : null;
205
+ const why = !paying ? (f.payingUnread ? "unread" : "none-declared") : !paying.counted ? "shared" : null;
206
+ const holdsOverOwed = { ratio: h && owed != null ? ratio(held, owed) : null, why };
207
+ const apart = wallets.filter((w) => !w.counted).map((w) => {
208
+ const b = bal(w), x = b ? holdingsOf(b) : null;
209
+ return { address: w.address, role: w.role, agents: w.agents, usdg: x ? fmtUnits(x.usdg, USDG_DECIMALS) : null, value: x ? fmtUnits(x.held, USDG_DECIMALS) : null, stale: x ? x.stale : 0 };
210
+ });
211
+ const rowAt = Number(f.rowAt);
212
+ return {
213
+ v: BOOKS_V, agentId: Number(f.agentId), at: now, rowAt: Number.isSafeInteger(rowAt) && rowAt > 0 ? rowAt : null, owner: row ? row.owner || null : null,
214
+ defaulted: row ? !!row.defaulted : null, frozen: row ? !!row.frozen : null,
215
+ wallets: wallets.map((w) => ({ address: w.address, role: w.role, owner: w.owner, agents: w.agents, counted: w.counted })),
216
+ holds: {
217
+ usdg: h ? fmtUnits(h.usdg, USDG_DECIMALS) : null, treasury: h ? h.treasury : [], stocks: h ? h.stocks : [], pt: h ? h.pt : null, vault, base,
218
+ value: h ? fmtUnits(held, USDG_DECIMALS) : null, noValue: h ? h.noValue : 0, stale: h ? h.stale : 0, treasuryShare: h && held > 0n ? ratio(treasuryValue, held) : null,
219
+ },
220
+ apart, owes, earns, record, holdsOverOwed, unread,
221
+ };
222
+ // [/treasury-audit]
223
+ }
224
+
225
+ /** A decimal string with at most 6 places, back to USDG units. */
226
+ function unitsOf(s) {
227
+ const m = /^(-?)([0-9]+)(?:\.([0-9]{1,6}))?$/.exec(String(s));
228
+ if (!m) throw new Error(`books: not a USDG amount: ${s}`);
229
+ const u = BigInt(m[2]) * 1_000_000n + BigInt((m[3] || "").padEnd(6, "0"));
230
+ return m[1] ? -u : u;
231
+ }
package/src/daily.mjs CHANGED
@@ -15,8 +15,9 @@
15
15
  // leaves its reservation at its most, counted for the rest of that day (as a borrow whose answer was lost stays counted).
16
16
  //
17
17
  // Every call counts in two ledgers and must fit in both. The agent's, "agent-<id>", from PRIORS_AGENT_ID, which a
18
- // daily limit requires: every key and every process acting for that agent shares one count, whichever client it runs
19
- // in (a count named after the wallet when the id was left out split one agent's day in two). And the wallet's,
18
+ // daily limit requires: every key and every process of this package acting for that agent on this state directory
19
+ // shares one count (a count named after the wallet when the id was left out split one agent's day in two; another
20
+ // Priors client, or a server with another state directory, keeps no count here). And the wallet's,
20
21
  // "wallet-<address>": a key run under another agent id, by mistake or for a second agent it controls, still shares
21
22
  // one count of the money it holds. All of a call's files are created before any ledger is listed, so the argument
22
23
  // above holds in each. Money counts in the UTC day it lands (GHSA-266h). A call reserves in the day it starts, and also
@@ -0,0 +1,64 @@
1
+ // Whose agent an address is, from Priors' check API (growth loop batch 20's CJ, docs/builds/2026-11-18-growth-loop-batch20.md
2
+ // criteria 5 and 6): GET /api/check?address= (data-worker/check.mjs) answers every agent that address owns or declared as
3
+ // its payment wallet, each with `matchedAs` ("owner", "declared wallet", or both) and its record. Read by the rule the
4
+ // hosted find_sellers' record follows (mcp-worker/tools.mjs rowOf) and Go mode's Tools line (web/tool-payee.js, batch 19's
5
+ // CG): the agents found, each once, at most three, and "And {n} more." past them.
6
+ // - Each agent found: its id, its agent page, how the address is its (from matchedAs: its declared wallet, its owner's
7
+ // address, or both), its loans repaid, and whether it has defaulted. Never a name here: a caller that shows one fences it.
8
+ // - None found, the check having answered: "Priors has no record for this address.", the same words for every address.
9
+ // - Not read (a failed read, an answer of another shape, or a matchedAs it has no words for): null, so the caller says the
10
+ // check could not be read, never "no record".
11
+ // - Under any list of agents: "A record, not a review. Not an endorsement."
12
+ // No word on the agent, its owner or the payee beyond those facts; no score, no amount, no $PRIORS figure.
13
+ // One source for both servers: the hosted find_agent_by_address imports this file (mcp-worker/tools.mjs, PAYEE_LOOKUP), and
14
+ // @priors/mcp's payee line after pay_url's and pay_gateway's payment (PRIORS_PAYEE_CHECK) imports
15
+ // packages/mcp/src/payee-lookup.mjs, a byte-for-byte copy (scripts/test-payee-lookup-package.mjs fails on any drift).
16
+
17
+ /** The agent page of agent `id` on priors.trade (the check API's own links.page). */
18
+ export const agentPage = (id) => `https://priors.trade/agent?id=${id}`;
19
+ export const NO_RECORD = "Priors has no record for this address.";
20
+ export const NOT_ENDORSED = "A record, not a review. Not an endorsement.";
21
+ /** How many agents an answer names before "And {n} more.". */
22
+ export const SHOWN = 3;
23
+
24
+ /** "wallet", "owner" or "both" from an agent's matchedAs; null for one it has no words for. */
25
+ export function howOf(matchedAs) {
26
+ const as = Array.isArray(matchedAs) ? matchedAs : [], w = as.includes("declared wallet"), o = as.includes("owner");
27
+ return w && o ? "both" : w ? "wallet" : o ? "owner" : null;
28
+ }
29
+
30
+ /**
31
+ * The check's answer for one address (its `agents` array; null when it was not read) as these words read it:
32
+ * { agents: [{ agentId, how, loansRepaid, defaulted, name, matchedAs }] (at most SHOWN), more } when it names an agent,
33
+ * { none: true } when it answered none, and null when it was not read or names an agent in a way there are no words for.
34
+ * `name` is the check's, as it came (a caller cleans and fences it); `matchedAs` the check's, as it came.
35
+ */
36
+ export function payeeReading(agents) {
37
+ if (!Array.isArray(agents)) return null;
38
+ if (agents.some((x) => x && Number.isInteger(x.agentId) && !howOf(x.matchedAs))) return null;
39
+ const seen = new Set(), found = [];
40
+ for (const x of agents) {
41
+ if (!x || !Number.isInteger(x.agentId) || seen.has(x.agentId)) continue;
42
+ seen.add(x.agentId);
43
+ const rec = x.record || {}, n = Number(rec.loansRepaid);
44
+ found.push({ agentId: x.agentId, how: howOf(x.matchedAs), loansRepaid: Number.isSafeInteger(n) && n >= 0 ? n : 0, defaulted: !!rec.defaulted, name: x.name == null ? null : String(x.name), matchedAs: x.matchedAs.map(String) });
45
+ }
46
+ if (!found.length) return { none: true };
47
+ return { agents: found.slice(0, SHOWN), more: found.length - Math.min(SHOWN, found.length) };
48
+ }
49
+
50
+ const HOW = { wallet: "its declared wallet", owner: "its owner's address", both: "its declared wallet, also its owner's address" };
51
+ /** One agent found: "agent #N (its page): the address is its declared wallet; 3 loans repaid, never defaulted." */
52
+ export function agentFacts(x) {
53
+ const loans = `${x.loansRepaid} ${x.loansRepaid === 1 ? "loan" : "loans"} repaid`;
54
+ return `agent #${x.agentId} (${agentPage(x.agentId)}): the address is ${HOW[x.how]}; ${loans}, ${x.defaulted ? "has DEFAULTED" : "never defaulted"}.`;
55
+ }
56
+ /** "And {n} more." past the agents named, or "". */
57
+ export const moreWords = (n) => (n > 0 ? `And ${n} more.` : "");
58
+
59
+ /** @priors/mcp's one line after a payment to `payTo` (PRIORS_PAYEE_CHECK): "" when the check was not read. */
60
+ export function payeeLine(payTo, reading) {
61
+ if (!reading) return "";
62
+ if (reading.none) return `Priors' check of ${payTo}: ${NO_RECORD}`;
63
+ return [`Priors' check of ${payTo}:`, ...reading.agents.map(agentFacts), moreWords(reading.more), NOT_ENDORSED].filter(Boolean).join(" ");
64
+ }