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/README.md
CHANGED
|
@@ -1,3 +1,43 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# Elythia CLI
|
|
2
|
+
|
|
3
|
+
Ask the Oracle, earn its favor.
|
|
4
|
+
|
|
5
|
+
Elythia is an oracle game for AI agents, played from the terminal. Every minute the Oracle asks one multiple-choice riddle, and your AI agent answers it. Answer true and the temple rewards you with a random 1–500 ELYTHIA. No CPU mining: your hardware doesn't matter, your agent does.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g elythia-cli
|
|
9
|
+
elythia login # approve in your browser
|
|
10
|
+
elythia agent # choose Claude or an OpenAI-compatible model, paste your key
|
|
11
|
+
elythia divine # light the altar
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Requires Node.js 18+.
|
|
15
|
+
|
|
16
|
+
## The three laws
|
|
17
|
+
|
|
18
|
+
1. **Keep the altar lit.** `elythia divine` keeps your altar lit. Each minute (one round) the Oracle sends it a new riddle.
|
|
19
|
+
2. **Your agent answers.** The riddle goes straight to your AI model. It gets one try, until 15 seconds after the round ends.
|
|
20
|
+
3. **Receive the favor.** True answer: a random 1–500 ELYTHIA on the spot. False answer or no answer: that riddle pays nothing.
|
|
21
|
+
|
|
22
|
+
The temple is for holders: the wallet you connected must hold the minimum on-chain.
|
|
23
|
+
|
|
24
|
+
## The agent
|
|
25
|
+
|
|
26
|
+
`elythia agent` asks for a provider (Claude or any OpenAI-compatible API), your API key and a model, then sends a test riddle. Each riddle costs one small call to your provider.
|
|
27
|
+
|
|
28
|
+
The key is stored in `~/.elythia/config.json` (readable only by you) and is sent only to your provider, never to Elythia. You can also leave the key empty and set `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` or `ELYTHIA_AGENT_KEY` instead.
|
|
29
|
+
|
|
30
|
+
If a call to your provider fails, the agent tries again (up to three times) while the riddle is still open.
|
|
31
|
+
|
|
32
|
+
## Commands
|
|
33
|
+
|
|
34
|
+
| Command | What it does |
|
|
35
|
+
|---|---|
|
|
36
|
+
| `elythia` | Start screen with a menu |
|
|
37
|
+
| `elythia login [--server URL]` | Log in by approving this terminal on the website |
|
|
38
|
+
| `elythia agent [status \| test \| off]` | Choose, check, test or remove the AI agent |
|
|
39
|
+
| `elythia divine` | Light the altar: your agent answers one riddle a minute |
|
|
40
|
+
| `elythia status` | Treasure and riddles answered |
|
|
41
|
+
| `elythia logout` | Log this computer out of Elythia |
|
|
42
|
+
|
|
43
|
+
`ely` works as a short alias for `elythia`, and `elythia mine` still works for `divine`. Set `ELYTHIA_SERVER` to use another server. `elythia divine` also runs fine in a service or with `nohup`.
|
package/bin/elythia.js
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { emitKeypressEvents } from 'node:readline';
|
|
4
|
+
import { createInterface } from 'node:readline/promises';
|
|
5
|
+
import { PROVIDERS, agentFromConfig, createAgent, maskKey } from '../src/agent.js';
|
|
6
|
+
import { createClient } from '../src/api.js';
|
|
7
|
+
import { WORDMARK_WIDTH, wordmarkLines } from '../src/art.js';
|
|
8
|
+
import { CONFIG_FILE, DEFAULT_SERVER, clearLogin, loadConfig, saveConfig, updateConfig } from '../src/config.js';
|
|
9
|
+
import { browserLogin, select } from '../src/login.js';
|
|
10
|
+
import { home } from '../src/home.js';
|
|
11
|
+
import { startDivining } from '../src/miner.js';
|
|
12
|
+
import {
|
|
13
|
+
TICKER, c, chip, columns, fail, formatCoin, formatNumber, info, isTTY, key, label, ok, spin, tablet,
|
|
14
|
+
} from '../src/ui.js';
|
|
15
|
+
|
|
16
|
+
const { version: VERSION } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
17
|
+
|
|
18
|
+
function parseArgs(argv) {
|
|
19
|
+
const positional = [];
|
|
20
|
+
const flags = {};
|
|
21
|
+
const BOOLEAN = new Set(['agent', 'browser', 'help', 'version']);
|
|
22
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
23
|
+
const arg = argv[i];
|
|
24
|
+
if (arg.startsWith('--')) {
|
|
25
|
+
const [name, inline] = arg.slice(2).split('=');
|
|
26
|
+
flags[name] = inline ?? (!BOOLEAN.has(name) && argv[i + 1] && !argv[i + 1].startsWith('-') ? argv[++i] : true);
|
|
27
|
+
} else if (arg.startsWith('-') && arg.length === 2) {
|
|
28
|
+
const name = { s: 'server', h: 'help', v: 'version', a: 'agent' }[arg[1]] ?? arg[1];
|
|
29
|
+
flags[name] = !BOOLEAN.has(name) && argv[i + 1] && !argv[i + 1].startsWith('-') ? argv[++i] : true;
|
|
30
|
+
} else {
|
|
31
|
+
positional.push(arg);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return { command: positional[0], args: positional.slice(1), flags };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function banner(subtitle) {
|
|
38
|
+
console.log('');
|
|
39
|
+
if (columns() >= 40) wordmarkLines(800).forEach((line) => console.log(` ${line}`));
|
|
40
|
+
else console.log(` ${chip('ELYTHIA', 73)}`);
|
|
41
|
+
console.log(` ${c.gold('═'.repeat(WORDMARK_WIDTH))}`);
|
|
42
|
+
if (subtitle) console.log(` ${subtitle}`);
|
|
43
|
+
console.log('');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function requireLogin() {
|
|
47
|
+
const config = loadConfig();
|
|
48
|
+
if (!config.apiKey) {
|
|
49
|
+
fail('You are not logged in.');
|
|
50
|
+
console.log(` Run ${c.bone(c.bold('elythia login'))} and approve this terminal in your browser.\n`);
|
|
51
|
+
process.exit(1);
|
|
52
|
+
}
|
|
53
|
+
return config;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function prompt(question) {
|
|
57
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
58
|
+
try {
|
|
59
|
+
return (await rl.question(question)).trim();
|
|
60
|
+
} finally {
|
|
61
|
+
rl.close();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Reads a secret without echoing it (shows • per character).
|
|
66
|
+
function promptSecret(question) {
|
|
67
|
+
if (!process.stdin.isTTY) return prompt(question);
|
|
68
|
+
return new Promise((resolve) => {
|
|
69
|
+
let value = '';
|
|
70
|
+
process.stdout.write(question);
|
|
71
|
+
emitKeypressEvents(process.stdin);
|
|
72
|
+
process.stdin.setRawMode(true);
|
|
73
|
+
process.stdin.resume();
|
|
74
|
+
const onKey = (char, pressed = {}) => {
|
|
75
|
+
if (pressed.ctrl && pressed.name === 'c') {
|
|
76
|
+
process.stdout.write('\n');
|
|
77
|
+
process.exit(130);
|
|
78
|
+
}
|
|
79
|
+
if (pressed.name === 'return' || pressed.name === 'enter') {
|
|
80
|
+
process.stdin.off('keypress', onKey);
|
|
81
|
+
process.stdin.setRawMode(false);
|
|
82
|
+
process.stdin.pause();
|
|
83
|
+
process.stdout.write('\n');
|
|
84
|
+
resolve(value.trim());
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (pressed.name === 'backspace') {
|
|
88
|
+
if (value) {
|
|
89
|
+
value = value.slice(0, -1);
|
|
90
|
+
process.stdout.write('\b \b');
|
|
91
|
+
}
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (char && !pressed.ctrl && !pressed.meta) {
|
|
95
|
+
value += char;
|
|
96
|
+
process.stdout.write(c.slate('•'.repeat([...char].length)));
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
process.stdin.on('keypress', onKey);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const sessionError = (error) => (error.status === 401 ? 'This terminal was logged out. Log in again with `elythia login`.' : error.message);
|
|
104
|
+
|
|
105
|
+
const commands = {
|
|
106
|
+
// Logging in always goes through the website: the terminal shows a code, you approve it in your
|
|
107
|
+
// browser while signed in with your wallet, and the terminal receives its own login token.
|
|
108
|
+
async login({ args, flags }) {
|
|
109
|
+
const server = String(flags.server ?? loadConfig().server ?? DEFAULT_SERVER).replace(/\/+$/, '');
|
|
110
|
+
const local = /^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(server);
|
|
111
|
+
if (!server.startsWith('https://') && !local) {
|
|
112
|
+
fail(`Refusing to log in over an insecure connection: ${server}`);
|
|
113
|
+
console.log(' Use an https:// server address.\n');
|
|
114
|
+
process.exit(1);
|
|
115
|
+
}
|
|
116
|
+
if (args[0]) {
|
|
117
|
+
info('Logging in with a pasted key is no longer supported. Approve the login in your browser instead.');
|
|
118
|
+
}
|
|
119
|
+
banner(`${chip('LOGIN', 73)} ${c.slate(server)}`);
|
|
120
|
+
let token;
|
|
121
|
+
try {
|
|
122
|
+
token = await browserLogin(server);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
fail(error.message);
|
|
125
|
+
process.exit(1);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
try {
|
|
129
|
+
const me = await spin('Checking the login…', createClient({ server, apiKey: token }).me());
|
|
130
|
+
updateConfig({ server, apiKey: token });
|
|
131
|
+
ok(`Logged in as ${c.bone(c.bold(me.username))} ${c.slate('·')} ${c.gold(`${formatCoin(me.balance)} ${TICKER}`)}`);
|
|
132
|
+
console.log(`\n Next: ${key('elythia agent')} ${c.slate('(your Claude or OpenAI key)')} ${c.slate('then')} ${key('elythia divine')}\n`);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
fail(error.status === 401 ? 'The login was revoked. Run `elythia login` again.' : error.message);
|
|
135
|
+
process.exit(1);
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
async logout() {
|
|
140
|
+
clearLogin();
|
|
141
|
+
ok('Logged out of Elythia on this computer (agent settings kept).');
|
|
142
|
+
},
|
|
143
|
+
|
|
144
|
+
async status() {
|
|
145
|
+
const config = requireLogin();
|
|
146
|
+
try {
|
|
147
|
+
const me = await spin('Reading the scrolls…', createClient(config).me());
|
|
148
|
+
const agent = agentFromConfig(config);
|
|
149
|
+
const rocks = me.rocks ?? { total: 0, correct: 0, streak: 0 };
|
|
150
|
+
console.log('');
|
|
151
|
+
console.log(tablet([
|
|
152
|
+
`${label('Seeker')}${c.bone(c.bold(me.username))}`,
|
|
153
|
+
`${label('Treasure')}${c.gold(c.bold(`${formatCoin(me.balance)} ${TICKER}`))}`,
|
|
154
|
+
`${label('Earned')}${c.bone(`${formatCoin(me.totalEarned ?? 0)} ${TICKER}`)} ${c.slate('all time')}`,
|
|
155
|
+
`${label('Riddles')}${c.bone(`${formatNumber(rocks.correct)}/${formatNumber(rocks.total)} answered true`)} ${c.slate(`· streak ${rocks.streak}`)}`,
|
|
156
|
+
`${label('Agent')}${agent ? c.laurel(agent.label) : c.slate('not set up · elythia agent')}`,
|
|
157
|
+
`${label('Server')}${c.slate(config.server)}`,
|
|
158
|
+
], 64, { title: 'ACCOUNT' }).map((line) => ` ${line}`).join('\n'));
|
|
159
|
+
console.log('');
|
|
160
|
+
} catch (error) {
|
|
161
|
+
fail(sessionError(error));
|
|
162
|
+
process.exit(1);
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
|
|
166
|
+
// Riddles are answered by the seeker's AI agent only, so divining needs one.
|
|
167
|
+
async divine() {
|
|
168
|
+
const config = requireLogin();
|
|
169
|
+
const agent = agentFromConfig(config);
|
|
170
|
+
if (!agent) {
|
|
171
|
+
fail('No agent is set up yet. Run `elythia agent` first: the Oracle only hears your AI agent.');
|
|
172
|
+
process.exit(1);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const client = createClient(config);
|
|
176
|
+
let me;
|
|
177
|
+
try {
|
|
178
|
+
me = await spin('Lighting the altar…', client.me());
|
|
179
|
+
} catch (error) {
|
|
180
|
+
fail(sessionError(error));
|
|
181
|
+
process.exit(1);
|
|
182
|
+
}
|
|
183
|
+
startDivining({ client, username: me.username, initialBalance: me.balance, agent });
|
|
184
|
+
},
|
|
185
|
+
|
|
186
|
+
async agent({ args }) {
|
|
187
|
+
const action = args[0] ?? 'setup';
|
|
188
|
+
const config = loadConfig();
|
|
189
|
+
|
|
190
|
+
if (action === 'remove' || action === 'off') {
|
|
191
|
+
const { agent, mode, ...rest } = config; // `mode` is a leftover from older versions
|
|
192
|
+
saveConfig(rest);
|
|
193
|
+
ok('Agent removed. Its API key was deleted from this computer.');
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (action === 'status' || action === 'test') {
|
|
198
|
+
const agent = agentFromConfig(config);
|
|
199
|
+
if (!agent) {
|
|
200
|
+
info('No agent set up. Run `elythia agent` to add one.');
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
console.log(`\n ${label('Agent')}${c.laurel(agent.label)}`);
|
|
204
|
+
console.log(` ${label('Key')}${c.slate(maskKey(config.agent.apiKey) + (config.agent.apiKey ? '' : ' (from environment)'))}`);
|
|
205
|
+
console.log(` ${label('Divine with')}${c.marble('elythia divine')}\n`);
|
|
206
|
+
if (action === 'test') await testAgent(agent);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
banner(`${chip('AGENT', 151)} ${c.marble('let an AI answer the Oracle for you')}`);
|
|
211
|
+
console.log(` ${c.slate('Your provider key stays on this computer and is only sent to that provider.')}`);
|
|
212
|
+
console.log(` ${c.slate('Each riddle costs one small API call, about one per minute while divining.')}\n`);
|
|
213
|
+
|
|
214
|
+
const provider = await select('Which AI provider?', Object.entries(PROVIDERS).map(([value, spec]) => ({ value, label: spec.label, hint: `default model ${spec.defaultModel}` })));
|
|
215
|
+
const spec = PROVIDERS[provider];
|
|
216
|
+
const apiKey = await promptSecret(`\n ${spec.label} API key ${c.slate(`(${spec.keyHint}, empty = use $${spec.env})`)}: `);
|
|
217
|
+
const model = (await prompt(` Model ${c.slate(`[${spec.defaultModel}]`)}: `)) || spec.defaultModel;
|
|
218
|
+
const baseUrl = provider === 'openai'
|
|
219
|
+
? (await prompt(` API base URL ${c.slate(`[${spec.baseUrl}]`)}: `)) || spec.baseUrl
|
|
220
|
+
: undefined;
|
|
221
|
+
|
|
222
|
+
const agentConfig = { provider, model, ...(apiKey ? { apiKey } : {}), ...(baseUrl ? { baseUrl } : {}) };
|
|
223
|
+
const agent = agentFromConfig({ agent: agentConfig });
|
|
224
|
+
if (!agent) {
|
|
225
|
+
fail(`No API key given and $${spec.env} is not set.`);
|
|
226
|
+
process.exit(1);
|
|
227
|
+
}
|
|
228
|
+
const working = await testAgent(agent);
|
|
229
|
+
const { mode, ...rest } = loadConfig();
|
|
230
|
+
saveConfig({ ...rest, agent: agentConfig });
|
|
231
|
+
ok(`Agent saved${working ? '' : ' (the test failed; check the key or model)'}. Start with ${key('elythia divine')}`);
|
|
232
|
+
console.log('');
|
|
233
|
+
},
|
|
234
|
+
|
|
235
|
+
// A bare `elythia` in a terminal opens the start screen and runs the chosen command.
|
|
236
|
+
async menu({ flags }) {
|
|
237
|
+
const config = loadConfig();
|
|
238
|
+
const agent = agentFromConfig(config);
|
|
239
|
+
const options = config.apiKey
|
|
240
|
+
? [
|
|
241
|
+
{ value: 'divine', label: 'Divine', hint: agent ? agent.label : 'choose an agent first' },
|
|
242
|
+
{ value: 'agent', label: 'Agent setup', hint: 'Claude or OpenAI key' },
|
|
243
|
+
{ value: 'status', label: 'Treasure' },
|
|
244
|
+
{ value: 'logout', label: 'Log out' },
|
|
245
|
+
{ value: 'help', label: 'Help' },
|
|
246
|
+
{ value: null, label: 'Quit' },
|
|
247
|
+
]
|
|
248
|
+
: [
|
|
249
|
+
{ value: 'login', label: 'Log in', hint: 'approve in your browser' },
|
|
250
|
+
{ value: 'help', label: 'Help' },
|
|
251
|
+
{ value: null, label: 'Quit' },
|
|
252
|
+
];
|
|
253
|
+
const account = config.apiKey ? createClient(config).me() : null;
|
|
254
|
+
account?.catch(() => {}); // shown on the start screen; the chosen command reports errors itself
|
|
255
|
+
const choice = await home({ version: VERSION, options, account, agentLabel: agent?.label });
|
|
256
|
+
if (choice === 'divine') return agent ? commands.divine({ flags }) : commands.agent({ args: [], flags });
|
|
257
|
+
if (choice) await commands[choice]({ args: [], flags });
|
|
258
|
+
},
|
|
259
|
+
|
|
260
|
+
async help() {
|
|
261
|
+
banner(c.marble('ask the Oracle · earn its favor'));
|
|
262
|
+
const command = (name, args, text) => ` ${c.bone(c.bold(name.padEnd(8)))}${c.slate(args.padEnd(18))}${c.marble(text)}`;
|
|
263
|
+
const option = (flag, text) => ` ${c.bone(flag.padEnd(24))}${c.marble(text)}`;
|
|
264
|
+
console.log([
|
|
265
|
+
` ${c.granite('usage')} elythia <command> [options]`,
|
|
266
|
+
` elythia ${c.slate('(no command) opens the start screen')}`,
|
|
267
|
+
'',
|
|
268
|
+
` ${chip('COMMANDS', 73)}`,
|
|
269
|
+
command('login', '', 'Log in by approving this terminal on the website'),
|
|
270
|
+
command('divine', '', 'Light the altar: your agent answers one riddle a minute'),
|
|
271
|
+
command('agent', '[status|test|off]', 'Set up the AI agent (Claude or OpenAI)'),
|
|
272
|
+
command('status', '', 'Treasure, riddles and account stats'),
|
|
273
|
+
command('logout', '', 'Log this computer out of Elythia'),
|
|
274
|
+
'',
|
|
275
|
+
` ${chip('OPTIONS', 73)}`,
|
|
276
|
+
option('-s, --server <url>', `Server to log in to ${c.slate(`(default: ${DEFAULT_SERVER})`)}`),
|
|
277
|
+
option('-v, --version', 'Show the version'),
|
|
278
|
+
'',
|
|
279
|
+
` ${chip('THE LAWS', 194)}`,
|
|
280
|
+
` ${c.marble('Every minute the Oracle asks one riddle, and your AI agent answers it.')}`,
|
|
281
|
+
` ${c.marble('No CPU work. A true answer is rewarded with a random 1–500')} ${c.gold(TICKER)}${c.marble('.')}`,
|
|
282
|
+
` ${c.marble('One try per riddle, so the model you choose matters.')}`,
|
|
283
|
+
'',
|
|
284
|
+
` ${c.slate(`Config: ${CONFIG_FILE}`)}`,
|
|
285
|
+
'',
|
|
286
|
+
].join('\n'));
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
async function testAgent(agent) {
|
|
291
|
+
try {
|
|
292
|
+
const choice = await spin(`Asking ${agent.label} a test riddle…`, agent.answer('Which Greek god ruled the sea?', ['Apollo', 'Hermes', 'Poseidon', 'Hephaestus']));
|
|
293
|
+
if (choice === 2) ok(`${agent.label} answered C (Poseidon): true`);
|
|
294
|
+
else info(`${agent.label} answered ${'ABCD'[choice]}, the true answer was C. It works, but double-check the model.`);
|
|
295
|
+
return true;
|
|
296
|
+
} catch (error) {
|
|
297
|
+
fail(`The agent test failed: ${error.message}`);
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
commands.mine = commands.divine;
|
|
303
|
+
commands.balance = commands.status;
|
|
304
|
+
commands.whoami = commands.status;
|
|
305
|
+
|
|
306
|
+
const { command, args, flags } = parseArgs(process.argv.slice(2));
|
|
307
|
+
|
|
308
|
+
if (flags.version) {
|
|
309
|
+
console.log(VERSION);
|
|
310
|
+
} else if (!command && !flags.help && isTTY && process.stdin.isTTY) {
|
|
311
|
+
await commands.menu({ flags });
|
|
312
|
+
} else if (!command || flags.help || command === 'help') {
|
|
313
|
+
await commands.help();
|
|
314
|
+
} else if (commands[command]) {
|
|
315
|
+
await commands[command]({ args, flags });
|
|
316
|
+
} else {
|
|
317
|
+
fail(`Unknown command: ${command}`);
|
|
318
|
+
info(`Run ${c.bold('elythia help')} to see all commands.`);
|
|
319
|
+
process.exit(1);
|
|
320
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "elythia-cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Elythia: an oracle game for AI agents. Your agent answers one riddle a minute from the terminal and earns ELYTHIA.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"elythia": "bin/elythia.js",
|
|
8
|
+
"ely": "bin/elythia.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"src",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://elythia.run",
|
|
16
|
+
"keywords": [
|
|
17
|
+
"elythia",
|
|
18
|
+
"oracle",
|
|
19
|
+
"greek",
|
|
20
|
+
"cli",
|
|
21
|
+
"ai-agent",
|
|
22
|
+
"claude",
|
|
23
|
+
"openai",
|
|
24
|
+
"quiz"
|
|
25
|
+
],
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=18"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@anthropic-ai/sdk": "^1.6.0"
|
|
31
|
+
},
|
|
32
|
+
"author": "elythia-cli",
|
|
33
|
+
"license": "MIT"
|
|
34
|
+
}
|
package/src/agent.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// The agent: an AI model that answers each of the Oracle's riddles for you. It runs on your own
|
|
2
|
+
// API key, straight from this machine to the provider; the key is never sent to Elythia.
|
|
3
|
+
|
|
4
|
+
export const PROVIDERS = {
|
|
5
|
+
anthropic: {
|
|
6
|
+
label: 'Claude (Anthropic)',
|
|
7
|
+
defaultModel: 'claude-opus-5-5',
|
|
8
|
+
env: 'ANTHROPIC_API_KEY',
|
|
9
|
+
keyHint: 'sk-ant-…',
|
|
10
|
+
},
|
|
11
|
+
openai: {
|
|
12
|
+
label: 'OpenAI or compatible',
|
|
13
|
+
defaultModel: 'gpt-5-mini',
|
|
14
|
+
env: 'OPENAI_API_KEY',
|
|
15
|
+
keyHint: 'sk-…',
|
|
16
|
+
baseUrl: 'https://api.openai.com/v1',
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const LETTERS = ['A', 'B', 'C', 'D'];
|
|
21
|
+
const TIMEOUT_MS = 40_000;
|
|
22
|
+
|
|
23
|
+
const SYSTEM_PROMPT = 'You are an agent consulting the Oracle in Elythia, a quiz game. Each riddle is one multiple-choice question that has exactly one correct option. Pick the correct option.';
|
|
24
|
+
|
|
25
|
+
const questionText = (question, choices) =>
|
|
26
|
+
`${question}\n\n${choices.map((choice, i) => `${LETTERS[i]}) ${choice}`).join('\n')}`;
|
|
27
|
+
|
|
28
|
+
// Claude models that take `effort`, and the ones that accept `fallbacks: "default"`.
|
|
29
|
+
const EFFORT_MODELS = /^claude-(opus-(5|4-[5-8])|sonnet-(5|4-6)|fable|mythos)/;
|
|
30
|
+
const FALLBACK_MODELS = new Set(['claude-opus-5-5', 'claude-opus-5', 'claude-fable-5-1', 'claude-sonnet-5-5']);
|
|
31
|
+
|
|
32
|
+
async function askClaude({ apiKey, model }, question, choices) {
|
|
33
|
+
const { default: Anthropic } = await import('@anthropic-ai/sdk');
|
|
34
|
+
const client = new Anthropic({ apiKey, maxRetries: 1, timeout: TIMEOUT_MS });
|
|
35
|
+
const request = {
|
|
36
|
+
model,
|
|
37
|
+
max_tokens: 8000,
|
|
38
|
+
system: SYSTEM_PROMPT,
|
|
39
|
+
output_config: {
|
|
40
|
+
...(EFFORT_MODELS.test(model) ? { effort: 'low' } : {}),
|
|
41
|
+
format: {
|
|
42
|
+
type: 'json_schema',
|
|
43
|
+
schema: {
|
|
44
|
+
type: 'object',
|
|
45
|
+
properties: { answer: { type: 'string', enum: LETTERS } },
|
|
46
|
+
required: ['answer'],
|
|
47
|
+
additionalProperties: false,
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
messages: [{ role: 'user', content: questionText(question, choices) }],
|
|
52
|
+
};
|
|
53
|
+
const response = FALLBACK_MODELS.has(model)
|
|
54
|
+
? await client.beta.messages.create({ ...request, betas: ['server-side-fallback-2026-07-01'], fallbacks: 'default' })
|
|
55
|
+
: await client.messages.create(request);
|
|
56
|
+
if (response.stop_reason === 'refusal') throw new Error('the model declined to answer');
|
|
57
|
+
const text = response.content.find((block) => block.type === 'text')?.text ?? '';
|
|
58
|
+
return JSON.parse(text).answer;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function askOpenAI({ apiKey, model, baseUrl }, question, choices) {
|
|
62
|
+
const res = await fetch(`${(baseUrl || PROVIDERS.openai.baseUrl).replace(/\/+$/, '')}/chat/completions`, {
|
|
63
|
+
method: 'POST',
|
|
64
|
+
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
|
65
|
+
body: JSON.stringify({
|
|
66
|
+
model,
|
|
67
|
+
messages: [
|
|
68
|
+
{ role: 'system', content: `${SYSTEM_PROMPT} Reply with only the letter of the correct option.` },
|
|
69
|
+
{ role: 'user', content: questionText(question, choices) },
|
|
70
|
+
],
|
|
71
|
+
}),
|
|
72
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
73
|
+
});
|
|
74
|
+
const data = await res.json().catch(() => ({}));
|
|
75
|
+
if (!res.ok) throw new Error(data.error?.message ?? `HTTP ${res.status}`);
|
|
76
|
+
return data.choices?.[0]?.message?.content ?? '';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Reads the agent settings from the config, with the provider's usual env var as a key fallback.
|
|
80
|
+
export function agentFromConfig(config) {
|
|
81
|
+
const settings = config.agent;
|
|
82
|
+
if (!settings?.provider || !PROVIDERS[settings.provider]) return null;
|
|
83
|
+
const apiKey = settings.apiKey || process.env.ELYTHIA_AGENT_KEY || process.env[PROVIDERS[settings.provider].env];
|
|
84
|
+
if (!apiKey) return null;
|
|
85
|
+
return createAgent({ ...settings, apiKey });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function createAgent({ provider, apiKey, model, baseUrl }) {
|
|
89
|
+
const spec = PROVIDERS[provider];
|
|
90
|
+
const resolvedModel = model || spec.defaultModel;
|
|
91
|
+
return {
|
|
92
|
+
provider,
|
|
93
|
+
model: resolvedModel,
|
|
94
|
+
label: `${provider === 'anthropic' ? 'Claude' : 'OpenAI'} · ${resolvedModel}`,
|
|
95
|
+
// Resolves with the chosen option's index (0–3).
|
|
96
|
+
async answer(question, choices) {
|
|
97
|
+
const ask = provider === 'anthropic' ? askClaude : askOpenAI;
|
|
98
|
+
const reply = await ask({ apiKey, model: resolvedModel, baseUrl }, question, choices);
|
|
99
|
+
const letter = String(reply).trim().toUpperCase().match(/\b[ABCD]\b|^[ABCD]/)?.[0];
|
|
100
|
+
if (!letter) throw new Error(`unexpected reply: ${String(reply).slice(0, 40)}`);
|
|
101
|
+
return LETTERS.indexOf(letter);
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export const maskKey = (key) => (key ? `${key.slice(0, 6)}…${key.slice(-4)}` : '–');
|
package/src/api.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
const { version: VERSION } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
4
|
+
|
|
5
|
+
export class ApiError extends Error {
|
|
6
|
+
constructor(status, message, data = {}) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.data = data;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// Server text is printed to the terminal; strip control characters so a server can never
|
|
14
|
+
// inject escape sequences that rewrite the screen.
|
|
15
|
+
export const clean = (value) => String(value).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '');
|
|
16
|
+
|
|
17
|
+
export function createClient({ server, apiKey }) {
|
|
18
|
+
async function request(method, pathname, body) {
|
|
19
|
+
let res;
|
|
20
|
+
try {
|
|
21
|
+
res = await fetch(new URL(pathname, server), {
|
|
22
|
+
method,
|
|
23
|
+
headers: {
|
|
24
|
+
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
|
|
25
|
+
'Content-Type': 'application/json',
|
|
26
|
+
'X-Elythia-Client': `elythia-cli/${VERSION}`,
|
|
27
|
+
},
|
|
28
|
+
body: method === 'GET' ? undefined : JSON.stringify(body ?? {}),
|
|
29
|
+
signal: AbortSignal.timeout(15_000),
|
|
30
|
+
});
|
|
31
|
+
} catch {
|
|
32
|
+
throw new ApiError(0, `Could not reach ${server}`);
|
|
33
|
+
}
|
|
34
|
+
const data = await res.json().catch(() => ({}));
|
|
35
|
+
if (!res.ok) throw new ApiError(res.status, clean(data.error ?? `HTTP ${res.status}`), data);
|
|
36
|
+
return data;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
me: () => request('GET', '/api/cli/me'),
|
|
41
|
+
loginStart: (client) => request('POST', '/api/cli/login/start', { client }),
|
|
42
|
+
loginPoll: (deviceCode) => request('POST', '/api/cli/login/poll', { deviceCode }),
|
|
43
|
+
heartbeat: () => request('POST', '/api/cli/heartbeat'),
|
|
44
|
+
round: () => request('GET', '/api/cli/round'),
|
|
45
|
+
answer: (roundId, choice, mode, model) => request('POST', '/api/cli/answer', { roundId, choice, mode, model }),
|
|
46
|
+
};
|
|
47
|
+
}
|