@openclaw/llama-cpp-provider 2026.7.2-beta.2 → 2026.7.2-beta.3

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/README.md CHANGED
@@ -1,8 +1,9 @@
1
1
  # @openclaw/llama-cpp-provider
2
2
 
3
- Official llama.cpp embedding provider for OpenClaw.
3
+ Official llama.cpp text-inference and embedding provider for OpenClaw.
4
4
 
5
- This plugin runs local GGUF embedding models through `node-llama-cpp`.
5
+ This plugin runs local GGUF chat and embedding models in-process through
6
+ `node-llama-cpp`.
6
7
 
7
8
  ## Install
8
9
 
@@ -13,7 +14,22 @@ openclaw plugins install @openclaw/llama-cpp-provider
13
14
  Restart the Gateway after installing or updating the plugin. Use Node 24 for
14
15
  native installs and updates.
15
16
 
16
- ## Configure
17
+ ## Configure text inference
18
+
19
+ Choose **Local model (llama.cpp)** during onboarding. After explicit consent,
20
+ OpenClaw downloads Gemma 4 E4B IT Q4_K_M (approximately 5.0 GB) as the default.
21
+ The bundled download is offered only on machines with at least 16 GiB of RAM.
22
+ Discovery never downloads a model.
23
+
24
+ On smaller machines, use Ollama or LM Studio with a smaller model, use a cloud
25
+ provider, or configure any custom GGUF through `params.modelPath`. The 16 GiB
26
+ gate applies only to OpenClaw's bundled default download; custom GGUF models
27
+ remain available on any machine.
28
+
29
+ See the [llama.cpp provider guide](https://docs.openclaw.ai/plugins/llama-cpp)
30
+ for custom GGUF model configuration and hardware guidance.
31
+
32
+ ## Configure embeddings
17
33
 
18
34
  Set `agents.defaults.memorySearch.provider` to `local`. By default, the plugin
19
35
  downloads and uses the EmbeddingGemma GGUF model. Configure
package/dist/index.js CHANGED
@@ -2,8 +2,118 @@ import { createRequire } from "node:module";
2
2
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
- import { pathToFileURL } from "node:url";
6
5
  import { createLocalEmbeddingProvider } from "openclaw/plugin-sdk/memory-core-host-engine-embeddings";
6
+ import { pathToFileURL } from "node:url";
7
+ import { randomUUID } from "node:crypto";
8
+ import { createAssistantMessageEventStream } from "openclaw/plugin-sdk/llm";
9
+ import fs from "node:fs/promises";
10
+ //#region extensions/llama-cpp/src/defaults.ts
11
+ const LLAMA_CPP_PROVIDER_ID = "llama-cpp";
12
+ const LLAMA_CPP_PROVIDER_LABEL = "Local model (llama.cpp)";
13
+ const LLAMA_CPP_LOCAL_AUTH_MARKER = "llama-cpp-local";
14
+ const LLAMA_CPP_LOCAL_BASE_URL = "local://llama-cpp";
15
+ function resolveLlamaCppSyntheticApiKey() {
16
+ return LLAMA_CPP_LOCAL_AUTH_MARKER;
17
+ }
18
+ const DEFAULT_LLAMA_CPP_MODEL_ID = "gemma-4-e4b-it-q4_k_m";
19
+ const DEFAULT_LLAMA_CPP_MODEL_REF = `${LLAMA_CPP_PROVIDER_ID}/${DEFAULT_LLAMA_CPP_MODEL_ID}`;
20
+ const DEFAULT_LLAMA_CPP_MODEL_URI = "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf";
21
+ const DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE = "hf_unsloth_gemma-4-E4B-it-GGUF_gemma-4-E4B-it-Q4_K_M.gguf";
22
+ const DEFAULT_LLAMA_CPP_CONTEXT_SIZE = 8192;
23
+ const LLAMA_CPP_DEFAULT_MODEL_RAM_FLOOR_BYTES = 16 * 1024 ** 3;
24
+ function meetsLlamaCppDefaultModelRamFloor(totalmemBytes = os.totalmem()) {
25
+ return totalmemBytes >= LLAMA_CPP_DEFAULT_MODEL_RAM_FLOOR_BYTES;
26
+ }
27
+ function resolveLlamaCppModelCacheDir(provider) {
28
+ const configured = provider?.params?.modelCacheDir;
29
+ return typeof configured === "string" && configured.trim() ? resolveHomePath(configured.trim()) : path.join(os.homedir(), ".node-llama-cpp", "models");
30
+ }
31
+ function resolveHomePath(value) {
32
+ if (value === "~") return os.homedir();
33
+ if (value.startsWith("~/")) return path.join(os.homedir(), value.slice(2));
34
+ return value;
35
+ }
36
+ function resolveLlamaCppModelSource(model) {
37
+ const configured = model.params?.modelPath;
38
+ if (typeof configured === "string" && configured.trim()) return resolveHomePath(configured.trim());
39
+ return model.id === "gemma-4-e4b-it-q4_k_m" ? DEFAULT_LLAMA_CPP_MODEL_URI : resolveHomePath(model.id);
40
+ }
41
+ function resolveCachedLlamaCppModelPath(params) {
42
+ const source = resolveLlamaCppModelSource(params.model);
43
+ const cacheDir = resolveLlamaCppModelCacheDir(params.provider);
44
+ if (source === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") return path.join(cacheDir, DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
45
+ if (/^hf:/i.test(source)) return null;
46
+ if (/^https?:\/\//i.test(source)) return null;
47
+ const localPath = resolveHomePath(source);
48
+ return path.isAbsolute(localPath) ? localPath : path.resolve(cacheDir, localPath);
49
+ }
50
+ function buildDefaultLlamaCppModel() {
51
+ return {
52
+ id: DEFAULT_LLAMA_CPP_MODEL_ID,
53
+ name: "Gemma 4 E4B (Q4_K_M)",
54
+ api: "openai-completions",
55
+ reasoning: false,
56
+ input: ["text"],
57
+ cost: {
58
+ input: 0,
59
+ output: 0,
60
+ cacheRead: 0,
61
+ cacheWrite: 0
62
+ },
63
+ contextWindow: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
64
+ contextTokens: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
65
+ maxTokens: 2048,
66
+ params: {
67
+ modelPath: DEFAULT_LLAMA_CPP_MODEL_URI,
68
+ contextSize: "auto"
69
+ },
70
+ compat: {
71
+ supportsTools: true,
72
+ supportsUsageInStreaming: true
73
+ }
74
+ };
75
+ }
76
+ function buildLlamaCppProviderConfig(existing) {
77
+ const defaultModel = buildDefaultLlamaCppModel();
78
+ const configuredModels = existing?.models ?? [];
79
+ const models = configuredModels.some((model) => model.id === defaultModel.id) ? configuredModels : [...configuredModels, defaultModel];
80
+ return {
81
+ ...existing,
82
+ baseUrl: existing?.baseUrl ?? LLAMA_CPP_LOCAL_BASE_URL,
83
+ api: existing?.api ?? "openai-completions",
84
+ models
85
+ };
86
+ }
87
+ //#endregion
88
+ //#region extensions/llama-cpp/src/node-llama.runtime.ts
89
+ function isNodeLlamaCppMissing(error) {
90
+ if (!(error instanceof Error)) return false;
91
+ return error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes("node-llama-cpp");
92
+ }
93
+ function formatErrorMessage(error) {
94
+ return error instanceof Error ? error.message : String(error);
95
+ }
96
+ function formatLlamaCppSetupError(error) {
97
+ const detail = formatErrorMessage(error);
98
+ const missing = isNodeLlamaCppMissing(error);
99
+ return [
100
+ "Local llama.cpp is unavailable.",
101
+ missing ? "Reason: node-llama-cpp is missing or failed to install." : detail ? `Reason: ${detail}` : void 0,
102
+ missing && detail ? `Detail: ${detail}` : null,
103
+ "To enable local GGUF models:",
104
+ "1) Install the official provider plugin: openclaw plugins install @openclaw/llama-cpp-provider",
105
+ "2) Use Node 24 for native installs/updates.",
106
+ "3) If you use pnpm from source: pnpm approve-builds, then pnpm rebuild node-llama-cpp."
107
+ ].filter(Boolean).join("\n");
108
+ }
109
+ const requireFromPlugin = createRequire(import.meta.url);
110
+ function resolveNodeLlamaCppImportUrl() {
111
+ return pathToFileURL(requireFromPlugin.resolve("node-llama-cpp")).href;
112
+ }
113
+ async function importNodeLlamaCpp() {
114
+ return await import(resolveNodeLlamaCppImportUrl());
115
+ }
116
+ //#endregion
7
117
  //#region extensions/llama-cpp/src/embedding-provider.ts
8
118
  const LLAMA_CPP_EMBEDDING_PROVIDER_ID = "local";
9
119
  const LOCAL_EMBEDDING_RUNTIME_FACTS = Symbol.for("openclaw.localEmbeddingRuntimeFacts");
@@ -48,32 +158,6 @@ function textFromEmbeddingInput(input) {
48
158
  function toMemoryEmbeddingInput(input) {
49
159
  return typeof input === "string" ? { text: input } : input;
50
160
  }
51
- function isNodeLlamaCppMissing(err) {
52
- if (!(err instanceof Error)) return false;
53
- return err.code === "ERR_MODULE_NOT_FOUND" && err.message.includes("node-llama-cpp");
54
- }
55
- function formatErrorMessage(err) {
56
- if (err instanceof Error) return err.message;
57
- return String(err);
58
- }
59
- function formatLlamaCppSetupError(err) {
60
- const detail = formatErrorMessage(err);
61
- const missing = isNodeLlamaCppMissing(err);
62
- return [
63
- "Local llama.cpp embeddings unavailable.",
64
- missing ? "Reason: node-llama-cpp is missing or failed to install." : detail ? `Reason: ${detail}` : void 0,
65
- missing && detail ? `Detail: ${detail}` : null,
66
- "To enable local GGUF embeddings:",
67
- "1) Install the official provider plugin: openclaw plugins install @openclaw/llama-cpp-provider",
68
- "2) Use Node 24 for native installs/updates.",
69
- "3) If you use pnpm from source: pnpm approve-builds, then pnpm rebuild node-llama-cpp.",
70
- "Or set agents.defaults.memorySearch.provider to a remote embedding provider such as \"openai\", \"ollama\", \"lmstudio\", or \"voyage\"."
71
- ].filter(Boolean).join("\n");
72
- }
73
- const requireFromPlugin = createRequire(import.meta.url);
74
- function resolveNodeLlamaCppImportUrl() {
75
- return pathToFileURL(requireFromPlugin.resolve("node-llama-cpp")).href;
76
- }
77
161
  function copyLocalRuntimeFacts(source, target) {
78
162
  const getRuntimeFacts = Reflect.get(source, LOCAL_EMBEDDING_RUNTIME_FACTS);
79
163
  if (typeof getRuntimeFacts === "function") Object.defineProperty(target, LOCAL_EMBEDDING_RUNTIME_FACTS, {
@@ -160,13 +244,508 @@ const llamaCppEmbeddingProviderAdapter = {
160
244
  create: async (options) => await createLlamaCppEmbeddingProviderResult(options)
161
245
  };
162
246
  //#endregion
247
+ //#region extensions/llama-cpp/src/inference-provider.ts
248
+ let loadedModel;
249
+ let llamaInstance;
250
+ let operationQueue = Promise.resolve();
251
+ function zeroCostUsage(input = 0, output = 0) {
252
+ return {
253
+ input,
254
+ output,
255
+ cacheRead: 0,
256
+ cacheWrite: 0,
257
+ totalTokens: input + output,
258
+ cost: {
259
+ input: 0,
260
+ output: 0,
261
+ cacheRead: 0,
262
+ cacheWrite: 0,
263
+ total: 0
264
+ }
265
+ };
266
+ }
267
+ function buildMessage(params) {
268
+ return {
269
+ role: "assistant",
270
+ content: params.content,
271
+ api: params.model.api,
272
+ provider: params.model.provider,
273
+ model: params.model.id,
274
+ stopReason: params.stopReason,
275
+ usage: params.usage ?? zeroCostUsage(),
276
+ timestamp: Date.now(),
277
+ ...params.errorMessage ? { errorMessage: params.errorMessage } : {}
278
+ };
279
+ }
280
+ function extractText(content) {
281
+ if (typeof content === "string") return content;
282
+ if (!Array.isArray(content)) return "";
283
+ return content.filter((part) => Boolean(part) && typeof part === "object" && part.type === "text").map((part) => part.text).join("");
284
+ }
285
+ function normalizeArguments(value) {
286
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
287
+ }
288
+ function mapContextToLlamaChatHistory(context) {
289
+ const history = [];
290
+ if (context.systemPrompt?.trim()) history.push({
291
+ type: "system",
292
+ text: context.systemPrompt
293
+ });
294
+ const toolResults = new Map(context.messages.filter((message) => message.role === "toolResult").map((message) => [message.toolCallId, extractText(message.content)]));
295
+ const consumedToolResults = /* @__PURE__ */ new Set();
296
+ for (const message of context.messages) {
297
+ if (message.role === "user") {
298
+ history.push({
299
+ type: "user",
300
+ text: extractText(message.content)
301
+ });
302
+ continue;
303
+ }
304
+ if (message.role === "assistant") {
305
+ const response = [];
306
+ for (const part of message.content) {
307
+ if (part.type === "text") {
308
+ if (part.text) response.push(part.text);
309
+ continue;
310
+ }
311
+ if (part.type === "thinking") {
312
+ if (part.thinking) response.push({
313
+ type: "segment",
314
+ segmentType: "thought",
315
+ text: part.thinking,
316
+ ended: true
317
+ });
318
+ continue;
319
+ }
320
+ const result = toolResults.get(part.id);
321
+ if (result !== void 0) consumedToolResults.add(part.id);
322
+ response.push({
323
+ type: "functionCall",
324
+ name: part.name,
325
+ params: part.arguments,
326
+ result: result ?? ""
327
+ });
328
+ }
329
+ history.push({
330
+ type: "model",
331
+ response
332
+ });
333
+ continue;
334
+ }
335
+ if (!consumedToolResults.has(message.toolCallId)) history.push({
336
+ type: "user",
337
+ text: `Tool result (${message.toolName}): ${extractText(message.content)}`
338
+ });
339
+ }
340
+ return history;
341
+ }
342
+ function mapToolsToLlamaFunctions(context) {
343
+ if (!context.tools?.length) return;
344
+ return Object.fromEntries(context.tools.map((tool) => [tool.name, {
345
+ description: tool.description,
346
+ params: tool.parameters
347
+ }]));
348
+ }
349
+ function readContextSizeValue(value) {
350
+ if (value === "auto") return value;
351
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
352
+ }
353
+ function resolveContextSize(model, providerConfig) {
354
+ const configured = readContextSizeValue(model.params?.contextSize) ?? readContextSizeValue(providerConfig?.params?.contextSize);
355
+ if (typeof configured === "number") return configured;
356
+ return { max: typeof model.contextTokens === "number" && model.contextTokens > 0 ? Math.floor(model.contextTokens) : DEFAULT_LLAMA_CPP_CONTEXT_SIZE };
357
+ }
358
+ async function disposeLoadedModel() {
359
+ if (!loadedModel) return;
360
+ const previous = loadedModel;
361
+ loadedModel = void 0;
362
+ await previous.context.dispose();
363
+ await previous.model.dispose();
364
+ }
365
+ async function getLoadedModel(params) {
366
+ const source = resolveLlamaCppModelSource(params.model);
367
+ const modelPath = await params.runtime.resolveModelFile(source, {
368
+ directory: resolveLlamaCppModelCacheDir(params.providerConfig),
369
+ download: false
370
+ });
371
+ const contextSize = resolveContextSize(params.model, params.providerConfig);
372
+ const key = `${modelPath}\0${JSON.stringify(contextSize)}`;
373
+ if (loadedModel?.key === key) return loadedModel;
374
+ await disposeLoadedModel();
375
+ const llama = llamaInstance ?? await params.runtime.getLlama();
376
+ llamaInstance = llama;
377
+ const fitContextSize = typeof contextSize === "number" ? contextSize : contextSize.max;
378
+ const model = await llama.loadModel({
379
+ modelPath,
380
+ loadSignal: params.signal,
381
+ gpuLayers: { fitContext: { contextSize: fitContextSize } }
382
+ });
383
+ let context;
384
+ try {
385
+ context = await model.createContext({
386
+ contextSize,
387
+ createSignal: params.signal
388
+ });
389
+ const sequence = context.getSequence();
390
+ loadedModel = {
391
+ key,
392
+ model,
393
+ context,
394
+ sequence
395
+ };
396
+ return loadedModel;
397
+ } catch (error) {
398
+ await context?.dispose();
399
+ await model.dispose();
400
+ throw error;
401
+ }
402
+ }
403
+ async function serialize(operation) {
404
+ const current = operationQueue.then(operation, operation);
405
+ operationQueue = current.catch(() => void 0);
406
+ await current;
407
+ }
408
+ async function clearLlamaCppInferenceCacheForTests() {
409
+ await serialize(async () => {
410
+ await disposeLoadedModel();
411
+ if (llamaInstance) {
412
+ await llamaInstance.dispose();
413
+ llamaInstance = void 0;
414
+ }
415
+ });
416
+ }
417
+ function createLlamaCppStreamFn(params) {
418
+ return (model, context, options) => {
419
+ const stream = createAssistantMessageEventStream();
420
+ let streamedText = "";
421
+ let generationAborted = false;
422
+ let started = false;
423
+ let ended = false;
424
+ const signal = options?.signal;
425
+ const abortWhileQueued = () => {
426
+ if (started || ended) return;
427
+ ended = true;
428
+ stream.push({
429
+ type: "error",
430
+ reason: "aborted",
431
+ error: buildMessage({
432
+ model,
433
+ content: [],
434
+ stopReason: "aborted",
435
+ errorMessage: "Request was aborted"
436
+ })
437
+ });
438
+ stream.end();
439
+ };
440
+ signal?.addEventListener("abort", abortWhileQueued, { once: true });
441
+ if (signal?.aborted) abortWhileQueued();
442
+ const run = async () => {
443
+ if (ended) return;
444
+ started = true;
445
+ signal?.removeEventListener("abort", abortWhileQueued);
446
+ try {
447
+ const runtime = await importNodeLlamaCpp();
448
+ const sequence = (await getLoadedModel({
449
+ runtime,
450
+ model,
451
+ providerConfig: params.providerConfig,
452
+ signal: options?.signal
453
+ })).sequence;
454
+ const chat = new runtime.LlamaChat({
455
+ contextSequence: sequence,
456
+ chatWrapper: "auto",
457
+ autoDisposeSequence: false
458
+ });
459
+ const before = sequence.tokenMeter.getState();
460
+ let textStarted = false;
461
+ const partial = () => buildMessage({
462
+ model,
463
+ content: streamedText ? [{
464
+ type: "text",
465
+ text: streamedText
466
+ }] : [],
467
+ stopReason: "stop"
468
+ });
469
+ const appendTextDelta = (delta) => {
470
+ if (!delta) return;
471
+ if (!textStarted) {
472
+ textStarted = true;
473
+ stream.push({
474
+ type: "start",
475
+ partial: partial()
476
+ });
477
+ stream.push({
478
+ type: "text_start",
479
+ contentIndex: 0,
480
+ partial: partial()
481
+ });
482
+ }
483
+ streamedText += delta;
484
+ stream.push({
485
+ type: "text_delta",
486
+ contentIndex: 0,
487
+ delta
488
+ });
489
+ };
490
+ try {
491
+ const result = await chat.generateResponse(mapContextToLlamaChatHistory(context), {
492
+ functions: mapToolsToLlamaFunctions(context),
493
+ documentFunctionParams: true,
494
+ signal: options?.signal,
495
+ maxTokens: options?.maxTokens ?? model.maxTokens,
496
+ temperature: options?.temperature,
497
+ customStopTriggers: options?.stop,
498
+ onTextChunk: appendTextDelta
499
+ });
500
+ if (result.metadata.stopReason === "abort" || signal?.aborted) {
501
+ generationAborted = true;
502
+ throw signal?.reason ?? /* @__PURE__ */ new Error("Request was aborted");
503
+ }
504
+ const usageDelta = sequence.tokenMeter.diff(before);
505
+ if (!streamedText && result.response) appendTextDelta(result.response);
506
+ const content = streamedText ? [{
507
+ type: "text",
508
+ text: streamedText
509
+ }] : [];
510
+ if (textStarted) stream.push({
511
+ type: "text_end",
512
+ contentIndex: 0,
513
+ content: streamedText,
514
+ partial: partial()
515
+ });
516
+ const toolCalls = (result.functionCalls ?? []).map((call) => ({
517
+ type: "toolCall",
518
+ id: `llama_cpp_call_${randomUUID()}`,
519
+ name: call.functionName,
520
+ arguments: normalizeArguments(call.params)
521
+ }));
522
+ content.push(...toolCalls);
523
+ const reason = toolCalls.length > 0 ? "toolUse" : result.metadata.stopReason === "maxTokens" ? "length" : "stop";
524
+ const message = buildMessage({
525
+ model,
526
+ content,
527
+ stopReason: reason,
528
+ usage: zeroCostUsage(usageDelta.usedInputTokens, usageDelta.usedOutputTokens)
529
+ });
530
+ stream.push({
531
+ type: "done",
532
+ reason,
533
+ message
534
+ });
535
+ } finally {
536
+ chat.dispose();
537
+ }
538
+ } catch (error) {
539
+ const aborted = generationAborted || options?.signal?.aborted === true;
540
+ const reason = aborted ? "aborted" : "error";
541
+ const errorMessage = aborted ? "Request was aborted" : formatLlamaCppSetupError(error);
542
+ stream.push({
543
+ type: "error",
544
+ reason,
545
+ error: buildMessage({
546
+ model,
547
+ content: streamedText ? [{
548
+ type: "text",
549
+ text: streamedText
550
+ }] : [],
551
+ stopReason: reason,
552
+ errorMessage
553
+ })
554
+ });
555
+ } finally {
556
+ ended = true;
557
+ stream.end();
558
+ }
559
+ };
560
+ if (!ended) queueMicrotask(() => void serialize(run));
561
+ return stream;
562
+ };
563
+ }
564
+ if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.llamaCppInferenceTestApi")] = {
565
+ mapContextToLlamaChatHistory,
566
+ mapToolsToLlamaFunctions,
567
+ clearLlamaCppInferenceCacheForTests
568
+ };
569
+ //#endregion
570
+ //#region extensions/llama-cpp/src/setup.ts
571
+ const BYTES_PER_GB = 1e9;
572
+ const BYTES_PER_MB = 1e6;
573
+ function formatLlamaCppDownloadProgress(params) {
574
+ const downloadedSize = Math.max(0, params.downloadedSize);
575
+ const totalSize = Math.max(1, params.totalSize);
576
+ return `Downloading Gemma 4 E4B… ${Math.min(100, Math.floor(downloadedSize / totalSize * 100))}% (${(downloadedSize / BYTES_PER_GB).toFixed(1)}/${(totalSize / BYTES_PER_GB).toFixed(1)} GB, ${Math.max(0, Math.round(params.bytesPerSecond / BYTES_PER_MB))} MB/s)`;
577
+ }
578
+ function formatRamGb(totalmemBytes) {
579
+ return (totalmemBytes / 1024 ** 3).toFixed(1).replace(/\.0$/, "");
580
+ }
581
+ function readPrimaryModel(config) {
582
+ const model = config.agents?.defaults?.model;
583
+ return typeof model === "string" ? model : model?.primary;
584
+ }
585
+ function configuredCandidates(config) {
586
+ const existing = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
587
+ const provider = buildLlamaCppProviderConfig(existing);
588
+ const primary = readPrimaryModel(config);
589
+ const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(10) : void 0;
590
+ return provider.models.map((model) => ({
591
+ model,
592
+ provider
593
+ })).toSorted((a, b) => Number(b.model.id === primaryId) - Number(a.model.id === primaryId));
594
+ }
595
+ async function isFile(filePath) {
596
+ try {
597
+ return (await fs.stat(filePath)).isFile();
598
+ } catch {
599
+ return false;
600
+ }
601
+ }
602
+ async function detectLlamaCppSetup(ctx) {
603
+ let runtime;
604
+ try {
605
+ runtime = await importNodeLlamaCpp();
606
+ } catch {
607
+ return null;
608
+ }
609
+ for (const candidate of configuredCandidates(ctx.config)) try {
610
+ if (!await isFile(await runtime.resolveModelFile(resolveLlamaCppModelSource(candidate.model), {
611
+ directory: resolveLlamaCppModelCacheDir(candidate.provider),
612
+ download: false,
613
+ cli: false
614
+ }))) continue;
615
+ return {
616
+ modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
617
+ detail: `${candidate.model.id} (downloaded)`
618
+ };
619
+ } catch {}
620
+ return null;
621
+ }
622
+ function buildSetupResult(config, defaultModel = DEFAULT_LLAMA_CPP_MODEL_REF) {
623
+ return {
624
+ profiles: [],
625
+ defaultModel,
626
+ configPatch: { models: {
627
+ mode: config.models?.mode ?? "merge",
628
+ providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig(config.models?.providers?.[LLAMA_CPP_PROVIDER_ID]) }
629
+ } }
630
+ };
631
+ }
632
+ async function prepareLlamaCppSetup(ctx) {
633
+ return (await detectLlamaCppSetup(ctx))?.modelRef === ctx.modelRef ? buildSetupResult(ctx.config, ctx.modelRef) : null;
634
+ }
635
+ async function runLlamaCppSetup(ctx) {
636
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
637
+ const cacheDir = resolveLlamaCppModelCacheDir(existing);
638
+ const cachedPath = resolveCachedLlamaCppModelPath({
639
+ model: {
640
+ id: DEFAULT_LLAMA_CPP_MODEL_ID,
641
+ params: { modelPath: DEFAULT_LLAMA_CPP_MODEL_URI }
642
+ },
643
+ provider: existing
644
+ });
645
+ if (!cachedPath || !await isFile(cachedPath)) {
646
+ const totalmemBytes = os.totalmem();
647
+ if (!meetsLlamaCppDefaultModelRamFloor(totalmemBytes)) {
648
+ await ctx.prompter.note(`This machine has ${formatRamGb(totalmemBytes)} GB RAM; the bundled local model needs 16 GB+. Use Ollama/LM Studio with a smaller model, or a cloud provider.`, "Setup skipped");
649
+ return { profiles: [] };
650
+ }
651
+ if (!await ctx.prompter.confirm({
652
+ message: "Download Gemma 4 E4B IT Q4_K_M (about 5.0 GB) for local llama.cpp inference?",
653
+ initialValue: false
654
+ })) {
655
+ await ctx.prompter.note("Local model download skipped.", "Setup skipped");
656
+ return { profiles: [] };
657
+ }
658
+ const progress = ctx.prompter.progress("Preparing Gemma 4 E4B model download…");
659
+ try {
660
+ const runtime = await importNodeLlamaCpp();
661
+ let previousDownloadedSize;
662
+ let previousProgressAtMs;
663
+ let rollingBytesPerSecond = 0;
664
+ await (await runtime.createModelDownloader({
665
+ modelUri: DEFAULT_LLAMA_CPP_MODEL_URI,
666
+ dirPath: cacheDir,
667
+ fileName: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE,
668
+ showCliProgress: false,
669
+ onProgress: ({ downloadedSize, totalSize }) => {
670
+ const now = Date.now();
671
+ if (previousDownloadedSize !== void 0 && previousProgressAtMs !== void 0 && downloadedSize >= previousDownloadedSize && now > previousProgressAtMs) {
672
+ const elapsedSeconds = (now - previousProgressAtMs) / 1e3;
673
+ const currentBytesPerSecond = (downloadedSize - previousDownloadedSize) / elapsedSeconds;
674
+ rollingBytesPerSecond = rollingBytesPerSecond === 0 ? currentBytesPerSecond : rollingBytesPerSecond * .75 + currentBytesPerSecond * .25;
675
+ }
676
+ previousDownloadedSize = downloadedSize;
677
+ previousProgressAtMs = now;
678
+ const expectedSize = totalSize || 4977169568;
679
+ progress.update(formatLlamaCppDownloadProgress({
680
+ downloadedSize,
681
+ totalSize: expectedSize,
682
+ bytesPerSecond: rollingBytesPerSecond
683
+ }));
684
+ }
685
+ })).download({ signal: ctx.signal });
686
+ progress.stop("Gemma 4 E4B model downloaded");
687
+ } catch (error) {
688
+ progress.stop("Model download failed");
689
+ throw new Error(formatLlamaCppSetupError(error), { cause: error });
690
+ }
691
+ }
692
+ return buildSetupResult(ctx.config);
693
+ }
694
+ if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.llamaCppSetupTestApi")] = { formatLlamaCppDownloadProgress };
695
+ //#endregion
163
696
  //#region extensions/llama-cpp/index.ts
164
697
  var llama_cpp_default = definePluginEntry({
165
698
  id: "llama-cpp",
166
699
  name: "llama.cpp Provider",
167
- description: "Local GGUF embeddings through node-llama-cpp",
700
+ description: "Local GGUF text inference and embeddings through node-llama-cpp",
168
701
  register(api) {
169
702
  api.registerEmbeddingProvider(llamaCppEmbeddingProviderAdapter);
703
+ api.registerProvider({
704
+ id: LLAMA_CPP_PROVIDER_ID,
705
+ label: LLAMA_CPP_PROVIDER_LABEL,
706
+ docsPath: "/plugins/llama-cpp",
707
+ auth: [{
708
+ id: "local",
709
+ label: LLAMA_CPP_PROVIDER_LABEL,
710
+ hint: "In-process local GGUF model (about 5.0 GB download; requires 16 GB RAM)",
711
+ kind: "custom",
712
+ appGuidedSetup: {
713
+ detect: detectLlamaCppSetup,
714
+ prepare: prepareLlamaCppSetup
715
+ },
716
+ run: runLlamaCppSetup
717
+ }],
718
+ catalog: {
719
+ order: "late",
720
+ run: async (ctx) => ({ provider: buildLlamaCppProviderConfig(ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID]) })
721
+ },
722
+ staticCatalog: {
723
+ order: "late",
724
+ run: async () => ({ provider: buildLlamaCppProviderConfig() })
725
+ },
726
+ createStreamFn: ({ config, provider }) => createLlamaCppStreamFn({ providerConfig: config?.models?.providers?.[provider] }),
727
+ resolveSyntheticAuth: () => ({
728
+ apiKey: resolveLlamaCppSyntheticApiKey(),
729
+ source: "local llama.cpp runtime",
730
+ mode: "api-key"
731
+ }),
732
+ wizard: {
733
+ setup: {
734
+ choiceId: LLAMA_CPP_PROVIDER_ID,
735
+ choiceLabel: LLAMA_CPP_PROVIDER_LABEL,
736
+ choiceHint: "In-process local model (about 5.0 GB download; requires 16 GB RAM)",
737
+ groupId: LLAMA_CPP_PROVIDER_ID,
738
+ groupLabel: "Local llama.cpp",
739
+ groupHint: "No API key required",
740
+ methodId: "local"
741
+ },
742
+ modelPicker: {
743
+ label: "llama.cpp (local GGUF)",
744
+ hint: "Run a GGUF model in the OpenClaw process",
745
+ methodId: "local"
746
+ }
747
+ }
748
+ });
170
749
  }
171
750
  });
172
751
  //#endregion
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@openclaw/llama-cpp-provider",
3
- "version": "2026.7.2-beta.2",
3
+ "version": "2026.7.2-beta.3",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@openclaw/llama-cpp-provider",
9
- "version": "2026.7.2-beta.2",
9
+ "version": "2026.7.2-beta.3",
10
10
  "optionalDependencies": {
11
11
  "node-llama-cpp": "3.19.0"
12
12
  }
@@ -1,11 +1,41 @@
1
1
  {
2
2
  "id": "llama-cpp",
3
3
  "name": "llama.cpp Provider",
4
- "description": "Local GGUF embeddings through node-llama-cpp.",
4
+ "description": "Local GGUF text inference and embeddings through node-llama-cpp.",
5
5
  "activation": {
6
6
  "onStartup": false
7
7
  },
8
8
  "enabledByDefault": true,
9
+ "providers": ["llama-cpp"],
10
+ "providerRequest": {
11
+ "providers": {
12
+ "llama-cpp": {
13
+ "family": "llama-cpp"
14
+ }
15
+ }
16
+ },
17
+ "modelPricing": {
18
+ "providers": {
19
+ "llama-cpp": {
20
+ "external": false
21
+ }
22
+ }
23
+ },
24
+ "syntheticAuthRefs": ["llama-cpp"],
25
+ "nonSecretAuthMarkers": ["llama-cpp-local"],
26
+ "providerAuthChoices": [
27
+ {
28
+ "provider": "llama-cpp",
29
+ "method": "local",
30
+ "choiceId": "llama-cpp",
31
+ "appGuidedDiscovery": true,
32
+ "choiceLabel": "Local model (llama.cpp)",
33
+ "choiceHint": "Downloads an approximately 5.0 GB local model; requires 16 GB RAM",
34
+ "groupId": "llama-cpp",
35
+ "groupLabel": "Local llama.cpp",
36
+ "groupHint": "No API key required"
37
+ }
38
+ ],
9
39
  "contracts": {
10
40
  "embeddingProviders": ["local"]
11
41
  },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@openclaw/llama-cpp-provider",
3
- "version": "2026.7.2-beta.2",
4
- "description": "OpenClaw llama.cpp embedding provider plugin",
3
+ "version": "2026.7.2-beta.3",
4
+ "description": "OpenClaw llama.cpp text inference and embedding provider plugin",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/openclaw/openclaw"
@@ -23,10 +23,10 @@
23
23
  "minHostVersion": ">=2026.6.2"
24
24
  },
25
25
  "compat": {
26
- "pluginApi": ">=2026.7.2-beta.2"
26
+ "pluginApi": ">=2026.7.2-beta.3"
27
27
  },
28
28
  "build": {
29
- "openclawVersion": "2026.7.2-beta.2"
29
+ "openclawVersion": "2026.7.2-beta.3"
30
30
  },
31
31
  "release": {
32
32
  "bundleRuntimeDependencies": false,
@@ -44,7 +44,7 @@
44
44
  "README.md"
45
45
  ],
46
46
  "peerDependencies": {
47
- "openclaw": ">=2026.7.2-beta.2"
47
+ "openclaw": ">=2026.7.2-beta.3"
48
48
  },
49
49
  "peerDependenciesMeta": {
50
50
  "openclaw": {