@openclaw/llama-cpp-provider 2026.7.2-beta.7 → 2026.7.34

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