@priors/mcp 0.8.5 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # @priors/mcp changelog
2
2
 
3
+ ## 0.9.1 (2026-10-13)
4
+
5
+ - **`stock_line_request` checks the caps against the line the deposit opens.** The deposit is the line's need × 1.3,
6
+ so the vault opens about 1.3 times the line asked for (at most its largest line); the token's cap and the week's room
7
+ were checked against the line asked for, so a 100 USDG request with 110 USDG of room returned a link to a deposit that
8
+ opens 130 USDG, which the vault refuses. The request is now refused when the line the filled deposit opens is over
9
+ either, and the answer names the largest line that fits with the same room for a 23% fall.
10
+ - **`stock_line_request` sizes a named agent at its own loan-to-value**: the vault's `ltvOf(agent, token)`, the token's
11
+ own plus the agent's record bonus, which is what the vault opens its line at. It sized at the token's own, so an agent
12
+ with a bonus was asked for more of the token than its line needs (about 25% more at 75% against 60%). The answer says
13
+ the bonus; when that figure cannot be read, the request is refused rather than sized at the token's own.
14
+ - **`stock_line_request` without `agent_id` no longer turns a failed lookup into a new agent's link.** With a wallet
15
+ configured, a wallet that owns several agent identities, or none, a lookup that failed, or a key that can't be used
16
+ now gives a tool error that asks for `agent_id`; before, the link opened the new-agent deposit, where the owner could
17
+ fund another identity than the agent's. `PRIORS_AGENT_ID` is used when set. Only with no wallet configured (and no
18
+ `PRIORS_AGENT_ID`) is a request without `agent_id` for a new agent.
19
+ - `stock_line_request` refuses an agent whose owner has a default marked on their account (the pool's `ownerDefaults`,
20
+ which `StockVault.open` refuses for every agent of that owner), instead of a link to a sheet that can open nothing.
21
+ - `stock_line_request` names the tab as Go mode shows it (Stock lines, not Backing), and says the pool's grace as it is,
22
+ never rounded up (a 36 h grace reads 1.5 days). `pt_position` names it the same where the vault takes PT-USDG
23
+ behind a line ("Go mode's Stock lines tab").
24
+
25
+ ## 0.9.0 (2026-10-12)
26
+
27
+ - **`stock_line_request`**: when the agent's line is too small for a task, it asks its owner for a line backed by a
28
+ Robinhood stock token the owner holds. It checks the token takes new lines now (its price, holds, the token's cap, the
29
+ vault's room this week) and that the agent can take one, sizes the deposit to the line asked for (line ÷ LTV × 1.3,
30
+ so what the agent can draw holds through a 23% fall), states the cost in cents for a day and a week, says what a
31
+ default would keep as the live vault does it (its fair-default buffer, or the whole deposit), and returns a Go mode
32
+ link that opens the owner's deposit sheet already filled in. It reads; it never deposits, signs or holds the owner's
33
+ tokens. The same answer as the hosted server's tool (both from `src/stock-line.mjs`).
34
+ - `credit_status` names `stock_line_request` as the way to a bigger line, for an agent without a stock line.
35
+ - On `@priors/x402` 0.7.0.
36
+
3
37
  ## 0.8.5 (2026-10-12)
4
38
 
5
39
  - **Money counts in the UTC day it lands** (GHSA-266h-jfr9-42cx). A call reserved its room in the day it started and
package/README.md CHANGED
@@ -7,8 +7,8 @@ borrow from and repay the agent's own Priors line, and keep its spare USDG saved
7
7
  ## Just reading? Use the hosted server
8
8
 
9
9
  No install and no key: `https://mcp.priors.trade/mcp` (Streamable HTTP) answers the read-only questions (an agent's
10
- record and score, the pool's figures, recent loans, the facilitator's services) from the same public data as
11
- priors.trade. It holds no key and cannot send a transaction.
10
+ record and score, a backer's record, the pool's figures, recent loans, the facilitator's services) from the same public
11
+ data as priors.trade. It holds no key and cannot send a transaction.
12
12
 
13
13
  ```bash
14
14
  claude mcp add --transport http priors https://mcp.priors.trade/mcp
@@ -16,6 +16,13 @@ claude mcp add --transport http priors https://mcp.priors.trade/mcp
16
16
 
17
17
  or, in any client that takes a remote server: `{ "mcpServers": { "priors": { "url": "https://mcp.priors.trade/mcp" } } }`.
18
18
 
19
+ **Show the agent's record** in its README with the badge (its score and loans repaid, red once it has defaulted), its
20
+ own id for `<id>`; Copy badge on `priors.trade/agent?id=<id>` gives the line with the id filled in:
21
+
22
+ ```markdown
23
+ [![Priors record](https://priors.trade/api/badge/<id>.svg)](https://priors.trade/agent?id=<id>)
24
+ ```
25
+
19
26
  This package is the other half: a local server with the agent's wallet behind it, for paying, borrowing and
20
27
  repaying.
21
28
 
@@ -171,7 +178,7 @@ Settings → Developer → Edit Config (`claude_desktop_config.json`), then rest
171
178
  "mcpServers": {
172
179
  "priors": {
173
180
  "command": "npx",
174
- "args": ["-y", "@priors/mcp@0.8.5"],
181
+ "args": ["-y", "@priors/mcp@0.9.1"],
175
182
  "env": {
176
183
  "PRIORS_KEY": "0xYOUR_AGENT_WALLET_KEY",
177
184
  "PRIORS_AGENT_ID": "1234"
@@ -193,7 +200,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
193
200
  "mcpServers": {
194
201
  "priors": {
195
202
  "command": "npx",
196
- "args": ["-y", "@priors/mcp@0.8.5"],
203
+ "args": ["-y", "@priors/mcp@0.9.1"],
197
204
  "env": {
198
205
  "PRIORS_KEY": "${PRIORS_KEY}",
199
206
  "PRIORS_AGENT_ID": "${PRIORS_AGENT_ID:-}"
@@ -206,7 +213,7 @@ A project `.mcp.json` that reads the key from your shell's environment, so the f
206
213
  or, for your user only, from a macOS or Linux terminal:
207
214
 
208
215
  ```sh
209
- (read -rs PRIORS_KEY && umask 077 && mkdir -p ~/.config/priors && rm -f ~/.config/priors/agent.key && printf '%s\n' "$PRIORS_KEY" > ~/.config/priors/agent.key) && claude mcp add priors --scope user -- sh -c 'read -r PRIORS_KEY < "$1" && export PRIORS_KEY && exec npx -y @priors/mcp@0.8.5' priors-mcp ~/.config/priors/agent.key
216
+ (read -rs PRIORS_KEY && umask 077 && mkdir -p ~/.config/priors && rm -f ~/.config/priors/agent.key && printf '%s\n' "$PRIORS_KEY" > ~/.config/priors/agent.key) && claude mcp add priors --scope user -- sh -c 'read -r PRIORS_KEY < "$1" && export PRIORS_KEY && exec npx -y @priors/mcp@0.9.1' priors-mcp ~/.config/priors/agent.key
210
217
  ```
211
218
 
212
219
  It waits for the key without showing it (paste it, then Enter), saves it in a file only you can read, and gives Claude
@@ -262,7 +269,7 @@ to approve a borrow; this package, with the key, pays for APIs. With borrowing o
262
269
  approves each loan in Priors' Go mode. ElizaOS (`@elizaos/plugin-mcp`):
263
270
 
264
271
  ```ts
265
- "priors-wallet": { type: "stdio", command: "npx", args: ["-y", "@priors/mcp@0.8.5"],
272
+ "priors-wallet": { type: "stdio", command: "npx", args: ["-y", "@priors/mcp@0.9.1"],
266
273
  env: { PRIORS_KEY_FILE: "/home/agent/.config/priors/agent-7311.key", PRIORS_AGENT_ID: "7311",
267
274
  PRIORS_MAX_BORROW_USD: "0", PRIORS_MAX_BORROW_DAY_USD: "0", PRIORS_MAX_SPEND_DAY_USD: "1", PRIORS_MAX_PRICE_USD: "0.10",
268
275
  PRIORS_PAY_HOSTS: "api.example.com" } }
@@ -274,7 +281,7 @@ OpenClaw (`mcp.servers`, JSON5) takes the same `command`, `args` and `env`; Herm
274
281
  mcp_servers:
275
282
  priors-wallet:
276
283
  command: npx
277
- args: ["-y", "@priors/mcp@0.8.5"]
284
+ args: ["-y", "@priors/mcp@0.9.1"]
278
285
  env:
279
286
  PRIORS_KEY_FILE: /home/agent/.config/priors/agent-7311.key
280
287
  PRIORS_AGENT_ID: "7311"
@@ -301,7 +308,7 @@ key proves it is there: it signs the ERC-8004 identity registry's `AgentWalletSe
301
308
  agent's).
302
309
 
303
310
  ```sh
304
- PRIORS_KEY_FILE=~/.config/priors/agent-7311.key npx -y @priors/mcp@0.8.5 link-wallet --agent 7311
311
+ PRIORS_KEY_FILE=~/.config/priors/agent-7311.key npx -y @priors/mcp@0.9.1 link-wallet --agent 7311
305
312
  ```
306
313
 
307
314
  It reads the registry's EIP-712 domain and refuses to sign for any other, takes the owner from the chain (`--owner`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@priors/mcp",
3
3
  "mcpName": "io.github.priors-agents/priors",
4
- "version": "0.8.5",
4
+ "version": "0.9.1",
5
5
  "private": false,
6
6
  "description": "MCP server for Priors on Robinhood Chain: pay x402 URLs in USDG, read balances, credit lines and scores, borrow and repay, and buy, sell and redeem PT-USDG. Key from PRIORS_KEY_FILE (a file only you can read) or PRIORS_KEY, never the command line.",
7
7
  "type": "module",
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@modelcontextprotocol/sdk": "^1.30.1",
48
- "@priors/x402": "0.6.5",
48
+ "@priors/x402": "0.7.1",
49
49
  "ethers": "^6.13.4",
50
50
  "undici": "6.29.0",
51
51
  "viem": "^2.56.9",
package/src/server.mjs CHANGED
@@ -86,6 +86,7 @@ import { keyFromEnv, stateDirProblem } from "./key-file.mjs";
86
86
  import { parsePayHosts, hostAllowed, hostKey, guardFetch } from "./pay-hosts.mjs";
87
87
  import { agentOf, dailyLedger, ledgerOwners } from "./daily.mjs";
88
88
  import { shareFacts, factsLine, repaidPost } from "./share.mjs";
89
+ import { stockLineRequest } from "./stock-line.mjs";
89
90
 
90
91
  // @priors/x402 when installed from npm; the sibling package in the monorepo otherwise.
91
92
  async function loadX402() {
@@ -102,6 +103,16 @@ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import
102
103
  const ADDRESSES = JSON.parse(readFileSync(new URL("../deployments/4663.v2.json", import.meta.url), "utf8"));
103
104
  /** The stock tokens the stock vault accepts (a copy of the repository's deployments/stock-assets.4663.json). */
104
105
  const STOCK_ASSETS = JSON.parse(readFileSync(new URL("../deployments/stock-assets.4663.json", import.meta.url), "utf8")).assets;
106
+ // stock_line_request's reads of the stock vault beyond @priors/x402's: the token's cap and open lines, the vault's
107
+ // maxLine, the week's room and its root, the fair default's buffer (an implementation without seizeBufferOf keeps
108
+ // the whole deposit on a default: null), and a named agent's loan-to-value (ltvOf: the token's own plus its record bonus)
109
+ const STOCK_LINE_ABI = [
110
+ "function params() view returns (uint256 ltvBps, uint256 maxLine, uint256 epochCap, uint64 epochLength)", "function epochRoom() view returns (uint256)", "function agentId() view returns (uint256)",
111
+ "function openLinesOf(address token) view returns (uint256)", "function seizeBufferOf(address token) view returns (uint256)", "function ltvOf(uint256 id, address token) view returns (uint256)",
112
+ "function assets(address token) view returns (address feed, uint64 maxAge, uint8 tokenDecimals, uint8 feedDecimals, bool enabled, uint16 ltvBps, uint128 lineCap)",
113
+ ];
114
+ // Go mode's account page, where the owner reviews what the agent asked for (the hosted server's APP_URL)
115
+ const GO_APP_URL = "https://go.priors.trade/account";
105
116
  const DEFAULT_PAY_MAX_USD = 0.1;
106
117
 
107
118
  /** A private key (64 hex, optional 0x) anywhere in a string: refused on the command line. */
@@ -681,6 +692,32 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
681
692
  status: (id) => C.creditStatus(contracts, id),
682
693
  stockAssets: () => C.stockAssets(contracts, STOCK_ASSETS),
683
694
  stockPosition: (id) => C.stockPosition(contracts, id, STOCK_ASSETS),
695
+ // stock_line_request's inputs, shaped as the hosted server reads them from /api/stocks (sdk/stock-line.mjs)
696
+ stockLineInputs: async (symbol, id) => {
697
+ if (!addresses.stockVault) throw new ToolError("Priors has no stock vault configured: stock lines are not open.");
698
+ const v = new ethers.Contract(addresses.stockVault, STOCK_LINE_ABI, provider);
699
+ const meta = STOCK_ASSETS.find((a) => a.symbol.toUpperCase() === symbol) || null;
700
+ const [vp, room, root, pp] = await Promise.all([v.params(), v.epochRoom(), v.agentId(), contracts.pool.getParams()]);
701
+ let asset = null, agentLtv = null;
702
+ if (meta) {
703
+ // a named agent's own loan-to-value, its record bonus included: the vault opens its line at that, not the token's
704
+ // own (ltvOf(0, token), the stockAssets figure); unread, null, and the request is refused (sdk stock-line.mjs)
705
+ const [[x], a, lines, buffer, ltv] = await Promise.all([C.stockAssets(contracts, [meta]), v.assets(meta.token), v.openLinesOf(meta.token), v.seizeBufferOf(meta.token).catch(() => null),
706
+ id != null ? v.ltvOf(BigInt(id), meta.token).catch(() => null) : null]);
707
+ asset = { symbol: meta.symbol, name: meta.name, token: meta.token, answer: x.answer, decimals: meta.decimals, feedDecimals: meta.feedDecimals, ltvBps: x.ltvBps, usable: !!x.usable, hold: Number(x.hold || 0), holdReason: x.holdReason || "", lineCap: a.lineCap, openLines: lines, seizeBufferBps: buffer };
708
+ agentLtv = ltv;
709
+ }
710
+ let agent = null;
711
+ if (id != null) {
712
+ const st = await C.creditStatus(contracts, id);
713
+ // a default marked on the owner's account (the pool's ownerDefaults): StockVault.open refuses every agent of it
714
+ // the owner unread is never "no default on the owner's account" (review 2026-10-13): refused, try again
715
+ if (!st.owner) throw new ToolError(`Agent #${Number(id)}'s owner couldn't be read from the chain just now, so whether its owner has a default can't be told: try again in a minute.`);
716
+ const ownerDefaulted = (await contracts.pool.ownerDefaults(st.owner)) > 0n;
717
+ agent = { id: Number(id), defaulted: !!st.defaulted, ownerDefaulted, isRoot: !!st.isRoot, sponsor: Number(st.sponsor), activeLoans: st.openLoans.length, stockLine: !!st.collateral, ltvBps: agentLtv };
718
+ }
719
+ return { asset, vault: { maxLine: vp.maxLine, epochRoom: room, root: Number(root) }, pool: { feeBps: pp.feeBps, minLoan: pp.minLoan, graceDays: Number(pp.grace) / 86400 }, agent, count: STOCK_ASSETS.length };
720
+ },
684
721
  quote: (id, amount, term) => C.quoteBorrow(contracts, id, amount, term),
685
722
  borrow: (id, amount, term) => C.borrowLine(contracts, wallet, id, amount, term),
686
723
  repay: (loanId) => C.repayLoan(contracts, wallet, loanId),
@@ -1063,6 +1100,8 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
1063
1100
  ];
1064
1101
  if (s.openLoans.length === 0) lines.push("Open loans: none.");
1065
1102
  for (const l of s.openLoans) lines.push(`Open loan #${l.loanId}: ${usd(l.principal)} + fee ${usd(l.fee)} = ${usd(l.due)}, due ${when(l.dueAt)}${Date.now() / 1000 > l.dueAt ? " (PAST DUE: repay now)" : ""}.`);
1103
+ // the way to a bigger line when a task needs one (once per task: the tool's own rule)
1104
+ if (!s.defaulted && !s.isRoot && !s.collateral && contracts.stockVault) lines.push("A task that needs more than this line: stock_line_request asks the agent's owner for a line backed by a Robinhood stock token they hold.");
1066
1105
  lines.push(...(await autopayLines(id)));
1067
1106
  // The day's limits (0.8.0) for the agent this server acts for: what is used today, across restarts and sessions.
1068
1107
  if (ledger && (agent_id === undefined || BigInt(agent_id) === dayAgent)) {
@@ -1110,6 +1149,37 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
1110
1149
  return [`Agent #${id}: stock line of ${usd(p.line)}, ${p.status}.`, collateralText(p)].join("\n");
1111
1150
  });
1112
1151
 
1152
+ // ---- stock_line_request: the agent asks its owner for a stock-backed line (the hosted server's tool, the same answer:
1153
+ // sdk/stock-line.mjs). It reads; it never deposits, signs or holds the owner's tokens.
1154
+ tool("stock_line_request", {
1155
+ title: "Ask the owner for a stock-backed line",
1156
+ description: "When the agent's Priors line is too small for a task, ask its owner for a line backed by a Robinhood stock token the owner holds: checks the token takes new lines now (price, holds, caps, the week's room, against the line the deposit opens) and the agent can take one, sizes the deposit to the line asked for at the agent's own loan-to-value (its record bonus included), with room for a 23% fall, states the cost in cents for a day and a week and what a default would keep, and returns a Go mode link that opens the owner's deposit sheet already filled in. Nothing is deposited or signed by this tool. Ask once per task, and only for what the task needs. agent_id defaults to the configured agent (PRIORS_AGENT_ID, or the one identity minted to the configured wallet); when a wallet is configured and its agent can't be told, the call fails and asks for agent_id. Without agent_id and with no wallet configured, the request is for a new agent.",
1157
+ inputSchema: {
1158
+ agent_id: z.number().int().nonnegative().optional().describe("The agent the line is for (an ERC-8004 id); default: PRIORS_AGENT_ID or the configured wallet's agent (an error asks for agent_id when that can't be told), or a new agent when no wallet is configured."),
1159
+ symbol: z.string().min(1).max(12).describe("The stock token's ticker, e.g. SPY (stock_assets lists them)."),
1160
+ line_usd: z.number().positive().max(1_000_000).describe("The line wanted, in USDG (lines are capped at the vault's maxLine, 500 today)."),
1161
+ reason: z.string().max(200).optional().describe("Why the agent needs it, in one sentence, for its owner."),
1162
+ },
1163
+ annotations: { readOnlyHint: true, openWorldHint: true },
1164
+ }, async ({ agent_id, symbol, line_usd, reason }) => {
1165
+ // agent_id, else the configured agent: PRIORS_AGENT_ID, or the one identity minted to the configured wallet. A wallet
1166
+ // whose agent can't be told (several, none, the lookup failing, a key that can't be used) is a tool error that asks
1167
+ // for agent_id: a new agent's link would have the owner fund another identity than the agent's. Only with no wallet
1168
+ // and no PRIORS_AGENT_ID is the request for a new agent (null).
1169
+ let id = agent_id ?? null;
1170
+ if (agent_id === undefined) {
1171
+ const ask = "Pass agent_id, the agent the line is for: with a wallet configured, a request without it is never taken as one for a new agent.";
1172
+ if (env.PRIORS_AGENT_ID || wallet) {
1173
+ try { id = Number(await resolveAgent()); } catch (e) { throw new ToolError(e instanceof ToolError ? `${e.message.replace(/ Set PRIORS_AGENT_ID or pass agent_id\.$/, "")} ${ask}` : `This wallet's agent could not be looked up just now (${explain(e)}). ${ask}`); }
1174
+ } else if (keyProblem) throw new ToolError(`The configured wallet can't be used (${keyProblem}), so its agent can't be looked up. ${ask}`);
1175
+ }
1176
+ const want = String(symbol).trim().toUpperCase();
1177
+ const inp = await credit.stockLineInputs(want, id);
1178
+ const r = stockLineRequest({ ...inp, lineUsd: line_usd, reason, appUrl: GO_APP_URL, asOf: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), symbol });
1179
+ if (r.refusal) throw new ToolError(r.refusal);
1180
+ return r.text;
1181
+ });
1182
+
1113
1183
  // ---- score_of ------------------------------------------------------------------------------------------------
1114
1184
  // Priors Score v2 (open weights, published at /api/score-v2) next to the on-chain v1: optional. Not published
1115
1185
  // (404/503), slow or unreachable means v1 only, never a tool error; a defaulted agent never shows a positive v2.
@@ -1573,7 +1643,7 @@ export async function createPriorsMcpServer({ env = process.env, fetchImpl = glo
1573
1643
  ? `It also holds ${nf(m.balanceText)} PT-USDG of the market that matured on ${m.maturity.slice(0, 10)} (token ${m.token}): it redeems 1:1 for USDG now (pt_redeem with market ${m.market}).`
1574
1644
  : `It also holds ${nf(m.balanceText)} PT-USDG of an earlier market (token ${m.token}): it redeems 1:1 for USDG from ${m.maturity.slice(0, 10)}.`));
1575
1645
  const listingLine = (l) => (!l ? "The stock vault's listing could not be read just now."
1576
- : l.backsLines ? `The Priors stock vault takes PT-USDG behind an agent's line now, at up to ${l.ltvBps / 100}% of its value (all PT-USDG lines share one ${capText(l.lineCap)} cap): deposit it with the SDK's openPtLine(agentId, amount) or in Go mode's Backing tab.`
1646
+ : l.backsLines ? `The Priors stock vault takes PT-USDG behind an agent's line now, at up to ${l.ltvBps / 100}% of its value (all PT-USDG lines share one ${capText(l.lineCap)} cap): deposit it with the SDK's openPtLine(agentId, amount) or in Go mode's Stock lines tab.`
1577
1647
  : l.listed ? "The Priors stock vault lists PT-USDG but takes no new line on it now (disabled, or the shared cap is used up)."
1578
1648
  : `The Priors stock vault does not list PT-USDG yet. Once it does, PT-USDG backs an agent's line (planned: up to ${l.planned.ltvBps / 100}% of its value, one ${capText(BigInt(l.planned.lineCap))} cap for all PT-USDG lines).`);
1579
1649
  const slippage = z.number().int().min(0).max(500).optional().describe("Slippage margin in basis points under the quote, 0 to 500. Default 100 (1%), 10 for a redemption.");
@@ -0,0 +1,194 @@
1
+ // A stock line sized from the line it needs (docs/research/2026-10-12-scale-rwa/PLAN.md W1-W2): how much of a token to
2
+ // deposit for a line of L USDG, what that line costs in cents, and the default rule in words. Pure: no chain, no
3
+ // network; every figure in the units the contracts use (USDG 6 decimals, the token's own, the feed's own).
4
+ // One file for every place that says it:
5
+ // - the hosted MCP's stock_line_request (mcp-worker/tools.mjs);
6
+ // - the local MCP's (packages/mcp/src/stock-line.mjs, a copy that scripts/test-packages.mjs checks is identical);
7
+ // - Go mode's deposit sheet (web-src/priors-app.mjs: PriorsApp.stockLine).
8
+ // The vault (src/StockVault.sol open, _valueOf) values `amount` tokens at floor(amount × price ÷ 10^(token + feed − 6))
9
+ // and opens a line of floor(value × ltv ÷ 10,000), at most maxLine; the quote it runs at Deposit is the last word.
10
+
11
+ /** The deposit is the line's need × 1.3: the borrow room stays whole through a 23% fall (1 − 1 ÷ 1.3). */
12
+ export const HEADROOM_BPS = 13_000n;
13
+ /** The two costs a sheet shows: a day and a week. */
14
+ export const COST_DAYS = [1, 7];
15
+
16
+ const big = (x) => (typeof x === "bigint" ? x : BigInt(x));
17
+ const ceilDiv = (a, b) => (a + b - 1n) / b;
18
+
19
+ /** The smallest amount of the token the vault values at `usdg` (6 decimals) or more at `price`. */
20
+ export function tokensFor(usdg, price, tokenDecimals, feedDecimals) {
21
+ usdg = big(usdg); price = big(price);
22
+ if (price <= 0n) throw new RangeError("tokensFor: a price above zero");
23
+ const scale = Number(tokenDecimals) + Number(feedDecimals);
24
+ return scale >= 6 ? ceilDiv(usdg * 10n ** BigInt(scale - 6), price) : ceilDiv(usdg, price * 10n ** BigInt(6 - scale));
25
+ }
26
+
27
+ /** What the vault values `amount` of the token at (USDG, 6 decimals): its own rounding, down. */
28
+ export function valueOf(amount, price, tokenDecimals, feedDecimals) {
29
+ const scale = Number(tokenDecimals) + Number(feedDecimals);
30
+ return scale >= 6 ? (big(amount) * big(price)) / 10n ** BigInt(scale - 6) : big(amount) * big(price) * 10n ** BigInt(6 - scale);
31
+ }
32
+
33
+ /**
34
+ * The deposit for a line of `line` USDG on a token at `price` and `ltvBps` (the token's own, or the agent's with its
35
+ * record bonus): { line (capped at maxLine), needed (the least that opens it), deposit (needed's value × 1.3),
36
+ * capped, keep (the balance left after the deposit, when `balance` is given), short (the balance is under `needed`),
37
+ * tooSmall (under minLoan) }. `deposit` is never above the balance when one is given and covers `needed`; under
38
+ * `needed` the deposit is the whole balance and `short` says the line will be smaller.
39
+ */
40
+ export function sizeStockLine({ line, price, tokenDecimals, feedDecimals, ltvBps, maxLine = null, minLoan = null, balance = null }) {
41
+ let want = big(line);
42
+ const ltv = big(ltvBps);
43
+ if (want <= 0n) throw new RangeError("sizeStockLine: a line above zero");
44
+ if (ltv <= 0n || ltv > 10_000n) throw new RangeError("sizeStockLine: an LTV between 1 and 10,000 bps");
45
+ const capped = maxLine != null && want > big(maxLine);
46
+ if (capped) want = big(maxLine);
47
+ const neededValue = ceilDiv(want * 10_000n, ltv);
48
+ const needed = tokensFor(neededValue, price, tokenDecimals, feedDecimals);
49
+ let deposit = tokensFor(ceilDiv(neededValue * HEADROOM_BPS, 10_000n), price, tokenDecimals, feedDecimals);
50
+ let keep = null, short = false;
51
+ if (balance != null) {
52
+ const bal = big(balance);
53
+ short = bal < needed;
54
+ if (deposit > bal) deposit = bal;
55
+ keep = bal - deposit;
56
+ }
57
+ const opens = (valueOf(deposit, price, tokenDecimals, feedDecimals) * ltv) / 10_000n;
58
+ const lineOpened = maxLine != null && opens > big(maxLine) ? big(maxLine) : opens;
59
+ return { line: want, needed, deposit, capped, keep, short, lineOpened, tooSmall: minLoan != null && lineOpened < big(minLoan) };
60
+ }
61
+
62
+ /** The pool's fee on `line` USDG held `days` days: line × feeBps × days ÷ (30 × 10,000), rounded up (USDG units). */
63
+ export function lineFee(line, feeBps, days) {
64
+ return ceilDiv(big(line) * big(feeBps) * BigInt(days), 30n * 10_000n);
65
+ }
66
+
67
+ /** USDG units in dollars and cents: the nearest cent, half up; "$0.01" for anything above zero that rounds to 0. */
68
+ export function cents(units) {
69
+ units = big(units);
70
+ let c = (units + 5_000n) / 10_000n;
71
+ if (c === 0n && units > 0n) c = 1n;
72
+ return `$${(c / 100n).toLocaleString("en-US")}.${String(c % 100n).padStart(2, "0")}`;
73
+ }
74
+
75
+ /** The line's cost for each of COST_DAYS: [{ days, fee (USDG units), text ("$0.03") }]. */
76
+ export const lineCosts = (line, feeBps, days = COST_DAYS) => days.map((d) => { const fee = lineFee(line, feeBps, d); return { days: d, fee, text: cents(fee) }; });
77
+
78
+ /** The vault's default rule, from its buffer (bps) for the token: null when the vault has no buffer (an implementation
79
+ * from before the fair default, whose default keeps the whole deposit). */
80
+ export function defaultRule(bufferBps, graceDays = 3) {
81
+ if (bufferBps == null) return { kind: "all", bufferBps: null, text: `If a loan is still unpaid ${graceDays} days after it was due, the vault keeps the whole deposit. A falling price never sells it.` };
82
+ const pct = Number(big(bufferBps)) / 100;
83
+ return { kind: "fair", bufferBps: big(bufferBps), text: `If a loan is still unpaid ${graceDays} days after it was due, the vault keeps tokens worth what is owed plus ${pct}% and gives the rest back (it keeps them all if the stock's price can't be used that day). A falling price never sells it.` };
84
+ }
85
+
86
+ // ---- stock_line_request: an agent asks its owner for a stock line (both MCP servers) ----
87
+
88
+ /** Token units rounded up at `max` decimal places (of a `decimals`-decimal token): the figure a sheet fills. */
89
+ export function upAt(units, decimals, max = 6) {
90
+ const d = Number(decimals), cut = d > max ? 10n ** BigInt(d - max) : 1n;
91
+ return ((big(units) + cut - 1n) / cut) * cut;
92
+ }
93
+ /** Token units as a decimal string, rounded up at `max` places: what the link fills is never short of the figure said. */
94
+ export function tokenText(units, decimals, max = 6) {
95
+ const d = Number(decimals), up = upAt(units, d, max), base = 10n ** BigInt(d);
96
+ const frac = (up % base).toString().padStart(d, "0").slice(0, Math.min(d, max)).replace(/0+$/, "");
97
+ return `${up / base}${frac ? "." + frac : ""}`;
98
+ }
99
+ const usd = (units) => { const u = big(units), w = u / 1_000_000n, f = (u % 1_000_000n).toString().padStart(6, "0").replace(/0+$/, ""); return `${w}${f ? "." + f.slice(0, 6) : ""}`; };
100
+ const oneLine = (s, n) => String(s ?? "").replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim().slice(0, n);
101
+
102
+ /** Go mode's link for the request: the Stock lines tab's deposit sheet on that token, for that agent, sized to that line
103
+ * (web/account-stocks.js reads ai=stock once). It carries nothing to sign: the owner's own Deposit click does it all. */
104
+ export function stockLink(appUrl, { agentId = null, symbol, line }) {
105
+ const u = new URL(appUrl);
106
+ u.searchParams.set("ai", "stock");
107
+ if (agentId != null) u.searchParams.set("ai_agent", String(agentId));
108
+ u.searchParams.set("ai_token", symbol);
109
+ u.searchParams.set("ai_usd", usd(line));
110
+ u.hash = "ac-stocks";
111
+ return u.href;
112
+ }
113
+
114
+ /**
115
+ * The answer to stock_line_request, the same in both MCP servers: { refusal } when the line can't open now (and why,
116
+ * in words), else { data, text }. Inputs, read by each server its own way:
117
+ * asset { symbol, name, token, answer, decimals, feedDecimals, ltvBps, usable, hold, holdReason, lineCap, openLines,
118
+ * seizeBufferBps } (null: not a token the vault takes; ltvBps the token's own, ltvOf(0, token)); vault {
119
+ * maxLine, epochRoom, root }; pool { feeBps, minLoan, graceDays }; agent { id, defaulted, ownerDefaulted (a default
120
+ * marked on its owner's account: the pool's ownerDefaults, which StockVault.open refuses for every agent of that
121
+ * owner), isRoot, sponsor, activeLoans, stockLine, ltvBps } or null (a new agent), where ltvBps is the vault's
122
+ * ltvOf(id, token), the token's own plus the agent's record bonus: what the vault opens its line at (null when it
123
+ * could not be read: refused, since the token's own would ask the owner for more than the line needs); lineUsd (a
124
+ * number of dollars), reason (the agent's own words, kept in this answer only), appUrl, count (the tokens the vault
125
+ * takes, for the refusal), asOf.
126
+ * The caps (the token's, with its open lines; the week's room) hold the line the deposit opens, not the line asked for:
127
+ * the deposit the link fills (× 1.3, rounded up at 6 places) opens about 1.3 times the ask, at most maxLine. When that
128
+ * is over a cap the request is refused, naming the largest ask whose deposit still fits: the link never fills a
129
+ * deposit the vault would refuse, and never one with less room for a fall than it says.
130
+ */
131
+ export function stockLineRequest({ asset, vault, pool, agent = null, lineUsd, reason = "", appUrl, count = null, asOf = null, symbol = "" }) {
132
+ const n = Number(lineUsd);
133
+ if (!(n > 0) || n > 1_000_000) return { refusal: "line_usd must be above 0 and at most 1,000,000." };
134
+ const units = BigInt(Math.round(n * 1e6));
135
+ if (Math.abs(Number(units) / 1e6 - n) > 1e-9) return { refusal: "line_usd has more than 6 decimals (USDG has 6)." };
136
+ if (!asset) return { refusal: `${oneLine(symbol, 12) || "That token"} is not among the ${count ?? "listed"} tokens the Priors stock vault takes.` };
137
+ const sym = asset.symbol;
138
+ if (agent) {
139
+ if (agent.defaulted) return { refusal: `Agent #${agent.id} has defaulted: no new line can open for it.` };
140
+ if (agent.ownerDefaulted) return { refusal: `A default on the account that owns agent #${agent.id} stops new lines and loans for all its agents: no new line can open for it.` };
141
+ if (agent.isRoot) return { refusal: `Agent #${agent.id} is a backer (root): backers lend their stake, they do not borrow.` };
142
+ if (agent.stockLine) return { refusal: `Agent #${agent.id} already has a stock line. Its owner can add stock to it in Go mode (Stock lines tab, Add stock) to raise what it can draw.` };
143
+ if (agent.sponsor && String(agent.sponsor) !== String(vault.root) && Number(agent.activeLoans) > 0) return { refusal: `Agent #${agent.id} has ${agent.activeLoans} loan(s) open on its line from backer #${agent.sponsor}. A stock line takes over the agent's backing (one backer per agent), so those loans are repaid first.` };
144
+ }
145
+ if (!asset.usable || Number(asset.hold || 0) !== 0) return { refusal: `The vault opens no new line on ${sym} right now${asset.holdReason ? `: ${asset.holdReason}` : " (its price is not usable now)"}. stock_assets lists the tokens that take new lines.` };
146
+ if (asset.lineCap != null && big(asset.lineCap) === 0n) return { refusal: `The vault takes no new line on ${sym} (its cap is 0). stock_assets lists the tokens that take new lines.` };
147
+ if (agent && agent.ltvBps == null) return { refusal: `Agent #${agent.id}'s loan-to-value on ${sym} (the token's own plus its record bonus) could not be read from the chain just now, so the deposit cannot be sized: try again in a minute.` };
148
+ const ltvBps = big(agent ? agent.ltvBps : asset.ltvBps), ownBps = big(asset.ltvBps);
149
+ if (ltvBps <= 0n) return { refusal: `The vault takes no new line on ${sym} (its loan-to-value is 0). stock_assets lists the tokens that take new lines.` };
150
+ const sizing = { price: asset.answer, tokenDecimals: asset.decimals, feedDecimals: asset.feedDecimals, ltvBps, maxLine: vault.maxLine ?? null, minLoan: pool.minLoan ?? null };
151
+ const sized = sizeStockLine({ line: units, ...sizing });
152
+ if (pool.minLoan != null && sized.line < big(pool.minLoan)) return { refusal: `A line is at least ${usd(pool.minLoan)} USDG (the pool's smallest loan).` };
153
+ // the line the vault opens for the deposit the link fills (rounded up at 6 places, as said): what every cap holds
154
+ const opens = (line) => {
155
+ const v = (valueOf(upAt(sizeStockLine({ line, ...sizing }).deposit, asset.decimals), asset.answer, asset.decimals, asset.feedDecimals) * ltvBps) / 10_000n;
156
+ return vault.maxLine != null && v > big(vault.maxLine) ? big(vault.maxLine) : v;
157
+ };
158
+ const opened = opens(sized.line);
159
+ const tokenLeft = asset.lineCap != null && asset.openLines != null ? (big(asset.lineCap) > big(asset.openLines) ? big(asset.lineCap) - big(asset.openLines) : 0n) : null;
160
+ const weekLeft = vault.epochRoom != null ? big(vault.epochRoom) : null;
161
+ if ((tokenLeft != null && opened > tokenLeft) || (weekLeft != null && opened > weekLeft)) {
162
+ const room = tokenLeft == null ? weekLeft : weekLeft == null || tokenLeft < weekLeft ? tokenLeft : weekLeft;
163
+ // the largest ask whose deposit opens within the room (opens() never falls as the ask grows), to the cent below
164
+ let lo = 0n, hi = sized.line;
165
+ while (lo < hi) { const mid = (lo + hi + 1n) / 2n; if (opens(mid) <= room) lo = mid; else hi = mid - 1n; }
166
+ const fit = lo - (lo % 10_000n);
167
+ const fits = fit > 0n && (pool.minLoan == null || fit >= big(pool.minLoan));
168
+ const deposit = `the deposit for a ${usd(sized.line)} USDG line, with room for a 23% fall, opens ${usd(opened)} USDG`;
169
+ if (tokenLeft != null && opened > tokenLeft) return { refusal: `${sym} lines share a cap of ${usd(asset.lineCap)} USDG and ${usd(tokenLeft)} USDG of it is left, and ${deposit}: ${fits ? `ask for at most ${usd(fit)} USDG, or another token` : "ask for another token"}.` };
170
+ return { refusal: `The vault opens at most ${usd(weekLeft)} USDG of new lines more this week, and ${deposit}: ${fits ? `ask for at most ${usd(fit)} USDG, or later` : "ask later"}.` };
171
+ }
172
+ const costs = lineCosts(sized.line, pool.feeBps);
173
+ // the grace in days as the pool has it, never rounded up (a 36 h grace is 1.5 days, not 2): down to a tenth
174
+ const rule = defaultRule(asset.seizeBufferBps ?? null, Math.floor(Number(pool.graceDays ?? 3) * 10) / 10);
175
+ const approvalUrl = stockLink(appUrl, { agentId: agent ? agent.id : null, symbol: sym, line: sized.line });
176
+ const price = Number(big(asset.answer)) / 10 ** Number(asset.feedDecimals);
177
+ const why = oneLine(reason, 200);
178
+ const moves = agent && agent.sponsor && String(agent.sponsor) !== String(vault.root);
179
+ const data = {
180
+ kind: "stock_line_request", agentId: agent ? agent.id : null, symbol: sym, token: asset.token, lineUsd: usd(sized.line), capped: sized.capped,
181
+ price: price.toFixed(2), ltvBps: Number(ltvBps), neededTokens: tokenText(sized.needed, asset.decimals), depositTokens: tokenText(sized.deposit, asset.decimals),
182
+ lineOpenedUsd: usd(opened), costs: costs.map((c) => ({ days: c.days, usd: c.text.slice(1) })), feeBps: Number(pool.feeBps),
183
+ defaultRule: { kind: rule.kind, bufferBps: rule.bufferBps == null ? null : Number(rule.bufferBps) }, approvalUrl, reason: why || null, asOf,
184
+ };
185
+ const who = agent ? `Agent #${agent.id}` : "A new agent";
186
+ const text = [
187
+ `${who} asks its owner for a ${data.lineUsd} USDG line backed by ${sym}${sized.capped ? ` (lines are capped at ${usd(vault.maxLine)} USDG)` : ""}${why ? `. The agent's reason: "${why}"` : ""}.`,
188
+ `At $${data.price} and ${data.ltvBps / 100}% of its value${ltvBps > ownBps ? ` (${sym}'s own ${Number(ownBps) / 100}%, plus ${Number(ltvBps - ownBps) / 100}% for agent #${agent.id}'s record)` : ""}, the line needs at least ${data.neededTokens} ${sym}. The link fills ${data.depositTokens} ${sym} (1.3 times that), so what the agent can draw holds through a 23% fall; the owner keeps the rest of their ${sym}.`,
189
+ `Cost: borrowing the whole ${data.lineUsd} USDG costs about ${costs.map((c) => `${c.text} for ${c.days === 1 ? "a day" : c.days === 7 ? "a week" : `${c.days} days`}`).join(" or ")} (${data.feeBps / 100}% per 30 days), plus any backer premium.`,
190
+ `${rule.text} A default also stops new lines for every agent of that owner.${moves ? ` The agent's current line from backer #${agent.sponsor} moves to the stock vault when this one opens.` : ""}`,
191
+ `Nothing moves until the owner deposits, signed in to Go mode, where the vault's own quote is shown first: ${approvalUrl}`,
192
+ ].join("\n");
193
+ return { data, text };
194
+ }