@openclaw/llama-cpp-provider 2026.10.5-beta.3 → 2026.10.10-beta.1

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,1634 +1,12 @@
1
- import { C as resolveCachedLlamaCppModelPath, D as resolveLlamaCppEmbeddingModel, E as resolveLlamaCppDataDir, O as resolveLlamaCppModelCacheDir, S as buildLlamaCppProviderConfig, T as resolveLegacyLlamaCppModelCacheDir, _ as LLAMA_CPP_DEFAULT_PORT, a as DEFAULT_LLAMA_CPP_EMBEDDING_CONTEXT_SIZE, b as LLAMA_CPP_PROVIDER_LABEL, c as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION, d as DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE, f as DEFAULT_LLAMA_CPP_MODEL_ID, g as DEFAULT_LLAMA_CPP_MODEL_URI, h as DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES, i as DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE, k as resolveLlamaCppModelSource, l as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256, m as DEFAULT_LLAMA_CPP_MODEL_SHA256, n as resolveManagedLlamaCppProviderConfig, o as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, p as DEFAULT_LLAMA_CPP_MODEL_REVISION, s as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, u as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES, v as LLAMA_CPP_LOCAL_AUTH_MARKER, w as resolveHomePath, x as buildLlamaCppModel, y as LLAMA_CPP_PROVIDER_ID } from "./.setup/managed-provider-config-D0abOkC_.mjs";
1
+ import { C as resolveLegacyLlamaCppModelCacheDir, E as resolveLlamaCppModelCacheDir, T as resolveLlamaCppEmbeddingModel, _ as LLAMA_CPP_PROVIDER_ID, i as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, n as DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE, v as LLAMA_CPP_PROVIDER_LABEL } from "./.setup/defaults-CL2lz0cV.mjs";
2
+ import { a as LLAMA_SERVER_DEFAULT_ORIGIN, t as provider_discovery_default } from "./.setup/provider-discovery-97l8WbMa.mjs";
3
+ import { a as isManagedLlamaCppMediaProvider, i as LLAMA_CPP_MEDIA_TIMEOUT_MS, n as LLAMA_CPP_MEDIA_MAX_CHARS, o as resolveLlamaCppMediaModels, r as LLAMA_CPP_MEDIA_MAX_TOKENS, t as LLAMA_CPP_MEDIA_MAX_BYTES } from "./.setup/media-config-CZ7CluNV.mjs";
2
4
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
3
5
  import path from "node:path";
4
- import { getEmbeddingProvider } from "openclaw/plugin-sdk/embedding-providers";
5
- import os from "node:os";
6
- import { asOptionalRecord, asPositiveSafeInteger, isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
7
- import { createHash, randomUUID } from "node:crypto";
8
- import fs from "node:fs/promises";
9
- import net from "node:net";
10
- import { createAsyncLock } from "openclaw/plugin-sdk/async-lock-runtime";
11
- import { readProviderJsonResponse, readProviderTextResponse } from "openclaw/plugin-sdk/provider-http";
12
- import { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } from "openclaw/plugin-sdk/ssrf-runtime";
13
- import { fetchConfiguredLocalOriginWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime-internal";
14
- import { execFile } from "node:child_process";
15
- import fs$1, { constants } from "node:fs";
16
- import { sha256File } from "@openclaw/fs-safe/durability";
17
- import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
18
- import { toErrorObject } from "openclaw/plugin-sdk/error-runtime";
19
- import { ARCHIVE_LIMIT_ERROR_CODE, ArchiveLimitError, extractArchive } from "openclaw/plugin-sdk/archive";
20
- import { createSubsystemLogger } from "openclaw/plugin-sdk/logging-core";
21
- import { CUSTOM_LOCAL_AUTH_MARKER, applyAuthProfileConfig, buildApiKeyCredential, ensureApiKeyFromEnvOrPrompt, hasConfiguredSecretInput, isNonSecretApiKeyMarker, normalizeOptionalSecretInput } from "openclaw/plugin-sdk/provider-auth";
6
+ import { asPositiveSafeInteger, isRecord, normalizeOptionalString, truncateUtf16Safe } from "openclaw/plugin-sdk/string-coerce-runtime";
22
7
  import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
23
- import { removeAuthProfileConfig, removeProviderAuthProfilesWithLock, resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
24
- import { resolveConfiguredSecretInputString } from "openclaw/plugin-sdk/secret-input-runtime";
25
- import { LiveModelCatalogHttpError, runLiveProviderCatalog } from "openclaw/plugin-sdk/provider-catalog-live-runtime";
26
- import { SELF_HOSTED_DEFAULT_CONTEXT_WINDOW, SELF_HOSTED_DEFAULT_COST, SELF_HOSTED_DEFAULT_MAX_TOKENS, applyProviderDefaultModel, discoverOpenAICompatibleLocalModels } from "openclaw/plugin-sdk/provider-setup";
27
- import { upsertAuthProfileWithLockOrThrow } from "openclaw/plugin-sdk/provider-auth-api-key";
28
- import { selectPreferredLocalModelId } from "openclaw/plugin-sdk/provider-model-shared";
29
- import { streamSimple } from "openclaw/plugin-sdk/llm";
30
- import { setQwenChatTemplateThinking } from "openclaw/plugin-sdk/provider-stream-shared";
31
- import { listAgentIds, resolveAgentConfig } from "openclaw/plugin-sdk/agent-scope-runtime";
32
- //#region extensions/llama-cpp/src/llama-server-assets.ts
33
- const LLAMA_SERVER_RELEASE = "b10809";
34
- const LLAMA_SERVER_COMMIT = "5266f24da75dc449bd56cbed7addb9c8e4a6a73e";
35
- const MEBIBYTE$1 = 1048576;
36
- const CUDA_ARCHIVE_LIMITS = {
37
- maxArchiveBytes: 400 * MEBIBYTE$1,
38
- maxExtractedBytes: 600 * MEBIBYTE$1,
39
- maxEntryBytes: 521 * MEBIBYTE$1
40
- };
41
- const WINDOWS_X64_VC_RUNTIME = {
42
- archive: "vc-redist",
43
- name: "VC_redist.x64.exe",
44
- url: "https://download.visualstudio.microsoft.com/download/pr/ebdab8e5-1d7b-4d9f-a11b-cbb1720c3b12/843068991DAAA1F73AD9F6239BCE4D0F6A07A51F18C37EA2A867E9BECA71295C/VC_redist.x64.exe",
45
- sha256: "843068991daaa1f73ad9f6239bce4d0f6a07a51f18c37ea2a867e9beca71295c",
46
- size: 18731856,
47
- containerOffset: 63e4,
48
- containerSize: 18091661,
49
- nestedCabinet: "a4",
50
- files: [
51
- {
52
- source: "msvcp140.dll_amd64",
53
- target: "msvcp140.dll"
54
- },
55
- {
56
- source: "vcruntime140.dll_amd64",
57
- target: "vcruntime140.dll"
58
- },
59
- {
60
- source: "vcruntime140_1.dll_amd64",
61
- target: "vcruntime140_1.dll"
62
- }
63
- ]
64
- };
65
- const WINDOWS_ARM64_VC_RUNTIME = {
66
- archive: "vc-redist",
67
- name: "VC_redist.arm64.exe",
68
- url: "https://download.visualstudio.microsoft.com/download/pr/ece44298-3977-4f73-ab91-c13fe79cfea8/B70EF586669A620A0A30A1156969C05C6A3831DC8F8BC992DA75779D2A92F944/VC_redist.arm64.exe",
69
- sha256: "b70ef586669a620a0a30a1156969c05c6a3831dc8f8bc992da75779d2a92f944",
70
- size: 11870816,
71
- containerOffset: 684112,
72
- containerSize: 11176508,
73
- nestedCabinet: "a1",
74
- files: [{
75
- source: "msvcp140.dll_arm64",
76
- target: "msvcp140.dll"
77
- }, {
78
- source: "vcruntime140.dll_arm64",
79
- target: "vcruntime140.dll"
80
- }]
81
- };
82
- const MACOS_ALIASES = [
83
- ["libggml-rpc.0.23.0.dylib", ["libggml-rpc.0.dylib", "libggml-rpc.dylib"]],
84
- ["libllama.0.4.0.dylib", ["libllama.0.dylib", "libllama.dylib"]],
85
- ["libmtmd.0.4.0.dylib", ["libmtmd.0.dylib", "libmtmd.dylib"]],
86
- ["libggml.0.23.0.dylib", ["libggml.0.dylib", "libggml.dylib"]],
87
- ["libggml-base.0.23.0.dylib", ["libggml-base.0.dylib", "libggml-base.dylib"]],
88
- ["libggml-blas.0.23.0.dylib", ["libggml-blas.0.dylib", "libggml-blas.dylib"]],
89
- ["libllama-common.0.4.0.dylib", ["libllama-common.0.dylib", "libllama-common.dylib"]],
90
- ["libggml-cpu.0.23.0.dylib", ["libggml-cpu.0.dylib", "libggml-cpu.dylib"]]
91
- ];
92
- const MACOS_METAL_ALIASES = [...MACOS_ALIASES, ["libggml-metal.0.23.0.dylib", ["libggml-metal.0.dylib", "libggml-metal.dylib"]]];
93
- const LINUX_ALIASES = [
94
- ["libllama.so.0.4.0", ["libllama.so.0", "libllama.so"]],
95
- ["libggml.so.0.23.0", ["libggml.so.0", "libggml.so"]],
96
- ["libmtmd.so.0.4.0", ["libmtmd.so.0", "libmtmd.so"]],
97
- ["libggml-base.so.0.23.0", ["libggml-base.so.0", "libggml-base.so"]],
98
- ["libllama-common.so.0.4.0", ["libllama-common.so.0", "libllama-common.so"]]
99
- ];
100
- const LLAMA_SERVER_ASSETS = [
101
- {
102
- platform: "darwin",
103
- arch: "arm64",
104
- backend: "metal",
105
- archive: "tar.gz",
106
- archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
107
- name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-arm64.tar.gz`,
108
- sha256: "7d692df9e1e386e62f1c12b843903218041e6cd74c9415aa39a7ed3176f9eaa2",
109
- executable: "llama-server",
110
- regularFileAliases: MACOS_METAL_ALIASES
111
- },
112
- {
113
- platform: "darwin",
114
- arch: "x64",
115
- backend: "cpu",
116
- archive: "tar.gz",
117
- archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
118
- name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-x64.tar.gz`,
119
- sha256: "13b34aa8a5d87341a21065a83f54a8167e1aaa6fe0d66065de01632a1ed64be6",
120
- executable: "llama-server",
121
- regularFileAliases: MACOS_ALIASES
122
- },
123
- {
124
- platform: "linux",
125
- arch: "arm64",
126
- backend: "cpu",
127
- archive: "tar.gz",
128
- archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
129
- name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-arm64.tar.gz`,
130
- sha256: "f2b7333971e1b7b42e9268bfdbfa30f5f56e2897156084d2251385df94aec358",
131
- executable: "llama-server",
132
- regularFileAliases: LINUX_ALIASES
133
- },
134
- {
135
- platform: "linux",
136
- arch: "x64",
137
- backend: "cpu",
138
- archive: "tar.gz",
139
- archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
140
- name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-x64.tar.gz`,
141
- sha256: "5e34434ddc6d03cd1584f403201aff0d4bd1a5793a72ff7e286532dfd1e4b941",
142
- executable: "llama-server",
143
- regularFileAliases: LINUX_ALIASES
144
- },
145
- {
146
- platform: "win32",
147
- arch: "x64",
148
- backend: "cuda",
149
- archive: "zip",
150
- archiveRoot: ".",
151
- name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cuda-12.4-x64.zip`,
152
- sha256: "c77bfcd9ed8d91e8721a2d6a290b907fddd4fa5412a47b21c6fa1709116b85f9",
153
- executable: "llama-server.exe",
154
- regularFileAliases: [],
155
- limits: CUDA_ARCHIVE_LIMITS,
156
- dependencies: [{
157
- archive: "zip",
158
- archiveRoot: ".",
159
- name: "cudart-llama-bin-win-cuda-12.4-x64.zip",
160
- sha256: "8c79a9b226de4b3cacfd1f83d24f962d0773be79f1e7b75c6af4ded7e32ae1d6",
161
- regularFileAliases: [],
162
- files: [
163
- "cublas64_12.dll",
164
- "cublasLt64_12.dll",
165
- "cudart64_12.dll"
166
- ],
167
- limits: {
168
- ...CUDA_ARCHIVE_LIMITS,
169
- maxEntries: 3
170
- }
171
- }, WINDOWS_X64_VC_RUNTIME]
172
- },
173
- {
174
- platform: "win32",
175
- arch: "arm64",
176
- backend: "cpu",
177
- archive: "zip",
178
- archiveRoot: ".",
179
- name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-arm64.zip`,
180
- sha256: "c1058fe5764a687275c8d20d6bbc1454e787cdbb8ebb8c37a2f959f2b144dc77",
181
- executable: "llama-server.exe",
182
- regularFileAliases: [],
183
- dependencies: [WINDOWS_ARM64_VC_RUNTIME]
184
- },
185
- {
186
- platform: "win32",
187
- arch: "x64",
188
- backend: "cpu",
189
- archive: "zip",
190
- archiveRoot: ".",
191
- name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-x64.zip`,
192
- sha256: "9df3158ed228a641a4b127942d7f459f24c9e13f04682659d05c00c80099b6b5",
193
- executable: "llama-server.exe",
194
- regularFileAliases: [],
195
- dependencies: [WINDOWS_X64_VC_RUNTIME]
196
- }
197
- ];
198
- function selectLlamaServerAsset(platform = process.platform, arch = process.arch, acceleration) {
199
- const backend = acceleration?.kind ?? (platform === "darwin" && arch === "arm64" ? "metal" : "cpu");
200
- if (backend === "cuda" && acceleration?.kind === "cuda") {
201
- 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.`);
202
- if (!(acceleration.devices.length > 0 && acceleration.devices.every((device) => {
203
- const version = /^(\d+)\.(\d+)(?:\.\d+)?$/u.exec(device.driverVersion);
204
- return version && (Number(version[1]) > 551 || Number(version[1]) === 551 && Number(version[2]) >= 78) && (device.computeCapability === void 0 || device.computeCapability >= 5);
205
- }))) 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.");
206
- }
207
- const asset = LLAMA_SERVER_ASSETS.find((candidate) => candidate.platform === platform && candidate.arch === arch && candidate.backend === backend);
208
- 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.`);
209
- return asset;
210
- }
211
- function resolveManagedLlamaServerPaths(asset = selectLlamaServerAsset()) {
212
- const installDir = path.join(resolveLlamaCppDataDir(), LLAMA_SERVER_RELEASE, `${asset.platform}-${asset.arch}${asset.backend === "cuda" ? "-cuda-12.4" : ""}`);
213
- return {
214
- installDir,
215
- command: path.join(installDir, asset.executable),
216
- presetPath: path.join(resolveLlamaCppDataDir(), "models.ini")
217
- };
218
- }
219
- function findManagedLlamaServerAsset(command, platform = process.platform, arch = process.arch) {
220
- return LLAMA_SERVER_ASSETS.find((asset) => asset.platform === platform && asset.arch === arch && resolveManagedLlamaServerPaths(asset).command === command);
221
- }
222
- //#endregion
223
- //#region extensions/llama-cpp/src/llama-server-extract.ts
224
- const MEBIBYTE = 1048576;
225
- const LLAMA_ARCHIVE_LIMITS = {
226
- maxArchiveBytes: 256 * MEBIBYTE,
227
- maxEntries: 1e3,
228
- maxExtractedBytes: 512 * MEBIBYTE,
229
- maxEntryBytes: 256 * MEBIBYTE,
230
- maxMetaEntryBytes: MEBIBYTE
231
- };
232
- const MAX_ALIAS_BYTES = 512 * MEBIBYTE;
233
- function assertManifestBasename$1(filename) {
234
- if (!filename || filename === "." || filename === ".." || /[\\/]/u.test(filename) || path.basename(filename) !== filename) throw new Error(`invalid llama-server archive manifest filename: ${filename}`);
235
- return filename;
236
- }
237
- function resolveArchiveRoot(destDir, archiveRoot) {
238
- if (archiveRoot === ".") return destDir;
239
- if (path.isAbsolute(archiveRoot) || /\\/u.test(archiveRoot)) throw new Error(`invalid llama-server archive root: ${archiveRoot}`);
240
- const parts = archiveRoot.split("/");
241
- if (parts.some((part) => !part || part === "." || part === "..")) throw new Error(`invalid llama-server archive root: ${archiveRoot}`);
242
- return path.join(destDir, ...parts);
243
- }
244
- async function assertRegularFile$1(filePath, label) {
245
- const stat = await fs.lstat(filePath).catch(() => void 0);
246
- if (!stat?.isFile() || stat.nlink > 1) throw new Error(`llama-server archive does not contain regular ${label}`);
247
- return stat;
248
- }
249
- async function materializeAssetAliases(params) {
250
- const claimedNames = new Set(params.requiredFiles.map(assertManifestBasename$1));
251
- for (const file of claimedNames) await assertRegularFile$1(path.join(params.rootDir, file), `file ${file}`);
252
- let copiedBytes = 0;
253
- for (const [rawSource, rawAliases] of params.asset.regularFileAliases) {
254
- const source = assertManifestBasename$1(rawSource);
255
- if (claimedNames.has(source)) throw new Error(`duplicate llama-server archive manifest filename: ${source}`);
256
- claimedNames.add(source);
257
- const sourcePath = path.join(params.rootDir, source);
258
- const sourceStat = await assertRegularFile$1(sourcePath, `alias source ${source}`);
259
- for (const rawAlias of rawAliases) {
260
- const alias = assertManifestBasename$1(rawAlias);
261
- if (claimedNames.has(alias)) throw new Error(`duplicate llama-server archive manifest filename: ${alias}`);
262
- claimedNames.add(alias);
263
- copiedBytes += sourceStat.size;
264
- if (copiedBytes > MAX_ALIAS_BYTES) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.EXTRACTED_SIZE_EXCEEDS_LIMIT);
265
- const aliasPath = path.join(params.rootDir, alias);
266
- await fs.copyFile(sourcePath, aliasPath, constants.COPYFILE_EXCL);
267
- await fs.chmod(aliasPath, sourceStat.mode & 511);
268
- if ((await assertRegularFile$1(aliasPath, `alias ${alias}`)).size !== sourceStat.size) throw new Error(`llama-server archive alias copy is incomplete: ${alias}`);
269
- }
270
- }
271
- }
272
- async function extractVerifiedArchive(params) {
273
- const isTar = params.asset.archive === "tar.gz";
274
- const limits = {
275
- ...LLAMA_ARCHIVE_LIMITS,
276
- ...params.asset.limits
277
- };
278
- const aliasCount = params.asset.regularFileAliases.reduce((count, [, aliases]) => count + aliases.length, 0);
279
- if (aliasCount > limits.maxEntries) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.ENTRY_COUNT_EXCEEDS_LIMIT);
280
- await extractArchive({
281
- archivePath: params.archivePath,
282
- destDir: params.destDir,
283
- kind: isTar ? "tar" : "zip",
284
- timeoutMs: 0,
285
- limits: {
286
- ...limits,
287
- maxEntries: limits.maxEntries - aliasCount
288
- },
289
- tarGzip: isTar,
290
- entryFilter: (entry) => entry.kind === "symlink" ? "skip" : "extract",
291
- onFiltered: "skip-entry"
292
- });
293
- const rootDir = resolveArchiveRoot(params.destDir, params.asset.archiveRoot);
294
- await materializeAssetAliases({
295
- rootDir,
296
- asset: params.asset,
297
- requiredFiles: params.requiredFiles
298
- });
299
- return rootDir;
300
- }
301
- /** Extracts one verified asset and returns its unpublished executable path. */
302
- async function extractLlamaServerArchive(params) {
303
- const rootDir = await extractVerifiedArchive({
304
- ...params,
305
- requiredFiles: [params.asset.executable]
306
- });
307
- return path.join(rootDir, params.asset.executable);
308
- }
309
- async function extractLlamaServerDependencyArchive(params) {
310
- return await extractVerifiedArchive({
311
- ...params,
312
- requiredFiles: params.asset.files
313
- });
314
- }
315
- //#endregion
316
- //#region extensions/llama-cpp/src/llama-server-vc-runtime.ts
317
- const CAB_HEADER_SIZE = 12;
318
- const COPY_BUFFER_SIZE = 1048576;
319
- const EXPAND_TIMEOUT_MS = 6e4;
320
- function assertManifestBasename(filename) {
321
- if (!filename || filename === "." || filename === ".." || /[\\/]/u.test(filename) || path.basename(filename) !== filename) throw new Error(`invalid Visual C++ runtime manifest filename: ${filename}`);
322
- return filename;
323
- }
324
- async function writeFully(handle, buffer, length) {
325
- let offset = 0;
326
- while (offset < length) {
327
- const result = await handle.write(buffer, offset, length - offset);
328
- if (result.bytesWritten <= 0) throw new Error("Visual C++ runtime container copy made no progress");
329
- offset += result.bytesWritten;
330
- }
331
- }
332
- async function extractPinnedContainer(params) {
333
- const source = await fs.open(params.bundlePath, "r");
334
- try {
335
- const stat = await source.stat();
336
- if (!stat.isFile() || stat.size !== params.asset.size) throw new Error(`Visual C++ runtime bundle size mismatch: expected ${params.asset.size}, got ${stat.size}`);
337
- if (params.asset.containerOffset < 0 || params.asset.containerSize < CAB_HEADER_SIZE || params.asset.containerOffset + params.asset.containerSize > stat.size) throw new Error("invalid Visual C++ runtime container bounds");
338
- const header = Buffer.alloc(CAB_HEADER_SIZE);
339
- if ((await source.read(header, 0, header.length, params.asset.containerOffset)).bytesRead !== header.length || header.subarray(0, 4).toString("ascii") !== "MSCF" || header.readUInt32LE(8) !== params.asset.containerSize) throw new Error("Visual C++ runtime bundle does not contain the pinned cabinet");
340
- const target = await fs.open(params.containerPath, "wx", 384);
341
- try {
342
- const buffer = Buffer.allocUnsafe(Math.min(COPY_BUFFER_SIZE, params.asset.containerSize));
343
- let copied = 0;
344
- while (copied < params.asset.containerSize) {
345
- params.signal?.throwIfAborted();
346
- const requested = Math.min(buffer.length, params.asset.containerSize - copied);
347
- const result = await source.read(buffer, 0, requested, params.asset.containerOffset + copied);
348
- if (result.bytesRead <= 0) throw new Error("Visual C++ runtime container ended before its pinned size");
349
- await writeFully(target, buffer, result.bytesRead);
350
- copied += result.bytesRead;
351
- }
352
- } finally {
353
- await target.close();
354
- }
355
- } finally {
356
- await source.close();
357
- }
358
- }
359
- function resolveExpandCommand() {
360
- const systemRoot = process.env.SystemRoot;
361
- if (!systemRoot || !path.win32.isAbsolute(systemRoot)) throw new Error("SystemRoot is unavailable; cannot extract the Visual C++ runtime");
362
- return path.win32.join(systemRoot, "System32", "expand.exe");
363
- }
364
- async function runExpand(command, args, signal) {
365
- await new Promise((resolve, reject) => {
366
- execFile(command, args, {
367
- timeout: EXPAND_TIMEOUT_MS,
368
- signal,
369
- windowsHide: true
370
- }, (error, _stdout, stderr) => {
371
- if (error) {
372
- const detail = stderr.trim();
373
- reject(new Error(`Failed to extract the Visual C++ runtime${detail ? `: ${detail}` : ""}`, { cause: error }));
374
- } else resolve();
375
- });
376
- });
377
- }
378
- async function assertRegularFile(filePath, label) {
379
- const stat = await fs.lstat(filePath).catch(() => void 0);
380
- if (!stat?.isFile() || stat.nlink > 1) throw new Error(`Visual C++ runtime does not contain regular file ${label}`);
381
- }
382
- /** Extracts the pinned Microsoft redistributable DLLs without installing machine-wide state. */
383
- async function extractWindowsVcRuntime(params) {
384
- const nestedCabinet = assertManifestBasename(params.asset.nestedCabinet);
385
- const files = params.asset.files.map(({ source, target }) => ({
386
- source: assertManifestBasename(source),
387
- target: assertManifestBasename(target)
388
- }));
389
- if (new Set(files.map((file) => file.target)).size !== files.length) throw new Error("duplicate Visual C++ runtime target filename");
390
- const expandCommand = resolveExpandCommand();
391
- const containerPath = path.join(params.destDir, "bundle.cab");
392
- const nestedDir = path.join(params.destDir, "nested");
393
- const filesDir = path.join(params.destDir, "files");
394
- await Promise.all([
395
- fs.mkdir(params.destDir, { recursive: true }),
396
- fs.mkdir(nestedDir, { recursive: true }),
397
- fs.mkdir(filesDir, { recursive: true })
398
- ]);
399
- await extractPinnedContainer({
400
- asset: params.asset,
401
- bundlePath: params.bundlePath,
402
- containerPath,
403
- signal: params.signal
404
- });
405
- await runExpand(expandCommand, [
406
- `-F:${nestedCabinet}`,
407
- containerPath,
408
- nestedDir
409
- ], params.signal);
410
- const nestedPath = path.join(nestedDir, nestedCabinet);
411
- await assertRegularFile(nestedPath, nestedCabinet);
412
- for (const file of files) {
413
- params.signal?.throwIfAborted();
414
- await runExpand(expandCommand, [
415
- `-F:${file.source}`,
416
- nestedPath,
417
- filesDir
418
- ], params.signal);
419
- const sourcePath = path.join(filesDir, file.source);
420
- await assertRegularFile(sourcePath, file.source);
421
- const targetPath = path.join(params.destDir, file.target);
422
- await fs.copyFile(sourcePath, targetPath, constants.COPYFILE_EXCL);
423
- await assertRegularFile(targetPath, file.target);
424
- }
425
- return params.destDir;
426
- }
427
- //#endregion
428
- //#region extensions/llama-cpp/src/llama-server-install.ts
429
- const DOWNLOAD_TIMEOUT_MS = 18e5;
430
- const PROBE_TIMEOUT_MS = 15e3;
431
- const VERSION_TIMEOUT_MS = 12e4;
432
- const installationPromises = /* @__PURE__ */ new Map();
433
- function compareVersion(left, right) {
434
- const leftParts = left.split(".").map(Number);
435
- const rightParts = right.split(".").map(Number);
436
- for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
437
- const delta = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
438
- if (delta !== 0) return delta;
439
- }
440
- return 0;
441
- }
442
- /** The verified build cannot run on this host; rerunning setup cannot change that. */
443
- var UnsupportedLlamaServerHostError = class extends Error {
444
- constructor(..._args) {
445
- super(..._args);
446
- this.name = "UnsupportedLlamaServerHostError";
447
- }
448
- };
449
- function assertSupportedLinuxRuntime(asset) {
450
- if (asset.platform !== "linux") return;
451
- const header = asOptionalRecord(asOptionalRecord(process.report?.getReport())?.header);
452
- const glibc = typeof header?.glibcVersionRuntime === "string" ? header.glibcVersionRuntime : "";
453
- if (!glibc) throw new UnsupportedLlamaServerHostError("The verified Ubuntu llama-server build requires glibc and cannot run on musl/Alpine. Install llama-server manually for this host and configure its absolute path.");
454
- const minimum = asset.arch === "arm64" ? "2.38" : "2.34";
455
- if (compareVersion(glibc, minimum) < 0) throw new UnsupportedLlamaServerHostError(`The verified llama-server build requires glibc ${minimum}+ on Linux ${asset.arch}; this host has ${glibc}. Install a compatible llama-server manually and configure its absolute path.`);
456
- }
457
- const MACOS_MINIMUM = "13.3";
458
- async function assertSupportedMacosRuntime(asset, signal, cause) {
459
- if (asset.platform !== "darwin") return;
460
- const version = await runServerCommand("/usr/bin/sw_vers", ["-productVersion"], signal).catch(() => {
461
- signal?.throwIfAborted();
462
- return "";
463
- });
464
- if (!/^\d+\.\d+(?:\.\d+)?$/u.test(version) || compareVersion(version, MACOS_MINIMUM) >= 0) return;
465
- throw new UnsupportedLlamaServerHostError(`The verified llama-server ${LLAMA_SERVER_RELEASE} build requires macOS ${MACOS_MINIMUM}+; this Mac runs macOS ${version}. Build llama-server for this Mac and set models.providers.llama-cpp.localService.command to its absolute path, or use a remote model or embedding provider.`, cause === void 0 ? void 0 : { cause });
466
- }
467
- function assetUrl(asset) {
468
- return asset.url ?? `https://github.com/ggml-org/llama.cpp/releases/download/b10809/${asset.name}`;
469
- }
470
- const verifiedFiles = /* @__PURE__ */ new Map();
471
- const VERIFIED_FILE_LIMIT = 16;
472
- function fileIdentity(stat) {
473
- return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
474
- }
475
- function rememberVerifiedFile(filePath, stat, sha256) {
476
- verifiedFiles.delete(filePath);
477
- verifiedFiles.set(filePath, {
478
- identity: fileIdentity(stat),
479
- sha256
480
- });
481
- pruneMapToMaxSize(verifiedFiles, VERIFIED_FILE_LIMIT);
482
- }
483
- async function sha256File$1(filePath, signal) {
484
- signal?.throwIfAborted();
485
- try {
486
- const identity = fileIdentity(await fs.stat(filePath, { bigint: true }));
487
- const verified = verifiedFiles.get(filePath);
488
- if (verified?.identity === identity) return verified.sha256;
489
- verifiedFiles.delete(filePath);
490
- const handle = await fs.open(filePath, "r");
491
- try {
492
- const before = fileIdentity(await handle.stat({ bigint: true }));
493
- const { digest: sha256 } = await sha256File(handle, { signal });
494
- const after = await handle.stat({ bigint: true });
495
- if (before !== fileIdentity(after) || before !== fileIdentity(await fs.stat(filePath, { bigint: true }))) throw new Error(`File changed during integrity verification: ${filePath}. Retry setup.`);
496
- rememberVerifiedFile(filePath, after, sha256);
497
- return sha256;
498
- } finally {
499
- await handle.close();
500
- }
501
- } catch (error) {
502
- verifiedFiles.delete(filePath);
503
- throw error;
504
- }
505
- }
506
- function readResponseSha256(response) {
507
- for (const name of ["x-checksum-sha256", "x-linked-etag"]) {
508
- const value = response.headers.get(name)?.replace(/^W\//u, "").replaceAll("\"", "").trim();
509
- if (value && /^[a-f\d]{64}$/iu.test(value)) return value.toLowerCase();
510
- }
511
- const encoded = response.headers.get("digest")?.match(/(?:^|,)\s*sha-256=([^,\s]+)/iu)?.[1];
512
- return encoded ? Buffer.from(encoded, "base64").toString("hex") : void 0;
513
- }
514
- async function downloadVerifiedFile(params) {
515
- const partialPath = `${params.destination}.partial-${randomUUID()}`;
516
- await fs.mkdir(path.dirname(params.destination), { recursive: true });
517
- const { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } = await import("openclaw/plugin-sdk/ssrf-runtime");
518
- try {
519
- const { response, release } = await fetchWithSsrFGuard({
520
- url: params.url,
521
- signal: params.signal,
522
- timeoutMs: DOWNLOAD_TIMEOUT_MS,
523
- policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(params.url),
524
- requireHttps: true,
525
- auditContext: "llama-cpp-download"
526
- });
527
- try {
528
- if (!response.ok || !response.body) throw new Error(`download failed: HTTP ${response.status} ${response.statusText}`);
529
- const expectedSha256 = params.expectedSha256 ?? readResponseSha256(response);
530
- 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");
531
- const contentLength = Number(response.headers.get("content-length"));
532
- const totalSize = params.expectedSize ?? (Number.isFinite(contentLength) && contentLength > 0 ? contentLength : 0);
533
- const handle = await fs.open(partialPath, "wx", 384);
534
- const hash = createHash("sha256");
535
- let downloadedSize = 0;
536
- let previousSize = 0;
537
- let previousAt = Date.now();
538
- let rollingBytesPerSecond = 0;
539
- try {
540
- for await (const value of response.body.values({ preventCancel: true })) {
541
- const chunk = Buffer.from(value);
542
- await handle.writeFile(chunk);
543
- hash.update(chunk);
544
- downloadedSize += chunk.byteLength;
545
- const now = Date.now();
546
- if (now > previousAt) {
547
- const currentRate = (downloadedSize - previousSize) * 1e3 / (now - previousAt);
548
- rollingBytesPerSecond = rollingBytesPerSecond === 0 ? currentRate : rollingBytesPerSecond * .75 + currentRate * .25;
549
- previousSize = downloadedSize;
550
- previousAt = now;
551
- }
552
- params.onProgress?.({
553
- downloadedSize,
554
- totalSize,
555
- bytesPerSecond: rollingBytesPerSecond
556
- });
557
- }
558
- if (params.expectedSize && downloadedSize !== params.expectedSize) throw new Error(`download size mismatch: expected ${params.expectedSize}, got ${downloadedSize}`);
559
- const actualSha256 = hash.digest("hex");
560
- if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
561
- const completed = await handle.stat({ bigint: true });
562
- params.signal?.throwIfAborted();
563
- await fs.rename(partialPath, params.destination);
564
- const published = await handle.stat({ bigint: true });
565
- if (completed.size === published.size && completed.mtimeNs === published.mtimeNs) rememberVerifiedFile(params.destination, published, actualSha256);
566
- } finally {
567
- await handle.close();
568
- }
569
- } finally {
570
- await release();
571
- }
572
- } finally {
573
- await fs.rm(partialPath, { force: true }).catch(() => void 0);
574
- }
575
- }
576
- async function runServerCommand(command, args, signal, timeoutMs = PROBE_TIMEOUT_MS) {
577
- return await new Promise((resolve, reject) => {
578
- execFile(command, args, {
579
- timeout: timeoutMs,
580
- signal,
581
- windowsHide: true
582
- }, (error, stdout, stderr) => {
583
- if (error) reject(new Error(error.message, { cause: error }));
584
- else resolve(`${stdout}${stderr}`.trim());
585
- });
586
- });
587
- }
588
- function formatRuntimeDependencyError(error) {
589
- const detail = error instanceof Error ? error.message : String(error);
590
- if (process.platform === "linux") return new Error(`The verified llama-server build could not start. Install the OpenMP runtime (for example libgomp1 on Debian/Ubuntu or libgomp on Fedora), then rerun llama.cpp setup. Detail: ${detail}`, { cause: error });
591
- if (process.platform === "win32") return new Error(`The verified llama-server build could not start with its app-local Visual C++ runtime. Rerun llama.cpp setup to reinstall it, or configure a compatible llama-server manually. Detail: ${detail}`, { cause: error });
592
- return new Error(`The verified llama-server build could not start: ${detail}`, { cause: error });
593
- }
594
- async function queryServerVersion(command, signal) {
595
- try {
596
- return await runServerCommand(command, ["--version"], signal, VERSION_TIMEOUT_MS);
597
- } catch (error) {
598
- signal?.throwIfAborted();
599
- throw formatRuntimeDependencyError(error);
600
- }
601
- }
602
- function validateServerVersionOutput(command, version) {
603
- const match = (version.split(/\r?\n/u, 1)[0]?.trim() ?? "").match(/^version: .+ \(build (\d+), commit ([a-f\d]{9})\)$/u);
604
- const build = match?.[1] ? Number(match[1]) : void 0;
605
- const commit = match?.[2];
606
- 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"}`);
607
- }
608
- async function validateCudaServer(command, asset, signal) {
609
- if (asset.backend === "cuda") {
610
- const devices = await runServerCommand(command, ["--list-devices"], signal);
611
- 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.");
612
- }
613
- }
614
- async function validateInstalledServer(command, asset, signal) {
615
- validateServerVersionOutput(command, await queryServerVersion(command, signal));
616
- await validateCudaServer(command, asset, signal);
617
- }
618
- async function stageLlamaServerDependency(params) {
619
- const { dependency, extractDir, extractedRoot, index, options } = params;
620
- options.signal?.throwIfAborted();
621
- const dependencyArchive = path.join(extractDir, dependency.name);
622
- await downloadVerifiedFile({
623
- url: assetUrl(dependency),
624
- destination: dependencyArchive,
625
- expectedSha256: dependency.sha256,
626
- expectedSize: dependency.archive === "vc-redist" ? dependency.size : void 0,
627
- signal: options.signal,
628
- onProgress: options.onProgress
629
- });
630
- const dependencyExtractDir = path.join(extractDir, `dependency-${index}`);
631
- await fs.mkdir(dependencyExtractDir);
632
- const dependencyRoot = dependency.archive === "vc-redist" ? await extractWindowsVcRuntime({
633
- bundlePath: dependencyArchive,
634
- destDir: dependencyExtractDir,
635
- asset: dependency,
636
- signal: options.signal
637
- }) : await extractLlamaServerDependencyArchive({
638
- archivePath: dependencyArchive,
639
- destDir: dependencyExtractDir,
640
- asset: dependency
641
- });
642
- for (const file of dependencyFiles(dependency)) await fs.copyFile(path.join(dependencyRoot, file), path.join(extractedRoot, file), fs$1.constants.COPYFILE_EXCL);
643
- }
644
- function formatVcRuntimeFallbackError(startupError, fallbackError) {
645
- const startupDetail = startupError instanceof Error ? startupError.message : String(startupError);
646
- const fallbackDetail = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);
647
- return new Error(`The extracted llama-server could not start with the installed Windows runtime, and its app-local Visual C++ runtime fallback did not restore it. Initial startup detail: ${startupDetail} Fallback detail: ${fallbackDetail}`, { cause: fallbackError });
648
- }
649
- async function installLlamaServer(asset, options) {
650
- options.signal?.throwIfAborted();
651
- assertSupportedLinuxRuntime(asset);
652
- const { installDir, command } = resolveManagedLlamaServerPaths(asset);
653
- if (await fs.stat(command).then((stat) => stat.isFile()).catch(() => false)) {
654
- try {
655
- await validateInstalledServer(command, asset, options.signal);
656
- } catch (error) {
657
- await assertSupportedMacosRuntime(asset, options.signal, error);
658
- throw error;
659
- }
660
- return command;
661
- }
662
- await assertSupportedMacosRuntime(asset, options.signal);
663
- const dataDir = resolveLlamaCppDataDir();
664
- const archivePath = path.join(dataDir, `.download-${randomUUID()}-${asset.name}`);
665
- const extractDir = path.join(dataDir, `.extract-${randomUUID()}`);
666
- await fs.mkdir(dataDir, { recursive: true });
667
- try {
668
- await downloadVerifiedFile({
669
- url: assetUrl(asset),
670
- destination: archivePath,
671
- expectedSha256: asset.sha256,
672
- signal: options.signal,
673
- onProgress: options.onProgress
674
- });
675
- const serverExtractDir = path.join(extractDir, "server");
676
- await fs.mkdir(serverExtractDir, { recursive: true });
677
- const extractedCommand = await extractLlamaServerArchive({
678
- archivePath,
679
- destDir: serverExtractDir,
680
- asset
681
- });
682
- const extractedRoot = path.dirname(extractedCommand);
683
- const dependencies = asset.dependencies ?? [];
684
- const windowsRuntimeDependencies = [];
685
- for (const [index, dependency] of dependencies.entries()) if (dependency.archive === "vc-redist") windowsRuntimeDependencies.push({
686
- dependency,
687
- index
688
- });
689
- else await stageLlamaServerDependency({
690
- dependency,
691
- index,
692
- extractDir,
693
- extractedRoot,
694
- options
695
- });
696
- options.signal?.throwIfAborted();
697
- await fs.chmod(extractedCommand, 493);
698
- if (windowsRuntimeDependencies.length > 0) {
699
- let version;
700
- try {
701
- version = await queryServerVersion(extractedCommand, options.signal);
702
- } catch (startupError) {
703
- options.signal?.throwIfAborted();
704
- try {
705
- for (const { dependency, index } of windowsRuntimeDependencies) await stageLlamaServerDependency({
706
- dependency,
707
- index,
708
- extractDir,
709
- extractedRoot,
710
- options
711
- });
712
- } catch (stagingError) {
713
- options.signal?.throwIfAborted();
714
- throw formatVcRuntimeFallbackError(startupError, stagingError);
715
- }
716
- try {
717
- version = await queryServerVersion(extractedCommand, options.signal);
718
- } catch (retryError) {
719
- options.signal?.throwIfAborted();
720
- throw formatVcRuntimeFallbackError(startupError, retryError);
721
- }
722
- }
723
- validateServerVersionOutput(extractedCommand, version);
724
- await validateCudaServer(extractedCommand, asset, options.signal);
725
- } else await validateInstalledServer(extractedCommand, asset, options.signal);
726
- await fs.mkdir(path.dirname(installDir), { recursive: true });
727
- options.signal?.throwIfAborted();
728
- await fs.rm(installDir, {
729
- recursive: true,
730
- force: true
731
- });
732
- await fs.rename(extractedRoot, installDir);
733
- await validateInstalledServer(command, asset, options.signal);
734
- return command;
735
- } finally {
736
- await Promise.all([fs.rm(archivePath, { force: true }), fs.rm(extractDir, {
737
- recursive: true,
738
- force: true
739
- })]);
740
- }
741
- }
742
- function dependencyFiles(dependency) {
743
- return dependency.archive === "vc-redist" ? dependency.files.map((file) => file.target) : dependency.files;
744
- }
745
- async function ensureLlamaServerInstalled(options = {}) {
746
- options.signal?.throwIfAborted();
747
- const asset = options.asset ?? selectLlamaServerAsset();
748
- const key = resolveManagedLlamaServerPaths(asset).command;
749
- const previous = installationPromises.get(key);
750
- const pending = Promise.resolve(previous).catch(() => void 0).then(() => installLlamaServer(asset, options)).finally(() => {
751
- if (installationPromises.get(key) === pending) installationPromises.delete(key);
752
- });
753
- installationPromises.set(key, pending);
754
- return {
755
- command: previous && options.signal ? await new Promise((resolve, reject) => {
756
- const signal = options.signal;
757
- const onAbort = () => reject(toErrorObject(signal?.reason, "Installation cancelled"));
758
- signal?.addEventListener("abort", onAbort, { once: true });
759
- pending.then(resolve, reject).finally(() => signal?.removeEventListener("abort", onAbort));
760
- if (signal?.aborted) onAbort();
761
- }) : await pending,
762
- asset
763
- };
764
- }
765
- //#endregion
766
- //#region extensions/llama-cpp/src/llama-server-preset.ts
767
- function assertIniValue(value, label) {
768
- if (/\r|\n/u.test(value)) throw new Error(`${label} cannot contain a newline`);
769
- return value;
770
- }
771
- function normalizePresetName(name) {
772
- const colon = name.lastIndexOf(":");
773
- if (colon < 0) return name;
774
- const tag = name.slice(colon + 1);
775
- const quantization = /[-.]([a-zA-Z0-9_]+)$/u.exec(tag)?.[1] ?? tag;
776
- return name.slice(0, colon + 1) + quantization.replace(/[a-z]/g, (char) => char.toUpperCase());
777
- }
778
- function readModelSections(contents) {
779
- const headers = [...contents.matchAll(/(?<![^\r\n])\[[ \t]*([^\]]+)\][ \t]*(?:[;#][^\r\n]*)?(?:\r\n|\n|\r|(?![\s\S]))/g)];
780
- return {
781
- header: contents.slice(0, headers[0]?.index ?? contents.length),
782
- sections: new Map(headers.map((match, index) => [match[1], contents.slice(match.index, headers[index + 1]?.index ?? contents.length)]))
783
- };
784
- }
785
- const PRESET_KEY_ALIASES = {
786
- m: "model",
787
- LLAMA_ARG_MODEL: "model",
788
- c: "ctx-size",
789
- LLAMA_ARG_CTX_SIZE: "ctx-size",
790
- n: "n-predict",
791
- predict: "n-predict",
792
- LLAMA_ARG_N_PREDICT: "n-predict",
793
- "no-jinja": "jinja",
794
- LLAMA_ARG_JINJA: "jinja",
795
- ub: "ubatch-size",
796
- LLAMA_ARG_UBATCH: "ubatch-size",
797
- embeddings: "embedding",
798
- LLAMA_ARG_EMBEDDINGS: "embedding",
799
- np: "parallel",
800
- LLAMA_ARG_N_PARALLEL: "parallel",
801
- LLAMA_ARG_KV_UNIFIED_PER_SLOT: "kv-unified-per-slot"
802
- };
803
- const PRESET_SETTING_PATTERN = /(?<![^\r\n])([a-zA-Z_][a-zA-Z0-9_.-]*)([ \t]*=[ \t]*)([^\r\n]*?)([ \t]*(?:[;#][^\r\n]*)?)(\r\n|\n|\r|(?![\s\S]))/g;
804
- function readSettingKeys(section) {
805
- return new Set([...(section ?? "").matchAll(PRESET_SETTING_PATTERN)].map(([, key = ""]) => PRESET_KEY_ALIASES[key] ?? key));
806
- }
807
- function readServiceSettingKeys(service) {
808
- const caseInsensitiveEnv = process.platform === "win32";
809
- const keys = [...Object.entries(service?.env ?? {}).filter(([, value]) => value !== void 0).map(([key]) => caseInsensitiveEnv ? key.toUpperCase() : key).filter((key) => key.startsWith("LLAMA_ARG_")), ...(service?.args ?? []).filter((arg) => arg.startsWith("-")).map((arg) => arg.startsWith("--") ? arg.slice(2).replaceAll("_", "-") : arg.slice(1))];
810
- return new Set(keys.map((key) => PRESET_KEY_ALIASES[key] ?? key));
811
- }
812
- function updateModelSection(sections, id, values, newline) {
813
- assertIniValue(id, "llama.cpp model id");
814
- if (id.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
815
- const name = [...sections.keys()].filter((candidate) => normalizePresetName(candidate) === normalizePresetName(id)).toSorted((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right))).at(-1) ?? id;
816
- const pending = new Set(Object.keys(values));
817
- let contents = (sections.get(name) ?? `[${id}]${newline}`).replace(PRESET_SETTING_PATTERN, (line, key, separator, _value, comment, ending) => {
818
- const canonical = PRESET_KEY_ALIASES[key] ?? key;
819
- if (!Object.hasOwn(values, canonical)) return line;
820
- pending.delete(canonical);
821
- return `${canonical}${separator}${values[canonical]}${comment}${ending}`;
822
- });
823
- for (const key of pending) contents += `${/[\r\n]$/u.test(contents) ? "" : newline}${key} = ${values[key]}${newline}`;
824
- sections.set(name, contents);
825
- }
826
- function buildLlamaServerPreset(existing, params) {
827
- const newline = existing?.match(/\r\n|\n|\r/u)?.[0] ?? "\n";
828
- const { header, sections } = readModelSections(existing ?? "version = 1\n\n");
829
- const configuredIds = params.configuredChatModelIds ? new Set(params.configuredChatModelIds.map(normalizePresetName)) : void 0;
830
- 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);
831
- if (params.chatModel.mode === "configure") updateModelSection(sections, params.chatModel.id, {
832
- model: assertIniValue(params.chatModel.path, "llama.cpp model path"),
833
- "ctx-size": String(params.chatModel.contextSize ?? 65536),
834
- "n-predict": String(params.chatModel.maxTokens ?? 2048),
835
- jinja: "true"
836
- }, newline);
837
- const embeddingPath = params.embeddingModelPath ?? (!sections.has("embeddinggemma-300m-qat-q8_0") ? params.defaultEmbeddingModelPath : void 0);
838
- if (embeddingPath) {
839
- const configured = /* @__PURE__ */ new Set([
840
- ...readSettingKeys(sections.get(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID)),
841
- ...readSettingKeys(sections.get("*")),
842
- ...readServiceSettingKeys(params.serviceSettings)
843
- ]);
844
- const defaults = {
845
- parallel: "1",
846
- "ctx-size": String(DEFAULT_LLAMA_CPP_EMBEDDING_CONTEXT_SIZE),
847
- "ubatch-size": String(DEFAULT_LLAMA_CPP_EMBEDDING_CONTEXT_SIZE)
848
- };
849
- if (configured.has("parallel") || configured.has("kv-unified-per-slot")) delete defaults["ctx-size"];
850
- for (const key of configured) delete defaults[key];
851
- updateModelSection(sections, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, {
852
- model: assertIniValue(embeddingPath, "llama.cpp embedding model path"),
853
- embedding: "true",
854
- ...defaults
855
- }, newline);
856
- }
857
- const embeddingSection = sections.get(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID);
858
- if (!embeddingSection) throw new Error("llama.cpp embedding model path is required for a new managed preset");
859
- sections.delete(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID);
860
- const orderedSections = [...[...sections].toSorted(([left], [right]) => Number(left > right) - Number(left < right)).map(([, section]) => section), embeddingSection];
861
- return header + (header && !/[\r\n]$/u.test(header) ? newline : "") + orderedSections.map((section) => section.replace(/[\r\n]+$/u, "")).join(newline + newline) + newline;
862
- }
863
- //#endregion
864
- //#region extensions/llama-cpp/src/managed-server-orphans.ts
865
- const log = createSubsystemLogger("llama-cpp");
866
- const recoveries = /* @__PURE__ */ new Map();
867
- function readUniqueArgument(argv, name) {
868
- const values = argv.flatMap((argument, index) => {
869
- if (argument === name) {
870
- const value = argv[index + 1];
871
- return value === void 0 ? [] : [value];
872
- }
873
- return argument.startsWith(`${name}=`) ? [argument.slice(name.length + 1)] : [];
874
- });
875
- return values.length === 1 ? values[0] : void 0;
876
- }
877
- /** A new host process recovers once; in-process restarts retain that host's children. */
878
- async function recoverManagedLlamaServer(params) {
879
- params.signal?.throwIfAborted();
880
- if (!findManagedLlamaServerAsset(params.command)) return;
881
- const args = params.args ?? [];
882
- const preset = readUniqueArgument(args, "--models-preset");
883
- const host = readUniqueArgument(args, "--host");
884
- if (!preset || !host || readUniqueArgument(args, "--port") !== String(params.port)) return;
885
- const required = /* @__PURE__ */ new Map([
886
- ["--port", String(params.port)],
887
- ["--models-preset", preset],
888
- ["--host", host]
889
- ]);
890
- const cwd = !path.isAbsolute(preset) ? path.resolve(params.cwd ?? process.cwd()) : void 0;
891
- const key = JSON.stringify([
892
- params.command,
893
- [...required],
894
- cwd
895
- ]);
896
- let recovery = recoveries.get(key);
897
- if (!recovery) {
898
- recovery = (async () => {
899
- const { reapOrphanedProcesses } = await import("openclaw/plugin-sdk/process-runtime");
900
- if (typeof reapOrphanedProcesses !== "function") return;
901
- await reapOrphanedProcesses({
902
- command: params.command,
903
- cwd,
904
- matchesArguments: (argv) => [...required].every(([name, value]) => readUniqueArgument(argv, name) === value),
905
- signal: params.signal,
906
- onReap: (pid) => log.info(`reaping orphaned managed llama-server: pid=${pid} port=${params.port}`)
907
- });
908
- })().catch((error) => {
909
- recoveries.delete(key);
910
- throw error;
911
- });
912
- recoveries.set(key, recovery);
913
- }
914
- await recovery;
915
- params.signal?.throwIfAborted();
916
- }
917
- //#endregion
918
- //#region extensions/llama-cpp/src/hardware.ts
919
- const GIB$1 = 1024 ** 3;
920
- const MIB = 1024 ** 2;
921
- async function runHardwareProbe(command, args, signal) {
922
- try {
923
- return await new Promise((resolve, reject) => {
924
- execFile(command, args, {
925
- encoding: "utf8",
926
- timeout: 3e3,
927
- maxBuffer: 65536,
928
- signal
929
- }, (error, stdout) => error ? reject(error) : resolve(stdout));
930
- });
931
- } catch {
932
- signal?.throwIfAborted();
933
- return;
934
- }
935
- }
936
- async function readAvailableMemory(platform, signal) {
937
- if (platform === "linux") {
938
- const meminfo = await fs.readFile("/proc/meminfo", "utf8").catch(() => "");
939
- const available = /^MemAvailable:\s+(\d+)\s+kB$/mu.exec(meminfo)?.[1];
940
- if (available) return Number(available) * 1024;
941
- }
942
- if (platform === "darwin") {
943
- const vmstat = await runHardwareProbe("/usr/bin/vm_stat", [], signal);
944
- const pageSize = /page size of (\d+) bytes/u.exec(vmstat ?? "")?.[1];
945
- const free = /^Pages free:\s+(\d+)\./mu.exec(vmstat ?? "")?.[1];
946
- const inactive = /^Pages inactive:\s+(\d+)\./mu.exec(vmstat ?? "")?.[1];
947
- if (pageSize && free && inactive) return (Number(free) + Number(inactive)) * Number(pageSize);
948
- }
949
- return os.freemem();
950
- }
951
- async function readAvailableDisk(cacheDir, platform, signal) {
952
- let directory = path.resolve(cacheDir);
953
- while (true) try {
954
- const [capacity, stat] = await Promise.all([fs.statfs(directory), fs.stat(directory)]);
955
- let capacityGroup = `device:${stat.dev}`;
956
- if (platform === "linux" && ![
957
- 61267,
958
- 1481003842,
959
- 4076150800
960
- ].includes(capacity.type)) capacityGroup = void 0;
961
- if (platform === "darwin") {
962
- const disk = /^\/dev\/(disk\d+(?:s\d+)*)\s/mu.exec(await runHardwareProbe("/bin/df", ["-P", directory], signal) ?? "")?.[1];
963
- const info = disk ? await runHardwareProbe("/usr/sbin/diskutil", [
964
- "info",
965
- "-plist",
966
- disk
967
- ], signal) : void 0;
968
- const container = /<key>APFSContainerReference<\/key>\s*<string>(disk\d+)<\/string>/u.exec(info ?? "")?.[1];
969
- const filesystem = /<key>FilesystemType<\/key>\s*<string>([^<]+)<\/string>/u.exec(info ?? "")?.[1];
970
- capacityGroup = container ? `apfs:${container}` : filesystem && filesystem !== "apfs" ? capacityGroup : void 0;
971
- }
972
- return {
973
- availableBytes: capacity.bavail * capacity.bsize,
974
- capacityGroup
975
- };
976
- } catch (error) {
977
- signal?.throwIfAborted();
978
- const code = error instanceof Error && "code" in error ? error.code : void 0;
979
- const parent = path.dirname(directory);
980
- if (code !== "ENOENT" && code !== "ENOTDIR" || parent === directory) return;
981
- directory = parent;
982
- }
983
- }
984
- async function readAccelerator(platform, arch, signal) {
985
- if (platform === "darwin" && arch === "arm64") return { kind: "metal" };
986
- if (platform !== "linux" && platform !== "win32") return {
987
- kind: "cpu",
988
- reason: "No managed GPU backend is available for this host."
989
- };
990
- 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) => {
991
- const fields = line.split(",").map((field) => field.trim());
992
- const [total, available, driverVersion, compute] = fields.slice(-4);
993
- const name = fields.slice(0, -4).join(", ");
994
- const totalMemoryBytes = Number(total) * MIB;
995
- const availableMemoryBytes = Number(available) * MIB;
996
- const computeCapability = Number(compute);
997
- if (!name || !driverVersion || !/^\d+(?:\.\d+)+$/u.test(driverVersion) || !Number.isFinite(totalMemoryBytes) || !Number.isFinite(availableMemoryBytes) || totalMemoryBytes <= 0 || availableMemoryBytes < 0 || availableMemoryBytes > totalMemoryBytes) return [];
998
- return [{
999
- name,
1000
- totalMemoryBytes,
1001
- availableMemoryBytes,
1002
- driverVersion,
1003
- ...Number.isFinite(computeCapability) && computeCapability > 0 ? { computeCapability } : {}
1004
- }];
1005
- });
1006
- return devices.length > 0 ? {
1007
- kind: "cuda",
1008
- devices
1009
- } : {
1010
- kind: "cpu",
1011
- reason: "nvidia-smi did not report a usable NVIDIA GPU."
1012
- };
1013
- }
1014
- /** Read the Gateway host once during setup; never probe on inference requests. */
1015
- async function detectLlamaCppHardware(params) {
1016
- params.signal?.throwIfAborted();
1017
- const platform = os.platform();
1018
- const arch = os.arch();
1019
- const hostMemoryBytes = os.totalmem();
1020
- const constrainedMemory = process.constrainedMemory();
1021
- const constrained = constrainedMemory > 0 && constrainedMemory < hostMemoryBytes;
1022
- const totalMemoryBytes = constrained ? constrainedMemory : hostMemoryBytes;
1023
- const [availableMemory, modelDisk, runtimeDisk, accelerator] = await Promise.all([
1024
- readAvailableMemory(platform, params.signal),
1025
- readAvailableDisk(params.cacheDir, platform, params.signal),
1026
- readAvailableDisk(resolveLlamaCppDataDir(), platform, params.signal),
1027
- readAccelerator(platform, arch, params.signal)
1028
- ]);
1029
- params.signal?.throwIfAborted();
1030
- return {
1031
- platform,
1032
- arch,
1033
- totalMemoryBytes,
1034
- availableMemoryBytes: Math.min(totalMemoryBytes, availableMemory, constrained ? process.availableMemory() : totalMemoryBytes),
1035
- availableDiskBytes: modelDisk?.availableBytes,
1036
- availableRuntimeDiskBytes: runtimeDisk?.availableBytes,
1037
- sharedDisk: !modelDisk?.capacityGroup || !runtimeDisk?.capacityGroup || modelDisk.capacityGroup === runtimeDisk.capacityGroup,
1038
- accelerator
1039
- };
1040
- }
1041
- function formatLlamaCppMemory(bytes) {
1042
- return `${(bytes / GIB$1).toFixed(1).replace(/\.0$/u, "")} GiB`;
1043
- }
1044
- //#endregion
1045
- //#region extensions/llama-cpp/src/model-catalog.ts
1046
- const GIB = 1024 ** 3;
1047
- function modelRecipe(params) {
1048
- const source = params.source ?? `hf:${params.repository}/${params.file}#${params.revision}`;
1049
- return {
1050
- model: buildLlamaCppModel({
1051
- ...params,
1052
- source
1053
- }),
1054
- sizeBytes: params.sizeBytes,
1055
- memoryBytes: params.memoryGiB * GIB,
1056
- minimumSystemMemoryBytes: params.minimumSystemGiB * GIB,
1057
- requiresAcceleration: params.requiresAcceleration ?? false,
1058
- artifact: {
1059
- fileName: params.cacheFile ?? `hf_${params.repository.replaceAll("/", "_")}_${params.revision}_${params.file}`,
1060
- url: `https://huggingface.co/${params.repository}/resolve/${params.revision}/${params.file}?download=true`,
1061
- expectedSize: params.sizeBytes,
1062
- expectedSha256: params.sha256
1063
- }
1064
- };
1065
- }
1066
- const LLAMA_CPP_MODEL_RECIPES = [
1067
- modelRecipe({
1068
- id: "qwen3.8-27b-ud-q4_k_m",
1069
- name: "Qwen3.8 27B (UD-Q4_K_M)",
1070
- repository: "unsloth/Qwen3.8-27B-GGUF",
1071
- file: "Qwen3.8-27B-UD-Q4_K_M.gguf",
1072
- revision: "4ca720788d1e01f1bff70c033e0d0028fd02e502",
1073
- sha256: "322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482",
1074
- sizeBytes: 16464440224,
1075
- memoryGiB: 22,
1076
- minimumSystemGiB: 32,
1077
- requiresAcceleration: true,
1078
- reasoning: true,
1079
- maxTokens: 16384
1080
- }),
1081
- modelRecipe({
1082
- id: "muse-glimmer-30b-q4_k_m",
1083
- name: "Muse Glimmer 30B (Q4_K_M)",
1084
- repository: "meta-models/Muse-Glimmer-30B-GGUF",
1085
- file: "Muse-Glimmer-30B-KQuant-17GB-Q4_K_M.gguf",
1086
- revision: "70bf1b61ac09f91b24d39038091b41c582bc5d7a",
1087
- sha256: "4cc57c0f51040a226e5a72cc47b7613f7772950e460a665f7083de89f183f60e",
1088
- sizeBytes: 16756683904,
1089
- memoryGiB: 20,
1090
- minimumSystemGiB: 32,
1091
- requiresAcceleration: true,
1092
- reasoning: true,
1093
- maxTokens: 16384
1094
- }),
1095
- modelRecipe({
1096
- id: "gemma-4-26b-a4b-it-ud-q4_k_m",
1097
- name: "Gemma 4 26B A4B (UD-Q4_K_M)",
1098
- repository: "unsloth/gemma-4-26B-A4B-it-GGUF",
1099
- file: "gemma-4-26B-A4B-it-UD-Q4_K_M.gguf",
1100
- revision: "c099eb48e663fd284577b04978a94ffccb261841",
1101
- sha256: "f2c28b3dc4776931ac6f879e11f203dec637ea0f14267a86ec8f6165f63f293f",
1102
- sizeBytes: 16947541728,
1103
- memoryGiB: 22,
1104
- minimumSystemGiB: 32,
1105
- requiresAcceleration: true
1106
- }),
1107
- modelRecipe({
1108
- id: "gemma-4-12b-it-q4_k_m",
1109
- name: "Gemma 4 12B (Q4_K_M)",
1110
- repository: "unsloth/gemma-4-12b-it-GGUF",
1111
- file: "gemma-4-12b-it-Q4_K_M.gguf",
1112
- revision: "fc034cfff751157913579611efad8462ac1be606",
1113
- sha256: "0a270ec9fe6b34f4a0d33992b6135117b484ebc4766ab76b51d4ae8c457e4c42",
1114
- sizeBytes: 7121861440,
1115
- memoryGiB: 12,
1116
- minimumSystemGiB: 24,
1117
- requiresAcceleration: true,
1118
- reasoning: true,
1119
- maxTokens: 16384
1120
- }),
1121
- modelRecipe({
1122
- id: "qwen3.5-9b-q4_k_m",
1123
- name: "Qwen3.5 9B (Q4_K_M)",
1124
- repository: "unsloth/Qwen3.5-9B-GGUF",
1125
- file: "Qwen3.5-9B-Q4_K_M.gguf",
1126
- revision: "3885219b6810b007914f3a7950a8d1b469d598a5",
1127
- sha256: "03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8",
1128
- sizeBytes: 5680522464,
1129
- memoryGiB: 10,
1130
- minimumSystemGiB: 16,
1131
- reasoning: true,
1132
- maxTokens: 16384
1133
- }),
1134
- modelRecipe({
1135
- id: DEFAULT_LLAMA_CPP_MODEL_ID,
1136
- name: "Gemma 4 E4B (Q4_K_M)",
1137
- repository: "unsloth/gemma-4-E4B-it-GGUF",
1138
- file: "gemma-4-E4B-it-Q4_K_M.gguf",
1139
- revision: DEFAULT_LLAMA_CPP_MODEL_REVISION,
1140
- sha256: DEFAULT_LLAMA_CPP_MODEL_SHA256,
1141
- sizeBytes: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
1142
- memoryGiB: 10,
1143
- minimumSystemGiB: 16,
1144
- source: DEFAULT_LLAMA_CPP_MODEL_URI,
1145
- cacheFile: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE
1146
- }),
1147
- modelRecipe({
1148
- id: "qwen3.5-4b-q4_k_m",
1149
- name: "Qwen3.5 4B (Q4_K_M)",
1150
- repository: "unsloth/Qwen3.5-4B-GGUF",
1151
- file: "Qwen3.5-4B-Q4_K_M.gguf",
1152
- revision: "e87f176479d0855a907a41277aca2f8ee7a09523",
1153
- sha256: "00fe7986ff5f6b463e62455821146049db6f9313603938a70800d1fb69ef11a4",
1154
- sizeBytes: 2740937888,
1155
- memoryGiB: 6,
1156
- minimumSystemGiB: 8,
1157
- reasoning: true,
1158
- maxTokens: 16384
1159
- }),
1160
- modelRecipe({
1161
- id: "gemma-4-e2b-it-q4_k_m",
1162
- name: "Gemma 4 E2B (Q4_K_M)",
1163
- repository: "unsloth/gemma-4-E2B-it-GGUF",
1164
- file: "gemma-4-E2B-it-Q4_K_M.gguf",
1165
- revision: "0314792d7f1f7e229411f620751375812bb9faf2",
1166
- sha256: "740185b21d22ceb83a11c3aa62ad5842ef32c70f6096d756bbee85a1e4ec34b8",
1167
- sizeBytes: 3106738272,
1168
- memoryGiB: 6,
1169
- minimumSystemGiB: 8
1170
- })
1171
- ];
1172
- function resolveLlamaCppCatalogArtifact(source) {
1173
- return LLAMA_CPP_MODEL_RECIPES.find((recipe) => recipe.model.params?.modelPath === source)?.artifact;
1174
- }
1175
- function resolveLlamaCppModelCandidates(hardware, backend) {
1176
- const systemBudget = Math.min(hardware.availableMemoryBytes, hardware.totalMemoryBytes - Math.max(2 * GIB, hardware.totalMemoryBytes * .25));
1177
- 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;
1178
- const memoryBudgetBytes = backend === "cuda" ? Math.min(systemBudget, gpuBudget) : systemBudget;
1179
- return {
1180
- recipes: LLAMA_CPP_MODEL_RECIPES.filter((recipe) => (!recipe.requiresAcceleration || backend !== "cpu") && hardware.totalMemoryBytes >= recipe.minimumSystemMemoryBytes && memoryBudgetBytes >= recipe.memoryBytes),
1181
- memoryBudgetBytes
1182
- };
1183
- }
1184
- function recommendLlamaCppModel(hardware, backend, cached = {}) {
1185
- if (hardware.availableDiskBytes === void 0 || hardware.availableRuntimeDiskBytes === void 0) return {
1186
- kind: "unavailable",
1187
- reason: "Cannot measure free space in the model cache or runtime directory. Check their permissions and retry setup."
1188
- };
1189
- const { recipes: candidates, memoryBudgetBytes } = resolveLlamaCppModelCandidates(hardware, backend);
1190
- const runtimeDiskBytes = cached.runtime ? 0 : (backend === "cuda" ? 3 : 2) * GIB;
1191
- if (!hardware.sharedDisk && hardware.availableRuntimeDiskBytes < runtimeDiskBytes) return {
1192
- kind: "unavailable",
1193
- reason: "There is not enough free disk space in the runtime directory. Free space on that volume and retry setup."
1194
- };
1195
- const modelDiskBudget = hardware.sharedDisk ? Math.min(hardware.availableDiskBytes, hardware.availableRuntimeDiskBytes) - runtimeDiskBytes : hardware.availableDiskBytes;
1196
- for (const recipe of candidates) {
1197
- const modelDiskBytes = (cached.modelIds?.has(recipe.model.id) ? 0 : recipe.sizeBytes) + (cached.embedding ? 0 : DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES);
1198
- if (modelDiskBudget < modelDiskBytes) continue;
1199
- const placement = backend === "metal" ? "Metal unified memory" : backend === "cuda" ? "NVIDIA GPU memory" : "CPU memory";
1200
- return {
1201
- kind: "recommended",
1202
- recipe,
1203
- memoryBudgetBytes,
1204
- requiredDiskBytes: modelDiskBytes + runtimeDiskBytes,
1205
- reason: `${recipe.model.name} fits the ${formatLlamaCppMemory(memoryBudgetBytes)} ${placement} budget with a 64K context. Runtime verification checks the actual model before activation.`
1206
- };
1207
- }
1208
- return {
1209
- kind: "unavailable",
1210
- 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. For local memory search without a chat model, an embedding-only local server (about 0.3 GB for the default embedding model) can fit instead. Set memory.search.provider to "local" with openclaw config set memory.search.provider local, then re-run openclaw models auth login --provider llama-cpp --method local using the same profile for both commands.`
1211
- };
1212
- }
1213
- //#endregion
1214
- //#region extensions/llama-cpp/src/managed-server.ts
1215
- const modelPromises = /* @__PURE__ */ new Map();
1216
- const resolvedModelArtifacts = /* @__PURE__ */ new Map();
1217
- const presetState = {
1218
- appliedRevisions: /* @__PURE__ */ new Map(),
1219
- desiredRevisions: /* @__PURE__ */ new Map()
1220
- };
1221
- const runPresetTransition = createAsyncLock();
1222
- const LLAMA_CPP_PRESET_RELOAD_TIMEOUT_MS = 15e3;
1223
- function parseHuggingFaceSource(source) {
1224
- const [pathPart, revisionPart] = source.replace(/^(?:hf|huggingface):(?:\/\/)?/iu, "").split("#", 2);
1225
- const [user, repositoryWithTag, ...fileParts] = (pathPart ?? "").split("/");
1226
- const [repository, ...tagParts] = (repositoryWithTag ?? "").split(":");
1227
- if (!user || !repository) throw new Error(`Invalid Hugging Face model URI: ${source}`);
1228
- return {
1229
- user,
1230
- repository,
1231
- file: fileParts.length > 0 ? fileParts.join("/") : void 0,
1232
- revision: revisionPart || "main",
1233
- tag: tagParts.length > 0 ? tagParts.join(":") : void 0
1234
- };
1235
- }
1236
- async function resolveHuggingFaceArtifact(source, signal) {
1237
- const parsed = parseHuggingFaceSource(source);
1238
- let file = parsed.file;
1239
- let expectedSize;
1240
- if (!file) {
1241
- const tag = parsed.tag || "latest";
1242
- const manifestUrl = `https://huggingface.co/v2/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/manifests/${encodeURIComponent(tag)}`;
1243
- const { response, release } = await fetchWithSsrFGuard({
1244
- url: manifestUrl,
1245
- init: { headers: { "user-agent": "llama-cpp" } },
1246
- signal,
1247
- requireHttps: true,
1248
- policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(manifestUrl),
1249
- auditContext: "llama-cpp-model-resolve"
1250
- });
1251
- try {
1252
- if (!response.ok) throw new Error(`Cannot resolve ${source}: HTTP ${response.status}`);
1253
- const ggufFile = asOptionalRecord(asOptionalRecord(await readProviderJsonResponse(response, "llama.cpp Hugging Face manifest"))?.ggufFile);
1254
- file = typeof ggufFile?.rfilename === "string" ? ggufFile.rfilename : void 0;
1255
- expectedSize = typeof ggufFile?.size === "number" ? ggufFile.size : void 0;
1256
- if (!file) throw new Error(`Hugging Face did not return a GGUF file for ${source}`);
1257
- } finally {
1258
- await release();
1259
- }
1260
- }
1261
- const encodedFile = file.split("/").map(encodeURIComponent).join("/");
1262
- const url = `https://huggingface.co/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/resolve/${encodeURIComponent(parsed.revision)}/${encodedFile}?download=true`;
1263
- const fileInfoUrl = `https://huggingface.co/api/models/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/paths-info/${encodeURIComponent(parsed.revision)}`;
1264
- const { response: fileInfoResponse, release: releaseFileInfo } = await fetchWithSsrFGuard({
1265
- url: fileInfoUrl,
1266
- init: {
1267
- method: "POST",
1268
- headers: {
1269
- "content-type": "application/json",
1270
- "user-agent": "llama-cpp"
1271
- },
1272
- body: JSON.stringify({
1273
- paths: [file],
1274
- expand: false
1275
- })
1276
- },
1277
- signal,
1278
- requireHttps: true,
1279
- policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(fileInfoUrl),
1280
- auditContext: "llama-cpp-model-resolve"
1281
- });
1282
- let fileInfo;
1283
- try {
1284
- if (!fileInfoResponse.ok) throw new Error(`Cannot read Hugging Face integrity metadata for ${source}: HTTP ${fileInfoResponse.status}`);
1285
- fileInfo = await readProviderJsonResponse(fileInfoResponse, "llama.cpp Hugging Face file metadata");
1286
- } finally {
1287
- await releaseFileInfo();
1288
- }
1289
- const fileRow = Array.isArray(fileInfo) ? fileInfo.map((entry) => asOptionalRecord(entry)).find((entry) => entry?.path === file) : void 0;
1290
- const lfs = asOptionalRecord(fileRow?.lfs);
1291
- const expectedSha256 = typeof lfs?.oid === "string" && /^[a-f\d]{64}$/iu.test(lfs.oid) ? lfs.oid.toLowerCase() : void 0;
1292
- expectedSize = expectedSize ?? (typeof fileRow?.size === "number" ? fileRow.size : void 0);
1293
- if (!expectedSha256) throw new Error(`Hugging Face did not publish a SHA-256 LFS identity for ${source}`);
1294
- return {
1295
- fileName: `hf_${[
1296
- parsed.user,
1297
- parsed.repository,
1298
- parsed.revision === "main" ? "" : parsed.revision,
1299
- ...file.split("/")
1300
- ].filter(Boolean).join("_").replace(/[^a-z\d._-]+/giu, "_")}`,
1301
- url,
1302
- expectedSize,
1303
- expectedSha256
1304
- };
1305
- }
1306
- function defaultArtifact(source) {
1307
- const recipe = resolveLlamaCppCatalogArtifact(source);
1308
- if (recipe) return recipe;
1309
- if (source === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") return {
1310
- fileName: DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE,
1311
- 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`,
1312
- expectedSize: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES,
1313
- expectedSha256: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256
1314
- };
1315
- }
1316
- async function assertGguf(filePath) {
1317
- const handle = await fs.open(filePath, "r").catch((error) => {
1318
- 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 });
1319
- throw error;
1320
- });
1321
- try {
1322
- const header = Buffer.alloc(4);
1323
- const { bytesRead } = await handle.read(header, 0, header.length, 0);
1324
- if (bytesRead !== 4 || header.toString("ascii") !== "GGUF") throw new Error(`Model is not a GGUF file: ${filePath}`);
1325
- } finally {
1326
- await handle.close();
1327
- }
1328
- }
1329
- async function resolveModelArtifact(source, signal) {
1330
- const known = defaultArtifact(source);
1331
- if (known) return known;
1332
- if (/^(?:hf|huggingface):/iu.test(source)) return await resolveHuggingFaceArtifact(source, signal);
1333
- if (/^https:\/\//iu.test(source)) {
1334
- const url = new URL(source);
1335
- const fileName = path.basename(decodeURIComponent(url.pathname));
1336
- if (!fileName.toLowerCase().includes(".gguf")) throw new Error(`Remote model URL must name a GGUF file: ${source}`);
1337
- return {
1338
- fileName,
1339
- url: source
1340
- };
1341
- }
1342
- throw new Error(`Unsupported remote model URI: ${source}`);
1343
- }
1344
- async function resolveCachedModelArtifact(source, cacheDir, signal) {
1345
- const key = `${path.resolve(cacheDir)}\0${source}`;
1346
- const artifact = resolvedModelArtifacts.get(key) ?? await resolveModelArtifact(source, signal);
1347
- resolvedModelArtifacts.set(key, artifact);
1348
- return artifact;
1349
- }
1350
- async function resolveLlamaCppModelDownloadSize(source, cacheDir, signal) {
1351
- const artifact = await resolveCachedModelArtifact(source, cacheDir, signal);
1352
- if (artifact.expectedSize !== void 0) return artifact.expectedSize;
1353
- const result = await fetchWithSsrFGuard({
1354
- url: artifact.url,
1355
- init: { method: "HEAD" },
1356
- signal,
1357
- requireHttps: true,
1358
- policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(artifact.url),
1359
- auditContext: "llama-cpp-model-resolve"
1360
- }).catch(() => {
1361
- signal?.throwIfAborted();
1362
- });
1363
- if (!result) return;
1364
- const { response, release } = result;
1365
- try {
1366
- const size = response.ok ? Number(response.headers.get("content-length")) : 0;
1367
- return Number.isSafeInteger(size) && size > 0 ? size : void 0;
1368
- } finally {
1369
- await release();
1370
- }
1371
- }
1372
- async function ensureLlamaCppModel(params) {
1373
- const localSource = resolveHomePath(params.source);
1374
- if (!/^(?:hf|huggingface|https):/iu.test(localSource)) {
1375
- const localPath = path.isAbsolute(localSource) ? localSource : path.resolve(params.cacheDir, localSource);
1376
- await assertGguf(localPath);
1377
- return localPath;
1378
- }
1379
- const artifact = await resolveCachedModelArtifact(localSource, params.cacheDir, params.signal);
1380
- const destination = path.join(params.cacheDir, artifact.fileName);
1381
- const load = modelPromises.get(destination) ?? (async () => {
1382
- const exists = await fs.stat(destination).then((stat) => stat.isFile()).catch(() => false);
1383
- if (exists && artifact.expectedSha256 && await sha256File$1(destination, params.signal) === artifact.expectedSha256) return destination;
1384
- if (exists && !artifact.expectedSha256) {
1385
- await assertGguf(destination);
1386
- return destination;
1387
- }
1388
- if (!params.download) throw new Error(`Model is not cached at ${destination}`);
1389
- await downloadVerifiedFile({
1390
- url: artifact.url,
1391
- destination,
1392
- expectedSha256: artifact.expectedSha256,
1393
- expectedSize: artifact.expectedSize,
1394
- requireServerDigest: !artifact.expectedSha256,
1395
- signal: params.signal,
1396
- onProgress: params.onProgress
1397
- });
1398
- await assertGguf(destination);
1399
- return destination;
1400
- })();
1401
- modelPromises.set(destination, load);
1402
- try {
1403
- return await load;
1404
- } finally {
1405
- if (modelPromises.get(destination) === load) modelPromises.delete(destination);
1406
- }
1407
- }
1408
- async function writePreset(presetPath, contents) {
1409
- await fs.mkdir(path.dirname(presetPath), { recursive: true });
1410
- const temporary = `${presetPath}.tmp-${randomUUID()}`;
1411
- try {
1412
- await fs.writeFile(temporary, contents, { mode: 384 });
1413
- await fs.rename(temporary, presetPath);
1414
- } finally {
1415
- await fs.rm(temporary, { force: true });
1416
- }
1417
- }
1418
- async function updatePreset(presetPath, params) {
1419
- await runPresetTransition(async () => {
1420
- const existing = await fs.readFile(presetPath, "utf8").catch((error) => {
1421
- if (asOptionalRecord(error)?.code === "ENOENT") return;
1422
- throw error;
1423
- });
1424
- const next = buildLlamaServerPreset(existing, params);
1425
- if (next !== existing) await writePreset(presetPath, next);
1426
- if (params.reconcileOrigin) presetState.desiredRevisions.set(params.reconcileOrigin, `${presetPath}\0${next}`);
1427
- });
1428
- }
1429
- async function reconcileManagedLlamaServer(params) {
1430
- await runPresetTransition(async () => {
1431
- const origin = new URL(params.baseUrl).origin;
1432
- const revision = presetState.desiredRevisions.get(origin);
1433
- if (!revision || presetState.appliedRevisions.get(origin) === revision) return;
1434
- const { response, release } = await fetchConfiguredLocalOriginWithSsrFGuard({
1435
- url: `${origin}/models?reload=1`,
1436
- configuredLocalOriginBaseUrl: origin,
1437
- policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(origin),
1438
- signal: params.signal,
1439
- timeoutMs: LLAMA_CPP_PRESET_RELOAD_TIMEOUT_MS,
1440
- auditContext: "llama-server-preset-reload"
1441
- });
1442
- try {
1443
- if (!response.ok) throw new Error(`llama.cpp preset reload failed: HTTP ${response.status}`);
1444
- presetState.appliedRevisions.set(origin, revision);
1445
- } finally {
1446
- await release();
1447
- }
1448
- });
1449
- }
1450
- async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT) {
1451
- const tryPort = async (port) => await new Promise((resolve) => {
1452
- const server = net.createServer();
1453
- server.unref();
1454
- server.once("error", () => resolve(void 0));
1455
- server.listen(port, "127.0.0.1", () => {
1456
- const address = server.address();
1457
- const selected = typeof address === "object" && address ? address.port : void 0;
1458
- server.close(() => resolve(selected));
1459
- });
1460
- });
1461
- return await tryPort(preferred) ?? await tryPort(0) ?? Promise.reject(/* @__PURE__ */ new Error("No loopback port is available for llama-server"));
1462
- }
1463
- async function prepareManagedLlamaServer(params) {
1464
- params.signal?.throwIfAborted();
1465
- let command = params.localService?.command;
1466
- const asset = command === void 0 ? params.asset : findManagedLlamaServerAsset(command);
1467
- if (command !== void 0 && asset) try {
1468
- await fs.stat(command);
1469
- } catch (error) {
1470
- if (asOptionalRecord(error)?.code !== "ENOENT") throw error;
1471
- command = void 0;
1472
- }
1473
- command ??= (await ensureLlamaServerInstalled({
1474
- asset,
1475
- signal: params.signal,
1476
- onProgress: params.onProgress
1477
- })).command;
1478
- const port = params.port ?? await findAvailableLlamaServerPort(params.isolated ? 0 : void 0);
1479
- const rootUrl = `http://127.0.0.1:${port}`;
1480
- const reconcileOrigin = params.reconcileBaseUrl ? new URL(params.reconcileBaseUrl).origin : rootUrl;
1481
- const endpoint = {
1482
- command,
1483
- baseUrl: `${rootUrl}/v1`,
1484
- healthUrl: params.localService?.healthUrl ?? `${rootUrl}/health`
1485
- };
1486
- const configuredPreset = params.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset") ?? params.localService?.env?.LLAMA_ARG_MODELS_PRESET;
1487
- if (params.localService && !params.isolated) await recoverManagedLlamaServer({
1488
- command,
1489
- port,
1490
- cwd: params.localService.cwd,
1491
- args: params.localService.args,
1492
- signal: params.signal
1493
- });
1494
- if (params.localService && !configuredPreset && !params.isolated) {
1495
- await runPresetTransition(async () => {
1496
- presetState.desiredRevisions.delete(reconcileOrigin);
1497
- presetState.appliedRevisions.delete(reconcileOrigin);
1498
- });
1499
- return {
1500
- ...endpoint,
1501
- args: params.localService.args ?? []
1502
- };
1503
- }
1504
- const defaultPreset = configuredPreset ? path.resolve(params.localService?.cwd ?? process.cwd(), configuredPreset) : resolveManagedLlamaServerPaths(params.asset).presetPath;
1505
- const presetPath = params.isolated ? path.join(path.dirname(defaultPreset), `models-${randomUUID()}.ini`) : defaultPreset;
1506
- await updatePreset(presetPath, {
1507
- chatModel: params.chatModel,
1508
- configuredChatModelIds: params.configuredChatModelIds,
1509
- embeddingModelPath: params.embeddingModelPath,
1510
- defaultEmbeddingModelPath: params.defaultEmbeddingModelPath,
1511
- serviceSettings: params.isolated ? { env: process.env } : {
1512
- args: params.localService?.args,
1513
- env: {
1514
- ...process.env,
1515
- ...params.localService?.env
1516
- }
1517
- },
1518
- reconcileOrigin: params.isolated ? void 0 : reconcileOrigin
1519
- });
1520
- params.signal?.throwIfAborted();
1521
- return {
1522
- ...endpoint,
1523
- args: params.localService && !params.isolated ? params.localService.args ?? [] : [
1524
- "--host",
1525
- "127.0.0.1",
1526
- "--port",
1527
- String(port),
1528
- "--models-preset",
1529
- presetPath,
1530
- "--models-max",
1531
- "2",
1532
- "--metrics",
1533
- "--no-ui"
1534
- ]
1535
- };
1536
- }
1537
- async function ensureManagedLlamaServerForChat(params) {
1538
- if (!params.provider.localService || !params.provider.baseUrl) return;
1539
- const cacheDir = resolveLlamaCppModelCacheDir(params.provider);
1540
- let chatModelPath = resolveCachedLlamaCppModelPath({
1541
- model: params.model,
1542
- provider: params.provider
1543
- });
1544
- if (!chatModelPath && resolveLlamaCppModelSource(params.model) === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") {
1545
- const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
1546
- if (await fs.stat(legacy).then((stat) => stat.isFile()).catch(() => false)) chatModelPath = legacy;
1547
- }
1548
- chatModelPath = await ensureLlamaCppModel({
1549
- source: chatModelPath ?? resolveLlamaCppModelSource(params.model),
1550
- cacheDir,
1551
- download: false
1552
- });
1553
- const configuredContext = params.model.params?.contextSize;
1554
- const port = Number(new URL(params.provider.baseUrl).port);
1555
- await prepareManagedLlamaServer({
1556
- chatModel: {
1557
- mode: "configure",
1558
- id: params.model.id,
1559
- path: chatModelPath,
1560
- contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : params.model.contextTokens,
1561
- maxTokens: params.model.maxTokens
1562
- },
1563
- configuredChatModelIds: params.provider.models.map((model) => model.id),
1564
- defaultEmbeddingModelPath: path.join(cacheDir, DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE),
1565
- port: Number.isInteger(port) && port > 0 ? port : void 0,
1566
- reconcileBaseUrl: params.provider.baseUrl,
1567
- localService: params.provider.localService
1568
- });
1569
- }
1570
- async function fetchEndpoint(url, accept) {
1571
- try {
1572
- const configuredLocalOriginBaseUrl = new URL(url).origin;
1573
- const { response, release } = await fetchConfiguredLocalOriginWithSsrFGuard({
1574
- url,
1575
- configuredLocalOriginBaseUrl,
1576
- policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(configuredLocalOriginBaseUrl),
1577
- timeoutMs: 2500,
1578
- auditContext: "llama-server-inspect"
1579
- });
1580
- try {
1581
- if (!response.ok) return { ok: false };
1582
- return {
1583
- ok: true,
1584
- value: accept === "json" ? await readProviderJsonResponse(response, "llama-server inspection") : await readProviderTextResponse(response, "llama-server inspection")
1585
- };
1586
- } finally {
1587
- await release();
1588
- }
1589
- } catch {
1590
- return { ok: false };
1591
- }
1592
- }
1593
- async function inspectLlamaServerRuntime(params) {
1594
- const root = params.baseUrl.replace(/\/v1\/?$/u, "").replace(/\/+$/u, "");
1595
- const query = `model=${encodeURIComponent(params.modelId)}&autoload=false`;
1596
- const [health, models, props, metrics] = await Promise.all([
1597
- fetchEndpoint(`${root}/health`, "json"),
1598
- fetchEndpoint(`${root}/models`, "json"),
1599
- fetchEndpoint(`${root}/props?${query}`, "json"),
1600
- fetchEndpoint(`${root}/metrics?${query}`, "text")
1601
- ]);
1602
- const propsRecord = asOptionalRecord(props.value);
1603
- const modalities = asOptionalRecord(propsRecord?.modalities);
1604
- const modelsRecord = asOptionalRecord(models.value);
1605
- const selected = (Array.isArray(modelsRecord?.data) ? modelsRecord.data : []).map((row) => asOptionalRecord(row)).find((row) => row?.id === params.modelId);
1606
- const pathValue = typeof propsRecord?.model_path === "string" ? propsRecord.model_path : typeof selected?.path === "string" ? selected.path : void 0;
1607
- return {
1608
- engine: "llama.cpp",
1609
- state: health.ok && models.ok && props.ok && metrics.ok && !params.loadError ? "ready" : "failed",
1610
- backend: params.backend,
1611
- buildInfo: typeof propsRecord?.build_info === "string" ? propsRecord.build_info : void 0,
1612
- model: {
1613
- id: params.modelId,
1614
- ...pathValue ? { path: pathValue } : {}
1615
- },
1616
- capabilities: {
1617
- vision: modalities?.vision === true,
1618
- draft: false
1619
- },
1620
- endpoints: {
1621
- health: health.ok ? "ready" : "unavailable",
1622
- models: models.ok ? "ready" : "unavailable",
1623
- props: props.ok ? "ready" : "unavailable",
1624
- metrics: metrics.ok ? "ready" : "unavailable"
1625
- },
1626
- ...params.loadError ? { loadError: params.loadError } : {}
1627
- };
1628
- }
1629
- //#endregion
8
+ import { textResult } from "openclaw/plugin-sdk/tool-results";
1630
9
  //#region extensions/llama-cpp/src/embedding-provider.ts
1631
- const LOCAL_EMBEDDING_RUNTIME_FACTS = Symbol.for("openclaw.localEmbeddingRuntimeFacts");
1632
10
  function readIdentityLocalOptions(options) {
1633
11
  const local = options.local ?? {};
1634
12
  const provider = options.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
@@ -1663,61 +41,6 @@ function resolveModelIdentity(local, dimensions) {
1663
41
  }))
1664
42
  };
1665
43
  }
1666
- function resolveProviderPort(provider) {
1667
- const port = Number(new URL(provider.baseUrl ?? "").port);
1668
- if (!Number.isInteger(port) || port <= 0) throw new Error("Managed llama.cpp provider baseUrl must include a loopback port.");
1669
- return port;
1670
- }
1671
- async function prepareEmbeddingServer(options, embeddingSource) {
1672
- const provider = resolveManagedLlamaCppProviderConfig(options.config);
1673
- const embeddingModelPath = await ensureLlamaCppModel({
1674
- source: embeddingSource,
1675
- cacheDir: resolveLlamaCppModelCacheDir(provider),
1676
- download: true
1677
- });
1678
- await prepareManagedLlamaServer({
1679
- chatModel: { mode: "preserve" },
1680
- configuredChatModelIds: provider.models.map((model) => model.id),
1681
- embeddingModelPath,
1682
- port: resolveProviderPort(provider),
1683
- reconcileBaseUrl: provider.baseUrl,
1684
- localService: provider.localService
1685
- });
1686
- }
1687
- function wrapProvider(params) {
1688
- let runtimeFacts;
1689
- const refreshFacts = async (loadError) => {
1690
- runtimeFacts = await inspectLlamaServerRuntime({
1691
- baseUrl: params.baseUrl,
1692
- modelId: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
1693
- loadError
1694
- });
1695
- };
1696
- const withFacts = async (operation) => {
1697
- try {
1698
- const value = await operation();
1699
- await refreshFacts();
1700
- return value;
1701
- } catch (error) {
1702
- await refreshFacts(error instanceof Error ? error.message : String(error));
1703
- throw error;
1704
- }
1705
- };
1706
- const wrapped = {
1707
- id: "local",
1708
- model: params.canonicalModel,
1709
- dimensions: params.provider.dimensions,
1710
- maxInputTokens: params.provider.maxInputTokens ?? 2044,
1711
- embed: (input, callOptions) => withFacts(() => params.provider.embed(input, callOptions)),
1712
- embedBatch: (inputs, callOptions) => withFacts(() => params.provider.embedBatch(inputs, callOptions)),
1713
- close: params.provider.close
1714
- };
1715
- Object.defineProperty(wrapped, LOCAL_EMBEDDING_RUNTIME_FACTS, {
1716
- enumerable: false,
1717
- value: () => runtimeFacts
1718
- });
1719
- return wrapped;
1720
- }
1721
44
  const llamaCppEmbeddingProviderAdapter = {
1722
45
  id: "local",
1723
46
  defaultModel: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
@@ -1728,1058 +51,96 @@ const llamaCppEmbeddingProviderAdapter = {
1728
51
  },
1729
52
  create: async (options) => {
1730
53
  const local = readIdentityLocalOptions(options);
1731
- const embeddingModel = resolveLlamaCppEmbeddingModel(local);
1732
- const identity = resolveModelIdentity(local, options.dimensions);
1733
- await prepareEmbeddingServer(options, embeddingModel.source);
1734
- const genericAdapter = getEmbeddingProvider("openai-compatible", options.config);
1735
- if (!genericAdapter) throw new Error("OpenAI-compatible embedding transport is unavailable.");
1736
- const acquireLocalService = options.acquireLocalService;
1737
- const result = await genericAdapter.create({
1738
- ...options,
1739
- provider: LLAMA_CPP_PROVIDER_ID,
1740
- model: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
1741
- remote: void 0,
1742
- ...acquireLocalService ? { acquireLocalService: (...[target, signal]) => acquireLocalService({
1743
- ...target,
1744
- reconcile: reconcileManagedLlamaServer
1745
- }, signal) } : {}
1746
- });
1747
- if (!result.provider) return result;
1748
- return {
1749
- provider: wrapProvider({
1750
- provider: result.provider,
1751
- canonicalModel: identity.model,
1752
- baseUrl: resolveManagedLlamaCppProviderConfig(options.config).baseUrl ?? ""
1753
- }),
1754
- runtime: {
1755
- id: "local",
1756
- inlineQueryTimeoutMs: 3e5,
1757
- inlineBatchTimeoutMs: 6e5,
1758
- cacheKeyData: identity.cacheKeyData,
1759
- ...identity.aliases.length > 0 ? { indexIdentityAliases: identity.aliases } : {}
1760
- }
1761
- };
54
+ const { createLlamaCppEmbeddingProvider } = await import("./.setup/embedding-provider.runtime-FcwMX9AK.mjs");
55
+ return createLlamaCppEmbeddingProvider(options, resolveLlamaCppEmbeddingModel(local).source, resolveModelIdentity(local, options.dimensions));
1762
56
  }
1763
57
  };
1764
58
  //#endregion
1765
- //#region extensions/llama-cpp/src/external-server/auth.ts
1766
- function hasLlamaServerAuthorizationHeader(headers) {
1767
- const record = asOptionalRecord(headers);
1768
- if (!record) return false;
1769
- return Object.entries(record).some(([name, value]) => name.trim().toLowerCase() === "authorization" && hasConfiguredSecretInput(value));
1770
- }
1771
- function shouldUseLlamaServerSyntheticAuth(providerConfig) {
1772
- const apiKey = normalizeOptionalSecretInput(providerConfig?.apiKey)?.trim();
1773
- return !(hasConfiguredSecretInput(providerConfig?.apiKey) && apiKey !== "llama-cpp-local" && apiKey !== CUSTOM_LOCAL_AUTH_MARKER);
1774
- }
1775
- async function resolveLlamaServerProviderHeaders(params) {
1776
- const headers = asOptionalRecord(params.headers);
1777
- if (!headers) return;
1778
- const resolved = {};
1779
- for (const [name, value] of Object.entries(headers)) {
1780
- if (!params.config) {
1781
- if (typeof value === "string" && value.trim()) resolved[name] = value.trim();
1782
- continue;
1783
- }
1784
- const path = `models.providers.${LLAMA_CPP_PROVIDER_ID}.headers[${JSON.stringify(name)}]`;
1785
- const header = await resolveConfiguredSecretInputString({
1786
- config: params.config,
1787
- env: params.env ?? process.env,
1788
- value,
1789
- path,
1790
- unresolvedReasonStyle: "detailed"
1791
- });
1792
- if (header.unresolvedRefReason) throw new Error(`${path}: ${header.unresolvedRefReason}`);
1793
- if (header.value) resolved[name] = header.value;
1794
- }
1795
- return Object.keys(resolved).length > 0 ? resolved : void 0;
1796
- }
1797
- async function resolveLlamaServerRuntimeApiKey(params) {
1798
- const apiKey = (await resolveApiKeyForProvider({
1799
- provider: LLAMA_CPP_PROVIDER_ID,
1800
- cfg: params.config,
1801
- agentDir: params.agentDir,
1802
- profileId: params.profileId,
1803
- lockedProfile: params.profileId !== void 0
1804
- })).apiKey?.trim();
1805
- return apiKey && !isNonSecretApiKeyMarker(apiKey) ? apiKey : void 0;
1806
- }
1807
- //#endregion
1808
- //#region extensions/llama-cpp/src/external-server/defaults.ts
1809
- const LLAMA_SERVER_DEFAULT_ORIGIN = "http://127.0.0.1:8080";
1810
- const LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR = "LLAMA_SERVER_API_KEY";
1811
- const LLAMA_SERVER_DISCOVERY_TIMEOUT_MS = 5e3;
1812
- //#endregion
1813
- //#region extensions/llama-cpp/src/external-server/endpoint.ts
1814
- /** Resolves the server origin and its OpenAI-compatible `/v1` inference base. */
1815
- function resolveLlamaServerEndpoint(configuredBaseUrl) {
1816
- const configured = configuredBaseUrl?.trim() || "http://127.0.0.1:8080";
1817
- const parsed = new URL(/^[a-z][a-z\d+.-]*:\/\//iu.test(configured) ? configured : `http://${configured}`);
1818
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new TypeError(`Unsupported llama-server protocol: ${parsed.protocol}`);
1819
- if (parsed.username || parsed.password) throw new TypeError("llama-server base URL must not contain credentials");
1820
- parsed.pathname = parsed.pathname.replace(/\/+$/u, "").replace(/\/v1$/iu, "") || "/";
1821
- parsed.search = "";
1822
- parsed.hash = "";
1823
- const origin = parsed.toString().replace(/\/$/u, "");
1824
- return {
1825
- origin,
1826
- inferenceBaseUrl: `${origin}/v1`
1827
- };
1828
- }
1829
- /** Canonicalizes persisted provider config for the shared OpenAI transport. */
1830
- function normalizeLlamaServerProviderConfig(provider) {
1831
- const endpoint = resolveLlamaServerEndpoint(provider.baseUrl);
1832
- const request = provider.request ?? {};
1833
- const normalizedRequest = typeof request.allowPrivateNetwork === "boolean" ? request : {
1834
- ...request,
1835
- allowPrivateNetwork: true
1836
- };
1837
- return {
1838
- ...provider,
1839
- baseUrl: endpoint.inferenceBaseUrl,
1840
- api: "openai-completions",
1841
- request: normalizedRequest
1842
- };
1843
- }
1844
- //#endregion
1845
- //#region extensions/llama-cpp/src/external-server/models.ts
1846
- function normalizeStatus(value) {
1847
- switch (value) {
1848
- case "unloaded":
1849
- case "loading":
1850
- case "loaded":
1851
- case "sleeping":
1852
- case "downloading": return value;
1853
- default: return "unknown";
1854
- }
1855
- }
1856
- function resolveContextWindow(props) {
1857
- return asPositiveSafeInteger(props?.default_generation_settings?.n_ctx) ?? asPositiveSafeInteger(props?.n_ctx) ?? SELF_HOSTED_DEFAULT_CONTEXT_WINDOW;
1858
- }
1859
- function resolveMaxTokens(props, contextWindow) {
1860
- const params = props?.default_generation_settings?.params;
1861
- const advertised = asPositiveSafeInteger(params?.max_tokens) ?? asPositiveSafeInteger(params?.n_predict);
1862
- return Math.min(advertised ?? SELF_HOSTED_DEFAULT_MAX_TOKENS, contextWindow);
1863
- }
1864
- function resolveInput(row, props) {
1865
- const advertised = row.architecture?.input_modalities;
1866
- return Array.isArray(advertised) && advertised.includes("image") || props?.modalities?.vision === true ? ["text", "image"] : ["text"];
1867
- }
1868
- function buildCompat(props) {
1869
- const caps = props?.chat_template_caps;
1870
- return {
1871
- supportsStore: false,
1872
- supportsDeveloperRole: false,
1873
- supportsReasoningEffort: caps?.supports_reasoning_effort === true,
1874
- supportsTemperature: true,
1875
- supportsUsageInStreaming: true,
1876
- supportsTools: caps?.supports_tool_calls === true,
1877
- supportsStrictMode: false,
1878
- supportsJsonSchemaResponseFormat: true,
1879
- requiresStringContent: caps?.supports_typed_content !== true,
1880
- maxTokensField: "max_tokens"
1881
- };
1882
- }
1883
- /** Maps one llama-server model row plus optional runtime properties into OpenClaw config. */
1884
- function mapLlamaServerModel(row, props) {
1885
- const id = typeof row.id === "string" ? row.id.trim() : "";
1886
- if (!id || row.object !== void 0 && row.object !== "model") return null;
1887
- const contextWindow = resolveContextWindow(props);
1888
- const compat = buildCompat(props);
1889
- return {
1890
- config: {
1891
- id,
1892
- name: id,
1893
- reasoning: compat.supportsReasoningEffort === true,
1894
- input: resolveInput(row, props),
1895
- cost: { ...SELF_HOSTED_DEFAULT_COST },
1896
- contextWindow,
1897
- contextTokens: contextWindow,
1898
- maxTokens: resolveMaxTokens(props, contextWindow),
1899
- compat
1900
- },
1901
- status: normalizeStatus(row.status?.value),
1902
- failed: row.status?.failed === true
1903
- };
1904
- }
1905
- function buildLlamaServerProviderConfig(params) {
1906
- const models = Array.isArray(params.configured?.models) ? [...params.configured.models] : [];
1907
- const seen = new Set(models.map((model) => model.id));
1908
- for (const discovered of params.discoveredModels) {
1909
- if (seen.has(discovered.config.id)) continue;
1910
- seen.add(discovered.config.id);
1911
- models.push(discovered.config);
1912
- }
1913
- return normalizeLlamaServerProviderConfig({
1914
- ...params.configured,
1915
- baseUrl: params.configured?.baseUrl ?? "http://127.0.0.1:8080",
1916
- models
1917
- });
1918
- }
1919
- //#endregion
1920
- //#region extensions/llama-cpp/src/external-server/discovery.ts
1921
- /** Discovers llama-server models without loading, waking, or unloading them. */
1922
- async function discoverLlamaServer(params) {
1923
- const endpoint = resolveLlamaServerEndpoint(params.baseUrl);
1924
- const result = await discoverOpenAICompatibleLocalModels({
1925
- baseUrl: endpoint.inferenceBaseUrl,
1926
- serverBaseUrl: endpoint.origin,
1927
- apiKey: params.apiKey,
1928
- headers: params.headers,
1929
- label: "llama-server",
1930
- healthPath: "/health",
1931
- modelsPathOrder: "server-first",
1932
- routerModelProps: true,
1933
- timeoutMs: LLAMA_SERVER_DISCOVERY_TIMEOUT_MS,
1934
- signal: params.signal,
1935
- rawResult: true
1936
- });
1937
- if (result.kind !== "success") return {
1938
- ...result,
1939
- endpoint
1940
- };
1941
- return {
1942
- kind: "success",
1943
- endpoint,
1944
- models: result.rows.flatMap(({ model, props }) => {
1945
- const mapped = mapLlamaServerModel(model, props);
1946
- return mapped ? [mapped] : [];
1947
- })
1948
- };
1949
- }
1950
- //#endregion
1951
- //#region extensions/llama-cpp/src/external-server/provider.ts
1952
- /** Discovers external llama-server models for provider runtime resolution. */
1953
- async function discoverLlamaServerProvider(ctx) {
1954
- const configured = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1955
- const auth = ctx.resolveProviderApiKey(LLAMA_CPP_PROVIDER_ID);
1956
- const headers = await resolveLlamaServerProviderHeaders({
1957
- config: ctx.config,
1958
- env: ctx.env,
1959
- headers: configured?.headers
1960
- });
1961
- const authApiKey = auth.discoveryApiKey ?? auth.apiKey;
1962
- const apiKey = hasLlamaServerAuthorizationHeader(headers) || authApiKey && isNonSecretApiKeyMarker(authApiKey) ? void 0 : authApiKey;
1963
- return await runLiveProviderCatalog({
1964
- providerId: LLAMA_CPP_PROVIDER_ID,
1965
- profileId: apiKey ? auth.profileId : void 0,
1966
- run: async () => {
1967
- const discovery = await discoverLlamaServer({
1968
- baseUrl: configured?.baseUrl,
1969
- apiKey,
1970
- headers
1971
- });
1972
- if (discovery.kind !== "success") {
1973
- if (!configured && !apiKey && !headers) return null;
1974
- throw discovery.kind === "http-error" ? new LiveModelCatalogHttpError(LLAMA_CPP_PROVIDER_ID, discovery.status) : discovery.error;
1975
- }
1976
- return { provider: buildLlamaServerProviderConfig({
1977
- configured,
1978
- discoveredModels: discovery.models
1979
- }) };
1980
- }
1981
- });
1982
- }
1983
- async function prepareLlamaServerDynamicModel(ctx) {
1984
- const apiKey = await resolveLlamaServerRuntimeApiKey({
1985
- config: ctx.config,
1986
- agentDir: ctx.agentDir,
1987
- profileId: ctx.authProfileId
1988
- });
1989
- const headers = await resolveLlamaServerProviderHeaders({
1990
- config: ctx.config,
1991
- env: process.env,
1992
- headers: ctx.providerConfig?.headers
1993
- });
1994
- const discovery = await discoverLlamaServer({
1995
- baseUrl: ctx.providerConfig?.baseUrl,
1996
- apiKey: hasLlamaServerAuthorizationHeader(headers) ? void 0 : apiKey,
1997
- headers
1998
- });
1999
- const model = discovery.kind === "success" ? discovery.models.find((entry) => entry.config.id === ctx.modelId) : void 0;
2000
- if (!model) return;
2001
- return {
2002
- ...model.config,
2003
- provider: LLAMA_CPP_PROVIDER_ID,
2004
- api: ctx.providerConfig?.api ?? "openai-completions",
2005
- baseUrl: resolveLlamaServerEndpoint(ctx.providerConfig?.baseUrl).inferenceBaseUrl,
2006
- input: model.config.input.filter((entry) => entry === "text" || entry === "image")
2007
- };
2008
- }
2009
- //#endregion
2010
- //#region extensions/llama-cpp/src/auth-config.ts
2011
- const LLAMA_CPP_DEFAULT_PROFILE_ID = `${LLAMA_CPP_PROVIDER_ID}:default`;
2012
- function buildLlamaCppAuthProfileRemovalPatch(config) {
2013
- const profileExists = Boolean(config.auth?.profiles?.[LLAMA_CPP_DEFAULT_PROFILE_ID]);
2014
- const referencedOrders = Object.entries(config.auth?.order ?? {}).filter(([, ids]) => ids.includes(LLAMA_CPP_DEFAULT_PROFILE_ID));
2015
- if (!profileExists && referencedOrders.length === 0) return {};
2016
- const authPatch = {};
2017
- if (profileExists) Reflect.set(authPatch, "profiles", { [LLAMA_CPP_DEFAULT_PROFILE_ID]: void 0 });
2018
- if (referencedOrders.length > 0) Reflect.set(authPatch, "order", Object.fromEntries(referencedOrders.map(([providerId, ids]) => {
2019
- const next = ids.filter((id) => id !== LLAMA_CPP_DEFAULT_PROFILE_ID);
2020
- return [providerId, next.length > 0 ? next : void 0];
2021
- })));
2022
- return { auth: authPatch };
2023
- }
2024
- //#endregion
2025
- //#region extensions/llama-cpp/src/external-server/setup.ts
2026
- function selectSetupModelId(discovery) {
2027
- const candidates = discovery.models.filter((model) => !model.failed);
2028
- const ready = candidates.filter((model) => model.status === "loaded" || model.status === "sleeping");
2029
- const ids = (ready.length > 0 ? ready : candidates).map((model) => model.config.id);
2030
- return selectPreferredLocalModelId(ids) ?? ids[0];
2031
- }
2032
- function describeDiscoveryFailure(result) {
2033
- switch (result.kind) {
2034
- case "unreachable": return `llama-server could not be reached at ${result.endpoint.origin}.`;
2035
- case "http-error": return `llama-server returned HTTP ${result.status} for ${result.path} at ${result.endpoint.origin}.`;
2036
- case "invalid-response": return `llama-server returned an invalid response from ${result.path} at ${result.endpoint.origin}.`;
2037
- default: throw new Error("Unexpected llama-server discovery result");
2038
- }
2039
- }
2040
- function stripAuthOverrides(provider, removeAuthorization) {
2041
- if (!provider) return provider;
2042
- const headers = removeAuthorization ? stripAuthorizationHeader(provider.headers) : provider.headers;
2043
- return {
2044
- ...provider,
2045
- auth: void 0,
2046
- apiKey: void 0,
2047
- ...removeAuthorization ? { headers } : {}
2048
- };
2049
- }
2050
- function stripEndpointCredentials(provider) {
2051
- if (!provider) return;
2052
- const { localService: _localService, ...external } = provider;
2053
- if (!provider.localService) return {
2054
- ...external,
2055
- auth: void 0,
2056
- apiKey: void 0,
2057
- headers: void 0
2058
- };
2059
- const { auth: _auth, apiKey: _apiKey, headers: _headers, localService: _managedService, models: _managedModels, params: managedParams, timeoutSeconds: _managedTimeout, ...externalProvider } = provider;
2060
- const { modelCacheDir: _modelCacheDir, ...params } = managedParams ?? {};
2061
- return {
2062
- ...externalProvider,
2063
- models: [],
2064
- params: Object.keys(params).length > 0 ? params : void 0
2065
- };
2066
- }
2067
- function hasEndpointChanged(provider, baseUrl) {
2068
- if (!provider) return false;
2069
- return resolveLlamaServerEndpoint(provider.baseUrl ?? "http://127.0.0.1:8080").inferenceBaseUrl !== resolveLlamaServerEndpoint(baseUrl).inferenceBaseUrl;
2070
- }
2071
- function stripLlamaServerEndpointAuth(config) {
2072
- const withoutProfile = removeAuthProfileConfig(config, LLAMA_CPP_DEFAULT_PROFILE_ID);
2073
- const provider = withoutProfile.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2074
- const endpointSafeProvider = stripEndpointCredentials(provider);
2075
- if (!endpointSafeProvider) return withoutProfile;
2076
- return {
2077
- ...withoutProfile,
2078
- models: {
2079
- ...withoutProfile.models,
2080
- providers: {
2081
- ...withoutProfile.models?.providers,
2082
- [LLAMA_CPP_PROVIDER_ID]: endpointSafeProvider
2083
- }
2084
- }
2085
- };
2086
- }
2087
- function stripAuthorizationHeader(headers) {
2088
- const filtered = Object.fromEntries(Object.entries(headers ?? {}).filter(([name]) => name.toLowerCase() !== "authorization"));
2089
- return Object.keys(filtered).length > 0 ? filtered : void 0;
2090
- }
2091
- function buildExistingProviderConfig(params) {
2092
- const configured = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2093
- const endpointSafe = params.resetEndpoint ? stripEndpointCredentials(configured) : configured;
2094
- const existing = params.persistence.kind === "preserve" ? endpointSafe : stripAuthOverrides(endpointSafe, params.persistence.kind === "upsert");
2095
- return buildLlamaServerProviderConfig({
2096
- configured: {
2097
- ...existing,
2098
- baseUrl: params.discovery.endpoint.inferenceBaseUrl,
2099
- models: existing?.models ?? []
2100
- },
2101
- discoveredModels: params.discovery.models
2102
- });
2103
- }
2104
- function buildSetupResult$1(params) {
2105
- return {
2106
- profiles: params.persistence.kind === "upsert" ? [{
2107
- profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
2108
- credential: buildApiKeyCredential(LLAMA_CPP_PROVIDER_ID, params.persistence.credential, void 0, { config: params.config })
2109
- }] : [],
2110
- defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${params.modelId}`,
2111
- configPatch: {
2112
- ...params.persistence.kind === "remove" ? buildLlamaCppAuthProfileRemovalPatch(params.config) : {},
2113
- models: {
2114
- mode: params.config.models?.mode ?? "merge",
2115
- providers: { [LLAMA_CPP_PROVIDER_ID]: buildExistingProviderConfig(params) }
2116
- }
2117
- }
2118
- };
2119
- }
2120
- async function removeDefaultAuthProfile(config, agentDir) {
2121
- if (!await removeProviderAuthProfilesWithLock({
2122
- cfg: config,
2123
- agentDir,
2124
- provider: "llama-cpp",
2125
- profileIds: [LLAMA_CPP_DEFAULT_PROFILE_ID]
2126
- })) throw new Error("Failed to remove the previous llama-server auth profile; wait a moment and retry.");
2127
- }
2128
- async function discoverForSetup(ctx) {
2129
- const provider = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2130
- if (provider?.localService) return null;
2131
- try {
2132
- const headers = await resolveLlamaServerProviderHeaders({
2133
- config: ctx.config,
2134
- env: ctx.env,
2135
- headers: provider?.headers
2136
- });
2137
- const apiKey = !hasLlamaServerAuthorizationHeader(headers) ? await resolveLlamaServerRuntimeApiKey({ config: ctx.config }) : void 0;
2138
- const discovery = await discoverLlamaServer({
2139
- baseUrl: provider?.baseUrl ?? "http://127.0.0.1:8080",
2140
- apiKey,
2141
- headers,
2142
- signal: ctx.signal
2143
- });
2144
- return discovery.kind === "success" ? discovery : null;
2145
- } catch {
2146
- return null;
2147
- }
2148
- }
2149
- /** Read-only discovery for the guided local-provider setup ladder. */
2150
- async function detectLlamaServerSetup(ctx) {
2151
- const discovery = await discoverForSetup(ctx);
2152
- if (!discovery) return null;
2153
- const modelId = selectSetupModelId(discovery);
2154
- if (!modelId) return null;
2155
- return {
2156
- modelRef: `${LLAMA_CPP_PROVIDER_ID}/${modelId}`,
2157
- detail: `${modelId} at ${discovery.endpoint.origin}`
2158
- };
2159
- }
2160
- /** Rechecks one guided candidate and returns the config needed for a live probe. */
2161
- async function prepareLlamaServerSetup(ctx) {
2162
- const discovery = await discoverForSetup(ctx);
2163
- if (!discovery) return null;
2164
- const prefix = `${LLAMA_CPP_PROVIDER_ID}/`;
2165
- const modelId = ctx.modelRef.startsWith(prefix) ? ctx.modelRef.slice(prefix.length) : "";
2166
- if (!modelId || !discovery.models.some((model) => model.config.id === modelId)) return null;
2167
- return buildSetupResult$1({
2168
- config: ctx.config,
2169
- discovery,
2170
- modelId,
2171
- resetEndpoint: false,
2172
- persistence: { kind: "preserve" }
2173
- });
2174
- }
2175
- /** Interactive setup for an existing llama-server endpoint. */
2176
- async function runLlamaServerSetup(ctx) {
2177
- const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2178
- const defaultOrigin = resolveLlamaServerEndpoint(existing?.baseUrl).origin;
2179
- const endpoint = resolveLlamaServerEndpoint(await ctx.prompter.text({
2180
- message: `${LLAMA_CPP_PROVIDER_LABEL} URL`,
2181
- initialValue: defaultOrigin,
2182
- placeholder: LLAMA_SERVER_DEFAULT_ORIGIN,
2183
- validate: (value) => {
2184
- if (!value?.trim()) return "Required";
2185
- try {
2186
- resolveLlamaServerEndpoint(value);
2187
- return;
2188
- } catch {
2189
- return "Enter a valid HTTP or HTTPS URL without embedded credentials (e.g. http://localhost:8080).";
2190
- }
2191
- }
2192
- }));
2193
- const endpointChanged = Boolean(existing?.localService) || hasEndpointChanged(existing, endpoint.inferenceBaseUrl);
2194
- const resolvedHeaders = endpointChanged ? void 0 : await resolveLlamaServerProviderHeaders({
2195
- config: ctx.config,
2196
- env: ctx.env,
2197
- headers: existing?.headers
2198
- });
2199
- const usesApiKey = await ctx.prompter.confirm({
2200
- message: "Does this llama-server require an API key?",
2201
- initialValue: false
2202
- });
2203
- let apiKey;
2204
- let headers = resolvedHeaders;
2205
- let persistence;
2206
- if (!usesApiKey) persistence = { kind: "remove" };
2207
- else {
2208
- const hasConfiguredProfile = Boolean(ctx.config.auth?.profiles?.[LLAMA_CPP_DEFAULT_PROFILE_ID]);
2209
- const profileApiKey = !endpointChanged && !hasLlamaServerAuthorizationHeader(resolvedHeaders) && hasConfiguredProfile ? await resolveLlamaServerRuntimeApiKey({
2210
- config: ctx.config,
2211
- agentDir: ctx.agentDir,
2212
- profileId: LLAMA_CPP_DEFAULT_PROFILE_ID
2213
- }) : void 0;
2214
- if (profileApiKey) {
2215
- apiKey = profileApiKey;
2216
- persistence = { kind: "preserve" };
2217
- } else {
2218
- let credentialInput;
2219
- apiKey = await ensureApiKeyFromEnvOrPrompt({
2220
- config: endpointChanged ? stripLlamaServerEndpointAuth(ctx.config) : ctx.config,
2221
- env: endpointChanged ? {} : ctx.env,
2222
- provider: LLAMA_CPP_PROVIDER_ID,
2223
- envLabel: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
2224
- promptMessage: "Enter the llama-server API key",
2225
- normalize: (value) => value.trim(),
2226
- validate: (value) => value.trim() ? void 0 : "Required",
2227
- prompter: ctx.prompter,
2228
- secretInputMode: ctx.secretInputMode,
2229
- setCredential: async (input) => {
2230
- credentialInput = input;
2231
- }
2232
- });
2233
- if (credentialInput === void 0) throw new Error("llama-server API-key setup did not produce a credential");
2234
- headers = stripAuthorizationHeader(resolvedHeaders);
2235
- persistence = {
2236
- kind: "upsert",
2237
- credential: credentialInput
2238
- };
2239
- }
2240
- }
2241
- const discovery = await discoverLlamaServer({
2242
- baseUrl: endpoint.inferenceBaseUrl,
2243
- apiKey,
2244
- headers,
2245
- signal: ctx.signal
2246
- });
2247
- if (discovery.kind !== "success") throw new Error(describeDiscoveryFailure(discovery));
2248
- const modelId = selectSetupModelId(discovery);
2249
- if (!modelId) throw new Error(`No llama-server text models were found at ${discovery.endpoint.origin}.`);
2250
- if (persistence.kind === "remove") await removeDefaultAuthProfile(ctx.config, ctx.agentDir);
2251
- return buildSetupResult$1({
2252
- config: ctx.config,
2253
- discovery,
2254
- modelId,
2255
- resetEndpoint: endpointChanged,
2256
- persistence
2257
- });
2258
- }
2259
- async function validateNonInteractiveDiscovery(ctx) {
2260
- const configuredProvider = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2261
- const baseUrl = normalizeOptionalSecretInput(ctx.opts.customBaseUrl) ?? configuredProvider?.baseUrl ?? "http://127.0.0.1:8080";
2262
- const endpointChanged = Boolean(configuredProvider?.localService) || hasEndpointChanged(configuredProvider, baseUrl);
2263
- const providerApiKey = normalizeOptionalSecretInput(ctx.opts.llamaServerApiKey);
2264
- const customApiKey = normalizeOptionalSecretInput(ctx.opts.customApiKey);
2265
- const authoredApiKey = providerApiKey ?? customApiKey;
2266
- const hasAuthoredApiKey = authoredApiKey !== void 0;
2267
- const resolvedApiKey = await ctx.resolveApiKey({
2268
- provider: LLAMA_CPP_PROVIDER_ID,
2269
- flagValue: authoredApiKey,
2270
- flagName: providerApiKey === void 0 ? "--custom-api-key" : "--llama-server-api-key",
2271
- envVar: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
2272
- envVarName: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
2273
- required: false
2274
- });
2275
- const resolvedHeaders = endpointChanged ? void 0 : await resolveLlamaServerProviderHeaders({
2276
- config: ctx.config,
2277
- env: process.env,
2278
- headers: configuredProvider?.headers
2279
- });
2280
- let apiKey;
2281
- let headers = resolvedHeaders;
2282
- let persistence;
2283
- if (hasAuthoredApiKey && resolvedApiKey) {
2284
- apiKey = resolvedApiKey.key;
2285
- headers = stripAuthorizationHeader(resolvedHeaders);
2286
- persistence = {
2287
- kind: "upsert",
2288
- credential: resolvedApiKey
2289
- };
2290
- } else if (endpointChanged || hasLlamaServerAuthorizationHeader(resolvedHeaders)) persistence = { kind: "remove" };
2291
- else if (resolvedApiKey?.source === "profile") {
2292
- apiKey = resolvedApiKey.key;
2293
- persistence = { kind: "preserve" };
2294
- } else if (resolvedApiKey) {
2295
- apiKey = resolvedApiKey.key;
2296
- persistence = {
2297
- kind: "upsert",
2298
- credential: resolvedApiKey
2299
- };
2300
- } else persistence = { kind: "remove" };
2301
- const discovery = await discoverLlamaServer({
2302
- baseUrl,
2303
- apiKey,
2304
- headers
2305
- });
2306
- if (discovery.kind !== "success") throw new Error(describeDiscoveryFailure(discovery));
2307
- const requestedModelId = normalizeOptionalSecretInput(ctx.opts.customModelId);
2308
- const modelId = requestedModelId ?? selectSetupModelId(discovery);
2309
- if (!modelId || !discovery.models.some((model) => model.config.id === modelId)) {
2310
- const available = discovery.models.map((model) => model.config.id).join(", ");
2311
- throw new Error(requestedModelId ? `llama-server model ${requestedModelId} was not found. Available models: ${available}` : `No llama-server text models were found at ${discovery.endpoint.origin}.`);
2312
- }
2313
- return {
2314
- discovery,
2315
- modelId,
2316
- resetEndpoint: endpointChanged,
2317
- persistence
2318
- };
2319
- }
2320
- async function validateLlamaServerNonInteractive(ctx) {
2321
- await validateNonInteractiveDiscovery(ctx);
2322
- return true;
2323
- }
2324
- /** Non-interactive setup with optional API-key persistence. */
2325
- async function configureLlamaServerNonInteractive(ctx) {
2326
- const validated = await validateNonInteractiveDiscovery(ctx);
2327
- const providerConfig = buildExistingProviderConfig({
2328
- config: ctx.config,
2329
- ...validated
2330
- });
2331
- let config = {
2332
- ...ctx.config,
2333
- models: {
2334
- ...ctx.config.models,
2335
- mode: ctx.config.models?.mode ?? "merge",
2336
- providers: {
2337
- ...ctx.config.models?.providers,
2338
- [LLAMA_CPP_PROVIDER_ID]: providerConfig
2339
- }
2340
- }
2341
- };
2342
- if (validated.persistence.kind === "upsert") {
2343
- const credential = ctx.toApiKeyCredential({
2344
- provider: LLAMA_CPP_PROVIDER_ID,
2345
- resolved: validated.persistence.credential
2346
- });
2347
- if (!credential) return null;
2348
- await upsertAuthProfileWithLockOrThrow({
2349
- profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
2350
- credential,
2351
- agentDir: ctx.agentDir
2352
- });
2353
- config = applyAuthProfileConfig(config, {
2354
- profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
2355
- provider: LLAMA_CPP_PROVIDER_ID,
2356
- mode: "api_key"
2357
- });
2358
- } else if (validated.persistence.kind === "remove") {
2359
- await removeDefaultAuthProfile(ctx.config, ctx.agentDir);
2360
- config = removeAuthProfileConfig(config, LLAMA_CPP_DEFAULT_PROFILE_ID);
2361
- }
2362
- ctx.runtime.log(`Default ${LLAMA_CPP_PROVIDER_LABEL} model: ${validated.modelId}`);
2363
- return applyProviderDefaultModel(config, `${LLAMA_CPP_PROVIDER_ID}/${validated.modelId}`);
2364
- }
2365
- //#endregion
2366
- //#region extensions/llama-cpp/src/external-server/stream.ts
2367
- /** Maps shared structured-output requests to the shape accepted by older llama-server builds. */
2368
- function normalizeLlamaServerResponseFormat(payload, requestedResponseFormat) {
2369
- const responseFormat = isRecord(payload.response_format) ? payload.response_format : requestedResponseFormat;
2370
- if (!responseFormat || responseFormat.type === "text") return;
2371
- const schema = responseFormat.type === "json_schema" ? isRecord(responseFormat.json_schema) ? responseFormat.json_schema.schema : responseFormat.schema : responseFormat.type === "json_object" ? responseFormat.schema : responseFormat;
2372
- if (isRecord(schema)) payload.response_format = {
2373
- type: "json_object",
2374
- schema
2375
- };
2376
- }
2377
- /** Keeps the shared OpenAI transport and adjusts llama-server request compatibility. */
2378
- function wrapLlamaServerStream(ctx) {
2379
- const underlying = ctx.streamFn ?? streamSimple;
2380
- return (model, context, options) => {
2381
- if (model.provider !== "llama-cpp") return underlying(model, context, options);
2382
- const onPayload = options?.onPayload;
2383
- return underlying(model, context, {
2384
- ...options,
2385
- onPayload: async (payload, requestModel) => {
2386
- const customized = await onPayload?.(payload, requestModel) ?? payload;
2387
- if (isRecord(customized)) {
2388
- if ((options?.reasoning ?? ctx.thinkingLevel) === "off") setQwenChatTemplateThinking(customized, false);
2389
- normalizeLlamaServerResponseFormat(customized, options?.responseFormat);
2390
- }
2391
- return customized;
2392
- }
2393
- });
2394
- };
2395
- }
2396
- //#endregion
2397
- //#region extensions/llama-cpp/src/setup.ts
2398
- const BYTES_PER_GB = 1e9;
2399
- const BYTES_PER_MB = 1e6;
2400
- function formatDownloadProgress(label, params) {
2401
- const downloadedSize = Math.max(0, params.downloadedSize);
2402
- const totalSize = Math.max(1, params.totalSize);
2403
- 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)`;
2404
- }
2405
- function describeEmbeddingDownload(isDefault) {
2406
- return isDefault ? "the local embedding model (about 0.3 GB)" : "your configured local embedding model";
2407
- }
2408
- async function configuredCandidates(config) {
2409
- const provider = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2410
- if (!provider?.localService) return [];
2411
- const { resolveDefaultModelForAgent } = await import("openclaw/plugin-sdk/agent-runtime");
2412
- const primary = resolveDefaultModelForAgent({
2413
- cfg: config,
2414
- allowManifestNormalization: false,
2415
- allowPluginNormalization: false
2416
- });
2417
- const primaryId = primary.provider === "llama-cpp" ? primary.model : void 0;
2418
- return provider.models.map((model) => ({
2419
- model,
2420
- provider
2421
- })).toSorted((a, b) => Number(b.model.id === primaryId) - Number(a.model.id === primaryId));
2422
- }
2423
- async function isFile(filePath) {
2424
- return await fs.stat(filePath).then((stat) => stat.isFile()).catch(() => false);
2425
- }
2426
- async function resolveCachedArtifact(source, cacheDir, signal) {
2427
- return await ensureLlamaCppModel({
2428
- source,
2429
- cacheDir,
2430
- download: false,
2431
- signal
2432
- }).catch(() => {
2433
- signal?.throwIfAborted();
2434
- });
2435
- }
2436
- async function resolveCachedCandidate(candidate, signal) {
2437
- const source = resolveLlamaCppModelSource(candidate.model);
2438
- const resolved = resolveCachedLlamaCppModelPath(candidate);
2439
- if (resolved && await isFile(resolved)) return resolved;
2440
- if (candidate.model.id === "gemma-4-e4b-it-q4_k_m") {
2441
- const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
2442
- if (await isFile(legacy)) return legacy;
2443
- }
2444
- if (/^(?:hf|huggingface|https):/iu.test(source)) return await resolveCachedArtifact(source, resolveLlamaCppModelCacheDir(candidate.provider), signal);
2445
- }
2446
- function buildSetupResult(params) {
2447
- const existing = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2448
- const switchingFromExternal = Boolean(existing && !existing.localService);
2449
- return {
2450
- profiles: [],
2451
- ...params.defaultModel ? { defaultModel: params.defaultModel } : {},
2452
- configPatch: {
2453
- ...buildLlamaCppAuthProfileRemovalPatch(params.config),
2454
- models: {
2455
- mode: params.config.models?.mode ?? "merge",
2456
- providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig({
2457
- existing: switchingFromExternal ? void 0 : existing,
2458
- managed: params.managed,
2459
- modelInventory: params.plan === "embedding-only" ? [] : params.model ? [params.model, ...existing?.localService ? existing.models.filter((model) => model.id !== params.model?.id) : []] : existing?.models
2460
- }) }
2461
- }
2462
- }
2463
- };
2464
- }
2465
- async function detectLlamaCppSetup(ctx) {
2466
- const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2467
- const command = existing?.localService?.command;
2468
- const presetPath = existing?.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset");
2469
- if (!command || !path.isAbsolute(command) || !await isFile(command) || !presetPath || !await isFile(presetPath)) return null;
2470
- for (const candidate of await configuredCandidates(ctx.config)) if (await resolveCachedCandidate(candidate, ctx.signal)) return {
2471
- modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
2472
- detail: "Managed llama.cpp server ready"
2473
- };
2474
- return null;
2475
- }
2476
- async function prepareLlamaCppSetup(ctx) {
2477
- const detected = await detectLlamaCppSetup(ctx);
2478
- const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2479
- if (detected?.modelRef !== ctx.modelRef || !existing?.localService?.command) return null;
2480
- const baseUrl = existing.baseUrl?.replace(/\/+$/u, "") ?? "";
2481
- const rootUrl = baseUrl.replace(/\/v1$/u, "");
2482
- return buildSetupResult({
2483
- config: ctx.config,
2484
- plan: "chat",
2485
- defaultModel: ctx.modelRef,
2486
- managed: {
2487
- command: existing.localService.command,
2488
- baseUrl,
2489
- healthUrl: existing.localService.healthUrl ?? `${rootUrl}/health`,
2490
- args: existing.localService.args ?? []
2491
- }
2492
- });
2493
- }
2494
- function resolveEmbeddingSetup(config, cacheDir) {
2495
- const defaults = config.memory?.search;
2496
- const models = listAgentIds(config).flatMap((agentId) => {
2497
- const override = resolveAgentConfig(config, agentId)?.memory?.search;
2498
- if (!(override?.enabled ?? defaults?.enabled ?? true) || (override?.provider ?? defaults?.provider) !== "local") return [];
2499
- return [resolveLlamaCppEmbeddingModel({
2500
- modelPath: override?.local?.modelPath ?? defaults?.local?.modelPath,
2501
- modelCacheDir: cacheDir
2502
- })];
2503
- });
2504
- const model = models[0] ?? resolveLlamaCppEmbeddingModel({ modelCacheDir: cacheDir });
2505
- return {
2506
- model,
2507
- localMemoryIntent: models.length > 0,
2508
- conflict: models.some((candidate) => candidate.source !== model.source)
2509
- };
2510
- }
2511
- async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localMemoryIntent, hardware, asset, runtimeNote) {
2512
- let candidate = candidates[0];
2513
- const configuredPath = candidate ? await resolveCachedCandidate(candidate, ctx.signal) : void 0;
2514
- if (candidate && configuredPath) {
2515
- if (runtimeNote && !await ctx.prompter.confirm({
2516
- message: `${runtimeNote} Use cached ${candidate.model.name} on Gateway host ${os.hostname()} with the verified CPU runtime?`,
2517
- initialValue: false
2518
- })) return;
2519
- return {
2520
- kind: "chat",
2521
- candidate,
2522
- cachedPath: configuredPath
2523
- };
2524
- }
2525
- const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2526
- const provider = existing?.localService ? existing : buildLlamaCppProviderConfig();
2527
- const cacheDir = resolveLlamaCppModelCacheDir(provider);
2528
- if (candidate) {
2529
- const source = resolveLlamaCppModelSource(candidate.model);
2530
- let size;
2531
- try {
2532
- if (path.isAbsolute(source) || !/^[a-z][a-z\d+.-]*:/iu.test(source)) {
2533
- const cachedPath = await ensureLlamaCppModel({
2534
- source,
2535
- cacheDir,
2536
- download: false,
2537
- signal: ctx.signal
2538
- });
2539
- return {
2540
- kind: "chat",
2541
- candidate,
2542
- cachedPath
2543
- };
2544
- }
2545
- size = await resolveLlamaCppModelDownloadSize(source, cacheDir, ctx.signal);
2546
- } catch (error) {
2547
- ctx.signal?.throwIfAborted();
2548
- await ctx.prompter.note(`Cannot use configured model ${candidate.model.name}: ${error instanceof Error ? error.message : String(error)} Check params.modelPath and retry llama.cpp setup.`, "Setup skipped");
2549
- return;
2550
- }
2551
- return await ctx.prompter.confirm({
2552
- message: `${runtimeNote ? `${runtimeNote}\n` : ""}Download ${candidate.model.name} (${size ? `${(size / BYTES_PER_GB).toFixed(1)} GB` : "size unknown"}), ${describeEmbeddingDownload(embeddingModelIsDefault)}, and the verified ${asset.backend.toUpperCase()} runtime on Gateway host ${os.hostname()}, then use this model?`,
2553
- initialValue: false
2554
- }) ? {
2555
- kind: "chat",
2556
- candidate
2557
- } : void 0;
2558
- }
2559
- const cachedModels = /* @__PURE__ */ new Map();
2560
- for (const recipe of resolveLlamaCppModelCandidates(hardware, asset.backend).recipes) {
2561
- const cached = await resolveCachedArtifact(resolveLlamaCppModelSource(recipe.model), cacheDir, ctx.signal);
2562
- if (cached) {
2563
- cachedModels.set(recipe.model.id, cached);
2564
- break;
2565
- }
2566
- }
2567
- const cachedEmbedding = embeddingModelIsDefault && Boolean(await resolveCachedArtifact("hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf", cacheDir, ctx.signal));
2568
- const recommendation = recommendLlamaCppModel(hardware, asset.backend, {
2569
- modelIds: new Set(cachedModels.keys()),
2570
- embedding: cachedEmbedding,
2571
- runtime: await isFile(resolveManagedLlamaServerPaths(asset).command)
2572
- });
2573
- if (recommendation.kind === "recommended") {
2574
- const { recipe } = recommendation;
2575
- const cachedPath = cachedModels.get(recipe.model.id);
2576
- candidate = {
2577
- model: recipe.model,
2578
- provider
2579
- };
2580
- const recommendationSummary = [
2581
- `Runs on Gateway host ${os.hostname()} (${hardware.platform}/${hardware.arch}), using ${asset.backend === "metal" ? "Apple Metal" : asset.backend === "cuda" ? "NVIDIA CUDA" : "the CPU"}.`,
2582
- `${formatLlamaCppMemory(hardware.totalMemoryBytes)} RAM; ${formatLlamaCppMemory(hardware.availableDiskBytes ?? 0)} free disk.`,
2583
- !hardware.sharedDisk ? `${formatLlamaCppMemory(hardware.availableRuntimeDiskBytes ?? 0)} free on the runtime volume.` : void 0,
2584
- runtimeNote,
2585
- recommendation.reason,
2586
- !embeddingModelIsDefault ? "This estimate includes the default embedding model; your configured embedding model may need more memory and disk space." : void 0,
2587
- "OpenClaw will check a real tool call before making this your default model."
2588
- ].filter(Boolean).join("\n");
2589
- if (await ctx.prompter.confirm({
2590
- 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?`}`,
2591
- initialValue: false
2592
- })) return {
2593
- kind: "chat",
2594
- candidate,
2595
- cachedPath
2596
- };
2597
- } else if (!localMemoryIntent) {
2598
- await ctx.prompter.note(recommendation.reason, "Setup skipped");
2599
- return;
2600
- }
2601
- if (localMemoryIntent && existing && (!existing.localService || existing.models.length > 0)) {
2602
- await ctx.prompter.note("Embedding-only setup cannot replace an existing llama.cpp server or configured llama.cpp chat routes. Move those routes to another provider, remove any existing server config, then retry llama.cpp setup.", "Setup skipped");
2603
- return;
2604
- }
2605
- if (localMemoryIntent) {
2606
- if (await ctx.prompter.confirm({
2607
- 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.`,
2608
- initialValue: false
2609
- })) return { kind: "embedding-only" };
2610
- }
2611
- await ctx.prompter.note("Local model setup skipped.", "Setup skipped");
2612
- }
2613
- async function runLlamaCppSetup(ctx) {
2614
- const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2615
- const managedExisting = existing?.localService ? existing : void 0;
2616
- const cacheDir = resolveLlamaCppModelCacheDir(managedExisting);
2617
- const embeddingSetup = resolveEmbeddingSetup(ctx.config, cacheDir);
2618
- if (embeddingSetup.conflict) {
2619
- await ctx.prompter.note("Configured agents resolve to different local embedding models. Set memory.search.local.modelPath and any per-agent overrides to the same value, then retry llama.cpp setup.", "Setup skipped");
2620
- return { profiles: [] };
2621
- }
2622
- const embeddingModel = embeddingSetup.model;
2623
- const hardware = await detectLlamaCppHardware({
2624
- cacheDir,
2625
- signal: ctx.signal
2626
- });
2627
- let asset;
2628
- let runtimeNote;
2629
- try {
2630
- asset = selectLlamaServerAsset(hardware.platform, hardware.arch, hardware.accelerator);
2631
- } catch (error) {
2632
- if (hardware.accelerator.kind !== "cuda") throw error;
2633
- asset = selectLlamaServerAsset(hardware.platform, hardware.arch, { kind: "cpu" });
2634
- runtimeNote = `${error instanceof Error ? error.message : String(error)} This recommendation uses CPU execution.`;
2635
- }
2636
- const plan = await resolveSetupPlan(ctx, await configuredCandidates(ctx.config), embeddingModel.isDefault, embeddingSetup.localMemoryIntent, hardware, asset, runtimeNote);
2637
- if (!plan) return { profiles: [] };
2638
- const progress = ctx.prompter.progress("Preparing managed llama.cpp server…");
2639
- try {
2640
- await ensureLlamaServerInstalled({
2641
- asset,
2642
- signal: ctx.signal,
2643
- onProgress: (status) => progress.update(formatDownloadProgress("llama.cpp runtime", status))
2644
- });
2645
- let chatModel;
2646
- if (plan.kind === "chat") {
2647
- const chatModelPath = plan.cachedPath ?? await ensureLlamaCppModel({
2648
- source: resolveLlamaCppModelSource(plan.candidate.model),
2649
- cacheDir,
2650
- download: true,
2651
- signal: ctx.signal,
2652
- onProgress: (status) => progress.update(formatDownloadProgress(plan.candidate.model.name, status))
2653
- });
2654
- const configuredContext = plan.candidate.model.params?.contextSize;
2655
- chatModel = {
2656
- mode: "configure",
2657
- id: plan.candidate.model.id,
2658
- path: chatModelPath,
2659
- contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : plan.candidate.model.contextTokens,
2660
- maxTokens: plan.candidate.model.maxTokens
2661
- };
2662
- } else chatModel = { mode: "remove" };
2663
- const embeddingModelLabel = embeddingModel.isDefault ? "EmbeddingGemma" : "configured embedding model";
2664
- const embeddingModelPath = await ensureLlamaCppModel({
2665
- source: embeddingModel.source,
2666
- cacheDir,
2667
- download: true,
2668
- signal: ctx.signal,
2669
- onProgress: (status) => progress.update(formatDownloadProgress(embeddingModelLabel, status))
2670
- });
2671
- const managed = await prepareManagedLlamaServer({
2672
- chatModel,
2673
- configuredChatModelIds: plan.kind === "chat" ? plan.candidate.provider.models.map((model) => model.id) : [],
2674
- embeddingModelPath,
2675
- asset,
2676
- isolated: true,
2677
- signal: ctx.signal,
2678
- onProgress: (status) => progress.update(formatDownloadProgress("llama.cpp runtime", status))
2679
- });
2680
- ctx.signal?.throwIfAborted();
2681
- progress.stop("Managed llama.cpp server prepared");
2682
- return buildSetupResult({
2683
- config: ctx.config,
2684
- managed,
2685
- plan: plan.kind,
2686
- ...plan.kind === "chat" ? {
2687
- defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${plan.candidate.model.id}`,
2688
- model: plan.candidate.model
2689
- } : {}
2690
- });
2691
- } catch (error) {
2692
- progress.stop("llama.cpp setup failed");
2693
- const detail = error instanceof Error ? error.message : String(error);
2694
- throw new Error(error instanceof UnsupportedLlamaServerHostError ? `Managed llama.cpp setup is unavailable on this host. ${detail}` : `Managed llama.cpp setup failed. Run openclaw doctor, fix the reported runtime or model issue, then retry. ${detail}`, { cause: error });
2695
- }
2696
- }
2697
- //#endregion
2698
59
  //#region extensions/llama-cpp/src/managed-provider.ts
2699
60
  function wrapLlamaCppStream(ctx) {
2700
- const inner = wrapLlamaServerStream(ctx);
2701
61
  const providerConfig = ctx.config?.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2702
- if (!providerConfig?.localService) return inner;
2703
62
  const selectedModel = ctx.model;
2704
- if (!selectedModel) return;
63
+ if (providerConfig?.localService && !selectedModel) return;
2705
64
  return async (...args) => {
2706
- await ensureManagedLlamaServerForChat({
2707
- provider: providerConfig,
2708
- model: selectedModel
2709
- });
2710
- return inner(...args);
65
+ const { wrapLlamaServerStream } = await import("./.setup/stream-Cu8XUda8.mjs");
66
+ if (providerConfig?.localService && selectedModel) {
67
+ const { ensureManagedLlamaServerForChat } = await import("./.setup/managed-server-C2ukpg0h.mjs");
68
+ const signal = args[2]?.signal;
69
+ signal?.throwIfAborted();
70
+ await ensureManagedLlamaServerForChat({
71
+ provider: providerConfig,
72
+ model: selectedModel,
73
+ ...signal ? { signal } : {}
74
+ });
75
+ signal?.throwIfAborted();
76
+ }
77
+ return wrapLlamaServerStream(ctx)(...args);
2711
78
  };
2712
79
  }
2713
- function registerLlamaCppProvider(api) {
80
+ function registerLlamaCppProvider(api, mediaProvider) {
2714
81
  api.registerProvider({
2715
- id: LLAMA_CPP_PROVIDER_ID,
2716
- label: LLAMA_CPP_PROVIDER_LABEL,
2717
- docsPath: "/plugins/llama-cpp",
2718
- envVars: [LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR],
2719
- auth: [{
2720
- id: "local",
2721
- label: LLAMA_CPP_PROVIDER_LABEL,
2722
- hint: "Choose a Qwen, Gemma, or Muse model for this Gateway’s hardware and install llama.cpp",
2723
- kind: "custom",
2724
- wizard: {
2725
- choiceId: LLAMA_CPP_PROVIDER_ID,
2726
- choiceLabel: "Managed local server",
2727
- choiceHint: "Choose a Qwen, Gemma, or Muse model for this Gateway’s hardware and install llama.cpp",
2728
- groupId: LLAMA_CPP_PROVIDER_ID,
2729
- groupLabel: "Local llama.cpp",
2730
- groupHint: "Managed or external llama.cpp server",
2731
- methodId: "local"
2732
- },
2733
- appGuidedSetup: {
2734
- detect: detectLlamaCppSetup,
2735
- prepare: prepareLlamaCppSetup
2736
- },
2737
- run: runLlamaCppSetup
2738
- }, {
2739
- id: "existing-server",
2740
- label: "Existing llama-server",
2741
- hint: "Connect to an existing local, private, or remote llama.cpp server",
2742
- kind: "custom",
2743
- wizard: {
2744
- choiceId: "llama-cpp-existing-server",
2745
- choiceLabel: "Existing llama-server",
2746
- choiceHint: "Connect to a llama.cpp server managed outside OpenClaw",
2747
- groupId: LLAMA_CPP_PROVIDER_ID,
2748
- groupLabel: "Local llama.cpp",
2749
- groupHint: "Managed or external llama.cpp server",
2750
- methodId: "existing-server"
82
+ ...provider_discovery_default,
83
+ auth: [
84
+ {
85
+ id: "local",
86
+ label: LLAMA_CPP_PROVIDER_LABEL,
87
+ hint: "Choose a Qwen, Gemma, or Muse model for this Gateway’s hardware and install llama.cpp",
88
+ kind: "custom",
89
+ wizard: {
90
+ choiceId: LLAMA_CPP_PROVIDER_ID,
91
+ choiceLabel: "Managed local server",
92
+ choiceHint: "Choose a Qwen, Gemma, or Muse model for this Gateway’s hardware and install llama.cpp",
93
+ groupId: LLAMA_CPP_PROVIDER_ID,
94
+ groupLabel: "Local llama.cpp",
95
+ groupHint: "Managed or external llama.cpp server",
96
+ methodId: "local"
97
+ },
98
+ appGuidedSetup: {
99
+ detect: async (ctx) => (await import("./.setup/setup-Cscvds1K.mjs")).detectLlamaCppSetup(ctx),
100
+ prepare: async (ctx) => (await import("./.setup/setup-Cscvds1K.mjs")).prepareLlamaCppSetup(ctx)
101
+ },
102
+ run: async (ctx) => (await import("./.setup/setup-Cscvds1K.mjs")).runLlamaCppSetup(ctx),
103
+ runNonInteractive: async (ctx) => (await import("./.setup/setup-Cscvds1K.mjs")).configureLlamaCppNonInteractive(ctx)
2751
104
  },
2752
- appGuidedSetup: {
2753
- detect: detectLlamaServerSetup,
2754
- prepare: prepareLlamaServerSetup
105
+ {
106
+ id: "existing-server",
107
+ label: "Existing llama-server",
108
+ hint: "Connect to an existing local, private, or remote llama.cpp server",
109
+ kind: "custom",
110
+ wizard: {
111
+ choiceId: "llama-cpp-existing-server",
112
+ choiceLabel: "Existing llama-server",
113
+ choiceHint: "Connect to a llama.cpp server managed outside OpenClaw",
114
+ groupId: LLAMA_CPP_PROVIDER_ID,
115
+ groupLabel: "Local llama.cpp",
116
+ groupHint: "Managed or external llama.cpp server",
117
+ methodId: "existing-server"
118
+ },
119
+ appGuidedSetup: {
120
+ detect: async (ctx) => (await import("./.setup/setup-sQ_NpNbD.mjs")).detectLlamaServerSetup(ctx),
121
+ prepare: async (ctx) => (await import("./.setup/setup-sQ_NpNbD.mjs")).prepareLlamaServerSetup(ctx)
122
+ },
123
+ run: async (ctx) => (await import("./.setup/setup-sQ_NpNbD.mjs")).runLlamaServerSetup(ctx),
124
+ validateNonInteractive: async (ctx) => (await import("./.setup/setup-sQ_NpNbD.mjs")).validateLlamaServerNonInteractive(ctx),
125
+ runNonInteractive: async (ctx) => (await import("./.setup/setup-sQ_NpNbD.mjs")).configureLlamaServerNonInteractive(ctx)
2755
126
  },
2756
- run: runLlamaServerSetup,
2757
- validateNonInteractive: validateLlamaServerNonInteractive,
2758
- runNonInteractive: configureLlamaServerNonInteractive
2759
- }],
2760
- catalog: {
2761
- order: "late",
2762
- run: async (ctx) => {
2763
- const configured = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2764
- return configured?.localService ? { provider: buildLlamaCppProviderConfig({
2765
- existing: configured,
2766
- modelInventory: configured.models
2767
- }) } : await discoverLlamaServerProvider(ctx);
127
+ {
128
+ id: "local-media",
129
+ label: "Managed local OCR and vision",
130
+ hint: "Recommend, install and verify local image models for this Gateway",
131
+ kind: "custom",
132
+ run: async (ctx) => {
133
+ const { runLlamaCppMediaSetup } = await import("./.setup/media-setup-Blmm3-wk.mjs");
134
+ return await runLlamaCppMediaSetup(ctx, mediaProvider);
135
+ }
2768
136
  }
137
+ ],
138
+ prepareDynamicModel: async (ctx) => {
139
+ if (ctx.config?.models?.providers?.["llama-cpp"]?.localService) return;
140
+ const { prepareLlamaServerDynamicModel } = await import("./.setup/provider-w5p9JK8O.mjs");
141
+ return prepareLlamaServerDynamicModel(ctx);
2769
142
  },
2770
- staticCatalog: {
2771
- order: "late",
2772
- run: async () => ({ provider: buildLlamaCppProviderConfig() })
2773
- },
2774
- resolveSyntheticAuth: ({ providerConfig }) => providerConfig?.localService || shouldUseLlamaServerSyntheticAuth(providerConfig) ? {
2775
- apiKey: LLAMA_CPP_LOCAL_AUTH_MARKER,
2776
- source: providerConfig?.localService ? "managed local llama.cpp server" : hasLlamaServerAuthorizationHeader(providerConfig?.headers) ? "models.providers.llama-cpp.headers.Authorization" : "models.providers.llama-cpp (synthetic local key)",
2777
- mode: "api-key"
2778
- } : void 0,
2779
- shouldDeferSyntheticProfileAuth: ({ resolvedApiKey }) => resolvedApiKey?.trim() === "llama-cpp-local" || resolvedApiKey?.trim() === CUSTOM_LOCAL_AUTH_MARKER,
2780
- normalizeConfig: ({ providerConfig }) => providerConfig.localService ? providerConfig : normalizeLlamaServerProviderConfig(providerConfig),
2781
- prepareDynamicModel: async (ctx) => ctx.config?.models?.providers?.["llama-cpp"]?.localService ? void 0 : await prepareLlamaServerDynamicModel(ctx),
2782
- reconcileLocalService: reconcileManagedLlamaServer,
143
+ reconcileLocalService: async (ctx) => (await import("./.setup/managed-server-C2ukpg0h.mjs")).reconcileManagedLlamaServer(ctx),
2783
144
  wrapSimpleCompletionStreamFn: wrapLlamaCppStream,
2784
145
  wrapStreamFn: wrapLlamaCppStream,
2785
146
  ...buildProviderToolCompatFamilyHooks("llamacpp-gbnf"),
@@ -2791,14 +152,123 @@ function registerLlamaCppProvider(api) {
2791
152
  });
2792
153
  }
2793
154
  //#endregion
155
+ //#region extensions/llama-cpp/src/media-provider.ts
156
+ /** The setup verifier and local_image tool consume this registered media entry point. */
157
+ function createLlamaCppMediaProvider() {
158
+ return {
159
+ id: LLAMA_CPP_PROVIDER_ID,
160
+ capabilities: ["image"],
161
+ describeImage: async (req) => (await import("./.setup/media-provider.runtime-LQf52Hb3.mjs")).describeLlamaCppImage(req),
162
+ describeImages: async (req) => (await import("./.setup/media-provider.runtime-LQf52Hb3.mjs")).describeLlamaCppImages(req)
163
+ };
164
+ }
165
+ //#endregion
166
+ //#region extensions/llama-cpp/src/media-tool.ts
167
+ /** Maps explicit task intent onto the same provider hook used by normal image understanding. */
168
+ function registerLlamaCppMediaTool(api, provider) {
169
+ api.registerTool((ctx) => {
170
+ if (ctx.sandboxed || !provider.describeImage) return null;
171
+ const describeImage = provider.describeImage;
172
+ const getConfig = () => ctx.getRuntimeConfig?.() ?? ctx.runtimeConfig ?? ctx.config ?? api.config;
173
+ const configured = getConfig().models?.providers?.[LLAMA_CPP_PROVIDER_ID];
174
+ if (!isManagedLlamaCppMediaProvider(configured) || !resolveLlamaCppMediaModels(configured)) return null;
175
+ return {
176
+ name: "local_image",
177
+ label: "Local Image",
178
+ description: "Inspect a local image with installed local models. Choose task ocr to transcribe visible text, or vision for photos, charts, diagrams, and spatial questions (default). No cloud fallback or model downloads. The original image remains available.",
179
+ parameters: {
180
+ type: "object",
181
+ properties: {
182
+ path: {
183
+ type: "string",
184
+ minLength: 1,
185
+ description: "Local image path or media:// reference."
186
+ },
187
+ task: {
188
+ type: "string",
189
+ enum: ["ocr", "vision"],
190
+ default: "vision"
191
+ },
192
+ prompt: {
193
+ type: "string",
194
+ maxLength: 8192
195
+ }
196
+ },
197
+ required: ["path"],
198
+ additionalProperties: false
199
+ },
200
+ async execute(_toolCallId, args, signal) {
201
+ signal?.throwIfAborted();
202
+ if (!isRecord(args)) throw new Error("Local image input must contain a path and optional ocr or vision task.");
203
+ const task = args.task === void 0 ? "vision" : args.task;
204
+ if (task !== "ocr" && task !== "vision") throw new Error("Local image task must be ocr or vision.");
205
+ const input = normalizeOptionalString(args.path);
206
+ if (!input) throw new Error("Local image path is required.");
207
+ if (/^[a-z][a-z0-9+.-]*:/iu.test(input) && !input.startsWith("media://") && !/^[a-z]:[\\/]/iu.test(input)) throw new Error("Local image requires a local path or media:// reference; URLs are not accepted.");
208
+ if (args.prompt !== void 0 && (typeof args.prompt !== "string" || args.prompt.length > 8192)) throw new Error("Local image prompt must be a string of at most 8192 characters.");
209
+ const cfg = getConfig();
210
+ const configuredProvider = cfg.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
211
+ const models = resolveLlamaCppMediaModels(configuredProvider);
212
+ if (!isManagedLlamaCppMediaProvider(configuredProvider) || !models || !ctx.agentDir) throw new Error("Run managed local media setup for this agent without an explicit llama.cpp request proxy before using local_image. When using an environment proxy, add the server address to NO_PROXY.");
213
+ const model = configuredProvider?.models.find((entry) => entry.id === models[task]);
214
+ if (!model?.input.includes("image")) throw new Error(`The configured local ${task} model is unavailable. Run managed local media setup again.`);
215
+ if (model.baseUrl !== void 0 && model.baseUrl !== configuredProvider?.baseUrl) throw new Error("The local image model endpoint must match the managed llama.cpp provider. Run managed local media setup again.");
216
+ const workspace = ctx.fsPolicy?.root ?? ctx.workspaceDir;
217
+ const localRoots = ctx.fsPolicy?.workspaceOnly ? workspace ? [path.resolve(workspace)] : [] : (await import("openclaw/plugin-sdk/media-local-roots")).getAgentScopedMediaLocalRoots(cfg, ctx.agentId, workspace);
218
+ const imageConfig = cfg.tools?.media?.image;
219
+ const maxBytes = Math.min(asPositiveSafeInteger(imageConfig?.maxBytes) ?? 10485760, LLAMA_CPP_MEDIA_MAX_BYTES);
220
+ const maxChars = Math.min(asPositiveSafeInteger(imageConfig?.maxChars) ?? 12e3, LLAMA_CPP_MEDIA_MAX_CHARS);
221
+ const timeoutMs = Math.min(imageConfig?.timeoutSeconds === void 0 ? LLAMA_CPP_MEDIA_TIMEOUT_MS : (asPositiveSafeInteger(imageConfig.timeoutSeconds) ?? 600) * 1e3, 2147483647);
222
+ const source = input.startsWith("media://") || input.startsWith("~") || path.isAbsolute(input) ? input : path.resolve(workspace ?? process.cwd(), input);
223
+ signal?.throwIfAborted();
224
+ const image = await api.runtime.media.loadWebMedia(source, {
225
+ maxBytes,
226
+ localRoots: [...localRoots, ...ctx.fsPolicy?.readOnlyRoots ?? []],
227
+ ...signal ? { requestInit: { signal } } : {}
228
+ });
229
+ signal?.throwIfAborted();
230
+ if (image.kind !== "image") throw new Error("Local image input must be an image.");
231
+ const result = await describeImage({
232
+ buffer: image.buffer,
233
+ fileName: image.fileName ?? path.basename(source),
234
+ mime: image.contentType,
235
+ provider: LLAMA_CPP_PROVIDER_ID,
236
+ model: model.id,
237
+ prompt: normalizeOptionalString(args.prompt) ?? (task === "ocr" ? "Transcribe all visible text exactly. Return only the text." : "Describe the image."),
238
+ maxTokens: Math.min(asPositiveSafeInteger(model.maxTokens) ?? 2048, LLAMA_CPP_MEDIA_MAX_TOKENS),
239
+ timeoutMs,
240
+ signal,
241
+ cfg,
242
+ agentId: ctx.agentId,
243
+ agentDir: ctx.agentDir,
244
+ workspaceDir: ctx.workspaceDir
245
+ });
246
+ signal?.throwIfAborted();
247
+ if (!result.text.trim()) throw new Error("The local image model returned no text. Run managed local media setup again.");
248
+ const text = truncateUtf16Safe(result.text, maxChars);
249
+ return textResult(text, {
250
+ text,
251
+ task,
252
+ provider: LLAMA_CPP_PROVIDER_ID,
253
+ model: result.model ?? model.id,
254
+ path: input
255
+ });
256
+ }
257
+ };
258
+ }, { name: "local_image" });
259
+ }
260
+ //#endregion
2794
261
  //#region extensions/llama-cpp/index.ts
2795
262
  var llama_cpp_default = definePluginEntry({
2796
263
  id: "llama-cpp",
2797
264
  name: "llama.cpp Provider",
2798
- description: "Managed and external llama.cpp servers for GGUF chat and embeddings",
265
+ description: "Managed and external llama.cpp servers for GGUF chat, embeddings and local images",
2799
266
  register(api) {
267
+ const mediaProvider = createLlamaCppMediaProvider();
2800
268
  api.registerEmbeddingProvider(llamaCppEmbeddingProviderAdapter);
2801
- registerLlamaCppProvider(api);
269
+ api.registerMediaUnderstandingProvider(mediaProvider);
270
+ registerLlamaCppMediaTool(api, mediaProvider);
271
+ registerLlamaCppProvider(api, mediaProvider);
2802
272
  }
2803
273
  });
2804
274
  //#endregion