@openclaw/llama-cpp-provider 2026.7.2-beta.5 → 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/README.md +17 -18
- package/dist/doctor-contract-api.js +55 -0
- package/dist/index.js +798 -624
- package/dist/llama-server-assets-BEF3s_UC.js +181 -0
- package/openclaw.plugin.json +7 -3
- package/package.json +8 -7
package/dist/index.js
CHANGED
|
@@ -1,604 +1,738 @@
|
|
|
1
|
-
import {
|
|
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
|
+
import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
|
|
3
4
|
import os from "node:os";
|
|
4
5
|
import path from "node:path";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import fs from "node:fs
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
const
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
if (
|
|
34
|
-
|
|
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");
|
|
35
50
|
}
|
|
36
|
-
function
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
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;
|
|
40
58
|
}
|
|
41
|
-
function
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
+
}
|
|
49
119
|
}
|
|
50
|
-
function
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
cacheRead: 0,
|
|
61
|
-
cacheWrite: 0
|
|
62
|
-
},
|
|
63
|
-
contextWindow: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
|
|
64
|
-
contextTokens: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
|
|
65
|
-
maxTokens: 2048,
|
|
66
|
-
params: {
|
|
67
|
-
modelPath: DEFAULT_LLAMA_CPP_MODEL_URI,
|
|
68
|
-
contextSize: "auto"
|
|
69
|
-
},
|
|
70
|
-
compat: {
|
|
71
|
-
supportsTools: true,
|
|
72
|
-
supportsUsageInStreaming: true
|
|
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 });
|
|
73
130
|
}
|
|
74
|
-
}
|
|
131
|
+
}
|
|
75
132
|
}
|
|
76
|
-
function
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
};
|
|
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}`);
|
|
86
143
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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
|
+
});
|
|
92
151
|
}
|
|
93
|
-
function
|
|
94
|
-
|
|
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 });
|
|
95
157
|
}
|
|
96
|
-
function
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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
|
+
}
|
|
115
209
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
+
}
|
|
124
223
|
}
|
|
125
|
-
|
|
126
|
-
|
|
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
|
+
};
|
|
127
240
|
}
|
|
128
|
-
function
|
|
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}`);
|
|
129
288
|
return {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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
|
|
133
299
|
};
|
|
134
300
|
}
|
|
135
|
-
function
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
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
|
|
143
308
|
};
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
model: aliasModel,
|
|
151
|
-
cacheKeyData: createLlamaCppCacheKeyData(aliasModel, outputDimensionality)
|
|
152
|
-
}))
|
|
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
|
|
153
315
|
};
|
|
154
316
|
}
|
|
155
|
-
function
|
|
156
|
-
|
|
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
|
+
}
|
|
157
329
|
}
|
|
158
|
-
function
|
|
159
|
-
|
|
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
|
+
}
|
|
160
383
|
}
|
|
161
|
-
function
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
enumerable: false,
|
|
165
|
-
value: getRuntimeFacts
|
|
166
|
-
});
|
|
384
|
+
function assertIniValue(value, label) {
|
|
385
|
+
if (/\r|\n/u.test(value)) throw new Error(`${label} cannot contain a newline`);
|
|
386
|
+
return value;
|
|
167
387
|
}
|
|
168
|
-
function
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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}`;
|
|
193
439
|
return {
|
|
194
|
-
|
|
195
|
-
|
|
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
|
|
196
457
|
};
|
|
197
458
|
}
|
|
198
|
-
async function
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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
|
+
}
|
|
204
500
|
}
|
|
205
|
-
function
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
|
|
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
|
+
}
|
|
224
523
|
}
|
|
225
|
-
function
|
|
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;
|
|
226
538
|
return {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
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 } : {}
|
|
232
558
|
};
|
|
233
559
|
}
|
|
234
|
-
const llamaCppEmbeddingProviderAdapter = {
|
|
235
|
-
id: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
|
|
236
|
-
defaultModel: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
|
|
237
|
-
transport: "local",
|
|
238
|
-
formatSetupError: formatLlamaCppSetupError,
|
|
239
|
-
resolveIndexIdentity: (options) => {
|
|
240
|
-
const createOptions = buildMemoryCreateOptions(options, options.dimensions);
|
|
241
|
-
const local = readLocalOptions(createOptions);
|
|
242
|
-
return resolveLlamaCppModelIdentity(local, normalizeOptionalString(local.modelPath) ?? DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, createOptions.outputDimensionality);
|
|
243
|
-
},
|
|
244
|
-
create: async (options) => await createLlamaCppEmbeddingProviderResult(options)
|
|
245
|
-
};
|
|
246
560
|
//#endregion
|
|
247
|
-
//#region extensions/llama-cpp/src/
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
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) {
|
|
252
568
|
return {
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
cacheWrite: 0,
|
|
257
|
-
totalTokens: input + output,
|
|
258
|
-
cost: {
|
|
259
|
-
input: 0,
|
|
260
|
-
output: 0,
|
|
261
|
-
cacheRead: 0,
|
|
262
|
-
cacheWrite: 0,
|
|
263
|
-
total: 0
|
|
264
|
-
}
|
|
569
|
+
provider: "local",
|
|
570
|
+
model,
|
|
571
|
+
...typeof dimensions === "number" ? { outputDimensionality: dimensions } : {}
|
|
265
572
|
};
|
|
266
573
|
}
|
|
267
|
-
function
|
|
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);
|
|
268
590
|
return {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
usage: params.usage ?? zeroCostUsage(),
|
|
276
|
-
timestamp: Date.now(),
|
|
277
|
-
...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
|
+
}))
|
|
278
597
|
};
|
|
279
598
|
}
|
|
280
|
-
function
|
|
281
|
-
|
|
282
|
-
if (!
|
|
283
|
-
return
|
|
284
|
-
}
|
|
285
|
-
function
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
}
|
|
323
|
-
if (part.type === "thinking") {
|
|
324
|
-
if (part.thinking) response.push({
|
|
325
|
-
type: "segment",
|
|
326
|
-
segmentType: "thought",
|
|
327
|
-
text: part.thinking,
|
|
328
|
-
ended: true
|
|
329
|
-
});
|
|
330
|
-
continue;
|
|
331
|
-
}
|
|
332
|
-
const result = toolResults.get(part.id);
|
|
333
|
-
if (result !== void 0) consumedToolResults.add(part.id);
|
|
334
|
-
response.push({
|
|
335
|
-
type: "functionCall",
|
|
336
|
-
name: part.name,
|
|
337
|
-
params: part.arguments,
|
|
338
|
-
result: result ?? ""
|
|
339
|
-
});
|
|
340
|
-
}
|
|
341
|
-
history.push({
|
|
342
|
-
type: "model",
|
|
343
|
-
response
|
|
344
|
-
});
|
|
345
|
-
continue;
|
|
346
|
-
}
|
|
347
|
-
if (!consumedToolResults.has(message.toolCallId)) history.push({
|
|
348
|
-
type: "user",
|
|
349
|
-
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)
|
|
350
641
|
});
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
}
|
|
354
|
-
function mapToolsToLlamaFunctions(context) {
|
|
355
|
-
if (!context.tools?.length) return;
|
|
356
|
-
return Object.fromEntries(context.tools.map((tool) => [tool.name, {
|
|
357
|
-
description: tool.description,
|
|
358
|
-
params: tool.parameters
|
|
359
|
-
}]));
|
|
360
|
-
}
|
|
361
|
-
function readContextSizeValue(value) {
|
|
362
|
-
if (value === "auto") return value;
|
|
363
|
-
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
|
|
364
|
-
}
|
|
365
|
-
function resolveContextSize(model, providerConfig) {
|
|
366
|
-
const configured = readContextSizeValue(model.params?.contextSize) ?? readContextSizeValue(providerConfig?.params?.contextSize);
|
|
367
|
-
if (typeof configured === "number") return configured;
|
|
368
|
-
return { max: typeof model.contextTokens === "number" && model.contextTokens > 0 ? Math.floor(model.contextTokens) : DEFAULT_LLAMA_CPP_CONTEXT_SIZE };
|
|
369
|
-
}
|
|
370
|
-
async function disposeLoadedModel() {
|
|
371
|
-
if (!loadedModel) return;
|
|
372
|
-
const previous = loadedModel;
|
|
373
|
-
loadedModel = void 0;
|
|
374
|
-
await previous.context.dispose();
|
|
375
|
-
await previous.model.dispose();
|
|
376
|
-
}
|
|
377
|
-
async function getLoadedModel(params) {
|
|
378
|
-
const source = resolveLlamaCppModelSource(params.model);
|
|
379
|
-
const modelPath = await params.runtime.resolveModelFile(source, {
|
|
380
|
-
directory: resolveLlamaCppModelCacheDir(params.providerConfig),
|
|
381
|
-
download: false
|
|
382
|
-
});
|
|
383
|
-
const contextSize = resolveContextSize(params.model, params.providerConfig);
|
|
384
|
-
const key = `${modelPath}\0${JSON.stringify(contextSize)}`;
|
|
385
|
-
if (loadedModel?.key === key) return loadedModel;
|
|
386
|
-
await disposeLoadedModel();
|
|
387
|
-
const llama = llamaInstance ?? await params.runtime.getLlama();
|
|
388
|
-
llamaInstance = llama;
|
|
389
|
-
const fitContextSize = typeof contextSize === "number" ? contextSize : contextSize.max;
|
|
390
|
-
const model = await llama.loadModel({
|
|
391
|
-
modelPath,
|
|
392
|
-
loadSignal: params.signal,
|
|
393
|
-
gpuLayers: { fitContext: { contextSize: fitContextSize } }
|
|
394
|
-
});
|
|
395
|
-
let context;
|
|
642
|
+
})();
|
|
643
|
+
preparedEmbeddingServers.set(key, pending);
|
|
396
644
|
try {
|
|
397
|
-
|
|
398
|
-
contextSize,
|
|
399
|
-
createSignal: params.signal
|
|
400
|
-
});
|
|
401
|
-
const sequence = context.getSequence();
|
|
402
|
-
loadedModel = {
|
|
403
|
-
key,
|
|
404
|
-
llama,
|
|
405
|
-
model,
|
|
406
|
-
context,
|
|
407
|
-
sequence
|
|
408
|
-
};
|
|
409
|
-
return loadedModel;
|
|
645
|
+
await pending;
|
|
410
646
|
} catch (error) {
|
|
411
|
-
|
|
412
|
-
await model.dispose();
|
|
647
|
+
if (preparedEmbeddingServers.get(key) === pending) preparedEmbeddingServers.delete(key);
|
|
413
648
|
throw error;
|
|
414
649
|
}
|
|
415
650
|
}
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
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;
|
|
427
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
|
|
428
683
|
});
|
|
684
|
+
return wrapped;
|
|
429
685
|
}
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
signal: options?.signal
|
|
466
|
-
});
|
|
467
|
-
const sequence = loaded.sequence;
|
|
468
|
-
const chat = new runtime.LlamaChat({
|
|
469
|
-
contextSequence: sequence,
|
|
470
|
-
chatWrapper: "auto",
|
|
471
|
-
autoDisposeSequence: false
|
|
472
|
-
});
|
|
473
|
-
const before = sequence.tokenMeter.getState();
|
|
474
|
-
const functions = mapToolsToLlamaFunctions(context);
|
|
475
|
-
let textStarted = false;
|
|
476
|
-
const partial = () => buildMessage({
|
|
477
|
-
model,
|
|
478
|
-
content: streamedText ? [{
|
|
479
|
-
type: "text",
|
|
480
|
-
text: streamedText
|
|
481
|
-
}] : [],
|
|
482
|
-
stopReason: "stop"
|
|
483
|
-
});
|
|
484
|
-
const appendTextDelta = (delta) => {
|
|
485
|
-
if (!delta) return;
|
|
486
|
-
if (!textStarted) {
|
|
487
|
-
textStarted = true;
|
|
488
|
-
stream.push({
|
|
489
|
-
type: "start",
|
|
490
|
-
partial: partial()
|
|
491
|
-
});
|
|
492
|
-
stream.push({
|
|
493
|
-
type: "text_start",
|
|
494
|
-
contentIndex: 0,
|
|
495
|
-
partial: partial()
|
|
496
|
-
});
|
|
497
|
-
}
|
|
498
|
-
streamedText += delta;
|
|
499
|
-
stream.push({
|
|
500
|
-
type: "text_delta",
|
|
501
|
-
contentIndex: 0,
|
|
502
|
-
delta
|
|
503
|
-
});
|
|
504
|
-
};
|
|
505
|
-
try {
|
|
506
|
-
const grammar = functions || !options?.responseFormat ? void 0 : await resolveLlamaCppResponseGrammar({
|
|
507
|
-
llama: loaded.llama,
|
|
508
|
-
responseFormat: options.responseFormat
|
|
509
|
-
});
|
|
510
|
-
const generationOptions = {
|
|
511
|
-
signal: options?.signal,
|
|
512
|
-
maxTokens: options?.maxTokens ?? model.maxTokens,
|
|
513
|
-
temperature: options?.temperature,
|
|
514
|
-
customStopTriggers: options?.stop,
|
|
515
|
-
onTextChunk: appendTextDelta,
|
|
516
|
-
...functions ? {
|
|
517
|
-
functions,
|
|
518
|
-
documentFunctionParams: true
|
|
519
|
-
} : grammar ? { grammar } : {}
|
|
520
|
-
};
|
|
521
|
-
const result = await chat.generateResponse(mapContextToLlamaChatHistory(context), generationOptions);
|
|
522
|
-
if (result.metadata.stopReason === "abort" || signal?.aborted) {
|
|
523
|
-
generationAborted = true;
|
|
524
|
-
throw signal?.reason ?? /* @__PURE__ */ new Error("Request was aborted");
|
|
525
|
-
}
|
|
526
|
-
const usageDelta = sequence.tokenMeter.diff(before);
|
|
527
|
-
if (!streamedText && result.response) appendTextDelta(result.response);
|
|
528
|
-
const content = streamedText ? [{
|
|
529
|
-
type: "text",
|
|
530
|
-
text: streamedText
|
|
531
|
-
}] : [];
|
|
532
|
-
if (textStarted) stream.push({
|
|
533
|
-
type: "text_end",
|
|
534
|
-
contentIndex: 0,
|
|
535
|
-
content: streamedText,
|
|
536
|
-
partial: partial()
|
|
537
|
-
});
|
|
538
|
-
const toolCalls = (result.functionCalls ?? []).map((call) => ({
|
|
539
|
-
type: "toolCall",
|
|
540
|
-
id: `llama_cpp_call_${randomUUID()}`,
|
|
541
|
-
name: call.functionName,
|
|
542
|
-
arguments: normalizeArguments(call.params)
|
|
543
|
-
}));
|
|
544
|
-
content.push(...toolCalls);
|
|
545
|
-
const reason = toolCalls.length > 0 ? "toolUse" : result.metadata.stopReason === "maxTokens" ? "length" : "stop";
|
|
546
|
-
const message = buildMessage({
|
|
547
|
-
model,
|
|
548
|
-
content,
|
|
549
|
-
stopReason: reason,
|
|
550
|
-
usage: zeroCostUsage(usageDelta.usedInputTokens, usageDelta.usedOutputTokens)
|
|
551
|
-
});
|
|
552
|
-
stream.push({
|
|
553
|
-
type: "done",
|
|
554
|
-
reason,
|
|
555
|
-
message
|
|
556
|
-
});
|
|
557
|
-
} finally {
|
|
558
|
-
chat.dispose();
|
|
559
|
-
}
|
|
560
|
-
} catch (error) {
|
|
561
|
-
const aborted = generationAborted || options?.signal?.aborted === true;
|
|
562
|
-
const reason = aborted ? "aborted" : "error";
|
|
563
|
-
const errorMessage = aborted ? "Request was aborted" : formatLlamaCppSetupError(error);
|
|
564
|
-
stream.push({
|
|
565
|
-
type: "error",
|
|
566
|
-
reason,
|
|
567
|
-
error: buildMessage({
|
|
568
|
-
model,
|
|
569
|
-
content: streamedText ? [{
|
|
570
|
-
type: "text",
|
|
571
|
-
text: streamedText
|
|
572
|
-
}] : [],
|
|
573
|
-
stopReason: reason,
|
|
574
|
-
errorMessage
|
|
575
|
-
})
|
|
576
|
-
});
|
|
577
|
-
} finally {
|
|
578
|
-
ended = true;
|
|
579
|
-
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 } : {}
|
|
580
721
|
}
|
|
581
722
|
};
|
|
582
|
-
|
|
583
|
-
return stream;
|
|
584
|
-
};
|
|
585
|
-
}
|
|
586
|
-
if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.llamaCppInferenceTestApi")] = {
|
|
587
|
-
mapContextToLlamaChatHistory,
|
|
588
|
-
mapToolsToLlamaFunctions,
|
|
589
|
-
clearLlamaCppInferenceCacheForTests
|
|
723
|
+
}
|
|
590
724
|
};
|
|
591
725
|
//#endregion
|
|
592
726
|
//#region extensions/llama-cpp/src/setup.ts
|
|
593
727
|
const BYTES_PER_GB = 1e9;
|
|
594
728
|
const BYTES_PER_MB = 1e6;
|
|
595
|
-
function
|
|
729
|
+
function formatDownloadProgress(label, params) {
|
|
596
730
|
const downloadedSize = Math.max(0, params.downloadedSize);
|
|
597
731
|
const totalSize = Math.max(1, params.totalSize);
|
|
598
|
-
return `Downloading
|
|
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)`;
|
|
599
733
|
}
|
|
600
734
|
function formatRamGb(totalmemBytes) {
|
|
601
|
-
return (totalmemBytes / 1024 ** 3).toFixed(1).replace(/\.0
|
|
735
|
+
return (totalmemBytes / 1024 ** 3).toFixed(1).replace(/\.0$/u, "");
|
|
602
736
|
}
|
|
603
737
|
function readPrimaryModel(config) {
|
|
604
738
|
const model = config.agents?.defaults?.model;
|
|
@@ -608,118 +742,145 @@ function configuredCandidates(config) {
|
|
|
608
742
|
const existing = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
609
743
|
const provider = buildLlamaCppProviderConfig(existing);
|
|
610
744
|
const primary = readPrimaryModel(config);
|
|
611
|
-
const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(
|
|
745
|
+
const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
|
|
612
746
|
return provider.models.map((model) => ({
|
|
613
747
|
model,
|
|
614
748
|
provider
|
|
615
749
|
})).toSorted((a, b) => Number(b.model.id === primaryId) - Number(a.model.id === primaryId));
|
|
616
750
|
}
|
|
617
751
|
async function isFile(filePath) {
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
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;
|
|
622
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);
|
|
623
767
|
}
|
|
624
|
-
|
|
625
|
-
let runtime;
|
|
768
|
+
function readConfiguredPort(provider) {
|
|
626
769
|
try {
|
|
627
|
-
|
|
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;
|
|
628
774
|
} catch {
|
|
629
|
-
return
|
|
775
|
+
return;
|
|
630
776
|
}
|
|
631
|
-
for (const candidate of configuredCandidates(ctx.config)) try {
|
|
632
|
-
if (!await isFile(await runtime.resolveModelFile(resolveLlamaCppModelSource(candidate.model), {
|
|
633
|
-
directory: resolveLlamaCppModelCacheDir(candidate.provider),
|
|
634
|
-
download: false,
|
|
635
|
-
cli: false
|
|
636
|
-
}))) continue;
|
|
637
|
-
return {
|
|
638
|
-
modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
|
|
639
|
-
detail: `${candidate.model.id} (downloaded)`
|
|
640
|
-
};
|
|
641
|
-
} catch {}
|
|
642
|
-
return null;
|
|
643
777
|
}
|
|
644
|
-
function buildSetupResult(
|
|
778
|
+
function buildSetupResult(params) {
|
|
645
779
|
return {
|
|
646
780
|
profiles: [],
|
|
647
|
-
defaultModel,
|
|
781
|
+
defaultModel: params.defaultModel ?? DEFAULT_LLAMA_CPP_MODEL_REF,
|
|
648
782
|
configPatch: { models: {
|
|
649
|
-
mode: config.models?.mode ?? "merge",
|
|
650
|
-
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) }
|
|
651
785
|
} }
|
|
652
786
|
};
|
|
653
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
|
+
}
|
|
654
799
|
async function prepareLlamaCppSetup(ctx) {
|
|
655
|
-
|
|
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
|
+
});
|
|
656
817
|
}
|
|
657
818
|
async function runLlamaCppSetup(ctx) {
|
|
658
819
|
const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
659
|
-
const
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
},
|
|
665
|
-
provider: existing
|
|
666
|
-
});
|
|
667
|
-
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);
|
|
668
825
|
const totalmemBytes = os.totalmem();
|
|
669
|
-
if (!meetsLlamaCppDefaultModelRamFloor(totalmemBytes)) {
|
|
670
|
-
await ctx.prompter.note(`This
|
|
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");
|
|
671
828
|
return { profiles: [] };
|
|
672
829
|
}
|
|
673
830
|
if (!await ctx.prompter.confirm({
|
|
674
|
-
message: "
|
|
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?",
|
|
675
832
|
initialValue: false
|
|
676
833
|
})) {
|
|
677
|
-
await ctx.prompter.note("Local model
|
|
834
|
+
await ctx.prompter.note("Local model setup skipped.", "Setup skipped");
|
|
678
835
|
return { profiles: [] };
|
|
679
836
|
}
|
|
680
|
-
const progress = ctx.prompter.progress("Preparing Gemma 4 E4B model download…");
|
|
681
|
-
try {
|
|
682
|
-
const runtime = await importNodeLlamaCpp();
|
|
683
|
-
let previousDownloadedSize;
|
|
684
|
-
let previousProgressAtMs;
|
|
685
|
-
let rollingBytesPerSecond = 0;
|
|
686
|
-
await (await runtime.createModelDownloader({
|
|
687
|
-
modelUri: DEFAULT_LLAMA_CPP_MODEL_URI,
|
|
688
|
-
dirPath: cacheDir,
|
|
689
|
-
fileName: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE,
|
|
690
|
-
showCliProgress: false,
|
|
691
|
-
onProgress: ({ downloadedSize, totalSize }) => {
|
|
692
|
-
const now = Date.now();
|
|
693
|
-
if (previousDownloadedSize !== void 0 && previousProgressAtMs !== void 0 && downloadedSize >= previousDownloadedSize && now > previousProgressAtMs) {
|
|
694
|
-
const elapsedSeconds = (now - previousProgressAtMs) / 1e3;
|
|
695
|
-
const currentBytesPerSecond = (downloadedSize - previousDownloadedSize) / elapsedSeconds;
|
|
696
|
-
rollingBytesPerSecond = rollingBytesPerSecond === 0 ? currentBytesPerSecond : rollingBytesPerSecond * .75 + currentBytesPerSecond * .25;
|
|
697
|
-
}
|
|
698
|
-
previousDownloadedSize = downloadedSize;
|
|
699
|
-
previousProgressAtMs = now;
|
|
700
|
-
const expectedSize = totalSize || 4977169568;
|
|
701
|
-
progress.update(formatLlamaCppDownloadProgress({
|
|
702
|
-
downloadedSize,
|
|
703
|
-
totalSize: expectedSize,
|
|
704
|
-
bytesPerSecond: rollingBytesPerSecond
|
|
705
|
-
}));
|
|
706
|
-
}
|
|
707
|
-
})).download({ signal: ctx.signal });
|
|
708
|
-
progress.stop("Gemma 4 E4B model downloaded");
|
|
709
|
-
} catch (error) {
|
|
710
|
-
progress.stop("Model download failed");
|
|
711
|
-
throw new Error(formatLlamaCppSetupError(error), { cause: error });
|
|
712
|
-
}
|
|
713
837
|
}
|
|
714
|
-
|
|
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
|
+
}
|
|
715
877
|
}
|
|
716
|
-
if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.llamaCppSetupTestApi")] = { formatLlamaCppDownloadProgress };
|
|
717
878
|
//#endregion
|
|
718
879
|
//#region extensions/llama-cpp/index.ts
|
|
719
880
|
var llama_cpp_default = definePluginEntry({
|
|
720
881
|
id: "llama-cpp",
|
|
721
882
|
name: "llama.cpp Provider",
|
|
722
|
-
description: "
|
|
883
|
+
description: "Managed local llama.cpp server for GGUF chat and embeddings",
|
|
723
884
|
register(api) {
|
|
724
885
|
api.registerEmbeddingProvider(llamaCppEmbeddingProviderAdapter);
|
|
725
886
|
api.registerProvider({
|
|
@@ -729,7 +890,7 @@ var llama_cpp_default = definePluginEntry({
|
|
|
729
890
|
auth: [{
|
|
730
891
|
id: "local",
|
|
731
892
|
label: LLAMA_CPP_PROVIDER_LABEL,
|
|
732
|
-
hint: "
|
|
893
|
+
hint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
|
|
733
894
|
kind: "custom",
|
|
734
895
|
appGuidedSetup: {
|
|
735
896
|
detect: detectLlamaCppSetup,
|
|
@@ -745,25 +906,38 @@ var llama_cpp_default = definePluginEntry({
|
|
|
745
906
|
order: "late",
|
|
746
907
|
run: async () => ({ provider: buildLlamaCppProviderConfig() })
|
|
747
908
|
},
|
|
748
|
-
createStreamFn: ({ config, provider }) => createLlamaCppStreamFn({ providerConfig: config?.models?.providers?.[provider] }),
|
|
749
909
|
resolveSyntheticAuth: () => ({
|
|
750
910
|
apiKey: resolveLlamaCppSyntheticApiKey(),
|
|
751
|
-
source: "local llama.cpp
|
|
911
|
+
source: "managed local llama.cpp server",
|
|
752
912
|
mode: "api-key"
|
|
753
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
|
+
},
|
|
927
|
+
...buildProviderToolCompatFamilyHooks("llamacpp-gbnf"),
|
|
754
928
|
wizard: {
|
|
755
929
|
setup: {
|
|
756
930
|
choiceId: LLAMA_CPP_PROVIDER_ID,
|
|
757
931
|
choiceLabel: LLAMA_CPP_PROVIDER_LABEL,
|
|
758
|
-
choiceHint: "
|
|
932
|
+
choiceHint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
|
|
759
933
|
groupId: LLAMA_CPP_PROVIDER_ID,
|
|
760
934
|
groupLabel: "Local llama.cpp",
|
|
761
935
|
groupHint: "No API key required",
|
|
762
936
|
methodId: "local"
|
|
763
937
|
},
|
|
764
938
|
modelPicker: {
|
|
765
|
-
label: "llama.cpp
|
|
766
|
-
hint: "Run a GGUF model
|
|
939
|
+
label: "llama.cpp",
|
|
940
|
+
hint: "Run a GGUF model with OpenClaw's managed local llama.cpp server",
|
|
767
941
|
methodId: "local"
|
|
768
942
|
}
|
|
769
943
|
}
|