brsh 3.10.4 → 3.10.6

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/lib/local/read.js CHANGED
@@ -29,7 +29,8 @@ class Read extends LocalCommand {
29
29
  }
30
30
 
31
31
  this.nchars = options.nchars;
32
- this.var = options.name;
32
+ this.names = options.name || [];
33
+ this.raw = options.raw;
33
34
 
34
35
  return new Promise((resolve) => {
35
36
  const tid = setTimeout(() => {
@@ -54,35 +55,75 @@ class Read extends LocalCommand {
54
55
  this.inputBuffer = ""
55
56
  }
56
57
 
57
- if (key.length === 1) {
58
- this.inputBuffer += key;
58
+ //without -r a backslash escapes the next char, and backslash-newline continues the line
59
+ if(!this.raw && !this.escaped && key === '\\') {
60
+ this.escaped = true;
61
+ return;
59
62
  }
60
63
 
61
- if (key === 'Enter') {
62
- if (this.var) {
63
- this.context.setVar(this.var, this.inputBuffer || '');
64
- this.completionCallback();
65
- } else {
66
- this.completionCallback(this.inputBuffer || '');
64
+ if(this.escaped) {
65
+ delete this.escaped;
66
+ if(key === 'Enter') {
67
+ return;
67
68
  }
68
- return;
69
69
  }
70
70
 
71
- if(this.inputBuffer.length === this.nchars) {
72
- if(this.var) {
73
- this.context.setVar(this.var, this.inputBuffer)
74
- this.completionCallback();
71
+ if (key.length === 1) {
72
+ this.inputBuffer += key;
73
+ if(this.inputBuffer.length !== this.nchars) {
75
74
  return;
76
75
  }
77
- this.completionCallback(this.inputBuffer);
76
+ }
77
+
78
+ if(key === 'Enter' || this.inputBuffer.length === this.nchars) {
79
+ this._finish();
78
80
  }
79
81
  }
80
82
 
83
+ _finish() {
84
+ if(this.names.length < 1) {
85
+ return this.completionCallback(this.inputBuffer);
86
+ }
87
+
88
+ //getVar returns '' for unset, but an empty IFS is meaningful
89
+ const ifs = this.context.vars.IFS;
90
+ this._split(this.inputBuffer, ifs === undefined ? ' \t\n' : ifs)
91
+ .forEach((value, i) => this.context.setVar(this.names[i], value));
92
+ this.completionCallback();
93
+ }
94
+
95
+ //one value per name, the last one takes the remainder
96
+ _split(line, ifs) {
97
+ const {names} = this;
98
+ const esc = s => s.replace(/[\]\\^-]/g, '\\$&');
99
+ const ws = esc(ifs.replace(/[^ \t\n]/g, ''));
100
+ const other = esc(ifs.replace(/[ \t\n]/g, ''));
101
+ const trimStart = s => ws ? s.replace(new RegExp(`^[${ws}]+`), '') : s;
102
+ const trimEnd = s => ws ? s.replace(new RegExp(`[${ws}]+$`), '') : s;
103
+ const delim = ifs === '' ? null : new RegExp(other ? `[${ws}]*[${other}][${ws}]*|[${ws}]+` : `[${ws}]+`);
104
+
105
+ let rest = trimStart(line);
106
+ return names.map((_, i) => {
107
+ if(i === names.length -1) {
108
+ return trimEnd(rest);
109
+ }
110
+ const m = delim && delim.exec(rest);
111
+ if(!m) {
112
+ const field = rest;
113
+ rest = '';
114
+ return field;
115
+ }
116
+ const field = rest.slice(0, m.index);
117
+ rest = rest.slice(m.index + m[0].length);
118
+ return field;
119
+ });
120
+ }
121
+
81
122
  printHelp(e) {
82
123
  if(e) {
83
124
  this.stdOut = e.message;
84
125
  }
85
- this.stdOut = 'usage: read [-n nchars] [-p prompt] [-t timeout] [name ...]'
126
+ this.stdOut = 'usage: read [-r] [-n nchars] [-p prompt] [-t timeout] [name ...]'
86
127
  }
87
128
 
88
129
  parseArgs() {
@@ -102,6 +143,11 @@ class Read extends LocalCommand {
102
143
  alias: 't',
103
144
  type: Number
104
145
  },
146
+ {
147
+ name: 'raw',
148
+ alias: 'r',
149
+ type: Boolean
150
+ },
105
151
  {
106
152
  name: 'help',
107
153
  alias: 'h',
@@ -109,6 +155,7 @@ class Read extends LocalCommand {
109
155
  },
110
156
  {
111
157
  defaultOption: true,
158
+ multiple: true,
112
159
  name: 'name',
113
160
  type: String
114
161
  },
@@ -185,9 +185,10 @@ class ProgressTracker {
185
185
  }
186
186
 
187
187
  clear() {
188
+ const wasActive = this.active;
188
189
  this.stopTimer();
189
190
  this.active = false;
190
- if (this.enabled && typeof this.onRender === 'function') {
191
+ if (wasActive && this.enabled && typeof this.onRender === 'function') {
191
192
  this.onRender('');
192
193
  }
193
194
  }
@@ -1176,6 +1177,7 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1176
1177
 
1177
1178
  const tracker = this._createTracker();
1178
1179
  tracker.start('Running inference', { hint: 'evaluating prompt & preparing KV cache' });
1180
+ let firstToken = false;
1179
1181
 
1180
1182
  try {
1181
1183
  if (typeof this._wllama.createChatCompletion === 'function') {
@@ -1183,7 +1185,6 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1183
1185
 
1184
1186
  if (res && typeof res[Symbol.asyncIterator] === 'function') {
1185
1187
  let fullText = '';
1186
- let firstToken = false;
1187
1188
  for await (const chunk of res) {
1188
1189
  const delta = chunk?.choices?.[0]?.delta?.content ?? chunk?.choices?.[0]?.text ?? '';
1189
1190
  if (delta) {
@@ -1193,8 +1194,6 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1193
1194
  if (this.interactive) {
1194
1195
  this._replStatus = 'Streaming tokens...';
1195
1196
  this._renderRepl();
1196
- } else {
1197
- this._clearStatus();
1198
1197
  }
1199
1198
  }
1200
1199
  fullText += delta;
@@ -1204,7 +1203,7 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1204
1203
  }
1205
1204
  }
1206
1205
  tracker.clear();
1207
- if (!this.interactive) {
1206
+ if (!this.interactive && !firstToken) {
1208
1207
  this._clearStatus();
1209
1208
  }
1210
1209
  return fullText;
@@ -1236,7 +1235,6 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1236
1235
  const res = await this._wllama.createCompletion(compOpts);
1237
1236
  if (res && typeof res[Symbol.asyncIterator] === 'function') {
1238
1237
  let fullText = '';
1239
- let firstToken = false;
1240
1238
  for await (const chunk of res) {
1241
1239
  const delta = chunk?.choices?.[0]?.text ?? chunk?.choices?.[0]?.delta?.content ?? '';
1242
1240
  if (delta) {
@@ -1246,8 +1244,6 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1246
1244
  if (this.interactive) {
1247
1245
  this._replStatus = 'Streaming tokens...';
1248
1246
  this._renderRepl();
1249
- } else {
1250
- this._clearStatus();
1251
1247
  }
1252
1248
  }
1253
1249
  fullText += delta;
@@ -1257,7 +1253,7 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1257
1253
  }
1258
1254
  }
1259
1255
  tracker.clear();
1260
- if (!this.interactive) {
1256
+ if (!this.interactive && !firstToken) {
1261
1257
  this._clearStatus();
1262
1258
  }
1263
1259
  return fullText;
@@ -1275,7 +1271,7 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1275
1271
  return text;
1276
1272
  } finally {
1277
1273
  tracker.clear();
1278
- if (!this.interactive) {
1274
+ if (!this.interactive && !firstToken) {
1279
1275
  this._clearStatus();
1280
1276
  }
1281
1277
  }
@@ -1497,11 +1493,11 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1497
1493
 
1498
1494
  const tracker = this._createTracker();
1499
1495
  tracker.start('Running inference', { hint: 'evaluating prompt & preparing KV cache' });
1496
+ let streamedAny = false;
1500
1497
  try {
1501
1498
  const res = await this._wllama.createCompletion(compOpts);
1502
1499
  let outText = '';
1503
1500
  if (res && typeof res[Symbol.asyncIterator] === 'function') {
1504
- let streamedAny = false;
1505
1501
  for await (const chunk of res) {
1506
1502
  const delta = chunk?.choices?.[0]?.text ?? chunk?.choices?.[0]?.delta?.content ?? '';
1507
1503
  if (delta) {
@@ -1509,7 +1505,6 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1509
1505
  streamedAny = true;
1510
1506
  this._streamedStdout = true;
1511
1507
  tracker.clear();
1512
- this._clearStatus();
1513
1508
  }
1514
1509
  outText += delta;
1515
1510
  if (this.stdout && typeof this.stdout.write === 'function') {
@@ -1519,7 +1514,9 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1519
1514
  }
1520
1515
  }
1521
1516
  tracker.clear();
1522
- this._clearStatus();
1517
+ if (!streamedAny) {
1518
+ this._clearStatus();
1519
+ }
1523
1520
  if (streamedAny && outText.length > 0 && !outText.endsWith('\n') && this.stdout && typeof this.stdout.write === 'function') {
1524
1521
  this.stdout.write('\r\n');
1525
1522
  }
@@ -1532,7 +1529,9 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1532
1529
  return;
1533
1530
  } finally {
1534
1531
  tracker.clear();
1535
- this._clearStatus();
1532
+ if (!streamedAny) {
1533
+ this._clearStatus();
1534
+ }
1536
1535
  }
1537
1536
  }
1538
1537
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brsh",
3
- "version": "3.10.4",
3
+ "version": "3.10.6",
4
4
  "description": "A unix like shell written in javascript",
5
5
  "main": "./dist/shell.min.js",
6
6
  "module": "./dist/shell.es.js",
@@ -176,6 +176,92 @@ describe('read', () => {
176
176
  expect(shell.context.getVar('CHAR')).toBe('x');
177
177
  });
178
178
 
179
+ const feed = async (cmd, text) => {
180
+ const p = shell.onCommand(cmd);
181
+ await new Promise(resolve => setImmediate(resolve));
182
+ [...text].forEach(c => shell.onInput(c));
183
+ shell.onInput('Enter');
184
+ await p;
185
+ };
186
+
187
+ it('splits input across multiple names, last takes the remainder', async () => {
188
+ await feed('read -t 1 A B C', ' one two three four ');
189
+ expect(shell.context.getVar('A')).toBe('one');
190
+ expect(shell.context.getVar('B')).toBe('two');
191
+ expect(shell.context.getVar('C')).toBe('three four');
192
+ });
193
+
194
+ it('respects IFS', async () => {
195
+ await shell.onCommand('export IFS=:');
196
+ await feed('read -t 1 A B', 'x:y:z');
197
+ expect(shell.context.getVar('A')).toBe('x');
198
+ expect(shell.context.getVar('B')).toBe('y:z');
199
+ });
200
+
201
+ it('trims surrounding IFS whitespace with a single name', async () => {
202
+ await feed('read -t 1 V', ' padded value ');
203
+ expect(shell.context.getVar('V')).toBe('padded value');
204
+ });
205
+
206
+ it('leaves extra names empty when input has fewer fields', async () => {
207
+ await feed('read -t 1 A B C', 'only');
208
+ expect(shell.context.getVar('A')).toBe('only');
209
+ expect(shell.context.getVar('B')).toBe('');
210
+ expect(shell.context.getVar('C')).toBe('');
211
+ });
212
+
213
+ it('handles whitespace around non-whitespace IFS separators', async () => {
214
+ await shell.onCommand('export IFS=" :"');
215
+ await feed('read -t 1 A B C', 'x : y z');
216
+ expect(shell.context.getVar('A')).toBe('x');
217
+ expect(shell.context.getVar('B')).toBe('y');
218
+ expect(shell.context.getVar('C')).toBe('z');
219
+ });
220
+
221
+ it('treats an escaped backslash as a literal backslash without -r', async () => {
222
+ await feed('read -t 1 V', 'a\\\\b');
223
+ expect(shell.context.getVar('V')).toBe('a\\b');
224
+ });
225
+
226
+ it('continues the line on backslash-newline without -r', async () => {
227
+ const p = shell.onCommand('read -t 1 V');
228
+ await new Promise(resolve => setImmediate(resolve));
229
+ ['a', '\\', 'Enter', 'b', 'Enter'].forEach(k => shell.onInput(k));
230
+ await p;
231
+ expect(shell.context.getVar('V')).toBe('ab');
232
+ });
233
+
234
+ it('ends the line on backslash-newline with -r', async () => {
235
+ const p = shell.onCommand('read -r -t 1 V');
236
+ await new Promise(resolve => setImmediate(resolve));
237
+ ['a', '\\', 'Enter'].forEach(k => shell.onInput(k));
238
+ await p;
239
+ expect(shell.context.getVar('V')).toBe('a\\');
240
+ });
241
+
242
+ it('accepts -r combined with -n', async () => {
243
+ const p = shell.onCommand('read -r -n 3 -t 1 V');
244
+ await new Promise(resolve => setImmediate(resolve));
245
+ [...'a\\bcd'].forEach(c => shell.onInput(c));
246
+ await p;
247
+ expect(shell.context.getVar('V')).toBe('a\\b');
248
+ });
249
+
250
+ it('mentions -r in usage', async () => {
251
+ const { output } = await run(shell, 'read -h');
252
+ expect(output.join(' ')).toContain('-r');
253
+ });
254
+
255
+ it('strips backslashes without -r', async () => {
256
+ await feed('read -t 1 V', 'a\\bc');
257
+ expect(shell.context.getVar('V')).toBe('abc');
258
+ });
259
+
260
+ it('keeps backslashes with -r', async () => {
261
+ await feed('read -r -t 1 V', 'a\\bc');
262
+ expect(shell.context.getVar('V')).toBe('a\\bc');
263
+ });
264
+
179
265
  it('shows help with -h', async () => {
180
266
  const { output } = await run(shell, 'read -h');
181
267
  expect(output.join(' ')).toMatch(/usage/i);
package/test/wbt.test.js CHANGED
@@ -1276,6 +1276,23 @@ describe('WBT Wllama v3 WASM & WebGPU package (`wllama`, `llama`, `llama-cli`)',
1276
1276
  expect(combinedStatus).toContain('Loading model (tinyllama.gguf) weights');
1277
1277
  expect(combinedStatus).toContain('Running inference');
1278
1278
  expect(combinedStatus).toMatch(/\[.*\]/);
1279
+
1280
+ // Ensure status clearing (\r\x1b[K) never fires after tokens start streaming to stdout
1281
+ for (const cmd of ['wllama -m /home/tinyllama.gguf -p "No clobber"', 'wllama -m /home/tinyllama.gguf --raw -p "Raw no clobber"']) {
1282
+ const timeline = [];
1283
+ const onTok = (t) => timeline.push({ stream: 'token', data: String(t) });
1284
+ const onErr = (c) => timeline.push({ stream: 'err', data: String(c) });
1285
+ shell.on('token', onTok);
1286
+ shell.stderr.on('data', onErr);
1287
+ await run(shell, cmd);
1288
+ shell.removeListener('token', onTok);
1289
+ shell.stderr.removeListener('data', onErr);
1290
+
1291
+ const firstTokenIdx = timeline.findIndex(e => e.stream === 'token');
1292
+ expect(firstTokenIdx).toBeGreaterThanOrEqual(0);
1293
+ const errAfterFirstToken = timeline.slice(firstTokenIdx + 1).filter(e => e.stream === 'err' && e.data.includes('\x1b[K'));
1294
+ expect(errAfterFirstToken).toEqual([]);
1295
+ }
1279
1296
  });
1280
1297
 
1281
1298
  it('supports Hugging Face model loading (--hf / hf:), embeddings (wllama embed), info, and bench', async () => {