tryflop 0.0.1 → 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/README.md +66 -2
- package/bin/flop-mcp.mjs +22 -0
- package/bin/tryflop.mjs +36 -0
- package/e2e/sandbox-smoke.mjs +136 -0
- package/npm-shrinkwrap.json +2648 -0
- package/package.json +52 -5
- package/src/agent-settings.js +76 -0
- package/src/claim.js +516 -0
- package/src/cli.js +428 -0
- package/src/daily.js +363 -0
- package/src/files.js +104 -0
- package/src/flop-core.js +189 -0
- package/src/flop-node.js +346 -0
- package/src/format.js +180 -0
- package/src/gate.js +19 -0
- package/src/guard.js +231 -0
- package/src/home.js +96 -0
- package/src/install.js +110 -0
- package/src/keyfile.js +70 -0
- package/src/layout.js +55 -0
- package/src/miners.js +65 -0
- package/src/moments.js +50 -0
- package/src/outcome.js +128 -0
- package/src/outer.js +969 -0
- package/src/payer.js +834 -0
- package/src/questions.js +47 -0
- package/src/requests.js +178 -0
- package/src/roots.js +48 -0
- package/src/sandbox.js +223 -0
- package/src/scheduler.js +221 -0
- package/src/scoring.js +67 -0
- package/src/secrets.js +41 -0
- package/src/server.js +13 -0
- package/src/shared/config.js +366 -0
- package/src/shared/direct-core.js +226 -0
- package/src/shared/grants-core.js +69 -0
- package/src/shared/units.js +47 -0
- package/src/statusfile.js +70 -0
- package/src/tools.js +107 -0
- package/src/tryflop.js +622 -0
- package/src/wallet.js +123 -0
- package/bin/tryflop.js +0 -5
package/src/tryflop.js
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
// tryflop's INNER commands: everything that touches the wallet or Flop's chain (SPEC.md "tryflop"). bin/tryflop.mjs
|
|
2
|
+
// loads this only after ensureSandboxed() — inside macOS's sandbox, or natively on Windows and Linux. The commands that
|
|
3
|
+
// manage the operating system (setup, the scheduler's daily wrapper, uninstall) are src/outer.js, which starts these.
|
|
4
|
+
import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { parseArgs } from 'node:util';
|
|
7
|
+
import { readAgentSettings, newAgentSettings, settingsFrom, verifiedGrantOpen, writeAgentSettings } from './agent-settings.js';
|
|
8
|
+
import { decidedClaim, nextClaimAt, runClaimFlow } from './claim.js';
|
|
9
|
+
import { claimDue, claimWithWait, isDue, localDay, readDailyState, runDailyPass, takeLock, writeDailyState } from './daily.js';
|
|
10
|
+
import { writePrivateFile } from './files.js';
|
|
11
|
+
import { wordsGate } from './gate.js';
|
|
12
|
+
import { walletHome } from './layout.js';
|
|
13
|
+
import { minersFor } from './miners.js';
|
|
14
|
+
import { forPlatform, momentsToNotify } from './moments.js';
|
|
15
|
+
import { homeRoot, humanRoot, payersRoot } from './roots.js';
|
|
16
|
+
import { fetchScoringStatus, parseScoringStatus, scoringMode, STATUS_URL } from './scoring.js';
|
|
17
|
+
import { DIRECT, NETWORKS } from './shared/config.js';
|
|
18
|
+
import { formatFlop, PLANCK_PER_FLOP } from './shared/units.js';
|
|
19
|
+
import { appendAnswer, humanFiles, statusLine, utcTime, writeStatusFile } from './statusfile.js';
|
|
20
|
+
import { createWallet, loadWallet, restoreWallet, walletAddress, walletWords, WalletError } from './wallet.js';
|
|
21
|
+
|
|
22
|
+
/** tryflop's network unless --network says otherwise: Flop's public testnet ("all that matters is testnet"). */
|
|
23
|
+
export const DEFAULT_NETWORK = 'testnet';
|
|
24
|
+
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
25
|
+
const DAY_MS = 86_400_000;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @typedef {{ out: { write(text: string): unknown }, err: { write(text: string): unknown }, env: NodeJS.ProcessEnv,
|
|
29
|
+
* stdin?: NodeJS.ReadableStream & { isTTY?: boolean, setRawMode?: (on: boolean) => unknown } }} Io
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** @param {unknown} error */
|
|
33
|
+
const brief = (error) => String(/** @type {any} */ (error)?.message ?? error).replace(/\s+/g, ' ').slice(0, 300);
|
|
34
|
+
|
|
35
|
+
/** The real clock (timers never keep the process alive on their own). */
|
|
36
|
+
const realClock = {
|
|
37
|
+
now: () => Date.now(),
|
|
38
|
+
/** @param {number} ms @param {AbortSignal} [signal] */
|
|
39
|
+
sleep: (ms, signal) => new Promise((resolve, reject) => {
|
|
40
|
+
const timer = setTimeout(resolve, ms);
|
|
41
|
+
signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
|
|
42
|
+
}),
|
|
43
|
+
/** @param {number} ms @param {() => void} fn */
|
|
44
|
+
setTimer: (ms, fn) => {
|
|
45
|
+
const timer = setTimeout(fn, ms);
|
|
46
|
+
timer.unref();
|
|
47
|
+
return () => clearTimeout(timer);
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Parse `--network` (and any other options), and find the network and its wallet folder.
|
|
53
|
+
* @param {string[]} args @param {Io} io @param {Record<string, any>} [options]
|
|
54
|
+
* @returns {{ values: Record<string, any>, network: import('./shared/config.js').NetworkConfig, home: import('./layout.js').WalletHome } | number}
|
|
55
|
+
*/
|
|
56
|
+
function setupFor(args, io, options = {}) {
|
|
57
|
+
let values;
|
|
58
|
+
try {
|
|
59
|
+
({ values } = parseArgs({ args, options: { network: { type: 'string', default: DEFAULT_NETWORK }, ...options }, strict: true, allowPositionals: false }));
|
|
60
|
+
} catch (error) {
|
|
61
|
+
io.err.write(`tryflop: ${brief(error)}\n`);
|
|
62
|
+
return 2;
|
|
63
|
+
}
|
|
64
|
+
const name = String(values.network);
|
|
65
|
+
if (!Object.hasOwn(NETWORKS, name) || NETWORKS[/** @type {'devnet'|'testnet'} */ (name)].status !== 'live') {
|
|
66
|
+
io.err.write(`tryflop: there is no open Flop network called "${name.slice(0, 40)}" (testnet or devnet).\n`);
|
|
67
|
+
return 2;
|
|
68
|
+
}
|
|
69
|
+
const network = NETWORKS[/** @type {'devnet'|'testnet'} */ (name)];
|
|
70
|
+
return { values, network, home: walletHome(homeRoot(io.env), network.name) };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Log lines: stderr and <wallet folder>/tryflop.log (0600). Never a word, a key or a prompt. @param {Io} io @param {string} dir */
|
|
74
|
+
function logger(io, dir) {
|
|
75
|
+
return (/** @type {string} */ line) => {
|
|
76
|
+
const text = `tryflop ${new Date().toISOString()} ${line}\n`;
|
|
77
|
+
io.err.write(text);
|
|
78
|
+
try {
|
|
79
|
+
appendFileSync(join(dir, 'tryflop.log'), text, { mode: 0o600 });
|
|
80
|
+
} catch {
|
|
81
|
+
// stderr still has it
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The payer for this wallet (SPEC.md "Asking as the wallet itself"): the wallet pays its own fees; a day's purchases
|
|
88
|
+
* stay within the faucet's daily grant, one channel within DIRECT.maxChannelPlanck.
|
|
89
|
+
* @param {{ network: any, home: any, wallet: { address: string, pair: any }, io: Io, log: (line: string) => void }} o
|
|
90
|
+
*/
|
|
91
|
+
async function ownPayer({ network, home, wallet, io, log }) {
|
|
92
|
+
const [{ Payer }, adapter] = await Promise.all([import('./payer.js'), import('./flop-node.js')]);
|
|
93
|
+
const grant = BigInt(network.quickGrant?.flop ?? 10) * PLANCK_PER_FLOP;
|
|
94
|
+
const settings = { owner: wallet.address, maxFlopPerAsk: DIRECT.maxChannelPlanck, maxFlopPerDay: grant, maxFlopTotal: grant, idleSettleSeconds: 60 };
|
|
95
|
+
const payer = new Payer({ adapter, home, settings, key: wallet, network, payersRoot: payersRoot(io.env), clock: realClock, log, own: true, miners: minersFor(network) });
|
|
96
|
+
return { payer, adapter, grant };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The claim for this wallet (src/claim.js, `own`): testnet's signed agent lane only.
|
|
101
|
+
* @returns {(() => Promise<{ outcome: string, reason?: string }>) | null} null on a network without that lane
|
|
102
|
+
*/
|
|
103
|
+
function walletClaim({ network, home, wallet, adapter, api, say }) {
|
|
104
|
+
if (!network.faucet) return null;
|
|
105
|
+
// Testnet: the agent lane, signed by the wallet itself. Devnet: the anonymous lane (an address; nothing signed).
|
|
106
|
+
const signed = Boolean(network.quickGrant?.signed);
|
|
107
|
+
return async () => {
|
|
108
|
+
/** @type {{ outcome: string, reason?: string, nextClaimAt?: number }} */
|
|
109
|
+
let result = { outcome: 'not_sent' };
|
|
110
|
+
await runClaimFlow({
|
|
111
|
+
network, keyAddress: wallet.address, owner: wallet.address, recordFile: home.claimFile, yes: false, own: true,
|
|
112
|
+
chain: {
|
|
113
|
+
freeBalance: (address) => adapter.finalizedBalance(api, address),
|
|
114
|
+
finalizedNumber: () => adapter.finalizedNumber(api),
|
|
115
|
+
findExtrinsic: (txHash, from, to) => adapter.findExtrinsic(api, txHash, from, to),
|
|
116
|
+
transferFee: async () => { throw new Error('the wallet route sends nothing on'); },
|
|
117
|
+
prepareTransfer: async () => { throw new Error('the wallet route sends nothing on'); },
|
|
118
|
+
lock: async () => { throw new Error('the wallet route sends nothing on'); },
|
|
119
|
+
},
|
|
120
|
+
faucet: signed
|
|
121
|
+
? { ready: () => adapter.faucetReady(network), claim: (nonce) => adapter.claimAgentGrant(wallet.pair, network, nonce) }
|
|
122
|
+
: { ready: async () => ({ open: true, status: 'open' }), claim: () => adapter.claimAnonymousGrant(api, wallet.address, network) },
|
|
123
|
+
clock: realClock,
|
|
124
|
+
confirm: async () => false,
|
|
125
|
+
say,
|
|
126
|
+
onResult: (r) => {
|
|
127
|
+
// Read the way the claim decision reads it (an old faucet_busy record is a refusal retried after 30 minutes).
|
|
128
|
+
const c = /** @type {any} */ (decidedClaim(r.claim));
|
|
129
|
+
const next = nextClaimAt(r.claim);
|
|
130
|
+
// When the faucet can be asked next: 24 h after a grant or a claim still on its way, or a refusal's retry time.
|
|
131
|
+
// (never reached the faucet: unavailable → at once, i.e. the next trigger tries again)
|
|
132
|
+
result = { outcome: r.outcome, ...(c?.reason ? { reason: c.reason } : {}), ...(next !== undefined ? { nextClaimAt: next } : {}) };
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
return result;
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ── wallet-init (setup's sandboxed part) ──────────────────────────────────────────────────────────────────────
|
|
140
|
+
|
|
141
|
+
/** Make the wallet, or keep the one here. Prints one JSON line: { address, created }. Never the words. @param {string[]} args @param {Io} io */
|
|
142
|
+
export async function runWalletInit(args, io) {
|
|
143
|
+
const s = setupFor(args, io);
|
|
144
|
+
if (typeof s === 'number') return s;
|
|
145
|
+
try {
|
|
146
|
+
const { address } = await createWallet(s.home, s.network);
|
|
147
|
+
io.out.write(`${JSON.stringify({ address, created: true })}\n`);
|
|
148
|
+
} catch (error) {
|
|
149
|
+
if (!(error instanceof WalletError && error.code === 'EXISTS')) throw error;
|
|
150
|
+
io.out.write(`${JSON.stringify({ address: walletAddress(s.home, s.network), created: false })}\n`);
|
|
151
|
+
}
|
|
152
|
+
return 0;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ── settings-set (setup's and uninstall's writes, made inside the sandbox) ─────────────────────────────────────
|
|
156
|
+
|
|
157
|
+
/** Write the settings the outer process hands over (checked field by field); prints "ok". @param {string[]} args @param {Io} io */
|
|
158
|
+
export async function runSettingsSet(args, io) {
|
|
159
|
+
const s = setupFor(args, io, { json: { type: 'string' } });
|
|
160
|
+
if (typeof s === 'number') return s;
|
|
161
|
+
let settings = null;
|
|
162
|
+
try {
|
|
163
|
+
settings = settingsFrom(JSON.parse(String(s.values.json ?? '')));
|
|
164
|
+
} catch {
|
|
165
|
+
settings = null;
|
|
166
|
+
}
|
|
167
|
+
if (!settings) {
|
|
168
|
+
io.err.write('tryflop: settings-set needs --json with valid settings.\n');
|
|
169
|
+
return 2;
|
|
170
|
+
}
|
|
171
|
+
writeAgentSettings(s.home.dir, s.home.tryflopFile, settings);
|
|
172
|
+
io.out.write('ok\n');
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ── claim ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
177
|
+
|
|
178
|
+
/** tryflop claim: this wallet asks Flop's testnet faucet for its free test FLOP (once a day; never re-sent). @param {string[]} args @param {Io} io */
|
|
179
|
+
export async function runClaim(args, io) {
|
|
180
|
+
const s = setupFor(args, io);
|
|
181
|
+
if (typeof s === 'number') return s;
|
|
182
|
+
const { network, home } = s;
|
|
183
|
+
if (!network.faucet) {
|
|
184
|
+
io.err.write(`tryflop: Flop publishes no faucet for ${network.name}.\n`);
|
|
185
|
+
return 2;
|
|
186
|
+
}
|
|
187
|
+
let wallet;
|
|
188
|
+
try {
|
|
189
|
+
wallet = await loadWallet(home, network);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
io.err.write(`tryflop: ${brief(error)}\n`);
|
|
192
|
+
return 1;
|
|
193
|
+
}
|
|
194
|
+
// One claim at a time: the daily run claims under this same lock, so the two can never both read "no claim yet" and
|
|
195
|
+
// both send one (review, 27 Nov).
|
|
196
|
+
const release = takeLock(home.lockFile, { now: Date.now(), pid: process.pid, isAlive: processAlive });
|
|
197
|
+
if (!release) {
|
|
198
|
+
io.err.write('tryflop: a daily run is going right now and claims by itself; nothing was sent. Run "status" in a while.\n');
|
|
199
|
+
return 1;
|
|
200
|
+
}
|
|
201
|
+
const adapter = await import('./flop-node.js');
|
|
202
|
+
let api;
|
|
203
|
+
try {
|
|
204
|
+
api = await adapter.connect(network);
|
|
205
|
+
} catch (error) {
|
|
206
|
+
release();
|
|
207
|
+
io.err.write(`tryflop: Flop's ${network.name} could not be reached (${brief(error)}). Nothing was sent; try again later.\n`);
|
|
208
|
+
return 1;
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
let outcome = { outcome: 'not_sent' };
|
|
212
|
+
const claim = /** @type {() => Promise<{ outcome: string }>} */ (walletClaim({ network, home, wallet, adapter, api, say: (line) => io.out.write(`${line}\n`) }));
|
|
213
|
+
outcome = await claim();
|
|
214
|
+
return outcome.outcome === 'granted_now' || outcome.outcome === 'granted_earlier' ? 0 : 1;
|
|
215
|
+
} finally {
|
|
216
|
+
release();
|
|
217
|
+
await api.disconnect().catch(() => {});
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ── daily-run (what the scheduler's daily wrapper starts) ──────────────────────────────────────────────────────
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* One daily run (SPEC.md "tryflop daily"): lock, due check, the pass, then the records the human reads. Prints ONE
|
|
225
|
+
* JSON line last, for src/outer.js: { result, reason, moments: [{ kind, text }], line }.
|
|
226
|
+
* @param {string[]} args @param {Io} io @param {{ isAlive?: (pid: number) => boolean }} [deps]
|
|
227
|
+
*/
|
|
228
|
+
export async function runDailyRun(args, io, { isAlive = processAlive } = {}) {
|
|
229
|
+
const s = setupFor(args, io, { force: { type: 'boolean', default: false }, 'no-claim': { type: 'boolean', default: false } });
|
|
230
|
+
if (typeof s === 'number') return s;
|
|
231
|
+
const { network, home, values } = s;
|
|
232
|
+
const report = (/** @type {object} */ o) => io.out.write(`${JSON.stringify(o)}\n`);
|
|
233
|
+
let wallet;
|
|
234
|
+
try {
|
|
235
|
+
wallet = await loadWallet(home, network);
|
|
236
|
+
} catch (error) {
|
|
237
|
+
io.err.write(`tryflop: ${brief(error)}\n`);
|
|
238
|
+
report({ result: 'no_wallet', reason: brief(error), moments: [] });
|
|
239
|
+
return 1;
|
|
240
|
+
}
|
|
241
|
+
const log = logger(io, home.dir);
|
|
242
|
+
const settings = readAgentSettings(home.tryflopFile) ?? newAgentSettings();
|
|
243
|
+
const human = humanRoot(io.env);
|
|
244
|
+
mkdirSync(human, { recursive: true, mode: 0o700 }); // made by the sandbox on macOS; Windows and Linux have none (review, 27 Nov)
|
|
245
|
+
const now = Date.now();
|
|
246
|
+
const release = takeLock(home.lockFile, { now, pid: process.pid, isAlive });
|
|
247
|
+
if (!release) {
|
|
248
|
+
report({ result: 'skipped', reason: 'Another daily run is going.', moments: [] });
|
|
249
|
+
return 0;
|
|
250
|
+
}
|
|
251
|
+
const state = readDailyState(home.dailyFile);
|
|
252
|
+
try {
|
|
253
|
+
if (!values.force && !isDue({ now, state, hour: settings.hour, minute: settings.minute })) {
|
|
254
|
+
if (values['no-claim'] || !claimDue({ now, state })) {
|
|
255
|
+
report({ result: 'skipped', reason: 'Today\'s run is done (or its time has not come yet).', moments: [] });
|
|
256
|
+
return 0;
|
|
257
|
+
}
|
|
258
|
+
// Today's spending is done, but the faucet's 24 h ended after the day's first trigger: claim only.
|
|
259
|
+
const adapter = await import('./flop-node.js');
|
|
260
|
+
/** @type {{ outcome: string, reason?: string, nextClaimAt?: number }} */
|
|
261
|
+
let claimed = { outcome: 'not_sent', reason: 'Flop\'s network could not be reached' };
|
|
262
|
+
try {
|
|
263
|
+
const api = await adapter.connect(network);
|
|
264
|
+
try {
|
|
265
|
+
const claim = walletClaim({ network, home, wallet, adapter, api, say: log });
|
|
266
|
+
if (claim) claimed = await claimWithWait({ claim, now: () => Date.now(), sleep: (ms) => realClock.sleep(ms), log });
|
|
267
|
+
} finally {
|
|
268
|
+
await api.disconnect().catch(() => {});
|
|
269
|
+
}
|
|
270
|
+
} catch (error) {
|
|
271
|
+
log(`claim pass: ${brief(error)}`);
|
|
272
|
+
}
|
|
273
|
+
// Nothing decided (the network or chain could not be reached): keep the old time, so the next trigger tries again.
|
|
274
|
+
if (!['not_sent', 'unreadable', 'error'].includes(claimed.outcome) || claimed.nextClaimAt !== undefined) state.nextClaimAt = claimed.nextClaimAt;
|
|
275
|
+
writeDailyState(home.dailyFile, state);
|
|
276
|
+
report({ result: 'claimed', reason: claimWords(claimed), moments: [] });
|
|
277
|
+
return 0;
|
|
278
|
+
}
|
|
279
|
+
const { payer, adapter, grant } = await ownPayer({ network, home, wallet, io, log });
|
|
280
|
+
let api;
|
|
281
|
+
let result;
|
|
282
|
+
/** @type {bigint | undefined} */
|
|
283
|
+
let balance;
|
|
284
|
+
try {
|
|
285
|
+
result = await runDailyPass({
|
|
286
|
+
now: () => Date.now(), topic: settings.topic, miners: minersFor(network), grantPlanck: grant, state,
|
|
287
|
+
connect: async () => { api = await payer.ensureApi(); },
|
|
288
|
+
reconcile: async () => { await payer.housekeep(); return { frozen: payer.frozen }; },
|
|
289
|
+
finalizedNumber: () => adapter.finalizedNumber(api),
|
|
290
|
+
balance: () => adapter.finalizedBalance(api, wallet.address),
|
|
291
|
+
scoring: async (ours) => {
|
|
292
|
+
let status = null;
|
|
293
|
+
try {
|
|
294
|
+
status = parseScoringStatus(await fetchScoringStatus(io.env.FLOP_MCP_STATUS_URL || STATUS_URL));
|
|
295
|
+
} catch (error) {
|
|
296
|
+
log(`scoring status: ${brief(error)}`);
|
|
297
|
+
}
|
|
298
|
+
return scoringMode(status, ours);
|
|
299
|
+
},
|
|
300
|
+
claim: async () => {
|
|
301
|
+
// --no-claim: the FLOP came from elsewhere (another wallet sent it); the faucet is not asked at all.
|
|
302
|
+
if (values['no-claim']) return { outcome: 'skipped', reason: 'not asked (--no-claim)' };
|
|
303
|
+
const claim = walletClaim({ network, home, wallet, adapter, api, say: log });
|
|
304
|
+
return claim ? claim() : { outcome: 'not_sent', reason: 'no signed faucet lane on this network' };
|
|
305
|
+
},
|
|
306
|
+
sleep: (ms) => realClock.sleep(ms),
|
|
307
|
+
save: (s) => writeDailyState(home.dailyFile, s),
|
|
308
|
+
makePayer: (run) => {
|
|
309
|
+
payer.run = run;
|
|
310
|
+
return payer;
|
|
311
|
+
},
|
|
312
|
+
log,
|
|
313
|
+
});
|
|
314
|
+
if (api) balance = await adapter.finalizedBalance(api, wallet.address).catch(() => undefined);
|
|
315
|
+
} finally {
|
|
316
|
+
await payer.stop(0).catch(() => {});
|
|
317
|
+
}
|
|
318
|
+
const day = localDay(now);
|
|
319
|
+
for (const asked of result.asked) {
|
|
320
|
+
if (asked.status !== 'answered' || !asked.answer) continue;
|
|
321
|
+
try {
|
|
322
|
+
appendAnswer(human, day, { at: Date.now(), question: asked.question, answer: asked.answer, miner: String(asked.miner), channel: String(asked.channel) }, network.name);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
log(`answers file: ${brief(error)}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
// The record: completed days, failed days in a row (the "needs you" moment), and two weeks of history.
|
|
328
|
+
state.lastRunAt = now;
|
|
329
|
+
state.lastResult = `${result.status}: ${result.reason}`;
|
|
330
|
+
if (result.status === 'done') {
|
|
331
|
+
state.lastCompletedDay = day;
|
|
332
|
+
state.failedDays = 0;
|
|
333
|
+
} else if (result.status === 'failed' && state.lastFailedDay !== day) {
|
|
334
|
+
state.failedDays = (state.failedDays ?? 0) + 1;
|
|
335
|
+
state.lastFailedDay = day;
|
|
336
|
+
}
|
|
337
|
+
const answers = result.asked.filter((a) => a.status === 'answered').length;
|
|
338
|
+
const history = (state.history ?? []).filter((h) => h.day !== day);
|
|
339
|
+
const todayBefore = (state.history ?? []).find((h) => h.day === day);
|
|
340
|
+
history.push({ day, answers: answers + (todayBefore?.answers ?? 0), spentPlanck: String(result.spentPlanck + BigInt(todayBefore?.spentPlanck ?? '0')) });
|
|
341
|
+
state.history = history.slice(-14);
|
|
342
|
+
writeDailyState(home.dailyFile, state);
|
|
343
|
+
|
|
344
|
+
const moments = await newMoments({ now, state, settings, result, network, home, log });
|
|
345
|
+
balance ??= result.balancePlanck;
|
|
346
|
+
const line = statusLine({ daily: settings.daily, lastPaidAnswer: state.lastPaidAnswer, scoringState: state.scoring?.state, address: wallet.address, balancePlanck: balance });
|
|
347
|
+
try {
|
|
348
|
+
writeStatusFile(join(human, humanFiles(network.name).status), {
|
|
349
|
+
now, line, address: wallet.address, network: network.name,
|
|
350
|
+
result: `${utcTime(now)}: ${result.reason}`,
|
|
351
|
+
why: result.scoringWhy ?? 'not checked',
|
|
352
|
+
claim: claimWords(result.claim),
|
|
353
|
+
nextRun: settings.daily === 'on' ? `every day at ${String(settings.hour).padStart(2, '0')}:${String(settings.minute).padStart(2, '0')} (this computer's time), or when it wakes up after that` : 'not scheduled (setup was told no daily run); run "tryflop daily" by hand',
|
|
354
|
+
humanDir: human,
|
|
355
|
+
});
|
|
356
|
+
} catch (error) {
|
|
357
|
+
log(`status file: ${brief(error)}`);
|
|
358
|
+
}
|
|
359
|
+
report({ result: result.status, reason: result.reason, moments, line });
|
|
360
|
+
return result.status === 'failed' ? 1 : 0;
|
|
361
|
+
} finally {
|
|
362
|
+
release();
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** @param {{ outcome: string, reason?: string } | undefined} claim */
|
|
367
|
+
function claimWords(claim) {
|
|
368
|
+
if (!claim) return 'not checked';
|
|
369
|
+
const words = /** @type {Record<string, string>} */ ({
|
|
370
|
+
granted_now: 'claimed today', granted_earlier: 'already claimed in the last 24 hours',
|
|
371
|
+
held: 'a claim is on its way (never sent twice)', not_arrived: 'a claim is on its way (never sent twice)',
|
|
372
|
+
refused: claim.reason === 'faucet_busy' ? 'Flop\'s faucet was busy and reserved nothing; the next run asks again' : `refused by Flop's faucet (${claim.reason ?? 'no reason given'}); tried again tomorrow`,
|
|
373
|
+
refused_earlier: `refused by Flop's faucet earlier (${claim.reason ?? 'no reason given'}); tried again later`,
|
|
374
|
+
not_sent: 'not asked this time (the faucet was not serving)', unreadable: 'not asked (Flop\'s chain could not be read)',
|
|
375
|
+
skipped: 'not asked (--no-claim: the FLOP came from elsewhere)',
|
|
376
|
+
});
|
|
377
|
+
return words[claim.outcome] ?? claim.outcome;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Which human moments this run brings, recorded in moments.json so each is shown once (src/moments.js).
|
|
382
|
+
* @returns {Promise<import('./moments.js').Moment[]>}
|
|
383
|
+
*/
|
|
384
|
+
async function newMoments({ now, state, settings, result, network, home, log }) {
|
|
385
|
+
/** @type {import('./moments.js').MomentsSeen} */
|
|
386
|
+
let seen = {};
|
|
387
|
+
let first = false;
|
|
388
|
+
try {
|
|
389
|
+
seen = JSON.parse(readFileSync(home.momentsFile, 'utf8'));
|
|
390
|
+
} catch {
|
|
391
|
+
first = true;
|
|
392
|
+
}
|
|
393
|
+
// The weekly line starts a week after the first run, never on day one.
|
|
394
|
+
if (first || seen.weekly === undefined) seen.weekly = now;
|
|
395
|
+
let verified = false;
|
|
396
|
+
if (network.faucet && network.quickGrant?.signed) {
|
|
397
|
+
try {
|
|
398
|
+
const response = await fetch(`${network.faucet}/`, { headers: { accept: 'text/html' }, redirect: 'error', signal: AbortSignal.timeout(10_000) });
|
|
399
|
+
const html = response.status === 200 ? (await response.text()).slice(0, 300_000) : '';
|
|
400
|
+
verified = verifiedGrantOpen(html);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
log(`faucet page: ${brief(error)}`);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
const week = (state.history ?? []).filter((h) => Date.parse(`${h.day}T12:00:00`) >= now - 7 * DAY_MS);
|
|
406
|
+
const spent = week.reduce((sum, h) => sum + BigInt(h.spentPlanck), 0n);
|
|
407
|
+
const moments = momentsToNotify({
|
|
408
|
+
now, seen, backupShown: settings.backupShownAt !== undefined, walletAgeMs: now - Date.parse(settings.createdAt),
|
|
409
|
+
faucetConnectionRefused: result.claim?.outcome === 'refused' && /^ip_/.test(result.claim.reason ?? ''),
|
|
410
|
+
verifiedGrantOpen: verified, scoringOn: result.mode === 'ON', failedDays: state.failedDays ?? 0,
|
|
411
|
+
week: { answers: week.reduce((n, h) => n + h.answers, 0), spentFlop: formatFlop(spent), scoringOn: result.mode === 'ON' },
|
|
412
|
+
});
|
|
413
|
+
for (const m of moments) {
|
|
414
|
+
seen[m.kind] = now;
|
|
415
|
+
m.text = forPlatform(m.text, process.platform);
|
|
416
|
+
}
|
|
417
|
+
// The outer process shows its own words for each kind and rebuilds the weekly line from these numbers.
|
|
418
|
+
const weekFacts = { answers: week.reduce((n, h) => n + h.answers, 0), spentPlanck: String(spent), scoringOn: result.mode === 'ON' };
|
|
419
|
+
for (const m of moments) if (m.kind === 'weekly') /** @type {any} */ (m).week = weekFacts;
|
|
420
|
+
try {
|
|
421
|
+
writePrivateFile(home.momentsFile, `${JSON.stringify(seen)}\n`);
|
|
422
|
+
} catch (error) {
|
|
423
|
+
log(`moments file: ${brief(error)}`);
|
|
424
|
+
}
|
|
425
|
+
return moments;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** @param {number} pid */
|
|
429
|
+
function processAlive(pid) {
|
|
430
|
+
try {
|
|
431
|
+
process.kill(pid, 0);
|
|
432
|
+
return true;
|
|
433
|
+
} catch (error) {
|
|
434
|
+
return /** @type {any} */ (error).code === 'EPERM';
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// ── status ────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
439
|
+
|
|
440
|
+
/** tryflop status: the one line, then the details from the chain. @param {string[]} args @param {Io} io */
|
|
441
|
+
export async function runStatus(args, io) {
|
|
442
|
+
const s = setupFor(args, io);
|
|
443
|
+
if (typeof s === 'number') return s;
|
|
444
|
+
const { network, home } = s;
|
|
445
|
+
let wallet;
|
|
446
|
+
try {
|
|
447
|
+
wallet = await loadWallet(home, network);
|
|
448
|
+
} catch (error) {
|
|
449
|
+
io.err.write(`tryflop: ${brief(error)}\n`);
|
|
450
|
+
return 1;
|
|
451
|
+
}
|
|
452
|
+
const settings = readAgentSettings(home.tryflopFile) ?? newAgentSettings();
|
|
453
|
+
const state = readDailyState(home.dailyFile);
|
|
454
|
+
const { payer } = await ownPayer({ network, home, wallet, io, log: () => {} });
|
|
455
|
+
const { formatStatus } = await import('./format.js');
|
|
456
|
+
try {
|
|
457
|
+
const report = await payer.status();
|
|
458
|
+
io.out.write(`${statusLine({ daily: settings.daily, lastPaidAnswer: state.lastPaidAnswer, scoringState: state.scoring?.state, address: wallet.address, balancePlanck: report.ownerBalancePlanck })}\n\n`);
|
|
459
|
+
if (state.lastResult) io.out.write(`Last daily run: ${state.lastRunAt ? utcTime(state.lastRunAt) : '?'} — ${state.lastResult}\n`);
|
|
460
|
+
if (settings.backupShownAt === undefined) io.out.write(`Backup: not looked at yet. The human runs "${process.platform === 'win32' ? '~/.tryflop/bin/tryflop.cmd' : '~/.tryflop/bin/tryflop'} backup" themselves, in their own terminal (never through an AI agent).\n`);
|
|
461
|
+
io.out.write(`${formatStatus(report)}\n`);
|
|
462
|
+
} finally {
|
|
463
|
+
await payer.api?.disconnect?.().catch(() => {});
|
|
464
|
+
}
|
|
465
|
+
return 0;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// ── serve (the MCP server Claude Code starts) ─────────────────────────────────────────────────────────────────
|
|
469
|
+
|
|
470
|
+
/** tryflop serve: Claude's ask_flop paid from this wallet. stdout carries only MCP messages. @param {string[]} args @param {Io} io */
|
|
471
|
+
export async function runServe(args, io) {
|
|
472
|
+
for (const method of /** @type {const} */ (['log', 'info', 'debug', 'warn'])) {
|
|
473
|
+
console[method] = (...parts) => { io.err.write(`${parts.map(String).join(' ')}\n`); };
|
|
474
|
+
}
|
|
475
|
+
const s = setupFor(args, io);
|
|
476
|
+
if (typeof s === 'number') return s;
|
|
477
|
+
const { network, home } = s;
|
|
478
|
+
let wallet;
|
|
479
|
+
try {
|
|
480
|
+
wallet = await loadWallet(home, network);
|
|
481
|
+
} catch (error) {
|
|
482
|
+
io.err.write(`tryflop: ${brief(error)}\n`);
|
|
483
|
+
return 1;
|
|
484
|
+
}
|
|
485
|
+
const log = logger(io, home.dir);
|
|
486
|
+
const { payer } = await ownPayer({ network, home, wallet, io, log });
|
|
487
|
+
const { serve } = await import('./server.js');
|
|
488
|
+
const handle = serve(payer, { network: network.name, version: VERSION, own: true });
|
|
489
|
+
log(`serving ${network.name} (wallet ${wallet.address}, sandbox ${io.env.FLOP_MCP_SANDBOX ?? 'none'})`);
|
|
490
|
+
void payer.start();
|
|
491
|
+
return new Promise((resolve) => {
|
|
492
|
+
let stopping = false;
|
|
493
|
+
/** @param {string} why */
|
|
494
|
+
const stop = async (why) => {
|
|
495
|
+
if (stopping) return;
|
|
496
|
+
stopping = true;
|
|
497
|
+
log(`stopping (${why})`);
|
|
498
|
+
await payer.stop();
|
|
499
|
+
await handle.close().catch(() => {});
|
|
500
|
+
resolve(0);
|
|
501
|
+
if (process.stdout.writableLength) await new Promise((done) => { process.stdout.once('drain', done); setTimeout(done, 500).unref(); });
|
|
502
|
+
process.exit(0);
|
|
503
|
+
};
|
|
504
|
+
process.stdin.once('end', () => { void stop('stdin closed'); });
|
|
505
|
+
process.stdin.once('close', () => { void stop('stdin closed'); });
|
|
506
|
+
process.once('SIGTERM', () => { void stop('SIGTERM'); });
|
|
507
|
+
process.once('SIGINT', () => { void stop('SIGINT'); });
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// ── backup and restore (a person at a terminal only) ──────────────────────────────────────────────────────────
|
|
512
|
+
|
|
513
|
+
/** Read one line from a terminal; with `hidden`, nothing is echoed. @param {Io} io @param {boolean} hidden @returns {Promise<string>} */
|
|
514
|
+
function readLine(io, hidden) {
|
|
515
|
+
const input = /** @type {any} */ (io.stdin ?? process.stdin);
|
|
516
|
+
return new Promise((resolve) => {
|
|
517
|
+
let text = '';
|
|
518
|
+
if (hidden && input.setRawMode) input.setRawMode(true);
|
|
519
|
+
input.setEncoding?.('utf8');
|
|
520
|
+
input.resume();
|
|
521
|
+
const done = (/** @type {string} */ value) => {
|
|
522
|
+
input.removeListener('data', onData);
|
|
523
|
+
if (hidden && input.setRawMode) input.setRawMode(false);
|
|
524
|
+
input.pause();
|
|
525
|
+
io.out.write('\n');
|
|
526
|
+
resolve(value);
|
|
527
|
+
};
|
|
528
|
+
const onData = (/** @type {string} */ chunk) => {
|
|
529
|
+
for (const ch of chunk) {
|
|
530
|
+
if (ch === '\r' || ch === '\n') return done(text);
|
|
531
|
+
if (ch === '\u0003') return done(''); // Ctrl-C cancels
|
|
532
|
+
if (ch === '\u007f' || ch === '\b') text = text.slice(0, -1);
|
|
533
|
+
else text += ch;
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
input.on('data', onData);
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** tryflop backup: shows the 12 words to the person at this terminal, on a screen that is cleared afterwards. @param {string[]} args @param {Io} io */
|
|
541
|
+
export async function runBackup(args, io) {
|
|
542
|
+
const s = setupFor(args, io);
|
|
543
|
+
if (typeof s === 'number') return s;
|
|
544
|
+
const gate = wordsGate({ stdinTTY: Boolean((io.stdin ?? process.stdin).isTTY), stdoutTTY: Boolean(/** @type {any} */ (io.out).isTTY), env: io.env });
|
|
545
|
+
if (gate) {
|
|
546
|
+
io.err.write(`tryflop: ${gate}\n`);
|
|
547
|
+
return 2;
|
|
548
|
+
}
|
|
549
|
+
let words;
|
|
550
|
+
try {
|
|
551
|
+
words = walletWords(s.home, s.network);
|
|
552
|
+
} catch (error) {
|
|
553
|
+
io.err.write(`tryflop: ${brief(error)}\n`);
|
|
554
|
+
return 1;
|
|
555
|
+
}
|
|
556
|
+
io.out.write('Your Try Flop wallet\'s 12 recovery words restore it on any computer (tryflop restore), and anyone who sees them can take its FLOP.\nNobody from Try Flop or Flop will ever ask for them. Make sure no one, and no AI agent, can see your screen.\nType show and press Enter to see them (anything else cancels): ');
|
|
557
|
+
if ((await readLine(io, false)).trim().toLowerCase() !== 'show') {
|
|
558
|
+
io.out.write('Cancelled; nothing was shown.\n');
|
|
559
|
+
return 1;
|
|
560
|
+
}
|
|
561
|
+
// The terminal's alternate screen: the words never reach its scrollback, and vanish when Enter is pressed.
|
|
562
|
+
io.out.write(`\u001b[?1049h\u001b[H\u001b[2J\nYour 12 recovery words, in order:\n\n ${words.split(' ').map((w, i) => `${i + 1}. ${w}`).join('\n ')}\n\nWrite them on paper, in this order, and keep it somewhere safe. Press Enter when done (the words disappear).`);
|
|
563
|
+
await readLine(io, true);
|
|
564
|
+
io.out.write('\u001b[2J\u001b[?1049l');
|
|
565
|
+
const settings = readAgentSettings(s.home.tryflopFile) ?? newAgentSettings();
|
|
566
|
+
writeAgentSettings(s.home.dir, s.home.tryflopFile, { ...settings, backupShownAt: Date.now() });
|
|
567
|
+
io.out.write('Done: the words are off the screen. Keep the paper safe; this computer keeps its own copy for the daily run.\n');
|
|
568
|
+
return 0;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** tryflop restore: put a wallet you already have on this computer, from its 12 words typed by you. @param {string[]} args @param {Io} io */
|
|
572
|
+
export async function runRestore(args, io) {
|
|
573
|
+
const s = setupFor(args, io);
|
|
574
|
+
if (typeof s === 'number') return s;
|
|
575
|
+
const gate = wordsGate({ stdinTTY: Boolean((io.stdin ?? process.stdin).isTTY), stdoutTTY: Boolean(/** @type {any} */ (io.out).isTTY), env: io.env });
|
|
576
|
+
if (gate) {
|
|
577
|
+
io.err.write(`tryflop: ${gate}\n`);
|
|
578
|
+
return 2;
|
|
579
|
+
}
|
|
580
|
+
try {
|
|
581
|
+
io.err.write(`tryflop: this computer already has a Try Flop wallet (${walletAddress(s.home, s.network)}); it is never replaced (one wallet per person).\n`);
|
|
582
|
+
return 1;
|
|
583
|
+
} catch (error) {
|
|
584
|
+
if (!(error instanceof WalletError && error.code === 'MISSING')) {
|
|
585
|
+
io.err.write(`tryflop: ${brief(error)}\n`);
|
|
586
|
+
return 1;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
io.out.write('Type your 12 recovery words, separated by spaces, then press Enter (nothing shows while you type):\n');
|
|
590
|
+
const typed = await readLine(io, true);
|
|
591
|
+
try {
|
|
592
|
+
const { address } = await restoreWallet(s.home, s.network, typed);
|
|
593
|
+
io.out.write(`Restored: this computer now has your wallet ${address}. Next: ask your AI agent to run "tryflop setup" again to switch the daily run on.\n`);
|
|
594
|
+
return 0;
|
|
595
|
+
} catch (error) {
|
|
596
|
+
io.err.write(`tryflop: ${brief(error)}\n`);
|
|
597
|
+
return 1;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* Run one inner command.
|
|
603
|
+
* @param {string[]} argv @param {Partial<Io>} [io] @returns {Promise<number>}
|
|
604
|
+
*/
|
|
605
|
+
export async function mainInner(argv, io = {}) {
|
|
606
|
+
const fullIo = { out: process.stdout, err: process.stderr, env: process.env, stdin: process.stdin, ...io };
|
|
607
|
+
const [command, ...rest] = argv;
|
|
608
|
+
if (command === 'wallet-init') return runWalletInit(rest, fullIo);
|
|
609
|
+
if (command === 'settings-set') return runSettingsSet(rest, fullIo);
|
|
610
|
+
if (command === 'claim') return runClaim(rest, fullIo);
|
|
611
|
+
if (command === 'daily-run') return runDailyRun(rest, fullIo);
|
|
612
|
+
if (command === 'status') return runStatus(rest, fullIo);
|
|
613
|
+
if (command === 'serve') return runServe(rest, fullIo);
|
|
614
|
+
if (command === 'backup') return runBackup(rest, fullIo);
|
|
615
|
+
if (command === 'restore') return runRestore(rest, fullIo);
|
|
616
|
+
if (command === 'sandbox-check') {
|
|
617
|
+
const { runSandboxSmoke } = await import('../e2e/sandbox-smoke.mjs');
|
|
618
|
+
return runSandboxSmoke();
|
|
619
|
+
}
|
|
620
|
+
fullIo.err.write(`tryflop: unknown command "${String(command).slice(0, 30)}". Run: tryflop help\n`);
|
|
621
|
+
return 2;
|
|
622
|
+
}
|