@openclaw/llama-cpp-provider 2026.9.1 → 2026.9.2

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,18 +1,19 @@
1
- import { C as resolveLegacyLlamaCppModelCacheDir, D as resolveLlamaCppModelSource, E as resolveLlamaCppModelCacheDir, O as resolveLlamaCppSyntheticApiKey, S as resolveHomePath, T as resolveLlamaCppEmbeddingModel, _ as LLAMA_CPP_PROVIDER_ID, a as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, b as meetsLlamaCppDefaultModelRamFloor, c as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256, d as DEFAULT_LLAMA_CPP_MODEL_ID, f as DEFAULT_LLAMA_CPP_MODEL_REVISION, g as LLAMA_CPP_DEFAULT_PORT, i as DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE, l as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES, m as DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES, n as resolveManagedLlamaCppProviderConfig, o as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, p as DEFAULT_LLAMA_CPP_MODEL_SHA256, s as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION, u as DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE, v as LLAMA_CPP_PROVIDER_LABEL, w as resolveLlamaCppDataDir, x as resolveCachedLlamaCppModelPath, y as buildLlamaCppProviderConfig } from "./managed-provider-config-Ovg5QQxD.js";
1
+ import { C as resolveLlamaCppDataDir, D as resolveLlamaCppSyntheticApiKey, E as resolveLlamaCppModelSource, S as resolveLegacyLlamaCppModelCacheDir, T as resolveLlamaCppModelCacheDir, _ as LLAMA_CPP_PROVIDER_ID, a as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, b as resolveCachedLlamaCppModelPath, c as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256, d as DEFAULT_LLAMA_CPP_MODEL_ID, f as DEFAULT_LLAMA_CPP_MODEL_REVISION, g as LLAMA_CPP_DEFAULT_PORT, h as DEFAULT_LLAMA_CPP_MODEL_URI, i as DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE, l as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES, m as DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES, n as resolveManagedLlamaCppProviderConfig, o as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, p as DEFAULT_LLAMA_CPP_MODEL_SHA256, r as DEFAULT_LLAMA_CPP_CONTEXT_SIZE, s as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION, u as DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE, v as LLAMA_CPP_PROVIDER_LABEL, w as resolveLlamaCppEmbeddingModel, x as resolveHomePath, y as buildLlamaCppProviderConfig } from "./managed-provider-config-D9X1wNEo.js";
2
2
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
3
3
  import path from "node:path";
4
4
  import { getEmbeddingProvider } from "openclaw/plugin-sdk/embedding-providers";
5
5
  import os from "node:os";
6
6
  import { asBoolean, asOptionalRecord, asPositiveSafeInteger, isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
7
- import { execFile } from "node:child_process";
8
7
  import { createHash, randomUUID } from "node:crypto";
9
- import fs, { constants } from "node:fs";
10
- import fs$1 from "node:fs/promises";
11
- import { ARCHIVE_LIMIT_ERROR_CODE, ArchiveLimitError, extractArchive } from "openclaw/plugin-sdk/archive";
8
+ import fs from "node:fs/promises";
12
9
  import net from "node:net";
13
10
  import { readProviderJsonResponse, readProviderTextResponse } from "openclaw/plugin-sdk/provider-http";
14
11
  import { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } from "openclaw/plugin-sdk/ssrf-runtime";
15
12
  import { fetchConfiguredLocalOriginWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime-internal";
13
+ import { execFile } from "node:child_process";
14
+ import fs$1, { constants } from "node:fs";
15
+ import { toErrorObject } from "openclaw/plugin-sdk/error-runtime";
16
+ import { ARCHIVE_LIMIT_ERROR_CODE, ArchiveLimitError, extractArchive } from "openclaw/plugin-sdk/archive";
16
17
  import { CUSTOM_LOCAL_AUTH_MARKER, applyAuthProfileConfig, buildApiKeyCredential, ensureApiKeyFromEnvOrPrompt, hasConfiguredSecretInput, isNonSecretApiKeyMarker, normalizeOptionalSecretInput, upsertAuthProfileWithLock } from "openclaw/plugin-sdk/provider-auth";
17
18
  import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
18
19
  import { removeAuthProfileConfig, removeProviderAuthProfilesWithLock, resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
@@ -26,6 +27,12 @@ import { listAgentIds, resolveAgentConfig } from "openclaw/plugin-sdk/agent-scop
26
27
  //#region extensions/llama-cpp/src/llama-server-assets.ts
27
28
  const LLAMA_SERVER_RELEASE = "b10534";
28
29
  const LLAMA_SERVER_COMMIT = "2b5621094ef383cdcd8428ef6d22efe5df976532";
30
+ const MEBIBYTE$1 = 1048576;
31
+ const CUDA_ARCHIVE_LIMITS = {
32
+ maxArchiveBytes: 400 * MEBIBYTE$1,
33
+ maxExtractedBytes: 600 * MEBIBYTE$1,
34
+ maxEntryBytes: 520 * MEBIBYTE$1
35
+ };
29
36
  const MACOS_ALIASES = [
30
37
  ["libggml-rpc.0.20.2.dylib", ["libggml-rpc.0.dylib", "libggml-rpc.dylib"]],
31
38
  ["libllama.0.1.2.dylib", ["libllama.0.dylib", "libllama.dylib"]],
@@ -89,6 +96,34 @@ const LLAMA_SERVER_ASSETS = [
89
96
  executable: "llama-server",
90
97
  regularFileAliases: LINUX_ALIASES
91
98
  },
99
+ {
100
+ platform: "win32",
101
+ arch: "x64",
102
+ backend: "cuda",
103
+ archive: "zip",
104
+ archiveRoot: ".",
105
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cuda-12.4-x64.zip`,
106
+ sha256: "f4964cec6c96e90a5f7379e4c2d0c437d8f1fe4263cbb8f39c7625f7c5937986",
107
+ executable: "llama-server.exe",
108
+ regularFileAliases: [],
109
+ limits: CUDA_ARCHIVE_LIMITS,
110
+ dependencies: [{
111
+ archive: "zip",
112
+ archiveRoot: ".",
113
+ name: "cudart-llama-bin-win-cuda-12.4-x64.zip",
114
+ sha256: "8c79a9b226de4b3cacfd1f83d24f962d0773be79f1e7b75c6af4ded7e32ae1d6",
115
+ regularFileAliases: [],
116
+ files: [
117
+ "cublas64_12.dll",
118
+ "cublasLt64_12.dll",
119
+ "cudart64_12.dll"
120
+ ],
121
+ limits: {
122
+ ...CUDA_ARCHIVE_LIMITS,
123
+ maxEntries: 3
124
+ }
125
+ }]
126
+ },
92
127
  {
93
128
  platform: "win32",
94
129
  arch: "arm64",
@@ -112,13 +147,21 @@ const LLAMA_SERVER_ASSETS = [
112
147
  regularFileAliases: []
113
148
  }
114
149
  ];
115
- function selectLlamaServerAsset(platform = process.platform, arch = process.arch) {
116
- const asset = LLAMA_SERVER_ASSETS.find((candidate) => candidate.platform === platform && candidate.arch === arch);
150
+ function selectLlamaServerAsset(platform = process.platform, arch = process.arch, acceleration) {
151
+ const backend = acceleration?.kind ?? (platform === "darwin" && arch === "arm64" ? "metal" : "cpu");
152
+ if (backend === "cuda" && acceleration?.kind === "cuda") {
153
+ if (platform !== "win32" || arch !== "x64") throw new Error(`No verified CUDA llama-server ${LLAMA_SERVER_RELEASE} build is available for ${platform}/${arch}. Install a CUDA-enabled llama-server manually and configure its absolute path, or explicitly choose CPU setup.`);
154
+ if (!(acceleration.devices.length > 0 && acceleration.devices.every((device) => {
155
+ const version = /^(\d+)\.(\d+)(?:\.\d+)?$/u.exec(device.driverVersion);
156
+ return version && (Number(version[1]) > 551 || Number(version[1]) === 551 && Number(version[2]) >= 78) && (device.computeCapability === void 0 || device.computeCapability >= 5);
157
+ }))) throw new Error("The verified CUDA 12.4 build requires NVIDIA driver 551.78 or newer and compute capability 5.0 or newer. Update the NVIDIA driver, configure a compatible llama-server manually, or explicitly choose CPU setup.");
158
+ }
159
+ const asset = LLAMA_SERVER_ASSETS.find((candidate) => candidate.platform === platform && candidate.arch === arch && candidate.backend === backend);
117
160
  if (!asset) throw new Error(`No verified llama-server ${LLAMA_SERVER_RELEASE} build is available for ${platform}/${arch}. Install a compatible llama-server manually, then rerun llama.cpp setup with its absolute path.`);
118
161
  return asset;
119
162
  }
120
163
  function resolveManagedLlamaServerPaths(asset = selectLlamaServerAsset()) {
121
- const installDir = path.join(resolveLlamaCppDataDir(), LLAMA_SERVER_RELEASE, `${asset.platform}-${asset.arch}`);
164
+ const installDir = path.join(resolveLlamaCppDataDir(), LLAMA_SERVER_RELEASE, `${asset.platform}-${asset.arch}${asset.backend === "cuda" ? "-cuda-12.4" : ""}`);
122
165
  return {
123
166
  installDir,
124
167
  command: path.join(installDir, asset.executable),
@@ -148,13 +191,13 @@ function resolveArchiveRoot(destDir, archiveRoot) {
148
191
  return path.join(destDir, ...parts);
149
192
  }
150
193
  async function assertRegularFile(filePath, label) {
151
- const stat = await fs$1.lstat(filePath).catch(() => void 0);
194
+ const stat = await fs.lstat(filePath).catch(() => void 0);
152
195
  if (!stat?.isFile() || stat.nlink > 1) throw new Error(`llama-server archive does not contain regular ${label}`);
153
196
  return stat;
154
197
  }
155
198
  async function materializeAssetAliases(params) {
156
- const claimedNames = /* @__PURE__ */ new Set([assertManifestBasename(params.asset.executable)]);
157
- await assertRegularFile(path.join(params.rootDir, params.asset.executable), `executable ${params.asset.executable}`);
199
+ const claimedNames = new Set(params.requiredFiles.map(assertManifestBasename));
200
+ for (const file of claimedNames) await assertRegularFile(path.join(params.rootDir, file), `file ${file}`);
158
201
  let copiedBytes = 0;
159
202
  for (const [rawSource, rawAliases] of params.asset.regularFileAliases) {
160
203
  const source = assertManifestBasename(rawSource);
@@ -169,25 +212,28 @@ async function materializeAssetAliases(params) {
169
212
  copiedBytes += sourceStat.size;
170
213
  if (copiedBytes > MAX_ALIAS_BYTES) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.EXTRACTED_SIZE_EXCEEDS_LIMIT);
171
214
  const aliasPath = path.join(params.rootDir, alias);
172
- await fs$1.copyFile(sourcePath, aliasPath, constants.COPYFILE_EXCL);
173
- await fs$1.chmod(aliasPath, sourceStat.mode & 511);
215
+ await fs.copyFile(sourcePath, aliasPath, constants.COPYFILE_EXCL);
216
+ await fs.chmod(aliasPath, sourceStat.mode & 511);
174
217
  if ((await assertRegularFile(aliasPath, `alias ${alias}`)).size !== sourceStat.size) throw new Error(`llama-server archive alias copy is incomplete: ${alias}`);
175
218
  }
176
219
  }
177
220
  }
178
- /** Extracts one verified asset and returns its unpublished executable path. */
179
- async function extractLlamaServerArchive(params) {
221
+ async function extractVerifiedArchive(params) {
180
222
  const isTar = params.asset.archive === "tar.gz";
223
+ const limits = {
224
+ ...LLAMA_ARCHIVE_LIMITS,
225
+ ...params.asset.limits
226
+ };
181
227
  const aliasCount = params.asset.regularFileAliases.reduce((count, [, aliases]) => count + aliases.length, 0);
182
- if (aliasCount > LLAMA_ARCHIVE_LIMITS.maxEntries) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.ENTRY_COUNT_EXCEEDS_LIMIT);
228
+ if (aliasCount > limits.maxEntries) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.ENTRY_COUNT_EXCEEDS_LIMIT);
183
229
  await extractArchive({
184
230
  archivePath: params.archivePath,
185
231
  destDir: params.destDir,
186
232
  kind: isTar ? "tar" : "zip",
187
233
  timeoutMs: 0,
188
234
  limits: {
189
- ...LLAMA_ARCHIVE_LIMITS,
190
- maxEntries: LLAMA_ARCHIVE_LIMITS.maxEntries - aliasCount
235
+ ...limits,
236
+ maxEntries: limits.maxEntries - aliasCount
191
237
  },
192
238
  tarGzip: isTar,
193
239
  entryFilter: (entry) => entry.kind === "symlink" ? "skip" : "extract",
@@ -196,10 +242,25 @@ async function extractLlamaServerArchive(params) {
196
242
  const rootDir = resolveArchiveRoot(params.destDir, params.asset.archiveRoot);
197
243
  await materializeAssetAliases({
198
244
  rootDir,
199
- asset: params.asset
245
+ asset: params.asset,
246
+ requiredFiles: params.requiredFiles
247
+ });
248
+ return rootDir;
249
+ }
250
+ /** Extracts one verified asset and returns its unpublished executable path. */
251
+ async function extractLlamaServerArchive(params) {
252
+ const rootDir = await extractVerifiedArchive({
253
+ ...params,
254
+ requiredFiles: [params.asset.executable]
200
255
  });
201
256
  return path.join(rootDir, params.asset.executable);
202
257
  }
258
+ async function extractLlamaServerDependencyArchive(params) {
259
+ return await extractVerifiedArchive({
260
+ ...params,
261
+ requiredFiles: params.asset.files
262
+ });
263
+ }
203
264
  //#endregion
204
265
  //#region extensions/llama-cpp/src/llama-server-install.ts
205
266
  const DOWNLOAD_TIMEOUT_MS = 18e5;
@@ -225,15 +286,51 @@ function assertSupportedLinuxRuntime(asset) {
225
286
  function assetUrl(asset) {
226
287
  return `https://github.com/ggml-org/llama.cpp/releases/download/${LLAMA_SERVER_RELEASE}/${asset.name}`;
227
288
  }
228
- async function sha256File(filePath) {
229
- const hash = createHash("sha256");
230
- await new Promise((resolve, reject) => {
231
- const input = fs.createReadStream(filePath);
232
- input.on("data", (chunk) => hash.update(chunk));
233
- input.once("error", reject);
234
- input.once("end", resolve);
289
+ const verifiedFiles = /* @__PURE__ */ new Map();
290
+ const VERIFIED_FILE_LIMIT = 16;
291
+ function fileIdentity(stat) {
292
+ return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
293
+ }
294
+ function rememberVerifiedFile(filePath, stat, sha256) {
295
+ verifiedFiles.delete(filePath);
296
+ verifiedFiles.set(filePath, {
297
+ identity: fileIdentity(stat),
298
+ sha256
235
299
  });
236
- return hash.digest("hex");
300
+ if (verifiedFiles.size > VERIFIED_FILE_LIMIT) {
301
+ const oldest = verifiedFiles.keys().next().value;
302
+ if (oldest !== void 0) verifiedFiles.delete(oldest);
303
+ }
304
+ }
305
+ async function sha256File(filePath, signal) {
306
+ signal?.throwIfAborted();
307
+ try {
308
+ const identity = fileIdentity(await fs.stat(filePath, { bigint: true }));
309
+ const verified = verifiedFiles.get(filePath);
310
+ if (verified?.identity === identity) return verified.sha256;
311
+ verifiedFiles.delete(filePath);
312
+ const handle = await fs.open(filePath, "r");
313
+ try {
314
+ const before = fileIdentity(await handle.stat({ bigint: true }));
315
+ const hash = createHash("sha256");
316
+ const input = handle.createReadStream({
317
+ autoClose: false,
318
+ highWaterMark: 1048576,
319
+ signal
320
+ });
321
+ for await (const chunk of input) hash.update(chunk);
322
+ const after = await handle.stat({ bigint: true });
323
+ if (before !== fileIdentity(after) || before !== fileIdentity(await fs.stat(filePath, { bigint: true }))) throw new Error(`File changed during integrity verification: ${filePath}. Retry setup.`);
324
+ const sha256 = hash.digest("hex");
325
+ rememberVerifiedFile(filePath, after, sha256);
326
+ return sha256;
327
+ } finally {
328
+ await handle.close();
329
+ }
330
+ } catch (error) {
331
+ verifiedFiles.delete(filePath);
332
+ throw error;
333
+ }
237
334
  }
238
335
  function readResponseSha256(response) {
239
336
  for (const name of ["x-checksum-sha256", "x-linked-etag"]) {
@@ -245,7 +342,7 @@ function readResponseSha256(response) {
245
342
  }
246
343
  async function downloadVerifiedFile(params) {
247
344
  const partialPath = `${params.destination}.partial-${randomUUID()}`;
248
- await fs$1.mkdir(path.dirname(params.destination), { recursive: true });
345
+ await fs.mkdir(path.dirname(params.destination), { recursive: true });
249
346
  const { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } = await import("openclaw/plugin-sdk/ssrf-runtime");
250
347
  try {
251
348
  const { response, release } = await fetchWithSsrFGuard({
@@ -262,7 +359,7 @@ async function downloadVerifiedFile(params) {
262
359
  if (!expectedSha256 && params.requireServerDigest) throw new Error("the download server did not provide a SHA-256 digest; download the GGUF manually and configure its local path");
263
360
  const contentLength = Number(response.headers.get("content-length"));
264
361
  const totalSize = params.expectedSize ?? (Number.isFinite(contentLength) && contentLength > 0 ? contentLength : 0);
265
- const handle = await fs$1.open(partialPath, "wx", 384);
362
+ const handle = await fs.open(partialPath, "wx", 384);
266
363
  const hash = createHash("sha256");
267
364
  let downloadedSize = 0;
268
365
  let previousSize = 0;
@@ -287,23 +384,31 @@ async function downloadVerifiedFile(params) {
287
384
  bytesPerSecond: rollingBytesPerSecond
288
385
  });
289
386
  }
387
+ if (params.expectedSize && downloadedSize !== params.expectedSize) throw new Error(`download size mismatch: expected ${params.expectedSize}, got ${downloadedSize}`);
388
+ const actualSha256 = hash.digest("hex");
389
+ if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
390
+ const completed = await handle.stat({ bigint: true });
391
+ params.signal?.throwIfAborted();
392
+ await fs.rename(partialPath, params.destination);
393
+ const published = await handle.stat({ bigint: true });
394
+ if (completed.size === published.size && completed.mtimeNs === published.mtimeNs) rememberVerifiedFile(params.destination, published, actualSha256);
290
395
  } finally {
291
396
  await handle.close();
292
397
  }
293
- if (params.expectedSize && downloadedSize !== params.expectedSize) throw new Error(`download size mismatch: expected ${params.expectedSize}, got ${downloadedSize}`);
294
- const actualSha256 = hash.digest("hex");
295
- if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
296
- await fs$1.rename(partialPath, params.destination);
297
398
  } finally {
298
399
  await release();
299
400
  }
300
401
  } finally {
301
- await fs$1.rm(partialPath, { force: true }).catch(() => void 0);
402
+ await fs.rm(partialPath, { force: true }).catch(() => void 0);
302
403
  }
303
404
  }
304
- async function runVersion(command) {
405
+ async function runServerCommand(command, args, signal) {
305
406
  return await new Promise((resolve, reject) => {
306
- execFile(command, ["--version"], { timeout: VERSION_TIMEOUT_MS }, (error, stdout, stderr) => {
407
+ execFile(command, args, {
408
+ timeout: VERSION_TIMEOUT_MS,
409
+ signal,
410
+ windowsHide: true
411
+ }, (error, stdout, stderr) => {
307
412
  if (error) reject(new Error(error.message, { cause: error }));
308
413
  else resolve(`${stdout}${stderr}`.trim());
309
414
  });
@@ -315,72 +420,425 @@ function formatRuntimeDependencyError(error) {
315
420
  if (process.platform === "win32") return new Error(`The verified llama-server build could not start. Install the Microsoft Visual C++ 2015-2022 Redistributable, then rerun llama.cpp setup. Detail: ${detail}`, { cause: error });
316
421
  return new Error(`The verified llama-server build could not start: ${detail}`, { cause: error });
317
422
  }
318
- async function validateInstalledServer(command) {
423
+ async function validateInstalledServer(command, asset, signal) {
319
424
  let version;
320
425
  try {
321
- version = await runVersion(command);
426
+ version = await runServerCommand(command, ["--version"], signal);
322
427
  } catch (error) {
428
+ signal?.throwIfAborted();
323
429
  throw formatRuntimeDependencyError(error);
324
430
  }
325
431
  const match = (version.split(/\r?\n/u, 1)[0]?.trim() ?? "").match(/^version: .+ \(build (\d+), commit ([a-f\d]{9})\)$/u);
326
432
  const build = match?.[1] ? Number(match[1]) : void 0;
327
433
  const commit = match?.[2];
328
434
  if (build !== 10534 || commit !== "2b5621094ef383cdcd8428ef6d22efe5df976532".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"}`);
435
+ if (asset.backend === "cuda") {
436
+ const devices = await runServerCommand(command, ["--list-devices"], signal);
437
+ if (!/^\s*CUDA\d+: .+\(\d+ MiB, \d+ MiB free\)$/mu.test(devices)) throw new Error("The verified llama-server could not initialize an NVIDIA CUDA device. Update the NVIDIA driver and rerun setup, or configure a compatible llama-server manually. CPU fallback was not activated.");
438
+ }
329
439
  }
330
- async function installLlamaServer(asset) {
440
+ async function installLlamaServer(asset, options) {
441
+ options.signal?.throwIfAborted();
331
442
  assertSupportedLinuxRuntime(asset);
332
443
  const { installDir, command } = resolveManagedLlamaServerPaths(asset);
333
- if (await fs$1.stat(command).then((stat) => stat.isFile()).catch(() => false)) {
334
- await validateInstalledServer(command);
444
+ if (await fs.stat(command).then((stat) => stat.isFile()).catch(() => false)) {
445
+ await validateInstalledServer(command, asset, options.signal);
335
446
  return command;
336
447
  }
337
448
  const dataDir = resolveLlamaCppDataDir();
338
449
  const archivePath = path.join(dataDir, `.download-${randomUUID()}-${asset.name}`);
339
450
  const extractDir = path.join(dataDir, `.extract-${randomUUID()}`);
340
- await fs$1.mkdir(dataDir, { recursive: true });
451
+ await fs.mkdir(dataDir, { recursive: true });
341
452
  try {
342
453
  await downloadVerifiedFile({
343
454
  url: assetUrl(asset),
344
455
  destination: archivePath,
345
- expectedSha256: asset.sha256
456
+ expectedSha256: asset.sha256,
457
+ signal: options.signal,
458
+ onProgress: options.onProgress
346
459
  });
347
- await fs$1.mkdir(extractDir, { recursive: true });
460
+ const serverExtractDir = path.join(extractDir, "server");
461
+ await fs.mkdir(serverExtractDir, { recursive: true });
348
462
  const extractedCommand = await extractLlamaServerArchive({
349
463
  archivePath,
350
- destDir: extractDir,
464
+ destDir: serverExtractDir,
351
465
  asset
352
466
  });
353
467
  const extractedRoot = path.dirname(extractedCommand);
354
- await fs$1.chmod(extractedCommand, 493);
355
- await validateInstalledServer(extractedCommand);
356
- await fs$1.mkdir(path.dirname(installDir), { recursive: true });
357
- await fs$1.rm(installDir, {
468
+ for (const [index, dependency] of (asset.dependencies ?? []).entries()) {
469
+ options.signal?.throwIfAborted();
470
+ const dependencyArchive = path.join(extractDir, dependency.name);
471
+ await downloadVerifiedFile({
472
+ url: assetUrl(dependency),
473
+ destination: dependencyArchive,
474
+ expectedSha256: dependency.sha256,
475
+ signal: options.signal,
476
+ onProgress: options.onProgress
477
+ });
478
+ const dependencyExtractDir = path.join(extractDir, `dependency-${index}`);
479
+ await fs.mkdir(dependencyExtractDir);
480
+ const dependencyRoot = await extractLlamaServerDependencyArchive({
481
+ archivePath: dependencyArchive,
482
+ destDir: dependencyExtractDir,
483
+ asset: dependency
484
+ });
485
+ for (const file of dependency.files) await fs.copyFile(path.join(dependencyRoot, file), path.join(extractedRoot, file), fs$1.constants.COPYFILE_EXCL);
486
+ }
487
+ options.signal?.throwIfAborted();
488
+ await fs.chmod(extractedCommand, 493);
489
+ await validateInstalledServer(extractedCommand, asset, options.signal);
490
+ await fs.mkdir(path.dirname(installDir), { recursive: true });
491
+ options.signal?.throwIfAborted();
492
+ await fs.rm(installDir, {
358
493
  recursive: true,
359
494
  force: true
360
495
  });
361
- await fs$1.rename(extractedRoot, installDir);
362
- await validateInstalledServer(command);
496
+ await fs.rename(extractedRoot, installDir);
497
+ await validateInstalledServer(command, asset, options.signal);
363
498
  return command;
364
499
  } finally {
365
- await Promise.all([fs$1.rm(archivePath, { force: true }), fs$1.rm(extractDir, {
500
+ await Promise.all([fs.rm(archivePath, { force: true }), fs.rm(extractDir, {
366
501
  recursive: true,
367
502
  force: true
368
503
  })]);
369
504
  }
370
505
  }
371
- async function ensureLlamaServerInstalled() {
372
- const asset = selectLlamaServerAsset();
373
- const key = `${asset.platform}/${asset.arch}/${LLAMA_SERVER_RELEASE}`;
374
- const pending = installationPromises.get(key) ?? installLlamaServer(asset);
506
+ async function ensureLlamaServerInstalled(options = {}) {
507
+ options.signal?.throwIfAborted();
508
+ const asset = options.asset ?? selectLlamaServerAsset();
509
+ const key = resolveManagedLlamaServerPaths(asset).command;
510
+ const previous = installationPromises.get(key);
511
+ const pending = Promise.resolve(previous).catch(() => void 0).then(() => installLlamaServer(asset, options)).finally(() => {
512
+ if (installationPromises.get(key) === pending) installationPromises.delete(key);
513
+ });
375
514
  installationPromises.set(key, pending);
515
+ return {
516
+ command: previous && options.signal ? await new Promise((resolve, reject) => {
517
+ const signal = options.signal;
518
+ const onAbort = () => reject(toErrorObject(signal?.reason, "Installation cancelled"));
519
+ signal?.addEventListener("abort", onAbort, { once: true });
520
+ pending.then(resolve, reject).finally(() => signal?.removeEventListener("abort", onAbort));
521
+ if (signal?.aborted) onAbort();
522
+ }) : await pending,
523
+ asset
524
+ };
525
+ }
526
+ //#endregion
527
+ //#region extensions/llama-cpp/src/hardware.ts
528
+ const GIB$1 = 1024 ** 3;
529
+ const MIB = 1024 ** 2;
530
+ async function runHardwareProbe(command, args, signal) {
376
531
  try {
532
+ return await new Promise((resolve, reject) => {
533
+ execFile(command, args, {
534
+ encoding: "utf8",
535
+ timeout: 3e3,
536
+ maxBuffer: 65536,
537
+ signal
538
+ }, (error, stdout) => error ? reject(error) : resolve(stdout));
539
+ });
540
+ } catch {
541
+ signal?.throwIfAborted();
542
+ return;
543
+ }
544
+ }
545
+ async function readAvailableMemory(platform, signal) {
546
+ if (platform === "linux") {
547
+ const meminfo = await fs.readFile("/proc/meminfo", "utf8").catch(() => "");
548
+ const available = /^MemAvailable:\s+(\d+)\s+kB$/mu.exec(meminfo)?.[1];
549
+ if (available) return Number(available) * 1024;
550
+ }
551
+ if (platform === "darwin") {
552
+ const vmstat = await runHardwareProbe("/usr/bin/vm_stat", [], signal);
553
+ const pageSize = /page size of (\d+) bytes/u.exec(vmstat ?? "")?.[1];
554
+ const free = /^Pages free:\s+(\d+)\./mu.exec(vmstat ?? "")?.[1];
555
+ const inactive = /^Pages inactive:\s+(\d+)\./mu.exec(vmstat ?? "")?.[1];
556
+ if (pageSize && free && inactive) return (Number(free) + Number(inactive)) * Number(pageSize);
557
+ }
558
+ return os.freemem();
559
+ }
560
+ async function readAvailableDisk(cacheDir, platform, signal) {
561
+ let directory = path.resolve(cacheDir);
562
+ while (true) try {
563
+ const [capacity, stat] = await Promise.all([fs.statfs(directory), fs.stat(directory)]);
564
+ let capacityGroup = `device:${stat.dev}`;
565
+ if (platform === "linux" && ![
566
+ 61267,
567
+ 1481003842,
568
+ 4076150800
569
+ ].includes(capacity.type)) capacityGroup = void 0;
570
+ if (platform === "darwin") {
571
+ const disk = /^\/dev\/(disk\d+(?:s\d+)*)\s/mu.exec(await runHardwareProbe("/bin/df", ["-P", directory], signal) ?? "")?.[1];
572
+ const info = disk ? await runHardwareProbe("/usr/sbin/diskutil", [
573
+ "info",
574
+ "-plist",
575
+ disk
576
+ ], signal) : void 0;
577
+ const container = /<key>APFSContainerReference<\/key>\s*<string>(disk\d+)<\/string>/u.exec(info ?? "")?.[1];
578
+ const filesystem = /<key>FilesystemType<\/key>\s*<string>([^<]+)<\/string>/u.exec(info ?? "")?.[1];
579
+ capacityGroup = container ? `apfs:${container}` : filesystem && filesystem !== "apfs" ? capacityGroup : void 0;
580
+ }
377
581
  return {
378
- command: await pending,
379
- asset
582
+ availableBytes: capacity.bavail * capacity.bsize,
583
+ capacityGroup
584
+ };
585
+ } catch (error) {
586
+ signal?.throwIfAborted();
587
+ const code = error instanceof Error && "code" in error ? error.code : void 0;
588
+ const parent = path.dirname(directory);
589
+ if (code !== "ENOENT" && code !== "ENOTDIR" || parent === directory) return;
590
+ directory = parent;
591
+ }
592
+ }
593
+ async function readAccelerator(platform, arch, signal) {
594
+ if (platform === "darwin" && arch === "arm64") return { kind: "metal" };
595
+ if (platform !== "linux" && platform !== "win32") return {
596
+ kind: "cpu",
597
+ reason: "No managed GPU backend is available for this host."
598
+ };
599
+ const devices = ((await runHardwareProbe("nvidia-smi", ["--query-gpu=name,memory.total,memory.free,driver_version,compute_cap", "--format=csv,noheader,nounits"], signal))?.trim().split(/\r?\n/u) ?? []).slice(0, 32).flatMap((line) => {
600
+ const fields = line.split(",").map((field) => field.trim());
601
+ const [total, available, driverVersion, compute] = fields.slice(-4);
602
+ const name = fields.slice(0, -4).join(", ");
603
+ const totalMemoryBytes = Number(total) * MIB;
604
+ const availableMemoryBytes = Number(available) * MIB;
605
+ const computeCapability = Number(compute);
606
+ if (!name || !driverVersion || !/^\d+(?:\.\d+)+$/u.test(driverVersion) || !Number.isFinite(totalMemoryBytes) || !Number.isFinite(availableMemoryBytes) || totalMemoryBytes <= 0 || availableMemoryBytes < 0 || availableMemoryBytes > totalMemoryBytes) return [];
607
+ return [{
608
+ name,
609
+ totalMemoryBytes,
610
+ availableMemoryBytes,
611
+ driverVersion,
612
+ ...Number.isFinite(computeCapability) && computeCapability > 0 ? { computeCapability } : {}
613
+ }];
614
+ });
615
+ return devices.length > 0 ? {
616
+ kind: "cuda",
617
+ devices
618
+ } : {
619
+ kind: "cpu",
620
+ reason: "nvidia-smi did not report a usable NVIDIA GPU."
621
+ };
622
+ }
623
+ /** Read the Gateway host once during setup; never probe on inference requests. */
624
+ async function detectLlamaCppHardware(params) {
625
+ params.signal?.throwIfAborted();
626
+ const platform = os.platform();
627
+ const arch = os.arch();
628
+ const hostMemoryBytes = os.totalmem();
629
+ const constrainedMemory = process.constrainedMemory();
630
+ const constrained = constrainedMemory > 0 && constrainedMemory < hostMemoryBytes;
631
+ const totalMemoryBytes = constrained ? constrainedMemory : hostMemoryBytes;
632
+ const [availableMemory, modelDisk, runtimeDisk, accelerator] = await Promise.all([
633
+ readAvailableMemory(platform, params.signal),
634
+ readAvailableDisk(params.cacheDir, platform, params.signal),
635
+ readAvailableDisk(resolveLlamaCppDataDir(), platform, params.signal),
636
+ readAccelerator(platform, arch, params.signal)
637
+ ]);
638
+ params.signal?.throwIfAborted();
639
+ return {
640
+ platform,
641
+ arch,
642
+ totalMemoryBytes,
643
+ availableMemoryBytes: Math.min(totalMemoryBytes, availableMemory, constrained ? process.availableMemory() : totalMemoryBytes),
644
+ availableDiskBytes: modelDisk?.availableBytes,
645
+ availableRuntimeDiskBytes: runtimeDisk?.availableBytes,
646
+ sharedDisk: !modelDisk?.capacityGroup || !runtimeDisk?.capacityGroup || modelDisk.capacityGroup === runtimeDisk.capacityGroup,
647
+ accelerator
648
+ };
649
+ }
650
+ function formatLlamaCppMemory(bytes) {
651
+ return `${(bytes / GIB$1).toFixed(1).replace(/\.0$/u, "")} GiB`;
652
+ }
653
+ //#endregion
654
+ //#region extensions/llama-cpp/src/model-catalog.ts
655
+ const GIB = 1024 ** 3;
656
+ function modelRecipe(params) {
657
+ const source = params.source ?? `hf:${params.repository}/${params.file}#${params.revision}`;
658
+ return {
659
+ model: {
660
+ id: params.id,
661
+ name: params.name,
662
+ api: "openai-completions",
663
+ reasoning: params.reasoning ?? false,
664
+ input: ["text"],
665
+ cost: {
666
+ input: 0,
667
+ output: 0,
668
+ cacheRead: 0,
669
+ cacheWrite: 0
670
+ },
671
+ contextWindow: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
672
+ contextTokens: DEFAULT_LLAMA_CPP_CONTEXT_SIZE,
673
+ maxTokens: params.maxTokens ?? 2048,
674
+ params: {
675
+ modelPath: source,
676
+ contextSize: DEFAULT_LLAMA_CPP_CONTEXT_SIZE
677
+ },
678
+ compat: {
679
+ supportsTools: true,
680
+ supportsUsageInStreaming: true,
681
+ toolSchemaProfile: "llamacpp"
682
+ }
683
+ },
684
+ sizeBytes: params.sizeBytes,
685
+ memoryBytes: params.memoryGiB * GIB,
686
+ minimumSystemMemoryBytes: params.minimumSystemGiB * GIB,
687
+ requiresAcceleration: params.requiresAcceleration ?? false,
688
+ artifact: {
689
+ fileName: params.cacheFile ?? `hf_${params.repository.replaceAll("/", "_")}_${params.revision}_${params.file}`,
690
+ url: `https://huggingface.co/${params.repository}/resolve/${params.revision}/${params.file}?download=true`,
691
+ expectedSize: params.sizeBytes,
692
+ expectedSha256: params.sha256
693
+ }
694
+ };
695
+ }
696
+ const LLAMA_CPP_MODEL_RECIPES = [
697
+ modelRecipe({
698
+ id: "qwen3.8-27b-ud-q4_k_m",
699
+ name: "Qwen3.8 27B (UD-Q4_K_M)",
700
+ repository: "unsloth/Qwen3.8-27B-GGUF",
701
+ file: "Qwen3.8-27B-UD-Q4_K_M.gguf",
702
+ revision: "4ca720788d1e01f1bff70c033e0d0028fd02e502",
703
+ sha256: "322e194ff79741c7baa497c240f677f54b201b0efab44ca8e50f122b39123482",
704
+ sizeBytes: 16464440224,
705
+ memoryGiB: 22,
706
+ minimumSystemGiB: 32,
707
+ requiresAcceleration: true,
708
+ reasoning: true,
709
+ maxTokens: 16384
710
+ }),
711
+ modelRecipe({
712
+ id: "muse-glimmer-30b-q4_k_m",
713
+ name: "Muse Glimmer 30B (Q4_K_M)",
714
+ repository: "meta-models/Muse-Glimmer-30B-GGUF",
715
+ file: "Muse-Glimmer-30B-KQuant-17GB-Q4_K_M.gguf",
716
+ revision: "70bf1b61ac09f91b24d39038091b41c582bc5d7a",
717
+ sha256: "4cc57c0f51040a226e5a72cc47b7613f7772950e460a665f7083de89f183f60e",
718
+ sizeBytes: 16756683904,
719
+ memoryGiB: 20,
720
+ minimumSystemGiB: 32,
721
+ requiresAcceleration: true,
722
+ reasoning: true,
723
+ maxTokens: 16384
724
+ }),
725
+ modelRecipe({
726
+ id: "gemma-4-26b-a4b-it-ud-q4_k_m",
727
+ name: "Gemma 4 26B A4B (UD-Q4_K_M)",
728
+ repository: "unsloth/gemma-4-26B-A4B-it-GGUF",
729
+ file: "gemma-4-26B-A4B-it-UD-Q4_K_M.gguf",
730
+ revision: "c099eb48e663fd284577b04978a94ffccb261841",
731
+ sha256: "f2c28b3dc4776931ac6f879e11f203dec637ea0f14267a86ec8f6165f63f293f",
732
+ sizeBytes: 16947541728,
733
+ memoryGiB: 22,
734
+ minimumSystemGiB: 32,
735
+ requiresAcceleration: true
736
+ }),
737
+ modelRecipe({
738
+ id: "gemma-4-12b-it-q4_k_m",
739
+ name: "Gemma 4 12B (Q4_K_M)",
740
+ repository: "unsloth/gemma-4-12b-it-GGUF",
741
+ file: "gemma-4-12b-it-Q4_K_M.gguf",
742
+ revision: "fc034cfff751157913579611efad8462ac1be606",
743
+ sha256: "0a270ec9fe6b34f4a0d33992b6135117b484ebc4766ab76b51d4ae8c457e4c42",
744
+ sizeBytes: 7121861440,
745
+ memoryGiB: 12,
746
+ minimumSystemGiB: 24,
747
+ requiresAcceleration: true,
748
+ reasoning: true,
749
+ maxTokens: 16384
750
+ }),
751
+ modelRecipe({
752
+ id: "qwen3.5-9b-q4_k_m",
753
+ name: "Qwen3.5 9B (Q4_K_M)",
754
+ repository: "unsloth/Qwen3.5-9B-GGUF",
755
+ file: "Qwen3.5-9B-Q4_K_M.gguf",
756
+ revision: "3885219b6810b007914f3a7950a8d1b469d598a5",
757
+ sha256: "03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8",
758
+ sizeBytes: 5680522464,
759
+ memoryGiB: 10,
760
+ minimumSystemGiB: 16,
761
+ reasoning: true,
762
+ maxTokens: 16384
763
+ }),
764
+ modelRecipe({
765
+ id: DEFAULT_LLAMA_CPP_MODEL_ID,
766
+ name: "Gemma 4 E4B (Q4_K_M)",
767
+ repository: "unsloth/gemma-4-E4B-it-GGUF",
768
+ file: "gemma-4-E4B-it-Q4_K_M.gguf",
769
+ revision: DEFAULT_LLAMA_CPP_MODEL_REVISION,
770
+ sha256: DEFAULT_LLAMA_CPP_MODEL_SHA256,
771
+ sizeBytes: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
772
+ memoryGiB: 10,
773
+ minimumSystemGiB: 16,
774
+ source: DEFAULT_LLAMA_CPP_MODEL_URI,
775
+ cacheFile: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE
776
+ }),
777
+ modelRecipe({
778
+ id: "qwen3.5-4b-q4_k_m",
779
+ name: "Qwen3.5 4B (Q4_K_M)",
780
+ repository: "unsloth/Qwen3.5-4B-GGUF",
781
+ file: "Qwen3.5-4B-Q4_K_M.gguf",
782
+ revision: "e87f176479d0855a907a41277aca2f8ee7a09523",
783
+ sha256: "00fe7986ff5f6b463e62455821146049db6f9313603938a70800d1fb69ef11a4",
784
+ sizeBytes: 2740937888,
785
+ memoryGiB: 6,
786
+ minimumSystemGiB: 8,
787
+ reasoning: true,
788
+ maxTokens: 16384
789
+ }),
790
+ modelRecipe({
791
+ id: "gemma-4-e2b-it-q4_k_m",
792
+ name: "Gemma 4 E2B (Q4_K_M)",
793
+ repository: "unsloth/gemma-4-E2B-it-GGUF",
794
+ file: "gemma-4-E2B-it-Q4_K_M.gguf",
795
+ revision: "0314792d7f1f7e229411f620751375812bb9faf2",
796
+ sha256: "740185b21d22ceb83a11c3aa62ad5842ef32c70f6096d756bbee85a1e4ec34b8",
797
+ sizeBytes: 3106738272,
798
+ memoryGiB: 6,
799
+ minimumSystemGiB: 8
800
+ })
801
+ ];
802
+ function resolveLlamaCppCatalogArtifact(source) {
803
+ return LLAMA_CPP_MODEL_RECIPES.find((recipe) => recipe.model.params?.modelPath === source)?.artifact;
804
+ }
805
+ function resolveLlamaCppModelCandidates(hardware, backend) {
806
+ const systemBudget = Math.min(hardware.availableMemoryBytes, hardware.totalMemoryBytes - Math.max(2 * GIB, hardware.totalMemoryBytes * .25));
807
+ const gpuBudget = hardware.accelerator.kind === "cuda" ? Math.max(0, ...hardware.accelerator.devices.map((device) => Math.min(device.availableMemoryBytes, device.totalMemoryBytes - Math.max(GIB, device.totalMemoryBytes * .1)))) : 0;
808
+ const memoryBudgetBytes = backend === "cuda" ? Math.min(systemBudget, gpuBudget) : systemBudget;
809
+ return {
810
+ recipes: LLAMA_CPP_MODEL_RECIPES.filter((recipe) => (!recipe.requiresAcceleration || backend !== "cpu") && hardware.totalMemoryBytes >= recipe.minimumSystemMemoryBytes && memoryBudgetBytes >= recipe.memoryBytes),
811
+ memoryBudgetBytes
812
+ };
813
+ }
814
+ function recommendLlamaCppModel(hardware, backend, cached = {}) {
815
+ if (hardware.availableDiskBytes === void 0 || hardware.availableRuntimeDiskBytes === void 0) return {
816
+ kind: "unavailable",
817
+ reason: "Cannot measure free space in the model cache or runtime directory. Check their permissions and retry setup."
818
+ };
819
+ const { recipes: candidates, memoryBudgetBytes } = resolveLlamaCppModelCandidates(hardware, backend);
820
+ const runtimeDiskBytes = cached.runtime ? 0 : (backend === "cuda" ? 3 : 2) * GIB;
821
+ if (!hardware.sharedDisk && hardware.availableRuntimeDiskBytes < runtimeDiskBytes) return {
822
+ kind: "unavailable",
823
+ reason: "There is not enough free disk space in the runtime directory. Free space on that volume and retry setup."
824
+ };
825
+ const modelDiskBudget = hardware.sharedDisk ? Math.min(hardware.availableDiskBytes, hardware.availableRuntimeDiskBytes) - runtimeDiskBytes : hardware.availableDiskBytes;
826
+ for (const recipe of candidates) {
827
+ const modelDiskBytes = (cached.modelIds?.has(recipe.model.id) ? 0 : recipe.sizeBytes) + (cached.embedding ? 0 : DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES);
828
+ if (modelDiskBudget < modelDiskBytes) continue;
829
+ const placement = backend === "metal" ? "Metal unified memory" : backend === "cuda" ? "NVIDIA GPU memory" : "CPU memory";
830
+ return {
831
+ kind: "recommended",
832
+ recipe,
833
+ memoryBudgetBytes,
834
+ requiredDiskBytes: modelDiskBytes + runtimeDiskBytes,
835
+ reason: `${recipe.model.name} fits the ${formatLlamaCppMemory(memoryBudgetBytes)} ${placement} budget with a 64K context. Runtime verification checks the actual model before activation.`
380
836
  };
381
- } finally {
382
- if (installationPromises.get(key) === pending) installationPromises.delete(key);
383
837
  }
838
+ return {
839
+ kind: "unavailable",
840
+ reason: candidates.length > 0 ? "There is not enough free disk space for a recommended model, embeddings, and the runtime. Free space in the model cache and retry setup." : `No recommended model fits the current ${formatLlamaCppMemory(Math.max(0, memoryBudgetBytes))} memory budget. Close other applications and retry, or configure an existing GGUF or external server.`
841
+ };
384
842
  }
385
843
  //#endregion
386
844
  //#region extensions/llama-cpp/src/managed-server.ts
@@ -418,7 +876,7 @@ async function resolveHuggingFaceArtifact(source, signal) {
418
876
  });
419
877
  try {
420
878
  if (!response.ok) throw new Error(`Cannot resolve ${source}: HTTP ${response.status}`);
421
- const ggufFile = asOptionalRecord(asOptionalRecord(await response.json())?.ggufFile);
879
+ const ggufFile = asOptionalRecord(asOptionalRecord(await readProviderJsonResponse(response, "llama.cpp Hugging Face manifest"))?.ggufFile);
422
880
  file = typeof ggufFile?.rfilename === "string" ? ggufFile.rfilename : void 0;
423
881
  expectedSize = typeof ggufFile?.size === "number" ? ggufFile.size : void 0;
424
882
  if (!file) throw new Error(`Hugging Face did not return a GGUF file for ${source}`);
@@ -428,22 +886,33 @@ async function resolveHuggingFaceArtifact(source, signal) {
428
886
  }
429
887
  const encodedFile = file.split("/").map(encodeURIComponent).join("/");
430
888
  const url = `https://huggingface.co/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/resolve/${encodeURIComponent(parsed.revision)}/${encodedFile}?download=true`;
431
- const treeUrl = `https://huggingface.co/api/models/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/tree/${encodeURIComponent(parsed.revision)}?recursive=true&expand=true`;
432
- const { response: treeResponse, release: releaseTree } = await fetchWithSsrFGuard({
433
- url: treeUrl,
889
+ const fileInfoUrl = `https://huggingface.co/api/models/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/paths-info/${encodeURIComponent(parsed.revision)}`;
890
+ const { response: fileInfoResponse, release: releaseFileInfo } = await fetchWithSsrFGuard({
891
+ url: fileInfoUrl,
892
+ init: {
893
+ method: "POST",
894
+ headers: {
895
+ "content-type": "application/json",
896
+ "user-agent": "llama-cpp"
897
+ },
898
+ body: JSON.stringify({
899
+ paths: [file],
900
+ expand: false
901
+ })
902
+ },
434
903
  signal,
435
904
  requireHttps: true,
436
- policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(treeUrl),
905
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(fileInfoUrl),
437
906
  auditContext: "llama-cpp-model-resolve"
438
907
  });
439
- let tree;
908
+ let fileInfo;
440
909
  try {
441
- if (!treeResponse.ok) throw new Error(`Cannot read Hugging Face integrity metadata for ${source}: HTTP ${treeResponse.status}`);
442
- tree = await treeResponse.json();
910
+ if (!fileInfoResponse.ok) throw new Error(`Cannot read Hugging Face integrity metadata for ${source}: HTTP ${fileInfoResponse.status}`);
911
+ fileInfo = await readProviderJsonResponse(fileInfoResponse, "llama.cpp Hugging Face file metadata");
443
912
  } finally {
444
- await releaseTree();
913
+ await releaseFileInfo();
445
914
  }
446
- const fileRow = Array.isArray(tree) ? tree.map((entry) => asOptionalRecord(entry)).find((entry) => entry?.path === file) : void 0;
915
+ const fileRow = Array.isArray(fileInfo) ? fileInfo.map((entry) => asOptionalRecord(entry)).find((entry) => entry?.path === file) : void 0;
447
916
  const lfs = asOptionalRecord(fileRow?.lfs);
448
917
  const expectedSha256 = typeof lfs?.oid === "string" && /^[a-f\d]{64}$/iu.test(lfs.oid) ? lfs.oid.toLowerCase() : void 0;
449
918
  expectedSize = expectedSize ?? (typeof fileRow?.size === "number" ? fileRow.size : void 0);
@@ -461,12 +930,8 @@ async function resolveHuggingFaceArtifact(source, signal) {
461
930
  };
462
931
  }
463
932
  function defaultArtifact(source) {
464
- if (source === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") return {
465
- fileName: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE,
466
- url: `https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF/resolve/${DEFAULT_LLAMA_CPP_MODEL_REVISION}/gemma-4-E4B-it-Q4_K_M.gguf?download=true`,
467
- expectedSize: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
468
- expectedSha256: DEFAULT_LLAMA_CPP_MODEL_SHA256
469
- };
933
+ const recipe = resolveLlamaCppCatalogArtifact(source);
934
+ if (recipe) return recipe;
470
935
  if (source === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") return {
471
936
  fileName: DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE,
472
937
  url: `https://huggingface.co/ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/resolve/${DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION}/embeddinggemma-300m-qat-Q8_0.gguf?download=true`,
@@ -475,7 +940,7 @@ function defaultArtifact(source) {
475
940
  };
476
941
  }
477
942
  async function assertGguf(filePath) {
478
- const handle = await fs$1.open(filePath, "r").catch((error) => {
943
+ const handle = await fs.open(filePath, "r").catch((error) => {
479
944
  if ((error instanceof Error && "code" in error ? error.code : void 0) === "ENOENT") throw new Error(`Model file is missing: ${filePath}. Run interactive llama.cpp setup or correct params.modelPath.`, { cause: error });
480
945
  throw error;
481
946
  });
@@ -514,9 +979,9 @@ async function ensureLlamaCppModel(params) {
514
979
  const pending = modelPromises.get(destination);
515
980
  if (pending) return await pending;
516
981
  const load = (async () => {
517
- if (await fs$1.stat(destination).then((stat) => stat.isFile()).catch(() => false)) {
982
+ if (await fs.stat(destination).then((stat) => stat.isFile()).catch(() => false)) {
518
983
  if (artifact.expectedSha256) {
519
- if (await sha256File(destination) === artifact.expectedSha256) return destination;
984
+ if (await sha256File(destination, params.signal) === artifact.expectedSha256) return destination;
520
985
  } else {
521
986
  await assertGguf(destination);
522
987
  return destination;
@@ -588,14 +1053,14 @@ function renderLlamaServerPreset(params) {
588
1053
  ].join("\n");
589
1054
  }
590
1055
  async function writePreset(presetPath, contents) {
591
- await fs$1.mkdir(path.dirname(presetPath), { recursive: true });
1056
+ await fs.mkdir(path.dirname(presetPath), { recursive: true });
592
1057
  const temporary = `${presetPath}.tmp-${randomUUID()}`;
593
- await fs$1.writeFile(temporary, contents, { mode: 384 });
594
- await fs$1.rename(temporary, presetPath);
1058
+ await fs.writeFile(temporary, contents, { mode: 384 });
1059
+ await fs.rename(temporary, presetPath);
595
1060
  }
596
1061
  async function updatePreset(presetPath, params) {
597
1062
  const pending = (presetWritePromises.get(presetPath) ?? Promise.resolve()).catch(() => void 0).then(async () => {
598
- const existing = await fs$1.readFile(presetPath, "utf8").catch((error) => {
1063
+ const existing = await fs.readFile(presetPath, "utf8").catch((error) => {
599
1064
  if (asOptionalRecord(error)?.code === "ENOENT") return;
600
1065
  throw error;
601
1066
  });
@@ -639,21 +1104,36 @@ async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT)
639
1104
  return await tryPort(preferred) ?? await tryPort(0) ?? Promise.reject(/* @__PURE__ */ new Error("No loopback port is available for llama-server"));
640
1105
  }
641
1106
  async function prepareManagedLlamaServer(params) {
642
- const { command, asset } = await ensureLlamaServerInstalled();
643
- const { presetPath } = resolveManagedLlamaServerPaths(asset);
1107
+ params.signal?.throwIfAborted();
1108
+ const command = params.localService?.command ?? (await ensureLlamaServerInstalled({
1109
+ asset: params.asset,
1110
+ signal: params.signal,
1111
+ onProgress: params.onProgress
1112
+ })).command;
1113
+ const port = params.port ?? await findAvailableLlamaServerPort(params.isolated ? 0 : void 0);
1114
+ const rootUrl = `http://127.0.0.1:${port}`;
1115
+ const endpoint = {
1116
+ command,
1117
+ baseUrl: `${rootUrl}/v1`,
1118
+ healthUrl: params.localService?.healthUrl ?? `${rootUrl}/health`
1119
+ };
1120
+ const configuredPreset = params.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset") ?? params.localService?.env?.LLAMA_ARG_MODELS_PRESET;
1121
+ if (params.localService && !configuredPreset && !params.isolated) return {
1122
+ ...endpoint,
1123
+ args: params.localService.args ?? []
1124
+ };
1125
+ const defaultPreset = configuredPreset ? path.resolve(params.localService?.cwd ?? process.cwd(), configuredPreset) : resolveManagedLlamaServerPaths(params.asset).presetPath;
1126
+ const presetPath = params.isolated ? path.join(path.dirname(defaultPreset), `models-${randomUUID()}.ini`) : defaultPreset;
644
1127
  await updatePreset(presetPath, {
645
1128
  chatModel: params.chatModel,
646
1129
  embeddingModelIsDefault: params.embeddingModelIsDefault,
647
1130
  embeddingModelPath: params.embeddingModelPath,
648
1131
  defaultEmbeddingModelPath: params.defaultEmbeddingModelPath
649
1132
  });
650
- const port = params.port ?? await findAvailableLlamaServerPort();
651
- const rootUrl = `http://127.0.0.1:${port}`;
1133
+ params.signal?.throwIfAborted();
652
1134
  return {
653
- command,
654
- baseUrl: `${rootUrl}/v1`,
655
- healthUrl: `${rootUrl}/health`,
656
- args: [
1135
+ ...endpoint,
1136
+ args: params.localService && !params.isolated ? params.localService.args ?? [] : [
657
1137
  "--host",
658
1138
  "127.0.0.1",
659
1139
  "--port",
@@ -672,6 +1152,7 @@ async function ensureManagedLlamaServerForChat(params) {
672
1152
  const cacheDir = resolveLlamaCppModelCacheDir(params.provider);
673
1153
  const key = JSON.stringify([
674
1154
  params.provider.baseUrl,
1155
+ params.provider.localService,
675
1156
  params.model.id,
676
1157
  params.model.params,
677
1158
  cacheDir
@@ -683,7 +1164,7 @@ async function ensureManagedLlamaServerForChat(params) {
683
1164
  });
684
1165
  if (!chatModelPath && resolveLlamaCppModelSource(params.model) === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") {
685
1166
  const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), "hf_unsloth_gemma-4-E4B-it-GGUF_gemma-4-E4B-it-Q4_K_M.gguf");
686
- if (await fs$1.stat(legacy).then((stat) => stat.isFile()).catch(() => false)) chatModelPath = legacy;
1167
+ if (await fs.stat(legacy).then((stat) => stat.isFile()).catch(() => false)) chatModelPath = legacy;
687
1168
  }
688
1169
  chatModelPath = await ensureLlamaCppModel({
689
1170
  source: chatModelPath ?? resolveLlamaCppModelSource(params.model),
@@ -701,7 +1182,8 @@ async function ensureManagedLlamaServerForChat(params) {
701
1182
  maxTokens: params.model.maxTokens
702
1183
  },
703
1184
  defaultEmbeddingModelPath: path.join(cacheDir, "hf_ggml-org_embeddinggemma-300m-qat-Q8_0.gguf"),
704
- port: Number.isInteger(port) && port > 0 ? port : void 0
1185
+ port: Number.isInteger(port) && port > 0 ? port : void 0,
1186
+ localService: params.provider.localService
705
1187
  });
706
1188
  })();
707
1189
  chatPreparationPromises.set(key, pending);
@@ -831,6 +1313,7 @@ async function prepareEmbeddingServer(options, embeddingSource, embeddingModelIs
831
1313
  const cacheDir = resolveLlamaCppModelCacheDir(provider);
832
1314
  const key = JSON.stringify([
833
1315
  provider.baseUrl,
1316
+ provider.localService,
834
1317
  embeddingSource,
835
1318
  cacheDir
836
1319
  ]);
@@ -843,7 +1326,8 @@ async function prepareEmbeddingServer(options, embeddingSource, embeddingModelIs
843
1326
  cacheDir,
844
1327
  download: true
845
1328
  }),
846
- port: resolveProviderPort(provider)
1329
+ port: resolveProviderPort(provider),
1330
+ localService: provider.localService
847
1331
  });
848
1332
  })();
849
1333
  preparedEmbeddingServers.set(key, pending);
@@ -860,7 +1344,6 @@ function wrapProvider(params) {
860
1344
  runtimeFacts = await inspectLlamaServerRuntime({
861
1345
  baseUrl: params.baseUrl,
862
1346
  modelId: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
863
- backend: selectLlamaServerAsset().backend,
864
1347
  loadError
865
1348
  });
866
1349
  };
@@ -1597,9 +2080,6 @@ function formatDownloadProgress(label, params) {
1597
2080
  const totalSize = Math.max(1, params.totalSize);
1598
2081
  return `Downloading ${label}… ${Math.min(100, Math.floor(downloadedSize / totalSize * 100))}% (${(downloadedSize / BYTES_PER_GB).toFixed(1)}/${(totalSize / BYTES_PER_GB).toFixed(1)} GB, ${Math.max(0, Math.round(params.bytesPerSecond / BYTES_PER_MB))} MB/s)`;
1599
2082
  }
1600
- function formatRamGb(totalmemBytes) {
1601
- return (totalmemBytes / 1024 ** 3).toFixed(1).replace(/\.0$/u, "");
1602
- }
1603
2083
  function describeEmbeddingDownload(isDefault) {
1604
2084
  return isDefault ? "the local embedding model (about 0.3 GB)" : "your configured local embedding model";
1605
2085
  }
@@ -1622,9 +2102,19 @@ function configuredCandidates(config, scope) {
1622
2102
  })).toSorted((a, b) => Number(b.model.id === primaryId) - Number(a.model.id === primaryId));
1623
2103
  }
1624
2104
  async function isFile(filePath) {
1625
- return await fs$1.stat(filePath).then((stat) => stat.isFile()).catch(() => false);
2105
+ return await fs.stat(filePath).then((stat) => stat.isFile()).catch(() => false);
2106
+ }
2107
+ async function resolveCachedArtifact(source, cacheDir, signal) {
2108
+ return await ensureLlamaCppModel({
2109
+ source,
2110
+ cacheDir,
2111
+ download: false,
2112
+ signal
2113
+ }).catch(() => {
2114
+ signal?.throwIfAborted();
2115
+ });
1626
2116
  }
1627
- async function resolveCachedCandidate(candidate) {
2117
+ async function resolveCachedCandidate(candidate, signal) {
1628
2118
  const source = resolveLlamaCppModelSource(candidate.model);
1629
2119
  const resolved = resolveCachedLlamaCppModelPath(candidate);
1630
2120
  if (resolved && await isFile(resolved)) return resolved;
@@ -1632,21 +2122,7 @@ async function resolveCachedCandidate(candidate) {
1632
2122
  const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
1633
2123
  if (await isFile(legacy)) return legacy;
1634
2124
  }
1635
- if (/^(?:hf|huggingface|https):/iu.test(source)) return await ensureLlamaCppModel({
1636
- source,
1637
- cacheDir: resolveLlamaCppModelCacheDir(candidate.provider),
1638
- download: false
1639
- }).catch(() => void 0);
1640
- }
1641
- function readConfiguredPort(provider) {
1642
- try {
1643
- const url = new URL(provider?.baseUrl ?? "");
1644
- if (url.hostname !== "127.0.0.1" && url.hostname !== "localhost" && url.hostname !== "[::1]") return;
1645
- const port = Number(url.port);
1646
- return Number.isInteger(port) && port > 0 ? port : void 0;
1647
- } catch {
1648
- return;
1649
- }
2125
+ if (/^(?:hf|huggingface|https):/iu.test(source)) return await resolveCachedArtifact(source, resolveLlamaCppModelCacheDir(candidate.provider), signal);
1650
2126
  }
1651
2127
  function buildSetupResult(params) {
1652
2128
  const existing = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
@@ -1661,7 +2137,7 @@ function buildSetupResult(params) {
1661
2137
  providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig({
1662
2138
  existing: switchingFromExternal ? void 0 : existing,
1663
2139
  managed: params.managed,
1664
- ...params.plan === "embedding-only" ? { modelInventory: [] } : {}
2140
+ modelInventory: params.plan === "embedding-only" ? [] : params.model ? [params.model, ...existing?.localService ? existing.models.filter((model) => model.id !== params.model?.id) : []] : existing?.models
1665
2141
  }) }
1666
2142
  }
1667
2143
  }
@@ -1672,7 +2148,7 @@ async function detectLlamaCppSetup(ctx) {
1672
2148
  const command = existing?.localService?.command;
1673
2149
  const presetPath = existing?.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset");
1674
2150
  if (!command || !path.isAbsolute(command) || !await isFile(command) || !presetPath || !await isFile(presetPath)) return null;
1675
- for (const candidate of configuredCandidates(ctx.config, "detection")) if (await resolveCachedCandidate(candidate)) return {
2151
+ for (const candidate of configuredCandidates(ctx.config, "detection")) if (await resolveCachedCandidate(candidate, ctx.signal)) return {
1676
2152
  modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
1677
2153
  detail: "Managed llama.cpp server ready"
1678
2154
  };
@@ -1713,26 +2189,62 @@ function resolveEmbeddingSetup(config, cacheDir) {
1713
2189
  conflict: models.some((candidate) => candidate.source !== model.source)
1714
2190
  };
1715
2191
  }
1716
- async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localMemoryIntent) {
2192
+ async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localMemoryIntent, hardware, asset, runtimeNote) {
1717
2193
  let candidate = candidates[0];
1718
- const cachedPath = candidate ? await resolveCachedCandidate(candidate) : void 0;
1719
- if (candidate && cachedPath) return {
1720
- kind: "chat",
1721
- candidate,
1722
- cachedPath
1723
- };
1724
- candidate = candidates.find((entry) => entry.model.id === DEFAULT_LLAMA_CPP_MODEL_ID);
1725
- const totalmemBytes = os.totalmem();
1726
- if (candidate && meetsLlamaCppDefaultModelRamFloor(totalmemBytes)) {
2194
+ const configuredPath = candidate ? await resolveCachedCandidate(candidate, ctx.signal) : void 0;
2195
+ if (candidate && configuredPath) {
2196
+ if (runtimeNote && !await ctx.prompter.confirm({
2197
+ message: `${runtimeNote} Use cached ${candidate.model.name} on Gateway host ${os.hostname()} with the verified CPU runtime?`,
2198
+ initialValue: false
2199
+ })) return;
2200
+ return {
2201
+ kind: "chat",
2202
+ candidate,
2203
+ cachedPath: configuredPath
2204
+ };
2205
+ }
2206
+ const provider = candidate?.provider ?? buildLlamaCppProviderConfig();
2207
+ const cacheDir = resolveLlamaCppModelCacheDir(provider);
2208
+ const cachedModels = /* @__PURE__ */ new Map();
2209
+ for (const recipe of resolveLlamaCppModelCandidates(hardware, asset.backend).recipes) {
2210
+ const cached = await resolveCachedArtifact(resolveLlamaCppModelSource(recipe.model), cacheDir, ctx.signal);
2211
+ if (cached) {
2212
+ cachedModels.set(recipe.model.id, cached);
2213
+ break;
2214
+ }
2215
+ }
2216
+ const cachedEmbedding = embeddingModelIsDefault && Boolean(await resolveCachedArtifact("hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf", cacheDir, ctx.signal));
2217
+ const recommendation = recommendLlamaCppModel(hardware, asset.backend, {
2218
+ modelIds: new Set(cachedModels.keys()),
2219
+ embedding: cachedEmbedding,
2220
+ runtime: await isFile(resolveManagedLlamaServerPaths(asset).command)
2221
+ });
2222
+ if (recommendation.kind === "recommended") {
2223
+ const { recipe } = recommendation;
2224
+ const cachedPath = cachedModels.get(recipe.model.id);
2225
+ candidate = {
2226
+ model: recipe.model,
2227
+ provider
2228
+ };
2229
+ const recommendationSummary = [
2230
+ `Runs on Gateway host ${os.hostname()} (${hardware.platform}/${hardware.arch}), using ${asset.backend === "metal" ? "Apple Metal" : asset.backend === "cuda" ? "NVIDIA CUDA" : "the CPU"}.`,
2231
+ `${formatLlamaCppMemory(hardware.totalMemoryBytes)} RAM; ${formatLlamaCppMemory(hardware.availableDiskBytes ?? 0)} free disk.`,
2232
+ !hardware.sharedDisk ? `${formatLlamaCppMemory(hardware.availableRuntimeDiskBytes ?? 0)} free on the runtime volume.` : void 0,
2233
+ runtimeNote,
2234
+ recommendation.reason,
2235
+ !embeddingModelIsDefault ? "This estimate includes the default embedding model; your configured embedding model may need more memory and disk space." : void 0,
2236
+ "OpenClaw will check a real tool call before making this your default model."
2237
+ ].filter(Boolean).join("\n");
1727
2238
  if (await ctx.prompter.confirm({
1728
- message: `OpenClaw will install a verified llama.cpp server and download Gemma 4 E4B IT Q4_K_M (about 5.0 GB) plus ${describeEmbeddingDownload(embeddingModelIsDefault)}. Continue?`,
2239
+ message: `${recommendationSummary}\n\n${cachedPath ? `Use cached ${recipe.model.name}, download any missing embedding and ${asset.backend.toUpperCase()} runtime files, then use this model?` : `Download ${recipe.model.name} (${(recipe.sizeBytes / BYTES_PER_GB).toFixed(1)} GB), ${describeEmbeddingDownload(embeddingModelIsDefault)}, and the verified ${asset.backend.toUpperCase()} runtime, then use this model?`}`,
1729
2240
  initialValue: false
1730
2241
  })) return {
1731
2242
  kind: "chat",
1732
- candidate
2243
+ candidate,
2244
+ cachedPath
1733
2245
  };
1734
2246
  } else if (!localMemoryIntent) {
1735
- 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");
2247
+ await ctx.prompter.note(recommendation.reason, "Setup skipped");
1736
2248
  return;
1737
2249
  }
1738
2250
  const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
@@ -1742,7 +2254,7 @@ async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localM
1742
2254
  }
1743
2255
  if (localMemoryIntent) {
1744
2256
  if (await ctx.prompter.confirm({
1745
- message: `OpenClaw can install a verified llama.cpp server and download only ${describeEmbeddingDownload(embeddingModelIsDefault)}. This will not install or change your chat model. Continue?`,
2257
+ message: `${runtimeNote ? `${runtimeNote} ` : ""}Install a verified ${asset.backend.toUpperCase()} llama.cpp server on Gateway host ${os.hostname()} and download only ${describeEmbeddingDownload(embeddingModelIsDefault)}? Your chat model will stay unchanged.`,
1746
2258
  initialValue: false
1747
2259
  })) return { kind: "embedding-only" };
1748
2260
  }
@@ -1758,7 +2270,20 @@ async function runLlamaCppSetup(ctx) {
1758
2270
  return { profiles: [] };
1759
2271
  }
1760
2272
  const embeddingModel = embeddingSetup.model;
1761
- const plan = await resolveSetupPlan(ctx, configuredCandidates(ctx.config, "setup"), embeddingModel.isDefault, embeddingSetup.localMemoryIntent);
2273
+ const hardware = await detectLlamaCppHardware({
2274
+ cacheDir,
2275
+ signal: ctx.signal
2276
+ });
2277
+ let asset;
2278
+ let runtimeNote;
2279
+ try {
2280
+ asset = selectLlamaServerAsset(hardware.platform, hardware.arch, hardware.accelerator);
2281
+ } catch (error) {
2282
+ if (hardware.accelerator.kind !== "cuda") throw error;
2283
+ asset = selectLlamaServerAsset(hardware.platform, hardware.arch, { kind: "cpu" });
2284
+ runtimeNote = `${error instanceof Error ? error.message : String(error)} This recommendation uses CPU execution.`;
2285
+ }
2286
+ const plan = await resolveSetupPlan(ctx, configuredCandidates(ctx.config, "setup"), embeddingModel.isDefault, embeddingSetup.localMemoryIntent, hardware, asset, runtimeNote);
1762
2287
  if (!plan) return { profiles: [] };
1763
2288
  const progress = ctx.prompter.progress("Preparing managed llama.cpp server…");
1764
2289
  try {
@@ -1769,7 +2294,7 @@ async function runLlamaCppSetup(ctx) {
1769
2294
  cacheDir,
1770
2295
  download: true,
1771
2296
  signal: ctx.signal,
1772
- onProgress: (status) => progress.update(formatDownloadProgress("Gemma 4 E4B", status))
2297
+ onProgress: (status) => progress.update(formatDownloadProgress(plan.candidate.model.name, status))
1773
2298
  });
1774
2299
  const configuredContext = plan.candidate.model.params?.contextSize;
1775
2300
  chatModel = {
@@ -1792,19 +2317,21 @@ async function runLlamaCppSetup(ctx) {
1792
2317
  chatModel,
1793
2318
  embeddingModelIsDefault: embeddingModel.isDefault,
1794
2319
  embeddingModelPath,
1795
- port: readConfiguredPort(managedExisting)
2320
+ asset,
2321
+ isolated: true,
2322
+ signal: ctx.signal,
2323
+ onProgress: (status) => progress.update(formatDownloadProgress("llama.cpp runtime", status))
1796
2324
  });
1797
- if (!await removeProviderAuthProfilesWithLock({
1798
- provider: "llama-cpp",
1799
- profileIds: [LLAMA_CPP_DEFAULT_PROFILE_ID],
1800
- agentDir: ctx.agentDir
1801
- })) throw new Error("Failed to remove the previous llama.cpp endpoint auth profile");
2325
+ ctx.signal?.throwIfAborted();
1802
2326
  progress.stop("Managed llama.cpp server prepared");
1803
2327
  return buildSetupResult({
1804
2328
  config: ctx.config,
1805
2329
  managed,
1806
2330
  plan: plan.kind,
1807
- ...plan.kind === "chat" ? { defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${plan.candidate.model.id}` } : {}
2331
+ ...plan.kind === "chat" ? {
2332
+ defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${plan.candidate.model.id}`,
2333
+ model: plan.candidate.model
2334
+ } : {}
1808
2335
  });
1809
2336
  } catch (error) {
1810
2337
  progress.stop("llama.cpp setup failed");
@@ -1823,12 +2350,12 @@ function registerLlamaCppProvider(api) {
1823
2350
  auth: [{
1824
2351
  id: "local",
1825
2352
  label: LLAMA_CPP_PROVIDER_LABEL,
1826
- hint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
2353
+ hint: "Choose a Qwen, Gemma, or Muse model for this Gateway’s hardware and install llama.cpp",
1827
2354
  kind: "custom",
1828
2355
  wizard: {
1829
2356
  choiceId: LLAMA_CPP_PROVIDER_ID,
1830
2357
  choiceLabel: "Managed local server",
1831
- choiceHint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
2358
+ choiceHint: "Choose a Qwen, Gemma, or Muse model for this Gateway’s hardware and install llama.cpp",
1832
2359
  groupId: LLAMA_CPP_PROVIDER_ID,
1833
2360
  groupLabel: "Local llama.cpp",
1834
2361
  groupHint: "Managed or external llama.cpp server",
@@ -1885,10 +2412,10 @@ function registerLlamaCppProvider(api) {
1885
2412
  prepareDynamicModel: async (ctx) => ctx.config?.models?.providers?.["llama-cpp"]?.localService ? void 0 : await prepareLlamaServerDynamicModel(ctx),
1886
2413
  wrapStreamFn: (ctx) => {
1887
2414
  const providerConfig = ctx.config?.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1888
- if (!providerConfig?.localService) return wrapLlamaServerStream(ctx);
1889
- const inner = ctx.streamFn;
2415
+ const inner = wrapLlamaServerStream(ctx);
2416
+ if (!providerConfig?.localService) return inner;
1890
2417
  const selectedModel = ctx.model;
1891
- if (!inner || !selectedModel) return;
2418
+ if (!selectedModel) return;
1892
2419
  return async (model, context, options) => {
1893
2420
  await ensureManagedLlamaServerForChat({
1894
2421
  provider: providerConfig,
@@ -25,10 +25,6 @@ const DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID = "embeddinggemma-300m-qat-q8_0";
25
25
  const DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE = "hf_ggml-org_embeddinggemma-300m-qat-Q8_0.gguf";
26
26
  const DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES = 328577056;
27
27
  const DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256 = "6fa0c02a9c302be6f977521d399b4de3a46310a4f2621ee0063747881b673f67";
28
- const LLAMA_CPP_DEFAULT_MODEL_RAM_FLOOR_BYTES = 16 * 1024 ** 3;
29
- function meetsLlamaCppDefaultModelRamFloor(totalmemBytes = os.totalmem()) {
30
- return totalmemBytes >= LLAMA_CPP_DEFAULT_MODEL_RAM_FLOOR_BYTES;
31
- }
32
28
  function resolveLlamaCppDataDir() {
33
29
  return path.join(resolveStateDir(), "tools", "llama.cpp");
34
30
  }
@@ -123,4 +119,4 @@ function resolveManagedLlamaCppProviderConfig(config) {
123
119
  return provider;
124
120
  }
125
121
  //#endregion
126
- export { resolveLegacyLlamaCppModelCacheDir as C, resolveLlamaCppModelSource as D, resolveLlamaCppModelCacheDir as E, resolveLlamaCppSyntheticApiKey as O, resolveHomePath as S, resolveLlamaCppEmbeddingModel as T, LLAMA_CPP_PROVIDER_ID as _, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL as a, meetsLlamaCppDefaultModelRamFloor as b, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256 as c, DEFAULT_LLAMA_CPP_MODEL_ID as d, DEFAULT_LLAMA_CPP_MODEL_REVISION as f, LLAMA_CPP_DEFAULT_PORT as g, DEFAULT_LLAMA_CPP_MODEL_URI as h, DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE as i, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES as l, DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES as m, resolveManagedLlamaCppProviderConfig as n, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID as o, DEFAULT_LLAMA_CPP_MODEL_SHA256 as p, DEFAULT_LLAMA_CPP_CONTEXT_SIZE as r, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION as s, MANAGED_LLAMA_CPP_CONFIG_REQUIRED_MESSAGE as t, DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE as u, LLAMA_CPP_PROVIDER_LABEL as v, resolveLlamaCppDataDir as w, resolveCachedLlamaCppModelPath as x, buildLlamaCppProviderConfig as y };
122
+ export { resolveLlamaCppDataDir as C, resolveLlamaCppSyntheticApiKey as D, resolveLlamaCppModelSource as E, resolveLegacyLlamaCppModelCacheDir as S, resolveLlamaCppModelCacheDir as T, LLAMA_CPP_PROVIDER_ID as _, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL as a, resolveCachedLlamaCppModelPath as b, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256 as c, DEFAULT_LLAMA_CPP_MODEL_ID as d, DEFAULT_LLAMA_CPP_MODEL_REVISION as f, LLAMA_CPP_DEFAULT_PORT as g, DEFAULT_LLAMA_CPP_MODEL_URI as h, DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE as i, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES as l, DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES as m, resolveManagedLlamaCppProviderConfig as n, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID as o, DEFAULT_LLAMA_CPP_MODEL_SHA256 as p, DEFAULT_LLAMA_CPP_CONTEXT_SIZE as r, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION as s, MANAGED_LLAMA_CPP_CONFIG_REQUIRED_MESSAGE as t, DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE as u, LLAMA_CPP_PROVIDER_LABEL as v, resolveLlamaCppEmbeddingModel as w, resolveHomePath as x, buildLlamaCppProviderConfig as y };
@@ -1,4 +1,4 @@
1
- import { n as resolveManagedLlamaCppProviderConfig, t as MANAGED_LLAMA_CPP_CONFIG_REQUIRED_MESSAGE } from "./managed-provider-config-Ovg5QQxD.js";
1
+ import { n as resolveManagedLlamaCppProviderConfig, t as MANAGED_LLAMA_CPP_CONFIG_REQUIRED_MESSAGE } from "./managed-provider-config-D9X1wNEo.js";
2
2
  //#region extensions/llama-cpp/provider-policy-api.ts
3
3
  function inspectEmbeddingProviderSetup(params) {
4
4
  if (params.provider !== "local") return null;
@@ -48,7 +48,7 @@
48
48
  "appGuidedDiscovery": true,
49
49
  "appGuidedActionLabel": "Set up model",
50
50
  "choiceLabel": "Managed local server",
51
- "choiceHint": "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
51
+ "choiceHint": "Choose a Qwen, Gemma, or Muse model for this Gateway's hardware and install llama.cpp",
52
52
  "groupId": "llama-cpp",
53
53
  "groupLabel": "Local llama.cpp",
54
54
  "groupHint": "Managed or external llama.cpp server"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/llama-cpp-provider",
3
- "version": "2026.9.1",
3
+ "version": "2026.9.2",
4
4
  "description": "OpenClaw provider for managed and external llama.cpp servers",
5
5
  "repository": {
6
6
  "type": "git",
@@ -20,10 +20,10 @@
20
20
  "minHostVersion": ">=2026.6.2"
21
21
  },
22
22
  "compat": {
23
- "pluginApi": ">=2026.9.1"
23
+ "pluginApi": ">=2026.9.2"
24
24
  },
25
25
  "build": {
26
- "openclawVersion": "2026.9.1"
26
+ "openclawVersion": "2026.9.2"
27
27
  },
28
28
  "release": {
29
29
  "bundleRuntimeDependencies": false,
@@ -40,7 +40,7 @@
40
40
  "README.md"
41
41
  ],
42
42
  "peerDependencies": {
43
- "openclaw": ">=2026.9.1"
43
+ "openclaw": ">=2026.9.2"
44
44
  },
45
45
  "peerDependenciesMeta": {
46
46
  "openclaw": {