brsh 2.6.0 → 2.8.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 (46) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/Readme.md +145 -1
  3. package/bin/Readme.md +6 -3
  4. package/bin/brsh-shell.js +68 -9
  5. package/bin/exportFileSystem.js +192 -80
  6. package/dist/shell.es.js +2497 -1300
  7. package/dist/shell.es.js.map +1 -1
  8. package/dist/shell.min.js +21 -14
  9. package/dist/shell.min.js.map +1 -1
  10. package/dist/terminal.cjs.js +101 -0
  11. package/dist/terminal.cjs.js.map +1 -0
  12. package/dist/terminal.es.js +290 -6965
  13. package/dist/terminal.es.js.map +1 -1
  14. package/dist/terminal.min.js +4 -25
  15. package/dist/terminal.min.js.map +1 -1
  16. package/dist/wbt.es.js +3974 -0
  17. package/dist/wbt.es.js.map +1 -0
  18. package/dist/wbt.min.js +10 -0
  19. package/dist/wbt.min.js.map +1 -0
  20. package/index.js +160 -20
  21. package/lib/BinaryContainer.js +528 -0
  22. package/lib/Command.js +2 -1
  23. package/lib/FileSystem.js +31 -0
  24. package/lib/NodeFileSystem.js +19 -9
  25. package/lib/ReplCommand.js +520 -0
  26. package/lib/ScriptCommand.js +1 -1
  27. package/lib/Terminal.js +45 -10
  28. package/lib/WasmCommand.js +1123 -35
  29. package/lib/buildFilesystemStructure.js +15 -4
  30. package/lib/local/curl.js +60 -2
  31. package/lib/wbt/index.js +756 -0
  32. package/lib/wbt/packages/wllama.js +1051 -0
  33. package/lib/wbt/registry.js +193 -0
  34. package/lib/wbt/utils.js +118 -0
  35. package/package.json +11 -3
  36. package/test/binary-filesystem.test.js +248 -0
  37. package/test/curl.test.js +166 -0
  38. package/test/exportFileSystem.test.js +78 -0
  39. package/test/terminal.test.js +113 -0
  40. package/test/wasm-cli.test.js +127 -0
  41. package/test/wbt.test.js +1175 -0
  42. package/vite.config.demo.js +4 -0
  43. package/vite.config.js +4 -0
  44. package/vite.config.terminal.js +16 -12
  45. package/vite.config.wbt.js +21 -0
  46. package/vitest.config.js +6 -0
@@ -0,0 +1,1175 @@
1
+ import { createRequire } from 'module';
2
+ import { describe, it, expect, beforeEach } from 'vitest';
3
+ import { createShell, run } from './helpers.js';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ const Wbt = require('../lib/wbt/index.js');
7
+ const { wllamaInstances } = require('../lib/wbt/packages/wllama.js');
8
+
9
+ // Minimal valid WASM binary that exits cleanly with 0 via _start:
10
+ // (module (func (export "_start")))
11
+ const MINIMAL_WASM_BYTES = new Uint8Array([
12
+ 0x00, 0x61, 0x73, 0x6d, // \0asm
13
+ 0x01, 0x00, 0x00, 0x00, // version 1
14
+ 0x01, 0x04, 0x01, 0x60, 0x00, 0x00, // type section: 1 func () -> ()
15
+ 0x03, 0x02, 0x01, 0x00, // func section: 1 func of type 0
16
+ 0x07, 0x0a, 0x01, 0x06, 0x5f, 0x73, 0x74, 0x61, 0x72, 0x74, 0x00, 0x00, // export "_start"
17
+ 0x0a, 0x04, 0x01, 0x02, 0x00, 0x0b // code section: empty body
18
+ ]);
19
+
20
+ // Minimal WASM binary that exports `__eval() -> f64 (42.0)` for testing `asrun`
21
+ // (module (func (export "__eval") (result f64) f64.const 42))
22
+ const EVAL_42_WASM_BYTES = new Uint8Array([
23
+ 0x00, 0x61, 0x73, 0x6d,
24
+ 0x01, 0x00, 0x00, 0x00,
25
+ 0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7c, // () -> f64
26
+ 0x03, 0x02, 0x01, 0x00,
27
+ 0x07, 0x0a, 0x01, 0x06, 0x5f, 0x5f, 0x65, 0x76, 0x61, 0x6c, 0x00, 0x00, // export "__eval"
28
+ 0x0a, 0x0d, 0x01, 0x0b, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x40, 0x0b // f64.const 42.0
29
+ ]);
30
+
31
+ /**
32
+ * Standard CLI/Emscripten mock for sqlite3 so tests exercise the pure generic runtime + ReplCommand extension.
33
+ */
34
+ function createMockSqlJs() {
35
+ const { formatTable, formatPipeList, formatCsv } = require('../lib/wbt/utils.js');
36
+ return {
37
+ async main(args, io) {
38
+ let mode = 'list';
39
+ let dbPath = ':memory:';
40
+ let sql = null;
41
+ const positional = [];
42
+
43
+ for (let i = 0; i < args.length; i++) {
44
+ const a = args[i];
45
+ if (a === '-table' || a === '--table' || a === '-box') mode = 'table';
46
+ else if (a === '-csv' || a === '--csv') mode = 'csv';
47
+ else if (a === '-cmd' && i + 1 < args.length) sql = args[++i];
48
+ else if (!a.startsWith('-')) positional.push(a);
49
+ }
50
+
51
+ if (positional.length === 1) {
52
+ if (/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|\.)\b/i.test(positional[0])) {
53
+ sql = positional[0];
54
+ } else {
55
+ dbPath = positional[0];
56
+ }
57
+ } else if (positional.length >= 2) {
58
+ dbPath = positional[0];
59
+ sql = positional.slice(1).join(' ');
60
+ }
61
+ if (!sql && io.stdin && io.stdin.trim()) {
62
+ sql = io.stdin.trim();
63
+ }
64
+ if (!sql) return 0;
65
+
66
+ let state = { _tables: {} };
67
+ if (dbPath !== ':memory:') {
68
+ const existing = io.readFile(dbPath);
69
+ if (existing) {
70
+ try { state = JSON.parse(existing); } catch { /* ignore */ }
71
+ }
72
+ }
73
+
74
+ for (const rawStmt of sql.split(';').map(s => s.trim()).filter(Boolean)) {
75
+ if (rawStmt === '.tables') {
76
+ io.stdout(Object.keys(state._tables).sort().join(' '));
77
+ continue;
78
+ }
79
+ const createMatch = rawStmt.match(/^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)\s*\((.+)\)/i);
80
+ if (createMatch) {
81
+ const tbl = createMatch[1];
82
+ const cols = createMatch[2].split(',').map(c => c.trim().split(/\s+/)[0]);
83
+ state._tables[tbl] = { columns: cols, rows: [] };
84
+ continue;
85
+ }
86
+ const insertMatch = rawStmt.match(/^INSERT\s+INTO\s+(\w+)(?:\s*\(([^)]+)\))?\s+VALUES\s*\((.+)\)/i);
87
+ if (insertMatch) {
88
+ const tbl = insertMatch[1];
89
+ const vals = insertMatch[3].split(',').map(v => {
90
+ const s = v.trim().replace(/^['"]|['"]$/g, '');
91
+ const n = Number(s);
92
+ return Number.isNaN(n) ? s : n;
93
+ });
94
+ state._tables[tbl].rows.push(vals);
95
+ continue;
96
+ }
97
+ const selectTableMatch = rawStmt.match(/^SELECT\s+(.+)\s+FROM\s+(\w+)/i);
98
+ if (selectTableMatch) {
99
+ const tbl = state._tables[selectTableMatch[2]];
100
+ if (tbl) {
101
+ const lines = mode === 'table'
102
+ ? formatTable(tbl.columns, tbl.rows, { showRowCount: false })
103
+ : mode === 'csv'
104
+ ? formatCsv(tbl.columns, tbl.rows, true)
105
+ : formatPipeList(tbl.columns, tbl.rows, false);
106
+ lines.forEach(l => io.stdout(l));
107
+ }
108
+ continue;
109
+ }
110
+ const selectExprMatch = rawStmt.match(/^SELECT\s+(.+?)(?:\s+AS\s+(\w+))?$/i);
111
+ if (selectExprMatch) {
112
+ const val = Function(`return (${selectExprMatch[1]})`)();
113
+ io.stdout(String(val));
114
+ }
115
+ }
116
+
117
+ if (dbPath !== ':memory:') {
118
+ io.writeFile(dbPath, JSON.stringify(state));
119
+ }
120
+ return 0;
121
+ }
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Mock AssemblyScript CLI (`assemblyscript/asc`).
127
+ */
128
+ function createMockAsc() {
129
+ return {
130
+ ready: Promise.resolve(),
131
+ async main(args, options) {
132
+ let inputFile = null;
133
+ let outFile = null;
134
+ let textFile = null;
135
+ let evalCode = null;
136
+ for (let i = 0; i < args.length; i++) {
137
+ const a = args[i];
138
+ if ((a === '-o' || a === '--outFile') && i + 1 < args.length) {
139
+ outFile = args[++i];
140
+ } else if ((a === '-t' || a === '--textFile') && i + 1 < args.length) {
141
+ textFile = args[++i];
142
+ } else if ((a === '-e' || a === '--eval') && i + 1 < args.length) {
143
+ evalCode = args[++i];
144
+ } else if (!a.startsWith('-')) {
145
+ inputFile = a;
146
+ }
147
+ }
148
+ if (evalCode !== null) {
149
+ options.stdout(String(Function(`return (${evalCode})`)()));
150
+ return { error: null };
151
+ }
152
+ if (!inputFile) {
153
+ options.stderr.write('ERROR: No input file specified\n');
154
+ return { error: new Error('No input file specified') };
155
+ }
156
+ const src = options.readFile(inputFile, '.');
157
+ if (src == null) {
158
+ options.stderr.write(`ERROR: File not found: ${inputFile}\n`);
159
+ return { error: new Error(`File not found: ${inputFile}`) };
160
+ }
161
+ if (src.includes('SYNTAX_ERROR')) {
162
+ options.stderr.write(`ERROR TS1005: ';' expected in ${inputFile}\n`);
163
+ return { error: new Error('Compilation failed') };
164
+ }
165
+ if (outFile) {
166
+ const bytesToWrite = src.includes('__eval') ? EVAL_42_WASM_BYTES : MINIMAL_WASM_BYTES;
167
+ options.writeFile(outFile, bytesToWrite, '.');
168
+ }
169
+ if (textFile) {
170
+ options.writeFile(textFile, '(module\n (func (export "_start"))\n)\n', '.');
171
+ }
172
+ return { error: null };
173
+ }
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Mock QuickJS module using standard CLI main(args, io).
179
+ */
180
+ function createMockQuickJs() {
181
+ return {
182
+ async main(args, io) {
183
+ let code = io.stdin;
184
+ for (let i = 0; i < args.length; i++) {
185
+ if ((args[i] === '-e' || args[i] === '--eval') && i + 1 < args.length) code = args[++i];
186
+ else if (!args[i].startsWith('-')) code = io.readFile(args[i]);
187
+ }
188
+ if (code) io.stdout(String(Function(`return (${code})`)()));
189
+ return 0;
190
+ }
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Mock Lua module using standard CLI main(args, io).
196
+ */
197
+ function createMockLua() {
198
+ return {
199
+ async main(args, io) {
200
+ let code = io.stdin;
201
+ for (let i = 0; i < args.length; i++) {
202
+ if (args[i] === '-e' && i + 1 < args.length) code = args[++i];
203
+ else if (!args[i].startsWith('-')) code = io.readFile(args[i]);
204
+ }
205
+ if (code) {
206
+ const retMatch = code.match(/^return\s+(.+)$/);
207
+ if (retMatch) io.stdout(String(Function(`return (${retMatch[1]})`)()));
208
+ }
209
+ return 0;
210
+ }
211
+ };
212
+ }
213
+
214
+ /**
215
+ * Mock jq module using standard CLI main(args, io).
216
+ */
217
+ function createMockJq() {
218
+ return {
219
+ async main(args, io) {
220
+ if (args.includes('--help') || args.includes('-h')) {
221
+ io.stdout('jq - commandline JSON processor [version 1.7.1]');
222
+ io.stdout('Usage: jq [options] <jq filter> [file...]');
223
+ io.stdout(' -c, --compact-output compact instead of pretty-printed output;');
224
+ io.stdout(' -n, --null-input use `null` as the single input value;');
225
+ io.stdout(' -r, --raw-output output raw strings, not JSON texts;');
226
+ io.stdout(' -s, --slurp read (slurp) all inputs into an array;');
227
+ return 0;
228
+ }
229
+ const positional = args.filter(a => !a.startsWith('-'));
230
+ const filter = positional.shift() || '.';
231
+ const input = positional.length > 0 ? io.readFile(positional[0]) : io.stdin;
232
+ const data = JSON.parse(input);
233
+ const parts = filter.replace(/^\./, '').split('.').filter(Boolean);
234
+ let cur = data;
235
+ for (const p of parts) {
236
+ cur = cur ? cur[p] : undefined;
237
+ }
238
+ io.stdout(typeof cur === 'string' && args.includes('-r') ? cur : JSON.stringify(cur));
239
+ return 0;
240
+ }
241
+ };
242
+ }
243
+
244
+ /**
245
+ * Mock Python3 module using standard CLI main(args, io).
246
+ */
247
+ function createMockPyodide() {
248
+ return {
249
+ async main(args, io) {
250
+ let code = null;
251
+ for (let i = 0; i < args.length; i++) {
252
+ if (args[i] === '-c' && i + 1 < args.length) code = args[++i];
253
+ else if (!args[i].startsWith('-')) code = io.readFile(args[i]);
254
+ }
255
+ if (!code) code = io.stdin;
256
+ const printMatch = code && code.match(/print\(['"](.+?)['"]\)/);
257
+ if (printMatch) io.stdout(printMatch[1]);
258
+ else if (code && /^[\d\s+\-*/%()]+$/.test(code.trim())) io.stdout(String(Function(`return (${code})`)()));
259
+ return 0;
260
+ }
261
+ };
262
+ }
263
+
264
+ /**
265
+ * Mock DuckDB module using standard CLI main(args, io).
266
+ */
267
+ function createMockDuckDb() {
268
+ return {
269
+ async main(args, io) {
270
+ let sql = io.stdin;
271
+ for (let i = 0; i < args.length; i++) {
272
+ if ((args[i] === '-c' || args[i] === '-s') && i + 1 < args.length) sql = args[++i];
273
+ }
274
+ if (/SELECT\s+100\s+AS\s+total/i.test(sql)) {
275
+ io.stdout('100');
276
+ }
277
+ return 0;
278
+ }
279
+ };
280
+ }
281
+
282
+ /**
283
+ * Mock Graphviz module using standard CLI main(args, io).
284
+ */
285
+ function createMockGraphviz() {
286
+ return {
287
+ async main(args, io) {
288
+ let outFile = null;
289
+ let inFile = null;
290
+ for (let i = 0; i < args.length; i++) {
291
+ if (args[i] === '-o' && i + 1 < args.length) outFile = args[++i];
292
+ else if (!args[i].startsWith('-')) inFile = args[i];
293
+ }
294
+ const dotSource = inFile ? io.readFile(inFile) : io.stdin;
295
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg"><!-- ${(dotSource || '').trim()} --></svg>`;
296
+ if (outFile) io.writeFile(outFile, svg);
297
+ else io.stdout(svg);
298
+ return 0;
299
+ }
300
+ };
301
+ }
302
+
303
+ /**
304
+ * Mock FFmpeg virtual-FS class (instantiated by generic runtime's class/virtual-FS support).
305
+ */
306
+ function createMockFfmpeg() {
307
+ return class MockFFmpeg {
308
+ constructor() {
309
+ this.loaded = false;
310
+ this._files = new Map();
311
+ this._listeners = [];
312
+ }
313
+ on(evt, cb) {
314
+ if (evt === 'log') this._listeners.push(cb);
315
+ }
316
+ async load() {
317
+ this.loaded = true;
318
+ }
319
+ async writeFile(name, bytes) {
320
+ this._files.set(name, bytes);
321
+ }
322
+ async exec(args) {
323
+ const outName = args[args.length - 1];
324
+ for (const cb of this._listeners) {
325
+ cb({ message: `Transcoding to ${outName} complete` });
326
+ }
327
+ this._files.set(outName, new TextEncoder().encode('WEBVTT-TRANSCODED'));
328
+ return 0;
329
+ }
330
+ async readFile(name) {
331
+ return this._files.get(name) || null;
332
+ }
333
+ };
334
+ }
335
+
336
+ /**
337
+ * Mock Emscripten modularized CLI package (no custom adapter — tests generic runtime!).
338
+ */
339
+ function createMockEmscriptenCowsay() {
340
+ return async function EmscriptenModule(opts) {
341
+ return {
342
+ FS: {
343
+ _files: {},
344
+ writeFile(p, d) { this._files[p] = d; },
345
+ readFile(p) {
346
+ if (!(p in this._files)) throw new Error('ENOENT');
347
+ return this._files[p];
348
+ }
349
+ },
350
+ callMain(args) {
351
+ opts.print(`< ${args.join(' ') || 'moo'} >`);
352
+ return 0;
353
+ }
354
+ };
355
+ };
356
+ }
357
+
358
+ /**
359
+ * In-memory mock implementation of @wllama/wllama v3 for deterministic tests.
360
+ */
361
+ function createMockWllama() {
362
+ class MockWllama {
363
+ constructor(pathConfig, config = {}) {
364
+ this.pathConfig = pathConfig;
365
+ this.config = config;
366
+ this._loaded = false;
367
+ this._loadParams = {};
368
+ this._modelSource = null;
369
+ this.modelManager = {
370
+ getModels: async () => []
371
+ };
372
+ }
373
+
374
+ static getLibllamaVersion() {
375
+ return 'b6327-4d74393';
376
+ }
377
+
378
+ isSupportWebGPU() {
379
+ return true;
380
+ }
381
+
382
+ isMultithread() {
383
+ return true;
384
+ }
385
+
386
+ getNumThreads() {
387
+ return 4;
388
+ }
389
+
390
+ isModelLoaded() {
391
+ return this._loaded;
392
+ }
393
+
394
+ getModelMetadata() {
395
+ return {
396
+ hparams: { nVocab: 32000, nCtxTrain: 4096, nEmbd: 2048, nLayer: 22 },
397
+ meta: { 'general.name': 'TinyLlama-1.1B' }
398
+ };
399
+ }
400
+
401
+ async loadModel(blobs, params = {}) {
402
+ this._loaded = true;
403
+ this._loadParams = params;
404
+ this._modelSource = blobs.map(b => b.name || 'blob.gguf').join('+');
405
+ }
406
+
407
+ async loadModelFromUrl(urlOrObj, params = {}) {
408
+ if (typeof params.progressCallback === 'function') {
409
+ params.progressCallback({ loaded: 524288, total: 1048576 });
410
+ params.progressCallback({ loaded: 1048576, total: 1048576 });
411
+ }
412
+ this._loaded = true;
413
+ this._loadParams = params;
414
+ this._modelSource = typeof urlOrObj === 'string' ? urlOrObj : urlOrObj.url;
415
+ }
416
+
417
+ async loadModelFromHF(hfOpts, params = {}) {
418
+ if (typeof params.progressCallback === 'function') {
419
+ params.progressCallback({ loaded: 524288, total: 1048576 });
420
+ params.progressCallback({ loaded: 1048576, total: 1048576 });
421
+ }
422
+ this._loaded = true;
423
+ this._loadParams = params;
424
+ this._modelSource = `hf:${hfOpts.repo}:${hfOpts.quant || 'Q4_K_M'}`;
425
+ }
426
+
427
+ async getLoadedBlob() {
428
+ return new Uint8Array([0x47, 0x47, 0x55, 0x46, 0x03, 0x00, 0x00, 0x00]);
429
+ }
430
+
431
+ async createChatCompletion(opts) {
432
+ const messages = opts.messages || [];
433
+ const sysMsg = messages.find(m => m.role === 'system');
434
+ const userMsgs = messages.filter(m => m.role === 'user').map(m => m.content);
435
+ const prefix = sysMsg ? `[sys:${sysMsg.content}] ` : '';
436
+ const gpuTag = this._loadParams.n_gpu_layers === 0 ? 'CPU' : 'WebGPU';
437
+ const reply = `${prefix}Reply(${gpuTag},turns=${userMsgs.length}): ${userMsgs[userMsgs.length - 1] || ''}`;
438
+ return {
439
+ id: 'chatcmpl-wllama',
440
+ object: 'chat.completion',
441
+ choices: [
442
+ {
443
+ index: 0,
444
+ message: { role: 'assistant', content: reply },
445
+ finish_reason: 'stop'
446
+ }
447
+ ]
448
+ };
449
+ }
450
+
451
+ async createCompletion(opts) {
452
+ return {
453
+ id: 'cmpl-wllama',
454
+ object: 'text_completion',
455
+ choices: [
456
+ {
457
+ index: 0,
458
+ text: `${opts.prompt} [completed]`,
459
+ finish_reason: 'stop'
460
+ }
461
+ ]
462
+ };
463
+ }
464
+
465
+ async createEmbedding(opts) {
466
+ const text = String(opts.input || '');
467
+ return {
468
+ object: 'list',
469
+ data: [
470
+ {
471
+ object: 'embedding',
472
+ index: 0,
473
+ embedding: [text.length, 0.25, 0.5, 0.75]
474
+ }
475
+ ]
476
+ };
477
+ }
478
+
479
+ async testBackendOps() {
480
+ return { retcode: 0, success: true };
481
+ }
482
+
483
+ async exit() {
484
+ this._loaded = false;
485
+ }
486
+ }
487
+
488
+ return {
489
+ Wllama: MockWllama,
490
+ LoggerWithoutDebug: console
491
+ };
492
+ }
493
+
494
+ function createTestWbt() {
495
+ return Wbt.configure({
496
+ moduleLoader: async (pkgName) => {
497
+ if (pkgName === 'sql.js' || pkgName === 'sqlite3') return createMockSqlJs();
498
+ if (pkgName === '@wllama/wllama' || pkgName === 'wllama') return createMockWllama();
499
+ if (pkgName === 'assemblyscript/asc' || pkgName === 'assemblyscript') return createMockAsc();
500
+ if (pkgName === 'quickjs-emscripten' || pkgName === 'quickjs') return createMockQuickJs();
501
+ if (pkgName === 'wasmoon' || pkgName === 'lua') return createMockLua();
502
+ if (pkgName === 'jq-web' || pkgName === 'jq') return createMockJq();
503
+ if (pkgName === 'pyodide' || pkgName === 'python3') return createMockPyodide();
504
+ if (pkgName === '@duckdb/duckdb-wasm' || pkgName === 'duckdb') return createMockDuckDb();
505
+ if (pkgName === '@hpcc-js/wasm-graphviz' || pkgName === 'graphviz') return createMockGraphviz();
506
+ if (pkgName === '@ffmpeg/ffmpeg' || pkgName === 'ffmpeg') return createMockFfmpeg();
507
+ if (pkgName === 'cowsay-wasm') return createMockEmscriptenCowsay();
508
+ return null;
509
+ },
510
+ fetch: async (url) => {
511
+ if (url === 'https://example.com/hello.wasm') {
512
+ return {
513
+ ok: true,
514
+ status: 200,
515
+ arrayBuffer: async () => MINIMAL_WASM_BYTES.buffer
516
+ };
517
+ }
518
+ if (url === 'https://example.com/registry.json') {
519
+ return {
520
+ ok: true,
521
+ status: 200,
522
+ json: async () => ({
523
+ custompkg: {
524
+ name: 'custompkg',
525
+ bin: 'custompkg',
526
+ version: '2.0.0',
527
+ description: 'Remote registry test package',
528
+ cdnUrl: 'https://esm.sh/custompkg@2.0.0',
529
+ type: 'builtin-adapter',
530
+ adapter: 'quickjs'
531
+ }
532
+ })
533
+ };
534
+ }
535
+ return { ok: false, status: 404 };
536
+ },
537
+ sources: ['https://example.com/registry.json']
538
+ });
539
+ }
540
+
541
+ // ============================================================================
542
+ // Tests
543
+ // ============================================================================
544
+
545
+ describe('WBT optional package behavior', () => {
546
+ it('is NOT included in a default Shell instance unless registered', async () => {
547
+ const shell = await createShell();
548
+ const { errors, exitCode } = await run(shell, 'wbt list');
549
+ expect(exitCode).toBe(1);
550
+ expect(errors.join(' ')).toMatch(/Command not found/i);
551
+ });
552
+
553
+ it('can be registered into a Shell instance via shell.context.setCommand(Wbt)', async () => {
554
+ const shell = await createShell();
555
+ shell.context.setCommand(createTestWbt());
556
+ const { output, exitCode } = await run(shell, 'wbt --version');
557
+ expect(exitCode).toBe(0);
558
+ expect(output.join('\n')).toContain('wbt 1.1.0');
559
+ });
560
+ });
561
+
562
+ describe('WBT CLI subcommands (list, search, show, install, remove, update)', () => {
563
+ let shell;
564
+
565
+ beforeEach(async () => {
566
+ shell = await createShell({ filesystem: { home: {} } });
567
+ shell.context.setCommand(createTestWbt());
568
+ });
569
+
570
+ it('shows help when run with no arguments or --help', async () => {
571
+ const { output, exitCode } = await run(shell, 'wbt');
572
+ expect(exitCode).toBe(0);
573
+ const text = output.join('\n');
574
+ expect(text).toContain('Web Binary Tool');
575
+ expect(text).toContain('sqlite3');
576
+ expect(text).toContain('assemblyscript');
577
+ expect(text).toContain('jq');
578
+ expect(text).toContain('python3');
579
+ expect(text).toContain('duckdb');
580
+ expect(text).toContain('graphviz');
581
+ expect(text).toContain('ffmpeg');
582
+ });
583
+
584
+ it('lists available packages with `wbt list` and installed packages with `wbt list --installed`', async () => {
585
+ const allRes = await run(shell, 'wbt list');
586
+ expect(allRes.exitCode).toBe(0);
587
+ expect(allRes.output.join('\n')).toContain('sqlite3/wasm');
588
+ expect(allRes.output.join('\n')).toContain('assemblyscript/wasm');
589
+ expect(allRes.output.join('\n')).toContain('duckdb/wasm');
590
+
591
+ const emptyInstalled = await run(shell, 'wbt list --installed');
592
+ expect(emptyInstalled.exitCode).toBe(0);
593
+ expect(emptyInstalled.output).toEqual(['Listing...']);
594
+
595
+ await run(shell, 'wbt install sqlite3');
596
+ const afterInstall = await run(shell, 'wbt list --installed');
597
+ expect(afterInstall.output.join('\n')).toContain('sqlite3/wasm');
598
+ expect(afterInstall.output.join('\n')).toContain('[installed]');
599
+ });
600
+
601
+ it('searches packages by keyword with `wbt search`', async () => {
602
+ const { output, exitCode } = await run(shell, 'wbt search json');
603
+ expect(exitCode).toBe(0);
604
+ expect(output.join('\n')).toContain('jq/wasm');
605
+ expect(output.join('\n')).not.toContain('lua/wasm');
606
+ });
607
+
608
+ it('shows detailed package metadata with `wbt show`', async () => {
609
+ const { output, exitCode } = await run(shell, 'wbt show sqlite3');
610
+ expect(exitCode).toBe(0);
611
+ const text = output.join('\n');
612
+ expect(text).toContain('Package: sqlite3');
613
+ expect(text).toContain('State: not installed');
614
+ expect(text).toContain('Binary: sqlite3');
615
+
616
+ await run(shell, 'wbt install sqlite3');
617
+ const afterShow = await run(shell, 'wbt show sqlite3');
618
+ expect(afterShow.output.join('\n')).toContain('State: installed');
619
+ });
620
+
621
+ it('returns an error when installing an unknown package', async () => {
622
+ const { errors, exitCode } = await run(shell, 'wbt install nonexistent-wasm-pkg');
623
+ expect(exitCode).toBe(100);
624
+ expect(errors.join(' ')).toContain('Unable to locate package nonexistent-wasm-pkg');
625
+ });
626
+
627
+ it('removes an installed package and unregisters its binary from /bin', async () => {
628
+ await run(shell, 'wbt install sqlite3');
629
+ const check1 = await run(shell, 'which sqlite3');
630
+ expect(check1.output.join('')).toContain('/bin/sqlite3');
631
+
632
+ const rmRes = await run(shell, 'wbt remove sqlite3');
633
+ expect(rmRes.exitCode).toBe(0);
634
+ expect(rmRes.output.join('\n')).toContain('Removing sqlite3');
635
+
636
+ const check2 = await run(shell, 'sqlite3 --version');
637
+ expect(check2.exitCode).toBe(1);
638
+ expect(check2.errors.join(' ')).toMatch(/Command not found/i);
639
+ });
640
+
641
+ it('updates remote sources with `wbt update`', async () => {
642
+ const { output, exitCode } = await run(shell, 'wbt update');
643
+ expect(exitCode).toBe(0);
644
+ expect(output.join('\n')).toContain('Reading package lists... Done');
645
+
646
+ const showCustom = await run(shell, 'wbt show custompkg');
647
+ expect(showCustom.exitCode).toBe(0);
648
+ expect(showCustom.output.join('\n')).toContain('Remote registry test package');
649
+ });
650
+
651
+ it('restores installed commands from /var/lib/wbt/installed.json via Wbt.restoreInstalled', async () => {
652
+ await run(shell, 'wbt install sqlite3');
653
+ const rawFs = shell.context.fs.getRaw();
654
+ const rawPerms = shell.context.fs.getRawPermissions();
655
+
656
+ const savedInstalledJson = rawFs.var.lib.wbt['installed.json'];
657
+ const shell2 = await createShell({
658
+ filesystem: {
659
+ var: { lib: { wbt: { 'installed.json': savedInstalledJson } } }
660
+ },
661
+ permissions: rawPerms
662
+ });
663
+ const TestWbt = createTestWbt();
664
+ shell2.context.setCommand(TestWbt);
665
+ TestWbt.restoreInstalled(shell2);
666
+
667
+ const { output, exitCode } = await run(shell2, 'sqlite3 --version');
668
+ expect(exitCode).toBe(0);
669
+ expect(output.join('\n')).toContain('1.13.0');
670
+ });
671
+ });
672
+
673
+ describe('WBT SQLite3 WASM package (`sqlite3` / `sqlite`)', () => {
674
+ let shell;
675
+
676
+ beforeEach(async () => {
677
+ shell = await createShell({ filesystem: { home: {} } });
678
+ shell.context.setCommand(createTestWbt());
679
+ await run(shell, 'wbt install sqlite');
680
+ });
681
+
682
+ it('executes one-shot SQL queries and formats output', async () => {
683
+ const { output, exitCode } = await run(shell, 'sqlite3 "SELECT 40 + 2 AS answer"');
684
+ expect(exitCode).toBe(0);
685
+ expect(output).toContain('42');
686
+ });
687
+
688
+ it('persists SQLite database files in the brsh filesystem across invocations', async () => {
689
+ const res1 = await run(
690
+ shell,
691
+ 'sqlite3 /home/app.db "CREATE TABLE users (id INT, name TEXT); INSERT INTO users VALUES (1, \'Ada\'); INSERT INTO users VALUES (2, \'Grace\');"'
692
+ );
693
+ expect(res1.exitCode).toBe(0);
694
+ expect(shell.context.fs.exists('/home/app.db')).toBe(true);
695
+
696
+ const res2 = await run(shell, 'sqlite3 -table /home/app.db "SELECT * FROM users"');
697
+ expect(res2.exitCode).toBe(0);
698
+ const tableOut = res2.output.join('\n');
699
+ expect(tableOut).toContain('Ada');
700
+ expect(tableOut).toContain('Grace');
701
+ expect(tableOut).toContain('id');
702
+ expect(tableOut).toContain('name');
703
+ });
704
+
705
+ it('supports piped SQL via stdin and dot-commands (.tables)', async () => {
706
+ await run(shell, 'sqlite3 /home/test.db "CREATE TABLE items (id INT, title TEXT); INSERT INTO items VALUES (10, \'Book\');"');
707
+ const piped = await run(shell, 'echo "SELECT * FROM items;" | sqlite3 -csv /home/test.db');
708
+ expect(piped.exitCode).toBe(0);
709
+ expect(piped.output.join('\n')).toContain('id,title');
710
+ expect(piped.output.join('\n')).toContain('10,Book');
711
+
712
+ const tablesRes = await run(shell, 'sqlite3 /home/test.db ".tables"');
713
+ expect(tablesRes.exitCode).toBe(0);
714
+ expect(tablesRes.output.join('\n')).toContain('items');
715
+ });
716
+ });
717
+
718
+ describe('WBT AssemblyScript compiler (`asc`) and JIT/AOT runtime (`asrun` / `asnode`)', () => {
719
+ let shell;
720
+
721
+ beforeEach(async () => {
722
+ shell = await createShell({
723
+ filesystem: {
724
+ home: {
725
+ 'hello.ts': 'export function _start(): void {}',
726
+ 'broken.ts': 'SYNTAX_ERROR'
727
+ }
728
+ }
729
+ });
730
+ shell.context.setCommand(createTestWbt());
731
+ await run(shell, 'wbt install assemblyscript');
732
+ });
733
+
734
+ it('compiles AssemblyScript source files in the brsh filesystem to executable .wasm binaries', async () => {
735
+ const compileRes = await run(shell, 'asc /home/hello.ts -o /home/hello.wasm -t /home/hello.wat');
736
+ expect(compileRes.exitCode).toBe(0);
737
+ expect(shell.context.fs.exists('/home/hello.wasm')).toBe(true);
738
+ expect(shell.context.fs.exists('/home/hello.wat')).toBe(true);
739
+ expect(shell.context.fs.isExecutable('/home/hello.wasm')).toBe(true);
740
+
741
+ // Execute the compiled .wasm binary directly in brsh!
742
+ const execRes = await run(shell, '/home/hello.wasm');
743
+ expect(execRes.exitCode).toBe(0);
744
+ });
745
+
746
+ it('runs AssemblyScript `.ts` files and `-e` expressions directly via `asrun` / `asnode`', async () => {
747
+ const evalRes = await run(shell, 'asrun -e "21 * 2"');
748
+ expect(evalRes.exitCode).toBe(0);
749
+ expect(evalRes.output).toContain('42');
750
+
751
+ const fileRes = await run(shell, 'asnode /home/hello.ts');
752
+ expect(fileRes.exitCode).toBe(0);
753
+ });
754
+
755
+ it('reports compilation errors on invalid AssemblyScript source', async () => {
756
+ const { errors, exitCode } = await run(shell, 'asc /home/broken.ts -o /home/broken.wasm');
757
+ expect(exitCode).toBe(1);
758
+ expect(errors.join('\n')).toContain('TS1005');
759
+ });
760
+ });
761
+
762
+ describe('WBT Curated WASM Tools (`jq`, `python3`, `duckdb`, `dot`, `ffmpeg`) & Generic Runtime', () => {
763
+ let shell;
764
+
765
+ beforeEach(async () => {
766
+ shell = await createShell({
767
+ filesystem: {
768
+ home: {
769
+ 'data.json': '{"user":{"name":"Ada","role":"admin"}}',
770
+ 'hello.py': 'print("Hello from Pyodide!")',
771
+ 'graph.dot': 'digraph G { A -> B; }',
772
+ 'input.mp4': 'RAW_MEDIA_BYTES'
773
+ }
774
+ }
775
+ });
776
+ shell.context.setCommand(createTestWbt());
777
+ });
778
+
779
+ it('processes JSON files and piped JSON with `jq`', async () => {
780
+ await run(shell, 'wbt install jq');
781
+ const res = await run(shell, 'cat /home/data.json | jq -r ".user.name"');
782
+ expect(res.exitCode).toBe(0);
783
+ expect(res.output).toContain('Ada');
784
+ });
785
+
786
+ it('runs Python 3 scripts and `-c` expressions with `python3` / `python`', async () => {
787
+ await run(shell, 'wbt install python3');
788
+ const scriptRes = await run(shell, 'python3 /home/hello.py');
789
+ expect(scriptRes.exitCode).toBe(0);
790
+ expect(scriptRes.output).toContain('Hello from Pyodide!');
791
+
792
+ const evalRes = await run(shell, 'python -c "6 * 7"');
793
+ expect(evalRes.exitCode).toBe(0);
794
+ expect(evalRes.output).toContain('42');
795
+ });
796
+
797
+ it('runs analytical SQL queries with `duckdb`', async () => {
798
+ await run(shell, 'wbt install duckdb');
799
+ const res = await run(shell, 'duckdb -c "SELECT 100 AS total"');
800
+ expect(res.exitCode).toBe(0);
801
+ expect(res.output.join('\n')).toContain('100');
802
+ });
803
+
804
+ it('compiles Graphviz DOT files to SVG with `dot` (`graphviz` package)', async () => {
805
+ await run(shell, 'wbt install graphviz');
806
+ const res = await run(shell, 'dot -Tsvg /home/graph.dot -o /home/graph.svg');
807
+ expect(res.exitCode).toBe(0);
808
+ expect(shell.context.fs.exists('/home/graph.svg')).toBe(true);
809
+ expect(shell.context.fs.getFileByPath('/home/graph.svg')).toContain('<svg');
810
+ });
811
+
812
+ it('transcodes media files in the brsh filesystem with `ffmpeg`', async () => {
813
+ await run(shell, 'wbt install ffmpeg');
814
+ const res = await run(shell, 'ffmpeg -i /home/input.mp4 /home/output.webm');
815
+ expect(res.exitCode).toBe(0);
816
+ expect(shell.context.fs.exists('/home/output.webm')).toBe(true);
817
+ });
818
+
819
+ it('wraps arbitrary Emscripten / NPM packages at runtime without a custom adapter (`wbt install npm:<pkg>`)', async () => {
820
+ const installRes = await run(shell, 'wbt install npm:cowsay-wasm');
821
+ expect(installRes.exitCode).toBe(0);
822
+
823
+ const runRes = await run(shell, 'cowsay-wasm Hello Generic WASM');
824
+ expect(runRes.exitCode).toBe(0);
825
+ expect(runRes.output.join('\n')).toContain('< Hello Generic WASM >');
826
+ });
827
+
828
+ it('installs and runs a custom .wasm binary from a URL (`wbt install <name> <url>`) and supports mixing multiple packages with `<name> <url>` pairs', async () => {
829
+ // 1. Single `<name> <url>`
830
+ const installRes = await run(shell, 'wbt install mywasm https://example.com/hello.wasm');
831
+ expect(installRes.exitCode).toBe(0);
832
+ expect(installRes.output.join('\n')).toContain('Setting up mywasm');
833
+
834
+ const execRes = await run(shell, 'mywasm');
835
+ expect(execRes.exitCode).toBe(0);
836
+
837
+ // 2. Mixed multiple registry packages AND `<name> <url>` in one command
838
+ const mixedRes = await run(shell, 'wbt install jq otherwasm https://example.com/hello.wasm python3');
839
+ expect(mixedRes.exitCode).toBe(0);
840
+ const mixedOut = mixedRes.output.join('\n');
841
+ expect(mixedOut).toContain('Setting up jq');
842
+ expect(mixedOut).toContain('Setting up otherwasm');
843
+ expect(mixedOut).toContain('Setting up python3');
844
+
845
+ expect((await run(shell, 'otherwasm')).exitCode).toBe(0);
846
+ expect((await run(shell, 'python3 -c "2 + 2"')).output).toContain('4');
847
+ });
848
+
849
+ it('supports `wbt run <pkg> [args...]` without permanently installing the binary', async () => {
850
+ const runRes = await run(shell, 'wbt run quickjs -e "21 * 2"');
851
+ expect(runRes.exitCode).toBe(0);
852
+ expect(runRes.output).toContain('42');
853
+
854
+ const checkRes = await run(shell, 'which qjs');
855
+ expect(checkRes.exitCode).toBeGreaterThan(0);
856
+ });
857
+ });
858
+
859
+ describe('WBT interactive REPL mode', () => {
860
+ let shell;
861
+
862
+ beforeEach(async () => {
863
+ shell = await createShell({ filesystem: { home: {} } });
864
+ shell.context.setCommand(createTestWbt());
865
+ await run(shell, 'wbt install sqlite3');
866
+ });
867
+
868
+ it('enters interactive REPL mode when `sqlite3` is invoked with no query and evaluates keystrokes until .exit', async () => {
869
+ let interactiveFired = false;
870
+ shell.once('interactive', () => { interactiveFired = true; });
871
+
872
+ const screens = [];
873
+ const onOut = (line) => screens.push(line);
874
+ shell.on('stdOut', onOut);
875
+
876
+ const cmdPromise = shell.onCommand('sqlite3 /home/interactive.db');
877
+
878
+ await new Promise(r => setTimeout(r, 20));
879
+ expect(interactiveFired).toBe(true);
880
+
881
+ const query = 'CREATE TABLE t (x INT); INSERT INTO t VALUES (7); SELECT * FROM t;';
882
+ for (const ch of query) {
883
+ shell.onInput(ch);
884
+ }
885
+ shell.onInput('Enter');
886
+
887
+ await new Promise(r => setTimeout(r, 20));
888
+ expect(screens[screens.length - 1]).toContain('7');
889
+
890
+ for (const ch of '.exit') {
891
+ shell.onInput(ch);
892
+ }
893
+ shell.onInput('Enter');
894
+
895
+ await cmdPromise;
896
+ shell.removeListener('stdOut', onOut);
897
+
898
+ expect(shell.context.fs.exists('/home/interactive.db')).toBe(true);
899
+ });
900
+ });
901
+
902
+ describe('Direct .wasm binary in /bin (without wbt) and standardized --help across all WASM bins', () => {
903
+ it('executes a raw WASI .wasm binary placed directly in /bin by bare command name and supports --help', async () => {
904
+ const b64 = Buffer.from(MINIMAL_WASM_BYTES).toString('base64');
905
+ const shell = await createShell({
906
+ filesystem: {
907
+ bin: {
908
+ myjq: `data:application/wasm;base64,${b64}`
909
+ }
910
+ },
911
+ permissions: {
912
+ '/bin/myjq': 0o755
913
+ }
914
+ });
915
+
916
+ // Bare command lookup in PATH ('myjq') automatically wraps the .wasm binary in WasmCommand!
917
+ const { exitCode } = await run(shell, 'myjq');
918
+ expect(exitCode).toBe(0);
919
+
920
+ const helpRes = await run(shell, 'myjq --help');
921
+ expect(helpRes.exitCode).toBe(0);
922
+ const helpText = helpRes.output.join('\n');
923
+ expect(helpText).toContain('Usage: myjq [options] [args...]');
924
+ expect(helpText).toContain('-h, --help');
925
+ expect(helpText).toContain('-V, --version');
926
+ });
927
+
928
+ it('passes through native --help when a WASM binary implements it and falls back to standardized --help otherwise', async () => {
929
+ const shell = await createShell({ filesystem: { home: {} } });
930
+ shell.context.setCommand(createTestWbt());
931
+ await run(shell, 'wbt install jq python3 npm:cowsay-wasm');
932
+ await run(shell, 'wbt install mywasm https://example.com/hello.wasm');
933
+
934
+ // 1. Binaries without their own `--help` get the standardized fallback `--help` screen
935
+ for (const bin of ['python3', 'cowsay-wasm', 'mywasm']) {
936
+ const { output, exitCode } = await run(shell, `${bin} --help`);
937
+ expect(exitCode).toBe(0);
938
+ const text = output.join('\n');
939
+ expect(text).toContain('wasm) —');
940
+ expect(text).toContain('Usage:');
941
+ expect(text).toContain('Options:');
942
+ expect(text).toContain('-h, --help');
943
+ expect(text).toContain('-V, --version');
944
+ }
945
+
946
+ // 2. `jq` implements its own `--help` in main(args, io) -> passed through verbatim!
947
+ const jqRes = await run(shell, 'jq --help');
948
+ expect(jqRes.exitCode).toBe(0);
949
+ const jqHelp = jqRes.output.join('\n');
950
+ expect(jqHelp).toContain('jq - commandline JSON processor [version 1.7.1]');
951
+ expect(jqHelp).toContain('Usage: jq [options] <jq filter> [file...]');
952
+ expect(jqHelp).toContain('-r, --raw-output');
953
+ expect(jqHelp).toContain('-c, --compact-output');
954
+
955
+ // 3. `mywasm --help` introspects the compiled .wasm binary exports at runtime
956
+ const mywasmHelp = (await run(shell, 'mywasm --help')).output.join('\n');
957
+ expect(mywasmHelp).toContain('WASM Exports: _start');
958
+ });
959
+
960
+ it('introspects embedded Usage and CLI flags from a .wasm binary data section at runtime when the binary does not print help', async () => {
961
+ // Append a custom section / data payload containing embedded C strings (`Usage: ...` and `--flag` lines)
962
+ const embeddedStrings = new TextEncoder().encode(
963
+ '\0Usage: customtool [-v] <input>\n' +
964
+ ' -f, --format <fmt> Output format\n' +
965
+ ' --strict Strict mode\0'
966
+ );
967
+ // Custom section (id 0) with name "rodata" + embedded strings (payloadLen < 128 so 1-byte LEB128)
968
+ const secName = new TextEncoder().encode('rodata');
969
+ const payloadLen = 1 + secName.length + embeddedStrings.length;
970
+ const wasmWithData = new Uint8Array(MINIMAL_WASM_BYTES.length + 3 + secName.length + embeddedStrings.length);
971
+ wasmWithData.set(MINIMAL_WASM_BYTES, 0);
972
+ let offset = MINIMAL_WASM_BYTES.length;
973
+ wasmWithData[offset++] = 0x00; // custom section id
974
+ wasmWithData[offset++] = payloadLen;
975
+ wasmWithData[offset++] = secName.length;
976
+ wasmWithData.set(secName, offset);
977
+ offset += secName.length;
978
+ wasmWithData.set(embeddedStrings, offset);
979
+
980
+ const b64 = Buffer.from(wasmWithData).toString('base64');
981
+ const shell = await createShell({
982
+ filesystem: {
983
+ bin: {
984
+ customtool: `data:application/wasm;base64,${b64}`
985
+ }
986
+ },
987
+ permissions: {
988
+ '/bin/customtool': 0o755
989
+ }
990
+ });
991
+
992
+ const helpRes = await run(shell, 'customtool --help');
993
+ expect(helpRes.exitCode).toBe(0);
994
+ const helpText = helpRes.output.join('\n');
995
+ expect(helpText).toContain('Usage: customtool [-v] <input>');
996
+ expect(helpText).toContain('-f, --format <fmt> Output format');
997
+ expect(helpText).toContain('--strict Strict mode');
998
+ expect(helpText).toContain('WASM Exports: _start');
999
+ });
1000
+ });
1001
+
1002
+ describe('WBT Wllama v3 WASM & WebGPU package (`wllama`, `llama`, `llama-cli`)', () => {
1003
+ let shell;
1004
+
1005
+ beforeEach(async () => {
1006
+ wllamaInstances.clear();
1007
+ shell = await createShell({
1008
+ filesystem: {
1009
+ home: {
1010
+ 'tinyllama.gguf': 'GGUF_MODEL_BINARY_BYTES',
1011
+ 'prompt.txt': 'Explain WebGPU in one sentence.'
1012
+ }
1013
+ }
1014
+ });
1015
+ shell.context.setCommand(createTestWbt());
1016
+ await run(shell, 'wbt install wllama');
1017
+ });
1018
+
1019
+ it('registers wllama, llama, and llama-cli binaries and supports --help / --version', async () => {
1020
+ for (const bin of ['wllama', 'llama', 'llama-cli']) {
1021
+ const whichRes = await run(shell, `which ${bin}`);
1022
+ expect(whichRes.exitCode).toBe(0);
1023
+ expect(whichRes.output.join('')).toContain(`/bin/${bin}`);
1024
+ }
1025
+
1026
+ const helpRes = await run(shell, 'wllama --help');
1027
+ expect(helpRes.exitCode).toBe(0);
1028
+ expect(helpRes.output.join('\n')).toContain('WebGPU');
1029
+ expect(helpRes.output.join('\n')).toContain('--n-gpu-layers');
1030
+
1031
+ const runHelpRes = await run(shell, 'wbt run wllama --help');
1032
+ expect(runHelpRes.exitCode).toBe(0);
1033
+ expect(runHelpRes.output.join('\n')).toContain('Usage: wllama');
1034
+ });
1035
+
1036
+ it('runs one-shot chat completions from a local filesystem .gguf model, piped stdin, or -f file with WebGPU or --no-gpu', async () => {
1037
+ const res1 = await run(
1038
+ shell,
1039
+ 'wllama -m /home/tinyllama.gguf -s "Be concise" -p "Hello Wllama 3!"'
1040
+ );
1041
+ expect(res1.exitCode).toBe(0);
1042
+ expect(res1.output.join('\n')).toContain('[sys:Be concise] Reply(WebGPU,turns=1): Hello Wllama 3!');
1043
+
1044
+ // CPU fallback (--no-gpu / -ngl 0)
1045
+ const resCpu = await run(
1046
+ shell,
1047
+ 'llama -m /home/tinyllama.gguf --no-gpu -p "CPU test"'
1048
+ );
1049
+ expect(resCpu.exitCode).toBe(0);
1050
+ expect(resCpu.output.join('\n')).toContain('Reply(CPU,turns=1): CPU test');
1051
+
1052
+ // Piped stdin
1053
+ const piped = await run(
1054
+ shell,
1055
+ 'echo "Piped prompt" | llama-cli -m /home/tinyllama.gguf'
1056
+ );
1057
+ expect(piped.exitCode).toBe(0);
1058
+ expect(piped.output.join('\n')).toContain('Reply(WebGPU,turns=1): Piped prompt');
1059
+
1060
+ // File prompt (-f) and raw completion (--raw)
1061
+ const rawRes = await run(
1062
+ shell,
1063
+ 'wllama -m /home/tinyllama.gguf --raw -f /home/prompt.txt'
1064
+ );
1065
+ expect(rawRes.exitCode).toBe(0);
1066
+ expect(rawRes.output.join('\n')).toContain('Explain WebGPU in one sentence. [completed]');
1067
+ });
1068
+
1069
+ it('supports Hugging Face model loading (--hf / hf:), embeddings (wllama embed), info, and bench', async () => {
1070
+ const hfRes = await run(
1071
+ shell,
1072
+ 'wllama --hf Qwen/Qwen2.5-0.5B-Instruct-GGUF --quant Q4_K_M -p "From HF"'
1073
+ );
1074
+ expect(hfRes.exitCode).toBe(0);
1075
+ expect(hfRes.output.join('\n')).toContain('Reply(WebGPU,turns=1): From HF');
1076
+
1077
+ const embRes = await run(
1078
+ shell,
1079
+ 'wllama embed -m /home/tinyllama.gguf -p "hello"'
1080
+ );
1081
+ expect(embRes.exitCode).toBe(0);
1082
+ expect(JSON.parse(embRes.output.join(''))).toEqual([5, 0.25, 0.5, 0.75]);
1083
+
1084
+ const infoRes = await run(shell, 'wllama info -m /home/tinyllama.gguf');
1085
+ expect(infoRes.exitCode).toBe(0);
1086
+ expect(infoRes.output.join('\n')).toContain('WebGPU: enabled');
1087
+ expect(infoRes.output.join('\n')).toContain('layers=22');
1088
+
1089
+ const benchRes = await run(shell, 'wllama bench');
1090
+ expect(benchRes.exitCode).toBe(0);
1091
+ expect(benchRes.output.join('\n')).toContain('PASSED');
1092
+ });
1093
+
1094
+ it('enters interactive multi-turn chat REPL mode when `wllama` is invoked with no prompt', async () => {
1095
+ let interactiveFired = false;
1096
+ shell.once('interactive', () => { interactiveFired = true; });
1097
+
1098
+ const screens = [];
1099
+ const onOut = (line) => screens.push(line);
1100
+ shell.on('stdOut', onOut);
1101
+
1102
+ const cmdPromise = shell.onCommand('wllama -m /home/tinyllama.gguf');
1103
+
1104
+ await new Promise(r => setTimeout(r, 20));
1105
+ expect(interactiveFired).toBe(true);
1106
+
1107
+ for (const ch of 'First question') {
1108
+ shell.onInput(ch);
1109
+ }
1110
+ shell.onInput('Enter');
1111
+ await new Promise(r => setTimeout(r, 20));
1112
+ expect(screens[screens.length - 1]).toContain('Reply(WebGPU,turns=1): First question');
1113
+
1114
+ for (const ch of 'Second question') {
1115
+ shell.onInput(ch);
1116
+ }
1117
+ shell.onInput('Enter');
1118
+ await new Promise(r => setTimeout(r, 20));
1119
+ expect(screens[screens.length - 1]).toContain('Reply(WebGPU,turns=2): Second question');
1120
+
1121
+ shell.onInput('^D');
1122
+ await cmdPromise;
1123
+ shell.removeListener('stdOut', onOut);
1124
+ });
1125
+
1126
+ it('persists pulled remote models to the brsh filesystem via `--persist`, `-o`, and `wllama pull`', async () => {
1127
+ // 1. Run with `--persist` (saves to default /var/cache/wllama/<filename>.gguf)
1128
+ const persistRes = await run(
1129
+ shell,
1130
+ 'wllama --hf Qwen/Qwen2.5-0.5B-Instruct-GGUF --quant Q4_K_M --persist -p "Persist test"'
1131
+ );
1132
+ expect(persistRes.exitCode).toBe(0);
1133
+ expect(persistRes.output.join('\n')).toContain('Reply(WebGPU,turns=1): Persist test');
1134
+ expect(shell.context.fs.exists('/var/cache/wllama/Qwen2.5-0.5B-Instruct-GGUF-Q4_K_M.gguf')).toBe(true);
1135
+
1136
+ // 2. Run with `-o` / `--output` to persist to a custom path
1137
+ const outRes = await run(
1138
+ shell,
1139
+ 'wllama -m https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K.gguf -o /home/saved-stories.gguf -p "Saved custom"'
1140
+ );
1141
+ expect(outRes.exitCode).toBe(0);
1142
+ expect(shell.context.fs.exists('/home/saved-stories.gguf')).toBe(true);
1143
+
1144
+ // 3. Dedicated `wllama pull` subcommand streams download progress bars
1145
+ const pullRes = await run(
1146
+ shell,
1147
+ 'wllama pull hf:bartowski/SmolLM2-135M-Instruct-GGUF:Q4_K_M -o /home/smol.gguf'
1148
+ );
1149
+ expect(pullRes.exitCode).toBe(0);
1150
+ expect(pullRes.output.some(l => l.startsWith('\rPulling') && l.includes('50%'))).toBe(true);
1151
+ expect(pullRes.output.some(l => l.startsWith('\rPulling') && l.includes('100%'))).toBe(true);
1152
+ expect(pullRes.output.join('\n')).toContain('Persisted model');
1153
+ expect(pullRes.output.join('\n')).toContain('/home/smol.gguf');
1154
+ expect(shell.context.fs.exists('/home/smol.gguf')).toBe(true);
1155
+
1156
+ // 4. `-q` / `--no-progress` suppresses the progress bar
1157
+ const quietRes = await run(
1158
+ shell,
1159
+ 'wllama pull hf:ggml-org/models/tinyllamas/stories15M-q4_0.gguf -q -o /home/quiet.gguf'
1160
+ );
1161
+ expect(quietRes.exitCode).toBe(0);
1162
+ expect(quietRes.output.some(l => l.startsWith('\rPulling'))).toBe(false);
1163
+ expect(shell.context.fs.exists('/home/quiet.gguf')).toBe(true);
1164
+
1165
+ // 5. Verify `wllama models` lists persisted models in `/var/cache/wllama`
1166
+ const modelsRes = await run(shell, 'wllama models');
1167
+ expect(modelsRes.exitCode).toBe(0);
1168
+ expect(modelsRes.output.join('\n')).toContain('/var/cache/wllama/Qwen2.5-0.5B-Instruct-GGUF-Q4_K_M.gguf');
1169
+ expect(modelsRes.output.join('\n')).toContain('persisted (fs)');
1170
+ });
1171
+ });
1172
+
1173
+
1174
+
1175
+