@openclaw/llama-cpp-provider 2026.10.2 → 2026.10.5-beta.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.
Files changed (2) hide show
  1. package/dist/index.js +191 -91
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -14,14 +14,15 @@ import { fetchConfiguredLocalOriginWithSsrFGuard } from "openclaw/plugin-sdk/ssr
14
14
  import { execFile } from "node:child_process";
15
15
  import fs$1, { constants } from "node:fs";
16
16
  import { sha256File } from "@openclaw/fs-safe/durability";
17
+ import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
17
18
  import { toErrorObject } from "openclaw/plugin-sdk/error-runtime";
18
19
  import { ARCHIVE_LIMIT_ERROR_CODE, ArchiveLimitError, extractArchive } from "openclaw/plugin-sdk/archive";
20
+ import { createSubsystemLogger } from "openclaw/plugin-sdk/logging-core";
19
21
  import { CUSTOM_LOCAL_AUTH_MARKER, applyAuthProfileConfig, buildApiKeyCredential, ensureApiKeyFromEnvOrPrompt, hasConfiguredSecretInput, isNonSecretApiKeyMarker, normalizeOptionalSecretInput, upsertAuthProfileWithLock } from "openclaw/plugin-sdk/provider-auth";
20
22
  import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
21
23
  import { removeAuthProfileConfig, removeProviderAuthProfilesWithLock, resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
22
24
  import { resolveConfiguredSecretInputString } from "openclaw/plugin-sdk/secret-input-runtime";
23
25
  import { LiveModelCatalogHttpError, runLiveProviderCatalog } from "openclaw/plugin-sdk/provider-catalog-live-runtime";
24
- import { getCachedLiveCatalogValue } from "openclaw/plugin-sdk/provider-catalog-shared";
25
26
  import { SELF_HOSTED_DEFAULT_CONTEXT_WINDOW, SELF_HOSTED_DEFAULT_COST, SELF_HOSTED_DEFAULT_MAX_TOKENS, applyProviderDefaultModel, discoverOpenAICompatibleLocalModels } from "openclaw/plugin-sdk/provider-setup";
26
27
  import { selectPreferredLocalModelId } from "openclaw/plugin-sdk/provider-model-shared";
27
28
  import { streamSimple } from "openclaw/plugin-sdk/llm";
@@ -214,6 +215,9 @@ function resolveManagedLlamaServerPaths(asset = selectLlamaServerAsset()) {
214
215
  presetPath: path.join(resolveLlamaCppDataDir(), "models.ini")
215
216
  };
216
217
  }
218
+ function findManagedLlamaServerAsset(command, platform = process.platform, arch = process.arch) {
219
+ return LLAMA_SERVER_ASSETS.find((asset) => asset.platform === platform && asset.arch === arch && resolveManagedLlamaServerPaths(asset).command === command);
220
+ }
217
221
  //#endregion
218
222
  //#region extensions/llama-cpp/src/llama-server-extract.ts
219
223
  const MEBIBYTE = 1048576;
@@ -422,8 +426,8 @@ async function extractWindowsVcRuntime(params) {
422
426
  //#endregion
423
427
  //#region extensions/llama-cpp/src/llama-server-install.ts
424
428
  const DOWNLOAD_TIMEOUT_MS = 18e5;
425
- const VERSION_TIMEOUT_MS = 15e3;
426
- const FRESH_VERSION_TIMEOUT_MS = 12e4;
429
+ const PROBE_TIMEOUT_MS = 15e3;
430
+ const VERSION_TIMEOUT_MS = 12e4;
427
431
  const installationPromises = /* @__PURE__ */ new Map();
428
432
  function compareVersion(left, right) {
429
433
  const leftParts = left.split(".").map(Number);
@@ -473,10 +477,7 @@ function rememberVerifiedFile(filePath, stat, sha256) {
473
477
  identity: fileIdentity(stat),
474
478
  sha256
475
479
  });
476
- if (verifiedFiles.size > VERIFIED_FILE_LIMIT) {
477
- const oldest = verifiedFiles.keys().next().value;
478
- if (oldest !== void 0) verifiedFiles.delete(oldest);
479
- }
480
+ pruneMapToMaxSize(verifiedFiles, VERIFIED_FILE_LIMIT);
480
481
  }
481
482
  async function sha256File$1(filePath, signal) {
482
483
  signal?.throwIfAborted();
@@ -571,7 +572,7 @@ async function downloadVerifiedFile(params) {
571
572
  await fs.rm(partialPath, { force: true }).catch(() => void 0);
572
573
  }
573
574
  }
574
- async function runServerCommand(command, args, signal, timeoutMs = VERSION_TIMEOUT_MS) {
575
+ async function runServerCommand(command, args, signal, timeoutMs = PROBE_TIMEOUT_MS) {
575
576
  return await new Promise((resolve, reject) => {
576
577
  execFile(command, args, {
577
578
  timeout: timeoutMs,
@@ -589,9 +590,9 @@ function formatRuntimeDependencyError(error) {
589
590
  if (process.platform === "win32") return new Error(`The verified llama-server build could not start with its app-local Visual C++ runtime. Rerun llama.cpp setup to reinstall it, or configure a compatible llama-server manually. Detail: ${detail}`, { cause: error });
590
591
  return new Error(`The verified llama-server build could not start: ${detail}`, { cause: error });
591
592
  }
592
- async function queryServerVersion(command, signal, versionTimeoutMs = VERSION_TIMEOUT_MS) {
593
+ async function queryServerVersion(command, signal) {
593
594
  try {
594
- return await runServerCommand(command, ["--version"], signal, versionTimeoutMs);
595
+ return await runServerCommand(command, ["--version"], signal, VERSION_TIMEOUT_MS);
595
596
  } catch (error) {
596
597
  signal?.throwIfAborted();
597
598
  throw formatRuntimeDependencyError(error);
@@ -609,8 +610,8 @@ async function validateCudaServer(command, asset, signal) {
609
610
  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.");
610
611
  }
611
612
  }
612
- async function validateInstalledServer(command, asset, signal, versionTimeoutMs = VERSION_TIMEOUT_MS) {
613
- validateServerVersionOutput(command, await queryServerVersion(command, signal, versionTimeoutMs));
613
+ async function validateInstalledServer(command, asset, signal) {
614
+ validateServerVersionOutput(command, await queryServerVersion(command, signal));
614
615
  await validateCudaServer(command, asset, signal);
615
616
  }
616
617
  async function stageLlamaServerDependency(params) {
@@ -696,7 +697,7 @@ async function installLlamaServer(asset, options) {
696
697
  if (windowsRuntimeDependencies.length > 0) {
697
698
  let version;
698
699
  try {
699
- version = await queryServerVersion(extractedCommand, options.signal, FRESH_VERSION_TIMEOUT_MS);
700
+ version = await queryServerVersion(extractedCommand, options.signal);
700
701
  } catch (startupError) {
701
702
  options.signal?.throwIfAborted();
702
703
  try {
@@ -712,7 +713,7 @@ async function installLlamaServer(asset, options) {
712
713
  throw formatVcRuntimeFallbackError(startupError, stagingError);
713
714
  }
714
715
  try {
715
- version = await queryServerVersion(extractedCommand, options.signal, FRESH_VERSION_TIMEOUT_MS);
716
+ version = await queryServerVersion(extractedCommand, options.signal);
716
717
  } catch (retryError) {
717
718
  options.signal?.throwIfAborted();
718
719
  throw formatVcRuntimeFallbackError(startupError, retryError);
@@ -720,7 +721,7 @@ async function installLlamaServer(asset, options) {
720
721
  }
721
722
  validateServerVersionOutput(extractedCommand, version);
722
723
  await validateCudaServer(extractedCommand, asset, options.signal);
723
- } else await validateInstalledServer(extractedCommand, asset, options.signal, FRESH_VERSION_TIMEOUT_MS);
724
+ } else await validateInstalledServer(extractedCommand, asset, options.signal);
724
725
  await fs.mkdir(path.dirname(installDir), { recursive: true });
725
726
  options.signal?.throwIfAborted();
726
727
  await fs.rm(installDir, {
@@ -859,6 +860,60 @@ function buildLlamaServerPreset(existing, params) {
859
860
  return header + (header && !/[\r\n]$/u.test(header) ? newline : "") + orderedSections.map((section) => section.replace(/[\r\n]+$/u, "")).join(newline + newline) + newline;
860
861
  }
861
862
  //#endregion
863
+ //#region extensions/llama-cpp/src/managed-server-orphans.ts
864
+ const log = createSubsystemLogger("llama-cpp");
865
+ const recoveries = /* @__PURE__ */ new Map();
866
+ function readUniqueArgument(argv, name) {
867
+ const values = argv.flatMap((argument, index) => {
868
+ if (argument === name) {
869
+ const value = argv[index + 1];
870
+ return value === void 0 ? [] : [value];
871
+ }
872
+ return argument.startsWith(`${name}=`) ? [argument.slice(name.length + 1)] : [];
873
+ });
874
+ return values.length === 1 ? values[0] : void 0;
875
+ }
876
+ /** A new host process recovers once; in-process restarts retain that host's children. */
877
+ async function recoverManagedLlamaServer(params) {
878
+ params.signal?.throwIfAborted();
879
+ if (!findManagedLlamaServerAsset(params.command)) return;
880
+ const args = params.args ?? [];
881
+ const preset = readUniqueArgument(args, "--models-preset");
882
+ const host = readUniqueArgument(args, "--host");
883
+ if (!preset || !host || readUniqueArgument(args, "--port") !== String(params.port)) return;
884
+ const required = /* @__PURE__ */ new Map([
885
+ ["--port", String(params.port)],
886
+ ["--models-preset", preset],
887
+ ["--host", host]
888
+ ]);
889
+ const cwd = !path.isAbsolute(preset) ? path.resolve(params.cwd ?? process.cwd()) : void 0;
890
+ const key = JSON.stringify([
891
+ params.command,
892
+ [...required],
893
+ cwd
894
+ ]);
895
+ let recovery = recoveries.get(key);
896
+ if (!recovery) {
897
+ recovery = (async () => {
898
+ const { reapOrphanedProcesses } = await import("openclaw/plugin-sdk/process-runtime");
899
+ if (typeof reapOrphanedProcesses !== "function") return;
900
+ await reapOrphanedProcesses({
901
+ command: params.command,
902
+ cwd,
903
+ matchesArguments: (argv) => [...required].every(([name, value]) => readUniqueArgument(argv, name) === value),
904
+ signal: params.signal,
905
+ onReap: (pid) => log.info(`reaping orphaned managed llama-server: pid=${pid} port=${params.port}`)
906
+ });
907
+ })().catch((error) => {
908
+ recoveries.delete(key);
909
+ throw error;
910
+ });
911
+ recoveries.set(key, recovery);
912
+ }
913
+ await recovery;
914
+ params.signal?.throwIfAborted();
915
+ }
916
+ //#endregion
862
917
  //#region extensions/llama-cpp/src/hardware.ts
863
918
  const GIB$1 = 1024 ** 3;
864
919
  const MIB = 1024 ** 2;
@@ -1151,7 +1206,7 @@ function recommendLlamaCppModel(hardware, backend, cached = {}) {
1151
1206
  }
1152
1207
  return {
1153
1208
  kind: "unavailable",
1154
- 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.`
1209
+ reason: candidates.length > 0 ? "There is not enough free disk space for a recommended model, embeddings, and the runtime. Free space in the model cache and retry setup." : `No recommended model fits the current ${formatLlamaCppMemory(Math.max(0, memoryBudgetBytes))} memory budget. Close other applications and retry, or configure an existing GGUF or external server. For local memory search without a chat model, an embedding-only local server (about 0.3 GB for the default embedding model) can fit instead. Set memory.search.provider to "local" with openclaw config set memory.search.provider local, then re-run openclaw models auth login --provider llama-cpp --method local using the same profile for both commands.`
1155
1210
  };
1156
1211
  }
1157
1212
  //#endregion
@@ -1285,6 +1340,34 @@ async function resolveModelArtifact(source, signal) {
1285
1340
  }
1286
1341
  throw new Error(`Unsupported remote model URI: ${source}`);
1287
1342
  }
1343
+ async function resolveCachedModelArtifact(source, cacheDir, signal) {
1344
+ const key = `${path.resolve(cacheDir)}\0${source}`;
1345
+ const artifact = resolvedModelArtifacts.get(key) ?? await resolveModelArtifact(source, signal);
1346
+ resolvedModelArtifacts.set(key, artifact);
1347
+ return artifact;
1348
+ }
1349
+ async function resolveLlamaCppModelDownloadSize(source, cacheDir, signal) {
1350
+ const artifact = await resolveCachedModelArtifact(source, cacheDir, signal);
1351
+ if (artifact.expectedSize !== void 0) return artifact.expectedSize;
1352
+ const result = await fetchWithSsrFGuard({
1353
+ url: artifact.url,
1354
+ init: { method: "HEAD" },
1355
+ signal,
1356
+ requireHttps: true,
1357
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(artifact.url),
1358
+ auditContext: "llama-cpp-model-resolve"
1359
+ }).catch(() => {
1360
+ signal?.throwIfAborted();
1361
+ });
1362
+ if (!result) return;
1363
+ const { response, release } = result;
1364
+ try {
1365
+ const size = response.ok ? Number(response.headers.get("content-length")) : 0;
1366
+ return Number.isSafeInteger(size) && size > 0 ? size : void 0;
1367
+ } finally {
1368
+ await release();
1369
+ }
1370
+ }
1288
1371
  async function ensureLlamaCppModel(params) {
1289
1372
  const localSource = resolveHomePath(params.source);
1290
1373
  if (!/^(?:hf|huggingface|https):/iu.test(localSource)) {
@@ -1292,9 +1375,7 @@ async function ensureLlamaCppModel(params) {
1292
1375
  await assertGguf(localPath);
1293
1376
  return localPath;
1294
1377
  }
1295
- const artifactCacheKey = `${path.resolve(params.cacheDir)}\0${localSource}`;
1296
- const artifact = resolvedModelArtifacts.get(artifactCacheKey) ?? await resolveModelArtifact(localSource, params.signal);
1297
- resolvedModelArtifacts.set(artifactCacheKey, artifact);
1378
+ const artifact = await resolveCachedModelArtifact(localSource, params.cacheDir, params.signal);
1298
1379
  const destination = path.join(params.cacheDir, artifact.fileName);
1299
1380
  const load = modelPromises.get(destination) ?? (async () => {
1300
1381
  const exists = await fs.stat(destination).then((stat) => stat.isFile()).catch(() => false);
@@ -1380,8 +1461,16 @@ async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT)
1380
1461
  }
1381
1462
  async function prepareManagedLlamaServer(params) {
1382
1463
  params.signal?.throwIfAborted();
1383
- const command = params.localService?.command ?? (await ensureLlamaServerInstalled({
1384
- asset: params.asset,
1464
+ let command = params.localService?.command;
1465
+ const asset = command === void 0 ? params.asset : findManagedLlamaServerAsset(command);
1466
+ if (command !== void 0 && asset) try {
1467
+ await fs.stat(command);
1468
+ } catch (error) {
1469
+ if (asOptionalRecord(error)?.code !== "ENOENT") throw error;
1470
+ command = void 0;
1471
+ }
1472
+ command ??= (await ensureLlamaServerInstalled({
1473
+ asset,
1385
1474
  signal: params.signal,
1386
1475
  onProgress: params.onProgress
1387
1476
  })).command;
@@ -1394,6 +1483,13 @@ async function prepareManagedLlamaServer(params) {
1394
1483
  healthUrl: params.localService?.healthUrl ?? `${rootUrl}/health`
1395
1484
  };
1396
1485
  const configuredPreset = params.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset") ?? params.localService?.env?.LLAMA_ARG_MODELS_PRESET;
1486
+ if (params.localService && !params.isolated) await recoverManagedLlamaServer({
1487
+ command,
1488
+ port,
1489
+ cwd: params.localService.cwd,
1490
+ args: params.localService.args,
1491
+ signal: params.signal
1492
+ });
1397
1493
  if (params.localService && !configuredPreset && !params.isolated) {
1398
1494
  await runPresetTransition(async () => {
1399
1495
  presetState.desiredRevisions.delete(reconcileOrigin);
@@ -1611,8 +1707,8 @@ function wrapProvider(params) {
1611
1707
  model: params.canonicalModel,
1612
1708
  dimensions: params.provider.dimensions,
1613
1709
  maxInputTokens: params.provider.maxInputTokens ?? 2044,
1614
- embed: async (input, callOptions) => await withFacts(async () => await params.provider.embed(input, callOptions)),
1615
- embedBatch: async (inputs, callOptions) => await withFacts(async () => await params.provider.embedBatch(inputs, callOptions)),
1710
+ embed: (input, callOptions) => withFacts(() => params.provider.embed(input, callOptions)),
1711
+ embedBatch: (inputs, callOptions) => withFacts(() => params.provider.embedBatch(inputs, callOptions)),
1616
1712
  close: params.provider.close
1617
1713
  };
1618
1714
  Object.defineProperty(wrapped, LOCAL_EMBEDDING_RUNTIME_FACTS, {
@@ -1711,6 +1807,7 @@ async function resolveLlamaServerRuntimeApiKey(params) {
1711
1807
  //#region extensions/llama-cpp/src/external-server/defaults.ts
1712
1808
  const LLAMA_SERVER_DEFAULT_ORIGIN = "http://127.0.0.1:8080";
1713
1809
  const LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR = "LLAMA_SERVER_API_KEY";
1810
+ const LLAMA_SERVER_DISCOVERY_TIMEOUT_MS = 5e3;
1714
1811
  //#endregion
1715
1812
  //#region extensions/llama-cpp/src/external-server/endpoint.ts
1716
1813
  /** Resolves the server origin and its OpenAI-compatible `/v1` inference base. */
@@ -1823,44 +1920,31 @@ function buildLlamaServerProviderConfig(params) {
1823
1920
  /** Discovers llama-server models without loading, waking, or unloading them. */
1824
1921
  async function discoverLlamaServer(params) {
1825
1922
  const endpoint = resolveLlamaServerEndpoint(params.baseUrl);
1826
- const apiKey = params.apiKey?.trim();
1827
- const cacheTtlMs = Boolean(apiKey && !isNonSecretApiKeyMarker(apiKey)) || Boolean(params.headers && Object.keys(params.headers).length > 0) ? 0 : Math.max(0, params.cacheTtlMs ?? 3e4);
1828
- return await getCachedLiveCatalogValue({
1829
- keyParts: [
1830
- "llama-cpp",
1831
- "external",
1832
- endpoint.origin
1833
- ],
1834
- ttlMs: cacheTtlMs,
1835
- shouldCache: (result) => result.kind === "success",
1836
- load: async () => {
1837
- const result = await discoverOpenAICompatibleLocalModels({
1838
- baseUrl: endpoint.inferenceBaseUrl,
1839
- serverBaseUrl: endpoint.origin,
1840
- apiKey: params.apiKey,
1841
- headers: params.headers,
1842
- label: "llama-server",
1843
- healthPath: "/health",
1844
- modelsPathOrder: "server-first",
1845
- routerModelProps: true,
1846
- timeoutMs: params.timeoutMs ?? 5e3,
1847
- signal: params.signal,
1848
- rawResult: true
1849
- });
1850
- if (result.kind !== "success") return {
1851
- ...result,
1852
- endpoint
1853
- };
1854
- return {
1855
- kind: "success",
1856
- endpoint,
1857
- models: result.rows.flatMap(({ model, props }) => {
1858
- const mapped = mapLlamaServerModel(model, props);
1859
- return mapped ? [mapped] : [];
1860
- })
1861
- };
1862
- }
1923
+ const result = await discoverOpenAICompatibleLocalModels({
1924
+ baseUrl: endpoint.inferenceBaseUrl,
1925
+ serverBaseUrl: endpoint.origin,
1926
+ apiKey: params.apiKey,
1927
+ headers: params.headers,
1928
+ label: "llama-server",
1929
+ healthPath: "/health",
1930
+ modelsPathOrder: "server-first",
1931
+ routerModelProps: true,
1932
+ timeoutMs: LLAMA_SERVER_DISCOVERY_TIMEOUT_MS,
1933
+ signal: params.signal,
1934
+ rawResult: true
1863
1935
  });
1936
+ if (result.kind !== "success") return {
1937
+ ...result,
1938
+ endpoint
1939
+ };
1940
+ return {
1941
+ kind: "success",
1942
+ endpoint,
1943
+ models: result.rows.flatMap(({ model, props }) => {
1944
+ const mapped = mapLlamaServerModel(model, props);
1945
+ return mapped ? [mapped] : [];
1946
+ })
1947
+ };
1864
1948
  }
1865
1949
  //#endregion
1866
1950
  //#region extensions/llama-cpp/src/external-server/provider.ts
@@ -1882,8 +1966,7 @@ async function discoverLlamaServerProvider(ctx) {
1882
1966
  const discovery = await discoverLlamaServer({
1883
1967
  baseUrl: configured?.baseUrl,
1884
1968
  apiKey,
1885
- headers,
1886
- cacheTtlMs: 0
1969
+ headers
1887
1970
  });
1888
1971
  if (discovery.kind !== "success") {
1889
1972
  if (!configured && !apiKey && !headers) return null;
@@ -1910,8 +1993,7 @@ async function prepareLlamaServerDynamicModel(ctx) {
1910
1993
  const discovery = await discoverLlamaServer({
1911
1994
  baseUrl: ctx.providerConfig?.baseUrl,
1912
1995
  apiKey: hasLlamaServerAuthorizationHeader(headers) ? void 0 : apiKey,
1913
- headers,
1914
- cacheTtlMs: 0
1996
+ headers
1915
1997
  });
1916
1998
  const model = discovery.kind === "success" ? discovery.models.find((entry) => entry.config.id === ctx.modelId) : void 0;
1917
1999
  if (!model) return;
@@ -2056,8 +2138,7 @@ async function discoverForSetup(ctx) {
2056
2138
  baseUrl: provider?.baseUrl ?? "http://127.0.0.1:8080",
2057
2139
  apiKey,
2058
2140
  headers,
2059
- signal: ctx.signal,
2060
- cacheTtlMs: 0
2141
+ signal: ctx.signal
2061
2142
  });
2062
2143
  return discovery.kind === "success" ? discovery : null;
2063
2144
  } catch {
@@ -2160,8 +2241,7 @@ async function runLlamaServerSetup(ctx) {
2160
2241
  baseUrl: endpoint.inferenceBaseUrl,
2161
2242
  apiKey,
2162
2243
  headers,
2163
- signal: ctx.signal,
2164
- cacheTtlMs: 0
2244
+ signal: ctx.signal
2165
2245
  });
2166
2246
  if (discovery.kind !== "success") throw new Error(describeDiscoveryFailure(discovery));
2167
2247
  const modelId = selectSetupModelId(discovery);
@@ -2220,21 +2300,14 @@ async function validateNonInteractiveDiscovery(ctx) {
2220
2300
  const discovery = await discoverLlamaServer({
2221
2301
  baseUrl,
2222
2302
  apiKey,
2223
- headers,
2224
- cacheTtlMs: 0
2303
+ headers
2225
2304
  });
2226
- if (discovery.kind !== "success") {
2227
- ctx.runtime.error(describeDiscoveryFailure(discovery));
2228
- ctx.runtime.exit(1);
2229
- return null;
2230
- }
2305
+ if (discovery.kind !== "success") throw new Error(describeDiscoveryFailure(discovery));
2231
2306
  const requestedModelId = normalizeOptionalSecretInput(ctx.opts.customModelId);
2232
2307
  const modelId = requestedModelId ?? selectSetupModelId(discovery);
2233
2308
  if (!modelId || !discovery.models.some((model) => model.config.id === modelId)) {
2234
2309
  const available = discovery.models.map((model) => model.config.id).join(", ");
2235
- 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}.`);
2236
- ctx.runtime.exit(1);
2237
- return null;
2310
+ throw new Error(requestedModelId ? `llama-server model ${requestedModelId} was not found. Available models: ${available}` : `No llama-server text models were found at ${discovery.endpoint.origin}.`);
2238
2311
  }
2239
2312
  return {
2240
2313
  discovery,
@@ -2244,12 +2317,12 @@ async function validateNonInteractiveDiscovery(ctx) {
2244
2317
  };
2245
2318
  }
2246
2319
  async function validateLlamaServerNonInteractive(ctx) {
2247
- return Boolean(await validateNonInteractiveDiscovery(ctx));
2320
+ await validateNonInteractiveDiscovery(ctx);
2321
+ return true;
2248
2322
  }
2249
2323
  /** Non-interactive setup with optional API-key persistence. */
2250
2324
  async function configureLlamaServerNonInteractive(ctx) {
2251
2325
  const validated = await validateNonInteractiveDiscovery(ctx);
2252
- if (!validated) return null;
2253
2326
  const providerConfig = buildExistingProviderConfig({
2254
2327
  config: ctx.config,
2255
2328
  ...validated
@@ -2335,13 +2408,9 @@ function readPrimaryModel(config) {
2335
2408
  const model = config.agents?.defaults?.model;
2336
2409
  return typeof model === "string" ? model : model?.primary;
2337
2410
  }
2338
- function configuredCandidates(config, scope) {
2339
- const existing = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2340
- const managedExisting = existing?.localService ? existing : void 0;
2341
- const provider = buildLlamaCppProviderConfig({
2342
- existing: managedExisting,
2343
- ...managedExisting && scope === "detection" ? { modelInventory: managedExisting.models } : {}
2344
- });
2411
+ function configuredCandidates(config) {
2412
+ const provider = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2413
+ if (!provider?.localService) return [];
2345
2414
  const primary = readPrimaryModel(config);
2346
2415
  const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
2347
2416
  return provider.models.map((model) => ({
@@ -2396,7 +2465,7 @@ async function detectLlamaCppSetup(ctx) {
2396
2465
  const command = existing?.localService?.command;
2397
2466
  const presetPath = existing?.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset");
2398
2467
  if (!command || !path.isAbsolute(command) || !await isFile(command) || !presetPath || !await isFile(presetPath)) return null;
2399
- for (const candidate of configuredCandidates(ctx.config, "detection")) if (await resolveCachedCandidate(candidate, ctx.signal)) return {
2468
+ for (const candidate of configuredCandidates(ctx.config)) if (await resolveCachedCandidate(candidate, ctx.signal)) return {
2400
2469
  modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
2401
2470
  detail: "Managed llama.cpp server ready"
2402
2471
  };
@@ -2451,8 +2520,40 @@ async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localM
2451
2520
  cachedPath: configuredPath
2452
2521
  };
2453
2522
  }
2454
- const provider = candidate?.provider ?? buildLlamaCppProviderConfig();
2523
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2524
+ const provider = existing?.localService ? existing : buildLlamaCppProviderConfig();
2455
2525
  const cacheDir = resolveLlamaCppModelCacheDir(provider);
2526
+ if (candidate) {
2527
+ const source = resolveLlamaCppModelSource(candidate.model);
2528
+ let size;
2529
+ try {
2530
+ if (path.isAbsolute(source) || !/^[a-z][a-z\d+.-]*:/iu.test(source)) {
2531
+ const cachedPath = await ensureLlamaCppModel({
2532
+ source,
2533
+ cacheDir,
2534
+ download: false,
2535
+ signal: ctx.signal
2536
+ });
2537
+ return {
2538
+ kind: "chat",
2539
+ candidate,
2540
+ cachedPath
2541
+ };
2542
+ }
2543
+ size = await resolveLlamaCppModelDownloadSize(source, cacheDir, ctx.signal);
2544
+ } catch (error) {
2545
+ ctx.signal?.throwIfAborted();
2546
+ 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");
2547
+ return;
2548
+ }
2549
+ return await ctx.prompter.confirm({
2550
+ 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?`,
2551
+ initialValue: false
2552
+ }) ? {
2553
+ kind: "chat",
2554
+ candidate
2555
+ } : void 0;
2556
+ }
2456
2557
  const cachedModels = /* @__PURE__ */ new Map();
2457
2558
  for (const recipe of resolveLlamaCppModelCandidates(hardware, asset.backend).recipes) {
2458
2559
  const cached = await resolveCachedArtifact(resolveLlamaCppModelSource(recipe.model), cacheDir, ctx.signal);
@@ -2495,7 +2596,6 @@ async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localM
2495
2596
  await ctx.prompter.note(recommendation.reason, "Setup skipped");
2496
2597
  return;
2497
2598
  }
2498
- const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
2499
2599
  if (localMemoryIntent && existing && (!existing.localService || existing.models.length > 0)) {
2500
2600
  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");
2501
2601
  return;
@@ -2531,7 +2631,7 @@ async function runLlamaCppSetup(ctx) {
2531
2631
  asset = selectLlamaServerAsset(hardware.platform, hardware.arch, { kind: "cpu" });
2532
2632
  runtimeNote = `${error instanceof Error ? error.message : String(error)} This recommendation uses CPU execution.`;
2533
2633
  }
2534
- const plan = await resolveSetupPlan(ctx, configuredCandidates(ctx.config, "setup"), embeddingModel.isDefault, embeddingSetup.localMemoryIntent, hardware, asset, runtimeNote);
2634
+ const plan = await resolveSetupPlan(ctx, configuredCandidates(ctx.config), embeddingModel.isDefault, embeddingSetup.localMemoryIntent, hardware, asset, runtimeNote);
2535
2635
  if (!plan) return { profiles: [] };
2536
2636
  const progress = ctx.prompter.progress("Preparing managed llama.cpp server…");
2537
2637
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/llama-cpp-provider",
3
- "version": "2026.10.2",
3
+ "version": "2026.10.5-beta.2",
4
4
  "description": "OpenClaw provider for managed and external llama.cpp servers",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,10 +21,10 @@
21
21
  "minHostVersion": ">=2026.6.2"
22
22
  },
23
23
  "compat": {
24
- "pluginApi": ">=2026.10.2"
24
+ "pluginApi": ">=2026.10.5-beta.2"
25
25
  },
26
26
  "build": {
27
- "openclawVersion": "2026.10.2"
27
+ "openclawVersion": "2026.10.5-beta.2"
28
28
  },
29
29
  "release": {
30
30
  "bundleRuntimeDependencies": false,
@@ -36,7 +36,7 @@
36
36
  ]
37
37
  },
38
38
  "dependencies": {
39
- "@openclaw/fs-safe": "0.24.2"
39
+ "@openclaw/fs-safe": "0.25.0"
40
40
  },
41
41
  "files": [
42
42
  "dist/**",
@@ -46,7 +46,7 @@
46
46
  "assets/activity.svg"
47
47
  ],
48
48
  "peerDependencies": {
49
- "openclaw": ">=2026.10.2"
49
+ "openclaw": ">=2026.10.5-beta.2"
50
50
  },
51
51
  "peerDependenciesMeta": {
52
52
  "openclaw": {