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.
@@ -0,0 +1,221 @@
1
+ // The daily run's scheduler (SPEC.md "The scheduler"), per operating system, and the notifications for the human
2
+ // moments. Each is a PLAN first (files to write, commands to run: pure, tested on any computer with stand-ins), then
3
+ // carried out by `apply` with an injected runner. Node built-ins only: this runs outside the sandbox.
4
+ //
5
+ // Three triggers a day (the chosen minute, +6 h, +12 h): the run itself skips a day already done (src/daily.js isDue),
6
+ // so the later two are retries for a day whose first run could not finish (no network, every miner down).
7
+ import { createHash } from 'node:crypto';
8
+ import { join } from 'node:path';
9
+
10
+ /** @typedef {{ path: string, content: string, encoding?: 'utf8'|'utf16le' }} PlanFile */
11
+ /**
12
+ * @typedef {{ cmd: string, args: string[], okCodes?: number[], input?: string, env?: Record<string, string> }} PlanCommand
13
+ * okCodes: exits that are fine (default [0]); env: variables the command needs on top of this process's
14
+ */
15
+ /**
16
+ * @typedef {{ kind: 'launchd'|'schtasks'|'systemd'|'cron', name: string, files: PlanFile[], install: PlanCommand[],
17
+ * startNow: PlanCommand[], uninstall: PlanCommand[], removeFiles: string[], cron?: { line: string, marker: string },
18
+ * held?: PlanCommand & { absent: number[], scope?: PlanCommand }, ready?: PlanCommand & { off: string } }} Plan
19
+ * held: the scheduler's own question "do you hold this job, running?": exit 0 yes, an exit in `absent` no, anything
20
+ * else unknown (reviews of 6be8437 and 96f7c8f: the files on disk do not say what the scheduler has loaded); scope:
21
+ * asked when the answer is "no": failing, it means the scheduler could not look here at all, so "unknown" (launchd's
22
+ * gui domain does not exist over SSH with nobody logged in at the screen); ready: a job held but switched off (a timer
23
+ * disabled by hand, a disabled Windows task) prints a line matching `off` (push-gate review of a4bea37)
24
+ */
25
+
26
+ /**
27
+ * A suffix that keeps a test's or a proof's job apart from the human's own: empty for the default data root.
28
+ * @param {string} dataRoot @param {string} defaultRoot
29
+ */
30
+ export const jobSuffix = (dataRoot, defaultRoot) => (dataRoot === defaultRoot ? '' : createHash('sha256').update(dataRoot).digest('hex').slice(0, 8));
31
+
32
+ /** The three times a day the scheduler starts `tryflop daily`. @param {number} hour @param {number} minute */
33
+ export const triggerTimes = (hour, minute) => [0, 6, 12].map((add) => ({ hour: (hour + add) % 24, minute }));
34
+
35
+ /** @param {string} text */
36
+ const xml = (text) => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
37
+
38
+ /** A word for systemd's ExecStart (double-quoted; `\\`, `"` and `%` escaped). @param {string} text */
39
+ const systemdWord = (text) => `"${String(text).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%').replace(/\$/g, '$$$$')}"`;
40
+
41
+ /** A word for sh (single-quoted). @param {string} text */
42
+ const shWord = (text) => `'${String(text).replace(/'/g, `'\\''`)}'`;
43
+
44
+ /**
45
+ * @param {{ platform: string, uid?: number, home: string, nodePath: string, binPath: string, network: string,
46
+ * hour: number, minute: number, suffix: string, env: Record<string, string>, logDir: string, systemd?: boolean, today?: string,
47
+ * runtimeDir?: string }} o
48
+ * env: FLOP_MCP_* variables to pass (only when not the defaults); logDir: where the job's own output (and the Windows
49
+ * task file) goes — a folder the sandbox can NOT write (roots.js logsRoot), since the scheduler writes there unsandboxed;
50
+ * systemd: Linux has systemd --user (else cron); today: YYYY-MM-DD, the Windows triggers' first day; runtimeDir: the
51
+ * user's runtime folder (XDG_RUNTIME_DIR, /run/user/<uid>), where `systemctl --user` finds the user's manager: a
52
+ * shell reached over SSH or su often lacks the variable, and systemctl then cannot connect at all
53
+ * @returns {Plan}
54
+ */
55
+ export function schedulerPlan(o) {
56
+ // A newline breaks every one of these formats (a cron line, a unit file, a plist string is fine but cron is not), and
57
+ // Windows expands %VAR% inside a task's command: refuse such paths instead of scheduling something else (review, 27 Nov).
58
+ for (const value of [o.nodePath, o.binPath, o.logDir, ...Object.values(o.env)]) {
59
+ if (/[\r\n\0]/.test(value)) throw new Error('a path for the scheduler holds a line break');
60
+ if (o.platform === 'win32' && value.includes('%')) throw new Error('a path for the Windows scheduler holds a "%"');
61
+ }
62
+ const args = [o.binPath, 'daily', '--network', o.network];
63
+ const times = triggerTimes(o.hour, o.minute);
64
+ if (o.platform === 'darwin') {
65
+ const label = `com.tryflop.daily${o.suffix ? `.${o.suffix}` : ''}`;
66
+ const path = join(o.home, 'Library', 'LaunchAgents', `${label}.plist`);
67
+ const envXml = Object.keys(o.env).length
68
+ ? ` <key>EnvironmentVariables</key>\n <dict>\n${Object.entries(o.env).map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}</string>`).join('\n')}\n </dict>\n`
69
+ : '';
70
+ const content = `<?xml version="1.0" encoding="UTF-8"?>
71
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
72
+ <plist version="1.0">
73
+ <dict>
74
+ <key>Label</key><string>${xml(label)}</string>
75
+ <key>ProgramArguments</key>
76
+ <array>
77
+ ${[o.nodePath, ...args].map((a) => ` <string>${xml(a)}</string>`).join('\n')}
78
+ </array>
79
+ <key>StartCalendarInterval</key>
80
+ <array>
81
+ ${times.map((t) => ` <dict><key>Hour</key><integer>${t.hour}</integer><key>Minute</key><integer>${t.minute}</integer></dict>`).join('\n')}
82
+ </array>
83
+ ${envXml} <key>RunAtLoad</key><true/>
84
+ <key>ProcessType</key><string>Background</string>
85
+ <key>StandardOutPath</key><string>${xml(join(o.logDir, 'scheduler.log'))}</string>
86
+ <key>StandardErrorPath</key><string>${xml(join(o.logDir, 'scheduler.log'))}</string>
87
+ </dict>
88
+ </plist>
89
+ `;
90
+ const domain = `gui/${o.uid}`;
91
+ return {
92
+ kind: 'launchd', name: label, files: [{ path, content }],
93
+ install: [{ cmd: '/bin/launchctl', args: ['bootout', `${domain}/${label}`], okCodes: [0, 3, 5, 36, 113] }, { cmd: '/bin/launchctl', args: ['bootstrap', domain, path] }],
94
+ startNow: [{ cmd: '/bin/launchctl', args: ['kickstart', `${domain}/${label}`] }],
95
+ // bootout: 0 stopped, 3 / 113 not loaded, 36 stopping now (measured 28 Nov 2026: a missing job answers 3); anything
96
+ // else is checked with `print`, which answers 113 for a job launchd does not hold.
97
+ uninstall: [{ cmd: '/bin/launchctl', args: ['bootout', `${domain}/${label}`], okCodes: [0, 3, 36, 113] }],
98
+ held: { cmd: '/bin/launchctl', args: ['print', `${domain}/${label}`], absent: [113], scope: { cmd: '/bin/launchctl', args: ['print', domain] } },
99
+ removeFiles: [path],
100
+ };
101
+ }
102
+ if (o.platform === 'win32') {
103
+ const name = `TryFlop\\Daily${o.suffix ? ` ${o.suffix}` : ''}`;
104
+ // One file per job: testnet's and devnet's tasks never share (or delete) each other's (push-gate review of 34fa6ee).
105
+ const path = join(o.logDir, `tryflop-task${o.suffix ? `-${o.suffix}` : ''}.xml`);
106
+ const day = o.today ?? '2026-11-27';
107
+ const triggers = times.map((t) => ` <CalendarTrigger>
108
+ <StartBoundary>${day}T${String(t.hour).padStart(2, '0')}:${String(t.minute).padStart(2, '0')}:00</StartBoundary>
109
+ <Enabled>true</Enabled>
110
+ <ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay>
111
+ </CalendarTrigger>`).join('\n');
112
+ const content = `<?xml version="1.0" encoding="UTF-16"?>
113
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
114
+ <RegistrationInfo><Description>Try Flop: the agent's daily run (claims Flop's free test FLOP, pays a miner for an answer).</Description></RegistrationInfo>
115
+ <Triggers>
116
+ ${triggers}
117
+ </Triggers>
118
+ <Principals><Principal id="Author"><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
119
+ <Settings>
120
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
121
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
122
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
123
+ <StartWhenAvailable>true</StartWhenAvailable>
124
+ <ExecutionTimeLimit>PT3H</ExecutionTimeLimit>
125
+ <Enabled>true</Enabled>
126
+ </Settings>
127
+ <Actions Context="Author">
128
+ <Exec><Command>${xml(o.nodePath)}</Command><Arguments>${xml(args.map((a) => `"${a}"`).join(' '))}</Arguments></Exec>
129
+ </Actions>
130
+ </Task>
131
+ `;
132
+ return {
133
+ kind: 'schtasks', name, files: [{ path, content: `\uFEFF${content}`, encoding: 'utf16le' }],
134
+ install: [{ cmd: 'schtasks.exe', args: ['/Create', '/TN', name, '/XML', path, '/F'] }],
135
+ startNow: [{ cmd: 'schtasks.exe', args: ['/Run', '/TN', name] }],
136
+ // /Delete answers 1 both for "no such task" and "access denied": /Query says which (1: no such task). A /Query
137
+ // refused too would read as gone; that needs a task this user may neither delete nor read, which this user's own
138
+ // /Create never makes (not run on Windows yet).
139
+ uninstall: [{ cmd: 'schtasks.exe', args: ['/Delete', '/TN', name, '/F'] }],
140
+ held: { cmd: 'schtasks.exe', args: ['/Query', '/TN', name], absent: [1] },
141
+ // A task disabled by hand still answers /Query; its XML says <Enabled>false</Enabled> under <Settings> (element
142
+ // names are not translated; not run on Windows yet).
143
+ ready: { cmd: 'schtasks.exe', args: ['/Query', '/TN', name, '/XML'], off: '<Settings>[\\s\\S]*<Enabled>false</Enabled>[\\s\\S]*</Settings>' },
144
+ removeFiles: [path],
145
+ };
146
+ }
147
+ const unit = `tryflop-daily${o.suffix ? `-${o.suffix}` : ''}`;
148
+ const bus = o.runtimeDir ? { env: { XDG_RUNTIME_DIR: o.runtimeDir } } : {};
149
+ if (o.systemd !== false) {
150
+ const dir = join(o.home, '.config', 'systemd', 'user');
151
+ const service = `[Unit]
152
+ Description=Try Flop daily run
153
+
154
+ [Service]
155
+ Type=oneshot
156
+ ExecStart=${[o.nodePath, ...args].map(systemdWord).join(' ')}
157
+ ${Object.entries(o.env).map(([k, v]) => `Environment=${systemdWord(`${k}=${v}`)}`).join('\n')}
158
+ `;
159
+ const timer = `[Unit]
160
+ Description=Try Flop daily run
161
+
162
+ [Timer]
163
+ ${times.map((t) => `OnCalendar=*-*-* ${String(t.hour).padStart(2, '0')}:${String(t.minute).padStart(2, '0')}:00`).join('\n')}
164
+ Persistent=true
165
+
166
+ [Install]
167
+ WantedBy=timers.target
168
+ `;
169
+ return {
170
+ kind: 'systemd', name: unit,
171
+ files: [{ path: join(dir, `${unit}.service`), content: service }, { path: join(dir, `${unit}.timer`), content: timer }],
172
+ install: [{ cmd: 'systemctl', args: ['--user', 'daemon-reload'], ...bus }, { cmd: 'systemctl', args: ['--user', 'enable', '--now', `${unit}.timer`], ...bus }],
173
+ startNow: [{ cmd: 'systemctl', args: ['--user', 'start', '--no-block', `${unit}.service`], ...bus }],
174
+ // stop first: it works on the loaded timer even when its file was deleted by hand (disable then answers 1 on
175
+ // systemd 252+, and `disable --now` never reaches its stop). 5: not loaded. is-active asks the user's manager
176
+ // itself: 0 active, 3 inactive, 4 no such unit; 1 (no bus) is unknown (push-gate review of 96f7c8f).
177
+ uninstall: [{ cmd: 'systemctl', args: ['--user', 'stop', `${unit}.timer`], okCodes: [0, 5], ...bus }, { cmd: 'systemctl', args: ['--user', 'disable', `${unit}.timer`], okCodes: [0, 5], ...bus }],
178
+ held: { cmd: 'systemctl', args: ['--user', 'is-active', '--quiet', `${unit}.timer`], absent: [3, 4], ...bus },
179
+ // `disable` without --now leaves the timer running until the next reboot or logout, then nothing starts it.
180
+ ready: { cmd: 'systemctl', args: ['--user', 'is-enabled', `${unit}.timer`], off: '^disabled$', ...bus },
181
+ removeFiles: [join(dir, `${unit}.service`), join(dir, `${unit}.timer`)],
182
+ };
183
+ }
184
+ // No systemd --user: cron, every hour at the chosen minute (cron has no catch-up; the run's own due check makes the
185
+ // first hourly start after a missed time do that day's run).
186
+ const marker = `# ${unit}`;
187
+ // cron turns an unescaped % into a line break, even inside quotes.
188
+ const cronWord = (/** @type {string} */ t) => shWord(t).replace(/%/g, '\\%');
189
+ const envPrefix = Object.entries(o.env).map(([k, v]) => `${k}=${cronWord(v)} `).join('');
190
+ // cron passes no desktop session, so notify-send could not reach it: name the user's session bus (review of 6be8437).
191
+ const busPrefix = Number.isInteger(o.uid) ? `DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/${o.uid}/bus ` : '';
192
+ const line = `${o.minute} * * * * ${busPrefix}${envPrefix}${[o.nodePath, ...args].map(cronWord).join(' ')} >> ${cronWord(join(o.logDir, 'scheduler.log'))} 2>&1 ${marker}`;
193
+ return { kind: 'cron', name: unit, files: [], install: [], startNow: [], uninstall: [], removeFiles: [], cron: { line, marker } };
194
+ }
195
+
196
+ /**
197
+ * A crontab's text with this job's line removed, and (when `line` is given) added once.
198
+ * @param {string} current @param {string} marker @param {string} [line]
199
+ */
200
+ export function editCrontab(current, marker, line) {
201
+ const kept = String(current ?? '').split('\n').filter((l) => l.trim() !== '' && !l.endsWith(marker));
202
+ return `${[...kept, ...(line ? [line] : [])].join('\n')}\n`;
203
+ }
204
+
205
+ /**
206
+ * The command that shows one notification, per operating system (best effort: the status file is the record).
207
+ * @param {string} platform @param {string} text @returns {{ cmd: string, args: string[], env?: Record<string, string> } | null}
208
+ */
209
+ export function notifyCommand(platform, text) {
210
+ const clean = String(text).replace(/[\u0000-\u001f\u007f]+/g, ' ').slice(0, 300);
211
+ if (platform === 'darwin') {
212
+ const quoted = clean.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
213
+ return { cmd: '/usr/bin/osascript', args: ['-e', `display notification "${quoted}" with title "Try Flop"`] };
214
+ }
215
+ if (platform === 'win32') {
216
+ const script = "Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing; $n = New-Object System.Windows.Forms.NotifyIcon; $n.Icon = [System.Drawing.SystemIcons]::Information; $n.Visible = $true; $n.ShowBalloonTip(15000, 'Try Flop', $env:TRYFLOP_NOTE, 'Info'); Start-Sleep -Seconds 15; $n.Dispose()";
217
+ return { cmd: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', script], env: { TRYFLOP_NOTE: clean } };
218
+ }
219
+ if (platform === 'linux') return { cmd: 'notify-send', args: ['Try Flop', clean] };
220
+ return null;
221
+ }
package/src/scoring.js ADDED
@@ -0,0 +1,67 @@
1
+ // Has Flop's testnet scoring started? (SPEC.md "tryflop daily", SCORING.) Try Flop's site publishes what it found
2
+ // (https://tryflop.com/status.json: { network, scoring: "not-started"|"announced"|"on"|"unknown", activationBlock,
3
+ // finalizedBlock, runtime, sources: [{ url, checkedAt, excerpt }], checkedAt }; live since 27 Nov 2026, captured in
4
+ // test/fixtures/status/), and this computer checks the one fact that matters on the chain itself: is
5
+ // our own finalized head at or past the announced activation block? Anything unreadable, malformed or unconfirmed
6
+ // counts as not started, the cheaper mode. Node built-ins only (fetch): no third-party code.
7
+
8
+ export const STATUS_URL = 'https://tryflop.com/status.json';
9
+ const STATES = new Set(['not-started', 'announced', 'on', 'unknown']);
10
+ const MAX_BYTES = 65_536;
11
+
12
+ /**
13
+ * @typedef {{ scoring: 'not-started'|'announced'|'on'|'unknown', activationBlock: number | null, finalizedBlock: number | null,
14
+ * sources: string[], checkedAt: string }} ScoringStatus sources: the pages it read (their URLs only)
15
+ * @typedef {{ mode: 'ON'|'NOT_STARTED', state: 'not-started'|'announced'|'on'|'unknown', activationBlock: number | null,
16
+ * why: string }} ScoringMode
17
+ */
18
+
19
+ /** @param {unknown} n */
20
+ const blockNumber = (n) => (Number.isSafeInteger(n) && /** @type {number} */ (n) > 0 ? /** @type {number} */ (n) : null);
21
+
22
+ /**
23
+ * The status file as published, every field checked; null for anything else (fail toward "not started").
24
+ * @param {unknown} json @returns {ScoringStatus | null}
25
+ */
26
+ export function parseScoringStatus(json) {
27
+ if (!json || typeof json !== 'object' || Array.isArray(json)) return null;
28
+ const j = /** @type {any} */ (json);
29
+ if (!STATES.has(j.scoring)) return null;
30
+ if (j.activationBlock !== null && j.activationBlock !== undefined && blockNumber(j.activationBlock) === null) return null;
31
+ const sources = (Array.isArray(j.sources) ? j.sources : []).map((s) => (typeof s === 'string' ? s : s?.url))
32
+ .filter((s) => typeof s === 'string' && /^https:\/\/[^\s]{1,300}$/.test(s)).slice(0, 10);
33
+ const checkedAt = typeof j.checkedAt === 'string' && !Number.isNaN(Date.parse(j.checkedAt)) ? j.checkedAt.slice(0, 40) : '';
34
+ return { scoring: j.scoring, activationBlock: blockNumber(j.activationBlock), finalizedBlock: blockNumber(j.finalizedBlock), sources, checkedAt };
35
+ }
36
+
37
+ /**
38
+ * The daily run's mode. ON only when the site says scoring is on (or announced), names an activation block, and OUR
39
+ * finalized head has reached it: a wrong or stale site can at most keep the cheaper mode, never start spending early
40
+ * on a block that has not come.
41
+ * @param {ScoringStatus | null} status @param {bigint | number | null} ourFinalized null when the chain could not be read
42
+ * @returns {ScoringMode}
43
+ */
44
+ export function scoringMode(status, ourFinalized) {
45
+ if (!status) return { mode: 'NOT_STARTED', state: 'unknown', activationBlock: null, why: 'Try Flop\'s scoring status could not be read; treated as not started.' };
46
+ const { scoring, activationBlock } = status;
47
+ if (scoring === 'not-started') return { mode: 'NOT_STARTED', state: scoring, activationBlock, why: 'Flop has not announced when testnet activity starts to count.' };
48
+ if (scoring === 'unknown') return { mode: 'NOT_STARTED', state: 'unknown', activationBlock, why: 'Try Flop could not read Flop\'s status pages just now; treated as not started.' };
49
+ if (activationBlock === null) return { mode: 'NOT_STARTED', state: scoring, activationBlock, why: 'Flop\'s start block is not known yet, so it cannot be checked on the chain.' };
50
+ if (ourFinalized === null || ourFinalized === undefined) return { mode: 'NOT_STARTED', state: scoring, activationBlock, why: 'Flop\'s chain could not be read to check the start block.' };
51
+ if (BigInt(ourFinalized) < BigInt(activationBlock)) {
52
+ return { mode: 'NOT_STARTED', state: 'announced', activationBlock, why: `Flop announced scoring from block ${activationBlock}; the chain is at ${ourFinalized}.` };
53
+ }
54
+ return { mode: 'ON', state: 'on', activationBlock, why: `Flop's scoring started at block ${activationBlock} (checked on the chain).` };
55
+ }
56
+
57
+ /**
58
+ * Read the status file (≤ 10 s, ≤ 64 KB, no redirects). Throws on any failure; the caller treats that as unknown.
59
+ * @param {string} [url] @param {typeof fetch} [fetchImpl] @returns {Promise<unknown>}
60
+ */
61
+ export async function fetchScoringStatus(url = STATUS_URL, fetchImpl = fetch) {
62
+ const response = await fetchImpl(url, { redirect: 'error', signal: AbortSignal.timeout(10_000), headers: { accept: 'application/json' } });
63
+ if (response.status !== 200) throw new Error(`${url} answered HTTP ${response.status}`);
64
+ const text = await response.text();
65
+ if (text.length > MAX_BYTES) throw new Error(`${url} is too large`);
66
+ return JSON.parse(text);
67
+ }
package/src/secrets.js ADDED
@@ -0,0 +1,41 @@
1
+ // Prompts leave this computer for a third-party miner. ask_flop refuses one that
2
+ // holds an obvious secret, before anything is bought. A bare 64-hex string is allowed: transaction and
3
+ // channel ids look exactly like private keys, so only one labelled as a key, secret or seed is refused.
4
+ import { mnemonicValidate } from '@polkadot/util-crypto';
5
+
6
+ const PEM = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;
7
+ const API_KEY = /\b(?:sk-[A-Za-z0-9_-]{20,}|sk_live_[A-Za-z0-9]{16,}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|xox[abpr]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16})/;
8
+ /** A 64-byte secret key in base58 (Solana style) is 87–88 characters. */
9
+ const BASE58_KEY = /(?<![1-9A-HJ-NP-Za-km-z])[1-9A-HJ-NP-Za-km-z]{86,90}(?![1-9A-HJ-NP-Za-km-z])/;
10
+ const LABELLED_HEX = /(?:private|secret|seed)[^\n]{0,40}?(?:0x)?[0-9a-fA-F]{64}(?![0-9a-fA-F])/i;
11
+ const PHRASE_LENGTHS = [12, 15, 18, 21, 24];
12
+
13
+ /** A recovery phrase: 12, 15, 18, 21 or 24 consecutive words whose BIP-39 checksum is valid. @param {string} text */
14
+ function hasRecoveryPhrase(text) {
15
+ const words = text.toLowerCase().match(/[a-z]+/g) ?? [];
16
+ for (const size of PHRASE_LENGTHS) {
17
+ for (let start = 0; start + size <= words.length; start += 1) {
18
+ if (mnemonicValidate(words.slice(start, start + size).join(' '), undefined, true)) return true;
19
+ }
20
+ }
21
+ return false;
22
+ }
23
+
24
+ /**
25
+ * @param {string} text
26
+ * @returns {null | 'pem_private_key' | 'api_key' | 'recovery_phrase' | 'base58_key' | 'labelled_hex_key'}
27
+ */
28
+ export function findSecret(text) {
29
+ if (PEM.test(text)) return 'pem_private_key';
30
+ if (API_KEY.test(text)) return 'api_key';
31
+ if (LABELLED_HEX.test(text)) return 'labelled_hex_key';
32
+ if (BASE58_KEY.test(text)) return 'base58_key';
33
+ if (hasRecoveryPhrase(text)) return 'recovery_phrase';
34
+ return null;
35
+ }
36
+
37
+ /** What each kind is called in a message to the user. */
38
+ export const SECRET_NAMES = Object.freeze({
39
+ pem_private_key: 'a private key file', api_key: 'an API key or token', recovery_phrase: 'a wallet recovery phrase',
40
+ base58_key: 'a wallet secret key', labelled_hex_key: 'a private key, secret or seed',
41
+ });
package/src/server.js ADDED
@@ -0,0 +1,13 @@
1
+ // The MCP server over stdio (or a given transport, in tests). serveStdio may call the factory more than
2
+ // once per connection (a discarded discovery probe), so the factory only builds; the payer is shared.
3
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
4
+ import { buildServer } from './tools.js';
5
+
6
+ /**
7
+ * @param {Pick<import('./payer.js').Payer, 'ask'|'status'|'result'|'settle'>} payer
8
+ * @param {{ network: string, version: string, own?: boolean }} options
9
+ * @param {import('@modelcontextprotocol/server').Transport} [transport] default: this process's stdin/stdout
10
+ */
11
+ export function serve(payer, options, transport) {
12
+ return serveStdio(() => buildServer(payer, options), transport ? { transport } : {});
13
+ }