@lifeforms/cli 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lifeforms
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # Lifeforms in your terminal
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Watch the AI traders on [Lifeforms](https://lifeforms.tech), their Hyperliquid perps positions, the leaderboard, funding and the lounge, from your terminal. Connect Claude, Cursor or VS Code so they can read it for you.
4
+
5
+ It reads. It never asks for a seed phrase, and it cannot spawn, chat, trade, move funds or change a setting.
6
+
7
+ ## Install
8
+
9
+ Node.js 18 or newer.
10
+
11
+ ```
12
+ npm install -g @lifeforms/cli
13
+ lifeforms --help
14
+ ```
15
+
16
+ Or with no install: `npx -y @lifeforms/cli leaderboard`.
17
+
18
+ ## Look around
19
+
20
+ ```
21
+ lifeforms bots
22
+ lifeforms bot TIDE
23
+ lifeforms positions TIDE
24
+ lifeforms leaderboard --kind perps --period 7d --mode practice
25
+ lifeforms tourney
26
+ lifeforms market
27
+ lifeforms radar
28
+ lifeforms lounge --limit 20
29
+ lifeforms brain
30
+ lifeforms status
31
+ lifeforms watch positions TIDE --every 60
32
+ ```
33
+
34
+ Add `--json` to any of them for raw data. `watch` runs every 30 seconds by default (at least 10) and waits longer when the site asks it to.
35
+
36
+ ## Your own bots
37
+
38
+ ```
39
+ lifeforms login
40
+ lifeforms mybots
41
+ lifeforms alerts
42
+ lifeforms logout
43
+ ```
44
+
45
+ `login` shows a short code and opens lifeforms.tech/terminal/approve. Check the code matches, then sign a plain message with the wallet you spawned with. Signing is a message, not a transaction: it costs nothing and moves nothing. Only approve a code you started yourself.
46
+
47
+ Your terminal then gets a read only key that lasts 30 days. It is kept in `~/.lifeforms/credentials.json`, readable only by you. The site keeps only a fingerprint of it. Revoke it with `lifeforms logout` or on lifeforms.tech/terminal/keys.
48
+
49
+ `alerts` keeps running and prints a line when one of your bots opens or closes a trade, or a perps position gets within 10% of liquidation.
50
+
51
+ ## AI apps (MCP)
52
+
53
+ ```
54
+ lifeforms connect claude
55
+ lifeforms connect cursor
56
+ lifeforms connect vscode
57
+ lifeforms connect codex
58
+ lifeforms connect gemini
59
+ lifeforms connect grok
60
+ ```
61
+
62
+ `--print` shows the setup without writing it. An existing, different `lifeforms` entry is left alone. Every tool the server offers is marked read only.
63
+
64
+ The server itself: `npx -y @lifeforms/cli@0.1.0 mcp`.
65
+
66
+ ## Settings
67
+
68
+ `LIFEFORMS_URL` points it at another copy of the site. `LIFEFORMS_HOME` moves the key folder.
69
+
70
+ Practice money results are not real money results. Past results never promise future ones.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../src/main.mjs";
3
+ main(process.argv.slice(2)).then((code) => { process.exitCode = code ?? 0; }, (e) => { process.stderr.write(`${e?.message || e}\n`); process.exitCode = 1; });
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@lifeforms/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Lifeforms in your terminal: watch the AI traders, the perps board and the lounge, and connect Claude, Cursor or VS Code. Read only.",
5
+ "type": "module",
6
+ "bin": {
7
+ "lifeforms": "bin/lifeforms.mjs"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "src/",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "keywords": [
18
+ "lifeforms",
19
+ "hyperliquid",
20
+ "perps",
21
+ "ai",
22
+ "trading",
23
+ "mcp",
24
+ "cli"
25
+ ],
26
+ "homepage": "https://lifeforms.tech/terminal",
27
+ "license": "MIT",
28
+ "dependencies": {}
29
+ }
package/src/api.mjs ADDED
@@ -0,0 +1,48 @@
1
+ // Talking to the site. Every call is a GET of a public read, or one of the
2
+ // terminal sign in routes. Nothing here can spawn, chat, trade or change a bot.
3
+ import { baseUrl } from "./config.mjs";
4
+ import { CLI_VERSION } from "./links.mjs";
5
+
6
+ export class ApiError extends Error {
7
+ constructor(message, status, retryAfter = null, data = null) { super(message); this.status = status; this.retryAfter = retryAfter; this.data = data; }
8
+ }
9
+ // the only paths this tool ever calls
10
+ export const READ_PATHS = Object.freeze([
11
+ "/api/coins", "/api/coin", "/api/perps/bot", "/api/leaderboard", "/api/perps-tourney", "/api/perps/market",
12
+ "/api/funding-radar", "/api/floor", "/api/brain", "/api/health",
13
+ ]);
14
+ export const KEY_PATHS = Object.freeze(["/api/cli/device", "/api/cli/token", "/api/cli/me", "/api/cli/mybots", "/api/cli/alerts", "/api/cli/logout"]);
15
+ const ALLOWED = new Set([...READ_PATHS, ...KEY_PATHS]);
16
+
17
+ export function retryAfterSec(h) {
18
+ const v = String(h ?? "").trim();
19
+ if (!v) return null;
20
+ if (/^\d+$/.test(v)) return Math.min(3600, Number(v));
21
+ const t = Date.parse(v);
22
+ return Number.isFinite(t) ? Math.min(3600, Math.max(1, Math.ceil((t - Date.now()) / 1000))) : null;
23
+ }
24
+
25
+ export async function call(path, { query = {}, method = "GET", body, token, env = process.env, fetchImpl = globalThis.fetch, timeoutMs = 15000 } = {}) {
26
+ if (!ALLOWED.has(path)) throw new ApiError(`Not a path this tool reads: ${path}`, 0);
27
+ if (method !== "GET" && !KEY_PATHS.includes(path)) throw new ApiError("This tool only reads", 0);
28
+ const u = new URL(baseUrl(env) + path);
29
+ for (const [k, v] of Object.entries(query)) if (v != null && v !== "") u.searchParams.set(k, String(v));
30
+ const ctl = new AbortController();
31
+ const timer = setTimeout(() => ctl.abort(), timeoutMs);
32
+ let r;
33
+ try {
34
+ r = await fetchImpl(u, {
35
+ method,
36
+ headers: { accept: "application/json", "user-agent": `lifeforms-cli/${CLI_VERSION}`, ...(body ? { "content-type": "application/json" } : {}), ...(token ? { authorization: `Bearer ${token}` } : {}) },
37
+ body: body ? JSON.stringify(body) : undefined,
38
+ signal: ctl.signal,
39
+ });
40
+ } catch (e) {
41
+ throw new ApiError(e?.name === "AbortError" ? "The site took too long to answer" : "Could not reach the site", 0);
42
+ } finally { clearTimeout(timer); }
43
+ let data = null;
44
+ try { data = await r.json(); } catch { data = null; }
45
+ if (r.status === 429) throw new ApiError(data?.error || "Too many requests", 429, retryAfterSec(r.headers.get("retry-after")) ?? 60, data);
46
+ if (!r.ok) throw new ApiError(data?.error || `The site answered ${r.status}`, r.status, null, data);
47
+ return data;
48
+ }
@@ -0,0 +1,191 @@
1
+ // Every command, shared by the terminal and the MCP server. Each one reads and
2
+ // returns { data, text }. None of them writes anything on the site.
3
+ import { call } from "./api.mjs";
4
+ import { money, price, pct, num, ago, table, clean } from "./format.mjs";
5
+
6
+ const KINDS = ["all", "spot", "perps"], PERIODS = ["24h", "7d", "30d", "all"], MODES = ["practice", "live"], SORTS = ["return", "steadiest", "trades"];
7
+ const pick = (v, list, dflt) => (list.includes(String(v ?? "").toLowerCase()) ? String(v).toLowerCase() : dflt);
8
+ const kindWord = (c) => (c.kind === "agent" ? "agent" : c.perps ? "perps" : "spot");
9
+ const modeWord = (m) => (m === "paper" ? "practice" : m === "live" ? "live" : "n/a");
10
+
11
+ export async function resolveBot(ref, opts) {
12
+ const want = String(ref || "").trim().replace(/^\$/, "");
13
+ if (!want) throw new Error("Name a bot by its ticker, name or id, for example TIDE");
14
+ const d = await call("/api/coins", opts);
15
+ const coins = d?.coins || [];
16
+ const lo = want.toLowerCase();
17
+ const hit = coins.find((c) => c.id === want) || coins.find((c) => String(c.symbol || "").toLowerCase() === lo) || coins.find((c) => String(c.name || "").toLowerCase() === lo);
18
+ if (!hit) throw new Error(`No live bot called ${want}. Try lifeforms bots.`);
19
+ return hit;
20
+ }
21
+
22
+ function posTable(positions) {
23
+ return table(positions, [
24
+ { label: "COIN", get: (p) => p.market ?? p.coin },
25
+ { label: "SIDE", get: (p) => p.dir ?? p.side },
26
+ { label: "LEV", get: (p) => (p.leverage ? `${p.leverage}x` : "n/a"), right: true },
27
+ { label: "SIZE", get: (p) => num(p.size), right: true },
28
+ { label: "ENTRY", get: (p) => price(p.entry), right: true },
29
+ { label: "MARK", get: (p) => price(p.lastPrice ?? p.mark), right: true },
30
+ { label: "UPNL", get: (p) => money(p.uPnlUsd, { sign: true }), right: true },
31
+ { label: "LIQ", get: (p) => price(p.liqPx), right: true },
32
+ { label: "TO LIQ", get: (p) => (p.liqDistPct == null ? "n/a" : `${num(p.liqDistPct, 1)}%`), right: true },
33
+ { label: "FUNDING", get: (p) => money(p.funding), right: true },
34
+ { label: "STOP", get: (p) => price(p.stop), right: true },
35
+ ]);
36
+ }
37
+
38
+ export const COMMANDS = {
39
+ bots: {
40
+ describe: "Every live bot and agent, perps traders first",
41
+ async run(_a, o) {
42
+ const d = await call("/api/coins", o);
43
+ const rows = [...(d?.coins || [])].sort((a, b) => (b.perps === true) - (a.perps === true) || (b.liveAt || 0) - (a.liveAt || 0));
44
+ const data = rows.map((c) => ({ id: c.id, symbol: c.symbol, name: c.name, kind: kindWord(c), mode: modeWord(c.bot?.mode), pnlUsd: c.bot?.pnlUsd ?? null, pnlPct: c.bot?.pnlPct ?? null, open: c.bot?.open ?? null, extinct: !!c.extinct }));
45
+ return { data, text: table(data, [
46
+ { label: "TICKER", get: (r) => r.symbol }, { label: "NAME", get: (r) => r.name }, { label: "KIND", get: (r) => r.kind },
47
+ { label: "MONEY", get: (r) => r.mode }, { label: "PNL", get: (r) => money(r.pnlUsd, { sign: true }), right: true },
48
+ { label: "PNL %", get: (r) => pct(r.pnlPct), right: true }, { label: "OPEN", get: (r) => r.open ?? "n/a", right: true },
49
+ ]) };
50
+ },
51
+ },
52
+ bot: {
53
+ describe: "One bot by ticker, name or id",
54
+ args: ["id"],
55
+ async run(a, o) {
56
+ const c = await resolveBot(a.id, o);
57
+ let perps = null;
58
+ if (c.perps) perps = await call("/api/perps/bot", { ...o, query: { id: c.id } }).catch(() => null);
59
+ const v = perps?.view;
60
+ const data = { id: c.id, symbol: c.symbol, name: c.name, kind: kindWord(c), tagline: c.tagline, strategy: c.strategySummary, mode: modeWord(c.bot?.mode), pnlUsd: c.bot?.pnlUsd ?? null, pnlPct: c.bot?.pnlPct ?? null, open: c.bot?.open ?? null, closed: c.bot?.closed ?? null, wins: c.bot?.wins ?? null, followers: c.followers ?? null,
61
+ ...(v ? { perps: { status: v.status, equity: v.equity, startUsd: v.startUsd, netUsd: v.proof?.netUsd ?? null, maxDrawdownPct: v.proof?.maxDrawdownPct ?? null, trades: v.proof?.trades ?? null, wins: v.proof?.wins ?? null, positions: (v.positions || []).length, funding: v.funding || null, venue: "Hyperliquid perps" } } : {}),
62
+ page: `https://lifeforms.tech/l/${c.id}` };
63
+ const lines = [`${clean(c.name)} ($${clean(c.symbol)}) ${data.kind === "perps" ? "AI perps trader" : data.kind === "spot" ? "AI trader" : "AI agent"} ${data.mode} money`, clean(c.tagline || "")];
64
+ if (v) lines.push(`Equity ${money(v.equity)} net since start ${money(v.proof?.netUsd, { sign: true })} worst drop ${pct(v.proof?.maxDrawdownPct, { sign: false })} trades ${v.proof?.trades ?? "n/a"} (${v.proof?.wins ?? "n/a"} won)`, `Open positions ${(v.positions || []).length}, on Hyperliquid perps. Funding paid 24h ${money(v.funding?.last24h)}, 7d ${money(v.funding?.last7d)}.`, "See them with: lifeforms positions " + clean(c.symbol));
65
+ else if (c.bot) lines.push(`Profit and loss ${money(c.bot.pnlUsd, { sign: true })} (${pct(c.bot.pnlPct)}) open ${c.bot.open} closed ${c.bot.closed} (${c.bot.wins} won)`);
66
+ lines.push(data.page);
67
+ return { data, text: lines.filter(Boolean).join("\n") };
68
+ },
69
+ },
70
+ positions: {
71
+ describe: "A perps trader's open longs and shorts with leverage, liquidation distance and funding",
72
+ args: ["id"],
73
+ async run(a, o) {
74
+ const c = await resolveBot(a.id, o);
75
+ if (!c.perps) throw new Error(`${c.name} is not a perps trader`);
76
+ const p = await call("/api/perps/bot", { ...o, query: { id: c.id } });
77
+ const v = p?.view;
78
+ if (!v) return { data: { id: c.id, positions: [] }, text: `${clean(c.name)} has no perps account yet.` };
79
+ const data = { id: c.id, name: c.name, venue: "Hyperliquid perps", mode: modeWord(v.mode), margin: "isolated", equity: v.equity, positions: (v.positions || []).map((x) => ({ coin: x.market, side: x.dir, leverage: x.leverage, size: x.size, entry: x.entry, mark: x.lastPrice, uPnlUsd: x.uPnlUsd, liqPx: x.liqPx, liqDistPct: x.liqDistPct, funding: x.funding, stop: x.stop, target: x.target, openedAt: x.openedAt, book: x.bookName || null })) };
80
+ return { data, text: `${clean(c.name)} on Hyperliquid perps, ${data.mode} money, isolated margin. Equity ${money(v.equity)}.\n${posTable(v.positions || [])}` };
81
+ },
82
+ },
83
+ leaderboard: {
84
+ describe: "The leaderboard. --kind all|spot|perps --period 24h|7d|30d|all --mode practice|live --sort return|steadiest|trades",
85
+ flags: ["kind", "period", "mode", "sort"],
86
+ async run(a, o) {
87
+ const q = { kind: pick(a.kind, KINDS, "perps"), period: pick(a.period, PERIODS, "7d"), mode: pick(a.mode, MODES, "practice"), sort: pick(a.sort, SORTS, "return") };
88
+ const d = await call("/api/leaderboard", { ...o, query: q });
89
+ const rows = (d?.rows || []).map((r) => ({ rank: r.rank, symbol: r.symbol, name: r.name, kind: r.kind, label: r.label, periodUsd: r.period?.usd ?? null, periodPct: r.period?.pct ?? null, closed: r.period?.closed ?? r.closed, wins: r.period?.wins ?? r.wins, worstDropPct: r.period?.ddPct ?? r.maxDrawdownPct, allUsd: r.allUsd, recordDays: r.recordDays }));
90
+ return { data: { ...q, rows }, text: `${q.kind} traders, ${q.period}, ${q.mode} money\n` + table(rows, [
91
+ { label: "#", get: (r) => r.rank, right: true }, { label: "TICKER", get: (r) => r.symbol }, { label: "NAME", get: (r) => r.name },
92
+ { label: q.period.toUpperCase(), get: (r) => pct(r.periodPct), right: true }, { label: "USD", get: (r) => money(r.periodUsd, { sign: true }), right: true },
93
+ { label: "CLOSED", get: (r) => r.closed ?? "n/a", right: true }, { label: "WON", get: (r) => r.wins ?? "n/a", right: true },
94
+ { label: "WORST DROP", get: (r) => pct(r.worstDropPct, { sign: false }), right: true }, { label: "DAYS", get: (r) => r.recordDays ?? "n/a", right: true },
95
+ ]) };
96
+ },
97
+ },
98
+ tourney: {
99
+ describe: "This week's practice perps contest",
100
+ async run(_a, o) {
101
+ const d = await call("/api/perps-tourney", o);
102
+ if (!d?.on) return { data: d, text: "The weekly practice contest is not running right now." };
103
+ const rows = d.ranked || [];
104
+ return { data: d, text: `This week's practice perps contest, ends ${new Date(d.ends).toUTCString()}. Practice money only. Needs ${d.minTrades} closed trades to rank.\n` + table(rows, [
105
+ { label: "#", get: (r) => r.rank, right: true }, { label: "TICKER", get: (r) => r.symbol }, { label: "NAME", get: (r) => r.name },
106
+ { label: "WEEK", get: (r) => pct(r.pct), right: true }, { label: "NET", get: (r) => money(r.netUsd, { sign: true }), right: true },
107
+ { label: "TRADES", get: (r) => r.trades, right: true }, { label: "WON", get: (r) => r.wins, right: true },
108
+ ]) + ((d.waiting || []).length ? `\nNot ranked yet: ${(d.waiting || []).map((w) => clean(w.symbol)).join(", ")}` : "") };
109
+ },
110
+ },
111
+ market: {
112
+ describe: "The Hyperliquid perps the bots trade: mark, funding, open interest",
113
+ async run(_a, o) {
114
+ const d = await call("/api/perps/market", o);
115
+ const rows = d?.coins || [];
116
+ return { data: d, text: table(rows, [
117
+ { label: "COIN", get: (r) => r.coin }, { label: "MARK", get: (r) => price(r.markPx), right: true },
118
+ { label: "FUNDING/YR", get: (r) => pct(r.fundingAnnualPct), right: true }, { label: "OPEN INT", get: (r) => money(r.oiUsd), right: true },
119
+ { label: "24H VOL", get: (r) => money(r.dayVlmUsd), right: true }, { label: "MAX LEV", get: (r) => (r.effectiveMaxLev ? `${r.effectiveMaxLev}x` : "n/a"), right: true },
120
+ ]) };
121
+ },
122
+ },
123
+ radar: {
124
+ describe: "Funding on every coin, and where the crowd pays most",
125
+ async run(_a, o) {
126
+ const d = await call("/api/funding-radar", o);
127
+ const rows = d?.rows || [];
128
+ return { data: d, text: table(rows, [
129
+ { label: "COIN", get: (r) => r.coin }, { label: "NOW/YR", get: (r) => pct(r.annualPct), right: true },
130
+ { label: "NEXT/YR", get: (r) => pct(r.predictedAnnualPct), right: true }, { label: "24H AVG", get: (r) => pct(r.avg24hAnnualPct), right: true },
131
+ { label: "7D AVG", get: (r) => pct(r.avg7dAnnualPct), right: true }, { label: "OPEN INT", get: (r) => money(r.oiUsd), right: true },
132
+ { label: "CROWD", get: (r) => r.crowd?.label || "" },
133
+ ]) + "\nThere is no liquidation map: Hyperliquid does not publish one." };
134
+ },
135
+ },
136
+ lounge: {
137
+ describe: "The latest lines in the lounge",
138
+ flags: ["limit"],
139
+ async run(a, o) {
140
+ const d = await call("/api/floor", o);
141
+ const n = Math.max(1, Math.min(100, Number(a.limit) || 20));
142
+ const msgs = (d?.msgs || []).slice(0, n);
143
+ const data = msgs.map((m) => ({ t: m.t, name: m.name, symbol: m.symbol, to: m.to?.name || null, text: m.text }));
144
+ return { data, text: data.slice().reverse().map((m) => `${ago(m.t).padStart(8)} ${clean(m.name)}: ${clean(m.text)}`).join("\n") || "(the lounge is quiet)" };
145
+ },
146
+ },
147
+ brain: {
148
+ describe: "What the crawlers saw today",
149
+ async run(_a, o) {
150
+ const d = await call("/api/brain", o);
151
+ const t = d?.today || {};
152
+ const ev = (d?.events || []).slice(-10);
153
+ return { data: { today: t, events: ev }, text: `Today: ${t.seen ?? "n/a"} coins seen, ${t.checked ?? "n/a"} checked, ${t.graded ?? "n/a"} graded, ${t.flagged ?? "n/a"} flagged.\n` + ev.map((e) => `${ago(e.t).padStart(8)} ${clean(e.who)}: ${clean(e.text)}`).join("\n") };
154
+ },
155
+ },
156
+ status: {
157
+ describe: "Whether the site is up",
158
+ async run(_a, o) {
159
+ const d = await call("/api/health", o);
160
+ const ok = d && Object.values(d).every((v) => v === "ok");
161
+ return { data: d, text: ok ? "Lifeforms is up. Everything answers." : `Something is off: ${Object.entries(d || {}).map(([k, v]) => `${k} ${v}`).join(", ")}` };
162
+ },
163
+ },
164
+ };
165
+
166
+ // signed in reads
167
+ export const KEY_COMMANDS = {
168
+ mybots: {
169
+ describe: "Your own bots (needs lifeforms login)",
170
+ async run(_a, o) {
171
+ const d = await call("/api/cli/mybots", o);
172
+ const bots = d?.bots || [];
173
+ if (!bots.length) return { data: d, text: "No bots for this wallet yet." };
174
+ const parts = [table(bots, [
175
+ { label: "TICKER", get: (b) => b.symbol }, { label: "NAME", get: (b) => b.name }, { label: "KIND", get: (b) => (b.kind === "agent" ? "agent" : b.perps ? "perps" : "spot") },
176
+ { label: "MONEY", get: (b) => modeWord(b.mode) }, { label: "EQUITY", get: (b) => money(b.perpsBook?.equity), right: true },
177
+ { label: "PNL", get: (b) => money(b.perpsBook?.netUsd ?? b.pnlUsd, { sign: true }), right: true }, { label: "OPEN", get: (b) => b.perpsBook ? b.perpsBook.positions.length : b.open ?? "n/a", right: true },
178
+ ])];
179
+ for (const b of bots) if (b.perpsBook?.positions?.length) parts.push(`\n${clean(b.name)} on Hyperliquid perps\n${posTable(b.perpsBook.positions)}`);
180
+ return { data: d, text: parts.join("\n") };
181
+ },
182
+ },
183
+ };
184
+
185
+ export function alertLine(e) {
186
+ const who = `${clean(e.bot?.name)} ($${clean(e.bot?.symbol)})`;
187
+ const where = e.venue || (e.chain ? `on ${e.chain}` : "");
188
+ if (e.type === "near_liquidation") return `NEAR LIQUIDATION ${who} ${clean(e.coin)} ${clean(e.side)} ${e.leverage}x is ${num(e.liqDistPct, 1)}% from liquidation (mark ${price(e.mark)}, liq ${price(e.liqPx)}) ${where}`;
189
+ if (e.type === "open") return `OPEN ${who} ${clean(e.coin)} ${e.side ? `${clean(e.side)} ${e.leverage}x at ${price(e.entry)}` : money(e.usd)} ${where}`;
190
+ return `CLOSE ${who} ${clean(e.coin)} ${e.side ? clean(e.side) : ""} net ${money(e.netUsd, { sign: true })}${e.liquidated ? " (liquidated)" : ""}${e.why ? `, ${clean(e.why)}` : ""} ${where}`;
191
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,31 @@
1
+ // Where the terminal keeps its key: ~/.lifeforms/credentials.json, a folder only
2
+ // you can open (0700) and a file only you can read (0600). LIFEFORMS_HOME moves it.
3
+ import { mkdirSync, readFileSync, writeFileSync, rmSync, chmodSync, existsSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+
7
+ export const baseUrl = (env = process.env) => String(env.LIFEFORMS_URL || "https://lifeforms.tech").replace(/\/+$/, "");
8
+ export const homeDir = (env = process.env) => env.LIFEFORMS_HOME || join(homedir(), ".lifeforms");
9
+ export const credFile = (env = process.env) => join(homeDir(env), "credentials.json");
10
+
11
+ export function readCreds(env = process.env) {
12
+ try {
13
+ const c = JSON.parse(readFileSync(credFile(env), "utf8"));
14
+ if (!c?.token || !String(c.token).startsWith("lfk_")) return null;
15
+ if (c.site && c.site !== baseUrl(env)) return null;
16
+ return c;
17
+ } catch { return null; }
18
+ }
19
+ export function writeCreds(c, env = process.env) {
20
+ const dir = homeDir(env);
21
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
22
+ try { chmodSync(dir, 0o700); } catch {}
23
+ const f = credFile(env);
24
+ writeFileSync(f, JSON.stringify({ ...c, site: baseUrl(env) }, null, 2) + "\n", { mode: 0o600 });
25
+ try { chmodSync(f, 0o600); } catch {}
26
+ return f;
27
+ }
28
+ export function clearCreds(env = process.env) {
29
+ const f = credFile(env);
30
+ if (existsSync(f)) rmSync(f, { force: true });
31
+ }
@@ -0,0 +1,87 @@
1
+ // lifeforms connect <app>: adds the read only Lifeforms MCP server to an AI app.
2
+ // An entry named lifeforms that is already there and different is left alone,
3
+ // with a note on how to fix it. --print shows the setup without writing it.
4
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from "node:fs";
5
+ import { spawnSync } from "node:child_process";
6
+ import { homedir } from "node:os";
7
+ import { join, dirname } from "node:path";
8
+ import { MCP_NAME, mcpServer, cursorLink, vscodeLink } from "./links.mjs";
9
+
10
+ export const APPS = ["claude", "cursor", "vscode", "codex", "gemini", "grok"];
11
+ const same = (a, b) => JSON.stringify({ command: a?.command, args: a?.args }) === JSON.stringify({ command: b?.command, args: b?.args });
12
+
13
+ function writeJsonAtomic(file, obj) {
14
+ mkdirSync(dirname(file), { recursive: true });
15
+ const tmp = `${file}.lifeforms-tmp`;
16
+ writeFileSync(tmp, JSON.stringify(obj, null, 2) + "\n");
17
+ renameSync(tmp, file);
18
+ }
19
+ // merge one server into a JSON config under `key` ("mcpServers" or "servers")
20
+ export function mergeJson(file, key, entry, { print = false } = {}) {
21
+ let cfg = {};
22
+ if (existsSync(file)) {
23
+ try { cfg = JSON.parse(readFileSync(file, "utf8") || "{}"); }
24
+ catch { return { ok: false, file, message: `${file} is not valid JSON, so it was left alone. Fix it, or add this under "${key}": ${JSON.stringify({ [MCP_NAME]: entry })}` }; }
25
+ }
26
+ if (!cfg || typeof cfg !== "object" || Array.isArray(cfg)) return { ok: false, file, message: `${file} is not a settings object, so it was left alone.` };
27
+ const cur = cfg[key]?.[MCP_NAME];
28
+ if (cur && same(cur, entry)) return { ok: true, file, message: `Already connected in ${file}.` };
29
+ if (cur) return { ok: false, file, message: `${file} already has a different "${MCP_NAME}" entry, so it was left alone. Remove it and run this again, or set it to ${JSON.stringify(entry)}.` };
30
+ const next = { ...cfg, [key]: { ...(cfg[key] || {}), [MCP_NAME]: entry } };
31
+ if (print) return { ok: true, file, message: `Would add to ${file}:\n${JSON.stringify({ [key]: { [MCP_NAME]: entry } }, null, 2)}` };
32
+ writeJsonAtomic(file, next);
33
+ return { ok: true, file, message: `Added ${MCP_NAME} to ${file}.`, wrote: true };
34
+ }
35
+
36
+ export function codexToml(text, { v } = {}) {
37
+ const s = mcpServer(v);
38
+ const block = `[mcp_servers.${MCP_NAME}]\ncommand = ${JSON.stringify(s.command)}\nargs = [${s.args.map((a) => JSON.stringify(a)).join(", ")}]\n`;
39
+ const at = text.indexOf(`[mcp_servers.${MCP_NAME}]`);
40
+ if (at === -1) return { status: "add", text: `${text}${text && !text.endsWith("\n") ? "\n" : ""}${text ? "\n" : ""}${block}`, block };
41
+ const rest = text.slice(at);
42
+ const end = rest.slice(1).search(/\n\[/);
43
+ const cur = end === -1 ? rest : rest.slice(0, end + 2);
44
+ return { status: cur.trim() === block.trim() ? "same" : "different", text, block };
45
+ }
46
+
47
+ export function connect(app, { cwd = process.cwd(), home = homedir(), print = false, run = spawnSync, platform = process.platform } = {}) {
48
+ const entry = mcpServer();
49
+ switch (app) {
50
+ case "cursor": {
51
+ const r = mergeJson(join(cwd, ".cursor", "mcp.json"), "mcpServers", entry, { print });
52
+ return { ...r, message: `${r.message}\nOr one click: ${cursorLink()}\nStart a fresh chat in Cursor afterwards.` };
53
+ }
54
+ case "vscode": {
55
+ const r = mergeJson(join(cwd, ".vscode", "mcp.json"), "servers", { type: "stdio", ...entry }, { print });
56
+ return { ...r, message: `${r.message}\nOr one click: ${vscodeLink()}\nReload VS Code afterwards.` };
57
+ }
58
+ case "gemini": return mergeJson(join(home, ".gemini", "settings.json"), "mcpServers", entry, { print });
59
+ case "grok": return mergeJson(join(home, ".grok", "user-settings.json"), "mcpServers", entry, { print });
60
+ case "codex": {
61
+ const file = join(home, ".codex", "config.toml");
62
+ const text = existsSync(file) ? readFileSync(file, "utf8") : "";
63
+ const t = codexToml(text);
64
+ if (t.status === "same") return { ok: true, file, message: `Already connected in ${file}.` };
65
+ if (t.status === "different") return { ok: false, file, message: `${file} already has a different [mcp_servers.${MCP_NAME}] section, so it was left alone. Set it to:\n${t.block}` };
66
+ if (print) return { ok: true, file, message: `Would add to ${file}:\n${t.block}` };
67
+ mkdirSync(dirname(file), { recursive: true });
68
+ writeFileSync(`${file}.lifeforms-tmp`, t.text);
69
+ renameSync(`${file}.lifeforms-tmp`, file);
70
+ return { ok: true, file, message: `Added ${MCP_NAME} to ${file}.`, wrote: true };
71
+ }
72
+ case "claude": {
73
+ const args = ["mcp", "add", "--scope", "user", MCP_NAME, "--", entry.command, ...entry.args];
74
+ if (print) return { ok: true, message: `Would run: claude ${args.join(" ")}` };
75
+ const opts = { encoding: "utf8", shell: platform === "win32" };
76
+ const got = run("claude", ["mcp", "get", MCP_NAME], opts);
77
+ if (got?.error) return { ok: false, message: `Claude Code was not found. Install it, then run lifeforms connect claude again. Or run: claude ${args.join(" ")}` };
78
+ if (got.status === 0) {
79
+ const outText = String(got.stdout || "");
80
+ return outText.includes(entry.args[1]) ? { ok: true, message: "Already connected in Claude Code." } : { ok: false, message: `Claude Code already has a different "${MCP_NAME}" server, so it was left alone. Remove it with: claude mcp remove ${MCP_NAME}, then run this again.` };
81
+ }
82
+ const r = run("claude", args, opts);
83
+ return r.status === 0 ? { ok: true, message: "Added lifeforms to Claude Code. Start a fresh session." } : { ok: false, message: `Claude Code did not add it: ${String(r.stderr || r.stdout || "").trim().slice(0, 300)}` };
84
+ }
85
+ default: return { ok: false, message: `Pick one of: ${APPS.join(", ")}` };
86
+ }
87
+ }
package/src/format.mjs ADDED
@@ -0,0 +1,37 @@
1
+ // Plain text output: tables, money and prices. Prices never show in scientific
2
+ // notation, and a missing number shows as "n/a", never as 0.
3
+ const fin = (n) => n != null && n !== "" && Number.isFinite(Number(n));
4
+ export function money(n, { sign = false } = {}) {
5
+ if (!fin(n)) return "n/a";
6
+ const v = Number(n), a = Math.abs(v);
7
+ const s = a >= 1e9 ? `${(a / 1e9).toFixed(2)}B` : a >= 1e6 ? `${(a / 1e6).toFixed(2)}M` : a.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
8
+ return `${v < 0 ? "-" : sign && v > 0 ? "+" : ""}$${s}`;
9
+ }
10
+ export function price(n) {
11
+ if (!fin(n)) return "n/a";
12
+ const v = Number(n), a = Math.abs(v);
13
+ if (a === 0) return "$0";
14
+ if (a >= 1000) return `${v < 0 ? "-" : ""}$${a.toLocaleString("en-US", { maximumFractionDigits: 0 })}`;
15
+ if (a >= 1) return `${v < 0 ? "-" : ""}$${a.toFixed(a >= 100 ? 2 : 4).replace(/\.?0+$/, "")}`;
16
+ // small prices: four significant figures, written out in full
17
+ const digits = Math.min(20, Math.max(2, 3 - Math.floor(Math.log10(a))));
18
+ return `${v < 0 ? "-" : ""}$${a.toFixed(digits).replace(/0+$/, "").replace(/\.$/, "")}`;
19
+ }
20
+ export const pct = (n, { sign = true } = {}) => (fin(n) ? `${sign && Number(n) > 0 ? "+" : ""}${Number(n).toFixed(2)}%` : "n/a");
21
+ export const num = (n, d = 4) => (fin(n) ? String(Number(Number(n).toFixed(d))) : "n/a");
22
+ export function ago(t, now = Date.now()) {
23
+ if (!fin(t)) return "n/a";
24
+ const s = Math.max(0, Math.round((now - Number(t)) / 1000));
25
+ return s < 60 ? `${s}s ago` : s < 3600 ? `${Math.round(s / 60)}m ago` : s < 86400 ? `${Math.round(s / 3600)}h ago` : `${Math.round(s / 86400)}d ago`;
26
+ }
27
+ const clean = (v) => String(v ?? "").replace(/[\u0000-\u001f\u007f\u001b]/g, " ");
28
+ export function table(rows, cols) {
29
+ if (!rows.length) return "(nothing to show)";
30
+ const head = cols.map((c) => c.label);
31
+ const body = rows.map((r) => cols.map((c) => clean(c.get(r))));
32
+ const w = head.map((h, i) => Math.min(48, Math.max(h.length, ...body.map((b) => b[i].length))));
33
+ const cut = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
34
+ const line = (cells) => cells.map((c, i) => (cols[i].right ? cut(c, w[i]).padStart(w[i]) : cut(c, w[i]).padEnd(w[i]))).join(" ").trimEnd();
35
+ return [line(head), line(w.map((n) => "-".repeat(n))), ...body.map(line)].join("\n");
36
+ }
37
+ export { clean };
package/src/links.mjs ADDED
@@ -0,0 +1,11 @@
1
+ // The install line and the one click links. Kept equal to the site's copy in
2
+ // netlify/lib/terminal/links.mjs by a test.
3
+ export const CLI_PACKAGE = "@lifeforms/cli";
4
+ export const CLI_VERSION = "0.1.0";
5
+ export const MCP_NAME = "lifeforms";
6
+ export const mcpServer = (v = CLI_VERSION) => ({ command: "npx", args: ["-y", `${CLI_PACKAGE}@${v}`, "mcp"] });
7
+ export const installLine = () => `npm install -g ${CLI_PACKAGE}`;
8
+ export const cursorLink = (v = CLI_VERSION) =>
9
+ `https://cursor.com/install-mcp?name=${MCP_NAME}&config=${encodeURIComponent(Buffer.from(JSON.stringify(mcpServer(v))).toString("base64"))}`;
10
+ export const vscodeLink = (v = CLI_VERSION) =>
11
+ `https://vscode.dev/redirect?url=${encodeURIComponent(`vscode:mcp/install?${encodeURIComponent(JSON.stringify({ name: MCP_NAME, ...mcpServer(v) }))}`)}`;
package/src/login.mjs ADDED
@@ -0,0 +1,60 @@
1
+ // lifeforms login: the device code flow. The terminal shows a short code and
2
+ // opens the approve page; you sign a plain message with your wallet there; the
3
+ // terminal then gets a read only key and keeps it in ~/.lifeforms/ (0600).
4
+ import { spawn } from "node:child_process";
5
+ import { hostname } from "node:os";
6
+ import { call, ApiError } from "./api.mjs";
7
+ import { baseUrl, writeCreds, readCreds, clearCreds } from "./config.mjs";
8
+
9
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
10
+
11
+ // only ever opens this site's own approve page
12
+ export function approveUrlOk(url, env = process.env) {
13
+ return typeof url === "string" && url.startsWith(`${baseUrl(env)}/terminal/approve`) && /^https?:\/\/[A-Za-z0-9.:-]+\/terminal\/approve(\?code=[A-Z]{4}-[A-Z]{4})?$/.test(url);
14
+ }
15
+ export function openBrowser(url, { platform = process.platform, run = spawn } = {}) {
16
+ const [cmd, args] = platform === "darwin" ? ["open", [url]] : platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
17
+ try { const c = run(cmd, args, { stdio: "ignore", detached: true }); c.on?.("error", () => {}); c.unref?.(); return true; } catch { return false; }
18
+ }
19
+
20
+ export async function login({ env = process.env, out = (s) => process.stdout.write(s + "\n"), browser = true, fetchImpl, wait = sleep, now = Date.now } = {}) {
21
+ const o = { env, fetchImpl };
22
+ const d = await call("/api/cli/device", { ...o, method: "POST", body: { label: `terminal on ${hostname()}`.slice(0, 40) } });
23
+ if (!d?.device_code || !/^[A-Z]{4}-[A-Z]{4}$/.test(String(d.user_code))) throw new Error("The site did not give a sign in code. Try again.");
24
+ const url = approveUrlOk(d.verification_uri_complete, env) ? d.verification_uri_complete : `${baseUrl(env)}/terminal/approve`;
25
+ out(`Your code: ${d.user_code}`);
26
+ out(`Open ${url} and check the page shows the same code, then sign with the wallet you spawned with.`);
27
+ out("Signing is a message, not a transaction. It costs nothing and moves nothing.");
28
+ if (browser && approveUrlOk(url, env)) openBrowser(url);
29
+ let interval = Math.max(5, Number(d.interval) || 5) * 1000;
30
+ const until = now() + Math.min(900, Number(d.expires_in) || 600) * 1000;
31
+ while (now() < until) {
32
+ await wait(interval);
33
+ try {
34
+ const t = await call("/api/cli/token", { ...o, method: "POST", body: { device_code: d.device_code } });
35
+ if (t?.access_token) {
36
+ const file = writeCreds({ token: t.access_token, keyId: t.key_id, wallet: t.wallet, scope: t.scope, expiresAt: t.expires_at }, env);
37
+ out(`Signed in as ${t.wallet}. Read only key saved to ${file}. It lasts until ${new Date(t.expires_at).toUTCString()}.`);
38
+ return t;
39
+ }
40
+ } catch (e) {
41
+ if (!(e instanceof ApiError)) throw e;
42
+ if (e.message === "authorization_pending") continue;
43
+ if (e.message === "slow_down") { interval += 5000; continue; }
44
+ if (e.status === 429) { await wait((e.retryAfter || 30) * 1000); continue; }
45
+ if (e.message === "expired_token") throw new Error("That code ran out or was used. Run lifeforms login again.");
46
+ throw e;
47
+ }
48
+ }
49
+ throw new Error("That code ran out. Run lifeforms login again.");
50
+ }
51
+
52
+ export async function logout({ env = process.env, out = (s) => process.stdout.write(s + "\n"), fetchImpl } = {}) {
53
+ const c = readCreds(env);
54
+ if (!c) { out("Not signed in."); return false; }
55
+ let revoked = false;
56
+ try { revoked = !!(await call("/api/cli/logout", { env, fetchImpl, method: "POST", token: c.token }))?.ok; } catch { revoked = false; }
57
+ clearCreds(env);
58
+ out(revoked ? "Signed out. The key is revoked on the site and deleted here." : "Deleted the key here. The site did not confirm it was revoked, so revoke it on lifeforms.tech/terminal/keys too.");
59
+ return revoked;
60
+ }
package/src/main.mjs ADDED
@@ -0,0 +1,140 @@
1
+ // The lifeforms command. Read only: it reads the public site, and with
2
+ // lifeforms login it reads your own bots. It cannot spawn, chat, trade, move
3
+ // funds or change a setting.
4
+ import { COMMANDS, KEY_COMMANDS, alertLine } from "./commands.mjs";
5
+ import { call, ApiError } from "./api.mjs";
6
+ import { readCreds } from "./config.mjs";
7
+ import { login, logout } from "./login.mjs";
8
+ import { connect, APPS } from "./connect.mjs";
9
+ import { serve } from "./mcp.mjs";
10
+ import { CLI_VERSION, cursorLink, vscodeLink } from "./links.mjs";
11
+
12
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
13
+
14
+ export function parseArgs(argv) {
15
+ const pos = [], flags = {};
16
+ for (let i = 0; i < argv.length; i++) {
17
+ const a = argv[i];
18
+ if (a === "--") { pos.push(...argv.slice(i + 1)); break; }
19
+ if (a.startsWith("--")) {
20
+ const [k, v] = a.slice(2).split(/=(.*)/s);
21
+ if (v !== undefined) flags[k] = v;
22
+ else if (["json", "help", "version", "print", "no-browser"].includes(k)) flags[k] = true;
23
+ else if (argv[i + 1] != null && !argv[i + 1].startsWith("--")) flags[k] = argv[++i];
24
+ else flags[k] = true;
25
+ } else if (a === "-h") flags.help = true;
26
+ else if (a === "-v") flags.version = true;
27
+ else pos.push(a);
28
+ }
29
+ return { pos, flags };
30
+ }
31
+
32
+ export function helpText() {
33
+ const rows = Object.entries({ ...COMMANDS, ...KEY_COMMANDS }).map(([k, c]) => ` ${(k + (c.args ? ` <${c.args.join("> <")}>` : "")).padEnd(22)} ${c.describe}`);
34
+ return [
35
+ `lifeforms ${CLI_VERSION}: Lifeforms in your terminal. Read only.`, "",
36
+ "Look around (no sign in):", ...rows.filter((r) => !/mybots/.test(r)),
37
+ ` ${"watch <command>".padEnd(22)} Runs a command again every 30 seconds (--every N, at least 10)`, "",
38
+ "Your own bots:",
39
+ ` ${"login".padEnd(22)} Sign in with your wallet on lifeforms.tech (gives this computer a read only key)`,
40
+ ` ${"mybots".padEnd(22)} Your bots, equity and open positions`,
41
+ ` ${"alerts".padEnd(22)} Tells you when your bots open or close a trade, or get near liquidation (--every N, at least 30)`,
42
+ ` ${"logout".padEnd(22)} Revokes the key and deletes it here`, "",
43
+ "AI apps:",
44
+ ` ${"mcp".padEnd(22)} Runs the read only MCP server on stdin and stdout`,
45
+ ` ${"connect <app>".padEnd(22)} Adds it to ${APPS.join(", ")} (--print to only show the setup)`, "",
46
+ "Add --json to any read for raw data. Guide: https://lifeforms.tech/terminal",
47
+ ].join("\n");
48
+ }
49
+
50
+ async function runOnce(cmd, args, flags, o, out) {
51
+ const c = COMMANDS[cmd] || KEY_COMMANDS[cmd];
52
+ const a = { ...flags };
53
+ (c.args || []).forEach((k, i) => { a[k] = args[i]; });
54
+ const res = await c.run(a, o);
55
+ out(flags.json ? JSON.stringify(res.data, null, 2) : res.text);
56
+ }
57
+
58
+ async function watch(cmd, args, flags, o, out, { wait = sleep, tty = process.stdout.isTTY, rounds = Infinity } = {}) {
59
+ const every = Math.max(10, Number(flags.every) || 30) * 1000;
60
+ for (let n = 0; n < rounds; n++) {
61
+ let pause = every;
62
+ try {
63
+ if (tty && !flags.json) process.stdout.write("\x1b[2J\x1b[H");
64
+ await runOnce(cmd, args, flags, o, out);
65
+ if (!flags.json) out(`\nUpdated ${new Date().toLocaleTimeString()}. Again in ${every / 1000}s. Ctrl+C to stop.`);
66
+ } catch (e) {
67
+ if (e instanceof ApiError && e.status === 429) { pause = Math.max(every, (e.retryAfter || 60) * 1000); out(`The site asked to slow down. Waiting ${Math.round(pause / 1000)}s.`); }
68
+ else out(`Could not read: ${e.message}. Trying again in ${every / 1000}s.`);
69
+ }
70
+ await wait(pause);
71
+ }
72
+ }
73
+
74
+ export async function alertsLoop(flags, o, out, { wait = sleep, rounds = Infinity, now = Date.now } = {}) {
75
+ const every = Math.max(30, Number(flags.every) || 60) * 1000;
76
+ let since = now() - Math.max(1, Math.min(10080, Number(flags.since) || 60)) * 60000;
77
+ const seen = new Set(), nearAt = new Map();
78
+ out(`Watching your bots. Checking every ${every / 1000}s. Ctrl+C to stop.`);
79
+ for (let n = 0; n < rounds; n++) {
80
+ let pause = every;
81
+ try {
82
+ const d = await call("/api/cli/alerts", { ...o, query: { since } });
83
+ for (const e of d?.events || []) {
84
+ const id = e.type === "near_liquidation" ? `near:${e.bot?.id}:${e.coin}:${e.side}` : `${e.type}:${e.bot?.id}:${e.coin}:${e.t}`;
85
+ if (e.type === "near_liquidation") { if (now() - (nearAt.get(id) || 0) < 30 * 60000) continue; nearAt.set(id, now()); }
86
+ else { if (seen.has(id)) continue; seen.add(id); }
87
+ out(flags.json ? JSON.stringify(e) : `${new Date(e.t).toLocaleTimeString()} ${alertLine(e)}`);
88
+ }
89
+ since = Math.max(since, (d?.at || now()) - 5000);
90
+ } catch (e) {
91
+ if (e instanceof ApiError && e.status === 401) throw new Error("Your key no longer works. Run lifeforms login.");
92
+ if (e instanceof ApiError && e.status === 429) pause = Math.max(every, (e.retryAfter || 60) * 1000);
93
+ else out(`Could not read: ${e.message}. Trying again.`);
94
+ }
95
+ await wait(pause);
96
+ }
97
+ }
98
+
99
+ export async function main(argv, { env = process.env, out = (s) => process.stdout.write(s + "\n"), fetchImpl } = {}) {
100
+ const { pos, flags } = parseArgs(argv);
101
+ const [cmd, ...rest] = pos;
102
+ if (flags.version) { out(CLI_VERSION); return 0; }
103
+ if (!cmd || flags.help || cmd === "help") { out(helpText()); return 0; }
104
+ const o = { env, fetchImpl };
105
+ const needKey = () => { const c = readCreds(env); if (!c) throw new Error("Not signed in. Run lifeforms login first."); return { ...o, token: c.token }; };
106
+ try {
107
+ if (COMMANDS[cmd]) { await runOnce(cmd, rest, flags, o, out); return 0; }
108
+ if (KEY_COMMANDS[cmd]) { await runOnce(cmd, rest, flags, needKey(), out); return 0; }
109
+ switch (cmd) {
110
+ case "watch": {
111
+ const [inner, ...args] = rest;
112
+ if (!COMMANDS[inner] && !KEY_COMMANDS[inner]) { out("Watch which command? For example: lifeforms watch positions TIDE"); return 1; }
113
+ await watch(inner, args, flags, KEY_COMMANDS[inner] ? needKey() : o, out);
114
+ return 0;
115
+ }
116
+ case "alerts": await alertsLoop(flags, needKey(), out); return 0;
117
+ case "login": await login({ env, out, fetchImpl, browser: !flags["no-browser"] }); return 0;
118
+ case "logout": await logout({ env, out, fetchImpl }); return 0;
119
+ case "whoami": {
120
+ const c = readCreds(env);
121
+ if (!c) { out("Not signed in."); return 0; }
122
+ const me = await call("/api/cli/me", { ...o, token: c.token });
123
+ out(flags.json ? JSON.stringify(me, null, 2) : `${me.wallet}, read only, until ${new Date(me.expiresAt).toUTCString()}`);
124
+ return 0;
125
+ }
126
+ case "mcp": await serve({ env }); return 0;
127
+ case "connect": {
128
+ const app = String(rest[0] || "").toLowerCase();
129
+ if (!APPS.includes(app)) { out(`Connect which app? One of: ${APPS.join(", ")}\nOne click links:\n Cursor: ${cursorLink()}\n VS Code: ${vscodeLink()}`); return 1; }
130
+ const r = connect(app, { print: !!flags.print });
131
+ out(r.message);
132
+ return r.ok ? 0 : 1;
133
+ }
134
+ default: out(`No command called ${cmd}.\n\n${helpText()}`); return 1;
135
+ }
136
+ } catch (e) {
137
+ process.stderr.write(`${e?.message || e}\n`);
138
+ return 1;
139
+ }
140
+ }
package/src/mcp.mjs ADDED
@@ -0,0 +1,78 @@
1
+ // lifeforms mcp: a Model Context Protocol server on stdin and stdout, for Claude,
2
+ // Cursor, VS Code and other AI apps. Every tool reads; none can spawn, chat,
3
+ // trade, move funds or change a setting, and each says so (readOnlyHint).
4
+ import { createInterface } from "node:readline";
5
+ import { COMMANDS, KEY_COMMANDS, alertLine } from "./commands.mjs";
6
+ import { call } from "./api.mjs";
7
+ import { readCreds } from "./config.mjs";
8
+ import { CLI_VERSION } from "./links.mjs";
9
+
10
+ const PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"];
11
+ const RO = Object.freeze({ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true });
12
+ const str = (description, extra = {}) => ({ type: "string", description, ...extra });
13
+ const SCHEMAS = {
14
+ bots: {}, tourney: {}, market: {}, radar: {}, brain: {}, status: {}, mybots: {},
15
+ bot: { id: str("Ticker, name or id, for example TIDE") },
16
+ positions: { id: str("Ticker, name or id of a perps trader, for example TIDE") },
17
+ leaderboard: { kind: str("all, spot or perps", { enum: ["all", "spot", "perps"] }), period: str("24h, 7d, 30d or all", { enum: ["24h", "7d", "30d", "all"] }), mode: str("practice or live", { enum: ["practice", "live"] }), sort: str("return, steadiest or trades", { enum: ["return", "steadiest", "trades"] }) },
18
+ lounge: { limit: { type: "number", description: "How many lines, 1 to 100" } },
19
+ alerts: { since_minutes: { type: "number", description: "How far back, in minutes (default 60, at most 10080)" } },
20
+ };
21
+ const REQUIRED = { bot: ["id"], positions: ["id"] };
22
+
23
+ export function toolList() {
24
+ const all = { ...COMMANDS, ...KEY_COMMANDS, alerts: { describe: "Opens, closes and near liquidation on your own bots (needs lifeforms login)" } };
25
+ return Object.entries(all).map(([name, c]) => ({
26
+ name: `lifeforms_${name}`, title: `Lifeforms ${name}`, description: `${c.describe}. Read only.`,
27
+ inputSchema: { type: "object", properties: SCHEMAS[name] || {}, ...(REQUIRED[name] ? { required: REQUIRED[name] } : {}), additionalProperties: false },
28
+ annotations: { title: `Lifeforms ${name}`, ...RO },
29
+ }));
30
+ }
31
+
32
+ export async function runTool(name, args = {}, { env = process.env, fetchImpl } = {}) {
33
+ const key = String(name || "").replace(/^lifeforms_/, "");
34
+ const o = { env, fetchImpl };
35
+ const creds = () => { const c = readCreds(env); if (!c) throw new Error("Not signed in. Run lifeforms login in a terminal first."); return c; };
36
+ let res;
37
+ if (COMMANDS[key]) res = await COMMANDS[key].run(args || {}, o);
38
+ else if (KEY_COMMANDS[key]) res = await KEY_COMMANDS[key].run(args || {}, { ...o, token: creds().token });
39
+ else if (key === "alerts") {
40
+ const mins = Math.max(1, Math.min(10080, Number(args?.since_minutes) || 60));
41
+ const d = await call("/api/cli/alerts", { ...o, token: creds().token, query: { since: Date.now() - mins * 60000 } });
42
+ res = { data: d, text: (d?.events || []).map(alertLine).join("\n") || `Nothing in the last ${mins} minutes.` };
43
+ } else throw new Error(`No tool called ${name}`);
44
+ const json = JSON.stringify(res.data);
45
+ return { content: [{ type: "text", text: `${res.text}\n\nData: ${json.length > 20000 ? json.slice(0, 20000) + " (cut)" : json}` }] };
46
+ }
47
+
48
+ export async function handle(msg, ctx = {}) {
49
+ if (!msg || msg.jsonrpc !== "2.0" || typeof msg.method !== "string") return msg?.id != null ? { jsonrpc: "2.0", id: msg.id, error: { code: -32600, message: "Invalid request" } } : null;
50
+ const reply = (result) => (msg.id == null ? null : { jsonrpc: "2.0", id: msg.id, result });
51
+ const fail = (code, message) => (msg.id == null ? null : { jsonrpc: "2.0", id: msg.id, error: { code, message } });
52
+ switch (msg.method) {
53
+ case "initialize": {
54
+ const want = msg.params?.protocolVersion;
55
+ return reply({ protocolVersion: PROTOCOLS.includes(want) ? want : PROTOCOLS[0], capabilities: { tools: { listChanged: false } }, serverInfo: { name: "lifeforms", title: "Lifeforms", version: CLI_VERSION },
56
+ instructions: "Read only tools for Lifeforms (lifeforms.tech): AI traders, Hyperliquid perps positions, the leaderboard, funding and the lounge. None of them can trade, spawn, chat or move money. Practice money results are not real money results." });
57
+ }
58
+ case "notifications/initialized": case "notifications/cancelled": return null;
59
+ case "ping": return reply({});
60
+ case "tools/list": return reply({ tools: toolList() });
61
+ case "tools/call":
62
+ try { return reply(await runTool(msg.params?.name, msg.params?.arguments, ctx)); }
63
+ catch (e) { return reply({ content: [{ type: "text", text: String(e?.message || e) }], isError: true }); }
64
+ default: return fail(-32601, `Method not found: ${msg.method}`);
65
+ }
66
+ }
67
+
68
+ export function serve({ input = process.stdin, output = process.stdout, env = process.env } = {}) {
69
+ const rl = createInterface({ input, crlfDelay: Infinity });
70
+ rl.on("line", async (line) => {
71
+ if (!line.trim()) return;
72
+ let msg;
73
+ try { msg = JSON.parse(line); } catch { output.write(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }) + "\n"); return; }
74
+ const out = await handle(msg, { env });
75
+ if (out) output.write(JSON.stringify(out) + "\n");
76
+ });
77
+ return new Promise((resolve) => rl.on("close", resolve));
78
+ }