@miraifi/plugin-elizaos 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +83 -2
- package/package.json +29 -4
- package/src/index.mjs +278 -0
- package/src/parse.mjs +67 -0
- package/src/words.mjs +105 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MIRAI contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,84 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @miraifi/plugin-elizaos
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MIRAI for [elizaOS](https://github.com/elizaOS/eliza) agents. Before an agent pays, hires or trusts another ERC-8004
|
|
4
|
+
agent on Robinhood Chain, it can read that agent's [MIRAI](https://miraifi.family) credit record and MIRAI Score. It
|
|
5
|
+
can also quote a loan and prepare unsigned borrow and repay transactions for its owner. The plugin holds no key and
|
|
6
|
+
signs nothing.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @miraifi/plugin-elizaos
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Add it to the character (elizaOS 1.7 or later, including 2.x):
|
|
15
|
+
|
|
16
|
+
```json
|
|
17
|
+
{
|
|
18
|
+
"name": "MyAgent",
|
|
19
|
+
"plugins": ["@elizaos/plugin-sql", "@elizaos/plugin-bootstrap", "@miraifi/plugin-elizaos"],
|
|
20
|
+
"settings": {
|
|
21
|
+
"MIRAI_AGENT_ID": "25754",
|
|
22
|
+
"MIRAI_RECEIVER": "0xYourAgentWallet"
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Every setting is optional and is read from the character first, then the environment:
|
|
28
|
+
|
|
29
|
+
| Setting | What it does |
|
|
30
|
+
|---|---|
|
|
31
|
+
| `MIRAI_API` | MIRAI API base URL (default `https://miraifi.family`) |
|
|
32
|
+
| `MIRAI_RPC` | Robinhood Chain RPC for quotes and loan reads (default the public node) |
|
|
33
|
+
| `MIRAI_AGENT_ID` | this agent's own ERC-8004 id: turns on the `MIRAI_OWN_RECORD` provider |
|
|
34
|
+
| `MIRAI_RECEIVER` | the address a prepared borrow sends USDG to; when set, an address in a message never replaces it |
|
|
35
|
+
| `MIRAI_PAYER` | the payer whose USDG allowance a prepared repayment checks |
|
|
36
|
+
|
|
37
|
+
## Actions
|
|
38
|
+
|
|
39
|
+
Every action answers in words, through the callback and as the action's result text.
|
|
40
|
+
|
|
41
|
+
| Action | What it reads from the message | What it answers |
|
|
42
|
+
|---|---|---|
|
|
43
|
+
| `MIRAI_CHECK_AGENT` | an agent id (`#25754`, `agent 25754`) | loans repaid, USDG repaid, late repayments, any default, line and debt |
|
|
44
|
+
| `MIRAI_AGENT_SCORE` | an agent id | MIRAI Score, floor, each component, what the next floor needs |
|
|
45
|
+
| `MIRAI_AGENT_RECORD` | an agent id | line, backer, every loan with its UTC due date, the grace end of an overdue loan |
|
|
46
|
+
| `MIRAI_QUOTE_LOAN` | agent, amount (`5 USDG`), term (`for 14 days`) | the exact fee and the total to repay |
|
|
47
|
+
| `MIRAI_PREPARE_BORROW` | agent, amount, term, receiving address (or `MIRAI_RECEIVER`) | an UNSIGNED borrow transaction: to, value, data |
|
|
48
|
+
| `MIRAI_PREPARE_REPAY` | a loan id (`loan 12`), optionally the payer | the UNSIGNED approval (when needed) and repayment, in order |
|
|
49
|
+
|
|
50
|
+
On elizaOS 2, each action also declares `parameters`, so the planner's extracted values are used when present.
|
|
51
|
+
Otherwise the values come from the message's own words. Links, code blocks, inline code and anything in braces are
|
|
52
|
+
taken out before an id, an amount or an address is read, so a number in a URL or a pasted JSON object never becomes
|
|
53
|
+
an agent, a price or a receiver. A message naming two different addresses prepares nothing.
|
|
54
|
+
|
|
55
|
+
Example messages:
|
|
56
|
+
|
|
57
|
+
- "Before we pay it, check agent #25754 on MIRAI."
|
|
58
|
+
- "What is agent #25754's MIRAI Score?"
|
|
59
|
+
- "How much does it cost to borrow 5 USDG for 14 days on agent #25754's line?"
|
|
60
|
+
- "Prepare a borrow of 5 USDG for 14 days for agent #25754."
|
|
61
|
+
- "Prepare the repayment of MIRAI loan 12."
|
|
62
|
+
|
|
63
|
+
## Provider
|
|
64
|
+
|
|
65
|
+
`MIRAI_OWN_RECORD` (dynamic) gives the model this agent's own line, debt, open loans with due dates and score when
|
|
66
|
+
`MIRAI_AGENT_ID` is set. It is cached for a minute.
|
|
67
|
+
|
|
68
|
+
## Disclosure
|
|
69
|
+
|
|
70
|
+
- Reads use MIRAI's free public API and Robinhood Chain's public node. No key, no sign-in.
|
|
71
|
+
- Prepared transactions are for the agent's owner, its declared ERC-8004 wallet or an operator to sign in their own
|
|
72
|
+
wallet. The plugin never sends one. Check the receiving address before signing.
|
|
73
|
+
- Agent names are written by their owners: the plugin quotes them as one line of data.
|
|
74
|
+
- A loan unpaid three days after its due date can be marked defaulted, and the default stays on the agent's record.
|
|
75
|
+
|
|
76
|
+
## Test
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
npm install && npm test
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## License
|
|
83
|
+
|
|
84
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@miraifi/plugin-elizaos",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "MIRAI for elizaOS agents: check an ERC-8004 agent's repayment record and MIRAI Score on Robinhood Chain, quote a loan, and prepare unsigned USDG borrow and repay transactions. Holds no key.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.mjs",
|
|
7
|
+
"exports": { ".": "./src/index.mjs", "./package.json": "./package.json" },
|
|
8
|
+
"files": ["src/", "README.md", "LICENSE"],
|
|
9
|
+
"engines": { "node": ">=20.19" },
|
|
10
|
+
"scripts": { "test": "node --test test/*.test.mjs" },
|
|
11
|
+
"dependencies": { "@miraifi/sdk": "^0.1.0" },
|
|
12
|
+
"peerDependencies": { "@elizaos/core": ">=1.7.0" },
|
|
13
|
+
"peerDependenciesMeta": { "@elizaos/core": { "optional": true } },
|
|
14
|
+
"packageType": "plugin",
|
|
15
|
+
"agentConfig": {
|
|
16
|
+
"pluginType": "elizaos:plugin:1.0.0",
|
|
17
|
+
"pluginParameters": {
|
|
18
|
+
"MIRAI_API": { "type": "string", "description": "MIRAI API base URL (default https://miraifi.family)." },
|
|
19
|
+
"MIRAI_RPC": { "type": "string", "description": "Robinhood Chain RPC for quotes and loan reads (default the public node)." },
|
|
20
|
+
"MIRAI_AGENT_ID": { "type": "string", "description": "This agent's own ERC-8004 id, for the MIRAI_OWN_RECORD provider (optional)." },
|
|
21
|
+
"MIRAI_RECEIVER": { "type": "string", "description": "The address a prepared borrow sends USDG to; when set, an address in a message never replaces it (optional)." },
|
|
22
|
+
"MIRAI_PAYER": { "type": "string", "description": "The payer whose USDG allowance a prepared repayment checks (optional)." }
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"keywords": ["mirai", "elizaos", "elizaos-plugin", "plugin", "erc-8004", "ai-agents", "credit", "usdg", "robinhood-chain"],
|
|
26
|
+
"author": "MIRAI contributors",
|
|
27
|
+
"homepage": "https://miraifi.family",
|
|
28
|
+
"repository": { "type": "git", "url": "git+https://github.com/miraifi/mirai.git", "directory": "packages/plugin-elizaos" },
|
|
29
|
+
"bugs": { "url": "https://github.com/miraifi/mirai/issues" },
|
|
30
|
+
"license": "MIT"
|
|
31
|
+
}
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
// @miraifi/plugin-elizaos: MIRAI for elizaOS agents. Six actions and one provider over @miraifi/sdk:
|
|
2
|
+
// check an ERC-8004 agent, its MIRAI Score, its record, quote a loan, and prepare (never send) a borrow or a repayment.
|
|
3
|
+
// The plugin holds no key and signs nothing: a prepared transaction is for the agent owner's own wallet.
|
|
4
|
+
// Every action answers in words, through the callback and as the action's result text.
|
|
5
|
+
import * as defaultSdk from "@miraifi/sdk";
|
|
6
|
+
import { checkWords, scoreWords, recordWords, quoteWords, usdg, when, plural } from "./words.mjs";
|
|
7
|
+
import { agentIdOf, loanIdOf, amountOf, daysOf, addressOf, isAddress } from "./parse.mjs";
|
|
8
|
+
|
|
9
|
+
export const SETTINGS = Object.freeze({
|
|
10
|
+
MIRAI_API: "MIRAI API base URL (default https://miraifi.family)",
|
|
11
|
+
MIRAI_RPC: "Robinhood Chain RPC for quotes and loan reads (default the public node)",
|
|
12
|
+
MIRAI_AGENT_ID: "This agent's own ERC-8004 id, for the MIRAI_OWN_RECORD provider (optional)",
|
|
13
|
+
MIRAI_RECEIVER: "The address a prepared borrow sends USDG to; when set, an address in a message never replaces it (optional)",
|
|
14
|
+
MIRAI_PAYER: "The payer address a prepared repayment checks the USDG allowance of (optional)",
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const textOf = (message) => String(message?.content?.text ?? "");
|
|
18
|
+
const short = (e) => String(e?.shortMessage || e?.reason || e?.message || e).replace(/\s+/g, " ").slice(0, 240);
|
|
19
|
+
|
|
20
|
+
/** A setting from the agent's character (runtime.getSetting), else the process environment. */
|
|
21
|
+
export function settingOf(runtime, key, env = process.env) {
|
|
22
|
+
const v = typeof runtime?.getSetting === "function" ? runtime.getSetting(key) : undefined;
|
|
23
|
+
const s = v === undefined || v === null || v === "" ? env[key] : v;
|
|
24
|
+
return s === undefined || s === null || String(s).trim() === "" ? undefined : String(s).trim();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** An integer parameter the elizaOS 2 planner extracted, if it is one. */
|
|
28
|
+
const param = (options, key) => {
|
|
29
|
+
const v = options?.parameters?.[key];
|
|
30
|
+
return v === undefined || v === null || v === "" ? undefined : v;
|
|
31
|
+
};
|
|
32
|
+
const idParam = (options, key) => {
|
|
33
|
+
const v = param(options, key);
|
|
34
|
+
const x = Number(v);
|
|
35
|
+
return v !== undefined && Number.isInteger(x) && x >= 0 ? x : undefined;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** Builds the plugin. `sdk` replaces @miraifi/sdk (tests); `env` replaces process.env. */
|
|
39
|
+
export function createMiraiPlugin({ sdk = defaultSdk, env = process.env } = {}) {
|
|
40
|
+
const d = sdk.DEPLOYMENTS[sdk.CHAIN_ID || 4663];
|
|
41
|
+
const perRuntime = new WeakMap();
|
|
42
|
+
function miraiOf(runtime) {
|
|
43
|
+
const key = runtime && typeof runtime === "object" ? runtime : perRuntime;
|
|
44
|
+
if (!perRuntime.has(key)) {
|
|
45
|
+
const apiUrl = settingOf(runtime, "MIRAI_API", env) || d.api;
|
|
46
|
+
let client = null;
|
|
47
|
+
perRuntime.set(key, {
|
|
48
|
+
site: apiUrl.replace(/\/+$/, ""),
|
|
49
|
+
api: sdk.api(apiUrl),
|
|
50
|
+
client: () => (client ||= new sdk.MiraiClient({ apiUrl, rpcUrl: settingOf(runtime, "MIRAI_RPC", env) })),
|
|
51
|
+
cache: new Map(),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return perRuntime.get(key);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Answer through the callback and as the action's result. */
|
|
58
|
+
async function answer(callback, action, success, text, data = {}) {
|
|
59
|
+
if (typeof callback === "function") await callback({ text, actions: [action] });
|
|
60
|
+
return { success, text, values: { miraiAnswer: text }, data: { actionName: action, ...data } };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const agentFrom = (message, options) => idParam(options, "agentId") ?? agentIdOf(textOf(message));
|
|
64
|
+
const askAgent = "Which agent? Give its ERC-8004 id on Robinhood Chain, for example agent #25754.";
|
|
65
|
+
const readAction = ({ name, similes, description, keywords, call, words, example }) => ({
|
|
66
|
+
name, similes, description,
|
|
67
|
+
parameters: [{ name: "agentId", description: "The agent's ERC-8004 id on Robinhood Chain", required: true, schema: { type: "integer", minimum: 0 } }],
|
|
68
|
+
validate: async (_runtime, message) => keywords.test(textOf(message)),
|
|
69
|
+
handler: async (runtime, message, _state, options, callback) => {
|
|
70
|
+
const id = agentFrom(message, options);
|
|
71
|
+
if (id == null) return answer(callback, name, false, askAgent);
|
|
72
|
+
const m = miraiOf(runtime);
|
|
73
|
+
try {
|
|
74
|
+
return answer(callback, name, true, words(await call(m, id), m), { agentId: id });
|
|
75
|
+
} catch (e) {
|
|
76
|
+
if (e?.status === 404) return answer(callback, name, true, `Agent #${id} is not known to MIRAI: no ERC-8004 identity or MIRAI record was found for it on Robinhood Chain.`, { agentId: id });
|
|
77
|
+
return answer(callback, name, false, `MIRAI could not be read for agent #${id}: ${short(e)}`, { agentId: id });
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
examples: [example],
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const checkAgent = readAction({
|
|
84
|
+
name: "MIRAI_CHECK_AGENT",
|
|
85
|
+
similes: ["CHECK_AGENT_CREDIT", "AGENT_REPAYMENT_RECORD", "IS_AGENT_TRUSTWORTHY"],
|
|
86
|
+
description: "Check whether an ERC-8004 agent on Robinhood Chain has repaid real money on MIRAI (loans repaid, late repayments, any default, its line and debt) before paying, hiring or trusting it. Needs the agent id, as #25754.",
|
|
87
|
+
keywords: /\b(check|trust|reliab|repa(id|y)|default|credit|record|safe|vet)\w*/i,
|
|
88
|
+
call: (m, id) => m.api.check(id),
|
|
89
|
+
words: (r, m) => checkWords(r, m.site),
|
|
90
|
+
example: [
|
|
91
|
+
{ name: "{{name1}}", content: { text: "Before we pay it, check agent #25754 on MIRAI." } },
|
|
92
|
+
{ name: "{{agentName}}", content: { text: "Agent #25754 on MIRAI: 1 loan repaid (5.023334 USDG), 0 late repayments, never defaulted.", actions: ["MIRAI_CHECK_AGENT"] } },
|
|
93
|
+
],
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
const agentScore = readAction({
|
|
97
|
+
name: "MIRAI_AGENT_SCORE",
|
|
98
|
+
similes: ["MIRAI_SCORE", "AGENT_CREDIT_SCORE", "AGENT_TRUST_SCORE"],
|
|
99
|
+
description: "Read an agent's MIRAI Score (0 to 1000) and floor, every component with its reason, penalties, and what the next floor needs. Points come only from money someone else put at risk on the agent, repaid on time. Needs the agent id.",
|
|
100
|
+
keywords: /\b(score|floor|rating|rank)\w*/i,
|
|
101
|
+
call: (m, id) => m.api.score(id),
|
|
102
|
+
words: (s) => scoreWords(s),
|
|
103
|
+
example: [
|
|
104
|
+
{ name: "{{name1}}", content: { text: "What is agent #25754's MIRAI Score?" } },
|
|
105
|
+
{ name: "{{agentName}}", content: { text: "MIRAI Score of agent #25754: 8 of 1000, floor \"footing\".", actions: ["MIRAI_AGENT_SCORE"] } },
|
|
106
|
+
],
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
const agentRecord = readAction({
|
|
110
|
+
name: "MIRAI_AGENT_RECORD",
|
|
111
|
+
similes: ["MIRAI_RECORD", "AGENT_LOANS", "AGENT_CREDIT_LINE"],
|
|
112
|
+
description: "Read an agent's MIRAI record: its line, what it owes and has available, its backer, and every loan with its due date; for an overdue loan, when its grace ends. Needs the agent id.",
|
|
113
|
+
keywords: /\b(record|loans?|line|backer|owe[sd]?|due|history|overdue)\b/i,
|
|
114
|
+
call: (m, id) => m.api.agentRecord(id),
|
|
115
|
+
words: (r) => recordWords(r),
|
|
116
|
+
example: [
|
|
117
|
+
{ name: "{{name1}}", content: { text: "Show agent #25754's MIRAI loans and line." } },
|
|
118
|
+
{ name: "{{agentName}}", content: { text: "Agent #25754: line 25 USDG, owed 5 USDG, available 20 USDG. Loan #2 is due 2026-12-14 15:00 UTC.", actions: ["MIRAI_AGENT_RECORD"] } },
|
|
119
|
+
],
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
/** The agent, amount and term of a loan, from the planner's parameters or the message's own words. */
|
|
123
|
+
function loanTerms(message, options) {
|
|
124
|
+
const text = textOf(message);
|
|
125
|
+
const agentId = agentFrom(message, options);
|
|
126
|
+
const a = param(options, "amount") ?? amountOf(text);
|
|
127
|
+
const daysRaw = param(options, "days") ?? daysOf(text);
|
|
128
|
+
if (a && typeof a === "object" && a.error) return { error: `Nothing was prepared: ${a.error}.` };
|
|
129
|
+
const amount = a == null ? null : String(a).trim();
|
|
130
|
+
const days = daysRaw == null ? null : Number(daysRaw);
|
|
131
|
+
if (agentId == null) return { error: askAgent };
|
|
132
|
+
if (!amount || !/^\d+(\.\d{1,6})?$/.test(amount)) return { error: 'How much USDG? Say an amount such as "5 USDG" (at most 6 decimals).' };
|
|
133
|
+
if (!Number.isInteger(days) || days < 1 || days > 30) return { error: 'For how many days? Say a whole number of days from 1 to 30, such as "for 14 days".' };
|
|
134
|
+
return { agentId, amount, days };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const quoteLoan = {
|
|
138
|
+
name: "MIRAI_QUOTE_LOAN",
|
|
139
|
+
similes: ["MIRAI_LOAN_FEE", "QUOTE_BORROW", "LOAN_COST"],
|
|
140
|
+
description: "Quote the exact fee of borrowing USDG on an agent's MIRAI line for a number of days, read from the MIRAI lens contract. Needs the agent id, the amount and the term. Moves no money.",
|
|
141
|
+
parameters: [
|
|
142
|
+
{ name: "agentId", description: "The agent's ERC-8004 id", required: true, schema: { type: "integer", minimum: 0 } },
|
|
143
|
+
{ name: "amount", description: "USDG to borrow, e.g. \"5\"", required: true, schema: { type: "string" } },
|
|
144
|
+
{ name: "days", description: "Term in days, 1 to 30", required: true, schema: { type: "integer", minimum: 1, maximum: 30 } },
|
|
145
|
+
],
|
|
146
|
+
validate: async (_runtime, message) => /\b(quote|fee|cost|how much|price)\b/i.test(textOf(message)) && /\b(borrow|loan|line|mirai)\b/i.test(textOf(message)),
|
|
147
|
+
handler: async (runtime, message, _state, options, callback) => {
|
|
148
|
+
const t = loanTerms(message, options);
|
|
149
|
+
if (t.error) return answer(callback, "MIRAI_QUOTE_LOAN", false, t.error);
|
|
150
|
+
try {
|
|
151
|
+
const c = miraiOf(runtime).client();
|
|
152
|
+
const p = await c.params();
|
|
153
|
+
const amt = Number(t.amount);
|
|
154
|
+
if (amt < p.minLoan || amt > p.maxLoan) return answer(callback, "MIRAI_QUOTE_LOAN", false, `A MIRAI loan is ${usdg(p.minLoan)} to ${usdg(p.maxLoan)} USDG; ${t.amount} is outside that.`, t);
|
|
155
|
+
if (t.days < p.minTermDays || t.days > p.maxTermDays) return answer(callback, "MIRAI_QUOTE_LOAN", false, `A MIRAI loan runs ${p.minTermDays} to ${p.maxTermDays} days.`, t);
|
|
156
|
+
const q = await c.quote(t.agentId, t.amount, t.days);
|
|
157
|
+
return answer(callback, "MIRAI_QUOTE_LOAN", true, quoteWords({ agent: t.agentId, amount: amt, days: t.days, fee: q.fee, premium: q.premium, total: q.total, due: q.due }), { ...t, fee: q.total, repay: q.due });
|
|
158
|
+
} catch (e) {
|
|
159
|
+
return answer(callback, "MIRAI_QUOTE_LOAN", false, `The quote could not be read: ${short(e)}`, t);
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
examples: [[
|
|
163
|
+
{ name: "{{name1}}", content: { text: "How much does it cost to borrow 5 USDG for 14 days on agent #25754's MIRAI line?" } },
|
|
164
|
+
{ name: "{{agentName}}", content: { text: "Borrowing 5 USDG for 14 days on agent #25754's line costs 0.023334 USDG: repay 5.023334 USDG by the due date.", actions: ["MIRAI_QUOTE_LOAN"] } },
|
|
165
|
+
]],
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const prepareBorrow = {
|
|
169
|
+
name: "MIRAI_PREPARE_BORROW",
|
|
170
|
+
similes: ["MIRAI_BORROW", "BORROW_USDG", "PREPARE_LOAN"],
|
|
171
|
+
description: "Prepare an UNSIGNED MIRAI borrow transaction on Robinhood Chain for the agent's owner, its declared wallet or an operator to sign. Nothing is sent. Needs the agent id, the amount, the term and the receiving address (the MIRAI_RECEIVER setting when set).",
|
|
172
|
+
parameters: [
|
|
173
|
+
{ name: "agentId", description: "The agent's ERC-8004 id", required: true, schema: { type: "integer", minimum: 0 } },
|
|
174
|
+
{ name: "amount", description: "USDG to borrow, e.g. \"5\"", required: true, schema: { type: "string" } },
|
|
175
|
+
{ name: "days", description: "Term in days, 1 to 30", required: true, schema: { type: "integer", minimum: 1, maximum: 30 } },
|
|
176
|
+
{ name: "to", description: "Address that receives the USDG", required: false, schema: { type: "string" } },
|
|
177
|
+
],
|
|
178
|
+
validate: async (_runtime, message) => /\bborrow\w*|\btake (a|out a) loan\b/i.test(textOf(message)),
|
|
179
|
+
handler: async (runtime, message, _state, options, callback) => {
|
|
180
|
+
const t = loanTerms(message, options);
|
|
181
|
+
if (t.error) return answer(callback, "MIRAI_PREPARE_BORROW", false, t.error);
|
|
182
|
+
const fixed = settingOf(runtime, "MIRAI_RECEIVER", env);
|
|
183
|
+
const named = param(options, "to") ?? addressOf(textOf(message));
|
|
184
|
+
if (named && typeof named === "object") return answer(callback, "MIRAI_PREPARE_BORROW", false, `Nothing was prepared: ${named.error}. Name the one address that receives the USDG.`);
|
|
185
|
+
const to = fixed || named;
|
|
186
|
+
if (fixed && !isAddress(fixed)) return answer(callback, "MIRAI_PREPARE_BORROW", false, "Nothing was prepared: the MIRAI_RECEIVER setting is not an address.");
|
|
187
|
+
if (!to) return answer(callback, "MIRAI_PREPARE_BORROW", false, "Which address receives the USDG? Name it (0x followed by 40 hex characters), or set MIRAI_RECEIVER in the agent's settings.", t);
|
|
188
|
+
if (!isAddress(to)) return answer(callback, "MIRAI_PREPARE_BORROW", false, "Nothing was prepared: the receiving address must be 0x followed by 40 hex characters.", t);
|
|
189
|
+
try {
|
|
190
|
+
const tx = await miraiOf(runtime).client().prepareBorrow(t.agentId, t.amount, t.days, to);
|
|
191
|
+
const unsigned = { chainId: 4663, to: tx.to, value: "0", data: tx.data };
|
|
192
|
+
const text = `Prepared an UNSIGNED borrow for agent #${t.agentId}: ${t.amount} USDG for ${plural(t.days, "day")}, sent to ${to}${fixed ? " (the MIRAI_RECEIVER setting)" : ""}. ` +
|
|
193
|
+
`Fee ${usdg(tx.quote.total)} USDG, so ${usdg(tx.quote.due)} USDG is due when the loan ends; the transaction allows at most 1% more fee than this quote. Nothing was sent.\n` +
|
|
194
|
+
`To borrow, the agent's owner, its declared ERC-8004 wallet or an operator it named signs this on Robinhood Chain (chain 4663): to ${tx.to}, value 0, data ${tx.data}.\n` +
|
|
195
|
+
"Check the receiving address before signing. Three days after the due date anyone may mark an unpaid loan defaulted, and the default stays on the agent's record.";
|
|
196
|
+
return answer(callback, "MIRAI_PREPARE_BORROW", true, text, { ...t, receiver: to, unsigned, fee: tx.quote.total, repay: tx.quote.due });
|
|
197
|
+
} catch (e) {
|
|
198
|
+
return answer(callback, "MIRAI_PREPARE_BORROW", false, `Nothing was prepared: ${short(e)}`, t);
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
examples: [[
|
|
202
|
+
{ name: "{{name1}}", content: { text: "Prepare a borrow of 5 USDG for 14 days for agent #25754 to 0x2222222222222222222222222222222222222222." } },
|
|
203
|
+
{ name: "{{agentName}}", content: { text: "Prepared an UNSIGNED borrow for agent #25754: 5 USDG for 14 days. Fee 0.023334 USDG. Nothing was sent.", actions: ["MIRAI_PREPARE_BORROW"] } },
|
|
204
|
+
]],
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const prepareRepay = {
|
|
208
|
+
name: "MIRAI_PREPARE_REPAY",
|
|
209
|
+
similes: ["MIRAI_REPAY", "REPAY_LOAN", "PAY_BACK_LOAN"],
|
|
210
|
+
description: "Prepare the UNSIGNED transactions that repay a MIRAI loan in full: a USDG approval when the payer's allowance is short, then the repayment. Nothing is sent; anyone can repay any loan. Needs the loan id, as loan 12.",
|
|
211
|
+
parameters: [
|
|
212
|
+
{ name: "loanId", description: "The MIRAI loan id", required: true, schema: { type: "integer", minimum: 1 } },
|
|
213
|
+
{ name: "from", description: "Payer address, to check its USDG allowance", required: false, schema: { type: "string" } },
|
|
214
|
+
],
|
|
215
|
+
validate: async (_runtime, message) => /\brepa(y|id|ying|yment)\b|\bpay (it )?back\b/i.test(textOf(message)),
|
|
216
|
+
handler: async (runtime, message, _state, options, callback) => {
|
|
217
|
+
const loanId = idParam(options, "loanId") ?? loanIdOf(textOf(message));
|
|
218
|
+
if (!loanId) return answer(callback, "MIRAI_PREPARE_REPAY", false, "Which loan? Give the MIRAI loan id, for example loan 12.");
|
|
219
|
+
const fixed = settingOf(runtime, "MIRAI_PAYER", env);
|
|
220
|
+
const named = param(options, "from") ?? addressOf(textOf(message));
|
|
221
|
+
const from = fixed || (named && typeof named === "string" ? named : undefined);
|
|
222
|
+
if (from && !isAddress(from)) return answer(callback, "MIRAI_PREPARE_REPAY", false, "Nothing was prepared: the payer address must be 0x followed by 40 hex characters.", { loanId });
|
|
223
|
+
try {
|
|
224
|
+
const p = await miraiOf(runtime).client().prepareRepay(loanId, from);
|
|
225
|
+
const L = p.loan;
|
|
226
|
+
const steps = p.txs.map((t, i) => `${i + 1}) ${t.note}: to ${t.to}, value 0, data ${t.data}`).join("\n");
|
|
227
|
+
const text = `Prepared the UNSIGNED repayment of loan #${loanId} (agent #${L.agent}): ${usdg(L.due)} USDG, due ${when(L.dueAt)}${Math.floor(Date.now() / 1000) > L.dueAt ? " (already past due: it will count as late)" : ""}. Nothing was sent.\n` +
|
|
228
|
+
`Send these in order from the payer's wallet on Robinhood Chain (chain 4663)${from ? "" : "; with no payer address given, the approval step is included in case the allowance is short"}:\n${steps}`;
|
|
229
|
+
return answer(callback, "MIRAI_PREPARE_REPAY", true, text, { loanId, agentId: L.agent, due: L.due, unsigned: p.txs.map((t) => ({ chainId: 4663, to: t.to, value: "0", data: t.data, note: t.note })) });
|
|
230
|
+
} catch (e) {
|
|
231
|
+
return answer(callback, "MIRAI_PREPARE_REPAY", false, `Nothing was prepared for loan #${loanId}: ${short(e)}`, { loanId });
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
examples: [[
|
|
235
|
+
{ name: "{{name1}}", content: { text: "Prepare the repayment of MIRAI loan 12." } },
|
|
236
|
+
{ name: "{{agentName}}", content: { text: "Prepared the UNSIGNED repayment of loan #12 (agent #25754): 5.023334 USDG. Nothing was sent.", actions: ["MIRAI_PREPARE_REPAY"] } },
|
|
237
|
+
]],
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
/** This agent's own MIRAI standing, for the model's context when MIRAI_AGENT_ID is set; cached for a minute. */
|
|
241
|
+
const ownRecord = {
|
|
242
|
+
name: "MIRAI_OWN_RECORD",
|
|
243
|
+
description: "This agent's own MIRAI line, debt, open loans with due dates, and score (needs MIRAI_AGENT_ID).",
|
|
244
|
+
dynamic: true,
|
|
245
|
+
get: async (runtime) => {
|
|
246
|
+
const raw = settingOf(runtime, "MIRAI_AGENT_ID", env);
|
|
247
|
+
const id = raw != null && /^\d{1,9}$/.test(raw) ? Number(raw) : null;
|
|
248
|
+
if (id == null) return { text: "", values: {}, data: {} };
|
|
249
|
+
const m = miraiOf(runtime);
|
|
250
|
+
const hit = m.cache.get(id);
|
|
251
|
+
if (hit && Date.now() - hit.at < 60_000) return hit.value;
|
|
252
|
+
try {
|
|
253
|
+
const r = await m.api.agentRecord(id);
|
|
254
|
+
const open = (r.loans || []).filter((l) => l.status === "open");
|
|
255
|
+
const lines = [`This agent is MIRAI agent #${id}: line ${usdg(r.line)} USDG, owed ${usdg(r.owed)} USDG, available ${usdg(r.available)} USDG, MIRAI Score ${r.score?.score ?? 0} (${r.score?.floor ?? "lot"}).`];
|
|
256
|
+
for (const l of open) lines.push(`Open loan #${l.id}: ${usdg(l.principal + l.fee)} USDG due ${when(l.dueAt)}${l.overdue ? `, OVERDUE, grace ends ${when(l.graceEndsAt)}` : ""}.`);
|
|
257
|
+
if (!open.length) lines.push("No open MIRAI loan.");
|
|
258
|
+
const value = { text: lines.join("\n"), values: { miraiAgentId: id, miraiOwed: r.owed, miraiAvailable: r.available }, data: { openLoans: open.map((l) => ({ id: l.id, dueAt: l.dueAt })) } };
|
|
259
|
+
m.cache.set(id, { at: Date.now(), value });
|
|
260
|
+
return value;
|
|
261
|
+
} catch (e) {
|
|
262
|
+
return { text: `MIRAI agent #${id}: its record could not be read just now.`, values: {}, data: {} };
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
return {
|
|
268
|
+
name: "mirai",
|
|
269
|
+
description: "MIRAI credit records for ERC-8004 agents on Robinhood Chain: check an agent before paying or trusting it, read its MIRAI Score and loans, quote a loan, and prepare unsigned borrow and repay transactions. Holds no key.",
|
|
270
|
+
actions: [checkAgent, agentScore, agentRecord, quoteLoan, prepareBorrow, prepareRepay],
|
|
271
|
+
providers: [ownRecord],
|
|
272
|
+
evaluators: [],
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export const miraiPlugin = createMiraiPlugin();
|
|
277
|
+
export default miraiPlugin;
|
|
278
|
+
export { agentIdOf, loanIdOf, amountOf, daysOf, addressOf, cleanText } from "./parse.mjs";
|
package/src/parse.mjs
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// What an action reads from a chat message: agent and loan ids, an amount of USDG, a term, an address.
|
|
2
|
+
// Links, code blocks, inline code and anything in braces are taken out first, wherever they stand, so a number inside
|
|
3
|
+
// a URL's path or query, a pasted JSON object or an example block is never read as an id, an amount or an address.
|
|
4
|
+
|
|
5
|
+
const WORD = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, ten: 10, fourteen: 14, thirty: 30 };
|
|
6
|
+
|
|
7
|
+
export function cleanText(text) {
|
|
8
|
+
let s = String(text ?? "");
|
|
9
|
+
s = s.replace(/```[\s\S]*?(?:```|$)/g, " "); // fenced blocks, an unclosed one runs to the end
|
|
10
|
+
s = s.replace(/`[^`\n]*`?/g, " "); // inline code
|
|
11
|
+
for (let i = 0; i < 10 && /\{[^{}]*\}/.test(s); i++) s = s.replace(/\{[^{}]*\}/g, " ");
|
|
12
|
+
s = s.replace(/\{[\s\S]*$/, " "); // an object that never closes
|
|
13
|
+
s = s.replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi, " ").replace(/\bwww\.\S+/gi, " ");
|
|
14
|
+
return s;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const n = (x) => (x == null ? null : Number(x));
|
|
18
|
+
|
|
19
|
+
/** The loan id the message names ("loan 12", "loan #12", "loan id 12"), or null. */
|
|
20
|
+
export function loanIdOf(text) {
|
|
21
|
+
const m = cleanText(text).match(/\bloan\s*(?:id\s*)?(?:no\.?\s*|number\s*)?#?\s*(\d{1,9})\b/i);
|
|
22
|
+
return m ? n(m[1]) : null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The agent id the message names ("agent #25754", "agent 25754", "#25754"), never a loan's number, or null. */
|
|
26
|
+
export function agentIdOf(text) {
|
|
27
|
+
const s = cleanText(text).replace(/\bloan\s*(?:id\s*)?(?:no\.?\s*|number\s*)?#?\s*\d{1,9}\b/gi, " ");
|
|
28
|
+
const m = s.match(/\bagent\s*(?:id\s*)?(?:no\.?\s*|number\s*)?#?\s*(\d{1,9})\b/i) || s.match(/(?:^|[^\w&])#(\d{1,9})\b/) || s.match(/\berc-?8004\s*(?:id\s*)?#?\s*(\d{1,9})\b/i);
|
|
29
|
+
return m ? n(m[1]) : null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The loan term in days ("for 14 days", "7-day", "a week"), or null. */
|
|
33
|
+
export function daysOf(text) {
|
|
34
|
+
const s = cleanText(text);
|
|
35
|
+
const m = s.match(/\b(\d{1,3})\s*-?\s*days?\b/i);
|
|
36
|
+
if (m) return n(m[1]);
|
|
37
|
+
const w = s.match(/\b(one|two|three|four|five|six|seven|ten|fourteen|thirty)\s*-?\s*days?\b/i);
|
|
38
|
+
if (w) return WORD[w[1].toLowerCase()];
|
|
39
|
+
if (/\b(?:a|one)\s+week\b/i.test(s)) return 7;
|
|
40
|
+
if (/\btwo\s+weeks\b/i.test(s)) return 14;
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The amount of USDG the message names, as the decimal string it wrote ("5 USDG", "$12.5", "borrow 5"), or null.
|
|
46
|
+
* Ids, loan numbers, terms and addresses are taken out first. More than 6 decimals answers { error }.
|
|
47
|
+
*/
|
|
48
|
+
export function amountOf(text) {
|
|
49
|
+
const s = cleanText(text)
|
|
50
|
+
.replace(/\b0x[0-9a-fA-F]+\b/g, " ")
|
|
51
|
+
.replace(/\b(?:loan|agent|erc-?8004)\s*(?:id\s*)?(?:no\.?\s*|number\s*)?#?\s*\d+\b/gi, " ")
|
|
52
|
+
.replace(/#\d+/g, " ")
|
|
53
|
+
.replace(/\b\d{1,3}\s*-?\s*days?\b/gi, " ");
|
|
54
|
+
const m = s.match(/(\d+(?:\.\d+)?)\s*(?:usdg|usdc|usd|dollars?)\b/i) || s.match(/\$\s*(\d+(?:\.\d+)?)/) || s.match(/\b(?:borrow|quote|loan of|for)\s+(\d+(?:\.\d+)?)\b/i);
|
|
55
|
+
if (!m) return null;
|
|
56
|
+
if ((m[1].split(".")[1] || "").length > 6) return { error: `${m[1]} has more than 6 decimals; USDG counts in millionths` };
|
|
57
|
+
return m[1];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The one address the message names, or null; two different ones answer { error } rather than a guess. */
|
|
61
|
+
export function addressOf(text) {
|
|
62
|
+
const all = [...new Set((cleanText(text).match(/\b0x[0-9a-fA-F]{40}\b/g) || []).map((a) => a.toLowerCase()))];
|
|
63
|
+
if (all.length > 1) return { error: "the message names more than one address" };
|
|
64
|
+
return all.length ? cleanText(text).match(new RegExp(all[0], "i"))[0] : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const isAddress = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
|
package/src/words.mjs
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Plain-English answers built from the JSON of the MIRAI public API (https://miraifi.family/api/...).
|
|
2
|
+
// Every function here is pure: JSON in, one string out. Names and notes are written by agent owners, so they are
|
|
3
|
+
// reduced to one short quoted line and never passed on as instructions.
|
|
4
|
+
|
|
5
|
+
export const SITE = "https://miraifi.family";
|
|
6
|
+
const FLOORS = ["lot", "footing", "frame", "tower", "skyline"];
|
|
7
|
+
|
|
8
|
+
/** Owner-written text as one quoted line: no control characters, no markup, at most `max` characters. */
|
|
9
|
+
export function quoted(text, max = 80) {
|
|
10
|
+
const s = String(text ?? "")
|
|
11
|
+
.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069]/g, " ")
|
|
12
|
+
.replace(/[<>`"\\]/g, "")
|
|
13
|
+
.replace(/\s+/g, " ")
|
|
14
|
+
.trim();
|
|
15
|
+
if (!s) return "";
|
|
16
|
+
return `"${s.length > max ? s.slice(0, max - 1) + "…" : s}"`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A USDG amount for people: up to 6 decimals, no trailing zeros. */
|
|
20
|
+
export function usdg(n) {
|
|
21
|
+
const x = Number(n);
|
|
22
|
+
if (!Number.isFinite(x)) return "0";
|
|
23
|
+
return x.toFixed(6).replace(/\.?0+$/, "") || "0";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A unix time (seconds) as "YYYY-MM-DD HH:MM UTC". */
|
|
27
|
+
export function when(unix) {
|
|
28
|
+
const t = Number(unix);
|
|
29
|
+
if (!Number.isFinite(t) || t <= 0) return "an unknown time";
|
|
30
|
+
return new Date(t * 1000).toISOString().slice(0, 16).replace("T", " ") + " UTC";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const plural = (n, one, many = one + "s") => `${n} ${Number(n) === 1 ? one : many}`;
|
|
34
|
+
const agentLabel = (id, name) => `agent #${id}${quoted(name) ? ` (${quoted(name)})` : ""}`;
|
|
35
|
+
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
36
|
+
|
|
37
|
+
/** /api/check → "has this agent repaid real money?" */
|
|
38
|
+
export function checkWords(r, site = SITE) {
|
|
39
|
+
if (!r || r.agent == null) return "MIRAI returned no record.";
|
|
40
|
+
const head = `${cap(agentLabel(r.agent, r.name))} on MIRAI`;
|
|
41
|
+
const page = `Page: ${site}/agent/${r.agent}.`;
|
|
42
|
+
const limit = "A record shows how an agent repaid money someone else put at risk on MIRAI; it does not say whether its service is good.";
|
|
43
|
+
if (!r.inPool) {
|
|
44
|
+
return `${head}: it has an ERC-8004 identity on Robinhood Chain but has never had a MIRAI line, so there is no repayment record yet (no loans, no default). ${page} ${limit}`;
|
|
45
|
+
}
|
|
46
|
+
const lines = [
|
|
47
|
+
`${head}: ${plural(r.loansRepaid ?? 0, "loan")} repaid (${usdg(r.repaidUsdg)} USDG), ${plural(r.late ?? 0, "late repayment")}, ` +
|
|
48
|
+
(r.defaulted ? "and a DEFAULT on its record. A default is permanent: treat it as a hard stop." : "never defaulted."),
|
|
49
|
+
`Line ${usdg(r.line)} USDG, owed now ${usdg(r.owed)} USDG${r.source && r.source !== "none" ? `, backed by ${r.source}` : ""}. On-chain score ${r.score ?? 0} (${r.tier ?? "unproven"}).`,
|
|
50
|
+
`${page} ${limit}`,
|
|
51
|
+
];
|
|
52
|
+
return lines.join("\n");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** /api/score → the MIRAI Score with every component and what the next floor needs. */
|
|
56
|
+
export function scoreWords(s) {
|
|
57
|
+
if (!s || s.agent == null) return "MIRAI returned no score.";
|
|
58
|
+
if (s.unknown) return `Agent #${s.agent} is not known to MIRAI: no identity or record was found, so it has no MIRAI Score.`;
|
|
59
|
+
if (s.defaulted) return `Agent #${s.agent} has a MIRAI Score of 0 of ${s.max ?? 1000}: ${s.reason || "a loan defaulted"}. A default is permanent.`;
|
|
60
|
+
const rung = Number(s.rung ?? FLOORS.indexOf(s.floor));
|
|
61
|
+
const out = [`MIRAI Score of agent #${s.agent}: ${s.score} of ${s.max ?? 1000}, floor "${s.floor}" (${rung + 1} of ${FLOORS.length}). Points come only from money someone else put at risk on the agent, repaid on time.`];
|
|
62
|
+
const comps = (s.components || []).map((c) => `${c.key} ${c.points}/${c.max} (${c.why})`);
|
|
63
|
+
if (comps.length) out.push(`Components: ${comps.join("; ")}.`);
|
|
64
|
+
const pens = (s.penalties || []).map((p) => `${p.key} ${p.points} (${p.why})`);
|
|
65
|
+
out.push(pens.length ? `Penalties: ${pens.join("; ")}.` : "Penalties: none.");
|
|
66
|
+
if (s.next) {
|
|
67
|
+
const open = (s.next.needs || []).filter((n) => !n.met).map((n) => `${n.key} ${n.have} of ${n.need}`);
|
|
68
|
+
const met = (s.next.needs || []).filter((n) => n.met).map((n) => `${n.key} ${n.have} of ${n.need}`);
|
|
69
|
+
out.push(`Next floor "${s.next.floor}": ${open.length ? `still needs ${open.join(", ")}` : "every condition is met"}${met.length ? `; already met: ${met.join(", ")}` : ""}${s.next.blocked ? `; blocked by ${s.next.blocked}` : ""}.`);
|
|
70
|
+
} else {
|
|
71
|
+
out.push("It is on the top floor.");
|
|
72
|
+
}
|
|
73
|
+
if (s.version) out.push(`Score version ${s.version}; weights at ${SITE}/api/score/weights.`);
|
|
74
|
+
return out.join("\n");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** /api/agent-record → line, backer and loans, with due dates and grace for an overdue loan. */
|
|
78
|
+
export function recordWords(r, { maxLoans = 10 } = {}) {
|
|
79
|
+
if (!r || r.agent == null) return "MIRAI returned no record.";
|
|
80
|
+
const out = [`${cap(agentLabel(r.agent, r.name))}: line ${usdg(r.line)} USDG, owed ${usdg(r.owed)} USDG, available ${usdg(r.available)} USDG.`];
|
|
81
|
+
if (r.backer) {
|
|
82
|
+
out.push(`Backer: agent #${r.backer.id}${quoted(r.backer.name) ? ` (${quoted(r.backer.name)})` : ""}, ${r.backer.kind || "backer"}${r.backer.hook ? `, with a hook contract ${r.backer.hook} that can refuse a borrow` : ""}.`);
|
|
83
|
+
} else {
|
|
84
|
+
out.push(r.inPool ? "No backer now." : "It has never had a MIRAI line.");
|
|
85
|
+
}
|
|
86
|
+
if (r.score && typeof r.score.score === "number") out.push(`MIRAI Score ${r.score.score} of ${r.score.max ?? 1000}, floor "${r.score.floor}".`);
|
|
87
|
+
const loans = [...(r.loans || [])].sort((a, b) => b.id - a.id);
|
|
88
|
+
if (!loans.length) out.push("No loans yet.");
|
|
89
|
+
for (const l of loans.slice(0, maxLoans)) {
|
|
90
|
+
let s = `Loan #${l.id}: ${usdg(l.principal)} USDG for ${l.termDays} days, fee ${usdg(l.fee)}, taken ${when(l.takenAt)}, due ${when(l.dueAt)}, ${l.status}`;
|
|
91
|
+
if (l.status === "repaid") s += `${l.late ? " late" : " on time"} (${when(l.repaidAt)})`;
|
|
92
|
+
if (l.overdue) s += `, OVERDUE: grace ends ${when(l.graceEndsAt)}, then anyone may mark it defaulted`;
|
|
93
|
+
out.push(s + ".");
|
|
94
|
+
}
|
|
95
|
+
if (loans.length > maxLoans) out.push(`…and ${loans.length - maxLoans} older loans.`);
|
|
96
|
+
out.push(`Page: ${r.page || `${SITE}/agent/${r.agent}`}.`);
|
|
97
|
+
return out.join("\n");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A fee quote in words. */
|
|
101
|
+
export function quoteWords({ agent, amount, days, fee, premium, total, due }) {
|
|
102
|
+
return `Borrowing ${usdg(amount)} USDG for ${plural(days, "day")} on agent #${agent}'s line costs ${usdg(total)} USDG ` +
|
|
103
|
+
`(base fee ${usdg(fee)}${Number(premium) ? `, backer premium ${usdg(premium)}` : ""}): repay ${usdg(due)} USDG by the due date. ` +
|
|
104
|
+
"The fee is fixed when the loan opens and is due in full even if it is repaid early; three days after the due date anyone may mark the loan defaulted.";
|
|
105
|
+
}
|