tryflop 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/daily.js ADDED
@@ -0,0 +1,363 @@
1
+ // `tryflop daily` (SPEC.md "tryflop daily"): what the scheduler starts every day. This file is the INNER run's rules,
2
+ // SDK-free: src/tryflop.js wires the payer (src/payer.js, own wallet), the chain, the faucet claim (src/claim.js) and the
3
+ // scoring check (src/scoring.js) in as stand-in-able functions, so tests drive every edge without the network.
4
+ // The money rules are the payer's: nothing is ever re-sent, the chain decides an unknown outcome, every purchase is
5
+ // checked at the purchase itself (the run's channel cap and budget, the wallet's balance), and a daily run moves to the
6
+ // next miner only when nothing was bought for the question.
7
+ import { closeSync, openSync, readFileSync, unlinkSync, writeSync } from 'node:fs';
8
+ import { writePrivateFile } from './home.js';
9
+ import { dailyQuestions } from './questions.js';
10
+ import { formatFlop, PLANCK_PER_FLOP } from './shared/units.js';
11
+
12
+ const HOUR_MS = 3_600_000;
13
+ const DAY_MS = 24 * HOUR_MS;
14
+ /** A lock older than this belongs to a run that died without removing it (a run takes well under an hour). */
15
+ const STALE_LOCK_MS = 3 * HOUR_MS;
16
+ /** What the run never locks in a channel: the wallet's own network fees (payer.js WALLET_FEE_RESERVE_PLANCK). */
17
+ const FEE_RESERVE = PLANCK_PER_FLOP / 20n;
18
+
19
+ /** Mode caps (SPEC.md): channels per run and questions per channel. */
20
+ export const MODES = Object.freeze({
21
+ /** Before scoring: the least spend that keeps the faucet flowing (one settled paid channel), one short question. */
22
+ NOT_STARTED: Object.freeze({ maxChannels: 1, questionsPerChannel: 1, maxTokens: 300 }),
23
+ /** Scoring on (or the faucet asks for the last grant to be spent first): the day's grant, on real questions. */
24
+ ON: Object.freeze({ maxChannels: 8, questionsPerChannel: 4, maxTokens: 500 }),
25
+ });
26
+
27
+ /** Payer refusals and failures that bought nothing for THIS question and say nothing about other miners. */
28
+ /** Refusals that mean "this miner's deposit is more than the run's budget or the wallet holds": a cheaper one may fit. */
29
+ const DEPOSIT_TOO_BIG = new Set(['budget', 'per_run', 'wallet_balance']);
30
+ const NEXT_MINER = new Set(['no_miner', 'open_failed', 'miner_rejected', 'turn_refused', 'price_ceiling', 'not_sent', 'allowance', 'too_large', 'stale_head', 'busy']);
31
+
32
+ /**
33
+ * @typedef {{ lastCompletedDay?: string, lastRunAt?: number, lastResult?: string, lastPaidAnswer?: { at: number, miner: string,
34
+ * channel: string, settled: string }, scoring?: { state: string, activationBlock: number | null, checkedAt: number, why: string },
35
+ * rolloverNeeded?: boolean, failedDays?: number, lastFailedDay?: string, history?: Array<{ day: string, answers: number, spentPlanck: string }>,
36
+ * nextClaimAt?: number, askedDay?: string, askedCount?: number }} DailyState
37
+ * askedDay/askedCount: how many of the day's questions already went out (answered, unknown, or failed after a purchase),
38
+ * so a later run the same day starts after them and never sends one again (review of ef43de4)
39
+ * nextClaimAt: when the faucet's 24 h from the last claim end. The scheduler fires at the same minute each day and a claim
40
+ * is stamped seconds after it, so the next day's first trigger often lands just inside the window: a later trigger the
41
+ * day's run waits for it (CLAIM_WAIT_MS) and any later trigger claims on its own (claimDue; push-gate reviews, 27 Nov:
42
+ * without both, the daily run claimed every other day)
43
+ */
44
+
45
+ /** @param {string} file @returns {DailyState} */
46
+ export function readDailyState(file) {
47
+ try {
48
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
49
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
50
+ } catch {
51
+ return {};
52
+ }
53
+ }
54
+
55
+ /** @param {string} file @param {DailyState} state */
56
+ export const writeDailyState = (file, state) => writePrivateFile(file, `${JSON.stringify(state, null, 2)}\n`);
57
+
58
+ /** The local calendar day of `ms`, as YYYY-MM-DD (the scheduler's day). @param {number} ms */
59
+ export function localDay(ms) {
60
+ const d = new Date(ms);
61
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
62
+ }
63
+
64
+ /** Days since 1970 in local time (the question rotation). @param {number} ms */
65
+ export const localDayNumber = (ms) => {
66
+ const d = new Date(ms);
67
+ return Math.floor(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) / DAY_MS);
68
+ };
69
+
70
+ /**
71
+ * Is a run due? Not when today's run already completed. Otherwise yes once the chosen time of day has come, or at once
72
+ * when a whole day was missed (a computer that slept through it).
73
+ * @param {{ now: number, state: DailyState, hour: number, minute: number }} o
74
+ */
75
+ export function isDue({ now, state, hour, minute }) {
76
+ const today = localDay(now);
77
+ if (state.lastCompletedDay === today) return false;
78
+ const d = new Date(now);
79
+ if (d.getHours() * 60 + d.getMinutes() >= hour * 60 + minute) return true;
80
+ const yesterday = localDay(now - DAY_MS);
81
+ return !state.lastCompletedDay || state.lastCompletedDay < yesterday;
82
+ }
83
+
84
+ /** A day's run whose claim is due within this long waits for it, under its lock, and claims in the same run. */
85
+ export const CLAIM_WAIT_MS = 30 * 60_000;
86
+
87
+ /**
88
+ * Should a trigger that runs no full pass (its day is done, or its time has not come) still claim? Yes once the faucet's
89
+ * next possible claim is at most CLAIM_WAIT_MS away, on any day (claimWithWait then waits for it): a claim stamped
90
+ * seconds after a trigger is never pushed to a later trigger, nor a day (push-gate reviews 2 and 3, 27 Nov).
91
+ * @param {{ now: number, state: DailyState }} o
92
+ */
93
+ export function claimDue({ now, state }) {
94
+ return Number.isSafeInteger(state.nextClaimAt) && now + CLAIM_WAIT_MS >= /** @type {number} */ (state.nextClaimAt);
95
+ }
96
+
97
+ /**
98
+ * Claim; when the faucet's next possible claim (the 24 h from the last grant, or its own retry time) is at most
99
+ * CLAIM_WAIT_MS away, wait for it ONCE and claim again. Each call goes through claim.js's decision, which reads claim.json
100
+ * afresh: it never sends inside the faucet's window and never re-sends a claim whose outcome is unknown.
101
+ * @param {{ claim: () => Promise<{ outcome: string, reason?: string, nextClaimAt?: number }>, now: () => number,
102
+ * sleep?: (ms: number) => Promise<unknown>, log: (line: string) => void }} o
103
+ */
104
+ export async function claimWithWait({ claim, now, sleep, log }) {
105
+ const first = await claim();
106
+ const next = first.nextClaimAt;
107
+ const waitable = first.outcome === 'granted_earlier' || first.outcome === 'refused_earlier' || first.outcome === 'refused';
108
+ if (!sleep || !waitable || !Number.isSafeInteger(next) || /** @type {number} */ (next) - now() > CLAIM_WAIT_MS) return first;
109
+ const ms = Math.max(0, /** @type {number} */ (next) - now()) + 5_000;
110
+ log(`Flop's faucet can be asked again at ${new Date(/** @type {number} */ (next)).toISOString()}: waiting ${Math.ceil(ms / 1000)} s to claim in this run`);
111
+ await sleep(ms);
112
+ return claim();
113
+ }
114
+
115
+ /**
116
+ * One daily run at a time: an exclusive lock file holding this process's id. A lock whose process is gone, or that is
117
+ * older than 3 hours, is taken over.
118
+ * @param {string} file @param {{ now: number, pid: number, isAlive: (pid: number) => boolean }} o
119
+ * @returns {(() => void) | null} the release, or null when another live run holds it
120
+ */
121
+ export function takeLock(file, { now, pid, isAlive }) {
122
+ for (let attempt = 0; attempt < 2; attempt += 1) {
123
+ try {
124
+ const fd = openSync(file, 'wx', 0o600);
125
+ writeSync(fd, JSON.stringify({ pid, at: now }));
126
+ closeSync(fd);
127
+ return () => { try { unlinkSync(file); } catch { /* already gone */ } };
128
+ } catch (error) {
129
+ if (/** @type {any} */ (error).code !== 'EEXIST') throw error;
130
+ let held;
131
+ try {
132
+ held = JSON.parse(readFileSync(file, 'utf8'));
133
+ } catch {
134
+ held = null;
135
+ }
136
+ const alive = held && Number.isInteger(held.pid) && held.pid !== pid && isAlive(held.pid) && now - Number(held.at) < STALE_LOCK_MS;
137
+ if (alive) return null;
138
+ try { unlinkSync(file); } catch { /* raced: try again */ }
139
+ }
140
+ }
141
+ return null;
142
+ }
143
+
144
+ /**
145
+ * @typedef {{ question: string, status: string, reason?: string, miner?: string, channel?: string, answer?: string,
146
+ * paidPlanck?: bigint, requestId?: string }} AskedQuestion
147
+ * @typedef {{ status: 'done'|'partial'|'skipped'|'failed', reason: string, mode?: 'ON'|'NOT_STARTED', scoringWhy?: string,
148
+ * claim?: { outcome: string, reason?: string }, asked: AskedQuestion[], settled?: { status: string, channel?: string, message: string }[],
149
+ * balancePlanck?: bigint, spentPlanck: bigint }} DailyResult
150
+ */
151
+
152
+ /**
153
+ * The run itself (after the lock and the due check: src/tryflop.js holds those). Every dependency is injected.
154
+ * @param {{
155
+ * now: () => number,
156
+ * topic: string,
157
+ * miners: readonly { id: string, model: string }[],
158
+ * grantPlanck: bigint,
159
+ * state: DailyState,
160
+ * connect: () => Promise<void>,
161
+ * reconcile: () => Promise<{ frozen: boolean }>,
162
+ * finalizedNumber: () => Promise<bigint>,
163
+ * balance: () => Promise<bigint>,
164
+ * scoring: (ourFinalized: bigint | null) => Promise<{ mode: 'ON'|'NOT_STARTED', state: string, activationBlock: number | null, why: string }>,
165
+ * claim: () => Promise<{ outcome: string, reason?: string, nextClaimAt?: number }>,
166
+ * sleep?: (ms: number) => Promise<unknown>,
167
+ * makePayer: (run: { maxChannels: number, budgetPlanck: bigint }) => { ask: (input: any) => Promise<any>, settle: () => Promise<any> },
168
+ * save?: (state: DailyState) => void,
169
+ * log: (line: string) => void,
170
+ * }} deps
171
+ * @returns {Promise<DailyResult>}
172
+ */
173
+ export async function runDailyPass(deps) {
174
+ const { now, topic, miners, grantPlanck, state, log } = deps;
175
+ /** @type {DailyResult} */
176
+ const result = { status: 'failed', reason: '', asked: [], spentPlanck: 0n };
177
+ try {
178
+ await deps.connect();
179
+ } catch (error) {
180
+ result.reason = `Flop's network could not be reached (${brief(error)}).`;
181
+ return result;
182
+ }
183
+ let frozen = false;
184
+ try {
185
+ ({ frozen } = await deps.reconcile());
186
+ } catch (error) {
187
+ log(`reconcile: ${brief(error)}`);
188
+ }
189
+ let finalized = null;
190
+ try {
191
+ finalized = await deps.finalizedNumber();
192
+ } catch (error) {
193
+ log(`finalized head: ${brief(error)}`);
194
+ }
195
+ const scoring = await deps.scoring(finalized);
196
+ result.mode = scoring.mode;
197
+ result.scoringWhy = scoring.why;
198
+ state.scoring = { state: scoring.state, activationBlock: scoring.activationBlock, checkedAt: now(), why: scoring.why };
199
+
200
+ // CLAIM: Flop's faucet, for this wallet, under the claim diagram's rules (never twice within a day, never re-sent).
201
+ let claim;
202
+ try {
203
+ // The scheduler fires at the same minute every day and a claim is stamped seconds after it, so today's window often
204
+ // ends moments after this run starts: wait for it here instead of skipping a day's grant.
205
+ claim = await claimWithWait({ claim: deps.claim, now, sleep: deps.sleep, log });
206
+ } catch (error) {
207
+ claim = { outcome: 'error', reason: brief(error) };
208
+ }
209
+ result.claim = claim;
210
+ // A claim not asked for (`daily --no-claim`: the FLOP came from elsewhere) changes nothing the faucet decides.
211
+ if (claim.outcome !== 'skipped') state.nextClaimAt = Number.isSafeInteger(/** @type {any} */ (claim).nextClaimAt) ? /** @type {any} */ (claim).nextClaimAt : undefined;
212
+ if (claim.outcome === 'granted_now' || claim.outcome === 'granted_earlier') state.rolloverNeeded = false;
213
+ // Flop's faucet names it `agent_spend_missing` ("the next grant needs a finalized spend of the last one", flop.network
214
+ // /llms.txt, read 27 Nov 2026); any reason naming a rollover counts too.
215
+ if ((claim.outcome === 'refused' || claim.outcome === 'refused_earlier') && /agent_spend_missing|rollover/i.test(claim.reason ?? '')) state.rolloverNeeded = true;
216
+
217
+ if (frozen) {
218
+ result.status = 'partial';
219
+ result.reason = 'A payment is still being confirmed on Flop\'s chain, so nothing new was bought this time.';
220
+ return result;
221
+ }
222
+ let balance;
223
+ try {
224
+ balance = await deps.balance();
225
+ } catch (error) {
226
+ result.reason = `The wallet's balance could not be read (${brief(error)}).`;
227
+ return result;
228
+ }
229
+ result.balancePlanck = balance;
230
+ // The mode's caps. Before scoring, one channel keeps the faucet flowing; if the faucet asked for the last grant to be
231
+ // spent first (rollover), the day's grant is spent like in ON (it earns nothing until scoring starts: status says so).
232
+ const spendAll = scoring.mode === 'ON' || state.rolloverNeeded === true;
233
+ const mode = spendAll ? MODES.ON : MODES.NOT_STARTED;
234
+ const usable = balance - FEE_RESERVE;
235
+ const budget = spendAll ? (usable < grantPlanck ? usable : grantPlanck) : (usable < 2n * PLANCK_PER_FLOP ? usable : 2n * PLANCK_PER_FLOP);
236
+ if (budget < PLANCK_PER_FLOP / 2n) {
237
+ // Done for today only when no more FLOP can come today (the faucet refused, or already gave today's grant); a
238
+ // faucet that was not serving, an unreadable chain or a claim still on its way is retried 6 and 12 hours later
239
+ // (review, 27 Nov: the faucet sat at its floor for all of 26 Nov).
240
+ const busy = claim.reason === 'faucet_busy'; // the faucet asked for a retry later today (claim.js BUSY_RETRY_MS)
241
+ const settledForToday = !busy && ['refused', 'refused_earlier', 'granted_earlier', 'granted_now'].includes(claim.outcome);
242
+ result.status = settledForToday ? 'done' : 'partial';
243
+ const why = claim.outcome === 'held' || claim.outcome === 'not_arrived' ? ' (a faucet claim is still on its way)'
244
+ : claim.outcome === 'skipped' ? ' (the faucet was not asked: --no-claim)'
245
+ : settledForToday ? '' : ' (the faucet could not be asked; a later run tries again)';
246
+ result.reason = `The wallet holds ${formatFlop(balance)} FLOP: too little to buy an answer yet${why}.`;
247
+ return result;
248
+ }
249
+
250
+ const payer = deps.makePayer({ maxChannels: mode.maxChannels, budgetPlanck: budget });
251
+ // The day's questions after those an earlier run already sent today: none is ever sent twice.
252
+ const day = localDay(now());
253
+ const already = state.askedDay === day && Number.isSafeInteger(state.askedCount) ? /** @type {number} */ (state.askedCount) : 0;
254
+ const questions = dailyQuestions(topic, localDayNumber(now()), already + mode.maxChannels * mode.questionsPerChannel).slice(already);
255
+ // After the run: questions answered, plus the one an unknown or failed-after-purchase turn used; a question refused
256
+ // before anything was sent (no miner, the caps) is not counted, so the next run asks it.
257
+ const consumed = () => { state.askedDay = day; state.askedCount = already + q + (stop === 'unknown' || stop === 'failed' ? 1 : 0); };
258
+ /** @type {{ status: string, channel?: string, message: string }[]} */
259
+ const settled = [];
260
+ let stop = '';
261
+ let stopReason = '';
262
+ let q = 0;
263
+ let minerIndex = 0;
264
+ for (let channel = 0; channel < mode.maxChannels && !stop && q < questions.length; channel += 1) {
265
+ let answeredHere = 0;
266
+ for (let i = 0; i < mode.questionsPerChannel && q < questions.length; i += 1) {
267
+ const question = questions[q];
268
+ let answered = false;
269
+ // Recorded as sent before it can be: a run stopped while this question is out (a re-install, a crash) never sends
270
+ // it again; a question that then turns out never to have left is only skipped (review of 2b3a0ff).
271
+ state.askedDay = day;
272
+ state.askedCount = already + q + 1;
273
+ deps.save?.(state);
274
+ // Next miner only when nothing was bought for this question, and only before this channel served anything.
275
+ while (!answered && minerIndex < miners.length) {
276
+ const miner = miners[minerIndex];
277
+ const r = await payer.ask({ prompt: question, maxTokens: mode.maxTokens, miner: miner.id });
278
+ /** @type {AskedQuestion} */
279
+ const entry = { question, status: r.status, reason: r.reason, miner: r.miner ?? miner.id, channel: r.channel, requestId: r.requestId, paidPlanck: r.paidPlanck ?? 0n };
280
+ if (r.status === 'answered') entry.answer = r.answer;
281
+ result.asked.push(entry);
282
+ result.spentPlanck += r.paidPlanck ?? 0n;
283
+ if (r.status === 'answered') {
284
+ answered = true;
285
+ answeredHere += 1;
286
+ log(`answered by ${entry.miner} on channel ${entry.channel} (request ${r.requestId}${(r.paidPlanck ?? 0n) > 0n ? `, bought the channel for ${formatFlop(r.paidPlanck)} FLOP` : ''})`);
287
+ continue;
288
+ }
289
+ // The payer's own words (fixed texts and its own checks' reasons; never a miner's raw text).
290
+ log(`${miner.id}: ${r.status} (${r.reason}): ${String(r.message ?? '').replace(/\s+/g, ' ').slice(0, 400)}`);
291
+ const boughtNothing = (r.paidPlanck ?? 0n) === 0n;
292
+ // This miner's deposit does not fit what is left (the run's budget, the wallet) and nothing was bought this run
293
+ // yet: a cheaper miner may fit, so it sits out (28 Nov: antju2 asks 1.73 FLOP, ecamli-testnet 0.945).
294
+ if (boughtNothing && answeredHere === 0 && result.spentPlanck === 0n && DEPOSIT_TOO_BIG.has(String(r.reason)) && minerIndex + 1 < miners.length) { minerIndex += 1; continue; }
295
+ if (r.reason === 'per_run' || r.reason === 'per_day' || r.reason === 'no_flop' || r.reason === 'wallet_balance' || r.reason === 'budget') { stop = 'cap'; stopReason = String(r.reason); break; }
296
+ if (boughtNothing && answeredHere === 0 && NEXT_MINER.has(String(r.reason))) { minerIndex += 1; continue; }
297
+ // Unknown, or failed after a purchase: never re-sent; the chain decides. Stop spending this run.
298
+ stop = r.status === 'unknown' ? 'unknown' : 'failed';
299
+ break;
300
+ }
301
+ if (!answered) { if (!stop) stop = 'no_miner'; break; }
302
+ q += 1;
303
+ }
304
+ if (answeredHere > 0 || stop) {
305
+ try {
306
+ settled.push(await payer.settle());
307
+ } catch (error) {
308
+ settled.push({ status: 'unknown', message: brief(error) });
309
+ }
310
+ }
311
+ }
312
+ result.settled = settled;
313
+ consumed();
314
+ const answers = result.asked.filter((a) => a.status === 'answered').length;
315
+ if (answers > 0) {
316
+ const last = [...result.asked].reverse().find((a) => a.status === 'answered');
317
+ const settle = [...settled].reverse().find((s) => s.channel === last?.channel);
318
+ state.lastPaidAnswer = { at: now(), miner: String(last?.miner), channel: String(last?.channel), settled: settle?.status ?? 'unknown' };
319
+ }
320
+ if (stop === 'unknown') {
321
+ result.status = 'partial';
322
+ result.reason = 'An answer\'s outcome is not confirmed yet; it is never re-sent. Flop\'s chain decides, and the next run checks.';
323
+ } else if (answers === 0) {
324
+ result.status = 'partial';
325
+ result.reason = stop === 'no_miner' ? 'No listed miner could take a question right now; nothing was bought. The next run tries again.' : 'No question was answered this time.';
326
+ } else if (spendAll && DAY_LIMIT_REASONS.has(stopReason) && channelsOf(result.asked) < mode.maxChannels && budget - result.spentPlanck >= oneChannel(result.asked)) {
327
+ // ON, stopped by a spending cap although this run's own budget could still pay one more channel and it had channels
328
+ // left: the rolling 24 h limit (Claude's own asks share it) was full, and a later trigger spends the rest once it
329
+ // frees. A run stopped by its own budget is done: the next trigger would buy nothing, and the day would never end
330
+ // (review of 6be8437). The reasons alone cannot tell the two apart (the SDK's `budget` and the guard's `per_run` both
331
+ // stand for the smaller of the run's budget and the day's limit). Claude's asks during the run count against the
332
+ // run in the payer (its ledger since the run began) but not in `spentPlanck`: that case is partial too, on purpose,
333
+ // since they used the shared day's limit, and the later triggers try again once it frees (at most two more a day).
334
+ result.status = 'partial';
335
+ result.reason = `${answers} paid answer${answers === 1 ? '' : 's'}; the day's cap stopped the rest for now.`;
336
+ } else {
337
+ result.status = 'done';
338
+ result.reason = `${answers} paid answer${answers === 1 ? '' : 's'}.`;
339
+ }
340
+ return result;
341
+ }
342
+
343
+ /** The payer's refusals that can mean the rolling 24 h limit (shared with Claude's asks) is full. */
344
+ const DAY_LIMIT_REASONS = new Set(['per_day', 'budget', 'per_run']);
345
+
346
+ /** The channels this run used. @param {{ channel?: string }[]} asked */
347
+ const channelsOf = (asked) => new Set(asked.filter((a) => a.channel).map((a) => a.channel)).size;
348
+
349
+ /**
350
+ * What one more channel costs, as this run saw it: the largest single payment it made (a channel's escrow), and never
351
+ * less than the payer's own floor for a purchase (0.5 FLOP).
352
+ * @param {{ paidPlanck?: bigint }[]} asked
353
+ */
354
+ function oneChannel(asked) {
355
+ let most = PLANCK_PER_FLOP / 2n;
356
+ for (const a of asked) if ((a.paidPlanck ?? 0n) > most) most = /** @type {bigint} */ (a.paidPlanck);
357
+ return most;
358
+ }
359
+
360
+ /** @param {unknown} error */
361
+ function brief(error) {
362
+ return String(/** @type {any} */ (error)?.message ?? error).replace(/\s+/g, ' ').slice(0, 200);
363
+ }
package/src/files.js ADDED
@@ -0,0 +1,104 @@
1
+ // Private files and folders, like ~/.ssh: folders 0700, files 0600, no symbolic links, atomic writes. Node built-ins
2
+ // only, so the tryflop commands that run OUTSIDE the sandbox (setup, the scheduler's daily wrapper, uninstall) can use
3
+ // them without loading any third-party code (src/home.js re-exports them for the rest).
4
+ import { closeSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from 'node:fs';
5
+ import { randomBytes } from 'node:crypto';
6
+ import { dirname } from 'node:path';
7
+
8
+
9
+ /**
10
+ * Windows has no POSIX permission bits: Node reports group and other as copies of the owner's (files 0o666, folders
11
+ * 0o777), so a mode check would refuse every file there (review, 27 Nov). A Windows user profile's folders are
12
+ * private to that user by its own access lists; the mode checks apply on macOS and Linux only.
13
+ */
14
+ const POSIX_MODES = process.platform !== 'win32';
15
+
16
+ export class HomeError extends Error {
17
+ /** @param {'NOT_PRIVATE'|'SYMLINK'|'BAD_SETTINGS'|'MISSING'} code @param {string} message */
18
+ constructor(code, message) {
19
+ super(message);
20
+ this.name = 'HomeError';
21
+ this.code = code;
22
+ }
23
+ }
24
+
25
+ /** Create `dir` (0700) if needed; refuse a symbolic link or a folder others can read. @param {string} dir */
26
+ export function ensurePrivateDir(dir) {
27
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
28
+ const stat = lstatSync(dir);
29
+ if (stat.isSymbolicLink()) throw new HomeError('SYMLINK', `${dir} is a symbolic link; flop-mcp keeps its data only in a real folder.`);
30
+ if (!stat.isDirectory()) throw new HomeError('NOT_PRIVATE', `${dir} is not a folder.`);
31
+ if (POSIX_MODES && stat.mode & 0o077) throw new HomeError('NOT_PRIVATE', `${dir} can be read by other users. Fix it with: chmod 700 '${dir}'`);
32
+ }
33
+
34
+ /** A regular file only this user can read. @param {string} file */
35
+ export function assertPrivateFile(file) {
36
+ let stat;
37
+ try {
38
+ stat = lstatSync(file);
39
+ } catch (error) {
40
+ if (/** @type {any} */ (error).code === 'ENOENT') throw new HomeError('MISSING', `${file} does not exist.`);
41
+ throw error;
42
+ }
43
+ if (stat.isSymbolicLink()) throw new HomeError('SYMLINK', `${file} is a symbolic link; flop-mcp reads only a real file there.`);
44
+ if (!stat.isFile()) throw new HomeError('NOT_PRIVATE', `${file} is not a file.`);
45
+ if (POSIX_MODES && stat.mode & 0o077) throw new HomeError('NOT_PRIVATE', `${file} can be read by other users. Fix it with: chmod 600 '${file}'`);
46
+ }
47
+
48
+ /** Write a 0600 temporary file next to `file`, flushed to disk; returns its path. */
49
+ function writeTemp(file, text) {
50
+ const temp = `${file}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`;
51
+ const fd = openSync(temp, 'wx', 0o600);
52
+ try {
53
+ writeSync(fd, text);
54
+ fsyncSync(fd);
55
+ } catch (error) {
56
+ closeSync(fd);
57
+ unlinkSync(temp);
58
+ throw error;
59
+ }
60
+ closeSync(fd);
61
+ return temp;
62
+ }
63
+
64
+ /** Flush a folder's entries (the rename or link inside it) to disk. @param {string} dir */
65
+ function syncDir(dir) {
66
+ if (!POSIX_MODES) return; // Windows cannot open a folder to flush it; NTFS journals the rename itself
67
+ const fd = openSync(dir, 'r');
68
+ try {
69
+ fsyncSync(fd);
70
+ } finally {
71
+ closeSync(fd);
72
+ }
73
+ }
74
+
75
+ /** Replace `file` atomically: the old or the new content, never a partial file. @param {string} file @param {string} text */
76
+ export function writePrivateFile(file, text) {
77
+ const temp = writeTemp(file, text);
78
+ try {
79
+ renameSync(temp, file);
80
+ } catch (error) {
81
+ unlinkSync(temp);
82
+ throw error;
83
+ }
84
+ syncDir(dirname(file));
85
+ }
86
+
87
+ /**
88
+ * Create `file` only if it does not exist yet, atomically (a hard link fails when the name is taken).
89
+ * @param {string} file @param {string} text @returns {boolean} false when the file already existed
90
+ */
91
+ export function createPrivateFileOnce(file, text) {
92
+ const temp = writeTemp(file, text);
93
+ try {
94
+ linkSync(temp, file);
95
+ return true;
96
+ } catch (error) {
97
+ if (/** @type {any} */ (error).code === 'EEXIST') return false;
98
+ throw error;
99
+ } finally {
100
+ unlinkSync(temp);
101
+ syncDir(dirname(file));
102
+ }
103
+ }
104
+
@@ -0,0 +1,189 @@
1
+ // SDK-free rules behind src/flop-node.js, so Node tests cover them without loading the SDK (which only
2
+ // ever runs inside the sandbox): reading a granted session, building a turn, the orphan refund rules
3
+ // ported from apps/agent-app/src/direct.js refundOrphans (proven live there on 23 Nov), and what a
4
+ // transfer's error means (the agent app's flop.js sendOutcome).
5
+ import { hexToU8a, u8aToString } from '@polkadot/util';
6
+ import { PLANCK_PER_FLOP, toPlanck } from './shared/units.js';
7
+ import { causeText, refusedForFees } from './shared/direct-core.js';
8
+
9
+ /**
10
+ * @typedef {{ found: boolean, active: boolean, expiresAtBlock: number, capPlanck: bigint, spentPlanck: bigint,
11
+ * perTxPlanck: bigint, dailyPlanck: bigint, epochSpentPlanck: bigint, epochStartBlock: number,
12
+ * dailyLeftPlanck: bigint, allowedPallets: string[] }} SessionView
13
+ */
14
+
15
+ /**
16
+ * Pallet names as text. The SDK's getSession returns the chain's raw JSON, so each name arrives as 0x hex
17
+ * bytes ("0x436f…" = "ComputeChannel", seen live on devnet 24 Nov); text passes through.
18
+ * @param {readonly string[]} pallets
19
+ */
20
+ export function decodePallets(pallets) {
21
+ return pallets.map((p) => (typeof p === 'string' && /^0x(?:[0-9a-fA-F]{2})*$/.test(p) ? u8aToString(hexToU8a(p)) : String(p)));
22
+ }
23
+
24
+ /**
25
+ * Why this key may not buy, or null. "Compute only" means exactly ['ComputeChannel']:
26
+ * an empty list (some devnet sessions have one) or any other pallet is refused.
27
+ * @param {SessionView} view @param {{ minLeftPlanck: bigint }} limits
28
+ * @returns {null | 'missing' | 'inactive' | 'too_broad' | 'cap_used'}
29
+ */
30
+ export function sessionProblem(view, { minLeftPlanck }) {
31
+ if (!view.found) return 'missing';
32
+ if (!view.active) return 'inactive';
33
+ if (view.allowedPallets.length !== 1 || view.allowedPallets[0] !== 'ComputeChannel') return 'too_broad';
34
+ if (view.capPlanck - view.spentPlanck < minLeftPlanck) return 'cap_used';
35
+ return null;
36
+ }
37
+
38
+ /**
39
+ * A chat turn for the miner. A system message only when the caller gave one.
40
+ * @param {{ version: string, model: string, prompt: string, system?: string, maxTokens: number }} input version: the SDK's CHAT_TURN_VERSION, or STRUCTURED_CHAT_TURN_VERSION for a model with chatTemplate
41
+ */
42
+ export function buildEnvelope({ version, model, prompt, system, maxTokens }) {
43
+ return {
44
+ version,
45
+ model,
46
+ messages: [...(system ? [{ role: /** @type {const} */ ('system'), content: system }] : []), { role: /** @type {const} */ ('user'), content: prompt }],
47
+ max_tokens: maxTokens,
48
+ };
49
+ }
50
+
51
+ /**
52
+ * The most turns a channel the connector opens may carry (written on chain at the open). Since issue #163 (Flop's
53
+ * registerSessionEvidence fee, ~1.31 FLOP per session, is charged to the MINER) miners refuse channels whose turn count
54
+ * their share of the escrow cannot cover: on 28 Nov 2026 15:06 UTC antju2 answered a 64-turn, 1.733 FLOP open with
55
+ * 503 max_turns_exceeded, maxAllowedTurns 4, AFTER the open had landed (the escrow then waits out its window for a
56
+ * timeout refund). The daily run never asks more than 4 questions on one channel (daily.js MODES: 1 before scoring, 4 in
57
+ * ON); Claude's ask_flop may ask more, and its 5th question then fails once ("nothing was charged") and the retry buys a
58
+ * new channel within the same caps. The escrow does not depend on this number (a bare open is the capacity floor), so
59
+ * the connector opens with 4. A cheaper miner may allow fewer turns for its smaller escrow (unmeasured).
60
+ */
61
+ export const CHANNEL_MAX_TURNS = 4;
62
+
63
+ export const NON_TEXT_ANSWER = '(The miner\'s verified answer was not plain text, for example a tool call. It was paid for; the connector cannot show it.)';
64
+
65
+ /**
66
+ * The text of a verified receipt's output. A non-text answer (the SDK's decodeTextTurnOutput throws on a
67
+ * tool-call frame) is reported with a fixed notice, never thrown: a paid answer must never turn "unknown".
68
+ * @param {(output: Uint8Array) => Uint8Array} decode the SDK's decodeTextTurnOutput @param {Uint8Array} output
69
+ */
70
+ export function answerText(decode, output) {
71
+ try {
72
+ return new TextDecoder().decode(decode(output));
73
+ } catch {
74
+ return NON_TEXT_ANSWER;
75
+ }
76
+ }
77
+
78
+ /**
79
+ * What is left of the granted session's daily limit at `block`. The chain clears `epoch_spent` only when the
80
+ * session next pays, so a session whose epoch (day) has ended still stores the old day's number: taking it as
81
+ * used would refuse every purchase for ever ("try again tomorrow" never comes; review, 24 Nov:
82
+ * four live devnet sessions still showed yesterday's spend 47.5 h later). An unknown epoch length counts as a
83
+ * fresh day: the chain enforces the real cap either way.
84
+ * @param {{ dailyPlanck: bigint, epochSpentPlanck: bigint, epochStartBlock: number, epochLengthBlocks: number, block: number }} session
85
+ * @returns {bigint}
86
+ */
87
+ export function dailyLeftPlanck({ dailyPlanck, epochSpentPlanck, epochStartBlock, epochLengthBlocks, block }) {
88
+ if (!(epochLengthBlocks > 0) || !(epochStartBlock > 0) || block >= epochStartBlock + epochLengthBlocks) return dailyPlanck;
89
+ return dailyPlanck > epochSpentPlanck ? dailyPlanck - epochSpentPlanck : 0n;
90
+ }
91
+
92
+ /** True when the SDK journal holds this request's verified answer. @param {{ requests: Record<string, { status: string }> }} state @param {string} requestId */
93
+ export const requestDone = (state, requestId) => state.requests[requestId]?.status === 'done';
94
+
95
+ /**
96
+ * Get the escrow of every orphaned channel back: once its window has ended and it is still Open at
97
+ * finality, `submitTimeout` sends computeChannel.timeout (permissionless: it also works after a revoke),
98
+ * which refunds the escrow to the owner. A channel already Closed (or gone) was settled late by the miner
99
+ * or never opened: only a timeout submitted here counts as "refunded". Takes and releases the journal lock.
100
+ * @param {import('@flop-labs/sdk').computeChannel.SpendJournal} journal
101
+ * @param {{ readChannel: (channelHex: string) => Promise<{ block: bigint, channel: { state: string, openedAt: bigint, maxDuration: bigint } | null }>,
102
+ * submitTimeout: (channelHex: string) => Promise<void> }} chain
103
+ * @returns {Promise<Array<{ channel: string, outcome: 'refunded'|'closed'|'not_yet'|'failed'|'unknown', message?: string }>>}
104
+ */
105
+ export async function refundOrphansWith(journal, { readChannel, submitTimeout }) {
106
+ await journal.acquire();
107
+ try {
108
+ const results = [];
109
+ for (const record of journal.state().channels.filter((c) => c.state === 'orphaned')) {
110
+ const { block, channel } = await readChannel(record.channel);
111
+ if (!channel || channel.state === 'Closed') {
112
+ await journal.putChannel({ ...record, state: 'closed', note: 'closed on chain before a refund was asked' });
113
+ results.push({ channel: record.channel, outcome: /** @type {const} */ ('closed') });
114
+ continue;
115
+ }
116
+ // Any other state (e.g. force-settled, waiting for its challenge window) is not ours to time out.
117
+ if (channel.state !== 'Open' || block <= channel.openedAt + channel.maxDuration) {
118
+ results.push({ channel: record.channel, outcome: /** @type {const} */ ('not_yet') });
119
+ continue;
120
+ }
121
+ try {
122
+ await submitTimeout(record.channel);
123
+ await journal.putChannel({ ...record, state: 'closed', note: 'refunded by timeout' });
124
+ results.push({ channel: record.channel, outcome: /** @type {const} */ ('refunded') });
125
+ } catch (error) {
126
+ const e = /** @type {any} */ (error);
127
+ results.push({ channel: record.channel, outcome: e?.code === 'TRANSACTION_FINALIZED_FAILED' ? 'failed' : 'unknown', message: String(e?.message ?? e).slice(0, 300) });
128
+ }
129
+ }
130
+ return results;
131
+ } finally {
132
+ await journal.release();
133
+ }
134
+ }
135
+
136
+ /**
137
+ * What a transfer's error means: "failed" only when it surely moved nothing (included and failed at finality,
138
+ * or refused by the pool because the signer cannot pay the fee), else "unknown", which the chain settles. The
139
+ * agent app's flop.js sendOutcome, keyed on the error's code instead of the SDK class so it runs without the
140
+ * SDK, and stricter on a plain error: only the fee refusal counts there, never any 1010. SDK 0.9.0 to 0.12.1 wrap
141
+ * every refusal at submit time as TransactionUnconfirmedError("SubmissionError") with the node's "1010: …" only
142
+ * in `cause`; "outdated" (1010) and 1012 can mean this very transaction landed.
143
+ * @param {unknown} error
144
+ * @returns {{ outcome: 'failed'|'unknown', message: string, detail: string }} detail: the node's reason, for logs
145
+ */
146
+ export function sendOutcome(error) {
147
+ const message = error instanceof Error ? error.message : String(error);
148
+ const detail = causeText(error);
149
+ if (/** @type {any} */ (error)?.code === 'TRANSACTION_FINALIZED_FAILED') return { outcome: 'failed', message, detail };
150
+ if (refusedForFees(error)) return { outcome: 'failed', message: detail, detail };
151
+ if (/^1010\b.*Inability to pay some fees/i.test(message)) return { outcome: 'failed', message, detail };
152
+ return { outcome: 'unknown', message, detail };
153
+ }
154
+
155
+ /**
156
+ * Whether the testnet faucet can pay one agent grant now, from its own /limits (Flop's step before signing a claim,
157
+ * flop.network/llms.txt): status "open" and the agent claim path, and room for one grant both above its balance floor
158
+ * and in its daily cap. A faucet AT its floor still says "open" and answers every claim 503 low_balance (all of
159
+ * 26 Nov 2026), which the SDK calls unknown and the connector would then hold for a day. The grant size is the
160
+ * faucet's own when it states one. Amounts are FLOP as decimal strings; anything unreadable counts as not serving.
161
+ * @param {any} limits the parsed /limits JSON
162
+ * @param {{ claimPath: string, grantFlop: number }} expected the SDK's claim path; the network's published grant
163
+ * @returns {{ open: boolean, status: string }}
164
+ */
165
+ export function faucetServes(limits, { claimPath, grantFlop }) {
166
+ const faucet = limits?.faucet;
167
+ /** @param {unknown} value */
168
+ const flop = (value) => {
169
+ try {
170
+ return typeof value === 'string' && value.length <= 40 ? toPlanck(value) : undefined;
171
+ } catch {
172
+ return undefined;
173
+ }
174
+ };
175
+ const status = typeof faucet?.status === 'string' ? faucet.status.slice(0, 40) : 'missing';
176
+ if (status !== 'open') return { open: false, status };
177
+ if (faucet.agent?.claimPath !== claimPath) return { open: false, status: 'open, but not for this claim path' };
178
+ const stated = faucet.agent?.grantFlop;
179
+ const grant = BigInt(Number.isSafeInteger(stated) && stated > 0 ? stated : grantFlop) * PLANCK_PER_FLOP;
180
+ const balance = flop(faucet.balanceFlop);
181
+ const floor = flop(faucet.minBalanceFlop);
182
+ if (balance === undefined || floor === undefined) return { open: false, status: 'open, but its balance is unreadable' };
183
+ if (balance - floor < grant) return { open: false, status: 'open, but at its balance floor (it refuses grants until refilled)' };
184
+ if (faucet.dailyCap !== undefined) {
185
+ const left = flop(faucet.dailyCap?.remainingFlop);
186
+ if (left === undefined || left < grant) return { open: false, status: 'open, but its daily cap is used up' };
187
+ }
188
+ return { open: true, status };
189
+ }