@openclaw/llama-cpp-provider 2026.9.1 → 2026.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -1,22 +1,24 @@
|
|
|
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
5
|
import os from "node:os";
|
|
6
6
|
import { asBoolean, asOptionalRecord, asPositiveSafeInteger, isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
7
|
-
import { execFile } from "node:child_process";
|
|
8
7
|
import { createHash, randomUUID } from "node:crypto";
|
|
9
|
-
import fs
|
|
10
|
-
import fs$1 from "node:fs/promises";
|
|
11
|
-
import { ARCHIVE_LIMIT_ERROR_CODE, ArchiveLimitError, extractArchive } from "openclaw/plugin-sdk/archive";
|
|
8
|
+
import fs from "node:fs/promises";
|
|
12
9
|
import net from "node:net";
|
|
13
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";
|
|
19
20
|
import { resolveConfiguredSecretInputString } from "openclaw/plugin-sdk/secret-input-runtime";
|
|
21
|
+
import * as liveCatalogRuntime from "openclaw/plugin-sdk/provider-catalog-live-runtime";
|
|
20
22
|
import { getCachedLiveCatalogValue } from "openclaw/plugin-sdk/provider-catalog-shared";
|
|
21
23
|
import { SELF_HOSTED_DEFAULT_CONTEXT_WINDOW, SELF_HOSTED_DEFAULT_COST, SELF_HOSTED_DEFAULT_MAX_TOKENS, applyProviderDefaultModel, discoverOpenAICompatibleLocalModels } from "openclaw/plugin-sdk/provider-setup";
|
|
22
24
|
import { selectPreferredLocalModelId } from "openclaw/plugin-sdk/provider-model-shared";
|
|
@@ -24,25 +26,31 @@ import { streamSimple } from "openclaw/plugin-sdk/llm";
|
|
|
24
26
|
import { setQwenChatTemplateThinking } from "openclaw/plugin-sdk/provider-stream-shared";
|
|
25
27
|
import { listAgentIds, resolveAgentConfig } from "openclaw/plugin-sdk/agent-scope-runtime";
|
|
26
28
|
//#region extensions/llama-cpp/src/llama-server-assets.ts
|
|
27
|
-
const LLAMA_SERVER_RELEASE = "
|
|
28
|
-
const LLAMA_SERVER_COMMIT = "
|
|
29
|
+
const LLAMA_SERVER_RELEASE = "b10809";
|
|
30
|
+
const LLAMA_SERVER_COMMIT = "5266f24da75dc449bd56cbed7addb9c8e4a6a73e";
|
|
31
|
+
const MEBIBYTE$1 = 1048576;
|
|
32
|
+
const CUDA_ARCHIVE_LIMITS = {
|
|
33
|
+
maxArchiveBytes: 400 * MEBIBYTE$1,
|
|
34
|
+
maxExtractedBytes: 600 * MEBIBYTE$1,
|
|
35
|
+
maxEntryBytes: 521 * MEBIBYTE$1
|
|
36
|
+
};
|
|
29
37
|
const MACOS_ALIASES = [
|
|
30
|
-
["libggml-rpc.0.
|
|
31
|
-
["libllama.0.
|
|
32
|
-
["libmtmd.0.
|
|
33
|
-
["libggml.0.
|
|
34
|
-
["libggml-base.0.
|
|
35
|
-
["libggml-blas.0.
|
|
36
|
-
["libllama-common.0.
|
|
37
|
-
["libggml-cpu.0.
|
|
38
|
+
["libggml-rpc.0.23.0.dylib", ["libggml-rpc.0.dylib", "libggml-rpc.dylib"]],
|
|
39
|
+
["libllama.0.4.0.dylib", ["libllama.0.dylib", "libllama.dylib"]],
|
|
40
|
+
["libmtmd.0.4.0.dylib", ["libmtmd.0.dylib", "libmtmd.dylib"]],
|
|
41
|
+
["libggml.0.23.0.dylib", ["libggml.0.dylib", "libggml.dylib"]],
|
|
42
|
+
["libggml-base.0.23.0.dylib", ["libggml-base.0.dylib", "libggml-base.dylib"]],
|
|
43
|
+
["libggml-blas.0.23.0.dylib", ["libggml-blas.0.dylib", "libggml-blas.dylib"]],
|
|
44
|
+
["libllama-common.0.4.0.dylib", ["libllama-common.0.dylib", "libllama-common.dylib"]],
|
|
45
|
+
["libggml-cpu.0.23.0.dylib", ["libggml-cpu.0.dylib", "libggml-cpu.dylib"]]
|
|
38
46
|
];
|
|
39
|
-
const MACOS_METAL_ALIASES = [...MACOS_ALIASES, ["libggml-metal.0.
|
|
47
|
+
const MACOS_METAL_ALIASES = [...MACOS_ALIASES, ["libggml-metal.0.23.0.dylib", ["libggml-metal.0.dylib", "libggml-metal.dylib"]]];
|
|
40
48
|
const LINUX_ALIASES = [
|
|
41
|
-
["libllama.so.0.
|
|
42
|
-
["libggml.so.0.
|
|
43
|
-
["libmtmd.so.0.
|
|
44
|
-
["libggml-base.so.0.
|
|
45
|
-
["libllama-common.so.0.
|
|
49
|
+
["libllama.so.0.4.0", ["libllama.so.0", "libllama.so"]],
|
|
50
|
+
["libggml.so.0.23.0", ["libggml.so.0", "libggml.so"]],
|
|
51
|
+
["libmtmd.so.0.4.0", ["libmtmd.so.0", "libmtmd.so"]],
|
|
52
|
+
["libggml-base.so.0.23.0", ["libggml-base.so.0", "libggml-base.so"]],
|
|
53
|
+
["libllama-common.so.0.4.0", ["libllama-common.so.0", "libllama-common.so"]]
|
|
46
54
|
];
|
|
47
55
|
const LLAMA_SERVER_ASSETS = [
|
|
48
56
|
{
|
|
@@ -52,7 +60,7 @@ const LLAMA_SERVER_ASSETS = [
|
|
|
52
60
|
archive: "tar.gz",
|
|
53
61
|
archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
|
|
54
62
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-arm64.tar.gz`,
|
|
55
|
-
sha256: "
|
|
63
|
+
sha256: "7d692df9e1e386e62f1c12b843903218041e6cd74c9415aa39a7ed3176f9eaa2",
|
|
56
64
|
executable: "llama-server",
|
|
57
65
|
regularFileAliases: MACOS_METAL_ALIASES
|
|
58
66
|
},
|
|
@@ -63,7 +71,7 @@ const LLAMA_SERVER_ASSETS = [
|
|
|
63
71
|
archive: "tar.gz",
|
|
64
72
|
archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
|
|
65
73
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-x64.tar.gz`,
|
|
66
|
-
sha256: "
|
|
74
|
+
sha256: "13b34aa8a5d87341a21065a83f54a8167e1aaa6fe0d66065de01632a1ed64be6",
|
|
67
75
|
executable: "llama-server",
|
|
68
76
|
regularFileAliases: MACOS_ALIASES
|
|
69
77
|
},
|
|
@@ -74,7 +82,7 @@ const LLAMA_SERVER_ASSETS = [
|
|
|
74
82
|
archive: "tar.gz",
|
|
75
83
|
archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
|
|
76
84
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-arm64.tar.gz`,
|
|
77
|
-
sha256: "
|
|
85
|
+
sha256: "f2b7333971e1b7b42e9268bfdbfa30f5f56e2897156084d2251385df94aec358",
|
|
78
86
|
executable: "llama-server",
|
|
79
87
|
regularFileAliases: LINUX_ALIASES
|
|
80
88
|
},
|
|
@@ -85,10 +93,38 @@ const LLAMA_SERVER_ASSETS = [
|
|
|
85
93
|
archive: "tar.gz",
|
|
86
94
|
archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
|
|
87
95
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-x64.tar.gz`,
|
|
88
|
-
sha256: "
|
|
96
|
+
sha256: "5e34434ddc6d03cd1584f403201aff0d4bd1a5793a72ff7e286532dfd1e4b941",
|
|
89
97
|
executable: "llama-server",
|
|
90
98
|
regularFileAliases: LINUX_ALIASES
|
|
91
99
|
},
|
|
100
|
+
{
|
|
101
|
+
platform: "win32",
|
|
102
|
+
arch: "x64",
|
|
103
|
+
backend: "cuda",
|
|
104
|
+
archive: "zip",
|
|
105
|
+
archiveRoot: ".",
|
|
106
|
+
name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cuda-12.4-x64.zip`,
|
|
107
|
+
sha256: "c77bfcd9ed8d91e8721a2d6a290b907fddd4fa5412a47b21c6fa1709116b85f9",
|
|
108
|
+
executable: "llama-server.exe",
|
|
109
|
+
regularFileAliases: [],
|
|
110
|
+
limits: CUDA_ARCHIVE_LIMITS,
|
|
111
|
+
dependencies: [{
|
|
112
|
+
archive: "zip",
|
|
113
|
+
archiveRoot: ".",
|
|
114
|
+
name: "cudart-llama-bin-win-cuda-12.4-x64.zip",
|
|
115
|
+
sha256: "8c79a9b226de4b3cacfd1f83d24f962d0773be79f1e7b75c6af4ded7e32ae1d6",
|
|
116
|
+
regularFileAliases: [],
|
|
117
|
+
files: [
|
|
118
|
+
"cublas64_12.dll",
|
|
119
|
+
"cublasLt64_12.dll",
|
|
120
|
+
"cudart64_12.dll"
|
|
121
|
+
],
|
|
122
|
+
limits: {
|
|
123
|
+
...CUDA_ARCHIVE_LIMITS,
|
|
124
|
+
maxEntries: 3
|
|
125
|
+
}
|
|
126
|
+
}]
|
|
127
|
+
},
|
|
92
128
|
{
|
|
93
129
|
platform: "win32",
|
|
94
130
|
arch: "arm64",
|
|
@@ -96,7 +132,7 @@ const LLAMA_SERVER_ASSETS = [
|
|
|
96
132
|
archive: "zip",
|
|
97
133
|
archiveRoot: ".",
|
|
98
134
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-arm64.zip`,
|
|
99
|
-
sha256: "
|
|
135
|
+
sha256: "c1058fe5764a687275c8d20d6bbc1454e787cdbb8ebb8c37a2f959f2b144dc77",
|
|
100
136
|
executable: "llama-server.exe",
|
|
101
137
|
regularFileAliases: []
|
|
102
138
|
},
|
|
@@ -107,18 +143,26 @@ const LLAMA_SERVER_ASSETS = [
|
|
|
107
143
|
archive: "zip",
|
|
108
144
|
archiveRoot: ".",
|
|
109
145
|
name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-x64.zip`,
|
|
110
|
-
sha256: "
|
|
146
|
+
sha256: "9df3158ed228a641a4b127942d7f459f24c9e13f04682659d05c00c80099b6b5",
|
|
111
147
|
executable: "llama-server.exe",
|
|
112
148
|
regularFileAliases: []
|
|
113
149
|
}
|
|
114
150
|
];
|
|
115
|
-
function selectLlamaServerAsset(platform = process.platform, arch = process.arch) {
|
|
116
|
-
const
|
|
151
|
+
function selectLlamaServerAsset(platform = process.platform, arch = process.arch, acceleration) {
|
|
152
|
+
const backend = acceleration?.kind ?? (platform === "darwin" && arch === "arm64" ? "metal" : "cpu");
|
|
153
|
+
if (backend === "cuda" && acceleration?.kind === "cuda") {
|
|
154
|
+
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.`);
|
|
155
|
+
if (!(acceleration.devices.length > 0 && acceleration.devices.every((device) => {
|
|
156
|
+
const version = /^(\d+)\.(\d+)(?:\.\d+)?$/u.exec(device.driverVersion);
|
|
157
|
+
return version && (Number(version[1]) > 551 || Number(version[1]) === 551 && Number(version[2]) >= 78) && (device.computeCapability === void 0 || device.computeCapability >= 5);
|
|
158
|
+
}))) 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.");
|
|
159
|
+
}
|
|
160
|
+
const asset = LLAMA_SERVER_ASSETS.find((candidate) => candidate.platform === platform && candidate.arch === arch && candidate.backend === backend);
|
|
117
161
|
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.`);
|
|
118
162
|
return asset;
|
|
119
163
|
}
|
|
120
164
|
function resolveManagedLlamaServerPaths(asset = selectLlamaServerAsset()) {
|
|
121
|
-
const installDir = path.join(resolveLlamaCppDataDir(), LLAMA_SERVER_RELEASE, `${asset.platform}-${asset.arch}`);
|
|
165
|
+
const installDir = path.join(resolveLlamaCppDataDir(), LLAMA_SERVER_RELEASE, `${asset.platform}-${asset.arch}${asset.backend === "cuda" ? "-cuda-12.4" : ""}`);
|
|
122
166
|
return {
|
|
123
167
|
installDir,
|
|
124
168
|
command: path.join(installDir, asset.executable),
|
|
@@ -148,13 +192,13 @@ function resolveArchiveRoot(destDir, archiveRoot) {
|
|
|
148
192
|
return path.join(destDir, ...parts);
|
|
149
193
|
}
|
|
150
194
|
async function assertRegularFile(filePath, label) {
|
|
151
|
-
const stat = await fs
|
|
195
|
+
const stat = await fs.lstat(filePath).catch(() => void 0);
|
|
152
196
|
if (!stat?.isFile() || stat.nlink > 1) throw new Error(`llama-server archive does not contain regular ${label}`);
|
|
153
197
|
return stat;
|
|
154
198
|
}
|
|
155
199
|
async function materializeAssetAliases(params) {
|
|
156
|
-
const claimedNames =
|
|
157
|
-
await assertRegularFile(path.join(params.rootDir,
|
|
200
|
+
const claimedNames = new Set(params.requiredFiles.map(assertManifestBasename));
|
|
201
|
+
for (const file of claimedNames) await assertRegularFile(path.join(params.rootDir, file), `file ${file}`);
|
|
158
202
|
let copiedBytes = 0;
|
|
159
203
|
for (const [rawSource, rawAliases] of params.asset.regularFileAliases) {
|
|
160
204
|
const source = assertManifestBasename(rawSource);
|
|
@@ -169,25 +213,28 @@ async function materializeAssetAliases(params) {
|
|
|
169
213
|
copiedBytes += sourceStat.size;
|
|
170
214
|
if (copiedBytes > MAX_ALIAS_BYTES) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.EXTRACTED_SIZE_EXCEEDS_LIMIT);
|
|
171
215
|
const aliasPath = path.join(params.rootDir, alias);
|
|
172
|
-
await fs
|
|
173
|
-
await fs
|
|
216
|
+
await fs.copyFile(sourcePath, aliasPath, constants.COPYFILE_EXCL);
|
|
217
|
+
await fs.chmod(aliasPath, sourceStat.mode & 511);
|
|
174
218
|
if ((await assertRegularFile(aliasPath, `alias ${alias}`)).size !== sourceStat.size) throw new Error(`llama-server archive alias copy is incomplete: ${alias}`);
|
|
175
219
|
}
|
|
176
220
|
}
|
|
177
221
|
}
|
|
178
|
-
|
|
179
|
-
async function extractLlamaServerArchive(params) {
|
|
222
|
+
async function extractVerifiedArchive(params) {
|
|
180
223
|
const isTar = params.asset.archive === "tar.gz";
|
|
224
|
+
const limits = {
|
|
225
|
+
...LLAMA_ARCHIVE_LIMITS,
|
|
226
|
+
...params.asset.limits
|
|
227
|
+
};
|
|
181
228
|
const aliasCount = params.asset.regularFileAliases.reduce((count, [, aliases]) => count + aliases.length, 0);
|
|
182
|
-
if (aliasCount >
|
|
229
|
+
if (aliasCount > limits.maxEntries) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.ENTRY_COUNT_EXCEEDS_LIMIT);
|
|
183
230
|
await extractArchive({
|
|
184
231
|
archivePath: params.archivePath,
|
|
185
232
|
destDir: params.destDir,
|
|
186
233
|
kind: isTar ? "tar" : "zip",
|
|
187
234
|
timeoutMs: 0,
|
|
188
235
|
limits: {
|
|
189
|
-
...
|
|
190
|
-
maxEntries:
|
|
236
|
+
...limits,
|
|
237
|
+
maxEntries: limits.maxEntries - aliasCount
|
|
191
238
|
},
|
|
192
239
|
tarGzip: isTar,
|
|
193
240
|
entryFilter: (entry) => entry.kind === "symlink" ? "skip" : "extract",
|
|
@@ -196,14 +243,30 @@ async function extractLlamaServerArchive(params) {
|
|
|
196
243
|
const rootDir = resolveArchiveRoot(params.destDir, params.asset.archiveRoot);
|
|
197
244
|
await materializeAssetAliases({
|
|
198
245
|
rootDir,
|
|
199
|
-
asset: params.asset
|
|
246
|
+
asset: params.asset,
|
|
247
|
+
requiredFiles: params.requiredFiles
|
|
248
|
+
});
|
|
249
|
+
return rootDir;
|
|
250
|
+
}
|
|
251
|
+
/** Extracts one verified asset and returns its unpublished executable path. */
|
|
252
|
+
async function extractLlamaServerArchive(params) {
|
|
253
|
+
const rootDir = await extractVerifiedArchive({
|
|
254
|
+
...params,
|
|
255
|
+
requiredFiles: [params.asset.executable]
|
|
200
256
|
});
|
|
201
257
|
return path.join(rootDir, params.asset.executable);
|
|
202
258
|
}
|
|
259
|
+
async function extractLlamaServerDependencyArchive(params) {
|
|
260
|
+
return await extractVerifiedArchive({
|
|
261
|
+
...params,
|
|
262
|
+
requiredFiles: params.asset.files
|
|
263
|
+
});
|
|
264
|
+
}
|
|
203
265
|
//#endregion
|
|
204
266
|
//#region extensions/llama-cpp/src/llama-server-install.ts
|
|
205
267
|
const DOWNLOAD_TIMEOUT_MS = 18e5;
|
|
206
268
|
const VERSION_TIMEOUT_MS = 15e3;
|
|
269
|
+
const FRESH_VERSION_TIMEOUT_MS = 12e4;
|
|
207
270
|
const installationPromises = /* @__PURE__ */ new Map();
|
|
208
271
|
function compareVersion(left, right) {
|
|
209
272
|
const leftParts = left.split(".").map(Number);
|
|
@@ -225,15 +288,51 @@ function assertSupportedLinuxRuntime(asset) {
|
|
|
225
288
|
function assetUrl(asset) {
|
|
226
289
|
return `https://github.com/ggml-org/llama.cpp/releases/download/${LLAMA_SERVER_RELEASE}/${asset.name}`;
|
|
227
290
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
291
|
+
const verifiedFiles = /* @__PURE__ */ new Map();
|
|
292
|
+
const VERIFIED_FILE_LIMIT = 16;
|
|
293
|
+
function fileIdentity(stat) {
|
|
294
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
295
|
+
}
|
|
296
|
+
function rememberVerifiedFile(filePath, stat, sha256) {
|
|
297
|
+
verifiedFiles.delete(filePath);
|
|
298
|
+
verifiedFiles.set(filePath, {
|
|
299
|
+
identity: fileIdentity(stat),
|
|
300
|
+
sha256
|
|
235
301
|
});
|
|
236
|
-
|
|
302
|
+
if (verifiedFiles.size > VERIFIED_FILE_LIMIT) {
|
|
303
|
+
const oldest = verifiedFiles.keys().next().value;
|
|
304
|
+
if (oldest !== void 0) verifiedFiles.delete(oldest);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
async function sha256File(filePath, signal) {
|
|
308
|
+
signal?.throwIfAborted();
|
|
309
|
+
try {
|
|
310
|
+
const identity = fileIdentity(await fs.stat(filePath, { bigint: true }));
|
|
311
|
+
const verified = verifiedFiles.get(filePath);
|
|
312
|
+
if (verified?.identity === identity) return verified.sha256;
|
|
313
|
+
verifiedFiles.delete(filePath);
|
|
314
|
+
const handle = await fs.open(filePath, "r");
|
|
315
|
+
try {
|
|
316
|
+
const before = fileIdentity(await handle.stat({ bigint: true }));
|
|
317
|
+
const hash = createHash("sha256");
|
|
318
|
+
const input = handle.createReadStream({
|
|
319
|
+
autoClose: false,
|
|
320
|
+
highWaterMark: 1048576,
|
|
321
|
+
signal
|
|
322
|
+
});
|
|
323
|
+
for await (const chunk of input) hash.update(chunk);
|
|
324
|
+
const after = await handle.stat({ bigint: true });
|
|
325
|
+
if (before !== fileIdentity(after) || before !== fileIdentity(await fs.stat(filePath, { bigint: true }))) throw new Error(`File changed during integrity verification: ${filePath}. Retry setup.`);
|
|
326
|
+
const sha256 = hash.digest("hex");
|
|
327
|
+
rememberVerifiedFile(filePath, after, sha256);
|
|
328
|
+
return sha256;
|
|
329
|
+
} finally {
|
|
330
|
+
await handle.close();
|
|
331
|
+
}
|
|
332
|
+
} catch (error) {
|
|
333
|
+
verifiedFiles.delete(filePath);
|
|
334
|
+
throw error;
|
|
335
|
+
}
|
|
237
336
|
}
|
|
238
337
|
function readResponseSha256(response) {
|
|
239
338
|
for (const name of ["x-checksum-sha256", "x-linked-etag"]) {
|
|
@@ -245,7 +344,7 @@ function readResponseSha256(response) {
|
|
|
245
344
|
}
|
|
246
345
|
async function downloadVerifiedFile(params) {
|
|
247
346
|
const partialPath = `${params.destination}.partial-${randomUUID()}`;
|
|
248
|
-
await fs
|
|
347
|
+
await fs.mkdir(path.dirname(params.destination), { recursive: true });
|
|
249
348
|
const { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } = await import("openclaw/plugin-sdk/ssrf-runtime");
|
|
250
349
|
try {
|
|
251
350
|
const { response, release } = await fetchWithSsrFGuard({
|
|
@@ -262,7 +361,7 @@ async function downloadVerifiedFile(params) {
|
|
|
262
361
|
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");
|
|
263
362
|
const contentLength = Number(response.headers.get("content-length"));
|
|
264
363
|
const totalSize = params.expectedSize ?? (Number.isFinite(contentLength) && contentLength > 0 ? contentLength : 0);
|
|
265
|
-
const handle = await fs
|
|
364
|
+
const handle = await fs.open(partialPath, "wx", 384);
|
|
266
365
|
const hash = createHash("sha256");
|
|
267
366
|
let downloadedSize = 0;
|
|
268
367
|
let previousSize = 0;
|
|
@@ -287,23 +386,31 @@ async function downloadVerifiedFile(params) {
|
|
|
287
386
|
bytesPerSecond: rollingBytesPerSecond
|
|
288
387
|
});
|
|
289
388
|
}
|
|
389
|
+
if (params.expectedSize && downloadedSize !== params.expectedSize) throw new Error(`download size mismatch: expected ${params.expectedSize}, got ${downloadedSize}`);
|
|
390
|
+
const actualSha256 = hash.digest("hex");
|
|
391
|
+
if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
|
|
392
|
+
const completed = await handle.stat({ bigint: true });
|
|
393
|
+
params.signal?.throwIfAborted();
|
|
394
|
+
await fs.rename(partialPath, params.destination);
|
|
395
|
+
const published = await handle.stat({ bigint: true });
|
|
396
|
+
if (completed.size === published.size && completed.mtimeNs === published.mtimeNs) rememberVerifiedFile(params.destination, published, actualSha256);
|
|
290
397
|
} finally {
|
|
291
398
|
await handle.close();
|
|
292
399
|
}
|
|
293
|
-
if (params.expectedSize && downloadedSize !== params.expectedSize) throw new Error(`download size mismatch: expected ${params.expectedSize}, got ${downloadedSize}`);
|
|
294
|
-
const actualSha256 = hash.digest("hex");
|
|
295
|
-
if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
|
|
296
|
-
await fs$1.rename(partialPath, params.destination);
|
|
297
400
|
} finally {
|
|
298
401
|
await release();
|
|
299
402
|
}
|
|
300
403
|
} finally {
|
|
301
|
-
await fs
|
|
404
|
+
await fs.rm(partialPath, { force: true }).catch(() => void 0);
|
|
302
405
|
}
|
|
303
406
|
}
|
|
304
|
-
async function
|
|
407
|
+
async function runServerCommand(command, args, signal, timeoutMs = VERSION_TIMEOUT_MS) {
|
|
305
408
|
return await new Promise((resolve, reject) => {
|
|
306
|
-
execFile(command,
|
|
409
|
+
execFile(command, args, {
|
|
410
|
+
timeout: timeoutMs,
|
|
411
|
+
signal,
|
|
412
|
+
windowsHide: true
|
|
413
|
+
}, (error, stdout, stderr) => {
|
|
307
414
|
if (error) reject(new Error(error.message, { cause: error }));
|
|
308
415
|
else resolve(`${stdout}${stderr}`.trim());
|
|
309
416
|
});
|
|
@@ -315,79 +422,512 @@ function formatRuntimeDependencyError(error) {
|
|
|
315
422
|
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 });
|
|
316
423
|
return new Error(`The verified llama-server build could not start: ${detail}`, { cause: error });
|
|
317
424
|
}
|
|
318
|
-
async function validateInstalledServer(command) {
|
|
425
|
+
async function validateInstalledServer(command, asset, signal, versionTimeoutMs = VERSION_TIMEOUT_MS) {
|
|
319
426
|
let version;
|
|
320
427
|
try {
|
|
321
|
-
version = await
|
|
428
|
+
version = await runServerCommand(command, ["--version"], signal, versionTimeoutMs);
|
|
322
429
|
} catch (error) {
|
|
430
|
+
signal?.throwIfAborted();
|
|
323
431
|
throw formatRuntimeDependencyError(error);
|
|
324
432
|
}
|
|
325
433
|
const match = (version.split(/\r?\n/u, 1)[0]?.trim() ?? "").match(/^version: .+ \(build (\d+), commit ([a-f\d]{9})\)$/u);
|
|
326
434
|
const build = match?.[1] ? Number(match[1]) : void 0;
|
|
327
435
|
const commit = match?.[2];
|
|
328
|
-
if (build !==
|
|
436
|
+
if (build !== 10809 || commit !== "5266f24da75dc449bd56cbed7addb9c8e4a6a73e".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"}`);
|
|
437
|
+
if (asset.backend === "cuda") {
|
|
438
|
+
const devices = await runServerCommand(command, ["--list-devices"], signal);
|
|
439
|
+
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.");
|
|
440
|
+
}
|
|
329
441
|
}
|
|
330
|
-
async function installLlamaServer(asset) {
|
|
442
|
+
async function installLlamaServer(asset, options) {
|
|
443
|
+
options.signal?.throwIfAborted();
|
|
331
444
|
assertSupportedLinuxRuntime(asset);
|
|
332
445
|
const { installDir, command } = resolveManagedLlamaServerPaths(asset);
|
|
333
|
-
if (await fs
|
|
334
|
-
await validateInstalledServer(command);
|
|
446
|
+
if (await fs.stat(command).then((stat) => stat.isFile()).catch(() => false)) {
|
|
447
|
+
await validateInstalledServer(command, asset, options.signal);
|
|
335
448
|
return command;
|
|
336
449
|
}
|
|
337
450
|
const dataDir = resolveLlamaCppDataDir();
|
|
338
451
|
const archivePath = path.join(dataDir, `.download-${randomUUID()}-${asset.name}`);
|
|
339
452
|
const extractDir = path.join(dataDir, `.extract-${randomUUID()}`);
|
|
340
|
-
await fs
|
|
453
|
+
await fs.mkdir(dataDir, { recursive: true });
|
|
341
454
|
try {
|
|
342
455
|
await downloadVerifiedFile({
|
|
343
456
|
url: assetUrl(asset),
|
|
344
457
|
destination: archivePath,
|
|
345
|
-
expectedSha256: asset.sha256
|
|
458
|
+
expectedSha256: asset.sha256,
|
|
459
|
+
signal: options.signal,
|
|
460
|
+
onProgress: options.onProgress
|
|
346
461
|
});
|
|
347
|
-
|
|
462
|
+
const serverExtractDir = path.join(extractDir, "server");
|
|
463
|
+
await fs.mkdir(serverExtractDir, { recursive: true });
|
|
348
464
|
const extractedCommand = await extractLlamaServerArchive({
|
|
349
465
|
archivePath,
|
|
350
|
-
destDir:
|
|
466
|
+
destDir: serverExtractDir,
|
|
351
467
|
asset
|
|
352
468
|
});
|
|
353
469
|
const extractedRoot = path.dirname(extractedCommand);
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
470
|
+
for (const [index, dependency] of (asset.dependencies ?? []).entries()) {
|
|
471
|
+
options.signal?.throwIfAborted();
|
|
472
|
+
const dependencyArchive = path.join(extractDir, dependency.name);
|
|
473
|
+
await downloadVerifiedFile({
|
|
474
|
+
url: assetUrl(dependency),
|
|
475
|
+
destination: dependencyArchive,
|
|
476
|
+
expectedSha256: dependency.sha256,
|
|
477
|
+
signal: options.signal,
|
|
478
|
+
onProgress: options.onProgress
|
|
479
|
+
});
|
|
480
|
+
const dependencyExtractDir = path.join(extractDir, `dependency-${index}`);
|
|
481
|
+
await fs.mkdir(dependencyExtractDir);
|
|
482
|
+
const dependencyRoot = await extractLlamaServerDependencyArchive({
|
|
483
|
+
archivePath: dependencyArchive,
|
|
484
|
+
destDir: dependencyExtractDir,
|
|
485
|
+
asset: dependency
|
|
486
|
+
});
|
|
487
|
+
for (const file of dependency.files) await fs.copyFile(path.join(dependencyRoot, file), path.join(extractedRoot, file), fs$1.constants.COPYFILE_EXCL);
|
|
488
|
+
}
|
|
489
|
+
options.signal?.throwIfAborted();
|
|
490
|
+
await fs.chmod(extractedCommand, 493);
|
|
491
|
+
await validateInstalledServer(extractedCommand, asset, options.signal, FRESH_VERSION_TIMEOUT_MS);
|
|
492
|
+
await fs.mkdir(path.dirname(installDir), { recursive: true });
|
|
493
|
+
options.signal?.throwIfAborted();
|
|
494
|
+
await fs.rm(installDir, {
|
|
358
495
|
recursive: true,
|
|
359
496
|
force: true
|
|
360
497
|
});
|
|
361
|
-
await fs
|
|
362
|
-
await validateInstalledServer(command);
|
|
498
|
+
await fs.rename(extractedRoot, installDir);
|
|
499
|
+
await validateInstalledServer(command, asset, options.signal);
|
|
363
500
|
return command;
|
|
364
501
|
} finally {
|
|
365
|
-
await Promise.all([fs
|
|
502
|
+
await Promise.all([fs.rm(archivePath, { force: true }), fs.rm(extractDir, {
|
|
366
503
|
recursive: true,
|
|
367
504
|
force: true
|
|
368
505
|
})]);
|
|
369
506
|
}
|
|
370
507
|
}
|
|
371
|
-
async function ensureLlamaServerInstalled() {
|
|
372
|
-
|
|
373
|
-
const
|
|
374
|
-
const
|
|
508
|
+
async function ensureLlamaServerInstalled(options = {}) {
|
|
509
|
+
options.signal?.throwIfAborted();
|
|
510
|
+
const asset = options.asset ?? selectLlamaServerAsset();
|
|
511
|
+
const key = resolveManagedLlamaServerPaths(asset).command;
|
|
512
|
+
const previous = installationPromises.get(key);
|
|
513
|
+
const pending = Promise.resolve(previous).catch(() => void 0).then(() => installLlamaServer(asset, options)).finally(() => {
|
|
514
|
+
if (installationPromises.get(key) === pending) installationPromises.delete(key);
|
|
515
|
+
});
|
|
375
516
|
installationPromises.set(key, pending);
|
|
517
|
+
return {
|
|
518
|
+
command: previous && options.signal ? await new Promise((resolve, reject) => {
|
|
519
|
+
const signal = options.signal;
|
|
520
|
+
const onAbort = () => reject(toErrorObject(signal?.reason, "Installation cancelled"));
|
|
521
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
522
|
+
pending.then(resolve, reject).finally(() => signal?.removeEventListener("abort", onAbort));
|
|
523
|
+
if (signal?.aborted) onAbort();
|
|
524
|
+
}) : await pending,
|
|
525
|
+
asset
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
//#endregion
|
|
529
|
+
//#region extensions/llama-cpp/src/llama-server-preset.ts
|
|
530
|
+
const LLAMA_CPP_EMBEDDING_UBATCH_SIZE = 2048;
|
|
531
|
+
function assertIniValue(value, label) {
|
|
532
|
+
if (/\r|\n/u.test(value)) throw new Error(`${label} cannot contain a newline`);
|
|
533
|
+
return value;
|
|
534
|
+
}
|
|
535
|
+
function normalizePresetName(name) {
|
|
536
|
+
const colon = name.lastIndexOf(":");
|
|
537
|
+
if (colon < 0) return name;
|
|
538
|
+
const tag = name.slice(colon + 1);
|
|
539
|
+
const quantization = /[-.]([a-zA-Z0-9_]+)$/u.exec(tag)?.[1] ?? tag;
|
|
540
|
+
return name.slice(0, colon + 1) + quantization.replace(/[a-z]/g, (char) => char.toUpperCase());
|
|
541
|
+
}
|
|
542
|
+
function readModelSections(contents) {
|
|
543
|
+
const headers = [...contents.matchAll(/(?<![^\r\n])\[[ \t]*([^\]]+)\][ \t]*(?:[;#][^\r\n]*)?(?:\r\n|\n|\r|(?![\s\S]))/g)];
|
|
544
|
+
return {
|
|
545
|
+
header: contents.slice(0, headers[0]?.index ?? contents.length),
|
|
546
|
+
sections: new Map(headers.map((match, index) => [match[1], contents.slice(match.index, headers[index + 1]?.index ?? contents.length)]))
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
const PRESET_KEY_ALIASES = {
|
|
550
|
+
m: "model",
|
|
551
|
+
LLAMA_ARG_MODEL: "model",
|
|
552
|
+
c: "ctx-size",
|
|
553
|
+
LLAMA_ARG_CTX_SIZE: "ctx-size",
|
|
554
|
+
n: "n-predict",
|
|
555
|
+
predict: "n-predict",
|
|
556
|
+
LLAMA_ARG_N_PREDICT: "n-predict",
|
|
557
|
+
"no-jinja": "jinja",
|
|
558
|
+
LLAMA_ARG_JINJA: "jinja",
|
|
559
|
+
ub: "ubatch-size",
|
|
560
|
+
LLAMA_ARG_UBATCH: "ubatch-size",
|
|
561
|
+
embeddings: "embedding",
|
|
562
|
+
LLAMA_ARG_EMBEDDINGS: "embedding"
|
|
563
|
+
};
|
|
564
|
+
function updateModelSection(sections, id, values, newline) {
|
|
565
|
+
assertIniValue(id, "llama.cpp model id");
|
|
566
|
+
if (id.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
|
|
567
|
+
const name = [...sections.keys()].filter((candidate) => normalizePresetName(candidate) === normalizePresetName(id)).toSorted((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right))).at(-1) ?? id;
|
|
568
|
+
const pending = new Set(Object.keys(values));
|
|
569
|
+
let contents = (sections.get(name) ?? `[${id}]${newline}`).replace(/(?<![^\r\n])([a-zA-Z_][a-zA-Z0-9_.-]*)([ \t]*=[ \t]*)([^\r\n]*?)([ \t]*(?:[;#][^\r\n]*)?)(\r\n|\n|\r|(?![\s\S]))/g, (line, key, separator, _value, comment, ending) => {
|
|
570
|
+
const canonical = PRESET_KEY_ALIASES[key] ?? key;
|
|
571
|
+
if (!Object.hasOwn(values, canonical)) return line;
|
|
572
|
+
pending.delete(canonical);
|
|
573
|
+
return `${canonical}${separator}${values[canonical]}${comment}${ending}`;
|
|
574
|
+
});
|
|
575
|
+
for (const key of pending) contents += `${/[\r\n]$/u.test(contents) ? "" : newline}${key} = ${values[key]}${newline}`;
|
|
576
|
+
sections.set(name, contents);
|
|
577
|
+
}
|
|
578
|
+
function buildLlamaServerPreset(existing, params) {
|
|
579
|
+
const newline = existing?.match(/\r\n|\n|\r/u)?.[0] ?? "\n";
|
|
580
|
+
const { header, sections } = readModelSections(existing ?? "version = 1\n\n");
|
|
581
|
+
const configuredIds = params.configuredChatModelIds ? new Set(params.configuredChatModelIds.map(normalizePresetName)) : void 0;
|
|
582
|
+
for (const id of sections.keys()) if (id !== "*" && id !== "embeddinggemma-300m-qat-q8_0" && (params.chatModel.mode === "remove" || configuredIds && !configuredIds.has(normalizePresetName(id)))) sections.delete(id);
|
|
583
|
+
if (params.chatModel.mode === "configure") updateModelSection(sections, params.chatModel.id, {
|
|
584
|
+
model: assertIniValue(params.chatModel.path, "llama.cpp model path"),
|
|
585
|
+
"ctx-size": String(params.chatModel.contextSize ?? 65536),
|
|
586
|
+
"n-predict": String(params.chatModel.maxTokens ?? 2048),
|
|
587
|
+
jinja: "true"
|
|
588
|
+
}, newline);
|
|
589
|
+
const embeddingPath = params.embeddingModelPath ?? (!sections.has("embeddinggemma-300m-qat-q8_0") ? params.defaultEmbeddingModelPath : void 0);
|
|
590
|
+
if (embeddingPath) {
|
|
591
|
+
const isDefault = params.embeddingModelPath ? params.embeddingModelIsDefault : true;
|
|
592
|
+
updateModelSection(sections, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, {
|
|
593
|
+
model: assertIniValue(embeddingPath, "llama.cpp embedding model path"),
|
|
594
|
+
...isDefault ? { "ubatch-size": String(LLAMA_CPP_EMBEDDING_UBATCH_SIZE) } : {},
|
|
595
|
+
embedding: "true"
|
|
596
|
+
}, newline);
|
|
597
|
+
}
|
|
598
|
+
const embeddingSection = sections.get(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID);
|
|
599
|
+
if (!embeddingSection) throw new Error("llama.cpp embedding model path is required for a new managed preset");
|
|
600
|
+
sections.delete(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID);
|
|
601
|
+
const orderedSections = [...[...sections].toSorted(([left], [right]) => Number(left > right) - Number(left < right)).map(([, section]) => section), embeddingSection];
|
|
602
|
+
return header + (header && !/[\r\n]$/u.test(header) ? newline : "") + orderedSections.map((section) => section.replace(/[\r\n]+$/u, "")).join(newline + newline) + newline;
|
|
603
|
+
}
|
|
604
|
+
//#endregion
|
|
605
|
+
//#region extensions/llama-cpp/src/hardware.ts
|
|
606
|
+
const GIB$1 = 1024 ** 3;
|
|
607
|
+
const MIB = 1024 ** 2;
|
|
608
|
+
async function runHardwareProbe(command, args, signal) {
|
|
376
609
|
try {
|
|
610
|
+
return await new Promise((resolve, reject) => {
|
|
611
|
+
execFile(command, args, {
|
|
612
|
+
encoding: "utf8",
|
|
613
|
+
timeout: 3e3,
|
|
614
|
+
maxBuffer: 65536,
|
|
615
|
+
signal
|
|
616
|
+
}, (error, stdout) => error ? reject(error) : resolve(stdout));
|
|
617
|
+
});
|
|
618
|
+
} catch {
|
|
619
|
+
signal?.throwIfAborted();
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
async function readAvailableMemory(platform, signal) {
|
|
624
|
+
if (platform === "linux") {
|
|
625
|
+
const meminfo = await fs.readFile("/proc/meminfo", "utf8").catch(() => "");
|
|
626
|
+
const available = /^MemAvailable:\s+(\d+)\s+kB$/mu.exec(meminfo)?.[1];
|
|
627
|
+
if (available) return Number(available) * 1024;
|
|
628
|
+
}
|
|
629
|
+
if (platform === "darwin") {
|
|
630
|
+
const vmstat = await runHardwareProbe("/usr/bin/vm_stat", [], signal);
|
|
631
|
+
const pageSize = /page size of (\d+) bytes/u.exec(vmstat ?? "")?.[1];
|
|
632
|
+
const free = /^Pages free:\s+(\d+)\./mu.exec(vmstat ?? "")?.[1];
|
|
633
|
+
const inactive = /^Pages inactive:\s+(\d+)\./mu.exec(vmstat ?? "")?.[1];
|
|
634
|
+
if (pageSize && free && inactive) return (Number(free) + Number(inactive)) * Number(pageSize);
|
|
635
|
+
}
|
|
636
|
+
return os.freemem();
|
|
637
|
+
}
|
|
638
|
+
async function readAvailableDisk(cacheDir, platform, signal) {
|
|
639
|
+
let directory = path.resolve(cacheDir);
|
|
640
|
+
while (true) try {
|
|
641
|
+
const [capacity, stat] = await Promise.all([fs.statfs(directory), fs.stat(directory)]);
|
|
642
|
+
let capacityGroup = `device:${stat.dev}`;
|
|
643
|
+
if (platform === "linux" && ![
|
|
644
|
+
61267,
|
|
645
|
+
1481003842,
|
|
646
|
+
4076150800
|
|
647
|
+
].includes(capacity.type)) capacityGroup = void 0;
|
|
648
|
+
if (platform === "darwin") {
|
|
649
|
+
const disk = /^\/dev\/(disk\d+(?:s\d+)*)\s/mu.exec(await runHardwareProbe("/bin/df", ["-P", directory], signal) ?? "")?.[1];
|
|
650
|
+
const info = disk ? await runHardwareProbe("/usr/sbin/diskutil", [
|
|
651
|
+
"info",
|
|
652
|
+
"-plist",
|
|
653
|
+
disk
|
|
654
|
+
], signal) : void 0;
|
|
655
|
+
const container = /<key>APFSContainerReference<\/key>\s*<string>(disk\d+)<\/string>/u.exec(info ?? "")?.[1];
|
|
656
|
+
const filesystem = /<key>FilesystemType<\/key>\s*<string>([^<]+)<\/string>/u.exec(info ?? "")?.[1];
|
|
657
|
+
capacityGroup = container ? `apfs:${container}` : filesystem && filesystem !== "apfs" ? capacityGroup : void 0;
|
|
658
|
+
}
|
|
377
659
|
return {
|
|
378
|
-
|
|
379
|
-
|
|
660
|
+
availableBytes: capacity.bavail * capacity.bsize,
|
|
661
|
+
capacityGroup
|
|
662
|
+
};
|
|
663
|
+
} catch (error) {
|
|
664
|
+
signal?.throwIfAborted();
|
|
665
|
+
const code = error instanceof Error && "code" in error ? error.code : void 0;
|
|
666
|
+
const parent = path.dirname(directory);
|
|
667
|
+
if (code !== "ENOENT" && code !== "ENOTDIR" || parent === directory) return;
|
|
668
|
+
directory = parent;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
async function readAccelerator(platform, arch, signal) {
|
|
672
|
+
if (platform === "darwin" && arch === "arm64") return { kind: "metal" };
|
|
673
|
+
if (platform !== "linux" && platform !== "win32") return {
|
|
674
|
+
kind: "cpu",
|
|
675
|
+
reason: "No managed GPU backend is available for this host."
|
|
676
|
+
};
|
|
677
|
+
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) => {
|
|
678
|
+
const fields = line.split(",").map((field) => field.trim());
|
|
679
|
+
const [total, available, driverVersion, compute] = fields.slice(-4);
|
|
680
|
+
const name = fields.slice(0, -4).join(", ");
|
|
681
|
+
const totalMemoryBytes = Number(total) * MIB;
|
|
682
|
+
const availableMemoryBytes = Number(available) * MIB;
|
|
683
|
+
const computeCapability = Number(compute);
|
|
684
|
+
if (!name || !driverVersion || !/^\d+(?:\.\d+)+$/u.test(driverVersion) || !Number.isFinite(totalMemoryBytes) || !Number.isFinite(availableMemoryBytes) || totalMemoryBytes <= 0 || availableMemoryBytes < 0 || availableMemoryBytes > totalMemoryBytes) return [];
|
|
685
|
+
return [{
|
|
686
|
+
name,
|
|
687
|
+
totalMemoryBytes,
|
|
688
|
+
availableMemoryBytes,
|
|
689
|
+
driverVersion,
|
|
690
|
+
...Number.isFinite(computeCapability) && computeCapability > 0 ? { computeCapability } : {}
|
|
691
|
+
}];
|
|
692
|
+
});
|
|
693
|
+
return devices.length > 0 ? {
|
|
694
|
+
kind: "cuda",
|
|
695
|
+
devices
|
|
696
|
+
} : {
|
|
697
|
+
kind: "cpu",
|
|
698
|
+
reason: "nvidia-smi did not report a usable NVIDIA GPU."
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
/** Read the Gateway host once during setup; never probe on inference requests. */
|
|
702
|
+
async function detectLlamaCppHardware(params) {
|
|
703
|
+
params.signal?.throwIfAborted();
|
|
704
|
+
const platform = os.platform();
|
|
705
|
+
const arch = os.arch();
|
|
706
|
+
const hostMemoryBytes = os.totalmem();
|
|
707
|
+
const constrainedMemory = process.constrainedMemory();
|
|
708
|
+
const constrained = constrainedMemory > 0 && constrainedMemory < hostMemoryBytes;
|
|
709
|
+
const totalMemoryBytes = constrained ? constrainedMemory : hostMemoryBytes;
|
|
710
|
+
const [availableMemory, modelDisk, runtimeDisk, accelerator] = await Promise.all([
|
|
711
|
+
readAvailableMemory(platform, params.signal),
|
|
712
|
+
readAvailableDisk(params.cacheDir, platform, params.signal),
|
|
713
|
+
readAvailableDisk(resolveLlamaCppDataDir(), platform, params.signal),
|
|
714
|
+
readAccelerator(platform, arch, params.signal)
|
|
715
|
+
]);
|
|
716
|
+
params.signal?.throwIfAborted();
|
|
717
|
+
return {
|
|
718
|
+
platform,
|
|
719
|
+
arch,
|
|
720
|
+
totalMemoryBytes,
|
|
721
|
+
availableMemoryBytes: Math.min(totalMemoryBytes, availableMemory, constrained ? process.availableMemory() : totalMemoryBytes),
|
|
722
|
+
availableDiskBytes: modelDisk?.availableBytes,
|
|
723
|
+
availableRuntimeDiskBytes: runtimeDisk?.availableBytes,
|
|
724
|
+
sharedDisk: !modelDisk?.capacityGroup || !runtimeDisk?.capacityGroup || modelDisk.capacityGroup === runtimeDisk.capacityGroup,
|
|
725
|
+
accelerator
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
function formatLlamaCppMemory(bytes) {
|
|
729
|
+
return `${(bytes / GIB$1).toFixed(1).replace(/\.0$/u, "")} GiB`;
|
|
730
|
+
}
|
|
731
|
+
//#endregion
|
|
732
|
+
//#region extensions/llama-cpp/src/model-catalog.ts
|
|
733
|
+
const GIB = 1024 ** 3;
|
|
734
|
+
function modelRecipe(params) {
|
|
735
|
+
const source = params.source ?? `hf:${params.repository}/${params.file}#${params.revision}`;
|
|
736
|
+
return {
|
|
737
|
+
model: {
|
|
738
|
+
id: params.id,
|
|
739
|
+
name: params.name,
|
|
740
|
+
api: "openai-completions",
|
|
741
|
+
reasoning: params.reasoning ?? false,
|
|
742
|
+
input: ["text"],
|
|
743
|
+
cost: {
|
|
744
|
+
input: 0,
|
|
745
|
+
output: 0,
|
|
746
|
+
cacheRead: 0,
|
|
747
|
+
cacheWrite: 0
|
|
748
|
+
},
|
|
749
|
+
contextWindow: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
|
|
750
|
+
contextTokens: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
|
|
751
|
+
maxTokens: params.maxTokens ?? 2048,
|
|
752
|
+
params: {
|
|
753
|
+
modelPath: source,
|
|
754
|
+
contextSize: DEFAULT_LLAMA_CPP_CONTEXT_SIZE
|
|
755
|
+
},
|
|
756
|
+
compat: {
|
|
757
|
+
supportsTools: true,
|
|
758
|
+
supportsUsageInStreaming: true,
|
|
759
|
+
toolSchemaProfile: "llamacpp"
|
|
760
|
+
}
|
|
761
|
+
},
|
|
762
|
+
sizeBytes: params.sizeBytes,
|
|
763
|
+
memoryBytes: params.memoryGiB * GIB,
|
|
764
|
+
minimumSystemMemoryBytes: params.minimumSystemGiB * GIB,
|
|
765
|
+
requiresAcceleration: params.requiresAcceleration ?? false,
|
|
766
|
+
artifact: {
|
|
767
|
+
fileName: params.cacheFile ?? `hf_${params.repository.replaceAll("/", "_")}_${params.revision}_${params.file}`,
|
|
768
|
+
url: `https://huggingface.co/${params.repository}/resolve/${params.revision}/${params.file}?download=true`,
|
|
769
|
+
expectedSize: params.sizeBytes,
|
|
770
|
+
expectedSha256: params.sha256
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
const LLAMA_CPP_MODEL_RECIPES = [
|
|
775
|
+
modelRecipe({
|
|
776
|
+
id: "qwen3.8-27b-ud-q4_k_m",
|
|
777
|
+
name: "Qwen3.8 27B (UD-Q4_K_M)",
|
|
778
|
+
repository: "unsloth/Qwen3.8-27B-GGUF",
|
|
779
|
+
file: "Qwen3.8-27B-UD-Q4_K_M.gguf",
|
|
780
|
+
revision: "4ca720788d1e01f1bff70c033e0d0028fd02e502",
|
|
781
|
+
sha256: "322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482",
|
|
782
|
+
sizeBytes: 16464440224,
|
|
783
|
+
memoryGiB: 22,
|
|
784
|
+
minimumSystemGiB: 32,
|
|
785
|
+
requiresAcceleration: true,
|
|
786
|
+
reasoning: true,
|
|
787
|
+
maxTokens: 16384
|
|
788
|
+
}),
|
|
789
|
+
modelRecipe({
|
|
790
|
+
id: "muse-glimmer-30b-q4_k_m",
|
|
791
|
+
name: "Muse Glimmer 30B (Q4_K_M)",
|
|
792
|
+
repository: "meta-models/Muse-Glimmer-30B-GGUF",
|
|
793
|
+
file: "Muse-Glimmer-30B-KQuant-17GB-Q4_K_M.gguf",
|
|
794
|
+
revision: "70bf1b61ac09f91b24d39038091b41c582bc5d7a",
|
|
795
|
+
sha256: "4cc57c0f51040a226e5a72cc47b7613f7772950e460a665f7083de89f183f60e",
|
|
796
|
+
sizeBytes: 16756683904,
|
|
797
|
+
memoryGiB: 20,
|
|
798
|
+
minimumSystemGiB: 32,
|
|
799
|
+
requiresAcceleration: true,
|
|
800
|
+
reasoning: true,
|
|
801
|
+
maxTokens: 16384
|
|
802
|
+
}),
|
|
803
|
+
modelRecipe({
|
|
804
|
+
id: "gemma-4-26b-a4b-it-ud-q4_k_m",
|
|
805
|
+
name: "Gemma 4 26B A4B (UD-Q4_K_M)",
|
|
806
|
+
repository: "unsloth/gemma-4-26B-A4B-it-GGUF",
|
|
807
|
+
file: "gemma-4-26B-A4B-it-UD-Q4_K_M.gguf",
|
|
808
|
+
revision: "c099eb48e663fd284577b04978a94ffccb261841",
|
|
809
|
+
sha256: "f2c28b3dc4776931ac6f879e11f203dec637ea0f14267a86ec8f6165f63f293f",
|
|
810
|
+
sizeBytes: 16947541728,
|
|
811
|
+
memoryGiB: 22,
|
|
812
|
+
minimumSystemGiB: 32,
|
|
813
|
+
requiresAcceleration: true
|
|
814
|
+
}),
|
|
815
|
+
modelRecipe({
|
|
816
|
+
id: "gemma-4-12b-it-q4_k_m",
|
|
817
|
+
name: "Gemma 4 12B (Q4_K_M)",
|
|
818
|
+
repository: "unsloth/gemma-4-12b-it-GGUF",
|
|
819
|
+
file: "gemma-4-12b-it-Q4_K_M.gguf",
|
|
820
|
+
revision: "fc034cfff751157913579611efad8462ac1be606",
|
|
821
|
+
sha256: "0a270ec9fe6b34f4a0d33992b6135117b484ebc4766ab76b51d4ae8c457e4c42",
|
|
822
|
+
sizeBytes: 7121861440,
|
|
823
|
+
memoryGiB: 12,
|
|
824
|
+
minimumSystemGiB: 24,
|
|
825
|
+
requiresAcceleration: true,
|
|
826
|
+
reasoning: true,
|
|
827
|
+
maxTokens: 16384
|
|
828
|
+
}),
|
|
829
|
+
modelRecipe({
|
|
830
|
+
id: "qwen3.5-9b-q4_k_m",
|
|
831
|
+
name: "Qwen3.5 9B (Q4_K_M)",
|
|
832
|
+
repository: "unsloth/Qwen3.5-9B-GGUF",
|
|
833
|
+
file: "Qwen3.5-9B-Q4_K_M.gguf",
|
|
834
|
+
revision: "3885219b6810b007914f3a7950a8d1b469d598a5",
|
|
835
|
+
sha256: "03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8",
|
|
836
|
+
sizeBytes: 5680522464,
|
|
837
|
+
memoryGiB: 10,
|
|
838
|
+
minimumSystemGiB: 16,
|
|
839
|
+
reasoning: true,
|
|
840
|
+
maxTokens: 16384
|
|
841
|
+
}),
|
|
842
|
+
modelRecipe({
|
|
843
|
+
id: DEFAULT_LLAMA_CPP_MODEL_ID,
|
|
844
|
+
name: "Gemma 4 E4B (Q4_K_M)",
|
|
845
|
+
repository: "unsloth/gemma-4-E4B-it-GGUF",
|
|
846
|
+
file: "gemma-4-E4B-it-Q4_K_M.gguf",
|
|
847
|
+
revision: DEFAULT_LLAMA_CPP_MODEL_REVISION,
|
|
848
|
+
sha256: DEFAULT_LLAMA_CPP_MODEL_SHA256,
|
|
849
|
+
sizeBytes: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
|
|
850
|
+
memoryGiB: 10,
|
|
851
|
+
minimumSystemGiB: 16,
|
|
852
|
+
source: DEFAULT_LLAMA_CPP_MODEL_URI,
|
|
853
|
+
cacheFile: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE
|
|
854
|
+
}),
|
|
855
|
+
modelRecipe({
|
|
856
|
+
id: "qwen3.5-4b-q4_k_m",
|
|
857
|
+
name: "Qwen3.5 4B (Q4_K_M)",
|
|
858
|
+
repository: "unsloth/Qwen3.5-4B-GGUF",
|
|
859
|
+
file: "Qwen3.5-4B-Q4_K_M.gguf",
|
|
860
|
+
revision: "e87f176479d0855a907a41277aca2f8ee7a09523",
|
|
861
|
+
sha256: "00fe7986ff5f6b463e62455821146049db6f9313603938a70800d1fb69ef11a4",
|
|
862
|
+
sizeBytes: 2740937888,
|
|
863
|
+
memoryGiB: 6,
|
|
864
|
+
minimumSystemGiB: 8,
|
|
865
|
+
reasoning: true,
|
|
866
|
+
maxTokens: 16384
|
|
867
|
+
}),
|
|
868
|
+
modelRecipe({
|
|
869
|
+
id: "gemma-4-e2b-it-q4_k_m",
|
|
870
|
+
name: "Gemma 4 E2B (Q4_K_M)",
|
|
871
|
+
repository: "unsloth/gemma-4-E2B-it-GGUF",
|
|
872
|
+
file: "gemma-4-E2B-it-Q4_K_M.gguf",
|
|
873
|
+
revision: "0314792d7f1f7e229411f620751375812bb9faf2",
|
|
874
|
+
sha256: "740185b21d22ceb83a11c3aa62ad5842ef32c70f6096d756bbee85a1e4ec34b8",
|
|
875
|
+
sizeBytes: 3106738272,
|
|
876
|
+
memoryGiB: 6,
|
|
877
|
+
minimumSystemGiB: 8
|
|
878
|
+
})
|
|
879
|
+
];
|
|
880
|
+
function resolveLlamaCppCatalogArtifact(source) {
|
|
881
|
+
return LLAMA_CPP_MODEL_RECIPES.find((recipe) => recipe.model.params?.modelPath === source)?.artifact;
|
|
882
|
+
}
|
|
883
|
+
function resolveLlamaCppModelCandidates(hardware, backend) {
|
|
884
|
+
const systemBudget = Math.min(hardware.availableMemoryBytes, hardware.totalMemoryBytes - Math.max(2 * GIB, hardware.totalMemoryBytes * .25));
|
|
885
|
+
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;
|
|
886
|
+
const memoryBudgetBytes = backend === "cuda" ? Math.min(systemBudget, gpuBudget) : systemBudget;
|
|
887
|
+
return {
|
|
888
|
+
recipes: LLAMA_CPP_MODEL_RECIPES.filter((recipe) => (!recipe.requiresAcceleration || backend !== "cpu") && hardware.totalMemoryBytes >= recipe.minimumSystemMemoryBytes && memoryBudgetBytes >= recipe.memoryBytes),
|
|
889
|
+
memoryBudgetBytes
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
function recommendLlamaCppModel(hardware, backend, cached = {}) {
|
|
893
|
+
if (hardware.availableDiskBytes === void 0 || hardware.availableRuntimeDiskBytes === void 0) return {
|
|
894
|
+
kind: "unavailable",
|
|
895
|
+
reason: "Cannot measure free space in the model cache or runtime directory. Check their permissions and retry setup."
|
|
896
|
+
};
|
|
897
|
+
const { recipes: candidates, memoryBudgetBytes } = resolveLlamaCppModelCandidates(hardware, backend);
|
|
898
|
+
const runtimeDiskBytes = cached.runtime ? 0 : (backend === "cuda" ? 3 : 2) * GIB;
|
|
899
|
+
if (!hardware.sharedDisk && hardware.availableRuntimeDiskBytes < runtimeDiskBytes) return {
|
|
900
|
+
kind: "unavailable",
|
|
901
|
+
reason: "There is not enough free disk space in the runtime directory. Free space on that volume and retry setup."
|
|
902
|
+
};
|
|
903
|
+
const modelDiskBudget = hardware.sharedDisk ? Math.min(hardware.availableDiskBytes, hardware.availableRuntimeDiskBytes) - runtimeDiskBytes : hardware.availableDiskBytes;
|
|
904
|
+
for (const recipe of candidates) {
|
|
905
|
+
const modelDiskBytes = (cached.modelIds?.has(recipe.model.id) ? 0 : recipe.sizeBytes) + (cached.embedding ? 0 : DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES);
|
|
906
|
+
if (modelDiskBudget < modelDiskBytes) continue;
|
|
907
|
+
const placement = backend === "metal" ? "Metal unified memory" : backend === "cuda" ? "NVIDIA GPU memory" : "CPU memory";
|
|
908
|
+
return {
|
|
909
|
+
kind: "recommended",
|
|
910
|
+
recipe,
|
|
911
|
+
memoryBudgetBytes,
|
|
912
|
+
requiredDiskBytes: modelDiskBytes + runtimeDiskBytes,
|
|
913
|
+
reason: `${recipe.model.name} fits the ${formatLlamaCppMemory(memoryBudgetBytes)} ${placement} budget with a 64K context. Runtime verification checks the actual model before activation.`
|
|
380
914
|
};
|
|
381
|
-
} finally {
|
|
382
|
-
if (installationPromises.get(key) === pending) installationPromises.delete(key);
|
|
383
915
|
}
|
|
916
|
+
return {
|
|
917
|
+
kind: "unavailable",
|
|
918
|
+
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.`
|
|
919
|
+
};
|
|
384
920
|
}
|
|
385
921
|
//#endregion
|
|
386
922
|
//#region extensions/llama-cpp/src/managed-server.ts
|
|
387
923
|
const modelPromises = /* @__PURE__ */ new Map();
|
|
388
|
-
const
|
|
389
|
-
const
|
|
390
|
-
|
|
924
|
+
const resolvedModelArtifacts = /* @__PURE__ */ new Map();
|
|
925
|
+
const presetState = {
|
|
926
|
+
appliedRevisions: /* @__PURE__ */ new Map(),
|
|
927
|
+
desiredRevisions: /* @__PURE__ */ new Map(),
|
|
928
|
+
transition: Promise.resolve()
|
|
929
|
+
};
|
|
930
|
+
const LLAMA_CPP_PRESET_RELOAD_TIMEOUT_MS = 15e3;
|
|
391
931
|
function parseHuggingFaceSource(source) {
|
|
392
932
|
const [pathPart, revisionPart] = source.replace(/^(?:hf|huggingface):(?:\/\/)?/iu, "").split("#", 2);
|
|
393
933
|
const [user, repositoryWithTag, ...fileParts] = (pathPart ?? "").split("/");
|
|
@@ -418,7 +958,7 @@ async function resolveHuggingFaceArtifact(source, signal) {
|
|
|
418
958
|
});
|
|
419
959
|
try {
|
|
420
960
|
if (!response.ok) throw new Error(`Cannot resolve ${source}: HTTP ${response.status}`);
|
|
421
|
-
const ggufFile = asOptionalRecord(asOptionalRecord(await response.
|
|
961
|
+
const ggufFile = asOptionalRecord(asOptionalRecord(await readProviderJsonResponse(response, "llama.cpp Hugging Face manifest"))?.ggufFile);
|
|
422
962
|
file = typeof ggufFile?.rfilename === "string" ? ggufFile.rfilename : void 0;
|
|
423
963
|
expectedSize = typeof ggufFile?.size === "number" ? ggufFile.size : void 0;
|
|
424
964
|
if (!file) throw new Error(`Hugging Face did not return a GGUF file for ${source}`);
|
|
@@ -428,22 +968,33 @@ async function resolveHuggingFaceArtifact(source, signal) {
|
|
|
428
968
|
}
|
|
429
969
|
const encodedFile = file.split("/").map(encodeURIComponent).join("/");
|
|
430
970
|
const url = `https://huggingface.co/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/resolve/${encodeURIComponent(parsed.revision)}/${encodedFile}?download=true`;
|
|
431
|
-
const
|
|
432
|
-
const { response:
|
|
433
|
-
url:
|
|
971
|
+
const fileInfoUrl = `https://huggingface.co/api/models/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/paths-info/${encodeURIComponent(parsed.revision)}`;
|
|
972
|
+
const { response: fileInfoResponse, release: releaseFileInfo } = await fetchWithSsrFGuard({
|
|
973
|
+
url: fileInfoUrl,
|
|
974
|
+
init: {
|
|
975
|
+
method: "POST",
|
|
976
|
+
headers: {
|
|
977
|
+
"content-type": "application/json",
|
|
978
|
+
"user-agent": "llama-cpp"
|
|
979
|
+
},
|
|
980
|
+
body: JSON.stringify({
|
|
981
|
+
paths: [file],
|
|
982
|
+
expand: false
|
|
983
|
+
})
|
|
984
|
+
},
|
|
434
985
|
signal,
|
|
435
986
|
requireHttps: true,
|
|
436
|
-
policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(
|
|
987
|
+
policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(fileInfoUrl),
|
|
437
988
|
auditContext: "llama-cpp-model-resolve"
|
|
438
989
|
});
|
|
439
|
-
let
|
|
990
|
+
let fileInfo;
|
|
440
991
|
try {
|
|
441
|
-
if (!
|
|
442
|
-
|
|
992
|
+
if (!fileInfoResponse.ok) throw new Error(`Cannot read Hugging Face integrity metadata for ${source}: HTTP ${fileInfoResponse.status}`);
|
|
993
|
+
fileInfo = await readProviderJsonResponse(fileInfoResponse, "llama.cpp Hugging Face file metadata");
|
|
443
994
|
} finally {
|
|
444
|
-
await
|
|
995
|
+
await releaseFileInfo();
|
|
445
996
|
}
|
|
446
|
-
const fileRow = Array.isArray(
|
|
997
|
+
const fileRow = Array.isArray(fileInfo) ? fileInfo.map((entry) => asOptionalRecord(entry)).find((entry) => entry?.path === file) : void 0;
|
|
447
998
|
const lfs = asOptionalRecord(fileRow?.lfs);
|
|
448
999
|
const expectedSha256 = typeof lfs?.oid === "string" && /^[a-f\d]{64}$/iu.test(lfs.oid) ? lfs.oid.toLowerCase() : void 0;
|
|
449
1000
|
expectedSize = expectedSize ?? (typeof fileRow?.size === "number" ? fileRow.size : void 0);
|
|
@@ -461,12 +1012,8 @@ async function resolveHuggingFaceArtifact(source, signal) {
|
|
|
461
1012
|
};
|
|
462
1013
|
}
|
|
463
1014
|
function defaultArtifact(source) {
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
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`,
|
|
467
|
-
expectedSize: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
|
|
468
|
-
expectedSha256: DEFAULT_LLAMA_CPP_MODEL_SHA256
|
|
469
|
-
};
|
|
1015
|
+
const recipe = resolveLlamaCppCatalogArtifact(source);
|
|
1016
|
+
if (recipe) return recipe;
|
|
470
1017
|
if (source === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") return {
|
|
471
1018
|
fileName: DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE,
|
|
472
1019
|
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`,
|
|
@@ -475,7 +1022,7 @@ function defaultArtifact(source) {
|
|
|
475
1022
|
};
|
|
476
1023
|
}
|
|
477
1024
|
async function assertGguf(filePath) {
|
|
478
|
-
const handle = await fs
|
|
1025
|
+
const handle = await fs.open(filePath, "r").catch((error) => {
|
|
479
1026
|
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 });
|
|
480
1027
|
throw error;
|
|
481
1028
|
});
|
|
@@ -509,18 +1056,16 @@ async function ensureLlamaCppModel(params) {
|
|
|
509
1056
|
await assertGguf(localPath);
|
|
510
1057
|
return localPath;
|
|
511
1058
|
}
|
|
512
|
-
const
|
|
1059
|
+
const artifactCacheKey = `${path.resolve(params.cacheDir)}\0${localSource}`;
|
|
1060
|
+
const artifact = resolvedModelArtifacts.get(artifactCacheKey) ?? await resolveModelArtifact(localSource, params.signal);
|
|
1061
|
+
resolvedModelArtifacts.set(artifactCacheKey, artifact);
|
|
513
1062
|
const destination = path.join(params.cacheDir, artifact.fileName);
|
|
514
|
-
const
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
if (
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
} else {
|
|
521
|
-
await assertGguf(destination);
|
|
522
|
-
return destination;
|
|
523
|
-
}
|
|
1063
|
+
const load = modelPromises.get(destination) ?? (async () => {
|
|
1064
|
+
const exists = await fs.stat(destination).then((stat) => stat.isFile()).catch(() => false);
|
|
1065
|
+
if (exists && artifact.expectedSha256 && await sha256File(destination, params.signal) === artifact.expectedSha256) return destination;
|
|
1066
|
+
if (exists && !artifact.expectedSha256) {
|
|
1067
|
+
await assertGguf(destination);
|
|
1068
|
+
return destination;
|
|
524
1069
|
}
|
|
525
1070
|
if (!params.download) throw new Error(`Model is not cached at ${destination}`);
|
|
526
1071
|
await downloadVerifiedFile({
|
|
@@ -542,88 +1087,52 @@ async function ensureLlamaCppModel(params) {
|
|
|
542
1087
|
if (modelPromises.get(destination) === load) modelPromises.delete(destination);
|
|
543
1088
|
}
|
|
544
1089
|
}
|
|
545
|
-
function assertIniValue(value, label) {
|
|
546
|
-
if (/\r|\n/u.test(value)) throw new Error(`${label} cannot contain a newline`);
|
|
547
|
-
return value;
|
|
548
|
-
}
|
|
549
|
-
function renderChatModelSection(params) {
|
|
550
|
-
const id = assertIniValue(params.id, "llama.cpp model id");
|
|
551
|
-
if (id.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
|
|
552
|
-
return [
|
|
553
|
-
`[${id}]`,
|
|
554
|
-
`model = ${assertIniValue(params.modelPath, "llama.cpp model path")}`,
|
|
555
|
-
`ctx-size = ${params.contextSize ?? 65536}`,
|
|
556
|
-
`n-predict = ${params.maxTokens ?? 2048}`,
|
|
557
|
-
"jinja = true"
|
|
558
|
-
].join("\n");
|
|
559
|
-
}
|
|
560
|
-
function renderEmbeddingModelSection(params) {
|
|
561
|
-
return [
|
|
562
|
-
`[${DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID}]`,
|
|
563
|
-
`model = ${assertIniValue(params.modelPath, "llama.cpp embedding model path")}`,
|
|
564
|
-
...params.isDefault ? [`ubatch-size = ${LLAMA_CPP_EMBEDDING_UBATCH_SIZE}`] : [],
|
|
565
|
-
"embedding = true"
|
|
566
|
-
].join("\n");
|
|
567
|
-
}
|
|
568
|
-
function readModelSection(contents, id) {
|
|
569
|
-
if (!contents) return;
|
|
570
|
-
const lines = contents.split(/\r?\n/u);
|
|
571
|
-
const start = lines.indexOf(`[${id}]`);
|
|
572
|
-
if (start < 0) return;
|
|
573
|
-
let end = start + 1;
|
|
574
|
-
while (end < lines.length && !/^\[[^\]]+\]$/u.test(lines[end] ?? "")) end += 1;
|
|
575
|
-
return lines.slice(start, end).join("\n").trimEnd();
|
|
576
|
-
}
|
|
577
|
-
function readChatModelSection(contents) {
|
|
578
|
-
const id = contents?.split(/\r?\n/u).map((line) => /^\[([^\]]+)\]$/u.exec(line)?.[1]).find((candidate) => candidate && candidate !== "embeddinggemma-300m-qat-q8_0");
|
|
579
|
-
return id ? readModelSection(contents, id) : void 0;
|
|
580
|
-
}
|
|
581
|
-
function renderLlamaServerPreset(params) {
|
|
582
|
-
return [
|
|
583
|
-
"version = 1",
|
|
584
|
-
"",
|
|
585
|
-
...params.chatSection ? [params.chatSection, ""] : [],
|
|
586
|
-
params.embeddingSection,
|
|
587
|
-
""
|
|
588
|
-
].join("\n");
|
|
589
|
-
}
|
|
590
1090
|
async function writePreset(presetPath, contents) {
|
|
591
|
-
await fs
|
|
1091
|
+
await fs.mkdir(path.dirname(presetPath), { recursive: true });
|
|
592
1092
|
const temporary = `${presetPath}.tmp-${randomUUID()}`;
|
|
593
|
-
|
|
594
|
-
|
|
1093
|
+
try {
|
|
1094
|
+
await fs.writeFile(temporary, contents, { mode: 384 });
|
|
1095
|
+
await fs.rename(temporary, presetPath);
|
|
1096
|
+
} finally {
|
|
1097
|
+
await fs.rm(temporary, { force: true });
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
async function runPresetTransition(run) {
|
|
1101
|
+
const pending = presetState.transition.catch(() => void 0).then(run);
|
|
1102
|
+
presetState.transition = pending;
|
|
1103
|
+
await pending;
|
|
595
1104
|
}
|
|
596
1105
|
async function updatePreset(presetPath, params) {
|
|
597
|
-
|
|
598
|
-
const existing = await fs
|
|
1106
|
+
await runPresetTransition(async () => {
|
|
1107
|
+
const existing = await fs.readFile(presetPath, "utf8").catch((error) => {
|
|
599
1108
|
if (asOptionalRecord(error)?.code === "ENOENT") return;
|
|
600
1109
|
throw error;
|
|
601
1110
|
});
|
|
602
|
-
const
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
})
|
|
1111
|
+
const next = buildLlamaServerPreset(existing, params);
|
|
1112
|
+
if (next !== existing) await writePreset(presetPath, next);
|
|
1113
|
+
if (params.reconcileOrigin) presetState.desiredRevisions.set(params.reconcileOrigin, `${presetPath}\0${next}`);
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
async function reconcileManagedLlamaServer(params) {
|
|
1117
|
+
await runPresetTransition(async () => {
|
|
1118
|
+
const origin = new URL(params.baseUrl).origin;
|
|
1119
|
+
const revision = presetState.desiredRevisions.get(origin);
|
|
1120
|
+
if (!revision || presetState.appliedRevisions.get(origin) === revision) return;
|
|
1121
|
+
const { response, release } = await fetchConfiguredLocalOriginWithSsrFGuard({
|
|
1122
|
+
url: `${origin}/models?reload=1`,
|
|
1123
|
+
configuredLocalOriginBaseUrl: origin,
|
|
1124
|
+
policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(origin),
|
|
1125
|
+
signal: params.signal,
|
|
1126
|
+
timeoutMs: LLAMA_CPP_PRESET_RELOAD_TIMEOUT_MS,
|
|
1127
|
+
auditContext: "llama-server-preset-reload"
|
|
1128
|
+
});
|
|
1129
|
+
try {
|
|
1130
|
+
if (!response.ok) throw new Error(`llama.cpp preset reload failed: HTTP ${response.status}`);
|
|
1131
|
+
presetState.appliedRevisions.set(origin, revision);
|
|
1132
|
+
} finally {
|
|
1133
|
+
await release();
|
|
1134
|
+
}
|
|
620
1135
|
});
|
|
621
|
-
presetWritePromises.set(presetPath, pending);
|
|
622
|
-
try {
|
|
623
|
-
await pending;
|
|
624
|
-
} finally {
|
|
625
|
-
if (presetWritePromises.get(presetPath) === pending) presetWritePromises.delete(presetPath);
|
|
626
|
-
}
|
|
627
1136
|
}
|
|
628
1137
|
async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT) {
|
|
629
1138
|
const tryPort = async (port) => await new Promise((resolve) => {
|
|
@@ -639,21 +1148,45 @@ async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT)
|
|
|
639
1148
|
return await tryPort(preferred) ?? await tryPort(0) ?? Promise.reject(/* @__PURE__ */ new Error("No loopback port is available for llama-server"));
|
|
640
1149
|
}
|
|
641
1150
|
async function prepareManagedLlamaServer(params) {
|
|
642
|
-
|
|
643
|
-
const
|
|
1151
|
+
params.signal?.throwIfAborted();
|
|
1152
|
+
const command = params.localService?.command ?? (await ensureLlamaServerInstalled({
|
|
1153
|
+
asset: params.asset,
|
|
1154
|
+
signal: params.signal,
|
|
1155
|
+
onProgress: params.onProgress
|
|
1156
|
+
})).command;
|
|
1157
|
+
const port = params.port ?? await findAvailableLlamaServerPort(params.isolated ? 0 : void 0);
|
|
1158
|
+
const rootUrl = `http://127.0.0.1:${port}`;
|
|
1159
|
+
const reconcileOrigin = params.reconcileBaseUrl ? new URL(params.reconcileBaseUrl).origin : rootUrl;
|
|
1160
|
+
const endpoint = {
|
|
1161
|
+
command,
|
|
1162
|
+
baseUrl: `${rootUrl}/v1`,
|
|
1163
|
+
healthUrl: params.localService?.healthUrl ?? `${rootUrl}/health`
|
|
1164
|
+
};
|
|
1165
|
+
const configuredPreset = params.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset") ?? params.localService?.env?.LLAMA_ARG_MODELS_PRESET;
|
|
1166
|
+
if (params.localService && !configuredPreset && !params.isolated) {
|
|
1167
|
+
await runPresetTransition(async () => {
|
|
1168
|
+
presetState.desiredRevisions.delete(reconcileOrigin);
|
|
1169
|
+
presetState.appliedRevisions.delete(reconcileOrigin);
|
|
1170
|
+
});
|
|
1171
|
+
return {
|
|
1172
|
+
...endpoint,
|
|
1173
|
+
args: params.localService.args ?? []
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
const defaultPreset = configuredPreset ? path.resolve(params.localService?.cwd ?? process.cwd(), configuredPreset) : resolveManagedLlamaServerPaths(params.asset).presetPath;
|
|
1177
|
+
const presetPath = params.isolated ? path.join(path.dirname(defaultPreset), `models-${randomUUID()}.ini`) : defaultPreset;
|
|
644
1178
|
await updatePreset(presetPath, {
|
|
645
1179
|
chatModel: params.chatModel,
|
|
1180
|
+
configuredChatModelIds: params.configuredChatModelIds,
|
|
646
1181
|
embeddingModelIsDefault: params.embeddingModelIsDefault,
|
|
647
1182
|
embeddingModelPath: params.embeddingModelPath,
|
|
648
|
-
defaultEmbeddingModelPath: params.defaultEmbeddingModelPath
|
|
1183
|
+
defaultEmbeddingModelPath: params.defaultEmbeddingModelPath,
|
|
1184
|
+
reconcileOrigin: params.isolated ? void 0 : reconcileOrigin
|
|
649
1185
|
});
|
|
650
|
-
|
|
651
|
-
const rootUrl = `http://127.0.0.1:${port}`;
|
|
1186
|
+
params.signal?.throwIfAborted();
|
|
652
1187
|
return {
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
healthUrl: `${rootUrl}/health`,
|
|
656
|
-
args: [
|
|
1188
|
+
...endpoint,
|
|
1189
|
+
args: params.localService && !params.isolated ? params.localService.args ?? [] : [
|
|
657
1190
|
"--host",
|
|
658
1191
|
"127.0.0.1",
|
|
659
1192
|
"--port",
|
|
@@ -670,47 +1203,35 @@ async function prepareManagedLlamaServer(params) {
|
|
|
670
1203
|
async function ensureManagedLlamaServerForChat(params) {
|
|
671
1204
|
if (!params.provider.localService || !params.provider.baseUrl) return;
|
|
672
1205
|
const cacheDir = resolveLlamaCppModelCacheDir(params.provider);
|
|
673
|
-
|
|
674
|
-
params.
|
|
675
|
-
params.
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
let chatModelPath = resolveCachedLlamaCppModelPath({
|
|
681
|
-
model: params.model,
|
|
682
|
-
provider: params.provider
|
|
683
|
-
});
|
|
684
|
-
if (!chatModelPath && resolveLlamaCppModelSource(params.model) === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") {
|
|
685
|
-
const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), "hf_unsloth_gemma-4-E4B-it-GGUF_gemma-4-E4B-it-Q4_K_M.gguf");
|
|
686
|
-
if (await fs$1.stat(legacy).then((stat) => stat.isFile()).catch(() => false)) chatModelPath = legacy;
|
|
687
|
-
}
|
|
688
|
-
chatModelPath = await ensureLlamaCppModel({
|
|
689
|
-
source: chatModelPath ?? resolveLlamaCppModelSource(params.model),
|
|
690
|
-
cacheDir,
|
|
691
|
-
download: false
|
|
692
|
-
});
|
|
693
|
-
const configuredContext = params.model.params?.contextSize;
|
|
694
|
-
const port = Number(new URL(params.provider.baseUrl).port);
|
|
695
|
-
await prepareManagedLlamaServer({
|
|
696
|
-
chatModel: {
|
|
697
|
-
mode: "configure",
|
|
698
|
-
id: params.model.id,
|
|
699
|
-
path: chatModelPath,
|
|
700
|
-
contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : params.model.contextTokens,
|
|
701
|
-
maxTokens: params.model.maxTokens
|
|
702
|
-
},
|
|
703
|
-
defaultEmbeddingModelPath: path.join(cacheDir, "hf_ggml-org_embeddinggemma-300m-qat-Q8_0.gguf"),
|
|
704
|
-
port: Number.isInteger(port) && port > 0 ? port : void 0
|
|
705
|
-
});
|
|
706
|
-
})();
|
|
707
|
-
chatPreparationPromises.set(key, pending);
|
|
708
|
-
try {
|
|
709
|
-
await pending;
|
|
710
|
-
} catch (error) {
|
|
711
|
-
if (chatPreparationPromises.get(key) === pending) chatPreparationPromises.delete(key);
|
|
712
|
-
throw error;
|
|
1206
|
+
let chatModelPath = resolveCachedLlamaCppModelPath({
|
|
1207
|
+
model: params.model,
|
|
1208
|
+
provider: params.provider
|
|
1209
|
+
});
|
|
1210
|
+
if (!chatModelPath && resolveLlamaCppModelSource(params.model) === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") {
|
|
1211
|
+
const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
|
|
1212
|
+
if (await fs.stat(legacy).then((stat) => stat.isFile()).catch(() => false)) chatModelPath = legacy;
|
|
713
1213
|
}
|
|
1214
|
+
chatModelPath = await ensureLlamaCppModel({
|
|
1215
|
+
source: chatModelPath ?? resolveLlamaCppModelSource(params.model),
|
|
1216
|
+
cacheDir,
|
|
1217
|
+
download: false
|
|
1218
|
+
});
|
|
1219
|
+
const configuredContext = params.model.params?.contextSize;
|
|
1220
|
+
const port = Number(new URL(params.provider.baseUrl).port);
|
|
1221
|
+
await prepareManagedLlamaServer({
|
|
1222
|
+
chatModel: {
|
|
1223
|
+
mode: "configure",
|
|
1224
|
+
id: params.model.id,
|
|
1225
|
+
path: chatModelPath,
|
|
1226
|
+
contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : params.model.contextTokens,
|
|
1227
|
+
maxTokens: params.model.maxTokens
|
|
1228
|
+
},
|
|
1229
|
+
configuredChatModelIds: params.provider.models.map((model) => model.id),
|
|
1230
|
+
defaultEmbeddingModelPath: path.join(cacheDir, DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE),
|
|
1231
|
+
port: Number.isInteger(port) && port > 0 ? port : void 0,
|
|
1232
|
+
reconcileBaseUrl: params.provider.baseUrl,
|
|
1233
|
+
localService: params.provider.localService
|
|
1234
|
+
});
|
|
714
1235
|
}
|
|
715
1236
|
async function fetchEndpoint(url, accept) {
|
|
716
1237
|
try {
|
|
@@ -774,7 +1295,6 @@ async function inspectLlamaServerRuntime(params) {
|
|
|
774
1295
|
//#endregion
|
|
775
1296
|
//#region extensions/llama-cpp/src/embedding-provider.ts
|
|
776
1297
|
const LOCAL_EMBEDDING_RUNTIME_FACTS = Symbol.for("openclaw.localEmbeddingRuntimeFacts");
|
|
777
|
-
const preparedEmbeddingServers = /* @__PURE__ */ new Map();
|
|
778
1298
|
function readLocalOptions(options) {
|
|
779
1299
|
return options.local ?? {};
|
|
780
1300
|
}
|
|
@@ -828,31 +1348,20 @@ function resolveProviderPort(provider) {
|
|
|
828
1348
|
}
|
|
829
1349
|
async function prepareEmbeddingServer(options, embeddingSource, embeddingModelIsDefault) {
|
|
830
1350
|
const provider = resolveConfiguredProvider(options);
|
|
831
|
-
const
|
|
832
|
-
|
|
833
|
-
provider
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
}),
|
|
846
|
-
port: resolveProviderPort(provider)
|
|
847
|
-
});
|
|
848
|
-
})();
|
|
849
|
-
preparedEmbeddingServers.set(key, pending);
|
|
850
|
-
try {
|
|
851
|
-
await pending;
|
|
852
|
-
} catch (error) {
|
|
853
|
-
if (preparedEmbeddingServers.get(key) === pending) preparedEmbeddingServers.delete(key);
|
|
854
|
-
throw error;
|
|
855
|
-
}
|
|
1351
|
+
const embeddingModelPath = await ensureLlamaCppModel({
|
|
1352
|
+
source: embeddingSource,
|
|
1353
|
+
cacheDir: resolveLlamaCppModelCacheDir(provider),
|
|
1354
|
+
download: true
|
|
1355
|
+
});
|
|
1356
|
+
await prepareManagedLlamaServer({
|
|
1357
|
+
chatModel: { mode: "preserve" },
|
|
1358
|
+
configuredChatModelIds: provider.models.map((model) => model.id),
|
|
1359
|
+
embeddingModelIsDefault,
|
|
1360
|
+
embeddingModelPath,
|
|
1361
|
+
port: resolveProviderPort(provider),
|
|
1362
|
+
reconcileBaseUrl: provider.baseUrl,
|
|
1363
|
+
localService: provider.localService
|
|
1364
|
+
});
|
|
856
1365
|
}
|
|
857
1366
|
function wrapProvider(params) {
|
|
858
1367
|
let runtimeFacts;
|
|
@@ -860,7 +1369,6 @@ function wrapProvider(params) {
|
|
|
860
1369
|
runtimeFacts = await inspectLlamaServerRuntime({
|
|
861
1370
|
baseUrl: params.baseUrl,
|
|
862
1371
|
modelId: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
|
|
863
|
-
backend: selectLlamaServerAsset().backend,
|
|
864
1372
|
loadError
|
|
865
1373
|
});
|
|
866
1374
|
};
|
|
@@ -904,11 +1412,16 @@ const llamaCppEmbeddingProviderAdapter = {
|
|
|
904
1412
|
await prepareEmbeddingServer(options, embeddingModel.source, embeddingModel.isDefault);
|
|
905
1413
|
const genericAdapter = getEmbeddingProvider("openai-compatible", options.config);
|
|
906
1414
|
if (!genericAdapter) throw new Error("OpenAI-compatible embedding transport is unavailable.");
|
|
1415
|
+
const acquireLocalService = options.acquireLocalService;
|
|
907
1416
|
const result = await genericAdapter.create({
|
|
908
1417
|
...options,
|
|
909
1418
|
provider: LLAMA_CPP_PROVIDER_ID,
|
|
910
1419
|
model: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
|
|
911
|
-
remote: void 0
|
|
1420
|
+
remote: void 0,
|
|
1421
|
+
...acquireLocalService ? { acquireLocalService: (...[target, signal]) => acquireLocalService({
|
|
1422
|
+
...target,
|
|
1423
|
+
reconcile: reconcileManagedLlamaServer
|
|
1424
|
+
}, signal) } : {}
|
|
912
1425
|
});
|
|
913
1426
|
if (!result.provider) return result;
|
|
914
1427
|
return {
|
|
@@ -1138,6 +1651,36 @@ async function discoverLlamaServer(params) {
|
|
|
1138
1651
|
}
|
|
1139
1652
|
//#endregion
|
|
1140
1653
|
//#region extensions/llama-cpp/src/external-server/provider.ts
|
|
1654
|
+
const liveCatalogSdk = liveCatalogRuntime;
|
|
1655
|
+
async function runLlamaServerCatalog(params) {
|
|
1656
|
+
if (liveCatalogSdk.runLiveProviderCatalog) return await liveCatalogSdk.runLiveProviderCatalog(params);
|
|
1657
|
+
const identity = {
|
|
1658
|
+
provider: params.providerId,
|
|
1659
|
+
...params.profileId ? { profileId: params.profileId } : {}
|
|
1660
|
+
};
|
|
1661
|
+
try {
|
|
1662
|
+
const result = await params.run();
|
|
1663
|
+
return result ? {
|
|
1664
|
+
...result,
|
|
1665
|
+
outcomes: [...result.outcomes ?? [], {
|
|
1666
|
+
...identity,
|
|
1667
|
+
status: "ready"
|
|
1668
|
+
}]
|
|
1669
|
+
} : result;
|
|
1670
|
+
} catch (error) {
|
|
1671
|
+
return {
|
|
1672
|
+
providers: {},
|
|
1673
|
+
outcomes: [error instanceof liveCatalogRuntime.LiveModelCatalogHttpError && (error.status === 401 || error.status === 403) ? {
|
|
1674
|
+
...identity,
|
|
1675
|
+
status: "auth-rejected",
|
|
1676
|
+
rejectionScope: "catalog"
|
|
1677
|
+
} : {
|
|
1678
|
+
...identity,
|
|
1679
|
+
status: "unavailable"
|
|
1680
|
+
}]
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1141
1684
|
/** Discovers external llama-server models for provider runtime resolution. */
|
|
1142
1685
|
async function discoverLlamaServerProvider(ctx) {
|
|
1143
1686
|
const configured = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
@@ -1147,23 +1690,28 @@ async function discoverLlamaServerProvider(ctx) {
|
|
|
1147
1690
|
env: ctx.env,
|
|
1148
1691
|
headers: configured?.headers
|
|
1149
1692
|
});
|
|
1150
|
-
const
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1693
|
+
const authApiKey = auth.discoveryApiKey ?? auth.apiKey;
|
|
1694
|
+
const apiKey = hasLlamaServerAuthorizationHeader(headers) || authApiKey && isNonSecretApiKeyMarker(authApiKey) ? void 0 : authApiKey;
|
|
1695
|
+
return await runLlamaServerCatalog({
|
|
1696
|
+
providerId: LLAMA_CPP_PROVIDER_ID,
|
|
1697
|
+
profileId: apiKey ? auth.profileId : void 0,
|
|
1698
|
+
run: async () => {
|
|
1699
|
+
const discovery = await discoverLlamaServer({
|
|
1700
|
+
baseUrl: configured?.baseUrl,
|
|
1701
|
+
apiKey,
|
|
1702
|
+
headers,
|
|
1703
|
+
cacheTtlMs: 0
|
|
1704
|
+
});
|
|
1705
|
+
if (discovery.kind !== "success") {
|
|
1706
|
+
if (!configured && !apiKey && !headers) return null;
|
|
1707
|
+
throw discovery.kind === "http-error" ? new liveCatalogRuntime.LiveModelCatalogHttpError(LLAMA_CPP_PROVIDER_ID, discovery.status) : discovery.error;
|
|
1708
|
+
}
|
|
1709
|
+
return { provider: buildLlamaServerProviderConfig({
|
|
1710
|
+
configured,
|
|
1711
|
+
discoveredModels: discovery.models
|
|
1712
|
+
}) };
|
|
1713
|
+
}
|
|
1154
1714
|
});
|
|
1155
|
-
if (discovery.kind !== "success") return configured ? { provider: buildLlamaServerProviderConfig({
|
|
1156
|
-
configured,
|
|
1157
|
-
discoveredModels: []
|
|
1158
|
-
}) } : null;
|
|
1159
|
-
return { provider: buildLlamaServerProviderConfig({
|
|
1160
|
-
configured: {
|
|
1161
|
-
...configured,
|
|
1162
|
-
baseUrl: discovery.endpoint.inferenceBaseUrl,
|
|
1163
|
-
models: configured?.models ?? []
|
|
1164
|
-
},
|
|
1165
|
-
discoveredModels: discovery.models
|
|
1166
|
-
}) };
|
|
1167
1715
|
}
|
|
1168
1716
|
async function prepareLlamaServerDynamicModel(ctx) {
|
|
1169
1717
|
const apiKey = await resolveLlamaServerRuntimeApiKey({
|
|
@@ -1597,9 +2145,6 @@ function formatDownloadProgress(label, params) {
|
|
|
1597
2145
|
const totalSize = Math.max(1, params.totalSize);
|
|
1598
2146
|
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)`;
|
|
1599
2147
|
}
|
|
1600
|
-
function formatRamGb(totalmemBytes) {
|
|
1601
|
-
return (totalmemBytes / 1024 ** 3).toFixed(1).replace(/\.0$/u, "");
|
|
1602
|
-
}
|
|
1603
2148
|
function describeEmbeddingDownload(isDefault) {
|
|
1604
2149
|
return isDefault ? "the local embedding model (about 0.3 GB)" : "your configured local embedding model";
|
|
1605
2150
|
}
|
|
@@ -1622,9 +2167,19 @@ function configuredCandidates(config, scope) {
|
|
|
1622
2167
|
})).toSorted((a, b) => Number(b.model.id === primaryId) - Number(a.model.id === primaryId));
|
|
1623
2168
|
}
|
|
1624
2169
|
async function isFile(filePath) {
|
|
1625
|
-
return await fs
|
|
2170
|
+
return await fs.stat(filePath).then((stat) => stat.isFile()).catch(() => false);
|
|
1626
2171
|
}
|
|
1627
|
-
async function
|
|
2172
|
+
async function resolveCachedArtifact(source, cacheDir, signal) {
|
|
2173
|
+
return await ensureLlamaCppModel({
|
|
2174
|
+
source,
|
|
2175
|
+
cacheDir,
|
|
2176
|
+
download: false,
|
|
2177
|
+
signal
|
|
2178
|
+
}).catch(() => {
|
|
2179
|
+
signal?.throwIfAborted();
|
|
2180
|
+
});
|
|
2181
|
+
}
|
|
2182
|
+
async function resolveCachedCandidate(candidate, signal) {
|
|
1628
2183
|
const source = resolveLlamaCppModelSource(candidate.model);
|
|
1629
2184
|
const resolved = resolveCachedLlamaCppModelPath(candidate);
|
|
1630
2185
|
if (resolved && await isFile(resolved)) return resolved;
|
|
@@ -1632,21 +2187,7 @@ async function resolveCachedCandidate(candidate) {
|
|
|
1632
2187
|
const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
|
|
1633
2188
|
if (await isFile(legacy)) return legacy;
|
|
1634
2189
|
}
|
|
1635
|
-
if (/^(?:hf|huggingface|https):/iu.test(source)) return await
|
|
1636
|
-
source,
|
|
1637
|
-
cacheDir: resolveLlamaCppModelCacheDir(candidate.provider),
|
|
1638
|
-
download: false
|
|
1639
|
-
}).catch(() => void 0);
|
|
1640
|
-
}
|
|
1641
|
-
function readConfiguredPort(provider) {
|
|
1642
|
-
try {
|
|
1643
|
-
const url = new URL(provider?.baseUrl ?? "");
|
|
1644
|
-
if (url.hostname !== "127.0.0.1" && url.hostname !== "localhost" && url.hostname !== "[::1]") return;
|
|
1645
|
-
const port = Number(url.port);
|
|
1646
|
-
return Number.isInteger(port) && port > 0 ? port : void 0;
|
|
1647
|
-
} catch {
|
|
1648
|
-
return;
|
|
1649
|
-
}
|
|
2190
|
+
if (/^(?:hf|huggingface|https):/iu.test(source)) return await resolveCachedArtifact(source, resolveLlamaCppModelCacheDir(candidate.provider), signal);
|
|
1650
2191
|
}
|
|
1651
2192
|
function buildSetupResult(params) {
|
|
1652
2193
|
const existing = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
@@ -1661,7 +2202,7 @@ function buildSetupResult(params) {
|
|
|
1661
2202
|
providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig({
|
|
1662
2203
|
existing: switchingFromExternal ? void 0 : existing,
|
|
1663
2204
|
managed: params.managed,
|
|
1664
|
-
|
|
2205
|
+
modelInventory: params.plan === "embedding-only" ? [] : params.model ? [params.model, ...existing?.localService ? existing.models.filter((model) => model.id !== params.model?.id) : []] : existing?.models
|
|
1665
2206
|
}) }
|
|
1666
2207
|
}
|
|
1667
2208
|
}
|
|
@@ -1672,7 +2213,7 @@ async function detectLlamaCppSetup(ctx) {
|
|
|
1672
2213
|
const command = existing?.localService?.command;
|
|
1673
2214
|
const presetPath = existing?.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset");
|
|
1674
2215
|
if (!command || !path.isAbsolute(command) || !await isFile(command) || !presetPath || !await isFile(presetPath)) return null;
|
|
1675
|
-
for (const candidate of configuredCandidates(ctx.config, "detection")) if (await resolveCachedCandidate(candidate)) return {
|
|
2216
|
+
for (const candidate of configuredCandidates(ctx.config, "detection")) if (await resolveCachedCandidate(candidate, ctx.signal)) return {
|
|
1676
2217
|
modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
|
|
1677
2218
|
detail: "Managed llama.cpp server ready"
|
|
1678
2219
|
};
|
|
@@ -1713,26 +2254,62 @@ function resolveEmbeddingSetup(config, cacheDir) {
|
|
|
1713
2254
|
conflict: models.some((candidate) => candidate.source !== model.source)
|
|
1714
2255
|
};
|
|
1715
2256
|
}
|
|
1716
|
-
async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localMemoryIntent) {
|
|
2257
|
+
async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localMemoryIntent, hardware, asset, runtimeNote) {
|
|
1717
2258
|
let candidate = candidates[0];
|
|
1718
|
-
const
|
|
1719
|
-
if (candidate &&
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
2259
|
+
const configuredPath = candidate ? await resolveCachedCandidate(candidate, ctx.signal) : void 0;
|
|
2260
|
+
if (candidate && configuredPath) {
|
|
2261
|
+
if (runtimeNote && !await ctx.prompter.confirm({
|
|
2262
|
+
message: `${runtimeNote} Use cached ${candidate.model.name} on Gateway host ${os.hostname()} with the verified CPU runtime?`,
|
|
2263
|
+
initialValue: false
|
|
2264
|
+
})) return;
|
|
2265
|
+
return {
|
|
2266
|
+
kind: "chat",
|
|
2267
|
+
candidate,
|
|
2268
|
+
cachedPath: configuredPath
|
|
2269
|
+
};
|
|
2270
|
+
}
|
|
2271
|
+
const provider = candidate?.provider ?? buildLlamaCppProviderConfig();
|
|
2272
|
+
const cacheDir = resolveLlamaCppModelCacheDir(provider);
|
|
2273
|
+
const cachedModels = /* @__PURE__ */ new Map();
|
|
2274
|
+
for (const recipe of resolveLlamaCppModelCandidates(hardware, asset.backend).recipes) {
|
|
2275
|
+
const cached = await resolveCachedArtifact(resolveLlamaCppModelSource(recipe.model), cacheDir, ctx.signal);
|
|
2276
|
+
if (cached) {
|
|
2277
|
+
cachedModels.set(recipe.model.id, cached);
|
|
2278
|
+
break;
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
const cachedEmbedding = embeddingModelIsDefault && Boolean(await resolveCachedArtifact("hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf", cacheDir, ctx.signal));
|
|
2282
|
+
const recommendation = recommendLlamaCppModel(hardware, asset.backend, {
|
|
2283
|
+
modelIds: new Set(cachedModels.keys()),
|
|
2284
|
+
embedding: cachedEmbedding,
|
|
2285
|
+
runtime: await isFile(resolveManagedLlamaServerPaths(asset).command)
|
|
2286
|
+
});
|
|
2287
|
+
if (recommendation.kind === "recommended") {
|
|
2288
|
+
const { recipe } = recommendation;
|
|
2289
|
+
const cachedPath = cachedModels.get(recipe.model.id);
|
|
2290
|
+
candidate = {
|
|
2291
|
+
model: recipe.model,
|
|
2292
|
+
provider
|
|
2293
|
+
};
|
|
2294
|
+
const recommendationSummary = [
|
|
2295
|
+
`Runs on Gateway host ${os.hostname()} (${hardware.platform}/${hardware.arch}), using ${asset.backend === "metal" ? "Apple Metal" : asset.backend === "cuda" ? "NVIDIA CUDA" : "the CPU"}.`,
|
|
2296
|
+
`${formatLlamaCppMemory(hardware.totalMemoryBytes)} RAM; ${formatLlamaCppMemory(hardware.availableDiskBytes ?? 0)} free disk.`,
|
|
2297
|
+
!hardware.sharedDisk ? `${formatLlamaCppMemory(hardware.availableRuntimeDiskBytes ?? 0)} free on the runtime volume.` : void 0,
|
|
2298
|
+
runtimeNote,
|
|
2299
|
+
recommendation.reason,
|
|
2300
|
+
!embeddingModelIsDefault ? "This estimate includes the default embedding model; your configured embedding model may need more memory and disk space." : void 0,
|
|
2301
|
+
"OpenClaw will check a real tool call before making this your default model."
|
|
2302
|
+
].filter(Boolean).join("\n");
|
|
1727
2303
|
if (await ctx.prompter.confirm({
|
|
1728
|
-
message: `
|
|
2304
|
+
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?`}`,
|
|
1729
2305
|
initialValue: false
|
|
1730
2306
|
})) return {
|
|
1731
2307
|
kind: "chat",
|
|
1732
|
-
candidate
|
|
2308
|
+
candidate,
|
|
2309
|
+
cachedPath
|
|
1733
2310
|
};
|
|
1734
2311
|
} else if (!localMemoryIntent) {
|
|
1735
|
-
await ctx.prompter.note(
|
|
2312
|
+
await ctx.prompter.note(recommendation.reason, "Setup skipped");
|
|
1736
2313
|
return;
|
|
1737
2314
|
}
|
|
1738
2315
|
const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
@@ -1742,7 +2319,7 @@ async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localM
|
|
|
1742
2319
|
}
|
|
1743
2320
|
if (localMemoryIntent) {
|
|
1744
2321
|
if (await ctx.prompter.confirm({
|
|
1745
|
-
message: `
|
|
2322
|
+
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.`,
|
|
1746
2323
|
initialValue: false
|
|
1747
2324
|
})) return { kind: "embedding-only" };
|
|
1748
2325
|
}
|
|
@@ -1758,7 +2335,20 @@ async function runLlamaCppSetup(ctx) {
|
|
|
1758
2335
|
return { profiles: [] };
|
|
1759
2336
|
}
|
|
1760
2337
|
const embeddingModel = embeddingSetup.model;
|
|
1761
|
-
const
|
|
2338
|
+
const hardware = await detectLlamaCppHardware({
|
|
2339
|
+
cacheDir,
|
|
2340
|
+
signal: ctx.signal
|
|
2341
|
+
});
|
|
2342
|
+
let asset;
|
|
2343
|
+
let runtimeNote;
|
|
2344
|
+
try {
|
|
2345
|
+
asset = selectLlamaServerAsset(hardware.platform, hardware.arch, hardware.accelerator);
|
|
2346
|
+
} catch (error) {
|
|
2347
|
+
if (hardware.accelerator.kind !== "cuda") throw error;
|
|
2348
|
+
asset = selectLlamaServerAsset(hardware.platform, hardware.arch, { kind: "cpu" });
|
|
2349
|
+
runtimeNote = `${error instanceof Error ? error.message : String(error)} This recommendation uses CPU execution.`;
|
|
2350
|
+
}
|
|
2351
|
+
const plan = await resolveSetupPlan(ctx, configuredCandidates(ctx.config, "setup"), embeddingModel.isDefault, embeddingSetup.localMemoryIntent, hardware, asset, runtimeNote);
|
|
1762
2352
|
if (!plan) return { profiles: [] };
|
|
1763
2353
|
const progress = ctx.prompter.progress("Preparing managed llama.cpp server…");
|
|
1764
2354
|
try {
|
|
@@ -1769,7 +2359,7 @@ async function runLlamaCppSetup(ctx) {
|
|
|
1769
2359
|
cacheDir,
|
|
1770
2360
|
download: true,
|
|
1771
2361
|
signal: ctx.signal,
|
|
1772
|
-
onProgress: (status) => progress.update(formatDownloadProgress(
|
|
2362
|
+
onProgress: (status) => progress.update(formatDownloadProgress(plan.candidate.model.name, status))
|
|
1773
2363
|
});
|
|
1774
2364
|
const configuredContext = plan.candidate.model.params?.contextSize;
|
|
1775
2365
|
chatModel = {
|
|
@@ -1790,21 +2380,24 @@ async function runLlamaCppSetup(ctx) {
|
|
|
1790
2380
|
});
|
|
1791
2381
|
const managed = await prepareManagedLlamaServer({
|
|
1792
2382
|
chatModel,
|
|
2383
|
+
configuredChatModelIds: plan.kind === "chat" ? plan.candidate.provider.models.map((model) => model.id) : [],
|
|
1793
2384
|
embeddingModelIsDefault: embeddingModel.isDefault,
|
|
1794
2385
|
embeddingModelPath,
|
|
1795
|
-
|
|
2386
|
+
asset,
|
|
2387
|
+
isolated: true,
|
|
2388
|
+
signal: ctx.signal,
|
|
2389
|
+
onProgress: (status) => progress.update(formatDownloadProgress("llama.cpp runtime", status))
|
|
1796
2390
|
});
|
|
1797
|
-
|
|
1798
|
-
provider: "llama-cpp",
|
|
1799
|
-
profileIds: [LLAMA_CPP_DEFAULT_PROFILE_ID],
|
|
1800
|
-
agentDir: ctx.agentDir
|
|
1801
|
-
})) throw new Error("Failed to remove the previous llama.cpp endpoint auth profile");
|
|
2391
|
+
ctx.signal?.throwIfAborted();
|
|
1802
2392
|
progress.stop("Managed llama.cpp server prepared");
|
|
1803
2393
|
return buildSetupResult({
|
|
1804
2394
|
config: ctx.config,
|
|
1805
2395
|
managed,
|
|
1806
2396
|
plan: plan.kind,
|
|
1807
|
-
...plan.kind === "chat" ? {
|
|
2397
|
+
...plan.kind === "chat" ? {
|
|
2398
|
+
defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${plan.candidate.model.id}`,
|
|
2399
|
+
model: plan.candidate.model
|
|
2400
|
+
} : {}
|
|
1808
2401
|
});
|
|
1809
2402
|
} catch (error) {
|
|
1810
2403
|
progress.stop("llama.cpp setup failed");
|
|
@@ -1814,6 +2407,20 @@ async function runLlamaCppSetup(ctx) {
|
|
|
1814
2407
|
}
|
|
1815
2408
|
//#endregion
|
|
1816
2409
|
//#region extensions/llama-cpp/src/managed-provider.ts
|
|
2410
|
+
function wrapManagedLlamaCppStream(ctx, streamFn = ctx.streamFn) {
|
|
2411
|
+
const providerConfig = ctx.config?.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
2412
|
+
if (!providerConfig?.localService) return;
|
|
2413
|
+
const inner = streamFn;
|
|
2414
|
+
const selectedModel = ctx.model;
|
|
2415
|
+
if (!inner || !selectedModel) return;
|
|
2416
|
+
return async (...args) => {
|
|
2417
|
+
await ensureManagedLlamaServerForChat({
|
|
2418
|
+
provider: providerConfig,
|
|
2419
|
+
model: selectedModel
|
|
2420
|
+
});
|
|
2421
|
+
return inner(...args);
|
|
2422
|
+
};
|
|
2423
|
+
}
|
|
1817
2424
|
function registerLlamaCppProvider(api) {
|
|
1818
2425
|
api.registerProvider({
|
|
1819
2426
|
id: LLAMA_CPP_PROVIDER_ID,
|
|
@@ -1823,12 +2430,12 @@ function registerLlamaCppProvider(api) {
|
|
|
1823
2430
|
auth: [{
|
|
1824
2431
|
id: "local",
|
|
1825
2432
|
label: LLAMA_CPP_PROVIDER_LABEL,
|
|
1826
|
-
hint: "
|
|
2433
|
+
hint: "Choose a Qwen, Gemma, or Muse model for this Gateway’s hardware and install llama.cpp",
|
|
1827
2434
|
kind: "custom",
|
|
1828
2435
|
wizard: {
|
|
1829
2436
|
choiceId: LLAMA_CPP_PROVIDER_ID,
|
|
1830
2437
|
choiceLabel: "Managed local server",
|
|
1831
|
-
choiceHint: "
|
|
2438
|
+
choiceHint: "Choose a Qwen, Gemma, or Muse model for this Gateway’s hardware and install llama.cpp",
|
|
1832
2439
|
groupId: LLAMA_CPP_PROVIDER_ID,
|
|
1833
2440
|
groupLabel: "Local llama.cpp",
|
|
1834
2441
|
groupHint: "Managed or external llama.cpp server",
|
|
@@ -1883,19 +2490,11 @@ function registerLlamaCppProvider(api) {
|
|
|
1883
2490
|
shouldDeferSyntheticProfileAuth: ({ resolvedApiKey }) => resolvedApiKey?.trim() === resolveLlamaCppSyntheticApiKey() || resolvedApiKey?.trim() === CUSTOM_LOCAL_AUTH_MARKER,
|
|
1884
2491
|
normalizeConfig: ({ providerConfig }) => providerConfig.localService ? providerConfig : normalizeLlamaServerProviderConfig(providerConfig),
|
|
1885
2492
|
prepareDynamicModel: async (ctx) => ctx.config?.models?.providers?.["llama-cpp"]?.localService ? void 0 : await prepareLlamaServerDynamicModel(ctx),
|
|
2493
|
+
reconcileLocalService: reconcileManagedLlamaServer,
|
|
2494
|
+
wrapSimpleCompletionStreamFn: wrapManagedLlamaCppStream,
|
|
1886
2495
|
wrapStreamFn: (ctx) => {
|
|
1887
|
-
const
|
|
1888
|
-
|
|
1889
|
-
const inner = ctx.streamFn;
|
|
1890
|
-
const selectedModel = ctx.model;
|
|
1891
|
-
if (!inner || !selectedModel) return;
|
|
1892
|
-
return async (model, context, options) => {
|
|
1893
|
-
await ensureManagedLlamaServerForChat({
|
|
1894
|
-
provider: providerConfig,
|
|
1895
|
-
model: selectedModel
|
|
1896
|
-
});
|
|
1897
|
-
return inner(model, context, options);
|
|
1898
|
-
};
|
|
2496
|
+
const streamFn = wrapLlamaServerStream(ctx);
|
|
2497
|
+
return ctx.config?.models?.providers?.["llama-cpp"]?.localService ? wrapManagedLlamaCppStream(ctx, streamFn) : streamFn;
|
|
1899
2498
|
},
|
|
1900
2499
|
...buildProviderToolCompatFamilyHooks("llamacpp-gbnf"),
|
|
1901
2500
|
wizard: { modelPicker: {
|