brsh 3.2.0 → 3.3.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/CHANGELOG.md +7 -0
- package/POSIX-CHECKLIST.md +3 -0
- package/dist/shell.es.js +279 -43
- package/dist/shell.es.js.map +1 -1
- package/dist/shell.min.js +8 -8
- package/dist/shell.min.js.map +1 -1
- package/dist/wbt.es.js +275 -167
- package/dist/wbt.es.js.map +1 -1
- package/dist/wbt.min.js +8 -3
- package/dist/wbt.min.js.map +1 -1
- package/index.js +285 -57
- package/lib/ReplCommand.js +21 -1
- package/lib/ScriptCommand.js +101 -0
- package/lib/wbt/packages/wllama.js +240 -15
- package/package.json +1 -1
- package/test/scripts.test.js +80 -0
- package/test/shell.test.js +115 -0
- package/test/wbt.test.js +92 -8
|
@@ -230,9 +230,14 @@ async function getOrInitWllamaInstance(opts = {}) {
|
|
|
230
230
|
wbtConfig = {},
|
|
231
231
|
loadModel = true,
|
|
232
232
|
persist = false,
|
|
233
|
-
persistPath = null
|
|
233
|
+
persistPath = null,
|
|
234
|
+
onStatus = null
|
|
234
235
|
} = opts;
|
|
235
236
|
|
|
237
|
+
if (typeof onStatus === 'function') {
|
|
238
|
+
onStatus('Initializing WASM runtime...');
|
|
239
|
+
}
|
|
240
|
+
|
|
236
241
|
const mod = await loadModule('@wllama/wllama', pkgMeta.cdnUrl, wbtConfig.moduleLoader);
|
|
237
242
|
const Wllama = mod.Wllama || mod.default || mod;
|
|
238
243
|
const LoggerWithoutDebug = mod.LoggerWithoutDebug || undefined;
|
|
@@ -290,6 +295,9 @@ async function getOrInitWllamaInstance(opts = {}) {
|
|
|
290
295
|
if (wllamaInstances.has(cacheKey)) {
|
|
291
296
|
const existing = wllamaInstances.get(cacheKey);
|
|
292
297
|
if (typeof existing.isModelLoaded !== 'function' || existing.isModelLoaded()) {
|
|
298
|
+
if (typeof onStatus === 'function') {
|
|
299
|
+
onStatus('Loaded model from cache.');
|
|
300
|
+
}
|
|
293
301
|
let persisted = null;
|
|
294
302
|
if ((persist || persistPath) && fs && resolvedPersistPath) {
|
|
295
303
|
if (fs.exists(resolvedPersistPath)) {
|
|
@@ -322,6 +330,9 @@ async function getOrInitWllamaInstance(opts = {}) {
|
|
|
322
330
|
if (candidatePath) {
|
|
323
331
|
const cachedBytes = readBytesFromFs(fs, candidatePath);
|
|
324
332
|
if (cachedBytes && cachedBytes.byteLength > 0) {
|
|
333
|
+
if (typeof onStatus === 'function') {
|
|
334
|
+
onStatus(`Loading model from ${candidatePath}...`);
|
|
335
|
+
}
|
|
325
336
|
const cachedBlob = new Blob([cachedBytes], { type: 'application/octet-stream' });
|
|
326
337
|
cachedBlob.name = candidatePath.split('/').pop() || 'model.gguf';
|
|
327
338
|
await wllama.loadModel([cachedBlob], loadParams);
|
|
@@ -335,6 +346,9 @@ async function getOrInitWllamaInstance(opts = {}) {
|
|
|
335
346
|
writeBytesToFs(fs, resolvedPersistPath, loadedFromPersistedFs.bytes, 'application/octet-stream');
|
|
336
347
|
}
|
|
337
348
|
} else if (modelSpec.kind === 'fs') {
|
|
349
|
+
if (typeof onStatus === 'function') {
|
|
350
|
+
onStatus(`Loading model from ${modelSpec.path}...`);
|
|
351
|
+
}
|
|
338
352
|
const bytes = readBytesFromFs(fs, modelSpec.path);
|
|
339
353
|
if (!bytes) {
|
|
340
354
|
throw new Error(`${modelSpec.path}: No such file or directory`);
|
|
@@ -353,11 +367,17 @@ async function getOrInitWllamaInstance(opts = {}) {
|
|
|
353
367
|
blobs.push(mmBlob);
|
|
354
368
|
}
|
|
355
369
|
|
|
370
|
+
if (typeof onStatus === 'function') {
|
|
371
|
+
onStatus(`Loading model ${modelBlob.name} into memory...`);
|
|
372
|
+
}
|
|
356
373
|
await wllama.loadModel(blobs, loadParams);
|
|
357
374
|
if (resolvedPersistPath && resolvedPersistPath !== modelSpec.path) {
|
|
358
375
|
writeBytesToFs(fs, resolvedPersistPath, bytes, 'application/octet-stream');
|
|
359
376
|
}
|
|
360
377
|
} else if (modelSpec.kind === 'hf-quant' && typeof wllama.loadModelFromHF === 'function') {
|
|
378
|
+
if (typeof onStatus === 'function') {
|
|
379
|
+
onStatus(`Pulling model ${modelSpec.repo} (${modelSpec.quant})...`);
|
|
380
|
+
}
|
|
361
381
|
try {
|
|
362
382
|
await wllama.loadModelFromHF(
|
|
363
383
|
{
|
|
@@ -369,13 +389,22 @@ async function getOrInitWllamaInstance(opts = {}) {
|
|
|
369
389
|
} catch (err) {
|
|
370
390
|
if (typeof mod.getHFModelSource === 'function') {
|
|
371
391
|
const src = await mod.getHFModelSource({ repo: modelSpec.repo, quant: modelSpec.quant });
|
|
392
|
+
if (typeof onStatus === 'function') {
|
|
393
|
+
onStatus(`Pulling model ${modelSpec.repo} (${modelSpec.quant})...`);
|
|
394
|
+
}
|
|
372
395
|
downloadedBlob = await fetchUrlAsGgufBlob(src.url || src, loadParams.progressCallback);
|
|
396
|
+
if (typeof onStatus === 'function') {
|
|
397
|
+
onStatus(`Loading model into memory...`);
|
|
398
|
+
}
|
|
373
399
|
await wllama.loadModel([downloadedBlob], loadParams);
|
|
374
400
|
} else {
|
|
375
401
|
throw err;
|
|
376
402
|
}
|
|
377
403
|
}
|
|
378
404
|
} else if (modelSpec.kind === 'hf-file' && typeof wllama.loadModelFromHF === 'function') {
|
|
405
|
+
if (typeof onStatus === 'function') {
|
|
406
|
+
onStatus(`Pulling model ${modelSpec.repo}/${modelSpec.file}...`);
|
|
407
|
+
}
|
|
379
408
|
try {
|
|
380
409
|
await wllama.loadModelFromHF(
|
|
381
410
|
{
|
|
@@ -386,10 +415,16 @@ async function getOrInitWllamaInstance(opts = {}) {
|
|
|
386
415
|
);
|
|
387
416
|
} catch {
|
|
388
417
|
downloadedBlob = await fetchUrlAsGgufBlob(modelSpec.url, loadParams.progressCallback);
|
|
418
|
+
if (typeof onStatus === 'function') {
|
|
419
|
+
onStatus(`Loading model into memory...`);
|
|
420
|
+
}
|
|
389
421
|
await wllama.loadModel([downloadedBlob], loadParams);
|
|
390
422
|
}
|
|
391
423
|
} else {
|
|
392
424
|
const targetUrl = modelSpec.url || DEFAULT_MODEL_URL;
|
|
425
|
+
if (typeof onStatus === 'function') {
|
|
426
|
+
onStatus(`Pulling model from ${targetUrl.split('/').pop().split('?')[0] || targetUrl}...`);
|
|
427
|
+
}
|
|
393
428
|
try {
|
|
394
429
|
if (mmprojSpec && /^https?:\/\//i.test(mmprojSpec)) {
|
|
395
430
|
await wllama.loadModelFromUrl({ url: targetUrl, mmprojUrl: mmprojSpec }, loadParams);
|
|
@@ -398,10 +433,17 @@ async function getOrInitWllamaInstance(opts = {}) {
|
|
|
398
433
|
}
|
|
399
434
|
} catch {
|
|
400
435
|
downloadedBlob = await fetchUrlAsGgufBlob(targetUrl, loadParams.progressCallback);
|
|
436
|
+
if (typeof onStatus === 'function') {
|
|
437
|
+
onStatus(`Loading model into memory...`);
|
|
438
|
+
}
|
|
401
439
|
await wllama.loadModel([downloadedBlob], loadParams);
|
|
402
440
|
}
|
|
403
441
|
}
|
|
404
442
|
|
|
443
|
+
if (typeof onStatus === 'function') {
|
|
444
|
+
onStatus('Model loaded.');
|
|
445
|
+
}
|
|
446
|
+
|
|
405
447
|
let persisted = null;
|
|
406
448
|
if (loadedFromPersistedFs) {
|
|
407
449
|
persisted = {
|
|
@@ -484,6 +526,7 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
484
526
|
let embeddings = false;
|
|
485
527
|
let rawCompletion = false;
|
|
486
528
|
let jsonOutput = false;
|
|
529
|
+
let stream = true;
|
|
487
530
|
let jinja = true;
|
|
488
531
|
let persist = false;
|
|
489
532
|
let persistPath = null;
|
|
@@ -577,6 +620,10 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
577
620
|
if (!subcommand) subcommand = 'embed';
|
|
578
621
|
} else if (a === '--raw' || a === '--completion') {
|
|
579
622
|
rawCompletion = true;
|
|
623
|
+
} else if (a === '--stream') {
|
|
624
|
+
stream = true;
|
|
625
|
+
} else if (a === '--no-stream') {
|
|
626
|
+
stream = false;
|
|
580
627
|
} else if (a === '--json') {
|
|
581
628
|
jsonOutput = true;
|
|
582
629
|
} else if (a === '--no-jinja') {
|
|
@@ -642,6 +689,7 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
642
689
|
embeddings,
|
|
643
690
|
rawCompletion,
|
|
644
691
|
jsonOutput,
|
|
692
|
+
stream,
|
|
645
693
|
persist,
|
|
646
694
|
persistPath,
|
|
647
695
|
showProgress,
|
|
@@ -691,6 +739,21 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
691
739
|
return lines;
|
|
692
740
|
}
|
|
693
741
|
|
|
742
|
+
_renderStatus(msg) {
|
|
743
|
+
if (!this._parsed.showProgress || this._parsed.jsonOutput) return;
|
|
744
|
+
this.emit('wllama:status', msg);
|
|
745
|
+
if (this.stderr && typeof this.stderr.write === 'function') {
|
|
746
|
+
this.stderr.write(`\r\x1b[K${msg}`);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
_clearStatus() {
|
|
751
|
+
if (!this._parsed.showProgress || this._parsed.jsonOutput) return;
|
|
752
|
+
if (this.stderr && typeof this.stderr.write === 'function') {
|
|
753
|
+
this.stderr.write('\r\x1b[K');
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
|
|
694
757
|
_attachProgressCallback() {
|
|
695
758
|
if (!this._parsed.showProgress || this._parsed.modelSpec.kind === 'fs') return;
|
|
696
759
|
const label = this._parsed.model || this._parsed.modelSpec.file || this._parsed.modelSpec.repo || this._parsed.modelSpec.url || 'model.gguf';
|
|
@@ -700,8 +763,16 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
700
763
|
const isDone = total > 0 && loaded >= total;
|
|
701
764
|
if (lastEmit === 0 || isDone || now - lastEmit >= 40) {
|
|
702
765
|
lastEmit = now;
|
|
703
|
-
|
|
704
|
-
this.
|
|
766
|
+
const progressStr = formatDownloadProgress(label, loaded, total);
|
|
767
|
+
if (this.interactive) {
|
|
768
|
+
this._replStatus = progressStr.replace(/^\r/, '');
|
|
769
|
+
this._renderRepl();
|
|
770
|
+
} else if (this._parsed.subcommand === 'pull') {
|
|
771
|
+
this.stdOut = progressStr;
|
|
772
|
+
this.flush();
|
|
773
|
+
} else {
|
|
774
|
+
this._renderStatus(progressStr.replace(/^\r/, ''));
|
|
775
|
+
}
|
|
705
776
|
}
|
|
706
777
|
};
|
|
707
778
|
}
|
|
@@ -711,6 +782,15 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
711
782
|
this._attachProgressCallback();
|
|
712
783
|
}
|
|
713
784
|
|
|
785
|
+
const onStatus = (msg) => {
|
|
786
|
+
if (this.interactive) {
|
|
787
|
+
this._replStatus = msg;
|
|
788
|
+
this._renderRepl();
|
|
789
|
+
} else {
|
|
790
|
+
this._renderStatus(msg);
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
|
|
714
794
|
const { wllama, Wllama, persisted } = await getOrInitWllamaInstance({
|
|
715
795
|
modelSpec: this._parsed.modelSpec,
|
|
716
796
|
mmprojSpec: this._parsed.mmproj,
|
|
@@ -720,11 +800,15 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
720
800
|
wbtConfig,
|
|
721
801
|
loadModel,
|
|
722
802
|
persist: this._parsed.persist,
|
|
723
|
-
persistPath: this._parsed.persistPath
|
|
803
|
+
persistPath: this._parsed.persistPath,
|
|
804
|
+
onStatus
|
|
724
805
|
});
|
|
725
806
|
this._wllama = wllama;
|
|
726
807
|
this._WllamaClass = Wllama;
|
|
727
808
|
this._persisted = persisted;
|
|
809
|
+
if (!this.interactive) {
|
|
810
|
+
this._clearStatus();
|
|
811
|
+
}
|
|
728
812
|
}
|
|
729
813
|
|
|
730
814
|
async initRepl() {
|
|
@@ -779,40 +863,133 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
779
863
|
|
|
780
864
|
try {
|
|
781
865
|
this._messages.push({ role: 'user', content: trimmed });
|
|
782
|
-
|
|
866
|
+
let streamedAny = false;
|
|
867
|
+
const reply = await this._runChatTurn(this._messages, (delta) => {
|
|
868
|
+
streamedAny = true;
|
|
869
|
+
if (typeof this.streamReplChunk === 'function') {
|
|
870
|
+
this.streamReplChunk(delta);
|
|
871
|
+
}
|
|
872
|
+
});
|
|
783
873
|
this._messages.push({ role: 'assistant', content: reply });
|
|
874
|
+
if (streamedAny) {
|
|
875
|
+
return { streamed: true };
|
|
876
|
+
}
|
|
784
877
|
return { output: reply.split(/\r?\n/) };
|
|
785
878
|
} catch (err) {
|
|
786
879
|
return { error: `wllama: ${err.message || err}` };
|
|
787
880
|
}
|
|
788
881
|
}
|
|
789
882
|
|
|
790
|
-
async _runChatTurn(messages) {
|
|
883
|
+
async _runChatTurn(messages, onToken = null) {
|
|
884
|
+
const shouldStream = Boolean(this._parsed.stream && !this._parsed.jsonOutput);
|
|
791
885
|
const opts = {
|
|
792
886
|
messages,
|
|
793
887
|
max_tokens: this._parsed.maxTokens,
|
|
794
888
|
temperature: this._parsed.temperature,
|
|
795
|
-
stream:
|
|
889
|
+
stream: shouldStream
|
|
796
890
|
};
|
|
797
891
|
if (this._parsed.topK !== undefined) opts.top_k = this._parsed.topK;
|
|
798
892
|
if (this._parsed.topP !== undefined) opts.top_p = this._parsed.topP;
|
|
799
893
|
|
|
894
|
+
if (this.interactive) {
|
|
895
|
+
this._replStatus = 'Running inference...';
|
|
896
|
+
this._renderRepl();
|
|
897
|
+
} else {
|
|
898
|
+
this._renderStatus('Running inference...');
|
|
899
|
+
}
|
|
900
|
+
|
|
800
901
|
if (typeof this._wllama.createChatCompletion === 'function') {
|
|
801
902
|
const res = await this._wllama.createChatCompletion(opts);
|
|
903
|
+
|
|
904
|
+
if (res && typeof res[Symbol.asyncIterator] === 'function') {
|
|
905
|
+
let fullText = '';
|
|
906
|
+
let firstToken = false;
|
|
907
|
+
for await (const chunk of res) {
|
|
908
|
+
const delta = chunk?.choices?.[0]?.delta?.content ?? chunk?.choices?.[0]?.text ?? '';
|
|
909
|
+
if (delta) {
|
|
910
|
+
if (!firstToken) {
|
|
911
|
+
firstToken = true;
|
|
912
|
+
if (this.interactive) {
|
|
913
|
+
this._replStatus = 'Streaming tokens...';
|
|
914
|
+
this._renderRepl();
|
|
915
|
+
} else {
|
|
916
|
+
this._clearStatus();
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
fullText += delta;
|
|
920
|
+
if (typeof onToken === 'function') {
|
|
921
|
+
onToken(delta);
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
if (!this.interactive) {
|
|
926
|
+
this._clearStatus();
|
|
927
|
+
}
|
|
928
|
+
return fullText;
|
|
929
|
+
}
|
|
930
|
+
|
|
802
931
|
if (this._parsed.jsonOutput) {
|
|
932
|
+
if (!this.interactive) this._clearStatus();
|
|
803
933
|
return JSON.stringify(res);
|
|
804
934
|
}
|
|
805
|
-
|
|
935
|
+
const text = extractCompletionText(res);
|
|
936
|
+
if (!this.interactive) {
|
|
937
|
+
this._clearStatus();
|
|
938
|
+
}
|
|
939
|
+
if (typeof onToken === 'function' && text) {
|
|
940
|
+
onToken(text);
|
|
941
|
+
}
|
|
942
|
+
return text;
|
|
806
943
|
}
|
|
944
|
+
|
|
807
945
|
// Fallback if mock/custom instance only implements createCompletion
|
|
808
946
|
const lastMsg = messages[messages.length - 1]?.content || '';
|
|
809
|
-
const
|
|
947
|
+
const compOpts = {
|
|
810
948
|
prompt: lastMsg,
|
|
811
949
|
max_tokens: this._parsed.maxTokens,
|
|
812
950
|
temperature: this._parsed.temperature,
|
|
813
|
-
stream:
|
|
814
|
-
}
|
|
815
|
-
|
|
951
|
+
stream: shouldStream
|
|
952
|
+
};
|
|
953
|
+
if (this._parsed.topK !== undefined) compOpts.top_k = this._parsed.topK;
|
|
954
|
+
if (this._parsed.topP !== undefined) compOpts.top_p = this._parsed.topP;
|
|
955
|
+
|
|
956
|
+
const res = await this._wllama.createCompletion(compOpts);
|
|
957
|
+
if (res && typeof res[Symbol.asyncIterator] === 'function') {
|
|
958
|
+
let fullText = '';
|
|
959
|
+
let firstToken = false;
|
|
960
|
+
for await (const chunk of res) {
|
|
961
|
+
const delta = chunk?.choices?.[0]?.text ?? chunk?.choices?.[0]?.delta?.content ?? '';
|
|
962
|
+
if (delta) {
|
|
963
|
+
if (!firstToken) {
|
|
964
|
+
firstToken = true;
|
|
965
|
+
if (this.interactive) {
|
|
966
|
+
this._replStatus = 'Streaming tokens...';
|
|
967
|
+
this._renderRepl();
|
|
968
|
+
} else {
|
|
969
|
+
this._clearStatus();
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
fullText += delta;
|
|
973
|
+
if (typeof onToken === 'function') {
|
|
974
|
+
onToken(delta);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
if (!this.interactive) {
|
|
979
|
+
this._clearStatus();
|
|
980
|
+
}
|
|
981
|
+
return fullText;
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
if (!this.interactive) {
|
|
985
|
+
this._clearStatus();
|
|
986
|
+
}
|
|
987
|
+
if (this._parsed.jsonOutput) return JSON.stringify(res);
|
|
988
|
+
const text = extractCompletionText(res);
|
|
989
|
+
if (typeof onToken === 'function' && text) {
|
|
990
|
+
onToken(text);
|
|
991
|
+
}
|
|
992
|
+
return text;
|
|
816
993
|
}
|
|
817
994
|
|
|
818
995
|
_formatModelInfo() {
|
|
@@ -958,6 +1135,8 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
958
1135
|
' -ngl, --n-gpu-layers=N Number of layers offloaded to WebGPU (default: all)',
|
|
959
1136
|
' --no-gpu, --cpu Disable WebGPU and run on WASM SIMD CPU only',
|
|
960
1137
|
' --raw, --completion Use raw text completion instead of chat completion',
|
|
1138
|
+
' --stream Stream tokens as they are generated (default: enabled)',
|
|
1139
|
+
' --no-stream Disable token streaming and wait for full response',
|
|
961
1140
|
' --embed, --embeddings Generate embeddings instead of text completion',
|
|
962
1141
|
' --json Output raw JSON response',
|
|
963
1142
|
' -h, --help Show this help message and exit',
|
|
@@ -1009,17 +1188,44 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
1009
1188
|
}
|
|
1010
1189
|
|
|
1011
1190
|
if (this._parsed.rawCompletion) {
|
|
1191
|
+
const shouldStream = Boolean(this._parsed.stream && !this._parsed.jsonOutput);
|
|
1012
1192
|
const compOpts = {
|
|
1013
1193
|
prompt: inputText,
|
|
1014
1194
|
max_tokens: this._parsed.maxTokens,
|
|
1015
1195
|
temperature: this._parsed.temperature,
|
|
1016
|
-
stream:
|
|
1196
|
+
stream: shouldStream
|
|
1017
1197
|
};
|
|
1018
1198
|
if (this._parsed.topK !== undefined) compOpts.top_k = this._parsed.topK;
|
|
1019
1199
|
if (this._parsed.topP !== undefined) compOpts.top_p = this._parsed.topP;
|
|
1020
1200
|
|
|
1201
|
+
this._renderStatus('Running inference...');
|
|
1021
1202
|
const res = await this._wllama.createCompletion(compOpts);
|
|
1022
|
-
|
|
1203
|
+
let outText = '';
|
|
1204
|
+
if (res && typeof res[Symbol.asyncIterator] === 'function') {
|
|
1205
|
+
let streamedAny = false;
|
|
1206
|
+
for await (const chunk of res) {
|
|
1207
|
+
const delta = chunk?.choices?.[0]?.text ?? chunk?.choices?.[0]?.delta?.content ?? '';
|
|
1208
|
+
if (delta) {
|
|
1209
|
+
if (!streamedAny) {
|
|
1210
|
+
streamedAny = true;
|
|
1211
|
+
this._streamedStdout = true;
|
|
1212
|
+
this._clearStatus();
|
|
1213
|
+
}
|
|
1214
|
+
outText += delta;
|
|
1215
|
+
if (this.stdout && typeof this.stdout.write === 'function') {
|
|
1216
|
+
this.stdout.write(delta);
|
|
1217
|
+
}
|
|
1218
|
+
this.emit('token', delta);
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
this._clearStatus();
|
|
1222
|
+
if (streamedAny && outText.length > 0 && !outText.endsWith('\n') && this.stdout && typeof this.stdout.write === 'function') {
|
|
1223
|
+
this.stdout.write('\r\n');
|
|
1224
|
+
}
|
|
1225
|
+
} else {
|
|
1226
|
+
this._clearStatus();
|
|
1227
|
+
outText = this._parsed.jsonOutput ? JSON.stringify(res) : extractCompletionText(res);
|
|
1228
|
+
}
|
|
1023
1229
|
outText.split(/\r?\n/).forEach(l => { this.stdOut = l; });
|
|
1024
1230
|
return;
|
|
1025
1231
|
}
|
|
@@ -1030,7 +1236,26 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
|
1030
1236
|
}
|
|
1031
1237
|
messages.push({ role: 'user', content: inputText });
|
|
1032
1238
|
|
|
1033
|
-
const
|
|
1239
|
+
const shouldStream = Boolean(this._parsed.stream && !this._parsed.jsonOutput);
|
|
1240
|
+
let outText = '';
|
|
1241
|
+
if (shouldStream) {
|
|
1242
|
+
let streamedAny = false;
|
|
1243
|
+
outText = await this._runChatTurn(messages, (delta) => {
|
|
1244
|
+
if (!streamedAny) {
|
|
1245
|
+
streamedAny = true;
|
|
1246
|
+
this._streamedStdout = true;
|
|
1247
|
+
}
|
|
1248
|
+
if (this.stdout && typeof this.stdout.write === 'function') {
|
|
1249
|
+
this.stdout.write(delta);
|
|
1250
|
+
}
|
|
1251
|
+
this.emit('token', delta);
|
|
1252
|
+
});
|
|
1253
|
+
if (streamedAny && outText.length > 0 && !outText.endsWith('\n') && this.stdout && typeof this.stdout.write === 'function') {
|
|
1254
|
+
this.stdout.write('\r\n');
|
|
1255
|
+
}
|
|
1256
|
+
} else {
|
|
1257
|
+
outText = await this._runChatTurn(messages);
|
|
1258
|
+
}
|
|
1034
1259
|
outText.split(/\r?\n/).forEach(l => { this.stdOut = l; });
|
|
1035
1260
|
} catch (err) {
|
|
1036
1261
|
this.stdErr = `${binName}: ${err.message || err}`;
|
package/package.json
CHANGED
package/test/scripts.test.js
CHANGED
|
@@ -452,3 +452,83 @@ describe('sequential script execution', () => {
|
|
|
452
452
|
expect(output[2]).toBe('3');
|
|
453
453
|
});
|
|
454
454
|
});
|
|
455
|
+
|
|
456
|
+
describe('multiline quotes and line continuations in scripts', () => {
|
|
457
|
+
it('joins lines with unclosed double quotes into a single logical line', async () => {
|
|
458
|
+
const shell = await createShell({
|
|
459
|
+
filesystem: {
|
|
460
|
+
scripts: {
|
|
461
|
+
'multiline-dq.sh': '#!/sh.js\necho "hello\nworld"'
|
|
462
|
+
}
|
|
463
|
+
},
|
|
464
|
+
permissions: execPerms('/scripts/multiline-dq.sh')
|
|
465
|
+
});
|
|
466
|
+
const { output } = await run(shell, '/scripts/multiline-dq.sh');
|
|
467
|
+
expect(output).toEqual(['hello', 'world']);
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
it('joins lines with unclosed single quotes into a single logical line', async () => {
|
|
471
|
+
const shell = await createShell({
|
|
472
|
+
filesystem: {
|
|
473
|
+
scripts: {
|
|
474
|
+
'multiline-sq.sh': '#!/sh.js\necho \'first\nsecond\''
|
|
475
|
+
}
|
|
476
|
+
},
|
|
477
|
+
permissions: execPerms('/scripts/multiline-sq.sh')
|
|
478
|
+
});
|
|
479
|
+
const { output } = await run(shell, '/scripts/multiline-sq.sh');
|
|
480
|
+
expect(output).toEqual(['first', 'second']);
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
it('joins lines with trailing line continuation backslash', async () => {
|
|
484
|
+
const shell = await createShell({
|
|
485
|
+
filesystem: {
|
|
486
|
+
scripts: {
|
|
487
|
+
'continuation.sh': '#!/sh.js\necho \\\n hello \\\n world'
|
|
488
|
+
}
|
|
489
|
+
},
|
|
490
|
+
permissions: execPerms('/scripts/continuation.sh')
|
|
491
|
+
});
|
|
492
|
+
const { output } = await run(shell, '/scripts/continuation.sh');
|
|
493
|
+
expect(output).toEqual(['hello world']);
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
it('supports line continuation in if conditions', async () => {
|
|
497
|
+
const shell = await createShell({
|
|
498
|
+
filesystem: {
|
|
499
|
+
scripts: {
|
|
500
|
+
'if-cont.sh': '#!/sh.js\nif [ 1 = 1 ] \\\n && [ 2 = 2 ]; then\necho matched\nfi'
|
|
501
|
+
}
|
|
502
|
+
},
|
|
503
|
+
permissions: execPerms('/scripts/if-cont.sh')
|
|
504
|
+
});
|
|
505
|
+
const { output } = await run(shell, '/scripts/if-cont.sh');
|
|
506
|
+
expect(output).toEqual(['matched']);
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
it('supports negation operator in if condition: if ! command; then', async () => {
|
|
510
|
+
const shell = await createShell({
|
|
511
|
+
filesystem: {
|
|
512
|
+
scripts: {
|
|
513
|
+
'if-not.sh': '#!/sh.js\nif ! which non_existent_binary; then\necho "not found handled"\nfi'
|
|
514
|
+
}
|
|
515
|
+
},
|
|
516
|
+
permissions: execPerms('/scripts/if-not.sh')
|
|
517
|
+
});
|
|
518
|
+
const { output } = await run(shell, '/scripts/if-not.sh');
|
|
519
|
+
expect(output).toEqual(['not found handled']);
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
it('does not execute if block when condition with ! succeeds: if ! true; then', async () => {
|
|
523
|
+
const shell = await createShell({
|
|
524
|
+
filesystem: {
|
|
525
|
+
scripts: {
|
|
526
|
+
'if-not-true.sh': '#!/sh.js\nif ! true; then\necho unexpected\nelse\necho expected\nfi'
|
|
527
|
+
}
|
|
528
|
+
},
|
|
529
|
+
permissions: execPerms('/scripts/if-not-true.sh')
|
|
530
|
+
});
|
|
531
|
+
const { output } = await run(shell, '/scripts/if-not-true.sh');
|
|
532
|
+
expect(output).toEqual(['expected']);
|
|
533
|
+
});
|
|
534
|
+
});
|
package/test/shell.test.js
CHANGED
|
@@ -604,3 +604,118 @@ describe('MOTD, profile, and initial command startup chain', () => {
|
|
|
604
604
|
});
|
|
605
605
|
});
|
|
606
606
|
|
|
607
|
+
describe('negation operator (!)', () => {
|
|
608
|
+
let shell;
|
|
609
|
+
beforeEach(async () => { shell = await createShell(); });
|
|
610
|
+
|
|
611
|
+
it('inverts successful exit code 0 to 1 for ! true', async () => {
|
|
612
|
+
const { exitCode } = await run(shell, '! true');
|
|
613
|
+
expect(exitCode).toBe(1);
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
it('inverts failure exit code to 0 for ! false', async () => {
|
|
617
|
+
const { exitCode } = await run(shell, '! false');
|
|
618
|
+
expect(exitCode).toBe(0);
|
|
619
|
+
});
|
|
620
|
+
|
|
621
|
+
it('inverts non-zero exit code of missing command for ! which wllama', async () => {
|
|
622
|
+
const { exitCode } = await run(shell, '! which wllama');
|
|
623
|
+
expect(exitCode).toBe(0);
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
it('inverts exit code in conditional chains with &&', async () => {
|
|
627
|
+
const { output, exitCode } = await run(shell, '! false && echo "negated success"');
|
|
628
|
+
expect(output).toContain('negated success');
|
|
629
|
+
expect(exitCode).toBe(0);
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
it('inverts exit code in conditional chains with ||', async () => {
|
|
633
|
+
const { output, exitCode } = await run(shell, '! true || echo "fallback"');
|
|
634
|
+
expect(output).toContain('fallback');
|
|
635
|
+
expect(exitCode).toBe(0);
|
|
636
|
+
});
|
|
637
|
+
|
|
638
|
+
it('inverts exit code of a pipeline with leading !', async () => {
|
|
639
|
+
const { exitCode } = await run(shell, '! true | false');
|
|
640
|
+
expect(exitCode).toBe(0);
|
|
641
|
+
});
|
|
642
|
+
|
|
643
|
+
it('inverts exit code of a pipeline stage', async () => {
|
|
644
|
+
const { exitCode } = await run(shell, 'false | ! true');
|
|
645
|
+
expect(exitCode).toBe(1);
|
|
646
|
+
});
|
|
647
|
+
});
|
|
648
|
+
|
|
649
|
+
describe('stream redirection syntax', () => {
|
|
650
|
+
let shell;
|
|
651
|
+
beforeEach(async () => {
|
|
652
|
+
shell = await createShell({
|
|
653
|
+
filesystem: {
|
|
654
|
+
home: {}
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
});
|
|
658
|
+
|
|
659
|
+
it('redirects stderr to stdout with 2>&1', async () => {
|
|
660
|
+
const { output, errors } = await run(shell, 'cat /non_existent 2>&1');
|
|
661
|
+
expect(errors).toHaveLength(0);
|
|
662
|
+
expect(output.length).toBeGreaterThan(0);
|
|
663
|
+
expect(output[0]).toContain('No such file or directory');
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
it('pipes stderr into next stage when using 2>&1 |', async () => {
|
|
667
|
+
const { output } = await run(shell, 'cat /non_existent 2>&1 | cat');
|
|
668
|
+
expect(output.length).toBeGreaterThan(0);
|
|
669
|
+
expect(output[0]).toContain('No such file or directory');
|
|
670
|
+
});
|
|
671
|
+
|
|
672
|
+
it('discards stderr when redirected to /dev/null with 2> /dev/null', async () => {
|
|
673
|
+
const { output, errors, exitCode } = await run(shell, 'cat /non_existent 2> /dev/null');
|
|
674
|
+
expect(errors).toHaveLength(0);
|
|
675
|
+
expect(output).toHaveLength(0);
|
|
676
|
+
expect(exitCode).not.toBe(0);
|
|
677
|
+
});
|
|
678
|
+
|
|
679
|
+
it('strips 2>&1 from positional arguments (argv) so command does not receive it as an argument', async () => {
|
|
680
|
+
// which rejects with "which requires a single argument" if 2>&1 is not stripped
|
|
681
|
+
const { output, errors } = await run(shell, 'which non_existent 2>&1');
|
|
682
|
+
expect(output.join(' ')).not.toContain('which requires a single argument');
|
|
683
|
+
expect(errors.join(' ')).not.toContain('which requires a single argument');
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
it('redirects stderr to a file with 2>', async () => {
|
|
687
|
+
await run(shell, 'cat /non_existent 2> /home/err.txt');
|
|
688
|
+
const content = shell.context.fs.getFileByPath('/home/err.txt');
|
|
689
|
+
expect(content).toContain('No such file or directory');
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
it('appends stderr to a file with 2>>', async () => {
|
|
693
|
+
shell.context.fs.setFileByPath('/home/err.txt', 'existing', true);
|
|
694
|
+
await run(shell, 'cat /non_existent 2>> /home/err.txt');
|
|
695
|
+
const content = shell.context.fs.getFileByPath('/home/err.txt');
|
|
696
|
+
expect(content).toContain('existing\n');
|
|
697
|
+
expect(content).toContain('No such file or directory');
|
|
698
|
+
});
|
|
699
|
+
|
|
700
|
+
it('redirects stdout with 1> and 1>>', async () => {
|
|
701
|
+
await run(shell, 'echo first 1> /home/out.txt');
|
|
702
|
+
await run(shell, 'echo second 1>> /home/out.txt');
|
|
703
|
+
expect(shell.context.fs.getFileByPath('/home/out.txt')).toBe('first\nsecond');
|
|
704
|
+
});
|
|
705
|
+
|
|
706
|
+
it('redirects both stdout and stderr to a file with &>', async () => {
|
|
707
|
+
await run(shell, 'echo test &> /home/combined.txt');
|
|
708
|
+
expect(shell.context.fs.getFileByPath('/home/combined.txt')).toBe('test');
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
it('redirects both stdout and stderr to a file with > file 2>&1', async () => {
|
|
712
|
+
await run(shell, 'echo msg > /home/both.txt 2>&1');
|
|
713
|
+
expect(shell.context.fs.getFileByPath('/home/both.txt')).toBe('msg');
|
|
714
|
+
});
|
|
715
|
+
|
|
716
|
+
it('preserves quoted redirection tokens as literal arguments', async () => {
|
|
717
|
+
const { output } = await run(shell, 'echo "2>&1"');
|
|
718
|
+
expect(output).toEqual(['2>&1']);
|
|
719
|
+
});
|
|
720
|
+
});
|
|
721
|
+
|