@openclaw/llama-cpp-provider 2026.7.2-beta.7 → 2026.8.1-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,605 +1,1489 @@
1
- import { createRequire } from "node:module";
1
+ import { C as resolveHomePath, D as resolveLlamaCppModelSource, E as resolveLlamaCppModelCacheDir, O as resolveLlamaCppSyntheticApiKey, S as resolveCachedLlamaCppModelPath, T as resolveLlamaCppDataDir, _ as LLAMA_CPP_DEFAULT_PORT, a as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, b as buildLlamaCppProviderConfig, c as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256, d as DEFAULT_LLAMA_CPP_MODEL_ID, f as DEFAULT_LLAMA_CPP_MODEL_REF, h as DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES, i as DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE, l as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES, m as DEFAULT_LLAMA_CPP_MODEL_SHA256, n as resolveManagedLlamaCppProviderConfig, o as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, p as DEFAULT_LLAMA_CPP_MODEL_REVISION, s as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION, u as DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE, v as LLAMA_CPP_PROVIDER_ID, w as resolveLegacyLlamaCppModelCacheDir, x as meetsLlamaCppDefaultModelRamFloor, y as LLAMA_CPP_PROVIDER_LABEL } from "./managed-provider-config-BDKErKo0.js";
2
2
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
3
- import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
4
- import os from "node:os";
5
3
  import path from "node:path";
6
- import { createLocalEmbeddingProvider } from "openclaw/plugin-sdk/memory-core-host-engine-embeddings";
7
- import { pathToFileURL } from "node:url";
8
- import { randomUUID } from "node:crypto";
9
- import { createAssistantMessageEventStream } from "openclaw/plugin-sdk/llm";
10
- import fs from "node:fs/promises";
11
- //#region extensions/llama-cpp/src/defaults.ts
12
- const LLAMA_CPP_PROVIDER_ID = "llama-cpp";
13
- const LLAMA_CPP_PROVIDER_LABEL = "Local model (llama.cpp)";
14
- const LLAMA_CPP_LOCAL_AUTH_MARKER = "llama-cpp-local";
15
- const LLAMA_CPP_LOCAL_BASE_URL = "local://llama-cpp";
16
- function resolveLlamaCppSyntheticApiKey() {
17
- return LLAMA_CPP_LOCAL_AUTH_MARKER;
18
- }
19
- const DEFAULT_LLAMA_CPP_MODEL_ID = "gemma-4-e4b-it-q4_k_m";
20
- const DEFAULT_LLAMA_CPP_MODEL_REF = `${LLAMA_CPP_PROVIDER_ID}/${DEFAULT_LLAMA_CPP_MODEL_ID}`;
21
- const DEFAULT_LLAMA_CPP_MODEL_URI = "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf";
22
- const DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE = "hf_unsloth_gemma-4-E4B-it-GGUF_gemma-4-E4B-it-Q4_K_M.gguf";
23
- const DEFAULT_LLAMA_CPP_CONTEXT_SIZE = 8192;
24
- const LLAMA_CPP_DEFAULT_MODEL_RAM_FLOOR_BYTES = 16 * 1024 ** 3;
25
- function meetsLlamaCppDefaultModelRamFloor(totalmemBytes = os.totalmem()) {
26
- return totalmemBytes >= LLAMA_CPP_DEFAULT_MODEL_RAM_FLOOR_BYTES;
27
- }
28
- function resolveLlamaCppModelCacheDir(provider) {
29
- const configured = provider?.params?.modelCacheDir;
30
- return typeof configured === "string" && configured.trim() ? resolveHomePath(configured.trim()) : path.join(os.homedir(), ".node-llama-cpp", "models");
31
- }
32
- function resolveHomePath(value) {
33
- if (value === "~") return os.homedir();
34
- if (value.startsWith("~/")) return path.join(os.homedir(), value.slice(2));
35
- return value;
4
+ import { getEmbeddingProvider } from "openclaw/plugin-sdk/embedding-providers";
5
+ import { asBoolean, asOptionalRecord, asPositiveSafeInteger, isRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
6
+ import os from "node:os";
7
+ import { execFile } from "node:child_process";
8
+ import { createHash, randomUUID } from "node:crypto";
9
+ import fs from "node:fs";
10
+ import fsp from "node:fs/promises";
11
+ import JSZip from "jszip";
12
+ import * as tar from "tar";
13
+ import net from "node:net";
14
+ import { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } from "openclaw/plugin-sdk/ssrf-runtime";
15
+ import { fetchConfiguredLocalOriginWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime-internal";
16
+ import { CUSTOM_LOCAL_AUTH_MARKER, applyAuthProfileConfig, buildApiKeyCredential, ensureApiKeyFromEnvOrPrompt, hasConfiguredSecretInput, isNonSecretApiKeyMarker, normalizeOptionalSecretInput, upsertAuthProfileWithLock } from "openclaw/plugin-sdk/provider-auth";
17
+ import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
18
+ import { removeAuthProfileConfig, removeProviderAuthProfilesWithLock, resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
19
+ import { resolveConfiguredSecretInputString } from "openclaw/plugin-sdk/secret-input-runtime";
20
+ import { getCachedLiveCatalogValue } from "openclaw/plugin-sdk/provider-catalog-shared";
21
+ import { SELF_HOSTED_DEFAULT_CONTEXT_WINDOW, SELF_HOSTED_DEFAULT_COST, SELF_HOSTED_DEFAULT_MAX_TOKENS, applyProviderDefaultModel, discoverOpenAICompatibleLocalModels } from "openclaw/plugin-sdk/provider-setup";
22
+ import { selectPreferredLocalModelId } from "openclaw/plugin-sdk/provider-model-shared";
23
+ import { streamSimple } from "openclaw/plugin-sdk/llm";
24
+ import { setQwenChatTemplateThinking } from "openclaw/plugin-sdk/provider-stream-shared";
25
+ //#region extensions/llama-cpp/src/llama-server-assets.ts
26
+ const LLAMA_SERVER_RELEASE = "b10357";
27
+ const LLAMA_SERVER_COMMIT = "689e227db485c6b33d061555e74034c93a867649";
28
+ const LLAMA_SERVER_ASSETS = [
29
+ {
30
+ platform: "darwin",
31
+ arch: "arm64",
32
+ backend: "metal",
33
+ archive: "tar.gz",
34
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-arm64.tar.gz`,
35
+ sha256: "7f464a2d473d53ebb9c1d7d16db1258ec98c371569816491850686e6a4334c52",
36
+ executable: "llama-server"
37
+ },
38
+ {
39
+ platform: "darwin",
40
+ arch: "x64",
41
+ backend: "cpu",
42
+ archive: "tar.gz",
43
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-x64.tar.gz`,
44
+ sha256: "8282cf6b30bfab87080044e98b7b78f2896bfc60414926fae6039a89c0fb6ec2",
45
+ executable: "llama-server"
46
+ },
47
+ {
48
+ platform: "linux",
49
+ arch: "arm64",
50
+ backend: "cpu",
51
+ archive: "tar.gz",
52
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-arm64.tar.gz`,
53
+ sha256: "0653b6aa14de35920824045bca7e48f98f629f41943d0fefab1e317bbe8e22a8",
54
+ executable: "llama-server"
55
+ },
56
+ {
57
+ platform: "linux",
58
+ arch: "x64",
59
+ backend: "cpu",
60
+ archive: "tar.gz",
61
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-x64.tar.gz`,
62
+ sha256: "6b0ba012036e6d727521100158bfcaa73b460fbb31acab2931c9485f347bd16b",
63
+ executable: "llama-server"
64
+ },
65
+ {
66
+ platform: "win32",
67
+ arch: "arm64",
68
+ backend: "cpu",
69
+ archive: "zip",
70
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-arm64.zip`,
71
+ sha256: "a0d73be8d3151d9401fa193f1b83c6d7401191b41786e75f0a60184058333e86",
72
+ executable: "llama-server.exe"
73
+ },
74
+ {
75
+ platform: "win32",
76
+ arch: "x64",
77
+ backend: "cpu",
78
+ archive: "zip",
79
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-x64.zip`,
80
+ sha256: "6c64cc7db679980fcb34bbbe96b2b1df6127e90ccdad2bd6fbe39532fee2fc4e",
81
+ executable: "llama-server.exe"
82
+ }
83
+ ];
84
+ function selectLlamaServerAsset(platform = process.platform, arch = process.arch) {
85
+ const asset = LLAMA_SERVER_ASSETS.find((candidate) => candidate.platform === platform && candidate.arch === arch);
86
+ if (!asset) throw new Error(`No verified llama-server ${LLAMA_SERVER_RELEASE} build is available for ${platform}/${arch}. Install a compatible llama-server manually, then rerun llama.cpp setup with its absolute path.`);
87
+ return asset;
88
+ }
89
+ function resolveManagedLlamaServerPaths(asset = selectLlamaServerAsset()) {
90
+ const installDir = path.join(resolveLlamaCppDataDir(), LLAMA_SERVER_RELEASE, `${asset.platform}-${asset.arch}`);
91
+ return {
92
+ installDir,
93
+ command: path.join(installDir, asset.executable),
94
+ presetPath: path.join(resolveLlamaCppDataDir(), "models.ini")
95
+ };
96
+ }
97
+ //#endregion
98
+ //#region extensions/llama-cpp/src/llama-server-install.ts
99
+ const DOWNLOAD_TIMEOUT_MS = 30 * 6e4;
100
+ const VERSION_TIMEOUT_MS = 15e3;
101
+ const installationPromises = /* @__PURE__ */ new Map();
102
+ function compareVersion(left, right) {
103
+ const leftParts = left.split(".").map(Number);
104
+ const rightParts = right.split(".").map(Number);
105
+ for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
106
+ const delta = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
107
+ if (delta !== 0) return delta;
108
+ }
109
+ return 0;
36
110
  }
37
- function resolveLlamaCppModelSource(model) {
38
- const configured = model.params?.modelPath;
39
- if (typeof configured === "string" && configured.trim()) return resolveHomePath(configured.trim());
40
- return model.id === "gemma-4-e4b-it-q4_k_m" ? DEFAULT_LLAMA_CPP_MODEL_URI : resolveHomePath(model.id);
111
+ function assertSupportedLinuxRuntime(asset) {
112
+ if (asset.platform !== "linux") return;
113
+ const header = asOptionalRecord(asOptionalRecord(process.report?.getReport())?.header);
114
+ const glibc = typeof header?.glibcVersionRuntime === "string" ? header.glibcVersionRuntime : "";
115
+ if (!glibc) throw new Error("The verified Ubuntu llama-server build requires glibc and cannot run on musl/Alpine. Install llama-server manually for this host and configure its absolute path.");
116
+ const minimum = asset.arch === "arm64" ? "2.38" : "2.34";
117
+ if (compareVersion(glibc, minimum) < 0) throw new Error(`The verified llama-server build requires glibc ${minimum}+ on Linux ${asset.arch}; this host has ${glibc}. Install a compatible llama-server manually and configure its absolute path.`);
41
118
  }
42
- function resolveCachedLlamaCppModelPath(params) {
43
- const source = resolveLlamaCppModelSource(params.model);
44
- const cacheDir = resolveLlamaCppModelCacheDir(params.provider);
45
- if (source === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") return path.join(cacheDir, DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
46
- if (/^hf:/i.test(source)) return null;
47
- if (/^https?:\/\//i.test(source)) return null;
48
- const localPath = resolveHomePath(source);
49
- return path.isAbsolute(localPath) ? localPath : path.resolve(cacheDir, localPath);
119
+ function assetUrl(asset) {
120
+ return `https://github.com/ggml-org/llama.cpp/releases/download/${LLAMA_SERVER_RELEASE}/${asset.name}`;
121
+ }
122
+ async function sha256File(filePath) {
123
+ const hash = createHash("sha256");
124
+ await new Promise((resolve, reject) => {
125
+ const input = fs.createReadStream(filePath);
126
+ input.on("data", (chunk) => hash.update(chunk));
127
+ input.once("error", reject);
128
+ input.once("end", resolve);
129
+ });
130
+ return hash.digest("hex");
131
+ }
132
+ function readResponseSha256(response) {
133
+ for (const name of ["x-checksum-sha256", "x-linked-etag"]) {
134
+ const value = response.headers.get(name)?.replace(/^W\//u, "").replaceAll("\"", "").trim();
135
+ if (value && /^[a-f\d]{64}$/iu.test(value)) return value.toLowerCase();
136
+ }
137
+ const encoded = response.headers.get("digest")?.match(/(?:^|,)\s*sha-256=([^,\s]+)/iu)?.[1];
138
+ return encoded ? Buffer.from(encoded, "base64").toString("hex") : void 0;
139
+ }
140
+ async function downloadVerifiedFile(params) {
141
+ const partialPath = `${params.destination}.partial-${randomUUID()}`;
142
+ await fsp.mkdir(path.dirname(params.destination), { recursive: true });
143
+ const { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } = await import("openclaw/plugin-sdk/ssrf-runtime");
144
+ try {
145
+ const { response, release } = await fetchWithSsrFGuard({
146
+ url: params.url,
147
+ signal: params.signal,
148
+ timeoutMs: DOWNLOAD_TIMEOUT_MS,
149
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(params.url),
150
+ requireHttps: true,
151
+ auditContext: "llama-cpp-download"
152
+ });
153
+ try {
154
+ if (!response.ok || !response.body) throw new Error(`download failed: HTTP ${response.status} ${response.statusText}`);
155
+ const expectedSha256 = params.expectedSha256 ?? readResponseSha256(response);
156
+ if (!expectedSha256 && params.requireServerDigest) throw new Error("the download server did not provide a SHA-256 digest; download the GGUF manually and configure its local path");
157
+ const contentLength = Number(response.headers.get("content-length"));
158
+ const totalSize = params.expectedSize ?? (Number.isFinite(contentLength) && contentLength > 0 ? contentLength : 0);
159
+ const handle = await fsp.open(partialPath, "wx", 384);
160
+ const hash = createHash("sha256");
161
+ const reader = response.body.getReader();
162
+ let downloadedSize = 0;
163
+ let previousSize = 0;
164
+ let previousAt = Date.now();
165
+ let rollingBytesPerSecond = 0;
166
+ try {
167
+ for (;;) {
168
+ const { done, value } = await reader.read();
169
+ if (done) break;
170
+ const chunk = Buffer.from(value);
171
+ await handle.writeFile(chunk);
172
+ hash.update(chunk);
173
+ downloadedSize += chunk.byteLength;
174
+ const now = Date.now();
175
+ if (now > previousAt) {
176
+ const currentRate = (downloadedSize - previousSize) * 1e3 / (now - previousAt);
177
+ rollingBytesPerSecond = rollingBytesPerSecond === 0 ? currentRate : rollingBytesPerSecond * .75 + currentRate * .25;
178
+ }
179
+ previousSize = downloadedSize;
180
+ previousAt = now;
181
+ params.onProgress?.({
182
+ downloadedSize,
183
+ totalSize,
184
+ bytesPerSecond: rollingBytesPerSecond
185
+ });
186
+ }
187
+ } finally {
188
+ await handle.close();
189
+ }
190
+ if (params.expectedSize && downloadedSize !== params.expectedSize) throw new Error(`download size mismatch: expected ${params.expectedSize}, got ${downloadedSize}`);
191
+ const actualSha256 = hash.digest("hex");
192
+ if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
193
+ await fsp.rename(partialPath, params.destination);
194
+ } finally {
195
+ await release();
196
+ }
197
+ } finally {
198
+ await fsp.rm(partialPath, { force: true }).catch(() => void 0);
199
+ }
200
+ }
201
+ async function extractZip(archivePath, destination) {
202
+ const zip = await JSZip.loadAsync(await fsp.readFile(archivePath));
203
+ for (const entry of Object.values(zip.files)) {
204
+ const normalized = path.posix.normalize(entry.name);
205
+ if (normalized.startsWith("/") || normalized === ".." || normalized.startsWith("../")) throw new Error(`unsafe path in llama-server archive: ${entry.name}`);
206
+ const outputPath = path.join(destination, ...normalized.split("/"));
207
+ if (entry.dir) await fsp.mkdir(outputPath, { recursive: true });
208
+ else {
209
+ await fsp.mkdir(path.dirname(outputPath), { recursive: true });
210
+ await fsp.writeFile(outputPath, await entry.async("nodebuffer"), { mode: 384 });
211
+ }
212
+ }
213
+ }
214
+ async function findExecutable(root, executable) {
215
+ for (const entry of await fsp.readdir(root, { withFileTypes: true })) {
216
+ const candidate = path.join(root, entry.name);
217
+ if (entry.isFile() && entry.name === executable) return candidate;
218
+ if (entry.isDirectory()) {
219
+ const nested = await findExecutable(candidate, executable).catch(() => void 0);
220
+ if (nested) return nested;
221
+ }
222
+ }
223
+ throw new Error(`llama-server archive does not contain ${executable}`);
224
+ }
225
+ async function runVersion(command) {
226
+ return await new Promise((resolve, reject) => {
227
+ execFile(command, ["--version"], { timeout: VERSION_TIMEOUT_MS }, (error, stdout, stderr) => {
228
+ if (error) reject(new Error(error.message, { cause: error }));
229
+ else resolve(`${stdout}${stderr}`.trim());
230
+ });
231
+ });
50
232
  }
51
- function buildDefaultLlamaCppModel() {
233
+ function formatRuntimeDependencyError(error) {
234
+ const detail = error instanceof Error ? error.message : String(error);
235
+ 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 });
236
+ if (process.platform === "win32") return new Error(`The verified llama-server build could not start. Install the Microsoft Visual C++ 2015-2022 Redistributable, then rerun llama.cpp setup. Detail: ${detail}`, { cause: error });
237
+ return new Error(`The verified llama-server build could not start: ${detail}`, { cause: error });
238
+ }
239
+ async function validateInstalledServer(command) {
240
+ let version;
241
+ try {
242
+ version = await runVersion(command);
243
+ } catch (error) {
244
+ throw formatRuntimeDependencyError(error);
245
+ }
246
+ if (!version.includes(`version: 10357`) || !version.includes("689e227db485c6b33d061555e74034c93a867649".slice(0, 9))) throw new Error(`Unexpected llama-server build at ${command}: expected ${LLAMA_SERVER_RELEASE} (${LLAMA_SERVER_COMMIT.slice(0, 9)}), got ${version || "no version output"}`);
247
+ }
248
+ async function installLlamaServer(asset) {
249
+ assertSupportedLinuxRuntime(asset);
250
+ const { installDir, command } = resolveManagedLlamaServerPaths(asset);
251
+ if (await fsp.stat(command).then((stat) => stat.isFile()).catch(() => false)) {
252
+ await validateInstalledServer(command);
253
+ return command;
254
+ }
255
+ const dataDir = resolveLlamaCppDataDir();
256
+ const archivePath = path.join(dataDir, `.download-${randomUUID()}-${asset.name}`);
257
+ const extractDir = path.join(dataDir, `.extract-${randomUUID()}`);
258
+ await fsp.mkdir(dataDir, { recursive: true });
259
+ try {
260
+ await downloadVerifiedFile({
261
+ url: assetUrl(asset),
262
+ destination: archivePath,
263
+ expectedSha256: asset.sha256
264
+ });
265
+ await fsp.mkdir(extractDir, { recursive: true });
266
+ if (asset.archive === "zip") await extractZip(archivePath, extractDir);
267
+ else await tar.x({
268
+ file: archivePath,
269
+ cwd: extractDir,
270
+ preservePaths: false
271
+ });
272
+ const extractedCommand = await findExecutable(extractDir, asset.executable);
273
+ const extractedRoot = path.dirname(extractedCommand);
274
+ await fsp.chmod(extractedCommand, 493);
275
+ await validateInstalledServer(extractedCommand);
276
+ await fsp.mkdir(path.dirname(installDir), { recursive: true });
277
+ await fsp.rm(installDir, {
278
+ recursive: true,
279
+ force: true
280
+ });
281
+ await fsp.rename(extractedRoot, installDir);
282
+ await validateInstalledServer(command);
283
+ return command;
284
+ } finally {
285
+ await Promise.all([fsp.rm(archivePath, { force: true }), fsp.rm(extractDir, {
286
+ recursive: true,
287
+ force: true
288
+ })]);
289
+ }
290
+ }
291
+ async function ensureLlamaServerInstalled() {
292
+ const asset = selectLlamaServerAsset();
293
+ const key = `${asset.platform}/${asset.arch}/${LLAMA_SERVER_RELEASE}`;
294
+ const pending = installationPromises.get(key) ?? installLlamaServer(asset);
295
+ installationPromises.set(key, pending);
296
+ try {
297
+ return {
298
+ command: await pending,
299
+ asset
300
+ };
301
+ } finally {
302
+ if (installationPromises.get(key) === pending) installationPromises.delete(key);
303
+ }
304
+ }
305
+ //#endregion
306
+ //#region extensions/llama-cpp/src/managed-server.ts
307
+ const modelPromises = /* @__PURE__ */ new Map();
308
+ const chatPreparationPromises = /* @__PURE__ */ new Map();
309
+ function parseHuggingFaceSource(source) {
310
+ const [pathPart, revisionPart] = source.replace(/^(?:hf|huggingface):(?:\/\/)?/iu, "").split("#", 2);
311
+ const [user, repositoryWithTag, ...fileParts] = (pathPart ?? "").split("/");
312
+ const [repository, ...tagParts] = (repositoryWithTag ?? "").split(":");
313
+ if (!user || !repository) throw new Error(`Invalid Hugging Face model URI: ${source}`);
52
314
  return {
53
- id: DEFAULT_LLAMA_CPP_MODEL_ID,
54
- name: "Gemma 4 E4B (Q4_K_M)",
55
- api: "openai-completions",
56
- reasoning: false,
57
- input: ["text"],
58
- cost: {
59
- input: 0,
60
- output: 0,
61
- cacheRead: 0,
62
- cacheWrite: 0
63
- },
64
- contextWindow: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
65
- contextTokens: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
66
- maxTokens: 2048,
67
- params: {
68
- modelPath: DEFAULT_LLAMA_CPP_MODEL_URI,
69
- contextSize: "auto"
70
- },
71
- compat: {
72
- supportsTools: true,
73
- supportsUsageInStreaming: true
315
+ user,
316
+ repository,
317
+ file: fileParts.length > 0 ? fileParts.join("/") : void 0,
318
+ revision: revisionPart || "main",
319
+ tag: tagParts.length > 0 ? tagParts.join(":") : void 0
320
+ };
321
+ }
322
+ async function resolveHuggingFaceArtifact(source, signal) {
323
+ const parsed = parseHuggingFaceSource(source);
324
+ let file = parsed.file;
325
+ let expectedSize;
326
+ if (!file) {
327
+ const tag = parsed.tag || "latest";
328
+ const manifestUrl = `https://huggingface.co/v2/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/manifests/${encodeURIComponent(tag)}`;
329
+ const { response, release } = await fetchWithSsrFGuard({
330
+ url: manifestUrl,
331
+ init: { headers: { "user-agent": "llama-cpp" } },
332
+ signal,
333
+ requireHttps: true,
334
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(manifestUrl),
335
+ auditContext: "llama-cpp-model-resolve"
336
+ });
337
+ try {
338
+ if (!response.ok) throw new Error(`Cannot resolve ${source}: HTTP ${response.status}`);
339
+ const ggufFile = asOptionalRecord(asOptionalRecord(await response.json())?.ggufFile);
340
+ file = typeof ggufFile?.rfilename === "string" ? ggufFile.rfilename : void 0;
341
+ expectedSize = typeof ggufFile?.size === "number" ? ggufFile.size : void 0;
342
+ if (!file) throw new Error(`Hugging Face did not return a GGUF file for ${source}`);
343
+ } finally {
344
+ await release();
74
345
  }
346
+ }
347
+ const encodedFile = file.split("/").map(encodeURIComponent).join("/");
348
+ const url = `https://huggingface.co/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/resolve/${encodeURIComponent(parsed.revision)}/${encodedFile}?download=true`;
349
+ const treeUrl = `https://huggingface.co/api/models/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/tree/${encodeURIComponent(parsed.revision)}?recursive=true&expand=true`;
350
+ const { response: treeResponse, release: releaseTree } = await fetchWithSsrFGuard({
351
+ url: treeUrl,
352
+ signal,
353
+ requireHttps: true,
354
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(treeUrl),
355
+ auditContext: "llama-cpp-model-resolve"
356
+ });
357
+ let tree;
358
+ try {
359
+ if (!treeResponse.ok) throw new Error(`Cannot read Hugging Face integrity metadata for ${source}: HTTP ${treeResponse.status}`);
360
+ tree = await treeResponse.json();
361
+ } finally {
362
+ await releaseTree();
363
+ }
364
+ const fileRow = Array.isArray(tree) ? tree.map((entry) => asOptionalRecord(entry)).find((entry) => entry?.path === file) : void 0;
365
+ const lfs = asOptionalRecord(fileRow?.lfs);
366
+ const expectedSha256 = typeof lfs?.oid === "string" && /^[a-f\d]{64}$/iu.test(lfs.oid) ? lfs.oid.toLowerCase() : void 0;
367
+ expectedSize = expectedSize ?? (typeof fileRow?.size === "number" ? fileRow.size : void 0);
368
+ if (!expectedSha256) throw new Error(`Hugging Face did not publish a SHA-256 LFS identity for ${source}`);
369
+ return {
370
+ fileName: `hf_${[
371
+ parsed.user,
372
+ parsed.repository,
373
+ parsed.revision === "main" ? "" : parsed.revision,
374
+ ...file.split("/")
375
+ ].filter(Boolean).join("_").replace(/[^a-z\d._-]+/giu, "_")}`,
376
+ url,
377
+ expectedSize,
378
+ expectedSha256
379
+ };
380
+ }
381
+ function defaultArtifact(source) {
382
+ if (source === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") return {
383
+ fileName: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE,
384
+ url: `https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF/resolve/${DEFAULT_LLAMA_CPP_MODEL_REVISION}/gemma-4-E4B-it-Q4_K_M.gguf?download=true`,
385
+ expectedSize: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
386
+ expectedSha256: DEFAULT_LLAMA_CPP_MODEL_SHA256
387
+ };
388
+ if (source === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") return {
389
+ fileName: DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE,
390
+ 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`,
391
+ expectedSize: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES,
392
+ expectedSha256: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256
75
393
  };
76
394
  }
77
- function buildLlamaCppProviderConfig(existing) {
78
- const defaultModel = buildDefaultLlamaCppModel();
79
- const configuredModels = existing?.models ?? [];
80
- const models = configuredModels.some((model) => model.id === defaultModel.id) ? configuredModels : [...configuredModels, defaultModel];
395
+ async function assertGguf(filePath) {
396
+ const handle = await fsp.open(filePath, "r").catch((error) => {
397
+ 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 });
398
+ throw error;
399
+ });
400
+ try {
401
+ const header = Buffer.alloc(4);
402
+ const { bytesRead } = await handle.read(header, 0, header.length, 0);
403
+ if (bytesRead !== 4 || header.toString("ascii") !== "GGUF") throw new Error(`Model is not a GGUF file: ${filePath}`);
404
+ } finally {
405
+ await handle.close();
406
+ }
407
+ }
408
+ async function resolveModelArtifact(source, signal) {
409
+ const known = defaultArtifact(source);
410
+ if (known) return known;
411
+ if (/^(?:hf|huggingface):/iu.test(source)) return await resolveHuggingFaceArtifact(source, signal);
412
+ if (/^https:\/\//iu.test(source)) {
413
+ const url = new URL(source);
414
+ const fileName = path.basename(decodeURIComponent(url.pathname));
415
+ if (!fileName.toLowerCase().includes(".gguf")) throw new Error(`Remote model URL must name a GGUF file: ${source}`);
416
+ return {
417
+ fileName,
418
+ url: source
419
+ };
420
+ }
421
+ throw new Error(`Unsupported remote model URI: ${source}`);
422
+ }
423
+ async function ensureLlamaCppModel(params) {
424
+ const localSource = resolveHomePath(params.source);
425
+ if (!/^(?:hf|huggingface|https):/iu.test(localSource)) {
426
+ const localPath = path.isAbsolute(localSource) ? localSource : path.resolve(params.cacheDir, localSource);
427
+ await assertGguf(localPath);
428
+ return localPath;
429
+ }
430
+ const artifact = await resolveModelArtifact(localSource, params.signal);
431
+ const destination = path.join(params.cacheDir, artifact.fileName);
432
+ const pending = modelPromises.get(destination);
433
+ if (pending) return await pending;
434
+ const load = (async () => {
435
+ if (await fsp.stat(destination).then((stat) => stat.isFile()).catch(() => false)) if (artifact.expectedSha256) {
436
+ if (await sha256File(destination) === artifact.expectedSha256) return destination;
437
+ } else {
438
+ await assertGguf(destination);
439
+ return destination;
440
+ }
441
+ if (!params.download) throw new Error(`Model is not cached at ${destination}`);
442
+ await downloadVerifiedFile({
443
+ url: artifact.url,
444
+ destination,
445
+ expectedSha256: artifact.expectedSha256,
446
+ expectedSize: artifact.expectedSize,
447
+ requireServerDigest: !artifact.expectedSha256,
448
+ signal: params.signal,
449
+ onProgress: params.onProgress
450
+ });
451
+ await assertGguf(destination);
452
+ return destination;
453
+ })();
454
+ modelPromises.set(destination, load);
455
+ try {
456
+ return await load;
457
+ } finally {
458
+ if (modelPromises.get(destination) === load) modelPromises.delete(destination);
459
+ }
460
+ }
461
+ function assertIniValue(value, label) {
462
+ if (/\r|\n/u.test(value)) throw new Error(`${label} cannot contain a newline`);
463
+ return value;
464
+ }
465
+ function renderLlamaServerPreset(params) {
466
+ const embeddingId = assertIniValue(params.embeddingModelId, "llama.cpp embedding model id");
467
+ if (embeddingId.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
468
+ const lines = ["version = 1", ""];
469
+ if (params.chatModelId || params.chatModelPath) {
470
+ if (!params.chatModelId || !params.chatModelPath) throw new Error("llama.cpp chat model id and path must be provided together");
471
+ const chatId = assertIniValue(params.chatModelId, "llama.cpp model id");
472
+ if (chatId.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
473
+ lines.push(`[${chatId}]`, `model = ${assertIniValue(params.chatModelPath, "llama.cpp model path")}`, `ctx-size = ${params.contextSize ?? 65536}`, `n-predict = ${params.maxTokens ?? 2048}`, "jinja = true", "");
474
+ }
475
+ lines.push(`[${embeddingId}]`, `model = ${assertIniValue(params.embeddingModelPath, "llama.cpp embedding model path")}`, "embedding = true", "");
476
+ return lines.join("\n");
477
+ }
478
+ async function writePreset(presetPath, contents) {
479
+ await fsp.mkdir(path.dirname(presetPath), { recursive: true });
480
+ const temporary = `${presetPath}.tmp-${randomUUID()}`;
481
+ await fsp.writeFile(temporary, contents, { mode: 384 });
482
+ await fsp.rename(temporary, presetPath);
483
+ }
484
+ async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT) {
485
+ const tryPort = async (port) => await new Promise((resolve) => {
486
+ const server = net.createServer();
487
+ server.unref();
488
+ server.once("error", () => resolve(void 0));
489
+ server.listen(port, "127.0.0.1", () => {
490
+ const address = server.address();
491
+ const selected = typeof address === "object" && address ? address.port : void 0;
492
+ server.close(() => resolve(selected));
493
+ });
494
+ });
495
+ return await tryPort(preferred) ?? await tryPort(0) ?? Promise.reject(/* @__PURE__ */ new Error("No loopback port is available for llama-server"));
496
+ }
497
+ async function prepareManagedLlamaServer(params) {
498
+ const { command, asset } = await ensureLlamaServerInstalled();
499
+ const { presetPath } = resolveManagedLlamaServerPaths(asset);
500
+ await writePreset(presetPath, renderLlamaServerPreset({
501
+ ...params.chatModelPath ? {
502
+ chatModelId: params.chatModelId ?? "gemma-4-e4b-it-q4_k_m",
503
+ chatModelPath: params.chatModelPath
504
+ } : {},
505
+ contextSize: params.contextSize,
506
+ maxTokens: params.maxTokens,
507
+ embeddingModelId: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
508
+ embeddingModelPath: params.embeddingModelPath
509
+ }));
510
+ const port = params.port ?? await findAvailableLlamaServerPort();
511
+ const rootUrl = `http://127.0.0.1:${port}`;
81
512
  return {
82
- ...existing,
83
- baseUrl: existing?.baseUrl ?? LLAMA_CPP_LOCAL_BASE_URL,
84
- api: existing?.api ?? "openai-completions",
85
- models
513
+ command,
514
+ baseUrl: `${rootUrl}/v1`,
515
+ healthUrl: `${rootUrl}/health`,
516
+ args: [
517
+ "--host",
518
+ "127.0.0.1",
519
+ "--port",
520
+ String(port),
521
+ "--models-preset",
522
+ presetPath,
523
+ "--models-max",
524
+ "2",
525
+ "--metrics",
526
+ "--no-ui"
527
+ ]
86
528
  };
87
529
  }
88
- //#endregion
89
- //#region extensions/llama-cpp/src/node-llama.runtime.ts
90
- function isNodeLlamaCppMissing(error) {
91
- if (!(error instanceof Error)) return false;
92
- return error.code === "ERR_MODULE_NOT_FOUND" && error.message.includes("node-llama-cpp");
93
- }
94
- function formatErrorMessage(error) {
95
- return error instanceof Error ? error.message : String(error);
96
- }
97
- function formatLlamaCppSetupError(error) {
98
- const detail = formatErrorMessage(error);
99
- const missing = isNodeLlamaCppMissing(error);
100
- return [
101
- "Local llama.cpp is unavailable.",
102
- missing ? "Reason: node-llama-cpp is missing or failed to install." : detail ? `Reason: ${detail}` : void 0,
103
- missing && detail ? `Detail: ${detail}` : null,
104
- "To enable local GGUF models:",
105
- "1) Install the official provider plugin: openclaw plugins install @openclaw/llama-cpp-provider",
106
- "2) Use Node 24 for native installs/updates.",
107
- "3) If you use pnpm from source: pnpm approve-builds, then pnpm rebuild node-llama-cpp."
108
- ].filter(Boolean).join("\n");
109
- }
110
- const requireFromPlugin = createRequire(import.meta.url);
111
- function resolveNodeLlamaCppImportUrl() {
112
- return pathToFileURL(requireFromPlugin.resolve("node-llama-cpp")).href;
113
- }
114
- async function importNodeLlamaCpp() {
115
- return await import(resolveNodeLlamaCppImportUrl());
530
+ async function ensureManagedLlamaServerForChat(params) {
531
+ if (!params.provider.localService || !params.provider.baseUrl) return;
532
+ const cacheDir = resolveLlamaCppModelCacheDir(params.provider);
533
+ const key = JSON.stringify([
534
+ params.provider.baseUrl,
535
+ params.model.id,
536
+ params.model.params,
537
+ cacheDir
538
+ ]);
539
+ const pending = chatPreparationPromises.get(key) ?? (async () => {
540
+ let chatModelPath = resolveCachedLlamaCppModelPath({
541
+ model: params.model,
542
+ provider: params.provider
543
+ });
544
+ if (!chatModelPath && resolveLlamaCppModelSource(params.model) === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") {
545
+ const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), "hf_unsloth_gemma-4-E4B-it-GGUF_gemma-4-E4B-it-Q4_K_M.gguf");
546
+ if (await fsp.stat(legacy).then((stat) => stat.isFile()).catch(() => false)) chatModelPath = legacy;
547
+ }
548
+ chatModelPath = await ensureLlamaCppModel({
549
+ source: chatModelPath ?? resolveLlamaCppModelSource(params.model),
550
+ cacheDir,
551
+ download: false
552
+ });
553
+ const configuredContext = params.model.params?.contextSize;
554
+ const port = Number(new URL(params.provider.baseUrl).port);
555
+ await prepareManagedLlamaServer({
556
+ chatModelId: params.model.id,
557
+ chatModelPath,
558
+ contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : params.model.contextTokens,
559
+ maxTokens: params.model.maxTokens,
560
+ embeddingModelPath: path.join(cacheDir, "hf_ggml-org_embeddinggemma-300m-qat-Q8_0.gguf"),
561
+ port: Number.isInteger(port) && port > 0 ? port : void 0
562
+ });
563
+ })();
564
+ chatPreparationPromises.set(key, pending);
565
+ try {
566
+ await pending;
567
+ } catch (error) {
568
+ if (chatPreparationPromises.get(key) === pending) chatPreparationPromises.delete(key);
569
+ throw error;
570
+ }
571
+ }
572
+ async function fetchEndpoint(url, accept) {
573
+ try {
574
+ const configuredLocalOriginBaseUrl = new URL(url).origin;
575
+ const { response, release } = await fetchConfiguredLocalOriginWithSsrFGuard({
576
+ url,
577
+ configuredLocalOriginBaseUrl,
578
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(configuredLocalOriginBaseUrl),
579
+ timeoutMs: 2500,
580
+ auditContext: "llama-server-inspect"
581
+ });
582
+ try {
583
+ if (!response.ok) return { ok: false };
584
+ return {
585
+ ok: true,
586
+ value: accept === "json" ? await response.json() : await response.text()
587
+ };
588
+ } finally {
589
+ await release();
590
+ }
591
+ } catch {
592
+ return { ok: false };
593
+ }
594
+ }
595
+ async function inspectLlamaServerRuntime(params) {
596
+ const root = params.baseUrl.replace(/\/v1\/?$/u, "").replace(/\/+$/u, "");
597
+ const query = `model=${encodeURIComponent(params.modelId)}&autoload=false`;
598
+ const [health, models, props, metrics] = await Promise.all([
599
+ fetchEndpoint(`${root}/health`, "json"),
600
+ fetchEndpoint(`${root}/models`, "json"),
601
+ fetchEndpoint(`${root}/props?${query}`, "json"),
602
+ fetchEndpoint(`${root}/metrics?${query}`, "text")
603
+ ]);
604
+ const propsRecord = asOptionalRecord(props.value);
605
+ const modalities = asOptionalRecord(propsRecord?.modalities);
606
+ const modelsRecord = asOptionalRecord(models.value);
607
+ const selected = (Array.isArray(modelsRecord?.data) ? modelsRecord.data : []).map((row) => asOptionalRecord(row)).find((row) => row?.id === params.modelId);
608
+ const pathValue = typeof propsRecord?.model_path === "string" ? propsRecord.model_path : typeof selected?.path === "string" ? selected.path : void 0;
609
+ return {
610
+ engine: "llama.cpp",
611
+ state: health.ok && models.ok && props.ok && metrics.ok && !params.loadError ? "ready" : "failed",
612
+ backend: params.backend,
613
+ buildInfo: typeof propsRecord?.build_info === "string" ? propsRecord.build_info : void 0,
614
+ model: {
615
+ id: params.modelId,
616
+ ...pathValue ? { path: pathValue } : {}
617
+ },
618
+ capabilities: {
619
+ vision: modalities?.vision === true,
620
+ draft: false
621
+ },
622
+ endpoints: {
623
+ health: health.ok ? "ready" : "unavailable",
624
+ models: models.ok ? "ready" : "unavailable",
625
+ props: props.ok ? "ready" : "unavailable",
626
+ metrics: metrics.ok ? "ready" : "unavailable"
627
+ },
628
+ ...params.loadError ? { loadError: params.loadError } : {}
629
+ };
116
630
  }
117
631
  //#endregion
118
632
  //#region extensions/llama-cpp/src/embedding-provider.ts
119
- const LLAMA_CPP_EMBEDDING_PROVIDER_ID = "local";
120
633
  const LOCAL_EMBEDDING_RUNTIME_FACTS = Symbol.for("openclaw.localEmbeddingRuntimeFacts");
121
- const DEFAULT_LLAMA_CPP_EMBEDDING_MODEL = "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf";
122
- const DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_CACHE_FILE_NAME = "hf_ggml-org_embeddinggemma-300m-qat-Q8_0.gguf";
123
- function normalizeOptionalString(value) {
124
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
125
- }
634
+ const preparedEmbeddingServers = /* @__PURE__ */ new Map();
126
635
  function readLocalOptions(options) {
127
636
  return options.local ?? {};
128
637
  }
129
- function createLlamaCppCacheKeyData(model, outputDimensionality) {
638
+ function createCacheKeyData(model, dimensions) {
130
639
  return {
131
- provider: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
640
+ provider: "local",
132
641
  model,
133
- ...typeof outputDimensionality === "number" ? { outputDimensionality } : {}
642
+ ...typeof dimensions === "number" ? { outputDimensionality: dimensions } : {}
134
643
  };
135
644
  }
136
- function resolveLlamaCppModelIdentity(local, modelPath, outputDimensionality) {
137
- const modelCacheDir = normalizeOptionalString(local.modelCacheDir) ?? path.join(os.homedir(), ".node-llama-cpp", "models");
138
- const resolvedDefaultModelPath = path.resolve(modelCacheDir, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_CACHE_FILE_NAME);
139
- const resolvedModelPath = /^(?:hf:|https?:\/\/)/i.test(modelPath) ? void 0 : path.resolve(modelCacheDir, modelPath);
140
- if (modelPath !== DEFAULT_LLAMA_CPP_EMBEDDING_MODEL && resolvedModelPath !== resolvedDefaultModelPath) return {
645
+ function resolveModelIdentity(local, modelPath, dimensions) {
646
+ const configuredCacheDir = normalizeOptionalString(local.modelCacheDir) ?? resolveLlamaCppModelCacheDir();
647
+ const currentDefaultPath = path.resolve(configuredCacheDir, DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE);
648
+ const legacyDefaultPath = path.resolve(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE);
649
+ const resolvedPath = /^(?:hf:|https?:\/\/)/iu.test(modelPath) ? void 0 : path.resolve(configuredCacheDir, modelPath);
650
+ if (!(modelPath === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf" || resolvedPath === currentDefaultPath || resolvedPath === legacyDefaultPath)) return {
141
651
  model: modelPath,
142
- cacheKeyData: createLlamaCppCacheKeyData(modelPath, outputDimensionality),
652
+ cacheKeyData: createCacheKeyData(modelPath, dimensions),
143
653
  aliases: []
144
654
  };
145
- const aliasModels = /* @__PURE__ */ new Set([resolvedDefaultModelPath, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_CACHE_FILE_NAME]);
146
- if (modelPath !== DEFAULT_LLAMA_CPP_EMBEDDING_MODEL) aliasModels.add(modelPath);
655
+ const aliases = /* @__PURE__ */ new Set([
656
+ currentDefaultPath,
657
+ legacyDefaultPath,
658
+ DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE
659
+ ]);
660
+ if (modelPath !== "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") aliases.add(modelPath);
147
661
  return {
148
662
  model: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
149
- cacheKeyData: createLlamaCppCacheKeyData(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, outputDimensionality),
150
- aliases: Array.from(aliasModels, (aliasModel) => ({
151
- model: aliasModel,
152
- cacheKeyData: createLlamaCppCacheKeyData(aliasModel, outputDimensionality)
663
+ cacheKeyData: createCacheKeyData(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, dimensions),
664
+ aliases: [...aliases].map((model) => ({
665
+ model,
666
+ cacheKeyData: createCacheKeyData(model, dimensions)
153
667
  }))
154
668
  };
155
669
  }
156
- function textFromEmbeddingInput(input) {
157
- return typeof input === "string" ? input : input.text;
670
+ function resolveConfiguredProvider(options) {
671
+ return resolveManagedLlamaCppProviderConfig(options.config);
158
672
  }
159
- function toMemoryEmbeddingInput(input) {
160
- return typeof input === "string" ? { text: input } : input;
673
+ function resolveProviderPort(provider) {
674
+ const port = Number(new URL(provider.baseUrl ?? "").port);
675
+ if (!Number.isInteger(port) || port <= 0) throw new Error("Managed llama.cpp provider baseUrl must include a loopback port.");
676
+ return port;
161
677
  }
162
- function copyLocalRuntimeFacts(source, target) {
163
- const getRuntimeFacts = Reflect.get(source, LOCAL_EMBEDDING_RUNTIME_FACTS);
164
- if (typeof getRuntimeFacts === "function") Object.defineProperty(target, LOCAL_EMBEDDING_RUNTIME_FACTS, {
678
+ async function prepareEmbeddingServer(options, embeddingSource) {
679
+ const provider = resolveConfiguredProvider(options);
680
+ const configuredPrimary = options.config.agents?.defaults?.model;
681
+ const primaryRef = typeof configuredPrimary === "string" ? configuredPrimary : configuredPrimary?.primary;
682
+ const primaryId = primaryRef?.startsWith(`llama-cpp/`) ? primaryRef.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
683
+ const chatModel = provider.models.find((model) => model.id === primaryId) ?? provider.models.find((model) => model.id !== "gemma-4-e4b-it-q4_k_m") ?? provider.models[0];
684
+ const cacheDir = resolveLlamaCppModelCacheDir(provider);
685
+ const key = JSON.stringify([
686
+ provider.baseUrl,
687
+ chatModel?.id ?? null,
688
+ embeddingSource,
689
+ cacheDir
690
+ ]);
691
+ const pending = preparedEmbeddingServers.get(key) ?? (async () => {
692
+ const [chatModelPath, embeddingModelPath] = await Promise.all([chatModel ? ensureLlamaCppModel({
693
+ source: resolveLlamaCppModelSource(chatModel),
694
+ cacheDir,
695
+ download: false
696
+ }) : Promise.resolve(void 0), ensureLlamaCppModel({
697
+ source: embeddingSource,
698
+ cacheDir,
699
+ download: true
700
+ })]);
701
+ const configuredContext = chatModel?.params?.contextSize;
702
+ await prepareManagedLlamaServer({
703
+ ...chatModel ? { chatModelId: chatModel.id } : {},
704
+ chatModelPath,
705
+ contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : chatModel?.contextTokens,
706
+ maxTokens: chatModel?.maxTokens,
707
+ embeddingModelPath,
708
+ port: resolveProviderPort(provider)
709
+ });
710
+ })();
711
+ preparedEmbeddingServers.set(key, pending);
712
+ try {
713
+ await pending;
714
+ } catch (error) {
715
+ if (preparedEmbeddingServers.get(key) === pending) preparedEmbeddingServers.delete(key);
716
+ throw error;
717
+ }
718
+ }
719
+ function wrapProvider(params) {
720
+ let runtimeFacts;
721
+ const refreshFacts = async (loadError) => {
722
+ runtimeFacts = await inspectLlamaServerRuntime({
723
+ baseUrl: params.baseUrl,
724
+ modelId: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
725
+ backend: selectLlamaServerAsset().backend,
726
+ loadError
727
+ });
728
+ };
729
+ const withFacts = async (operation) => {
730
+ try {
731
+ const value = await operation();
732
+ await refreshFacts();
733
+ return value;
734
+ } catch (error) {
735
+ await refreshFacts(error instanceof Error ? error.message : String(error));
736
+ throw error;
737
+ }
738
+ };
739
+ const wrapped = {
740
+ id: "local",
741
+ model: params.canonicalModel,
742
+ dimensions: params.provider.dimensions,
743
+ maxInputTokens: params.provider.maxInputTokens,
744
+ embed: async (input, callOptions) => await withFacts(async () => await params.provider.embed(input, callOptions)),
745
+ embedBatch: async (inputs, callOptions) => await withFacts(async () => await params.provider.embedBatch(inputs, callOptions)),
746
+ close: params.provider.close
747
+ };
748
+ Object.defineProperty(wrapped, LOCAL_EMBEDDING_RUNTIME_FACTS, {
165
749
  enumerable: false,
166
- value: getRuntimeFacts
750
+ value: () => runtimeFacts
167
751
  });
752
+ return wrapped;
168
753
  }
169
- function adaptMemoryEmbeddingProvider(provider) {
170
- const adapted = {
171
- id: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
172
- model: provider.model,
173
- maxInputTokens: provider.maxInputTokens,
174
- embed: async (input, callOptions) => await provider.embedQuery(textFromEmbeddingInput(input), { signal: callOptions?.signal }),
175
- embedBatch: async (inputs, callOptions) => {
176
- if (provider.embedBatchInputs) return await provider.embedBatchInputs(inputs.map(toMemoryEmbeddingInput), { signal: callOptions?.signal });
177
- return await provider.embedBatch(inputs.map(textFromEmbeddingInput), { signal: callOptions?.signal });
178
- },
179
- close: provider.close
754
+ const llamaCppEmbeddingProviderAdapter = {
755
+ id: "local",
756
+ defaultModel: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
757
+ transport: "local",
758
+ formatSetupError: (error) => `Managed local embeddings are unavailable. Run \`openclaw configure\`, choose llama.cpp, and retry. ${error instanceof Error ? error.message : String(error)}`,
759
+ resolveIndexIdentity: (options) => {
760
+ const local = readLocalOptions(options);
761
+ return resolveModelIdentity(local, normalizeOptionalString(local.modelPath) ?? "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf", options.dimensions);
762
+ },
763
+ create: async (options) => {
764
+ const local = readLocalOptions(options);
765
+ const modelPath = normalizeOptionalString(local.modelPath) ?? "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf";
766
+ await prepareEmbeddingServer(options, modelPath);
767
+ const genericAdapter = getEmbeddingProvider("openai-compatible", options.config);
768
+ if (!genericAdapter) throw new Error("OpenAI-compatible embedding transport is unavailable.");
769
+ const result = await genericAdapter.create({
770
+ ...options,
771
+ provider: LLAMA_CPP_PROVIDER_ID,
772
+ model: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
773
+ remote: void 0
774
+ });
775
+ if (!result.provider) return result;
776
+ const identity = resolveModelIdentity(local, modelPath, options.dimensions);
777
+ return {
778
+ provider: wrapProvider({
779
+ provider: result.provider,
780
+ canonicalModel: identity.model,
781
+ baseUrl: resolveConfiguredProvider(options).baseUrl ?? ""
782
+ }),
783
+ runtime: {
784
+ id: "local",
785
+ inlineQueryTimeoutMs: 5 * 6e4,
786
+ inlineBatchTimeoutMs: 10 * 6e4,
787
+ cacheKeyData: identity.cacheKeyData,
788
+ ...identity.aliases.length > 0 ? { indexIdentityAliases: identity.aliases } : {}
789
+ }
790
+ };
791
+ }
792
+ };
793
+ //#endregion
794
+ //#region extensions/llama-cpp/src/external-server/auth.ts
795
+ function hasLlamaServerAuthorizationHeader(headers) {
796
+ const record = asOptionalRecord(headers);
797
+ if (!record) return false;
798
+ return Object.entries(record).some(([name, value]) => name.trim().toLowerCase() === "authorization" && hasConfiguredSecretInput(value));
799
+ }
800
+ function shouldUseLlamaServerSyntheticAuth(providerConfig) {
801
+ const apiKey = normalizeOptionalSecretInput(providerConfig?.apiKey)?.trim();
802
+ return !(hasConfiguredSecretInput(providerConfig?.apiKey) && apiKey !== resolveLlamaCppSyntheticApiKey() && apiKey !== CUSTOM_LOCAL_AUTH_MARKER);
803
+ }
804
+ async function resolveLlamaServerProviderHeaders(params) {
805
+ const headers = asOptionalRecord(params.headers);
806
+ if (!headers) return;
807
+ const resolved = {};
808
+ for (const [name, value] of Object.entries(headers)) {
809
+ if (!params.config) {
810
+ if (typeof value === "string" && value.trim()) resolved[name] = value.trim();
811
+ continue;
812
+ }
813
+ const path = `models.providers.${LLAMA_CPP_PROVIDER_ID}.headers.${name}`;
814
+ const header = await resolveConfiguredSecretInputString({
815
+ config: params.config,
816
+ env: params.env ?? process.env,
817
+ value,
818
+ path,
819
+ unresolvedReasonStyle: "detailed"
820
+ });
821
+ if (header.unresolvedRefReason) throw new Error(`${path}: ${header.unresolvedRefReason}`);
822
+ if (header.value) resolved[name] = header.value;
823
+ }
824
+ return Object.keys(resolved).length > 0 ? resolved : void 0;
825
+ }
826
+ async function resolveLlamaServerRuntimeApiKey(params) {
827
+ const apiKey = (await resolveApiKeyForProvider({
828
+ provider: LLAMA_CPP_PROVIDER_ID,
829
+ cfg: params.config,
830
+ agentDir: params.agentDir,
831
+ profileId: params.profileId,
832
+ lockedProfile: params.profileId !== void 0
833
+ })).apiKey?.trim();
834
+ return apiKey && !isNonSecretApiKeyMarker(apiKey) ? apiKey : void 0;
835
+ }
836
+ //#endregion
837
+ //#region extensions/llama-cpp/src/external-server/defaults.ts
838
+ const LLAMA_SERVER_DEFAULT_ORIGIN = "http://127.0.0.1:8080";
839
+ const LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR = "LLAMA_SERVER_API_KEY";
840
+ //#endregion
841
+ //#region extensions/llama-cpp/src/external-server/endpoint.ts
842
+ function toFetchableBaseUrl(value) {
843
+ if (/^[a-z][a-z\d+.-]*:\/\//iu.test(value)) return value;
844
+ return `http://${value}`;
845
+ }
846
+ /** Resolves the server origin and its OpenAI-compatible `/v1` inference base. */
847
+ function resolveLlamaServerEndpoint(configuredBaseUrl) {
848
+ const configured = configuredBaseUrl?.trim() || "http://127.0.0.1:8080";
849
+ const parsed = new URL(toFetchableBaseUrl(configured));
850
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new TypeError(`Unsupported llama-server protocol: ${parsed.protocol}`);
851
+ if (parsed.username || parsed.password) throw new TypeError("llama-server base URL must not contain credentials");
852
+ parsed.pathname = parsed.pathname.replace(/\/+$/u, "").replace(/\/v1$/iu, "") || "/";
853
+ parsed.search = "";
854
+ parsed.hash = "";
855
+ const origin = parsed.toString().replace(/\/$/u, "");
856
+ return {
857
+ origin,
858
+ inferenceBaseUrl: `${origin}/v1`
180
859
  };
181
- copyLocalRuntimeFacts(provider, adapted);
182
- return adapted;
183
- }
184
- async function createLlamaCppMemoryEmbeddingProvider(options, runtimeOptions = {}) {
185
- const createOptions = buildMemoryCreateOptions(options, options.outputDimensionality);
186
- const local = readLocalOptions(createOptions);
187
- const provider = await createLocalEmbeddingProvider(createOptions, { nodeLlamaCppImportUrl: runtimeOptions.nodeLlamaCppImportUrl ?? resolveNodeLlamaCppImportUrl() });
188
- const identity = resolveLlamaCppModelIdentity(local, provider.model, createOptions.outputDimensionality);
189
- const identifiedProvider = identity.model === provider.model ? provider : {
190
- ...provider,
191
- model: identity.model
860
+ }
861
+ /** Canonicalizes persisted provider config for the shared OpenAI transport. */
862
+ function normalizeLlamaServerProviderConfig(provider) {
863
+ const endpoint = resolveLlamaServerEndpoint(provider.baseUrl);
864
+ const request = provider.request ?? {};
865
+ const normalizedRequest = typeof request.allowPrivateNetwork === "boolean" ? request : {
866
+ ...request,
867
+ allowPrivateNetwork: true
192
868
  };
193
- if (identifiedProvider !== provider) copyLocalRuntimeFacts(provider, identifiedProvider);
194
869
  return {
195
- provider: identifiedProvider,
196
- runtime: createLlamaCppEmbeddingProviderRuntime(identity)
870
+ ...provider,
871
+ baseUrl: endpoint.inferenceBaseUrl,
872
+ api: "openai-completions",
873
+ request: normalizedRequest
197
874
  };
198
875
  }
199
- async function createLlamaCppEmbeddingProviderResult(options, runtimeOptions = {}) {
200
- const result = await createLlamaCppMemoryEmbeddingProvider(buildMemoryCreateOptions(options, options.dimensions), runtimeOptions);
876
+ //#endregion
877
+ //#region extensions/llama-cpp/src/external-server/models.ts
878
+ function normalizeStatus(value) {
879
+ switch (value) {
880
+ case "unloaded":
881
+ case "loading":
882
+ case "loaded":
883
+ case "sleeping":
884
+ case "downloading": return value;
885
+ default: return "unknown";
886
+ }
887
+ }
888
+ function resolveContextWindow(props) {
889
+ return asPositiveSafeInteger(props?.default_generation_settings?.n_ctx) ?? asPositiveSafeInteger(props?.n_ctx) ?? SELF_HOSTED_DEFAULT_CONTEXT_WINDOW;
890
+ }
891
+ function resolveMaxTokens(props, contextWindow) {
892
+ const params = props?.default_generation_settings?.params;
893
+ const advertised = asPositiveSafeInteger(params?.max_tokens) ?? asPositiveSafeInteger(params?.n_predict);
894
+ return Math.min(advertised ?? SELF_HOSTED_DEFAULT_MAX_TOKENS, contextWindow);
895
+ }
896
+ function resolveInput(row, props) {
897
+ const advertised = row.architecture?.input_modalities;
898
+ return Array.isArray(advertised) && advertised.includes("image") || props?.modalities?.vision === true ? ["text", "image"] : ["text"];
899
+ }
900
+ function buildCompat(props) {
901
+ const caps = props?.chat_template_caps;
201
902
  return {
202
- provider: result.provider ? adaptMemoryEmbeddingProvider(result.provider) : null,
203
- runtime: result.runtime
903
+ supportsStore: false,
904
+ supportsDeveloperRole: false,
905
+ supportsReasoningEffort: false,
906
+ supportsTemperature: true,
907
+ supportsUsageInStreaming: true,
908
+ supportsTools: asBoolean(caps?.supports_tools) === true && asBoolean(caps?.supports_tool_calls) === true,
909
+ supportsStrictMode: false,
910
+ supportsJsonSchemaResponseFormat: true,
911
+ requiresStringContent: !(asBoolean(caps?.supports_typed_content) === true),
912
+ maxTokensField: "max_tokens"
204
913
  };
205
914
  }
206
- function buildMemoryCreateOptions(options, outputDimensionality) {
207
- const local = readLocalOptions(options);
208
- const modelPath = normalizeOptionalString(local.modelPath) || DEFAULT_LLAMA_CPP_EMBEDDING_MODEL;
915
+ /** Maps one llama-server model row plus optional runtime properties into OpenClaw config. */
916
+ function mapLlamaServerModel(row, props) {
917
+ const id = typeof row.id === "string" ? row.id.trim() : "";
918
+ if (!id || row.object !== void 0 && row.object !== "model") return null;
919
+ const contextWindow = resolveContextWindow(props);
209
920
  return {
210
- config: options.config,
211
- agentDir: options.agentDir,
212
- provider: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
213
- fallback: "none",
214
- remote: options.remote,
215
- model: modelPath,
216
- inputType: options.inputType,
217
- queryInputType: options.queryInputType,
218
- documentInputType: options.documentInputType,
219
- local: {
220
- ...local,
221
- modelPath
921
+ config: {
922
+ id,
923
+ name: id,
924
+ reasoning: false,
925
+ input: resolveInput(row, props),
926
+ cost: { ...SELF_HOSTED_DEFAULT_COST },
927
+ contextWindow,
928
+ contextTokens: contextWindow,
929
+ maxTokens: resolveMaxTokens(props, contextWindow),
930
+ compat: buildCompat(props)
222
931
  },
223
- outputDimensionality
932
+ status: normalizeStatus(row.status?.value),
933
+ failed: row.status?.failed === true
224
934
  };
225
935
  }
226
- function createLlamaCppEmbeddingProviderRuntime(identity) {
936
+ /** Keeps explicit rows first and appends models discovered from the server. */
937
+ function mergeLlamaServerModels(params) {
938
+ const explicit = Array.isArray(params.explicitModels) ? params.explicitModels : [];
939
+ const merged = [...explicit];
940
+ const seen = new Set(explicit.map((model) => model.id));
941
+ for (const discovered of params.discoveredModels) {
942
+ if (seen.has(discovered.config.id)) continue;
943
+ seen.add(discovered.config.id);
944
+ merged.push(discovered.config);
945
+ }
946
+ return merged;
947
+ }
948
+ function buildLlamaServerProviderConfig(params) {
949
+ return normalizeLlamaServerProviderConfig({
950
+ ...params.configured,
951
+ baseUrl: params.configured?.baseUrl ?? "http://127.0.0.1:8080",
952
+ models: mergeLlamaServerModels({
953
+ explicitModels: params.configured?.models,
954
+ discoveredModels: params.discoveredModels
955
+ })
956
+ });
957
+ }
958
+ //#endregion
959
+ //#region extensions/llama-cpp/src/external-server/discovery.ts
960
+ /** Discovers llama-server models without loading, waking, or unloading them. */
961
+ async function discoverLlamaServer(params) {
962
+ const endpoint = resolveLlamaServerEndpoint(params.baseUrl);
963
+ const apiKey = params.apiKey?.trim();
964
+ const cacheTtlMs = Boolean(apiKey && !isNonSecretApiKeyMarker(apiKey)) || Boolean(params.headers && Object.keys(params.headers).length > 0) ? 0 : Math.max(0, params.cacheTtlMs ?? 3e4);
965
+ return await getCachedLiveCatalogValue({
966
+ keyParts: [
967
+ "llama-cpp",
968
+ "external",
969
+ endpoint.origin
970
+ ],
971
+ ttlMs: cacheTtlMs,
972
+ shouldCache: (result) => result.kind === "success",
973
+ load: async () => {
974
+ const result = await discoverOpenAICompatibleLocalModels({
975
+ baseUrl: endpoint.inferenceBaseUrl,
976
+ serverBaseUrl: endpoint.origin,
977
+ apiKey: params.apiKey,
978
+ headers: params.headers,
979
+ label: "llama-server",
980
+ healthPath: "/health",
981
+ modelsPathOrder: "server-first",
982
+ routerModelProps: true,
983
+ timeoutMs: params.timeoutMs ?? 5e3,
984
+ signal: params.signal,
985
+ rawResult: true
986
+ });
987
+ if (result.kind !== "success") return {
988
+ ...result,
989
+ endpoint
990
+ };
991
+ return {
992
+ kind: "success",
993
+ endpoint,
994
+ models: result.rows.flatMap(({ model, props }) => {
995
+ const mapped = mapLlamaServerModel(model, props);
996
+ return mapped ? [mapped] : [];
997
+ })
998
+ };
999
+ }
1000
+ });
1001
+ }
1002
+ //#endregion
1003
+ //#region extensions/llama-cpp/src/external-server/provider.ts
1004
+ /** Discovers external llama-server models for provider runtime resolution. */
1005
+ async function discoverLlamaServerProvider(ctx) {
1006
+ const configured = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1007
+ const auth = ctx.resolveProviderApiKey(LLAMA_CPP_PROVIDER_ID);
1008
+ const headers = await resolveLlamaServerProviderHeaders({
1009
+ config: ctx.config,
1010
+ env: ctx.env,
1011
+ headers: configured?.headers
1012
+ });
1013
+ const discovery = await discoverLlamaServer({
1014
+ baseUrl: configured?.baseUrl,
1015
+ apiKey: hasLlamaServerAuthorizationHeader(headers) ? void 0 : auth.discoveryApiKey ?? auth.apiKey,
1016
+ headers
1017
+ });
1018
+ if (discovery.kind !== "success") return configured ? { provider: buildLlamaServerProviderConfig({
1019
+ configured,
1020
+ discoveredModels: []
1021
+ }) } : null;
1022
+ return { provider: buildLlamaServerProviderConfig({
1023
+ configured: {
1024
+ ...configured,
1025
+ baseUrl: discovery.endpoint.inferenceBaseUrl,
1026
+ models: configured?.models ?? []
1027
+ },
1028
+ discoveredModels: discovery.models
1029
+ }) };
1030
+ }
1031
+ async function prepareLlamaServerDynamicModel(ctx) {
1032
+ const apiKey = await resolveLlamaServerRuntimeApiKey({
1033
+ config: ctx.config,
1034
+ agentDir: ctx.agentDir,
1035
+ profileId: ctx.authProfileId
1036
+ });
1037
+ const headers = await resolveLlamaServerProviderHeaders({
1038
+ config: ctx.config,
1039
+ env: process.env,
1040
+ headers: ctx.providerConfig?.headers
1041
+ });
1042
+ const discovery = await discoverLlamaServer({
1043
+ baseUrl: ctx.providerConfig?.baseUrl,
1044
+ apiKey: hasLlamaServerAuthorizationHeader(headers) ? void 0 : apiKey,
1045
+ headers,
1046
+ cacheTtlMs: 0
1047
+ });
1048
+ const model = discovery.kind === "success" ? discovery.models.find((entry) => entry.config.id === ctx.modelId) : void 0;
1049
+ if (!model) return;
227
1050
  return {
228
- id: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
229
- inlineQueryTimeoutMs: 5 * 6e4,
230
- inlineBatchTimeoutMs: 10 * 6e4,
231
- cacheKeyData: identity.cacheKeyData,
232
- ...identity.aliases.length > 0 ? { indexIdentityAliases: identity.aliases } : {}
1051
+ ...model.config,
1052
+ provider: LLAMA_CPP_PROVIDER_ID,
1053
+ api: ctx.providerConfig?.api ?? "openai-completions",
1054
+ baseUrl: resolveLlamaServerEndpoint(ctx.providerConfig?.baseUrl).inferenceBaseUrl,
1055
+ input: model.config.input.filter((entry) => entry === "text" || entry === "image")
233
1056
  };
234
1057
  }
235
- const llamaCppEmbeddingProviderAdapter = {
236
- id: LLAMA_CPP_EMBEDDING_PROVIDER_ID,
237
- defaultModel: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
238
- transport: "local",
239
- formatSetupError: formatLlamaCppSetupError,
240
- resolveIndexIdentity: (options) => {
241
- const createOptions = buildMemoryCreateOptions(options, options.dimensions);
242
- const local = readLocalOptions(createOptions);
243
- return resolveLlamaCppModelIdentity(local, normalizeOptionalString(local.modelPath) ?? DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, createOptions.outputDimensionality);
244
- },
245
- create: async (options) => await createLlamaCppEmbeddingProviderResult(options)
246
- };
247
1058
  //#endregion
248
- //#region extensions/llama-cpp/src/inference-provider.ts
249
- let loadedModel;
250
- let llamaInstance;
251
- let operationQueue = Promise.resolve();
252
- function zeroCostUsage(input = 0, output = 0) {
1059
+ //#region extensions/llama-cpp/src/auth-config.ts
1060
+ const LLAMA_CPP_DEFAULT_PROFILE_ID = `${LLAMA_CPP_PROVIDER_ID}:default`;
1061
+ function buildLlamaCppAuthProfileRemovalPatch(config) {
1062
+ const profileExists = Boolean(config.auth?.profiles?.[LLAMA_CPP_DEFAULT_PROFILE_ID]);
1063
+ const referencedOrders = Object.entries(config.auth?.order ?? {}).filter(([, ids]) => ids.includes(LLAMA_CPP_DEFAULT_PROFILE_ID));
1064
+ if (!profileExists && referencedOrders.length === 0) return {};
1065
+ const authPatch = {};
1066
+ if (profileExists) Reflect.set(authPatch, "profiles", { [LLAMA_CPP_DEFAULT_PROFILE_ID]: void 0 });
1067
+ if (referencedOrders.length > 0) Reflect.set(authPatch, "order", Object.fromEntries(referencedOrders.map(([providerId, ids]) => {
1068
+ const next = ids.filter((id) => id !== LLAMA_CPP_DEFAULT_PROFILE_ID);
1069
+ return [providerId, next.length > 0 ? next : void 0];
1070
+ })));
1071
+ return { auth: authPatch };
1072
+ }
1073
+ //#endregion
1074
+ //#region extensions/llama-cpp/src/external-server/setup.ts
1075
+ function selectSetupModelId(discovery) {
1076
+ const healthy = discovery.models.filter((model) => !model.failed);
1077
+ const ids = (healthy.length > 0 ? healthy : discovery.models).toSorted((left, right) => {
1078
+ const leftLoaded = left.status === "loaded" || left.status === "sleeping";
1079
+ const rightLoaded = right.status === "loaded" || right.status === "sleeping";
1080
+ return Number(rightLoaded) - Number(leftLoaded);
1081
+ }).map((model) => model.config.id);
1082
+ return selectPreferredLocalModelId(ids) ?? ids[0];
1083
+ }
1084
+ function describeDiscoveryFailure(result) {
1085
+ switch (result.kind) {
1086
+ case "unreachable": return `llama-server could not be reached at ${result.endpoint.origin}.`;
1087
+ case "http-error": return `llama-server returned HTTP ${result.status} for ${result.path} at ${result.endpoint.origin}.`;
1088
+ case "invalid-response": return `llama-server returned an invalid response from ${result.path} at ${result.endpoint.origin}.`;
1089
+ default: throw new Error("Unexpected llama-server discovery result");
1090
+ }
1091
+ }
1092
+ function stripAuthOverrides(provider, removeAuthorization) {
1093
+ if (!provider) return provider;
1094
+ const headers = removeAuthorization ? stripAuthorizationHeader(provider.headers) : provider.headers;
253
1095
  return {
254
- input,
255
- output,
256
- cacheRead: 0,
257
- cacheWrite: 0,
258
- totalTokens: input + output,
259
- cost: {
260
- input: 0,
261
- output: 0,
262
- cacheRead: 0,
263
- cacheWrite: 0,
264
- total: 0
265
- }
1096
+ ...provider,
1097
+ auth: void 0,
1098
+ apiKey: void 0,
1099
+ ...removeAuthorization ? { headers } : {}
1100
+ };
1101
+ }
1102
+ function stripEndpointCredentials(provider) {
1103
+ if (!provider) return;
1104
+ const { localService: _localService, ...external } = provider;
1105
+ if (!provider.localService) return {
1106
+ ...external,
1107
+ auth: void 0,
1108
+ apiKey: void 0,
1109
+ headers: void 0
1110
+ };
1111
+ const { auth: _auth, apiKey: _apiKey, headers: _headers, localService: _managedService, models: _managedModels, params: managedParams, timeoutSeconds: _managedTimeout, ...externalProvider } = provider;
1112
+ const { modelCacheDir: _modelCacheDir, ...params } = managedParams ?? {};
1113
+ return {
1114
+ ...externalProvider,
1115
+ models: [],
1116
+ params: Object.keys(params).length > 0 ? params : void 0
266
1117
  };
267
1118
  }
268
- function buildMessage(params) {
1119
+ function hasEndpointChanged(provider, baseUrl) {
1120
+ if (!provider) return false;
1121
+ return resolveLlamaServerEndpoint(provider.baseUrl ?? "http://127.0.0.1:8080").inferenceBaseUrl !== resolveLlamaServerEndpoint(baseUrl).inferenceBaseUrl;
1122
+ }
1123
+ function stripLlamaServerEndpointAuth(config) {
1124
+ const withoutProfile = removeAuthProfileConfig(config, LLAMA_CPP_DEFAULT_PROFILE_ID);
1125
+ const provider = withoutProfile.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1126
+ const endpointSafeProvider = stripEndpointCredentials(provider);
1127
+ if (!endpointSafeProvider) return withoutProfile;
269
1128
  return {
270
- role: "assistant",
271
- content: params.content,
272
- api: params.model.api,
273
- provider: params.model.provider,
274
- model: params.model.id,
275
- stopReason: params.stopReason,
276
- usage: params.usage ?? zeroCostUsage(),
277
- timestamp: Date.now(),
278
- ...params.errorMessage ? { errorMessage: params.errorMessage } : {}
1129
+ ...withoutProfile,
1130
+ models: {
1131
+ ...withoutProfile.models,
1132
+ providers: {
1133
+ ...withoutProfile.models?.providers,
1134
+ [LLAMA_CPP_PROVIDER_ID]: endpointSafeProvider
1135
+ }
1136
+ }
279
1137
  };
280
1138
  }
281
- function extractText(content) {
282
- if (typeof content === "string") return content;
283
- if (!Array.isArray(content)) return "";
284
- return content.filter((part) => Boolean(part) && typeof part === "object" && part.type === "text").map((part) => part.text).join("");
285
- }
286
- function normalizeArguments(value) {
287
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
288
- }
289
- async function resolveLlamaCppResponseGrammar(params) {
290
- const responseFormat = params.responseFormat;
291
- if (!responseFormat) return;
292
- if (Object.keys(responseFormat).length === 0) return await params.llama.getGrammarFor("json");
293
- if (responseFormat.type === "json_object") return await params.llama.getGrammarFor("json");
294
- if (responseFormat.type === "text") return;
295
- if (responseFormat.type === "json_schema") {
296
- const schema = normalizeArguments(normalizeArguments(responseFormat.json_schema).schema);
297
- return Object.keys(schema).length > 0 ? await params.llama.createGrammarForJsonSchema(schema) : await params.llama.getGrammarFor("json");
298
- }
299
- return await params.llama.createGrammarForJsonSchema(responseFormat);
300
- }
301
- function mapContextToLlamaChatHistory(context) {
302
- const history = [];
303
- if (context.systemPrompt?.trim()) history.push({
304
- type: "system",
305
- text: context.systemPrompt
1139
+ function stripAuthorizationHeader(headers) {
1140
+ const filtered = Object.fromEntries(Object.entries(headers ?? {}).filter(([name]) => name.toLowerCase() !== "authorization"));
1141
+ return Object.keys(filtered).length > 0 ? filtered : void 0;
1142
+ }
1143
+ function buildExistingProviderConfig(params) {
1144
+ const configured = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1145
+ const endpointSafe = params.resetEndpoint ? stripEndpointCredentials(configured) : configured;
1146
+ const existing = params.persistence.kind === "preserve" ? endpointSafe : stripAuthOverrides(endpointSafe, params.persistence.kind === "upsert");
1147
+ return buildLlamaServerProviderConfig({
1148
+ configured: {
1149
+ ...existing,
1150
+ baseUrl: params.discovery.endpoint.inferenceBaseUrl,
1151
+ models: existing?.models ?? []
1152
+ },
1153
+ discoveredModels: params.discovery.models
306
1154
  });
307
- const toolResults = new Map(context.messages.filter((message) => message.role === "toolResult").map((message) => [message.toolCallId, extractText(message.content)]));
308
- const consumedToolResults = /* @__PURE__ */ new Set();
309
- for (const message of context.messages) {
310
- if (message.role === "user") {
311
- history.push({
312
- type: "user",
313
- text: extractText(message.content)
314
- });
315
- continue;
1155
+ }
1156
+ function buildSetupResult$1(params) {
1157
+ return {
1158
+ profiles: params.persistence.kind === "upsert" ? [{
1159
+ profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
1160
+ credential: buildApiKeyCredential(LLAMA_CPP_PROVIDER_ID, params.persistence.credential, void 0, { config: params.config })
1161
+ }] : [],
1162
+ defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${params.modelId}`,
1163
+ configPatch: {
1164
+ ...params.persistence.kind === "remove" ? buildLlamaCppAuthProfileRemovalPatch(params.config) : {},
1165
+ models: {
1166
+ mode: params.config.models?.mode ?? "merge",
1167
+ providers: { [LLAMA_CPP_PROVIDER_ID]: buildExistingProviderConfig(params) }
1168
+ }
316
1169
  }
317
- if (message.role === "assistant") {
318
- const response = [];
319
- for (const part of message.content) {
320
- if (part.type === "text") {
321
- if (part.text) response.push(part.text);
322
- continue;
323
- }
324
- if (part.type === "thinking") {
325
- if (part.thinking) response.push({
326
- type: "segment",
327
- segmentType: "thought",
328
- text: part.thinking,
329
- ended: true
330
- });
331
- continue;
1170
+ };
1171
+ }
1172
+ async function removeDefaultAuthProfile(agentDir) {
1173
+ if (!await removeProviderAuthProfilesWithLock({
1174
+ agentDir,
1175
+ provider: "llama-cpp",
1176
+ profileIds: [LLAMA_CPP_DEFAULT_PROFILE_ID]
1177
+ })) throw new Error("Failed to remove the previous llama-server auth profile; wait a moment and retry.");
1178
+ }
1179
+ async function discoverForSetup(params) {
1180
+ const providerConfig = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1181
+ const headers = await resolveLlamaServerProviderHeaders({
1182
+ config: params.config,
1183
+ env: params.env,
1184
+ headers: providerConfig?.headers
1185
+ });
1186
+ const resolvedApiKey = !hasLlamaServerAuthorizationHeader(headers) ? await resolveLlamaServerRuntimeApiKey({ config: params.config }) : void 0;
1187
+ return await discoverLlamaServer({
1188
+ baseUrl: params.baseUrl,
1189
+ apiKey: resolvedApiKey,
1190
+ headers,
1191
+ signal: params.signal,
1192
+ cacheTtlMs: 0
1193
+ });
1194
+ }
1195
+ async function discoverWithAccess(params) {
1196
+ return await discoverLlamaServer({
1197
+ baseUrl: params.baseUrl,
1198
+ apiKey: params.apiKey,
1199
+ headers: params.headers,
1200
+ signal: params.signal,
1201
+ cacheTtlMs: 0
1202
+ });
1203
+ }
1204
+ /** Read-only discovery for the guided local-provider setup ladder. */
1205
+ async function detectLlamaServerSetup(ctx) {
1206
+ const provider = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1207
+ if (provider?.localService) return null;
1208
+ const baseUrl = provider?.baseUrl ?? "http://127.0.0.1:8080";
1209
+ let discovery;
1210
+ try {
1211
+ discovery = await discoverForSetup({
1212
+ config: ctx.config,
1213
+ baseUrl,
1214
+ env: ctx.env,
1215
+ signal: ctx.signal
1216
+ });
1217
+ } catch {
1218
+ return null;
1219
+ }
1220
+ if (discovery.kind !== "success") return null;
1221
+ const modelId = selectSetupModelId(discovery);
1222
+ if (!modelId) return null;
1223
+ return {
1224
+ modelRef: `${LLAMA_CPP_PROVIDER_ID}/${modelId}`,
1225
+ detail: `${modelId} at ${discovery.endpoint.origin}`
1226
+ };
1227
+ }
1228
+ /** Rechecks one guided candidate and returns the config needed for a live probe. */
1229
+ async function prepareLlamaServerSetup(ctx) {
1230
+ const provider = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1231
+ if (provider?.localService) return null;
1232
+ let discovery;
1233
+ try {
1234
+ discovery = await discoverForSetup({
1235
+ config: ctx.config,
1236
+ baseUrl: provider?.baseUrl ?? "http://127.0.0.1:8080",
1237
+ env: ctx.env,
1238
+ signal: ctx.signal
1239
+ });
1240
+ } catch {
1241
+ return null;
1242
+ }
1243
+ if (discovery.kind !== "success") return null;
1244
+ const prefix = `${LLAMA_CPP_PROVIDER_ID}/`;
1245
+ const modelId = ctx.modelRef.startsWith(prefix) ? ctx.modelRef.slice(prefix.length) : "";
1246
+ if (!modelId || !discovery.models.some((model) => model.config.id === modelId)) return null;
1247
+ return buildSetupResult$1({
1248
+ config: ctx.config,
1249
+ discovery,
1250
+ modelId,
1251
+ resetEndpoint: false,
1252
+ persistence: { kind: "preserve" }
1253
+ });
1254
+ }
1255
+ /** Interactive setup for an existing llama-server endpoint. */
1256
+ async function runLlamaServerSetup(ctx) {
1257
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1258
+ const defaultOrigin = resolveLlamaServerEndpoint(existing?.baseUrl).origin;
1259
+ const endpoint = resolveLlamaServerEndpoint(await ctx.prompter.text({
1260
+ message: `${LLAMA_CPP_PROVIDER_LABEL} URL`,
1261
+ initialValue: defaultOrigin,
1262
+ placeholder: LLAMA_SERVER_DEFAULT_ORIGIN,
1263
+ validate: (value) => value?.trim() ? void 0 : "Required"
1264
+ }));
1265
+ const endpointChanged = Boolean(existing?.localService) || hasEndpointChanged(existing, endpoint.inferenceBaseUrl);
1266
+ const resolvedHeaders = endpointChanged ? void 0 : await resolveLlamaServerProviderHeaders({
1267
+ config: ctx.config,
1268
+ env: ctx.env,
1269
+ headers: existing?.headers
1270
+ });
1271
+ const usesApiKey = await ctx.prompter.confirm({
1272
+ message: "Does this llama-server require an API key?",
1273
+ initialValue: false
1274
+ });
1275
+ let apiKey;
1276
+ let headers = resolvedHeaders;
1277
+ let persistence;
1278
+ if (!usesApiKey) persistence = { kind: "remove" };
1279
+ else {
1280
+ const hasConfiguredProfile = Boolean(ctx.config.auth?.profiles?.[LLAMA_CPP_DEFAULT_PROFILE_ID]);
1281
+ const profileApiKey = !endpointChanged && !hasLlamaServerAuthorizationHeader(resolvedHeaders) && hasConfiguredProfile ? await resolveLlamaServerRuntimeApiKey({
1282
+ config: ctx.config,
1283
+ agentDir: ctx.agentDir,
1284
+ profileId: LLAMA_CPP_DEFAULT_PROFILE_ID
1285
+ }) : void 0;
1286
+ if (profileApiKey) {
1287
+ apiKey = profileApiKey;
1288
+ persistence = { kind: "preserve" };
1289
+ } else {
1290
+ let credentialInput;
1291
+ apiKey = await ensureApiKeyFromEnvOrPrompt({
1292
+ config: endpointChanged ? stripLlamaServerEndpointAuth(ctx.config) : ctx.config,
1293
+ env: endpointChanged ? {} : ctx.env,
1294
+ provider: LLAMA_CPP_PROVIDER_ID,
1295
+ envLabel: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
1296
+ promptMessage: "Enter the llama-server API key",
1297
+ normalize: (value) => value.trim(),
1298
+ validate: (value) => value.trim() ? void 0 : "Required",
1299
+ prompter: ctx.prompter,
1300
+ secretInputMode: ctx.secretInputMode,
1301
+ setCredential: async (input) => {
1302
+ credentialInput = input;
332
1303
  }
333
- const result = toolResults.get(part.id);
334
- if (result !== void 0) consumedToolResults.add(part.id);
335
- response.push({
336
- type: "functionCall",
337
- name: part.name,
338
- params: part.arguments,
339
- result: result ?? ""
340
- });
341
- }
342
- history.push({
343
- type: "model",
344
- response
345
1304
  });
346
- continue;
1305
+ if (credentialInput === void 0) throw new Error("llama-server API-key setup did not produce a credential");
1306
+ headers = stripAuthorizationHeader(resolvedHeaders);
1307
+ persistence = {
1308
+ kind: "upsert",
1309
+ credential: credentialInput
1310
+ };
347
1311
  }
348
- if (!consumedToolResults.has(message.toolCallId)) history.push({
349
- type: "user",
350
- text: `Tool result (${message.toolName}): ${extractText(message.content)}`
351
- });
352
1312
  }
353
- return history;
354
- }
355
- function mapToolsToLlamaFunctions(context) {
356
- if (!context.tools?.length) return;
357
- return Object.fromEntries(context.tools.map((tool) => [tool.name, {
358
- description: tool.description,
359
- params: tool.parameters
360
- }]));
361
- }
362
- function readContextSizeValue(value) {
363
- if (value === "auto") return value;
364
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
365
- }
366
- function resolveContextSize(model, providerConfig) {
367
- const configured = readContextSizeValue(model.params?.contextSize) ?? readContextSizeValue(providerConfig?.params?.contextSize);
368
- if (typeof configured === "number") return configured;
369
- return { max: typeof model.contextTokens === "number" && model.contextTokens > 0 ? Math.floor(model.contextTokens) : DEFAULT_LLAMA_CPP_CONTEXT_SIZE };
370
- }
371
- async function disposeLoadedModel() {
372
- if (!loadedModel) return;
373
- const previous = loadedModel;
374
- loadedModel = void 0;
375
- await previous.context.dispose();
376
- await previous.model.dispose();
377
- }
378
- async function getLoadedModel(params) {
379
- const source = resolveLlamaCppModelSource(params.model);
380
- const modelPath = await params.runtime.resolveModelFile(source, {
381
- directory: resolveLlamaCppModelCacheDir(params.providerConfig),
382
- download: false
1313
+ const discovery = await discoverWithAccess({
1314
+ baseUrl: endpoint.inferenceBaseUrl,
1315
+ apiKey,
1316
+ headers,
1317
+ signal: ctx.signal
383
1318
  });
384
- const contextSize = resolveContextSize(params.model, params.providerConfig);
385
- const key = `${modelPath}\0${JSON.stringify(contextSize)}`;
386
- if (loadedModel?.key === key) return loadedModel;
387
- await disposeLoadedModel();
388
- const llama = llamaInstance ?? await params.runtime.getLlama();
389
- llamaInstance = llama;
390
- const fitContextSize = typeof contextSize === "number" ? contextSize : contextSize.max;
391
- const model = await llama.loadModel({
392
- modelPath,
393
- loadSignal: params.signal,
394
- gpuLayers: { fitContext: { contextSize: fitContextSize } }
1319
+ if (discovery.kind !== "success") throw new Error(describeDiscoveryFailure(discovery));
1320
+ const modelId = selectSetupModelId(discovery);
1321
+ if (!modelId) throw new Error(`No llama-server text models were found at ${discovery.endpoint.origin}.`);
1322
+ if (persistence.kind === "remove") await removeDefaultAuthProfile(ctx.agentDir);
1323
+ return buildSetupResult$1({
1324
+ config: ctx.config,
1325
+ discovery,
1326
+ modelId,
1327
+ resetEndpoint: endpointChanged,
1328
+ persistence
395
1329
  });
396
- let context;
397
- try {
398
- context = await model.createContext({
399
- contextSize,
400
- createSignal: params.signal
401
- });
402
- const sequence = context.getSequence();
403
- loadedModel = {
404
- key,
405
- llama,
406
- model,
407
- context,
408
- sequence
1330
+ }
1331
+ async function validateNonInteractiveDiscovery(ctx) {
1332
+ const configuredProvider = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1333
+ const baseUrl = normalizeOptionalSecretInput(ctx.opts.customBaseUrl) ?? configuredProvider?.baseUrl ?? "http://127.0.0.1:8080";
1334
+ const endpointChanged = Boolean(configuredProvider?.localService) || hasEndpointChanged(configuredProvider, baseUrl);
1335
+ const providerApiKey = normalizeOptionalSecretInput(ctx.opts.llamaServerApiKey);
1336
+ const customApiKey = normalizeOptionalSecretInput(ctx.opts.customApiKey);
1337
+ const authoredApiKey = providerApiKey ?? customApiKey;
1338
+ const hasAuthoredApiKey = authoredApiKey !== void 0;
1339
+ const resolvedApiKey = await ctx.resolveApiKey({
1340
+ provider: LLAMA_CPP_PROVIDER_ID,
1341
+ flagValue: authoredApiKey,
1342
+ flagName: providerApiKey === void 0 ? "--custom-api-key" : "--llama-server-api-key",
1343
+ envVar: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
1344
+ envVarName: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
1345
+ required: false
1346
+ });
1347
+ const resolvedHeaders = endpointChanged ? void 0 : await resolveLlamaServerProviderHeaders({
1348
+ config: ctx.config,
1349
+ env: process.env,
1350
+ headers: configuredProvider?.headers
1351
+ });
1352
+ let apiKey;
1353
+ let headers = resolvedHeaders;
1354
+ let persistence;
1355
+ if (hasAuthoredApiKey && resolvedApiKey) {
1356
+ apiKey = resolvedApiKey.key;
1357
+ headers = stripAuthorizationHeader(resolvedHeaders);
1358
+ persistence = {
1359
+ kind: "upsert",
1360
+ credential: resolvedApiKey
409
1361
  };
410
- return loadedModel;
411
- } catch (error) {
412
- await context?.dispose();
413
- await model.dispose();
414
- throw error;
1362
+ } else if (endpointChanged || hasLlamaServerAuthorizationHeader(resolvedHeaders)) persistence = { kind: "remove" };
1363
+ else if (resolvedApiKey?.source === "profile") {
1364
+ apiKey = resolvedApiKey.key;
1365
+ persistence = { kind: "preserve" };
1366
+ } else if (resolvedApiKey) {
1367
+ apiKey = resolvedApiKey.key;
1368
+ persistence = {
1369
+ kind: "upsert",
1370
+ credential: resolvedApiKey
1371
+ };
1372
+ } else persistence = { kind: "remove" };
1373
+ const discovery = await discoverWithAccess({
1374
+ baseUrl,
1375
+ apiKey,
1376
+ headers
1377
+ });
1378
+ if (discovery.kind !== "success") {
1379
+ ctx.runtime.error(describeDiscoveryFailure(discovery));
1380
+ ctx.runtime.exit(1);
1381
+ return null;
1382
+ }
1383
+ const requestedModelId = normalizeOptionalSecretInput(ctx.opts.customModelId);
1384
+ const modelId = requestedModelId ?? selectSetupModelId(discovery);
1385
+ if (!modelId || !discovery.models.some((model) => model.config.id === modelId)) {
1386
+ const available = discovery.models.map((model) => model.config.id).join(", ");
1387
+ ctx.runtime.error(requestedModelId ? `llama-server model ${requestedModelId} was not found. Available models: ${available}` : `No llama-server text models were found at ${discovery.endpoint.origin}.`);
1388
+ ctx.runtime.exit(1);
1389
+ return null;
415
1390
  }
1391
+ return {
1392
+ discovery,
1393
+ modelId,
1394
+ resetEndpoint: endpointChanged,
1395
+ persistence
1396
+ };
416
1397
  }
417
- async function serialize(operation) {
418
- const current = operationQueue.then(operation, operation);
419
- operationQueue = current.catch(() => void 0);
420
- await current;
1398
+ async function validateLlamaServerNonInteractive(ctx) {
1399
+ return Boolean(await validateNonInteractiveDiscovery(ctx));
421
1400
  }
422
- async function clearLlamaCppInferenceCacheForTests() {
423
- await serialize(async () => {
424
- await disposeLoadedModel();
425
- if (llamaInstance) {
426
- await llamaInstance.dispose();
427
- llamaInstance = void 0;
428
- }
1401
+ /** Non-interactive setup with optional API-key persistence. */
1402
+ async function configureLlamaServerNonInteractive(ctx) {
1403
+ const validated = await validateNonInteractiveDiscovery(ctx);
1404
+ if (!validated) return null;
1405
+ const providerConfig = buildExistingProviderConfig({
1406
+ config: ctx.config,
1407
+ discovery: validated.discovery,
1408
+ resetEndpoint: validated.resetEndpoint,
1409
+ persistence: validated.persistence
429
1410
  });
1411
+ let config = {
1412
+ ...ctx.config,
1413
+ models: {
1414
+ ...ctx.config.models,
1415
+ mode: ctx.config.models?.mode ?? "merge",
1416
+ providers: {
1417
+ ...ctx.config.models?.providers,
1418
+ [LLAMA_CPP_PROVIDER_ID]: providerConfig
1419
+ }
1420
+ }
1421
+ };
1422
+ if (validated.persistence.kind === "upsert") {
1423
+ const credential = ctx.toApiKeyCredential({
1424
+ provider: LLAMA_CPP_PROVIDER_ID,
1425
+ resolved: validated.persistence.credential
1426
+ });
1427
+ if (!credential) return null;
1428
+ await upsertAuthProfileWithLock({
1429
+ profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
1430
+ credential,
1431
+ agentDir: ctx.agentDir
1432
+ });
1433
+ config = applyAuthProfileConfig(config, {
1434
+ profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
1435
+ provider: LLAMA_CPP_PROVIDER_ID,
1436
+ mode: "api_key"
1437
+ });
1438
+ } else if (validated.persistence.kind === "remove") {
1439
+ await removeDefaultAuthProfile(ctx.agentDir);
1440
+ config = removeAuthProfileConfig(config, LLAMA_CPP_DEFAULT_PROFILE_ID);
1441
+ }
1442
+ ctx.runtime.log(`Default ${LLAMA_CPP_PROVIDER_LABEL} model: ${validated.modelId}`);
1443
+ return applyProviderDefaultModel(config, `${LLAMA_CPP_PROVIDER_ID}/${validated.modelId}`);
1444
+ }
1445
+ //#endregion
1446
+ //#region extensions/llama-cpp/src/external-server/stream.ts
1447
+ /** Maps shared structured-output requests to the shape accepted by older llama-server builds. */
1448
+ function normalizeLlamaServerResponseFormat(payload, requestedResponseFormat) {
1449
+ const responseFormat = isRecord(payload.response_format) ? payload.response_format : requestedResponseFormat;
1450
+ if (!responseFormat || responseFormat.type === "text") return;
1451
+ const schema = responseFormat.type === "json_schema" ? isRecord(responseFormat.json_schema) ? responseFormat.json_schema.schema : responseFormat.schema : responseFormat.type === "json_object" ? responseFormat.schema : responseFormat;
1452
+ if (isRecord(schema)) payload.response_format = {
1453
+ type: "json_object",
1454
+ schema
1455
+ };
430
1456
  }
431
- function createLlamaCppStreamFn(params) {
1457
+ /** Keeps the shared OpenAI transport and adjusts llama-server request compatibility. */
1458
+ function wrapLlamaServerStream(ctx) {
1459
+ const underlying = ctx.streamFn ?? streamSimple;
432
1460
  return (model, context, options) => {
433
- const stream = createAssistantMessageEventStream();
434
- let streamedText = "";
435
- let generationAborted = false;
436
- let started = false;
437
- let ended = false;
438
- const signal = options?.signal;
439
- const abortWhileQueued = () => {
440
- if (started || ended) return;
441
- ended = true;
442
- stream.push({
443
- type: "error",
444
- reason: "aborted",
445
- error: buildMessage({
446
- model,
447
- content: [],
448
- stopReason: "aborted",
449
- errorMessage: "Request was aborted"
450
- })
451
- });
452
- stream.end();
453
- };
454
- signal?.addEventListener("abort", abortWhileQueued, { once: true });
455
- if (signal?.aborted) abortWhileQueued();
456
- const run = async () => {
457
- if (ended) return;
458
- started = true;
459
- signal?.removeEventListener("abort", abortWhileQueued);
460
- try {
461
- const runtime = await importNodeLlamaCpp();
462
- const loaded = await getLoadedModel({
463
- runtime,
464
- model,
465
- providerConfig: params.providerConfig,
466
- signal: options?.signal
467
- });
468
- const sequence = loaded.sequence;
469
- const chat = new runtime.LlamaChat({
470
- contextSequence: sequence,
471
- chatWrapper: "auto",
472
- autoDisposeSequence: false
473
- });
474
- const before = sequence.tokenMeter.getState();
475
- const functions = mapToolsToLlamaFunctions(context);
476
- let textStarted = false;
477
- const partial = () => buildMessage({
478
- model,
479
- content: streamedText ? [{
480
- type: "text",
481
- text: streamedText
482
- }] : [],
483
- stopReason: "stop"
484
- });
485
- const appendTextDelta = (delta) => {
486
- if (!delta) return;
487
- if (!textStarted) {
488
- textStarted = true;
489
- stream.push({
490
- type: "start",
491
- partial: partial()
492
- });
493
- stream.push({
494
- type: "text_start",
495
- contentIndex: 0,
496
- partial: partial()
497
- });
498
- }
499
- streamedText += delta;
500
- stream.push({
501
- type: "text_delta",
502
- contentIndex: 0,
503
- delta
504
- });
505
- };
506
- try {
507
- const grammar = functions || !options?.responseFormat ? void 0 : await resolveLlamaCppResponseGrammar({
508
- llama: loaded.llama,
509
- responseFormat: options.responseFormat
510
- });
511
- const generationOptions = {
512
- signal: options?.signal,
513
- maxTokens: options?.maxTokens ?? model.maxTokens,
514
- temperature: options?.temperature,
515
- customStopTriggers: options?.stop,
516
- onTextChunk: appendTextDelta,
517
- ...functions ? {
518
- functions,
519
- documentFunctionParams: true
520
- } : grammar ? { grammar } : {}
521
- };
522
- const result = await chat.generateResponse(mapContextToLlamaChatHistory(context), generationOptions);
523
- if (result.metadata.stopReason === "abort" || signal?.aborted) {
524
- generationAborted = true;
525
- throw signal?.reason ?? /* @__PURE__ */ new Error("Request was aborted");
526
- }
527
- const usageDelta = sequence.tokenMeter.diff(before);
528
- if (!streamedText && result.response) appendTextDelta(result.response);
529
- const content = streamedText ? [{
530
- type: "text",
531
- text: streamedText
532
- }] : [];
533
- if (textStarted) stream.push({
534
- type: "text_end",
535
- contentIndex: 0,
536
- content: streamedText,
537
- partial: partial()
538
- });
539
- const toolCalls = (result.functionCalls ?? []).map((call) => ({
540
- type: "toolCall",
541
- id: `llama_cpp_call_${randomUUID()}`,
542
- name: call.functionName,
543
- arguments: normalizeArguments(call.params)
544
- }));
545
- content.push(...toolCalls);
546
- const reason = toolCalls.length > 0 ? "toolUse" : result.metadata.stopReason === "maxTokens" ? "length" : "stop";
547
- const message = buildMessage({
548
- model,
549
- content,
550
- stopReason: reason,
551
- usage: zeroCostUsage(usageDelta.usedInputTokens, usageDelta.usedOutputTokens)
552
- });
553
- stream.push({
554
- type: "done",
555
- reason,
556
- message
557
- });
558
- } finally {
559
- chat.dispose();
1461
+ if (model.provider !== "llama-cpp") return underlying(model, context, options);
1462
+ const onPayload = options?.onPayload;
1463
+ return underlying(model, context, {
1464
+ ...options,
1465
+ onPayload: async (payload, requestModel) => {
1466
+ const customized = await onPayload?.(payload, requestModel) ?? payload;
1467
+ if (isRecord(customized)) {
1468
+ if (ctx.thinkingLevel === "off") setQwenChatTemplateThinking(customized, false);
1469
+ normalizeLlamaServerResponseFormat(customized, options?.responseFormat);
560
1470
  }
561
- } catch (error) {
562
- const aborted = generationAborted || options?.signal?.aborted === true;
563
- const reason = aborted ? "aborted" : "error";
564
- const errorMessage = aborted ? "Request was aborted" : formatLlamaCppSetupError(error);
565
- stream.push({
566
- type: "error",
567
- reason,
568
- error: buildMessage({
569
- model,
570
- content: streamedText ? [{
571
- type: "text",
572
- text: streamedText
573
- }] : [],
574
- stopReason: reason,
575
- errorMessage
576
- })
577
- });
578
- } finally {
579
- ended = true;
580
- stream.end();
1471
+ return customized;
581
1472
  }
582
- };
583
- if (!ended) queueMicrotask(() => void serialize(run));
584
- return stream;
1473
+ });
585
1474
  };
586
1475
  }
587
- if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.llamaCppInferenceTestApi")] = {
588
- mapContextToLlamaChatHistory,
589
- mapToolsToLlamaFunctions,
590
- clearLlamaCppInferenceCacheForTests
591
- };
592
1476
  //#endregion
593
1477
  //#region extensions/llama-cpp/src/setup.ts
594
1478
  const BYTES_PER_GB = 1e9;
595
1479
  const BYTES_PER_MB = 1e6;
596
- function formatLlamaCppDownloadProgress(params) {
1480
+ function formatDownloadProgress(label, params) {
597
1481
  const downloadedSize = Math.max(0, params.downloadedSize);
598
1482
  const totalSize = Math.max(1, params.totalSize);
599
- return `Downloading Gemma 4 E4B… ${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)`;
1483
+ 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)`;
600
1484
  }
601
1485
  function formatRamGb(totalmemBytes) {
602
- return (totalmemBytes / 1024 ** 3).toFixed(1).replace(/\.0$/, "");
1486
+ return (totalmemBytes / 1024 ** 3).toFixed(1).replace(/\.0$/u, "");
603
1487
  }
604
1488
  function readPrimaryModel(config) {
605
1489
  const model = config.agents?.defaults?.model;
@@ -607,169 +1491,249 @@ function readPrimaryModel(config) {
607
1491
  }
608
1492
  function configuredCandidates(config) {
609
1493
  const existing = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
610
- const provider = buildLlamaCppProviderConfig(existing);
1494
+ const provider = buildLlamaCppProviderConfig(existing?.localService ? existing : void 0);
611
1495
  const primary = readPrimaryModel(config);
612
- const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(10) : void 0;
1496
+ const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
613
1497
  return provider.models.map((model) => ({
614
1498
  model,
615
1499
  provider
616
1500
  })).toSorted((a, b) => Number(b.model.id === primaryId) - Number(a.model.id === primaryId));
617
1501
  }
618
1502
  async function isFile(filePath) {
619
- try {
620
- return (await fs.stat(filePath)).isFile();
621
- } catch {
622
- return false;
1503
+ return await fsp.stat(filePath).then((stat) => stat.isFile()).catch(() => false);
1504
+ }
1505
+ async function resolveCachedCandidate(candidate) {
1506
+ const source = resolveLlamaCppModelSource(candidate.model);
1507
+ const resolved = resolveCachedLlamaCppModelPath(candidate);
1508
+ if (resolved && await isFile(resolved)) return resolved;
1509
+ if (candidate.model.id === "gemma-4-e4b-it-q4_k_m") {
1510
+ const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
1511
+ if (await isFile(legacy)) return legacy;
623
1512
  }
1513
+ if (/^(?:hf|huggingface|https):/iu.test(source)) return await ensureLlamaCppModel({
1514
+ source,
1515
+ cacheDir: resolveLlamaCppModelCacheDir(candidate.provider),
1516
+ download: false
1517
+ }).catch(() => void 0);
624
1518
  }
625
- async function detectLlamaCppSetup(ctx) {
626
- let runtime;
1519
+ function readConfiguredPort(provider) {
627
1520
  try {
628
- runtime = await importNodeLlamaCpp();
1521
+ const url = new URL(provider?.baseUrl ?? "");
1522
+ if (url.hostname !== "127.0.0.1" && url.hostname !== "localhost" && url.hostname !== "[::1]") return;
1523
+ const port = Number(url.port);
1524
+ return Number.isInteger(port) && port > 0 ? port : void 0;
629
1525
  } catch {
630
- return null;
1526
+ return;
631
1527
  }
632
- for (const candidate of configuredCandidates(ctx.config)) try {
633
- if (!await isFile(await runtime.resolveModelFile(resolveLlamaCppModelSource(candidate.model), {
634
- directory: resolveLlamaCppModelCacheDir(candidate.provider),
635
- download: false,
636
- cli: false
637
- }))) continue;
638
- return {
639
- modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
640
- detail: `${candidate.model.id} (downloaded)`
641
- };
642
- } catch {}
643
- return null;
644
1528
  }
645
- function buildSetupResult(config, defaultModel = DEFAULT_LLAMA_CPP_MODEL_REF) {
1529
+ function buildSetupResult(params) {
1530
+ const existing = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1531
+ const switchingFromExternal = Boolean(existing && !existing.localService);
646
1532
  return {
647
1533
  profiles: [],
648
- defaultModel,
649
- configPatch: { models: {
650
- mode: config.models?.mode ?? "merge",
651
- providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig(config.models?.providers?.[LLAMA_CPP_PROVIDER_ID]) }
652
- } }
1534
+ defaultModel: params.defaultModel ?? DEFAULT_LLAMA_CPP_MODEL_REF,
1535
+ configPatch: {
1536
+ ...buildLlamaCppAuthProfileRemovalPatch(params.config),
1537
+ models: {
1538
+ mode: params.config.models?.mode ?? "merge",
1539
+ providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig(switchingFromExternal ? void 0 : existing, params.managed) }
1540
+ }
1541
+ }
653
1542
  };
654
1543
  }
1544
+ async function detectLlamaCppSetup(ctx) {
1545
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1546
+ const command = existing?.localService?.command;
1547
+ const presetPath = existing?.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset");
1548
+ if (!command || !path.isAbsolute(command) || !await isFile(command) || !presetPath || !await isFile(presetPath)) return null;
1549
+ for (const candidate of configuredCandidates(ctx.config)) if (await resolveCachedCandidate(candidate)) return {
1550
+ modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
1551
+ detail: "Managed llama.cpp server ready"
1552
+ };
1553
+ return null;
1554
+ }
655
1555
  async function prepareLlamaCppSetup(ctx) {
656
- return (await detectLlamaCppSetup(ctx))?.modelRef === ctx.modelRef ? buildSetupResult(ctx.config, ctx.modelRef) : null;
1556
+ const detected = await detectLlamaCppSetup(ctx);
1557
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1558
+ if (detected?.modelRef !== ctx.modelRef || !existing?.localService?.command) return null;
1559
+ const baseUrl = existing.baseUrl?.replace(/\/+$/u, "") ?? "";
1560
+ const rootUrl = baseUrl.replace(/\/v1$/u, "");
1561
+ return buildSetupResult({
1562
+ config: ctx.config,
1563
+ defaultModel: ctx.modelRef,
1564
+ managed: {
1565
+ command: existing.localService.command,
1566
+ baseUrl,
1567
+ healthUrl: existing.localService.healthUrl ?? `${rootUrl}/health`,
1568
+ args: existing.localService.args ?? []
1569
+ }
1570
+ });
657
1571
  }
658
1572
  async function runLlamaCppSetup(ctx) {
659
1573
  const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
660
- const cacheDir = resolveLlamaCppModelCacheDir(existing);
661
- const cachedPath = resolveCachedLlamaCppModelPath({
662
- model: {
663
- id: DEFAULT_LLAMA_CPP_MODEL_ID,
664
- params: { modelPath: DEFAULT_LLAMA_CPP_MODEL_URI }
665
- },
666
- provider: existing
667
- });
668
- if (!cachedPath || !await isFile(cachedPath)) {
1574
+ const managedExisting = existing?.localService ? existing : void 0;
1575
+ const candidates = configuredCandidates(ctx.config);
1576
+ let selected = candidates[0];
1577
+ let chatModelPath = selected ? await resolveCachedCandidate(selected) : void 0;
1578
+ if (!chatModelPath) {
1579
+ selected = candidates.find((candidate) => candidate.model.id === DEFAULT_LLAMA_CPP_MODEL_ID);
669
1580
  const totalmemBytes = os.totalmem();
670
- if (!meetsLlamaCppDefaultModelRamFloor(totalmemBytes)) {
671
- await ctx.prompter.note(`This machine has ${formatRamGb(totalmemBytes)} GB RAM; the bundled local model needs 16 GB+. Use Ollama/LM Studio with a smaller model, or a cloud provider.`, "Setup skipped");
1581
+ if (!selected || !meetsLlamaCppDefaultModelRamFloor(totalmemBytes)) {
1582
+ await ctx.prompter.note(`This Gateway has ${formatRamGb(totalmemBytes)} GB RAM; the recommended model needs 16 GB+. Configure an existing smaller GGUF, use Ollama or LM Studio, or choose a cloud provider.`, "Setup skipped");
672
1583
  return { profiles: [] };
673
1584
  }
674
1585
  if (!await ctx.prompter.confirm({
675
- message: "Download Gemma 4 E4B IT Q4_K_M (about 5.0 GB) for local llama.cpp inference?",
1586
+ message: "OpenClaw will install a verified llama.cpp server and download Gemma 4 E4B IT Q4_K_M (about 5.0 GB) plus the local embedding model (about 0.3 GB). Continue?",
676
1587
  initialValue: false
677
1588
  })) {
678
- await ctx.prompter.note("Local model download skipped.", "Setup skipped");
1589
+ await ctx.prompter.note("Local model setup skipped.", "Setup skipped");
679
1590
  return { profiles: [] };
680
1591
  }
681
- const progress = ctx.prompter.progress("Preparing Gemma 4 E4B model download…");
682
- try {
683
- const runtime = await importNodeLlamaCpp();
684
- let previousDownloadedSize;
685
- let previousProgressAtMs;
686
- let rollingBytesPerSecond = 0;
687
- await (await runtime.createModelDownloader({
688
- modelUri: DEFAULT_LLAMA_CPP_MODEL_URI,
689
- dirPath: cacheDir,
690
- fileName: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE,
691
- showCliProgress: false,
692
- onProgress: ({ downloadedSize, totalSize }) => {
693
- const now = Date.now();
694
- if (previousDownloadedSize !== void 0 && previousProgressAtMs !== void 0 && downloadedSize >= previousDownloadedSize && now > previousProgressAtMs) {
695
- const elapsedSeconds = (now - previousProgressAtMs) / 1e3;
696
- const currentBytesPerSecond = (downloadedSize - previousDownloadedSize) / elapsedSeconds;
697
- rollingBytesPerSecond = rollingBytesPerSecond === 0 ? currentBytesPerSecond : rollingBytesPerSecond * .75 + currentBytesPerSecond * .25;
698
- }
699
- previousDownloadedSize = downloadedSize;
700
- previousProgressAtMs = now;
701
- const expectedSize = totalSize || 4977169568;
702
- progress.update(formatLlamaCppDownloadProgress({
703
- downloadedSize,
704
- totalSize: expectedSize,
705
- bytesPerSecond: rollingBytesPerSecond
706
- }));
707
- }
708
- })).download({ signal: ctx.signal });
709
- progress.stop("Gemma 4 E4B model downloaded");
710
- } catch (error) {
711
- progress.stop("Model download failed");
712
- throw new Error(formatLlamaCppSetupError(error), { cause: error });
713
- }
714
1592
  }
715
- return buildSetupResult(ctx.config);
1593
+ if (!selected) throw new Error("llama.cpp setup could not resolve a chat model");
1594
+ const progress = ctx.prompter.progress("Preparing managed llama.cpp server…");
1595
+ try {
1596
+ const cacheDir = resolveLlamaCppModelCacheDir(managedExisting);
1597
+ chatModelPath ??= await ensureLlamaCppModel({
1598
+ source: resolveLlamaCppModelSource(selected.model),
1599
+ cacheDir,
1600
+ download: true,
1601
+ signal: ctx.signal,
1602
+ onProgress: (status) => progress.update(formatDownloadProgress("Gemma 4 E4B", status))
1603
+ });
1604
+ const embeddingModelPath = await ensureLlamaCppModel({
1605
+ source: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
1606
+ cacheDir,
1607
+ download: true,
1608
+ signal: ctx.signal,
1609
+ onProgress: (status) => progress.update(formatDownloadProgress("EmbeddingGemma", status))
1610
+ });
1611
+ const configuredContext = selected.model.params?.contextSize;
1612
+ const contextSize = typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : selected.model.contextTokens;
1613
+ const managed = await prepareManagedLlamaServer({
1614
+ chatModelId: selected.model.id,
1615
+ chatModelPath,
1616
+ contextSize,
1617
+ maxTokens: selected.model.maxTokens,
1618
+ embeddingModelPath,
1619
+ port: readConfiguredPort(managedExisting)
1620
+ });
1621
+ if (!await removeProviderAuthProfilesWithLock({
1622
+ provider: "llama-cpp",
1623
+ profileIds: [LLAMA_CPP_DEFAULT_PROFILE_ID],
1624
+ agentDir: ctx.agentDir
1625
+ })) throw new Error("Failed to remove the previous llama.cpp endpoint auth profile");
1626
+ progress.stop("Managed llama.cpp server prepared");
1627
+ return buildSetupResult({
1628
+ config: ctx.config,
1629
+ managed,
1630
+ defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${selected.model.id}`
1631
+ });
1632
+ } catch (error) {
1633
+ progress.stop("llama.cpp setup failed");
1634
+ const detail = error instanceof Error ? error.message : String(error);
1635
+ throw new Error(`Managed llama.cpp setup failed. Run openclaw doctor, fix the reported runtime or model issue, then retry. ${detail}`, { cause: error });
1636
+ }
1637
+ }
1638
+ //#endregion
1639
+ //#region extensions/llama-cpp/src/managed-provider.ts
1640
+ function registerLlamaCppProvider(api) {
1641
+ api.registerProvider({
1642
+ id: LLAMA_CPP_PROVIDER_ID,
1643
+ label: LLAMA_CPP_PROVIDER_LABEL,
1644
+ docsPath: "/plugins/llama-cpp",
1645
+ envVars: [LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR],
1646
+ auth: [{
1647
+ id: "local",
1648
+ label: LLAMA_CPP_PROVIDER_LABEL,
1649
+ hint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
1650
+ kind: "custom",
1651
+ wizard: {
1652
+ choiceId: LLAMA_CPP_PROVIDER_ID,
1653
+ choiceLabel: "Managed local server",
1654
+ choiceHint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
1655
+ groupId: LLAMA_CPP_PROVIDER_ID,
1656
+ groupLabel: "Local llama.cpp",
1657
+ groupHint: "Managed or external llama.cpp server",
1658
+ methodId: "local"
1659
+ },
1660
+ appGuidedSetup: {
1661
+ detect: detectLlamaCppSetup,
1662
+ prepare: prepareLlamaCppSetup
1663
+ },
1664
+ run: runLlamaCppSetup
1665
+ }, {
1666
+ id: "existing-server",
1667
+ label: "Existing llama-server",
1668
+ hint: "Connect to an existing local, private, or remote llama.cpp server",
1669
+ kind: "custom",
1670
+ wizard: {
1671
+ choiceId: "llama-cpp-existing-server",
1672
+ choiceLabel: "Existing llama-server",
1673
+ choiceHint: "Connect to a llama.cpp server managed outside OpenClaw",
1674
+ groupId: LLAMA_CPP_PROVIDER_ID,
1675
+ groupLabel: "Local llama.cpp",
1676
+ groupHint: "Managed or external llama.cpp server",
1677
+ methodId: "existing-server"
1678
+ },
1679
+ appGuidedSetup: {
1680
+ detect: detectLlamaServerSetup,
1681
+ prepare: prepareLlamaServerSetup
1682
+ },
1683
+ run: runLlamaServerSetup,
1684
+ validateNonInteractive: validateLlamaServerNonInteractive,
1685
+ runNonInteractive: async (ctx) => await configureLlamaServerNonInteractive(ctx)
1686
+ }],
1687
+ catalog: {
1688
+ order: "late",
1689
+ run: async (ctx) => {
1690
+ const configured = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1691
+ return configured?.localService ? { provider: buildLlamaCppProviderConfig(configured) } : await discoverLlamaServerProvider(ctx);
1692
+ }
1693
+ },
1694
+ staticCatalog: {
1695
+ order: "late",
1696
+ run: async () => ({ provider: buildLlamaCppProviderConfig() })
1697
+ },
1698
+ resolveSyntheticAuth: ({ providerConfig }) => providerConfig?.localService || shouldUseLlamaServerSyntheticAuth(providerConfig) ? {
1699
+ apiKey: resolveLlamaCppSyntheticApiKey(),
1700
+ source: providerConfig?.localService ? "managed local llama.cpp server" : hasLlamaServerAuthorizationHeader(providerConfig?.headers) ? "models.providers.llama-cpp.headers.Authorization" : "models.providers.llama-cpp (synthetic local key)",
1701
+ mode: "api-key"
1702
+ } : void 0,
1703
+ shouldDeferSyntheticProfileAuth: ({ resolvedApiKey }) => resolvedApiKey?.trim() === resolveLlamaCppSyntheticApiKey() || resolvedApiKey?.trim() === CUSTOM_LOCAL_AUTH_MARKER,
1704
+ normalizeConfig: ({ providerConfig }) => providerConfig.localService ? providerConfig : normalizeLlamaServerProviderConfig(providerConfig),
1705
+ prepareDynamicModel: async (ctx) => ctx.config?.models?.providers?.["llama-cpp"]?.localService ? void 0 : await prepareLlamaServerDynamicModel(ctx),
1706
+ wrapStreamFn: (ctx) => {
1707
+ const providerConfig = ctx.config?.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1708
+ if (!providerConfig?.localService) return wrapLlamaServerStream(ctx);
1709
+ const inner = ctx.streamFn;
1710
+ const selectedModel = ctx.model;
1711
+ if (!inner || !selectedModel) return;
1712
+ return async (model, context, options) => {
1713
+ await ensureManagedLlamaServerForChat({
1714
+ provider: providerConfig,
1715
+ model: selectedModel
1716
+ });
1717
+ return inner(model, context, options);
1718
+ };
1719
+ },
1720
+ ...buildProviderToolCompatFamilyHooks("llamacpp-gbnf"),
1721
+ wizard: { modelPicker: {
1722
+ label: "llama.cpp",
1723
+ hint: `Use a managed server or connect to ${LLAMA_SERVER_DEFAULT_ORIGIN}`,
1724
+ methodId: "local"
1725
+ } }
1726
+ });
716
1727
  }
717
- if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.llamaCppSetupTestApi")] = { formatLlamaCppDownloadProgress };
718
1728
  //#endregion
719
1729
  //#region extensions/llama-cpp/index.ts
720
1730
  var llama_cpp_default = definePluginEntry({
721
1731
  id: "llama-cpp",
722
1732
  name: "llama.cpp Provider",
723
- description: "Local GGUF text inference and embeddings through node-llama-cpp",
1733
+ description: "Managed and external llama.cpp servers for GGUF chat and embeddings",
724
1734
  register(api) {
725
1735
  api.registerEmbeddingProvider(llamaCppEmbeddingProviderAdapter);
726
- api.registerProvider({
727
- id: LLAMA_CPP_PROVIDER_ID,
728
- label: LLAMA_CPP_PROVIDER_LABEL,
729
- docsPath: "/plugins/llama-cpp",
730
- auth: [{
731
- id: "local",
732
- label: LLAMA_CPP_PROVIDER_LABEL,
733
- hint: "In-process local GGUF model (about 5.0 GB download; requires 16 GB RAM)",
734
- kind: "custom",
735
- appGuidedSetup: {
736
- detect: detectLlamaCppSetup,
737
- prepare: prepareLlamaCppSetup
738
- },
739
- run: runLlamaCppSetup
740
- }],
741
- catalog: {
742
- order: "late",
743
- run: async (ctx) => ({ provider: buildLlamaCppProviderConfig(ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID]) })
744
- },
745
- staticCatalog: {
746
- order: "late",
747
- run: async () => ({ provider: buildLlamaCppProviderConfig() })
748
- },
749
- createStreamFn: ({ config, provider }) => createLlamaCppStreamFn({ providerConfig: config?.models?.providers?.[provider] }),
750
- resolveSyntheticAuth: () => ({
751
- apiKey: resolveLlamaCppSyntheticApiKey(),
752
- source: "local llama.cpp runtime",
753
- mode: "api-key"
754
- }),
755
- ...buildProviderToolCompatFamilyHooks("llamacpp-gbnf"),
756
- wizard: {
757
- setup: {
758
- choiceId: LLAMA_CPP_PROVIDER_ID,
759
- choiceLabel: LLAMA_CPP_PROVIDER_LABEL,
760
- choiceHint: "In-process local model (about 5.0 GB download; requires 16 GB RAM)",
761
- groupId: LLAMA_CPP_PROVIDER_ID,
762
- groupLabel: "Local llama.cpp",
763
- groupHint: "No API key required",
764
- methodId: "local"
765
- },
766
- modelPicker: {
767
- label: "llama.cpp (local GGUF)",
768
- hint: "Run a GGUF model in the OpenClaw process",
769
- methodId: "local"
770
- }
771
- }
772
- });
1736
+ registerLlamaCppProvider(api);
773
1737
  }
774
1738
  });
775
1739
  //#endregion