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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,351 @@
1
+ import { C as resolveLegacyLlamaCppModelCacheDir, D as resolveLlamaCppModelSource, E as resolveLlamaCppModelCacheDir, T as resolveLlamaCppEmbeddingModel, _ as LLAMA_CPP_PROVIDER_ID, b as buildLlamaCppProviderConfig, l as DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE, x as resolveCachedLlamaCppModelPath } from "./defaults-CL2lz0cV.mjs";
2
+ import { o as resolveLlamaCppMediaModels } from "./media-config-CZ7CluNV.mjs";
3
+ import { c as formatLlamaCppMemory, i as recommendLlamaCppModel, m as selectLlamaServerAsset, o as resolveLlamaCppModelCandidates, p as resolveManagedLlamaServerPaths, s as detectLlamaCppHardware } from "./media-catalog-M5BEPQng.mjs";
4
+ import { ensureLlamaCppModel, n as UnsupportedLlamaServerHostError, prepareManagedLlamaServer, r as ensureLlamaServerInstalled, resolveLlamaCppModelDownloadSize } from "./managed-server-C2ukpg0h.mjs";
5
+ import { n as buildLlamaCppAuthProfileRemovalPatch } from "./auth-config-DPqFwXcI.mjs";
6
+ import path from "node:path";
7
+ import os from "node:os";
8
+ import fs from "node:fs/promises";
9
+ import { listAgentIds, resolveAgentConfig } from "openclaw/plugin-sdk/agent-scope-runtime";
10
+ import { mergeDeep } from "openclaw/plugin-sdk/plugin-config-runtime";
11
+ //#region extensions/llama-cpp/src/setup.ts
12
+ const BYTES_PER_GB = 1e9;
13
+ const BYTES_PER_MB = 1e6;
14
+ function formatDownloadProgress(label, params) {
15
+ const downloadedSize = Math.max(0, params.downloadedSize);
16
+ const totalSize = Math.max(1, params.totalSize);
17
+ 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)`;
18
+ }
19
+ function describeEmbeddingDownload(isDefault) {
20
+ return isDefault ? "the local embedding model (about 0.3 GB)" : "your configured local embedding model";
21
+ }
22
+ async function configuredCandidates(config) {
23
+ const provider = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
24
+ if (!provider?.localService) return [];
25
+ const mediaModels = resolveLlamaCppMediaModels(provider);
26
+ const candidates = provider.models.filter((model) => model.id !== mediaModels?.ocr && model.id !== mediaModels?.vision).map((model) => ({
27
+ model,
28
+ provider
29
+ }));
30
+ if (candidates.length < 2) return candidates;
31
+ const { resolveDefaultModelForAgent } = await import("openclaw/plugin-sdk/agent-runtime");
32
+ const primary = resolveDefaultModelForAgent({
33
+ cfg: config,
34
+ allowManifestNormalization: false,
35
+ allowPluginNormalization: false
36
+ });
37
+ const primaryId = primary.provider === "llama-cpp" ? primary.model : void 0;
38
+ return candidates.toSorted((a, b) => Number(b.model.id === primaryId) - Number(a.model.id === primaryId));
39
+ }
40
+ async function isFile(filePath) {
41
+ return await fs.stat(filePath).then((stat) => stat.isFile()).catch(() => false);
42
+ }
43
+ async function resolveCachedArtifact(source, cacheDir, signal) {
44
+ return await ensureLlamaCppModel({
45
+ source,
46
+ cacheDir,
47
+ download: false,
48
+ signal
49
+ }).catch(() => {
50
+ signal?.throwIfAborted();
51
+ });
52
+ }
53
+ async function resolveCachedCandidate(candidate, signal) {
54
+ const source = resolveLlamaCppModelSource(candidate.model);
55
+ const resolved = resolveCachedLlamaCppModelPath(candidate);
56
+ if (resolved && await isFile(resolved)) return resolved;
57
+ if (candidate.model.id === "gemma-4-e4b-it-q4_k_m") {
58
+ const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
59
+ if (await isFile(legacy)) return legacy;
60
+ }
61
+ if (/^(?:hf|huggingface|https):/iu.test(source)) return await resolveCachedArtifact(source, resolveLlamaCppModelCacheDir(candidate.provider), signal);
62
+ }
63
+ function buildSetupResult(params) {
64
+ const existing = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
65
+ const switchingFromExternal = Boolean(existing && !existing.localService);
66
+ return {
67
+ profiles: [],
68
+ ...params.defaultModel ? { defaultModel: params.defaultModel } : {},
69
+ configPatch: {
70
+ ...buildLlamaCppAuthProfileRemovalPatch(params.config),
71
+ models: {
72
+ mode: params.config.models?.mode ?? "merge",
73
+ providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig({
74
+ existing: switchingFromExternal ? void 0 : existing,
75
+ managed: params.managed,
76
+ modelInventory: params.plan === "embedding-only" ? existing?.models ?? [] : params.model ? [params.model, ...existing?.localService ? existing.models.filter((model) => model.id !== params.model?.id) : []] : existing?.models
77
+ }) }
78
+ }
79
+ }
80
+ };
81
+ }
82
+ async function detectLlamaCppSetup(ctx) {
83
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
84
+ const command = existing?.localService?.command;
85
+ const presetPath = existing?.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset");
86
+ if (!command || !path.isAbsolute(command) || !await isFile(command) || !presetPath || !await isFile(presetPath)) return null;
87
+ for (const candidate of await configuredCandidates(ctx.config)) if (await resolveCachedCandidate(candidate, ctx.signal)) return {
88
+ modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
89
+ detail: "Managed llama.cpp server ready"
90
+ };
91
+ return null;
92
+ }
93
+ async function prepareLlamaCppSetup(ctx) {
94
+ const detected = await detectLlamaCppSetup(ctx);
95
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
96
+ if (detected?.modelRef !== ctx.modelRef || !existing?.localService?.command) return null;
97
+ const baseUrl = existing.baseUrl?.replace(/\/+$/u, "") ?? "";
98
+ const rootUrl = baseUrl.replace(/\/v1$/u, "");
99
+ return buildSetupResult({
100
+ config: ctx.config,
101
+ plan: "chat",
102
+ defaultModel: ctx.modelRef,
103
+ managed: {
104
+ command: existing.localService.command,
105
+ baseUrl,
106
+ healthUrl: existing.localService.healthUrl ?? `${rootUrl}/health`,
107
+ args: existing.localService.args ?? []
108
+ }
109
+ });
110
+ }
111
+ function resolveEmbeddingSetup(config, cacheDir) {
112
+ const defaults = config.memory?.search;
113
+ const models = listAgentIds(config).flatMap((agentId) => {
114
+ const override = resolveAgentConfig(config, agentId)?.memory?.search;
115
+ if (!(override?.enabled ?? defaults?.enabled ?? true) || (override?.provider ?? defaults?.provider) !== "local") return [];
116
+ return [resolveLlamaCppEmbeddingModel({
117
+ modelPath: override?.local?.modelPath ?? defaults?.local?.modelPath,
118
+ modelCacheDir: cacheDir
119
+ })];
120
+ });
121
+ const model = models[0] ?? resolveLlamaCppEmbeddingModel({ modelCacheDir: cacheDir });
122
+ return {
123
+ model,
124
+ localMemoryIntent: models.length > 0,
125
+ conflict: models.some((candidate) => candidate.source !== model.source)
126
+ };
127
+ }
128
+ async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localMemoryIntent, hardware, asset, runtimeNote) {
129
+ if (ctx.embeddingOnly) return await resolveEmbeddingOnlyPlan(ctx, candidates, localMemoryIntent);
130
+ let candidate = candidates[0];
131
+ const configuredPath = candidate ? await resolveCachedCandidate(candidate, ctx.signal) : void 0;
132
+ if (candidate && configuredPath) {
133
+ if (runtimeNote && !await ctx.prompter.confirm({
134
+ message: `${runtimeNote} Use cached ${candidate.model.name} on Gateway host ${os.hostname()} with the verified CPU runtime?`,
135
+ initialValue: false
136
+ })) return;
137
+ return {
138
+ kind: "chat",
139
+ candidate,
140
+ cachedPath: configuredPath
141
+ };
142
+ }
143
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
144
+ const provider = existing?.localService ? existing : buildLlamaCppProviderConfig();
145
+ const cacheDir = resolveLlamaCppModelCacheDir(provider);
146
+ if (candidate) {
147
+ const source = resolveLlamaCppModelSource(candidate.model);
148
+ let size;
149
+ try {
150
+ if (path.isAbsolute(source) || !/^[a-z][a-z\d+.-]*:/iu.test(source)) {
151
+ const cachedPath = await ensureLlamaCppModel({
152
+ source,
153
+ cacheDir,
154
+ download: false,
155
+ signal: ctx.signal
156
+ });
157
+ return {
158
+ kind: "chat",
159
+ candidate,
160
+ cachedPath
161
+ };
162
+ }
163
+ size = await resolveLlamaCppModelDownloadSize(source, cacheDir, ctx.signal);
164
+ } catch (error) {
165
+ ctx.signal?.throwIfAborted();
166
+ await ctx.prompter.note(`Cannot use configured model ${candidate.model.name}: ${error instanceof Error ? error.message : String(error)} Check params.modelPath and retry llama.cpp setup.`, "Setup skipped");
167
+ return;
168
+ }
169
+ return await ctx.prompter.confirm({
170
+ message: `${runtimeNote ? `${runtimeNote}\n` : ""}Download ${candidate.model.name} (${size ? `${(size / BYTES_PER_GB).toFixed(1)} GB` : "size unknown"}), ${describeEmbeddingDownload(embeddingModelIsDefault)}, and the verified ${asset.backend.toUpperCase()} runtime on Gateway host ${os.hostname()}, then use this model?`,
171
+ initialValue: false
172
+ }) ? {
173
+ kind: "chat",
174
+ candidate
175
+ } : void 0;
176
+ }
177
+ const cachedModels = /* @__PURE__ */ new Map();
178
+ for (const recipe of resolveLlamaCppModelCandidates(hardware, asset.backend).recipes) {
179
+ const cached = await resolveCachedArtifact(resolveLlamaCppModelSource(recipe.model), cacheDir, ctx.signal);
180
+ if (cached) {
181
+ cachedModels.set(recipe.model.id, cached);
182
+ break;
183
+ }
184
+ }
185
+ const cachedEmbedding = embeddingModelIsDefault && Boolean(await resolveCachedArtifact("hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf", cacheDir, ctx.signal));
186
+ const recommendation = recommendLlamaCppModel(hardware, asset.backend, {
187
+ modelIds: new Set(cachedModels.keys()),
188
+ embedding: cachedEmbedding,
189
+ runtime: await isFile(resolveManagedLlamaServerPaths(asset).command)
190
+ });
191
+ if (recommendation.kind === "recommended") {
192
+ const { recipe } = recommendation;
193
+ const cachedPath = cachedModels.get(recipe.model.id);
194
+ candidate = {
195
+ model: recipe.model,
196
+ provider
197
+ };
198
+ const recommendationSummary = [
199
+ `Runs on Gateway host ${os.hostname()} (${hardware.platform}/${hardware.arch}), using ${asset.backend === "metal" ? "Apple Metal" : asset.backend === "cuda" ? "NVIDIA CUDA" : "the CPU"}.`,
200
+ `${formatLlamaCppMemory(hardware.totalMemoryBytes)} RAM; ${formatLlamaCppMemory(hardware.availableDiskBytes ?? 0)} free disk.`,
201
+ !hardware.sharedDisk ? `${formatLlamaCppMemory(hardware.availableRuntimeDiskBytes ?? 0)} free on the runtime volume.` : void 0,
202
+ runtimeNote,
203
+ recommendation.reason,
204
+ !embeddingModelIsDefault ? "This estimate includes the default embedding model; your configured embedding model may need more memory and disk space." : void 0,
205
+ "OpenClaw will check a real tool call before making this your default model."
206
+ ].filter(Boolean).join("\n");
207
+ if (await ctx.prompter.confirm({
208
+ message: `${recommendationSummary}\n\n${cachedPath ? `Use cached ${recipe.model.name}, download any missing embedding and ${asset.backend.toUpperCase()} runtime files, then use this model?` : `Download ${recipe.model.name} (${(recipe.sizeBytes / BYTES_PER_GB).toFixed(1)} GB), ${describeEmbeddingDownload(embeddingModelIsDefault)}, and the verified ${asset.backend.toUpperCase()} runtime, then use this model?`}`,
209
+ initialValue: false
210
+ })) return {
211
+ kind: "chat",
212
+ candidate,
213
+ cachedPath
214
+ };
215
+ } else if (!localMemoryIntent) {
216
+ await ctx.prompter.note(recommendation.reason, "Setup skipped");
217
+ return;
218
+ }
219
+ const embeddingPlan = await resolveEmbeddingOnlyPlan(ctx, candidates, localMemoryIntent);
220
+ if (embeddingPlan) {
221
+ if (await ctx.prompter.confirm({
222
+ message: `${runtimeNote ? `${runtimeNote} ` : ""}Install a verified ${asset.backend.toUpperCase()} llama.cpp server on Gateway host ${os.hostname()} and download only ${describeEmbeddingDownload(embeddingModelIsDefault)}? Your chat model will stay unchanged.`,
223
+ initialValue: false
224
+ })) return embeddingPlan;
225
+ }
226
+ await ctx.prompter.note("Local model setup skipped.", "Setup skipped");
227
+ }
228
+ async function resolveEmbeddingOnlyPlan(ctx, candidates, localMemoryIntent) {
229
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
230
+ if (localMemoryIntent && existing && (!existing.localService || candidates.length > 0)) {
231
+ await ctx.prompter.note("Embedding-only setup cannot replace an existing llama.cpp server or configured llama.cpp chat routes. Move those routes to another provider, remove any existing server config, then retry llama.cpp setup.", "Setup skipped");
232
+ return;
233
+ }
234
+ return localMemoryIntent ? { kind: "embedding-only" } : void 0;
235
+ }
236
+ async function runLlamaCppSetup(ctx) {
237
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
238
+ const managedExisting = existing?.localService ? existing : void 0;
239
+ const mediaModels = resolveLlamaCppMediaModels(managedExisting);
240
+ const cacheDir = resolveLlamaCppModelCacheDir(managedExisting);
241
+ const embeddingSetup = resolveEmbeddingSetup(ctx.config, cacheDir);
242
+ if (embeddingSetup.conflict) {
243
+ await ctx.prompter.note("Configured agents resolve to different local embedding models. Set memory.search.local.modelPath and any per-agent overrides to the same value, then retry llama.cpp setup.", "Setup skipped");
244
+ return { profiles: [] };
245
+ }
246
+ const embeddingModel = embeddingSetup.model;
247
+ const hardware = await detectLlamaCppHardware({
248
+ cacheDir,
249
+ signal: ctx.signal
250
+ });
251
+ let asset;
252
+ let runtimeNote;
253
+ try {
254
+ asset = selectLlamaServerAsset(hardware.platform, hardware.arch, hardware.accelerator);
255
+ } catch (error) {
256
+ if (hardware.accelerator.kind !== "cuda") throw error;
257
+ asset = selectLlamaServerAsset(hardware.platform, hardware.arch, { kind: "cpu" });
258
+ runtimeNote = `${error instanceof Error ? error.message : String(error)} This recommendation uses CPU execution.`;
259
+ }
260
+ const plan = await resolveSetupPlan(ctx, await configuredCandidates(ctx.config), embeddingModel.isDefault, embeddingSetup.localMemoryIntent, hardware, asset, runtimeNote);
261
+ if (!plan) return { profiles: [] };
262
+ const progress = ctx.prompter.progress(`${ctx.embeddingOnly && runtimeNote ? `${runtimeNote}\n` : ""}Preparing managed llama.cpp server…`);
263
+ try {
264
+ await ensureLlamaServerInstalled({
265
+ asset,
266
+ signal: ctx.signal,
267
+ onProgress: (status) => progress.update(formatDownloadProgress("llama.cpp runtime", status))
268
+ });
269
+ let chatModel;
270
+ if (plan.kind === "chat") {
271
+ const chatModelPath = plan.cachedPath ?? await ensureLlamaCppModel({
272
+ source: resolveLlamaCppModelSource(plan.candidate.model),
273
+ cacheDir,
274
+ download: true,
275
+ signal: ctx.signal,
276
+ onProgress: (status) => progress.update(formatDownloadProgress(plan.candidate.model.name, status))
277
+ });
278
+ const configuredContext = plan.candidate.model.params?.contextSize;
279
+ chatModel = {
280
+ mode: "configure",
281
+ id: plan.candidate.model.id,
282
+ path: chatModelPath,
283
+ contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : plan.candidate.model.contextTokens,
284
+ maxTokens: plan.candidate.model.maxTokens
285
+ };
286
+ } else chatModel = { mode: mediaModels ? "preserve" : "remove" };
287
+ const embeddingModelLabel = embeddingModel.isDefault ? "EmbeddingGemma" : "configured embedding model";
288
+ const embeddingModelPath = await ensureLlamaCppModel({
289
+ source: embeddingModel.source,
290
+ cacheDir,
291
+ download: true,
292
+ signal: ctx.signal,
293
+ onProgress: (status) => progress.update(formatDownloadProgress(embeddingModelLabel, status))
294
+ });
295
+ const managed = await prepareManagedLlamaServer({
296
+ chatModel,
297
+ configuredChatModelIds: mediaModels ? managedExisting?.models.map((model) => model.id) : plan.kind === "chat" ? plan.candidate.provider.models.map((model) => model.id) : [],
298
+ ...mediaModels ? {
299
+ mediaModels: [],
300
+ modelsMax: 1,
301
+ localService: managedExisting?.localService
302
+ } : {},
303
+ embeddingModelPath,
304
+ asset,
305
+ isolated: true,
306
+ signal: ctx.signal,
307
+ onProgress: (status) => progress.update(formatDownloadProgress("llama.cpp runtime", status))
308
+ });
309
+ ctx.signal?.throwIfAborted();
310
+ progress.stop("Managed llama.cpp server prepared");
311
+ return buildSetupResult({
312
+ config: ctx.config,
313
+ managed,
314
+ plan: plan.kind,
315
+ ...plan.kind === "chat" ? {
316
+ defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${plan.candidate.model.id}`,
317
+ model: plan.candidate.model
318
+ } : {}
319
+ });
320
+ } catch (error) {
321
+ progress.stop("llama.cpp setup failed");
322
+ const detail = error instanceof Error ? error.message : String(error);
323
+ throw new Error(error instanceof UnsupportedLlamaServerHostError ? `Managed llama.cpp setup is unavailable on this host. ${detail}` : `Managed llama.cpp setup failed. Run openclaw doctor, fix the reported runtime or model issue, then retry. ${detail}`, { cause: error });
324
+ }
325
+ }
326
+ async function configureLlamaCppNonInteractive(ctx) {
327
+ if (ctx.opts.llamaCppEmbeddingOnly !== true) throw new Error("Managed llama.cpp non-interactive setup requires --llama-cpp-embedding-only to consent to downloading the embedding model and verified server runtime.");
328
+ const result = await runLlamaCppSetup({
329
+ config: ctx.config,
330
+ embeddingOnly: true,
331
+ prompter: {
332
+ async confirm() {
333
+ throw new Error("Non-interactive embedding-only setup cannot prompt.");
334
+ },
335
+ async note(message) {
336
+ throw new Error(message);
337
+ },
338
+ progress(label) {
339
+ ctx.runtime.log(label);
340
+ return {
341
+ update: ctx.runtime.log,
342
+ stop: ctx.runtime.log
343
+ };
344
+ }
345
+ }
346
+ });
347
+ if (!result.configPatch) throw new Error("Set memory.search.provider to \"local\" (globally or for an enabled agent), then retry embedding-only setup.");
348
+ return mergeDeep(ctx.config, result.configPatch, { undefinedValues: "replace" });
349
+ }
350
+ //#endregion
351
+ export { configureLlamaCppNonInteractive, detectLlamaCppSetup, prepareLlamaCppSetup, runLlamaCppSetup };