flop-guild 0.2.6 → 0.2.7
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/dist/autopilot.js +129 -28
- package/dist/content.js +256 -0
- package/dist/flop.js +55 -17
- package/dist/server.js +23 -63
- package/dist/shell.js +18 -2
- package/dist/sync-docs.js +19 -0
- package/package.json +2 -2
- package/site/guides/agent-quickstart.md +23 -5
- package/site/guides/autopilot.md +10 -5
- package/site/guides/claude-vps.md +134 -0
- package/site/guides/manual-pc.md +65 -0
- package/site/index.html +3 -166
- package/site/llms.txt +7 -4
- package/site/skill.md +16 -1
- package/skill.md +153 -0
package/dist/autopilot.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Autopilot: one agent identity per config. Faucet, enroll, run tasks under a daily budget
|
|
2
|
-
// and a per-session cap, save every receipt,
|
|
2
|
+
// and a per-session cap, save every receipt. Gateway, faucet and network trouble is logged and
|
|
3
|
+
// retried with backoff (30 s doubling to 10 min); only config and auth errors end the run.
|
|
3
4
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
4
5
|
import { request } from "node:https";
|
|
5
6
|
import { join } from "node:path";
|
|
@@ -58,12 +59,50 @@ function saveState(agent, s) {
|
|
|
58
59
|
function appendReceipt(path, rec) {
|
|
59
60
|
appendFileSync(path, JSON.stringify(rec) + "\n", { mode: 0o600 });
|
|
60
61
|
}
|
|
62
|
+
/** Errors that a retry cannot fix and that must end the run. */
|
|
63
|
+
export class ConfigError extends Error {
|
|
64
|
+
constructor(message) {
|
|
65
|
+
super(message);
|
|
66
|
+
this.name = "ConfigError";
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** auth and config errors end the run; everything else (503, provider_error, network) is retried. */
|
|
70
|
+
export function classifyError(e) {
|
|
71
|
+
if (e instanceof ConfigError)
|
|
72
|
+
return "config";
|
|
73
|
+
const status = e?.status;
|
|
74
|
+
if (status === 401 || status === 403)
|
|
75
|
+
return "auth";
|
|
76
|
+
const m = String(e?.message ?? e);
|
|
77
|
+
if (/allowance expired|not enrolled|HTTP 40[13]\b|unauthori[sz]ed|forbidden|invalid api key/i.test(m))
|
|
78
|
+
return "auth";
|
|
79
|
+
if (/genesis|networks\.json|must be|own-miners|own miner|no autopilot config|bad key name|no key "|no wallet|keystore|FLOP_GUILD_PASSPHRASE/i.test(m))
|
|
80
|
+
return "config";
|
|
81
|
+
return "transient";
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* FLOP to count for a failed session. Released or never recorded: nothing was spent.
|
|
85
|
+
* Settled: the settled amount. Anything else is unknown, so count the full cap.
|
|
86
|
+
*/
|
|
87
|
+
export function spendOnError(e, capFlop) {
|
|
88
|
+
const x = e;
|
|
89
|
+
if (x?.ledgerState === "released" || x?.ledgerState === "none")
|
|
90
|
+
return 0;
|
|
91
|
+
if (typeof x?.settledFlop === "number" && Number.isFinite(x.settledFlop))
|
|
92
|
+
return x.settledFlop;
|
|
93
|
+
return capFlop;
|
|
94
|
+
}
|
|
95
|
+
/** 30 s, 60 s, 120 s ... capped at 10 minutes. */
|
|
96
|
+
export function backoffMs(attempt, baseMs = 30_000, maxMs = 600_000) {
|
|
97
|
+
return Math.min(maxMs, baseMs * 2 ** Math.max(0, attempt));
|
|
98
|
+
}
|
|
61
99
|
export function summary(cfg, s) {
|
|
62
100
|
const left = Math.max(0, cfg.dailyBudgetFlop - s.spentFlop);
|
|
63
101
|
return [
|
|
64
102
|
`flop-guild autopilot ${cfg.agent} (${cfg.network}) ${s.day}`,
|
|
65
103
|
`sessions ${s.sessions}, verified ${s.verified}`,
|
|
66
104
|
`spent ${s.spentFlop.toFixed(6)} of ${cfg.dailyBudgetFlop} FLOP (left ${left.toFixed(6)}), cap ${cfg.perSessionCapFlop} per session`,
|
|
105
|
+
s.failedAttempts ? `failed attempts ${s.failedAttempts} (retried)` : "",
|
|
67
106
|
s.faucet ? `faucet ${s.faucet.outcome}${s.faucet.reason ? ` (${s.faucet.reason})` : ""}${s.faucet.raised ? ", balance raised" : ""}` : "faucet not claimed today",
|
|
68
107
|
s.stoppedReason ? `stopped: ${s.stoppedReason}` : "",
|
|
69
108
|
]
|
|
@@ -96,8 +135,10 @@ export function status(configPath) {
|
|
|
96
135
|
const cfg = loadConfig(configPath);
|
|
97
136
|
return summary(cfg, loadState(cfg.agent));
|
|
98
137
|
}
|
|
99
|
-
/** Run once. Never creates wallets or keys: the identity must already exist. */
|
|
100
|
-
export async function autopilot(configPath,
|
|
138
|
+
/** Run the task list once. Never creates wallets or keys: the identity must already exist. */
|
|
139
|
+
export async function autopilot(configPath, opts = {}) {
|
|
140
|
+
const log = opts.log ?? ((s) => process.stderr.write(`${new Date().toISOString()} ${s}\n`));
|
|
141
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
101
142
|
const cfg = loadConfig(configPath);
|
|
102
143
|
const tasks = loadTasks(cfg.tasks);
|
|
103
144
|
const { loadNetwork, connect } = await import("./net.js");
|
|
@@ -105,45 +146,105 @@ export async function autopilot(configPath, log = (s) => process.stderr.write(s
|
|
|
105
146
|
const agent = { name: cfg.agent };
|
|
106
147
|
const own = f.loadOwnMiners(cfg.ownMiners);
|
|
107
148
|
const state = loadState(cfg.agent);
|
|
149
|
+
state.stoppedReason = undefined; // a new run reports its own outcome
|
|
108
150
|
const flows = cfg.flow === "auto" ? ["wallet", "did"] : [cfg.flow];
|
|
109
151
|
// Identity must already exist; autopilot never generates one.
|
|
110
152
|
for (const flow of flows)
|
|
111
153
|
await f.address(agent, flow);
|
|
154
|
+
let attempt = 0;
|
|
155
|
+
const retryOrThrow = async (what, e) => {
|
|
156
|
+
const kind = classifyError(e);
|
|
157
|
+
const msg = e?.message ?? String(e);
|
|
158
|
+
if (kind !== "transient")
|
|
159
|
+
throw new ConfigError(`${what}: ${kind} error, stopping: ${msg}`);
|
|
160
|
+
const wait = backoffMs(attempt++, opts.baseMs, opts.maxMs);
|
|
161
|
+
state.failedAttempts = (state.failedAttempts ?? 0) + 1;
|
|
162
|
+
saveState(cfg.agent, state);
|
|
163
|
+
appendReceipt(cfg.receipts, { kind: "retry", ts: new Date().toISOString(), agent: cfg.agent, what, error: msg.slice(0, 500), wait_ms: wait });
|
|
164
|
+
log(`${what} failed: ${msg.split("\n")[0]}. Retrying in ${Math.round(wait / 1000)} s.`);
|
|
165
|
+
await sleep(wait);
|
|
166
|
+
};
|
|
112
167
|
const net = loadNetwork(cfg.network);
|
|
113
|
-
|
|
168
|
+
let api;
|
|
114
169
|
try {
|
|
170
|
+
for (;;) {
|
|
171
|
+
try {
|
|
172
|
+
({ api } = await connect(net)); // genesis guard: a mismatch is a config error
|
|
173
|
+
attempt = 0;
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
catch (e) {
|
|
177
|
+
await retryOrThrow("connect", e);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
115
180
|
if (cfg.claimFaucet && !state.faucet) {
|
|
116
|
-
|
|
117
|
-
|
|
181
|
+
// One claim per day. If the request fails before an answer, its outcome is unknown and it is not repeated.
|
|
182
|
+
let c;
|
|
183
|
+
try {
|
|
184
|
+
c = await f.faucetClaim(net, api, agent, flows[0]);
|
|
185
|
+
}
|
|
186
|
+
catch (e) {
|
|
187
|
+
if (classifyError(e) !== "transient")
|
|
188
|
+
throw e;
|
|
189
|
+
c = { outcome: "unknown", reason: `request failed: ${e.message}`, raised: false };
|
|
190
|
+
}
|
|
191
|
+
state.faucet = { outcome: c.outcome, reason: c.reason, raised: !!c.raised, at: new Date().toISOString() };
|
|
118
192
|
saveState(cfg.agent, state);
|
|
119
193
|
appendReceipt(cfg.receipts, { kind: "faucet", ts: state.faucet.at, agent: cfg.agent, ...c });
|
|
120
|
-
|
|
194
|
+
if (/cooldown/i.test(c.reason ?? ""))
|
|
195
|
+
log(`faucet: address on cooldown, normal; next claim after ${c.retryAfterSeconds ?? "?"} s`);
|
|
196
|
+
else
|
|
197
|
+
log(`faucet: ${c.outcome}${c.reason ? ` (${c.reason})` : ""}${c.before ? `, balance ${c.before} -> ${c.after}` : ""}`);
|
|
121
198
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
199
|
+
for (;;) {
|
|
200
|
+
let cred;
|
|
201
|
+
try {
|
|
202
|
+
cred = f.loadCredential(cfg.agent);
|
|
203
|
+
}
|
|
204
|
+
catch { }
|
|
205
|
+
if (cred && cred.expires_at > Date.now())
|
|
206
|
+
break;
|
|
207
|
+
try {
|
|
208
|
+
const r = await f.enroll(net, api, agent, flows);
|
|
209
|
+
appendReceipt(cfg.receipts, { kind: "enroll", ts: new Date().toISOString(), agent: cfg.agent, ...r });
|
|
210
|
+
if (!r.worked)
|
|
211
|
+
throw new Error(`enrollment failed: ${r.attempts.map((a) => `${a.flow}: ${a.detail}`).join("; ")}`);
|
|
212
|
+
log(`enrolled via ${r.worked} flow`);
|
|
213
|
+
attempt = 0;
|
|
214
|
+
}
|
|
215
|
+
catch (e) {
|
|
216
|
+
await retryOrThrow("enroll", e);
|
|
217
|
+
}
|
|
133
218
|
}
|
|
134
|
-
for (
|
|
219
|
+
for (let i = 0; i < tasks.length;) {
|
|
135
220
|
const left = cfg.dailyBudgetFlop - state.spentFlop;
|
|
136
221
|
if (left < cfg.perSessionCapFlop) {
|
|
137
222
|
state.stoppedReason = "daily budget reached";
|
|
138
223
|
break;
|
|
139
224
|
}
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
225
|
+
const task = tasks[i];
|
|
226
|
+
let receipt;
|
|
227
|
+
try {
|
|
228
|
+
({ receipt } = await f.session(net, api, agent, {
|
|
229
|
+
prompt: task.prompt,
|
|
230
|
+
model: task.model,
|
|
231
|
+
capFlop: cfg.perSessionCapFlop,
|
|
232
|
+
maxTokens: cfg.maxTokens,
|
|
233
|
+
ownMiners: own,
|
|
234
|
+
}));
|
|
235
|
+
}
|
|
236
|
+
catch (e) {
|
|
237
|
+
// Keep the budget honest: a released ledger spent nothing, an unknown one counts the full cap.
|
|
238
|
+
const counted = spendOnError(e, cfg.perSessionCapFlop);
|
|
239
|
+
state.spentFlop += counted;
|
|
240
|
+
saveState(cfg.agent, state);
|
|
241
|
+
const x = e;
|
|
242
|
+
appendReceipt(cfg.receipts, { kind: "session_error", ts: new Date().toISOString(), agent: cfg.agent, task: i, request_id: x.requestId, status: x.status, code: x.code, ledger_state: x.ledgerState ?? "unknown", counted_flop: counted, error: String(e.message).slice(0, 500) });
|
|
243
|
+
await retryOrThrow(`session ${i + 1}/${tasks.length}`, e);
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
attempt = 0;
|
|
247
|
+
i++;
|
|
147
248
|
appendReceipt(cfg.receipts, { kind: "session", ...receipt });
|
|
148
249
|
// Count the settled amount when known, otherwise the full cap (conservative).
|
|
149
250
|
const spent = receipt.settled_flop != null ? Number(receipt.settled_flop) : cfg.perSessionCapFlop;
|
|
@@ -155,7 +256,7 @@ export async function autopilot(configPath, log = (s) => process.stderr.write(s
|
|
|
155
256
|
log(`session ${receipt.request_id}: ${receipt.verified ? "verified" : receipt.verification}, spent ${spent}`);
|
|
156
257
|
if (receipt.own_miner) {
|
|
157
258
|
state.stoppedReason = `served by own miner ${receipt.miner}; spend to own miners is not allowed`;
|
|
158
|
-
throw new
|
|
259
|
+
throw new ConfigError(state.stoppedReason);
|
|
159
260
|
}
|
|
160
261
|
}
|
|
161
262
|
if (!state.stoppedReason)
|
|
@@ -169,7 +270,7 @@ export async function autopilot(configPath, log = (s) => process.stderr.write(s
|
|
|
169
270
|
throw new Error(`${e.message}\n${s}`);
|
|
170
271
|
}
|
|
171
272
|
finally {
|
|
172
|
-
await api
|
|
273
|
+
await api?.disconnect();
|
|
173
274
|
}
|
|
174
275
|
saveState(cfg.agent, state);
|
|
175
276
|
const s = summary(cfg, state);
|
package/dist/content.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// One source for the role steps and the guide list. The home page, skill.md, llms.txt, the agent
|
|
2
|
+
// quick start, the packaged skill.md and the hosted MCP all render from here, so they cannot drift.
|
|
3
|
+
// Text uses a small Markdown subset: `code`, [text](url), and the word PROVISIONAL.
|
|
4
|
+
import { render } from "./config.js";
|
|
5
|
+
import { esc } from "./shell.js";
|
|
6
|
+
export const ROLES = [
|
|
7
|
+
{
|
|
8
|
+
id: "agent",
|
|
9
|
+
name: "Agent",
|
|
10
|
+
sub: "Run a devnet agent from your terminal",
|
|
11
|
+
tag: "Start here",
|
|
12
|
+
need: [
|
|
13
|
+
["Hardware", "None"],
|
|
14
|
+
["Software", "Node 22 or newer. A coding agent such as Claude Code is optional."],
|
|
15
|
+
["Identity", "A did:key and a wallet (setup makes both)"],
|
|
16
|
+
["Tokens", "None: the faucet is free. Faucet limits PROVISIONAL, testnet limits are not published."],
|
|
17
|
+
["Time", "Minutes a day"],
|
|
18
|
+
],
|
|
19
|
+
steps: [
|
|
20
|
+
{
|
|
21
|
+
title: "Install Node 22",
|
|
22
|
+
cmd: { runin: "Run in: Ubuntu terminal, or WSL on Windows (not PowerShell)", code: "curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -\nsudo apt-get install -y nodejs\nnode --version" },
|
|
23
|
+
after: "On macOS, use the Node 22 installer from nodejs.org.",
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
title: "Set a passphrase of 12 or more characters",
|
|
27
|
+
cmd: { runin: "Run in: Ubuntu terminal", code: "export FLOP_GUILD_PASSPHRASE='your long passphrase here'" },
|
|
28
|
+
after: "This password locks your agent's keys on your own machine. It never leaves your computer, it only lasts for this terminal window, and if you lose it the keys can't be recovered. Save it in a password manager.",
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
title: "Run setup",
|
|
32
|
+
before: "Makes the did:key and the wallet, claims the faucet, enrolls with the gateway and writes the autopilot config. Add `--no-announce` to skip the public hello in {{ROOM}}.",
|
|
33
|
+
cmd: { code: "npx flop-guild setup myagent" },
|
|
34
|
+
},
|
|
35
|
+
{ title: "Check the identity and the balance", cmd: { code: "npx flop-guild whoami --key myagent\nnpx flop-guild balance myagent" } },
|
|
36
|
+
{
|
|
37
|
+
title: "Run the autopilot",
|
|
38
|
+
before: "The daily budget and the per-spend cap were set by setup in agent.json. Gateway and network errors are logged and retried with backoff; it stops only on config or auth errors.",
|
|
39
|
+
cmd: { code: "npx flop-guild autopilot --config agent.json" },
|
|
40
|
+
},
|
|
41
|
+
{ title: "Verify", before: "Find your did:key in the [{{ROOM}}]({{ROOM_URL}}) room on Technocore." },
|
|
42
|
+
],
|
|
43
|
+
notes: [
|
|
44
|
+
"This runs on devnet until Flop publishes testnet endpoints. Devnet earns nothing and no airdrop is promised.",
|
|
45
|
+
"More: [Start](/start) (make a key in the browser), [Agent quick start](/guides/agent-quickstart), [Autopilot](/guides/autopilot), [Join the guild](/guides/join-guild).",
|
|
46
|
+
],
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
id: "miner",
|
|
50
|
+
name: "Miner",
|
|
51
|
+
sub: "Serve inference from your own GPU host",
|
|
52
|
+
need: [
|
|
53
|
+
["GPU", "NVIDIA, 16 GB VRAM or more PROVISIONAL"],
|
|
54
|
+
["Host", "Docker, Docker Compose and the NVIDIA Container Toolkit"],
|
|
55
|
+
["Network", "A public DNS name with ports 80 and 443 open, or a tunnel to 127.0.0.1:8645"],
|
|
56
|
+
["Disk", "About 56 GB for the model checkpoint, plus volumes"],
|
|
57
|
+
["Account", "A dedicated sr25519 account, separate from any validator"],
|
|
58
|
+
["Stake", "Sponsored on devnet. Testnet PROVISIONAL"],
|
|
59
|
+
],
|
|
60
|
+
steps: [
|
|
61
|
+
{ title: "Get a GPU host", before: "Renting capacity alone is not mining: whoever operates the host owns the miner account." },
|
|
62
|
+
{ title: "Install the host software", before: "The NVIDIA driver, Docker, Docker Compose and the NVIDIA Container Toolkit." },
|
|
63
|
+
{ title: "Point a DNS name, or a tunnel, at the host" },
|
|
64
|
+
{ title: "Create the dedicated miner account" },
|
|
65
|
+
{ title: "Get the miner software", before: "From Flop's miner manual. Verify its checksums." },
|
|
66
|
+
{ title: "Rehearse on devnet first" },
|
|
67
|
+
{
|
|
68
|
+
title: "Complete calibration",
|
|
69
|
+
before: "The whole host is calibrated once, an uncalibrated host returns 503, and a calibration job left unanswered past its deadline is slashed. Job counts PROVISIONAL",
|
|
70
|
+
},
|
|
71
|
+
{ title: "Switch to testnet when the endpoints are published" },
|
|
72
|
+
],
|
|
73
|
+
notes: [
|
|
74
|
+
"One miner account per host. A second account on the same host adds nothing.",
|
|
75
|
+
"Estimate demand and earnings with the [miner calculator](/miner), or see the devnet ranking:",
|
|
76
|
+
{ code: "npx flop-guild miners" },
|
|
77
|
+
],
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
id: "validator",
|
|
81
|
+
name: "Validator",
|
|
82
|
+
sub: "Testnet validator prep, summary only",
|
|
83
|
+
need: [
|
|
84
|
+
["CPU", "8 dedicated cores PROVISIONAL"],
|
|
85
|
+
["RAM", "32 GB (64 GB on the testnet page) PROVISIONAL"],
|
|
86
|
+
["Storage", "4 TB NVMe PROVISIONAL"],
|
|
87
|
+
["Network", "1 Gbps PROVISIONAL"],
|
|
88
|
+
["Ports", "30333 (P2P) and 7001 (DA) PROVISIONAL"],
|
|
89
|
+
],
|
|
90
|
+
steps: [
|
|
91
|
+
{ title: "Read Flop's validator prep kit", before: "[docs.flop.network/testnet-validator-prep](https://docs.flop.network/testnet-validator-prep/)" },
|
|
92
|
+
{ title: "Register your team", before: "Through Flop's GitHub issue form (first 50 testnet validators)." },
|
|
93
|
+
{ title: "Generate keys only after Flop announces the runtime freeze" },
|
|
94
|
+
{ title: "Follow Flop's operator onboarding" },
|
|
95
|
+
],
|
|
96
|
+
notes: ["This kit does not run validators yet."],
|
|
97
|
+
},
|
|
98
|
+
];
|
|
99
|
+
/** Listed on the home page, in skill.md, llms.txt and the MCP. Each slug has site/guides/<slug>.md. */
|
|
100
|
+
export const GUIDES = [
|
|
101
|
+
{ slug: "claude-vps", title: "Claude subscription: get a VPS and let Claude Code set up your agent", summary: "A small Ubuntu VPS, Claude Code does the setup, systemd keeps the autopilot running." },
|
|
102
|
+
{ slug: "manual-pc", title: "Run it yourself on your own PC", summary: "WSL Ubuntu on Windows, or a Mac or Linux terminal: Node 22, passphrase, setup, autopilot." },
|
|
103
|
+
{ slug: "agent-quickstart", title: "Agent quick start", summary: "The role steps, then wallet, faucet, enrollment and one capped session by hand." },
|
|
104
|
+
{ slug: "autopilot", title: "Autopilot", summary: "Daily budget, per-session cap, receipts, retries." },
|
|
105
|
+
{ slug: "join-guild", title: "Join the guild", summary: "did:key, first signed message, reading the room." },
|
|
106
|
+
];
|
|
107
|
+
// ---------- Markdown subset ----------
|
|
108
|
+
/** Inline Markdown: escape, then `code`, [text](url) and the PROVISIONAL tag. */
|
|
109
|
+
export function inline(s) {
|
|
110
|
+
return esc(s)
|
|
111
|
+
.replace(/`([^`]+)`/g, "<code>$1</code>")
|
|
112
|
+
.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+|\/[^)\s]*)\)/g, '<a href="$2">$1</a>')
|
|
113
|
+
.replace(/\bPROVISIONAL\b(?![^<]*<\/code>)/g, '<span class="prov">PROVISIONAL</span>');
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Headings, paragraphs, lists, indented code, inline code and links. A paragraph that is a single
|
|
117
|
+
* "Run in: ..." line right before a code block becomes that block's label.
|
|
118
|
+
*/
|
|
119
|
+
export function mdToHtml(md) {
|
|
120
|
+
const out = [];
|
|
121
|
+
let para = [];
|
|
122
|
+
let list = [];
|
|
123
|
+
let ordered = false;
|
|
124
|
+
let code = [];
|
|
125
|
+
const flush = () => {
|
|
126
|
+
if (para.length)
|
|
127
|
+
out.push(`<p>${inline(para.join(" "))}</p>`), (para = []);
|
|
128
|
+
if (list.length)
|
|
129
|
+
out.push(`<${ordered ? "ol" : "ul"}>${list.map((l) => `<li>${inline(l)}</li>`).join("")}</${ordered ? "ol" : "ul"}>`), (list = []);
|
|
130
|
+
if (code.length) {
|
|
131
|
+
const prev = out.at(-1)?.match(/^<p>(Run in: [^<]*)<\/p>$/);
|
|
132
|
+
if (prev)
|
|
133
|
+
out.pop();
|
|
134
|
+
out.push(`<pre${prev ? ` data-runin="${prev[1]}"` : ""}><code>${esc(code.join("\n"))}</code></pre>`);
|
|
135
|
+
code = [];
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
for (const line of md.split("\n")) {
|
|
139
|
+
if (/^ {4}/.test(line) && !list.length) {
|
|
140
|
+
if (para.length)
|
|
141
|
+
flush();
|
|
142
|
+
code.push(line.slice(4));
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (code.length && line.trim() === "") {
|
|
146
|
+
code.push("");
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (code.length) {
|
|
150
|
+
while (code.at(-1) === "")
|
|
151
|
+
code.pop();
|
|
152
|
+
flush();
|
|
153
|
+
}
|
|
154
|
+
const h = line.match(/^(#{1,3}) (.*)$/);
|
|
155
|
+
const li = line.match(/^(?:- |(\d+)\. )(.*)$/);
|
|
156
|
+
if (h)
|
|
157
|
+
flush(), out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
|
|
158
|
+
else if (li) {
|
|
159
|
+
if (para.length)
|
|
160
|
+
flush();
|
|
161
|
+
ordered = !!li[1];
|
|
162
|
+
list.push(li[2]);
|
|
163
|
+
}
|
|
164
|
+
else if (line.trim() === "")
|
|
165
|
+
flush();
|
|
166
|
+
else if (list.length && /^ {2,}/.test(line))
|
|
167
|
+
list[list.length - 1] += " " + line.trim();
|
|
168
|
+
else
|
|
169
|
+
para.push(line.trim());
|
|
170
|
+
}
|
|
171
|
+
while (code.at(-1) === "")
|
|
172
|
+
code.pop();
|
|
173
|
+
flush();
|
|
174
|
+
return out.join("\n");
|
|
175
|
+
}
|
|
176
|
+
// ---------- renderers ----------
|
|
177
|
+
const absLinks = (s) => s.replace(/\]\(\//g, "]({{PUBLIC_URL}}/");
|
|
178
|
+
function cmdMd(c) {
|
|
179
|
+
return `${c.runin ?? "Run in: Ubuntu, macOS Terminal, or WSL on Windows (not PowerShell)"}\n\n${c.code
|
|
180
|
+
.split("\n")
|
|
181
|
+
.map((l) => " " + l)
|
|
182
|
+
.join("\n")}\n`;
|
|
183
|
+
}
|
|
184
|
+
/** Markdown for one role or all three. Same text as the home page. */
|
|
185
|
+
export function roleMd(r, level = 2) {
|
|
186
|
+
const h = "#".repeat(level);
|
|
187
|
+
const parts = [`${h} ${r.name}${r.tag ? ` (${r.tag.toLowerCase()})` : ""}`, "", `${r.sub}.`, "", "What you need:", "", ...r.need.map(([k, v]) => `- ${k}: ${v}`), "", "Steps:", ""];
|
|
188
|
+
r.steps.forEach((s, i) => {
|
|
189
|
+
parts.push(`${h}# ${r.name} step ${i + 1}: ${s.title}`, "");
|
|
190
|
+
if (s.before)
|
|
191
|
+
parts.push(s.before, "");
|
|
192
|
+
if (s.cmd)
|
|
193
|
+
parts.push(cmdMd(s.cmd));
|
|
194
|
+
if (s.after)
|
|
195
|
+
parts.push(s.after, "");
|
|
196
|
+
});
|
|
197
|
+
for (const n of r.notes)
|
|
198
|
+
parts.push(typeof n === "string" ? n : cmdMd(n), "");
|
|
199
|
+
return absLinks(parts.join("\n")).replace(/\n{3,}/g, "\n\n");
|
|
200
|
+
}
|
|
201
|
+
export function rolesMd(level = 2) {
|
|
202
|
+
return ROLES.map((r) => roleMd(r, level)).join("\n");
|
|
203
|
+
}
|
|
204
|
+
export function guidesMd() {
|
|
205
|
+
return GUIDES.map((g) => `- [${g.title}]({{PUBLIC_URL}}/guides/${g.slug}) ([Markdown]({{PUBLIC_URL}}/guides/${g.slug}.md)): ${g.summary}`).join("\n");
|
|
206
|
+
}
|
|
207
|
+
/** Fill {{ROLES_MD}}, {{ROLE_MD:agent}}, {{GUIDES_MD}}, then the host and room placeholders. */
|
|
208
|
+
export function expand(template) {
|
|
209
|
+
return render(template
|
|
210
|
+
.replace(/\{\{ROLE_MD:(agent|miner|validator)\}\}/g, (_m, id) => roleMd(ROLES.find((r) => r.id === id), 2))
|
|
211
|
+
.replaceAll("{{ROLES_MD}}", rolesMd(2))
|
|
212
|
+
.replaceAll("{{GUIDES_MD}}", guidesMd()));
|
|
213
|
+
}
|
|
214
|
+
function cmdHtml(c) {
|
|
215
|
+
return `<pre${c.runin ? ` data-runin="${esc(c.runin)}"` : ""}><code>${esc(c.code)}</code></pre>`;
|
|
216
|
+
}
|
|
217
|
+
/** The role tabs and panels on the home page. Icons come from the shell. */
|
|
218
|
+
export function rolesHtml(icons) {
|
|
219
|
+
const tabs = ROLES.map((r, i) => ` <button type="button" class="role" role="tab" id="tab-${r.id}" aria-controls="panel-${r.id}" aria-selected="${i === 0}">
|
|
220
|
+
<span class="role-top"><span class="tile">${icons[r.id] ?? ""}</span><span class="role-name">${esc(r.name)}</span>${r.tag ? `<span class="tag">${esc(r.tag)}</span>` : ""}</span>
|
|
221
|
+
<span class="role-sub">${esc(r.sub)}</span>
|
|
222
|
+
<span class="prog"><span class="prog-text">0 of ${r.steps.length} done</span><span class="bar"><span class="fill"></span></span></span>
|
|
223
|
+
</button>`).join("\n");
|
|
224
|
+
const panels = ROLES.map((r) => {
|
|
225
|
+
const need = r.need.map(([k, v]) => `<tr><th>${esc(k)}</th><td>${inline(v)}</td></tr>`).join("\n");
|
|
226
|
+
const steps = r.steps
|
|
227
|
+
.map((s, i) => `<li class="step"><div class="card step-card">
|
|
228
|
+
<div class="step-head"><input type="checkbox" class="step-done" aria-label="Mark step ${i + 1} done"><h3>${inline(s.title)}</h3></div>
|
|
229
|
+
${s.before ? `<p class="muted small">${inline(s.before)}</p>\n` : ""}${s.cmd ? cmdHtml(s.cmd) + "\n" : ""}${s.after ? `<p class="muted small">${inline(s.after)}</p>\n` : ""}</div></li>`)
|
|
230
|
+
.join("\n");
|
|
231
|
+
const notes = r.notes.map((n, i) => (typeof n === "string" ? `<p${i === 0 ? ' class="note"' : ""}>${inline(n)}</p>` : cmdHtml(n))).join("\n");
|
|
232
|
+
return `<section class="panel" role="tabpanel" id="panel-${r.id}" aria-labelledby="tab-${r.id}" data-role="${r.id}">
|
|
233
|
+
<h2 class="panel-title">${esc(r.name)}</h2>
|
|
234
|
+
<div class="panel-grid">
|
|
235
|
+
<aside class="card need-card">
|
|
236
|
+
<h3>What you need</h3>
|
|
237
|
+
<table class="need">
|
|
238
|
+
${need}
|
|
239
|
+
</table>
|
|
240
|
+
</aside>
|
|
241
|
+
<div class="steps-col">
|
|
242
|
+
<ol class="timeline">
|
|
243
|
+
${steps}
|
|
244
|
+
</ol>
|
|
245
|
+
<div class="card notes">
|
|
246
|
+
${notes}
|
|
247
|
+
</div>
|
|
248
|
+
</div>
|
|
249
|
+
</div>
|
|
250
|
+
</section>`;
|
|
251
|
+
}).join("\n\n");
|
|
252
|
+
return `<div class="roles" role="tablist" aria-label="Roles">\n${tabs}\n</div>\n\n${panels}`;
|
|
253
|
+
}
|
|
254
|
+
export function guidesHtml(icon) {
|
|
255
|
+
return `<div class="agent-links">\n${GUIDES.map((g) => ` <a class="card link-card" href="/guides/${g.slug}"><span class="tile">${icon}</span><span><b>${esc(g.title)}</b><span class="muted small">${esc(g.summary)}</span></span></a>`).join("\n")}\n</div>`;
|
|
256
|
+
}
|
package/dist/flop.js
CHANGED
|
@@ -198,6 +198,40 @@ async function chainCheck(api, terminal) {
|
|
|
198
198
|
extrinsic_exists: extrinsic < block.block.extrinsics.length,
|
|
199
199
|
};
|
|
200
200
|
}
|
|
201
|
+
/** A failed gateway session, with what the ledger says about the money. */
|
|
202
|
+
export class SessionError extends Error {
|
|
203
|
+
status;
|
|
204
|
+
requestId;
|
|
205
|
+
ledgerState;
|
|
206
|
+
settledFlop;
|
|
207
|
+
code;
|
|
208
|
+
constructor(message, status, // HTTP status, 0 for a network error
|
|
209
|
+
requestId, ledgerState, // "released", "settled", ..., "none" (no row), undefined (lookup failed)
|
|
210
|
+
settledFlop, code) {
|
|
211
|
+
super(message);
|
|
212
|
+
this.status = status;
|
|
213
|
+
this.requestId = requestId;
|
|
214
|
+
this.ledgerState = ledgerState;
|
|
215
|
+
this.settledFlop = settledFlop;
|
|
216
|
+
this.code = code;
|
|
217
|
+
this.name = "SessionError";
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async function ledgerRow(net, key, requestId) {
|
|
221
|
+
try {
|
|
222
|
+
const l = await fetch(`${net.gateway}/keys/me/receipts/${encodeURIComponent(requestId)}`, { headers: { "user-agent": UA, authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(20_000) });
|
|
223
|
+
if (l.status === 404)
|
|
224
|
+
return { state: "none", text: "no ledger row" };
|
|
225
|
+
if (!l.ok)
|
|
226
|
+
return { text: `lookup HTTP ${l.status}` };
|
|
227
|
+
const row = await l.json();
|
|
228
|
+
const settled = row.settled_spend_raw != null ? Number(fmtFlop(BigInt(row.settled_spend_raw))) : undefined;
|
|
229
|
+
return { state: row.state, settled, text: `${row.state}, settled ${row.settled_spend ?? "unknown"}` };
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
return { text: "unknown" };
|
|
233
|
+
}
|
|
234
|
+
}
|
|
201
235
|
/** Gateway route: bearer from enrollment, max_cost_flop cap, then ledger + on-chain check of the receipt. */
|
|
202
236
|
export async function session(net, api, agent, o) {
|
|
203
237
|
if (!(o.capFlop > 0))
|
|
@@ -210,27 +244,31 @@ export async function session(net, api, agent, o) {
|
|
|
210
244
|
throw new Error("gateway allowance expired; it cannot be renewed by re-enrolling");
|
|
211
245
|
const model = o.model ?? cred.model;
|
|
212
246
|
const requestId = randomUUID();
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
247
|
+
let res;
|
|
248
|
+
let body;
|
|
249
|
+
try {
|
|
250
|
+
res = await fetch(`${net.gateway}/chat/completions`, {
|
|
251
|
+
method: "POST",
|
|
252
|
+
headers: { "user-agent": UA, "content-type": "application/json", authorization: `Bearer ${cred.key}`, "x-request-id": requestId },
|
|
253
|
+
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 }),
|
|
254
|
+
});
|
|
255
|
+
body = await res.text();
|
|
256
|
+
}
|
|
257
|
+
catch (e) {
|
|
258
|
+
const l = await ledgerRow(net, cred.key, requestId);
|
|
259
|
+
throw new SessionError(`session network error (request ${requestId}, ledger: ${l.text}): ${e.message}`, 0, requestId, l.state, l.settled);
|
|
260
|
+
}
|
|
219
261
|
if (!res.ok) {
|
|
220
|
-
// A failure does not prove no paid work happened: report the ledger state
|
|
221
|
-
|
|
262
|
+
// A failure does not prove no paid work happened: report the ledger state; the caller decides about retries.
|
|
263
|
+
const l = await ledgerRow(net, cred.key, requestId);
|
|
264
|
+
const msg = body.trimStart().startsWith("<") ? "(HTML error page)" : body.slice(0, 400);
|
|
265
|
+
let code;
|
|
222
266
|
try {
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
const row = await l.json();
|
|
226
|
-
ledger = `${row.state}, settled ${row.settled_spend ?? "unknown"}`;
|
|
227
|
-
}
|
|
228
|
-
else
|
|
229
|
-
ledger = `lookup HTTP ${l.status}`;
|
|
267
|
+
const j = JSON.parse(body);
|
|
268
|
+
code = j?.error?.code ?? j?.error?.type ?? j?.code;
|
|
230
269
|
}
|
|
231
270
|
catch { }
|
|
232
|
-
|
|
233
|
-
throw new Error(`session HTTP ${res.status} (request ${requestId}, ledger: ${ledger}): ${msg}`);
|
|
271
|
+
throw new SessionError(`session HTTP ${res.status} (request ${requestId}, ledger: ${l.text}): ${msg}`, res.status, requestId, l.state, l.settled, code);
|
|
234
272
|
}
|
|
235
273
|
const j = JSON.parse(body);
|
|
236
274
|
const reply = String(j.choices?.[0]?.message?.content ?? "");
|