@oblyx-app/cli 0.0.0-stage → 1.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.
Files changed (3) hide show
  1. package/README.md +34 -2
  2. package/bin/oblyx.js +307 -0
  3. package/package.json +33 -4
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # Oblyx CLI
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
+ Private AI from your terminal. Every model on one USDG balance; prompts and replies are not stored.
4
+
5
+ ```sh
6
+ npm install -g @oblyx-app/cli
7
+ oblyx login # paste a key from https://oblyx.app/chat?keys=1
8
+ oblyx "explain a context window in plain words"
9
+ ```
10
+
11
+ ## Commands
12
+
13
+ | Command | What it does |
14
+ | --- | --- |
15
+ | `oblyx "question"` | Ask once; the answer streams back |
16
+ | `cat file \| oblyx "summarize"` | Pipe text in as context |
17
+ | `oblyx chat` | Interactive chat (`/model <id>`, `/clear`, `/exit`) |
18
+ | `oblyx image "prompt" -o out.png` | Generate an image and save it |
19
+ | `oblyx models [--kind text\|image]` | List models |
20
+ | `oblyx use <model>` | Set the default chat or image model |
21
+ | `oblyx balance` | Show your balance |
22
+ | `oblyx login [key]` / `oblyx logout` | Save or remove your API key |
23
+
24
+ Options: `-m/--model`, `-s/--system`, `--max-tokens`, `--no-stream`, `-q/--quiet`, `--json`.
25
+
26
+ Every reply prints its cost on stderr (`▪ model · tokens · cost · balance`), so piping stdout stays clean.
27
+
28
+ ## Configuration
29
+
30
+ The key is saved to `~/.config/oblyx/config.json` (permissions 600). You can also set:
31
+
32
+ - `OBLYX_API_KEY`: use this key instead of the saved one
33
+ - `OBLYX_BASE_URL`: server address (default `https://oblyx.app`)
34
+
35
+ Requires Node.js 18 or newer. No dependencies.
package/bin/oblyx.js ADDED
@@ -0,0 +1,307 @@
1
+ #!/usr/bin/env node
2
+ // Oblyx CLI — private AI from your terminal. No dependencies; Node 18+.
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import readline from 'node:readline';
7
+
8
+ const VERSION = '1.0.0';
9
+ const CONF_DIR = process.env.OBLYX_CONFIG_DIR || path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'oblyx');
10
+ const CONF_FILE = path.join(CONF_DIR, 'config.json');
11
+
12
+ // ── tiny styling (off when not a TTY or NO_COLOR is set) ──
13
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
14
+ const etty = process.stderr.isTTY && !process.env.NO_COLOR;
15
+ const paint = (on, code) => (s) => (on ? `\x1b[${code}m${s}\x1b[0m` : String(s));
16
+ const c = { amber: paint(tty, '38;5;214'), dim: paint(tty, '2'), bold: paint(tty, '1'), red: paint(tty, '31'), green: paint(tty, '32'), violet: paint(tty, '38;5;141') };
17
+ const ce = { dim: paint(etty, '2'), red: paint(etty, '31'), amber: paint(etty, '38;5;214') };
18
+ const say = (...a) => process.stdout.write(a.join(' ') + '\n');
19
+ const note = (...a) => process.stderr.write(a.join(' ') + '\n');
20
+ const die = (msg, code = 1) => { note(ce.red('✖ ') + msg); process.exit(code); };
21
+
22
+ // ── config ──
23
+ function loadConf() { try { return JSON.parse(fs.readFileSync(CONF_FILE, 'utf8')); } catch { return {}; } }
24
+ function saveConf(conf) {
25
+ fs.mkdirSync(CONF_DIR, { recursive: true, mode: 0o700 });
26
+ fs.writeFileSync(CONF_FILE, JSON.stringify(conf, null, 2) + '\n', { mode: 0o600 });
27
+ try { fs.chmodSync(CONF_FILE, 0o600); } catch {}
28
+ }
29
+ const conf = loadConf();
30
+ const BASE = (process.env.OBLYX_BASE_URL || conf.baseUrl || 'https://oblyx.app').replace(/\/+$/, '');
31
+ const KEY = () => process.env.OBLYX_API_KEY || conf.key || '';
32
+
33
+ // ── args ──
34
+ function parseArgs(argv) {
35
+ const out = { _: [], flags: {} };
36
+ const takes = new Set(['m', 'model', 's', 'system', 'o', 'out', 'kind', 'max-tokens', 'temperature', 't']);
37
+ const alias = { m: 'model', s: 'system', o: 'out', t: 'temperature', h: 'help', v: 'version' };
38
+ for (let i = 0; i < argv.length; i++) {
39
+ const a = argv[i];
40
+ if (a === '--') { out._.push(...argv.slice(i + 1)); break; }
41
+ if (a.startsWith('--')) {
42
+ let [k, v] = a.slice(2).split(/=(.*)/s);
43
+ if (v === undefined && takes.has(k)) v = argv[++i];
44
+ out.flags[alias[k] || k] = v === undefined ? true : v;
45
+ } else if (/^-[a-z]$/i.test(a)) {
46
+ const k = a[1];
47
+ out.flags[alias[k] || k] = takes.has(k) ? argv[++i] : true;
48
+ } else out._.push(a);
49
+ }
50
+ return out;
51
+ }
52
+
53
+ // ── http ──
54
+ async function api(p, opts = {}, { auth = true } = {}) {
55
+ const headers = { 'Content-Type': 'application/json', 'User-Agent': `oblyx-cli/${VERSION}`, ...(opts.headers || {}) };
56
+ if (auth) {
57
+ const k = KEY();
58
+ if (!k) die(`Not logged in. Run ${c.bold('oblyx login')} (get a key at ${BASE}/chat?keys=1).`);
59
+ headers.Authorization = `Bearer ${k}`;
60
+ }
61
+ let r;
62
+ try { r = await fetch(BASE + p, { ...opts, headers }); }
63
+ catch (e) { die(`Could not reach ${BASE} (${e.cause?.code || e.message}).`); }
64
+ if (!r.ok) {
65
+ let msg = `HTTP ${r.status}`;
66
+ try { const j = await r.json(); msg = j.error?.message || j.error || msg; } catch {}
67
+ if (r.status === 401) msg += ` — run ${c.bold('oblyx login')} with a valid key.`;
68
+ if (r.status === 402) msg += ` — top up at ${BASE}/chat`;
69
+ die(msg, r.status === 402 ? 2 : 1);
70
+ }
71
+ return r;
72
+ }
73
+ const money = (v, d = 4) => '$' + Number(v || 0).toFixed(d);
74
+
75
+ async function readStdin() {
76
+ if (process.stdin.isTTY) return '';
77
+ const chunks = [];
78
+ for await (const ch of process.stdin) chunks.push(ch);
79
+ return Buffer.concat(chunks).toString('utf8');
80
+ }
81
+
82
+ function ask(question, { hidden = false } = {}) {
83
+ return new Promise((resolve) => {
84
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: true });
85
+ if (hidden) {
86
+ const write = rl._writeToOutput.bind(rl);
87
+ rl._writeToOutput = (s) => write(s.startsWith(question) ? s : s.replace(/[^\r\n]/g, '•'));
88
+ }
89
+ rl.question(question, (a) => { rl.close(); if (hidden) process.stderr.write('\n'); resolve(a.trim()); });
90
+ });
91
+ }
92
+
93
+ // ── models ──
94
+ let modelCache;
95
+ async function models() {
96
+ if (!modelCache) modelCache = (await (await api('/v1/models', {}, { auth: false })).json()).data || [];
97
+ return modelCache;
98
+ }
99
+ async function pickModel(kind, wanted) {
100
+ const list = await models();
101
+ const pool = list.filter((m) => (m.kind || 'text') === kind);
102
+ if (wanted) {
103
+ const hit = list.find((m) => m.id === wanted) || pool.find((m) => m.id.endsWith('/' + wanted) || m.id.includes(wanted));
104
+ if (!hit) die(`Unknown model "${wanted}". See ${c.bold('oblyx models')}.`);
105
+ return hit.id;
106
+ }
107
+ const saved = kind === 'image' ? conf.imageModel : conf.model;
108
+ if (saved && pool.find((m) => m.id === saved)) return saved;
109
+ const pick = kind === 'text' ? pool.find((m) => /haiku|flash|mini/i.test(m.id)) || pool[0] : pool[0];
110
+ if (!pick) die(`No ${kind} models are available right now.`);
111
+ return pick.id;
112
+ }
113
+
114
+ // ── chat (streaming) ──
115
+ async function complete(messages, { model, flags, print = true }) {
116
+ const body = { model, messages, stream: !flags['no-stream'], oblyx_receipt: true };
117
+ if (flags['max-tokens']) body.max_tokens = Number(flags['max-tokens']);
118
+ if (flags.temperature) body.temperature = Number(flags.temperature);
119
+ const r = await api('/v1/chat/completions', { method: 'POST', body: JSON.stringify(body) });
120
+ let text = '', receipt = null;
121
+ if (!body.stream) {
122
+ const j = await r.json();
123
+ text = j.choices?.[0]?.message?.content || '';
124
+ receipt = j.oblyx_receipt;
125
+ if (print) process.stdout.write(text + (text.endsWith('\n') ? '' : '\n'));
126
+ return { text, receipt };
127
+ }
128
+ const dec = new TextDecoder(); let buf = '';
129
+ for await (const chunk of r.body) {
130
+ buf += dec.decode(chunk, { stream: true });
131
+ let i;
132
+ while ((i = buf.indexOf('\n')) >= 0) {
133
+ const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1);
134
+ if (!line.startsWith('data:')) continue;
135
+ const data = line.slice(5).trim();
136
+ if (data === '[DONE]') continue;
137
+ let o; try { o = JSON.parse(data); } catch { continue; }
138
+ if (o.oblyx_receipt) { receipt = o.oblyx_receipt; continue; }
139
+ if (o.error) die(o.error.message || 'Stream error');
140
+ const d = o.choices?.[0]?.delta?.content;
141
+ if (d) { text += d; if (print) process.stdout.write(d); }
142
+ }
143
+ }
144
+ if (print && !text.endsWith('\n')) process.stdout.write('\n');
145
+ return { text, receipt };
146
+ }
147
+ function showReceipt(r, flags) {
148
+ if (!r || flags.quiet || flags.q) return;
149
+ note(ce.dim(`▪ ${r.model} · ${r.prompt_tokens} in / ${r.completion_tokens} out · ${money(r.charged_usd, 5)} · balance ${money(r.balance_usd, 2)}`));
150
+ }
151
+
152
+ // ── commands ──
153
+ const cmds = {
154
+ async login(args) {
155
+ let key = args._[0] || process.env.OBLYX_API_KEY;
156
+ if (!key) {
157
+ note(`Get a key at ${ce.amber(BASE + '/chat?keys=1')} (Menu → API keys).`);
158
+ key = await ask('Paste your Oblyx API key: ', { hidden: true });
159
+ }
160
+ if (!/^(oblyx|veilo)_/.test(key)) die('That does not look like an Oblyx key (it starts with oblyx_).');
161
+ const r = await fetch(BASE + '/v1/balance', { headers: { Authorization: `Bearer ${key}` } }).catch(() => null);
162
+ if (!r) die(`Could not reach ${BASE}.`);
163
+ if (r.status === 401) die('That key was rejected.');
164
+ const j = await r.json();
165
+ saveConf({ ...conf, key });
166
+ say(c.green('✔') + ` Logged in as ${c.bold(short(j.address))} · balance ${c.amber(money(j.balance_usd, 2))}`);
167
+ note(ce.dim(`Key saved to ${CONF_FILE}`));
168
+ },
169
+ async logout() {
170
+ const { key, ...rest } = conf; saveConf(rest);
171
+ say(c.green('✔') + ' Logged out. Revoke the key in Oblyx Chat → API keys if you no longer need it.');
172
+ },
173
+ async balance(args) {
174
+ const j = await (await api('/v1/balance')).json();
175
+ if (args.flags.json) return say(JSON.stringify(j));
176
+ say(`${c.amber(money(j.balance_usd, 2))} ${c.dim(short(j.address))}`);
177
+ },
178
+ async models(args) {
179
+ const kind = args.flags.kind;
180
+ let list = await models();
181
+ if (kind) list = list.filter((m) => (m.kind || 'text') === kind);
182
+ if (args.flags.json) return say(JSON.stringify(list, null, 2));
183
+ const def = { text: conf.model, image: conf.imageModel };
184
+ const w = Math.min(46, Math.max(...list.map((m) => m.id.length)));
185
+ for (const m of list) {
186
+ const k = m.kind || 'text';
187
+ const mark = def[k] === m.id ? c.amber('●') : ' ';
188
+ say(`${mark} ${m.id.padEnd(w)} ${c.dim(k.padEnd(5))} ${m.sealed ? c.violet('sealed ') : ''}${c.dim(m.name || '')}`);
189
+ }
190
+ note(ce.dim(`\n${list.length} models · set a default with: oblyx use <model>`));
191
+ },
192
+ async use(args) {
193
+ const want = args._[0];
194
+ if (!want) die('Usage: oblyx use <model>');
195
+ const list = await models();
196
+ const m = list.find((x) => x.id === want) || list.find((x) => x.id.endsWith('/' + want) || x.id.includes(want));
197
+ if (!m) die(`Unknown model "${want}".`);
198
+ if (!['text', 'image'].includes(m.kind || 'text')) die('Only chat and image models can be defaults in the CLI.');
199
+ saveConf({ ...conf, [(m.kind || 'text') === 'image' ? 'imageModel' : 'model']: m.id });
200
+ say(c.green('✔') + ` Default ${(m.kind || 'text') === 'image' ? 'image' : 'chat'} model: ${c.bold(m.id)}`);
201
+ },
202
+ async ask(args) {
203
+ const stdin = await readStdin();
204
+ const q = args._.join(' ').trim();
205
+ if (!q && !stdin.trim()) die('Usage: oblyx "your question" (or pipe text in: cat file | oblyx "summarize")');
206
+ const content = stdin.trim() ? (q ? `${q}\n\n"""\n${stdin.trim()}\n"""` : stdin.trim()) : q;
207
+ const model = await pickModel('text', args.flags.model);
208
+ const messages = [];
209
+ if (args.flags.system) messages.push({ role: 'system', content: String(args.flags.system) });
210
+ messages.push({ role: 'user', content });
211
+ const { receipt } = await complete(messages, { model, flags: args.flags });
212
+ showReceipt(receipt, args.flags);
213
+ },
214
+ async chat(args) {
215
+ if (!process.stdin.isTTY) return cmds.ask(args);
216
+ let model = await pickModel('text', args.flags.model);
217
+ let history = args.flags.system ? [{ role: 'system', content: String(args.flags.system) }] : [];
218
+ let spent = 0;
219
+ note(`${ce.amber('oblyx chat')} ${ce.dim(`· ${model} · /model <id> · /clear · /exit`)}`);
220
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true, historySize: 200 });
221
+ const prompt = () => rl.setPrompt(c.amber('› ')) || rl.prompt();
222
+ prompt();
223
+ for await (const line of rl) {
224
+ const t = line.trim();
225
+ if (!t) { prompt(); continue; }
226
+ if (t === '/exit' || t === '/quit') break;
227
+ if (t === '/clear') { history = history.filter((m) => m.role === 'system'); note(ce.dim('Conversation cleared.')); prompt(); continue; }
228
+ if (t.startsWith('/model')) {
229
+ const want = t.split(/\s+/)[1];
230
+ if (want) { try { model = await pickModel('text', want); } catch {} }
231
+ note(ce.dim(`Model: ${model}`)); prompt(); continue;
232
+ }
233
+ history.push({ role: 'user', content: t });
234
+ rl.pause();
235
+ const { text, receipt } = await complete(history.slice(-24), { model, flags: args.flags });
236
+ history.push({ role: 'assistant', content: text });
237
+ if (receipt) spent += Number(receipt.charged_usd || 0);
238
+ showReceipt(receipt, args.flags);
239
+ rl.resume(); prompt();
240
+ }
241
+ rl.close();
242
+ note(ce.dim(`Session cost ${money(spent, 4)}. Nothing was stored.`));
243
+ },
244
+ async image(args) {
245
+ const q = args._.join(' ').trim() || (await readStdin()).trim();
246
+ if (!q) die('Usage: oblyx image "a pixel-art fox at night" [-o fox.png]');
247
+ const model = await pickModel('image', args.flags.model);
248
+ if (etty) note(ce.dim(`Generating with ${model}…`));
249
+ const r = await api('/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model, messages: [{ role: 'user', content: q }], oblyx_receipt: true }) });
250
+ const j = await r.json();
251
+ const imgs = j.choices?.[0]?.message?.images || [];
252
+ if (!imgs.length) die(j.choices?.[0]?.message?.content || 'The model returned no image.');
253
+ const outs = [];
254
+ imgs.forEach((im, i) => {
255
+ const url = im.image_url?.url || im.url || '';
256
+ const m = url.match(/^data:image\/(\w+);base64,(.+)$/s);
257
+ if (!m) return;
258
+ const ext = m[1] === 'jpeg' ? 'jpg' : m[1];
259
+ let file = args.flags.out ? String(args.flags.out) : `oblyx-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}.${ext}`;
260
+ if (imgs.length > 1) file = file.replace(/(\.\w+)?$/, `-${i + 1}$1`);
261
+ fs.writeFileSync(file, Buffer.from(m[2], 'base64'));
262
+ outs.push(file);
263
+ });
264
+ for (const f of outs) say(c.green('✔') + ' ' + path.resolve(f));
265
+ showReceipt(j.oblyx_receipt, args.flags);
266
+ },
267
+ help() {
268
+ say(`${c.amber('oblyx')} ${c.dim('v' + VERSION)} — private AI from your terminal
269
+
270
+ ${c.bold('Usage')}
271
+ oblyx "question" Ask once, answer streams back
272
+ cat notes.md | oblyx "summarize" Pipe text in as context
273
+ oblyx chat Interactive chat (/model, /clear, /exit)
274
+ oblyx image "prompt" [-o f.png] Generate an image and save it
275
+ oblyx models [--kind text|image|video|music]
276
+ oblyx use <model> Set your default chat or image model
277
+ oblyx balance Show your USDG balance
278
+ oblyx login [key] | logout
279
+
280
+ ${c.bold('Options')}
281
+ -m, --model <id> Model for this call
282
+ -s, --system <text> System prompt
283
+ --max-tokens <n> Cap the reply length
284
+ --no-stream Wait for the full answer
285
+ -q, --quiet Hide the cost line
286
+ --json JSON output (models, balance)
287
+
288
+ ${c.bold('Environment')}
289
+ OBLYX_API_KEY use this key instead of the saved one
290
+ OBLYX_BASE_URL server (default https://oblyx.app)
291
+
292
+ Keys: ${BASE}/chat?keys=1 · Docs: ${BASE}/docs.html`);
293
+ },
294
+ };
295
+ const short = (a = '') => (a.length > 12 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a);
296
+
297
+ // ── main ──
298
+ const args = parseArgs(process.argv.slice(2));
299
+ if (args.flags.version) { say(VERSION); process.exit(0); }
300
+ const first = args._[0];
301
+ let run;
302
+ if (args.flags.help || first === 'help') run = cmds.help;
303
+ else if (first && Object.hasOwn(cmds, first) && first !== 'help') { args._.shift(); run = cmds[first]; }
304
+ else if (!first && process.stdin.isTTY) run = cmds.chat;
305
+ else run = cmds.ask;
306
+ process.on('SIGINT', () => { process.stdout.write(tty ? '\x1b[0m\n' : '\n'); process.exit(130); });
307
+ Promise.resolve(run(args)).catch((e) => die(e?.message || String(e)));
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@oblyx-app/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Oblyx CLI: private AI from your terminal. Every model, one balance, nothing stored.",
5
+ "type": "module",
6
+ "bin": {
7
+ "oblyx": "bin/oblyx.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "README.md"
12
+ ],
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "keywords": [
17
+ "ai",
18
+ "cli",
19
+ "llm",
20
+ "chat",
21
+ "privacy",
22
+ "openai-compatible",
23
+ "oblyx"
24
+ ],
25
+ "homepage": "https://oblyx.app",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/oblyx-ai/veilo.git",
29
+ "directory": "cli"
30
+ },
31
+ "author": "Oblyx <dev@oblyx.app>",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ }
35
+ }