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

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/dist/index.js CHANGED
@@ -1,605 +1,738 @@
1
- import { createRequire } from "node:module";
1
+ import { A as resolveLlamaCppModelSource, C as buildLlamaCppProviderConfig, D as resolveLegacyLlamaCppModelCacheDir, E as resolveHomePath, O as resolveLlamaCppDataDir, S as LLAMA_CPP_PROVIDER_LABEL, T as resolveCachedLlamaCppModelPath, _ as DEFAULT_LLAMA_CPP_MODEL_SHA256, a as selectLlamaServerAsset, b as LLAMA_CPP_DEFAULT_PORT, c as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, d as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256, f as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES, g as DEFAULT_LLAMA_CPP_MODEL_REVISION, h as DEFAULT_LLAMA_CPP_MODEL_REF, i as resolveManagedLlamaServerPaths, j as resolveLlamaCppSyntheticApiKey, k as resolveLlamaCppModelCacheDir, l as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, m as DEFAULT_LLAMA_CPP_MODEL_ID, n as LLAMA_SERVER_COMMIT, p as DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE, r as LLAMA_SERVER_RELEASE, s as DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE, u as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION, v as DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES, w as meetsLlamaCppDefaultModelRamFloor, x as LLAMA_CPP_PROVIDER_ID } from "./llama-server-assets-BEF3s_UC.js";
2
2
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
3
3
  import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
- import { createLocalEmbeddingProvider } from "openclaw/plugin-sdk/memory-core-host-engine-embeddings";
7
- 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;
6
+ import { getEmbeddingProvider } from "openclaw/plugin-sdk/embedding-providers";
7
+ import { asOptionalRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
8
+ import { execFile } from "node:child_process";
9
+ import { createHash, randomUUID } from "node:crypto";
10
+ import fs from "node:fs";
11
+ import fsp from "node:fs/promises";
12
+ import JSZip from "jszip";
13
+ import * as tar from "tar";
14
+ import net from "node:net";
15
+ import { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } from "openclaw/plugin-sdk/ssrf-runtime";
16
+ import { fetchConfiguredLocalOriginWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime-internal";
17
+ //#region extensions/llama-cpp/src/llama-server-install.ts
18
+ const DOWNLOAD_TIMEOUT_MS = 30 * 6e4;
19
+ const VERSION_TIMEOUT_MS = 15e3;
20
+ const installationPromises = /* @__PURE__ */ new Map();
21
+ function compareVersion(left, right) {
22
+ const leftParts = left.split(".").map(Number);
23
+ const rightParts = right.split(".").map(Number);
24
+ for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
25
+ const delta = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
26
+ if (delta !== 0) return delta;
27
+ }
28
+ return 0;
29
+ }
30
+ function assertSupportedLinuxRuntime(asset) {
31
+ if (asset.platform !== "linux") return;
32
+ const header = asOptionalRecord(asOptionalRecord(process.report?.getReport())?.header);
33
+ const glibc = typeof header?.glibcVersionRuntime === "string" ? header.glibcVersionRuntime : "";
34
+ if (!glibc) throw new Error("The verified Ubuntu llama-server build requires glibc and cannot run on musl/Alpine. Install llama-server manually for this host and configure its absolute path.");
35
+ const minimum = asset.arch === "arm64" ? "2.38" : "2.34";
36
+ if (compareVersion(glibc, minimum) < 0) throw new Error(`The verified llama-server build requires glibc ${minimum}+ on Linux ${asset.arch}; this host has ${glibc}. Install a compatible llama-server manually and configure its absolute path.`);
37
+ }
38
+ function assetUrl(asset) {
39
+ return `https://github.com/ggml-org/llama.cpp/releases/download/${LLAMA_SERVER_RELEASE}/${asset.name}`;
40
+ }
41
+ async function sha256File(filePath) {
42
+ const hash = createHash("sha256");
43
+ await new Promise((resolve, reject) => {
44
+ const input = fs.createReadStream(filePath);
45
+ input.on("data", (chunk) => hash.update(chunk));
46
+ input.once("error", reject);
47
+ input.once("end", resolve);
48
+ });
49
+ return hash.digest("hex");
36
50
  }
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);
51
+ function readResponseSha256(response) {
52
+ for (const name of ["x-checksum-sha256", "x-linked-etag"]) {
53
+ const value = response.headers.get(name)?.replace(/^W\//u, "").replaceAll("\"", "").trim();
54
+ if (value && /^[a-f\d]{64}$/iu.test(value)) return value.toLowerCase();
55
+ }
56
+ const encoded = response.headers.get("digest")?.match(/(?:^|,)\s*sha-256=([^,\s]+)/iu)?.[1];
57
+ return encoded ? Buffer.from(encoded, "base64").toString("hex") : void 0;
41
58
  }
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);
59
+ async function downloadVerifiedFile(params) {
60
+ const partialPath = `${params.destination}.partial-${randomUUID()}`;
61
+ await fsp.mkdir(path.dirname(params.destination), { recursive: true });
62
+ const { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } = await import("openclaw/plugin-sdk/ssrf-runtime");
63
+ try {
64
+ const { response, release } = await fetchWithSsrFGuard({
65
+ url: params.url,
66
+ signal: params.signal,
67
+ timeoutMs: DOWNLOAD_TIMEOUT_MS,
68
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(params.url),
69
+ requireHttps: true,
70
+ auditContext: "llama-cpp-download"
71
+ });
72
+ try {
73
+ if (!response.ok || !response.body) throw new Error(`download failed: HTTP ${response.status} ${response.statusText}`);
74
+ const expectedSha256 = params.expectedSha256 ?? readResponseSha256(response);
75
+ if (!expectedSha256 && params.requireServerDigest) throw new Error("the download server did not provide a SHA-256 digest; download the GGUF manually and configure its local path");
76
+ const contentLength = Number(response.headers.get("content-length"));
77
+ const totalSize = params.expectedSize ?? (Number.isFinite(contentLength) && contentLength > 0 ? contentLength : 0);
78
+ const handle = await fsp.open(partialPath, "wx", 384);
79
+ const hash = createHash("sha256");
80
+ const reader = response.body.getReader();
81
+ let downloadedSize = 0;
82
+ let previousSize = 0;
83
+ let previousAt = Date.now();
84
+ let rollingBytesPerSecond = 0;
85
+ try {
86
+ for (;;) {
87
+ const { done, value } = await reader.read();
88
+ if (done) break;
89
+ const chunk = Buffer.from(value);
90
+ await handle.writeFile(chunk);
91
+ hash.update(chunk);
92
+ downloadedSize += chunk.byteLength;
93
+ const now = Date.now();
94
+ if (now > previousAt) {
95
+ const currentRate = (downloadedSize - previousSize) * 1e3 / (now - previousAt);
96
+ rollingBytesPerSecond = rollingBytesPerSecond === 0 ? currentRate : rollingBytesPerSecond * .75 + currentRate * .25;
97
+ }
98
+ previousSize = downloadedSize;
99
+ previousAt = now;
100
+ params.onProgress?.({
101
+ downloadedSize,
102
+ totalSize,
103
+ bytesPerSecond: rollingBytesPerSecond
104
+ });
105
+ }
106
+ } finally {
107
+ await handle.close();
108
+ }
109
+ if (params.expectedSize && downloadedSize !== params.expectedSize) throw new Error(`download size mismatch: expected ${params.expectedSize}, got ${downloadedSize}`);
110
+ const actualSha256 = hash.digest("hex");
111
+ if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
112
+ await fsp.rename(partialPath, params.destination);
113
+ } finally {
114
+ await release();
115
+ }
116
+ } finally {
117
+ await fsp.rm(partialPath, { force: true }).catch(() => void 0);
118
+ }
50
119
  }
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
120
+ async function extractZip(archivePath, destination) {
121
+ const zip = await JSZip.loadAsync(await fsp.readFile(archivePath));
122
+ for (const entry of Object.values(zip.files)) {
123
+ const normalized = path.posix.normalize(entry.name);
124
+ if (normalized.startsWith("/") || normalized === ".." || normalized.startsWith("../")) throw new Error(`unsafe path in llama-server archive: ${entry.name}`);
125
+ const outputPath = path.join(destination, ...normalized.split("/"));
126
+ if (entry.dir) await fsp.mkdir(outputPath, { recursive: true });
127
+ else {
128
+ await fsp.mkdir(path.dirname(outputPath), { recursive: true });
129
+ await fsp.writeFile(outputPath, await entry.async("nodebuffer"), { mode: 384 });
74
130
  }
75
- };
131
+ }
76
132
  }
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
- };
133
+ async function findExecutable(root, executable) {
134
+ for (const entry of await fsp.readdir(root, { withFileTypes: true })) {
135
+ const candidate = path.join(root, entry.name);
136
+ if (entry.isFile() && entry.name === executable) return candidate;
137
+ if (entry.isDirectory()) {
138
+ const nested = await findExecutable(candidate, executable).catch(() => void 0);
139
+ if (nested) return nested;
140
+ }
141
+ }
142
+ throw new Error(`llama-server archive does not contain ${executable}`);
87
143
  }
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");
144
+ async function runVersion(command) {
145
+ return await new Promise((resolve, reject) => {
146
+ execFile(command, ["--version"], { timeout: VERSION_TIMEOUT_MS }, (error, stdout, stderr) => {
147
+ if (error) reject(new Error(error.message, { cause: error }));
148
+ else resolve(`${stdout}${stderr}`.trim());
149
+ });
150
+ });
93
151
  }
94
- function formatErrorMessage(error) {
95
- return error instanceof Error ? error.message : String(error);
152
+ function formatRuntimeDependencyError(error) {
153
+ const detail = error instanceof Error ? error.message : String(error);
154
+ if (process.platform === "linux") return new Error(`The verified llama-server build could not start. Install the OpenMP runtime (for example libgomp1 on Debian/Ubuntu or libgomp on Fedora), then rerun llama.cpp setup. Detail: ${detail}`, { cause: error });
155
+ if (process.platform === "win32") return new Error(`The verified llama-server build could not start. Install the Microsoft Visual C++ 2015-2022 Redistributable, then rerun llama.cpp setup. Detail: ${detail}`, { cause: error });
156
+ return new Error(`The verified llama-server build could not start: ${detail}`, { cause: error });
96
157
  }
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());
158
+ async function validateInstalledServer(command) {
159
+ let version;
160
+ try {
161
+ version = await runVersion(command);
162
+ } catch (error) {
163
+ throw formatRuntimeDependencyError(error);
164
+ }
165
+ if (!version.includes(`version: 10357`) || !version.includes("689e227db485c6b33d061555e74034c93a867649".slice(0, 9))) throw new Error(`Unexpected llama-server build at ${command}: expected ${LLAMA_SERVER_RELEASE} (${LLAMA_SERVER_COMMIT.slice(0, 9)}), got ${version || "no version output"}`);
166
+ }
167
+ async function installLlamaServer(asset) {
168
+ assertSupportedLinuxRuntime(asset);
169
+ const { installDir, command } = resolveManagedLlamaServerPaths(asset);
170
+ if (await fsp.stat(command).then((stat) => stat.isFile()).catch(() => false)) {
171
+ await validateInstalledServer(command);
172
+ return command;
173
+ }
174
+ const dataDir = resolveLlamaCppDataDir();
175
+ const archivePath = path.join(dataDir, `.download-${randomUUID()}-${asset.name}`);
176
+ const extractDir = path.join(dataDir, `.extract-${randomUUID()}`);
177
+ await fsp.mkdir(dataDir, { recursive: true });
178
+ try {
179
+ await downloadVerifiedFile({
180
+ url: assetUrl(asset),
181
+ destination: archivePath,
182
+ expectedSha256: asset.sha256
183
+ });
184
+ await fsp.mkdir(extractDir, { recursive: true });
185
+ if (asset.archive === "zip") await extractZip(archivePath, extractDir);
186
+ else await tar.x({
187
+ file: archivePath,
188
+ cwd: extractDir,
189
+ preservePaths: false
190
+ });
191
+ const extractedCommand = await findExecutable(extractDir, asset.executable);
192
+ const extractedRoot = path.dirname(extractedCommand);
193
+ await fsp.chmod(extractedCommand, 493);
194
+ await validateInstalledServer(extractedCommand);
195
+ await fsp.mkdir(path.dirname(installDir), { recursive: true });
196
+ await fsp.rm(installDir, {
197
+ recursive: true,
198
+ force: true
199
+ });
200
+ await fsp.rename(extractedRoot, installDir);
201
+ await validateInstalledServer(command);
202
+ return command;
203
+ } finally {
204
+ await Promise.all([fsp.rm(archivePath, { force: true }), fsp.rm(extractDir, {
205
+ recursive: true,
206
+ force: true
207
+ })]);
208
+ }
116
209
  }
117
- //#endregion
118
- //#region extensions/llama-cpp/src/embedding-provider.ts
119
- const LLAMA_CPP_EMBEDDING_PROVIDER_ID = "local";
120
- const LOCAL_EMBEDDING_RUNTIME_FACTS = Symbol.for("openclaw.localEmbeddingRuntimeFacts");
121
- const DEFAULT_LLAMA_CPP_EMBEDDING_MODEL = "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf";
122
- const DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_CACHE_FILE_NAME = "hf_ggml-org_embeddinggemma-300m-qat-Q8_0.gguf";
123
- function normalizeOptionalString(value) {
124
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
210
+ async function ensureLlamaServerInstalled() {
211
+ const asset = selectLlamaServerAsset();
212
+ const key = `${asset.platform}/${asset.arch}/${LLAMA_SERVER_RELEASE}`;
213
+ const pending = installationPromises.get(key) ?? installLlamaServer(asset);
214
+ installationPromises.set(key, pending);
215
+ try {
216
+ return {
217
+ command: await pending,
218
+ asset
219
+ };
220
+ } finally {
221
+ if (installationPromises.get(key) === pending) installationPromises.delete(key);
222
+ }
125
223
  }
126
- function readLocalOptions(options) {
127
- return options.local ?? {};
224
+ //#endregion
225
+ //#region extensions/llama-cpp/src/managed-server.ts
226
+ const modelPromises = /* @__PURE__ */ new Map();
227
+ const chatPreparationPromises = /* @__PURE__ */ new Map();
228
+ function parseHuggingFaceSource(source) {
229
+ const [pathPart, revisionPart] = source.replace(/^(?:hf|huggingface):(?:\/\/)?/iu, "").split("#", 2);
230
+ const [user, repositoryWithTag, ...fileParts] = (pathPart ?? "").split("/");
231
+ const [repository, ...tagParts] = (repositoryWithTag ?? "").split(":");
232
+ if (!user || !repository) throw new Error(`Invalid Hugging Face model URI: ${source}`);
233
+ return {
234
+ user,
235
+ repository,
236
+ file: fileParts.length > 0 ? fileParts.join("/") : void 0,
237
+ revision: revisionPart || "main",
238
+ tag: tagParts.length > 0 ? tagParts.join(":") : void 0
239
+ };
128
240
  }
129
- function createLlamaCppCacheKeyData(model, outputDimensionality) {
241
+ async function resolveHuggingFaceArtifact(source, signal) {
242
+ const parsed = parseHuggingFaceSource(source);
243
+ let file = parsed.file;
244
+ let expectedSize;
245
+ if (!file) {
246
+ const tag = parsed.tag || "latest";
247
+ const manifestUrl = `https://huggingface.co/v2/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/manifests/${encodeURIComponent(tag)}`;
248
+ const { response, release } = await fetchWithSsrFGuard({
249
+ url: manifestUrl,
250
+ init: { headers: { "user-agent": "llama-cpp" } },
251
+ signal,
252
+ requireHttps: true,
253
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(manifestUrl),
254
+ auditContext: "llama-cpp-model-resolve"
255
+ });
256
+ try {
257
+ if (!response.ok) throw new Error(`Cannot resolve ${source}: HTTP ${response.status}`);
258
+ const ggufFile = asOptionalRecord(asOptionalRecord(await response.json())?.ggufFile);
259
+ file = typeof ggufFile?.rfilename === "string" ? ggufFile.rfilename : void 0;
260
+ expectedSize = typeof ggufFile?.size === "number" ? ggufFile.size : void 0;
261
+ if (!file) throw new Error(`Hugging Face did not return a GGUF file for ${source}`);
262
+ } finally {
263
+ await release();
264
+ }
265
+ }
266
+ const encodedFile = file.split("/").map(encodeURIComponent).join("/");
267
+ const url = `https://huggingface.co/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/resolve/${encodeURIComponent(parsed.revision)}/${encodedFile}?download=true`;
268
+ const treeUrl = `https://huggingface.co/api/models/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/tree/${encodeURIComponent(parsed.revision)}?recursive=true&expand=true`;
269
+ const { response: treeResponse, release: releaseTree } = await fetchWithSsrFGuard({
270
+ url: treeUrl,
271
+ signal,
272
+ requireHttps: true,
273
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(treeUrl),
274
+ auditContext: "llama-cpp-model-resolve"
275
+ });
276
+ let tree;
277
+ try {
278
+ if (!treeResponse.ok) throw new Error(`Cannot read Hugging Face integrity metadata for ${source}: HTTP ${treeResponse.status}`);
279
+ tree = await treeResponse.json();
280
+ } finally {
281
+ await releaseTree();
282
+ }
283
+ const fileRow = Array.isArray(tree) ? tree.map((entry) => asOptionalRecord(entry)).find((entry) => entry?.path === file) : void 0;
284
+ const lfs = asOptionalRecord(fileRow?.lfs);
285
+ const expectedSha256 = typeof lfs?.oid === "string" && /^[a-f\d]{64}$/iu.test(lfs.oid) ? lfs.oid.toLowerCase() : void 0;
286
+ expectedSize = expectedSize ?? (typeof fileRow?.size === "number" ? fileRow.size : void 0);
287
+ if (!expectedSha256) throw new Error(`Hugging Face did not publish a SHA-256 LFS identity for ${source}`);
130
288
  return {
131
- provider: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
132
- model,
133
- ...typeof outputDimensionality === "number" ? { outputDimensionality } : {}
289
+ source,
290
+ fileName: `hf_${[
291
+ parsed.user,
292
+ parsed.repository,
293
+ parsed.revision === "main" ? "" : parsed.revision,
294
+ ...file.split("/")
295
+ ].filter(Boolean).join("_").replace(/[^a-z\d._-]+/giu, "_")}`,
296
+ url,
297
+ expectedSize,
298
+ expectedSha256
134
299
  };
135
300
  }
136
- function resolveLlamaCppModelIdentity(local, modelPath, outputDimensionality) {
137
- const modelCacheDir = normalizeOptionalString(local.modelCacheDir) ?? path.join(os.homedir(), ".node-llama-cpp", "models");
138
- const resolvedDefaultModelPath = path.resolve(modelCacheDir, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_CACHE_FILE_NAME);
139
- const resolvedModelPath = /^(?:hf:|https?:\/\/)/i.test(modelPath) ? void 0 : path.resolve(modelCacheDir, modelPath);
140
- if (modelPath !== DEFAULT_LLAMA_CPP_EMBEDDING_MODEL && resolvedModelPath !== resolvedDefaultModelPath) return {
141
- model: modelPath,
142
- cacheKeyData: createLlamaCppCacheKeyData(modelPath, outputDimensionality),
143
- aliases: []
301
+ function defaultArtifact(source) {
302
+ if (source === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") return {
303
+ source,
304
+ fileName: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE,
305
+ url: `https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF/resolve/${DEFAULT_LLAMA_CPP_MODEL_REVISION}/gemma-4-E4B-it-Q4_K_M.gguf?download=true`,
306
+ expectedSize: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
307
+ expectedSha256: DEFAULT_LLAMA_CPP_MODEL_SHA256
144
308
  };
145
- 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);
147
- return {
148
- model: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
149
- cacheKeyData: createLlamaCppCacheKeyData(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, outputDimensionality),
150
- aliases: Array.from(aliasModels, (aliasModel) => ({
151
- model: aliasModel,
152
- cacheKeyData: createLlamaCppCacheKeyData(aliasModel, outputDimensionality)
153
- }))
309
+ if (source === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") return {
310
+ source,
311
+ fileName: DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE,
312
+ url: `https://huggingface.co/ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/resolve/${DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION}/embeddinggemma-300m-qat-Q8_0.gguf?download=true`,
313
+ expectedSize: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES,
314
+ expectedSha256: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256
154
315
  };
155
316
  }
156
- function textFromEmbeddingInput(input) {
157
- return typeof input === "string" ? input : input.text;
317
+ async function assertGguf(filePath) {
318
+ const handle = await fsp.open(filePath, "r").catch((error) => {
319
+ if ((error instanceof Error && "code" in error ? error.code : void 0) === "ENOENT") throw new Error(`Model file is missing: ${filePath}. Run interactive llama.cpp setup or correct params.modelPath.`, { cause: error });
320
+ throw error;
321
+ });
322
+ try {
323
+ const header = Buffer.alloc(4);
324
+ const { bytesRead } = await handle.read(header, 0, header.length, 0);
325
+ if (bytesRead !== 4 || header.toString("ascii") !== "GGUF") throw new Error(`Model is not a GGUF file: ${filePath}`);
326
+ } finally {
327
+ await handle.close();
328
+ }
158
329
  }
159
- function toMemoryEmbeddingInput(input) {
160
- return typeof input === "string" ? { text: input } : input;
330
+ async function resolveModelArtifact(source, signal) {
331
+ const known = defaultArtifact(source);
332
+ if (known) return known;
333
+ if (/^(?:hf|huggingface):/iu.test(source)) return await resolveHuggingFaceArtifact(source, signal);
334
+ if (/^https:\/\//iu.test(source)) {
335
+ const url = new URL(source);
336
+ const fileName = path.basename(decodeURIComponent(url.pathname));
337
+ if (!fileName.toLowerCase().includes(".gguf")) throw new Error(`Remote model URL must name a GGUF file: ${source}`);
338
+ return {
339
+ source,
340
+ fileName,
341
+ url: source
342
+ };
343
+ }
344
+ throw new Error(`Unsupported remote model URI: ${source}`);
345
+ }
346
+ async function ensureLlamaCppModel(params) {
347
+ const localSource = resolveHomePath(params.source);
348
+ if (!/^(?:hf|huggingface|https):/iu.test(localSource)) {
349
+ const localPath = path.isAbsolute(localSource) ? localSource : path.resolve(params.cacheDir, localSource);
350
+ await assertGguf(localPath);
351
+ return localPath;
352
+ }
353
+ const artifact = await resolveModelArtifact(localSource, params.signal);
354
+ const destination = path.join(params.cacheDir, artifact.fileName);
355
+ const pending = modelPromises.get(destination);
356
+ if (pending) return await pending;
357
+ const load = (async () => {
358
+ if (await fsp.stat(destination).then((stat) => stat.isFile()).catch(() => false)) if (artifact.expectedSha256) {
359
+ if (await sha256File(destination) === artifact.expectedSha256) return destination;
360
+ } else {
361
+ await assertGguf(destination);
362
+ return destination;
363
+ }
364
+ if (!params.download) throw new Error(`Model is not cached at ${destination}`);
365
+ await downloadVerifiedFile({
366
+ url: artifact.url,
367
+ destination,
368
+ expectedSha256: artifact.expectedSha256,
369
+ expectedSize: artifact.expectedSize,
370
+ requireServerDigest: !artifact.expectedSha256,
371
+ signal: params.signal,
372
+ onProgress: params.onProgress
373
+ });
374
+ await assertGguf(destination);
375
+ return destination;
376
+ })();
377
+ modelPromises.set(destination, load);
378
+ try {
379
+ return await load;
380
+ } finally {
381
+ if (modelPromises.get(destination) === load) modelPromises.delete(destination);
382
+ }
161
383
  }
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
- });
384
+ function assertIniValue(value, label) {
385
+ if (/\r|\n/u.test(value)) throw new Error(`${label} cannot contain a newline`);
386
+ return value;
168
387
  }
169
- function adaptMemoryEmbeddingProvider(provider) {
170
- const adapted = {
171
- id: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
172
- model: provider.model,
173
- maxInputTokens: provider.maxInputTokens,
174
- embed: async (input, callOptions) => await provider.embedQuery(textFromEmbeddingInput(input), { signal: callOptions?.signal }),
175
- embedBatch: async (inputs, callOptions) => {
176
- if (provider.embedBatchInputs) return await provider.embedBatchInputs(inputs.map(toMemoryEmbeddingInput), { signal: callOptions?.signal });
177
- return await provider.embedBatch(inputs.map(textFromEmbeddingInput), { signal: callOptions?.signal });
178
- },
179
- close: provider.close
180
- };
181
- copyLocalRuntimeFacts(provider, adapted);
182
- return adapted;
183
- }
184
- async function createLlamaCppMemoryEmbeddingProvider(options, runtimeOptions = {}) {
185
- const createOptions = buildMemoryCreateOptions(options, options.outputDimensionality);
186
- const local = readLocalOptions(createOptions);
187
- const provider = await createLocalEmbeddingProvider(createOptions, { nodeLlamaCppImportUrl: runtimeOptions.nodeLlamaCppImportUrl ?? resolveNodeLlamaCppImportUrl() });
188
- 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);
388
+ function renderLlamaServerPreset(params) {
389
+ const chatId = assertIniValue(params.chatModelId, "llama.cpp model id");
390
+ const embeddingId = assertIniValue(params.embeddingModelId, "llama.cpp embedding model id");
391
+ if (chatId.includes("]") || embeddingId.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
392
+ return [
393
+ "version = 1",
394
+ "",
395
+ `[${chatId}]`,
396
+ `model = ${assertIniValue(params.chatModelPath, "llama.cpp model path")}`,
397
+ `ctx-size = ${params.contextSize ?? 65536}`,
398
+ `n-predict = ${params.maxTokens ?? 2048}`,
399
+ "jinja = true",
400
+ "",
401
+ `[${embeddingId}]`,
402
+ `model = ${assertIniValue(params.embeddingModelPath, "llama.cpp embedding model path")}`,
403
+ "embedding = true",
404
+ ""
405
+ ].join("\n");
406
+ }
407
+ async function writePreset(presetPath, contents) {
408
+ await fsp.mkdir(path.dirname(presetPath), { recursive: true });
409
+ const temporary = `${presetPath}.tmp-${randomUUID()}`;
410
+ await fsp.writeFile(temporary, contents, { mode: 384 });
411
+ await fsp.rename(temporary, presetPath);
412
+ }
413
+ async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT) {
414
+ const tryPort = async (port) => await new Promise((resolve) => {
415
+ const server = net.createServer();
416
+ server.unref();
417
+ server.once("error", () => resolve(void 0));
418
+ server.listen(port, "127.0.0.1", () => {
419
+ const address = server.address();
420
+ const selected = typeof address === "object" && address ? address.port : void 0;
421
+ server.close(() => resolve(selected));
422
+ });
423
+ });
424
+ return await tryPort(preferred) ?? await tryPort(0) ?? Promise.reject(/* @__PURE__ */ new Error("No loopback port is available for llama-server"));
425
+ }
426
+ async function prepareManagedLlamaServer(params) {
427
+ const { command, asset } = await ensureLlamaServerInstalled();
428
+ const { presetPath } = resolveManagedLlamaServerPaths(asset);
429
+ await writePreset(presetPath, renderLlamaServerPreset({
430
+ chatModelId: params.chatModelId ?? "gemma-4-e4b-it-q4_k_m",
431
+ chatModelPath: params.chatModelPath,
432
+ contextSize: params.contextSize,
433
+ maxTokens: params.maxTokens,
434
+ embeddingModelId: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
435
+ embeddingModelPath: params.embeddingModelPath
436
+ }));
437
+ const port = params.port ?? await findAvailableLlamaServerPort();
438
+ const rootUrl = `http://127.0.0.1:${port}`;
194
439
  return {
195
- provider: identifiedProvider,
196
- runtime: createLlamaCppEmbeddingProviderRuntime(identity)
440
+ command,
441
+ presetPath,
442
+ baseUrl: `${rootUrl}/v1`,
443
+ healthUrl: `${rootUrl}/health`,
444
+ args: [
445
+ "--host",
446
+ "127.0.0.1",
447
+ "--port",
448
+ String(port),
449
+ "--models-preset",
450
+ presetPath,
451
+ "--models-max",
452
+ "2",
453
+ "--metrics",
454
+ "--no-ui"
455
+ ],
456
+ backend: asset.backend
197
457
  };
198
458
  }
199
- async function createLlamaCppEmbeddingProviderResult(options, runtimeOptions = {}) {
200
- const result = await createLlamaCppMemoryEmbeddingProvider(buildMemoryCreateOptions(options, options.dimensions), runtimeOptions);
201
- return {
202
- provider: result.provider ? adaptMemoryEmbeddingProvider(result.provider) : null,
203
- runtime: result.runtime
204
- };
459
+ async function ensureManagedLlamaServerForChat(params) {
460
+ if (!params.provider.localService || !params.provider.baseUrl) return;
461
+ const cacheDir = resolveLlamaCppModelCacheDir(params.provider);
462
+ const key = JSON.stringify([
463
+ params.provider.baseUrl,
464
+ params.model.id,
465
+ params.model.params,
466
+ cacheDir
467
+ ]);
468
+ const pending = chatPreparationPromises.get(key) ?? (async () => {
469
+ let chatModelPath = resolveCachedLlamaCppModelPath({
470
+ model: params.model,
471
+ provider: params.provider
472
+ });
473
+ if (!chatModelPath && resolveLlamaCppModelSource(params.model) === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") {
474
+ const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), "hf_unsloth_gemma-4-E4B-it-GGUF_gemma-4-E4B-it-Q4_K_M.gguf");
475
+ if (await fsp.stat(legacy).then((stat) => stat.isFile()).catch(() => false)) chatModelPath = legacy;
476
+ }
477
+ chatModelPath = await ensureLlamaCppModel({
478
+ source: chatModelPath ?? resolveLlamaCppModelSource(params.model),
479
+ cacheDir,
480
+ download: false
481
+ });
482
+ const configuredContext = params.model.params?.contextSize;
483
+ const port = Number(new URL(params.provider.baseUrl).port);
484
+ await prepareManagedLlamaServer({
485
+ chatModelId: params.model.id,
486
+ chatModelPath,
487
+ contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : params.model.contextTokens,
488
+ maxTokens: params.model.maxTokens,
489
+ embeddingModelPath: path.join(cacheDir, "hf_ggml-org_embeddinggemma-300m-qat-Q8_0.gguf"),
490
+ port: Number.isInteger(port) && port > 0 ? port : void 0
491
+ });
492
+ })();
493
+ chatPreparationPromises.set(key, pending);
494
+ try {
495
+ await pending;
496
+ } catch (error) {
497
+ if (chatPreparationPromises.get(key) === pending) chatPreparationPromises.delete(key);
498
+ throw error;
499
+ }
205
500
  }
206
- function buildMemoryCreateOptions(options, outputDimensionality) {
207
- const local = readLocalOptions(options);
208
- const modelPath = normalizeOptionalString(local.modelPath) || DEFAULT_LLAMA_CPP_EMBEDDING_MODEL;
209
- return {
210
- config: options.config,
211
- agentDir: options.agentDir,
212
- provider: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
213
- fallback: "none",
214
- remote: options.remote,
215
- model: modelPath,
216
- inputType: options.inputType,
217
- queryInputType: options.queryInputType,
218
- documentInputType: options.documentInputType,
219
- local: {
220
- ...local,
221
- modelPath
222
- },
223
- outputDimensionality
224
- };
501
+ async function fetchEndpoint(url, accept) {
502
+ try {
503
+ const configuredLocalOriginBaseUrl = new URL(url).origin;
504
+ const { response, release } = await fetchConfiguredLocalOriginWithSsrFGuard({
505
+ url,
506
+ configuredLocalOriginBaseUrl,
507
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(configuredLocalOriginBaseUrl),
508
+ timeoutMs: 2500,
509
+ auditContext: "llama-server-inspect"
510
+ });
511
+ try {
512
+ if (!response.ok) return { ok: false };
513
+ return {
514
+ ok: true,
515
+ value: accept === "json" ? await response.json() : await response.text()
516
+ };
517
+ } finally {
518
+ await release();
519
+ }
520
+ } catch {
521
+ return { ok: false };
522
+ }
225
523
  }
226
- function createLlamaCppEmbeddingProviderRuntime(identity) {
524
+ async function inspectLlamaServerRuntime(params) {
525
+ const root = params.baseUrl.replace(/\/v1\/?$/u, "").replace(/\/+$/u, "");
526
+ const query = `model=${encodeURIComponent(params.modelId)}&autoload=false`;
527
+ const [health, models, props, metrics] = await Promise.all([
528
+ fetchEndpoint(`${root}/health`, "json"),
529
+ fetchEndpoint(`${root}/models`, "json"),
530
+ fetchEndpoint(`${root}/props?${query}`, "json"),
531
+ fetchEndpoint(`${root}/metrics?${query}`, "text")
532
+ ]);
533
+ const propsRecord = asOptionalRecord(props.value);
534
+ const modalities = asOptionalRecord(propsRecord?.modalities);
535
+ const modelsRecord = asOptionalRecord(models.value);
536
+ const selected = (Array.isArray(modelsRecord?.data) ? modelsRecord.data : []).map((row) => asOptionalRecord(row)).find((row) => row?.id === params.modelId);
537
+ const pathValue = typeof propsRecord?.model_path === "string" ? propsRecord.model_path : typeof selected?.path === "string" ? selected.path : void 0;
227
538
  return {
228
- id: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
229
- inlineQueryTimeoutMs: 5 * 6e4,
230
- inlineBatchTimeoutMs: 10 * 6e4,
231
- cacheKeyData: identity.cacheKeyData,
232
- ...identity.aliases.length > 0 ? { indexIdentityAliases: identity.aliases } : {}
539
+ engine: "llama.cpp",
540
+ state: health.ok && models.ok && props.ok && metrics.ok && !params.loadError ? "ready" : "failed",
541
+ backend: params.backend,
542
+ buildInfo: typeof propsRecord?.build_info === "string" ? propsRecord.build_info : void 0,
543
+ model: {
544
+ id: params.modelId,
545
+ ...pathValue ? { path: pathValue } : {}
546
+ },
547
+ capabilities: {
548
+ vision: modalities?.vision === true,
549
+ draft: false
550
+ },
551
+ endpoints: {
552
+ health: health.ok ? "ready" : "unavailable",
553
+ models: models.ok ? "ready" : "unavailable",
554
+ props: props.ok ? "ready" : "unavailable",
555
+ metrics: metrics.ok ? "ready" : "unavailable"
556
+ },
557
+ ...params.loadError ? { loadError: params.loadError } : {}
233
558
  };
234
559
  }
235
- const llamaCppEmbeddingProviderAdapter = {
236
- id: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
237
- defaultModel: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
238
- transport: "local",
239
- formatSetupError: formatLlamaCppSetupError,
240
- resolveIndexIdentity: (options) => {
241
- const createOptions = buildMemoryCreateOptions(options, options.dimensions);
242
- const local = readLocalOptions(createOptions);
243
- return resolveLlamaCppModelIdentity(local, normalizeOptionalString(local.modelPath) ?? DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, createOptions.outputDimensionality);
244
- },
245
- create: async (options) => await createLlamaCppEmbeddingProviderResult(options)
246
- };
247
560
  //#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) {
561
+ //#region extensions/llama-cpp/src/embedding-provider.ts
562
+ const LOCAL_EMBEDDING_RUNTIME_FACTS = Symbol.for("openclaw.localEmbeddingRuntimeFacts");
563
+ const preparedEmbeddingServers = /* @__PURE__ */ new Map();
564
+ function readLocalOptions(options) {
565
+ return options.local ?? {};
566
+ }
567
+ function createCacheKeyData(model, dimensions) {
253
568
  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
- }
569
+ provider: "local",
570
+ model,
571
+ ...typeof dimensions === "number" ? { outputDimensionality: dimensions } : {}
266
572
  };
267
573
  }
268
- function buildMessage(params) {
574
+ function resolveModelIdentity(local, modelPath, dimensions) {
575
+ const configuredCacheDir = normalizeOptionalString(local.modelCacheDir) ?? resolveLlamaCppModelCacheDir();
576
+ const currentDefaultPath = path.resolve(configuredCacheDir, DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE);
577
+ const legacyDefaultPath = path.resolve(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE);
578
+ const resolvedPath = /^(?:hf:|https?:\/\/)/iu.test(modelPath) ? void 0 : path.resolve(configuredCacheDir, modelPath);
579
+ if (!(modelPath === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf" || resolvedPath === currentDefaultPath || resolvedPath === legacyDefaultPath)) return {
580
+ model: modelPath,
581
+ cacheKeyData: createCacheKeyData(modelPath, dimensions),
582
+ aliases: []
583
+ };
584
+ const aliases = /* @__PURE__ */ new Set([
585
+ currentDefaultPath,
586
+ legacyDefaultPath,
587
+ DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE
588
+ ]);
589
+ if (modelPath !== "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") aliases.add(modelPath);
269
590
  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 } : {}
591
+ model: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
592
+ cacheKeyData: createCacheKeyData(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, dimensions),
593
+ aliases: [...aliases].map((model) => ({
594
+ model,
595
+ cacheKeyData: createCacheKeyData(model, dimensions)
596
+ }))
279
597
  };
280
598
  }
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)}`
599
+ function resolveConfiguredProvider(options) {
600
+ const provider = options.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
601
+ if (!provider?.localService || !provider.baseUrl) throw new Error("Local embeddings need the managed llama.cpp server config. Run `openclaw configure`, choose llama.cpp once, then retry `openclaw memory status --deep`.");
602
+ return provider;
603
+ }
604
+ function resolveProviderPort(provider) {
605
+ const port = Number(new URL(provider.baseUrl ?? "").port);
606
+ if (!Number.isInteger(port) || port <= 0) throw new Error("Managed llama.cpp provider baseUrl must include a loopback port.");
607
+ return port;
608
+ }
609
+ async function prepareEmbeddingServer(options, embeddingSource) {
610
+ const provider = resolveConfiguredProvider(options);
611
+ const configuredPrimary = options.config.agents?.defaults?.model;
612
+ const primaryRef = typeof configuredPrimary === "string" ? configuredPrimary : configuredPrimary?.primary;
613
+ const primaryId = primaryRef?.startsWith(`llama-cpp/`) ? primaryRef.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
614
+ const chatModel = provider.models.find((model) => model.id === primaryId) ?? provider.models.find((model) => model.id !== "gemma-4-e4b-it-q4_k_m") ?? provider.models[0];
615
+ if (!chatModel) throw new Error("Managed llama.cpp provider has no chat model preset.");
616
+ const cacheDir = resolveLlamaCppModelCacheDir(provider);
617
+ const key = JSON.stringify([
618
+ provider.baseUrl,
619
+ chatModel.id,
620
+ embeddingSource,
621
+ cacheDir
622
+ ]);
623
+ const pending = preparedEmbeddingServers.get(key) ?? (async () => {
624
+ const [chatModelPath, embeddingModelPath] = await Promise.all([ensureLlamaCppModel({
625
+ source: resolveLlamaCppModelSource(chatModel),
626
+ cacheDir,
627
+ download: false
628
+ }), ensureLlamaCppModel({
629
+ source: embeddingSource,
630
+ cacheDir,
631
+ download: true
632
+ })]);
633
+ const configuredContext = chatModel.params?.contextSize;
634
+ await prepareManagedLlamaServer({
635
+ chatModelId: chatModel.id,
636
+ chatModelPath,
637
+ contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : chatModel.contextTokens,
638
+ maxTokens: chatModel.maxTokens,
639
+ embeddingModelPath,
640
+ port: resolveProviderPort(provider)
351
641
  });
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;
642
+ })();
643
+ preparedEmbeddingServers.set(key, pending);
397
644
  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;
645
+ await pending;
411
646
  } catch (error) {
412
- await context?.dispose();
413
- await model.dispose();
647
+ if (preparedEmbeddingServers.get(key) === pending) preparedEmbeddingServers.delete(key);
414
648
  throw error;
415
649
  }
416
650
  }
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;
651
+ function wrapProvider(params) {
652
+ let runtimeFacts;
653
+ const refreshFacts = async (loadError) => {
654
+ runtimeFacts = await inspectLlamaServerRuntime({
655
+ baseUrl: params.baseUrl,
656
+ modelId: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
657
+ backend: selectLlamaServerAsset().backend,
658
+ loadError
659
+ });
660
+ };
661
+ const withFacts = async (operation) => {
662
+ try {
663
+ const value = await operation();
664
+ await refreshFacts();
665
+ return value;
666
+ } catch (error) {
667
+ await refreshFacts(error instanceof Error ? error.message : String(error));
668
+ throw error;
428
669
  }
670
+ };
671
+ const wrapped = {
672
+ id: "local",
673
+ model: params.canonicalModel,
674
+ dimensions: params.provider.dimensions,
675
+ maxInputTokens: params.provider.maxInputTokens,
676
+ embed: async (input, callOptions) => await withFacts(async () => await params.provider.embed(input, callOptions)),
677
+ embedBatch: async (inputs, callOptions) => await withFacts(async () => await params.provider.embedBatch(inputs, callOptions)),
678
+ close: params.provider.close
679
+ };
680
+ Object.defineProperty(wrapped, LOCAL_EMBEDDING_RUNTIME_FACTS, {
681
+ enumerable: false,
682
+ value: () => runtimeFacts
429
683
  });
684
+ return wrapped;
430
685
  }
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();
686
+ const llamaCppEmbeddingProviderAdapter = {
687
+ id: "local",
688
+ defaultModel: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
689
+ transport: "local",
690
+ formatSetupError: (error) => `Managed local embeddings are unavailable. Run \`openclaw configure\`, choose llama.cpp, and retry. ${error instanceof Error ? error.message : String(error)}`,
691
+ resolveIndexIdentity: (options) => {
692
+ const local = readLocalOptions(options);
693
+ return resolveModelIdentity(local, normalizeOptionalString(local.modelPath) ?? "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf", options.dimensions);
694
+ },
695
+ create: async (options) => {
696
+ const local = readLocalOptions(options);
697
+ const modelPath = normalizeOptionalString(local.modelPath) ?? "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf";
698
+ await prepareEmbeddingServer(options, modelPath);
699
+ const genericAdapter = getEmbeddingProvider("openai-compatible", options.config);
700
+ if (!genericAdapter) throw new Error("OpenAI-compatible embedding transport is unavailable.");
701
+ const result = await genericAdapter.create({
702
+ ...options,
703
+ provider: LLAMA_CPP_PROVIDER_ID,
704
+ model: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
705
+ remote: void 0
706
+ });
707
+ if (!result.provider) return result;
708
+ const identity = resolveModelIdentity(local, modelPath, options.dimensions);
709
+ return {
710
+ provider: wrapProvider({
711
+ provider: result.provider,
712
+ canonicalModel: identity.model,
713
+ baseUrl: resolveConfiguredProvider(options).baseUrl ?? ""
714
+ }),
715
+ runtime: {
716
+ id: "local",
717
+ inlineQueryTimeoutMs: 5 * 6e4,
718
+ inlineBatchTimeoutMs: 10 * 6e4,
719
+ cacheKeyData: identity.cacheKeyData,
720
+ ...identity.aliases.length > 0 ? { indexIdentityAliases: identity.aliases } : {}
581
721
  }
582
722
  };
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
723
+ }
591
724
  };
592
725
  //#endregion
593
726
  //#region extensions/llama-cpp/src/setup.ts
594
727
  const BYTES_PER_GB = 1e9;
595
728
  const BYTES_PER_MB = 1e6;
596
- function formatLlamaCppDownloadProgress(params) {
729
+ function formatDownloadProgress(label, params) {
597
730
  const downloadedSize = Math.max(0, params.downloadedSize);
598
731
  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)`;
732
+ return `Downloading ${label}… ${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
733
  }
601
734
  function formatRamGb(totalmemBytes) {
602
- return (totalmemBytes / 1024 ** 3).toFixed(1).replace(/\.0$/, "");
735
+ return (totalmemBytes / 1024 ** 3).toFixed(1).replace(/\.0$/u, "");
603
736
  }
604
737
  function readPrimaryModel(config) {
605
738
  const model = config.agents?.defaults?.model;
@@ -609,118 +742,145 @@ function configuredCandidates(config) {
609
742
  const existing = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
610
743
  const provider = buildLlamaCppProviderConfig(existing);
611
744
  const primary = readPrimaryModel(config);
612
- const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(10) : void 0;
745
+ const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
613
746
  return provider.models.map((model) => ({
614
747
  model,
615
748
  provider
616
749
  })).toSorted((a, b) => Number(b.model.id === primaryId) - Number(a.model.id === primaryId));
617
750
  }
618
751
  async function isFile(filePath) {
619
- try {
620
- return (await fs.stat(filePath)).isFile();
621
- } catch {
622
- return false;
752
+ return await fsp.stat(filePath).then((stat) => stat.isFile()).catch(() => false);
753
+ }
754
+ async function resolveCachedCandidate(candidate) {
755
+ const source = resolveLlamaCppModelSource(candidate.model);
756
+ const resolved = resolveCachedLlamaCppModelPath(candidate);
757
+ if (resolved && await isFile(resolved)) return resolved;
758
+ if (candidate.model.id === "gemma-4-e4b-it-q4_k_m") {
759
+ const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
760
+ if (await isFile(legacy)) return legacy;
623
761
  }
762
+ if (/^(?:hf|huggingface|https):/iu.test(source)) return await ensureLlamaCppModel({
763
+ source,
764
+ cacheDir: resolveLlamaCppModelCacheDir(candidate.provider),
765
+ download: false
766
+ }).catch(() => void 0);
624
767
  }
625
- async function detectLlamaCppSetup(ctx) {
626
- let runtime;
768
+ function readConfiguredPort(provider) {
627
769
  try {
628
- runtime = await importNodeLlamaCpp();
770
+ const url = new URL(provider?.baseUrl ?? "");
771
+ if (url.hostname !== "127.0.0.1" && url.hostname !== "localhost" && url.hostname !== "[::1]") return;
772
+ const port = Number(url.port);
773
+ return Number.isInteger(port) && port > 0 ? port : void 0;
629
774
  } catch {
630
- return null;
775
+ return;
631
776
  }
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
777
  }
645
- function buildSetupResult(config, defaultModel = DEFAULT_LLAMA_CPP_MODEL_REF) {
778
+ function buildSetupResult(params) {
646
779
  return {
647
780
  profiles: [],
648
- defaultModel,
781
+ defaultModel: params.defaultModel ?? DEFAULT_LLAMA_CPP_MODEL_REF,
649
782
  configPatch: { models: {
650
- mode: config.models?.mode ?? "merge",
651
- providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig(config.models?.providers?.[LLAMA_CPP_PROVIDER_ID]) }
783
+ mode: params.config.models?.mode ?? "merge",
784
+ providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig(params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID], params.managed) }
652
785
  } }
653
786
  };
654
787
  }
788
+ async function detectLlamaCppSetup(ctx) {
789
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
790
+ const command = existing?.localService?.command;
791
+ const presetPath = existing?.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset");
792
+ if (!command || !path.isAbsolute(command) || !await isFile(command) || !presetPath || !await isFile(presetPath)) return null;
793
+ for (const candidate of configuredCandidates(ctx.config)) if (await resolveCachedCandidate(candidate)) return {
794
+ modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
795
+ detail: "Managed llama.cpp server ready"
796
+ };
797
+ return null;
798
+ }
655
799
  async function prepareLlamaCppSetup(ctx) {
656
- return (await detectLlamaCppSetup(ctx))?.modelRef === ctx.modelRef ? buildSetupResult(ctx.config, ctx.modelRef) : null;
800
+ const detected = await detectLlamaCppSetup(ctx);
801
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
802
+ if (detected?.modelRef !== ctx.modelRef || !existing?.localService?.command) return null;
803
+ const baseUrl = existing.baseUrl?.replace(/\/+$/u, "") ?? "";
804
+ const rootUrl = baseUrl.replace(/\/v1$/u, "");
805
+ return buildSetupResult({
806
+ config: ctx.config,
807
+ defaultModel: ctx.modelRef,
808
+ managed: {
809
+ command: existing.localService.command,
810
+ presetPath: existing.localService.args?.find((_, index, args) => args[index - 1] === "--models-preset") ?? resolveManagedLlamaServerPaths(selectLlamaServerAsset()).presetPath,
811
+ baseUrl,
812
+ healthUrl: existing.localService.healthUrl ?? `${rootUrl}/health`,
813
+ args: existing.localService.args ?? [],
814
+ backend: selectLlamaServerAsset().backend
815
+ }
816
+ });
657
817
  }
658
818
  async function runLlamaCppSetup(ctx) {
659
819
  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)) {
820
+ const candidates = configuredCandidates(ctx.config);
821
+ let selected = candidates[0];
822
+ let chatModelPath = selected ? await resolveCachedCandidate(selected) : void 0;
823
+ if (!chatModelPath) {
824
+ selected = candidates.find((candidate) => candidate.model.id === DEFAULT_LLAMA_CPP_MODEL_ID);
669
825
  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");
826
+ if (!selected || !meetsLlamaCppDefaultModelRamFloor(totalmemBytes)) {
827
+ await ctx.prompter.note(`This Gateway has ${formatRamGb(totalmemBytes)} GB RAM; the recommended model needs 16 GB+. Configure an existing smaller GGUF, use Ollama or LM Studio, or choose a cloud provider.`, "Setup skipped");
672
828
  return { profiles: [] };
673
829
  }
674
830
  if (!await ctx.prompter.confirm({
675
- message: "Download Gemma 4 E4B IT Q4_K_M (about 5.0 GB) for local llama.cpp inference?",
831
+ message: "OpenClaw will install a verified llama.cpp server and download Gemma 4 E4B IT Q4_K_M (about 5.0 GB) plus the local embedding model (about 0.3 GB). Continue?",
676
832
  initialValue: false
677
833
  })) {
678
- await ctx.prompter.note("Local model download skipped.", "Setup skipped");
834
+ await ctx.prompter.note("Local model setup skipped.", "Setup skipped");
679
835
  return { profiles: [] };
680
836
  }
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
837
  }
715
- return buildSetupResult(ctx.config);
838
+ if (!selected) throw new Error("llama.cpp setup could not resolve a chat model");
839
+ const progress = ctx.prompter.progress("Preparing managed llama.cpp server…");
840
+ try {
841
+ const cacheDir = resolveLlamaCppModelCacheDir(existing);
842
+ chatModelPath ??= await ensureLlamaCppModel({
843
+ source: resolveLlamaCppModelSource(selected.model),
844
+ cacheDir,
845
+ download: true,
846
+ signal: ctx.signal,
847
+ onProgress: (status) => progress.update(formatDownloadProgress("Gemma 4 E4B", status))
848
+ });
849
+ const embeddingModelPath = await ensureLlamaCppModel({
850
+ source: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
851
+ cacheDir,
852
+ download: true,
853
+ signal: ctx.signal,
854
+ onProgress: (status) => progress.update(formatDownloadProgress("EmbeddingGemma", status))
855
+ });
856
+ const configuredContext = selected.model.params?.contextSize;
857
+ const contextSize = typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : selected.model.contextTokens;
858
+ const managed = await prepareManagedLlamaServer({
859
+ chatModelId: selected.model.id,
860
+ chatModelPath,
861
+ contextSize,
862
+ maxTokens: selected.model.maxTokens,
863
+ embeddingModelPath,
864
+ port: readConfiguredPort(existing)
865
+ });
866
+ progress.stop("Managed llama.cpp server prepared");
867
+ return buildSetupResult({
868
+ config: ctx.config,
869
+ managed,
870
+ defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${selected.model.id}`
871
+ });
872
+ } catch (error) {
873
+ progress.stop("llama.cpp setup failed");
874
+ const detail = error instanceof Error ? error.message : String(error);
875
+ throw new Error(`Managed llama.cpp setup failed. Run openclaw doctor, fix the reported runtime or model issue, then retry. ${detail}`, { cause: error });
876
+ }
716
877
  }
717
- if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.llamaCppSetupTestApi")] = { formatLlamaCppDownloadProgress };
718
878
  //#endregion
719
879
  //#region extensions/llama-cpp/index.ts
720
880
  var llama_cpp_default = definePluginEntry({
721
881
  id: "llama-cpp",
722
882
  name: "llama.cpp Provider",
723
- description: "Local GGUF text inference and embeddings through node-llama-cpp",
883
+ description: "Managed local llama.cpp server for GGUF chat and embeddings",
724
884
  register(api) {
725
885
  api.registerEmbeddingProvider(llamaCppEmbeddingProviderAdapter);
726
886
  api.registerProvider({
@@ -730,7 +890,7 @@ var llama_cpp_default = definePluginEntry({
730
890
  auth: [{
731
891
  id: "local",
732
892
  label: LLAMA_CPP_PROVIDER_LABEL,
733
- hint: "In-process local GGUF model (about 5.0 GB download; requires 16 GB RAM)",
893
+ hint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
734
894
  kind: "custom",
735
895
  appGuidedSetup: {
736
896
  detect: detectLlamaCppSetup,
@@ -746,26 +906,38 @@ var llama_cpp_default = definePluginEntry({
746
906
  order: "late",
747
907
  run: async () => ({ provider: buildLlamaCppProviderConfig() })
748
908
  },
749
- createStreamFn: ({ config, provider }) => createLlamaCppStreamFn({ providerConfig: config?.models?.providers?.[provider] }),
750
909
  resolveSyntheticAuth: () => ({
751
910
  apiKey: resolveLlamaCppSyntheticApiKey(),
752
- source: "local llama.cpp runtime",
911
+ source: "managed local llama.cpp server",
753
912
  mode: "api-key"
754
913
  }),
914
+ wrapStreamFn: (ctx) => {
915
+ const inner = ctx.streamFn;
916
+ const providerConfig = ctx.config?.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
917
+ const selectedModel = ctx.model;
918
+ if (!inner || !providerConfig?.localService || !selectedModel) return;
919
+ return async (model, context, options) => {
920
+ await ensureManagedLlamaServerForChat({
921
+ provider: providerConfig,
922
+ model: selectedModel
923
+ });
924
+ return inner(model, context, options);
925
+ };
926
+ },
755
927
  ...buildProviderToolCompatFamilyHooks("llamacpp-gbnf"),
756
928
  wizard: {
757
929
  setup: {
758
930
  choiceId: LLAMA_CPP_PROVIDER_ID,
759
931
  choiceLabel: LLAMA_CPP_PROVIDER_LABEL,
760
- choiceHint: "In-process local model (about 5.0 GB download; requires 16 GB RAM)",
932
+ choiceHint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
761
933
  groupId: LLAMA_CPP_PROVIDER_ID,
762
934
  groupLabel: "Local llama.cpp",
763
935
  groupHint: "No API key required",
764
936
  methodId: "local"
765
937
  },
766
938
  modelPicker: {
767
- label: "llama.cpp (local GGUF)",
768
- hint: "Run a GGUF model in the OpenClaw process",
939
+ label: "llama.cpp",
940
+ hint: "Run a GGUF model with OpenClaw's managed local llama.cpp server",
769
941
  methodId: "local"
770
942
  }
771
943
  }