tryflop 0.0.1 → 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/src/outer.js ADDED
@@ -0,0 +1,969 @@
1
+ // tryflop's OUTER commands (SPEC.md "tryflop setup", "tryflop daily", "The scheduler"): they manage the operating system
2
+ // (the copy of the code, the scheduler, Claude Code's registration, notifications) and start the INNER commands
3
+ // (src/tryflop.js) as child processes, which sandbox themselves on macOS. Node built-ins and this package's own
4
+ // built-in-only modules ONLY: nothing third-party ever runs outside the sandbox (test/outer.test.js walks the imports).
5
+ import { spawn, spawnSync } from 'node:child_process';
6
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
7
+ import { homedir, tmpdir } from 'node:os';
8
+ import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { parseArgs } from 'node:util';
11
+ import { newAgentSettings, readAgentSettings } from './agent-settings.js';
12
+ import { installApp } from './install.js';
13
+ import { walletHome } from './layout.js';
14
+ import { cleanTopic } from './questions.js';
15
+ import { appRoot, homeRoot, humanRoot, launcherCommand, launcherDir, logsRoot, payersRoot } from './roots.js';
16
+ import { editCrontab, jobSuffix, notifyCommand, schedulerPlan } from './scheduler.js';
17
+ import { humanFiles } from './statusfile.js';
18
+ import { forPlatform, MOMENT_TEXT, weeklyText } from './moments.js';
19
+ import { formatFlop } from './shared/units.js';
20
+
21
+ const APP_DIR = resolve(fileURLToPath(new URL('..', import.meta.url)));
22
+ const PKG = JSON.parse(readFileSync(join(APP_DIR, 'package.json'), 'utf8'));
23
+ export const VERSION = PKG.version;
24
+ const NETWORK_NAMES = new Set(['testnet', 'devnet']);
25
+ /** Homebrew (Apple silicon or Intel) or MacPorts: the sandbox cannot run their Node (src/sandbox.js). */
26
+ const PACKAGE_MANAGER_NODE = /^\/(?:opt\/homebrew|usr\/local\/Cellar|opt\/local)\//;
27
+ export const NVM_VERSION = 'v0.41.0';
28
+
29
+ export const UNSANDBOXED_NOTICE = 'Note: on Windows and Linux Try Flop runs without an operating-system sandbox: Flop\'s code runs with your user\'s permissions.';
30
+
31
+ /**
32
+ * @typedef {{ out: { write(text: string): unknown }, err: { write(text: string): unknown }, env: NodeJS.ProcessEnv,
33
+ * platform: string, execPath: string, uid: number, home: string, now: () => number,
34
+ * run: (cmd: string, args: string[], o?: { input?: string, env?: Record<string, string>, timeoutMs?: number }) => { status: number | null, stdout: string, stderr: string, error?: string },
35
+ * detach: (cmd: string, args: string[]) => void }} OuterIo
36
+ * detach: start a program that outlives this one (cron's first run)
37
+ */
38
+
39
+ /** The real way to run a program: no shell, pipes, a time limit. */
40
+ export const realRun = (/** @type {string} */ cmd, /** @type {string[]} */ args, /** @type {any} */ o = {}) => {
41
+ // A daily run can take hours and its chain library logs every reconnect: 64 MB, not the 1 MB default (review, 27 Nov).
42
+ const r = spawnSync(cmd, args, { encoding: 'utf8', input: o.input, timeout: o.timeoutMs ?? 60_000, env: o.env ? { ...process.env, ...o.env } : process.env, windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
43
+ return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '', ...(r.error ? { error: r.error.message } : {}) };
44
+ };
45
+
46
+ /** Start a program in the background that outlives this process (its output is dropped; the run keeps its own log). */
47
+ export const realDetach = (/** @type {string} */ cmd, /** @type {string[]} */ args) => {
48
+ spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref();
49
+ };
50
+
51
+ /**
52
+ * Claude Code's name for this install's tool: "tryflop" for the person's own testnet install; the network and a
53
+ * non-default data folder's hash otherwise, so a test or a proof never replaces the person's own tool (review of 2b3a0ff).
54
+ * @param {OuterIo} io @param {string} network
55
+ */
56
+ export const claudeServerName = (io, network) => ['tryflop', jobSuffixFor(io, network)].filter(Boolean).join('-');
57
+
58
+ /**
59
+ * The scheduler job's name suffix: the network (testnet has none: it is the person's own) and, for a data folder other
60
+ * than the default (tests, proofs), its hash; so devnet's job never replaces testnet's (review, 27 Nov).
61
+ * @param {OuterIo} io @param {string} network
62
+ */
63
+ const jobSuffixFor = (io, network) => [network === 'testnet' ? '' : network, jobSuffix(homeRoot(io.env), homeRoot({}))].filter(Boolean).join('-');
64
+
65
+ /** A Flop address as the wallet prints it (anything else the sandboxed child printed is not shown). */
66
+ const SS58 = /^[1-9A-HJ-NP-Za-km-z]{46,48}$/;
67
+
68
+ /**
69
+ * What the outer process shows for the inner run's report: its own words for each known moment (never the child's
70
+ * text: sandboxed code must not get a notification channel to the human), the weekly line rebuilt from checked numbers,
71
+ * and the status text cleaned (review, 27 Nov).
72
+ * @param {any} report @param {string} platform
73
+ * @returns {{ notes: string[], line: string, summary: string }}
74
+ */
75
+ export function trustedReport(report, platform) {
76
+ const notes = [];
77
+ const seen = new Set();
78
+ for (const m of Array.isArray(report?.moments) ? report.moments.slice(0, 6) : []) {
79
+ const kind = String(m?.kind ?? '');
80
+ if (seen.has(kind)) continue;
81
+ seen.add(kind);
82
+ if (Object.hasOwn(MOMENT_TEXT, kind)) notes.push(forPlatform(MOMENT_TEXT[/** @type {keyof typeof MOMENT_TEXT} */ (kind)], platform));
83
+ else if (kind === 'weekly') {
84
+ const w = m?.week ?? {};
85
+ if (Number.isSafeInteger(w.answers) && w.answers >= 0 && /^[0-9]{1,30}$/.test(String(w.spentPlanck))) {
86
+ notes.push(weeklyText({ answers: w.answers, spentFlop: formatFlop(BigInt(w.spentPlanck)), scoringOn: w.scoringOn === true }));
87
+ }
88
+ }
89
+ }
90
+ return { notes, line: fromSandbox(String(report?.line ?? ''), 300).trim(), summary: fromSandbox(`${report?.result ?? ''}: ${report?.reason ?? ''}`, 500).trim() };
91
+ }
92
+
93
+ /** A Node version as numbers. @param {string} v */
94
+ const parts = (v) => v.replace(/^v/, '').split('.').map((n) => Number.parseInt(n, 10));
95
+
96
+ /**
97
+ * Whether this Node can run tryflop, and if not, exactly what to do (SPEC.md setup: the first two checks).
98
+ * @param {{ platform: string, version: string, execPath: string, realExecPath: string }} o @returns {string | null}
99
+ */
100
+ export function nodeProblem({ platform, version, execPath, realExecPath }) {
101
+ const [major, minor] = parts(version);
102
+ const again = `npx -y tryflop@${VERSION} setup`;
103
+ if (platform === 'darwin' && (PACKAGE_MANAGER_NODE.test(execPath) || PACKAGE_MANAGER_NODE.test(realExecPath))) {
104
+ return [
105
+ `This Node.js (${realExecPath}) comes from Homebrew or MacPorts, and Try Flop's macOS sandbox cannot run it (it loads libraries from the package manager's folders).`,
106
+ 'Install Node 22 with nvm instead (no admin password needed), then run setup again, in one line:',
107
+ ` curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/${NVM_VERSION}/install.sh | bash && export NVM_DIR="$HOME/.nvm" && . "$NVM_DIR/nvm.sh" && nvm install 22 && ${again}`,
108
+ 'Homebrew\'s Node stays installed and keeps working for everything else.',
109
+ ].join('\n');
110
+ }
111
+ if (major < 22 || (major === 22 && minor < 15)) {
112
+ return `Try Flop needs Node.js 22.15 or newer; this is ${version}. Install the current Node 22 LTS from https://nodejs.org (or with nvm), then run: ${again}`;
113
+ }
114
+ return null;
115
+ }
116
+
117
+ /**
118
+ * Text that came out of the sandbox (a child's stderr), made safe to show outside it: printable characters and line
119
+ * breaks only, and not too much of it (security review, 27 Nov 2026: a compromised child could write terminal escapes).
120
+ * @param {string} text @param {number} [max]
121
+ */
122
+ export const fromSandbox = (text, max = 4000) => String(text ?? '').replace(/\r\n/g, '\n').replace(/[^\x20-\x7E\n\u00A0-\uFFFF]/g, '').replace(/[\u0080-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069]/g, '').slice(-max);
123
+
124
+ /** The inner command, as a child: it sandboxes itself on macOS. Output is piped (never a file in a hidden folder). */
125
+ function runInner(/** @type {OuterIo} */ io, /** @type {string} */ binPath, /** @type {string[]} */ args, timeoutMs = 120_000) {
126
+ return io.run(io.execPath, [binPath, ...args], { timeoutMs });
127
+ }
128
+
129
+ /**
130
+ * Save settings by handing them to the sandboxed child (`settings-set`): this process never writes into a folder the
131
+ * sandbox can change (security reviews, 27 Nov). Throws when the child refuses.
132
+ * @param {OuterIo} io @param {string} binPath @param {string} network @param {object} settings
133
+ */
134
+ function saveSettings(io, binPath, network, settings) {
135
+ const r = runInner(io, binPath, ['settings-set', '--network', network, '--json', JSON.stringify(settings)]);
136
+ if (r.status !== 0) throw new Error(`the settings could not be saved (${fromSandbox(r.stderr || r.error || '', 300).trim() || `exit ${r.status}`})`);
137
+ }
138
+
139
+ /** The FLOP_MCP_* variables to hand on to the scheduler: only those that differ from the defaults (tests, proofs). @param {NodeJS.ProcessEnv} env */
140
+ function passedEnv(env) {
141
+ /** @type {Record<string, string>} */
142
+ const out = {};
143
+ for (const name of ['FLOP_MCP_HOME', 'FLOP_MCP_PAYERS', 'FLOP_MCP_HUMAN_DIR', 'FLOP_MCP_APP_ROOT', 'FLOP_MCP_STATUS_URL']) {
144
+ if (env[name]) out[name] = String(env[name]);
145
+ }
146
+ return out;
147
+ }
148
+
149
+ /**
150
+ * The data folders: either none is set (the person's own install, in the default folders), or all four are set, side by
151
+ * side in one folder of their own (a test, a proof: ~/.tryflop-proof/{home,payers,TryFlop,app}). An ALLOW rule, not a
152
+ * list of forbidden places: three review rounds each found a place the list lacked (the launcher's folder, Node's own
153
+ * folder, a link that leads elsewhere). With the four side by side and none of them a link, the sandbox may write only
154
+ * three sibling folders, which can hold nothing that runs outside it: not the code copy or its launcher and logs (the
155
+ * fourth sibling and the bin/ and logs/ beside it), not Node, not a scheduler's folder (push-gate review of a4bea37).
156
+ * @param {NodeJS.ProcessEnv} env @returns {string | null}
157
+ */
158
+ export function dataFolderProblem(env) {
159
+ const names = /** @type {const} */ (['FLOP_MCP_HOME', 'FLOP_MCP_PAYERS', 'FLOP_MCP_HUMAN_DIR', 'FLOP_MCP_APP_ROOT']);
160
+ const set = names.filter((name) => env[name]);
161
+ if (set.length === 0) return null;
162
+ const rule = `Data folders other than the defaults are for tests and proofs: then set all four (${names.join(', ')}) to <dir>/home, <dir>/payers, <dir>/TryFlop and <dir>/app as absolute paths, where <dir> is a folder of their own directly inside your home folder or the system's temp folder, none of them a link`;
163
+ if (set.length < names.length) return `${rule}; ${names.filter((name) => !env[name]).join(', ')} ${set.length === 3 ? 'is' : 'are'} missing (a mix would share this computer's own launcher, code or status file). Nothing was changed.`;
164
+ // Compared as the file system sees them: through links (the sandbox grants real paths), and on a Mac or Windows disk
165
+ // without case and in one Unicode form (there ~/.TryFlop is ~/.tryflop, and "é" written two ways is one name).
166
+ const fold = (/** @type {string} */ p) => { const real = realish(p); return process.platform === 'darwin' || process.platform === 'win32' ? real.normalize('NFC').toLowerCase() : real; };
167
+ const within = (/** @type {string} */ outer, /** @type {string} */ inner) => inner.startsWith(outer.endsWith(sep) ? outer : outer + sep);
168
+ if (names.some((name) => !isAbsolute(String(env[name])))) return `${rule} (the scheduler starts in another folder, so a relative path would name somewhere else). Nothing was changed.`;
169
+ const folders = [homeRoot(env), payersRoot(env), humanRoot(env), appRoot(env)];
170
+ const parent = dirname(folders[0]);
171
+ // Exactly these names, side by side: no data folder can be something that runs (~/Library/LaunchAgents, ~/.nvm/...).
172
+ if (folders.some((folder, n) => folder !== join(parent, ['home', 'payers', 'TryFlop', 'app'][n]))) return `${rule}. Nothing was changed.`;
173
+ // <dir> directly inside the home or temp folder: never inside another install's data folder (whose sandbox could then
174
+ // rewrite this install's code) nor anywhere deeper that something else runs from (push-gate review of 4ac7d10).
175
+ if (![homedir(), tmpdir()].some((place) => fold(dirname(parent)) === fold(place))) return `${rule}; ${parent} is not directly inside either. Nothing was changed.`;
176
+ // <dir> itself too: a link there would put all four inside wherever it leads (another install's data folder: push-gate
177
+ // review of 2875307).
178
+ for (const path of [parent, ...folders, join(parent, 'bin'), join(parent, 'logs')]) {
179
+ let link = false;
180
+ try { link = lstatSync(path).isSymbolicLink(); } catch { /* not there yet */ }
181
+ if (link) return `${rule}: ${path} is a link. Nothing was changed.`;
182
+ }
183
+ // That folder is not the home folder or above it, and shares nothing with this computer's own Try Flop.
184
+ const own = fold(parent);
185
+ const home = fold(homedir());
186
+ const defaults = [dirname(appRoot({})), homeRoot({}), payersRoot({}), humanRoot({})].map(fold);
187
+ if (own === home || within(own, home) || defaults.some((d) => d === own || within(d, own) || within(own, d))) {
188
+ return `${rule}; ${parent} is your home folder, holds it, or overlaps this computer's own Try Flop folders. Nothing was changed.`;
189
+ }
190
+ // Nobody else may have put anything there: <dir> and what is already in it belong to this user and no other user may
191
+ // write them. In the temp folder (Linux's /tmp is shared by every user) <dir> must already exist, made privately
192
+ // (mkdtemp), so nobody can create it first (security review of 2875307). Windows has no such owners here; its temp
193
+ // folder is the user's own.
194
+ if (typeof process.getuid === 'function' && typeof process.getgid === 'function') {
195
+ const uid = process.getuid();
196
+ const gid = process.getgid();
197
+ const inTemp = fold(dirname(parent)) === fold(tmpdir());
198
+ // A temp folder others may write must be sticky (/tmp is 1777), or they could rename <dir> away and swap in their own.
199
+ if (inTemp) {
200
+ let t = null;
201
+ try { t = statSync(tmpdir()); } catch { /* none */ }
202
+ if (!t || ((t.mode & 0o022) !== 0 && (t.mode & 0o1000) === 0)) return `${rule}; the temp folder ${tmpdir()} lets others swap folders in it. Nothing was changed.`;
203
+ }
204
+ for (const path of [parent, ...folders, join(parent, 'bin'), join(parent, 'logs')]) {
205
+ let st;
206
+ try { st = lstatSync(path); } catch { st = null; }
207
+ if (!st) {
208
+ if (path === parent && inTemp) return `${rule}; ${parent} must already exist in the temp folder, made by you alone (mkdtemp). Nothing was changed.`;
209
+ continue;
210
+ }
211
+ // Group write is harmless only for a group of one: Linux's usual umask 002 comes with a private group numbered like
212
+ // the user (uid 1000, gid 1000: push-gate review of 2875307). A Mac's main group (staff, 20) is everyone's, so
213
+ // there it is refused. Write by others never is fine.
214
+ const privateGroup = st.gid === gid && gid === uid;
215
+ if (st.uid !== uid || (st.mode & 0o002) !== 0 || ((st.mode & 0o020) !== 0 && !privateGroup)) return `${rule}; ${path} belongs to another user or others may write it. Nothing was changed.`;
216
+ }
217
+ }
218
+ // Node itself must not sit where the sandbox may write: the scheduler starts it outside the sandbox.
219
+ let node = process.execPath;
220
+ try { node = realpathSync(process.execPath); } catch { /* keep the given path */ }
221
+ const nodeFolded = process.platform === 'darwin' || process.platform === 'win32' ? node.normalize('NFC').toLowerCase() : node;
222
+ if (folders.slice(0, 3).some((folder) => within(fold(folder), nodeFolded))) return `${rule}; this Node (${node}) sits inside one of them. Nothing was changed.`;
223
+ return null;
224
+ }
225
+
226
+ /**
227
+ * A path as the file system resolves it: the real path of its nearest existing folder, plus the rest. @param {string} p
228
+ */
229
+ function realish(p) {
230
+ let head = resolve(p);
231
+ const rest = [];
232
+ for (;;) {
233
+ try {
234
+ return join(realpathSync(head), ...rest);
235
+ } catch {
236
+ const up = dirname(head);
237
+ if (up === head) return resolve(p);
238
+ rest.unshift(basename(head));
239
+ head = up;
240
+ }
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Delete Try Flop's own entries in a folder, then the folder itself if it is empty now.
246
+ * @param {string} dir @param {(name: string, path: string) => boolean} own
247
+ */
248
+ function removeOwn(dir, own) {
249
+ let names;
250
+ try {
251
+ names = readdirSync(dir);
252
+ } catch {
253
+ return;
254
+ }
255
+ for (const name of names) if (own(name, join(dir, name))) rmSync(join(dir, name), { recursive: true, force: true });
256
+ try {
257
+ rmdirSync(dir);
258
+ } catch { /* something else lives there: kept */ }
259
+ }
260
+
261
+ /**
262
+ * tryflop setup (SPEC.md "tryflop setup"). Quick (well under a minute): the long first run starts in the background.
263
+ * @param {string[]} args @param {OuterIo} io @returns {Promise<number>}
264
+ */
265
+ export async function runSetup(args, io) {
266
+ let values;
267
+ try {
268
+ ({ values } = parseArgs({ args, options: { network: { type: 'string', default: 'testnet' }, topic: { type: 'string' }, daily: { type: 'string' }, 'no-claude': { type: 'boolean', default: false } }, strict: true, allowPositionals: false }));
269
+ } catch (error) {
270
+ io.err.write(`tryflop: ${/** @type {Error} */ (error).message}\nusage: tryflop setup [--daily on|off] [--topic "<a subject for the daily questions>"] [--network testnet]\n`);
271
+ return 2;
272
+ }
273
+ const network = String(values.network);
274
+ if (!NETWORK_NAMES.has(network)) {
275
+ io.err.write('tryflop: --network is testnet (or devnet for testing).\n');
276
+ return 2;
277
+ }
278
+ if (values.daily !== undefined && values.daily !== 'on' && values.daily !== 'off') {
279
+ io.err.write('tryflop: --daily is on (the human said yes to a daily run) or off.\n');
280
+ return 2;
281
+ }
282
+ let realExec = io.execPath;
283
+ try { realExec = realpathSync(io.execPath); } catch { /* keep the given path */ }
284
+ const problem = nodeProblem({ platform: io.platform, version: process.version, execPath: io.execPath, realExecPath: realExec });
285
+ if (problem) {
286
+ io.err.write(`tryflop: ${problem}\n`);
287
+ return 1;
288
+ }
289
+ const lines = ['Try Flop setup — an independent tool, not made by Flop Labs.', ''];
290
+ if (io.platform !== 'darwin') lines.push(UNSANDBOXED_NOTICE, '');
291
+
292
+ // 1. The code the scheduler and Claude Code start: a copy outside every folder the sandbox may write.
293
+ let app;
294
+ try {
295
+ app = installApp({ appDir: APP_DIR, appRoot: appRoot(io.env), version: VERSION, name: PKG.name });
296
+ } catch (error) {
297
+ io.err.write(`tryflop: could not copy Try Flop to ${appRoot(io.env)} (${/** @type {Error} */ (error).message}).\n`);
298
+ return 1;
299
+ }
300
+
301
+ const cmd = writeLauncher(io, app.binPath);
302
+
303
+ // 2. The wallet (sandboxed child). Its words are never printed.
304
+ const made = runInner(io, app.binPath, ['wallet-init', '--network', network]);
305
+ let wallet;
306
+ try {
307
+ wallet = JSON.parse(made.stdout.trim().split('\n').pop() ?? '');
308
+ } catch {
309
+ wallet = null;
310
+ }
311
+ if (made.status !== 0 || typeof wallet?.address !== 'string' || !SS58.test(wallet.address)) {
312
+ io.err.write(`tryflop: the wallet could not be made.\n${fromSandbox(made.stderr || made.error || '', 1500).trim()}\n`);
313
+ return 1;
314
+ }
315
+ const home = walletHome(homeRoot(io.env), /** @type {'testnet'|'devnet'} */ (network));
316
+
317
+ // 3. Settings: the daily brief's topic and a random minute of the day (kept once chosen).
318
+ const before = readAgentSettings(home.tryflopFile);
319
+ const settings = before ?? newAgentSettings({ now: io.now });
320
+ if (values.topic !== undefined) settings.topic = cleanTopic(values.topic);
321
+ saveSettings(io, app.binPath, network, settings);
322
+
323
+ lines.push(wallet.created
324
+ ? `Made this agent's own Flop wallet: ${wallet.address}`
325
+ : `This computer already has a Try Flop wallet, kept as it is (one wallet per person): ${wallet.address}`);
326
+ lines.push(`Its files: ${home.dir} (private to your user). What it does: ${join(humanRoot(io.env), humanFiles(network).status)}`);
327
+ lines.push('');
328
+
329
+ // 4. Claude Code: the ask_flop tool, paid from this wallet.
330
+ if (!values['no-claude']) lines.push(...registerClaude(io, app.binPath, network));
331
+
332
+ // 5. The daily run, only with the human's yes; a "no" after an earlier "yes" removes it (review, 27 Nov).
333
+ const suffix = jobSuffixFor(io, network);
334
+ /** @type {'on'|'off'|'gone'|'unknown' | undefined} */
335
+ let state;
336
+ // Every command printed for another network than testnet must name it, or it acts on testnet's wallet and job.
337
+ const net = network !== 'testnet' ? ` --network ${network}` : '';
338
+ if (values.daily === 'on') {
339
+ const done = installScheduler(io, { binPath: app.binPath, network, settings, suffix, logDir: logsRoot(io.env), lockFile: home.lockFile });
340
+ if (done.ok) {
341
+ settings.daily = 'on';
342
+ settings.scheduler = done.kind;
343
+ saveSettings(io, app.binPath, network, settings);
344
+ lines.push(/** @type {any} */ (done).unchanged
345
+ ? `Daily run: already on (${done.kind}), every day at ${hhmm(settings)} this computer's time; nothing changed. Status: ${cmd} status${net}`
346
+ : `Daily run: on (${done.kind}), every day at ${hhmm(settings)} this computer's time, and again 6 and 12 hours later if a run could not finish. The first run started now, in the background: it claims Flop's free test FLOP for this wallet (Flop's faucet can take 15 minutes or more) and pays a miner for one short answer. Check in about 20 minutes with: ${cmd} status${net}`);
347
+ if (done.note) lines.push(done.note);
348
+ } else if (/** @type {any} */ (done).busy) {
349
+ lines.push(`Daily run: on; a run is going right now, so it was left as it is. Run setup again once it has finished. Status: ${cmd} status${net}`);
350
+ } else {
351
+ // Whatever an earlier install left is gone or broken now: record off, so no later setup reports "already on".
352
+ const left = removeScheduler(io, network, settings);
353
+ settings.daily = 'off';
354
+ delete settings.scheduler;
355
+ saveSettings(io, app.binPath, network, settings);
356
+ lines.push(`Daily run: NOT installed (${/** @type {{ why: string }} */ (done).why}). Run "${cmd} daily${net}" by hand once a day, or ask your AI agent to.`);
357
+ if (left.length) lines.push(`An earlier daily run could NOT be fully removed: ${left.join('; ')}.`);
358
+ }
359
+ } else if (values.daily === 'off') {
360
+ const problems = removeScheduler(io, network, settings);
361
+ settings.daily = 'off';
362
+ delete settings.scheduler;
363
+ saveSettings(io, app.binPath, network, settings);
364
+ lines.push(problems.length
365
+ ? `Daily run: could NOT be fully removed: ${problems.join('; ')}.`
366
+ : `Daily run: off, as asked (any daily run set up earlier is removed). Run "${cmd} daily${net}" by hand when you want one.`);
367
+ } else if (settings.daily === 'on' && (state = jobState(io, network, settings)) === 'unknown') {
368
+ lines.push(`Daily run: on, but this computer's scheduler could not say whether its job is there right now, so nothing was changed. Run setup again later; to stop it: ${cmd} setup --daily off${net}`);
369
+ } else if (settings.daily === 'on' && state === 'on') {
370
+ // Re-install it with THIS copy: a newer version's setup must not leave the job starting the old one (review of ef43de4).
371
+ const done = installScheduler(io, { binPath: app.binPath, network, settings, suffix, logDir: logsRoot(io.env), startNow: false, lockFile: home.lockFile });
372
+ if (!done.ok && /** @type {any} */ (done).busy) {
373
+ lines.push(`Daily run: on; a run is going right now, so it was left as it is. Run setup again once it has finished to update it. To stop it: ${cmd} setup --daily off${net}`);
374
+ } else if (done.ok) {
375
+ settings.scheduler = done.kind;
376
+ saveSettings(io, app.binPath, network, settings);
377
+ lines.push(`Daily run: already on (${done.kind}), every day at ${hhmm(settings)} this computer's time, now running this version. To stop it: ${cmd} setup --daily off${net}`);
378
+ if (done.note) lines.push(done.note);
379
+ } else {
380
+ const left = removeScheduler(io, network, settings);
381
+ settings.daily = 'off';
382
+ delete settings.scheduler;
383
+ saveSettings(io, app.binPath, network, settings);
384
+ lines.push(`Daily run: could not be updated to this version (${/** @type {{ why: string }} */ (done).why}), so it is off now. Run "${cmd} daily${net}" by hand once a day.`);
385
+ if (left.length) lines.push(`The old daily run could NOT be fully removed: ${left.join('; ')}.`);
386
+ }
387
+ } else {
388
+ if (settings.daily === 'on') {
389
+ // The settings say on, but the job is gone (removed by hand, or an uninstall that could not save its settings) or
390
+ // switched off by hand: the human's yes was for a job they have since stopped, so what is left of it goes and the
391
+ // human is asked again; only --daily on turns it back on (reviews of 6be8437 and 4ac7d10).
392
+ const left = removeScheduler(io, network, settings);
393
+ settings.daily = 'off';
394
+ delete settings.scheduler;
395
+ saveSettings(io, app.binPath, network, settings);
396
+ lines.push(state === 'off'
397
+ ? 'The daily run was on, but its job was switched off by hand, so it is removed and off now.'
398
+ : 'The daily run was on, but its job is no longer on this computer (removed by hand, or by an uninstall), so it is off now.');
399
+ if (left.length) lines.push(`It could NOT be fully removed: ${left.join('; ')}.`);
400
+ }
401
+ lines.push(
402
+ 'Daily run: not set up yet. Ask your human this, word for word:',
403
+ ` "May Try Flop run once a day in the background on this computer? It claims Flop's free test FLOP for its own wallet and pays a miner for a short daily answer about '${settings.topic}'. Test FLOP has no value, and it never uses any other wallet or money. You can stop it any time with: ${cmd} uninstall${net}"`,
404
+ `If they say yes, run: ${cmd} setup --daily on${net}`,
405
+ );
406
+ }
407
+ lines.push(
408
+ '',
409
+ `For the human, once: save the wallet's 12 recovery words. Open a terminal window yourself (not through an AI agent) and run: ${cmd} backup${net}`,
410
+ `Status any time: ${cmd} status${net}`,
411
+ 'AI agents: never run "backup" or "restore", and never read the wallet\'s files: they hold the words.',
412
+ '',
413
+ 'Flop says compute purchased in settled sessions is what its airdrop counts. Scoring is on since 30 November 2026 (block 448,897), test FLOP has no value, and Flop decides who qualifies and how much.',
414
+ );
415
+ io.out.write(`${lines.join('\n')}\n`);
416
+ return 0;
417
+ }
418
+
419
+ /**
420
+ * The launcher: one short command that always starts the copied code with this Node (the human's own terminal may put
421
+ * another Node first, e.g. Homebrew's, which the sandbox refuses). Outside every folder the sandbox may write.
422
+ * @param {OuterIo} io @param {string} binPath @returns {string} the command to print
423
+ */
424
+ export function writeLauncher(io, binPath) {
425
+ const dir = launcherDir(io.env);
426
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
427
+ // A data folder other than the default (a test, a proof) travels with the launcher, or its commands would act on the
428
+ // default install (review of ef43de4).
429
+ const env = Object.entries(passedEnv(io.env));
430
+ if (io.platform === 'win32') {
431
+ writeFileSync(join(dir, 'tryflop.cmd'), `@echo off\r\n${env.map(([k, v]) => `set "${k}=${v}"\r\n`).join('')}"${io.execPath}" "${binPath}" %*\r\n`);
432
+ } else {
433
+ const q = (/** @type {string} */ t) => `'${t.replace(/'/g, `'\\''`)}'`;
434
+ writeFileSync(join(dir, 'tryflop'), `#!/bin/sh\n# Try Flop's launcher (written by tryflop setup): this Node and the copied code.\n${env.map(([k, v]) => `export ${k}=${q(v)}\n`).join('')}exec ${q(io.execPath)} ${q(binPath)} "$@"\n`, { mode: 0o700 });
435
+ chmodSync(join(dir, 'tryflop'), 0o700);
436
+ }
437
+ if (!Object.keys(passedEnv(io.env)).length) return launcherCommand(io.platform);
438
+ const own = join(dir, io.platform === 'win32' ? 'tryflop.cmd' : 'tryflop');
439
+ return io.platform === 'win32' ? own.replace(/\\/g, '/') : own;
440
+ }
441
+
442
+ /**
443
+ * Remove this network's daily job from every scheduler that could hold it (a half-done setup is cleaned too), and say
444
+ * what could not be removed instead of claiming it was (review of ef43de4).
445
+ * @param {OuterIo} io @param {string} network @param {{ hour: number, minute: number } | null} settings
446
+ * @returns {string[]} problems, each with the command that finishes the job by hand
447
+ */
448
+ export function removeScheduler(io, network, settings) {
449
+ const problems = [];
450
+ for (const plan of jobPlans(io, network, settings)) {
451
+ if (plan.kind === 'cron') {
452
+ const current = io.run('crontab', ['-l'], { timeoutMs: 20_000 });
453
+ // No answer at all (a timeout) is never "removed" (push-gate review of b96ca53).
454
+ if (plan.cron && cronTimedOut(current)) problems.push(`crontab -l did not answer: check with "crontab -l" that no line ends in ${plan.cron.marker}`);
455
+ if (plan.cron && current.status === 0 && hasCronLine(current.stdout, plan.cron.marker)) {
456
+ const written = io.run('crontab', ['-'], { input: editCrontab(current.stdout, plan.cron.marker), timeoutMs: 20_000 });
457
+ if (written.status !== 0) problems.push(`the cron line could not be removed: run "crontab -e" and delete the line ending in ${plan.cron.marker}`);
458
+ }
459
+ continue;
460
+ }
461
+ const present = jobFilesHere(plan);
462
+ const anyFile = plan.removeFiles.some((file) => existsSync(file));
463
+ const failed = [];
464
+ for (const step of plan.uninstall) {
465
+ const r = io.run(step.cmd, step.args, { timeoutMs: 60_000, env: step.env });
466
+ if (!(step.okCodes ?? [0]).includes(r.status ?? -1)) failed.push(`${step.cmd} ${step.args.join(' ')} answered ${r.status ?? 'nothing'}${r.stderr.trim() ? ` (${r.stderr.trim().slice(0, 120)})` : ''}`);
467
+ }
468
+ // A stop that answered neither "stopped" nor "not loaded": ask the scheduler itself whether it still holds the job,
469
+ // with or without its file (a failed install deletes its new file while an older job may still be loaded; a timer
470
+ // file deleted by hand leaves the timer loaded: push-gate reviews of 34fa6ee and 96f7c8f). With no answer either way
471
+ // (systemctl without a bus), only a job whose file is here may still be loaded; with no systemd manager for this
472
+ // user at all (WSL, a container), nothing can be, so deleting the files IS the removal.
473
+ // An unknown answer counts as held for launchd and Task Scheduler, file or not (their file goes below either way, so
474
+ // the next removal must not read its absence as "removed"); for systemd only while its .timer is here (push-gate
475
+ // review of a4bea37).
476
+ let stuck = false;
477
+ if (failed.length && !(plan.kind === 'systemd' && noUserManager(io))) {
478
+ const held = heldState(io, plan);
479
+ stuck = held === 'yes' || (held === 'unknown' && (plan.kind !== 'systemd' || present));
480
+ }
481
+ if (stuck) problems.push(...failed.map((f) => `${f}: run it again by hand`));
482
+ // Possibly still loaded. systemd: the unit files stay, so the next removal sees the job even if is-active cannot
483
+ // answer (review of 6be8437). launchd and Task Scheduler answer for themselves, so their file goes anyway: a kept
484
+ // plist would load the job again at every login (push-gate review of 3f55b81).
485
+ if (stuck && plan.kind === 'systemd') continue;
486
+ for (const file of plan.removeFiles) rmSync(file, { force: true });
487
+ if (plan.kind === 'systemd' && anyFile) io.run('systemctl', ['--user', 'daemon-reload'], { timeoutMs: 20_000, env: { XDG_RUNTIME_DIR: userRuntimeDir(io) } });
488
+ }
489
+ return problems;
490
+ }
491
+
492
+ /**
493
+ * The user's runtime folder (XDG_RUNTIME_DIR), where `systemctl --user` finds the user's manager: a shell reached over
494
+ * SSH or su often lacks the variable, and systemctl then cannot connect even while the manager runs.
495
+ * @param {OuterIo} io
496
+ */
497
+ const userRuntimeDir = (io) => String(io.env.XDG_RUNTIME_DIR || `/run/user/${io.uid}`);
498
+
499
+ /**
500
+ * No systemd manager runs for this user (WSL with systemd off, a container): neither the given runtime folder nor this
501
+ * user's own holds systemd/ (`su` without `-` keeps another user's XDG_RUNTIME_DIR: push-gate review of 3f55b81).
502
+ * @param {OuterIo} io
503
+ */
504
+ const noUserManager = (io) => !existsSync(join(userRuntimeDir(io), 'systemd')) && !existsSync(join('/run/user', String(io.uid), 'systemd'));
505
+
506
+ /**
507
+ * The job's own file is here: for systemd the .timer (what runs; a lone .service from a half-written install is just a
508
+ * file to delete), otherwise any of its files.
509
+ * @param {import('./scheduler.js').Plan} plan
510
+ */
511
+ const jobFilesHere = (plan) => plan.removeFiles.some((file) => (plan.kind !== 'systemd' || file.endsWith('.timer')) && existsSync(file));
512
+
513
+ /**
514
+ * The scheduler's own answer: does it hold this job, running? 'unknown' when it cannot say (no question, no bus, a
515
+ * timeout, launchd outside a desktop login).
516
+ * @param {OuterIo} io @param {import('./scheduler.js').Plan} plan @returns {'yes'|'no'|'unknown'}
517
+ */
518
+ function heldState(io, plan) {
519
+ const held = plan.held;
520
+ if (!held) return 'unknown';
521
+ const r = io.run(held.cmd, held.args, { timeoutMs: 20_000, env: held.env });
522
+ if (r.status === 0) return 'yes';
523
+ if (r.status === null || !held.absent.includes(r.status)) return 'unknown';
524
+ if (held.scope && io.run(held.scope.cmd, held.scope.args, { timeoutMs: 20_000, env: held.scope.env }).status !== 0) return 'unknown';
525
+ return 'no';
526
+ }
527
+
528
+ /**
529
+ * Held but switched off by hand (a timer disabled, a Windows task disabled)? 'unknown' when the question failed: never
530
+ * read as "not off", or re-pointing would switch it back on (push-gate review of 2875307).
531
+ * @param {OuterIo} io @param {import('./scheduler.js').Plan} plan @returns {'off'|'on'|'unknown'}
532
+ */
533
+ function switchedOff(io, plan) {
534
+ if (!plan.ready) return 'on';
535
+ const r = io.run(plan.ready.cmd, plan.ready.args, { timeoutMs: 20_000, env: plan.ready.env });
536
+ if (new RegExp(plan.ready.off, 'm').test(String(r.stdout))) return 'off';
537
+ return r.status === 0 ? 'on' : 'unknown';
538
+ }
539
+
540
+ /**
541
+ * A `crontab -l` that gave no answer in time: the only "can't tell". No crontab program (ENOENT), one this user may not
542
+ * run (EACCES: openSUSE's secure profile installs it 4750) or one refusing this user (cron.allow) all mean no cron job
543
+ * of ours (push-gate review of 3ff0c9f).
544
+ * @param {{ status: number | null, error?: string }} r
545
+ */
546
+ const cronTimedOut = (r) => r.status === null && /ETIMEDOUT/.test(String(r.error ?? ''));
547
+
548
+ /**
549
+ * Whether a crontab holds this job's line, live: the marker ENDS the line (testnet's is the start of devnet's), and a
550
+ * line the person commented out is not a job (push-gate review of 3f55b81).
551
+ * @param {string} text @param {string} marker
552
+ */
553
+ const hasCronLine = (text, marker) => String(text).split('\n').some((line) => line.endsWith(marker) && !line.trimStart().startsWith('#'));
554
+
555
+ /**
556
+ * Every scheduler plan that could hold this network's job: on Linux the systemd timer (whether or not systemctl answers
557
+ * now) and the cron line, both. For removing and finding a job; never installed from (no code path).
558
+ * @param {OuterIo} io @param {string} network @param {{ hour: number, minute: number } | null} settings
559
+ */
560
+ function jobPlans(io, network, settings) {
561
+ const base = { platform: io.platform, uid: io.uid, home: io.home, nodePath: io.execPath, binPath: '', network, hour: settings?.hour ?? 0, minute: settings?.minute ?? 0, suffix: jobSuffixFor(io, network), env: {}, logDir: logsRoot(io.env), runtimeDir: userRuntimeDir(io) };
562
+ return io.platform === 'linux' ? [schedulerPlan({ ...base, systemd: true }), schedulerPlan({ ...base, systemd: false })] : [schedulerPlan(base)];
563
+ }
564
+
565
+ /**
566
+ * Where this network's daily job stands on this computer (SPEC.md "tryflop setup", DAILY):
567
+ * on will run: launchd's plist is here or launchd holds it (a plist loads at every login); systemd's .timer is
568
+ * here or the manager runs it, and it is not disabled; Task Scheduler holds the task, not disabled; a live
569
+ * crontab line (the marker ENDS the line; a commented line is no job)
570
+ * off switched off by hand: a disabled timer, a disabled Windows task
571
+ * gone nothing of it is left (removed by hand, or by an uninstall that could not save its settings)
572
+ * unknown the scheduler could not say (no answer, a timeout, no bus)
573
+ * Plain setup re-points only "on"; "off" and "gone" are never quietly re-installed or re-enabled (reviews of 6be8437
574
+ * and 4ac7d10).
575
+ * @param {OuterIo} io @param {string} network @param {{ hour: number, minute: number } | null} settings
576
+ * @returns {'on'|'off'|'gone'|'unknown'}
577
+ */
578
+ export function jobState(io, network, settings) {
579
+ let unknown = false;
580
+ for (const plan of jobPlans(io, network, settings)) {
581
+ if (plan.cron) {
582
+ const current = io.run('crontab', ['-l'], { timeoutMs: 20_000 });
583
+ if (current.status === 0 && hasCronLine(current.stdout, plan.cron.marker)) return 'on';
584
+ // No answer at all (a timeout) is "can't tell"; no crontab program, an empty crontab or cron refusing this user
585
+ // (cron.allow) all mean no cron job of ours.
586
+ if (cronTimedOut(current)) unknown = true;
587
+ continue;
588
+ }
589
+ // No systemd manager for this user (cron-only Linux, WSL, a container): no timer can run, and systemctl cannot answer.
590
+ if (plan.kind === 'systemd' && noUserManager(io)) continue;
591
+ const files = jobFilesHere(plan);
592
+ if (plan.kind === 'launchd' && files) {
593
+ // A plist loads at every login, but launchd can only be asked from a desktop login: over SSH with nobody logged in
594
+ // at the screen, re-pointing would fail and switch it off (push-gate review of 2875307).
595
+ const scope = plan.held?.scope;
596
+ if (scope && io.run(scope.cmd, scope.args, { timeoutMs: 20_000, env: scope.env }).status !== 0) { unknown = true; continue; }
597
+ return 'on';
598
+ }
599
+ const held = heldState(io, plan);
600
+ // systemd: a .timer here starts at the next boot unless disabled. Windows: the task file is only setup's copy.
601
+ // A running timer whose file was deleted by hand: the person meant it gone (is-enabled cannot answer for it).
602
+ if (plan.kind === 'systemd' && held === 'yes' && !files) return 'off';
603
+ if (held === 'yes' || (plan.kind === 'systemd' && files)) {
604
+ const switched = switchedOff(io, plan);
605
+ if (switched !== 'unknown') return switched;
606
+ unknown = true;
607
+ continue;
608
+ }
609
+ if (held === 'unknown') unknown = true;
610
+ }
611
+ return unknown ? 'unknown' : 'gone';
612
+ }
613
+
614
+ /** Whether anything of this network's job may be on this computer (on, off or can't tell). @param {OuterIo} io @param {string} network @param {{ hour: number, minute: number } | null} settings */
615
+ export function jobInstalled(io, network, settings) {
616
+ return jobState(io, network, settings) !== 'gone';
617
+ }
618
+
619
+ /**
620
+ * Whether a daily run holds its lock now (a live process, under 3 hours old: src/daily.js takeLock's rule).
621
+ * @param {string} lockFile @param {number} now
622
+ */
623
+ function runInProgress(lockFile, now) {
624
+ try {
625
+ const held = JSON.parse(readFileSync(lockFile, 'utf8'));
626
+ if (!Number.isInteger(held?.pid) || now - Number(held.at) >= 3 * 3_600_000) return false;
627
+ process.kill(held.pid, 0);
628
+ return true;
629
+ } catch (error) {
630
+ return /** @type {any} */ (error)?.code === 'EPERM';
631
+ }
632
+ }
633
+
634
+ /** @param {{ hour: number, minute: number }} s */
635
+ const hhmm = (s) => `${String(s.hour).padStart(2, '0')}:${String(s.minute).padStart(2, '0')}`;
636
+
637
+ /**
638
+ * `claude mcp add` when Claude Code is on this computer and the tool is not registered yet. Its user scope makes the
639
+ * tool available in every project; Claude Code still asks before each call unless the human allows it.
640
+ * @param {OuterIo} io @param {string} binPath @param {string} network @returns {string[]}
641
+ */
642
+ export function registerClaude(io, binPath, network) {
643
+ const server = claudeServerName(io, network);
644
+ const envFlags = Object.entries(passedEnv(io.env)).flatMap(([k, v]) => ['-e', `${k}=${v}`]);
645
+ // The name BEFORE -e: `-e, --env <env...>` takes several values and would read the name as one ("Invalid environment
646
+ // variable format: tryflop-…", Claude Code 2.1.332; review of 6be8437).
647
+ const add = ['mcp', 'add', '--scope', 'user', server, ...envFlags, '--', io.execPath, binPath, 'serve', '--network', network];
648
+ // The same command for a person to paste: forward slashes on Windows (Claude Code's Git Bash reads `C:\Users` as
649
+ // `C:Users`), quotes around anything with a space or a shell character (C:/Program Files/nodejs/node.exe).
650
+ const word = (/** @type {string} */ a) => {
651
+ const w = io.platform === 'win32' ? a.replace(/\\/g, '/') : a;
652
+ return /[\s"'$`\\;&|<>()*?!#]/.test(w) ? `"${w.replace(/(["\\$`])/g, '\\$1')}"` : w;
653
+ };
654
+ const line = ` claude ${add.map(word).join(' ')}`;
655
+ const probe = io.run('claude', ['--version'], { timeoutMs: 20_000 });
656
+ if (probe.status !== 0) {
657
+ // On Windows an npm-installed Claude Code is claude.cmd, which a program can only start through a shell: say so
658
+ // instead of "not found" (review, 27 Nov).
659
+ if (io.platform === 'win32') return ['Claude Code: could not be started from here (on Windows it may be installed as claude.cmd), so no ask_flop tool was added. If you use Claude Code, add it with:', line];
660
+ return ['Claude Code: not found on this computer, so no ask_flop tool was added. With Claude Code installed, add it with:', line];
661
+ }
662
+ const got = io.run('claude', ['mcp', 'get', server], { timeoutMs: 20_000 });
663
+ if (got.status === 0) {
664
+ if (sameTool(got.stdout, io.execPath, `${binPath} serve --network ${network}`, passedEnv(io.env))) return [`Claude Code: the "${server}" tool is already added (ask Claude to "ask Flop" something).`];
665
+ // Added by another copy (an older version, or another install): point it at this one (review of ef43de4).
666
+ io.run('claude', ['mcp', 'remove', server, '--scope', 'user'], { timeoutMs: 20_000 });
667
+ }
668
+ const added = io.run('claude', add, { timeoutMs: 30_000 });
669
+ return added.status === 0
670
+ ? [`Claude Code: added the "${server}" tool for all your projects. Claude can now "ask Flop" (paid from this wallet's test FLOP); Claude Code asks you before each use.`]
671
+ : [`Claude Code: adding the tool failed (${(added.stderr || added.error || '').trim().slice(0, 200)}). Add it by hand with:`, line];
672
+ }
673
+
674
+ /**
675
+ * Whether `claude mcp get`'s answer describes the tool THIS install would add: the same Node (`Command:`), the same code
676
+ * (`Args:`) and the same FLOP_MCP_* environment. The real CLI prints all three and exits 0 even when that Node is gone
677
+ * ("Failed to connect"), so the code path alone said "already added" for a tool whose Node had been removed (review
678
+ * of 4ac7d10; output read from Claude Code 2.1.332, 28 Nov 2026).
679
+ * The whole Args line is compared (this code, `serve`, this network): a path with a space stays one path, and a tool
680
+ * pointed at the other network is not this one (review of c8a13bb).
681
+ * @param {string} text @param {string} nodePath @param {string} argsLine @param {Record<string, string>} env
682
+ */
683
+ export function sameTool(text, nodePath, argsLine, env) {
684
+ const lines = String(text).split('\n').map((line) => line.trim());
685
+ const command = lines.find((line) => line.startsWith('Command:'))?.slice('Command:'.length).trim();
686
+ const args = lines.find((line) => line.startsWith('Args:'))?.slice('Args:'.length).trim() ?? '';
687
+ const shown = lines.filter((line) => /^FLOP_MCP_[A-Z_]+=/.test(line)).sort();
688
+ const wanted = Object.entries(env).map(([k, v]) => `${k}=${v}`).sort();
689
+ return command === nodePath && args === argsLine && shown.length === wanted.length && shown.every((line, n) => line === wanted[n]);
690
+ }
691
+
692
+ /**
693
+ * Install the scheduler for this computer (SPEC.md "The scheduler") and start the first run now.
694
+ * @param {OuterIo} io @param {{ binPath: string, network: string, settings: { hour: number, minute: number }, suffix: string, logDir: string, startNow?: boolean, lockFile?: string }} o
695
+ * startNow: false when re-pointing an installed job (setup run again): no kickstart, though on a Mac launchd's
696
+ * RunAtLoad starts one run when the changed plist is loaded (it skips a day already done: daily.js isDue); lockFile: the daily run's lock —
697
+ * an installed job is never re-installed while a run holds it (on a Mac that would stop the run; review of 2b3a0ff)
698
+ * @returns {{ ok: true, kind: string, unchanged?: boolean, note?: string } | { ok: false, why: string, busy?: boolean }}
699
+ * note: a line for the human (a Linux timer without lingering stops at logout)
700
+ */
701
+ export function installScheduler(io, { binPath, network, settings, suffix, logDir, startNow = true, lockFile }) {
702
+ const env = passedEnv(io.env);
703
+ if (io.platform === 'win32' && Object.keys(env).length) return { ok: false, why: 'a non-default data folder cannot be scheduled on Windows' };
704
+ let systemd = io.platform === 'linux' ? io.run('systemctl', ['--user', 'show-environment'], { timeoutMs: 20_000, env: { XDG_RUNTIME_DIR: userRuntimeDir(io) } }).status === 0 : undefined;
705
+ /** @type {{ note?: string }} */
706
+ const extra = {};
707
+ if (systemd) {
708
+ // Without lingering a user timer runs only while the person is logged in (a server over SSH: never once they log
709
+ // out); cron runs regardless, so it is used instead when it is there (review of ef43de4). Without cron either, the
710
+ // timer it is, and the human is told how to keep it running (review of 6be8437).
711
+ const linger = io.run('loginctl', ['show-user', String(io.env.USER ?? ''), '-p', 'Linger'], { timeoutMs: 20_000 });
712
+ if (!/Linger=yes/.test(linger.stdout)) {
713
+ const cronThere = io.run('crontab', ['-l'], { timeoutMs: 20_000 });
714
+ if (cronThere.status === 0 || /no crontab/i.test(cronThere.stderr)) systemd = false;
715
+ else extra.note = 'Note: this timer runs only while you are logged in to this computer. To keep it running after you log out, run once: loginctl enable-linger (if that is refused: sudo loginctl enable-linger "$USER")';
716
+ }
717
+ }
718
+ const d = new Date(io.now());
719
+ const today = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
720
+ const plan = schedulerPlan({ platform: io.platform, uid: io.uid, home: io.home, nodePath: io.execPath, binPath, network, hour: settings.hour, minute: settings.minute, suffix, env, logDir, systemd, today, runtimeDir: userRuntimeDir(io) });
721
+ // Already installed exactly like this: nothing to do (and nothing running is stopped).
722
+ // The same files are not enough: the scheduler must also hold the job, running (a task deleted by hand on Windows, a
723
+ // timer disabled by hand, a launchd job booted out by hand would read "already on" forever: push-gate reviews of
724
+ // 3f55b81 and 96f7c8f).
725
+ const same = plan.cron
726
+ ? (() => { const c = io.run('crontab', ['-l'], { timeoutMs: 20_000 }); return c.status === 0 && c.stdout.split('\n').includes(plan.cron.line); })()
727
+ : plan.files.length > 0 && plan.files.every((f) => { try { return readFileSync(f.path, f.encoding ?? 'utf8') === f.content; } catch { return false; } }) && heldState(io, plan) !== 'no' && switchedOff(io, plan) !== 'off';
728
+ if (same) return { ok: true, kind: plan.kind, unchanged: true, ...extra };
729
+ // Installed by the scheduler's own answer too (a job launchd holds without its plist): never re-installed during a run.
730
+ const installed = jobInstalled(io, network, settings);
731
+ if (installed && lockFile && runInProgress(lockFile, io.now())) return { ok: false, busy: true, why: 'a daily run is going right now' };
732
+ // Linux: the other kind (systemd or cron) may hold an older job: remove both first, so only this one remains.
733
+ if (io.platform === 'linux') {
734
+ // Never two jobs: an older one that cannot be removed stops the install (push-gate review of 34fa6ee).
735
+ const left = removeScheduler(io, network, settings);
736
+ if (left.length) return { ok: false, why: `an earlier daily job could not be removed first (${left.join('; ')})` };
737
+ }
738
+ /** @type {string[]} */
739
+ const written = [];
740
+ try {
741
+ mkdirSync(logDir, { recursive: true, mode: 0o700 });
742
+ for (const file of plan.files) {
743
+ mkdirSync(dirname(file.path), { recursive: true });
744
+ writeFileSync(file.path, file.content, { encoding: file.encoding ?? 'utf8', mode: 0o600 });
745
+ written.push(file.path);
746
+ }
747
+ } catch (error) {
748
+ // Half-written: what this attempt wrote may not stay (a lone file confuses every later removal).
749
+ for (const path of written) rmSync(path, { force: true });
750
+ return { ok: false, why: `could not write ${plan.kind}'s file: ${/** @type {Error} */ (error).message}` };
751
+ }
752
+ if (plan.cron) {
753
+ const current = io.run('crontab', ['-l'], { timeoutMs: 20_000 });
754
+ // "no crontab for <user>" is an empty crontab; any other failure must never be read as one: writing would replace
755
+ // the person's whole crontab with this line (review, 27 Nov).
756
+ const empty = current.status !== 0 && /no crontab/i.test(current.stderr);
757
+ if (current.status !== 0 && !empty) return { ok: false, why: `crontab -l failed (${(current.stderr || current.error || '').trim().slice(0, 200)}), so the crontab was left alone` };
758
+ const written = io.run('crontab', ['-'], { input: editCrontab(empty ? '' : current.stdout, plan.cron.marker, plan.cron.line), timeoutMs: 20_000 });
759
+ if (written.status !== 0) return { ok: false, why: `crontab refused the line: ${(written.stderr || written.error || '').trim().slice(0, 200)}` };
760
+ // cron has no "start now": start the first run in the background ourselves.
761
+ if (startNow) io.detach(io.execPath, [binPath, 'daily', '--network', network]);
762
+ return { ok: true, kind: 'cron' };
763
+ }
764
+ for (const step of plan.install) {
765
+ const r = io.run(step.cmd, step.args, { timeoutMs: 60_000, env: step.env });
766
+ if (!(step.okCodes ?? [0]).includes(r.status ?? -1)) {
767
+ // Leave nothing behind that would start later on its own (a plist loads at the next login) while setup said "not installed".
768
+ for (const file of plan.removeFiles) rmSync(file, { force: true });
769
+ return { ok: false, why: `${step.cmd} ${step.args[0]} answered ${r.status}: ${(r.stderr || r.error || '').trim().slice(0, 200)}` };
770
+ }
771
+ }
772
+ if (startNow) for (const step of plan.startNow) io.run(step.cmd, step.args, { timeoutMs: 60_000, env: step.env });
773
+ return { ok: true, kind: plan.kind, ...extra };
774
+ }
775
+
776
+ /**
777
+ * tryflop daily: what the scheduler starts. Runs the inner daily-run (sandboxed on macOS), then shows each new human
778
+ * moment as a notification. Nothing else is ever shown.
779
+ * @param {string[]} args @param {OuterIo} io @returns {Promise<number>}
780
+ */
781
+ export async function runDaily(args, io) {
782
+ let values;
783
+ try {
784
+ ({ values } = parseArgs({ args, options: { network: { type: 'string', default: 'testnet' }, force: { type: 'boolean', default: false }, 'no-claim': { type: 'boolean', default: false } }, strict: true, allowPositionals: false }));
785
+ } catch (error) {
786
+ io.err.write(`tryflop: ${/** @type {Error} */ (error).message}\n`);
787
+ return 2;
788
+ }
789
+ // Checked here too: the network names a file in ~/.tryflop/logs (silent days), so "../x" must never reach it (review of 6be8437).
790
+ if (!NETWORK_NAMES.has(String(values.network))) {
791
+ io.err.write('tryflop: --network is testnet (or devnet for testing).\n');
792
+ return 2;
793
+ }
794
+ const binPath = join(APP_DIR, 'bin', 'tryflop.mjs');
795
+ const r = runInner(io, binPath, ['daily-run', '--network', String(values.network), ...(values.force ? ['--force'] : []), ...(values['no-claim'] ? ['--no-claim'] : [])], 3 * 3_600_000);
796
+ if (r.stderr) io.err.write(fromSandbox(r.stderr));
797
+ let report;
798
+ try {
799
+ report = JSON.parse(r.stdout.trim().split('\n').pop() ?? '');
800
+ } catch {
801
+ report = null;
802
+ }
803
+ if (!report || typeof report !== 'object') {
804
+ io.err.write(`tryflop: the daily run ended without a report (exit ${r.status}${r.error ? `, ${fromSandbox(r.error, 200)}` : ''}).\n`);
805
+ noteSilentDay(io, true, String(values.network));
806
+ return 1;
807
+ }
808
+ noteSilentDay(io, false, String(values.network));
809
+ const shown = trustedReport(report, io.platform);
810
+ for (const text of shown.notes) {
811
+ const command = notifyCommand(io.platform, text);
812
+ if (command) io.run(command.cmd, command.args, { env: command.env, timeoutMs: 30_000 });
813
+ }
814
+ io.out.write(`${shown.line ? `${shown.line}\n` : ''}Daily run: ${shown.summary}\n`);
815
+ return r.status ?? 1;
816
+ }
817
+
818
+ /**
819
+ * A run that started but gave no report (the sandbox refused to start, a folder replaced by a link, a crash) writes no
820
+ * status either: count such days outside the sandbox; three IN A ROW notify the person once per streak, and any report
821
+ * clears it (reviews, 27 Nov). A Node removed after setup starts nothing at all, so it cannot be counted here.
822
+ * @param {OuterIo} io @param {boolean} silent true when this run gave no report @param {string} [network]
823
+ */
824
+ export function noteSilentDay(io, silent, network = 'testnet') {
825
+ // One count per network: a devnet report must not clear testnet's (review of ef43de4).
826
+ const file = join(logsRoot(io.env), network === 'testnet' ? 'silent-days.json' : `silent-days-${network}.json`);
827
+ if (!silent) {
828
+ rmSync(file, { force: true });
829
+ return;
830
+ }
831
+ const dayOf = (/** @type {number} */ ms) => { const d = new Date(ms); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
832
+ const today = dayOf(io.now());
833
+ let saved = { days: /** @type {string[]} */ ([]), shown: '' };
834
+ try {
835
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
836
+ if (parsed && Array.isArray(parsed.days)) saved = { days: parsed.days.filter((x) => typeof x === 'string' && /^\d{4}-\d\d-\d\d$/.test(x)), shown: typeof parsed.shown === 'string' ? parsed.shown : '' };
837
+ } catch { /* none yet */ }
838
+ if (!saved.days.includes(today)) saved.days.push(today);
839
+ saved.days = saved.days.slice(-3);
840
+ const inARow = saved.days.length === 3 && [1, 2].every((i) => dayOf(Date.parse(`${saved.days[i - 1]}T12:00:00`) + 86_400_000) === saved.days[i]);
841
+ const notify = inARow && saved.days[2] === today && !saved.shown;
842
+ if (notify) saved.shown = today;
843
+ try {
844
+ mkdirSync(logsRoot(io.env), { recursive: true, mode: 0o700 });
845
+ writeFileSync(file, JSON.stringify(saved));
846
+ } catch { /* best effort */ }
847
+ if (notify) {
848
+ const command = notifyCommand(io.platform, forPlatform(MOMENT_TEXT.needs_you, io.platform));
849
+ if (command) io.run(command.cmd, command.args, { env: command.env, timeoutMs: 30_000 });
850
+ }
851
+ }
852
+
853
+ /**
854
+ * tryflop uninstall: the scheduler, Claude Code's tool and the copied code go; the wallet NEVER does (it may hold FLOP,
855
+ * and its words are the only way back to it).
856
+ * @param {string[]} args @param {OuterIo} io @returns {Promise<number>}
857
+ */
858
+ export async function runUninstall(args, io) {
859
+ let values;
860
+ try {
861
+ ({ values } = parseArgs({ args, options: { network: { type: 'string', default: 'testnet' } }, strict: true, allowPositionals: false }));
862
+ } catch (error) {
863
+ io.err.write(`tryflop: ${/** @type {Error} */ (error).message}\n`);
864
+ return 2;
865
+ }
866
+ const network = String(values.network);
867
+ if (!NETWORK_NAMES.has(network)) {
868
+ io.err.write('tryflop: --network is testnet (or devnet for testing).\n');
869
+ return 2;
870
+ }
871
+ const home = walletHome(homeRoot(io.env), /** @type {'testnet'|'devnet'} */ (network));
872
+ const settings = readAgentSettings(home.tryflopFile);
873
+ const lines = [];
874
+ const problems = removeScheduler(io, network, settings);
875
+ lines.push(problems.length ? `The daily run could NOT be fully removed: ${problems.join('; ')}.` : 'The daily run is removed.');
876
+ // The sandboxed child saves it; when it cannot start (Homebrew's Node, which only setup checks for), every other step
877
+ // still runs and this is reported. A later plain setup finds no job and asks again instead (review of 6be8437).
878
+ let unsaved = '';
879
+ // Only a record that says on needs changing: an uninstall run twice, or with the daily run never on, has nothing to
880
+ // save and must not warn (push-gate review of 34fa6ee).
881
+ if (settings?.daily === 'on') {
882
+ try {
883
+ saveSettings(io, join(APP_DIR, 'bin', 'tryflop.mjs'), network, { ...settings, daily: 'off' });
884
+ } catch (error) {
885
+ unsaved = /** @type {Error} */ (error).message;
886
+ }
887
+ }
888
+ const server = claudeServerName(io, network);
889
+ const got = io.run('claude', ['mcp', 'get', server], { timeoutMs: 20_000 });
890
+ if (got.status === 0) {
891
+ io.run('claude', ['mcp', 'remove', server, '--scope', 'user'], { timeoutMs: 20_000 });
892
+ lines.push(`Claude Code's "${server}" tool is removed.`);
893
+ } else if (got.error && io.platform === 'win32') {
894
+ lines.push(`Claude Code could not be started from here; if you use it, remove the tool with: claude mcp remove ${server} --scope user`);
895
+ }
896
+ // The copied code, the launcher and the logs are shared by both networks: kept only while the other one still RUNS
897
+ // from them (its daily job is on, or its Claude tool is added); a wallet alone needs no code (review of ef43de4).
898
+ const other = network === 'testnet' ? 'devnet' : 'testnet';
899
+ const otherSettings = readAgentSettings(walletHome(homeRoot(io.env), other).tryflopFile);
900
+ const otherTool = io.run('claude', ['mcp', 'get', claudeServerName(io, other)], { timeoutMs: 20_000 }).status === 0;
901
+ if (otherSettings?.daily === 'on' || otherTool) {
902
+ lines.push(`The copied code and the launcher stay: this computer's ${other} ${otherSettings?.daily === 'on' ? 'daily run' : 'Claude tool'} still uses them (uninstall --network ${other} removes them).`);
903
+ } else {
904
+ // Only Try Flop's own entries, then each folder if nothing else is in it: a test's folder may sit beside other things
905
+ // (push-gate review of 96f7c8f).
906
+ const apps = appRoot(io.env);
907
+ const had = existsSync(apps);
908
+ removeOwn(apps, (name, path) => existsSync(join(path, '.complete')) || /\.tmp-\d+$/.test(name));
909
+ if (had && !existsSync(apps)) lines.push(`The copied code (${apps}) is removed.`);
910
+ removeOwn(logsRoot(io.env), (name) => /^(?:scheduler\.log|silent-days(?:-[a-z]+)?\.json|tryflop-task(?:-[a-z0-9-]+)?\.xml)$/.test(name));
911
+ removeOwn(launcherDir(io.env), (name) => name === 'tryflop' || name === 'tryflop.cmd');
912
+ }
913
+ if (unsaved) lines.push(`Try Flop's settings could not be updated (${unsaved}): they still say the daily run is on. Its job is ${problems.length ? 'NOT fully removed (above)' : 'removed'}, so a later setup asks your human again instead of turning it back on.`);
914
+ lines.push(
915
+ '',
916
+ `The wallet was NOT removed: ${home.dir}. It may still hold test FLOP, and its 12 words are the only way back to it.`,
917
+ `To use it on another computer, run "npx -y tryflop@${VERSION} restore${network !== 'testnet' ? ` --network ${network}` : ''}" there yourself and type the words (one wallet per person).`,
918
+ `To delete it for good, first save the words (run "npx -y tryflop@${VERSION} backup${network !== 'testnet' ? ` --network ${network}` : ''}" yourself, in your own terminal), then delete that folder. ${payersRoot(io.env)} holds only payment locks.`,
919
+ );
920
+ io.out.write(`${lines.join('\n')}\n`);
921
+ // Something was left to do by hand: say so to an agent too.
922
+ return unsaved || problems.length ? 1 : 0;
923
+ }
924
+
925
+ export const HELP = `tryflop ${VERSION} — Try Flop for AI agents: the agent's own Flop wallet claims Flop's free test FLOP and pays real
926
+ miners for AI answers, every day. An independent tool, not made by Flop Labs. https://tryflop.com/agent.md
927
+
928
+ tryflop setup [--daily on|off] [--topic "<subject>"] make the wallet (one per person), add Claude Code's tool, and
929
+ with the human's yes, the daily run
930
+ tryflop status where things stand (the wallet, the last paid answer, scoring)
931
+ tryflop daily [--force] [--no-claim] one daily run now (the scheduler starts this); --no-claim when
932
+ the wallet got its FLOP elsewhere: the faucet is not asked
933
+ tryflop claim ask Flop's testnet faucet for this wallet's free FLOP (once a day)
934
+ tryflop backup FOR THE HUMAN, in their own terminal: show the 12 recovery words
935
+ tryflop restore FOR THE HUMAN, in their own terminal: bring a wallet to this computer
936
+ tryflop uninstall remove the daily run and Claude's tool (never the wallet)
937
+ tryflop serve the MCP server (Claude Code starts it)
938
+
939
+ Every command takes --network testnet (the default) or devnet. AI agents: never run backup or restore, never read the
940
+ wallet's files, never make a second wallet or move FLOP between wallets, never re-send a payment whose outcome is unknown
941
+ (run "tryflop status"), and pass any error on word for word.
942
+ macOS runs Flop's code inside its own sandbox. ${UNSANDBOXED_NOTICE}`;
943
+
944
+ /**
945
+ * Run one outer command.
946
+ * @param {string[]} argv @param {Partial<OuterIo>} [io] @returns {Promise<number>}
947
+ */
948
+ export async function mainOuter(argv, io = {}) {
949
+ /** @type {OuterIo} */
950
+ const full = {
951
+ out: process.stdout, err: process.stderr, env: process.env, platform: process.platform, execPath: process.execPath,
952
+ uid: typeof process.getuid === 'function' ? process.getuid() : 0, home: homedir(), now: () => Date.now(), run: realRun, detach: realDetach, ...io,
953
+ };
954
+ const [command, ...rest] = argv;
955
+ const problem = command === 'setup' || command === 'daily' || command === 'uninstall' ? dataFolderProblem(full.env) : null;
956
+ if (problem) {
957
+ full.err.write(`tryflop: ${problem}\n`);
958
+ return 2;
959
+ }
960
+ if (command === 'setup') return runSetup(rest, full);
961
+ if (command === 'daily') return runDaily(rest, full);
962
+ if (command === 'uninstall') return runUninstall(rest, full);
963
+ if (command === 'version' || command === '--version') {
964
+ full.out.write(`${VERSION}\n`);
965
+ return 0;
966
+ }
967
+ full.out.write(`${HELP}\n`);
968
+ return command === undefined || command === 'help' || command === '--help' || command === '-h' ? 0 : 2;
969
+ }