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