brsh 3.4.0 → 3.6.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.
@@ -53,15 +53,18 @@ function getDefaultPersistPath(modelSpec) {
53
53
  return `${DEFAULT_PERSIST_DIR}/${fileName}`;
54
54
  }
55
55
 
56
+ function formatSize(bytes) {
57
+ if (!bytes || bytes <= 0) return '0 B';
58
+ if (bytes >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
59
+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
60
+ if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
61
+ return `${bytes} B`;
62
+ }
63
+
56
64
  /**
57
65
  * Formats an in-place carriage-return (\r) download progress bar line.
58
66
  */
59
67
  function formatDownloadProgress(label, loaded, total, width = 20) {
60
- const formatSize = (bytes) => {
61
- if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
62
- if (bytes >= 1024) return `${(bytes / (1024 * 1024 * 1024 >= 1 ? 1024 * 1024 : 1024)).toFixed(1)} KB`;
63
- return `${bytes} B`;
64
- };
65
68
  const shortLabel = (label || 'model.gguf').split('/').pop().split('?')[0] || label;
66
69
  if (total > 0) {
67
70
  const ratio = Math.max(0, Math.min(1, loaded / total));
@@ -73,6 +76,123 @@ function formatDownloadProgress(label, loaded, total, width = 20) {
73
76
  return `\rPulling ${shortLabel}: ${formatSize(loaded)} downloaded...`;
74
77
  }
75
78
 
79
+ /**
80
+ * Animated intermediate & determinate progress tracker for model weights loading,
81
+ * compilation, and inference execution.
82
+ */
83
+ class ProgressTracker {
84
+ constructor({ onRender = null, width = 20, intervalMs = 80, enabled = true } = {}) {
85
+ this.onRender = onRender;
86
+ this.width = width;
87
+ this.intervalMs = intervalMs;
88
+ this.enabled = enabled;
89
+ this.label = '';
90
+ this.total = 0;
91
+ this.loaded = 0;
92
+ this.hint = '';
93
+ this.startTime = 0;
94
+ this.step = 0;
95
+ this.timer = null;
96
+ this.active = false;
97
+ this.isDeterminate = false;
98
+ }
99
+
100
+ start(label, { total = 0, loaded = 0, hint = '', determinate = null } = {}) {
101
+ if (!this.enabled) return;
102
+ this.stopTimer();
103
+ this.label = label || 'Loading';
104
+ this.total = total || 0;
105
+ this.loaded = loaded || 0;
106
+ this.hint = hint || '';
107
+ this.startTime = Date.now();
108
+ this.step = 0;
109
+ this.active = true;
110
+ this.isDeterminate = determinate !== null ? determinate : (this.total > 0 && this.loaded > 0);
111
+ this.render();
112
+ this.timer = setInterval(() => {
113
+ this.step++;
114
+ this.render();
115
+ }, this.intervalMs);
116
+ }
117
+
118
+ update({ loaded, total, hint } = {}) {
119
+ if (!this.enabled || !this.active) return;
120
+ if (typeof total === 'number' && total > 0) {
121
+ this.total = total;
122
+ this.isDeterminate = true;
123
+ }
124
+ if (typeof loaded === 'number' && loaded >= 0) {
125
+ this.loaded = loaded;
126
+ if (this.total > 0) {
127
+ this.isDeterminate = true;
128
+ }
129
+ }
130
+ if (typeof hint === 'string') {
131
+ this.hint = hint;
132
+ }
133
+ this.render();
134
+ }
135
+
136
+ formatLine() {
137
+ const elapsedSec = ((Date.now() - this.startTime) / 1000).toFixed(1) + 's';
138
+ if (this.isDeterminate && this.total > 0) {
139
+ const ratio = Math.max(0, Math.min(1, this.loaded / this.total));
140
+ const pct = Math.round(ratio * 100);
141
+ const filled = Math.round(ratio * this.width);
142
+ const bar = '█'.repeat(filled) + '░'.repeat(Math.max(0, this.width - filled));
143
+ const sizeStr = `${formatSize(this.loaded)} / ${formatSize(this.total)}`;
144
+ const hintStr = this.hint ? ` (${this.hint})` : '';
145
+ return `${this.label}: [${bar}] ${String(pct).padStart(3)}% (${sizeStr}, ${elapsedSec})${hintStr}`;
146
+ }
147
+
148
+ // Bouncing intermediate bar animation
149
+ const blockWidth = 5;
150
+ const maxPos = Math.max(1, this.width - blockWidth);
151
+ const cycle = maxPos * 2;
152
+ const posInCycle = this.step % cycle;
153
+ const offset = posInCycle < maxPos ? posInCycle : cycle - posInCycle;
154
+ const left = '░'.repeat(offset);
155
+ const middle = '█'.repeat(blockWidth);
156
+ const right = '░'.repeat(Math.max(0, this.width - offset - blockWidth));
157
+ const bar = `[${left}${middle}${right}]`;
158
+ const hintStr = this.hint ? ` (${this.hint})` : '';
159
+ return `${this.label}: ${bar} ${elapsedSec}${hintStr}`;
160
+ }
161
+
162
+ render() {
163
+ if (!this.enabled || !this.active || typeof this.onRender !== 'function') return;
164
+ this.onRender(this.formatLine());
165
+ }
166
+
167
+ stopTimer() {
168
+ if (this.timer !== null) {
169
+ clearInterval(this.timer);
170
+ this.timer = null;
171
+ }
172
+ }
173
+
174
+ finish(msg = 'Done') {
175
+ if (!this.enabled || !this.active) return;
176
+ this.stopTimer();
177
+ const elapsedSec = ((Date.now() - this.startTime) / 1000).toFixed(1) + 's';
178
+ const bar = '█'.repeat(this.width);
179
+ const sizeStr = this.total > 0 ? `, ${formatSize(this.total)}` : '';
180
+ const line = `${this.label}: [${bar}] 100% (${elapsedSec}${sizeStr}) — ${msg}`;
181
+ if (typeof this.onRender === 'function') {
182
+ this.onRender(line);
183
+ }
184
+ this.active = false;
185
+ }
186
+
187
+ clear() {
188
+ this.stopTimer();
189
+ this.active = false;
190
+ if (this.enabled && typeof this.onRender === 'function') {
191
+ this.onRender('');
192
+ }
193
+ }
194
+ }
195
+
76
196
 
77
197
  /**
78
198
  * Resolves a model spec (`hf:owner/repo/file.gguf`, `owner/repo:Q4_K_M`, URL, or filesystem path)
@@ -258,6 +378,9 @@ async function getOrInitWllamaInstance(opts = {}) {
258
378
  loadModel = true,
259
379
  persist = false,
260
380
  persistPath = null,
381
+ tracker = null,
382
+ shortLabel = 'model.gguf',
383
+ isPullCommand = false,
261
384
  onStatus = null
262
385
  } = opts;
263
386
 
@@ -325,6 +448,9 @@ async function getOrInitWllamaInstance(opts = {}) {
325
448
  if (typeof onStatus === 'function') {
326
449
  onStatus('Loaded model from cache.');
327
450
  }
451
+ if (tracker) {
452
+ tracker.finish('Loaded model from cache');
453
+ }
328
454
  let persisted = null;
329
455
  if ((persist || persistPath) && fs && resolvedPersistPath) {
330
456
  if (fs.exists(resolvedPersistPath)) {
@@ -349,6 +475,20 @@ async function getOrInitWllamaInstance(opts = {}) {
349
475
  let downloadedBlob = null;
350
476
  let loadedFromPersistedFs = null;
351
477
 
478
+ const makeLoadParams = (hint = 'loading tensors') => {
479
+ return {
480
+ ...loadParams,
481
+ progressCallback: ({ loaded, total }) => {
482
+ if (tracker) {
483
+ tracker.update({ loaded, total, hint });
484
+ }
485
+ if (typeof loadParams.progressCallback === 'function') {
486
+ loadParams.progressCallback({ loaded, total });
487
+ }
488
+ }
489
+ };
490
+ };
491
+
352
492
  // If a remote model was previously persisted into the brsh filesystem, load directly from fs
353
493
  if (modelSpec.kind !== 'fs' && fs) {
354
494
  const candidatePath = (resolvedPersistPath && fs.exists(resolvedPersistPath))
@@ -360,10 +500,19 @@ async function getOrInitWllamaInstance(opts = {}) {
360
500
  if (typeof onStatus === 'function') {
361
501
  onStatus(`Loading model from ${candidatePath}...`);
362
502
  }
503
+ if (tracker) {
504
+ tracker.start(`Loading model (${shortLabel}) weights`, {
505
+ total: cachedBytes.byteLength,
506
+ hint: 'parsing tensors & compiling WebGPU shaders'
507
+ });
508
+ }
363
509
  const cachedBlob = new Blob([cachedBytes], { type: 'application/octet-stream' });
364
510
  cachedBlob.name = candidatePath.split('/').pop() || 'model.gguf';
365
- await wllama.loadModel([cachedBlob], loadParams);
511
+ await wllama.loadModel([cachedBlob], makeLoadParams());
366
512
  loadedFromPersistedFs = { path: candidatePath, bytes: cachedBytes };
513
+ if (tracker) {
514
+ tracker.finish('Model weights loaded');
515
+ }
367
516
  }
368
517
  }
369
518
  }
@@ -376,6 +525,9 @@ async function getOrInitWllamaInstance(opts = {}) {
376
525
  if (typeof onStatus === 'function') {
377
526
  onStatus(`Loading model from ${modelSpec.path}...`);
378
527
  }
528
+ if (tracker) {
529
+ tracker.start(`Loading model (${shortLabel}) weights`, { hint: 'reading file' });
530
+ }
379
531
  const bytes = readBytesFromFs(fs, modelSpec.path);
380
532
  if (!bytes) {
381
533
  throw new Error(`${modelSpec.path}: No such file or directory`);
@@ -397,7 +549,17 @@ async function getOrInitWllamaInstance(opts = {}) {
397
549
  if (typeof onStatus === 'function') {
398
550
  onStatus(`Loading model ${modelBlob.name} into memory...`);
399
551
  }
400
- await wllama.loadModel(blobs, loadParams);
552
+ if (tracker) {
553
+ tracker.start(`Loading model (${shortLabel}) weights`, {
554
+ total: bytes.byteLength,
555
+ loaded: bytes.byteLength,
556
+ hint: 'parsing tensors & compiling WebGPU shaders'
557
+ });
558
+ }
559
+ await wllama.loadModel(blobs, makeLoadParams());
560
+ if (tracker) {
561
+ tracker.finish('Model weights loaded');
562
+ }
401
563
  if (resolvedPersistPath && resolvedPersistPath !== modelSpec.path) {
402
564
  writeBytesToFs(fs, resolvedPersistPath, bytes, 'application/octet-stream');
403
565
  }
@@ -405,25 +567,46 @@ async function getOrInitWllamaInstance(opts = {}) {
405
567
  if (typeof onStatus === 'function') {
406
568
  onStatus(`Pulling model ${modelSpec.repo} (${modelSpec.quant})...`);
407
569
  }
570
+ if (tracker) {
571
+ tracker.start(`Pulling ${shortLabel}`, { hint: 'connecting to Hugging Face' });
572
+ }
408
573
  try {
409
574
  await wllama.loadModelFromHF(
410
575
  {
411
576
  repo: modelSpec.repo,
412
577
  quant: modelSpec.quant
413
578
  },
414
- loadParams
579
+ makeLoadParams('downloading')
415
580
  );
581
+ if (tracker) {
582
+ tracker.finish('Model weights loaded');
583
+ }
416
584
  } catch (err) {
417
585
  if (typeof mod.getHFModelSource === 'function') {
418
586
  const src = await mod.getHFModelSource({ repo: modelSpec.repo, quant: modelSpec.quant });
419
587
  if (typeof onStatus === 'function') {
420
588
  onStatus(`Pulling model ${modelSpec.repo} (${modelSpec.quant})...`);
421
589
  }
422
- downloadedBlob = await fetchUrlAsGgufBlob(src.url || src, loadParams.progressCallback);
590
+ if (tracker) {
591
+ tracker.start(`Pulling ${shortLabel}`, { hint: 'downloading' });
592
+ }
593
+ downloadedBlob = await fetchUrlAsGgufBlob(src.url || src, (p) => {
594
+ if (tracker) tracker.update({ loaded: p.loaded, total: p.total, hint: 'downloading' });
595
+ if (typeof loadParams.progressCallback === 'function') loadParams.progressCallback(p);
596
+ });
423
597
  if (typeof onStatus === 'function') {
424
598
  onStatus(`Loading model into memory...`);
425
599
  }
426
- await wllama.loadModel([downloadedBlob], loadParams);
600
+ if (tracker) {
601
+ tracker.start(`Loading model (${shortLabel}) weights`, {
602
+ total: downloadedBlob.size,
603
+ hint: 'parsing tensors & compiling WebGPU shaders'
604
+ });
605
+ }
606
+ await wllama.loadModel([downloadedBlob], makeLoadParams());
607
+ if (tracker) {
608
+ tracker.finish('Model weights loaded');
609
+ }
427
610
  } else {
428
611
  throw err;
429
612
  }
@@ -432,38 +615,77 @@ async function getOrInitWllamaInstance(opts = {}) {
432
615
  if (typeof onStatus === 'function') {
433
616
  onStatus(`Pulling model ${modelSpec.repo}/${modelSpec.file}...`);
434
617
  }
618
+ if (tracker) {
619
+ tracker.start(`Pulling ${shortLabel}`, { hint: 'connecting to Hugging Face' });
620
+ }
435
621
  try {
436
622
  await wllama.loadModelFromHF(
437
623
  {
438
624
  repo: modelSpec.repo,
439
625
  file: modelSpec.file
440
626
  },
441
- loadParams
627
+ makeLoadParams('downloading')
442
628
  );
629
+ if (tracker) {
630
+ tracker.finish('Model weights loaded');
631
+ }
443
632
  } catch {
444
- downloadedBlob = await fetchUrlAsGgufBlob(modelSpec.url, loadParams.progressCallback);
633
+ if (tracker) {
634
+ tracker.start(`Pulling ${shortLabel}`, { hint: 'downloading' });
635
+ }
636
+ downloadedBlob = await fetchUrlAsGgufBlob(modelSpec.url, (p) => {
637
+ if (tracker) tracker.update({ loaded: p.loaded, total: p.total, hint: 'downloading' });
638
+ if (typeof loadParams.progressCallback === 'function') loadParams.progressCallback(p);
639
+ });
445
640
  if (typeof onStatus === 'function') {
446
641
  onStatus(`Loading model into memory...`);
447
642
  }
448
- await wllama.loadModel([downloadedBlob], loadParams);
643
+ if (tracker) {
644
+ tracker.start(`Loading model (${shortLabel}) weights`, {
645
+ total: downloadedBlob.size,
646
+ hint: 'parsing tensors & compiling WebGPU shaders'
647
+ });
648
+ }
649
+ await wllama.loadModel([downloadedBlob], makeLoadParams());
650
+ if (tracker) {
651
+ tracker.finish('Model weights loaded');
652
+ }
449
653
  }
450
654
  } else {
451
655
  const targetUrl = modelSpec.url || DEFAULT_MODEL_URL;
452
656
  if (typeof onStatus === 'function') {
453
657
  onStatus(`Pulling model from ${targetUrl.split('/').pop().split('?')[0] || targetUrl}...`);
454
658
  }
659
+ if (tracker) {
660
+ tracker.start(`Pulling ${shortLabel}`, { hint: 'downloading' });
661
+ }
455
662
  try {
456
663
  if (mmprojSpec && /^https?:\/\//i.test(mmprojSpec)) {
457
- await wllama.loadModelFromUrl({ url: targetUrl, mmprojUrl: mmprojSpec }, loadParams);
664
+ await wllama.loadModelFromUrl({ url: targetUrl, mmprojUrl: mmprojSpec }, makeLoadParams('downloading'));
458
665
  } else {
459
- await wllama.loadModelFromUrl(targetUrl, loadParams);
666
+ await wllama.loadModelFromUrl(targetUrl, makeLoadParams('downloading'));
667
+ }
668
+ if (tracker) {
669
+ tracker.finish('Model weights loaded');
460
670
  }
461
671
  } catch {
462
- downloadedBlob = await fetchUrlAsGgufBlob(targetUrl, loadParams.progressCallback);
672
+ downloadedBlob = await fetchUrlAsGgufBlob(targetUrl, (p) => {
673
+ if (tracker) tracker.update({ loaded: p.loaded, total: p.total, hint: 'downloading' });
674
+ if (typeof loadParams.progressCallback === 'function') loadParams.progressCallback(p);
675
+ });
463
676
  if (typeof onStatus === 'function') {
464
677
  onStatus(`Loading model into memory...`);
465
678
  }
466
- await wllama.loadModel([downloadedBlob], loadParams);
679
+ if (tracker) {
680
+ tracker.start(`Loading model (${shortLabel}) weights`, {
681
+ total: downloadedBlob.size,
682
+ hint: 'parsing tensors & compiling WebGPU shaders'
683
+ });
684
+ }
685
+ await wllama.loadModel([downloadedBlob], makeLoadParams());
686
+ if (tracker) {
687
+ tracker.finish('Model weights loaded');
688
+ }
467
689
  }
468
690
  }
469
691
 
@@ -781,6 +1003,27 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
781
1003
  }
782
1004
  }
783
1005
 
1006
+ _createTracker(defaultLabel = 'Loading') {
1007
+ const enabled = Boolean(this._parsed.showProgress && !this._parsed.jsonOutput);
1008
+ return new ProgressTracker({
1009
+ enabled,
1010
+ width: 20,
1011
+ intervalMs: 80,
1012
+ onRender: (line) => {
1013
+ if (this.interactive) {
1014
+ this._replStatus = line;
1015
+ this._renderRepl();
1016
+ } else {
1017
+ if (line) {
1018
+ this._renderStatus(line);
1019
+ } else {
1020
+ this._clearStatus();
1021
+ }
1022
+ }
1023
+ }
1024
+ });
1025
+ }
1026
+
784
1027
  _attachProgressCallback() {
785
1028
  if (!this._parsed.showProgress || this._parsed.modelSpec.kind === 'fs') return;
786
1029
  const label = this._parsed.model || this._parsed.modelSpec.file || this._parsed.modelSpec.repo || this._parsed.modelSpec.url || 'model.gguf';
@@ -809,6 +1052,10 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
809
1052
  this._attachProgressCallback();
810
1053
  }
811
1054
 
1055
+ const rawLabel = this._parsed.model || this._parsed.modelSpec.file || this._parsed.modelSpec.repo || this._parsed.modelSpec.url || 'model.gguf';
1056
+ const shortLabel = rawLabel.split('/').pop().split('?')[0] || rawLabel;
1057
+ const tracker = this._createTracker();
1058
+
812
1059
  const onStatus = (msg) => {
813
1060
  if (this.interactive) {
814
1061
  this._replStatus = msg;
@@ -818,23 +1065,32 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
818
1065
  }
819
1066
  };
820
1067
 
821
- const { wllama, Wllama, persisted } = await getOrInitWllamaInstance({
822
- modelSpec: this._parsed.modelSpec,
823
- mmprojSpec: this._parsed.mmproj,
824
- loadParams: this._parsed.loadParams,
825
- fs: this.fs,
826
- pkgMeta,
827
- wbtConfig,
828
- loadModel,
829
- persist: this._parsed.persist,
830
- persistPath: this._parsed.persistPath,
831
- onStatus
832
- });
833
- this._wllama = wllama;
834
- this._WllamaClass = Wllama;
835
- this._persisted = persisted;
836
- if (!this.interactive) {
837
- this._clearStatus();
1068
+ try {
1069
+ const { wllama, Wllama, persisted } = await getOrInitWllamaInstance({
1070
+ modelSpec: this._parsed.modelSpec,
1071
+ mmprojSpec: this._parsed.mmproj,
1072
+ loadParams: this._parsed.loadParams,
1073
+ fs: this.fs,
1074
+ pkgMeta,
1075
+ wbtConfig,
1076
+ loadModel,
1077
+ persist: this._parsed.persist,
1078
+ persistPath: this._parsed.persistPath,
1079
+ tracker,
1080
+ shortLabel,
1081
+ isPullCommand: this._parsed.subcommand === 'pull',
1082
+ onStatus
1083
+ });
1084
+ this._wllama = wllama;
1085
+ this._WllamaClass = Wllama;
1086
+ this._persisted = persisted;
1087
+ } finally {
1088
+ if (tracker) {
1089
+ tracker.clear();
1090
+ }
1091
+ if (!this.interactive) {
1092
+ this._clearStatus();
1093
+ }
838
1094
  }
839
1095
  }
840
1096
 
@@ -918,24 +1174,75 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
918
1174
  if (this._parsed.topK !== undefined) opts.top_k = this._parsed.topK;
919
1175
  if (this._parsed.topP !== undefined) opts.top_p = this._parsed.topP;
920
1176
 
921
- if (this.interactive) {
922
- this._replStatus = 'Running inference...';
923
- this._renderRepl();
924
- } else {
925
- this._renderStatus('Running inference...');
926
- }
1177
+ const tracker = this._createTracker();
1178
+ tracker.start('Running inference', { hint: 'evaluating prompt & preparing KV cache' });
1179
+
1180
+ try {
1181
+ if (typeof this._wllama.createChatCompletion === 'function') {
1182
+ const res = await this._wllama.createChatCompletion(opts);
1183
+
1184
+ if (res && typeof res[Symbol.asyncIterator] === 'function') {
1185
+ let fullText = '';
1186
+ let firstToken = false;
1187
+ for await (const chunk of res) {
1188
+ const delta = chunk?.choices?.[0]?.delta?.content ?? chunk?.choices?.[0]?.text ?? '';
1189
+ if (delta) {
1190
+ if (!firstToken) {
1191
+ firstToken = true;
1192
+ tracker.clear();
1193
+ if (this.interactive) {
1194
+ this._replStatus = 'Streaming tokens...';
1195
+ this._renderRepl();
1196
+ } else {
1197
+ this._clearStatus();
1198
+ }
1199
+ }
1200
+ fullText += delta;
1201
+ if (typeof onToken === 'function') {
1202
+ onToken(delta);
1203
+ }
1204
+ }
1205
+ }
1206
+ tracker.clear();
1207
+ if (!this.interactive) {
1208
+ this._clearStatus();
1209
+ }
1210
+ return fullText;
1211
+ }
927
1212
 
928
- if (typeof this._wllama.createChatCompletion === 'function') {
929
- const res = await this._wllama.createChatCompletion(opts);
1213
+ tracker.clear();
1214
+ if (!this.interactive) this._clearStatus();
1215
+ if (this._parsed.jsonOutput) {
1216
+ return JSON.stringify(res);
1217
+ }
1218
+ const text = extractCompletionText(res);
1219
+ if (typeof onToken === 'function' && text) {
1220
+ onToken(text);
1221
+ }
1222
+ return text;
1223
+ }
930
1224
 
1225
+ // Fallback if mock/custom instance only implements createCompletion
1226
+ const lastMsg = messages[messages.length - 1]?.content || '';
1227
+ const compOpts = {
1228
+ prompt: lastMsg,
1229
+ max_tokens: this._parsed.maxTokens,
1230
+ temperature: this._parsed.temperature,
1231
+ stream: shouldStream
1232
+ };
1233
+ if (this._parsed.topK !== undefined) compOpts.top_k = this._parsed.topK;
1234
+ if (this._parsed.topP !== undefined) compOpts.top_p = this._parsed.topP;
1235
+
1236
+ const res = await this._wllama.createCompletion(compOpts);
931
1237
  if (res && typeof res[Symbol.asyncIterator] === 'function') {
932
1238
  let fullText = '';
933
1239
  let firstToken = false;
934
1240
  for await (const chunk of res) {
935
- const delta = chunk?.choices?.[0]?.delta?.content ?? chunk?.choices?.[0]?.text ?? '';
1241
+ const delta = chunk?.choices?.[0]?.text ?? chunk?.choices?.[0]?.delta?.content ?? '';
936
1242
  if (delta) {
937
1243
  if (!firstToken) {
938
1244
  firstToken = true;
1245
+ tracker.clear();
939
1246
  if (this.interactive) {
940
1247
  this._replStatus = 'Streaming tokens...';
941
1248
  this._renderRepl();
@@ -949,74 +1256,29 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
949
1256
  }
950
1257
  }
951
1258
  }
1259
+ tracker.clear();
952
1260
  if (!this.interactive) {
953
1261
  this._clearStatus();
954
1262
  }
955
1263
  return fullText;
956
1264
  }
957
1265
 
958
- if (this._parsed.jsonOutput) {
959
- if (!this.interactive) this._clearStatus();
960
- return JSON.stringify(res);
961
- }
962
- const text = extractCompletionText(res);
1266
+ tracker.clear();
963
1267
  if (!this.interactive) {
964
1268
  this._clearStatus();
965
1269
  }
1270
+ if (this._parsed.jsonOutput) return JSON.stringify(res);
1271
+ const text = extractCompletionText(res);
966
1272
  if (typeof onToken === 'function' && text) {
967
1273
  onToken(text);
968
1274
  }
969
1275
  return text;
970
- }
971
-
972
- // Fallback if mock/custom instance only implements createCompletion
973
- const lastMsg = messages[messages.length - 1]?.content || '';
974
- const compOpts = {
975
- prompt: lastMsg,
976
- max_tokens: this._parsed.maxTokens,
977
- temperature: this._parsed.temperature,
978
- stream: shouldStream
979
- };
980
- if (this._parsed.topK !== undefined) compOpts.top_k = this._parsed.topK;
981
- if (this._parsed.topP !== undefined) compOpts.top_p = this._parsed.topP;
982
-
983
- const res = await this._wllama.createCompletion(compOpts);
984
- if (res && typeof res[Symbol.asyncIterator] === 'function') {
985
- let fullText = '';
986
- let firstToken = false;
987
- for await (const chunk of res) {
988
- const delta = chunk?.choices?.[0]?.text ?? chunk?.choices?.[0]?.delta?.content ?? '';
989
- if (delta) {
990
- if (!firstToken) {
991
- firstToken = true;
992
- if (this.interactive) {
993
- this._replStatus = 'Streaming tokens...';
994
- this._renderRepl();
995
- } else {
996
- this._clearStatus();
997
- }
998
- }
999
- fullText += delta;
1000
- if (typeof onToken === 'function') {
1001
- onToken(delta);
1002
- }
1003
- }
1004
- }
1276
+ } finally {
1277
+ tracker.clear();
1005
1278
  if (!this.interactive) {
1006
1279
  this._clearStatus();
1007
1280
  }
1008
- return fullText;
1009
1281
  }
1010
-
1011
- if (!this.interactive) {
1012
- this._clearStatus();
1013
- }
1014
- if (this._parsed.jsonOutput) return JSON.stringify(res);
1015
- const text = extractCompletionText(res);
1016
- if (typeof onToken === 'function' && text) {
1017
- onToken(text);
1018
- }
1019
- return text;
1020
1282
  }
1021
1283
 
1022
1284
  _formatModelInfo() {
@@ -1204,7 +1466,15 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1204
1466
  }
1205
1467
 
1206
1468
  if (this._parsed.embeddings || this._parsed.subcommand === 'embed') {
1207
- const embRes = await this._wllama.createEmbedding({ input: inputText });
1469
+ const tracker = this._createTracker();
1470
+ tracker.start('Computing embeddings', { hint: 'evaluating prompt' });
1471
+ let embRes;
1472
+ try {
1473
+ embRes = await this._wllama.createEmbedding({ input: inputText });
1474
+ } finally {
1475
+ tracker.clear();
1476
+ this._clearStatus();
1477
+ }
1208
1478
  if (this._parsed.jsonOutput) {
1209
1479
  this.stdOut = JSON.stringify(embRes);
1210
1480
  } else {
@@ -1225,36 +1495,45 @@ function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
1225
1495
  if (this._parsed.topK !== undefined) compOpts.top_k = this._parsed.topK;
1226
1496
  if (this._parsed.topP !== undefined) compOpts.top_p = this._parsed.topP;
1227
1497
 
1228
- this._renderStatus('Running inference...');
1229
- const res = await this._wllama.createCompletion(compOpts);
1230
- let outText = '';
1231
- if (res && typeof res[Symbol.asyncIterator] === 'function') {
1232
- let streamedAny = false;
1233
- for await (const chunk of res) {
1234
- const delta = chunk?.choices?.[0]?.text ?? chunk?.choices?.[0]?.delta?.content ?? '';
1235
- if (delta) {
1236
- if (!streamedAny) {
1237
- streamedAny = true;
1238
- this._streamedStdout = true;
1239
- this._clearStatus();
1240
- }
1241
- outText += delta;
1242
- if (this.stdout && typeof this.stdout.write === 'function') {
1243
- this.stdout.write(delta);
1498
+ const tracker = this._createTracker();
1499
+ tracker.start('Running inference', { hint: 'evaluating prompt & preparing KV cache' });
1500
+ try {
1501
+ const res = await this._wllama.createCompletion(compOpts);
1502
+ let outText = '';
1503
+ if (res && typeof res[Symbol.asyncIterator] === 'function') {
1504
+ let streamedAny = false;
1505
+ for await (const chunk of res) {
1506
+ const delta = chunk?.choices?.[0]?.text ?? chunk?.choices?.[0]?.delta?.content ?? '';
1507
+ if (delta) {
1508
+ if (!streamedAny) {
1509
+ streamedAny = true;
1510
+ this._streamedStdout = true;
1511
+ tracker.clear();
1512
+ this._clearStatus();
1513
+ }
1514
+ outText += delta;
1515
+ if (this.stdout && typeof this.stdout.write === 'function') {
1516
+ this.stdout.write(delta);
1517
+ }
1518
+ this.emit('token', delta);
1244
1519
  }
1245
- this.emit('token', delta);
1246
1520
  }
1521
+ tracker.clear();
1522
+ this._clearStatus();
1523
+ if (streamedAny && outText.length > 0 && !outText.endsWith('\n') && this.stdout && typeof this.stdout.write === 'function') {
1524
+ this.stdout.write('\r\n');
1525
+ }
1526
+ } else {
1527
+ tracker.clear();
1528
+ this._clearStatus();
1529
+ outText = this._parsed.jsonOutput ? JSON.stringify(res) : extractCompletionText(res);
1247
1530
  }
1531
+ outText.split(/\r?\n/).forEach(l => { this.stdOut = l; });
1532
+ return;
1533
+ } finally {
1534
+ tracker.clear();
1248
1535
  this._clearStatus();
1249
- if (streamedAny && outText.length > 0 && !outText.endsWith('\n') && this.stdout && typeof this.stdout.write === 'function') {
1250
- this.stdout.write('\r\n');
1251
- }
1252
- } else {
1253
- this._clearStatus();
1254
- outText = this._parsed.jsonOutput ? JSON.stringify(res) : extractCompletionText(res);
1255
1536
  }
1256
- outText.split(/\r?\n/).forEach(l => { this.stdOut = l; });
1257
- return;
1258
1537
  }
1259
1538
 
1260
1539
  const messages = [];