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/terminal.js
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
// The terminal side: answers shown formatted (bold, lists, tables) as the app shows them, a spinner and a progress
|
|
2
|
+
// bar while the app works, and questions (Allow?, the key). Styles only on a terminal, never in a pipe or a file.
|
|
3
|
+
import { fstatSync } from 'node:fs';
|
|
4
|
+
import { emitKeypressEvents } from 'node:readline';
|
|
5
|
+
import { PassThrough } from 'node:stream';
|
|
6
|
+
import { text as readAll } from 'node:stream/consumers';
|
|
7
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
8
|
+
import { marked } from 'marked';
|
|
9
|
+
const COLOR = process.stdout.isTTY === true && !process.env.NO_COLOR;
|
|
10
|
+
const style = (on, off) => (s) => (COLOR ? `\x1b[${on}m${s}\x1b[${off}m` : s);
|
|
11
|
+
export const B = style(1, 22);
|
|
12
|
+
const I = style(3, 23);
|
|
13
|
+
const U = style(4, 24);
|
|
14
|
+
export const DIM = style(2, 22);
|
|
15
|
+
export const C = style(36, 39);
|
|
16
|
+
export const G = style(32, 39);
|
|
17
|
+
export const R = style(31, 39);
|
|
18
|
+
export const visible = (s) => stripVTControlCharacters(s).length;
|
|
19
|
+
/** The rows a line takes on screen, wrapped at `cols`. */
|
|
20
|
+
// shortcut: wide letters (CJK) count as one column, so a wrapped line of them is counted short.
|
|
21
|
+
export const rowsOf = (line, cols) => Math.max(1, Math.ceil(visible(line) / cols));
|
|
22
|
+
/** "Writing… 42 words" */
|
|
23
|
+
export const writing = (text) => `Writing… ${text.split(/\s+/).filter(Boolean).length} words`;
|
|
24
|
+
/** Simple math as text: $86^\circ\text{F}$ and $26.4^{\circ}C$ → 86°F, 26.4°C. */
|
|
25
|
+
export const math = (s) => s.replace(/\$([^$\n]+)\$/g, (_, m) => m
|
|
26
|
+
.replace(/\^?\{?\\(circ|degree)\}?/g, '°')
|
|
27
|
+
.replace(/\\text\{([^}]*)\}/g, '$1')
|
|
28
|
+
.replace(/\\times/g, '×')
|
|
29
|
+
.replace(/\\/g, '')
|
|
30
|
+
.replace(/[{}^]/g, ''));
|
|
31
|
+
const unescape = (s) => s
|
|
32
|
+
.replace(/&/g, '&')
|
|
33
|
+
.replace(/</g, '<')
|
|
34
|
+
.replace(/>/g, '>')
|
|
35
|
+
.replace(/"/g, '"')
|
|
36
|
+
.replace(/'/g, "'");
|
|
37
|
+
function inline(tokens = []) {
|
|
38
|
+
return tokens
|
|
39
|
+
.map(t => {
|
|
40
|
+
if (t.type === 'strong')
|
|
41
|
+
return B(inline(t.tokens));
|
|
42
|
+
if (t.type === 'em')
|
|
43
|
+
return I(inline(t.tokens));
|
|
44
|
+
if (t.type === 'codespan')
|
|
45
|
+
return C(unescape(t.text));
|
|
46
|
+
if (t.type === 'link')
|
|
47
|
+
return `${U(inline(t.tokens))} ${DIM(`(${t.href})`)}`;
|
|
48
|
+
if (t.type === 'br')
|
|
49
|
+
return '\n';
|
|
50
|
+
if ('tokens' in t && t.tokens)
|
|
51
|
+
return inline(t.tokens);
|
|
52
|
+
return unescape(math('text' in t ? String(t.text) : t.raw));
|
|
53
|
+
})
|
|
54
|
+
.join('');
|
|
55
|
+
}
|
|
56
|
+
function table(t) {
|
|
57
|
+
const rows = [t.header.map(c => B(inline(c.tokens))), ...t.rows.map(r => r.map(c => inline(c.tokens)))];
|
|
58
|
+
const widths = rows[0].map((_, i) => Math.max(...rows.map(r => visible(r[i] ?? ''))));
|
|
59
|
+
const line = (l, m, r) => l + widths.map(w => '─'.repeat(w + 2)).join(m) + r;
|
|
60
|
+
const row = (r) => '│' + r.map((c, i) => ` ${c}${' '.repeat(widths[i] - visible(c))} `).join('│') + '│';
|
|
61
|
+
return [line('┌', '┬', '┐'), row(rows[0]), line('├', '┼', '┤'), ...rows.slice(1).map(row), line('└', '┴', '┘')].join('\n');
|
|
62
|
+
}
|
|
63
|
+
function blocks(tokens, indent = '') {
|
|
64
|
+
return tokens
|
|
65
|
+
.map(t => {
|
|
66
|
+
if (t.type === 'heading')
|
|
67
|
+
return '\n' + B(U(inline(t.tokens)));
|
|
68
|
+
if (t.type === 'paragraph' || t.type === 'text')
|
|
69
|
+
return indent + inline('tokens' in t && t.tokens ? t.tokens : [t]);
|
|
70
|
+
if (t.type === 'list') {
|
|
71
|
+
const l = t;
|
|
72
|
+
return l.items.map((it, n) => `${indent}${l.ordered ? `${(Number(l.start) || 1) + n}.` : '•'} ${blocks(it.tokens, indent + ' ').trimStart()}`).join('\n');
|
|
73
|
+
}
|
|
74
|
+
if (t.type === 'table')
|
|
75
|
+
return table(t);
|
|
76
|
+
if (t.type === 'code')
|
|
77
|
+
return t.text
|
|
78
|
+
.split('\n')
|
|
79
|
+
.map(l => indent + ' ' + C(l))
|
|
80
|
+
.join('\n');
|
|
81
|
+
if (t.type === 'blockquote')
|
|
82
|
+
return blocks(t.tokens, indent + DIM('│ '));
|
|
83
|
+
if (t.type === 'hr')
|
|
84
|
+
return DIM('─'.repeat(40));
|
|
85
|
+
return '';
|
|
86
|
+
})
|
|
87
|
+
.filter(Boolean)
|
|
88
|
+
.join('\n');
|
|
89
|
+
}
|
|
90
|
+
/** An answer's markdown as terminal text; the text as it came when it isn't a terminal. */
|
|
91
|
+
export const render = (markdown) => (COLOR ? blocks(marked.lexer(markdown)) : markdown.trim());
|
|
92
|
+
/** A spinner with the time so far, on stderr (so stdout stays the answer alone); nothing outside a terminal. */
|
|
93
|
+
/** `text` may be a function, read each time it draws (so a word count isn't made for every word that streams in). */
|
|
94
|
+
export function spinner(text) {
|
|
95
|
+
if (!process.stderr.isTTY)
|
|
96
|
+
return { update: (_) => undefined, stop: () => undefined };
|
|
97
|
+
const frames = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏';
|
|
98
|
+
const started = Date.now();
|
|
99
|
+
let i = 0;
|
|
100
|
+
const draw = () => {
|
|
101
|
+
const s = Math.floor((Date.now() - started) / 1000);
|
|
102
|
+
process.stderr.write(`\r\x1b[K${C(frames[i++ % frames.length])} ${typeof text === 'string' ? text : text()}${s >= 3 ? DIM(` ${s}s`) : ''}`);
|
|
103
|
+
};
|
|
104
|
+
draw();
|
|
105
|
+
const timer = setInterval(draw, 100);
|
|
106
|
+
return {
|
|
107
|
+
update: (t) => void (text = t),
|
|
108
|
+
stop: () => {
|
|
109
|
+
clearInterval(timer);
|
|
110
|
+
process.stderr.write('\r\x1b[K');
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** `████████░░░░ 64%` */
|
|
115
|
+
export const bar = (percent, width = 24) => {
|
|
116
|
+
const full = Math.round((Math.min(100, Math.max(0, percent)) / 100) * width);
|
|
117
|
+
return `${C('█'.repeat(full))}${DIM('░'.repeat(width - full))} ${Math.round(percent)}%`;
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* A chat's messages, as Claude Code reads them: lines pasted together (they arrive in one burst) are one message, and
|
|
121
|
+
* Shift+Enter goes on to the next (`chatKeyboard` ends that line with `NEW_LINE`; a line ending in \ does too), and
|
|
122
|
+
* Backspace at the start of a next line goes back to the end of the one above (given `input`, where readline hears keys).
|
|
123
|
+
*/
|
|
124
|
+
export function messages(rl, burstMs = 30, input) {
|
|
125
|
+
const prompt = rl.getPrompt();
|
|
126
|
+
const bursts = [];
|
|
127
|
+
let current = [];
|
|
128
|
+
let timer;
|
|
129
|
+
let closed = false;
|
|
130
|
+
let wake;
|
|
131
|
+
rl.on('line', (l) => {
|
|
132
|
+
current.push(l);
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
timer = setTimeout(() => {
|
|
135
|
+
bursts.push(current);
|
|
136
|
+
current = [];
|
|
137
|
+
wake?.();
|
|
138
|
+
}, burstMs);
|
|
139
|
+
});
|
|
140
|
+
rl.on('close', () => {
|
|
141
|
+
clearTimeout(timer);
|
|
142
|
+
if (current.length)
|
|
143
|
+
bursts.push(current);
|
|
144
|
+
closed = true;
|
|
145
|
+
wake?.();
|
|
146
|
+
});
|
|
147
|
+
// The lines of the message being written, before its last.
|
|
148
|
+
let message = [];
|
|
149
|
+
input?.on('keypress', (_, key) => {
|
|
150
|
+
// readline has already seen the Backspace (nothing to delete): back up to the line above, shown again with the
|
|
151
|
+
// cursor at its end.
|
|
152
|
+
if (key?.name !== 'backspace' || rl.line !== '' || !message.length)
|
|
153
|
+
return;
|
|
154
|
+
const above = message.pop();
|
|
155
|
+
rl.setPrompt(message.length ? NEXT_PROMPT : prompt);
|
|
156
|
+
// One row less: the box is pulled down a row first, so it stays on the bottom rows.
|
|
157
|
+
process.stdout.write(`${pullDown(1)}\x1b[${rowsOf(` ${above}`, process.stdout.columns || 80)}A\r\x1b[J`);
|
|
158
|
+
rl.prompt();
|
|
159
|
+
rl.write(above);
|
|
160
|
+
});
|
|
161
|
+
// Listening starts here, not at the first read: nothing typed or pasted before it is lost.
|
|
162
|
+
return (async function* () {
|
|
163
|
+
for (;;) {
|
|
164
|
+
while (!bursts.length && !closed)
|
|
165
|
+
await new Promise(r => (wake = r));
|
|
166
|
+
const burst = bursts.shift();
|
|
167
|
+
if (!burst)
|
|
168
|
+
return;
|
|
169
|
+
message.push(...burst);
|
|
170
|
+
const last = message.at(-1);
|
|
171
|
+
if ((last.endsWith(NEW_LINE) || last.endsWith('\\')) && !closed) {
|
|
172
|
+
message[message.length - 1] = last.slice(0, -1);
|
|
173
|
+
rl.setPrompt(NEXT_PROMPT);
|
|
174
|
+
rl.prompt();
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
rl.setPrompt(prompt);
|
|
178
|
+
yield message.join('\n');
|
|
179
|
+
message = [];
|
|
180
|
+
}
|
|
181
|
+
})();
|
|
182
|
+
}
|
|
183
|
+
/** Runs `fn` with the keys to itself: a chat's readline (and its / list) stops hearing them meanwhile. */
|
|
184
|
+
export async function ownKeys(owner, fn) {
|
|
185
|
+
owner?.pause();
|
|
186
|
+
try {
|
|
187
|
+
return await fn();
|
|
188
|
+
}
|
|
189
|
+
finally {
|
|
190
|
+
owner?.resume();
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/** Ends a line that goes on: Shift+Enter becomes this and Enter, so readline (one line at a time) can take it. */
|
|
194
|
+
export const NEW_LINE = '\u200b';
|
|
195
|
+
/** The prompt of a message's next lines; the input box knows a next line by it. */
|
|
196
|
+
const NEXT_PROMPT = ' ';
|
|
197
|
+
/**
|
|
198
|
+
* Moves what is on screen down `n` rows (blank rows go in at the top of the window), the cursor with it: the one way
|
|
199
|
+
* the chat's box is kept on the bottom rows when something above or below it took rows away.
|
|
200
|
+
*/
|
|
201
|
+
const pullDown = (n) => (n > 0 ? `\x1b7\x1b[1;1H\x1b[${n}L\x1b8\x1b[${n}B` : '');
|
|
202
|
+
/** Keys one at a time to `onKey` (raw mode), as lists, questions and the key prompt read them; the function returned
|
|
203
|
+
* stops that and puts the terminal back. */
|
|
204
|
+
export function rawKeys(onKey, hideCursor = false) {
|
|
205
|
+
const { stdin, stderr } = process;
|
|
206
|
+
emitKeypressEvents(stdin);
|
|
207
|
+
stdin.setRawMode(true);
|
|
208
|
+
stdin.resume();
|
|
209
|
+
if (hideCursor)
|
|
210
|
+
stderr.write('\x1b[?25l');
|
|
211
|
+
stdin.on('keypress', onKey);
|
|
212
|
+
return () => {
|
|
213
|
+
stdin.off('keypress', onKey);
|
|
214
|
+
stdin.setRawMode(false);
|
|
215
|
+
stdin.pause();
|
|
216
|
+
if (hideCursor)
|
|
217
|
+
stderr.write('\x1b[?25h');
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
/** Lines on stderr redrawn in place (a list, a question), then erased. */
|
|
221
|
+
export function redrawn() {
|
|
222
|
+
const out = process.stderr;
|
|
223
|
+
let drawn = 0;
|
|
224
|
+
const erase = () => (drawn ? `\x1b[${drawn}A\x1b[J` : '');
|
|
225
|
+
return {
|
|
226
|
+
draw: (lines) => {
|
|
227
|
+
out.write(`${erase()}${lines.join('\n')}\n`);
|
|
228
|
+
// A long line wraps: count the rows it takes, so the redraw (and the erase) starts in the right place.
|
|
229
|
+
drawn = lines.reduce((n, l) => n + rowsOf(l, out.columns || 80), 0);
|
|
230
|
+
},
|
|
231
|
+
erase: () => void out.write(erase()),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Keys as a terminal reports them once asked (kitty's keyboard protocol, xterm's modifyOtherKeys), back as readline
|
|
236
|
+
* knows them: Shift+Enter, Option+Enter (Esc then Enter) and any modified Enter as a new line; Esc, Ctrl+C, Alt+x as usual.
|
|
237
|
+
*/
|
|
238
|
+
// shortcut: a report split across two reads isn't joined; local terminals send each whole.
|
|
239
|
+
export function decodeKeys(s) {
|
|
240
|
+
return s.replace(/\x1b\[13;\d+u|\x1b\[27;\d+;13~|\x1b\r/g, `${NEW_LINE}\r`).replace(/\x1b\[(\d+)(?:;(\d+))?u|\x1b\[27;(\d+);(\d+)~/g, (_, a, am, bm, b) => {
|
|
241
|
+
const code = Number(a ?? b);
|
|
242
|
+
const mod = Number(am ?? bm ?? 1) - 1;
|
|
243
|
+
// Keys with no character (the keypad, media keys) are kitty's private-use codes: dropped.
|
|
244
|
+
if (code >= 0xe000 && code <= 0xf8ff)
|
|
245
|
+
return '';
|
|
246
|
+
let ch = String.fromCodePoint(code);
|
|
247
|
+
if (mod & 1)
|
|
248
|
+
ch = ch.toUpperCase();
|
|
249
|
+
if (mod & 4 && /^[a-z@[\\\]^_ ]$/i.test(ch))
|
|
250
|
+
ch = String.fromCharCode(ch.toUpperCase().charCodeAt(0) & 0x1f);
|
|
251
|
+
return `${mod & 2 ? '\x1b' : ''}${ch}`;
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* The keyboard for a chat, where Shift+Enter starts a new line: the terminal is asked to report modified keys (Apple's
|
|
256
|
+
* Terminal can't; there Option+Enter does it, with "Use Option as Meta key"), its reports are turned back into plain
|
|
257
|
+
* keys for readline, and it is put back as it was when the chat ends, however it ends.
|
|
258
|
+
*/
|
|
259
|
+
export function chatKeyboard() {
|
|
260
|
+
const { stdin, stdout } = process;
|
|
261
|
+
const input = Object.assign(new PassThrough(), { isTTY: true, setRawMode: (on) => stdin.setRawMode(on) });
|
|
262
|
+
const report = (on) => stdout.write(on ? '\x1b[>1u\x1b[>4;2m' : '\x1b[<u\x1b[>4;0m');
|
|
263
|
+
// The answer to `row()`'s question comes in with the keys: taken out before readline sees it.
|
|
264
|
+
let asked;
|
|
265
|
+
// Once it hasn't answered, it isn't asked again (each prompt would wait the 200 ms for nothing).
|
|
266
|
+
let deaf = false;
|
|
267
|
+
const onData = (d) => {
|
|
268
|
+
let text = d.toString('utf8');
|
|
269
|
+
if (asked) {
|
|
270
|
+
text = text.replace(/\x1b\[(\d+);\d+R/, (_, r) => {
|
|
271
|
+
asked?.(Number(r));
|
|
272
|
+
asked = undefined;
|
|
273
|
+
return '';
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
if (text)
|
|
277
|
+
input.write(decodeKeys(text));
|
|
278
|
+
};
|
|
279
|
+
const restore = () => report(false);
|
|
280
|
+
const start = () => {
|
|
281
|
+
report(true);
|
|
282
|
+
stdin.on('data', onData);
|
|
283
|
+
stdin.setRawMode(true);
|
|
284
|
+
stdin.resume();
|
|
285
|
+
};
|
|
286
|
+
const stop = () => {
|
|
287
|
+
stdin.off('data', onData);
|
|
288
|
+
report(false);
|
|
289
|
+
};
|
|
290
|
+
process.on('exit', restore);
|
|
291
|
+
start();
|
|
292
|
+
return {
|
|
293
|
+
input,
|
|
294
|
+
pause: stop,
|
|
295
|
+
resume: start,
|
|
296
|
+
/** The cursor's row (1 = top), asked of the terminal; undefined if it doesn't say within 200 ms. */
|
|
297
|
+
row: () => new Promise(resolve => {
|
|
298
|
+
if (deaf)
|
|
299
|
+
return resolve(undefined);
|
|
300
|
+
asked = resolve;
|
|
301
|
+
stdout.write('\x1b[6n');
|
|
302
|
+
setTimeout(() => {
|
|
303
|
+
if (asked !== resolve)
|
|
304
|
+
return;
|
|
305
|
+
asked = undefined;
|
|
306
|
+
deaf = true;
|
|
307
|
+
resolve(undefined);
|
|
308
|
+
}, 200);
|
|
309
|
+
}),
|
|
310
|
+
close: () => {
|
|
311
|
+
stop();
|
|
312
|
+
process.off('exit', restore);
|
|
313
|
+
stdin.setRawMode(false);
|
|
314
|
+
stdin.pause();
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
/** A line cut to `max` letters, with … */
|
|
319
|
+
const cut = (s, max) => (s.length > max ? `${s.slice(0, Math.max(0, max - 1))}…` : s);
|
|
320
|
+
/**
|
|
321
|
+
* A question with options, as Claude Code asks one: ↑↓ to move, Enter to choose, a number picks at once; with `multi`
|
|
322
|
+
* Space ticks several; with `other` the last row takes typed text (typing anywhere goes there). Undefined on Esc.
|
|
323
|
+
*/
|
|
324
|
+
export function select(title, options, o = {}) {
|
|
325
|
+
const out = process.stderr;
|
|
326
|
+
const view = redrawn();
|
|
327
|
+
const otherAt = o.other ? options.length : -1;
|
|
328
|
+
const count = options.length + (o.other ? 1 : 0);
|
|
329
|
+
const ticked = new Set();
|
|
330
|
+
let at = 0;
|
|
331
|
+
let typed = '';
|
|
332
|
+
const draw = () => {
|
|
333
|
+
const cols = out.columns || 80;
|
|
334
|
+
const lines = [`${C('?')} ${B(title)}`];
|
|
335
|
+
for (let i = 0; i < count; i++) {
|
|
336
|
+
const here = i === at;
|
|
337
|
+
const isOther = i === otherAt;
|
|
338
|
+
const box = o.multi ? `${ticked.has(i) || (isOther && typed.trim()) ? G('◉') : '◯'} ` : '';
|
|
339
|
+
const label = isOther ? (typed ? `${typed}${here ? '▏' : ''}` : DIM(`Type something else…${here ? '▏' : ''}`)) : `${i + 1}. ${options[i].label}`;
|
|
340
|
+
const about = !isOther && options[i].description ? ` ${DIM(cut(options[i].description, Math.max(10, cols - options[i].label.length - 14)))}` : '';
|
|
341
|
+
lines.push(`${here ? C('❯') : ' '} ${box}${here && !isOther ? C(label) : label}${about}`);
|
|
342
|
+
}
|
|
343
|
+
lines.push(DIM(o.multi ? ' ↑↓ move · Space tick · Enter send · Esc skip' : ' ↑↓ move · Enter choose · Esc skip'));
|
|
344
|
+
view.draw(lines);
|
|
345
|
+
};
|
|
346
|
+
return new Promise(resolve => {
|
|
347
|
+
draw();
|
|
348
|
+
const finish = (answer) => {
|
|
349
|
+
stop();
|
|
350
|
+
view.erase();
|
|
351
|
+
out.write(`${answer ? G('✔') : DIM('–')} ${cut(title, 60)} ${answer ? C(answer.join(', ') || '(nothing)') : DIM('skipped')}\n`);
|
|
352
|
+
resolve(answer);
|
|
353
|
+
};
|
|
354
|
+
const stop = rawKeys((s, key = {}) => {
|
|
355
|
+
if (key.name === 'escape' || (key.ctrl && key.name === 'c'))
|
|
356
|
+
return finish(undefined);
|
|
357
|
+
if (key.name === 'return' || key.name === 'enter') {
|
|
358
|
+
if (o.multi)
|
|
359
|
+
return finish([...[...ticked].sort((a, b) => a - b).map(i => options[i].label), ...(typed.trim() ? [typed.trim()] : [])]);
|
|
360
|
+
if (at === otherAt)
|
|
361
|
+
return typed.trim() ? finish([typed.trim()]) : undefined;
|
|
362
|
+
return finish([options[at].label]);
|
|
363
|
+
}
|
|
364
|
+
if (key.name === 'up')
|
|
365
|
+
at = (at - 1 + count) % count;
|
|
366
|
+
else if (key.name === 'down' || key.name === 'tab')
|
|
367
|
+
at = (at + 1) % count;
|
|
368
|
+
else if (at === otherAt && key.name === 'backspace')
|
|
369
|
+
typed = typed.slice(0, -1);
|
|
370
|
+
else if (o.multi && key.name === 'space' && at !== otherAt) {
|
|
371
|
+
if (ticked.has(at))
|
|
372
|
+
ticked.delete(at);
|
|
373
|
+
else
|
|
374
|
+
ticked.add(at);
|
|
375
|
+
}
|
|
376
|
+
else if (at !== otherAt && s && /^[1-9]$/.test(s) && Number(s) <= options.length) {
|
|
377
|
+
at = Number(s) - 1;
|
|
378
|
+
if (!o.multi)
|
|
379
|
+
return finish([options[at].label]);
|
|
380
|
+
if (ticked.has(at))
|
|
381
|
+
ticked.delete(at);
|
|
382
|
+
else
|
|
383
|
+
ticked.add(at);
|
|
384
|
+
}
|
|
385
|
+
else if (o.other && s && !key.ctrl && s >= ' ') {
|
|
386
|
+
at = otherAt;
|
|
387
|
+
typed += s;
|
|
388
|
+
}
|
|
389
|
+
else
|
|
390
|
+
return;
|
|
391
|
+
draw();
|
|
392
|
+
}, true);
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
/** The commands that start with what is typed ("/w" → /web); none once a space is typed or it isn't a command. */
|
|
396
|
+
/** A command and what it does, as the / list and /help show it. */
|
|
397
|
+
export const commandRow = ([c, about]) => ` ${C(c.padEnd(7))} ${DIM(about)}`;
|
|
398
|
+
export const slashMatches = (line, commands) => (line.startsWith('/') && !line.includes(' ') ? commands.filter(([c]) => c.startsWith(line)) : []);
|
|
399
|
+
/**
|
|
400
|
+
* Starts the chat at the bottom of the window, as Claude Code does: what was on screen scrolls up into the terminal's
|
|
401
|
+
* history (nothing is lost), so the box sits on the last rows and the chat grows upward from it. `clear` empties the
|
|
402
|
+
* window first (`/clear`).
|
|
403
|
+
*/
|
|
404
|
+
export function toBottom(clear = false) {
|
|
405
|
+
if (!process.stdout.isTTY)
|
|
406
|
+
return;
|
|
407
|
+
process.stdout.write(`${clear ? '\x1b[2J' : ''}\x1b[999;1H${'\n'.repeat(Math.max(0, (process.stdout.rows || 24) - 1))}`);
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* The chat's input line between two rules, as Claude Code draws it, so it is plain where to type; while a line starting
|
|
411
|
+
* with "/" is typed, the commands that fit are listed under the lower rule. Enter takes the lower rule and the list
|
|
412
|
+
* away; `commit(message)` then puts the sent message back as a plain `› …` line in place of the box, so the chat reads
|
|
413
|
+
* without rules and the box is always the last thing on screen. `top()` draws the upper rule before a prompt.
|
|
414
|
+
*/
|
|
415
|
+
export function inputBox(rl, commands, input = process.stdin, row) {
|
|
416
|
+
if (!process.stdout.isTTY)
|
|
417
|
+
return { top: async () => undefined, commit: () => undefined, stop: () => undefined };
|
|
418
|
+
const out = process.stdout;
|
|
419
|
+
const rule = () => DIM('─'.repeat(out.columns || 80));
|
|
420
|
+
// Only while the line is being typed: keys pressed during an answer draw nothing.
|
|
421
|
+
let active = false;
|
|
422
|
+
// A box has been drawn (the next gets an empty line above it), and the last one has that line.
|
|
423
|
+
let started = false;
|
|
424
|
+
let gap = false;
|
|
425
|
+
// Rows drawn under the line: the rule, and the / list when shown.
|
|
426
|
+
let shown = 0;
|
|
427
|
+
const draw = () => {
|
|
428
|
+
if (!active)
|
|
429
|
+
return;
|
|
430
|
+
// The list only on a message's first line: a command is a whole message.
|
|
431
|
+
const items = rl.getPrompt() === NEXT_PROMPT ? [] : slashMatches(rl.line, commands);
|
|
432
|
+
const below = [rule(), ...items.map(commandRow)];
|
|
433
|
+
// The list got shorter: the box is pulled down to the bottom rows instead of leaving a gap under it.
|
|
434
|
+
let s = pullDown(shown - below.length);
|
|
435
|
+
const { cols } = rl.getCursorPos();
|
|
436
|
+
// Room under the line (the screen scrolls if it is at the bottom), back to where the cursor was (`getCursorPos`
|
|
437
|
+
// counts the prompt too), and the rule and list drawn below.
|
|
438
|
+
s += `${'\n'.repeat(below.length)}\x1b[${below.length}A\x1b[${cols + 1}G\x1b7\n\x1b[J${below.join('\n')}\x1b8`;
|
|
439
|
+
out.write(s);
|
|
440
|
+
shown = below.length;
|
|
441
|
+
};
|
|
442
|
+
let queued = false;
|
|
443
|
+
const onKey = (_, key) => {
|
|
444
|
+
// Enter: readline has moved to the line below, where the rule was.
|
|
445
|
+
if (key?.name === 'return' || key?.name === 'enter') {
|
|
446
|
+
if (active)
|
|
447
|
+
out.write('\x1b[J');
|
|
448
|
+
active = false;
|
|
449
|
+
shown = 0;
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
// A burst of keys (a paste) draws once.
|
|
453
|
+
if (queued)
|
|
454
|
+
return;
|
|
455
|
+
queued = true;
|
|
456
|
+
setImmediate(() => {
|
|
457
|
+
queued = false;
|
|
458
|
+
draw();
|
|
459
|
+
});
|
|
460
|
+
};
|
|
461
|
+
const prompt = rl.prompt.bind(rl);
|
|
462
|
+
rl.prompt = (preserveCursor) => {
|
|
463
|
+
prompt(preserveCursor);
|
|
464
|
+
active = true;
|
|
465
|
+
draw();
|
|
466
|
+
};
|
|
467
|
+
input.on('keypress', onKey);
|
|
468
|
+
return {
|
|
469
|
+
// An empty line between an answer and the next box, which goes on the bottom rows: a list or question that was
|
|
470
|
+
// drawn and taken away (`/model`, Allow) leaves empty rows under the cursor, so what is on screen moves down
|
|
471
|
+
// into them (blank rows go in at the top of the window).
|
|
472
|
+
top: async () => {
|
|
473
|
+
gap = started;
|
|
474
|
+
started = true;
|
|
475
|
+
const at = await row?.();
|
|
476
|
+
out.write(`${at === undefined ? '' : pullDown((out.rows || 24) - 2 - (gap ? 1 : 0) - at)}${gap ? '\n' : ''}${rule()}\n`);
|
|
477
|
+
},
|
|
478
|
+
commit: (message) => {
|
|
479
|
+
// From just under the sent lines back up to the upper rule: one row for it, and each line's rows (prompts are
|
|
480
|
+
// two wide). An empty Enter takes the box and its empty line away, as if nothing was typed.
|
|
481
|
+
const lines = message.split('\n');
|
|
482
|
+
const rows = 1 + lines.reduce((n, l) => n + rowsOf(` ${l}`, out.columns || 80), 0);
|
|
483
|
+
const empty = !message.trim();
|
|
484
|
+
out.write(`\x1b[${rows + (empty && gap ? 1 : 0)}A\r\x1b[J${empty ? '' : `${lines.map((l, i) => `${i ? ' ' : `${C('›')} `}${l}`).join('\n')}\n`}`);
|
|
485
|
+
if (empty && !gap)
|
|
486
|
+
started = false;
|
|
487
|
+
},
|
|
488
|
+
stop: () => {
|
|
489
|
+
input.off('keypress', onKey);
|
|
490
|
+
rl.prompt = prompt;
|
|
491
|
+
if (active)
|
|
492
|
+
out.write('\x1b[J');
|
|
493
|
+
},
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
/** Reads a secret typed or pasted on the terminal, shown as dots. */
|
|
497
|
+
export function secret(prompt) {
|
|
498
|
+
const { stderr } = process;
|
|
499
|
+
stderr.write(prompt);
|
|
500
|
+
return new Promise((resolve, reject) => {
|
|
501
|
+
let text = '';
|
|
502
|
+
const done = (err) => {
|
|
503
|
+
stop();
|
|
504
|
+
stderr.write('\n');
|
|
505
|
+
if (err)
|
|
506
|
+
reject(err);
|
|
507
|
+
else
|
|
508
|
+
resolve(text.trim());
|
|
509
|
+
};
|
|
510
|
+
const stop = rawKeys((s, key) => {
|
|
511
|
+
if (key.ctrl && key.name === 'c')
|
|
512
|
+
return done(new Error('cancelled'));
|
|
513
|
+
if (key.name === 'return' || key.name === 'enter')
|
|
514
|
+
return done();
|
|
515
|
+
if (key.name === 'backspace') {
|
|
516
|
+
if (text)
|
|
517
|
+
stderr.write('\b \b');
|
|
518
|
+
text = text.slice(0, -1);
|
|
519
|
+
}
|
|
520
|
+
else if (s && !key.ctrl && s >= ' ') {
|
|
521
|
+
text += s;
|
|
522
|
+
stderr.write('•'.repeat(s.length));
|
|
523
|
+
}
|
|
524
|
+
});
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
/** Everything piped in (`cat notes.txt | z1llm ask …`, `< notes.txt`); empty otherwise. */
|
|
528
|
+
export async function piped() {
|
|
529
|
+
// Only a pipe or a file: an inherited stdin that never ends (a CI job, another program) mustn't hang it.
|
|
530
|
+
const kind = fstatSync(0);
|
|
531
|
+
if (!kind.isFIFO() && !kind.isFile())
|
|
532
|
+
return '';
|
|
533
|
+
return readAll(process.stdin);
|
|
534
|
+
}
|
package/dist/update.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Tells of a newer z1llm on npm, as Claude Code does: npm is asked at most once a day (2 s at most), and what it said
|
|
2
|
+
// is kept beside the key, so the other runs that day only read a file.
|
|
3
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { CLI_NAME } from './brand.js';
|
|
6
|
+
import { configFile } from './key.js';
|
|
7
|
+
const DAY = 24 * 60 * 60 * 1000;
|
|
8
|
+
/** Whether version `a` is later than `b` ("0.1.10" > "0.1.9"); a pre-release suffix is ignored. */
|
|
9
|
+
export function newer(a, b) {
|
|
10
|
+
const parts = (v) => v.split('-')[0].split('.').map(Number);
|
|
11
|
+
const [x, y] = [parts(a), parts(b)];
|
|
12
|
+
for (let i = 0; i < 3; i++)
|
|
13
|
+
if ((x[i] ?? 0) !== (y[i] ?? 0))
|
|
14
|
+
return (x[i] ?? 0) > (y[i] ?? 0);
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
/** The version on npm when it is newer than `current`; undefined when it isn't, or npm couldn't be asked. */
|
|
18
|
+
export async function updateNotice(current, o = {}) {
|
|
19
|
+
const { now = Date.now(), file = join(dirname(configFile()), 'update.json'), registry = 'https://registry.npmjs.org' } = o;
|
|
20
|
+
let state = {};
|
|
21
|
+
try {
|
|
22
|
+
state = JSON.parse(readFileSync(file, 'utf8'));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
// never checked yet
|
|
26
|
+
}
|
|
27
|
+
if (!state.checked || now - state.checked > DAY) {
|
|
28
|
+
try {
|
|
29
|
+
const res = await fetch(`${registry}/${CLI_NAME}/latest`, { signal: AbortSignal.timeout(2000) });
|
|
30
|
+
const version = res.ok ? (await res.json()).version : undefined;
|
|
31
|
+
if (typeof version === 'string')
|
|
32
|
+
state.latest = version;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// offline, or npm slow: asked again tomorrow
|
|
36
|
+
}
|
|
37
|
+
state.checked = now;
|
|
38
|
+
try {
|
|
39
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
40
|
+
writeFileSync(file, JSON.stringify(state));
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// can't keep it: asked again next run
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return state.latest && newer(state.latest, current) ? state.latest : undefined;
|
|
47
|
+
}
|
package/package.json
CHANGED
|
@@ -1,10 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "z1llm",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Zero1LLM from the terminal: your models, chat, pictures and videos, with the Zero1LLM app open.",
|
|
5
5
|
"license": "MIT",
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
"
|
|
6
|
+
"repository": { "type": "git", "url": "git+https://github.com/THE01X-Zeronex/Zero1LLM.git", "directory": "packages/cli" },
|
|
7
|
+
"type": "module",
|
|
8
|
+
"homepage": "https://www.zero1llm.ai/docs/local-api",
|
|
9
|
+
"keywords": ["zero1llm", "llm", "local", "ai", "cli"],
|
|
10
|
+
"engines": { "node": ">=20" },
|
|
11
|
+
"bin": { "z1llm": "dist/cli.js", "zero1llm": "dist/cli.js" },
|
|
12
|
+
"files": ["dist", "README.md"],
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"@zero1llm/sdk": "^0.1.0",
|
|
15
|
+
"marked": "^16.4.2"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc -p tsconfig.json",
|
|
19
|
+
"typecheck": "tsc -p tsconfig.test.json --noEmit",
|
|
20
|
+
"test": "tsc -p tsconfig.json && tsc -p tsconfig.test.json && node --test \"out/test/**/*.test.js\""
|
|
21
|
+
}
|
|
10
22
|
}
|