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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1115 @@
1
+ import { C as resolveLegacyLlamaCppModelCacheDir, D as resolveLlamaCppModelSource, E as resolveLlamaCppModelCacheDir, S as resolveHomePath, a as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, c as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES, h as LLAMA_CPP_DEFAULT_PORT, l as DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE, n as DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE, o as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION, r as DEFAULT_LLAMA_CPP_EMBEDDING_CONTEXT_SIZE, s as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256, w as resolveLlamaCppDataDir, x as resolveCachedLlamaCppModelPath } from "./defaults-CL2lz0cV.mjs";
2
+ import { a as resolveLlamaCppCatalogArtifact, d as LLAMA_SERVER_RELEASE, f as findManagedLlamaServerAsset, m as selectLlamaServerAsset, p as resolveManagedLlamaServerPaths, r as resolveLlamaCppMediaArtifact, u as LLAMA_SERVER_COMMIT } from "./media-catalog-M5BEPQng.mjs";
3
+ import path from "node:path";
4
+ import { asOptionalRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
5
+ import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
6
+ import { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } from "openclaw/plugin-sdk/ssrf-runtime";
7
+ import { fetchConfiguredLocalOriginWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime-internal";
8
+ import { createHash, randomUUID } from "node:crypto";
9
+ import fs from "node:fs/promises";
10
+ import net from "node:net";
11
+ import { createAsyncLock } from "openclaw/plugin-sdk/async-lock-runtime";
12
+ import { execFile } from "node:child_process";
13
+ import fs$1, { constants, createWriteStream } from "node:fs";
14
+ import { sha256File } from "@openclaw/fs-safe/durability";
15
+ import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
16
+ import { toErrorObject } from "openclaw/plugin-sdk/error-runtime";
17
+ import { ARCHIVE_LIMIT_ERROR_CODE, ArchiveLimitError, extractArchive } from "openclaw/plugin-sdk/archive";
18
+ import { pipeline } from "node:stream/promises";
19
+ import { createSubsystemLogger } from "openclaw/plugin-sdk/logging-core";
20
+ //#region extensions/llama-cpp/src/llama-server-extract.ts
21
+ const MEBIBYTE = 1048576;
22
+ const LLAMA_ARCHIVE_LIMITS = {
23
+ maxArchiveBytes: 256 * MEBIBYTE,
24
+ maxEntries: 1e3,
25
+ maxExtractedBytes: 512 * MEBIBYTE,
26
+ maxEntryBytes: 256 * MEBIBYTE,
27
+ maxMetaEntryBytes: MEBIBYTE
28
+ };
29
+ const MAX_ALIAS_BYTES = 512 * MEBIBYTE;
30
+ async function assertRegularFile$1(filePath, label) {
31
+ const stat = await fs.lstat(filePath).catch(() => void 0);
32
+ if (!stat?.isFile() || stat.nlink > 1) throw new Error(`llama-server archive does not contain regular ${label}`);
33
+ return stat;
34
+ }
35
+ async function materializeAssetAliases(params) {
36
+ for (const file of params.requiredFiles) await assertRegularFile$1(path.join(params.rootDir, file), `file ${file}`);
37
+ let copiedBytes = 0;
38
+ for (const [source, aliases] of params.asset.regularFileAliases) {
39
+ const sourcePath = path.join(params.rootDir, source);
40
+ const sourceStat = await assertRegularFile$1(sourcePath, `alias source ${source}`);
41
+ for (const alias of aliases) {
42
+ copiedBytes += sourceStat.size;
43
+ if (copiedBytes > MAX_ALIAS_BYTES) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.EXTRACTED_SIZE_EXCEEDS_LIMIT);
44
+ const aliasPath = path.join(params.rootDir, alias);
45
+ await fs.copyFile(sourcePath, aliasPath, constants.COPYFILE_EXCL);
46
+ await fs.chmod(aliasPath, sourceStat.mode & 511);
47
+ }
48
+ }
49
+ }
50
+ async function extractVerifiedArchive(params) {
51
+ const isTar = params.asset.archive === "tar.gz";
52
+ const limits = {
53
+ ...LLAMA_ARCHIVE_LIMITS,
54
+ ...params.asset.limits
55
+ };
56
+ const aliasCount = params.asset.regularFileAliases.reduce((count, [, aliases]) => count + aliases.length, 0);
57
+ if (aliasCount > limits.maxEntries) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.ENTRY_COUNT_EXCEEDS_LIMIT);
58
+ await extractArchive({
59
+ archivePath: params.archivePath,
60
+ destDir: params.destDir,
61
+ kind: isTar ? "tar" : "zip",
62
+ timeoutMs: 0,
63
+ limits: {
64
+ ...limits,
65
+ maxEntries: limits.maxEntries - aliasCount
66
+ },
67
+ tarGzip: isTar,
68
+ entryFilter: (entry) => entry.kind === "symlink" ? "skip" : "extract",
69
+ onFiltered: "skip-entry"
70
+ });
71
+ const rootDir = path.join(params.destDir, params.asset.archiveRoot);
72
+ await materializeAssetAliases({
73
+ rootDir,
74
+ asset: params.asset,
75
+ requiredFiles: params.requiredFiles
76
+ });
77
+ return rootDir;
78
+ }
79
+ /** Extracts one verified asset and returns its unpublished executable path. */
80
+ async function extractLlamaServerArchive(params) {
81
+ const rootDir = await extractVerifiedArchive({
82
+ ...params,
83
+ requiredFiles: [params.asset.executable]
84
+ });
85
+ return path.join(rootDir, params.asset.executable);
86
+ }
87
+ async function extractLlamaServerDependencyArchive(params) {
88
+ return await extractVerifiedArchive({
89
+ ...params,
90
+ requiredFiles: params.asset.files
91
+ });
92
+ }
93
+ //#endregion
94
+ //#region extensions/llama-cpp/src/llama-server-vc-runtime.ts
95
+ const CAB_HEADER_SIZE = 12;
96
+ const EXPAND_TIMEOUT_MS = 6e4;
97
+ async function extractPinnedContainer(params) {
98
+ const source = await fs.open(params.bundlePath, "r");
99
+ try {
100
+ const stat = await source.stat();
101
+ if (!stat.isFile() || stat.size !== params.asset.size) throw new Error(`Visual C++ runtime bundle size mismatch: expected ${params.asset.size}, got ${stat.size}`);
102
+ if (params.asset.containerOffset < 0 || params.asset.containerSize < CAB_HEADER_SIZE || params.asset.containerOffset + params.asset.containerSize > stat.size) throw new Error("invalid Visual C++ runtime container bounds");
103
+ const header = Buffer.alloc(CAB_HEADER_SIZE);
104
+ if ((await source.read(header, 0, header.length, params.asset.containerOffset)).bytesRead !== header.length || header.subarray(0, 4).toString("ascii") !== "MSCF" || header.readUInt32LE(8) !== params.asset.containerSize) throw new Error("Visual C++ runtime bundle does not contain the pinned cabinet");
105
+ await pipeline(source.createReadStream({
106
+ start: params.asset.containerOffset,
107
+ end: params.asset.containerOffset + params.asset.containerSize - 1,
108
+ autoClose: false
109
+ }), createWriteStream(params.containerPath, {
110
+ flags: "wx",
111
+ mode: 384
112
+ }), { signal: params.signal });
113
+ } finally {
114
+ await source.close();
115
+ }
116
+ }
117
+ function resolveExpandCommand() {
118
+ const systemRoot = process.env.SystemRoot;
119
+ if (!systemRoot || !path.win32.isAbsolute(systemRoot)) throw new Error("SystemRoot is unavailable; cannot extract the Visual C++ runtime");
120
+ return path.win32.join(systemRoot, "System32", "expand.exe");
121
+ }
122
+ async function runExpand(command, args, signal) {
123
+ await new Promise((resolve, reject) => {
124
+ execFile(command, args, {
125
+ timeout: EXPAND_TIMEOUT_MS,
126
+ signal,
127
+ windowsHide: true
128
+ }, (error, _stdout, stderr) => {
129
+ if (error) {
130
+ const detail = stderr.trim();
131
+ reject(new Error(`Failed to extract the Visual C++ runtime${detail ? `: ${detail}` : ""}`, { cause: error }));
132
+ } else resolve();
133
+ });
134
+ });
135
+ }
136
+ async function assertRegularFile(filePath, label) {
137
+ const stat = await fs.lstat(filePath).catch(() => void 0);
138
+ if (!stat?.isFile() || stat.nlink > 1) throw new Error(`Visual C++ runtime does not contain regular file ${label}`);
139
+ }
140
+ /** Extracts the pinned Microsoft redistributable DLLs without installing machine-wide state. */
141
+ async function extractWindowsVcRuntime(params) {
142
+ const { nestedCabinet, files } = params.asset;
143
+ const expandCommand = resolveExpandCommand();
144
+ const containerPath = path.join(params.destDir, "bundle.cab");
145
+ const nestedDir = path.join(params.destDir, "nested");
146
+ const filesDir = path.join(params.destDir, "files");
147
+ await Promise.all([
148
+ fs.mkdir(params.destDir, { recursive: true }),
149
+ fs.mkdir(nestedDir, { recursive: true }),
150
+ fs.mkdir(filesDir, { recursive: true })
151
+ ]);
152
+ await extractPinnedContainer({
153
+ asset: params.asset,
154
+ bundlePath: params.bundlePath,
155
+ containerPath,
156
+ signal: params.signal
157
+ });
158
+ await runExpand(expandCommand, [
159
+ `-F:${nestedCabinet}`,
160
+ containerPath,
161
+ nestedDir
162
+ ], params.signal);
163
+ const nestedPath = path.join(nestedDir, nestedCabinet);
164
+ await assertRegularFile(nestedPath, nestedCabinet);
165
+ for (const file of files) {
166
+ params.signal?.throwIfAborted();
167
+ await runExpand(expandCommand, [
168
+ `-F:${file.source}`,
169
+ nestedPath,
170
+ filesDir
171
+ ], params.signal);
172
+ const sourcePath = path.join(filesDir, file.source);
173
+ await assertRegularFile(sourcePath, file.source);
174
+ const targetPath = path.join(params.destDir, file.target);
175
+ await fs.copyFile(sourcePath, targetPath, constants.COPYFILE_EXCL);
176
+ }
177
+ return params.destDir;
178
+ }
179
+ //#endregion
180
+ //#region extensions/llama-cpp/src/llama-server-install.ts
181
+ const DOWNLOAD_TIMEOUT_MS = 18e5;
182
+ const PROBE_TIMEOUT_MS = 15e3;
183
+ const VERSION_TIMEOUT_MS = 12e4;
184
+ const installationPromises = /* @__PURE__ */ new Map();
185
+ function compareVersion(left, right) {
186
+ const leftParts = left.split(".").map(Number);
187
+ const rightParts = right.split(".").map(Number);
188
+ for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) {
189
+ const delta = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
190
+ if (delta !== 0) return delta;
191
+ }
192
+ return 0;
193
+ }
194
+ /** The verified build cannot run on this host; rerunning setup cannot change that. */
195
+ var UnsupportedLlamaServerHostError = class extends Error {
196
+ constructor(..._args) {
197
+ super(..._args);
198
+ this.name = "UnsupportedLlamaServerHostError";
199
+ }
200
+ };
201
+ function assertSupportedLinuxRuntime(asset) {
202
+ if (asset.platform !== "linux") return;
203
+ const header = asOptionalRecord(asOptionalRecord(process.report?.getReport())?.header);
204
+ const glibc = typeof header?.glibcVersionRuntime === "string" ? header.glibcVersionRuntime : "";
205
+ if (!glibc) throw new UnsupportedLlamaServerHostError("The verified Ubuntu llama-server build requires glibc and cannot run on musl/Alpine. Install llama-server manually for this host and configure its absolute path.");
206
+ const minimum = asset.arch === "arm64" ? "2.38" : "2.34";
207
+ if (compareVersion(glibc, minimum) < 0) throw new UnsupportedLlamaServerHostError(`The verified llama-server build requires glibc ${minimum}+ on Linux ${asset.arch}; this host has ${glibc}. Install a compatible llama-server manually and configure its absolute path.`);
208
+ }
209
+ const MACOS_MINIMUM = "13.3";
210
+ async function assertSupportedMacosRuntime(asset, signal, cause) {
211
+ if (asset.platform !== "darwin") return;
212
+ const version = await runServerCommand("/usr/bin/sw_vers", ["-productVersion"], signal).catch(() => {
213
+ signal?.throwIfAborted();
214
+ return "";
215
+ });
216
+ if (!/^\d+\.\d+(?:\.\d+)?$/u.test(version) || compareVersion(version, MACOS_MINIMUM) >= 0) return;
217
+ throw new UnsupportedLlamaServerHostError(`The verified llama-server ${LLAMA_SERVER_RELEASE} build requires macOS ${MACOS_MINIMUM}+; this Mac runs macOS ${version}. Build llama-server for this Mac and set models.providers.llama-cpp.localService.command to its absolute path, or use a remote model or embedding provider.`, cause === void 0 ? void 0 : { cause });
218
+ }
219
+ function assetUrl(asset) {
220
+ return asset.url ?? `https://github.com/ggml-org/llama.cpp/releases/download/b10809/${asset.name}`;
221
+ }
222
+ const verifiedFiles = /* @__PURE__ */ new Map();
223
+ const VERIFIED_FILE_LIMIT = 16;
224
+ function fileIdentity(stat) {
225
+ return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
226
+ }
227
+ function rememberVerifiedFile(filePath, stat, sha256) {
228
+ verifiedFiles.delete(filePath);
229
+ verifiedFiles.set(filePath, {
230
+ identity: fileIdentity(stat),
231
+ sha256
232
+ });
233
+ pruneMapToMaxSize(verifiedFiles, VERIFIED_FILE_LIMIT);
234
+ }
235
+ async function sha256File$1(filePath, signal) {
236
+ signal?.throwIfAborted();
237
+ try {
238
+ const identity = fileIdentity(await fs.stat(filePath, { bigint: true }));
239
+ const verified = verifiedFiles.get(filePath);
240
+ if (verified?.identity === identity) return verified.sha256;
241
+ verifiedFiles.delete(filePath);
242
+ const handle = await fs.open(filePath, "r");
243
+ try {
244
+ const before = fileIdentity(await handle.stat({ bigint: true }));
245
+ const { digest: sha256 } = await sha256File(handle, { signal });
246
+ const after = await handle.stat({ bigint: true });
247
+ if (before !== fileIdentity(after) || before !== fileIdentity(await fs.stat(filePath, { bigint: true }))) throw new Error(`File changed during integrity verification: ${filePath}. Retry setup.`);
248
+ rememberVerifiedFile(filePath, after, sha256);
249
+ return sha256;
250
+ } finally {
251
+ await handle.close();
252
+ }
253
+ } catch (error) {
254
+ verifiedFiles.delete(filePath);
255
+ throw error;
256
+ }
257
+ }
258
+ function readResponseSha256(response) {
259
+ for (const name of ["x-checksum-sha256", "x-linked-etag"]) {
260
+ const value = response.headers.get(name)?.replace(/^W\//u, "").replaceAll("\"", "").trim();
261
+ if (value && /^[a-f\d]{64}$/iu.test(value)) return value.toLowerCase();
262
+ }
263
+ const encoded = response.headers.get("digest")?.match(/(?:^|,)\s*sha-256=([^,\s]+)/iu)?.[1];
264
+ return encoded ? Buffer.from(encoded, "base64").toString("hex") : void 0;
265
+ }
266
+ async function downloadVerifiedFile(params) {
267
+ const partialPath = `${params.destination}.partial-${randomUUID()}`;
268
+ await fs.mkdir(path.dirname(params.destination), { recursive: true });
269
+ const { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } = await import("openclaw/plugin-sdk/ssrf-runtime");
270
+ try {
271
+ const { response, release } = await fetchWithSsrFGuard({
272
+ url: params.url,
273
+ signal: params.signal,
274
+ timeoutMs: DOWNLOAD_TIMEOUT_MS,
275
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(params.url),
276
+ requireHttps: true,
277
+ auditContext: "llama-cpp-download"
278
+ });
279
+ try {
280
+ if (!response.ok || !response.body) throw new Error(`download failed: HTTP ${response.status} ${response.statusText}`);
281
+ const expectedSha256 = params.expectedSha256 ?? readResponseSha256(response);
282
+ 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");
283
+ const contentLength = Number(response.headers.get("content-length"));
284
+ const totalSize = params.expectedSize ?? (Number.isFinite(contentLength) && contentLength > 0 ? contentLength : 0);
285
+ const handle = await fs.open(partialPath, "wx", 384);
286
+ const hash = createHash("sha256");
287
+ let downloadedSize = 0;
288
+ let previousSize = 0;
289
+ let previousAt = Date.now();
290
+ let rollingBytesPerSecond = 0;
291
+ try {
292
+ for await (const value of response.body.values({ preventCancel: true })) {
293
+ const chunk = Buffer.from(value);
294
+ await handle.writeFile(chunk);
295
+ hash.update(chunk);
296
+ downloadedSize += chunk.byteLength;
297
+ const now = Date.now();
298
+ if (now > previousAt) {
299
+ const currentRate = (downloadedSize - previousSize) * 1e3 / (now - previousAt);
300
+ rollingBytesPerSecond = rollingBytesPerSecond === 0 ? currentRate : rollingBytesPerSecond * .75 + currentRate * .25;
301
+ previousSize = downloadedSize;
302
+ previousAt = now;
303
+ }
304
+ params.onProgress?.({
305
+ downloadedSize,
306
+ totalSize,
307
+ bytesPerSecond: rollingBytesPerSecond
308
+ });
309
+ }
310
+ if (params.expectedSize && downloadedSize !== params.expectedSize) throw new Error(`download size mismatch: expected ${params.expectedSize}, got ${downloadedSize}`);
311
+ const actualSha256 = hash.digest("hex");
312
+ if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
313
+ const completed = await handle.stat({ bigint: true });
314
+ params.signal?.throwIfAborted();
315
+ await fs.rename(partialPath, params.destination);
316
+ const published = await handle.stat({ bigint: true });
317
+ if (completed.size === published.size && completed.mtimeNs === published.mtimeNs) rememberVerifiedFile(params.destination, published, actualSha256);
318
+ } finally {
319
+ await handle.close();
320
+ }
321
+ } finally {
322
+ await release();
323
+ }
324
+ } finally {
325
+ await fs.rm(partialPath, { force: true }).catch(() => void 0);
326
+ }
327
+ }
328
+ async function runServerCommand(command, args, signal, timeoutMs = PROBE_TIMEOUT_MS) {
329
+ return await new Promise((resolve, reject) => {
330
+ execFile(command, args, {
331
+ timeout: timeoutMs,
332
+ signal,
333
+ windowsHide: true
334
+ }, (error, stdout, stderr) => {
335
+ if (error) reject(new Error(error.message, { cause: error }));
336
+ else resolve(`${stdout}${stderr}`.trim());
337
+ });
338
+ });
339
+ }
340
+ function formatRuntimeDependencyError(error) {
341
+ const detail = error instanceof Error ? error.message : String(error);
342
+ if (process.platform === "linux") return new Error(`The verified llama-server build could not start. Install the OpenMP runtime (for example libgomp1 on Debian/Ubuntu or libgomp on Fedora), then rerun llama.cpp setup. Detail: ${detail}`, { cause: error });
343
+ 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 });
344
+ return new Error(`The verified llama-server build could not start: ${detail}`, { cause: error });
345
+ }
346
+ async function queryServerVersion(command, signal) {
347
+ try {
348
+ return await runServerCommand(command, ["--version"], signal, VERSION_TIMEOUT_MS);
349
+ } catch (error) {
350
+ signal?.throwIfAborted();
351
+ throw formatRuntimeDependencyError(error);
352
+ }
353
+ }
354
+ function validateServerVersionOutput(command, version) {
355
+ const match = (version.split(/\r?\n/u, 1)[0]?.trim() ?? "").match(/^version: .+ \(build (\d+), commit ([a-f\d]{9})\)$/u);
356
+ const build = match?.[1] ? Number(match[1]) : void 0;
357
+ const commit = match?.[2];
358
+ if (build !== 10809 || commit !== "5266f24da75dc449bd56cbed7addb9c8e4a6a73e".slice(0, 9)) throw new Error(`Unexpected llama-server build at ${command}: expected ${LLAMA_SERVER_RELEASE} (${LLAMA_SERVER_COMMIT.slice(0, 9)}), got ${version || "no version output"}`);
359
+ }
360
+ async function validateCudaServer(command, asset, signal) {
361
+ if (asset.backend === "cuda") {
362
+ const devices = await runServerCommand(command, ["--list-devices"], signal);
363
+ 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.");
364
+ }
365
+ }
366
+ async function validateInstalledServer(command, asset, signal) {
367
+ validateServerVersionOutput(command, await queryServerVersion(command, signal));
368
+ await validateCudaServer(command, asset, signal);
369
+ }
370
+ async function stageLlamaServerDependency(params) {
371
+ const { dependency, extractDir, extractedRoot, index, options } = params;
372
+ options.signal?.throwIfAborted();
373
+ const dependencyArchive = path.join(extractDir, dependency.name);
374
+ await downloadVerifiedFile({
375
+ url: assetUrl(dependency),
376
+ destination: dependencyArchive,
377
+ expectedSha256: dependency.sha256,
378
+ expectedSize: dependency.archive === "vc-redist" ? dependency.size : void 0,
379
+ signal: options.signal,
380
+ onProgress: options.onProgress
381
+ });
382
+ const dependencyExtractDir = path.join(extractDir, `dependency-${index}`);
383
+ await fs.mkdir(dependencyExtractDir);
384
+ const dependencyRoot = dependency.archive === "vc-redist" ? await extractWindowsVcRuntime({
385
+ bundlePath: dependencyArchive,
386
+ destDir: dependencyExtractDir,
387
+ asset: dependency,
388
+ signal: options.signal
389
+ }) : await extractLlamaServerDependencyArchive({
390
+ archivePath: dependencyArchive,
391
+ destDir: dependencyExtractDir,
392
+ asset: dependency
393
+ });
394
+ for (const file of dependencyFiles(dependency)) await fs.copyFile(path.join(dependencyRoot, file), path.join(extractedRoot, file), fs$1.constants.COPYFILE_EXCL);
395
+ }
396
+ function formatVcRuntimeFallbackError(startupError, fallbackError) {
397
+ const startupDetail = startupError instanceof Error ? startupError.message : String(startupError);
398
+ const fallbackDetail = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);
399
+ return new Error(`The extracted llama-server could not start with the installed Windows runtime, and its app-local Visual C++ runtime fallback did not restore it. Initial startup detail: ${startupDetail} Fallback detail: ${fallbackDetail}`, { cause: fallbackError });
400
+ }
401
+ async function installLlamaServer(asset, options) {
402
+ options.signal?.throwIfAborted();
403
+ assertSupportedLinuxRuntime(asset);
404
+ const { installDir, command } = resolveManagedLlamaServerPaths(asset);
405
+ if (await fs.stat(command).then((stat) => stat.isFile()).catch(() => false)) {
406
+ try {
407
+ await validateInstalledServer(command, asset, options.signal);
408
+ } catch (error) {
409
+ await assertSupportedMacosRuntime(asset, options.signal, error);
410
+ throw error;
411
+ }
412
+ return command;
413
+ }
414
+ await assertSupportedMacosRuntime(asset, options.signal);
415
+ const dataDir = resolveLlamaCppDataDir();
416
+ const archivePath = path.join(dataDir, `.download-${randomUUID()}-${asset.name}`);
417
+ const extractDir = path.join(dataDir, `.extract-${randomUUID()}`);
418
+ await fs.mkdir(dataDir, { recursive: true });
419
+ try {
420
+ await downloadVerifiedFile({
421
+ url: assetUrl(asset),
422
+ destination: archivePath,
423
+ expectedSha256: asset.sha256,
424
+ signal: options.signal,
425
+ onProgress: options.onProgress
426
+ });
427
+ const serverExtractDir = path.join(extractDir, "server");
428
+ await fs.mkdir(serverExtractDir, { recursive: true });
429
+ const extractedCommand = await extractLlamaServerArchive({
430
+ archivePath,
431
+ destDir: serverExtractDir,
432
+ asset
433
+ });
434
+ const extractedRoot = path.dirname(extractedCommand);
435
+ const dependencies = asset.dependencies ?? [];
436
+ const windowsRuntimeDependencies = [];
437
+ for (const [index, dependency] of dependencies.entries()) if (dependency.archive === "vc-redist") windowsRuntimeDependencies.push({
438
+ dependency,
439
+ index
440
+ });
441
+ else await stageLlamaServerDependency({
442
+ dependency,
443
+ index,
444
+ extractDir,
445
+ extractedRoot,
446
+ options
447
+ });
448
+ options.signal?.throwIfAborted();
449
+ await fs.chmod(extractedCommand, 493);
450
+ if (windowsRuntimeDependencies.length > 0) {
451
+ let version;
452
+ try {
453
+ version = await queryServerVersion(extractedCommand, options.signal);
454
+ } catch (startupError) {
455
+ options.signal?.throwIfAborted();
456
+ try {
457
+ for (const { dependency, index } of windowsRuntimeDependencies) await stageLlamaServerDependency({
458
+ dependency,
459
+ index,
460
+ extractDir,
461
+ extractedRoot,
462
+ options
463
+ });
464
+ } catch (stagingError) {
465
+ options.signal?.throwIfAborted();
466
+ throw formatVcRuntimeFallbackError(startupError, stagingError);
467
+ }
468
+ try {
469
+ version = await queryServerVersion(extractedCommand, options.signal);
470
+ } catch (retryError) {
471
+ options.signal?.throwIfAborted();
472
+ throw formatVcRuntimeFallbackError(startupError, retryError);
473
+ }
474
+ }
475
+ validateServerVersionOutput(extractedCommand, version);
476
+ await validateCudaServer(extractedCommand, asset, options.signal);
477
+ } else await validateInstalledServer(extractedCommand, asset, options.signal);
478
+ await fs.mkdir(path.dirname(installDir), { recursive: true });
479
+ options.signal?.throwIfAborted();
480
+ await fs.rm(installDir, {
481
+ recursive: true,
482
+ force: true
483
+ });
484
+ await fs.rename(extractedRoot, installDir);
485
+ await validateInstalledServer(command, asset, options.signal);
486
+ return command;
487
+ } finally {
488
+ await Promise.all([fs.rm(archivePath, { force: true }), fs.rm(extractDir, {
489
+ recursive: true,
490
+ force: true
491
+ })]);
492
+ }
493
+ }
494
+ function dependencyFiles(dependency) {
495
+ return dependency.archive === "vc-redist" ? dependency.files.map((file) => file.target) : dependency.files;
496
+ }
497
+ async function ensureLlamaServerInstalled(options = {}) {
498
+ options.signal?.throwIfAborted();
499
+ const asset = options.asset ?? selectLlamaServerAsset();
500
+ const key = resolveManagedLlamaServerPaths(asset).command;
501
+ const previous = installationPromises.get(key);
502
+ const pending = Promise.resolve(previous).catch(() => void 0).then(() => installLlamaServer(asset, options)).finally(() => {
503
+ if (installationPromises.get(key) === pending) installationPromises.delete(key);
504
+ });
505
+ installationPromises.set(key, pending);
506
+ return {
507
+ command: previous && options.signal ? await new Promise((resolve, reject) => {
508
+ const signal = options.signal;
509
+ const onAbort = () => reject(toErrorObject(signal?.reason, "Installation cancelled"));
510
+ signal?.addEventListener("abort", onAbort, { once: true });
511
+ pending.then(resolve, reject).finally(() => signal?.removeEventListener("abort", onAbort));
512
+ if (signal?.aborted) onAbort();
513
+ }) : await pending,
514
+ asset
515
+ };
516
+ }
517
+ //#endregion
518
+ //#region extensions/llama-cpp/src/llama-server-preset.ts
519
+ function assertIniValue(value, label) {
520
+ if (/\r|\n/u.test(value)) throw new Error(`${label} cannot contain a newline`);
521
+ return value;
522
+ }
523
+ function normalizePresetName(name) {
524
+ const colon = name.lastIndexOf(":");
525
+ if (colon < 0) return name;
526
+ const tag = name.slice(colon + 1);
527
+ const quantization = /[-.]([a-zA-Z0-9_]+)$/u.exec(tag)?.[1] ?? tag;
528
+ return name.slice(0, colon + 1) + quantization.replace(/[a-z]/g, (char) => char.toUpperCase());
529
+ }
530
+ function readModelSections(contents) {
531
+ const headers = [...contents.matchAll(/(?<![^\r\n])\[[ \t]*([^\]]+)\][ \t]*(?:[;#][^\r\n]*)?(?:\r\n|\n|\r|(?![\s\S]))/g)];
532
+ return {
533
+ header: contents.slice(0, headers[0]?.index ?? contents.length),
534
+ sections: new Map(headers.map((match, index) => [match[1], contents.slice(match.index, headers[index + 1]?.index ?? contents.length)]))
535
+ };
536
+ }
537
+ const PRESET_KEY_ALIASES = {
538
+ m: "model",
539
+ LLAMA_ARG_MODEL: "model",
540
+ c: "ctx-size",
541
+ LLAMA_ARG_CTX_SIZE: "ctx-size",
542
+ n: "n-predict",
543
+ predict: "n-predict",
544
+ LLAMA_ARG_N_PREDICT: "n-predict",
545
+ "no-jinja": "jinja",
546
+ LLAMA_ARG_JINJA: "jinja",
547
+ ub: "ubatch-size",
548
+ LLAMA_ARG_UBATCH: "ubatch-size",
549
+ embeddings: "embedding",
550
+ LLAMA_ARG_EMBEDDINGS: "embedding",
551
+ LLAMA_ARG_MMPROJ: "mmproj",
552
+ mm: "mmproj",
553
+ mmdev: "mmproj-device",
554
+ MTMD_BACKEND_DEVICE: "mmproj-device",
555
+ LLAMA_ARG_IMAGE_MAX_TOKENS: "image-max-tokens",
556
+ np: "parallel",
557
+ LLAMA_ARG_N_PARALLEL: "parallel",
558
+ dev: "device",
559
+ LLAMA_ARG_DEVICE: "device",
560
+ sm: "split-mode",
561
+ LLAMA_ARG_SPLIT_MODE: "split-mode",
562
+ LLAMA_ARG_KV_UNIFIED_PER_SLOT: "kv-unified-per-slot"
563
+ };
564
+ function assertMediaPresetLimits(args, models) {
565
+ const limits = {
566
+ "ctx-size": Math.min(...models.map((model) => model.contextSize)),
567
+ "image-max-tokens": Math.min(...models.map((model) => model.imageMaxTokens)),
568
+ parallel: 1
569
+ };
570
+ for (let index = 0; index < args.length; index++) {
571
+ const [option = "", inlineValue] = args[index].split("=", 2);
572
+ const name = option.replace(/^--?/u, "").replaceAll("_", "-");
573
+ const limit = limits[PRESET_KEY_ALIASES[name] ?? name];
574
+ if (limit === void 0) continue;
575
+ const value = Number(inlineValue ?? args[++index]);
576
+ if (!Number.isInteger(value) || value < 1 || value > limit) throw new Error(`Router option ${option} exceeds the local media limit (${limit}). Lower it or move it into the existing model's preset section, then retry local media setup. Existing configuration is unchanged.`);
577
+ }
578
+ }
579
+ const PRESET_SETTING_PATTERN = /(?<![^\r\n])([a-zA-Z_][a-zA-Z0-9_.-]*)([ \t]*=[ \t]*)([^\r\n]*?)([ \t]*(?:[;#][^\r\n]*)?)(\r\n|\n|\r|(?![\s\S]))/g;
580
+ function readSettingKeys(section) {
581
+ return new Set([...(section ?? "").matchAll(PRESET_SETTING_PATTERN)].map(([, key = ""]) => PRESET_KEY_ALIASES[key] ?? key));
582
+ }
583
+ function readServiceSettingKeys(service) {
584
+ const caseInsensitiveEnv = process.platform === "win32";
585
+ const keys = [...Object.entries(service?.env ?? {}).filter(([, value]) => value !== void 0).map(([key]) => caseInsensitiveEnv ? key.toUpperCase() : key).filter((key) => key.startsWith("LLAMA_ARG_")), ...(service?.args ?? []).filter((arg) => arg.startsWith("-")).map((arg) => arg.startsWith("--") ? arg.slice(2).replaceAll("_", "-") : arg.slice(1))];
586
+ return new Set(keys.map((key) => PRESET_KEY_ALIASES[key] ?? key));
587
+ }
588
+ function updateModelSection(sections, id, values, newline) {
589
+ assertIniValue(id, "llama.cpp model id");
590
+ if (id.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
591
+ const name = [...sections.keys()].filter((candidate) => normalizePresetName(candidate) === normalizePresetName(id)).toSorted((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right))).at(-1) ?? id;
592
+ const pending = new Set(Object.keys(values));
593
+ let contents = (sections.get(name) ?? `[${id}]${newline}`).replace(PRESET_SETTING_PATTERN, (line, key, separator, _value, comment, ending) => {
594
+ const canonical = PRESET_KEY_ALIASES[key] ?? key;
595
+ if (!Object.hasOwn(values, canonical)) return line;
596
+ pending.delete(canonical);
597
+ return `${canonical}${separator}${values[canonical]}${comment}${ending}`;
598
+ });
599
+ for (const key of pending) contents += `${/[\r\n]$/u.test(contents) ? "" : newline}${key} = ${values[key]}${newline}`;
600
+ sections.set(name, contents);
601
+ }
602
+ function buildLlamaServerPreset(existing, params) {
603
+ const newline = existing?.match(/\r\n|\n|\r/u)?.[0] ?? "\n";
604
+ const { header, sections } = readModelSections(existing ?? "version = 1\n\n");
605
+ const configuredIds = params.configuredChatModelIds ? new Set(params.configuredChatModelIds.map(normalizePresetName)) : void 0;
606
+ for (const id of sections.keys()) if (id !== "*" && id !== "embeddinggemma-300m-qat-q8_0" && (params.chatModel.mode === "remove" || configuredIds && !configuredIds.has(normalizePresetName(id)))) sections.delete(id);
607
+ const models = [...params.chatModel.mode === "configure" ? [params.chatModel] : [], ...params.mediaModels ?? []];
608
+ for (const model of models) updateModelSection(sections, model.id, {
609
+ model: assertIniValue(model.path, "llama.cpp model path"),
610
+ "ctx-size": String(model.contextSize ?? 65536),
611
+ "n-predict": String(model.maxTokens ?? 2048),
612
+ jinja: "true",
613
+ ...model.projectorPath ? {
614
+ mmproj: assertIniValue(model.projectorPath, "llama.cpp projector path"),
615
+ "image-max-tokens": String(model.imageMaxTokens ?? 1024),
616
+ parallel: "1",
617
+ "load-on-startup": "false"
618
+ } : {},
619
+ ...model.device ? {
620
+ device: assertIniValue(model.device, "llama.cpp device"),
621
+ "mmproj-device": assertIniValue(model.device, "llama.cpp projector device"),
622
+ "split-mode": "none"
623
+ } : {}
624
+ }, newline);
625
+ const embeddingPath = params.embeddingModelPath ?? (!sections.has("embeddinggemma-300m-qat-q8_0") ? params.defaultEmbeddingModelPath : void 0);
626
+ if (embeddingPath) {
627
+ const configured = /* @__PURE__ */ new Set([
628
+ ...readSettingKeys(sections.get(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID)),
629
+ ...readSettingKeys(sections.get("*")),
630
+ ...readServiceSettingKeys(params.serviceSettings)
631
+ ]);
632
+ const defaults = {
633
+ parallel: "1",
634
+ "ctx-size": String(DEFAULT_LLAMA_CPP_EMBEDDING_CONTEXT_SIZE),
635
+ "ubatch-size": String(DEFAULT_LLAMA_CPP_EMBEDDING_CONTEXT_SIZE)
636
+ };
637
+ if (configured.has("parallel") || configured.has("kv-unified-per-slot")) delete defaults["ctx-size"];
638
+ for (const key of configured) delete defaults[key];
639
+ updateModelSection(sections, DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, {
640
+ model: assertIniValue(embeddingPath, "llama.cpp embedding model path"),
641
+ embedding: "true",
642
+ ...defaults
643
+ }, newline);
644
+ }
645
+ const embeddingSection = sections.get(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID);
646
+ if (!embeddingSection && params.mediaModels === void 0) throw new Error("llama.cpp embedding model path is required for a new managed preset");
647
+ sections.delete(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID);
648
+ const orderedSections = [...[...sections].toSorted(([left], [right]) => Number(left > right) - Number(left < right)).map(([, section]) => section), ...embeddingSection ? [embeddingSection] : []];
649
+ return header + (header && !/[\r\n]$/u.test(header) ? newline : "") + orderedSections.map((section) => section.replace(/[\r\n]+$/u, "")).join(newline + newline) + newline;
650
+ }
651
+ //#endregion
652
+ //#region extensions/llama-cpp/src/managed-server-orphans.ts
653
+ const log = createSubsystemLogger("llama-cpp");
654
+ const recoveries = /* @__PURE__ */ new Map();
655
+ function readUniqueArgument(argv, name) {
656
+ const values = argv.flatMap((argument, index) => {
657
+ if (argument === name) {
658
+ const value = argv[index + 1];
659
+ return value === void 0 ? [] : [value];
660
+ }
661
+ return argument.startsWith(`${name}=`) ? [argument.slice(name.length + 1)] : [];
662
+ });
663
+ return values.length === 1 ? values[0] : void 0;
664
+ }
665
+ /** A new host process recovers once; in-process restarts retain that host's children. */
666
+ async function recoverManagedLlamaServer(params) {
667
+ params.signal?.throwIfAborted();
668
+ if (!findManagedLlamaServerAsset(params.command)) return;
669
+ const args = params.args ?? [];
670
+ const preset = readUniqueArgument(args, "--models-preset");
671
+ const host = readUniqueArgument(args, "--host");
672
+ if (!preset || !host || readUniqueArgument(args, "--port") !== String(params.port)) return;
673
+ const required = /* @__PURE__ */ new Map([
674
+ ["--port", String(params.port)],
675
+ ["--models-preset", preset],
676
+ ["--host", host]
677
+ ]);
678
+ const cwd = !path.isAbsolute(preset) ? path.resolve(params.cwd ?? process.cwd()) : void 0;
679
+ const key = JSON.stringify([
680
+ params.command,
681
+ [...required],
682
+ cwd
683
+ ]);
684
+ let recovery = recoveries.get(key);
685
+ if (!recovery) {
686
+ recovery = (async () => {
687
+ const { reapOrphanedProcesses } = await import("openclaw/plugin-sdk/process-runtime");
688
+ await reapOrphanedProcesses({
689
+ command: params.command,
690
+ cwd,
691
+ matchesArguments: (argv) => [...required].every(([name, value]) => readUniqueArgument(argv, name) === value),
692
+ signal: params.signal,
693
+ onReap: (pid) => log.info(`reaping orphaned managed llama-server: pid=${pid} port=${params.port}`)
694
+ });
695
+ })().catch((error) => {
696
+ recoveries.delete(key);
697
+ throw error;
698
+ });
699
+ recoveries.set(key, recovery);
700
+ }
701
+ await recovery;
702
+ params.signal?.throwIfAborted();
703
+ }
704
+ //#endregion
705
+ //#region extensions/llama-cpp/src/managed-server.ts
706
+ const modelPromises = /* @__PURE__ */ new Map();
707
+ const resolvedModelArtifacts = /* @__PURE__ */ new Map();
708
+ const presetState = {
709
+ appliedRevisions: /* @__PURE__ */ new Map(),
710
+ desiredRevisions: /* @__PURE__ */ new Map()
711
+ };
712
+ const runPresetTransition = createAsyncLock();
713
+ const LLAMA_CPP_PRESET_RELOAD_TIMEOUT_MS = 15e3;
714
+ function parseHuggingFaceSource(source) {
715
+ const [pathPart, revisionPart] = source.replace(/^(?:hf|huggingface):(?:\/\/)?/iu, "").split("#", 2);
716
+ const [user, repositoryWithTag, ...fileParts] = (pathPart ?? "").split("/");
717
+ const [repository, ...tagParts] = (repositoryWithTag ?? "").split(":");
718
+ if (!user || !repository) throw new Error(`Invalid Hugging Face model URI: ${source}`);
719
+ return {
720
+ user,
721
+ repository,
722
+ file: fileParts.length > 0 ? fileParts.join("/") : void 0,
723
+ revision: revisionPart || "main",
724
+ tag: tagParts.length > 0 ? tagParts.join(":") : void 0
725
+ };
726
+ }
727
+ async function resolveHuggingFaceArtifact(source, signal) {
728
+ const parsed = parseHuggingFaceSource(source);
729
+ let file = parsed.file;
730
+ let expectedSize;
731
+ if (!file) {
732
+ const tag = parsed.tag || "latest";
733
+ const manifestUrl = `https://huggingface.co/v2/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/manifests/${encodeURIComponent(tag)}`;
734
+ const { response, release } = await fetchWithSsrFGuard({
735
+ url: manifestUrl,
736
+ init: { headers: { "user-agent": "llama-cpp" } },
737
+ signal,
738
+ requireHttps: true,
739
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(manifestUrl),
740
+ auditContext: "llama-cpp-model-resolve"
741
+ });
742
+ try {
743
+ if (!response.ok) throw new Error(`Cannot resolve ${source}: HTTP ${response.status}`);
744
+ const ggufFile = asOptionalRecord(asOptionalRecord(await readProviderJsonResponse(response, "llama.cpp Hugging Face manifest"))?.ggufFile);
745
+ file = typeof ggufFile?.rfilename === "string" ? ggufFile.rfilename : void 0;
746
+ expectedSize = typeof ggufFile?.size === "number" ? ggufFile.size : void 0;
747
+ if (!file) throw new Error(`Hugging Face did not return a GGUF file for ${source}`);
748
+ } finally {
749
+ await release();
750
+ }
751
+ }
752
+ const encodedFile = file.split("/").map(encodeURIComponent).join("/");
753
+ const url = `https://huggingface.co/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/resolve/${encodeURIComponent(parsed.revision)}/${encodedFile}?download=true`;
754
+ const fileInfoUrl = `https://huggingface.co/api/models/${encodeURIComponent(parsed.user)}/${encodeURIComponent(parsed.repository)}/paths-info/${encodeURIComponent(parsed.revision)}`;
755
+ const { response: fileInfoResponse, release: releaseFileInfo } = await fetchWithSsrFGuard({
756
+ url: fileInfoUrl,
757
+ init: {
758
+ method: "POST",
759
+ headers: {
760
+ "content-type": "application/json",
761
+ "user-agent": "llama-cpp"
762
+ },
763
+ body: JSON.stringify({
764
+ paths: [file],
765
+ expand: false
766
+ })
767
+ },
768
+ signal,
769
+ requireHttps: true,
770
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(fileInfoUrl),
771
+ auditContext: "llama-cpp-model-resolve"
772
+ });
773
+ let fileInfo;
774
+ try {
775
+ if (!fileInfoResponse.ok) throw new Error(`Cannot read Hugging Face integrity metadata for ${source}: HTTP ${fileInfoResponse.status}`);
776
+ fileInfo = await readProviderJsonResponse(fileInfoResponse, "llama.cpp Hugging Face file metadata");
777
+ } finally {
778
+ await releaseFileInfo();
779
+ }
780
+ const fileRow = Array.isArray(fileInfo) ? fileInfo.map((entry) => asOptionalRecord(entry)).find((entry) => entry?.path === file) : void 0;
781
+ const lfs = asOptionalRecord(fileRow?.lfs);
782
+ const expectedSha256 = typeof lfs?.oid === "string" && /^[a-f\d]{64}$/iu.test(lfs.oid) ? lfs.oid.toLowerCase() : void 0;
783
+ expectedSize = expectedSize ?? (typeof fileRow?.size === "number" ? fileRow.size : void 0);
784
+ if (!expectedSha256) throw new Error(`Hugging Face did not publish a SHA-256 LFS identity for ${source}`);
785
+ return {
786
+ fileName: `hf_${[
787
+ parsed.user,
788
+ parsed.repository,
789
+ parsed.revision === "main" ? "" : parsed.revision,
790
+ ...file.split("/")
791
+ ].filter(Boolean).join("_").replace(/[^a-z\d._-]+/giu, "_")}`,
792
+ url,
793
+ expectedSize,
794
+ expectedSha256
795
+ };
796
+ }
797
+ function defaultArtifact(source) {
798
+ const recipe = resolveLlamaCppCatalogArtifact(source) ?? resolveLlamaCppMediaArtifact(source);
799
+ if (recipe) return recipe;
800
+ if (source === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") return {
801
+ fileName: DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE,
802
+ 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`,
803
+ expectedSize: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES,
804
+ expectedSha256: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256
805
+ };
806
+ }
807
+ async function assertGguf(filePath) {
808
+ const handle = await fs.open(filePath, "r").catch((error) => {
809
+ 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 });
810
+ throw error;
811
+ });
812
+ try {
813
+ const header = Buffer.alloc(4);
814
+ const { bytesRead } = await handle.read(header, 0, header.length, 0);
815
+ if (bytesRead !== 4 || header.toString("ascii") !== "GGUF") throw new Error(`Model is not a GGUF file: ${filePath}`);
816
+ } finally {
817
+ await handle.close();
818
+ }
819
+ }
820
+ async function resolveModelArtifact(source, signal) {
821
+ const known = defaultArtifact(source);
822
+ if (known) return known;
823
+ if (/^(?:hf|huggingface):/iu.test(source)) return await resolveHuggingFaceArtifact(source, signal);
824
+ if (/^https:\/\//iu.test(source)) {
825
+ const url = new URL(source);
826
+ const fileName = path.basename(decodeURIComponent(url.pathname));
827
+ if (!fileName.toLowerCase().includes(".gguf")) throw new Error(`Remote model URL must name a GGUF file: ${source}`);
828
+ return {
829
+ fileName,
830
+ url: source
831
+ };
832
+ }
833
+ throw new Error(`Unsupported remote model URI: ${source}`);
834
+ }
835
+ async function resolveCachedModelArtifact(source, cacheDir, signal) {
836
+ const key = `${path.resolve(cacheDir)}\0${source}`;
837
+ const artifact = resolvedModelArtifacts.get(key) ?? await resolveModelArtifact(source, signal);
838
+ resolvedModelArtifacts.set(key, artifact);
839
+ return artifact;
840
+ }
841
+ async function resolveLlamaCppModelDownloadSize(source, cacheDir, signal) {
842
+ const artifact = await resolveCachedModelArtifact(source, cacheDir, signal);
843
+ if (artifact.expectedSize !== void 0) return artifact.expectedSize;
844
+ const result = await fetchWithSsrFGuard({
845
+ url: artifact.url,
846
+ init: { method: "HEAD" },
847
+ signal,
848
+ requireHttps: true,
849
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(artifact.url),
850
+ auditContext: "llama-cpp-model-resolve"
851
+ }).catch(() => {
852
+ signal?.throwIfAborted();
853
+ });
854
+ if (!result) return;
855
+ const { response, release } = result;
856
+ try {
857
+ const size = response.ok ? Number(response.headers.get("content-length")) : 0;
858
+ return Number.isSafeInteger(size) && size > 0 ? size : void 0;
859
+ } finally {
860
+ await release();
861
+ }
862
+ }
863
+ async function ensureLlamaCppModel(params) {
864
+ params.signal?.throwIfAborted();
865
+ const localSource = resolveHomePath(params.source);
866
+ if (!/^(?:hf|huggingface|https):/iu.test(localSource)) {
867
+ const localPath = path.isAbsolute(localSource) ? localSource : path.resolve(params.cacheDir, localSource);
868
+ await assertGguf(localPath);
869
+ return localPath;
870
+ }
871
+ const artifact = await resolveCachedModelArtifact(localSource, params.cacheDir, params.signal);
872
+ const destination = path.join(params.cacheDir, artifact.fileName);
873
+ const load = modelPromises.get(destination) ?? (async () => {
874
+ const exists = await fs.stat(destination).then((stat) => stat.isFile()).catch(() => false);
875
+ if (exists && artifact.expectedSha256 && (artifact.expectedSize === void 0 || (await fs.stat(destination)).size === artifact.expectedSize) && await sha256File$1(destination, params.signal) === artifact.expectedSha256) {
876
+ await assertGguf(destination);
877
+ return destination;
878
+ }
879
+ if (exists && !artifact.expectedSha256) {
880
+ await assertGguf(destination);
881
+ return destination;
882
+ }
883
+ if (!params.download) {
884
+ const repair = resolveLlamaCppMediaArtifact(localSource) ? " Run openclaw models auth login --provider llama-cpp --method local-media to download and verify the missing or invalid artifact." : "";
885
+ throw new Error(`Model is not cached at ${destination}.${repair}`);
886
+ }
887
+ await downloadVerifiedFile({
888
+ url: artifact.url,
889
+ destination,
890
+ expectedSha256: artifact.expectedSha256,
891
+ expectedSize: artifact.expectedSize,
892
+ requireServerDigest: !artifact.expectedSha256,
893
+ signal: params.signal,
894
+ onProgress: params.onProgress
895
+ });
896
+ await assertGguf(destination);
897
+ return destination;
898
+ })();
899
+ modelPromises.set(destination, load);
900
+ try {
901
+ return await load;
902
+ } finally {
903
+ if (modelPromises.get(destination) === load) modelPromises.delete(destination);
904
+ }
905
+ }
906
+ async function writePreset(presetPath, contents) {
907
+ await fs.mkdir(path.dirname(presetPath), { recursive: true });
908
+ const temporary = `${presetPath}.tmp-${randomUUID()}`;
909
+ try {
910
+ await fs.writeFile(temporary, contents, { mode: 384 });
911
+ await fs.rename(temporary, presetPath);
912
+ } finally {
913
+ await fs.rm(temporary, { force: true });
914
+ }
915
+ }
916
+ async function updatePreset(presetPath, params) {
917
+ await runPresetTransition(async () => {
918
+ const existing = await fs.readFile(presetPath, "utf8").catch((error) => {
919
+ if (asOptionalRecord(error)?.code === "ENOENT") return;
920
+ throw error;
921
+ });
922
+ const next = buildLlamaServerPreset(existing ?? params.initialContents, params);
923
+ if (next !== existing) await writePreset(presetPath, next);
924
+ if (params.reconcileOrigin) presetState.desiredRevisions.set(params.reconcileOrigin, `${presetPath}\0${next}`);
925
+ });
926
+ }
927
+ async function reconcileManagedLlamaServer(params) {
928
+ await runPresetTransition(async () => {
929
+ const origin = new URL(params.baseUrl).origin;
930
+ const revision = presetState.desiredRevisions.get(origin);
931
+ if (!revision || presetState.appliedRevisions.get(origin) === revision) return;
932
+ const { response, release } = await fetchConfiguredLocalOriginWithSsrFGuard({
933
+ url: `${origin}/models?reload=1`,
934
+ configuredLocalOriginBaseUrl: origin,
935
+ policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(origin),
936
+ signal: params.signal,
937
+ timeoutMs: LLAMA_CPP_PRESET_RELOAD_TIMEOUT_MS,
938
+ auditContext: "llama-server-preset-reload"
939
+ });
940
+ try {
941
+ if (!response.ok) throw new Error(`llama.cpp preset reload failed: HTTP ${response.status}`);
942
+ presetState.appliedRevisions.set(origin, revision);
943
+ } finally {
944
+ await release();
945
+ }
946
+ });
947
+ }
948
+ async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT) {
949
+ const tryPort = async (port) => await new Promise((resolve) => {
950
+ const server = net.createServer();
951
+ server.unref();
952
+ server.once("error", () => resolve(void 0));
953
+ server.listen(port, "127.0.0.1", () => {
954
+ const address = server.address();
955
+ const selected = typeof address === "object" && address ? address.port : void 0;
956
+ server.close(() => resolve(selected));
957
+ });
958
+ });
959
+ return await tryPort(preferred) ?? await tryPort(0) ?? Promise.reject(/* @__PURE__ */ new Error("No loopback port is available for llama-server"));
960
+ }
961
+ function resolveLlamaCppPresetPath(service) {
962
+ const args = service?.args ?? [];
963
+ return args.find((arg) => arg.startsWith("--models-preset="))?.slice(16) ?? args.find((_, index) => args[index - 1] === "--models-preset") ?? service?.env?.LLAMA_ARG_MODELS_PRESET;
964
+ }
965
+ async function prepareManagedLlamaServer(params) {
966
+ params.signal?.throwIfAborted();
967
+ let command = params.asset ? void 0 : params.localService?.command;
968
+ const asset = command === void 0 ? params.asset : findManagedLlamaServerAsset(command);
969
+ if (command !== void 0 && asset) try {
970
+ await fs.stat(command);
971
+ } catch (error) {
972
+ if (asOptionalRecord(error)?.code !== "ENOENT") throw error;
973
+ command = void 0;
974
+ }
975
+ command ??= (await ensureLlamaServerInstalled({
976
+ asset,
977
+ signal: params.signal,
978
+ onProgress: params.onProgress
979
+ })).command;
980
+ params.signal?.throwIfAborted();
981
+ const port = params.port ?? await findAvailableLlamaServerPort(params.isolated ? 0 : void 0);
982
+ const rootUrl = `http://127.0.0.1:${port}`;
983
+ const reconcileOrigin = params.reconcileBaseUrl ? new URL(params.reconcileBaseUrl).origin : rootUrl;
984
+ const endpoint = {
985
+ command,
986
+ baseUrl: `${rootUrl}/v1`,
987
+ healthUrl: (!params.isolated ? params.localService?.healthUrl : void 0) ?? `${rootUrl}/health`
988
+ };
989
+ const configuredPreset = resolveLlamaCppPresetPath(params.localService);
990
+ if (params.localService && !params.isolated) await recoverManagedLlamaServer({
991
+ command,
992
+ port,
993
+ cwd: params.localService.cwd,
994
+ args: params.localService.args,
995
+ signal: params.signal
996
+ });
997
+ if (params.localService && !configuredPreset && !params.isolated) {
998
+ await runPresetTransition(async () => {
999
+ presetState.desiredRevisions.delete(reconcileOrigin);
1000
+ presetState.appliedRevisions.delete(reconcileOrigin);
1001
+ });
1002
+ return {
1003
+ ...endpoint,
1004
+ args: params.localService.args ?? []
1005
+ };
1006
+ }
1007
+ const defaultPreset = configuredPreset ? path.resolve(params.localService?.cwd ?? process.cwd(), configuredPreset) : resolveManagedLlamaServerPaths(params.asset).presetPath;
1008
+ const presetPath = params.isolated ? path.join(path.dirname(defaultPreset), `models-${randomUUID()}.ini`) : defaultPreset;
1009
+ const initialContents = params.isolated && params.mediaModels ? await fs.readFile(defaultPreset, "utf8").catch((error) => {
1010
+ if (!configuredPreset && asOptionalRecord(error)?.code === "ENOENT") return;
1011
+ throw error;
1012
+ }) : void 0;
1013
+ params.signal?.throwIfAborted();
1014
+ try {
1015
+ await updatePreset(presetPath, {
1016
+ chatModel: params.chatModel,
1017
+ configuredChatModelIds: params.configuredChatModelIds,
1018
+ embeddingModelPath: params.embeddingModelPath,
1019
+ defaultEmbeddingModelPath: params.defaultEmbeddingModelPath,
1020
+ reconcileOrigin: params.isolated ? void 0 : reconcileOrigin,
1021
+ mediaModels: params.mediaModels,
1022
+ serviceSettings: params.isolated && !params.mediaModels ? { env: process.env } : {
1023
+ args: params.localService?.args,
1024
+ env: {
1025
+ ...process.env,
1026
+ ...params.localService?.env
1027
+ }
1028
+ },
1029
+ initialContents
1030
+ });
1031
+ params.signal?.throwIfAborted();
1032
+ } catch (error) {
1033
+ if (params.isolated) await fs.rm(presetPath, { force: true });
1034
+ throw error;
1035
+ }
1036
+ return {
1037
+ ...endpoint,
1038
+ args: params.localService && !params.isolated ? params.localService.args ?? [] : params.mediaModels && params.localService ? buildIsolatedMediaRouterArgs(params.localService.args ?? [], port, presetPath) : [
1039
+ "--host",
1040
+ "127.0.0.1",
1041
+ "--port",
1042
+ String(port),
1043
+ "--models-preset",
1044
+ presetPath,
1045
+ "--models-max",
1046
+ String(params.modelsMax ?? 2),
1047
+ "--metrics",
1048
+ "--no-ui"
1049
+ ]
1050
+ };
1051
+ }
1052
+ function buildIsolatedMediaRouterArgs(args, port, preset) {
1053
+ const values = /* @__PURE__ */ new Map([
1054
+ ["--host", "127.0.0.1"],
1055
+ ["--port", String(port)],
1056
+ ["--models-preset", preset],
1057
+ ["--models-max", "1"]
1058
+ ]);
1059
+ const result = [];
1060
+ for (let index = 0; index < args.length; index++) {
1061
+ const arg = args[index];
1062
+ const key = arg.split("=", 1)[0];
1063
+ if (values.has(key)) {
1064
+ if (!arg.includes("=")) index++;
1065
+ } else result.push(arg);
1066
+ }
1067
+ return [...result, ...[...values].flat()];
1068
+ }
1069
+ async function ensureManagedLlamaServerForChat(params) {
1070
+ if (!params.provider.localService || !params.provider.baseUrl) return;
1071
+ const cacheDir = resolveLlamaCppModelCacheDir(params.provider);
1072
+ let chatModelPath = resolveCachedLlamaCppModelPath({
1073
+ model: params.model,
1074
+ provider: params.provider
1075
+ });
1076
+ if (!chatModelPath && resolveLlamaCppModelSource(params.model) === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") {
1077
+ const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
1078
+ if (await fs.stat(legacy).then((stat) => stat.isFile()).catch(() => false)) chatModelPath = legacy;
1079
+ }
1080
+ chatModelPath = await ensureLlamaCppModel({
1081
+ source: chatModelPath ?? resolveLlamaCppModelSource(params.model),
1082
+ cacheDir,
1083
+ download: false,
1084
+ signal: params.signal
1085
+ });
1086
+ const projectorSource = params.model.params?.mmprojPath;
1087
+ const projectorPath = typeof projectorSource === "string" ? await ensureLlamaCppModel({
1088
+ source: projectorSource,
1089
+ cacheDir,
1090
+ download: false,
1091
+ signal: params.signal
1092
+ }) : void 0;
1093
+ const configuredContext = params.model.params?.contextSize;
1094
+ const port = Number(new URL(params.provider.baseUrl).port);
1095
+ await prepareManagedLlamaServer({
1096
+ chatModel: {
1097
+ mode: "configure",
1098
+ id: params.model.id,
1099
+ path: chatModelPath,
1100
+ contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : params.model.contextTokens,
1101
+ maxTokens: params.model.maxTokens,
1102
+ ...projectorPath ? { projectorPath } : {},
1103
+ ...typeof params.model.params?.imageMaxTokens === "number" ? { imageMaxTokens: params.model.params.imageMaxTokens } : {},
1104
+ ...typeof params.model.params?.device === "string" ? { device: params.model.params.device } : {}
1105
+ },
1106
+ configuredChatModelIds: params.provider.models.map((model) => model.id),
1107
+ ...params.provider.params?.mediaModels ? { mediaModels: [] } : { defaultEmbeddingModelPath: path.join(cacheDir, DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE) },
1108
+ port: Number.isInteger(port) && port > 0 ? port : void 0,
1109
+ reconcileBaseUrl: params.provider.baseUrl,
1110
+ localService: params.provider.localService,
1111
+ signal: params.signal
1112
+ });
1113
+ }
1114
+ //#endregion
1115
+ export { ensureLlamaCppModel, ensureManagedLlamaServerForChat, UnsupportedLlamaServerHostError as n, prepareManagedLlamaServer, ensureLlamaServerInstalled as r, reconcileManagedLlamaServer, resolveLlamaCppModelDownloadSize, resolveLlamaCppPresetPath, assertMediaPresetLimits as t };