elythia-cli 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -3
- package/bin/elythia.js +320 -0
- package/package.json +32 -4
- package/src/agent.js +106 -0
- package/src/api.js +47 -0
- package/src/art.js +247 -0
- package/src/config.js +41 -0
- package/src/defaults.js +1 -0
- package/src/home.js +82 -0
- package/src/login.js +115 -0
- package/src/miner.js +448 -0
- package/src/ui.js +191 -0
package/src/miner.js
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { emitKeypressEvents } from 'node:readline';
|
|
2
|
+
import { ALTAR_HEIGHT, ALTAR_WIDTH, altarFrame, sparkOrigin } from './art.js';
|
|
3
|
+
import {
|
|
4
|
+
SPINNER, TICKER, c, chip, clearScreen, clock, columns, countdown, drawCentered, enterFullScreen, fit, formatCoin,
|
|
5
|
+
formatDuration, formatNumber, hideCursor, isTTY, key, label, leaveFullScreen, padEnd,
|
|
6
|
+
showCursor, slab, sleep, sparkline, spread, tablet, timestamp,
|
|
7
|
+
} from './ui.js';
|
|
8
|
+
|
|
9
|
+
const FRAME_MS = 80;
|
|
10
|
+
const DEFAULT_HEARTBEAT_MS = 20_000;
|
|
11
|
+
const SNAPSHOT_REFRESH_MS = 3_000;
|
|
12
|
+
const NON_TTY_STATUS_MS = 60_000;
|
|
13
|
+
const FLASH_MS = 1_800;
|
|
14
|
+
const EMBER_MS = 260;
|
|
15
|
+
const LETTERS = ['A', 'B', 'C', 'D'];
|
|
16
|
+
const MAX_EVENTS = 3;
|
|
17
|
+
|
|
18
|
+
const pluralize = (count, word) => `${formatNumber(count)} ${word}${count === 1 ? '' : 's'}`;
|
|
19
|
+
|
|
20
|
+
// Wraps plain text to a width, at word boundaries.
|
|
21
|
+
function wrap(text, width, maxLines = 3) {
|
|
22
|
+
const lines = [];
|
|
23
|
+
let line = '';
|
|
24
|
+
for (const word of String(text).split(/\s+/)) {
|
|
25
|
+
if (line && (line + ' ' + word).length > width) {
|
|
26
|
+
lines.push(line);
|
|
27
|
+
line = word;
|
|
28
|
+
} else {
|
|
29
|
+
line = line ? `${line} ${word}` : word;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (line) lines.push(line);
|
|
33
|
+
return lines.length > maxLines ? [...lines.slice(0, maxLines - 1), fit(lines.slice(maxLines - 1).join(' '), width)] : lines;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const AGENT_ATTEMPTS = 3;
|
|
37
|
+
const AGENT_RETRY_MS = 2_500;
|
|
38
|
+
|
|
39
|
+
// One round = one riddle from the Oracle. No hashing: the altar only keeps a heartbeat going so
|
|
40
|
+
// the server hands it a riddle every round, and the seeker's AI agent answers it. A true answer
|
|
41
|
+
// pays a random reward straight away. (The server still calls a riddle a "rock".)
|
|
42
|
+
export function startDivining({ client, username, initialBalance, agent }) {
|
|
43
|
+
const interactive = isTTY && process.stdin.isTTY;
|
|
44
|
+
|
|
45
|
+
const state = {
|
|
46
|
+
online: false,
|
|
47
|
+
beating: false,
|
|
48
|
+
heartbeatAt: 0,
|
|
49
|
+
heartbeatMs: DEFAULT_HEARTBEAT_MS,
|
|
50
|
+
balance: initialBalance,
|
|
51
|
+
round: null,
|
|
52
|
+
rock: null,
|
|
53
|
+
answering: false,
|
|
54
|
+
agentRound: null,
|
|
55
|
+
agentStartedAt: 0,
|
|
56
|
+
seenPayoutRound: null,
|
|
57
|
+
snapshotAt: 0,
|
|
58
|
+
earned: 0,
|
|
59
|
+
payouts: 0,
|
|
60
|
+
correct: 0,
|
|
61
|
+
wrong: 0,
|
|
62
|
+
streak: 0,
|
|
63
|
+
rewards: [],
|
|
64
|
+
startedAt: Date.now(),
|
|
65
|
+
status: 'lighting the altar…',
|
|
66
|
+
frame: 0,
|
|
67
|
+
flashUntil: 0,
|
|
68
|
+
particles: [],
|
|
69
|
+
lastEmber: 0,
|
|
70
|
+
events: [],
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
function log(text) {
|
|
74
|
+
state.events.unshift({ at: Date.now(), text });
|
|
75
|
+
state.events.length = Math.min(state.events.length, MAX_EVENTS);
|
|
76
|
+
if (!isTTY) console.log(`${timestamp()} ${text}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ---------- Particles: embers drift up while the flame burns, a shower of gold on a true answer ----------
|
|
80
|
+
|
|
81
|
+
function burst({ count, colors, chars, speed = 1 }) {
|
|
82
|
+
const origin = sparkOrigin();
|
|
83
|
+
for (let i = 0; i < count; i += 1) {
|
|
84
|
+
state.particles.push({
|
|
85
|
+
x: origin.x + (Math.random() - 0.5) * 4,
|
|
86
|
+
y: origin.y,
|
|
87
|
+
vx: (Math.random() - 0.5) * 1.6 * speed,
|
|
88
|
+
vy: -(0.25 + Math.random() * 0.6) * speed,
|
|
89
|
+
life: 700 + Math.random() * 700,
|
|
90
|
+
char: chars[Math.floor(Math.random() * chars.length)],
|
|
91
|
+
color: colors[Math.floor(Math.random() * colors.length)],
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function stepParticles() {
|
|
97
|
+
state.particles = state.particles.filter((particle) => {
|
|
98
|
+
particle.x += particle.vx;
|
|
99
|
+
particle.y += particle.vy;
|
|
100
|
+
particle.vx *= 0.92;
|
|
101
|
+
particle.life -= FRAME_MS;
|
|
102
|
+
return particle.life > 0 && particle.y >= 0 && particle.y < ALTAR_HEIGHT;
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---------- Server snapshots ----------
|
|
107
|
+
|
|
108
|
+
function applySnapshot(snapshot) {
|
|
109
|
+
if (!snapshot?.round) return;
|
|
110
|
+
state.balance = snapshot.balance;
|
|
111
|
+
state.round = snapshot.round;
|
|
112
|
+
state.snapshotAt = Date.now();
|
|
113
|
+
|
|
114
|
+
const rock = snapshot.rock;
|
|
115
|
+
if (rock && rock.roundId !== state.rock?.roundId) {
|
|
116
|
+
if (rock.status === 'open') {
|
|
117
|
+
process.stdout.write(isTTY ? '\x07' : '');
|
|
118
|
+
if (!isTTY) log(`riddle #${rock.roundId} · ${rock.question} ${rock.choices.map((choice, i) => `[${LETTERS[i]}] ${choice}`).join(' ')}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (rock && !state.rock?.cracked && rock.cracked && rock.roundId === state.rock?.roundId) {
|
|
122
|
+
burst({ count: 22, colors: [231, 194, 158, 151], chars: ['✦', '✧', '·', '*'], speed: 1.4 });
|
|
123
|
+
}
|
|
124
|
+
state.rock = rock ?? state.rock;
|
|
125
|
+
if (state.rock?.status === 'open' && state.agentRound !== state.rock.roundId) runAgent(state.rock);
|
|
126
|
+
|
|
127
|
+
// Rewards land the moment a riddle is answered true.
|
|
128
|
+
const payout = snapshot.lastPayout;
|
|
129
|
+
if (state.seenPayoutRound === null) {
|
|
130
|
+
// Payouts from before this session don't count toward "this session".
|
|
131
|
+
state.seenPayoutRound = payout?.roundId ?? -1;
|
|
132
|
+
} else if (payout && payout.roundId > state.seenPayoutRound) {
|
|
133
|
+
state.seenPayoutRound = payout.roundId;
|
|
134
|
+
state.earned += payout.amount;
|
|
135
|
+
state.payouts += 1;
|
|
136
|
+
state.rewards.push(payout.amount);
|
|
137
|
+
if (state.rewards.length > 64) state.rewards.shift();
|
|
138
|
+
state.flashUntil = Date.now() + FLASH_MS;
|
|
139
|
+
log(`${c.gold('✦')} riddle #${payout.roundId} rewarded · ${c.gold(`+${formatCoin(payout.amount)} ${TICKER}`)}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ---------- Answering ----------
|
|
144
|
+
|
|
145
|
+
async function submitAnswer(choice, by) {
|
|
146
|
+
const rock = state.rock;
|
|
147
|
+
if (!rock || rock.status !== 'open' || state.answering) return;
|
|
148
|
+
state.answering = true;
|
|
149
|
+
try {
|
|
150
|
+
const result = await client.answer(rock.roundId, choice, by, agent.model);
|
|
151
|
+
applySnapshot(result);
|
|
152
|
+
if (result.rock?.roundId === rock.roundId) state.rock = result.rock;
|
|
153
|
+
const answered = result.rock;
|
|
154
|
+
if (answered.status === 'correct') {
|
|
155
|
+
state.correct += 1;
|
|
156
|
+
state.streak += 1;
|
|
157
|
+
log(`${c.laurel('✦')} agent answered ${LETTERS[choice]}: true`);
|
|
158
|
+
} else {
|
|
159
|
+
state.wrong += 1;
|
|
160
|
+
state.streak = 0;
|
|
161
|
+
log(`${c.crimson('✕')} agent answered ${LETTERS[choice]}: false, it was ${LETTERS[answered.correct]} (${answered.choices[answered.correct]})`);
|
|
162
|
+
}
|
|
163
|
+
} catch (error) {
|
|
164
|
+
if (error.status === 401) return stop(1, 'This terminal was logged out. Log in again with `elythia login`.');
|
|
165
|
+
log(`${c.crimson('✕')} answer not accepted: ${error.message}`);
|
|
166
|
+
if (error.status === 409 || error.status === 410) refreshSnapshot();
|
|
167
|
+
} finally {
|
|
168
|
+
state.answering = false;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// The agent gets a few tries while the riddle is open, in case the provider has a hiccup.
|
|
173
|
+
async function runAgent(rock) {
|
|
174
|
+
state.agentRound = rock.roundId;
|
|
175
|
+
for (let attempt = 1; attempt <= AGENT_ATTEMPTS; attempt += 1) {
|
|
176
|
+
state.agentStartedAt = Date.now();
|
|
177
|
+
try {
|
|
178
|
+
const choice = await agent.answer(rock.question, rock.choices);
|
|
179
|
+
if (state.rock?.roundId === rock.roundId && state.rock.status === 'open') await submitAnswer(choice, 'agent');
|
|
180
|
+
break;
|
|
181
|
+
} catch (error) {
|
|
182
|
+
const retry = attempt < AGENT_ATTEMPTS && rock.closesAt - Date.now() > AGENT_RETRY_MS * 2;
|
|
183
|
+
log(`${c.crimson('✕')} agent failed: ${fit(error.message, 60)}${retry ? ' · retrying' : ''}`);
|
|
184
|
+
if (!retry) break;
|
|
185
|
+
await sleep(AGENT_RETRY_MS);
|
|
186
|
+
} finally {
|
|
187
|
+
if (state.agentRound === rock.roundId) state.agentStartedAt = 0;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ---------- Rendering ----------
|
|
193
|
+
|
|
194
|
+
const working = () => state.online && state.rock?.status === 'open';
|
|
195
|
+
const flashing = () => Date.now() < state.flashUntil;
|
|
196
|
+
|
|
197
|
+
// How much of the answer window has passed: the flame burns lower as it runs out.
|
|
198
|
+
function windowProgress() {
|
|
199
|
+
const rock = state.rock;
|
|
200
|
+
if (!rock || rock.status !== 'open') return 0;
|
|
201
|
+
const opened = rock.endsAt - (state.round?.seconds ?? 60) * 1000;
|
|
202
|
+
return Math.min(1, Math.max(0, (Date.now() - opened) / (rock.closesAt - opened)));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function altarState() {
|
|
206
|
+
const rock = state.rock;
|
|
207
|
+
if (rock?.status === 'correct') return 'blessed';
|
|
208
|
+
if (rock?.status === 'wrong' || rock?.status === 'missed') return 'failed';
|
|
209
|
+
return state.online ? 'consulting' : 'idle';
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const rewardRange = () => (state.round?.reward
|
|
213
|
+
? `${formatNumber(state.round.reward.min)}–${formatNumber(state.round.reward.max)} ${TICKER}`
|
|
214
|
+
: '–');
|
|
215
|
+
|
|
216
|
+
function panelLines(width) {
|
|
217
|
+
const round = state.round;
|
|
218
|
+
const rock = state.rock;
|
|
219
|
+
const left = round ? round.endsAt - Date.now() : 0;
|
|
220
|
+
const barWidth = Math.max(8, Math.min(18, width - 26));
|
|
221
|
+
const progress = round ? 1 - Math.max(0, left) / (round.seconds * 1000) : 0;
|
|
222
|
+
const rockStatus = {
|
|
223
|
+
blessed: c.gold(`✦ true · +${formatCoin(rock?.reward ?? 0)} ${TICKER}`),
|
|
224
|
+
failed: c.crimson(rock?.status === 'missed' ? '✕ unanswered' : '✕ false'),
|
|
225
|
+
consulting: rock ? c.sea('◈ the Oracle awaits') : c.slate('first riddle on its way'),
|
|
226
|
+
idle: c.slate('altar dark'),
|
|
227
|
+
}[altarState()];
|
|
228
|
+
const answered = state.correct + state.wrong;
|
|
229
|
+
const accuracy = answered ? `${Math.round((state.correct / answered) * 100)}%` : '–';
|
|
230
|
+
const streak = `${c.gold('✦'.repeat(Math.min(8, state.streak)))}${c.shadow('·'.repeat(Math.max(0, 8 - state.streak)))}`;
|
|
231
|
+
const best = state.rewards.length ? Math.max(...state.rewards) : 0;
|
|
232
|
+
|
|
233
|
+
return [
|
|
234
|
+
`${label('Riddle')}${c.bone(rock ? `#${rock.roundId}` : '–')} ${rockStatus}`,
|
|
235
|
+
`${label('Round')}${slab(progress, barWidth)} ${c.bone(left > 0 ? countdown(left) : 'closing')} ${c.slate(round ? `· ${pluralize(round.miners, 'seeker')}` : '')}`,
|
|
236
|
+
`${label('Favor')}${c.gold(rewardRange())} ${c.slate('random, per true answer')}`,
|
|
237
|
+
'',
|
|
238
|
+
`${label('Rewards')}${c.gold(sparkline(state.rewards, Math.max(0, width - 28)))} ${c.slate(state.rewards.length ? `best ${formatNumber(best)}` : 'none yet')}`,
|
|
239
|
+
`${label('Answers')}${c.bone(`${state.correct}/${answered}`)} ${c.slate(`true · ${accuracy}`)}`,
|
|
240
|
+
`${label('Altar')}${state.online ? c.laurel('● lit') : c.crimson('○ dark')} ${c.slate(`· ${agent.label}`)}`,
|
|
241
|
+
'',
|
|
242
|
+
`${label('Treasure')}${(flashing() ? c.gold : c.bone)(c.bold(`${formatCoin(state.balance)} ${TICKER}`))}`,
|
|
243
|
+
`${label('Session')}${c.gold(`+${formatCoin(state.earned)}`)} ${c.slate(`· ${pluralize(state.payouts, 'riddle')} rewarded`)}`,
|
|
244
|
+
`${label('Streak')}${streak} ${c.marble(String(state.streak))}`,
|
|
245
|
+
];
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function optionCell(rock, i, width) {
|
|
249
|
+
const text = fit(rock.choices[i], width - 5);
|
|
250
|
+
const answered = rock.status !== 'open';
|
|
251
|
+
if (answered && i === rock.correct) return `${chip(LETTERS[i], 194)} ${c.gold(padEnd(text, width - 4))}`;
|
|
252
|
+
if (answered && i === rock.choice) return `${chip(LETTERS[i], 203)} ${c.crimson(padEnd(text, width - 4))}`;
|
|
253
|
+
return `${key(LETTERS[i])} ${(answered ? c.slate : c.marble)(padEnd(text, width - 4))}`;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function questionLines(width) {
|
|
257
|
+
const rock = state.rock;
|
|
258
|
+
const inner = width - 4;
|
|
259
|
+
if (!rock) {
|
|
260
|
+
return tablet([c.slate('The Oracle speaks within a minute. Your agent answers its riddle.')], width, { title: 'THE ORACLE' });
|
|
261
|
+
}
|
|
262
|
+
const half = Math.floor((inner - 2) / 2);
|
|
263
|
+
const twoColumns = rock.choices.every((choice) => choice.length <= half - 6);
|
|
264
|
+
const options = twoColumns
|
|
265
|
+
? [`${optionCell(rock, 0, half)} ${optionCell(rock, 1, half)}`, `${optionCell(rock, 2, half)} ${optionCell(rock, 3, half)}`]
|
|
266
|
+
: rock.choices.map((_, i) => optionCell(rock, i, inner));
|
|
267
|
+
|
|
268
|
+
const closesIn = rock.closesAt - Date.now();
|
|
269
|
+
const by = rock.answeredBy === 'agent' ? ` · ${agent.label}` : '';
|
|
270
|
+
let footer;
|
|
271
|
+
if (rock.status === 'correct') footer = c.gold(`✦ true · +${formatCoin(rock.reward ?? 0)} ${TICKER}${by} · next riddle at ${clock(rock.endsAt)}`);
|
|
272
|
+
else if (rock.status === 'wrong') footer = c.crimson(`✕ false, no favor this time${by} · next riddle at ${clock(rock.endsAt)}`);
|
|
273
|
+
else if (rock.status === 'missed') footer = c.crimson('✕ the round closed before an answer');
|
|
274
|
+
else if (state.answering) footer = c.sea(`${SPINNER[state.frame % SPINNER.length]} sending the agent's answer…`);
|
|
275
|
+
else if (state.agentStartedAt) footer = `${c.sea(SPINNER[state.frame % SPINNER.length])} ${c.sea('agent is consulting the Oracle')} ${c.slate(`· ${agent.label} · ${countdown(closesIn)} left`)}`;
|
|
276
|
+
else footer = c.slate(`${countdown(closesIn)} left · waiting for the agent`);
|
|
277
|
+
|
|
278
|
+
return tablet([
|
|
279
|
+
...wrap(rock.question, inner).map((line) => c.bone(c.bold(line))),
|
|
280
|
+
'',
|
|
281
|
+
...options,
|
|
282
|
+
'',
|
|
283
|
+
footer,
|
|
284
|
+
], width, { title: `THE ORACLE · RIDDLE #${rock.roundId}`, tone: c.bronze, accent: rock.status === 'open' ? c.sea : rock.status === 'correct' ? c.gold : c.crimson });
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function header(width) {
|
|
288
|
+
return spread(
|
|
289
|
+
`${chip('ELYTHIA', 73)} ${c.marble('temple')} ${c.slate('·')} ${c.bone(username)}`,
|
|
290
|
+
`${chip('AGENT', 151)} ${c.slate(formatDuration(Date.now() - state.startedAt))}`,
|
|
291
|
+
width,
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function eventLines(width) {
|
|
296
|
+
const lines = state.events.map((event) => `${c.shadow(clock(event.at))} ${fit(event.text, width - 11)}`);
|
|
297
|
+
while (lines.length < MAX_EVENTS) lines.push('');
|
|
298
|
+
return lines;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function footerLine(width) {
|
|
302
|
+
const spinner = working() ? c.sea(SPINNER[state.frame % SPINNER.length]) : c.slate('○');
|
|
303
|
+
const keys = interactive ? `${key('q')} ${c.slate('stop')}` : c.slate('ctrl+c to stop');
|
|
304
|
+
return spread(`${spinner} ${c.granite(state.status)}`, keys, width);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function frameLines() {
|
|
308
|
+
const width = Math.min(98, columns() - 4);
|
|
309
|
+
const time = Date.now();
|
|
310
|
+
if (width < 50) {
|
|
311
|
+
const rock = state.rock;
|
|
312
|
+
return [
|
|
313
|
+
`${chip('ELY', 73)} ${state.online ? c.laurel('●') : c.crimson('○')} ${c.gold(`${formatCoin(state.balance)} ${TICKER}`)}`,
|
|
314
|
+
rock ? fit(c.bone(rock.question), width) : '',
|
|
315
|
+
rock ? rock.choices.map((choice, i) => `${LETTERS[i]}:${fit(choice, 10)}`).join(' ') : '',
|
|
316
|
+
];
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const lines = [header(width), c.bronze('═'.repeat(width)), ''];
|
|
320
|
+
if (width >= ALTAR_WIDTH + 44) {
|
|
321
|
+
const art = altarFrame({ progress: windowProgress(), state: altarState(), time, particles: state.particles });
|
|
322
|
+
const panel = panelLines(width - ALTAR_WIDTH - 4);
|
|
323
|
+
const top = Math.floor((art.length - panel.length) / 2);
|
|
324
|
+
art.forEach((row, i) => lines.push(`${row} ${panel[i - top] ?? ''}`));
|
|
325
|
+
} else {
|
|
326
|
+
lines.push(...panelLines(width));
|
|
327
|
+
}
|
|
328
|
+
lines.push('', ...questionLines(width), '', ...eventLines(width), c.shadow('─'.repeat(width)), footerLine(width));
|
|
329
|
+
return lines;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const draw = () => drawCentered(frameLines());
|
|
333
|
+
|
|
334
|
+
function stop(exitCode = 0, reason) {
|
|
335
|
+
clearInterval(renderTimer);
|
|
336
|
+
clearInterval(plainStatusTimer);
|
|
337
|
+
if (interactive) {
|
|
338
|
+
process.stdin.setRawMode(false);
|
|
339
|
+
process.stdin.pause();
|
|
340
|
+
}
|
|
341
|
+
leaveFullScreen();
|
|
342
|
+
showCursor();
|
|
343
|
+
if (reason) console.error(`\n ${c.crimson('▼')} ${reason}`);
|
|
344
|
+
|
|
345
|
+
const elapsed = Date.now() - state.startedAt;
|
|
346
|
+
const answered = state.correct + state.wrong;
|
|
347
|
+
console.log(['', ...tablet([
|
|
348
|
+
`${label('Duration')}${c.bone(formatDuration(elapsed))} ${c.slate(`· ${agent.label}`)}`,
|
|
349
|
+
`${label('Answers')}${c.bone(`${state.correct}/${answered} true`)}`,
|
|
350
|
+
`${label('Earned')}${c.gold(`+${formatCoin(state.earned)} ${TICKER}`)} ${c.slate(`from ${pluralize(state.payouts, 'riddle')}`)}`,
|
|
351
|
+
`${label('Best favor')}${c.bone(state.rewards.length ? `${formatNumber(Math.max(...state.rewards))} ${TICKER}` : '–')}`,
|
|
352
|
+
`${label('Treasure')}${c.bone(c.bold(`${formatCoin(state.balance)} ${TICKER}`))}`,
|
|
353
|
+
], 58, { title: `SESSION · ${username}` }).map((line) => ` ${line}`),
|
|
354
|
+
''].join('\n'));
|
|
355
|
+
process.exit(exitCode);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// ---------- Heartbeat ----------
|
|
359
|
+
|
|
360
|
+
async function beat() {
|
|
361
|
+
if (state.beating) return;
|
|
362
|
+
state.beating = true;
|
|
363
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
364
|
+
try {
|
|
365
|
+
const result = await client.heartbeat();
|
|
366
|
+
applySnapshot(result);
|
|
367
|
+
state.heartbeatMs = (result.heartbeatSeconds ?? DEFAULT_HEARTBEAT_MS / 1000) * 1000;
|
|
368
|
+
if (!state.online) log(`${c.laurel('●')} altar lit · one riddle every ${state.round?.seconds ?? 60}s`);
|
|
369
|
+
state.online = true;
|
|
370
|
+
state.status = 'altar lit';
|
|
371
|
+
break;
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (error.status === 401) return stop(1, 'This terminal was logged out. Log in again with `elythia login`.');
|
|
374
|
+
if (error.status === 426) return stop(1, error.message);
|
|
375
|
+
state.online = false;
|
|
376
|
+
const wait = Math.min(30_000, 1000 * 2 ** attempt);
|
|
377
|
+
// Not holding enough: keep checking, so the altar lights again by itself after buying.
|
|
378
|
+
state.status = c.crimson(error.status === 403 ? `${error.message} · waiting` : `${error.message} · retrying in ${Math.round(wait / 1000)}s`);
|
|
379
|
+
if (!isTTY) console.log(`${timestamp()} ▼ ${error.message}`);
|
|
380
|
+
await sleep(wait);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
state.heartbeatAt = Date.now();
|
|
384
|
+
state.beating = false;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
let refreshing = false;
|
|
388
|
+
async function refreshSnapshot() {
|
|
389
|
+
if (refreshing) return;
|
|
390
|
+
refreshing = true;
|
|
391
|
+
try {
|
|
392
|
+
applySnapshot(await client.round());
|
|
393
|
+
} catch {
|
|
394
|
+
// The next heartbeat brings fresh data anyway.
|
|
395
|
+
} finally {
|
|
396
|
+
refreshing = false;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// ---------- Keys ----------
|
|
401
|
+
|
|
402
|
+
function onKey(_, pressed = {}) {
|
|
403
|
+
if ((pressed.ctrl && pressed.name === 'c') || pressed.name === 'q' || pressed.name === 'escape') stop(0);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// ---------- Main loop ----------
|
|
407
|
+
|
|
408
|
+
const renderTimer = setInterval(() => {
|
|
409
|
+
state.frame += 1;
|
|
410
|
+
const now = Date.now();
|
|
411
|
+
if (working() && now - state.lastEmber > EMBER_MS) {
|
|
412
|
+
state.lastEmber = now;
|
|
413
|
+
burst({ count: 2, colors: [195, 152, 116, 73], chars: ['·', '˙', '\''], speed: 0.8 });
|
|
414
|
+
}
|
|
415
|
+
stepParticles();
|
|
416
|
+
if (isTTY) draw();
|
|
417
|
+
|
|
418
|
+
if (!state.beating && now - state.heartbeatAt > state.heartbeatMs) beat();
|
|
419
|
+
if (now - state.snapshotAt > SNAPSHOT_REFRESH_MS) {
|
|
420
|
+
state.snapshotAt = now;
|
|
421
|
+
refreshSnapshot();
|
|
422
|
+
}
|
|
423
|
+
}, FRAME_MS);
|
|
424
|
+
|
|
425
|
+
const plainStatusTimer = isTTY ? null : setInterval(() => {
|
|
426
|
+
console.log(`${timestamp()} ${state.online ? 'altar lit' : 'altar dark'} · ${state.correct} true · +${formatCoin(state.earned)} ${TICKER} this session · treasure ${formatCoin(state.balance)} ${TICKER}`);
|
|
427
|
+
}, NON_TTY_STATUS_MS);
|
|
428
|
+
|
|
429
|
+
process.stdout.on('resize', () => {
|
|
430
|
+
if (isTTY) clearScreen();
|
|
431
|
+
});
|
|
432
|
+
process.on('SIGINT', () => stop(0));
|
|
433
|
+
process.on('SIGTERM', () => stop(0));
|
|
434
|
+
|
|
435
|
+
if (interactive) {
|
|
436
|
+
emitKeypressEvents(process.stdin);
|
|
437
|
+
process.stdin.setRawMode(true);
|
|
438
|
+
process.stdin.resume();
|
|
439
|
+
process.stdin.on('keypress', onKey);
|
|
440
|
+
}
|
|
441
|
+
if (isTTY) {
|
|
442
|
+
enterFullScreen();
|
|
443
|
+
hideCursor();
|
|
444
|
+
} else {
|
|
445
|
+
console.log(`Divining as ${username} · agent ${agent.label} · Ctrl+C to stop`);
|
|
446
|
+
}
|
|
447
|
+
beat();
|
|
448
|
+
}
|
package/src/ui.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// Terminal styling for the Elythia CLI: deep navy, mist teal for the Oracle and pale mint for
|
|
2
|
+
// rewards and the AI agent, in 256 colors, plus layout helpers.
|
|
3
|
+
|
|
4
|
+
const colorEnabled = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
5
|
+
const sgr = (open, close) => (text) => (colorEnabled ? `\x1b[${open}m${text}\x1b[${close}m` : String(text));
|
|
6
|
+
const fg = (code) => sgr(`38;5;${code}`, 39);
|
|
7
|
+
const bg = (code) => sgr(`48;5;${code}`, 49);
|
|
8
|
+
|
|
9
|
+
export const c = {
|
|
10
|
+
bold: sgr(1, 22),
|
|
11
|
+
dim: sgr(2, 22),
|
|
12
|
+
italic: sgr(3, 23),
|
|
13
|
+
underline: sgr(4, 24),
|
|
14
|
+
fg,
|
|
15
|
+
bg,
|
|
16
|
+
marble: fg(252),
|
|
17
|
+
granite: fg(245),
|
|
18
|
+
slate: fg(242),
|
|
19
|
+
shadow: fg(238),
|
|
20
|
+
bone: fg(255),
|
|
21
|
+
sea: fg(73),
|
|
22
|
+
deep: fg(60),
|
|
23
|
+
gold: fg(194),
|
|
24
|
+
bronze: fg(67),
|
|
25
|
+
laurel: fg(151),
|
|
26
|
+
crimson: fg(203),
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const isTTY = Boolean(process.stdout.isTTY);
|
|
30
|
+
export const SPINNER = ['◜', '◠', '◝', '◞', '◡', '◟'];
|
|
31
|
+
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
32
|
+
export const columns = () => process.stdout.columns || 80;
|
|
33
|
+
export const rows = () => process.stdout.rows || 24;
|
|
34
|
+
|
|
35
|
+
export const ok = (message) => console.log(` ${c.laurel('✦')} ${message}`);
|
|
36
|
+
export const fail = (message) => console.error(` ${c.crimson('✕')} ${message}`);
|
|
37
|
+
export const info = (message) => console.log(` ${c.sea('◈')} ${message}`);
|
|
38
|
+
|
|
39
|
+
export const hideCursor = () => isTTY && process.stdout.write('\x1b[?25l');
|
|
40
|
+
export const showCursor = () => isTTY && process.stdout.write('\x1b[?25h');
|
|
41
|
+
process.on('exit', showCursor);
|
|
42
|
+
|
|
43
|
+
// Length and truncation that ignore color codes.
|
|
44
|
+
const ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
|
|
45
|
+
export const strip = (text) => String(text).replace(ANSI, '');
|
|
46
|
+
export const visibleLength = (text) => [...strip(text)].length;
|
|
47
|
+
|
|
48
|
+
export function fit(text, width) {
|
|
49
|
+
if (visibleLength(text) <= width) return text;
|
|
50
|
+
let out = '';
|
|
51
|
+
let count = 0;
|
|
52
|
+
for (const part of String(text).split(/(\x1b\[[0-9;?]*[A-Za-z])/)) {
|
|
53
|
+
if (part.startsWith('\x1b[')) {
|
|
54
|
+
out += part;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
for (const char of part) {
|
|
58
|
+
if (count >= Math.max(0, width - 1)) break;
|
|
59
|
+
out += char;
|
|
60
|
+
count += 1;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return `${out}${colorEnabled ? '\x1b[0m' : ''}…`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const padEnd = (text, width) => text + ' '.repeat(Math.max(0, width - visibleLength(text)));
|
|
67
|
+
export const spread = (left, right, width) => left + ' '.repeat(Math.max(1, width - visibleLength(left) - visibleLength(right))) + right;
|
|
68
|
+
export const center = (text, width) => {
|
|
69
|
+
const space = Math.max(0, width - visibleLength(text));
|
|
70
|
+
return ' '.repeat(Math.floor(space / 2)) + text + ' '.repeat(Math.ceil(space / 2));
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
// Full-screen views use the alternate screen; the normal screen comes back untouched.
|
|
74
|
+
let fullScreen = false;
|
|
75
|
+
export const clearScreen = () => process.stdout.write('\x1b[2J\x1b[H');
|
|
76
|
+
|
|
77
|
+
export function enterFullScreen() {
|
|
78
|
+
if (fullScreen) return;
|
|
79
|
+
process.stdout.write('\x1b[?1049h');
|
|
80
|
+
clearScreen();
|
|
81
|
+
hideCursor();
|
|
82
|
+
fullScreen = true;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function leaveFullScreen() {
|
|
86
|
+
if (!fullScreen) return;
|
|
87
|
+
process.stdout.write('\x1b[?1049l');
|
|
88
|
+
showCursor();
|
|
89
|
+
fullScreen = false;
|
|
90
|
+
}
|
|
91
|
+
process.on('exit', leaveFullScreen);
|
|
92
|
+
|
|
93
|
+
// Draws a block of lines centered in the window, redrawn from the top-left every frame.
|
|
94
|
+
export function drawCentered(lines, { vertical = true } = {}) {
|
|
95
|
+
const width = columns();
|
|
96
|
+
const height = rows();
|
|
97
|
+
const blockWidth = Math.max(...lines.map(visibleLength));
|
|
98
|
+
const indent = ' '.repeat(Math.max(0, Math.floor((width - blockWidth) / 2)));
|
|
99
|
+
const top = vertical ? Math.max(0, Math.floor((height - lines.length) / 2)) : 0;
|
|
100
|
+
const out = [...Array(top).fill(''), ...lines.map((line) => indent + line)].slice(0, height);
|
|
101
|
+
process.stdout.write(`\x1b[H${out.map((row) => `\x1b[2K${fit(row, width - 1)}`).join('\n')}\x1b[0J`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ---------- Building blocks ----------
|
|
105
|
+
|
|
106
|
+
// A marble tablet: a box with a title tab in the top border.
|
|
107
|
+
export function tablet(lines, width, { title = '', tone = c.slate, accent = c.sea } = {}) {
|
|
108
|
+
const inner = width - 4;
|
|
109
|
+
const head = title
|
|
110
|
+
? `${tone('┏━')}${accent(` ${title} `)}${tone('━'.repeat(Math.max(0, width - visibleLength(title) - 5)))}${tone('┓')}`
|
|
111
|
+
: tone(`┏${'━'.repeat(width - 2)}┓`);
|
|
112
|
+
return [
|
|
113
|
+
head,
|
|
114
|
+
...lines.map((line) => `${tone('┃')} ${padEnd(fit(line, inner), inner)} ${tone('┃')}`),
|
|
115
|
+
tone(`┗${'━'.repeat(width - 2)}┛`),
|
|
116
|
+
];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export const rule = (width, char = '─') => c.shadow(char.repeat(width));
|
|
120
|
+
export const label = (text, width = 11) => c.granite(text.toUpperCase().padEnd(width));
|
|
121
|
+
export const chip = (text, tone = 73) => (colorEnabled ? `\x1b[48;5;${tone}m\x1b[38;5;232m\x1b[1m ${text} \x1b[22m\x1b[39m\x1b[49m` : `[${text}]`);
|
|
122
|
+
export const key = (text) => (colorEnabled ? `\x1b[48;5;238m\x1b[38;5;255m ${text} \x1b[39m\x1b[49m` : `<${text}>`);
|
|
123
|
+
|
|
124
|
+
// A progress bar of marble slabs that fill with the sea.
|
|
125
|
+
export function slab(fraction, width, tone = c.sea) {
|
|
126
|
+
const cells = Math.max(0, Math.min(width * 2, Math.round(fraction * width * 2)));
|
|
127
|
+
const full = Math.floor(cells / 2);
|
|
128
|
+
const half = cells % 2;
|
|
129
|
+
return tone('█'.repeat(full) + (half ? '▌' : '')) + c.shadow('░'.repeat(width - full - half));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const SPARK = '▁▂▃▄▅▆▇█';
|
|
133
|
+
export function sparkline(values, width) {
|
|
134
|
+
const recent = values.slice(-width);
|
|
135
|
+
const max = Math.max(...recent, 1);
|
|
136
|
+
return recent.map((value) => SPARK[Math.min(SPARK.length - 1, Math.round((value / max) * (SPARK.length - 1)))]).join('');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Shows a spinner while `task` runs. Prints nothing when the output isn't a terminal.
|
|
140
|
+
export async function spin(text, task) {
|
|
141
|
+
if (!isTTY) return task;
|
|
142
|
+
let frame = 0;
|
|
143
|
+
const draw = () => process.stdout.write(`\r\x1b[2K ${c.sea(SPINNER[frame++ % SPINNER.length])} ${c.granite(text)}`);
|
|
144
|
+
hideCursor();
|
|
145
|
+
draw();
|
|
146
|
+
const timer = setInterval(draw, 90);
|
|
147
|
+
try {
|
|
148
|
+
return await task;
|
|
149
|
+
} finally {
|
|
150
|
+
clearInterval(timer);
|
|
151
|
+
process.stdout.write('\r\x1b[2K');
|
|
152
|
+
showCursor();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ---------- Formatting ----------
|
|
157
|
+
|
|
158
|
+
export const TICKER = 'ELYTHIA';
|
|
159
|
+
|
|
160
|
+
export function formatHashrate(hashesPerSecond) {
|
|
161
|
+
const units = ['H/s', 'KH/s', 'MH/s', 'GH/s'];
|
|
162
|
+
let value = hashesPerSecond;
|
|
163
|
+
let unit = 0;
|
|
164
|
+
while (value >= 1000 && unit < units.length - 1) {
|
|
165
|
+
value /= 1000;
|
|
166
|
+
unit += 1;
|
|
167
|
+
}
|
|
168
|
+
return `${value.toFixed(unit === 0 ? 0 : 2)} ${units[unit]}`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export const formatNumber = (value) => new Intl.NumberFormat('en-US').format(value);
|
|
172
|
+
// Coin amounts: two decimals, or four for small amounts so a tiny payout doesn't show as 0.00.
|
|
173
|
+
export const formatCoin = (value) => {
|
|
174
|
+
const digits = Math.abs(value) > 0 && Math.abs(value) < 1 ? 4 : 2;
|
|
175
|
+
return new Intl.NumberFormat('en-US', { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value);
|
|
176
|
+
};
|
|
177
|
+
export const formatCompact = (value) => new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 }).format(value);
|
|
178
|
+
|
|
179
|
+
export function formatDuration(ms) {
|
|
180
|
+
const total = Math.floor(ms / 1000);
|
|
181
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
182
|
+
return `${pad(Math.floor(total / 3600))}:${pad(Math.floor((total % 3600) / 60))}:${pad(total % 60)}`;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export const countdown = (ms) => {
|
|
186
|
+
const seconds = Math.max(0, Math.ceil(ms / 1000));
|
|
187
|
+
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
export const clock = (time) => new Date(time).toLocaleTimeString('en-GB', { hour12: false });
|
|
191
|
+
export const timestamp = () => c.slate(clock(Date.now()));
|