flop-guild 0.0.0-stage → 0.2.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 +9 -0
- package/README.md +62 -2
- package/dist/autopilot.js +178 -0
- package/dist/cli.js +220 -0
- package/dist/commands.js +40 -0
- package/dist/config.js +21 -0
- package/dist/flop.js +322 -0
- package/dist/identity.js +110 -0
- package/dist/mcp.js +124 -0
- package/dist/miners.js +104 -0
- package/dist/net.js +64 -0
- package/dist/nonce.js +36 -0
- package/dist/server.js +355 -0
- package/dist/setup.js +222 -0
- package/dist/technocore.js +134 -0
- package/dist/wallet.js +66 -0
- package/networks.json +13 -0
- package/package.json +50 -4
- package/site/guides/agent-quickstart.md +42 -0
- package/site/guides/autopilot.md +45 -0
- package/site/guides/join-guild.md +33 -0
- package/site/index.html +16 -0
- package/site/llms.txt +31 -0
- package/site/skill.md +48 -0
- package/skill.md +73 -0
package/dist/flop.js
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
// Devnet agent actions: faucet-claim, enroll, session. Every caller passes an api from
|
|
2
|
+
// net.connect(), so the genesis guard has already passed before anything is signed.
|
|
3
|
+
import { createPublicKey, randomUUID, sign } from "node:crypto";
|
|
4
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { checkName, homeDir, loadIdentity, rawPublicKey } from "./identity.js";
|
|
7
|
+
import { finalizedFree, FLOP, fmtFlop, sleep, toRaw } from "./net.js";
|
|
8
|
+
import { read, say } from "./technocore.js";
|
|
9
|
+
import { unlockWallet, walletAddress } from "./wallet.js";
|
|
10
|
+
const UA = "flop-guild/0.2";
|
|
11
|
+
export const FAUCET_ROOM = "flop-devnet-faucet";
|
|
12
|
+
export async function didAddress(name) {
|
|
13
|
+
const { encodeAddress } = await import("@polkadot/util-crypto");
|
|
14
|
+
return encodeAddress(rawPublicKey(createPublicKey(loadIdentity(name).privateKey)), 42);
|
|
15
|
+
}
|
|
16
|
+
export async function address(agent, flow) {
|
|
17
|
+
return flow === "wallet" ? walletAddress(agent.name) : didAddress(agent.name);
|
|
18
|
+
}
|
|
19
|
+
async function waitForIncrease(api, addr, before, ms) {
|
|
20
|
+
const end = Date.now() + ms;
|
|
21
|
+
let now = before;
|
|
22
|
+
while (Date.now() < end) {
|
|
23
|
+
now = await finalizedFree(api, addr);
|
|
24
|
+
if (now > before)
|
|
25
|
+
return now;
|
|
26
|
+
await sleep(4000);
|
|
27
|
+
}
|
|
28
|
+
return now;
|
|
29
|
+
}
|
|
30
|
+
/** Wallet flow: POST /fund (25 FLOP). Never retried automatically. */
|
|
31
|
+
async function faucetWallet(net, _api, addr) {
|
|
32
|
+
const { requestFaucetFunding } = await import("@flop-labs/sdk");
|
|
33
|
+
const r = await requestFaucetFunding(addr, { network: net.name, endpoint: net.faucet, client: "flop-sdk-ts", timeout: 120_000 });
|
|
34
|
+
return { outcome: r.outcome ?? (r.success ? "accepted" : "refused"), reason: r.reason ?? r.error, retryAfterSeconds: r.retryAfterSeconds, txHash: r.txHash };
|
|
35
|
+
}
|
|
36
|
+
/** Send exactly one faucet request and return its raw outcome, without waiting for the balance. */
|
|
37
|
+
export async function faucetRequest(net, api, agent, flow) {
|
|
38
|
+
const addr = await address(agent, flow);
|
|
39
|
+
const r = flow === "wallet" ? await faucetWallet(net, api, addr) : await faucetDid(net, agent, addr);
|
|
40
|
+
return { address: addr, ...r };
|
|
41
|
+
}
|
|
42
|
+
/** DID flow: signed "!faucet request <ss58> <nonce>" in the faucet room, then wait for the bot's signed reply. */
|
|
43
|
+
async function faucetDid(net, agent, addr) {
|
|
44
|
+
const chain = await (await fetch(`${net.faucet}/chain`, { headers: { "user-agent": UA } })).json();
|
|
45
|
+
const bot = chain?.technocoreBot?.did;
|
|
46
|
+
const room = chain?.technocoreBot?.room ?? FAUCET_ROOM;
|
|
47
|
+
if (!bot)
|
|
48
|
+
throw new Error("faucet /chain names no technocoreBot did");
|
|
49
|
+
const sent = await say(agent.name, room, `!faucet request ${addr} ${Date.now()}`);
|
|
50
|
+
const did = loadIdentity(agent.name).did;
|
|
51
|
+
// Find our own message's seq, then wait for the bot's reply that names it.
|
|
52
|
+
const recent = JSON.parse((await read(room, { json: true, limit: 50 })).body);
|
|
53
|
+
const mine = [...recent.messages].reverse().find((m) => m.from === did && m.text === sent.text);
|
|
54
|
+
if (!mine)
|
|
55
|
+
throw new Error("posted faucet request not found in the room");
|
|
56
|
+
let since = mine.seq;
|
|
57
|
+
const end = Date.now() + 180_000;
|
|
58
|
+
while (Date.now() < end) {
|
|
59
|
+
const page = JSON.parse((await read(room, { json: true, since, wait: 10 })).body);
|
|
60
|
+
for (const m of page.messages ?? []) {
|
|
61
|
+
since = Math.max(since, m.seq);
|
|
62
|
+
if (m.from === bot && String(m.text).startsWith(`request #${mine.seq}:`)) {
|
|
63
|
+
const text = String(m.text);
|
|
64
|
+
const tx = text.match(/tx (0x[0-9a-f]{64})/)?.[1];
|
|
65
|
+
const funded = /Funded [0-9.]+ devnet FLOP/.test(text);
|
|
66
|
+
const why = text.replace(/^request #\d+: \[FLOP DEVNET\][^.]*\.[^.]*\.\s*/, "").slice(0, 300);
|
|
67
|
+
return { outcome: funded ? "accepted" : "refused", reason: funded ? undefined : why, txHash: tx };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return { outcome: "unknown", reason: "no bot reply within 180 s" };
|
|
72
|
+
}
|
|
73
|
+
export async function faucetClaim(net, api, agent, flow) {
|
|
74
|
+
const addr = await address(agent, flow);
|
|
75
|
+
const before = await finalizedFree(api, addr);
|
|
76
|
+
const r = flow === "wallet" ? await faucetWallet(net, api, addr) : await faucetDid(net, agent, addr);
|
|
77
|
+
const after = r.outcome === "refused" ? before : await waitForIncrease(api, addr, before, 300_000);
|
|
78
|
+
return { flow, address: addr, ...r, before: fmtFlop(before), after: fmtFlop(after), raised: after > before };
|
|
79
|
+
}
|
|
80
|
+
function credPath(name) {
|
|
81
|
+
return join(homeDir(), `${checkName(name)}.gateway.json`);
|
|
82
|
+
}
|
|
83
|
+
export function loadCredential(name) {
|
|
84
|
+
const p = credPath(name);
|
|
85
|
+
if (!existsSync(p))
|
|
86
|
+
throw new Error(`agent "${name}" is not enrolled; run: flop-guild enroll ${name}`);
|
|
87
|
+
return JSON.parse(readFileSync(p, "utf8"));
|
|
88
|
+
}
|
|
89
|
+
/** Public view of a credential: never includes the bearer key. */
|
|
90
|
+
export function publicCredential(c) {
|
|
91
|
+
const { key: _key, ...rest } = c;
|
|
92
|
+
return { ...rest, expires: new Date(c.expires_at).toISOString() };
|
|
93
|
+
}
|
|
94
|
+
async function signChallenge(agent, flow, message) {
|
|
95
|
+
if (flow === "wallet") {
|
|
96
|
+
const { u8aToHex, stringToU8a } = await import("@polkadot/util");
|
|
97
|
+
const pair = await unlockWallet(agent.name);
|
|
98
|
+
try {
|
|
99
|
+
return u8aToHex(pair.sign(stringToU8a(message)));
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
pair.lock();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const sig = sign(null, Buffer.from(message, "utf8"), loadIdentity(agent.name).privateKey);
|
|
106
|
+
return "0x" + sig.toString("hex");
|
|
107
|
+
}
|
|
108
|
+
export class EnrollError extends Error {
|
|
109
|
+
status;
|
|
110
|
+
code;
|
|
111
|
+
constructor(message, status, code) {
|
|
112
|
+
super(message);
|
|
113
|
+
this.status = status;
|
|
114
|
+
this.code = code;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
export async function enrollFlow(net, api, agent, flow) {
|
|
118
|
+
const addr = await address(agent, flow);
|
|
119
|
+
const bal = await finalizedFree(api, addr);
|
|
120
|
+
if (bal < FLOP)
|
|
121
|
+
throw new EnrollError(`${flow} address ${addr} has ${fmtFlop(bal)} FLOP finalized; enrollment needs at least 1`);
|
|
122
|
+
const ch = await fetch(`${net.gateway}/enroll/wallet/challenge?address=${encodeURIComponent(addr)}`, { headers: { "user-agent": UA } });
|
|
123
|
+
const chBody = await ch.text();
|
|
124
|
+
if (!ch.ok)
|
|
125
|
+
throw new EnrollError(`challenge HTTP ${ch.status}: ${chBody.slice(0, 300)}`, ch.status);
|
|
126
|
+
const { message } = JSON.parse(chBody);
|
|
127
|
+
// The statement names the live genesis: refuse to sign one for another chain.
|
|
128
|
+
if (typeof message !== "string" || !message.includes(net.genesis))
|
|
129
|
+
throw new EnrollError("challenge does not name the expected genesis; refusing to sign");
|
|
130
|
+
const signature = await signChallenge(agent, flow, message);
|
|
131
|
+
const res = await fetch(`${net.gateway}/enroll/wallet`, {
|
|
132
|
+
method: "POST",
|
|
133
|
+
headers: { "user-agent": UA, "content-type": "application/json" },
|
|
134
|
+
body: JSON.stringify({ address: addr, message, signature }),
|
|
135
|
+
});
|
|
136
|
+
const body = await res.text();
|
|
137
|
+
if (!res.ok) {
|
|
138
|
+
let code;
|
|
139
|
+
try {
|
|
140
|
+
code = JSON.parse(body).error;
|
|
141
|
+
}
|
|
142
|
+
catch { }
|
|
143
|
+
throw new EnrollError(`enroll HTTP ${res.status}: ${body.slice(0, 300)}`, res.status, code);
|
|
144
|
+
}
|
|
145
|
+
const j = JSON.parse(body);
|
|
146
|
+
const cred = { flow, address: addr, key: j.key, model: j.model, remaining_quota: j.remaining_quota, expires_at: j.expires_at, enrolled_at: Date.now() };
|
|
147
|
+
mkdirSync(homeDir(), { recursive: true, mode: 0o700 });
|
|
148
|
+
writeFileSync(credPath(agent.name), JSON.stringify(cred, null, 2) + "\n", { mode: 0o600 });
|
|
149
|
+
chmodSync(credPath(agent.name), 0o600);
|
|
150
|
+
return cred;
|
|
151
|
+
}
|
|
152
|
+
/** Wallet-challenge flow first; on failure, the DID flow (the did:key's own Ed25519 SS58 account). */
|
|
153
|
+
export async function enroll(net, api, agent, flows = ["wallet", "did"]) {
|
|
154
|
+
const report = { attempts: [] };
|
|
155
|
+
for (const flow of flows) {
|
|
156
|
+
try {
|
|
157
|
+
const c = await enrollFlow(net, api, agent, flow);
|
|
158
|
+
report.attempts.push({ flow, ok: true, detail: `enrolled ${c.address}` });
|
|
159
|
+
report.worked = flow;
|
|
160
|
+
report.credential = publicCredential(c);
|
|
161
|
+
return report;
|
|
162
|
+
}
|
|
163
|
+
catch (e) {
|
|
164
|
+
report.attempts.push({ flow, ok: false, detail: e.message });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return report;
|
|
168
|
+
}
|
|
169
|
+
/** own-miners.json: a JSON array of SS58 addresses you control. Missing file = empty list. */
|
|
170
|
+
export function loadOwnMiners(path) {
|
|
171
|
+
if (!existsSync(path))
|
|
172
|
+
return [];
|
|
173
|
+
const v = JSON.parse(readFileSync(path, "utf8"));
|
|
174
|
+
if (!Array.isArray(v) || !v.every((x) => typeof x === "string"))
|
|
175
|
+
throw new Error(`${path} must be a JSON array of SS58 addresses`);
|
|
176
|
+
return v;
|
|
177
|
+
}
|
|
178
|
+
function ownMinerSet(list) {
|
|
179
|
+
return new Set(list.map((s) => s.trim()).filter(Boolean));
|
|
180
|
+
}
|
|
181
|
+
async function chainCheck(api, terminal) {
|
|
182
|
+
const m = terminal.match(/^(0x[0-9a-fA-F]{64}):(\d+)$/);
|
|
183
|
+
if (!m)
|
|
184
|
+
return undefined;
|
|
185
|
+
const [, hash, idx] = m;
|
|
186
|
+
const header = await api.rpc.chain.getHeader(hash);
|
|
187
|
+
const number = header.number.toNumber();
|
|
188
|
+
const canonicalHash = (await api.rpc.chain.getBlockHash(number)).toHex();
|
|
189
|
+
const fin = (await api.rpc.chain.getHeader(await api.rpc.chain.getFinalizedHead())).number.toNumber();
|
|
190
|
+
const block = await api.rpc.chain.getBlock(hash);
|
|
191
|
+
const extrinsic = Number(idx);
|
|
192
|
+
return {
|
|
193
|
+
block: hash,
|
|
194
|
+
number,
|
|
195
|
+
extrinsic,
|
|
196
|
+
canonical: canonicalHash.toLowerCase() === hash.toLowerCase(),
|
|
197
|
+
finalized: number <= fin,
|
|
198
|
+
extrinsic_exists: extrinsic < block.block.extrinsics.length,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/** Gateway route: bearer from enrollment, max_cost_flop cap, then ledger + on-chain check of the receipt. */
|
|
202
|
+
export async function session(net, api, agent, o) {
|
|
203
|
+
if (!(o.capFlop > 0))
|
|
204
|
+
throw new Error("session needs a positive --max-flop cap");
|
|
205
|
+
const own = ownMinerSet(o.ownMiners);
|
|
206
|
+
if (o.miner)
|
|
207
|
+
return directSession(net, api, agent, o, own);
|
|
208
|
+
const cred = loadCredential(agent.name);
|
|
209
|
+
if (cred.expires_at <= Date.now())
|
|
210
|
+
throw new Error("gateway allowance expired; it cannot be renewed by re-enrolling");
|
|
211
|
+
const model = o.model ?? cred.model;
|
|
212
|
+
const requestId = randomUUID();
|
|
213
|
+
const res = await fetch(`${net.gateway}/chat/completions`, {
|
|
214
|
+
method: "POST",
|
|
215
|
+
headers: { "user-agent": UA, "content-type": "application/json", authorization: `Bearer ${cred.key}`, "x-request-id": requestId },
|
|
216
|
+
body: JSON.stringify({ model, messages: [{ role: "user", content: o.prompt }], max_tokens: o.maxTokens ?? 128, max_cost_flop: o.capFlop, max_wait_ms: 60_000 }),
|
|
217
|
+
});
|
|
218
|
+
const body = await res.text();
|
|
219
|
+
if (!res.ok) {
|
|
220
|
+
// A failure does not prove no paid work happened: report the ledger state, never auto-retry.
|
|
221
|
+
let ledger = "unknown";
|
|
222
|
+
try {
|
|
223
|
+
const l = await fetch(`${net.gateway}/keys/me/receipts/${encodeURIComponent(requestId)}`, { headers: { "user-agent": UA, authorization: `Bearer ${cred.key}` } });
|
|
224
|
+
if (l.ok) {
|
|
225
|
+
const row = await l.json();
|
|
226
|
+
ledger = `${row.state}, settled ${row.settled_spend ?? "unknown"}`;
|
|
227
|
+
}
|
|
228
|
+
else
|
|
229
|
+
ledger = `lookup HTTP ${l.status}`;
|
|
230
|
+
}
|
|
231
|
+
catch { }
|
|
232
|
+
const msg = body.trimStart().startsWith("<") ? "(HTML error page)" : body.slice(0, 400);
|
|
233
|
+
throw new Error(`session HTTP ${res.status} (request ${requestId}, ledger: ${ledger}): ${msg}`);
|
|
234
|
+
}
|
|
235
|
+
const j = JSON.parse(body);
|
|
236
|
+
const reply = String(j.choices?.[0]?.message?.content ?? "");
|
|
237
|
+
const xr = j.x_flop_receipt;
|
|
238
|
+
const miner = xr?.miner;
|
|
239
|
+
const receipt = {
|
|
240
|
+
ts: new Date().toISOString(),
|
|
241
|
+
agent: agent.name,
|
|
242
|
+
route: "gateway",
|
|
243
|
+
request_id: requestId,
|
|
244
|
+
model: j.model ?? model,
|
|
245
|
+
cap_flop: o.capFlop,
|
|
246
|
+
miner,
|
|
247
|
+
own_miner: !!miner && own.has(miner),
|
|
248
|
+
reply_chars: reply.length,
|
|
249
|
+
usage: j.usage,
|
|
250
|
+
x_flop_receipt: xr,
|
|
251
|
+
verified: false,
|
|
252
|
+
verification: "pending",
|
|
253
|
+
};
|
|
254
|
+
// Ledger: wait for a terminal state, then confirm its channel event on chain.
|
|
255
|
+
const end = Date.now() + (o.verifyTimeoutMs ?? 150_000);
|
|
256
|
+
let ledger;
|
|
257
|
+
while (Date.now() < end) {
|
|
258
|
+
const r = await fetch(`${net.gateway}/keys/me/receipts/${encodeURIComponent(requestId)}`, { headers: { "user-agent": UA, authorization: `Bearer ${cred.key}` } });
|
|
259
|
+
if (r.ok) {
|
|
260
|
+
ledger = await r.json();
|
|
261
|
+
if ((ledger.state === "settled" || ledger.state === "released") && ledger.terminal_event)
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
await sleep(6000);
|
|
265
|
+
}
|
|
266
|
+
receipt.ledger = ledger;
|
|
267
|
+
receipt.settled_flop = ledger?.settled_spend_raw != null ? fmtFlop(BigInt(ledger.settled_spend_raw)) : null;
|
|
268
|
+
if (!ledger)
|
|
269
|
+
receipt.verification = "no ledger row for this request id";
|
|
270
|
+
else if (!ledger.terminal_event)
|
|
271
|
+
receipt.verification = `ledger state ${ledger.state}, no terminal event yet`;
|
|
272
|
+
else {
|
|
273
|
+
const cc = await chainCheck(api, ledger.terminal_event);
|
|
274
|
+
receipt.chain_check = cc;
|
|
275
|
+
if (!cc)
|
|
276
|
+
receipt.verification = `terminal event ${ledger.terminal_event} is not a block event (not checked on chain)`;
|
|
277
|
+
else {
|
|
278
|
+
receipt.verified = cc.canonical && cc.finalized && cc.extrinsic_exists;
|
|
279
|
+
receipt.verification = receipt.verified ? "ledger terminal event found in a finalized canonical block" : "terminal event failed the chain check";
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return { reply, receipt };
|
|
283
|
+
}
|
|
284
|
+
/** Direct route via runDirectSession: the SDK verifies every turn receipt. Untested on devnet. */
|
|
285
|
+
async function directSession(net, api, agent, o, own) {
|
|
286
|
+
if (own.has(o.miner))
|
|
287
|
+
throw new Error(`refusing: ${o.miner} is listed in own-miners.json`);
|
|
288
|
+
const { runDirectSession } = await import("@flop-labs/sdk");
|
|
289
|
+
const pair = await unlockWallet(agent.name);
|
|
290
|
+
try {
|
|
291
|
+
const r = await runDirectSession({
|
|
292
|
+
api,
|
|
293
|
+
signer: pair,
|
|
294
|
+
miner: o.miner,
|
|
295
|
+
model: o.model ?? "qwen/qwen2.5-0.5b-instruct",
|
|
296
|
+
prompt: o.prompt,
|
|
297
|
+
maxFlop: toRaw(o.capFlop),
|
|
298
|
+
maxTokens: o.maxTokens ?? 128,
|
|
299
|
+
via: "auto",
|
|
300
|
+
endpoint: o.endpoint,
|
|
301
|
+
indexerUrl: net.explorer,
|
|
302
|
+
});
|
|
303
|
+
const receipt = {
|
|
304
|
+
ts: new Date().toISOString(),
|
|
305
|
+
agent: agent.name,
|
|
306
|
+
route: "direct",
|
|
307
|
+
request_id: Buffer.from(r.channelId).toString("hex"),
|
|
308
|
+
model: o.model ?? "qwen/qwen2.5-0.5b-instruct",
|
|
309
|
+
cap_flop: o.capFlop,
|
|
310
|
+
miner: r.miner,
|
|
311
|
+
own_miner: own.has(r.miner),
|
|
312
|
+
reply_chars: r.reply.length,
|
|
313
|
+
settle_tx: r.settleTx,
|
|
314
|
+
verified: r.receipts.length > 0,
|
|
315
|
+
verification: `SDK verified ${r.receipts.length} turn receipt(s); settle tx ${r.settleTx}`,
|
|
316
|
+
};
|
|
317
|
+
return { reply: r.reply, receipt };
|
|
318
|
+
}
|
|
319
|
+
finally {
|
|
320
|
+
pair.lock();
|
|
321
|
+
}
|
|
322
|
+
}
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// Ed25519 keys, did:key encoding and signing. node:crypto only.
|
|
2
|
+
import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from "node:crypto";
|
|
3
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
7
|
+
export function base58btc(bytes) {
|
|
8
|
+
let n = 0n;
|
|
9
|
+
for (const b of bytes)
|
|
10
|
+
n = (n << 8n) | BigInt(b);
|
|
11
|
+
let out = "";
|
|
12
|
+
while (n > 0n) {
|
|
13
|
+
out = B58[Number(n % 58n)] + out;
|
|
14
|
+
n /= 58n;
|
|
15
|
+
}
|
|
16
|
+
for (const b of bytes) {
|
|
17
|
+
if (b !== 0)
|
|
18
|
+
break;
|
|
19
|
+
out = "1" + out;
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
export function base58btcDecode(s) {
|
|
24
|
+
let n = 0n;
|
|
25
|
+
for (const c of s) {
|
|
26
|
+
const i = B58.indexOf(c);
|
|
27
|
+
if (i < 0)
|
|
28
|
+
throw new Error(`bad base58 character: ${c}`);
|
|
29
|
+
n = n * 58n + BigInt(i);
|
|
30
|
+
}
|
|
31
|
+
const bytes = [];
|
|
32
|
+
while (n > 0n) {
|
|
33
|
+
bytes.unshift(Number(n & 0xffn));
|
|
34
|
+
n >>= 8n;
|
|
35
|
+
}
|
|
36
|
+
for (const c of s) {
|
|
37
|
+
if (c !== "1")
|
|
38
|
+
break;
|
|
39
|
+
bytes.unshift(0);
|
|
40
|
+
}
|
|
41
|
+
return Uint8Array.from(bytes);
|
|
42
|
+
}
|
|
43
|
+
/** did:key = "did:key:z" + base58btc(0xed 0x01 || 32-byte public key) */
|
|
44
|
+
export function didFromPublicKey(pub) {
|
|
45
|
+
if (pub.length !== 32)
|
|
46
|
+
throw new Error("Ed25519 public key must be 32 bytes");
|
|
47
|
+
const buf = new Uint8Array(34);
|
|
48
|
+
buf[0] = 0xed;
|
|
49
|
+
buf[1] = 0x01;
|
|
50
|
+
buf.set(pub, 2);
|
|
51
|
+
return "did:key:z" + base58btc(buf);
|
|
52
|
+
}
|
|
53
|
+
export function publicKeyFromDid(did) {
|
|
54
|
+
if (!did.startsWith("did:key:z"))
|
|
55
|
+
throw new Error("not a did:key");
|
|
56
|
+
const raw = base58btcDecode(did.slice("did:key:z".length));
|
|
57
|
+
if (raw.length !== 34 || raw[0] !== 0xed || raw[1] !== 0x01)
|
|
58
|
+
throw new Error("not an Ed25519 did:key");
|
|
59
|
+
return raw.slice(2);
|
|
60
|
+
}
|
|
61
|
+
export function rawPublicKey(key) {
|
|
62
|
+
const jwk = key.export({ format: "jwk" });
|
|
63
|
+
if (!jwk.x)
|
|
64
|
+
throw new Error("not an Ed25519 key");
|
|
65
|
+
return Buffer.from(jwk.x, "base64url");
|
|
66
|
+
}
|
|
67
|
+
export function homeDir() {
|
|
68
|
+
return process.env.FLOP_GUILD_HOME || join(homedir(), ".flop-guild");
|
|
69
|
+
}
|
|
70
|
+
export function checkName(name) {
|
|
71
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,47}$/.test(name))
|
|
72
|
+
throw new Error(`bad key name "${name}" (use a-z, 0-9, _ and -)`);
|
|
73
|
+
return name;
|
|
74
|
+
}
|
|
75
|
+
export function keyPath(name) {
|
|
76
|
+
return join(homeDir(), `${checkName(name)}.key`);
|
|
77
|
+
}
|
|
78
|
+
/** Create a new key. Refuses to overwrite an existing one. Returns the public did only. */
|
|
79
|
+
export function keygen(name) {
|
|
80
|
+
const dir = homeDir();
|
|
81
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
82
|
+
const path = keyPath(name);
|
|
83
|
+
if (existsSync(path))
|
|
84
|
+
throw new Error(`key "${name}" already exists at ${path}; refusing to overwrite`);
|
|
85
|
+
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
|
|
86
|
+
const pem = privateKey.export({ format: "pem", type: "pkcs8" });
|
|
87
|
+
writeFileSync(path, pem, { mode: 0o600, flag: "wx" });
|
|
88
|
+
chmodSync(path, 0o600);
|
|
89
|
+
return { did: didFromPublicKey(rawPublicKey(publicKey)), path };
|
|
90
|
+
}
|
|
91
|
+
export function loadIdentity(name) {
|
|
92
|
+
const path = keyPath(name);
|
|
93
|
+
if (!existsSync(path))
|
|
94
|
+
throw new Error(`no key "${name}"; run: flop-guild keygen ${name}`);
|
|
95
|
+
const privateKey = createPrivateKey(readFileSync(path));
|
|
96
|
+
const did = didFromPublicKey(rawPublicKey(createPublicKey(privateKey)));
|
|
97
|
+
return { name, did, privateKey };
|
|
98
|
+
}
|
|
99
|
+
/** Ed25519 signature over the UTF-8 message, unpadded base64url (86 chars). */
|
|
100
|
+
export function signMessage(id, message) {
|
|
101
|
+
const sig = sign(null, Buffer.from(message, "utf8"), id.privateKey).toString("base64url");
|
|
102
|
+
if (sig.length !== 86)
|
|
103
|
+
throw new Error("unexpected signature length");
|
|
104
|
+
return sig;
|
|
105
|
+
}
|
|
106
|
+
export function verifyMessage(did, message, sig) {
|
|
107
|
+
const pub = publicKeyFromDid(did);
|
|
108
|
+
const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: Buffer.from(pub).toString("base64url") }, format: "jwk" });
|
|
109
|
+
return verify(null, Buffer.from(message, "utf8"), key, Buffer.from(sig, "base64url"));
|
|
110
|
+
}
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Stub MCP server over stdio (newline-delimited JSON-RPC 2.0). No SDK dependency.
|
|
3
|
+
import { createInterface } from "node:readline";
|
|
4
|
+
import { cmdAllow, cmdClaimRoom, cmdHeartbeat, cmdKeygen, cmdRead, cmdSay, DEFAULT_ROOM } from "./commands.js";
|
|
5
|
+
const str = (description) => ({ type: "string", description });
|
|
6
|
+
const int = (description) => ({ type: "integer", description });
|
|
7
|
+
const key = str('local key name (default "default")');
|
|
8
|
+
const room = str(`room name (default ${DEFAULT_ROOM})`);
|
|
9
|
+
const tools = [
|
|
10
|
+
{
|
|
11
|
+
name: "keygen",
|
|
12
|
+
description: "Create a new Ed25519 key and return its did:key. The secret stays on disk and is never returned.",
|
|
13
|
+
inputSchema: { type: "object", properties: { name: str("key name") }, required: ["name"] },
|
|
14
|
+
run: (a) => cmdKeygen(a.name),
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: "say",
|
|
18
|
+
description: 'Post a signed message to a room. Adds "(via flop-guild)".',
|
|
19
|
+
inputSchema: { type: "object", properties: { text: str("message"), room, key }, required: ["text"] },
|
|
20
|
+
run: (a) => cmdSay(a.key ?? "default", a.room ?? DEFAULT_ROOM, a.text),
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
name: "read",
|
|
24
|
+
description: "Read a room. Use since + wait (0..10 s) to wait for new messages.",
|
|
25
|
+
inputSchema: { type: "object", properties: { room, since: int("last seq seen"), wait: int("seconds"), limit: int("1..200") } },
|
|
26
|
+
run: (a) => cmdRead(a.room ?? DEFAULT_ROOM, { since: a.since, wait: a.wait, limit: a.limit, json: true }),
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
name: "heartbeat",
|
|
30
|
+
description: "Write the presence note hb-<nick> with the last seq seen.",
|
|
31
|
+
inputSchema: { type: "object", properties: { room, nick: str("nick"), seq: int("seq") }, required: ["nick"] },
|
|
32
|
+
run: (a) => cmdHeartbeat(a.room ?? DEFAULT_ROOM, a.nick, a.seq),
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
name: "claim_room",
|
|
36
|
+
description: "Claim ownership of a d- room. After a claim only the owner and allow-listed keys can post.",
|
|
37
|
+
inputSchema: { type: "object", properties: { room, key, fallback: str("room to try if taken") }, required: ["room"] },
|
|
38
|
+
run: (a) => cmdClaimRoom(a.key ?? "default", a.room, a.fallback),
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
name: "allow",
|
|
42
|
+
description: "Owner only: set the allow-list of did:keys that may post in an owned room.",
|
|
43
|
+
inputSchema: { type: "object", properties: { room, key, dids: { type: "array", items: { type: "string" } } }, required: ["room", "dids"] },
|
|
44
|
+
run: (a) => cmdAllow(a.key ?? "default", a.room, a.dids),
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
name: "faucet_claim",
|
|
48
|
+
description: "Claim devnet FLOP for an agent (genesis checked first). Never repeat an 'unknown' outcome: check the balance first.",
|
|
49
|
+
inputSchema: { type: "object", properties: { agent: str("agent name"), flow: { type: "string", enum: ["wallet", "did"] }, network: str("default devnet") }, required: ["agent"] },
|
|
50
|
+
run: (a) => withChain(a.network, async (net, api, f) => JSON.stringify(await f.faucetClaim(net, api, { name: a.agent }, a.flow ?? "wallet"), null, 2)),
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
name: "session",
|
|
54
|
+
description: "One inference through the gateway with a max-FLOP cap. Returns the reply and a receipt checked against the gateway ledger and the chain.",
|
|
55
|
+
inputSchema: {
|
|
56
|
+
type: "object",
|
|
57
|
+
properties: { agent: str("agent name"), prompt: str("prompt"), max_flop: { type: "number", description: "spend cap in FLOP" }, model: str("model slug"), network: str("default devnet") },
|
|
58
|
+
required: ["agent", "prompt", "max_flop"],
|
|
59
|
+
},
|
|
60
|
+
run: (a) => withChain(a.network, async (net, api, f) => {
|
|
61
|
+
const r = await f.session(net, api, { name: a.agent }, { prompt: a.prompt, capFlop: Number(a.max_flop), model: a.model, ownMiners: f.loadOwnMiners("own-miners.json") });
|
|
62
|
+
return `reply: ${r.reply}\n${JSON.stringify(r.receipt, null, 2)}`;
|
|
63
|
+
}),
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
name: "autopilot_status",
|
|
67
|
+
description: "Today's autopilot summary for a config file. Reads local state only.",
|
|
68
|
+
inputSchema: { type: "object", properties: { config: str("path, default agent.json") } },
|
|
69
|
+
run: async (a) => (await import("./autopilot.js")).status(a.config ?? "agent.json"),
|
|
70
|
+
},
|
|
71
|
+
];
|
|
72
|
+
async function withChain(network, fn) {
|
|
73
|
+
const { loadNetwork, connect } = await import("./net.js");
|
|
74
|
+
const f = await import("./flop.js");
|
|
75
|
+
const net = loadNetwork(network ?? "devnet");
|
|
76
|
+
const { api } = await connect(net);
|
|
77
|
+
try {
|
|
78
|
+
return await fn(net, api, f);
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
await api.disconnect();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function send(msg) {
|
|
85
|
+
process.stdout.write(JSON.stringify(msg) + "\n");
|
|
86
|
+
}
|
|
87
|
+
createInterface({ input: process.stdin }).on("line", async (line) => {
|
|
88
|
+
if (!line.trim())
|
|
89
|
+
return;
|
|
90
|
+
let req;
|
|
91
|
+
try {
|
|
92
|
+
req = JSON.parse(line);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } });
|
|
96
|
+
}
|
|
97
|
+
const reply = (result) => req.id !== undefined && send({ jsonrpc: "2.0", id: req.id, result });
|
|
98
|
+
switch (req.method) {
|
|
99
|
+
case "initialize":
|
|
100
|
+
return reply({
|
|
101
|
+
protocolVersion: req.params?.protocolVersion ?? "2025-06-18",
|
|
102
|
+
capabilities: { tools: {} },
|
|
103
|
+
serverInfo: { name: "flop-guild", version: "0.1.0" },
|
|
104
|
+
});
|
|
105
|
+
case "tools/list":
|
|
106
|
+
return reply({ tools: tools.map(({ run, ...t }) => t) });
|
|
107
|
+
case "tools/call": {
|
|
108
|
+
const tool = tools.find((t) => t.name === req.params?.name);
|
|
109
|
+
if (!tool)
|
|
110
|
+
return send({ jsonrpc: "2.0", id: req.id, error: { code: -32602, message: "unknown tool" } });
|
|
111
|
+
try {
|
|
112
|
+
return reply({ content: [{ type: "text", text: await tool.run(req.params.arguments ?? {}) }] });
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
return reply({ content: [{ type: "text", text: `error: ${e.message}` }], isError: true });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
case "ping":
|
|
119
|
+
return reply({});
|
|
120
|
+
default:
|
|
121
|
+
if (req.id !== undefined)
|
|
122
|
+
send({ jsonrpc: "2.0", id: req.id, error: { code: -32601, message: "method not found" } });
|
|
123
|
+
}
|
|
124
|
+
});
|
package/dist/miners.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Read-only miner ranking from the explorer's compute-channel list. No keys, no signing.
|
|
2
|
+
// Ranking is neutral: settled sessions, then settlement rate, then address. No miner is favored.
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { networksPath } from "./net.js";
|
|
5
|
+
const UA = "flop-guild/miners";
|
|
6
|
+
const PAGE = 100;
|
|
7
|
+
export function rank(channels) {
|
|
8
|
+
const by = new Map();
|
|
9
|
+
for (const c of channels) {
|
|
10
|
+
if (!c.miner)
|
|
11
|
+
continue;
|
|
12
|
+
const r = by.get(c.miner) ?? { miner: c.miner, settled: 0, timedout: 0, open: 0, rate: 0 };
|
|
13
|
+
if (c.status === "settled") {
|
|
14
|
+
r.settled += 1;
|
|
15
|
+
const t = c.settlement?.timestamp;
|
|
16
|
+
if (t && (!r.lastSettled || t > r.lastSettled))
|
|
17
|
+
r.lastSettled = t;
|
|
18
|
+
}
|
|
19
|
+
else if (c.status === "timedout")
|
|
20
|
+
r.timedout += 1;
|
|
21
|
+
else if (c.status === "open")
|
|
22
|
+
r.open += 1;
|
|
23
|
+
by.set(c.miner, r);
|
|
24
|
+
}
|
|
25
|
+
const rows = [...by.values()];
|
|
26
|
+
for (const r of rows)
|
|
27
|
+
r.rate = r.settled + r.timedout ? r.settled / (r.settled + r.timedout) : 0;
|
|
28
|
+
return rows.sort((a, b) => b.settled - a.settled || b.rate - a.rate || (a.miner < b.miner ? -1 : a.miner > b.miner ? 1 : 0));
|
|
29
|
+
}
|
|
30
|
+
async function page(base, offset) {
|
|
31
|
+
const res = await fetch(`${base}/api/compute-channels?limit=${PAGE}&offset=${offset}`, {
|
|
32
|
+
headers: { "user-agent": UA, accept: "application/json" },
|
|
33
|
+
signal: AbortSignal.timeout(20_000),
|
|
34
|
+
});
|
|
35
|
+
if (!res.ok)
|
|
36
|
+
throw new Error(`HTTP ${res.status}`);
|
|
37
|
+
const j = await res.json();
|
|
38
|
+
if (!Array.isArray(j?.data))
|
|
39
|
+
throw new Error("unexpected response shape (no data array)");
|
|
40
|
+
return { data: j.data, total: j.pagination?.total, hasMore: !!j.pagination?.hasMore };
|
|
41
|
+
}
|
|
42
|
+
export async function miners(network, limit, pages) {
|
|
43
|
+
const all = JSON.parse(readFileSync(networksPath(), "utf8"));
|
|
44
|
+
const explorer = all[network]?.explorer;
|
|
45
|
+
if (!explorer)
|
|
46
|
+
return `No explorer is configured for "${network}" in networks.json, so there is nothing to rank.`;
|
|
47
|
+
const base = explorer.replace(/\/+$/, "");
|
|
48
|
+
const channels = [];
|
|
49
|
+
let total;
|
|
50
|
+
let note = "";
|
|
51
|
+
for (let i = 0; i < pages; i++) {
|
|
52
|
+
try {
|
|
53
|
+
const p = await page(base, i * PAGE);
|
|
54
|
+
total ??= p.total;
|
|
55
|
+
channels.push(...p.data);
|
|
56
|
+
if (!p.hasMore)
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
if (i === 0)
|
|
61
|
+
return `The explorer did not answer (${base}/api/compute-channels: ${e.message}). No ranking this time; try again later.`;
|
|
62
|
+
note = `Stopped after ${i} page(s): ${e.message}. The ranking uses what was read.`;
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const rows = rank(channels);
|
|
67
|
+
const lines = [];
|
|
68
|
+
lines.push(`Miners on ${network}, from the ${channels.length} most recent compute sessions${total ? ` of ${total}` : ""} (${base}).`);
|
|
69
|
+
lines.push(`Ranked by settled sessions, then settlement rate = settled / (settled + timed out). Open sessions are not counted in the rate.`);
|
|
70
|
+
if (note)
|
|
71
|
+
lines.push(note);
|
|
72
|
+
if (!rows.length)
|
|
73
|
+
return [...lines, "No sessions with a miner were found."].join("\n");
|
|
74
|
+
lines.push("");
|
|
75
|
+
const head = ["#", "miner", "settled", "timed out", "open", "rate", "last settled (UTC)"];
|
|
76
|
+
const body = rows.slice(0, limit).map((r, i) => [
|
|
77
|
+
String(i + 1),
|
|
78
|
+
r.miner,
|
|
79
|
+
String(r.settled),
|
|
80
|
+
String(r.timedout),
|
|
81
|
+
String(r.open),
|
|
82
|
+
r.settled + r.timedout ? `${(r.rate * 100).toFixed(0)}%` : "-",
|
|
83
|
+
r.lastSettled ? new Date(r.lastSettled).toISOString().slice(0, 16).replace("T", " ") : "-",
|
|
84
|
+
]);
|
|
85
|
+
const w = head.map((h, c) => Math.max(h.length, ...body.map((b) => b[c].length)));
|
|
86
|
+
const fmt = (cells) => cells.map((x, c) => (c === 1 ? x.padEnd(w[c]) : x.padStart(w[c]))).join(" ");
|
|
87
|
+
lines.push(fmt(head), fmt(w.map((n) => "-".repeat(n))), ...body.map(fmt));
|
|
88
|
+
const top = rows[0];
|
|
89
|
+
lines.push("");
|
|
90
|
+
if (!top.settled) {
|
|
91
|
+
lines.push("No miner has a settled session in this window, so there is no top pick.");
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
lines.push(`Run a session on the top miner (${top.miner}):`);
|
|
95
|
+
lines.push(` flop --network ${network} --keystore agent.json --password-env FLOP_KEY_PASSWORD session run --miner '${top.miner}' --model qwen/qwen2.5-0.5b-instruct --prompt 'Say hi in five words.' --max-flop 0.01 --via auto --json`);
|
|
96
|
+
lines.push(" Add --endpoint <url> if the miner has no live signed offer.");
|
|
97
|
+
const own = existsSync("own-miners.json") ? JSON.parse(readFileSync("own-miners.json", "utf8")) : [];
|
|
98
|
+
if (Array.isArray(own) && own.includes(top.miner)) {
|
|
99
|
+
lines.push(" Note: this miner is listed in your own-miners.json. Spend routed to your own miner is not credited.");
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
lines.push("", "Past settlement is not a promise of future service. Read-only: no key was used.");
|
|
103
|
+
return lines.join("\n");
|
|
104
|
+
}
|