z1llm 0.0.1 → 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 +1 -1
- package/README.md +82 -2
- package/dist/brand.js +2 -0
- package/dist/choose.js +105 -0
- package/dist/cli.js +604 -0
- package/dist/key.js +28 -0
- package/dist/terminal.js +534 -0
- package/dist/update.js +47 -0
- package/package.json +18 -6
package/dist/cli.js
ADDED
|
@@ -0,0 +1,604 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// z1llm — Zero1LLM from the terminal (docs/SDK_PLAN.md §8, the CLI part 1, D232). A thin layer over @zero1llm/sdk: the
|
|
3
|
+
// app must be open with Settings → Local API on. Results go to stdout, spinners and questions to stderr.
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { createInterface } from 'node:readline';
|
|
8
|
+
import { parseArgs } from 'node:util';
|
|
9
|
+
import { APP_NAME, discover, Zero1LLM, Zero1LLMError } from '@zero1llm/sdk';
|
|
10
|
+
import { either, match, pick } from './choose.js';
|
|
11
|
+
import { CLI_NAME } from './brand.js';
|
|
12
|
+
import { configFile, savedKey, saveKey } from './key.js';
|
|
13
|
+
import { updateNotice } from './update.js';
|
|
14
|
+
import { B, bar, C, chatKeyboard, commandRow, DIM, G, inputBox, messages, ownKeys, piped, R, render, secret, select, slashMatches, spinner, toBottom, writing } from './terminal.js';
|
|
15
|
+
const OPTIONS = {
|
|
16
|
+
help: { type: 'boolean', short: 'h' },
|
|
17
|
+
version: { type: 'boolean', short: 'v' },
|
|
18
|
+
json: { type: 'boolean' },
|
|
19
|
+
model: { type: 'string', short: 'm' },
|
|
20
|
+
web: { type: 'boolean' },
|
|
21
|
+
'no-save': { type: 'boolean' },
|
|
22
|
+
plain: { type: 'boolean' },
|
|
23
|
+
shape: { type: 'string' },
|
|
24
|
+
seconds: { type: 'string' },
|
|
25
|
+
output: { type: 'string', short: 'o' },
|
|
26
|
+
clear: { type: 'boolean' },
|
|
27
|
+
};
|
|
28
|
+
const HELP = {
|
|
29
|
+
'': `${B(CLI_NAME)} — ${APP_NAME} from the terminal. ${APP_NAME} must be open, with Settings → Local API on.
|
|
30
|
+
|
|
31
|
+
${B('Usage')} ${CLI_NAME} <command> [options]
|
|
32
|
+
|
|
33
|
+
${C('status')} is ${APP_NAME} open, the Local API on, your key found
|
|
34
|
+
${C('key')} save your API key once (from Settings → Local API)
|
|
35
|
+
|
|
36
|
+
${C('models')} your models; loaded ones marked
|
|
37
|
+
${C('load')} [model] load a model, with a progress bar
|
|
38
|
+
${C('eject')} [model] unload a model, freeing its memory
|
|
39
|
+
|
|
40
|
+
${C('ask')} "question" one answer, then done
|
|
41
|
+
${C('chat')} [model] a back-and-forth chat (type / for commands)
|
|
42
|
+
|
|
43
|
+
${C('image')} "prompt" make a picture, saved as a file
|
|
44
|
+
${C('video')} "prompt" make a short video, saved as a file
|
|
45
|
+
|
|
46
|
+
${C('version')} this program's version
|
|
47
|
+
${C('help')} [command] more about a command
|
|
48
|
+
|
|
49
|
+
A model can be part of its name (${CLI_NAME} load qwen), or left out to pick from a list.
|
|
50
|
+
Every command takes --json for output scripts can read.`,
|
|
51
|
+
status: `${CLI_NAME} status — is ${APP_NAME} open, its Local API on, and your key found and accepted.`,
|
|
52
|
+
key: `${CLI_NAME} key [--clear]
|
|
53
|
+
|
|
54
|
+
Saves your API key, so you needn't set ZERO1LLM_API_KEY. Copy the key in ${APP_NAME} → Settings → Local API,
|
|
55
|
+
then paste it when asked (it isn't shown), or pipe it in: pbpaste | ${CLI_NAME} key
|
|
56
|
+
--clear remove the saved key
|
|
57
|
+
The key is kept in ${configFile()}, readable only by you. ZERO1LLM_API_KEY, when set, is used instead.`,
|
|
58
|
+
models: `${CLI_NAME} models — the models on this computer (size, how well each runs here, loaded or not) and the
|
|
59
|
+
cloud models ${APP_NAME} offers.`,
|
|
60
|
+
load: `${CLI_NAME} load [model]
|
|
61
|
+
|
|
62
|
+
Loads a model on this computer, showing how far it is. Give part of its name (${CLI_NAME} load gemma), or none to
|
|
63
|
+
pick from a list.`,
|
|
64
|
+
eject: `${CLI_NAME} eject [model] — stops a loaded model, freeing its memory. Leave the name out to pick.`,
|
|
65
|
+
ask: `${CLI_NAME} ask "question" [options]
|
|
66
|
+
|
|
67
|
+
One answer from ${APP_NAME}'s own chat (web search, memory, your tools), shown formatted. Saved in the app's sidebar.
|
|
68
|
+
-m, --model <name> which model (part of its name; default the app's current one)
|
|
69
|
+
--web search the web first
|
|
70
|
+
--no-save keep it out of the app's sidebar
|
|
71
|
+
--plain the model alone, without the app's chat (no web, memory or tools; not saved)
|
|
72
|
+
Piped text is added to the question: cat notes.txt | ${CLI_NAME} ask "summarise this"`,
|
|
73
|
+
chat: `${CLI_NAME} chat [model] [options]
|
|
74
|
+
|
|
75
|
+
A back-and-forth chat in the terminal, one chat in the app's sidebar. Type / for its commands: /web turns web
|
|
76
|
+
search on or off, /model switches model (/model qwen: by part of its name), /clear starts a new chat
|
|
77
|
+
and clears the screen (/new too), /exit (or Ctrl+D) leaves. Shift+Enter starts a new line (in Apple's Terminal:
|
|
78
|
+
Option+Enter, with "Use Option as Meta key" on in Settings → Profiles → Keyboard); lines pasted at once go as one
|
|
79
|
+
message.
|
|
80
|
+
Takes --web, --no-save and --plain as ${CLI_NAME} ask does.`,
|
|
81
|
+
image: `${CLI_NAME} image "prompt" [options]
|
|
82
|
+
|
|
83
|
+
Makes a picture where and as ${APP_NAME}'s chat would, and saves it as a PNG in ~/Pictures/${APP_NAME}.
|
|
84
|
+
--shape <shape> 1:1, 16:9, 9:16, 4:3, 3:4 or 4:5 (default the one set in the app)
|
|
85
|
+
-o, --output <path> a file to save it as, or a folder to save it in`,
|
|
86
|
+
video: `${CLI_NAME} video "prompt" [options]
|
|
87
|
+
|
|
88
|
+
Makes a short video on this computer and saves it as a WebM in your Movies (Mac) or Videos folder, under ${APP_NAME}.
|
|
89
|
+
It can take several minutes.
|
|
90
|
+
--seconds <n> how long, up to 10
|
|
91
|
+
--shape <shape> landscape or portrait
|
|
92
|
+
-o, --output <path> a file to save it as, or a folder to save it in`,
|
|
93
|
+
version: `${CLI_NAME} version — this program's version.`,
|
|
94
|
+
help: `${CLI_NAME} help [command] — what the commands do.`,
|
|
95
|
+
};
|
|
96
|
+
/** What `/` offers in a chat. */
|
|
97
|
+
const CHAT_COMMANDS = [
|
|
98
|
+
['/web', 'turn web search on or off'],
|
|
99
|
+
['/model', 'switch to another model'],
|
|
100
|
+
['/clear', 'start a new chat, clearing the screen'],
|
|
101
|
+
['/help', 'these commands'],
|
|
102
|
+
['/exit', 'leave (or Ctrl+D)'],
|
|
103
|
+
];
|
|
104
|
+
/** A mistake in how the command was used, or something to tell the user; no stack. */
|
|
105
|
+
class CliError extends Error {
|
|
106
|
+
}
|
|
107
|
+
/** The user left a list with Esc or Ctrl+C. */
|
|
108
|
+
class Cancelled extends Error {
|
|
109
|
+
}
|
|
110
|
+
/** An error to show as its message alone. */
|
|
111
|
+
const known = (e) => e instanceof Zero1LLMError || e instanceof CliError;
|
|
112
|
+
const print = (s) => process.stdout.write(`${s}\n`);
|
|
113
|
+
const note = (s) => process.stderr.write(`${s}\n`);
|
|
114
|
+
const json = (v) => print(JSON.stringify(v, null, 2));
|
|
115
|
+
const terminal = () => process.stdin.isTTY === true && process.stderr.isTTY === true;
|
|
116
|
+
const client = () => new Zero1LLM({ ...(process.env.ZERO1LLM_API_KEY ? {} : { apiKey: savedKey() }) });
|
|
117
|
+
const localChoice = (m) => ({
|
|
118
|
+
id: m.id,
|
|
119
|
+
name: m.name,
|
|
120
|
+
detail: [`${m.sizeGB} GB`.padStart(8), (m.fit ?? '').padEnd(6), m.state === 'loaded' ? '● loaded' : ''].join(' ').trimEnd(),
|
|
121
|
+
});
|
|
122
|
+
/** The model the user means: from part of its name, or picked from a list in a terminal. */
|
|
123
|
+
async function choose(query, choices, title) {
|
|
124
|
+
if (!choices.length)
|
|
125
|
+
throw new CliError(`No models to choose from: see ${CLI_NAME} models.`);
|
|
126
|
+
const chosen = async (list, filter = '') => {
|
|
127
|
+
const c = await pick(title, list, filter);
|
|
128
|
+
if (!c)
|
|
129
|
+
throw new Cancelled();
|
|
130
|
+
return c;
|
|
131
|
+
};
|
|
132
|
+
if (!query) {
|
|
133
|
+
if (terminal())
|
|
134
|
+
return chosen(choices);
|
|
135
|
+
throw new CliError(`Name a model: see ${CLI_NAME} models.`);
|
|
136
|
+
}
|
|
137
|
+
const m = match(query, choices);
|
|
138
|
+
if ('found' in m)
|
|
139
|
+
return m.found;
|
|
140
|
+
if ('several' in m) {
|
|
141
|
+
if (terminal())
|
|
142
|
+
return chosen(choices, query);
|
|
143
|
+
throw new CliError(`"${query}" matches ${either(m.several)}. Give more of the name.`);
|
|
144
|
+
}
|
|
145
|
+
const hint = m.none.length ? ` Did you mean ${either(m.none)}?` : '';
|
|
146
|
+
if (!terminal())
|
|
147
|
+
throw new CliError(`No model "${query}".${hint} See ${CLI_NAME} models.`);
|
|
148
|
+
note(`${R('✗')} No model "${query}".${hint}`);
|
|
149
|
+
return chosen(choices);
|
|
150
|
+
}
|
|
151
|
+
/** Where pictures and videos go unless -o says: ~/Pictures/Zero1LLM, and ~/Movies/Zero1LLM (Mac) or ~/Videos/Zero1LLM. */
|
|
152
|
+
const mediaFolder = (kind) => join(homedir(), kind === 'image' ? 'Pictures' : process.platform === 'darwin' ? 'Movies' : 'Videos', APP_NAME);
|
|
153
|
+
const EXT = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/webp': '.webp', 'video/webm': '.webm', 'video/mp4': '.mp4' };
|
|
154
|
+
/** A data URL's file extension, from its type. */
|
|
155
|
+
const extOf = (url, fallback) => EXT[/^data:([^;,]+)/.exec(url)?.[1] ?? ''] ?? fallback;
|
|
156
|
+
/**
|
|
157
|
+
* A picture, video or document the app's chat made (a data URL), saved where `z1llm image` / `video` save theirs,
|
|
158
|
+
* documents in ~/Documents/Zero1LLM under their own name; returns the path.
|
|
159
|
+
*/
|
|
160
|
+
function saveMade(kind, url, name) {
|
|
161
|
+
const dir = kind === 'file' ? join(homedir(), 'Documents', APP_NAME) : mediaFolder(kind === 'picture' ? 'image' : 'video');
|
|
162
|
+
mkdirSync(dir, { recursive: true });
|
|
163
|
+
const n = new Date();
|
|
164
|
+
const two = (v) => String(v).padStart(2, '0');
|
|
165
|
+
const stamp = `${n.getFullYear()}-${two(n.getMonth() + 1)}-${two(n.getDate())} ${two(n.getHours())}-${two(n.getMinutes())}-${two(n.getSeconds())}`;
|
|
166
|
+
// Nothing a file name can't hold on any system (Windows refuses : * ? " < > |).
|
|
167
|
+
const own = name?.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_');
|
|
168
|
+
const dot = own?.lastIndexOf('.') ?? -1;
|
|
169
|
+
const file = own && dot > 0 ? fileFor(dir, own.slice(0, dot), own.slice(dot)) : fileFor(dir, `${kind} ${stamp}`, extOf(url, kind === 'picture' ? '.png' : kind === 'video' ? '.webm' : ''));
|
|
170
|
+
writeFileSync(file, Buffer.from(url.slice(url.indexOf(',') + 1), 'base64'));
|
|
171
|
+
return file;
|
|
172
|
+
}
|
|
173
|
+
/** A file in `dir` named from the prompt that isn't taken: "a red fox" → a-red-fox.png, then a-red-fox-2.png. */
|
|
174
|
+
function fileFor(dir, prompt, ext) {
|
|
175
|
+
const base = prompt.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || APP_NAME.toLowerCase();
|
|
176
|
+
for (let n = 1;; n++) {
|
|
177
|
+
const f = join(dir, `${base}${n > 1 ? `-${n}` : ''}${ext}`);
|
|
178
|
+
if (!existsSync(f))
|
|
179
|
+
return f;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async function status(z, flags) {
|
|
183
|
+
// The address set by hand (ZERO1LLM_BASE_URL) is where the client looks, so status looks there too.
|
|
184
|
+
const set = process.env.ZERO1LLM_BASE_URL;
|
|
185
|
+
const found = set ?? discover();
|
|
186
|
+
const key = process.env.ZERO1LLM_API_KEY ? 'ZERO1LLM_API_KEY' : savedKey() ? configFile() : undefined;
|
|
187
|
+
let error;
|
|
188
|
+
let models = [];
|
|
189
|
+
try {
|
|
190
|
+
if (key)
|
|
191
|
+
models = await z.models.list();
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
if (!(e instanceof Zero1LLMError))
|
|
195
|
+
throw e;
|
|
196
|
+
error = e;
|
|
197
|
+
}
|
|
198
|
+
if (!found || !key || error)
|
|
199
|
+
process.exitCode = 1;
|
|
200
|
+
if (flags.json)
|
|
201
|
+
return json({ baseURL: z.baseURL, appFound: Boolean(found), key: key ?? null, ok: Boolean(found && key && !error), ...(error ? { error: { code: error.code, message: error.message } } : {}) });
|
|
202
|
+
const ok = (good, text) => print(`${good ? G('✔') : R('✗')} ${text}`);
|
|
203
|
+
ok(Boolean(found), set ? `${APP_NAME}'s Local API set to ${set} (ZERO1LLM_BASE_URL)` : found ? `${APP_NAME} is open, its Local API at ${found}` : `${APP_NAME} isn't open, or its Local API is off (Settings → Local API).`);
|
|
204
|
+
ok(Boolean(key), key ? `Key from ${key}` : `No key: run ${CLI_NAME} key`);
|
|
205
|
+
if (key && !error)
|
|
206
|
+
ok(true, `Answering: ${models.filter(m => m.local).length} models on this computer (${models.filter(m => m.loaded).length} loaded), ${models.filter(m => !m.local).length} in the cloud`);
|
|
207
|
+
else if (error && (found || error.code !== 'NOT_RUNNING'))
|
|
208
|
+
ok(false, error.code === 'UNAUTHORIZED' ? `The key isn't accepted: run ${CLI_NAME} key` : error.message);
|
|
209
|
+
}
|
|
210
|
+
async function key(flags) {
|
|
211
|
+
if (flags.clear) {
|
|
212
|
+
saveKey(undefined);
|
|
213
|
+
return print('Removed the saved key.');
|
|
214
|
+
}
|
|
215
|
+
const k = process.stdin.isTTY ? await secret(`Paste the key from ${APP_NAME} → Settings → Local API: `).catch(() => '') : (await piped()).trim();
|
|
216
|
+
if (!k)
|
|
217
|
+
throw new CliError('No key given.');
|
|
218
|
+
try {
|
|
219
|
+
await new Zero1LLM({ apiKey: k }).models.list();
|
|
220
|
+
}
|
|
221
|
+
catch (e) {
|
|
222
|
+
if (!(e instanceof Zero1LLMError))
|
|
223
|
+
throw e;
|
|
224
|
+
if (e.code === 'UNAUTHORIZED')
|
|
225
|
+
throw new CliError(`${APP_NAME} doesn't accept that key. Copy it again from Settings → Local API.`);
|
|
226
|
+
saveKey(k);
|
|
227
|
+
return print(`${G('✔')} Key saved. It couldn't be checked: ${e.message}`);
|
|
228
|
+
}
|
|
229
|
+
saveKey(k);
|
|
230
|
+
print(`${G('✔')} Key saved, and ${APP_NAME} accepts it.`);
|
|
231
|
+
}
|
|
232
|
+
async function models(z, flags) {
|
|
233
|
+
const [local, all] = await Promise.all([z.models.local(), z.models.list()]);
|
|
234
|
+
const cloud = all.filter(m => !m.local);
|
|
235
|
+
if (flags.json)
|
|
236
|
+
return json({ local, cloud });
|
|
237
|
+
print(B('On this computer'));
|
|
238
|
+
if (!local.length)
|
|
239
|
+
print(DIM(` None yet: download one in ${APP_NAME} → Models.`));
|
|
240
|
+
const width = Math.max(...local.map(m => m.name.length), 0);
|
|
241
|
+
for (const m of local) {
|
|
242
|
+
print(` ${m.name.padEnd(width)} ${`${m.sizeGB} GB`.padStart(8)} ${(m.fit ?? '').padEnd(10)} ${m.state === 'loaded' ? G('● loaded') : m.state === 'loading' ? C('… loading') : ''}`);
|
|
243
|
+
}
|
|
244
|
+
for (const owner of new Set(cloud.map(m => m.ownedBy))) {
|
|
245
|
+
print(`\n${B(owner)}`);
|
|
246
|
+
for (const m of cloud)
|
|
247
|
+
if (m.ownedBy === owner)
|
|
248
|
+
print(` ${m.name}`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/** Loads a model on this computer with a progress bar. */
|
|
252
|
+
async function loadWithBar(z, id, name) {
|
|
253
|
+
const s = spinner(`Loading ${name}…`);
|
|
254
|
+
return z.models
|
|
255
|
+
.load(id, { onProgress: p => s.update(p.stage === 'engine' ? 'Setting up the engine (first time only)…' : `Loading ${name} ${p.percent === undefined ? '…' : bar(p.percent)}`) })
|
|
256
|
+
.finally(s.stop);
|
|
257
|
+
}
|
|
258
|
+
async function load(z, query, flags) {
|
|
259
|
+
const local = await z.models.local();
|
|
260
|
+
const c = await choose(query, local.map(localChoice), 'Which model to load?');
|
|
261
|
+
const was = local.find(m => m.id === c.id);
|
|
262
|
+
if (was?.state === 'loaded')
|
|
263
|
+
return flags.json ? json(was) : print(`${G('✔')} ${c.name} is already loaded.`);
|
|
264
|
+
const m = await loadWithBar(z, c.id, c.name);
|
|
265
|
+
if (flags.json)
|
|
266
|
+
return json(m);
|
|
267
|
+
print(`${G('✔')} ${m.name} is loaded${m.contextSize ? DIM(` (remembers ${m.contextSize.toLocaleString('en')} tokens)`) : ''}.`);
|
|
268
|
+
}
|
|
269
|
+
async function eject(z, query, flags) {
|
|
270
|
+
const loaded = (await z.models.local()).filter(m => m.state === 'loaded');
|
|
271
|
+
if (!loaded.length)
|
|
272
|
+
return flags.json ? json(null) : print('No model is loaded.');
|
|
273
|
+
const c = await choose(query, loaded.map(localChoice), 'Which model to unload?');
|
|
274
|
+
const m = await z.models.eject(c.id);
|
|
275
|
+
if (flags.json)
|
|
276
|
+
return json(m);
|
|
277
|
+
print(`${G('✔')} ${c.name} is unloaded.`);
|
|
278
|
+
}
|
|
279
|
+
/** The model asked for with --model or a name, as an id; undefined for the app's choice. */
|
|
280
|
+
async function chatModel(z, query, required) {
|
|
281
|
+
if (!query && !required)
|
|
282
|
+
return undefined;
|
|
283
|
+
const all = await z.models.list();
|
|
284
|
+
return (await choose(query, all.map(m => chatChoice(m)), 'Which model?')).id;
|
|
285
|
+
}
|
|
286
|
+
const chatChoice = (m, current) => ({
|
|
287
|
+
id: m.id,
|
|
288
|
+
name: m.name,
|
|
289
|
+
detail: [m.local ? (m.loaded ? '● loaded' : 'on this computer') : m.ownedBy, m.id === current ? '← now' : ''].filter(Boolean).join(' '),
|
|
290
|
+
});
|
|
291
|
+
/**
|
|
292
|
+
* `/model` in a chat: the list (or part of a name) while the chat's own line reading waits, then the model loaded with
|
|
293
|
+
* its bar, so the next message doesn't wait on it unseen.
|
|
294
|
+
*/
|
|
295
|
+
async function switchModel(z, query, current, keys) {
|
|
296
|
+
const all = await z.models.list();
|
|
297
|
+
const c = await ownKeys(keys, () => choose(query, all.map(m => chatChoice(m, current)), 'Chat with which model?'));
|
|
298
|
+
const m = all.find(x => x.id === c.id);
|
|
299
|
+
if (m.local && !m.loaded)
|
|
300
|
+
await loadWithBar(z, m.id, m.name);
|
|
301
|
+
note(DIM(`Now chatting with ${m.name}.`));
|
|
302
|
+
return m.id;
|
|
303
|
+
}
|
|
304
|
+
/** One message to the app's chat: Allow / Deny asked on the terminal; the finished answer shown formatted. */
|
|
305
|
+
async function converse(z, options, flags, keys) {
|
|
306
|
+
const chat = z.assistant.send(options);
|
|
307
|
+
let s = spinner('Thinking…');
|
|
308
|
+
let entry;
|
|
309
|
+
let asked;
|
|
310
|
+
const saved = [];
|
|
311
|
+
try {
|
|
312
|
+
for await (const ev of chat) {
|
|
313
|
+
if (ev.type === 'status' && !entry && typeof ev.status.chatModel === 'string')
|
|
314
|
+
s.update(`${ev.status.chatModel} is thinking…`);
|
|
315
|
+
if (ev.type === 'progress')
|
|
316
|
+
s.update(ev.text);
|
|
317
|
+
if (ev.type === 'picture' || ev.type === 'video' || ev.type === 'file')
|
|
318
|
+
saved.push({ kind: ev.type === 'file' ? 'document' : ev.type, file: saveMade(ev.type, ev.url, ev.name) });
|
|
319
|
+
if (ev.type !== 'answer')
|
|
320
|
+
continue;
|
|
321
|
+
entry = ev.entry;
|
|
322
|
+
// Each ask or set of questions once (the entry comes again with every update).
|
|
323
|
+
const ask = entry.status === 'asking' ? entry.ask : entry.status === 'question' ? JSON.stringify(entry.questions) : undefined;
|
|
324
|
+
if (ask !== undefined && ask !== asked) {
|
|
325
|
+
asked = ask;
|
|
326
|
+
s.stop();
|
|
327
|
+
if (entry.status === 'asking')
|
|
328
|
+
await chat.decide(await allow(entry.ask, keys));
|
|
329
|
+
else
|
|
330
|
+
await chat.answer(await answer(entry.questions ?? [], keys));
|
|
331
|
+
s = spinner('Working…');
|
|
332
|
+
}
|
|
333
|
+
else if (entry.status === 'streaming')
|
|
334
|
+
s.update(() => writing(entry.text));
|
|
335
|
+
// Asked and answered: the same tool asking again later in the answer is a new ask.
|
|
336
|
+
if (ask === undefined)
|
|
337
|
+
asked = undefined;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
finally {
|
|
341
|
+
s.stop();
|
|
342
|
+
}
|
|
343
|
+
if (flags.json) {
|
|
344
|
+
json({ chatId: chat.chatId, ...entry, saved: saved.map(x => x.file) });
|
|
345
|
+
if (entry?.status === 'error')
|
|
346
|
+
process.exitCode = 1;
|
|
347
|
+
return entry;
|
|
348
|
+
}
|
|
349
|
+
if (entry?.status === 'error')
|
|
350
|
+
throw new CliError(entry.error ?? 'The answer failed.');
|
|
351
|
+
print(render(entry?.text ?? ''));
|
|
352
|
+
if (entry?.sources?.length)
|
|
353
|
+
print(`\n${DIM('Sources')}\n${entry.sources.map(x => DIM(` [${x.n}] ${x.title} — ${x.url}`)).join('\n')}`);
|
|
354
|
+
for (const x of saved)
|
|
355
|
+
print(`${G('✔')} Saved the ${x.kind}: ${B(x.file)}`);
|
|
356
|
+
if (entry?.status === 'stopped')
|
|
357
|
+
note(DIM('(stopped)'));
|
|
358
|
+
return entry;
|
|
359
|
+
}
|
|
360
|
+
/** Allow / Always allow / Deny, asked on the terminal; denied in a script. */
|
|
361
|
+
async function allow(ask, keys) {
|
|
362
|
+
if (!terminal()) {
|
|
363
|
+
note(`${R('✗')} Denied: ${ask ?? 'a tool'} (run in a terminal to allow it).`);
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
const options = [{ label: 'Allow' }, { label: 'Always allow', description: "don't ask again for this tool" }, { label: 'Deny' }];
|
|
367
|
+
const [chosen] = (await ownKeys(keys, () => select(`${ask ?? 'A tool asks to run.'} Allow?`, options))) ?? ['Deny'];
|
|
368
|
+
return chosen === 'Always allow' ? 'always' : chosen === 'Allow';
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* The AI's questions, each as a list; undefined skips them all (Esc, or a script). Typed text goes as a chosen answer:
|
|
372
|
+
* the app reads chosen and typed alike.
|
|
373
|
+
*/
|
|
374
|
+
async function answer(questions, keys) {
|
|
375
|
+
if (!terminal()) {
|
|
376
|
+
note(DIM("Skipped the AI's questions (run in a terminal to answer them)."));
|
|
377
|
+
return undefined;
|
|
378
|
+
}
|
|
379
|
+
const answers = [];
|
|
380
|
+
for (const q of questions) {
|
|
381
|
+
const chosen = await ownKeys(keys, () => select(q.question, q.options, { multi: q.multiSelect === true, other: true }));
|
|
382
|
+
if (!chosen)
|
|
383
|
+
return undefined;
|
|
384
|
+
answers.push({ chosen });
|
|
385
|
+
}
|
|
386
|
+
return answers.length ? answers : undefined;
|
|
387
|
+
}
|
|
388
|
+
/** The model alone (--plain): the answer written as it comes, formatted once finished. */
|
|
389
|
+
async function plainly(z, model, messages, flags) {
|
|
390
|
+
let text = '';
|
|
391
|
+
const s = spinner(() => (text ? writing(text) : 'Thinking…'));
|
|
392
|
+
try {
|
|
393
|
+
for await (const part of z.chat.stream({ model, messages }))
|
|
394
|
+
text += part.text;
|
|
395
|
+
}
|
|
396
|
+
finally {
|
|
397
|
+
s.stop();
|
|
398
|
+
}
|
|
399
|
+
if (flags.json)
|
|
400
|
+
json({ model, content: text });
|
|
401
|
+
else
|
|
402
|
+
print(render(text));
|
|
403
|
+
return text;
|
|
404
|
+
}
|
|
405
|
+
async function ask(z, words, flags) {
|
|
406
|
+
const input = await piped();
|
|
407
|
+
const question = [words.join(' '), input].filter(s => s.trim()).join('\n\n');
|
|
408
|
+
if (!question)
|
|
409
|
+
throw new CliError(`Ask something: ${CLI_NAME} ask "your question"`);
|
|
410
|
+
const model = await chatModel(z, flags.model, flags.plain === true);
|
|
411
|
+
if (flags.plain)
|
|
412
|
+
return void (await plainly(z, model, [{ role: 'user', content: question }], flags));
|
|
413
|
+
await converse(z, { text: question, ...(model ? { model } : {}), web: flags.web === true, ...(flags['no-save'] ? { save: false } : {}) }, flags);
|
|
414
|
+
}
|
|
415
|
+
async function chat(z, query, flags) {
|
|
416
|
+
let model = await chatModel(z, query ?? flags.model, flags.plain === true);
|
|
417
|
+
let chatId = crypto.randomUUID();
|
|
418
|
+
const history = [];
|
|
419
|
+
const commands = CHAT_COMMANDS.filter(([c]) => !(flags.plain && c === '/web'));
|
|
420
|
+
// On a terminal, Shift+Enter starts a new line; piped in, lines are read as they come.
|
|
421
|
+
const keyboard = process.stdin.isTTY ? chatKeyboard() : undefined;
|
|
422
|
+
const rl = createInterface({
|
|
423
|
+
input: keyboard?.input ?? process.stdin,
|
|
424
|
+
output: process.stdout,
|
|
425
|
+
terminal: process.stdout.isTTY === true,
|
|
426
|
+
prompt: `${C('›')} `,
|
|
427
|
+
// Tab completes the first command that fits.
|
|
428
|
+
completer: (line) => [slashMatches(line, commands).slice(0, 1).map(([c]) => c), line],
|
|
429
|
+
});
|
|
430
|
+
toBottom();
|
|
431
|
+
const box = inputBox(rl, commands, keyboard?.input, keyboard?.row);
|
|
432
|
+
const keys = {
|
|
433
|
+
pause: () => {
|
|
434
|
+
rl.pause();
|
|
435
|
+
keyboard?.pause();
|
|
436
|
+
},
|
|
437
|
+
resume: () => {
|
|
438
|
+
keyboard?.resume();
|
|
439
|
+
rl.resume();
|
|
440
|
+
},
|
|
441
|
+
};
|
|
442
|
+
// Ctrl+C leaves, as Ctrl+D does.
|
|
443
|
+
rl.on('SIGINT', () => rl.close());
|
|
444
|
+
let web = flags.web === true;
|
|
445
|
+
note(DIM(`Chatting${model ? ` with ${model}` : ''}${flags.plain ? ' (the model alone)' : `, web search ${web ? 'on' : 'off'}`}. Type / for commands, Shift+Enter for a new line.`));
|
|
446
|
+
try {
|
|
447
|
+
await box.top();
|
|
448
|
+
rl.prompt();
|
|
449
|
+
for await (const message of messages(rl, 30, keyboard?.input)) {
|
|
450
|
+
box.commit(message);
|
|
451
|
+
const text = message.trim();
|
|
452
|
+
if (text === '/exit' || text === '/quit')
|
|
453
|
+
break;
|
|
454
|
+
// One failed command or answer doesn't end the chat.
|
|
455
|
+
try {
|
|
456
|
+
if (text === '/web' && !flags.plain) {
|
|
457
|
+
web = !web;
|
|
458
|
+
note(DIM(`Web search ${web ? 'on' : 'off'}.`));
|
|
459
|
+
}
|
|
460
|
+
else if (text === '/model' || text.startsWith('/model ')) {
|
|
461
|
+
model = await switchModel(z, text.slice(6).trim() || undefined, model, keys);
|
|
462
|
+
}
|
|
463
|
+
else if (text === '/clear' || text === '/new') {
|
|
464
|
+
// As Claude Code's /clear: the screen too (what scrolled off stays in the terminal's history).
|
|
465
|
+
toBottom(true);
|
|
466
|
+
chatId = crypto.randomUUID();
|
|
467
|
+
history.length = 0;
|
|
468
|
+
note(DIM('A new chat. What the app keeps in memory (your name, say) it still knows.'));
|
|
469
|
+
}
|
|
470
|
+
else if (text === '/' || text === '/help') {
|
|
471
|
+
note(commands.map(commandRow).join('\n'));
|
|
472
|
+
}
|
|
473
|
+
else if (/^\/\w*$/.test(text)) {
|
|
474
|
+
note(`${R('✗')} No command ${text}. Type / to see them.`);
|
|
475
|
+
}
|
|
476
|
+
else if (text && flags.plain) {
|
|
477
|
+
history.push({ role: 'user', content: text });
|
|
478
|
+
history.push({ role: 'assistant', content: await plainly(z, model, history, flags) });
|
|
479
|
+
}
|
|
480
|
+
else if (text) {
|
|
481
|
+
await converse(z, { text, chatId, ...(model ? { model } : {}), web, ...(flags['no-save'] ? { save: false } : {}) }, flags, keys);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
catch (e) {
|
|
485
|
+
// Only `/model`'s list can be left with Esc.
|
|
486
|
+
if (e instanceof Cancelled)
|
|
487
|
+
note(DIM('Kept the same model.'));
|
|
488
|
+
else if (known(e))
|
|
489
|
+
note(`${R('✗')} ${e.message}`);
|
|
490
|
+
else
|
|
491
|
+
throw e;
|
|
492
|
+
}
|
|
493
|
+
await box.top();
|
|
494
|
+
rl.prompt();
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
finally {
|
|
498
|
+
// However the chat ends (an unexpected error too), the terminal is put back, so the process can end.
|
|
499
|
+
box.stop();
|
|
500
|
+
rl.close();
|
|
501
|
+
keyboard?.close();
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
async function media(z, kind, words, flags) {
|
|
505
|
+
const prompt = words.join(' ').trim();
|
|
506
|
+
if (!prompt)
|
|
507
|
+
throw new CliError(`Say what to show: ${CLI_NAME} ${kind} "a red fox in snow"`);
|
|
508
|
+
let made;
|
|
509
|
+
const s = spinner(kind === 'image' ? 'Drawing… (can take a minute)' : 'Making the video… (can take several minutes)');
|
|
510
|
+
try {
|
|
511
|
+
if (kind === 'image')
|
|
512
|
+
made = await z.images.create({ prompt, ...(flags.shape ? { shape: flags.shape } : {}) });
|
|
513
|
+
else {
|
|
514
|
+
const seconds = flags.seconds === undefined ? undefined : Number(flags.seconds);
|
|
515
|
+
if (seconds !== undefined && !(seconds > 0))
|
|
516
|
+
throw new CliError('--seconds is a number, up to 10.');
|
|
517
|
+
if (flags.shape && flags.shape !== 'landscape' && flags.shape !== 'portrait')
|
|
518
|
+
throw new CliError('--shape is landscape or portrait.');
|
|
519
|
+
made = await z.videos.create({ prompt, ...(seconds ? { seconds } : {}), ...(flags.shape ? { shape: flags.shape } : {}) });
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
finally {
|
|
523
|
+
s.stop();
|
|
524
|
+
}
|
|
525
|
+
// -o names the file, or a folder to put it in; else the usual folder, made the first time.
|
|
526
|
+
const into = flags.output && existsSync(flags.output) && statSync(flags.output).isDirectory() ? flags.output : flags.output ? undefined : mediaFolder(kind);
|
|
527
|
+
if (into)
|
|
528
|
+
mkdirSync(into, { recursive: true });
|
|
529
|
+
const file = resolve(into ? fileFor(into, prompt, extOf(made.url, kind === 'image' ? '.png' : '.webm')) : flags.output);
|
|
530
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
531
|
+
writeFileSync(file, made.bytes);
|
|
532
|
+
const { url: _, bytes: __, ...about } = made;
|
|
533
|
+
if (flags.json)
|
|
534
|
+
return json({ file, ...about });
|
|
535
|
+
print(`${G('✔')} Saved ${B(file)} ${DIM(`(${made.width}×${made.height}${made.frames ? `, ${made.frames} frames` : ''}, ${made.model})`)}`);
|
|
536
|
+
}
|
|
537
|
+
function version() {
|
|
538
|
+
return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
539
|
+
}
|
|
540
|
+
async function main(argv) {
|
|
541
|
+
let parsed;
|
|
542
|
+
try {
|
|
543
|
+
parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true });
|
|
544
|
+
}
|
|
545
|
+
catch (e) {
|
|
546
|
+
const option = /Unknown option '([^']+)'/.exec(e.message)?.[1];
|
|
547
|
+
throw new CliError(`${option ? `No option ${option}` : e.message}. See ${CLI_NAME} help.`);
|
|
548
|
+
}
|
|
549
|
+
const { values: flags, positionals } = parsed;
|
|
550
|
+
const [command = '', ...rest] = positionals;
|
|
551
|
+
const query = rest.join(' ') || undefined;
|
|
552
|
+
if (flags.version || command === 'version')
|
|
553
|
+
return print(version());
|
|
554
|
+
if (command === 'help' || flags.help || !command) {
|
|
555
|
+
const topic = command === 'help' ? (rest[0] ?? '') : command;
|
|
556
|
+
if (!(topic in HELP))
|
|
557
|
+
throw new CliError(`No command "${topic}". See ${CLI_NAME} help.`);
|
|
558
|
+
return print(HELP[topic]);
|
|
559
|
+
}
|
|
560
|
+
if (command === 'key')
|
|
561
|
+
return key(flags);
|
|
562
|
+
const z = client();
|
|
563
|
+
switch (command) {
|
|
564
|
+
case 'status':
|
|
565
|
+
return status(z, flags);
|
|
566
|
+
case 'models':
|
|
567
|
+
return models(z, flags);
|
|
568
|
+
case 'load':
|
|
569
|
+
return load(z, query, flags);
|
|
570
|
+
case 'eject':
|
|
571
|
+
return eject(z, query, flags);
|
|
572
|
+
case 'ask':
|
|
573
|
+
return ask(z, rest, flags);
|
|
574
|
+
case 'chat':
|
|
575
|
+
return chat(z, query, flags);
|
|
576
|
+
case 'image':
|
|
577
|
+
case 'video':
|
|
578
|
+
return media(z, command, rest, flags);
|
|
579
|
+
}
|
|
580
|
+
const near = match(command, Object.keys(HELP).filter(Boolean).map(k => ({ id: k, name: k })));
|
|
581
|
+
const hint = 'found' in near ? near.found.name : 'none' in near && near.none[0] ? near.none[0].name : undefined;
|
|
582
|
+
throw new CliError(`No command "${command}".${hint ? ` Did you mean ${CLI_NAME} ${hint}?` : ''} See ${CLI_NAME} help.`);
|
|
583
|
+
}
|
|
584
|
+
const argv = process.argv.slice(2);
|
|
585
|
+
// A newer version on npm, told once the command is done; never in a script, with --json or on CI, or when turned off.
|
|
586
|
+
const update = process.stderr.isTTY && !process.env.CI && !process.env.Z1LLM_NO_UPDATE_CHECK && !argv.includes('--json') ? updateNotice(version()) : undefined;
|
|
587
|
+
main(argv)
|
|
588
|
+
.catch((e) => {
|
|
589
|
+
if (e instanceof Cancelled) {
|
|
590
|
+
process.exitCode = 130;
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
process.exitCode = 1;
|
|
594
|
+
if (e instanceof Zero1LLMError && e.code === 'UNAUTHORIZED')
|
|
595
|
+
return note(`${R('✗')} No API key, or the wrong one. Run ${CLI_NAME} key and paste the key from ${APP_NAME} → Settings → Local API.`);
|
|
596
|
+
if (known(e))
|
|
597
|
+
return note(`${R('✗')} ${e.message}`);
|
|
598
|
+
note(`${R('✗')} ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`);
|
|
599
|
+
})
|
|
600
|
+
.finally(async () => {
|
|
601
|
+
const latest = await update;
|
|
602
|
+
if (latest)
|
|
603
|
+
note(`\n${C('Update available:')} ${version()} → ${B(latest)} ${DIM(`· npm install -g ${CLI_NAME}`)}`);
|
|
604
|
+
});
|
package/dist/key.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// The local API key, saved once by `z1llm key` so it needn't be pasted into every terminal. ZERO1LLM_API_KEY wins.
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { CLI_NAME } from './brand.js';
|
|
6
|
+
/** ~/.config/z1llm/config.json (XDG_CONFIG_HOME), %APPDATA%\z1llm\config.json on Windows. */
|
|
7
|
+
export function configFile() {
|
|
8
|
+
const base = process.platform === 'win32' ? (process.env.APPDATA ?? join(homedir(), 'AppData', 'Roaming')) : (process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'));
|
|
9
|
+
return join(base, CLI_NAME, 'config.json');
|
|
10
|
+
}
|
|
11
|
+
export function savedKey(file = configFile()) {
|
|
12
|
+
try {
|
|
13
|
+
const k = JSON.parse(readFileSync(file, 'utf8')).apiKey;
|
|
14
|
+
return typeof k === 'string' && k ? k : undefined;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Saves `key`, or removes the saved one when undefined. */
|
|
21
|
+
// shortcut: a file only you can read (as ~/.npmrc keeps tokens), not the keychain; move it there if users ask.
|
|
22
|
+
export function saveKey(key, file = configFile()) {
|
|
23
|
+
if (!key)
|
|
24
|
+
return rmSync(file, { force: true });
|
|
25
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
26
|
+
writeFileSync(file, `${JSON.stringify({ apiKey: key })}\n`, { mode: 0o600 });
|
|
27
|
+
chmodSync(file, 0o600);
|
|
28
|
+
}
|