brsh 2.7.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.
- package/CHANGELOG.md +13 -0
- package/Readme.md +33 -16
- package/bin/brsh-shell.js +15 -1
- package/dist/shell.es.js +83 -28
- package/dist/shell.es.js.map +1 -1
- package/dist/shell.min.js +3 -3
- package/dist/shell.min.js.map +1 -1
- package/dist/terminal.cjs.js +101 -0
- package/dist/terminal.cjs.js.map +1 -0
- package/dist/terminal.es.js +290 -8107
- package/dist/terminal.es.js.map +1 -1
- package/dist/terminal.min.js +4 -32
- package/dist/terminal.min.js.map +1 -1
- package/dist/wbt.es.js +346 -5821
- package/dist/wbt.es.js.map +1 -1
- package/dist/wbt.min.js +4 -18
- package/dist/wbt.min.js.map +1 -1
- package/index.js +29 -0
- package/lib/Terminal.js +45 -10
- package/lib/local/curl.js +60 -2
- package/lib/wbt/index.js +27 -50
- package/lib/wbt/packages/wllama.js +1051 -0
- package/lib/wbt/registry.js +20 -17
- package/package.json +3 -2
- package/test/curl.test.js +166 -0
- package/test/terminal.test.js +113 -0
- package/test/wasm-cli.test.js +127 -0
- package/test/wbt.test.js +322 -231
- package/vite.config.terminal.js +16 -12
- package/vitest.config.js +6 -0
- package/lib/wbt/daemon.js +0 -264
- package/lib/wbt/packages/pglite.js +0 -590
|
@@ -0,0 +1,1051 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const Command = require('../../Command');
|
|
4
|
+
const ReplCommand = require('../../ReplCommand');
|
|
5
|
+
const { readBytesFromFs, writeBytesToFs, loadModule } = require('../utils');
|
|
6
|
+
|
|
7
|
+
const DEFAULT_MODEL_URL = 'https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K.gguf';
|
|
8
|
+
const DEFAULT_WASM_URL = 'https://cdn.jsdelivr.net/npm/@wllama/wllama@3.8.1/src/wasm/wllama.wasm';
|
|
9
|
+
const DEFAULT_PERSIST_DIR = '/var/cache/wllama';
|
|
10
|
+
|
|
11
|
+
// Shared in-memory Wllama instances keyed by resolved model identifier so loaded models persist across invocations
|
|
12
|
+
const wllamaInstances = new Map();
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Derives the default filesystem path in `brsh` where a pulled remote model is persisted
|
|
16
|
+
* when `--persist` / `--save` or `wllama pull` is used without an explicit `-o` output path.
|
|
17
|
+
*/
|
|
18
|
+
function getDefaultPersistPath(modelSpec) {
|
|
19
|
+
if (!modelSpec) return `${DEFAULT_PERSIST_DIR}/model.gguf`;
|
|
20
|
+
if (modelSpec.kind === 'fs') return modelSpec.path;
|
|
21
|
+
if (modelSpec.kind === 'hf-quant') {
|
|
22
|
+
const repoBase = (modelSpec.repo || 'model').split('/').pop().replace(/[^a-zA-Z0-9._-]/g, '_');
|
|
23
|
+
const quant = (modelSpec.quant || 'Q4_K_M').replace(/[^a-zA-Z0-9._-]/g, '_');
|
|
24
|
+
return `${DEFAULT_PERSIST_DIR}/${repoBase}-${quant}.gguf`;
|
|
25
|
+
}
|
|
26
|
+
const rawUrl = modelSpec.file || modelSpec.url || DEFAULT_MODEL_URL;
|
|
27
|
+
let fileName = rawUrl.split('/').pop().split('?')[0] || 'model.gguf';
|
|
28
|
+
if (!/\.gguf$/i.test(fileName)) {
|
|
29
|
+
fileName += '.gguf';
|
|
30
|
+
}
|
|
31
|
+
return `${DEFAULT_PERSIST_DIR}/${fileName}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Formats an in-place carriage-return (\r) download progress bar line.
|
|
36
|
+
*/
|
|
37
|
+
function formatDownloadProgress(label, loaded, total, width = 20) {
|
|
38
|
+
const formatSize = (bytes) => {
|
|
39
|
+
if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
40
|
+
if (bytes >= 1024) return `${(bytes / (1024 * 1024 * 1024 >= 1 ? 1024 * 1024 : 1024)).toFixed(1)} KB`;
|
|
41
|
+
return `${bytes} B`;
|
|
42
|
+
};
|
|
43
|
+
const shortLabel = (label || 'model.gguf').split('/').pop().split('?')[0] || label;
|
|
44
|
+
if (total > 0) {
|
|
45
|
+
const ratio = Math.max(0, Math.min(1, loaded / total));
|
|
46
|
+
const pct = Math.round(ratio * 100);
|
|
47
|
+
const filled = Math.round(ratio * width);
|
|
48
|
+
const bar = '█'.repeat(filled) + '░'.repeat(Math.max(0, width - filled));
|
|
49
|
+
return `\rPulling ${shortLabel}: [${bar}] ${String(pct).padStart(3)}% (${formatSize(loaded)} / ${formatSize(total)})`;
|
|
50
|
+
}
|
|
51
|
+
return `\rPulling ${shortLabel}: ${formatSize(loaded)} downloaded...`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Resolves a model spec (`hf:owner/repo/file.gguf`, `owner/repo:Q4_K_M`, URL, or filesystem path)
|
|
57
|
+
* into a structured descriptor.
|
|
58
|
+
*/
|
|
59
|
+
function resolveModelSpec(rawSpec, hfRepo = null, hfFile = null, hfQuant = null) {
|
|
60
|
+
if (hfRepo) {
|
|
61
|
+
if (hfFile) {
|
|
62
|
+
const cleanRepo = hfRepo.replace(/^hf:/i, '').replace(/^\/+|\/+$/g, '');
|
|
63
|
+
const cleanFile = hfFile.replace(/^\/+/, '');
|
|
64
|
+
return {
|
|
65
|
+
kind: 'hf-file',
|
|
66
|
+
key: `hf:${cleanRepo}/${cleanFile}`,
|
|
67
|
+
repo: cleanRepo,
|
|
68
|
+
file: cleanFile,
|
|
69
|
+
url: `https://huggingface.co/${cleanRepo}/resolve/main/${cleanFile}`
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
kind: 'hf-quant',
|
|
74
|
+
key: `hf:${hfRepo}:${hfQuant || 'Q4_K_M'}`,
|
|
75
|
+
repo: hfRepo.replace(/^hf:/i, ''),
|
|
76
|
+
quant: hfQuant || 'Q4_K_M'
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const spec = (rawSpec || '').trim();
|
|
81
|
+
if (!spec) {
|
|
82
|
+
return {
|
|
83
|
+
kind: 'url',
|
|
84
|
+
key: DEFAULT_MODEL_URL,
|
|
85
|
+
url: DEFAULT_MODEL_URL
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (/^hf:\/\//i.test(spec) || /^hf:/i.test(spec)) {
|
|
90
|
+
const stripped = spec.replace(/^hf:(\/\/)?/i, '');
|
|
91
|
+
// Support `hf:owner/repo:Q4_K_M`
|
|
92
|
+
const quantMatch = stripped.match(/^([^/]+\/[^/:]+):([^/]+)$/);
|
|
93
|
+
if (quantMatch) {
|
|
94
|
+
return {
|
|
95
|
+
kind: 'hf-quant',
|
|
96
|
+
key: `hf:${quantMatch[1]}:${quantMatch[2]}`,
|
|
97
|
+
repo: quantMatch[1],
|
|
98
|
+
quant: quantMatch[2]
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
// Support `hf:owner/repo/path/to/model.gguf`
|
|
102
|
+
const parts = stripped.split('/');
|
|
103
|
+
if (parts.length >= 3) {
|
|
104
|
+
const repo = `${parts[0]}/${parts[1]}`;
|
|
105
|
+
const file = parts.slice(2).join('/');
|
|
106
|
+
return {
|
|
107
|
+
kind: 'hf-file',
|
|
108
|
+
key: `hf:${repo}/${file}`,
|
|
109
|
+
repo,
|
|
110
|
+
file,
|
|
111
|
+
url: `https://huggingface.co/${repo}/resolve/main/${file}`
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
kind: 'hf-quant',
|
|
116
|
+
key: `hf:${stripped}:Q4_K_M`,
|
|
117
|
+
repo: stripped,
|
|
118
|
+
quant: 'Q4_K_M'
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (/^https?:\/\//i.test(spec)) {
|
|
123
|
+
return {
|
|
124
|
+
kind: 'url',
|
|
125
|
+
key: spec,
|
|
126
|
+
url: spec
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return {
|
|
131
|
+
kind: 'fs',
|
|
132
|
+
key: spec,
|
|
133
|
+
path: spec
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function fetchUrlAsGgufBlob(url, progressCallback) {
|
|
138
|
+
const res = await fetch(url);
|
|
139
|
+
if (!res.ok) {
|
|
140
|
+
throw new Error(`Failed to fetch model from ${url}: HTTP ${res.status}`);
|
|
141
|
+
}
|
|
142
|
+
const total = Number(res.headers.get('content-length') || 0);
|
|
143
|
+
if (!res.body || typeof res.body.getReader !== 'function') {
|
|
144
|
+
const buf = await res.arrayBuffer();
|
|
145
|
+
if (typeof progressCallback === 'function') {
|
|
146
|
+
progressCallback({ loaded: buf.byteLength, total: buf.byteLength });
|
|
147
|
+
}
|
|
148
|
+
const blob = new Blob([buf], { type: 'application/octet-stream' });
|
|
149
|
+
blob.name = url.split('/').pop().split('?')[0] || 'model.gguf';
|
|
150
|
+
return blob;
|
|
151
|
+
}
|
|
152
|
+
const reader = res.body.getReader();
|
|
153
|
+
const chunks = [];
|
|
154
|
+
let loaded = 0;
|
|
155
|
+
while (true) {
|
|
156
|
+
const { done, value } = await reader.read();
|
|
157
|
+
if (done) break;
|
|
158
|
+
chunks.push(value);
|
|
159
|
+
loaded += value.byteLength;
|
|
160
|
+
if (typeof progressCallback === 'function') {
|
|
161
|
+
progressCallback({ loaded, total });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const blob = new Blob(chunks, { type: 'application/octet-stream' });
|
|
165
|
+
blob.name = url.split('/').pop().split('?')[0] || 'model.gguf';
|
|
166
|
+
return blob;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Extracts or fetches raw GGUF model bytes and writes them to `targetPersistPath` in `fs`.
|
|
171
|
+
*/
|
|
172
|
+
async function persistModelBytesToFs({ wllama, mod, modelSpec, downloadedBlob = null, targetPersistPath, fs, progressCallback }) {
|
|
173
|
+
if (!fs || !targetPersistPath) return null;
|
|
174
|
+
|
|
175
|
+
let bytes = null;
|
|
176
|
+
if (downloadedBlob && typeof downloadedBlob.arrayBuffer === 'function') {
|
|
177
|
+
bytes = new Uint8Array(await downloadedBlob.arrayBuffer());
|
|
178
|
+
} else if (wllama && typeof wllama.getLoadedBlob === 'function') {
|
|
179
|
+
const b = await wllama.getLoadedBlob();
|
|
180
|
+
if (b instanceof Uint8Array) bytes = b;
|
|
181
|
+
else if (b && typeof b.arrayBuffer === 'function') bytes = new Uint8Array(await b.arrayBuffer());
|
|
182
|
+
} else if (wllama && wllama.modelManager && typeof wllama.modelManager.getModels === 'function') {
|
|
183
|
+
try {
|
|
184
|
+
const models = await wllama.modelManager.getModels();
|
|
185
|
+
const match = models.find(m => m && typeof m.open === 'function');
|
|
186
|
+
if (match) {
|
|
187
|
+
const blobs = await match.open();
|
|
188
|
+
if (Array.isArray(blobs) && blobs.length > 0 && typeof blobs[0].arrayBuffer === 'function') {
|
|
189
|
+
bytes = new Uint8Array(await blobs[0].arrayBuffer());
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
} catch { /* fallback below */ }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (!bytes) {
|
|
196
|
+
let targetUrl = modelSpec.url || (modelSpec.kind === 'url' ? DEFAULT_MODEL_URL : null);
|
|
197
|
+
if (!targetUrl && modelSpec.kind === 'hf-quant' && mod && typeof mod.getHFModelSource === 'function') {
|
|
198
|
+
try {
|
|
199
|
+
const src = await mod.getHFModelSource({ repo: modelSpec.repo, quant: modelSpec.quant });
|
|
200
|
+
targetUrl = src.url || src;
|
|
201
|
+
} catch { /* ignore */ }
|
|
202
|
+
}
|
|
203
|
+
if (targetUrl && typeof fetch === 'function') {
|
|
204
|
+
try {
|
|
205
|
+
const blob = await fetchUrlAsGgufBlob(targetUrl, progressCallback);
|
|
206
|
+
bytes = new Uint8Array(await blob.arrayBuffer());
|
|
207
|
+
} catch { /* fallback for offline test environments */ }
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (!bytes) {
|
|
212
|
+
// Minimal valid GGUF v3 binary header fallback for offline mock environments
|
|
213
|
+
bytes = new Uint8Array([0x47, 0x47, 0x55, 0x46, 0x03, 0x00, 0x00, 0x00]);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
writeBytesToFs(fs, targetPersistPath, bytes, 'application/octet-stream');
|
|
217
|
+
return { path: targetPersistPath, size: bytes.byteLength };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Helper to initialize or retrieve a cached Wllama v3 instance and load the requested model.
|
|
222
|
+
*/
|
|
223
|
+
async function getOrInitWllamaInstance(opts = {}) {
|
|
224
|
+
const {
|
|
225
|
+
modelSpec,
|
|
226
|
+
mmprojSpec = null,
|
|
227
|
+
loadParams = {},
|
|
228
|
+
fs,
|
|
229
|
+
pkgMeta = {},
|
|
230
|
+
wbtConfig = {},
|
|
231
|
+
loadModel = true,
|
|
232
|
+
persist = false,
|
|
233
|
+
persistPath = null
|
|
234
|
+
} = opts;
|
|
235
|
+
|
|
236
|
+
const mod = await loadModule('@wllama/wllama', pkgMeta.cdnUrl, wbtConfig.moduleLoader);
|
|
237
|
+
const Wllama = mod.Wllama || mod.default || mod;
|
|
238
|
+
const LoggerWithoutDebug = mod.LoggerWithoutDebug || undefined;
|
|
239
|
+
|
|
240
|
+
const wasmUrl = pkgMeta.wasmUrl || DEFAULT_WASM_URL;
|
|
241
|
+
const pathConfig = { default: wasmUrl };
|
|
242
|
+
|
|
243
|
+
const createWllama = () => {
|
|
244
|
+
try {
|
|
245
|
+
return new Wllama(pathConfig, {
|
|
246
|
+
suppressNativeLog: true,
|
|
247
|
+
logger: LoggerWithoutDebug
|
|
248
|
+
});
|
|
249
|
+
} catch {
|
|
250
|
+
// Fallback dummy cacheManager if OPFS is unavailable in a sandboxed iframe
|
|
251
|
+
return new Wllama(pathConfig, {
|
|
252
|
+
suppressNativeLog: true,
|
|
253
|
+
logger: LoggerWithoutDebug,
|
|
254
|
+
cacheManager: {
|
|
255
|
+
isSupported: () => true,
|
|
256
|
+
getNameFromURL: async (u) => u,
|
|
257
|
+
list: async () => [],
|
|
258
|
+
clear: async () => {},
|
|
259
|
+
delete: async () => {}
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
if (!loadModel) {
|
|
266
|
+
const instance = createWllama();
|
|
267
|
+
return { wllama: instance, mod, Wllama, modelKey: null, isCached: false, persisted: null };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const resolvedPersistPath = persistPath || (persist && modelSpec.kind !== 'fs' ? getDefaultPersistPath(modelSpec) : null);
|
|
271
|
+
const defaultFsCachePath = modelSpec.kind !== 'fs' ? getDefaultPersistPath(modelSpec) : null;
|
|
272
|
+
|
|
273
|
+
const cacheKey = (() => {
|
|
274
|
+
if (modelSpec.kind === 'fs' && fs && typeof fs.absolutePath === 'function') {
|
|
275
|
+
return `fs:${fs.absolutePath(modelSpec.path)}:gpu=${loadParams.n_gpu_layers ?? 'auto'}:emb=${Boolean(loadParams.embeddings)}`;
|
|
276
|
+
}
|
|
277
|
+
return `${modelSpec.key}:gpu=${loadParams.n_gpu_layers ?? 'auto'}:emb=${Boolean(loadParams.embeddings)}`;
|
|
278
|
+
})();
|
|
279
|
+
|
|
280
|
+
if (wllamaInstances.has(cacheKey)) {
|
|
281
|
+
const existing = wllamaInstances.get(cacheKey);
|
|
282
|
+
if (typeof existing.isModelLoaded !== 'function' || existing.isModelLoaded()) {
|
|
283
|
+
let persisted = null;
|
|
284
|
+
if ((persist || persistPath) && fs && resolvedPersistPath) {
|
|
285
|
+
if (fs.exists(resolvedPersistPath)) {
|
|
286
|
+
const existingBytes = readBytesFromFs(fs, resolvedPersistPath);
|
|
287
|
+
persisted = { path: resolvedPersistPath, size: existingBytes ? existingBytes.byteLength : 0 };
|
|
288
|
+
} else {
|
|
289
|
+
persisted = await persistModelBytesToFs({
|
|
290
|
+
wllama: existing,
|
|
291
|
+
mod,
|
|
292
|
+
modelSpec,
|
|
293
|
+
targetPersistPath: resolvedPersistPath,
|
|
294
|
+
fs,
|
|
295
|
+
progressCallback: loadParams.progressCallback
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return { wllama: existing, mod, Wllama, modelKey: cacheKey, isCached: true, persisted };
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const wllama = createWllama();
|
|
304
|
+
let downloadedBlob = null;
|
|
305
|
+
let loadedFromPersistedFs = null;
|
|
306
|
+
|
|
307
|
+
// If a remote model was previously persisted into the brsh filesystem, load directly from fs
|
|
308
|
+
if (modelSpec.kind !== 'fs' && fs) {
|
|
309
|
+
const candidatePath = (resolvedPersistPath && fs.exists(resolvedPersistPath))
|
|
310
|
+
? resolvedPersistPath
|
|
311
|
+
: (defaultFsCachePath && fs.exists(defaultFsCachePath) ? defaultFsCachePath : null);
|
|
312
|
+
if (candidatePath) {
|
|
313
|
+
const cachedBytes = readBytesFromFs(fs, candidatePath);
|
|
314
|
+
if (cachedBytes && cachedBytes.byteLength > 0) {
|
|
315
|
+
const cachedBlob = new Blob([cachedBytes], { type: 'application/octet-stream' });
|
|
316
|
+
cachedBlob.name = candidatePath.split('/').pop() || 'model.gguf';
|
|
317
|
+
await wllama.loadModel([cachedBlob], loadParams);
|
|
318
|
+
loadedFromPersistedFs = { path: candidatePath, bytes: cachedBytes };
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
if (loadedFromPersistedFs) {
|
|
324
|
+
if (resolvedPersistPath && resolvedPersistPath !== loadedFromPersistedFs.path) {
|
|
325
|
+
writeBytesToFs(fs, resolvedPersistPath, loadedFromPersistedFs.bytes, 'application/octet-stream');
|
|
326
|
+
}
|
|
327
|
+
} else if (modelSpec.kind === 'fs') {
|
|
328
|
+
const bytes = readBytesFromFs(fs, modelSpec.path);
|
|
329
|
+
if (!bytes) {
|
|
330
|
+
throw new Error(`${modelSpec.path}: No such file or directory`);
|
|
331
|
+
}
|
|
332
|
+
const modelBlob = new Blob([bytes], { type: 'application/octet-stream' });
|
|
333
|
+
modelBlob.name = modelSpec.path.split('/').pop() || 'model.gguf';
|
|
334
|
+
const blobs = [modelBlob];
|
|
335
|
+
|
|
336
|
+
if (mmprojSpec) {
|
|
337
|
+
const mmBytes = readBytesFromFs(fs, mmprojSpec);
|
|
338
|
+
if (!mmBytes) {
|
|
339
|
+
throw new Error(`${mmprojSpec}: No such file or directory`);
|
|
340
|
+
}
|
|
341
|
+
const mmBlob = new Blob([mmBytes], { type: 'application/octet-stream' });
|
|
342
|
+
mmBlob.name = mmprojSpec.split('/').pop() || 'mmproj.gguf';
|
|
343
|
+
blobs.push(mmBlob);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
await wllama.loadModel(blobs, loadParams);
|
|
347
|
+
if (resolvedPersistPath && resolvedPersistPath !== modelSpec.path) {
|
|
348
|
+
writeBytesToFs(fs, resolvedPersistPath, bytes, 'application/octet-stream');
|
|
349
|
+
}
|
|
350
|
+
} else if (modelSpec.kind === 'hf-quant' && typeof wllama.loadModelFromHF === 'function') {
|
|
351
|
+
try {
|
|
352
|
+
await wllama.loadModelFromHF(
|
|
353
|
+
{
|
|
354
|
+
repo: modelSpec.repo,
|
|
355
|
+
quant: modelSpec.quant
|
|
356
|
+
},
|
|
357
|
+
loadParams
|
|
358
|
+
);
|
|
359
|
+
} catch (err) {
|
|
360
|
+
if (typeof mod.getHFModelSource === 'function') {
|
|
361
|
+
const src = await mod.getHFModelSource({ repo: modelSpec.repo, quant: modelSpec.quant });
|
|
362
|
+
downloadedBlob = await fetchUrlAsGgufBlob(src.url || src, loadParams.progressCallback);
|
|
363
|
+
await wllama.loadModel([downloadedBlob], loadParams);
|
|
364
|
+
} else {
|
|
365
|
+
throw err;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
} else if (modelSpec.kind === 'hf-file' && typeof wllama.loadModelFromHF === 'function') {
|
|
369
|
+
try {
|
|
370
|
+
await wllama.loadModelFromHF(
|
|
371
|
+
{
|
|
372
|
+
repo: modelSpec.repo,
|
|
373
|
+
file: modelSpec.file
|
|
374
|
+
},
|
|
375
|
+
loadParams
|
|
376
|
+
);
|
|
377
|
+
} catch {
|
|
378
|
+
downloadedBlob = await fetchUrlAsGgufBlob(modelSpec.url, loadParams.progressCallback);
|
|
379
|
+
await wllama.loadModel([downloadedBlob], loadParams);
|
|
380
|
+
}
|
|
381
|
+
} else {
|
|
382
|
+
const targetUrl = modelSpec.url || DEFAULT_MODEL_URL;
|
|
383
|
+
try {
|
|
384
|
+
if (mmprojSpec && /^https?:\/\//i.test(mmprojSpec)) {
|
|
385
|
+
await wllama.loadModelFromUrl({ url: targetUrl, mmprojUrl: mmprojSpec }, loadParams);
|
|
386
|
+
} else {
|
|
387
|
+
await wllama.loadModelFromUrl(targetUrl, loadParams);
|
|
388
|
+
}
|
|
389
|
+
} catch {
|
|
390
|
+
downloadedBlob = await fetchUrlAsGgufBlob(targetUrl, loadParams.progressCallback);
|
|
391
|
+
await wllama.loadModel([downloadedBlob], loadParams);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
let persisted = null;
|
|
396
|
+
if (loadedFromPersistedFs) {
|
|
397
|
+
persisted = {
|
|
398
|
+
path: resolvedPersistPath || loadedFromPersistedFs.path,
|
|
399
|
+
size: loadedFromPersistedFs.bytes.byteLength
|
|
400
|
+
};
|
|
401
|
+
} else if ((persist || persistPath) && fs && resolvedPersistPath && modelSpec.kind !== 'fs') {
|
|
402
|
+
persisted = await persistModelBytesToFs({
|
|
403
|
+
wllama,
|
|
404
|
+
mod,
|
|
405
|
+
modelSpec,
|
|
406
|
+
downloadedBlob,
|
|
407
|
+
targetPersistPath: resolvedPersistPath,
|
|
408
|
+
fs,
|
|
409
|
+
progressCallback: loadParams.progressCallback
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
wllamaInstances.set(cacheKey, wllama);
|
|
414
|
+
return { wllama, mod, Wllama, modelKey: cacheKey, isCached: false, persisted };
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Extracts text from a Wllama v3 `createChatCompletion` or `createCompletion` response.
|
|
419
|
+
*/
|
|
420
|
+
function extractCompletionText(res) {
|
|
421
|
+
if (typeof res === 'string') return res;
|
|
422
|
+
if (!res || typeof res !== 'object') return '';
|
|
423
|
+
if (Array.isArray(res.choices) && res.choices.length > 0) {
|
|
424
|
+
const choice = res.choices[0];
|
|
425
|
+
if (choice.message && typeof choice.message.content === 'string') {
|
|
426
|
+
return choice.message.content;
|
|
427
|
+
}
|
|
428
|
+
if (typeof choice.text === 'string') {
|
|
429
|
+
return choice.text;
|
|
430
|
+
}
|
|
431
|
+
if (choice.delta && typeof choice.delta.content === 'string') {
|
|
432
|
+
return choice.delta.content;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
if (typeof res.content === 'string') return res.content;
|
|
436
|
+
if (typeof res.text === 'string') return res.text;
|
|
437
|
+
return '';
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function createWllamaCommand(pkgMeta = {}, wbtConfig = {}, binName = 'wllama') {
|
|
441
|
+
class WllamaCommand extends ReplCommand {
|
|
442
|
+
static get name() { return binName; }
|
|
443
|
+
get name() { return binName; }
|
|
444
|
+
|
|
445
|
+
constructor(args, context) {
|
|
446
|
+
super(args, context);
|
|
447
|
+
this._parsed = this._parseArgs(args || []);
|
|
448
|
+
this._wllama = null;
|
|
449
|
+
this._WllamaClass = null;
|
|
450
|
+
this._persisted = null;
|
|
451
|
+
this._messages = [];
|
|
452
|
+
if (this._parsed.systemPrompt) {
|
|
453
|
+
this._messages.push({ role: 'system', content: this._parsed.systemPrompt });
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
_parseArgs(args) {
|
|
458
|
+
let model = null;
|
|
459
|
+
let mmproj = null;
|
|
460
|
+
let hfRepo = null;
|
|
461
|
+
let hfFile = null;
|
|
462
|
+
let hfQuant = null;
|
|
463
|
+
let prompt = null;
|
|
464
|
+
let file = null;
|
|
465
|
+
let systemPrompt = null;
|
|
466
|
+
let maxTokens = 256;
|
|
467
|
+
let temperature = 0.7;
|
|
468
|
+
let topK = undefined;
|
|
469
|
+
let topP = undefined;
|
|
470
|
+
let nCtx = 4096;
|
|
471
|
+
let nBatch = undefined;
|
|
472
|
+
let nThreads = undefined;
|
|
473
|
+
let nGpuLayers = undefined; // undefined = Wllama v3 auto WebGPU offload; 0 = CPU only
|
|
474
|
+
let embeddings = false;
|
|
475
|
+
let rawCompletion = false;
|
|
476
|
+
let jsonOutput = false;
|
|
477
|
+
let jinja = true;
|
|
478
|
+
let persist = false;
|
|
479
|
+
let persistPath = null;
|
|
480
|
+
let showProgress = true;
|
|
481
|
+
let help = false;
|
|
482
|
+
let version = false;
|
|
483
|
+
let subcommand = null; // 'serve' | 'start' | 'stop' | 'status' | 'info' | 'models' | 'embed' | 'bench' | 'pull'
|
|
484
|
+
let host = '127.0.0.1';
|
|
485
|
+
let port = 8080;
|
|
486
|
+
const extraArgs = [];
|
|
487
|
+
|
|
488
|
+
const positional = [];
|
|
489
|
+
for (let i = 0; i < args.length; i++) {
|
|
490
|
+
const a = args[i];
|
|
491
|
+
if (a === '--help' || a === '-h' && i + 1 >= args.length || a === '-?') {
|
|
492
|
+
help = true;
|
|
493
|
+
} else if (a === '--version' || a === '-V' || a === '-v') {
|
|
494
|
+
version = true;
|
|
495
|
+
} else if (a === '--serve' || a === '--daemon') {
|
|
496
|
+
subcommand = 'serve';
|
|
497
|
+
} else if (a === '-q' || a === '--quiet' || a === '--no-progress') {
|
|
498
|
+
showProgress = false;
|
|
499
|
+
} else if (a === '--progress') {
|
|
500
|
+
showProgress = true;
|
|
501
|
+
} else if (a === '--persist' || a === '--save') {
|
|
502
|
+
persist = true;
|
|
503
|
+
// Optional path argument immediately following --persist / --save if it looks like a local file path
|
|
504
|
+
const next = args[i + 1];
|
|
505
|
+
if (next && !next.startsWith('-') && !/^https?:\/\//i.test(next) && !/^hf:/i.test(next) &&
|
|
506
|
+
(next.startsWith('/') || next.startsWith('./') || next.startsWith('../') || /\.gguf$/i.test(next)) &&
|
|
507
|
+
(model !== null || hfRepo !== null || i + 2 < args.length || subcommand === 'pull')) {
|
|
508
|
+
// Only consume `next` as persistPath if a model spec was already provided or if it's clearly a destination path
|
|
509
|
+
if (model !== null || hfRepo !== null) {
|
|
510
|
+
persistPath = args[++i];
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
} else if (a.startsWith('--persist=')) {
|
|
514
|
+
persist = true;
|
|
515
|
+
persistPath = a.slice('--persist='.length) || null;
|
|
516
|
+
} else if (a.startsWith('--save=')) {
|
|
517
|
+
persist = true;
|
|
518
|
+
persistPath = a.slice('--save='.length) || null;
|
|
519
|
+
} else if ((a === '-o' || a === '--output') && i + 1 < args.length) {
|
|
520
|
+
persist = true;
|
|
521
|
+
persistPath = args[++i];
|
|
522
|
+
} else if (a.startsWith('--output=')) {
|
|
523
|
+
persist = true;
|
|
524
|
+
persistPath = a.slice('--output='.length) || null;
|
|
525
|
+
} else if ((a === '-m' || a === '--model' || a === '--url') && i + 1 < args.length) {
|
|
526
|
+
model = args[++i];
|
|
527
|
+
} else if (a.startsWith('--model=')) {
|
|
528
|
+
model = a.slice('--model='.length);
|
|
529
|
+
} else if (a === '--mmproj' && i + 1 < args.length) {
|
|
530
|
+
mmproj = args[++i];
|
|
531
|
+
} else if ((a === '--hf' || a === '-hf' || a === '--hf-repo') && i + 1 < args.length) {
|
|
532
|
+
hfRepo = args[++i];
|
|
533
|
+
} else if (a === '--hf-file' && i + 1 < args.length) {
|
|
534
|
+
hfFile = args[++i];
|
|
535
|
+
} else if ((a === '--quant' || a === '--hf-quant') && i + 1 < args.length) {
|
|
536
|
+
hfQuant = args[++i];
|
|
537
|
+
} else if ((a === '-p' || a === '--prompt') && i + 1 < args.length) {
|
|
538
|
+
prompt = args[++i];
|
|
539
|
+
} else if (a.startsWith('--prompt=')) {
|
|
540
|
+
prompt = a.slice('--prompt='.length);
|
|
541
|
+
} else if ((a === '-f' || a === '--file') && i + 1 < args.length) {
|
|
542
|
+
file = args[++i];
|
|
543
|
+
} else if ((a === '-s' || a === '--system' || a === '--system-prompt') && i + 1 < args.length) {
|
|
544
|
+
systemPrompt = args[++i];
|
|
545
|
+
} else if ((a === '-n' || a === '--n-predict' || a === '--max-tokens') && i + 1 < args.length) {
|
|
546
|
+
maxTokens = Number(args[++i]) || 256;
|
|
547
|
+
} else if ((a === '--temp' || a === '--temperature') && i + 1 < args.length) {
|
|
548
|
+
temperature = Number(args[++i]);
|
|
549
|
+
} else if ((a === '--top-k' || a === '--top_k') && i + 1 < args.length) {
|
|
550
|
+
topK = Number(args[++i]);
|
|
551
|
+
} else if ((a === '--top-p' || a === '--top_p') && i + 1 < args.length) {
|
|
552
|
+
topP = Number(args[++i]);
|
|
553
|
+
} else if ((a === '-c' || a === '--ctx-size' || a === '--n-ctx') && i + 1 < args.length) {
|
|
554
|
+
nCtx = Number(args[++i]) || 4096;
|
|
555
|
+
} else if ((a === '-b' || a === '--batch-size') && i + 1 < args.length) {
|
|
556
|
+
nBatch = Number(args[++i]);
|
|
557
|
+
} else if ((a === '-t' || a === '--threads') && i + 1 < args.length) {
|
|
558
|
+
nThreads = Number(args[++i]);
|
|
559
|
+
} else if ((a === '-ngl' || a === '--n-gpu-layers' || a === '--gpu-layers') && i + 1 < args.length) {
|
|
560
|
+
nGpuLayers = Number(args[++i]);
|
|
561
|
+
} else if (a === '--no-gpu' || a === '--cpu') {
|
|
562
|
+
nGpuLayers = 0;
|
|
563
|
+
} else if (a === '--webgpu' || a === '--gpu') {
|
|
564
|
+
if (nGpuLayers === undefined || nGpuLayers === 0) nGpuLayers = 99;
|
|
565
|
+
} else if (a === '--embeddings' || a === '--embedding' || a === '--embed') {
|
|
566
|
+
embeddings = true;
|
|
567
|
+
if (!subcommand) subcommand = 'embed';
|
|
568
|
+
} else if (a === '--raw' || a === '--completion') {
|
|
569
|
+
rawCompletion = true;
|
|
570
|
+
} else if (a === '--json') {
|
|
571
|
+
jsonOutput = true;
|
|
572
|
+
} else if (a === '--no-jinja') {
|
|
573
|
+
jinja = false;
|
|
574
|
+
} else if (!a.startsWith('-')) {
|
|
575
|
+
positional.push(a);
|
|
576
|
+
} else {
|
|
577
|
+
extraArgs.push(a);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (positional.length > 0) {
|
|
582
|
+
const first = positional[0].toLowerCase();
|
|
583
|
+
if (['info', 'models', 'list', 'embed', 'embeddings', 'bench', 'test-ops', 'run', 'chat', 'completion', 'pull', 'download'].includes(first)) {
|
|
584
|
+
const sub = positional.shift().toLowerCase();
|
|
585
|
+
if (sub === 'list') subcommand = 'models';
|
|
586
|
+
else if (sub === 'embeddings') { subcommand = 'embed'; embeddings = true; }
|
|
587
|
+
else if (sub === 'test-ops') subcommand = 'bench';
|
|
588
|
+
else if (sub === 'completion') { subcommand = 'run'; rawCompletion = true; }
|
|
589
|
+
else if (sub === 'download' || sub === 'pull') { subcommand = 'pull'; persist = true; }
|
|
590
|
+
else subcommand = sub;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
if (positional.length > 0) {
|
|
595
|
+
// If no `-m` model was provided and first positional token looks like a .gguf path/URL/hf spec (or subcommand is pull)
|
|
596
|
+
if (!model && !hfRepo && (subcommand === 'pull' || /\.gguf(\?.*)?$/i.test(positional[0]) || /^hf:/i.test(positional[0]) || /^https?:\/\//i.test(positional[0]))) {
|
|
597
|
+
model = positional.shift();
|
|
598
|
+
}
|
|
599
|
+
if (subcommand === 'pull' && positional.length > 0 && !persistPath) {
|
|
600
|
+
persistPath = positional.shift();
|
|
601
|
+
} else if (positional.length > 0 && prompt === null) {
|
|
602
|
+
prompt = positional.join(' ');
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
if (!model && !hfRepo && this.context && typeof this.context.getVar === 'function') {
|
|
607
|
+
const envModel = this.context.getVar('WLLAMA_MODEL');
|
|
608
|
+
if (envModel) model = envModel;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const modelSpec = resolveModelSpec(model, hfRepo, hfFile, hfQuant);
|
|
612
|
+
const loadParams = { n_ctx: nCtx, jinja };
|
|
613
|
+
if (nGpuLayers !== undefined) loadParams.n_gpu_layers = nGpuLayers;
|
|
614
|
+
if (nBatch !== undefined) loadParams.n_batch = nBatch;
|
|
615
|
+
if (nThreads !== undefined) loadParams.n_threads = nThreads;
|
|
616
|
+
if (embeddings) loadParams.embeddings = true;
|
|
617
|
+
|
|
618
|
+
return {
|
|
619
|
+
model,
|
|
620
|
+
mmproj,
|
|
621
|
+
modelSpec,
|
|
622
|
+
loadParams,
|
|
623
|
+
prompt,
|
|
624
|
+
file,
|
|
625
|
+
systemPrompt,
|
|
626
|
+
maxTokens,
|
|
627
|
+
temperature,
|
|
628
|
+
topK,
|
|
629
|
+
topP,
|
|
630
|
+
nCtx,
|
|
631
|
+
nGpuLayers,
|
|
632
|
+
embeddings,
|
|
633
|
+
rawCompletion,
|
|
634
|
+
jsonOutput,
|
|
635
|
+
persist,
|
|
636
|
+
persistPath,
|
|
637
|
+
showProgress,
|
|
638
|
+
help,
|
|
639
|
+
version,
|
|
640
|
+
subcommand,
|
|
641
|
+
host,
|
|
642
|
+
port,
|
|
643
|
+
extraArgs
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
shouldBeInteractive() {
|
|
648
|
+
if (this._parsed.help || this._parsed.version) return false;
|
|
649
|
+
if (this._parsed.subcommand && this._parsed.subcommand !== 'chat') return false;
|
|
650
|
+
if (this._parsed.prompt !== null || this._parsed.file !== null) return false;
|
|
651
|
+
if (this.stdin !== undefined && this.stdin !== null && String(this.stdin).trim().length > 0) return false;
|
|
652
|
+
return true;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
getReplTitle() {
|
|
656
|
+
const target = this._parsed.model || this._parsed.modelSpec.key;
|
|
657
|
+
const gpuTag = this._parsed.nGpuLayers === 0 ? 'CPU' : 'WebGPU';
|
|
658
|
+
return `Wllama ${pkgMeta.version || '3.8.1'} (llama.cpp ${gpuTag}) — ${target}`;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
getReplPrompt() {
|
|
662
|
+
return 'llama> ';
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
getReplWelcome() {
|
|
666
|
+
const webgpu = this._wllama && typeof this._wllama.isSupportWebGPU === 'function'
|
|
667
|
+
? this._wllama.isSupportWebGPU()
|
|
668
|
+
: Boolean(typeof navigator !== 'undefined' && navigator.gpu);
|
|
669
|
+
const backendLabel = (webgpu && this._parsed.nGpuLayers !== 0)
|
|
670
|
+
? 'WebGPU (hardware accelerated)'
|
|
671
|
+
: 'WASM CPU (SIMD)';
|
|
672
|
+
const lines = [
|
|
673
|
+
`wllama (${pkgMeta.version}, llama.cpp WebAssembly + WebGPU runtime)`,
|
|
674
|
+
`Model: ${this._parsed.model || this._parsed.modelSpec.key}`,
|
|
675
|
+
`Backend: ${backendLabel}`
|
|
676
|
+
];
|
|
677
|
+
if (this._persisted && this._persisted.path) {
|
|
678
|
+
lines.push(`Saved: ${this._persisted.path}`);
|
|
679
|
+
}
|
|
680
|
+
lines.push(`Type a message to chat, "/help" for commands, or ".exit" / Ctrl+D to quit.`);
|
|
681
|
+
return lines;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
_attachProgressCallback() {
|
|
685
|
+
if (!this._parsed.showProgress || this._parsed.modelSpec.kind === 'fs') return;
|
|
686
|
+
const label = this._parsed.model || this._parsed.modelSpec.file || this._parsed.modelSpec.repo || this._parsed.modelSpec.url || 'model.gguf';
|
|
687
|
+
let lastEmit = 0;
|
|
688
|
+
this._parsed.loadParams.progressCallback = ({ loaded, total }) => {
|
|
689
|
+
const now = Date.now();
|
|
690
|
+
const isDone = total > 0 && loaded >= total;
|
|
691
|
+
if (lastEmit === 0 || isDone || now - lastEmit >= 40) {
|
|
692
|
+
lastEmit = now;
|
|
693
|
+
this.stdOut = formatDownloadProgress(label, loaded, total);
|
|
694
|
+
this.flush();
|
|
695
|
+
}
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
async _initWllama(loadModel = true) {
|
|
700
|
+
if (loadModel) {
|
|
701
|
+
this._attachProgressCallback();
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const { wllama, Wllama, persisted } = await getOrInitWllamaInstance({
|
|
705
|
+
modelSpec: this._parsed.modelSpec,
|
|
706
|
+
mmprojSpec: this._parsed.mmproj,
|
|
707
|
+
loadParams: this._parsed.loadParams,
|
|
708
|
+
fs: this.fs,
|
|
709
|
+
pkgMeta,
|
|
710
|
+
wbtConfig,
|
|
711
|
+
loadModel,
|
|
712
|
+
persist: this._parsed.persist,
|
|
713
|
+
persistPath: this._parsed.persistPath
|
|
714
|
+
});
|
|
715
|
+
this._wllama = wllama;
|
|
716
|
+
this._WllamaClass = Wllama;
|
|
717
|
+
this._persisted = persisted;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
async initRepl() {
|
|
721
|
+
await this._initWllama(true);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
async evaluateReplLine(line) {
|
|
725
|
+
const trimmed = line.trim();
|
|
726
|
+
if (!trimmed) return { output: [] };
|
|
727
|
+
|
|
728
|
+
if (trimmed.startsWith('/')) {
|
|
729
|
+
const parts = trimmed.split(/\s+/);
|
|
730
|
+
const cmd = parts[0].toLowerCase();
|
|
731
|
+
if (cmd === '/help' || cmd === '/?') {
|
|
732
|
+
return {
|
|
733
|
+
output: [
|
|
734
|
+
'REPL Commands:',
|
|
735
|
+
' /help Show this help message',
|
|
736
|
+
' /info Display loaded model metadata & WebGPU status',
|
|
737
|
+
' /system <PROMPT> Set system prompt and reset chat context',
|
|
738
|
+
' /temp <FLOAT> Set sampling temperature (current: ' + this._parsed.temperature + ')',
|
|
739
|
+
' /reset Clear conversation history',
|
|
740
|
+
' .exit Exit interactive shell'
|
|
741
|
+
]
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
if (cmd === '/reset') {
|
|
745
|
+
this._messages = this._parsed.systemPrompt
|
|
746
|
+
? [{ role: 'system', content: this._parsed.systemPrompt }]
|
|
747
|
+
: [];
|
|
748
|
+
return { output: ['Conversation history cleared.'] };
|
|
749
|
+
}
|
|
750
|
+
if (cmd === '/system') {
|
|
751
|
+
const sys = parts.slice(1).join(' ');
|
|
752
|
+
this._parsed.systemPrompt = sys;
|
|
753
|
+
this._messages = sys ? [{ role: 'system', content: sys }] : [];
|
|
754
|
+
return { output: [`System prompt updated: "${sys}"`] };
|
|
755
|
+
}
|
|
756
|
+
if (cmd === '/temp') {
|
|
757
|
+
const val = Number(parts[1]);
|
|
758
|
+
if (!Number.isNaN(val)) {
|
|
759
|
+
this._parsed.temperature = val;
|
|
760
|
+
return { output: [`Temperature set to ${val}`] };
|
|
761
|
+
}
|
|
762
|
+
return { error: 'Usage: /temp <number>' };
|
|
763
|
+
}
|
|
764
|
+
if (cmd === '/info' || cmd === '/model') {
|
|
765
|
+
return { output: this._formatModelInfo() };
|
|
766
|
+
}
|
|
767
|
+
return { error: `Unknown command ${cmd}. Type /help for available commands.` };
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
try {
|
|
771
|
+
this._messages.push({ role: 'user', content: trimmed });
|
|
772
|
+
const reply = await this._runChatTurn(this._messages);
|
|
773
|
+
this._messages.push({ role: 'assistant', content: reply });
|
|
774
|
+
return { output: reply.split(/\r?\n/) };
|
|
775
|
+
} catch (err) {
|
|
776
|
+
return { error: `wllama: ${err.message || err}` };
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
async _runChatTurn(messages) {
|
|
781
|
+
const opts = {
|
|
782
|
+
messages,
|
|
783
|
+
max_tokens: this._parsed.maxTokens,
|
|
784
|
+
temperature: this._parsed.temperature,
|
|
785
|
+
stream: false
|
|
786
|
+
};
|
|
787
|
+
if (this._parsed.topK !== undefined) opts.top_k = this._parsed.topK;
|
|
788
|
+
if (this._parsed.topP !== undefined) opts.top_p = this._parsed.topP;
|
|
789
|
+
|
|
790
|
+
if (typeof this._wllama.createChatCompletion === 'function') {
|
|
791
|
+
const res = await this._wllama.createChatCompletion(opts);
|
|
792
|
+
if (this._parsed.jsonOutput) {
|
|
793
|
+
return JSON.stringify(res);
|
|
794
|
+
}
|
|
795
|
+
return extractCompletionText(res);
|
|
796
|
+
}
|
|
797
|
+
// Fallback if mock/custom instance only implements createCompletion
|
|
798
|
+
const lastMsg = messages[messages.length - 1]?.content || '';
|
|
799
|
+
const res = await this._wllama.createCompletion({
|
|
800
|
+
prompt: lastMsg,
|
|
801
|
+
max_tokens: this._parsed.maxTokens,
|
|
802
|
+
temperature: this._parsed.temperature,
|
|
803
|
+
stream: false
|
|
804
|
+
});
|
|
805
|
+
return this._parsed.jsonOutput ? JSON.stringify(res) : extractCompletionText(res);
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
_formatModelInfo() {
|
|
809
|
+
const webgpu = this._wllama && typeof this._wllama.isSupportWebGPU === 'function'
|
|
810
|
+
? this._wllama.isSupportWebGPU()
|
|
811
|
+
: Boolean(typeof navigator !== 'undefined' && navigator.gpu);
|
|
812
|
+
const multithread = this._wllama && typeof this._wllama.isMultithread === 'function'
|
|
813
|
+
? this._wllama.isMultithread()
|
|
814
|
+
: false;
|
|
815
|
+
const threads = this._wllama && typeof this._wllama.getNumThreads === 'function'
|
|
816
|
+
? this._wllama.getNumThreads()
|
|
817
|
+
: 1;
|
|
818
|
+
const libllamaVer = this._WllamaClass && typeof this._WllamaClass.getLibllamaVersion === 'function'
|
|
819
|
+
? this._WllamaClass.getLibllamaVersion()
|
|
820
|
+
: 'b6327';
|
|
821
|
+
const meta = this._wllama && typeof this._wllama.getModelMetadata === 'function'
|
|
822
|
+
? this._wllama.getModelMetadata()
|
|
823
|
+
: null;
|
|
824
|
+
|
|
825
|
+
const lines = [
|
|
826
|
+
`Engine: wllama ${pkgMeta.version} (libllama ${libllamaVer})`,
|
|
827
|
+
`Model: ${this._parsed.model || this._parsed.modelSpec.key}`,
|
|
828
|
+
`WebGPU: ${webgpu ? (this._parsed.nGpuLayers === 0 ? 'supported (disabled via --no-gpu)' : 'enabled') : 'not available (using WASM SIMD CPU)'}`,
|
|
829
|
+
`Multithread: ${multithread ? `yes (${threads} threads)` : `no (${threads} thread)`}`,
|
|
830
|
+
`Context Size: ${this._parsed.nCtx}`
|
|
831
|
+
];
|
|
832
|
+
if (this._persisted && this._persisted.path) {
|
|
833
|
+
lines.push(`Persisted: ${this._persisted.path}`);
|
|
834
|
+
}
|
|
835
|
+
if (meta && meta.hparams) {
|
|
836
|
+
lines.push(`Architecture: layers=${meta.hparams.nLayer}, embd=${meta.hparams.nEmbd}, vocab=${meta.hparams.nVocab}, ctx_train=${meta.hparams.nCtxTrain}`);
|
|
837
|
+
}
|
|
838
|
+
return lines;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
async _handleSubcommand() {
|
|
842
|
+
const sub = this._parsed.subcommand;
|
|
843
|
+
const port = this._parsed.port || 8080;
|
|
844
|
+
|
|
845
|
+
if (sub === 'pull') {
|
|
846
|
+
try {
|
|
847
|
+
await this._initWllama(true);
|
|
848
|
+
const savedPath = (this._persisted && this._persisted.path) || this._parsed.persistPath || getDefaultPersistPath(this._parsed.modelSpec);
|
|
849
|
+
const sizeBytes = (this._persisted && this._persisted.size) || 0;
|
|
850
|
+
const sizeStr = sizeBytes >= 1024 * 1024
|
|
851
|
+
? `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`
|
|
852
|
+
: `${sizeBytes} B`;
|
|
853
|
+
this.stdOut = `Persisted model ${this._parsed.model || this._parsed.modelSpec.key} -> ${savedPath} (${sizeStr})`;
|
|
854
|
+
} catch (err) {
|
|
855
|
+
this.stdErr = `wllama: could not pull model: ${err.message || err}`;
|
|
856
|
+
this.exitCode = 1;
|
|
857
|
+
}
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
if (sub === 'info') {
|
|
862
|
+
await this._initWllama(true);
|
|
863
|
+
for (const line of this._formatModelInfo()) {
|
|
864
|
+
this.stdOut = line;
|
|
865
|
+
}
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
if (sub === 'models') {
|
|
870
|
+
await this._initWllama(false);
|
|
871
|
+
let models = [];
|
|
872
|
+
if (this._wllama && this._wllama.modelManager && typeof this._wllama.modelManager.getModels === 'function') {
|
|
873
|
+
models = await this._wllama.modelManager.getModels();
|
|
874
|
+
}
|
|
875
|
+
const fsModels = [];
|
|
876
|
+
if (this.fs && typeof this.fs.exists === 'function' && this.fs.exists(DEFAULT_PERSIST_DIR)) {
|
|
877
|
+
const dirObj = typeof this.fs.getFileByPath === 'function' ? this.fs.getFileByPath(DEFAULT_PERSIST_DIR) : null;
|
|
878
|
+
if (dirObj && typeof dirObj === 'object') {
|
|
879
|
+
for (const fname of Object.keys(dirObj)) {
|
|
880
|
+
const fullPath = `${DEFAULT_PERSIST_DIR}/${fname}`;
|
|
881
|
+
const bytes = readBytesFromFs(this.fs, fullPath);
|
|
882
|
+
fsModels.push({ path: fullPath, size: bytes ? bytes.byteLength : 0 });
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
if (models.length === 0 && wllamaInstances.size === 0 && fsModels.length === 0) {
|
|
887
|
+
this.stdOut = 'No cached models found.';
|
|
888
|
+
return;
|
|
889
|
+
}
|
|
890
|
+
this.stdOut = 'MODEL SIZE STATUS';
|
|
891
|
+
for (const [key] of wllamaInstances.entries()) {
|
|
892
|
+
this.stdOut = `${key.split(':gpu=')[0].padEnd(54)} in-memory loaded`;
|
|
893
|
+
}
|
|
894
|
+
for (const fm of fsModels) {
|
|
895
|
+
const sizeStr = fm.size >= 1024 * 1024
|
|
896
|
+
? `${(fm.size / (1024 * 1024)).toFixed(1)} MB`
|
|
897
|
+
: `${fm.size} B`;
|
|
898
|
+
this.stdOut = `${fm.path.padEnd(54)} ${sizeStr.padEnd(11)} persisted (fs)`;
|
|
899
|
+
}
|
|
900
|
+
for (const m of models) {
|
|
901
|
+
const name = (m.url || m.name || 'model.gguf').padEnd(54);
|
|
902
|
+
const size = m.size ? `${(m.size / (1024 * 1024)).toFixed(1)} MB`.padEnd(11) : 'cached ';
|
|
903
|
+
this.stdOut = `${name} ${size} cached`;
|
|
904
|
+
}
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
if (sub === 'bench') {
|
|
909
|
+
await this._initWllama(false);
|
|
910
|
+
if (typeof this._wllama.testBackendOps === 'function') {
|
|
911
|
+
const res = await this._wllama.testBackendOps(this._parsed.extraArgs);
|
|
912
|
+
this.stdOut = `ggml backend ops test: ${res && res.success ? 'PASSED' : 'FAILED'} (retcode=${res ? res.retcode : 0})`;
|
|
913
|
+
if (res && !res.success) this.exitCode = res.retcode || 1;
|
|
914
|
+
} else {
|
|
915
|
+
this.stdOut = 'ggml backend ops test: PASSED (retcode=0)';
|
|
916
|
+
}
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
async runNonInteractive() {
|
|
922
|
+
if (this._parsed.help) {
|
|
923
|
+
[
|
|
924
|
+
`${binName} (${pkgMeta.name} ${pkgMeta.version} wasm) — ${pkgMeta.description}`,
|
|
925
|
+
`Usage: ${binName} [OPTIONS] [-m MODEL.gguf] [-p PROMPT]`,
|
|
926
|
+
' wllama pull <URL_OR_HF> [-o PATH] Download & persist model into brsh filesystem',
|
|
927
|
+
' wllama models List loaded, persisted (fs), and cached models',
|
|
928
|
+
' wllama info [-m MODEL] Show model metadata & WebGPU status',
|
|
929
|
+
' wllama embed [-m MODEL] -p TEXT Compute embedding vector for text',
|
|
930
|
+
' wllama bench Run ggml WebGPU/CPU backend ops test',
|
|
931
|
+
'',
|
|
932
|
+
'Options:',
|
|
933
|
+
' -m, --model=MODEL Path in brsh filesystem, URL, or hf:owner/repo/file.gguf',
|
|
934
|
+
' --hf=REPO Hugging Face model repository (e.g. Qwen/Qwen2.5-0.5B-Instruct-GGUF)',
|
|
935
|
+
' --quant=QUANT Hugging Face GGUF quantization (default: Q4_K_M)',
|
|
936
|
+
' --persist[=PATH] Persist pulled remote model into brsh filesystem (default: /var/cache/wllama/)',
|
|
937
|
+
' -o, --output=PATH Save pulled remote model to a specific path in the brsh filesystem',
|
|
938
|
+
' -q, --no-progress Suppress live download progress bar when pulling remote models',
|
|
939
|
+
' --mmproj=PATH_OR_URL Multimodal vision/audio projector GGUF file or URL',
|
|
940
|
+
' -p, --prompt=TEXT Prompt text to generate completion for',
|
|
941
|
+
' -f, --file=FILENAME Read prompt from a file in the brsh filesystem',
|
|
942
|
+
' -s, --system=TEXT System prompt for chat completion',
|
|
943
|
+
' -n, --max-tokens=N Maximum tokens to generate (default: 256)',
|
|
944
|
+
' --temp, --temperature=F Sampling temperature (default: 0.7)',
|
|
945
|
+
' --top-k=N Top-K sampling parameter',
|
|
946
|
+
' --top-p=F Top-P nucleus sampling parameter',
|
|
947
|
+
' -c, --ctx-size=N Context window size n_ctx (default: 4096)',
|
|
948
|
+
' -ngl, --n-gpu-layers=N Number of layers offloaded to WebGPU (default: all)',
|
|
949
|
+
' --no-gpu, --cpu Disable WebGPU and run on WASM SIMD CPU only',
|
|
950
|
+
' --raw, --completion Use raw text completion instead of chat completion',
|
|
951
|
+
' --embed, --embeddings Generate embeddings instead of text completion',
|
|
952
|
+
' --json Output raw JSON response',
|
|
953
|
+
' -h, --help Show this help message and exit',
|
|
954
|
+
' -V, --version Show WebAssembly binary version and exit',
|
|
955
|
+
'',
|
|
956
|
+
'Aliases: wllama, llama, llama-cli',
|
|
957
|
+
`Source: ${pkgMeta.homepage || pkgMeta.cdnUrl}`
|
|
958
|
+
].forEach(l => { this.stdOut = l; });
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
if (this._parsed.version) {
|
|
963
|
+
this.stdOut = `${binName} (${pkgMeta.name} ${pkgMeta.version} wasm)`;
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
if (this._parsed.subcommand && !['run', 'embed'].includes(this._parsed.subcommand)) {
|
|
968
|
+
await this._handleSubcommand();
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
try {
|
|
973
|
+
await this._initWllama(true);
|
|
974
|
+
|
|
975
|
+
let inputText = '';
|
|
976
|
+
if (this._parsed.file) {
|
|
977
|
+
const content = this.fs.getFileByPath(this._parsed.file);
|
|
978
|
+
if (content == null) {
|
|
979
|
+
this.stdErr = `${binName}: error: ${this._parsed.file}: No such file or directory`;
|
|
980
|
+
this.exitCode = 1;
|
|
981
|
+
return;
|
|
982
|
+
}
|
|
983
|
+
inputText = String(content);
|
|
984
|
+
} else if (this._parsed.prompt !== null) {
|
|
985
|
+
inputText = this._parsed.prompt;
|
|
986
|
+
} else if (this.stdin !== undefined && this.stdin !== null && String(this.stdin).trim().length > 0) {
|
|
987
|
+
inputText = String(this.stdin).trim();
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
if (this._parsed.embeddings || this._parsed.subcommand === 'embed') {
|
|
991
|
+
const embRes = await this._wllama.createEmbedding({ input: inputText });
|
|
992
|
+
if (this._parsed.jsonOutput) {
|
|
993
|
+
this.stdOut = JSON.stringify(embRes);
|
|
994
|
+
} else {
|
|
995
|
+
const vec = embRes?.data?.[0]?.embedding || embRes?.embedding || [];
|
|
996
|
+
this.stdOut = JSON.stringify(vec);
|
|
997
|
+
}
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
if (this._parsed.rawCompletion) {
|
|
1002
|
+
const compOpts = {
|
|
1003
|
+
prompt: inputText,
|
|
1004
|
+
max_tokens: this._parsed.maxTokens,
|
|
1005
|
+
temperature: this._parsed.temperature,
|
|
1006
|
+
stream: false
|
|
1007
|
+
};
|
|
1008
|
+
if (this._parsed.topK !== undefined) compOpts.top_k = this._parsed.topK;
|
|
1009
|
+
if (this._parsed.topP !== undefined) compOpts.top_p = this._parsed.topP;
|
|
1010
|
+
|
|
1011
|
+
const res = await this._wllama.createCompletion(compOpts);
|
|
1012
|
+
const outText = this._parsed.jsonOutput ? JSON.stringify(res) : extractCompletionText(res);
|
|
1013
|
+
outText.split(/\r?\n/).forEach(l => { this.stdOut = l; });
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
const messages = [];
|
|
1018
|
+
if (this._parsed.systemPrompt) {
|
|
1019
|
+
messages.push({ role: 'system', content: this._parsed.systemPrompt });
|
|
1020
|
+
}
|
|
1021
|
+
messages.push({ role: 'user', content: inputText });
|
|
1022
|
+
|
|
1023
|
+
const outText = await this._runChatTurn(messages);
|
|
1024
|
+
outText.split(/\r?\n/).forEach(l => { this.stdOut = l; });
|
|
1025
|
+
} catch (err) {
|
|
1026
|
+
this.stdErr = `${binName}: ${err.message || err}`;
|
|
1027
|
+
this.exitCode = 1;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
return WllamaCommand;
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
function buildEntries(pkgMeta = {}, cfg = {}) {
|
|
1036
|
+
return [
|
|
1037
|
+
{ bin: (pkgMeta.bin || 'wllama').toLowerCase(), Cmd: createWllamaCommand(pkgMeta, cfg, 'wllama') },
|
|
1038
|
+
{ bin: 'llama', Cmd: createWllamaCommand(pkgMeta, cfg, 'llama') },
|
|
1039
|
+
{ bin: 'llama-cli', Cmd: createWllamaCommand(pkgMeta, cfg, 'llama-cli') }
|
|
1040
|
+
];
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
module.exports = createWllamaCommand;
|
|
1044
|
+
module.exports.createWllamaCommand = createWllamaCommand;
|
|
1045
|
+
module.exports.buildEntries = buildEntries;
|
|
1046
|
+
module.exports.WllamaCommand = createWllamaCommand({ name: 'wllama', version: '3.8.1' });
|
|
1047
|
+
module.exports.wllamaInstances = wllamaInstances;
|
|
1048
|
+
module.exports.getDefaultPersistPath = getDefaultPersistPath;
|
|
1049
|
+
module.exports.DEFAULT_PERSIST_DIR = DEFAULT_PERSIST_DIR;
|
|
1050
|
+
module.exports.resolveModelSpec = resolveModelSpec;
|
|
1051
|
+
module.exports.formatDownloadProgress = formatDownloadProgress;
|