@openclaw/llama-cpp-provider 2026.9.1-beta.1 → 2026.9.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,18 +1,19 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { C as resolveLlamaCppDataDir, D as resolveLlamaCppSyntheticApiKey, E as resolveLlamaCppModelSource, S as resolveLegacyLlamaCppModelCacheDir, T as resolveLlamaCppModelCacheDir, _ as LLAMA_CPP_PROVIDER_ID, a as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, b as resolveCachedLlamaCppModelPath, c as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256, d as DEFAULT_LLAMA_CPP_MODEL_ID, f as DEFAULT_LLAMA_CPP_MODEL_REVISION, g as LLAMA_CPP_DEFAULT_PORT, h as DEFAULT_LLAMA_CPP_MODEL_URI, i as DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE, l as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES, m as DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES, n as resolveManagedLlamaCppProviderConfig, o as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, p as DEFAULT_LLAMA_CPP_MODEL_SHA256, r as DEFAULT_LLAMA_CPP_CONTEXT_SIZE, s as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION, u as DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE, v as LLAMA_CPP_PROVIDER_LABEL, w as resolveLlamaCppEmbeddingModel, x as resolveHomePath, y as buildLlamaCppProviderConfig } from "./managed-provider-config-D9X1wNEo.js";
|
|
2
2
|
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { getEmbeddingProvider } from "openclaw/plugin-sdk/embedding-providers";
|
|
5
|
-
import { asBoolean, asOptionalRecord, asPositiveSafeInteger, isRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
6
5
|
import os from "node:os";
|
|
7
|
-
import {
|
|
6
|
+
import { asBoolean, asOptionalRecord, asPositiveSafeInteger, isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
8
7
|
import { createHash, randomUUID } from "node:crypto";
|
|
9
|
-
import fs from "node:fs";
|
|
10
|
-
import fsp from "node:fs/promises";
|
|
11
|
-
import JSZip from "jszip";
|
|
12
|
-
import * as tar from "tar";
|
|
8
|
+
import fs from "node:fs/promises";
|
|
13
9
|
import net from "node:net";
|
|
10
|
+
import { readProviderJsonResponse, readProviderTextResponse } from "openclaw/plugin-sdk/provider-http";
|
|
14
11
|
import { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
15
12
|
import { fetchConfiguredLocalOriginWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime-internal";
|
|
13
|
+
import { execFile } from "node:child_process";
|
|
14
|
+
import fs$1, { constants } from "node:fs";
|
|
15
|
+
import { toErrorObject } from "openclaw/plugin-sdk/error-runtime";
|
|
16
|
+
import { ARCHIVE_LIMIT_ERROR_CODE, ArchiveLimitError, extractArchive } from "openclaw/plugin-sdk/archive";
|
|
16
17
|
import { CUSTOM_LOCAL_AUTH_MARKER, applyAuthProfileConfig, buildApiKeyCredential, ensureApiKeyFromEnvOrPrompt, hasConfiguredSecretInput, isNonSecretApiKeyMarker, normalizeOptionalSecretInput, upsertAuthProfileWithLock } from "openclaw/plugin-sdk/provider-auth";
|
|
17
18
|
import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
|
|
18
19
|
import { removeAuthProfileConfig, removeProviderAuthProfilesWithLock, resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
|
|
@@ -22,72 +23,145 @@ import { SELF_HOSTED_DEFAULT_CONTEXT_WINDOW, SELF_HOSTED_DEFAULT_COST, SELF_HOST
|
|
|
22
23
|
import { selectPreferredLocalModelId } from "openclaw/plugin-sdk/provider-model-shared";
|
|
23
24
|
import { streamSimple } from "openclaw/plugin-sdk/llm";
|
|
24
25
|
import { setQwenChatTemplateThinking } from "openclaw/plugin-sdk/provider-stream-shared";
|
|
26
|
+
import { listAgentIds, resolveAgentConfig } from "openclaw/plugin-sdk/agent-scope-runtime";
|
|
25
27
|
//#region extensions/llama-cpp/src/llama-server-assets.ts
|
|
26
|
-
const LLAMA_SERVER_RELEASE = "
|
|
27
|
-
const LLAMA_SERVER_COMMIT = "
|
|
28
|
+
const LLAMA_SERVER_RELEASE = "b10534";
|
|
29
|
+
const LLAMA_SERVER_COMMIT = "2b5621094ef383cdcd8428ef6d22efe5df976532";
|
|
30
|
+
const MEBIBYTE$1 = 1048576;
|
|
31
|
+
const CUDA_ARCHIVE_LIMITS = {
|
|
32
|
+
maxArchiveBytes: 400 * MEBIBYTE$1,
|
|
33
|
+
maxExtractedBytes: 600 * MEBIBYTE$1,
|
|
34
|
+
maxEntryBytes: 520 * MEBIBYTE$1
|
|
35
|
+
};
|
|
36
|
+
const MACOS_ALIASES = [
|
|
37
|
+
["libggml-rpc.0.20.2.dylib", ["libggml-rpc.0.dylib", "libggml-rpc.dylib"]],
|
|
38
|
+
["libllama.0.1.2.dylib", ["libllama.0.dylib", "libllama.dylib"]],
|
|
39
|
+
["libmtmd.0.1.2.dylib", ["libmtmd.0.dylib", "libmtmd.dylib"]],
|
|
40
|
+
["libggml.0.20.2.dylib", ["libggml.0.dylib", "libggml.dylib"]],
|
|
41
|
+
["libggml-base.0.20.2.dylib", ["libggml-base.0.dylib", "libggml-base.dylib"]],
|
|
42
|
+
["libggml-blas.0.20.2.dylib", ["libggml-blas.0.dylib", "libggml-blas.dylib"]],
|
|
43
|
+
["libllama-common.0.1.2.dylib", ["libllama-common.0.dylib", "libllama-common.dylib"]],
|
|
44
|
+
["libggml-cpu.0.20.2.dylib", ["libggml-cpu.0.dylib", "libggml-cpu.dylib"]]
|
|
45
|
+
];
|
|
46
|
+
const MACOS_METAL_ALIASES = [...MACOS_ALIASES, ["libggml-metal.0.20.2.dylib", ["libggml-metal.0.dylib", "libggml-metal.dylib"]]];
|
|
47
|
+
const LINUX_ALIASES = [
|
|
48
|
+
["libllama.so.0.1.2", ["libllama.so.0", "libllama.so"]],
|
|
49
|
+
["libggml.so.0.20.2", ["libggml.so.0", "libggml.so"]],
|
|
50
|
+
["libmtmd.so.0.1.2", ["libmtmd.so.0", "libmtmd.so"]],
|
|
51
|
+
["libggml-base.so.0.20.2", ["libggml-base.so.0", "libggml-base.so"]],
|
|
52
|
+
["libllama-common.so.0.1.2", ["libllama-common.so.0", "libllama-common.so"]]
|
|
53
|
+
];
|
|
28
54
|
const LLAMA_SERVER_ASSETS = [
|
|
29
55
|
{
|
|
30
56
|
platform: "darwin",
|
|
31
57
|
arch: "arm64",
|
|
32
58
|
backend: "metal",
|
|
33
59
|
archive: "tar.gz",
|
|
60
|
+
archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
|
|
34
61
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-arm64.tar.gz`,
|
|
35
|
-
sha256: "
|
|
36
|
-
executable: "llama-server"
|
|
62
|
+
sha256: "51f193eef26b053554e288fb924b24d41d3d7b2bafa338c19e2817fa793d5e86",
|
|
63
|
+
executable: "llama-server",
|
|
64
|
+
regularFileAliases: MACOS_METAL_ALIASES
|
|
37
65
|
},
|
|
38
66
|
{
|
|
39
67
|
platform: "darwin",
|
|
40
68
|
arch: "x64",
|
|
41
69
|
backend: "cpu",
|
|
42
70
|
archive: "tar.gz",
|
|
71
|
+
archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
|
|
43
72
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-x64.tar.gz`,
|
|
44
|
-
sha256: "
|
|
45
|
-
executable: "llama-server"
|
|
73
|
+
sha256: "69b13035f4301354922a8cfacd1bcf2bb2de4ff0c2e19fedb44963378ff53dc5",
|
|
74
|
+
executable: "llama-server",
|
|
75
|
+
regularFileAliases: MACOS_ALIASES
|
|
46
76
|
},
|
|
47
77
|
{
|
|
48
78
|
platform: "linux",
|
|
49
79
|
arch: "arm64",
|
|
50
80
|
backend: "cpu",
|
|
51
81
|
archive: "tar.gz",
|
|
82
|
+
archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
|
|
52
83
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-arm64.tar.gz`,
|
|
53
|
-
sha256: "
|
|
54
|
-
executable: "llama-server"
|
|
84
|
+
sha256: "66535de5cb9293c075a1951c51a3b2ae6f1899623e21177845f6d2a73b78c94e",
|
|
85
|
+
executable: "llama-server",
|
|
86
|
+
regularFileAliases: LINUX_ALIASES
|
|
55
87
|
},
|
|
56
88
|
{
|
|
57
89
|
platform: "linux",
|
|
58
90
|
arch: "x64",
|
|
59
91
|
backend: "cpu",
|
|
60
92
|
archive: "tar.gz",
|
|
93
|
+
archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
|
|
61
94
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-x64.tar.gz`,
|
|
62
|
-
sha256: "
|
|
63
|
-
executable: "llama-server"
|
|
95
|
+
sha256: "cc6a12b026edcf1b211be2bb7366c5dadcad778fd8f13019d0694038053d5e4a",
|
|
96
|
+
executable: "llama-server",
|
|
97
|
+
regularFileAliases: LINUX_ALIASES
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
platform: "win32",
|
|
101
|
+
arch: "x64",
|
|
102
|
+
backend: "cuda",
|
|
103
|
+
archive: "zip",
|
|
104
|
+
archiveRoot: ".",
|
|
105
|
+
name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cuda-12.4-x64.zip`,
|
|
106
|
+
sha256: "f4964cec6c96e90a5f7379e4c2d0c437d8f1fe4263cbb8f39c7625f7c5937986",
|
|
107
|
+
executable: "llama-server.exe",
|
|
108
|
+
regularFileAliases: [],
|
|
109
|
+
limits: CUDA_ARCHIVE_LIMITS,
|
|
110
|
+
dependencies: [{
|
|
111
|
+
archive: "zip",
|
|
112
|
+
archiveRoot: ".",
|
|
113
|
+
name: "cudart-llama-bin-win-cuda-12.4-x64.zip",
|
|
114
|
+
sha256: "8c79a9b226de4b3cacfd1f83d24f962d0773be79f1e7b75c6af4ded7e32ae1d6",
|
|
115
|
+
regularFileAliases: [],
|
|
116
|
+
files: [
|
|
117
|
+
"cublas64_12.dll",
|
|
118
|
+
"cublasLt64_12.dll",
|
|
119
|
+
"cudart64_12.dll"
|
|
120
|
+
],
|
|
121
|
+
limits: {
|
|
122
|
+
...CUDA_ARCHIVE_LIMITS,
|
|
123
|
+
maxEntries: 3
|
|
124
|
+
}
|
|
125
|
+
}]
|
|
64
126
|
},
|
|
65
127
|
{
|
|
66
128
|
platform: "win32",
|
|
67
129
|
arch: "arm64",
|
|
68
130
|
backend: "cpu",
|
|
69
131
|
archive: "zip",
|
|
132
|
+
archiveRoot: ".",
|
|
70
133
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-arm64.zip`,
|
|
71
|
-
sha256: "
|
|
72
|
-
executable: "llama-server.exe"
|
|
134
|
+
sha256: "d33618b10fda35d34d85da60926c6c470f98f3f66ce6b52c3c1f583461416012",
|
|
135
|
+
executable: "llama-server.exe",
|
|
136
|
+
regularFileAliases: []
|
|
73
137
|
},
|
|
74
138
|
{
|
|
75
139
|
platform: "win32",
|
|
76
140
|
arch: "x64",
|
|
77
141
|
backend: "cpu",
|
|
78
142
|
archive: "zip",
|
|
143
|
+
archiveRoot: ".",
|
|
79
144
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-x64.zip`,
|
|
80
|
-
sha256: "
|
|
81
|
-
executable: "llama-server.exe"
|
|
145
|
+
sha256: "295ae03ad58d9276afa36f5f8d111d67fc1491c7aff3a3e6d13051a772f93c21",
|
|
146
|
+
executable: "llama-server.exe",
|
|
147
|
+
regularFileAliases: []
|
|
82
148
|
}
|
|
83
149
|
];
|
|
84
|
-
function selectLlamaServerAsset(platform = process.platform, arch = process.arch) {
|
|
85
|
-
const
|
|
150
|
+
function selectLlamaServerAsset(platform = process.platform, arch = process.arch, acceleration) {
|
|
151
|
+
const backend = acceleration?.kind ?? (platform === "darwin" && arch === "arm64" ? "metal" : "cpu");
|
|
152
|
+
if (backend === "cuda" && acceleration?.kind === "cuda") {
|
|
153
|
+
if (platform !== "win32" || arch !== "x64") throw new Error(`No verified CUDA llama-server ${LLAMA_SERVER_RELEASE} build is available for ${platform}/${arch}. Install a CUDA-enabled llama-server manually and configure its absolute path, or explicitly choose CPU setup.`);
|
|
154
|
+
if (!(acceleration.devices.length > 0 && acceleration.devices.every((device) => {
|
|
155
|
+
const version = /^(\d+)\.(\d+)(?:\.\d+)?$/u.exec(device.driverVersion);
|
|
156
|
+
return version && (Number(version[1]) > 551 || Number(version[1]) === 551 && Number(version[2]) >= 78) && (device.computeCapability === void 0 || device.computeCapability >= 5);
|
|
157
|
+
}))) throw new Error("The verified CUDA 12.4 build requires NVIDIA driver 551.78 or newer and compute capability 5.0 or newer. Update the NVIDIA driver, configure a compatible llama-server manually, or explicitly choose CPU setup.");
|
|
158
|
+
}
|
|
159
|
+
const asset = LLAMA_SERVER_ASSETS.find((candidate) => candidate.platform === platform && candidate.arch === arch && candidate.backend === backend);
|
|
86
160
|
if (!asset) throw new Error(`No verified llama-server ${LLAMA_SERVER_RELEASE} build is available for ${platform}/${arch}. Install a compatible llama-server manually, then rerun llama.cpp setup with its absolute path.`);
|
|
87
161
|
return asset;
|
|
88
162
|
}
|
|
89
163
|
function resolveManagedLlamaServerPaths(asset = selectLlamaServerAsset()) {
|
|
90
|
-
const installDir = path.join(resolveLlamaCppDataDir(), LLAMA_SERVER_RELEASE, `${asset.platform}-${asset.arch}`);
|
|
164
|
+
const installDir = path.join(resolveLlamaCppDataDir(), LLAMA_SERVER_RELEASE, `${asset.platform}-${asset.arch}${asset.backend === "cuda" ? "-cuda-12.4" : ""}`);
|
|
91
165
|
return {
|
|
92
166
|
installDir,
|
|
93
167
|
command: path.join(installDir, asset.executable),
|
|
@@ -95,8 +169,101 @@ function resolveManagedLlamaServerPaths(asset = selectLlamaServerAsset()) {
|
|
|
95
169
|
};
|
|
96
170
|
}
|
|
97
171
|
//#endregion
|
|
172
|
+
//#region extensions/llama-cpp/src/llama-server-extract.ts
|
|
173
|
+
const MEBIBYTE = 1048576;
|
|
174
|
+
const LLAMA_ARCHIVE_LIMITS = {
|
|
175
|
+
maxArchiveBytes: 256 * MEBIBYTE,
|
|
176
|
+
maxEntries: 1e3,
|
|
177
|
+
maxExtractedBytes: 512 * MEBIBYTE,
|
|
178
|
+
maxEntryBytes: 256 * MEBIBYTE,
|
|
179
|
+
maxMetaEntryBytes: MEBIBYTE
|
|
180
|
+
};
|
|
181
|
+
const MAX_ALIAS_BYTES = 512 * MEBIBYTE;
|
|
182
|
+
function assertManifestBasename(filename) {
|
|
183
|
+
if (!filename || filename === "." || filename === ".." || /[\\/]/u.test(filename) || path.basename(filename) !== filename) throw new Error(`invalid llama-server archive manifest filename: ${filename}`);
|
|
184
|
+
return filename;
|
|
185
|
+
}
|
|
186
|
+
function resolveArchiveRoot(destDir, archiveRoot) {
|
|
187
|
+
if (archiveRoot === ".") return destDir;
|
|
188
|
+
if (path.isAbsolute(archiveRoot) || /\\/u.test(archiveRoot)) throw new Error(`invalid llama-server archive root: ${archiveRoot}`);
|
|
189
|
+
const parts = archiveRoot.split("/");
|
|
190
|
+
if (parts.some((part) => !part || part === "." || part === "..")) throw new Error(`invalid llama-server archive root: ${archiveRoot}`);
|
|
191
|
+
return path.join(destDir, ...parts);
|
|
192
|
+
}
|
|
193
|
+
async function assertRegularFile(filePath, label) {
|
|
194
|
+
const stat = await fs.lstat(filePath).catch(() => void 0);
|
|
195
|
+
if (!stat?.isFile() || stat.nlink > 1) throw new Error(`llama-server archive does not contain regular ${label}`);
|
|
196
|
+
return stat;
|
|
197
|
+
}
|
|
198
|
+
async function materializeAssetAliases(params) {
|
|
199
|
+
const claimedNames = new Set(params.requiredFiles.map(assertManifestBasename));
|
|
200
|
+
for (const file of claimedNames) await assertRegularFile(path.join(params.rootDir, file), `file ${file}`);
|
|
201
|
+
let copiedBytes = 0;
|
|
202
|
+
for (const [rawSource, rawAliases] of params.asset.regularFileAliases) {
|
|
203
|
+
const source = assertManifestBasename(rawSource);
|
|
204
|
+
if (claimedNames.has(source)) throw new Error(`duplicate llama-server archive manifest filename: ${source}`);
|
|
205
|
+
claimedNames.add(source);
|
|
206
|
+
const sourcePath = path.join(params.rootDir, source);
|
|
207
|
+
const sourceStat = await assertRegularFile(sourcePath, `alias source ${source}`);
|
|
208
|
+
for (const rawAlias of rawAliases) {
|
|
209
|
+
const alias = assertManifestBasename(rawAlias);
|
|
210
|
+
if (claimedNames.has(alias)) throw new Error(`duplicate llama-server archive manifest filename: ${alias}`);
|
|
211
|
+
claimedNames.add(alias);
|
|
212
|
+
copiedBytes += sourceStat.size;
|
|
213
|
+
if (copiedBytes > MAX_ALIAS_BYTES) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.EXTRACTED_SIZE_EXCEEDS_LIMIT);
|
|
214
|
+
const aliasPath = path.join(params.rootDir, alias);
|
|
215
|
+
await fs.copyFile(sourcePath, aliasPath, constants.COPYFILE_EXCL);
|
|
216
|
+
await fs.chmod(aliasPath, sourceStat.mode & 511);
|
|
217
|
+
if ((await assertRegularFile(aliasPath, `alias ${alias}`)).size !== sourceStat.size) throw new Error(`llama-server archive alias copy is incomplete: ${alias}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
async function extractVerifiedArchive(params) {
|
|
222
|
+
const isTar = params.asset.archive === "tar.gz";
|
|
223
|
+
const limits = {
|
|
224
|
+
...LLAMA_ARCHIVE_LIMITS,
|
|
225
|
+
...params.asset.limits
|
|
226
|
+
};
|
|
227
|
+
const aliasCount = params.asset.regularFileAliases.reduce((count, [, aliases]) => count + aliases.length, 0);
|
|
228
|
+
if (aliasCount > limits.maxEntries) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.ENTRY_COUNT_EXCEEDS_LIMIT);
|
|
229
|
+
await extractArchive({
|
|
230
|
+
archivePath: params.archivePath,
|
|
231
|
+
destDir: params.destDir,
|
|
232
|
+
kind: isTar ? "tar" : "zip",
|
|
233
|
+
timeoutMs: 0,
|
|
234
|
+
limits: {
|
|
235
|
+
...limits,
|
|
236
|
+
maxEntries: limits.maxEntries - aliasCount
|
|
237
|
+
},
|
|
238
|
+
tarGzip: isTar,
|
|
239
|
+
entryFilter: (entry) => entry.kind === "symlink" ? "skip" : "extract",
|
|
240
|
+
onFiltered: "skip-entry"
|
|
241
|
+
});
|
|
242
|
+
const rootDir = resolveArchiveRoot(params.destDir, params.asset.archiveRoot);
|
|
243
|
+
await materializeAssetAliases({
|
|
244
|
+
rootDir,
|
|
245
|
+
asset: params.asset,
|
|
246
|
+
requiredFiles: params.requiredFiles
|
|
247
|
+
});
|
|
248
|
+
return rootDir;
|
|
249
|
+
}
|
|
250
|
+
/** Extracts one verified asset and returns its unpublished executable path. */
|
|
251
|
+
async function extractLlamaServerArchive(params) {
|
|
252
|
+
const rootDir = await extractVerifiedArchive({
|
|
253
|
+
...params,
|
|
254
|
+
requiredFiles: [params.asset.executable]
|
|
255
|
+
});
|
|
256
|
+
return path.join(rootDir, params.asset.executable);
|
|
257
|
+
}
|
|
258
|
+
async function extractLlamaServerDependencyArchive(params) {
|
|
259
|
+
return await extractVerifiedArchive({
|
|
260
|
+
...params,
|
|
261
|
+
requiredFiles: params.asset.files
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
98
265
|
//#region extensions/llama-cpp/src/llama-server-install.ts
|
|
99
|
-
const DOWNLOAD_TIMEOUT_MS =
|
|
266
|
+
const DOWNLOAD_TIMEOUT_MS = 18e5;
|
|
100
267
|
const VERSION_TIMEOUT_MS = 15e3;
|
|
101
268
|
const installationPromises = /* @__PURE__ */ new Map();
|
|
102
269
|
function compareVersion(left, right) {
|
|
@@ -119,15 +286,51 @@ function assertSupportedLinuxRuntime(asset) {
|
|
|
119
286
|
function assetUrl(asset) {
|
|
120
287
|
return `https://github.com/ggml-org/llama.cpp/releases/download/${LLAMA_SERVER_RELEASE}/${asset.name}`;
|
|
121
288
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
289
|
+
const verifiedFiles = /* @__PURE__ */ new Map();
|
|
290
|
+
const VERIFIED_FILE_LIMIT = 16;
|
|
291
|
+
function fileIdentity(stat) {
|
|
292
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
293
|
+
}
|
|
294
|
+
function rememberVerifiedFile(filePath, stat, sha256) {
|
|
295
|
+
verifiedFiles.delete(filePath);
|
|
296
|
+
verifiedFiles.set(filePath, {
|
|
297
|
+
identity: fileIdentity(stat),
|
|
298
|
+
sha256
|
|
129
299
|
});
|
|
130
|
-
|
|
300
|
+
if (verifiedFiles.size > VERIFIED_FILE_LIMIT) {
|
|
301
|
+
const oldest = verifiedFiles.keys().next().value;
|
|
302
|
+
if (oldest !== void 0) verifiedFiles.delete(oldest);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
async function sha256File(filePath, signal) {
|
|
306
|
+
signal?.throwIfAborted();
|
|
307
|
+
try {
|
|
308
|
+
const identity = fileIdentity(await fs.stat(filePath, { bigint: true }));
|
|
309
|
+
const verified = verifiedFiles.get(filePath);
|
|
310
|
+
if (verified?.identity === identity) return verified.sha256;
|
|
311
|
+
verifiedFiles.delete(filePath);
|
|
312
|
+
const handle = await fs.open(filePath, "r");
|
|
313
|
+
try {
|
|
314
|
+
const before = fileIdentity(await handle.stat({ bigint: true }));
|
|
315
|
+
const hash = createHash("sha256");
|
|
316
|
+
const input = handle.createReadStream({
|
|
317
|
+
autoClose: false,
|
|
318
|
+
highWaterMark: 1048576,
|
|
319
|
+
signal
|
|
320
|
+
});
|
|
321
|
+
for await (const chunk of input) hash.update(chunk);
|
|
322
|
+
const after = await handle.stat({ bigint: true });
|
|
323
|
+
if (before !== fileIdentity(after) || before !== fileIdentity(await fs.stat(filePath, { bigint: true }))) throw new Error(`File changed during integrity verification: ${filePath}. Retry setup.`);
|
|
324
|
+
const sha256 = hash.digest("hex");
|
|
325
|
+
rememberVerifiedFile(filePath, after, sha256);
|
|
326
|
+
return sha256;
|
|
327
|
+
} finally {
|
|
328
|
+
await handle.close();
|
|
329
|
+
}
|
|
330
|
+
} catch (error) {
|
|
331
|
+
verifiedFiles.delete(filePath);
|
|
332
|
+
throw error;
|
|
333
|
+
}
|
|
131
334
|
}
|
|
132
335
|
function readResponseSha256(response) {
|
|
133
336
|
for (const name of ["x-checksum-sha256", "x-linked-etag"]) {
|
|
@@ -139,7 +342,7 @@ function readResponseSha256(response) {
|
|
|
139
342
|
}
|
|
140
343
|
async function downloadVerifiedFile(params) {
|
|
141
344
|
const partialPath = `${params.destination}.partial-${randomUUID()}`;
|
|
142
|
-
await
|
|
345
|
+
await fs.mkdir(path.dirname(params.destination), { recursive: true });
|
|
143
346
|
const { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } = await import("openclaw/plugin-sdk/ssrf-runtime");
|
|
144
347
|
try {
|
|
145
348
|
const { response, release } = await fetchWithSsrFGuard({
|
|
@@ -156,17 +359,14 @@ async function downloadVerifiedFile(params) {
|
|
|
156
359
|
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");
|
|
157
360
|
const contentLength = Number(response.headers.get("content-length"));
|
|
158
361
|
const totalSize = params.expectedSize ?? (Number.isFinite(contentLength) && contentLength > 0 ? contentLength : 0);
|
|
159
|
-
const handle = await
|
|
362
|
+
const handle = await fs.open(partialPath, "wx", 384);
|
|
160
363
|
const hash = createHash("sha256");
|
|
161
|
-
const reader = response.body.getReader();
|
|
162
364
|
let downloadedSize = 0;
|
|
163
365
|
let previousSize = 0;
|
|
164
366
|
let previousAt = Date.now();
|
|
165
367
|
let rollingBytesPerSecond = 0;
|
|
166
368
|
try {
|
|
167
|
-
for (
|
|
168
|
-
const { done, value } = await reader.read();
|
|
169
|
-
if (done) break;
|
|
369
|
+
for await (const value of response.body.values({ preventCancel: true })) {
|
|
170
370
|
const chunk = Buffer.from(value);
|
|
171
371
|
await handle.writeFile(chunk);
|
|
172
372
|
hash.update(chunk);
|
|
@@ -184,47 +384,31 @@ async function downloadVerifiedFile(params) {
|
|
|
184
384
|
bytesPerSecond: rollingBytesPerSecond
|
|
185
385
|
});
|
|
186
386
|
}
|
|
387
|
+
if (params.expectedSize && downloadedSize !== params.expectedSize) throw new Error(`download size mismatch: expected ${params.expectedSize}, got ${downloadedSize}`);
|
|
388
|
+
const actualSha256 = hash.digest("hex");
|
|
389
|
+
if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
|
|
390
|
+
const completed = await handle.stat({ bigint: true });
|
|
391
|
+
params.signal?.throwIfAborted();
|
|
392
|
+
await fs.rename(partialPath, params.destination);
|
|
393
|
+
const published = await handle.stat({ bigint: true });
|
|
394
|
+
if (completed.size === published.size && completed.mtimeNs === published.mtimeNs) rememberVerifiedFile(params.destination, published, actualSha256);
|
|
187
395
|
} finally {
|
|
188
396
|
await handle.close();
|
|
189
397
|
}
|
|
190
|
-
if (params.expectedSize && downloadedSize !== params.expectedSize) throw new Error(`download size mismatch: expected ${params.expectedSize}, got ${downloadedSize}`);
|
|
191
|
-
const actualSha256 = hash.digest("hex");
|
|
192
|
-
if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
|
|
193
|
-
await fsp.rename(partialPath, params.destination);
|
|
194
398
|
} finally {
|
|
195
399
|
await release();
|
|
196
400
|
}
|
|
197
401
|
} finally {
|
|
198
|
-
await
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
async function extractZip(archivePath, destination) {
|
|
202
|
-
const zip = await JSZip.loadAsync(await fsp.readFile(archivePath));
|
|
203
|
-
for (const entry of Object.values(zip.files)) {
|
|
204
|
-
const normalized = path.posix.normalize(entry.name);
|
|
205
|
-
if (normalized.startsWith("/") || normalized === ".." || normalized.startsWith("../")) throw new Error(`unsafe path in llama-server archive: ${entry.name}`);
|
|
206
|
-
const outputPath = path.join(destination, ...normalized.split("/"));
|
|
207
|
-
if (entry.dir) await fsp.mkdir(outputPath, { recursive: true });
|
|
208
|
-
else {
|
|
209
|
-
await fsp.mkdir(path.dirname(outputPath), { recursive: true });
|
|
210
|
-
await fsp.writeFile(outputPath, await entry.async("nodebuffer"), { mode: 384 });
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
async function findExecutable(root, executable) {
|
|
215
|
-
for (const entry of await fsp.readdir(root, { withFileTypes: true })) {
|
|
216
|
-
const candidate = path.join(root, entry.name);
|
|
217
|
-
if (entry.isFile() && entry.name === executable) return candidate;
|
|
218
|
-
if (entry.isDirectory()) {
|
|
219
|
-
const nested = await findExecutable(candidate, executable).catch(() => void 0);
|
|
220
|
-
if (nested) return nested;
|
|
221
|
-
}
|
|
402
|
+
await fs.rm(partialPath, { force: true }).catch(() => void 0);
|
|
222
403
|
}
|
|
223
|
-
throw new Error(`llama-server archive does not contain ${executable}`);
|
|
224
404
|
}
|
|
225
|
-
async function
|
|
405
|
+
async function runServerCommand(command, args, signal) {
|
|
226
406
|
return await new Promise((resolve, reject) => {
|
|
227
|
-
execFile(command,
|
|
407
|
+
execFile(command, args, {
|
|
408
|
+
timeout: VERSION_TIMEOUT_MS,
|
|
409
|
+
signal,
|
|
410
|
+
windowsHide: true
|
|
411
|
+
}, (error, stdout, stderr) => {
|
|
228
412
|
if (error) reject(new Error(error.message, { cause: error }));
|
|
229
413
|
else resolve(`${stdout}${stderr}`.trim());
|
|
230
414
|
});
|
|
@@ -236,74 +420,425 @@ function formatRuntimeDependencyError(error) {
|
|
|
236
420
|
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 });
|
|
237
421
|
return new Error(`The verified llama-server build could not start: ${detail}`, { cause: error });
|
|
238
422
|
}
|
|
239
|
-
async function validateInstalledServer(command) {
|
|
423
|
+
async function validateInstalledServer(command, asset, signal) {
|
|
240
424
|
let version;
|
|
241
425
|
try {
|
|
242
|
-
version = await
|
|
426
|
+
version = await runServerCommand(command, ["--version"], signal);
|
|
243
427
|
} catch (error) {
|
|
428
|
+
signal?.throwIfAborted();
|
|
244
429
|
throw formatRuntimeDependencyError(error);
|
|
245
430
|
}
|
|
246
431
|
const match = (version.split(/\r?\n/u, 1)[0]?.trim() ?? "").match(/^version: .+ \(build (\d+), commit ([a-f\d]{9})\)$/u);
|
|
247
432
|
const build = match?.[1] ? Number(match[1]) : void 0;
|
|
248
433
|
const commit = match?.[2];
|
|
249
|
-
if (build !==
|
|
434
|
+
if (build !== 10534 || commit !== "2b5621094ef383cdcd8428ef6d22efe5df976532".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"}`);
|
|
435
|
+
if (asset.backend === "cuda") {
|
|
436
|
+
const devices = await runServerCommand(command, ["--list-devices"], signal);
|
|
437
|
+
if (!/^\s*CUDA\d+: .+\(\d+ MiB, \d+ MiB free\)$/mu.test(devices)) throw new Error("The verified llama-server could not initialize an NVIDIA CUDA device. Update the NVIDIA driver and rerun setup, or configure a compatible llama-server manually. CPU fallback was not activated.");
|
|
438
|
+
}
|
|
250
439
|
}
|
|
251
|
-
async function installLlamaServer(asset) {
|
|
440
|
+
async function installLlamaServer(asset, options) {
|
|
441
|
+
options.signal?.throwIfAborted();
|
|
252
442
|
assertSupportedLinuxRuntime(asset);
|
|
253
443
|
const { installDir, command } = resolveManagedLlamaServerPaths(asset);
|
|
254
|
-
if (await
|
|
255
|
-
await validateInstalledServer(command);
|
|
444
|
+
if (await fs.stat(command).then((stat) => stat.isFile()).catch(() => false)) {
|
|
445
|
+
await validateInstalledServer(command, asset, options.signal);
|
|
256
446
|
return command;
|
|
257
447
|
}
|
|
258
448
|
const dataDir = resolveLlamaCppDataDir();
|
|
259
449
|
const archivePath = path.join(dataDir, `.download-${randomUUID()}-${asset.name}`);
|
|
260
450
|
const extractDir = path.join(dataDir, `.extract-${randomUUID()}`);
|
|
261
|
-
await
|
|
451
|
+
await fs.mkdir(dataDir, { recursive: true });
|
|
262
452
|
try {
|
|
263
453
|
await downloadVerifiedFile({
|
|
264
454
|
url: assetUrl(asset),
|
|
265
455
|
destination: archivePath,
|
|
266
|
-
expectedSha256: asset.sha256
|
|
456
|
+
expectedSha256: asset.sha256,
|
|
457
|
+
signal: options.signal,
|
|
458
|
+
onProgress: options.onProgress
|
|
267
459
|
});
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
460
|
+
const serverExtractDir = path.join(extractDir, "server");
|
|
461
|
+
await fs.mkdir(serverExtractDir, { recursive: true });
|
|
462
|
+
const extractedCommand = await extractLlamaServerArchive({
|
|
463
|
+
archivePath,
|
|
464
|
+
destDir: serverExtractDir,
|
|
465
|
+
asset
|
|
274
466
|
});
|
|
275
|
-
const extractedCommand = await findExecutable(extractDir, asset.executable);
|
|
276
467
|
const extractedRoot = path.dirname(extractedCommand);
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
468
|
+
for (const [index, dependency] of (asset.dependencies ?? []).entries()) {
|
|
469
|
+
options.signal?.throwIfAborted();
|
|
470
|
+
const dependencyArchive = path.join(extractDir, dependency.name);
|
|
471
|
+
await downloadVerifiedFile({
|
|
472
|
+
url: assetUrl(dependency),
|
|
473
|
+
destination: dependencyArchive,
|
|
474
|
+
expectedSha256: dependency.sha256,
|
|
475
|
+
signal: options.signal,
|
|
476
|
+
onProgress: options.onProgress
|
|
477
|
+
});
|
|
478
|
+
const dependencyExtractDir = path.join(extractDir, `dependency-${index}`);
|
|
479
|
+
await fs.mkdir(dependencyExtractDir);
|
|
480
|
+
const dependencyRoot = await extractLlamaServerDependencyArchive({
|
|
481
|
+
archivePath: dependencyArchive,
|
|
482
|
+
destDir: dependencyExtractDir,
|
|
483
|
+
asset: dependency
|
|
484
|
+
});
|
|
485
|
+
for (const file of dependency.files) await fs.copyFile(path.join(dependencyRoot, file), path.join(extractedRoot, file), fs$1.constants.COPYFILE_EXCL);
|
|
486
|
+
}
|
|
487
|
+
options.signal?.throwIfAborted();
|
|
488
|
+
await fs.chmod(extractedCommand, 493);
|
|
489
|
+
await validateInstalledServer(extractedCommand, asset, options.signal);
|
|
490
|
+
await fs.mkdir(path.dirname(installDir), { recursive: true });
|
|
491
|
+
options.signal?.throwIfAborted();
|
|
492
|
+
await fs.rm(installDir, {
|
|
281
493
|
recursive: true,
|
|
282
494
|
force: true
|
|
283
495
|
});
|
|
284
|
-
await
|
|
285
|
-
await validateInstalledServer(command);
|
|
496
|
+
await fs.rename(extractedRoot, installDir);
|
|
497
|
+
await validateInstalledServer(command, asset, options.signal);
|
|
286
498
|
return command;
|
|
287
499
|
} finally {
|
|
288
|
-
await Promise.all([
|
|
500
|
+
await Promise.all([fs.rm(archivePath, { force: true }), fs.rm(extractDir, {
|
|
289
501
|
recursive: true,
|
|
290
502
|
force: true
|
|
291
503
|
})]);
|
|
292
504
|
}
|
|
293
505
|
}
|
|
294
|
-
async function ensureLlamaServerInstalled() {
|
|
295
|
-
|
|
296
|
-
const
|
|
297
|
-
const
|
|
506
|
+
async function ensureLlamaServerInstalled(options = {}) {
|
|
507
|
+
options.signal?.throwIfAborted();
|
|
508
|
+
const asset = options.asset ?? selectLlamaServerAsset();
|
|
509
|
+
const key = resolveManagedLlamaServerPaths(asset).command;
|
|
510
|
+
const previous = installationPromises.get(key);
|
|
511
|
+
const pending = Promise.resolve(previous).catch(() => void 0).then(() => installLlamaServer(asset, options)).finally(() => {
|
|
512
|
+
if (installationPromises.get(key) === pending) installationPromises.delete(key);
|
|
513
|
+
});
|
|
298
514
|
installationPromises.set(key, pending);
|
|
515
|
+
return {
|
|
516
|
+
command: previous && options.signal ? await new Promise((resolve, reject) => {
|
|
517
|
+
const signal = options.signal;
|
|
518
|
+
const onAbort = () => reject(toErrorObject(signal?.reason, "Installation cancelled"));
|
|
519
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
520
|
+
pending.then(resolve, reject).finally(() => signal?.removeEventListener("abort", onAbort));
|
|
521
|
+
if (signal?.aborted) onAbort();
|
|
522
|
+
}) : await pending,
|
|
523
|
+
asset
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
//#endregion
|
|
527
|
+
//#region extensions/llama-cpp/src/hardware.ts
|
|
528
|
+
const GIB$1 = 1024 ** 3;
|
|
529
|
+
const MIB = 1024 ** 2;
|
|
530
|
+
async function runHardwareProbe(command, args, signal) {
|
|
299
531
|
try {
|
|
532
|
+
return await new Promise((resolve, reject) => {
|
|
533
|
+
execFile(command, args, {
|
|
534
|
+
encoding: "utf8",
|
|
535
|
+
timeout: 3e3,
|
|
536
|
+
maxBuffer: 65536,
|
|
537
|
+
signal
|
|
538
|
+
}, (error, stdout) => error ? reject(error) : resolve(stdout));
|
|
539
|
+
});
|
|
540
|
+
} catch {
|
|
541
|
+
signal?.throwIfAborted();
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
async function readAvailableMemory(platform, signal) {
|
|
546
|
+
if (platform === "linux") {
|
|
547
|
+
const meminfo = await fs.readFile("/proc/meminfo", "utf8").catch(() => "");
|
|
548
|
+
const available = /^MemAvailable:\s+(\d+)\s+kB$/mu.exec(meminfo)?.[1];
|
|
549
|
+
if (available) return Number(available) * 1024;
|
|
550
|
+
}
|
|
551
|
+
if (platform === "darwin") {
|
|
552
|
+
const vmstat = await runHardwareProbe("/usr/bin/vm_stat", [], signal);
|
|
553
|
+
const pageSize = /page size of (\d+) bytes/u.exec(vmstat ?? "")?.[1];
|
|
554
|
+
const free = /^Pages free:\s+(\d+)\./mu.exec(vmstat ?? "")?.[1];
|
|
555
|
+
const inactive = /^Pages inactive:\s+(\d+)\./mu.exec(vmstat ?? "")?.[1];
|
|
556
|
+
if (pageSize && free && inactive) return (Number(free) + Number(inactive)) * Number(pageSize);
|
|
557
|
+
}
|
|
558
|
+
return os.freemem();
|
|
559
|
+
}
|
|
560
|
+
async function readAvailableDisk(cacheDir, platform, signal) {
|
|
561
|
+
let directory = path.resolve(cacheDir);
|
|
562
|
+
while (true) try {
|
|
563
|
+
const [capacity, stat] = await Promise.all([fs.statfs(directory), fs.stat(directory)]);
|
|
564
|
+
let capacityGroup = `device:${stat.dev}`;
|
|
565
|
+
if (platform === "linux" && ![
|
|
566
|
+
61267,
|
|
567
|
+
1481003842,
|
|
568
|
+
4076150800
|
|
569
|
+
].includes(capacity.type)) capacityGroup = void 0;
|
|
570
|
+
if (platform === "darwin") {
|
|
571
|
+
const disk = /^\/dev\/(disk\d+(?:s\d+)*)\s/mu.exec(await runHardwareProbe("/bin/df", ["-P", directory], signal) ?? "")?.[1];
|
|
572
|
+
const info = disk ? await runHardwareProbe("/usr/sbin/diskutil", [
|
|
573
|
+
"info",
|
|
574
|
+
"-plist",
|
|
575
|
+
disk
|
|
576
|
+
], signal) : void 0;
|
|
577
|
+
const container = /<key>APFSContainerReference<\/key>\s*<string>(disk\d+)<\/string>/u.exec(info ?? "")?.[1];
|
|
578
|
+
const filesystem = /<key>FilesystemType<\/key>\s*<string>([^<]+)<\/string>/u.exec(info ?? "")?.[1];
|
|
579
|
+
capacityGroup = container ? `apfs:${container}` : filesystem && filesystem !== "apfs" ? capacityGroup : void 0;
|
|
580
|
+
}
|
|
300
581
|
return {
|
|
301
|
-
|
|
302
|
-
|
|
582
|
+
availableBytes: capacity.bavail * capacity.bsize,
|
|
583
|
+
capacityGroup
|
|
584
|
+
};
|
|
585
|
+
} catch (error) {
|
|
586
|
+
signal?.throwIfAborted();
|
|
587
|
+
const code = error instanceof Error && "code" in error ? error.code : void 0;
|
|
588
|
+
const parent = path.dirname(directory);
|
|
589
|
+
if (code !== "ENOENT" && code !== "ENOTDIR" || parent === directory) return;
|
|
590
|
+
directory = parent;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
async function readAccelerator(platform, arch, signal) {
|
|
594
|
+
if (platform === "darwin" && arch === "arm64") return { kind: "metal" };
|
|
595
|
+
if (platform !== "linux" && platform !== "win32") return {
|
|
596
|
+
kind: "cpu",
|
|
597
|
+
reason: "No managed GPU backend is available for this host."
|
|
598
|
+
};
|
|
599
|
+
const devices = ((await runHardwareProbe("nvidia-smi", ["--query-gpu=name,memory.total,memory.free,driver_version,compute_cap", "--format=csv,noheader,nounits"], signal))?.trim().split(/\r?\n/u) ?? []).slice(0, 32).flatMap((line) => {
|
|
600
|
+
const fields = line.split(",").map((field) => field.trim());
|
|
601
|
+
const [total, available, driverVersion, compute] = fields.slice(-4);
|
|
602
|
+
const name = fields.slice(0, -4).join(", ");
|
|
603
|
+
const totalMemoryBytes = Number(total) * MIB;
|
|
604
|
+
const availableMemoryBytes = Number(available) * MIB;
|
|
605
|
+
const computeCapability = Number(compute);
|
|
606
|
+
if (!name || !driverVersion || !/^\d+(?:\.\d+)+$/u.test(driverVersion) || !Number.isFinite(totalMemoryBytes) || !Number.isFinite(availableMemoryBytes) || totalMemoryBytes <= 0 || availableMemoryBytes < 0 || availableMemoryBytes > totalMemoryBytes) return [];
|
|
607
|
+
return [{
|
|
608
|
+
name,
|
|
609
|
+
totalMemoryBytes,
|
|
610
|
+
availableMemoryBytes,
|
|
611
|
+
driverVersion,
|
|
612
|
+
...Number.isFinite(computeCapability) && computeCapability > 0 ? { computeCapability } : {}
|
|
613
|
+
}];
|
|
614
|
+
});
|
|
615
|
+
return devices.length > 0 ? {
|
|
616
|
+
kind: "cuda",
|
|
617
|
+
devices
|
|
618
|
+
} : {
|
|
619
|
+
kind: "cpu",
|
|
620
|
+
reason: "nvidia-smi did not report a usable NVIDIA GPU."
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
/** Read the Gateway host once during setup; never probe on inference requests. */
|
|
624
|
+
async function detectLlamaCppHardware(params) {
|
|
625
|
+
params.signal?.throwIfAborted();
|
|
626
|
+
const platform = os.platform();
|
|
627
|
+
const arch = os.arch();
|
|
628
|
+
const hostMemoryBytes = os.totalmem();
|
|
629
|
+
const constrainedMemory = process.constrainedMemory();
|
|
630
|
+
const constrained = constrainedMemory > 0 && constrainedMemory < hostMemoryBytes;
|
|
631
|
+
const totalMemoryBytes = constrained ? constrainedMemory : hostMemoryBytes;
|
|
632
|
+
const [availableMemory, modelDisk, runtimeDisk, accelerator] = await Promise.all([
|
|
633
|
+
readAvailableMemory(platform, params.signal),
|
|
634
|
+
readAvailableDisk(params.cacheDir, platform, params.signal),
|
|
635
|
+
readAvailableDisk(resolveLlamaCppDataDir(), platform, params.signal),
|
|
636
|
+
readAccelerator(platform, arch, params.signal)
|
|
637
|
+
]);
|
|
638
|
+
params.signal?.throwIfAborted();
|
|
639
|
+
return {
|
|
640
|
+
platform,
|
|
641
|
+
arch,
|
|
642
|
+
totalMemoryBytes,
|
|
643
|
+
availableMemoryBytes: Math.min(totalMemoryBytes, availableMemory, constrained ? process.availableMemory() : totalMemoryBytes),
|
|
644
|
+
availableDiskBytes: modelDisk?.availableBytes,
|
|
645
|
+
availableRuntimeDiskBytes: runtimeDisk?.availableBytes,
|
|
646
|
+
sharedDisk: !modelDisk?.capacityGroup || !runtimeDisk?.capacityGroup || modelDisk.capacityGroup === runtimeDisk.capacityGroup,
|
|
647
|
+
accelerator
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
function formatLlamaCppMemory(bytes) {
|
|
651
|
+
return `${(bytes / GIB$1).toFixed(1).replace(/\.0$/u, "")} GiB`;
|
|
652
|
+
}
|
|
653
|
+
//#endregion
|
|
654
|
+
//#region extensions/llama-cpp/src/model-catalog.ts
|
|
655
|
+
const GIB = 1024 ** 3;
|
|
656
|
+
function modelRecipe(params) {
|
|
657
|
+
const source = params.source ?? `hf:${params.repository}/${params.file}#${params.revision}`;
|
|
658
|
+
return {
|
|
659
|
+
model: {
|
|
660
|
+
id: params.id,
|
|
661
|
+
name: params.name,
|
|
662
|
+
api: "openai-completions",
|
|
663
|
+
reasoning: params.reasoning ?? false,
|
|
664
|
+
input: ["text"],
|
|
665
|
+
cost: {
|
|
666
|
+
input: 0,
|
|
667
|
+
output: 0,
|
|
668
|
+
cacheRead: 0,
|
|
669
|
+
cacheWrite: 0
|
|
670
|
+
},
|
|
671
|
+
contextWindow: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
|
|
672
|
+
contextTokens: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
|
|
673
|
+
maxTokens: params.maxTokens ?? 2048,
|
|
674
|
+
params: {
|
|
675
|
+
modelPath: source,
|
|
676
|
+
contextSize: DEFAULT_LLAMA_CPP_CONTEXT_SIZE
|
|
677
|
+
},
|
|
678
|
+
compat: {
|
|
679
|
+
supportsTools: true,
|
|
680
|
+
supportsUsageInStreaming: true,
|
|
681
|
+
toolSchemaProfile: "llamacpp"
|
|
682
|
+
}
|
|
683
|
+
},
|
|
684
|
+
sizeBytes: params.sizeBytes,
|
|
685
|
+
memoryBytes: params.memoryGiB * GIB,
|
|
686
|
+
minimumSystemMemoryBytes: params.minimumSystemGiB * GIB,
|
|
687
|
+
requiresAcceleration: params.requiresAcceleration ?? false,
|
|
688
|
+
artifact: {
|
|
689
|
+
fileName: params.cacheFile ?? `hf_${params.repository.replaceAll("/", "_")}_${params.revision}_${params.file}`,
|
|
690
|
+
url: `https://huggingface.co/${params.repository}/resolve/${params.revision}/${params.file}?download=true`,
|
|
691
|
+
expectedSize: params.sizeBytes,
|
|
692
|
+
expectedSha256: params.sha256
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
const LLAMA_CPP_MODEL_RECIPES = [
|
|
697
|
+
modelRecipe({
|
|
698
|
+
id: "qwen3.8-27b-ud-q4_k_m",
|
|
699
|
+
name: "Qwen3.8 27B (UD-Q4_K_M)",
|
|
700
|
+
repository: "unsloth/Qwen3.8-27B-GGUF",
|
|
701
|
+
file: "Qwen3.8-27B-UD-Q4_K_M.gguf",
|
|
702
|
+
revision: "4ca720788d1e01f1bff70c033e0d0028fd02e502",
|
|
703
|
+
sha256: "322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482",
|
|
704
|
+
sizeBytes: 16464440224,
|
|
705
|
+
memoryGiB: 22,
|
|
706
|
+
minimumSystemGiB: 32,
|
|
707
|
+
requiresAcceleration: true,
|
|
708
|
+
reasoning: true,
|
|
709
|
+
maxTokens: 16384
|
|
710
|
+
}),
|
|
711
|
+
modelRecipe({
|
|
712
|
+
id: "muse-glimmer-30b-q4_k_m",
|
|
713
|
+
name: "Muse Glimmer 30B (Q4_K_M)",
|
|
714
|
+
repository: "meta-models/Muse-Glimmer-30B-GGUF",
|
|
715
|
+
file: "Muse-Glimmer-30B-KQuant-17GB-Q4_K_M.gguf",
|
|
716
|
+
revision: "70bf1b61ac09f91b24d39038091b41c582bc5d7a",
|
|
717
|
+
sha256: "4cc57c0f51040a226e5a72cc47b7613f7772950e460a665f7083de89f183f60e",
|
|
718
|
+
sizeBytes: 16756683904,
|
|
719
|
+
memoryGiB: 20,
|
|
720
|
+
minimumSystemGiB: 32,
|
|
721
|
+
requiresAcceleration: true,
|
|
722
|
+
reasoning: true,
|
|
723
|
+
maxTokens: 16384
|
|
724
|
+
}),
|
|
725
|
+
modelRecipe({
|
|
726
|
+
id: "gemma-4-26b-a4b-it-ud-q4_k_m",
|
|
727
|
+
name: "Gemma 4 26B A4B (UD-Q4_K_M)",
|
|
728
|
+
repository: "unsloth/gemma-4-26B-A4B-it-GGUF",
|
|
729
|
+
file: "gemma-4-26B-A4B-it-UD-Q4_K_M.gguf",
|
|
730
|
+
revision: "c099eb48e663fd284577b04978a94ffccb261841",
|
|
731
|
+
sha256: "f2c28b3dc4776931ac6f879e11f203dec637ea0f14267a86ec8f6165f63f293f",
|
|
732
|
+
sizeBytes: 16947541728,
|
|
733
|
+
memoryGiB: 22,
|
|
734
|
+
minimumSystemGiB: 32,
|
|
735
|
+
requiresAcceleration: true
|
|
736
|
+
}),
|
|
737
|
+
modelRecipe({
|
|
738
|
+
id: "gemma-4-12b-it-q4_k_m",
|
|
739
|
+
name: "Gemma 4 12B (Q4_K_M)",
|
|
740
|
+
repository: "unsloth/gemma-4-12b-it-GGUF",
|
|
741
|
+
file: "gemma-4-12b-it-Q4_K_M.gguf",
|
|
742
|
+
revision: "fc034cfff751157913579611efad8462ac1be606",
|
|
743
|
+
sha256: "0a270ec9fe6b34f4a0d33992b6135117b484ebc4766ab76b51d4ae8c457e4c42",
|
|
744
|
+
sizeBytes: 7121861440,
|
|
745
|
+
memoryGiB: 12,
|
|
746
|
+
minimumSystemGiB: 24,
|
|
747
|
+
requiresAcceleration: true,
|
|
748
|
+
reasoning: true,
|
|
749
|
+
maxTokens: 16384
|
|
750
|
+
}),
|
|
751
|
+
modelRecipe({
|
|
752
|
+
id: "qwen3.5-9b-q4_k_m",
|
|
753
|
+
name: "Qwen3.5 9B (Q4_K_M)",
|
|
754
|
+
repository: "unsloth/Qwen3.5-9B-GGUF",
|
|
755
|
+
file: "Qwen3.5-9B-Q4_K_M.gguf",
|
|
756
|
+
revision: "3885219b6810b007914f3a7950a8d1b469d598a5",
|
|
757
|
+
sha256: "03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8",
|
|
758
|
+
sizeBytes: 5680522464,
|
|
759
|
+
memoryGiB: 10,
|
|
760
|
+
minimumSystemGiB: 16,
|
|
761
|
+
reasoning: true,
|
|
762
|
+
maxTokens: 16384
|
|
763
|
+
}),
|
|
764
|
+
modelRecipe({
|
|
765
|
+
id: DEFAULT_LLAMA_CPP_MODEL_ID,
|
|
766
|
+
name: "Gemma 4 E4B (Q4_K_M)",
|
|
767
|
+
repository: "unsloth/gemma-4-E4B-it-GGUF",
|
|
768
|
+
file: "gemma-4-E4B-it-Q4_K_M.gguf",
|
|
769
|
+
revision: DEFAULT_LLAMA_CPP_MODEL_REVISION,
|
|
770
|
+
sha256: DEFAULT_LLAMA_CPP_MODEL_SHA256,
|
|
771
|
+
sizeBytes: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
|
|
772
|
+
memoryGiB: 10,
|
|
773
|
+
minimumSystemGiB: 16,
|
|
774
|
+
source: DEFAULT_LLAMA_CPP_MODEL_URI,
|
|
775
|
+
cacheFile: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE
|
|
776
|
+
}),
|
|
777
|
+
modelRecipe({
|
|
778
|
+
id: "qwen3.5-4b-q4_k_m",
|
|
779
|
+
name: "Qwen3.5 4B (Q4_K_M)",
|
|
780
|
+
repository: "unsloth/Qwen3.5-4B-GGUF",
|
|
781
|
+
file: "Qwen3.5-4B-Q4_K_M.gguf",
|
|
782
|
+
revision: "e87f176479d0855a907a41277aca2f8ee7a09523",
|
|
783
|
+
sha256: "00fe7986ff5f6b463e62455821146049db6f9313603938a70800d1fb69ef11a4",
|
|
784
|
+
sizeBytes: 2740937888,
|
|
785
|
+
memoryGiB: 6,
|
|
786
|
+
minimumSystemGiB: 8,
|
|
787
|
+
reasoning: true,
|
|
788
|
+
maxTokens: 16384
|
|
789
|
+
}),
|
|
790
|
+
modelRecipe({
|
|
791
|
+
id: "gemma-4-e2b-it-q4_k_m",
|
|
792
|
+
name: "Gemma 4 E2B (Q4_K_M)",
|
|
793
|
+
repository: "unsloth/gemma-4-E2B-it-GGUF",
|
|
794
|
+
file: "gemma-4-E2B-it-Q4_K_M.gguf",
|
|
795
|
+
revision: "0314792d7f1f7e229411f620751375812bb9faf2",
|
|
796
|
+
sha256: "740185b21d22ceb83a11c3aa62ad5842ef32c70f6096d756bbee85a1e4ec34b8",
|
|
797
|
+
sizeBytes: 3106738272,
|
|
798
|
+
memoryGiB: 6,
|
|
799
|
+
minimumSystemGiB: 8
|
|
800
|
+
})
|
|
801
|
+
];
|
|
802
|
+
function resolveLlamaCppCatalogArtifact(source) {
|
|
803
|
+
return LLAMA_CPP_MODEL_RECIPES.find((recipe) => recipe.model.params?.modelPath === source)?.artifact;
|
|
804
|
+
}
|
|
805
|
+
function resolveLlamaCppModelCandidates(hardware, backend) {
|
|
806
|
+
const systemBudget = Math.min(hardware.availableMemoryBytes, hardware.totalMemoryBytes - Math.max(2 * GIB, hardware.totalMemoryBytes * .25));
|
|
807
|
+
const gpuBudget = hardware.accelerator.kind === "cuda" ? Math.max(0, ...hardware.accelerator.devices.map((device) => Math.min(device.availableMemoryBytes, device.totalMemoryBytes - Math.max(GIB, device.totalMemoryBytes * .1)))) : 0;
|
|
808
|
+
const memoryBudgetBytes = backend === "cuda" ? Math.min(systemBudget, gpuBudget) : systemBudget;
|
|
809
|
+
return {
|
|
810
|
+
recipes: LLAMA_CPP_MODEL_RECIPES.filter((recipe) => (!recipe.requiresAcceleration || backend !== "cpu") && hardware.totalMemoryBytes >= recipe.minimumSystemMemoryBytes && memoryBudgetBytes >= recipe.memoryBytes),
|
|
811
|
+
memoryBudgetBytes
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
function recommendLlamaCppModel(hardware, backend, cached = {}) {
|
|
815
|
+
if (hardware.availableDiskBytes === void 0 || hardware.availableRuntimeDiskBytes === void 0) return {
|
|
816
|
+
kind: "unavailable",
|
|
817
|
+
reason: "Cannot measure free space in the model cache or runtime directory. Check their permissions and retry setup."
|
|
818
|
+
};
|
|
819
|
+
const { recipes: candidates, memoryBudgetBytes } = resolveLlamaCppModelCandidates(hardware, backend);
|
|
820
|
+
const runtimeDiskBytes = cached.runtime ? 0 : (backend === "cuda" ? 3 : 2) * GIB;
|
|
821
|
+
if (!hardware.sharedDisk && hardware.availableRuntimeDiskBytes < runtimeDiskBytes) return {
|
|
822
|
+
kind: "unavailable",
|
|
823
|
+
reason: "There is not enough free disk space in the runtime directory. Free space on that volume and retry setup."
|
|
824
|
+
};
|
|
825
|
+
const modelDiskBudget = hardware.sharedDisk ? Math.min(hardware.availableDiskBytes, hardware.availableRuntimeDiskBytes) - runtimeDiskBytes : hardware.availableDiskBytes;
|
|
826
|
+
for (const recipe of candidates) {
|
|
827
|
+
const modelDiskBytes = (cached.modelIds?.has(recipe.model.id) ? 0 : recipe.sizeBytes) + (cached.embedding ? 0 : DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES);
|
|
828
|
+
if (modelDiskBudget < modelDiskBytes) continue;
|
|
829
|
+
const placement = backend === "metal" ? "Metal unified memory" : backend === "cuda" ? "NVIDIA GPU memory" : "CPU memory";
|
|
830
|
+
return {
|
|
831
|
+
kind: "recommended",
|
|
832
|
+
recipe,
|
|
833
|
+
memoryBudgetBytes,
|
|
834
|
+
requiredDiskBytes: modelDiskBytes + runtimeDiskBytes,
|
|
835
|
+
reason: `${recipe.model.name} fits the ${formatLlamaCppMemory(memoryBudgetBytes)} ${placement} budget with a 64K context. Runtime verification checks the actual model before activation.`
|
|
303
836
|
};
|
|
304
|
-
} finally {
|
|
305
|
-
if (installationPromises.get(key) === pending) installationPromises.delete(key);
|
|
306
837
|
}
|
|
838
|
+
return {
|
|
839
|
+
kind: "unavailable",
|
|
840
|
+
reason: candidates.length > 0 ? "There is not enough free disk space for a recommended model, embeddings, and the runtime. Free space in the model cache and retry setup." : `No recommended model fits the current ${formatLlamaCppMemory(Math.max(0, memoryBudgetBytes))} memory budget. Close other applications and retry, or configure an existing GGUF or external server.`
|
|
841
|
+
};
|
|
307
842
|
}
|
|
308
843
|
//#endregion
|
|
309
844
|
//#region extensions/llama-cpp/src/managed-server.ts
|
|
@@ -341,7 +876,7 @@ async function resolveHuggingFaceArtifact(source, signal) {
|
|
|
341
876
|
});
|
|
342
877
|
try {
|
|
343
878
|
if (!response.ok) throw new Error(`Cannot resolve ${source}: HTTP ${response.status}`);
|
|
344
|
-
const ggufFile = asOptionalRecord(asOptionalRecord(await response.
|
|
879
|
+
const ggufFile = asOptionalRecord(asOptionalRecord(await readProviderJsonResponse(response, "llama.cpp Hugging Face manifest"))?.ggufFile);
|
|
345
880
|
file = typeof ggufFile?.rfilename === "string" ? ggufFile.rfilename : void 0;
|
|
346
881
|
expectedSize = typeof ggufFile?.size === "number" ? ggufFile.size : void 0;
|
|
347
882
|
if (!file) throw new Error(`Hugging Face did not return a GGUF file for ${source}`);
|
|
@@ -351,22 +886,33 @@ async function resolveHuggingFaceArtifact(source, signal) {
|
|
|
351
886
|
}
|
|
352
887
|
const encodedFile = file.split("/").map(encodeURIComponent).join("/");
|
|
353
888
|
const url = `https://huggingface.co/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/resolve/${encodeURIComponent(parsed.revision)}/${encodedFile}?download=true`;
|
|
354
|
-
const
|
|
355
|
-
const { response:
|
|
356
|
-
url:
|
|
889
|
+
const fileInfoUrl = `https://huggingface.co/api/models/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/paths-info/${encodeURIComponent(parsed.revision)}`;
|
|
890
|
+
const { response: fileInfoResponse, release: releaseFileInfo } = await fetchWithSsrFGuard({
|
|
891
|
+
url: fileInfoUrl,
|
|
892
|
+
init: {
|
|
893
|
+
method: "POST",
|
|
894
|
+
headers: {
|
|
895
|
+
"content-type": "application/json",
|
|
896
|
+
"user-agent": "llama-cpp"
|
|
897
|
+
},
|
|
898
|
+
body: JSON.stringify({
|
|
899
|
+
paths: [file],
|
|
900
|
+
expand: false
|
|
901
|
+
})
|
|
902
|
+
},
|
|
357
903
|
signal,
|
|
358
904
|
requireHttps: true,
|
|
359
|
-
policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(
|
|
905
|
+
policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(fileInfoUrl),
|
|
360
906
|
auditContext: "llama-cpp-model-resolve"
|
|
361
907
|
});
|
|
362
|
-
let
|
|
908
|
+
let fileInfo;
|
|
363
909
|
try {
|
|
364
|
-
if (!
|
|
365
|
-
|
|
910
|
+
if (!fileInfoResponse.ok) throw new Error(`Cannot read Hugging Face integrity metadata for ${source}: HTTP ${fileInfoResponse.status}`);
|
|
911
|
+
fileInfo = await readProviderJsonResponse(fileInfoResponse, "llama.cpp Hugging Face file metadata");
|
|
366
912
|
} finally {
|
|
367
|
-
await
|
|
913
|
+
await releaseFileInfo();
|
|
368
914
|
}
|
|
369
|
-
const fileRow = Array.isArray(
|
|
915
|
+
const fileRow = Array.isArray(fileInfo) ? fileInfo.map((entry) => asOptionalRecord(entry)).find((entry) => entry?.path === file) : void 0;
|
|
370
916
|
const lfs = asOptionalRecord(fileRow?.lfs);
|
|
371
917
|
const expectedSha256 = typeof lfs?.oid === "string" && /^[a-f\d]{64}$/iu.test(lfs.oid) ? lfs.oid.toLowerCase() : void 0;
|
|
372
918
|
expectedSize = expectedSize ?? (typeof fileRow?.size === "number" ? fileRow.size : void 0);
|
|
@@ -384,12 +930,8 @@ async function resolveHuggingFaceArtifact(source, signal) {
|
|
|
384
930
|
};
|
|
385
931
|
}
|
|
386
932
|
function defaultArtifact(source) {
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
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`,
|
|
390
|
-
expectedSize: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
|
|
391
|
-
expectedSha256: DEFAULT_LLAMA_CPP_MODEL_SHA256
|
|
392
|
-
};
|
|
933
|
+
const recipe = resolveLlamaCppCatalogArtifact(source);
|
|
934
|
+
if (recipe) return recipe;
|
|
393
935
|
if (source === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") return {
|
|
394
936
|
fileName: DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE,
|
|
395
937
|
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`,
|
|
@@ -398,7 +940,7 @@ function defaultArtifact(source) {
|
|
|
398
940
|
};
|
|
399
941
|
}
|
|
400
942
|
async function assertGguf(filePath) {
|
|
401
|
-
const handle = await
|
|
943
|
+
const handle = await fs.open(filePath, "r").catch((error) => {
|
|
402
944
|
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 });
|
|
403
945
|
throw error;
|
|
404
946
|
});
|
|
@@ -437,11 +979,13 @@ async function ensureLlamaCppModel(params) {
|
|
|
437
979
|
const pending = modelPromises.get(destination);
|
|
438
980
|
if (pending) return await pending;
|
|
439
981
|
const load = (async () => {
|
|
440
|
-
if (await
|
|
441
|
-
if (
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
982
|
+
if (await fs.stat(destination).then((stat) => stat.isFile()).catch(() => false)) {
|
|
983
|
+
if (artifact.expectedSha256) {
|
|
984
|
+
if (await sha256File(destination, params.signal) === artifact.expectedSha256) return destination;
|
|
985
|
+
} else {
|
|
986
|
+
await assertGguf(destination);
|
|
987
|
+
return destination;
|
|
988
|
+
}
|
|
445
989
|
}
|
|
446
990
|
if (!params.download) throw new Error(`Model is not cached at ${destination}`);
|
|
447
991
|
await downloadVerifiedFile({
|
|
@@ -509,26 +1053,23 @@ function renderLlamaServerPreset(params) {
|
|
|
509
1053
|
].join("\n");
|
|
510
1054
|
}
|
|
511
1055
|
async function writePreset(presetPath, contents) {
|
|
512
|
-
await
|
|
1056
|
+
await fs.mkdir(path.dirname(presetPath), { recursive: true });
|
|
513
1057
|
const temporary = `${presetPath}.tmp-${randomUUID()}`;
|
|
514
|
-
await
|
|
515
|
-
await
|
|
1058
|
+
await fs.writeFile(temporary, contents, { mode: 384 });
|
|
1059
|
+
await fs.rename(temporary, presetPath);
|
|
516
1060
|
}
|
|
517
1061
|
async function updatePreset(presetPath, params) {
|
|
518
1062
|
const pending = (presetWritePromises.get(presetPath) ?? Promise.resolve()).catch(() => void 0).then(async () => {
|
|
519
|
-
const existing = await
|
|
1063
|
+
const existing = await fs.readFile(presetPath, "utf8").catch((error) => {
|
|
520
1064
|
if (asOptionalRecord(error)?.code === "ENOENT") return;
|
|
521
1065
|
throw error;
|
|
522
1066
|
});
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
contextSize: params.contextSize,
|
|
530
|
-
maxTokens: params.maxTokens
|
|
531
|
-
}) : readChatModelSection(existing);
|
|
1067
|
+
const chatSection = params.chatModel.mode === "preserve" ? readChatModelSection(existing) : params.chatModel.mode === "configure" ? renderChatModelSection({
|
|
1068
|
+
id: params.chatModel.id,
|
|
1069
|
+
modelPath: params.chatModel.path,
|
|
1070
|
+
contextSize: params.chatModel.contextSize,
|
|
1071
|
+
maxTokens: params.chatModel.maxTokens
|
|
1072
|
+
}) : void 0;
|
|
532
1073
|
const embeddingSection = params.embeddingModelPath ? renderEmbeddingModelSection({
|
|
533
1074
|
isDefault: params.embeddingModelIsDefault,
|
|
534
1075
|
modelPath: params.embeddingModelPath
|
|
@@ -563,26 +1104,36 @@ async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT)
|
|
|
563
1104
|
return await tryPort(preferred) ?? await tryPort(0) ?? Promise.reject(/* @__PURE__ */ new Error("No loopback port is available for llama-server"));
|
|
564
1105
|
}
|
|
565
1106
|
async function prepareManagedLlamaServer(params) {
|
|
566
|
-
|
|
567
|
-
const
|
|
1107
|
+
params.signal?.throwIfAborted();
|
|
1108
|
+
const command = params.localService?.command ?? (await ensureLlamaServerInstalled({
|
|
1109
|
+
asset: params.asset,
|
|
1110
|
+
signal: params.signal,
|
|
1111
|
+
onProgress: params.onProgress
|
|
1112
|
+
})).command;
|
|
1113
|
+
const port = params.port ?? await findAvailableLlamaServerPort(params.isolated ? 0 : void 0);
|
|
1114
|
+
const rootUrl = `http://127.0.0.1:${port}`;
|
|
1115
|
+
const endpoint = {
|
|
1116
|
+
command,
|
|
1117
|
+
baseUrl: `${rootUrl}/v1`,
|
|
1118
|
+
healthUrl: params.localService?.healthUrl ?? `${rootUrl}/health`
|
|
1119
|
+
};
|
|
1120
|
+
const configuredPreset = params.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset") ?? params.localService?.env?.LLAMA_ARG_MODELS_PRESET;
|
|
1121
|
+
if (params.localService && !configuredPreset && !params.isolated) return {
|
|
1122
|
+
...endpoint,
|
|
1123
|
+
args: params.localService.args ?? []
|
|
1124
|
+
};
|
|
1125
|
+
const defaultPreset = configuredPreset ? path.resolve(params.localService?.cwd ?? process.cwd(), configuredPreset) : resolveManagedLlamaServerPaths(params.asset).presetPath;
|
|
1126
|
+
const presetPath = params.isolated ? path.join(path.dirname(defaultPreset), `models-${randomUUID()}.ini`) : defaultPreset;
|
|
568
1127
|
await updatePreset(presetPath, {
|
|
569
|
-
|
|
570
|
-
chatModelId: params.chatModelId ?? "gemma-4-e4b-it-q4_k_m",
|
|
571
|
-
chatModelPath: params.chatModelPath
|
|
572
|
-
} : {},
|
|
573
|
-
contextSize: params.contextSize,
|
|
574
|
-
maxTokens: params.maxTokens,
|
|
1128
|
+
chatModel: params.chatModel,
|
|
575
1129
|
embeddingModelIsDefault: params.embeddingModelIsDefault,
|
|
576
1130
|
embeddingModelPath: params.embeddingModelPath,
|
|
577
1131
|
defaultEmbeddingModelPath: params.defaultEmbeddingModelPath
|
|
578
1132
|
});
|
|
579
|
-
|
|
580
|
-
const rootUrl = `http://127.0.0.1:${port}`;
|
|
1133
|
+
params.signal?.throwIfAborted();
|
|
581
1134
|
return {
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
healthUrl: `${rootUrl}/health`,
|
|
585
|
-
args: [
|
|
1135
|
+
...endpoint,
|
|
1136
|
+
args: params.localService && !params.isolated ? params.localService.args ?? [] : [
|
|
586
1137
|
"--host",
|
|
587
1138
|
"127.0.0.1",
|
|
588
1139
|
"--port",
|
|
@@ -601,6 +1152,7 @@ async function ensureManagedLlamaServerForChat(params) {
|
|
|
601
1152
|
const cacheDir = resolveLlamaCppModelCacheDir(params.provider);
|
|
602
1153
|
const key = JSON.stringify([
|
|
603
1154
|
params.provider.baseUrl,
|
|
1155
|
+
params.provider.localService,
|
|
604
1156
|
params.model.id,
|
|
605
1157
|
params.model.params,
|
|
606
1158
|
cacheDir
|
|
@@ -612,7 +1164,7 @@ async function ensureManagedLlamaServerForChat(params) {
|
|
|
612
1164
|
});
|
|
613
1165
|
if (!chatModelPath && resolveLlamaCppModelSource(params.model) === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") {
|
|
614
1166
|
const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), "hf_unsloth_gemma-4-E4B-it-GGUF_gemma-4-E4B-it-Q4_K_M.gguf");
|
|
615
|
-
if (await
|
|
1167
|
+
if (await fs.stat(legacy).then((stat) => stat.isFile()).catch(() => false)) chatModelPath = legacy;
|
|
616
1168
|
}
|
|
617
1169
|
chatModelPath = await ensureLlamaCppModel({
|
|
618
1170
|
source: chatModelPath ?? resolveLlamaCppModelSource(params.model),
|
|
@@ -622,12 +1174,16 @@ async function ensureManagedLlamaServerForChat(params) {
|
|
|
622
1174
|
const configuredContext = params.model.params?.contextSize;
|
|
623
1175
|
const port = Number(new URL(params.provider.baseUrl).port);
|
|
624
1176
|
await prepareManagedLlamaServer({
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
1177
|
+
chatModel: {
|
|
1178
|
+
mode: "configure",
|
|
1179
|
+
id: params.model.id,
|
|
1180
|
+
path: chatModelPath,
|
|
1181
|
+
contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : params.model.contextTokens,
|
|
1182
|
+
maxTokens: params.model.maxTokens
|
|
1183
|
+
},
|
|
629
1184
|
defaultEmbeddingModelPath: path.join(cacheDir, "hf_ggml-org_embeddinggemma-300m-qat-Q8_0.gguf"),
|
|
630
|
-
port: Number.isInteger(port) && port > 0 ? port : void 0
|
|
1185
|
+
port: Number.isInteger(port) && port > 0 ? port : void 0,
|
|
1186
|
+
localService: params.provider.localService
|
|
631
1187
|
});
|
|
632
1188
|
})();
|
|
633
1189
|
chatPreparationPromises.set(key, pending);
|
|
@@ -652,7 +1208,7 @@ async function fetchEndpoint(url, accept) {
|
|
|
652
1208
|
if (!response.ok) return { ok: false };
|
|
653
1209
|
return {
|
|
654
1210
|
ok: true,
|
|
655
|
-
value: accept === "json" ? await response
|
|
1211
|
+
value: accept === "json" ? await readProviderJsonResponse(response, "llama-server inspection") : await readProviderTextResponse(response, "llama-server inspection")
|
|
656
1212
|
};
|
|
657
1213
|
} finally {
|
|
658
1214
|
await release();
|
|
@@ -719,14 +1275,14 @@ function createCacheKeyData(model, dimensions) {
|
|
|
719
1275
|
...typeof dimensions === "number" ? { outputDimensionality: dimensions } : {}
|
|
720
1276
|
};
|
|
721
1277
|
}
|
|
722
|
-
function resolveModelIdentity(local,
|
|
723
|
-
const
|
|
1278
|
+
function resolveModelIdentity(local, dimensions) {
|
|
1279
|
+
const embeddingModel = resolveLlamaCppEmbeddingModel(local);
|
|
1280
|
+
const configuredCacheDir = embeddingModel.cacheDir;
|
|
724
1281
|
const currentDefaultPath = path.resolve(configuredCacheDir, DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE);
|
|
725
1282
|
const legacyDefaultPath = path.resolve(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE);
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
cacheKeyData: createCacheKeyData(modelPath, dimensions),
|
|
1283
|
+
if (!embeddingModel.isDefault) return {
|
|
1284
|
+
model: embeddingModel.source,
|
|
1285
|
+
cacheKeyData: createCacheKeyData(embeddingModel.source, dimensions),
|
|
730
1286
|
aliases: []
|
|
731
1287
|
};
|
|
732
1288
|
const aliases = /* @__PURE__ */ new Set([
|
|
@@ -734,7 +1290,7 @@ function resolveModelIdentity(local, modelPath, dimensions) {
|
|
|
734
1290
|
legacyDefaultPath,
|
|
735
1291
|
DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE
|
|
736
1292
|
]);
|
|
737
|
-
if (
|
|
1293
|
+
if (embeddingModel.source !== "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") aliases.add(embeddingModel.source);
|
|
738
1294
|
return {
|
|
739
1295
|
model: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
|
|
740
1296
|
cacheKeyData: createCacheKeyData(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, dimensions),
|
|
@@ -744,14 +1300,6 @@ function resolveModelIdentity(local, modelPath, dimensions) {
|
|
|
744
1300
|
}))
|
|
745
1301
|
};
|
|
746
1302
|
}
|
|
747
|
-
function resolveLlamaCppEmbeddingModel(localValue) {
|
|
748
|
-
const local = readLocalOptions({ local: localValue });
|
|
749
|
-
const source = normalizeOptionalString(local.modelPath) ?? "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf";
|
|
750
|
-
return {
|
|
751
|
-
source,
|
|
752
|
-
isDefault: resolveModelIdentity(local, source).model === DEFAULT_LLAMA_CPP_EMBEDDING_MODEL
|
|
753
|
-
};
|
|
754
|
-
}
|
|
755
1303
|
function resolveConfiguredProvider(options) {
|
|
756
1304
|
return resolveManagedLlamaCppProviderConfig(options.config);
|
|
757
1305
|
}
|
|
@@ -765,18 +1313,21 @@ async function prepareEmbeddingServer(options, embeddingSource, embeddingModelIs
|
|
|
765
1313
|
const cacheDir = resolveLlamaCppModelCacheDir(provider);
|
|
766
1314
|
const key = JSON.stringify([
|
|
767
1315
|
provider.baseUrl,
|
|
1316
|
+
provider.localService,
|
|
768
1317
|
embeddingSource,
|
|
769
1318
|
cacheDir
|
|
770
1319
|
]);
|
|
771
1320
|
const pending = preparedEmbeddingServers.get(key) ?? (async () => {
|
|
772
1321
|
await prepareManagedLlamaServer({
|
|
1322
|
+
chatModel: { mode: "preserve" },
|
|
773
1323
|
embeddingModelIsDefault,
|
|
774
1324
|
embeddingModelPath: await ensureLlamaCppModel({
|
|
775
1325
|
source: embeddingSource,
|
|
776
1326
|
cacheDir,
|
|
777
1327
|
download: true
|
|
778
1328
|
}),
|
|
779
|
-
port: resolveProviderPort(provider)
|
|
1329
|
+
port: resolveProviderPort(provider),
|
|
1330
|
+
localService: provider.localService
|
|
780
1331
|
});
|
|
781
1332
|
})();
|
|
782
1333
|
preparedEmbeddingServers.set(key, pending);
|
|
@@ -793,7 +1344,6 @@ function wrapProvider(params) {
|
|
|
793
1344
|
runtimeFacts = await inspectLlamaServerRuntime({
|
|
794
1345
|
baseUrl: params.baseUrl,
|
|
795
1346
|
modelId: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
|
|
796
|
-
backend: selectLlamaServerAsset().backend,
|
|
797
1347
|
loadError
|
|
798
1348
|
});
|
|
799
1349
|
};
|
|
@@ -828,13 +1378,12 @@ const llamaCppEmbeddingProviderAdapter = {
|
|
|
828
1378
|
transport: "local",
|
|
829
1379
|
formatSetupError: (error) => `Managed local embeddings are unavailable. Run \`openclaw configure\`, choose llama.cpp, and retry. ${error instanceof Error ? error.message : String(error)}`,
|
|
830
1380
|
resolveIndexIdentity: (options) => {
|
|
831
|
-
|
|
832
|
-
return resolveModelIdentity(local, normalizeOptionalString(local.modelPath) ?? "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf", options.dimensions);
|
|
1381
|
+
return resolveModelIdentity(readIdentityLocalOptions(options), options.dimensions);
|
|
833
1382
|
},
|
|
834
1383
|
create: async (options) => {
|
|
835
1384
|
const local = readIdentityLocalOptions(options);
|
|
836
1385
|
const embeddingModel = resolveLlamaCppEmbeddingModel(local);
|
|
837
|
-
const identity = resolveModelIdentity(local,
|
|
1386
|
+
const identity = resolveModelIdentity(local, options.dimensions);
|
|
838
1387
|
await prepareEmbeddingServer(options, embeddingModel.source, embeddingModel.isDefault);
|
|
839
1388
|
const genericAdapter = getEmbeddingProvider("openai-compatible", options.config);
|
|
840
1389
|
if (!genericAdapter) throw new Error("OpenAI-compatible embedding transport is unavailable.");
|
|
@@ -853,8 +1402,8 @@ const llamaCppEmbeddingProviderAdapter = {
|
|
|
853
1402
|
}),
|
|
854
1403
|
runtime: {
|
|
855
1404
|
id: "local",
|
|
856
|
-
inlineQueryTimeoutMs:
|
|
857
|
-
inlineBatchTimeoutMs:
|
|
1405
|
+
inlineQueryTimeoutMs: 3e5,
|
|
1406
|
+
inlineBatchTimeoutMs: 6e5,
|
|
858
1407
|
cacheKeyData: identity.cacheKeyData,
|
|
859
1408
|
...identity.aliases.length > 0 ? { indexIdentityAliases: identity.aliases } : {}
|
|
860
1409
|
}
|
|
@@ -1531,16 +2080,20 @@ function formatDownloadProgress(label, params) {
|
|
|
1531
2080
|
const totalSize = Math.max(1, params.totalSize);
|
|
1532
2081
|
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)`;
|
|
1533
2082
|
}
|
|
1534
|
-
function
|
|
1535
|
-
return
|
|
2083
|
+
function describeEmbeddingDownload(isDefault) {
|
|
2084
|
+
return isDefault ? "the local embedding model (about 0.3 GB)" : "your configured local embedding model";
|
|
1536
2085
|
}
|
|
1537
2086
|
function readPrimaryModel(config) {
|
|
1538
2087
|
const model = config.agents?.defaults?.model;
|
|
1539
2088
|
return typeof model === "string" ? model : model?.primary;
|
|
1540
2089
|
}
|
|
1541
|
-
function configuredCandidates(config) {
|
|
2090
|
+
function configuredCandidates(config, scope) {
|
|
1542
2091
|
const existing = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1543
|
-
const
|
|
2092
|
+
const managedExisting = existing?.localService ? existing : void 0;
|
|
2093
|
+
const provider = buildLlamaCppProviderConfig({
|
|
2094
|
+
existing: managedExisting,
|
|
2095
|
+
...managedExisting && scope === "detection" ? { modelInventory: managedExisting.models } : {}
|
|
2096
|
+
});
|
|
1544
2097
|
const primary = readPrimaryModel(config);
|
|
1545
2098
|
const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
|
|
1546
2099
|
return provider.models.map((model) => ({
|
|
@@ -1549,9 +2102,19 @@ function configuredCandidates(config) {
|
|
|
1549
2102
|
})).toSorted((a, b) => Number(b.model.id === primaryId) - Number(a.model.id === primaryId));
|
|
1550
2103
|
}
|
|
1551
2104
|
async function isFile(filePath) {
|
|
1552
|
-
return await
|
|
2105
|
+
return await fs.stat(filePath).then((stat) => stat.isFile()).catch(() => false);
|
|
1553
2106
|
}
|
|
1554
|
-
async function
|
|
2107
|
+
async function resolveCachedArtifact(source, cacheDir, signal) {
|
|
2108
|
+
return await ensureLlamaCppModel({
|
|
2109
|
+
source,
|
|
2110
|
+
cacheDir,
|
|
2111
|
+
download: false,
|
|
2112
|
+
signal
|
|
2113
|
+
}).catch(() => {
|
|
2114
|
+
signal?.throwIfAborted();
|
|
2115
|
+
});
|
|
2116
|
+
}
|
|
2117
|
+
async function resolveCachedCandidate(candidate, signal) {
|
|
1555
2118
|
const source = resolveLlamaCppModelSource(candidate.model);
|
|
1556
2119
|
const resolved = resolveCachedLlamaCppModelPath(candidate);
|
|
1557
2120
|
if (resolved && await isFile(resolved)) return resolved;
|
|
@@ -1559,33 +2122,23 @@ async function resolveCachedCandidate(candidate) {
|
|
|
1559
2122
|
const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
|
|
1560
2123
|
if (await isFile(legacy)) return legacy;
|
|
1561
2124
|
}
|
|
1562
|
-
if (/^(?:hf|huggingface|https):/iu.test(source)) return await
|
|
1563
|
-
source,
|
|
1564
|
-
cacheDir: resolveLlamaCppModelCacheDir(candidate.provider),
|
|
1565
|
-
download: false
|
|
1566
|
-
}).catch(() => void 0);
|
|
1567
|
-
}
|
|
1568
|
-
function readConfiguredPort(provider) {
|
|
1569
|
-
try {
|
|
1570
|
-
const url = new URL(provider?.baseUrl ?? "");
|
|
1571
|
-
if (url.hostname !== "127.0.0.1" && url.hostname !== "localhost" && url.hostname !== "[::1]") return;
|
|
1572
|
-
const port = Number(url.port);
|
|
1573
|
-
return Number.isInteger(port) && port > 0 ? port : void 0;
|
|
1574
|
-
} catch {
|
|
1575
|
-
return;
|
|
1576
|
-
}
|
|
2125
|
+
if (/^(?:hf|huggingface|https):/iu.test(source)) return await resolveCachedArtifact(source, resolveLlamaCppModelCacheDir(candidate.provider), signal);
|
|
1577
2126
|
}
|
|
1578
2127
|
function buildSetupResult(params) {
|
|
1579
2128
|
const existing = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1580
2129
|
const switchingFromExternal = Boolean(existing && !existing.localService);
|
|
1581
2130
|
return {
|
|
1582
2131
|
profiles: [],
|
|
1583
|
-
defaultModel: params.defaultModel
|
|
2132
|
+
...params.defaultModel ? { defaultModel: params.defaultModel } : {},
|
|
1584
2133
|
configPatch: {
|
|
1585
2134
|
...buildLlamaCppAuthProfileRemovalPatch(params.config),
|
|
1586
2135
|
models: {
|
|
1587
2136
|
mode: params.config.models?.mode ?? "merge",
|
|
1588
|
-
providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig(
|
|
2137
|
+
providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig({
|
|
2138
|
+
existing: switchingFromExternal ? void 0 : existing,
|
|
2139
|
+
managed: params.managed,
|
|
2140
|
+
modelInventory: params.plan === "embedding-only" ? [] : params.model ? [params.model, ...existing?.localService ? existing.models.filter((model) => model.id !== params.model?.id) : []] : existing?.models
|
|
2141
|
+
}) }
|
|
1589
2142
|
}
|
|
1590
2143
|
}
|
|
1591
2144
|
};
|
|
@@ -1595,7 +2148,7 @@ async function detectLlamaCppSetup(ctx) {
|
|
|
1595
2148
|
const command = existing?.localService?.command;
|
|
1596
2149
|
const presetPath = existing?.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset");
|
|
1597
2150
|
if (!command || !path.isAbsolute(command) || !await isFile(command) || !presetPath || !await isFile(presetPath)) return null;
|
|
1598
|
-
for (const candidate of configuredCandidates(ctx.config)) if (await resolveCachedCandidate(candidate)) return {
|
|
2151
|
+
for (const candidate of configuredCandidates(ctx.config, "detection")) if (await resolveCachedCandidate(candidate, ctx.signal)) return {
|
|
1599
2152
|
modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
|
|
1600
2153
|
detail: "Managed llama.cpp server ready"
|
|
1601
2154
|
};
|
|
@@ -1609,6 +2162,7 @@ async function prepareLlamaCppSetup(ctx) {
|
|
|
1609
2162
|
const rootUrl = baseUrl.replace(/\/v1$/u, "");
|
|
1610
2163
|
return buildSetupResult({
|
|
1611
2164
|
config: ctx.config,
|
|
2165
|
+
plan: "chat",
|
|
1612
2166
|
defaultModel: ctx.modelRef,
|
|
1613
2167
|
managed: {
|
|
1614
2168
|
command: existing.localService.command,
|
|
@@ -1618,66 +2172,166 @@ async function prepareLlamaCppSetup(ctx) {
|
|
|
1618
2172
|
}
|
|
1619
2173
|
});
|
|
1620
2174
|
}
|
|
2175
|
+
function resolveEmbeddingSetup(config, cacheDir) {
|
|
2176
|
+
const defaults = config.memory?.search;
|
|
2177
|
+
const models = listAgentIds(config).flatMap((agentId) => {
|
|
2178
|
+
const override = resolveAgentConfig(config, agentId)?.memory?.search;
|
|
2179
|
+
if (!(override?.enabled ?? defaults?.enabled ?? true) || (override?.provider ?? defaults?.provider) !== "local") return [];
|
|
2180
|
+
return [resolveLlamaCppEmbeddingModel({
|
|
2181
|
+
modelPath: override?.local?.modelPath ?? defaults?.local?.modelPath,
|
|
2182
|
+
modelCacheDir: cacheDir
|
|
2183
|
+
})];
|
|
2184
|
+
});
|
|
2185
|
+
const model = models[0] ?? resolveLlamaCppEmbeddingModel({ modelCacheDir: cacheDir });
|
|
2186
|
+
return {
|
|
2187
|
+
model,
|
|
2188
|
+
localMemoryIntent: models.length > 0,
|
|
2189
|
+
conflict: models.some((candidate) => candidate.source !== model.source)
|
|
2190
|
+
};
|
|
2191
|
+
}
|
|
2192
|
+
async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localMemoryIntent, hardware, asset, runtimeNote) {
|
|
2193
|
+
let candidate = candidates[0];
|
|
2194
|
+
const configuredPath = candidate ? await resolveCachedCandidate(candidate, ctx.signal) : void 0;
|
|
2195
|
+
if (candidate && configuredPath) {
|
|
2196
|
+
if (runtimeNote && !await ctx.prompter.confirm({
|
|
2197
|
+
message: `${runtimeNote} Use cached ${candidate.model.name} on Gateway host ${os.hostname()} with the verified CPU runtime?`,
|
|
2198
|
+
initialValue: false
|
|
2199
|
+
})) return;
|
|
2200
|
+
return {
|
|
2201
|
+
kind: "chat",
|
|
2202
|
+
candidate,
|
|
2203
|
+
cachedPath: configuredPath
|
|
2204
|
+
};
|
|
2205
|
+
}
|
|
2206
|
+
const provider = candidate?.provider ?? buildLlamaCppProviderConfig();
|
|
2207
|
+
const cacheDir = resolveLlamaCppModelCacheDir(provider);
|
|
2208
|
+
const cachedModels = /* @__PURE__ */ new Map();
|
|
2209
|
+
for (const recipe of resolveLlamaCppModelCandidates(hardware, asset.backend).recipes) {
|
|
2210
|
+
const cached = await resolveCachedArtifact(resolveLlamaCppModelSource(recipe.model), cacheDir, ctx.signal);
|
|
2211
|
+
if (cached) {
|
|
2212
|
+
cachedModels.set(recipe.model.id, cached);
|
|
2213
|
+
break;
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
const cachedEmbedding = embeddingModelIsDefault && Boolean(await resolveCachedArtifact("hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf", cacheDir, ctx.signal));
|
|
2217
|
+
const recommendation = recommendLlamaCppModel(hardware, asset.backend, {
|
|
2218
|
+
modelIds: new Set(cachedModels.keys()),
|
|
2219
|
+
embedding: cachedEmbedding,
|
|
2220
|
+
runtime: await isFile(resolveManagedLlamaServerPaths(asset).command)
|
|
2221
|
+
});
|
|
2222
|
+
if (recommendation.kind === "recommended") {
|
|
2223
|
+
const { recipe } = recommendation;
|
|
2224
|
+
const cachedPath = cachedModels.get(recipe.model.id);
|
|
2225
|
+
candidate = {
|
|
2226
|
+
model: recipe.model,
|
|
2227
|
+
provider
|
|
2228
|
+
};
|
|
2229
|
+
const recommendationSummary = [
|
|
2230
|
+
`Runs on Gateway host ${os.hostname()} (${hardware.platform}/${hardware.arch}), using ${asset.backend === "metal" ? "Apple Metal" : asset.backend === "cuda" ? "NVIDIA CUDA" : "the CPU"}.`,
|
|
2231
|
+
`${formatLlamaCppMemory(hardware.totalMemoryBytes)} RAM; ${formatLlamaCppMemory(hardware.availableDiskBytes ?? 0)} free disk.`,
|
|
2232
|
+
!hardware.sharedDisk ? `${formatLlamaCppMemory(hardware.availableRuntimeDiskBytes ?? 0)} free on the runtime volume.` : void 0,
|
|
2233
|
+
runtimeNote,
|
|
2234
|
+
recommendation.reason,
|
|
2235
|
+
!embeddingModelIsDefault ? "This estimate includes the default embedding model; your configured embedding model may need more memory and disk space." : void 0,
|
|
2236
|
+
"OpenClaw will check a real tool call before making this your default model."
|
|
2237
|
+
].filter(Boolean).join("\n");
|
|
2238
|
+
if (await ctx.prompter.confirm({
|
|
2239
|
+
message: `${recommendationSummary}\n\n${cachedPath ? `Use cached ${recipe.model.name}, download any missing embedding and ${asset.backend.toUpperCase()} runtime files, then use this model?` : `Download ${recipe.model.name} (${(recipe.sizeBytes / BYTES_PER_GB).toFixed(1)} GB), ${describeEmbeddingDownload(embeddingModelIsDefault)}, and the verified ${asset.backend.toUpperCase()} runtime, then use this model?`}`,
|
|
2240
|
+
initialValue: false
|
|
2241
|
+
})) return {
|
|
2242
|
+
kind: "chat",
|
|
2243
|
+
candidate,
|
|
2244
|
+
cachedPath
|
|
2245
|
+
};
|
|
2246
|
+
} else if (!localMemoryIntent) {
|
|
2247
|
+
await ctx.prompter.note(recommendation.reason, "Setup skipped");
|
|
2248
|
+
return;
|
|
2249
|
+
}
|
|
2250
|
+
const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
2251
|
+
if (localMemoryIntent && existing && (!existing.localService || existing.models.length > 0)) {
|
|
2252
|
+
await ctx.prompter.note("Embedding-only setup cannot replace an existing llama.cpp server or configured llama.cpp chat routes. Move those routes to another provider, remove any existing server config, then retry llama.cpp setup.", "Setup skipped");
|
|
2253
|
+
return;
|
|
2254
|
+
}
|
|
2255
|
+
if (localMemoryIntent) {
|
|
2256
|
+
if (await ctx.prompter.confirm({
|
|
2257
|
+
message: `${runtimeNote ? `${runtimeNote} ` : ""}Install a verified ${asset.backend.toUpperCase()} llama.cpp server on Gateway host ${os.hostname()} and download only ${describeEmbeddingDownload(embeddingModelIsDefault)}? Your chat model will stay unchanged.`,
|
|
2258
|
+
initialValue: false
|
|
2259
|
+
})) return { kind: "embedding-only" };
|
|
2260
|
+
}
|
|
2261
|
+
await ctx.prompter.note("Local model setup skipped.", "Setup skipped");
|
|
2262
|
+
}
|
|
1621
2263
|
async function runLlamaCppSetup(ctx) {
|
|
1622
2264
|
const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1623
2265
|
const managedExisting = existing?.localService ? existing : void 0;
|
|
1624
|
-
const
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
const totalmemBytes = os.totalmem();
|
|
1630
|
-
if (!selected || !meetsLlamaCppDefaultModelRamFloor(totalmemBytes)) {
|
|
1631
|
-
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");
|
|
1632
|
-
return { profiles: [] };
|
|
1633
|
-
}
|
|
1634
|
-
if (!await ctx.prompter.confirm({
|
|
1635
|
-
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?",
|
|
1636
|
-
initialValue: false
|
|
1637
|
-
})) {
|
|
1638
|
-
await ctx.prompter.note("Local model setup skipped.", "Setup skipped");
|
|
1639
|
-
return { profiles: [] };
|
|
1640
|
-
}
|
|
2266
|
+
const cacheDir = resolveLlamaCppModelCacheDir(managedExisting);
|
|
2267
|
+
const embeddingSetup = resolveEmbeddingSetup(ctx.config, cacheDir);
|
|
2268
|
+
if (embeddingSetup.conflict) {
|
|
2269
|
+
await ctx.prompter.note("Configured agents resolve to different local embedding models. Set memory.search.local.modelPath and any per-agent overrides to the same value, then retry llama.cpp setup.", "Setup skipped");
|
|
2270
|
+
return { profiles: [] };
|
|
1641
2271
|
}
|
|
1642
|
-
|
|
2272
|
+
const embeddingModel = embeddingSetup.model;
|
|
2273
|
+
const hardware = await detectLlamaCppHardware({
|
|
2274
|
+
cacheDir,
|
|
2275
|
+
signal: ctx.signal
|
|
2276
|
+
});
|
|
2277
|
+
let asset;
|
|
2278
|
+
let runtimeNote;
|
|
2279
|
+
try {
|
|
2280
|
+
asset = selectLlamaServerAsset(hardware.platform, hardware.arch, hardware.accelerator);
|
|
2281
|
+
} catch (error) {
|
|
2282
|
+
if (hardware.accelerator.kind !== "cuda") throw error;
|
|
2283
|
+
asset = selectLlamaServerAsset(hardware.platform, hardware.arch, { kind: "cpu" });
|
|
2284
|
+
runtimeNote = `${error instanceof Error ? error.message : String(error)} This recommendation uses CPU execution.`;
|
|
2285
|
+
}
|
|
2286
|
+
const plan = await resolveSetupPlan(ctx, configuredCandidates(ctx.config, "setup"), embeddingModel.isDefault, embeddingSetup.localMemoryIntent, hardware, asset, runtimeNote);
|
|
2287
|
+
if (!plan) return { profiles: [] };
|
|
1643
2288
|
const progress = ctx.prompter.progress("Preparing managed llama.cpp server…");
|
|
1644
2289
|
try {
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
2290
|
+
let chatModel;
|
|
2291
|
+
if (plan.kind === "chat") {
|
|
2292
|
+
const chatModelPath = plan.cachedPath ?? await ensureLlamaCppModel({
|
|
2293
|
+
source: resolveLlamaCppModelSource(plan.candidate.model),
|
|
2294
|
+
cacheDir,
|
|
2295
|
+
download: true,
|
|
2296
|
+
signal: ctx.signal,
|
|
2297
|
+
onProgress: (status) => progress.update(formatDownloadProgress(plan.candidate.model.name, status))
|
|
2298
|
+
});
|
|
2299
|
+
const configuredContext = plan.candidate.model.params?.contextSize;
|
|
2300
|
+
chatModel = {
|
|
2301
|
+
mode: "configure",
|
|
2302
|
+
id: plan.candidate.model.id,
|
|
2303
|
+
path: chatModelPath,
|
|
2304
|
+
contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : plan.candidate.model.contextTokens,
|
|
2305
|
+
maxTokens: plan.candidate.model.maxTokens
|
|
2306
|
+
};
|
|
2307
|
+
} else chatModel = { mode: "remove" };
|
|
2308
|
+
const embeddingModelLabel = embeddingModel.isDefault ? "EmbeddingGemma" : "configured embedding model";
|
|
1653
2309
|
const embeddingModelPath = await ensureLlamaCppModel({
|
|
1654
|
-
source:
|
|
2310
|
+
source: embeddingModel.source,
|
|
1655
2311
|
cacheDir,
|
|
1656
2312
|
download: true,
|
|
1657
2313
|
signal: ctx.signal,
|
|
1658
|
-
onProgress: (status) => progress.update(formatDownloadProgress(
|
|
2314
|
+
onProgress: (status) => progress.update(formatDownloadProgress(embeddingModelLabel, status))
|
|
1659
2315
|
});
|
|
1660
|
-
const configuredContext = selected.model.params?.contextSize;
|
|
1661
|
-
const contextSize = typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : selected.model.contextTokens;
|
|
1662
2316
|
const managed = await prepareManagedLlamaServer({
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
contextSize,
|
|
1666
|
-
maxTokens: selected.model.maxTokens,
|
|
1667
|
-
embeddingModelIsDefault: true,
|
|
2317
|
+
chatModel,
|
|
2318
|
+
embeddingModelIsDefault: embeddingModel.isDefault,
|
|
1668
2319
|
embeddingModelPath,
|
|
1669
|
-
|
|
2320
|
+
asset,
|
|
2321
|
+
isolated: true,
|
|
2322
|
+
signal: ctx.signal,
|
|
2323
|
+
onProgress: (status) => progress.update(formatDownloadProgress("llama.cpp runtime", status))
|
|
1670
2324
|
});
|
|
1671
|
-
|
|
1672
|
-
provider: "llama-cpp",
|
|
1673
|
-
profileIds: [LLAMA_CPP_DEFAULT_PROFILE_ID],
|
|
1674
|
-
agentDir: ctx.agentDir
|
|
1675
|
-
})) throw new Error("Failed to remove the previous llama.cpp endpoint auth profile");
|
|
2325
|
+
ctx.signal?.throwIfAborted();
|
|
1676
2326
|
progress.stop("Managed llama.cpp server prepared");
|
|
1677
2327
|
return buildSetupResult({
|
|
1678
2328
|
config: ctx.config,
|
|
1679
2329
|
managed,
|
|
1680
|
-
|
|
2330
|
+
plan: plan.kind,
|
|
2331
|
+
...plan.kind === "chat" ? {
|
|
2332
|
+
defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${plan.candidate.model.id}`,
|
|
2333
|
+
model: plan.candidate.model
|
|
2334
|
+
} : {}
|
|
1681
2335
|
});
|
|
1682
2336
|
} catch (error) {
|
|
1683
2337
|
progress.stop("llama.cpp setup failed");
|
|
@@ -1696,12 +2350,12 @@ function registerLlamaCppProvider(api) {
|
|
|
1696
2350
|
auth: [{
|
|
1697
2351
|
id: "local",
|
|
1698
2352
|
label: LLAMA_CPP_PROVIDER_LABEL,
|
|
1699
|
-
hint: "
|
|
2353
|
+
hint: "Choose a Qwen, Gemma, or Muse model for this Gateway’s hardware and install llama.cpp",
|
|
1700
2354
|
kind: "custom",
|
|
1701
2355
|
wizard: {
|
|
1702
2356
|
choiceId: LLAMA_CPP_PROVIDER_ID,
|
|
1703
2357
|
choiceLabel: "Managed local server",
|
|
1704
|
-
choiceHint: "
|
|
2358
|
+
choiceHint: "Choose a Qwen, Gemma, or Muse model for this Gateway’s hardware and install llama.cpp",
|
|
1705
2359
|
groupId: LLAMA_CPP_PROVIDER_ID,
|
|
1706
2360
|
groupLabel: "Local llama.cpp",
|
|
1707
2361
|
groupHint: "Managed or external llama.cpp server",
|
|
@@ -1738,7 +2392,10 @@ function registerLlamaCppProvider(api) {
|
|
|
1738
2392
|
order: "late",
|
|
1739
2393
|
run: async (ctx) => {
|
|
1740
2394
|
const configured = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1741
|
-
return configured?.localService ? { provider: buildLlamaCppProviderConfig(
|
|
2395
|
+
return configured?.localService ? { provider: buildLlamaCppProviderConfig({
|
|
2396
|
+
existing: configured,
|
|
2397
|
+
modelInventory: configured.models
|
|
2398
|
+
}) } : await discoverLlamaServerProvider(ctx);
|
|
1742
2399
|
}
|
|
1743
2400
|
},
|
|
1744
2401
|
staticCatalog: {
|
|
@@ -1755,10 +2412,10 @@ function registerLlamaCppProvider(api) {
|
|
|
1755
2412
|
prepareDynamicModel: async (ctx) => ctx.config?.models?.providers?.["llama-cpp"]?.localService ? void 0 : await prepareLlamaServerDynamicModel(ctx),
|
|
1756
2413
|
wrapStreamFn: (ctx) => {
|
|
1757
2414
|
const providerConfig = ctx.config?.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1758
|
-
|
|
1759
|
-
|
|
2415
|
+
const inner = wrapLlamaServerStream(ctx);
|
|
2416
|
+
if (!providerConfig?.localService) return inner;
|
|
1760
2417
|
const selectedModel = ctx.model;
|
|
1761
|
-
if (!
|
|
2418
|
+
if (!selectedModel) return;
|
|
1762
2419
|
return async (model, context, options) => {
|
|
1763
2420
|
await ensureManagedLlamaServerForChat({
|
|
1764
2421
|
provider: providerConfig,
|