tryflop 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/src/cli.js ADDED
@@ -0,0 +1,428 @@
1
+ // The flop-mcp commands. bin/flop-mcp.mjs loads this only after ensureSandboxed(), so everything here
2
+ // (and everything it imports) runs inside the sandbox.
3
+ import { appendFileSync, existsSync, readFileSync, realpathSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { parseArgs } from 'node:util';
7
+ import { NETWORKS } from './shared/config.js';
8
+ import { formatFlop } from './shared/units.js';
9
+ import { defaultLimits, HomeError, homeRoot, loadSettings, networkHome, parseSettings, saveSettings } from './home.js';
10
+ import { createKey, KeyError, loadKey } from './keyfile.js';
11
+ import { payersRoot } from './roots.js';
12
+
13
+ const BIN = realpathSync(fileURLToPath(new URL('../bin/flop-mcp.mjs', import.meta.url)));
14
+ const INIT_USAGE = 'usage: flop-mcp init --owner <your wallet address> [--network devnet|testnet] [--max-per-ask <FLOP>] [--max-per-day <FLOP>] [--max-total <FLOP>]';
15
+ const CLAIM_USAGE = 'usage: flop-mcp claim --network testnet [--yes]';
16
+
17
+ /**
18
+ * @typedef {{ out: { write(text: string): unknown }, err: { write(text: string): unknown }, env: NodeJS.ProcessEnv, execPath: string,
19
+ * stdin?: NodeJS.ReadableStream & { isTTY?: boolean } }} Io stdin: where claim asks before it sends (default: this process's)
20
+ */
21
+
22
+ /** @param {Io} io @param {string} problem */
23
+ function usage(io, problem) {
24
+ io.err.write(`flop-mcp: ${problem}\n${INIT_USAGE}\n`);
25
+ return 2;
26
+ }
27
+
28
+ /** A path as one shell word: unchanged when plain, single-quoted otherwise. @param {string} text */
29
+ export function shellQuote(text) {
30
+ return /^[A-Za-z0-9_/.@:+=,-]+$/.test(text) ? text : `'${text.replace(/'/g, "'\\''")}'`;
31
+ }
32
+
33
+ /**
34
+ * A network the connector may run on: known and opened by Flop. serve, status and retire need no more:
35
+ * their housekeeping and retire get escrow and fee money BACK, which must keep working when no miner is
36
+ * listed (review, 26 Nov).
37
+ * @param {string} name @param {typeof NETWORKS} [networks] stand-ins in tests
38
+ * @returns {import('./shared/config.js').NetworkConfig | string} the config, or why not
39
+ */
40
+ export function liveNetwork(name, networks = NETWORKS) {
41
+ if (!Object.hasOwn(networks, name)) return `there is no Flop network called "${name}" (devnet or testnet).`;
42
+ const network = networks[/** @type {'devnet'|'testnet'} */ (name)];
43
+ if (network.status !== 'live') return `Flop has not published ${name} yet, so the connector cannot use it.`;
44
+ return network;
45
+ }
46
+
47
+ /**
48
+ * A network the connector may be SET UP on (init): opened, readable by this build, and with a miner to
49
+ * pay. Opened is not enough: testnet opened on 24 Nov 2026 with no miner, so a set-up there would end in
50
+ * errors at the first question.
51
+ * @param {string} name @param {typeof NETWORKS} [networks] stand-ins in tests
52
+ * @returns {import('./shared/config.js').NetworkConfig | string} the config, or why not
53
+ */
54
+ export function payableNetwork(name, networks = NETWORKS) {
55
+ const network = liveNetwork(name, networks);
56
+ if (typeof network === 'string') return network;
57
+ if (!network.readable) return `this build cannot read ${name} yet (its Flop SDK does not know that network's runtime), so the connector cannot be set up there.`;
58
+ if (!network.miners.length) return `Flop lists no miner on ${name} yet, so there is nothing to pay and the connector cannot be set up there.`;
59
+ return network;
60
+ }
61
+
62
+ /**
63
+ * The steps after init, by where the session key's fee money comes from: on a network whose faucet takes the key's own
64
+ * signed claim (testnet), the key claims it and passes the rest to the owner, whose wallet may still be empty; elsewhere
65
+ * the owner's wallet sends it.
66
+ * @param {import('./shared/config.js').NetworkConfig} network @param {string} execPath
67
+ * @returns {string[]}
68
+ */
69
+ export function initSteps(network, execPath) {
70
+ const command = (/** @type {string[]} */ ...args) => [shellQuote(execPath), shellQuote(BIN), ...args].join(' ');
71
+ const limit = 'give the session key above a spending limit on Flop, for compute only (ComputeChannel), for example 5 FLOP for 7 days.';
72
+ const funding = network.quickGrant?.signed
73
+ ? [
74
+ `1. Get ${network.name} FLOP (your wallet needs none for this). Run:`,
75
+ ` ${command('claim', '--network', network.name)}`,
76
+ ` The connector asks Flop's ${network.name} faucet for ${network.quickGrant.flop} FLOP for its own key, keeps 0.5 FLOP for its network fees and offers to send the rest to your wallet.`,
77
+ `2. In your wallet, ${limit}`,
78
+ ]
79
+ : [`1. In your wallet, ${limit}`, '2. From your wallet, send the session key 0.5 FLOP for network fees.'];
80
+ return [
81
+ 'Next steps:',
82
+ ...funding,
83
+ '3. Add it to Claude Code. In the project folder where you want to use it, run:',
84
+ ` claude mcp add flop -- ${command('serve', '--network', network.name)}`,
85
+ ];
86
+ }
87
+
88
+ /**
89
+ * flop-mcp init: make this network's session key and save the owner and the local limits.
90
+ * @param {string[]} args @param {Io} io @param {typeof NETWORKS} [networks] stand-ins in tests
91
+ * @returns {Promise<number>} exit code
92
+ */
93
+ export async function runInit(args, io, networks = NETWORKS) {
94
+ let values;
95
+ try {
96
+ ({ values } = parseArgs({
97
+ args,
98
+ options: {
99
+ owner: { type: 'string' },
100
+ network: { type: 'string', default: 'devnet' },
101
+ 'max-per-ask': { type: 'string' },
102
+ 'max-per-day': { type: 'string' },
103
+ 'max-total': { type: 'string' },
104
+ },
105
+ strict: true,
106
+ allowPositionals: false,
107
+ }));
108
+ } catch (error) {
109
+ return usage(io, /** @type {Error} */ (error).message);
110
+ }
111
+ if (!values.owner) return usage(io, '--owner is required: the address of the wallet that will pay for the answers.');
112
+ const network = payableNetwork(values.network, networks);
113
+ if (typeof network === 'string') return usage(io, network);
114
+ const defaults = defaultLimits(network.name);
115
+ let settings;
116
+ try {
117
+ settings = parseSettings({
118
+ owner: values.owner,
119
+ maxFlopPerAsk: values['max-per-ask'] ?? defaults.maxFlopPerAsk,
120
+ maxFlopPerDay: values['max-per-day'] ?? defaults.maxFlopPerDay,
121
+ maxFlopTotal: values['max-total'] ?? defaults.maxFlopTotal,
122
+ idleSettleSeconds: defaults.idleSettleSeconds,
123
+ });
124
+ } catch (error) {
125
+ if (error instanceof HomeError && error.code === 'BAD_SETTINGS') return usage(io, error.message.replace(/^config\.json: /, ''));
126
+ throw error;
127
+ }
128
+
129
+ const home = networkHome(homeRoot(io.env), network.name);
130
+ let address;
131
+ try {
132
+ ({ address } = await createKey(home, { genesis: network.genesis }));
133
+ } catch (error) {
134
+ if (!(error instanceof KeyError && error.code === 'EXISTS')) throw error;
135
+ if (existsSync(home.settingsFile)) {
136
+ io.err.write(`flop-mcp: ${network.name} already has a session key; it was left unchanged. To change the owner or the limits, edit ${home.settingsFile}.\n`);
137
+ return 1;
138
+ }
139
+ // An earlier init stopped after making the key: finish it with these settings.
140
+ ({ address } = await loadKey(home, { genesis: network.genesis }));
141
+ }
142
+ saveSettings(home, settings);
143
+ io.out.write([
144
+ `Flop connector is set up for ${network.name}.`,
145
+ 'An independent tool, not made by Flop Labs.',
146
+ '',
147
+ `Session key (give THIS address a spending limit): ${address}`,
148
+ `Owner (your wallet, which pays for the answers): ${settings.owner}`,
149
+ `Limits on this computer: ${formatFlop(settings.maxFlopPerAsk)} FLOP per answer, ${formatFlop(settings.maxFlopPerDay)} FLOP per day, ${formatFlop(settings.maxFlopTotal)} FLOP in total.`,
150
+ `Files: ${home.dir} (the key never leaves this computer and is never printed).`,
151
+ '',
152
+ ...initSteps(network, io.execPath),
153
+ '',
154
+ ].join('\n'));
155
+ return 0;
156
+ }
157
+
158
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
159
+
160
+ /** The real clock (timers do not keep the process alive on their own). */
161
+ export const realClock = {
162
+ now: () => Date.now(),
163
+ /** @param {number} ms @param {AbortSignal} [signal] */
164
+ sleep: (ms, signal) => new Promise((resolve, reject) => {
165
+ const timer = setTimeout(resolve, ms);
166
+ signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
167
+ }),
168
+ /** @param {number} ms @param {() => void} fn */
169
+ setTimer: (ms, fn) => {
170
+ const timer = setTimeout(fn, ms);
171
+ timer.unref();
172
+ return () => clearTimeout(timer);
173
+ },
174
+ };
175
+
176
+ /**
177
+ * Load what every running command needs: the network, its folder, the key and the settings.
178
+ * @param {string[]} args @param {Io} io
179
+ * @returns {Promise<{ network: any, home: import('./home.js').Home, key: { address: string, pair: any }, settings: import('./home.js').Settings } | number>}
180
+ * the parts, or an exit code after explaining the problem on stderr
181
+ */
182
+ async function loadSetup(args, io) {
183
+ let values;
184
+ try {
185
+ ({ values } = parseArgs({ args, options: { network: { type: 'string', default: 'devnet' } }, strict: true, allowPositionals: false }));
186
+ } catch (error) {
187
+ io.err.write(`flop-mcp: ${/** @type {Error} */ (error).message}\n`);
188
+ return 2;
189
+ }
190
+ const network = liveNetwork(values.network);
191
+ if (typeof network === 'string') {
192
+ io.err.write(`flop-mcp: ${network}\n`);
193
+ return 2;
194
+ }
195
+ const home = networkHome(homeRoot(io.env), network.name);
196
+ try {
197
+ const key = await loadKey(home, { genesis: network.genesis });
198
+ const settings = loadSettings(home);
199
+ return { network, home, key, settings };
200
+ } catch (error) {
201
+ const missing = /** @type {any} */ (error).code === 'MISSING';
202
+ io.err.write(missing
203
+ ? `flop-mcp: ${network.name} is not set up yet. Run: flop-mcp init --owner <your wallet address> --network ${network.name}\n`
204
+ : `flop-mcp: ${/** @type {Error} */ (error).message}\n`);
205
+ return 1;
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Log lines go to stderr and to <network folder>/server.log (0600): lifecycle and errors only, never a
211
+ * prompt, an answer or a key.
212
+ * @param {Io} io @param {import('./home.js').Home} home
213
+ */
214
+ function logger(io, home) {
215
+ return (/** @type {string} */ line) => {
216
+ const text = `flop-mcp ${new Date().toISOString()} ${line}\n`;
217
+ io.err.write(text);
218
+ try {
219
+ appendFileSync(join(home.dir, 'server.log'), text, { mode: 0o600 });
220
+ } catch {
221
+ // stderr still has it
222
+ }
223
+ };
224
+ }
225
+
226
+ /** @param {{ network: any, home: any, key: any, settings: any }} setup @param {Io} io */
227
+ async function makePayer({ network, home, key, settings }, io) {
228
+ const [{ Payer }, adapter] = await Promise.all([import('./payer.js'), import('./flop-node.js')]);
229
+ return new Payer({ adapter, home, settings, key, network, payersRoot: payersRoot(io.env), clock: realClock, log: logger(io, home) });
230
+ }
231
+
232
+ /**
233
+ * flop-mcp serve: the MCP server Claude Code starts. stdout carries only MCP messages: every console
234
+ * method writes to stderr from here on. Stops when stdin closes or on SIGTERM/SIGINT: it starts the
235
+ * open batch's close (the cooperative claim reaches the miner first) and exits within the grace period.
236
+ * @param {string[]} args @param {Io} io @returns {Promise<number>}
237
+ */
238
+ export async function runServe(args, io) {
239
+ for (const method of /** @type {const} */ (['log', 'info', 'debug', 'warn'])) {
240
+ console[method] = (...parts) => { io.err.write(`${parts.map(String).join(' ')}\n`); };
241
+ }
242
+ const setup = await loadSetup(args, io);
243
+ if (typeof setup === 'number') return setup;
244
+ const payer = await makePayer(setup, io);
245
+ const { serve } = await import('./server.js');
246
+ // Answer Claude at once (it waits 30 s for a server to start; reaching devnet alone took 8-17 s on 24 Nov):
247
+ // the chain connection and the first housekeeping run in the background, and tools connect on demand.
248
+ const handle = serve(payer, { network: setup.network.name, version: VERSION });
249
+ const log = logger(io, setup.home);
250
+ log(`serving ${setup.network.name} (key ${setup.key.address}, sandbox ${io.env.FLOP_MCP_SANDBOX ?? 'none'})`);
251
+ void payer.start();
252
+ return new Promise((resolve) => {
253
+ let stopping = false;
254
+ /** @param {string} why */
255
+ const stop = async (why) => {
256
+ if (stopping) return;
257
+ stopping = true;
258
+ log(`stopping (${why})`);
259
+ await payer.stop();
260
+ await handle.close().catch(() => {});
261
+ log('stopped');
262
+ resolve(0);
263
+ // Leftover sockets or reconnect timers must not keep a stopped server alive until the client kills it.
264
+ if (process.stdout.writableLength) await new Promise((done) => { process.stdout.once('drain', done); setTimeout(done, 500).unref(); });
265
+ process.exit(0);
266
+ };
267
+ process.stdin.once('end', () => { void stop('stdin closed'); });
268
+ process.stdin.once('close', () => { void stop('stdin closed'); });
269
+ process.once('SIGTERM', () => { void stop('SIGTERM'); });
270
+ process.once('SIGINT', () => { void stop('SIGINT'); });
271
+ });
272
+ }
273
+
274
+ /** flop-mcp status: what flop_status shows, in the terminal. @param {string[]} args @param {Io} io */
275
+ export async function runStatus(args, io) {
276
+ const setup = await loadSetup(args, io);
277
+ if (typeof setup === 'number') return setup;
278
+ const payer = await makePayer(setup, io);
279
+ const { formatStatus } = await import('./format.js');
280
+ try {
281
+ io.out.write(`${formatStatus(await payer.status())}\n`);
282
+ } finally {
283
+ await payer.api?.disconnect?.().catch(() => {});
284
+ }
285
+ return 0;
286
+ }
287
+
288
+ /**
289
+ * flop-mcp retire: send the session key's leftover fee money back to the owner, once its spending limit
290
+ * is revoked or expired and no channel is still open or waiting for a refund.
291
+ * @param {string[]} args @param {Io} io
292
+ */
293
+ export async function runRetire(args, io) {
294
+ const setup = await loadSetup(args, io);
295
+ if (typeof setup === 'number') return setup;
296
+ const adapter = await import('./flop-node.js');
297
+ const api = await adapter.connect(setup.network);
298
+ try {
299
+ const session = await adapter.readSession(api, setup.settings.owner, setup.key.address);
300
+ if (session.found && session.active) {
301
+ io.err.write('flop-mcp: this key\'s spending limit is still active. Revoke it in your wallet first, then run retire again.\n');
302
+ return 1;
303
+ }
304
+ const journal = adapter.openJournal(setup.home, setup.network.genesis, setup.settings.owner, payersRoot(io.env));
305
+ // Refunds first (they are signed by this key and need its fee money), then check nothing still waits.
306
+ await adapter.recoverJournal(api, journal);
307
+ await adapter.refundOrphans(api, setup.key.pair, journal);
308
+ const report = await adapter.recoverJournal(api, journal);
309
+ if (report.orphaned.length || report.unresolved.length) {
310
+ io.err.write(`flop-mcp: ${report.orphaned.length} channel(s) still wait for their window to end (up to 30 minutes after they were bought) and ${report.unresolved.length} payment(s) are unconfirmed; their refunds need this key's fee money. Run retire again later.\n`);
311
+ return 1;
312
+ }
313
+ // The sweep is signed by this key: hold the payer lock so no Claude session signs with it meanwhile.
314
+ await journal.acquire();
315
+ let swept;
316
+ try {
317
+ swept = await adapter.sweepFees(api, setup.key.pair, setup.settings.owner);
318
+ } finally {
319
+ await journal.release();
320
+ }
321
+ io.out.write(swept.outcome === 'ok'
322
+ ? `The session key's leftover fee money went back to ${setup.settings.owner} (transaction ${swept.txHash}).\n`
323
+ : `The fee money transfer ${swept.outcome === 'failed' ? 'failed' : 'has an unknown outcome; check your wallet before trying again'}: ${swept.message}\n`);
324
+ return swept.outcome === 'ok' ? 0 : 1;
325
+ } finally {
326
+ await api.disconnect().catch(() => {});
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Ask a yes/no question on the terminal; anything but y/yes is no, and with no terminal to answer on it is no.
332
+ * @param {Io} io @param {string} question
333
+ */
334
+ async function askYesNo(io, question) {
335
+ const input = io.stdin ?? process.stdin;
336
+ if (!input.isTTY) {
337
+ io.out.write(`${question}\n(No terminal to answer on, so the answer is no.)\n`);
338
+ return false;
339
+ }
340
+ const { createInterface } = await import('node:readline/promises');
341
+ const prompt = createInterface({ input, output: /** @type {NodeJS.WritableStream} */ (/** @type {unknown} */ (io.out)) });
342
+ try {
343
+ return /^\s*y(es)?\s*$/i.test(await prompt.question(question));
344
+ } finally {
345
+ prompt.close();
346
+ }
347
+ }
348
+
349
+ /**
350
+ * flop-mcp claim: on a network whose faucet takes the receiving key's own signed claim (testnet), this connector's key
351
+ * claims its FLOP, keeps 0.5 FLOP for its network fees and offers the rest to the owner (SPEC.md, the claim diagram;
352
+ * the rules are src/claim.js, the chain and faucet calls src/flop-node.js).
353
+ * @param {string[]} args @param {Io} io @returns {Promise<number>} exit code
354
+ */
355
+ export async function runClaim(args, io) {
356
+ let values;
357
+ try {
358
+ ({ values } = parseArgs({ args, options: { network: { type: 'string', default: 'devnet' }, yes: { type: 'boolean', default: false } }, strict: true, allowPositionals: false }));
359
+ } catch (error) {
360
+ io.err.write(`flop-mcp: ${/** @type {Error} */ (error).message}\n${CLAIM_USAGE}\n`);
361
+ return 2;
362
+ }
363
+ const network = liveNetwork(values.network);
364
+ if (typeof network === 'string') {
365
+ io.err.write(`flop-mcp: ${network}\n`);
366
+ return 2;
367
+ }
368
+ if (!network.quickGrant?.signed || !network.faucet) {
369
+ io.err.write(`flop-mcp: claim is for a network whose faucet takes a claim signed by the receiving key, which is testnet (--network testnet). On ${network.name}, your wallet gets FLOP from the faucet itself.\n`);
370
+ return 2;
371
+ }
372
+ const setup = await loadSetup(['--network', network.name], io);
373
+ if (typeof setup === 'number') return setup;
374
+ const [{ runClaimFlow }, adapter] = await Promise.all([import('./claim.js'), import('./flop-node.js')]);
375
+ let api;
376
+ try {
377
+ api = await adapter.connect(setup.network);
378
+ } catch (error) {
379
+ io.err.write(`flop-mcp: Flop's ${network.name} could not be reached (${/** @type {Error} */ (error).message}). Nothing was sent; try again later.\n`);
380
+ return 1;
381
+ }
382
+ try {
383
+ // The transfer to the owner is signed by this key: hold the payer lock so no Claude session signs with it meanwhile.
384
+ const journal = adapter.openJournal(setup.home, setup.network.genesis, setup.settings.owner, payersRoot(io.env));
385
+ return await runClaimFlow({
386
+ network: setup.network, keyAddress: setup.key.address, owner: setup.settings.owner, recordFile: setup.home.claimFile, yes: values.yes,
387
+ chain: {
388
+ freeBalance: (address) => adapter.finalizedBalance(api, address),
389
+ finalizedNumber: () => adapter.finalizedNumber(api),
390
+ findExtrinsic: (txHash, fromBlock, toBlock) => adapter.findExtrinsic(api, txHash, fromBlock, toBlock),
391
+ transferFee: (to, amountPlanck) => adapter.transferFee(api, setup.key.pair, to, amountPlanck),
392
+ prepareTransfer: (to, amountPlanck) => adapter.prepareTransfer(api, setup.key.pair, to, amountPlanck),
393
+ lock: async () => {
394
+ await journal.acquire();
395
+ return () => journal.release();
396
+ },
397
+ },
398
+ faucet: { ready: () => adapter.faucetReady(setup.network), claim: (nonce) => adapter.claimAgentGrant(setup.key.pair, setup.network, nonce) },
399
+ clock: realClock,
400
+ confirm: (question) => askYesNo(io, question),
401
+ say: (line) => { io.out.write(`${line}\n`); },
402
+ });
403
+ } finally {
404
+ await api.disconnect().catch(() => {});
405
+ }
406
+ }
407
+
408
+ /**
409
+ * Run one command.
410
+ * @param {string[]} argv process.argv.slice(2)
411
+ * @param {Partial<Io>} [io]
412
+ * @returns {Promise<number>} exit code
413
+ */
414
+ export async function main(argv, io = {}) {
415
+ const fullIo = { out: process.stdout, err: process.stderr, env: process.env, execPath: process.execPath, ...io };
416
+ const [command, ...rest] = argv;
417
+ if (command === 'init') return runInit(rest, fullIo);
418
+ if (command === 'serve') return runServe(rest, fullIo);
419
+ if (command === 'status') return runStatus(rest, fullIo);
420
+ if (command === 'retire') return runRetire(rest, fullIo);
421
+ if (command === 'claim') return runClaim(rest, fullIo);
422
+ if (command === 'sandbox-check') {
423
+ const { runSandboxSmoke } = await import('../e2e/sandbox-smoke.mjs');
424
+ return runSandboxSmoke();
425
+ }
426
+ fullIo.err.write('usage: flop-mcp init | claim | serve | status | retire | sandbox-check (each takes --network devnet|testnet; claim is for testnet)\n');
427
+ return 2;
428
+ }