@openclaw/llama-cpp-provider 2026.10.10 → 2026.11.5-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.
@@ -1,23 +1,230 @@
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-D8fdQAQN.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-CoQoxXtb.mjs";
1
+ import { 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, 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-B-3wLNsP.mjs";
2
+ import { a as resolveLlamaCppCatalogArtifact, r as resolveLlamaCppMediaArtifact } from "./media-catalog-D-CRqGbe.mjs";
3
3
  import path from "node:path";
4
4
  import { asOptionalRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
5
5
  import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
6
6
  import { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } from "openclaw/plugin-sdk/ssrf-runtime";
7
7
  import { fetchConfiguredLocalOriginWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime-internal";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
- import fs from "node:fs/promises";
9
+ import fsp from "node:fs/promises";
10
10
  import net from "node:net";
11
11
  import { createAsyncLock } from "openclaw/plugin-sdk/async-lock-runtime";
12
+ import { createSubsystemLogger } from "openclaw/plugin-sdk/logging-core";
12
13
  import { execFile } from "node:child_process";
13
- import fs$1, { constants, createWriteStream } from "node:fs";
14
+ import fs, { createWriteStream } from "node:fs";
15
+ import { pipeline } from "node:stream/promises";
14
16
  import { sha256File } from "@openclaw/fs-safe/durability";
17
+ import { ARCHIVE_LIMIT_ERROR_CODE, ArchiveLimitError, extractArchive } from "openclaw/plugin-sdk/archive";
15
18
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
16
19
  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
- // extensions/llama-cpp/src/llama-server-extract.ts
20
+ import { racePromiseWithAbortSignal } from "openclaw/plugin-sdk/time-runtime";
21
+ // extensions/llama-cpp/src/llama-server-assets.ts
22
+ const LLAMA_SERVER_RELEASE = "b10809";
23
+ const LLAMA_SERVER_COMMIT = "5266f24da75dc449bd56cbed7addb9c8e4a6a73e";
24
+ const MEBIBYTE$1 = 1048576;
25
+ const CUDA_ARCHIVE_LIMITS = {
26
+ maxArchiveBytes: 400 * MEBIBYTE$1,
27
+ maxExtractedBytes: 600 * MEBIBYTE$1,
28
+ maxEntryBytes: 521 * MEBIBYTE$1
29
+ };
30
+ const WINDOWS_X64_VC_RUNTIME = {
31
+ archive: "vc-redist",
32
+ name: "VC_redist.x64.exe",
33
+ url: "https://download.visualstudio.microsoft.com/download/pr/ebdab8e5-1d7b-4d9f-a11b-cbb1720c3b12/843068991DAAA1F73AD9F6239BCE4D0F6A07A51F18C37EA2A867E9BECA71295C/VC_redist.x64.exe",
34
+ sha256: "843068991daaa1f73ad9f6239bce4d0f6a07a51f18c37ea2a867e9beca71295c",
35
+ size: 18731856,
36
+ containerOffset: 63e4,
37
+ containerSize: 18091661,
38
+ nestedCabinet: "a4",
39
+ files: [
40
+ {
41
+ source: "msvcp140.dll_amd64",
42
+ target: "msvcp140.dll"
43
+ },
44
+ {
45
+ source: "vcruntime140.dll_amd64",
46
+ target: "vcruntime140.dll"
47
+ },
48
+ {
49
+ source: "vcruntime140_1.dll_amd64",
50
+ target: "vcruntime140_1.dll"
51
+ }
52
+ ]
53
+ };
54
+ const WINDOWS_ARM64_VC_RUNTIME = {
55
+ archive: "vc-redist",
56
+ name: "VC_redist.arm64.exe",
57
+ url: "https://download.visualstudio.microsoft.com/download/pr/ece44298-3977-4f73-ab91-c13fe79cfea8/B70EF586669A620A0A30A1156969C05C6A3831DC8F8BC992DA75779D2A92F944/VC_redist.arm64.exe",
58
+ sha256: "b70ef586669a620a0a30a1156969c05c6a3831dc8f8bc992da75779d2a92f944",
59
+ size: 11870816,
60
+ containerOffset: 684112,
61
+ containerSize: 11176508,
62
+ nestedCabinet: "a1",
63
+ files: [{
64
+ source: "msvcp140.dll_arm64",
65
+ target: "msvcp140.dll"
66
+ }, {
67
+ source: "vcruntime140.dll_arm64",
68
+ target: "vcruntime140.dll"
69
+ }]
70
+ };
71
+ const MACOS_ALIASES = [
72
+ ["libggml-rpc.0.23.0.dylib", ["libggml-rpc.0.dylib", "libggml-rpc.dylib"]],
73
+ ["libllama.0.4.0.dylib", ["libllama.0.dylib", "libllama.dylib"]],
74
+ ["libmtmd.0.4.0.dylib", ["libmtmd.0.dylib", "libmtmd.dylib"]],
75
+ ["libggml.0.23.0.dylib", ["libggml.0.dylib", "libggml.dylib"]],
76
+ ["libggml-base.0.23.0.dylib", ["libggml-base.0.dylib", "libggml-base.dylib"]],
77
+ ["libggml-blas.0.23.0.dylib", ["libggml-blas.0.dylib", "libggml-blas.dylib"]],
78
+ ["libllama-common.0.4.0.dylib", ["libllama-common.0.dylib", "libllama-common.dylib"]],
79
+ ["libggml-cpu.0.23.0.dylib", ["libggml-cpu.0.dylib", "libggml-cpu.dylib"]]
80
+ ];
81
+ const MACOS_METAL_ALIASES = [...MACOS_ALIASES, ["libggml-metal.0.23.0.dylib", ["libggml-metal.0.dylib", "libggml-metal.dylib"]]];
82
+ const LINUX_ALIASES = [
83
+ ["libllama.so.0.4.0", ["libllama.so.0", "libllama.so"]],
84
+ ["libggml.so.0.23.0", ["libggml.so.0", "libggml.so"]],
85
+ ["libmtmd.so.0.4.0", ["libmtmd.so.0", "libmtmd.so"]],
86
+ ["libggml-base.so.0.23.0", ["libggml-base.so.0", "libggml-base.so"]],
87
+ ["libllama-common.so.0.4.0", ["libllama-common.so.0", "libllama-common.so"]]
88
+ ];
89
+ const LLAMA_SERVER_ASSETS = [
90
+ {
91
+ platform: "darwin",
92
+ arch: "arm64",
93
+ backend: "metal",
94
+ archive: "tar.gz",
95
+ archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
96
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-arm64.tar.gz`,
97
+ sha256: "7d692df9e1e386e62f1c12b843903218041e6cd74c9415aa39a7ed3176f9eaa2",
98
+ sizeBytes: 11123196,
99
+ executable: "llama-server",
100
+ regularFileAliases: MACOS_METAL_ALIASES
101
+ },
102
+ {
103
+ platform: "darwin",
104
+ arch: "x64",
105
+ backend: "cpu",
106
+ archive: "tar.gz",
107
+ archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
108
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-x64.tar.gz`,
109
+ sha256: "13b34aa8a5d87341a21065a83f54a8167e1aaa6fe0d66065de01632a1ed64be6",
110
+ sizeBytes: 11175330,
111
+ executable: "llama-server",
112
+ regularFileAliases: MACOS_ALIASES
113
+ },
114
+ {
115
+ platform: "linux",
116
+ arch: "arm64",
117
+ backend: "cpu",
118
+ archive: "tar.gz",
119
+ archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
120
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-arm64.tar.gz`,
121
+ sha256: "f2b7333971e1b7b42e9268bfdbfa30f5f56e2897156084d2251385df94aec358",
122
+ sizeBytes: 13380118,
123
+ executable: "llama-server",
124
+ regularFileAliases: LINUX_ALIASES
125
+ },
126
+ {
127
+ platform: "linux",
128
+ arch: "x64",
129
+ backend: "cpu",
130
+ archive: "tar.gz",
131
+ archiveRoot: `llama-${LLAMA_SERVER_RELEASE}`,
132
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-x64.tar.gz`,
133
+ sha256: "5e34434ddc6d03cd1584f403201aff0d4bd1a5793a72ff7e286532dfd1e4b941",
134
+ sizeBytes: 16734586,
135
+ executable: "llama-server",
136
+ regularFileAliases: LINUX_ALIASES
137
+ },
138
+ {
139
+ platform: "win32",
140
+ arch: "x64",
141
+ backend: "cuda",
142
+ archive: "zip",
143
+ archiveRoot: ".",
144
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cuda-12.4-x64.zip`,
145
+ sha256: "c77bfcd9ed8d91e8721a2d6a290b907fddd4fa5412a47b21c6fa1709116b85f9",
146
+ sizeBytes: 253938543,
147
+ executable: "llama-server.exe",
148
+ regularFileAliases: [],
149
+ limits: CUDA_ARCHIVE_LIMITS,
150
+ dependencies: [{
151
+ archive: "zip",
152
+ archiveRoot: ".",
153
+ name: "cudart-llama-bin-win-cuda-12.4-x64.zip",
154
+ sha256: "8c79a9b226de4b3cacfd1f83d24f962d0773be79f1e7b75c6af4ded7e32ae1d6",
155
+ sizeBytes: 391443627,
156
+ regularFileAliases: [],
157
+ files: [
158
+ "cublas64_12.dll",
159
+ "cublasLt64_12.dll",
160
+ "cudart64_12.dll"
161
+ ],
162
+ limits: {
163
+ ...CUDA_ARCHIVE_LIMITS,
164
+ maxEntries: 3
165
+ }
166
+ }, WINDOWS_X64_VC_RUNTIME]
167
+ },
168
+ {
169
+ platform: "win32",
170
+ arch: "arm64",
171
+ backend: "cpu",
172
+ archive: "zip",
173
+ archiveRoot: ".",
174
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-arm64.zip`,
175
+ sha256: "c1058fe5764a687275c8d20d6bbc1454e787cdbb8ebb8c37a2f959f2b144dc77",
176
+ sizeBytes: 11974499,
177
+ executable: "llama-server.exe",
178
+ regularFileAliases: [],
179
+ dependencies: [WINDOWS_ARM64_VC_RUNTIME]
180
+ },
181
+ {
182
+ platform: "win32",
183
+ arch: "x64",
184
+ backend: "cpu",
185
+ archive: "zip",
186
+ archiveRoot: ".",
187
+ name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-x64.zip`,
188
+ sha256: "9df3158ed228a641a4b127942d7f459f24c9e13f04682659d05c00c80099b6b5",
189
+ sizeBytes: 18407457,
190
+ executable: "llama-server.exe",
191
+ regularFileAliases: [],
192
+ dependencies: [WINDOWS_X64_VC_RUNTIME]
193
+ }
194
+ ];
195
+ function selectLlamaServerAsset(platform = process.platform, arch = process.arch, acceleration) {
196
+ const backend = acceleration?.kind ?? (platform === "darwin" && arch === "arm64" ? "metal" : "cpu");
197
+ if (backend === "cuda" && acceleration?.kind === "cuda") {
198
+ 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.`);
199
+ if (!(acceleration.devices.length > 0 && acceleration.devices.every((device) => {
200
+ const version = /^(\d+)\.(\d+)(?:\.\d+)?$/u.exec(device.driverVersion);
201
+ return version && (Number(version[1]) > 551 || Number(version[1]) === 551 && Number(version[2]) >= 78) && (device.computeCapability === void 0 || device.computeCapability >= 5);
202
+ }))) 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.");
203
+ }
204
+ const asset = LLAMA_SERVER_ASSETS.find((candidate) => candidate.platform === platform && candidate.arch === arch && candidate.backend === backend);
205
+ 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.`);
206
+ return asset;
207
+ }
208
+ function resolveManagedLlamaServerPaths(asset = selectLlamaServerAsset()) {
209
+ const installDir = path.join(resolveLlamaCppDataDir(), LLAMA_SERVER_RELEASE, `${asset.platform}-${asset.arch}${asset.backend === "cuda" ? "-cuda-12.4" : ""}`);
210
+ return {
211
+ installDir,
212
+ command: path.join(installDir, asset.executable),
213
+ presetPath: path.join(resolveLlamaCppDataDir(), "models.ini")
214
+ };
215
+ }
216
+ function findManagedLlamaServerAsset(command, platform = process.platform, arch = process.arch) {
217
+ return LLAMA_SERVER_ASSETS.find((asset) => asset.platform === platform && asset.arch === arch && resolveManagedLlamaServerPaths(asset).command === command);
218
+ }
219
+ // extensions/llama-cpp/src/runtime-error.ts
220
+ function formatLlamaServerRuntimeError(error) {
221
+ const cause = error instanceof Error ? error : new Error(String(error));
222
+ const library = cause.message.match(/error while loading shared libraries: ([\w.+-]+):/u)?.[1];
223
+ if (!library) return cause;
224
+ const runtime = /^lib(?:ssl|crypto)\.so\.3$/u.test(library) ? "OpenSSL 3 (libssl3t64 or libssl3 on Debian/Ubuntu)" : library.startsWith("libgomp.so.") ? "OpenMP (libgomp1 on Debian/Ubuntu or libgomp on Fedora)" : library;
225
+ return new Error(`Missing llama-server shared library ${library}. Install the ${runtime} runtime using your system package manager, then rerun llama.cpp setup. Detail: ${cause.message}`, { cause });
226
+ }
227
+ // extensions/llama-cpp/src/llama-server-install.ts
21
228
  const MEBIBYTE = 1048576;
22
229
  const LLAMA_ARCHIVE_LIMITS = {
23
230
  maxArchiveBytes: 256 * MEBIBYTE,
@@ -27,37 +234,24 @@ const LLAMA_ARCHIVE_LIMITS = {
27
234
  maxMetaEntryBytes: MEBIBYTE
28
235
  };
29
236
  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}`);
237
+ const CAB_HEADER_SIZE = 12;
238
+ const EXPAND_TIMEOUT_MS = 6e4;
239
+ async function assertRegularFile(filePath, label, source = "llama-server archive") {
240
+ const stat = await fsp.lstat(filePath).catch(() => void 0);
241
+ if (!stat?.isFile() || stat.nlink > 1) throw new Error(`${source} does not contain regular ${label}`);
33
242
  return stat;
34
243
  }
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";
244
+ async function extractVerifiedArchive(archivePath, destDir, asset, requiredFiles) {
245
+ const isTar = asset.archive === "tar.gz";
52
246
  const limits = {
53
247
  ...LLAMA_ARCHIVE_LIMITS,
54
- ...params.asset.limits
248
+ ...asset.limits
55
249
  };
56
- const aliasCount = params.asset.regularFileAliases.reduce((count, [, aliases]) => count + aliases.length, 0);
250
+ const aliasCount = asset.regularFileAliases.reduce((count, [, aliases]) => count + aliases.length, 0);
57
251
  if (aliasCount > limits.maxEntries) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.ENTRY_COUNT_EXCEEDS_LIMIT);
58
252
  await extractArchive({
59
- archivePath: params.archivePath,
60
- destDir: params.destDir,
253
+ archivePath,
254
+ destDir,
61
255
  kind: isTar ? "tar" : "zip",
62
256
  timeoutMs: 0,
63
257
  limits: {
@@ -68,114 +262,28 @@ async function extractVerifiedArchive(params) {
68
262
  entryFilter: (entry) => entry.kind === "symlink" ? "skip" : "extract",
69
263
  onFiltered: "skip-entry"
70
264
  });
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
- // extensions/llama-cpp/src/llama-server-vc-runtime.ts
94
- const CAB_HEADER_SIZE = 12;
95
- const EXPAND_TIMEOUT_MS = 6e4;
96
- async function extractPinnedContainer(params) {
97
- const source = await fs.open(params.bundlePath, "r");
98
- try {
99
- const stat = await source.stat();
100
- if (!stat.isFile() || stat.size !== params.asset.size) throw new Error(`Visual C++ runtime bundle size mismatch: expected ${params.asset.size}, got ${stat.size}`);
101
- 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");
102
- const header = Buffer.alloc(CAB_HEADER_SIZE);
103
- 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");
104
- await pipeline(source.createReadStream({
105
- start: params.asset.containerOffset,
106
- end: params.asset.containerOffset + params.asset.containerSize - 1,
107
- autoClose: false
108
- }), createWriteStream(params.containerPath, {
109
- flags: "wx",
110
- mode: 384
111
- }), { signal: params.signal });
112
- } finally {
113
- await source.close();
265
+ const rootDir = path.join(destDir, asset.archiveRoot);
266
+ for (const file of requiredFiles) await assertRegularFile(path.join(rootDir, file), `file ${file}`);
267
+ let copiedBytes = 0;
268
+ for (const [source, aliases] of asset.regularFileAliases) {
269
+ const sourcePath = path.join(rootDir, source);
270
+ const sourceStat = await assertRegularFile(sourcePath, `alias source ${source}`);
271
+ for (const alias of aliases) {
272
+ copiedBytes += sourceStat.size;
273
+ if (copiedBytes > MAX_ALIAS_BYTES) throw new ArchiveLimitError(ARCHIVE_LIMIT_ERROR_CODE.EXTRACTED_SIZE_EXCEEDS_LIMIT);
274
+ const aliasPath = path.join(rootDir, alias);
275
+ await fsp.copyFile(sourcePath, aliasPath, fs.constants.COPYFILE_EXCL);
276
+ await fsp.chmod(aliasPath, sourceStat.mode & 511);
277
+ }
114
278
  }
115
- }
116
- function resolveExpandCommand() {
117
- const systemRoot = process.env.SystemRoot;
118
- if (!systemRoot || !path.win32.isAbsolute(systemRoot)) throw new Error("SystemRoot is unavailable; cannot extract the Visual C++ runtime");
119
- return path.win32.join(systemRoot, "System32", "expand.exe");
279
+ return rootDir;
120
280
  }
121
281
  async function runExpand(command, args, signal) {
122
- await new Promise((resolve, reject) => {
123
- execFile(command, args, {
124
- timeout: EXPAND_TIMEOUT_MS,
125
- signal,
126
- windowsHide: true
127
- }, (error, _stdout, stderr) => {
128
- if (error) {
129
- const detail = stderr.trim();
130
- reject(new Error(`Failed to extract the Visual C++ runtime${detail ? `: ${detail}` : ""}`, { cause: error }));
131
- } else resolve();
132
- });
282
+ await runServerCommand(command, args, signal, EXPAND_TIMEOUT_MS, (error, stderr) => {
283
+ const detail = stderr.trim();
284
+ return new Error(`Failed to extract the Visual C++ runtime${detail ? `: ${detail}` : ""}`, { cause: error });
133
285
  });
134
286
  }
135
- async function assertRegularFile(filePath, label) {
136
- const stat = await fs.lstat(filePath).catch(() => void 0);
137
- if (!stat?.isFile() || stat.nlink > 1) throw new Error(`Visual C++ runtime does not contain regular file ${label}`);
138
- }
139
- /** Extracts the pinned Microsoft redistributable DLLs without installing machine-wide state. */
140
- async function extractWindowsVcRuntime(params) {
141
- const { nestedCabinet, files } = params.asset;
142
- const expandCommand = resolveExpandCommand();
143
- const containerPath = path.join(params.destDir, "bundle.cab");
144
- const nestedDir = path.join(params.destDir, "nested");
145
- const filesDir = path.join(params.destDir, "files");
146
- await Promise.all([
147
- fs.mkdir(params.destDir, { recursive: true }),
148
- fs.mkdir(nestedDir, { recursive: true }),
149
- fs.mkdir(filesDir, { recursive: true })
150
- ]);
151
- await extractPinnedContainer({
152
- asset: params.asset,
153
- bundlePath: params.bundlePath,
154
- containerPath,
155
- signal: params.signal
156
- });
157
- await runExpand(expandCommand, [
158
- `-F:${nestedCabinet}`,
159
- containerPath,
160
- nestedDir
161
- ], params.signal);
162
- const nestedPath = path.join(nestedDir, nestedCabinet);
163
- await assertRegularFile(nestedPath, nestedCabinet);
164
- for (const file of files) {
165
- params.signal?.throwIfAborted();
166
- await runExpand(expandCommand, [
167
- `-F:${file.source}`,
168
- nestedPath,
169
- filesDir
170
- ], params.signal);
171
- const sourcePath = path.join(filesDir, file.source);
172
- await assertRegularFile(sourcePath, file.source);
173
- const targetPath = path.join(params.destDir, file.target);
174
- await fs.copyFile(sourcePath, targetPath, constants.COPYFILE_EXCL);
175
- }
176
- return params.destDir;
177
- }
178
- // extensions/llama-cpp/src/llama-server-install.ts
179
287
  const DOWNLOAD_TIMEOUT_MS = 18e5;
180
288
  const PROBE_TIMEOUT_MS = 15e3;
181
289
  const VERSION_TIMEOUT_MS = 12e4;
@@ -233,16 +341,16 @@ function rememberVerifiedFile(filePath, stat, sha256) {
233
341
  async function sha256File$1(filePath, signal) {
234
342
  signal?.throwIfAborted();
235
343
  try {
236
- const identity = fileIdentity(await fs.stat(filePath, { bigint: true }));
344
+ const identity = fileIdentity(await fsp.stat(filePath, { bigint: true }));
237
345
  const verified = verifiedFiles.get(filePath);
238
346
  if (verified?.identity === identity) return verified.sha256;
239
347
  verifiedFiles.delete(filePath);
240
- const handle = await fs.open(filePath, "r");
348
+ const handle = await fsp.open(filePath, "r");
241
349
  try {
242
350
  const before = fileIdentity(await handle.stat({ bigint: true }));
243
351
  const { digest: sha256 } = await sha256File(handle, { signal });
244
352
  const after = await handle.stat({ bigint: true });
245
- if (before !== fileIdentity(after) || before !== fileIdentity(await fs.stat(filePath, { bigint: true }))) throw new Error(`File changed during integrity verification: ${filePath}. Retry setup.`);
353
+ if (before !== fileIdentity(after) || before !== fileIdentity(await fsp.stat(filePath, { bigint: true }))) throw new Error(`File changed during integrity verification: ${filePath}. Retry setup.`);
246
354
  rememberVerifiedFile(filePath, after, sha256);
247
355
  return sha256;
248
356
  } finally {
@@ -263,7 +371,7 @@ function readResponseSha256(response) {
263
371
  }
264
372
  async function downloadVerifiedFile(params) {
265
373
  const partialPath = `${params.destination}.partial-${randomUUID()}`;
266
- await fs.mkdir(path.dirname(params.destination), { recursive: true });
374
+ await fsp.mkdir(path.dirname(params.destination), { recursive: true });
267
375
  const { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } = await import("openclaw/plugin-sdk/ssrf-runtime");
268
376
  try {
269
377
  const { response, release } = await fetchWithSsrFGuard({
@@ -280,7 +388,7 @@ async function downloadVerifiedFile(params) {
280
388
  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");
281
389
  const contentLength = Number(response.headers.get("content-length"));
282
390
  const totalSize = params.expectedSize ?? (Number.isFinite(contentLength) && contentLength > 0 ? contentLength : 0);
283
- const handle = await fs.open(partialPath, "wx", 384);
391
+ const handle = await fsp.open(partialPath, "wx", 384);
284
392
  const hash = createHash("sha256");
285
393
  let downloadedSize = 0;
286
394
  let previousSize = 0;
@@ -310,7 +418,7 @@ async function downloadVerifiedFile(params) {
310
418
  if (expectedSha256 && actualSha256 !== expectedSha256.toLowerCase()) throw new Error(`download SHA-256 mismatch: expected ${expectedSha256}, got ${actualSha256}`);
311
419
  const completed = await handle.stat({ bigint: true });
312
420
  params.signal?.throwIfAborted();
313
- await fs.rename(partialPath, params.destination);
421
+ await fsp.rename(partialPath, params.destination);
314
422
  const published = await handle.stat({ bigint: true });
315
423
  if (completed.size === published.size && completed.mtimeNs === published.mtimeNs) rememberVerifiedFile(params.destination, published, actualSha256);
316
424
  } finally {
@@ -320,34 +428,28 @@ async function downloadVerifiedFile(params) {
320
428
  await release();
321
429
  }
322
430
  } finally {
323
- await fs.rm(partialPath, { force: true }).catch(() => void 0);
431
+ await fsp.rm(partialPath, { force: true }).catch(() => void 0);
324
432
  }
325
433
  }
326
- async function runServerCommand(command, args, signal, timeoutMs = PROBE_TIMEOUT_MS) {
434
+ async function runServerCommand(command, args, signal, timeoutMs = PROBE_TIMEOUT_MS, formatError = formatRuntimeDependencyError) {
327
435
  return await new Promise((resolve, reject) => {
328
436
  execFile(command, args, {
329
437
  timeout: timeoutMs,
330
438
  signal,
331
439
  windowsHide: true
332
440
  }, (error, stdout, stderr) => {
333
- if (error) reject(new Error(error.message, { cause: error }));
441
+ if (error) reject(signal?.aborted ? toErrorObject(signal.reason, "Installation cancelled") : formatError(error, stderr));
334
442
  else resolve(`${stdout}${stderr}`.trim());
335
443
  });
336
444
  });
337
445
  }
338
446
  function formatRuntimeDependencyError(error) {
339
447
  const detail = error instanceof Error ? error.message : String(error);
340
- 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 });
341
448
  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 });
342
- return new Error(`The verified llama-server build could not start: ${detail}`, { cause: error });
449
+ return formatLlamaServerRuntimeError(error);
343
450
  }
344
- async function queryServerVersion(command, signal) {
345
- try {
346
- return await runServerCommand(command, ["--version"], signal, VERSION_TIMEOUT_MS);
347
- } catch (error) {
348
- signal?.throwIfAborted();
349
- throw formatRuntimeDependencyError(error);
350
- }
451
+ function queryServerVersion(command, signal) {
452
+ return runServerCommand(command, ["--version"], signal, VERSION_TIMEOUT_MS);
351
453
  }
352
454
  function validateServerVersionOutput(command, version) {
353
455
  const match = (version.split(/\r?\n/u, 1)[0]?.trim() ?? "").match(/^version: .+ \(build (\d+), commit ([a-f\d]{9})\)$/u);
@@ -365,32 +467,6 @@ async function validateInstalledServer(command, asset, signal) {
365
467
  validateServerVersionOutput(command, await queryServerVersion(command, signal));
366
468
  await validateCudaServer(command, asset, signal);
367
469
  }
368
- async function stageLlamaServerDependency(params) {
369
- const { dependency, extractDir, extractedRoot, index, options } = params;
370
- options.signal?.throwIfAborted();
371
- const dependencyArchive = path.join(extractDir, dependency.name);
372
- await downloadVerifiedFile({
373
- url: assetUrl(dependency),
374
- destination: dependencyArchive,
375
- expectedSha256: dependency.sha256,
376
- expectedSize: dependency.archive === "vc-redist" ? dependency.size : void 0,
377
- signal: options.signal,
378
- onProgress: options.onProgress
379
- });
380
- const dependencyExtractDir = path.join(extractDir, `dependency-${index}`);
381
- await fs.mkdir(dependencyExtractDir);
382
- const dependencyRoot = dependency.archive === "vc-redist" ? await extractWindowsVcRuntime({
383
- bundlePath: dependencyArchive,
384
- destDir: dependencyExtractDir,
385
- asset: dependency,
386
- signal: options.signal
387
- }) : await extractLlamaServerDependencyArchive({
388
- archivePath: dependencyArchive,
389
- destDir: dependencyExtractDir,
390
- asset: dependency
391
- });
392
- for (const file of dependencyFiles(dependency)) await fs.copyFile(path.join(dependencyRoot, file), path.join(extractedRoot, file), fs$1.constants.COPYFILE_EXCL);
393
- }
394
470
  function formatVcRuntimeFallbackError(startupError, fallbackError) {
395
471
  const startupDetail = startupError instanceof Error ? startupError.message : String(startupError);
396
472
  const fallbackDetail = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);
@@ -400,7 +476,7 @@ async function installLlamaServer(asset, options) {
400
476
  options.signal?.throwIfAborted();
401
477
  assertSupportedLinuxRuntime(asset);
402
478
  const { installDir, command } = resolveManagedLlamaServerPaths(asset);
403
- if (await fs.stat(command).then((stat) => stat.isFile()).catch(() => false)) {
479
+ if (await fsp.stat(command).then((stat) => stat.isFile()).catch(() => false)) {
404
480
  try {
405
481
  await validateInstalledServer(command, asset, options.signal);
406
482
  } catch (error) {
@@ -413,7 +489,7 @@ async function installLlamaServer(asset, options) {
413
489
  const dataDir = resolveLlamaCppDataDir();
414
490
  const archivePath = path.join(dataDir, `.download-${randomUUID()}-${asset.name}`);
415
491
  const extractDir = path.join(dataDir, `.extract-${randomUUID()}`);
416
- await fs.mkdir(dataDir, { recursive: true });
492
+ await fsp.mkdir(dataDir, { recursive: true });
417
493
  try {
418
494
  await downloadVerifiedFile({
419
495
  url: assetUrl(asset),
@@ -423,28 +499,82 @@ async function installLlamaServer(asset, options) {
423
499
  onProgress: options.onProgress
424
500
  });
425
501
  const serverExtractDir = path.join(extractDir, "server");
426
- await fs.mkdir(serverExtractDir, { recursive: true });
427
- const extractedCommand = await extractLlamaServerArchive({
428
- archivePath,
429
- destDir: serverExtractDir,
430
- asset
431
- });
502
+ await fsp.mkdir(serverExtractDir, { recursive: true });
503
+ const extractedCommand = path.join(await extractVerifiedArchive(archivePath, serverExtractDir, asset, [asset.executable]), asset.executable);
432
504
  const extractedRoot = path.dirname(extractedCommand);
505
+ const stageDependency = async (dependency, index) => {
506
+ options.signal?.throwIfAborted();
507
+ const dependencyArchive = path.join(extractDir, dependency.name);
508
+ await downloadVerifiedFile({
509
+ url: assetUrl(dependency),
510
+ destination: dependencyArchive,
511
+ expectedSha256: dependency.sha256,
512
+ expectedSize: dependency.archive === "vc-redist" ? dependency.size : void 0,
513
+ signal: options.signal,
514
+ onProgress: options.onProgress
515
+ });
516
+ const dependencyExtractDir = path.join(extractDir, `dependency-${index}`);
517
+ await fsp.mkdir(dependencyExtractDir);
518
+ let dependencyRoot;
519
+ if (dependency.archive === "vc-redist") {
520
+ const { nestedCabinet, files } = dependency;
521
+ const systemRoot = process.env.SystemRoot;
522
+ if (!systemRoot || !path.win32.isAbsolute(systemRoot)) throw new Error("SystemRoot is unavailable; cannot extract the Visual C++ runtime");
523
+ const expandCommand = path.win32.join(systemRoot, "System32", "expand.exe");
524
+ const containerPath = path.join(dependencyExtractDir, "bundle.cab");
525
+ const nestedDir = path.join(dependencyExtractDir, "nested");
526
+ const filesDir = path.join(dependencyExtractDir, "files");
527
+ await Promise.all([fsp.mkdir(nestedDir, { recursive: true }), fsp.mkdir(filesDir, { recursive: true })]);
528
+ const source = await fsp.open(dependencyArchive, "r");
529
+ try {
530
+ const stat = await source.stat();
531
+ if (!stat.isFile() || stat.size !== dependency.size) throw new Error(`Visual C++ runtime bundle size mismatch: expected ${dependency.size}, got ${stat.size}`);
532
+ if (dependency.containerOffset < 0 || dependency.containerSize < CAB_HEADER_SIZE || dependency.containerOffset + dependency.containerSize > stat.size) throw new Error("invalid Visual C++ runtime container bounds");
533
+ const header = Buffer.alloc(CAB_HEADER_SIZE);
534
+ if ((await source.read(header, 0, header.length, dependency.containerOffset)).bytesRead !== header.length || header.subarray(0, 4).toString("ascii") !== "MSCF" || header.readUInt32LE(8) !== dependency.containerSize) throw new Error("Visual C++ runtime bundle does not contain the pinned cabinet");
535
+ await pipeline(source.createReadStream({
536
+ start: dependency.containerOffset,
537
+ end: dependency.containerOffset + dependency.containerSize - 1,
538
+ autoClose: false
539
+ }), createWriteStream(containerPath, {
540
+ flags: "wx",
541
+ mode: 384
542
+ }), { signal: options.signal });
543
+ } finally {
544
+ await source.close();
545
+ }
546
+ await runExpand(expandCommand, [
547
+ `-F:${nestedCabinet}`,
548
+ containerPath,
549
+ nestedDir
550
+ ], options.signal);
551
+ const nestedPath = path.join(nestedDir, nestedCabinet);
552
+ await assertRegularFile(nestedPath, `file ${nestedCabinet}`, "Visual C++ runtime");
553
+ for (const file of files) {
554
+ options.signal?.throwIfAborted();
555
+ await runExpand(expandCommand, [
556
+ `-F:${file.source}`,
557
+ nestedPath,
558
+ filesDir
559
+ ], options.signal);
560
+ const sourcePath = path.join(filesDir, file.source);
561
+ await assertRegularFile(sourcePath, `file ${file.source}`, "Visual C++ runtime");
562
+ await fsp.copyFile(sourcePath, path.join(dependencyExtractDir, file.target), fs.constants.COPYFILE_EXCL);
563
+ }
564
+ dependencyRoot = dependencyExtractDir;
565
+ } else dependencyRoot = await extractVerifiedArchive(dependencyArchive, dependencyExtractDir, dependency, dependency.files);
566
+ const files = dependency.archive === "vc-redist" ? dependency.files.map((file) => file.target) : dependency.files;
567
+ for (const file of files) await fsp.copyFile(path.join(dependencyRoot, file), path.join(extractedRoot, file), fs.constants.COPYFILE_EXCL);
568
+ };
433
569
  const dependencies = asset.dependencies ?? [];
434
570
  const windowsRuntimeDependencies = [];
435
571
  for (const [index, dependency] of dependencies.entries()) if (dependency.archive === "vc-redist") windowsRuntimeDependencies.push({
436
572
  dependency,
437
573
  index
438
574
  });
439
- else await stageLlamaServerDependency({
440
- dependency,
441
- index,
442
- extractDir,
443
- extractedRoot,
444
- options
445
- });
575
+ else await stageDependency(dependency, index);
446
576
  options.signal?.throwIfAborted();
447
- await fs.chmod(extractedCommand, 493);
577
+ await fsp.chmod(extractedCommand, 493);
448
578
  if (windowsRuntimeDependencies.length > 0) {
449
579
  let version;
450
580
  try {
@@ -452,13 +582,7 @@ async function installLlamaServer(asset, options) {
452
582
  } catch (startupError) {
453
583
  options.signal?.throwIfAborted();
454
584
  try {
455
- for (const { dependency, index } of windowsRuntimeDependencies) await stageLlamaServerDependency({
456
- dependency,
457
- index,
458
- extractDir,
459
- extractedRoot,
460
- options
461
- });
585
+ for (const { dependency, index } of windowsRuntimeDependencies) await stageDependency(dependency, index);
462
586
  } catch (stagingError) {
463
587
  options.signal?.throwIfAborted();
464
588
  throw formatVcRuntimeFallbackError(startupError, stagingError);
@@ -473,25 +597,21 @@ async function installLlamaServer(asset, options) {
473
597
  validateServerVersionOutput(extractedCommand, version);
474
598
  await validateCudaServer(extractedCommand, asset, options.signal);
475
599
  } else await validateInstalledServer(extractedCommand, asset, options.signal);
476
- await fs.mkdir(path.dirname(installDir), { recursive: true });
600
+ await fsp.mkdir(path.dirname(installDir), { recursive: true });
477
601
  options.signal?.throwIfAborted();
478
- await fs.rm(installDir, {
602
+ await fsp.rm(installDir, {
479
603
  recursive: true,
480
604
  force: true
481
605
  });
482
- await fs.rename(extractedRoot, installDir);
483
- await validateInstalledServer(command, asset, options.signal);
606
+ await fsp.rename(extractedRoot, installDir);
484
607
  return command;
485
608
  } finally {
486
- await Promise.all([fs.rm(archivePath, { force: true }), fs.rm(extractDir, {
609
+ await Promise.all([fsp.rm(archivePath, { force: true }), fsp.rm(extractDir, {
487
610
  recursive: true,
488
611
  force: true
489
612
  })]);
490
613
  }
491
614
  }
492
- function dependencyFiles(dependency) {
493
- return dependency.archive === "vc-redist" ? dependency.files.map((file) => file.target) : dependency.files;
494
- }
495
615
  async function ensureLlamaServerInstalled(options = {}) {
496
616
  options.signal?.throwIfAborted();
497
617
  const asset = options.asset ?? selectLlamaServerAsset();
@@ -501,16 +621,7 @@ async function ensureLlamaServerInstalled(options = {}) {
501
621
  if (installationPromises.get(key) === pending) installationPromises.delete(key);
502
622
  });
503
623
  installationPromises.set(key, pending);
504
- return {
505
- command: previous && options.signal ? await new Promise((resolve, reject) => {
506
- const signal = options.signal;
507
- const onAbort = () => reject(toErrorObject(signal?.reason, "Installation cancelled"));
508
- signal?.addEventListener("abort", onAbort, { once: true });
509
- pending.then(resolve, reject).finally(() => signal?.removeEventListener("abort", onAbort));
510
- if (signal?.aborted) onAbort();
511
- }) : await pending,
512
- asset
513
- };
624
+ return { command: await racePromiseWithAbortSignal(pending, previous ? options.signal : void 0, (signal) => toErrorObject(signal.reason, "Installation cancelled")) };
514
625
  }
515
626
  // extensions/llama-cpp/src/llama-server-preset.ts
516
627
  function assertIniValue(value, label) {
@@ -645,9 +756,17 @@ function buildLlamaServerPreset(existing, params) {
645
756
  const orderedSections = [...[...sections].toSorted(([left], [right]) => Number(left > right) - Number(left < right)).map(([, section]) => section), ...embeddingSection ? [embeddingSection] : []];
646
757
  return header + (header && !/[\r\n]$/u.test(header) ? newline : "") + orderedSections.map((section) => section.replace(/[\r\n]+$/u, "")).join(newline + newline) + newline;
647
758
  }
648
- // extensions/llama-cpp/src/managed-server-orphans.ts
759
+ // extensions/llama-cpp/src/managed-server.ts
760
+ const modelPromises = /* @__PURE__ */ new Map();
649
761
  const log = createSubsystemLogger("llama-cpp");
650
762
  const recoveries = /* @__PURE__ */ new Map();
763
+ const resolvedModelArtifacts = /* @__PURE__ */ new Map();
764
+ const presetState = {
765
+ appliedRevisions: /* @__PURE__ */ new Map(),
766
+ desiredRevisions: /* @__PURE__ */ new Map()
767
+ };
768
+ const runPresetTransition = createAsyncLock();
769
+ const LLAMA_CPP_PRESET_RELOAD_TIMEOUT_MS = 15e3;
651
770
  function readUniqueArgument(argv, name) {
652
771
  const values = argv.flatMap((argument, index) => {
653
772
  if (argument === name) {
@@ -658,54 +777,6 @@ function readUniqueArgument(argv, name) {
658
777
  });
659
778
  return values.length === 1 ? values[0] : void 0;
660
779
  }
661
- /** A new host process recovers once; in-process restarts retain that host's children. */
662
- async function recoverManagedLlamaServer(params) {
663
- params.signal?.throwIfAborted();
664
- if (!findManagedLlamaServerAsset(params.command)) return;
665
- const args = params.args ?? [];
666
- const preset = readUniqueArgument(args, "--models-preset");
667
- const host = readUniqueArgument(args, "--host");
668
- if (!preset || !host || readUniqueArgument(args, "--port") !== String(params.port)) return;
669
- const required = /* @__PURE__ */ new Map([
670
- ["--port", String(params.port)],
671
- ["--models-preset", preset],
672
- ["--host", host]
673
- ]);
674
- const cwd = !path.isAbsolute(preset) ? path.resolve(params.cwd ?? process.cwd()) : void 0;
675
- const key = JSON.stringify([
676
- params.command,
677
- [...required],
678
- cwd
679
- ]);
680
- let recovery = recoveries.get(key);
681
- if (!recovery) {
682
- recovery = (async () => {
683
- const { reapOrphanedProcesses } = await import("openclaw/plugin-sdk/process-runtime");
684
- await reapOrphanedProcesses({
685
- command: params.command,
686
- cwd,
687
- matchesArguments: (argv) => [...required].every(([name, value]) => readUniqueArgument(argv, name) === value),
688
- signal: params.signal,
689
- onReap: (pid) => log.info(`reaping orphaned managed llama-server: pid=${pid} port=${params.port}`)
690
- });
691
- })().catch((error) => {
692
- recoveries.delete(key);
693
- throw error;
694
- });
695
- recoveries.set(key, recovery);
696
- }
697
- await recovery;
698
- params.signal?.throwIfAborted();
699
- }
700
- // extensions/llama-cpp/src/managed-server.ts
701
- const modelPromises = /* @__PURE__ */ new Map();
702
- const resolvedModelArtifacts = /* @__PURE__ */ new Map();
703
- const presetState = {
704
- appliedRevisions: /* @__PURE__ */ new Map(),
705
- desiredRevisions: /* @__PURE__ */ new Map()
706
- };
707
- const runPresetTransition = createAsyncLock();
708
- const LLAMA_CPP_PRESET_RELOAD_TIMEOUT_MS = 15e3;
709
780
  function parseHuggingFaceSource(source) {
710
781
  const [pathPart, revisionPart] = source.replace(/^(?:hf|huggingface):(?:\/\/)?/iu, "").split("#", 2);
711
782
  const [user, repositoryWithTag, ...fileParts] = (pathPart ?? "").split("/");
@@ -800,7 +871,7 @@ function defaultArtifact(source) {
800
871
  };
801
872
  }
802
873
  async function assertGguf(filePath) {
803
- const handle = await fs.open(filePath, "r").catch((error) => {
874
+ const handle = await fsp.open(filePath, "r").catch((error) => {
804
875
  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 });
805
876
  throw error;
806
877
  });
@@ -866,8 +937,8 @@ async function ensureLlamaCppModel(params) {
866
937
  const artifact = await resolveCachedModelArtifact(localSource, params.cacheDir, params.signal);
867
938
  const destination = path.join(params.cacheDir, artifact.fileName);
868
939
  const load = modelPromises.get(destination) ?? (async () => {
869
- const exists = await fs.stat(destination).then((stat) => stat.isFile()).catch(() => false);
870
- if (exists && artifact.expectedSha256 && (artifact.expectedSize === void 0 || (await fs.stat(destination)).size === artifact.expectedSize) && await sha256File$1(destination, params.signal) === artifact.expectedSha256) {
940
+ const exists = await fsp.stat(destination).then((stat) => stat.isFile()).catch(() => false);
941
+ if (exists && artifact.expectedSha256 && (artifact.expectedSize === void 0 || (await fsp.stat(destination)).size === artifact.expectedSize) && await sha256File$1(destination, params.signal) === artifact.expectedSha256) {
871
942
  await assertGguf(destination);
872
943
  return destination;
873
944
  }
@@ -899,18 +970,18 @@ async function ensureLlamaCppModel(params) {
899
970
  }
900
971
  }
901
972
  async function writePreset(presetPath, contents) {
902
- await fs.mkdir(path.dirname(presetPath), { recursive: true });
973
+ await fsp.mkdir(path.dirname(presetPath), { recursive: true });
903
974
  const temporary = `${presetPath}.tmp-${randomUUID()}`;
904
975
  try {
905
- await fs.writeFile(temporary, contents, { mode: 384 });
906
- await fs.rename(temporary, presetPath);
976
+ await fsp.writeFile(temporary, contents, { mode: 384 });
977
+ await fsp.rename(temporary, presetPath);
907
978
  } finally {
908
- await fs.rm(temporary, { force: true });
979
+ await fsp.rm(temporary, { force: true });
909
980
  }
910
981
  }
911
982
  async function updatePreset(presetPath, params) {
912
983
  await runPresetTransition(async () => {
913
- const existing = await fs.readFile(presetPath, "utf8").catch((error) => {
984
+ const existing = await fsp.readFile(presetPath, "utf8").catch((error) => {
914
985
  if (asOptionalRecord(error)?.code === "ENOENT") return;
915
986
  throw error;
916
987
  });
@@ -962,7 +1033,7 @@ async function prepareManagedLlamaServer(params) {
962
1033
  let command = params.asset ? void 0 : params.localService?.command;
963
1034
  const asset = command === void 0 ? params.asset : findManagedLlamaServerAsset(command);
964
1035
  if (command !== void 0 && asset) try {
965
- await fs.stat(command);
1036
+ await fsp.stat(command);
966
1037
  } catch (error) {
967
1038
  if (asOptionalRecord(error)?.code !== "ENOENT") throw error;
968
1039
  command = void 0;
@@ -982,13 +1053,48 @@ async function prepareManagedLlamaServer(params) {
982
1053
  healthUrl: (!params.isolated ? params.localService?.healthUrl : void 0) ?? `${rootUrl}/health`
983
1054
  };
984
1055
  const configuredPreset = resolveLlamaCppPresetPath(params.localService);
985
- if (params.localService && !params.isolated) await recoverManagedLlamaServer({
986
- command,
987
- port,
988
- cwd: params.localService.cwd,
989
- args: params.localService.args,
990
- signal: params.signal
991
- });
1056
+ if (params.localService && !params.isolated) {
1057
+ const { cwd: configuredCwd, args: configuredArgs } = params.localService;
1058
+ const signal = params.signal;
1059
+ signal?.throwIfAborted();
1060
+ if (findManagedLlamaServerAsset(command)) {
1061
+ const args = configuredArgs ?? [];
1062
+ const preset = readUniqueArgument(args, "--models-preset");
1063
+ const host = readUniqueArgument(args, "--host");
1064
+ if (preset && host && readUniqueArgument(args, "--port") === String(port)) {
1065
+ const required = /* @__PURE__ */ new Map([
1066
+ ["--port", String(port)],
1067
+ ["--models-preset", preset],
1068
+ ["--host", host]
1069
+ ]);
1070
+ const cwd = !path.isAbsolute(preset) ? path.resolve(configuredCwd ?? process.cwd()) : void 0;
1071
+ const key = JSON.stringify([
1072
+ command,
1073
+ [...required],
1074
+ cwd
1075
+ ]);
1076
+ let recovery = recoveries.get(key);
1077
+ if (!recovery) {
1078
+ recovery = (async () => {
1079
+ const { reapOrphanedProcesses } = await import("openclaw/plugin-sdk/process-runtime");
1080
+ await reapOrphanedProcesses({
1081
+ command,
1082
+ cwd,
1083
+ matchesArguments: (argv) => [...required].every(([name, value]) => readUniqueArgument(argv, name) === value),
1084
+ signal,
1085
+ onReap: (pid) => log.info(`reaping orphaned managed llama-server: pid=${pid} port=${port}`)
1086
+ });
1087
+ })().catch((error) => {
1088
+ recoveries.delete(key);
1089
+ throw error;
1090
+ });
1091
+ recoveries.set(key, recovery);
1092
+ }
1093
+ await recovery;
1094
+ signal?.throwIfAborted();
1095
+ }
1096
+ }
1097
+ }
992
1098
  if (params.localService && !configuredPreset && !params.isolated) {
993
1099
  await runPresetTransition(async () => {
994
1100
  presetState.desiredRevisions.delete(reconcileOrigin);
@@ -1001,7 +1107,7 @@ async function prepareManagedLlamaServer(params) {
1001
1107
  }
1002
1108
  const defaultPreset = configuredPreset ? path.resolve(params.localService?.cwd ?? process.cwd(), configuredPreset) : resolveManagedLlamaServerPaths(params.asset).presetPath;
1003
1109
  const presetPath = params.isolated ? path.join(path.dirname(defaultPreset), `models-${randomUUID()}.ini`) : defaultPreset;
1004
- const initialContents = params.isolated && params.mediaModels ? await fs.readFile(defaultPreset, "utf8").catch((error) => {
1110
+ const initialContents = params.isolated && params.mediaModels ? await fsp.readFile(defaultPreset, "utf8").catch((error) => {
1005
1111
  if (!configuredPreset && asOptionalRecord(error)?.code === "ENOENT") return;
1006
1112
  throw error;
1007
1113
  }) : void 0;
@@ -1025,7 +1131,7 @@ async function prepareManagedLlamaServer(params) {
1025
1131
  });
1026
1132
  params.signal?.throwIfAborted();
1027
1133
  } catch (error) {
1028
- if (params.isolated) await fs.rm(presetPath, { force: true });
1134
+ if (params.isolated) await fsp.rm(presetPath, { force: true });
1029
1135
  throw error;
1030
1136
  }
1031
1137
  return {
@@ -1068,10 +1174,6 @@ async function ensureManagedLlamaServerForChat(params) {
1068
1174
  model: params.model,
1069
1175
  provider: params.provider
1070
1176
  });
1071
- if (!chatModelPath && resolveLlamaCppModelSource(params.model) === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") {
1072
- const legacy = path.join(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE);
1073
- if (await fs.stat(legacy).then((stat) => stat.isFile()).catch(() => false)) chatModelPath = legacy;
1074
- }
1075
1177
  chatModelPath = await ensureLlamaCppModel({
1076
1178
  source: chatModelPath ?? resolveLlamaCppModelSource(params.model),
1077
1179
  cacheDir,
@@ -1106,4 +1208,4 @@ async function ensureManagedLlamaServerForChat(params) {
1106
1208
  signal: params.signal
1107
1209
  });
1108
1210
  }
1109
- export { ensureLlamaCppModel, ensureManagedLlamaServerForChat, UnsupportedLlamaServerHostError as n, prepareManagedLlamaServer, ensureLlamaServerInstalled as r, reconcileManagedLlamaServer, resolveLlamaCppModelDownloadSize, resolveLlamaCppPresetPath, assertMediaPresetLimits as t };
1211
+ export { resolveManagedLlamaServerPaths as a, ensureLlamaCppModel, ensureManagedLlamaServerForChat, formatLlamaServerRuntimeError as i, UnsupportedLlamaServerHostError as n, selectLlamaServerAsset as o, prepareManagedLlamaServer, ensureLlamaServerInstalled as r, reconcileManagedLlamaServer, resolveLlamaCppModelDownloadSize, resolveLlamaCppPresetPath, assertMediaPresetLimits as t };