@openclaw/llama-cpp-provider 2026.8.1-beta.2 → 2026.8.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.
package/dist/index.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as resolveLegacyLlamaCppModelCacheDir, D as resolveLlamaCppModelSource, E as resolveLlamaCppModelCacheDir, O as resolveLlamaCppSyntheticApiKey, S as resolveHomePath, T as resolveLlamaCppEmbeddingModel, _ as LLAMA_CPP_PROVIDER_ID, a as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, b as meetsLlamaCppDefaultModelRamFloor, c as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256, d as DEFAULT_LLAMA_CPP_MODEL_ID, f as DEFAULT_LLAMA_CPP_MODEL_REVISION, g as LLAMA_CPP_DEFAULT_PORT, i as DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE, l as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES, m as DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES, n as resolveManagedLlamaCppProviderConfig, o as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, p as DEFAULT_LLAMA_CPP_MODEL_SHA256, s as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION, u as DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE, v as LLAMA_CPP_PROVIDER_LABEL, w as resolveLlamaCppDataDir, x as resolveCachedLlamaCppModelPath, y as buildLlamaCppProviderConfig } from "./managed-provider-config-C9_YC5Rd.js";
|
|
2
2
|
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
|
3
|
-
import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
|
|
4
|
-
import os from "node:os";
|
|
5
3
|
import path from "node:path";
|
|
6
4
|
import { getEmbeddingProvider } from "openclaw/plugin-sdk/embedding-providers";
|
|
7
|
-
import
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { asBoolean, asOptionalRecord, asPositiveSafeInteger, isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
8
7
|
import { execFile } from "node:child_process";
|
|
9
8
|
import { createHash, randomUUID } from "node:crypto";
|
|
10
9
|
import fs from "node:fs";
|
|
@@ -14,6 +13,89 @@ import * as tar from "tar";
|
|
|
14
13
|
import net from "node:net";
|
|
15
14
|
import { fetchWithSsrFGuard, ssrfPolicyFromHttpBaseUrlAllowedOrigin } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
16
15
|
import { fetchConfiguredLocalOriginWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime-internal";
|
|
16
|
+
import { CUSTOM_LOCAL_AUTH_MARKER, applyAuthProfileConfig, buildApiKeyCredential, ensureApiKeyFromEnvOrPrompt, hasConfiguredSecretInput, isNonSecretApiKeyMarker, normalizeOptionalSecretInput, upsertAuthProfileWithLock } from "openclaw/plugin-sdk/provider-auth";
|
|
17
|
+
import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
|
|
18
|
+
import { removeAuthProfileConfig, removeProviderAuthProfilesWithLock, resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
|
|
19
|
+
import { resolveConfiguredSecretInputString } from "openclaw/plugin-sdk/secret-input-runtime";
|
|
20
|
+
import { getCachedLiveCatalogValue } from "openclaw/plugin-sdk/provider-catalog-shared";
|
|
21
|
+
import { SELF_HOSTED_DEFAULT_CONTEXT_WINDOW, SELF_HOSTED_DEFAULT_COST, SELF_HOSTED_DEFAULT_MAX_TOKENS, applyProviderDefaultModel, discoverOpenAICompatibleLocalModels } from "openclaw/plugin-sdk/provider-setup";
|
|
22
|
+
import { selectPreferredLocalModelId } from "openclaw/plugin-sdk/provider-model-shared";
|
|
23
|
+
import { streamSimple } from "openclaw/plugin-sdk/llm";
|
|
24
|
+
import { setQwenChatTemplateThinking } from "openclaw/plugin-sdk/provider-stream-shared";
|
|
25
|
+
import { listAgentIds, resolveAgentConfig } from "openclaw/plugin-sdk/agent-scope-runtime";
|
|
26
|
+
//#region extensions/llama-cpp/src/llama-server-assets.ts
|
|
27
|
+
const LLAMA_SERVER_RELEASE = "b10534";
|
|
28
|
+
const LLAMA_SERVER_COMMIT = "2b5621094ef383cdcd8428ef6d22efe5df976532";
|
|
29
|
+
const LLAMA_SERVER_ASSETS = [
|
|
30
|
+
{
|
|
31
|
+
platform: "darwin",
|
|
32
|
+
arch: "arm64",
|
|
33
|
+
backend: "metal",
|
|
34
|
+
archive: "tar.gz",
|
|
35
|
+
name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-arm64.tar.gz`,
|
|
36
|
+
sha256: "51f193eef26b053554e288fb924b24d41d3d7b2bafa338c19e2817fa793d5e86",
|
|
37
|
+
executable: "llama-server"
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
platform: "darwin",
|
|
41
|
+
arch: "x64",
|
|
42
|
+
backend: "cpu",
|
|
43
|
+
archive: "tar.gz",
|
|
44
|
+
name: `llama-${LLAMA_SERVER_RELEASE}-bin-macos-x64.tar.gz`,
|
|
45
|
+
sha256: "69b13035f4301354922a8cfacd1bcf2bb2de4ff0c2e19fedb44963378ff53dc5",
|
|
46
|
+
executable: "llama-server"
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
platform: "linux",
|
|
50
|
+
arch: "arm64",
|
|
51
|
+
backend: "cpu",
|
|
52
|
+
archive: "tar.gz",
|
|
53
|
+
name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-arm64.tar.gz`,
|
|
54
|
+
sha256: "66535de5cb9293c075a1951c51a3b2ae6f1899623e21177845f6d2a73b78c94e",
|
|
55
|
+
executable: "llama-server"
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
platform: "linux",
|
|
59
|
+
arch: "x64",
|
|
60
|
+
backend: "cpu",
|
|
61
|
+
archive: "tar.gz",
|
|
62
|
+
name: `llama-${LLAMA_SERVER_RELEASE}-bin-ubuntu-x64.tar.gz`,
|
|
63
|
+
sha256: "cc6a12b026edcf1b211be2bb7366c5dadcad778fd8f13019d0694038053d5e4a",
|
|
64
|
+
executable: "llama-server"
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
platform: "win32",
|
|
68
|
+
arch: "arm64",
|
|
69
|
+
backend: "cpu",
|
|
70
|
+
archive: "zip",
|
|
71
|
+
name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-arm64.zip`,
|
|
72
|
+
sha256: "d33618b10fda35d34d85da60926c6c470f98f3f66ce6b52c3c1f583461416012",
|
|
73
|
+
executable: "llama-server.exe"
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
platform: "win32",
|
|
77
|
+
arch: "x64",
|
|
78
|
+
backend: "cpu",
|
|
79
|
+
archive: "zip",
|
|
80
|
+
name: `llama-${LLAMA_SERVER_RELEASE}-bin-win-cpu-x64.zip`,
|
|
81
|
+
sha256: "295ae03ad58d9276afa36f5f8d111d67fc1491c7aff3a3e6d13051a772f93c21",
|
|
82
|
+
executable: "llama-server.exe"
|
|
83
|
+
}
|
|
84
|
+
];
|
|
85
|
+
function selectLlamaServerAsset(platform = process.platform, arch = process.arch) {
|
|
86
|
+
const asset = LLAMA_SERVER_ASSETS.find((candidate) => candidate.platform === platform && candidate.arch === arch);
|
|
87
|
+
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.`);
|
|
88
|
+
return asset;
|
|
89
|
+
}
|
|
90
|
+
function resolveManagedLlamaServerPaths(asset = selectLlamaServerAsset()) {
|
|
91
|
+
const installDir = path.join(resolveLlamaCppDataDir(), LLAMA_SERVER_RELEASE, `${asset.platform}-${asset.arch}`);
|
|
92
|
+
return {
|
|
93
|
+
installDir,
|
|
94
|
+
command: path.join(installDir, asset.executable),
|
|
95
|
+
presetPath: path.join(resolveLlamaCppDataDir(), "models.ini")
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
//#endregion
|
|
17
99
|
//#region extensions/llama-cpp/src/llama-server-install.ts
|
|
18
100
|
const DOWNLOAD_TIMEOUT_MS = 30 * 6e4;
|
|
19
101
|
const VERSION_TIMEOUT_MS = 15e3;
|
|
@@ -77,15 +159,12 @@ async function downloadVerifiedFile(params) {
|
|
|
77
159
|
const totalSize = params.expectedSize ?? (Number.isFinite(contentLength) && contentLength > 0 ? contentLength : 0);
|
|
78
160
|
const handle = await fsp.open(partialPath, "wx", 384);
|
|
79
161
|
const hash = createHash("sha256");
|
|
80
|
-
const reader = response.body.getReader();
|
|
81
162
|
let downloadedSize = 0;
|
|
82
163
|
let previousSize = 0;
|
|
83
164
|
let previousAt = Date.now();
|
|
84
165
|
let rollingBytesPerSecond = 0;
|
|
85
166
|
try {
|
|
86
|
-
for (
|
|
87
|
-
const { done, value } = await reader.read();
|
|
88
|
-
if (done) break;
|
|
167
|
+
for await (const value of response.body.values({ preventCancel: true })) {
|
|
89
168
|
const chunk = Buffer.from(value);
|
|
90
169
|
await handle.writeFile(chunk);
|
|
91
170
|
hash.update(chunk);
|
|
@@ -162,7 +241,10 @@ async function validateInstalledServer(command) {
|
|
|
162
241
|
} catch (error) {
|
|
163
242
|
throw formatRuntimeDependencyError(error);
|
|
164
243
|
}
|
|
165
|
-
|
|
244
|
+
const match = (version.split(/\r?\n/u, 1)[0]?.trim() ?? "").match(/^version: .+ \(build (\d+), commit ([a-f\d]{9})\)$/u);
|
|
245
|
+
const build = match?.[1] ? Number(match[1]) : void 0;
|
|
246
|
+
const commit = match?.[2];
|
|
247
|
+
if (build !== 10534 || commit !== "2b5621094ef383cdcd8428ef6d22efe5df976532".slice(0, 9)) throw new Error(`Unexpected llama-server build at ${command}: expected ${LLAMA_SERVER_RELEASE} (${LLAMA_SERVER_COMMIT.slice(0, 9)}), got ${version || "no version output"}`);
|
|
166
248
|
}
|
|
167
249
|
async function installLlamaServer(asset) {
|
|
168
250
|
assertSupportedLinuxRuntime(asset);
|
|
@@ -225,6 +307,8 @@ async function ensureLlamaServerInstalled() {
|
|
|
225
307
|
//#region extensions/llama-cpp/src/managed-server.ts
|
|
226
308
|
const modelPromises = /* @__PURE__ */ new Map();
|
|
227
309
|
const chatPreparationPromises = /* @__PURE__ */ new Map();
|
|
310
|
+
const presetWritePromises = /* @__PURE__ */ new Map();
|
|
311
|
+
const LLAMA_CPP_EMBEDDING_UBATCH_SIZE = 2048;
|
|
228
312
|
function parseHuggingFaceSource(source) {
|
|
229
313
|
const [pathPart, revisionPart] = source.replace(/^(?:hf|huggingface):(?:\/\/)?/iu, "").split("#", 2);
|
|
230
314
|
const [user, repositoryWithTag, ...fileParts] = (pathPart ?? "").split("/");
|
|
@@ -286,7 +370,6 @@ async function resolveHuggingFaceArtifact(source, signal) {
|
|
|
286
370
|
expectedSize = expectedSize ?? (typeof fileRow?.size === "number" ? fileRow.size : void 0);
|
|
287
371
|
if (!expectedSha256) throw new Error(`Hugging Face did not publish a SHA-256 LFS identity for ${source}`);
|
|
288
372
|
return {
|
|
289
|
-
source,
|
|
290
373
|
fileName: `hf_${[
|
|
291
374
|
parsed.user,
|
|
292
375
|
parsed.repository,
|
|
@@ -300,14 +383,12 @@ async function resolveHuggingFaceArtifact(source, signal) {
|
|
|
300
383
|
}
|
|
301
384
|
function defaultArtifact(source) {
|
|
302
385
|
if (source === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") return {
|
|
303
|
-
source,
|
|
304
386
|
fileName: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE,
|
|
305
387
|
url: `https://huggingface.co/unsloth/gemma-4-E4B-it-GGUF/resolve/${DEFAULT_LLAMA_CPP_MODEL_REVISION}/gemma-4-E4B-it-Q4_K_M.gguf?download=true`,
|
|
306
388
|
expectedSize: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
|
|
307
389
|
expectedSha256: DEFAULT_LLAMA_CPP_MODEL_SHA256
|
|
308
390
|
};
|
|
309
391
|
if (source === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") return {
|
|
310
|
-
source,
|
|
311
392
|
fileName: DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE,
|
|
312
393
|
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`,
|
|
313
394
|
expectedSize: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES,
|
|
@@ -336,7 +417,6 @@ async function resolveModelArtifact(source, signal) {
|
|
|
336
417
|
const fileName = path.basename(decodeURIComponent(url.pathname));
|
|
337
418
|
if (!fileName.toLowerCase().includes(".gguf")) throw new Error(`Remote model URL must name a GGUF file: ${source}`);
|
|
338
419
|
return {
|
|
339
|
-
source,
|
|
340
420
|
fileName,
|
|
341
421
|
url: source
|
|
342
422
|
};
|
|
@@ -385,22 +465,44 @@ function assertIniValue(value, label) {
|
|
|
385
465
|
if (/\r|\n/u.test(value)) throw new Error(`${label} cannot contain a newline`);
|
|
386
466
|
return value;
|
|
387
467
|
}
|
|
388
|
-
function
|
|
389
|
-
const
|
|
390
|
-
|
|
391
|
-
if (chatId.includes("]") || embeddingId.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
|
|
468
|
+
function renderChatModelSection(params) {
|
|
469
|
+
const id = assertIniValue(params.id, "llama.cpp model id");
|
|
470
|
+
if (id.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
|
|
392
471
|
return [
|
|
393
|
-
|
|
394
|
-
""
|
|
395
|
-
`[${chatId}]`,
|
|
396
|
-
`model = ${assertIniValue(params.chatModelPath, "llama.cpp model path")}`,
|
|
472
|
+
`[${id}]`,
|
|
473
|
+
`model = ${assertIniValue(params.modelPath, "llama.cpp model path")}`,
|
|
397
474
|
`ctx-size = ${params.contextSize ?? 65536}`,
|
|
398
475
|
`n-predict = ${params.maxTokens ?? 2048}`,
|
|
399
|
-
"jinja = true"
|
|
476
|
+
"jinja = true"
|
|
477
|
+
].join("\n");
|
|
478
|
+
}
|
|
479
|
+
function renderEmbeddingModelSection(params) {
|
|
480
|
+
return [
|
|
481
|
+
`[${DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID}]`,
|
|
482
|
+
`model = ${assertIniValue(params.modelPath, "llama.cpp embedding model path")}`,
|
|
483
|
+
...params.isDefault ? [`ubatch-size = ${LLAMA_CPP_EMBEDDING_UBATCH_SIZE}`] : [],
|
|
484
|
+
"embedding = true"
|
|
485
|
+
].join("\n");
|
|
486
|
+
}
|
|
487
|
+
function readModelSection(contents, id) {
|
|
488
|
+
if (!contents) return;
|
|
489
|
+
const lines = contents.split(/\r?\n/u);
|
|
490
|
+
const start = lines.indexOf(`[${id}]`);
|
|
491
|
+
if (start < 0) return;
|
|
492
|
+
let end = start + 1;
|
|
493
|
+
while (end < lines.length && !/^\[[^\]]+\]$/u.test(lines[end] ?? "")) end += 1;
|
|
494
|
+
return lines.slice(start, end).join("\n").trimEnd();
|
|
495
|
+
}
|
|
496
|
+
function readChatModelSection(contents) {
|
|
497
|
+
const id = contents?.split(/\r?\n/u).map((line) => /^\[([^\]]+)\]$/u.exec(line)?.[1]).find((candidate) => candidate && candidate !== "embeddinggemma-300m-qat-q8_0");
|
|
498
|
+
return id ? readModelSection(contents, id) : void 0;
|
|
499
|
+
}
|
|
500
|
+
function renderLlamaServerPreset(params) {
|
|
501
|
+
return [
|
|
502
|
+
"version = 1",
|
|
400
503
|
"",
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
"embedding = true",
|
|
504
|
+
...params.chatSection ? [params.chatSection, ""] : [],
|
|
505
|
+
params.embeddingSection,
|
|
404
506
|
""
|
|
405
507
|
].join("\n");
|
|
406
508
|
}
|
|
@@ -410,6 +512,38 @@ async function writePreset(presetPath, contents) {
|
|
|
410
512
|
await fsp.writeFile(temporary, contents, { mode: 384 });
|
|
411
513
|
await fsp.rename(temporary, presetPath);
|
|
412
514
|
}
|
|
515
|
+
async function updatePreset(presetPath, params) {
|
|
516
|
+
const pending = (presetWritePromises.get(presetPath) ?? Promise.resolve()).catch(() => void 0).then(async () => {
|
|
517
|
+
const existing = await fsp.readFile(presetPath, "utf8").catch((error) => {
|
|
518
|
+
if (asOptionalRecord(error)?.code === "ENOENT") return;
|
|
519
|
+
throw error;
|
|
520
|
+
});
|
|
521
|
+
const chatSection = params.chatModel.mode === "preserve" ? readChatModelSection(existing) : params.chatModel.mode === "configure" ? renderChatModelSection({
|
|
522
|
+
id: params.chatModel.id,
|
|
523
|
+
modelPath: params.chatModel.path,
|
|
524
|
+
contextSize: params.chatModel.contextSize,
|
|
525
|
+
maxTokens: params.chatModel.maxTokens
|
|
526
|
+
}) : void 0;
|
|
527
|
+
const embeddingSection = params.embeddingModelPath ? renderEmbeddingModelSection({
|
|
528
|
+
isDefault: params.embeddingModelIsDefault,
|
|
529
|
+
modelPath: params.embeddingModelPath
|
|
530
|
+
}) : readModelSection(existing, "embeddinggemma-300m-qat-q8_0") ?? (params.defaultEmbeddingModelPath ? renderEmbeddingModelSection({
|
|
531
|
+
isDefault: true,
|
|
532
|
+
modelPath: params.defaultEmbeddingModelPath
|
|
533
|
+
}) : void 0);
|
|
534
|
+
if (!embeddingSection) throw new Error("llama.cpp embedding model path is required for a new managed preset");
|
|
535
|
+
await writePreset(presetPath, renderLlamaServerPreset({
|
|
536
|
+
chatSection,
|
|
537
|
+
embeddingSection
|
|
538
|
+
}));
|
|
539
|
+
});
|
|
540
|
+
presetWritePromises.set(presetPath, pending);
|
|
541
|
+
try {
|
|
542
|
+
await pending;
|
|
543
|
+
} finally {
|
|
544
|
+
if (presetWritePromises.get(presetPath) === pending) presetWritePromises.delete(presetPath);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
413
547
|
async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT) {
|
|
414
548
|
const tryPort = async (port) => await new Promise((resolve) => {
|
|
415
549
|
const server = net.createServer();
|
|
@@ -426,19 +560,16 @@ async function findAvailableLlamaServerPort(preferred = LLAMA_CPP_DEFAULT_PORT)
|
|
|
426
560
|
async function prepareManagedLlamaServer(params) {
|
|
427
561
|
const { command, asset } = await ensureLlamaServerInstalled();
|
|
428
562
|
const { presetPath } = resolveManagedLlamaServerPaths(asset);
|
|
429
|
-
await
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
embeddingModelPath: params.embeddingModelPath
|
|
436
|
-
}));
|
|
563
|
+
await updatePreset(presetPath, {
|
|
564
|
+
chatModel: params.chatModel,
|
|
565
|
+
embeddingModelIsDefault: params.embeddingModelIsDefault,
|
|
566
|
+
embeddingModelPath: params.embeddingModelPath,
|
|
567
|
+
defaultEmbeddingModelPath: params.defaultEmbeddingModelPath
|
|
568
|
+
});
|
|
437
569
|
const port = params.port ?? await findAvailableLlamaServerPort();
|
|
438
570
|
const rootUrl = `http://127.0.0.1:${port}`;
|
|
439
571
|
return {
|
|
440
572
|
command,
|
|
441
|
-
presetPath,
|
|
442
573
|
baseUrl: `${rootUrl}/v1`,
|
|
443
574
|
healthUrl: `${rootUrl}/health`,
|
|
444
575
|
args: [
|
|
@@ -452,8 +583,7 @@ async function prepareManagedLlamaServer(params) {
|
|
|
452
583
|
"2",
|
|
453
584
|
"--metrics",
|
|
454
585
|
"--no-ui"
|
|
455
|
-
]
|
|
456
|
-
backend: asset.backend
|
|
586
|
+
]
|
|
457
587
|
};
|
|
458
588
|
}
|
|
459
589
|
async function ensureManagedLlamaServerForChat(params) {
|
|
@@ -482,11 +612,14 @@ async function ensureManagedLlamaServerForChat(params) {
|
|
|
482
612
|
const configuredContext = params.model.params?.contextSize;
|
|
483
613
|
const port = Number(new URL(params.provider.baseUrl).port);
|
|
484
614
|
await prepareManagedLlamaServer({
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
615
|
+
chatModel: {
|
|
616
|
+
mode: "configure",
|
|
617
|
+
id: params.model.id,
|
|
618
|
+
path: chatModelPath,
|
|
619
|
+
contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : params.model.contextTokens,
|
|
620
|
+
maxTokens: params.model.maxTokens
|
|
621
|
+
},
|
|
622
|
+
defaultEmbeddingModelPath: path.join(cacheDir, "hf_ggml-org_embeddinggemma-300m-qat-Q8_0.gguf"),
|
|
490
623
|
port: Number.isInteger(port) && port > 0 ? port : void 0
|
|
491
624
|
});
|
|
492
625
|
})();
|
|
@@ -564,6 +697,14 @@ const preparedEmbeddingServers = /* @__PURE__ */ new Map();
|
|
|
564
697
|
function readLocalOptions(options) {
|
|
565
698
|
return options.local ?? {};
|
|
566
699
|
}
|
|
700
|
+
function readIdentityLocalOptions(options) {
|
|
701
|
+
const local = readLocalOptions(options);
|
|
702
|
+
const provider = options.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
703
|
+
return provider?.localService ? {
|
|
704
|
+
...local,
|
|
705
|
+
modelCacheDir: resolveLlamaCppModelCacheDir(provider)
|
|
706
|
+
} : local;
|
|
707
|
+
}
|
|
567
708
|
function createCacheKeyData(model, dimensions) {
|
|
568
709
|
return {
|
|
569
710
|
provider: "local",
|
|
@@ -571,14 +712,14 @@ function createCacheKeyData(model, dimensions) {
|
|
|
571
712
|
...typeof dimensions === "number" ? { outputDimensionality: dimensions } : {}
|
|
572
713
|
};
|
|
573
714
|
}
|
|
574
|
-
function resolveModelIdentity(local,
|
|
575
|
-
const
|
|
715
|
+
function resolveModelIdentity(local, dimensions) {
|
|
716
|
+
const embeddingModel = resolveLlamaCppEmbeddingModel(local);
|
|
717
|
+
const configuredCacheDir = embeddingModel.cacheDir;
|
|
576
718
|
const currentDefaultPath = path.resolve(configuredCacheDir, DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE);
|
|
577
719
|
const legacyDefaultPath = path.resolve(resolveLegacyLlamaCppModelCacheDir(), DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE);
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
cacheKeyData: createCacheKeyData(modelPath, dimensions),
|
|
720
|
+
if (!embeddingModel.isDefault) return {
|
|
721
|
+
model: embeddingModel.source,
|
|
722
|
+
cacheKeyData: createCacheKeyData(embeddingModel.source, dimensions),
|
|
582
723
|
aliases: []
|
|
583
724
|
};
|
|
584
725
|
const aliases = /* @__PURE__ */ new Set([
|
|
@@ -586,7 +727,7 @@ function resolveModelIdentity(local, modelPath, dimensions) {
|
|
|
586
727
|
legacyDefaultPath,
|
|
587
728
|
DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE
|
|
588
729
|
]);
|
|
589
|
-
if (
|
|
730
|
+
if (embeddingModel.source !== "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") aliases.add(embeddingModel.source);
|
|
590
731
|
return {
|
|
591
732
|
model: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL,
|
|
592
733
|
cacheKeyData: createCacheKeyData(DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, dimensions),
|
|
@@ -597,46 +738,30 @@ function resolveModelIdentity(local, modelPath, dimensions) {
|
|
|
597
738
|
};
|
|
598
739
|
}
|
|
599
740
|
function resolveConfiguredProvider(options) {
|
|
600
|
-
|
|
601
|
-
if (!provider?.localService || !provider.baseUrl) throw new Error("Local embeddings need the managed llama.cpp server config. Run `openclaw configure`, choose llama.cpp once, then retry `openclaw memory status --deep`.");
|
|
602
|
-
return provider;
|
|
741
|
+
return resolveManagedLlamaCppProviderConfig(options.config);
|
|
603
742
|
}
|
|
604
743
|
function resolveProviderPort(provider) {
|
|
605
744
|
const port = Number(new URL(provider.baseUrl ?? "").port);
|
|
606
745
|
if (!Number.isInteger(port) || port <= 0) throw new Error("Managed llama.cpp provider baseUrl must include a loopback port.");
|
|
607
746
|
return port;
|
|
608
747
|
}
|
|
609
|
-
async function prepareEmbeddingServer(options, embeddingSource) {
|
|
748
|
+
async function prepareEmbeddingServer(options, embeddingSource, embeddingModelIsDefault) {
|
|
610
749
|
const provider = resolveConfiguredProvider(options);
|
|
611
|
-
const configuredPrimary = options.config.agents?.defaults?.model;
|
|
612
|
-
const primaryRef = typeof configuredPrimary === "string" ? configuredPrimary : configuredPrimary?.primary;
|
|
613
|
-
const primaryId = primaryRef?.startsWith(`llama-cpp/`) ? primaryRef.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
|
|
614
|
-
const chatModel = provider.models.find((model) => model.id === primaryId) ?? provider.models.find((model) => model.id !== "gemma-4-e4b-it-q4_k_m") ?? provider.models[0];
|
|
615
|
-
if (!chatModel) throw new Error("Managed llama.cpp provider has no chat model preset.");
|
|
616
750
|
const cacheDir = resolveLlamaCppModelCacheDir(provider);
|
|
617
751
|
const key = JSON.stringify([
|
|
618
752
|
provider.baseUrl,
|
|
619
|
-
chatModel.id,
|
|
620
753
|
embeddingSource,
|
|
621
754
|
cacheDir
|
|
622
755
|
]);
|
|
623
756
|
const pending = preparedEmbeddingServers.get(key) ?? (async () => {
|
|
624
|
-
const [chatModelPath, embeddingModelPath] = await Promise.all([ensureLlamaCppModel({
|
|
625
|
-
source: resolveLlamaCppModelSource(chatModel),
|
|
626
|
-
cacheDir,
|
|
627
|
-
download: false
|
|
628
|
-
}), ensureLlamaCppModel({
|
|
629
|
-
source: embeddingSource,
|
|
630
|
-
cacheDir,
|
|
631
|
-
download: true
|
|
632
|
-
})]);
|
|
633
|
-
const configuredContext = chatModel.params?.contextSize;
|
|
634
757
|
await prepareManagedLlamaServer({
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
758
|
+
chatModel: { mode: "preserve" },
|
|
759
|
+
embeddingModelIsDefault,
|
|
760
|
+
embeddingModelPath: await ensureLlamaCppModel({
|
|
761
|
+
source: embeddingSource,
|
|
762
|
+
cacheDir,
|
|
763
|
+
download: true
|
|
764
|
+
}),
|
|
640
765
|
port: resolveProviderPort(provider)
|
|
641
766
|
});
|
|
642
767
|
})();
|
|
@@ -689,13 +814,13 @@ const llamaCppEmbeddingProviderAdapter = {
|
|
|
689
814
|
transport: "local",
|
|
690
815
|
formatSetupError: (error) => `Managed local embeddings are unavailable. Run \`openclaw configure\`, choose llama.cpp, and retry. ${error instanceof Error ? error.message : String(error)}`,
|
|
691
816
|
resolveIndexIdentity: (options) => {
|
|
692
|
-
|
|
693
|
-
return resolveModelIdentity(local, normalizeOptionalString(local.modelPath) ?? "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf", options.dimensions);
|
|
817
|
+
return resolveModelIdentity(readIdentityLocalOptions(options), options.dimensions);
|
|
694
818
|
},
|
|
695
819
|
create: async (options) => {
|
|
696
|
-
const local =
|
|
697
|
-
const
|
|
698
|
-
|
|
820
|
+
const local = readIdentityLocalOptions(options);
|
|
821
|
+
const embeddingModel = resolveLlamaCppEmbeddingModel(local);
|
|
822
|
+
const identity = resolveModelIdentity(local, options.dimensions);
|
|
823
|
+
await prepareEmbeddingServer(options, embeddingModel.source, embeddingModel.isDefault);
|
|
699
824
|
const genericAdapter = getEmbeddingProvider("openai-compatible", options.config);
|
|
700
825
|
if (!genericAdapter) throw new Error("OpenAI-compatible embedding transport is unavailable.");
|
|
701
826
|
const result = await genericAdapter.create({
|
|
@@ -705,7 +830,6 @@ const llamaCppEmbeddingProviderAdapter = {
|
|
|
705
830
|
remote: void 0
|
|
706
831
|
});
|
|
707
832
|
if (!result.provider) return result;
|
|
708
|
-
const identity = resolveModelIdentity(local, modelPath, options.dimensions);
|
|
709
833
|
return {
|
|
710
834
|
provider: wrapProvider({
|
|
711
835
|
provider: result.provider,
|
|
@@ -723,6 +847,667 @@ const llamaCppEmbeddingProviderAdapter = {
|
|
|
723
847
|
}
|
|
724
848
|
};
|
|
725
849
|
//#endregion
|
|
850
|
+
//#region extensions/llama-cpp/src/external-server/auth.ts
|
|
851
|
+
function hasLlamaServerAuthorizationHeader(headers) {
|
|
852
|
+
const record = asOptionalRecord(headers);
|
|
853
|
+
if (!record) return false;
|
|
854
|
+
return Object.entries(record).some(([name, value]) => name.trim().toLowerCase() === "authorization" && hasConfiguredSecretInput(value));
|
|
855
|
+
}
|
|
856
|
+
function shouldUseLlamaServerSyntheticAuth(providerConfig) {
|
|
857
|
+
const apiKey = normalizeOptionalSecretInput(providerConfig?.apiKey)?.trim();
|
|
858
|
+
return !(hasConfiguredSecretInput(providerConfig?.apiKey) && apiKey !== resolveLlamaCppSyntheticApiKey() && apiKey !== CUSTOM_LOCAL_AUTH_MARKER);
|
|
859
|
+
}
|
|
860
|
+
async function resolveLlamaServerProviderHeaders(params) {
|
|
861
|
+
const headers = asOptionalRecord(params.headers);
|
|
862
|
+
if (!headers) return;
|
|
863
|
+
const resolved = {};
|
|
864
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
865
|
+
if (!params.config) {
|
|
866
|
+
if (typeof value === "string" && value.trim()) resolved[name] = value.trim();
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
869
|
+
const path = `models.providers.${LLAMA_CPP_PROVIDER_ID}.headers.${name}`;
|
|
870
|
+
const header = await resolveConfiguredSecretInputString({
|
|
871
|
+
config: params.config,
|
|
872
|
+
env: params.env ?? process.env,
|
|
873
|
+
value,
|
|
874
|
+
path,
|
|
875
|
+
unresolvedReasonStyle: "detailed"
|
|
876
|
+
});
|
|
877
|
+
if (header.unresolvedRefReason) throw new Error(`${path}: ${header.unresolvedRefReason}`);
|
|
878
|
+
if (header.value) resolved[name] = header.value;
|
|
879
|
+
}
|
|
880
|
+
return Object.keys(resolved).length > 0 ? resolved : void 0;
|
|
881
|
+
}
|
|
882
|
+
async function resolveLlamaServerRuntimeApiKey(params) {
|
|
883
|
+
const apiKey = (await resolveApiKeyForProvider({
|
|
884
|
+
provider: LLAMA_CPP_PROVIDER_ID,
|
|
885
|
+
cfg: params.config,
|
|
886
|
+
agentDir: params.agentDir,
|
|
887
|
+
profileId: params.profileId,
|
|
888
|
+
lockedProfile: params.profileId !== void 0
|
|
889
|
+
})).apiKey?.trim();
|
|
890
|
+
return apiKey && !isNonSecretApiKeyMarker(apiKey) ? apiKey : void 0;
|
|
891
|
+
}
|
|
892
|
+
//#endregion
|
|
893
|
+
//#region extensions/llama-cpp/src/external-server/defaults.ts
|
|
894
|
+
const LLAMA_SERVER_DEFAULT_ORIGIN = "http://127.0.0.1:8080";
|
|
895
|
+
const LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR = "LLAMA_SERVER_API_KEY";
|
|
896
|
+
//#endregion
|
|
897
|
+
//#region extensions/llama-cpp/src/external-server/endpoint.ts
|
|
898
|
+
function toFetchableBaseUrl(value) {
|
|
899
|
+
if (/^[a-z][a-z\d+.-]*:\/\//iu.test(value)) return value;
|
|
900
|
+
return `http://${value}`;
|
|
901
|
+
}
|
|
902
|
+
/** Resolves the server origin and its OpenAI-compatible `/v1` inference base. */
|
|
903
|
+
function resolveLlamaServerEndpoint(configuredBaseUrl) {
|
|
904
|
+
const configured = configuredBaseUrl?.trim() || "http://127.0.0.1:8080";
|
|
905
|
+
const parsed = new URL(toFetchableBaseUrl(configured));
|
|
906
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new TypeError(`Unsupported llama-server protocol: ${parsed.protocol}`);
|
|
907
|
+
if (parsed.username || parsed.password) throw new TypeError("llama-server base URL must not contain credentials");
|
|
908
|
+
parsed.pathname = parsed.pathname.replace(/\/+$/u, "").replace(/\/v1$/iu, "") || "/";
|
|
909
|
+
parsed.search = "";
|
|
910
|
+
parsed.hash = "";
|
|
911
|
+
const origin = parsed.toString().replace(/\/$/u, "");
|
|
912
|
+
return {
|
|
913
|
+
origin,
|
|
914
|
+
inferenceBaseUrl: `${origin}/v1`
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
/** Canonicalizes persisted provider config for the shared OpenAI transport. */
|
|
918
|
+
function normalizeLlamaServerProviderConfig(provider) {
|
|
919
|
+
const endpoint = resolveLlamaServerEndpoint(provider.baseUrl);
|
|
920
|
+
const request = provider.request ?? {};
|
|
921
|
+
const normalizedRequest = typeof request.allowPrivateNetwork === "boolean" ? request : {
|
|
922
|
+
...request,
|
|
923
|
+
allowPrivateNetwork: true
|
|
924
|
+
};
|
|
925
|
+
return {
|
|
926
|
+
...provider,
|
|
927
|
+
baseUrl: endpoint.inferenceBaseUrl,
|
|
928
|
+
api: "openai-completions",
|
|
929
|
+
request: normalizedRequest
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
//#endregion
|
|
933
|
+
//#region extensions/llama-cpp/src/external-server/models.ts
|
|
934
|
+
function normalizeStatus(value) {
|
|
935
|
+
switch (value) {
|
|
936
|
+
case "unloaded":
|
|
937
|
+
case "loading":
|
|
938
|
+
case "loaded":
|
|
939
|
+
case "sleeping":
|
|
940
|
+
case "downloading": return value;
|
|
941
|
+
default: return "unknown";
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
function resolveContextWindow(props) {
|
|
945
|
+
return asPositiveSafeInteger(props?.default_generation_settings?.n_ctx) ?? asPositiveSafeInteger(props?.n_ctx) ?? SELF_HOSTED_DEFAULT_CONTEXT_WINDOW;
|
|
946
|
+
}
|
|
947
|
+
function resolveMaxTokens(props, contextWindow) {
|
|
948
|
+
const params = props?.default_generation_settings?.params;
|
|
949
|
+
const advertised = asPositiveSafeInteger(params?.max_tokens) ?? asPositiveSafeInteger(params?.n_predict);
|
|
950
|
+
return Math.min(advertised ?? SELF_HOSTED_DEFAULT_MAX_TOKENS, contextWindow);
|
|
951
|
+
}
|
|
952
|
+
function resolveInput(row, props) {
|
|
953
|
+
const advertised = row.architecture?.input_modalities;
|
|
954
|
+
return Array.isArray(advertised) && advertised.includes("image") || props?.modalities?.vision === true ? ["text", "image"] : ["text"];
|
|
955
|
+
}
|
|
956
|
+
function buildCompat(props) {
|
|
957
|
+
const caps = props?.chat_template_caps;
|
|
958
|
+
return {
|
|
959
|
+
supportsStore: false,
|
|
960
|
+
supportsDeveloperRole: false,
|
|
961
|
+
supportsReasoningEffort: false,
|
|
962
|
+
supportsTemperature: true,
|
|
963
|
+
supportsUsageInStreaming: true,
|
|
964
|
+
supportsTools: asBoolean(caps?.supports_tool_calls) === true,
|
|
965
|
+
supportsStrictMode: false,
|
|
966
|
+
supportsJsonSchemaResponseFormat: true,
|
|
967
|
+
requiresStringContent: !(asBoolean(caps?.supports_typed_content) === true),
|
|
968
|
+
maxTokensField: "max_tokens"
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
/** Maps one llama-server model row plus optional runtime properties into OpenClaw config. */
|
|
972
|
+
function mapLlamaServerModel(row, props) {
|
|
973
|
+
const id = typeof row.id === "string" ? row.id.trim() : "";
|
|
974
|
+
if (!id || row.object !== void 0 && row.object !== "model") return null;
|
|
975
|
+
const contextWindow = resolveContextWindow(props);
|
|
976
|
+
return {
|
|
977
|
+
config: {
|
|
978
|
+
id,
|
|
979
|
+
name: id,
|
|
980
|
+
reasoning: false,
|
|
981
|
+
input: resolveInput(row, props),
|
|
982
|
+
cost: { ...SELF_HOSTED_DEFAULT_COST },
|
|
983
|
+
contextWindow,
|
|
984
|
+
contextTokens: contextWindow,
|
|
985
|
+
maxTokens: resolveMaxTokens(props, contextWindow),
|
|
986
|
+
compat: buildCompat(props)
|
|
987
|
+
},
|
|
988
|
+
status: normalizeStatus(row.status?.value),
|
|
989
|
+
failed: row.status?.failed === true
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
/** Keeps explicit rows first and appends models discovered from the server. */
|
|
993
|
+
function mergeLlamaServerModels(params) {
|
|
994
|
+
const explicit = Array.isArray(params.explicitModels) ? params.explicitModels : [];
|
|
995
|
+
const merged = [...explicit];
|
|
996
|
+
const seen = new Set(explicit.map((model) => model.id));
|
|
997
|
+
for (const discovered of params.discoveredModels) {
|
|
998
|
+
if (seen.has(discovered.config.id)) continue;
|
|
999
|
+
seen.add(discovered.config.id);
|
|
1000
|
+
merged.push(discovered.config);
|
|
1001
|
+
}
|
|
1002
|
+
return merged;
|
|
1003
|
+
}
|
|
1004
|
+
function buildLlamaServerProviderConfig(params) {
|
|
1005
|
+
return normalizeLlamaServerProviderConfig({
|
|
1006
|
+
...params.configured,
|
|
1007
|
+
baseUrl: params.configured?.baseUrl ?? "http://127.0.0.1:8080",
|
|
1008
|
+
models: mergeLlamaServerModels({
|
|
1009
|
+
explicitModels: params.configured?.models,
|
|
1010
|
+
discoveredModels: params.discoveredModels
|
|
1011
|
+
})
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
//#endregion
|
|
1015
|
+
//#region extensions/llama-cpp/src/external-server/discovery.ts
|
|
1016
|
+
/** Discovers llama-server models without loading, waking, or unloading them. */
|
|
1017
|
+
async function discoverLlamaServer(params) {
|
|
1018
|
+
const endpoint = resolveLlamaServerEndpoint(params.baseUrl);
|
|
1019
|
+
const apiKey = params.apiKey?.trim();
|
|
1020
|
+
const cacheTtlMs = Boolean(apiKey && !isNonSecretApiKeyMarker(apiKey)) || Boolean(params.headers && Object.keys(params.headers).length > 0) ? 0 : Math.max(0, params.cacheTtlMs ?? 3e4);
|
|
1021
|
+
return await getCachedLiveCatalogValue({
|
|
1022
|
+
keyParts: [
|
|
1023
|
+
"llama-cpp",
|
|
1024
|
+
"external",
|
|
1025
|
+
endpoint.origin
|
|
1026
|
+
],
|
|
1027
|
+
ttlMs: cacheTtlMs,
|
|
1028
|
+
shouldCache: (result) => result.kind === "success",
|
|
1029
|
+
load: async () => {
|
|
1030
|
+
const result = await discoverOpenAICompatibleLocalModels({
|
|
1031
|
+
baseUrl: endpoint.inferenceBaseUrl,
|
|
1032
|
+
serverBaseUrl: endpoint.origin,
|
|
1033
|
+
apiKey: params.apiKey,
|
|
1034
|
+
headers: params.headers,
|
|
1035
|
+
label: "llama-server",
|
|
1036
|
+
healthPath: "/health",
|
|
1037
|
+
modelsPathOrder: "server-first",
|
|
1038
|
+
routerModelProps: true,
|
|
1039
|
+
timeoutMs: params.timeoutMs ?? 5e3,
|
|
1040
|
+
signal: params.signal,
|
|
1041
|
+
rawResult: true
|
|
1042
|
+
});
|
|
1043
|
+
if (result.kind !== "success") return {
|
|
1044
|
+
...result,
|
|
1045
|
+
endpoint
|
|
1046
|
+
};
|
|
1047
|
+
return {
|
|
1048
|
+
kind: "success",
|
|
1049
|
+
endpoint,
|
|
1050
|
+
models: result.rows.flatMap(({ model, props }) => {
|
|
1051
|
+
const mapped = mapLlamaServerModel(model, props);
|
|
1052
|
+
return mapped ? [mapped] : [];
|
|
1053
|
+
})
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
//#endregion
|
|
1059
|
+
//#region extensions/llama-cpp/src/external-server/provider.ts
|
|
1060
|
+
/** Discovers external llama-server models for provider runtime resolution. */
|
|
1061
|
+
async function discoverLlamaServerProvider(ctx) {
|
|
1062
|
+
const configured = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1063
|
+
const auth = ctx.resolveProviderApiKey(LLAMA_CPP_PROVIDER_ID);
|
|
1064
|
+
const headers = await resolveLlamaServerProviderHeaders({
|
|
1065
|
+
config: ctx.config,
|
|
1066
|
+
env: ctx.env,
|
|
1067
|
+
headers: configured?.headers
|
|
1068
|
+
});
|
|
1069
|
+
const discovery = await discoverLlamaServer({
|
|
1070
|
+
baseUrl: configured?.baseUrl,
|
|
1071
|
+
apiKey: hasLlamaServerAuthorizationHeader(headers) ? void 0 : auth.discoveryApiKey ?? auth.apiKey,
|
|
1072
|
+
headers
|
|
1073
|
+
});
|
|
1074
|
+
if (discovery.kind !== "success") return configured ? { provider: buildLlamaServerProviderConfig({
|
|
1075
|
+
configured,
|
|
1076
|
+
discoveredModels: []
|
|
1077
|
+
}) } : null;
|
|
1078
|
+
return { provider: buildLlamaServerProviderConfig({
|
|
1079
|
+
configured: {
|
|
1080
|
+
...configured,
|
|
1081
|
+
baseUrl: discovery.endpoint.inferenceBaseUrl,
|
|
1082
|
+
models: configured?.models ?? []
|
|
1083
|
+
},
|
|
1084
|
+
discoveredModels: discovery.models
|
|
1085
|
+
}) };
|
|
1086
|
+
}
|
|
1087
|
+
async function prepareLlamaServerDynamicModel(ctx) {
|
|
1088
|
+
const apiKey = await resolveLlamaServerRuntimeApiKey({
|
|
1089
|
+
config: ctx.config,
|
|
1090
|
+
agentDir: ctx.agentDir,
|
|
1091
|
+
profileId: ctx.authProfileId
|
|
1092
|
+
});
|
|
1093
|
+
const headers = await resolveLlamaServerProviderHeaders({
|
|
1094
|
+
config: ctx.config,
|
|
1095
|
+
env: process.env,
|
|
1096
|
+
headers: ctx.providerConfig?.headers
|
|
1097
|
+
});
|
|
1098
|
+
const discovery = await discoverLlamaServer({
|
|
1099
|
+
baseUrl: ctx.providerConfig?.baseUrl,
|
|
1100
|
+
apiKey: hasLlamaServerAuthorizationHeader(headers) ? void 0 : apiKey,
|
|
1101
|
+
headers,
|
|
1102
|
+
cacheTtlMs: 0
|
|
1103
|
+
});
|
|
1104
|
+
const model = discovery.kind === "success" ? discovery.models.find((entry) => entry.config.id === ctx.modelId) : void 0;
|
|
1105
|
+
if (!model) return;
|
|
1106
|
+
return {
|
|
1107
|
+
...model.config,
|
|
1108
|
+
provider: LLAMA_CPP_PROVIDER_ID,
|
|
1109
|
+
api: ctx.providerConfig?.api ?? "openai-completions",
|
|
1110
|
+
baseUrl: resolveLlamaServerEndpoint(ctx.providerConfig?.baseUrl).inferenceBaseUrl,
|
|
1111
|
+
input: model.config.input.filter((entry) => entry === "text" || entry === "image")
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
//#endregion
|
|
1115
|
+
//#region extensions/llama-cpp/src/auth-config.ts
|
|
1116
|
+
const LLAMA_CPP_DEFAULT_PROFILE_ID = `${LLAMA_CPP_PROVIDER_ID}:default`;
|
|
1117
|
+
function buildLlamaCppAuthProfileRemovalPatch(config) {
|
|
1118
|
+
const profileExists = Boolean(config.auth?.profiles?.[LLAMA_CPP_DEFAULT_PROFILE_ID]);
|
|
1119
|
+
const referencedOrders = Object.entries(config.auth?.order ?? {}).filter(([, ids]) => ids.includes(LLAMA_CPP_DEFAULT_PROFILE_ID));
|
|
1120
|
+
if (!profileExists && referencedOrders.length === 0) return {};
|
|
1121
|
+
const authPatch = {};
|
|
1122
|
+
if (profileExists) Reflect.set(authPatch, "profiles", { [LLAMA_CPP_DEFAULT_PROFILE_ID]: void 0 });
|
|
1123
|
+
if (referencedOrders.length > 0) Reflect.set(authPatch, "order", Object.fromEntries(referencedOrders.map(([providerId, ids]) => {
|
|
1124
|
+
const next = ids.filter((id) => id !== LLAMA_CPP_DEFAULT_PROFILE_ID);
|
|
1125
|
+
return [providerId, next.length > 0 ? next : void 0];
|
|
1126
|
+
})));
|
|
1127
|
+
return { auth: authPatch };
|
|
1128
|
+
}
|
|
1129
|
+
//#endregion
|
|
1130
|
+
//#region extensions/llama-cpp/src/external-server/setup.ts
|
|
1131
|
+
function selectSetupModelId(discovery) {
|
|
1132
|
+
const candidates = discovery.models.filter((model) => !model.failed);
|
|
1133
|
+
const ready = candidates.filter((model) => model.status === "loaded" || model.status === "sleeping");
|
|
1134
|
+
const ids = (ready.length > 0 ? ready : candidates).map((model) => model.config.id);
|
|
1135
|
+
return selectPreferredLocalModelId(ids) ?? ids[0];
|
|
1136
|
+
}
|
|
1137
|
+
function describeDiscoveryFailure(result) {
|
|
1138
|
+
switch (result.kind) {
|
|
1139
|
+
case "unreachable": return `llama-server could not be reached at ${result.endpoint.origin}.`;
|
|
1140
|
+
case "http-error": return `llama-server returned HTTP ${result.status} for ${result.path} at ${result.endpoint.origin}.`;
|
|
1141
|
+
case "invalid-response": return `llama-server returned an invalid response from ${result.path} at ${result.endpoint.origin}.`;
|
|
1142
|
+
default: throw new Error("Unexpected llama-server discovery result");
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
function stripAuthOverrides(provider, removeAuthorization) {
|
|
1146
|
+
if (!provider) return provider;
|
|
1147
|
+
const headers = removeAuthorization ? stripAuthorizationHeader(provider.headers) : provider.headers;
|
|
1148
|
+
return {
|
|
1149
|
+
...provider,
|
|
1150
|
+
auth: void 0,
|
|
1151
|
+
apiKey: void 0,
|
|
1152
|
+
...removeAuthorization ? { headers } : {}
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
function stripEndpointCredentials(provider) {
|
|
1156
|
+
if (!provider) return;
|
|
1157
|
+
const { localService: _localService, ...external } = provider;
|
|
1158
|
+
if (!provider.localService) return {
|
|
1159
|
+
...external,
|
|
1160
|
+
auth: void 0,
|
|
1161
|
+
apiKey: void 0,
|
|
1162
|
+
headers: void 0
|
|
1163
|
+
};
|
|
1164
|
+
const { auth: _auth, apiKey: _apiKey, headers: _headers, localService: _managedService, models: _managedModels, params: managedParams, timeoutSeconds: _managedTimeout, ...externalProvider } = provider;
|
|
1165
|
+
const { modelCacheDir: _modelCacheDir, ...params } = managedParams ?? {};
|
|
1166
|
+
return {
|
|
1167
|
+
...externalProvider,
|
|
1168
|
+
models: [],
|
|
1169
|
+
params: Object.keys(params).length > 0 ? params : void 0
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
function hasEndpointChanged(provider, baseUrl) {
|
|
1173
|
+
if (!provider) return false;
|
|
1174
|
+
return resolveLlamaServerEndpoint(provider.baseUrl ?? "http://127.0.0.1:8080").inferenceBaseUrl !== resolveLlamaServerEndpoint(baseUrl).inferenceBaseUrl;
|
|
1175
|
+
}
|
|
1176
|
+
function stripLlamaServerEndpointAuth(config) {
|
|
1177
|
+
const withoutProfile = removeAuthProfileConfig(config, LLAMA_CPP_DEFAULT_PROFILE_ID);
|
|
1178
|
+
const provider = withoutProfile.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1179
|
+
const endpointSafeProvider = stripEndpointCredentials(provider);
|
|
1180
|
+
if (!endpointSafeProvider) return withoutProfile;
|
|
1181
|
+
return {
|
|
1182
|
+
...withoutProfile,
|
|
1183
|
+
models: {
|
|
1184
|
+
...withoutProfile.models,
|
|
1185
|
+
providers: {
|
|
1186
|
+
...withoutProfile.models?.providers,
|
|
1187
|
+
[LLAMA_CPP_PROVIDER_ID]: endpointSafeProvider
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
function stripAuthorizationHeader(headers) {
|
|
1193
|
+
const filtered = Object.fromEntries(Object.entries(headers ?? {}).filter(([name]) => name.toLowerCase() !== "authorization"));
|
|
1194
|
+
return Object.keys(filtered).length > 0 ? filtered : void 0;
|
|
1195
|
+
}
|
|
1196
|
+
function buildExistingProviderConfig(params) {
|
|
1197
|
+
const configured = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1198
|
+
const endpointSafe = params.resetEndpoint ? stripEndpointCredentials(configured) : configured;
|
|
1199
|
+
const existing = params.persistence.kind === "preserve" ? endpointSafe : stripAuthOverrides(endpointSafe, params.persistence.kind === "upsert");
|
|
1200
|
+
return buildLlamaServerProviderConfig({
|
|
1201
|
+
configured: {
|
|
1202
|
+
...existing,
|
|
1203
|
+
baseUrl: params.discovery.endpoint.inferenceBaseUrl,
|
|
1204
|
+
models: existing?.models ?? []
|
|
1205
|
+
},
|
|
1206
|
+
discoveredModels: params.discovery.models
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
function buildSetupResult$1(params) {
|
|
1210
|
+
return {
|
|
1211
|
+
profiles: params.persistence.kind === "upsert" ? [{
|
|
1212
|
+
profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
|
|
1213
|
+
credential: buildApiKeyCredential(LLAMA_CPP_PROVIDER_ID, params.persistence.credential, void 0, { config: params.config })
|
|
1214
|
+
}] : [],
|
|
1215
|
+
defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${params.modelId}`,
|
|
1216
|
+
configPatch: {
|
|
1217
|
+
...params.persistence.kind === "remove" ? buildLlamaCppAuthProfileRemovalPatch(params.config) : {},
|
|
1218
|
+
models: {
|
|
1219
|
+
mode: params.config.models?.mode ?? "merge",
|
|
1220
|
+
providers: { [LLAMA_CPP_PROVIDER_ID]: buildExistingProviderConfig(params) }
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
async function removeDefaultAuthProfile(agentDir) {
|
|
1226
|
+
if (!await removeProviderAuthProfilesWithLock({
|
|
1227
|
+
agentDir,
|
|
1228
|
+
provider: "llama-cpp",
|
|
1229
|
+
profileIds: [LLAMA_CPP_DEFAULT_PROFILE_ID]
|
|
1230
|
+
})) throw new Error("Failed to remove the previous llama-server auth profile; wait a moment and retry.");
|
|
1231
|
+
}
|
|
1232
|
+
async function discoverForSetup(ctx) {
|
|
1233
|
+
const provider = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1234
|
+
if (provider?.localService) return null;
|
|
1235
|
+
try {
|
|
1236
|
+
const headers = await resolveLlamaServerProviderHeaders({
|
|
1237
|
+
config: ctx.config,
|
|
1238
|
+
env: ctx.env,
|
|
1239
|
+
headers: provider?.headers
|
|
1240
|
+
});
|
|
1241
|
+
const apiKey = !hasLlamaServerAuthorizationHeader(headers) ? await resolveLlamaServerRuntimeApiKey({ config: ctx.config }) : void 0;
|
|
1242
|
+
const discovery = await discoverLlamaServer({
|
|
1243
|
+
baseUrl: provider?.baseUrl ?? "http://127.0.0.1:8080",
|
|
1244
|
+
apiKey,
|
|
1245
|
+
headers,
|
|
1246
|
+
signal: ctx.signal,
|
|
1247
|
+
cacheTtlMs: 0
|
|
1248
|
+
});
|
|
1249
|
+
return discovery.kind === "success" ? discovery : null;
|
|
1250
|
+
} catch {
|
|
1251
|
+
return null;
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
async function discoverWithAccess(params) {
|
|
1255
|
+
return await discoverLlamaServer({
|
|
1256
|
+
baseUrl: params.baseUrl,
|
|
1257
|
+
apiKey: params.apiKey,
|
|
1258
|
+
headers: params.headers,
|
|
1259
|
+
signal: params.signal,
|
|
1260
|
+
cacheTtlMs: 0
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
/** Read-only discovery for the guided local-provider setup ladder. */
|
|
1264
|
+
async function detectLlamaServerSetup(ctx) {
|
|
1265
|
+
const discovery = await discoverForSetup(ctx);
|
|
1266
|
+
if (!discovery) return null;
|
|
1267
|
+
const modelId = selectSetupModelId(discovery);
|
|
1268
|
+
if (!modelId) return null;
|
|
1269
|
+
return {
|
|
1270
|
+
modelRef: `${LLAMA_CPP_PROVIDER_ID}/${modelId}`,
|
|
1271
|
+
detail: `${modelId} at ${discovery.endpoint.origin}`
|
|
1272
|
+
};
|
|
1273
|
+
}
|
|
1274
|
+
/** Rechecks one guided candidate and returns the config needed for a live probe. */
|
|
1275
|
+
async function prepareLlamaServerSetup(ctx) {
|
|
1276
|
+
const discovery = await discoverForSetup(ctx);
|
|
1277
|
+
if (!discovery) return null;
|
|
1278
|
+
const prefix = `${LLAMA_CPP_PROVIDER_ID}/`;
|
|
1279
|
+
const modelId = ctx.modelRef.startsWith(prefix) ? ctx.modelRef.slice(prefix.length) : "";
|
|
1280
|
+
if (!modelId || !discovery.models.some((model) => model.config.id === modelId)) return null;
|
|
1281
|
+
return buildSetupResult$1({
|
|
1282
|
+
config: ctx.config,
|
|
1283
|
+
discovery,
|
|
1284
|
+
modelId,
|
|
1285
|
+
resetEndpoint: false,
|
|
1286
|
+
persistence: { kind: "preserve" }
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
/** Interactive setup for an existing llama-server endpoint. */
|
|
1290
|
+
async function runLlamaServerSetup(ctx) {
|
|
1291
|
+
const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1292
|
+
const defaultOrigin = resolveLlamaServerEndpoint(existing?.baseUrl).origin;
|
|
1293
|
+
const endpoint = resolveLlamaServerEndpoint(await ctx.prompter.text({
|
|
1294
|
+
message: `${LLAMA_CPP_PROVIDER_LABEL} URL`,
|
|
1295
|
+
initialValue: defaultOrigin,
|
|
1296
|
+
placeholder: LLAMA_SERVER_DEFAULT_ORIGIN,
|
|
1297
|
+
validate: (value) => value?.trim() ? void 0 : "Required"
|
|
1298
|
+
}));
|
|
1299
|
+
const endpointChanged = Boolean(existing?.localService) || hasEndpointChanged(existing, endpoint.inferenceBaseUrl);
|
|
1300
|
+
const resolvedHeaders = endpointChanged ? void 0 : await resolveLlamaServerProviderHeaders({
|
|
1301
|
+
config: ctx.config,
|
|
1302
|
+
env: ctx.env,
|
|
1303
|
+
headers: existing?.headers
|
|
1304
|
+
});
|
|
1305
|
+
const usesApiKey = await ctx.prompter.confirm({
|
|
1306
|
+
message: "Does this llama-server require an API key?",
|
|
1307
|
+
initialValue: false
|
|
1308
|
+
});
|
|
1309
|
+
let apiKey;
|
|
1310
|
+
let headers = resolvedHeaders;
|
|
1311
|
+
let persistence;
|
|
1312
|
+
if (!usesApiKey) persistence = { kind: "remove" };
|
|
1313
|
+
else {
|
|
1314
|
+
const hasConfiguredProfile = Boolean(ctx.config.auth?.profiles?.[LLAMA_CPP_DEFAULT_PROFILE_ID]);
|
|
1315
|
+
const profileApiKey = !endpointChanged && !hasLlamaServerAuthorizationHeader(resolvedHeaders) && hasConfiguredProfile ? await resolveLlamaServerRuntimeApiKey({
|
|
1316
|
+
config: ctx.config,
|
|
1317
|
+
agentDir: ctx.agentDir,
|
|
1318
|
+
profileId: LLAMA_CPP_DEFAULT_PROFILE_ID
|
|
1319
|
+
}) : void 0;
|
|
1320
|
+
if (profileApiKey) {
|
|
1321
|
+
apiKey = profileApiKey;
|
|
1322
|
+
persistence = { kind: "preserve" };
|
|
1323
|
+
} else {
|
|
1324
|
+
let credentialInput;
|
|
1325
|
+
apiKey = await ensureApiKeyFromEnvOrPrompt({
|
|
1326
|
+
config: endpointChanged ? stripLlamaServerEndpointAuth(ctx.config) : ctx.config,
|
|
1327
|
+
env: endpointChanged ? {} : ctx.env,
|
|
1328
|
+
provider: LLAMA_CPP_PROVIDER_ID,
|
|
1329
|
+
envLabel: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
|
|
1330
|
+
promptMessage: "Enter the llama-server API key",
|
|
1331
|
+
normalize: (value) => value.trim(),
|
|
1332
|
+
validate: (value) => value.trim() ? void 0 : "Required",
|
|
1333
|
+
prompter: ctx.prompter,
|
|
1334
|
+
secretInputMode: ctx.secretInputMode,
|
|
1335
|
+
setCredential: async (input) => {
|
|
1336
|
+
credentialInput = input;
|
|
1337
|
+
}
|
|
1338
|
+
});
|
|
1339
|
+
if (credentialInput === void 0) throw new Error("llama-server API-key setup did not produce a credential");
|
|
1340
|
+
headers = stripAuthorizationHeader(resolvedHeaders);
|
|
1341
|
+
persistence = {
|
|
1342
|
+
kind: "upsert",
|
|
1343
|
+
credential: credentialInput
|
|
1344
|
+
};
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
const discovery = await discoverWithAccess({
|
|
1348
|
+
baseUrl: endpoint.inferenceBaseUrl,
|
|
1349
|
+
apiKey,
|
|
1350
|
+
headers,
|
|
1351
|
+
signal: ctx.signal
|
|
1352
|
+
});
|
|
1353
|
+
if (discovery.kind !== "success") throw new Error(describeDiscoveryFailure(discovery));
|
|
1354
|
+
const modelId = selectSetupModelId(discovery);
|
|
1355
|
+
if (!modelId) throw new Error(`No llama-server text models were found at ${discovery.endpoint.origin}.`);
|
|
1356
|
+
if (persistence.kind === "remove") await removeDefaultAuthProfile(ctx.agentDir);
|
|
1357
|
+
return buildSetupResult$1({
|
|
1358
|
+
config: ctx.config,
|
|
1359
|
+
discovery,
|
|
1360
|
+
modelId,
|
|
1361
|
+
resetEndpoint: endpointChanged,
|
|
1362
|
+
persistence
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
async function validateNonInteractiveDiscovery(ctx) {
|
|
1366
|
+
const configuredProvider = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1367
|
+
const baseUrl = normalizeOptionalSecretInput(ctx.opts.customBaseUrl) ?? configuredProvider?.baseUrl ?? "http://127.0.0.1:8080";
|
|
1368
|
+
const endpointChanged = Boolean(configuredProvider?.localService) || hasEndpointChanged(configuredProvider, baseUrl);
|
|
1369
|
+
const providerApiKey = normalizeOptionalSecretInput(ctx.opts.llamaServerApiKey);
|
|
1370
|
+
const customApiKey = normalizeOptionalSecretInput(ctx.opts.customApiKey);
|
|
1371
|
+
const authoredApiKey = providerApiKey ?? customApiKey;
|
|
1372
|
+
const hasAuthoredApiKey = authoredApiKey !== void 0;
|
|
1373
|
+
const resolvedApiKey = await ctx.resolveApiKey({
|
|
1374
|
+
provider: LLAMA_CPP_PROVIDER_ID,
|
|
1375
|
+
flagValue: authoredApiKey,
|
|
1376
|
+
flagName: providerApiKey === void 0 ? "--custom-api-key" : "--llama-server-api-key",
|
|
1377
|
+
envVar: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
|
|
1378
|
+
envVarName: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
|
|
1379
|
+
required: false
|
|
1380
|
+
});
|
|
1381
|
+
const resolvedHeaders = endpointChanged ? void 0 : await resolveLlamaServerProviderHeaders({
|
|
1382
|
+
config: ctx.config,
|
|
1383
|
+
env: process.env,
|
|
1384
|
+
headers: configuredProvider?.headers
|
|
1385
|
+
});
|
|
1386
|
+
let apiKey;
|
|
1387
|
+
let headers = resolvedHeaders;
|
|
1388
|
+
let persistence;
|
|
1389
|
+
if (hasAuthoredApiKey && resolvedApiKey) {
|
|
1390
|
+
apiKey = resolvedApiKey.key;
|
|
1391
|
+
headers = stripAuthorizationHeader(resolvedHeaders);
|
|
1392
|
+
persistence = {
|
|
1393
|
+
kind: "upsert",
|
|
1394
|
+
credential: resolvedApiKey
|
|
1395
|
+
};
|
|
1396
|
+
} else if (endpointChanged || hasLlamaServerAuthorizationHeader(resolvedHeaders)) persistence = { kind: "remove" };
|
|
1397
|
+
else if (resolvedApiKey?.source === "profile") {
|
|
1398
|
+
apiKey = resolvedApiKey.key;
|
|
1399
|
+
persistence = { kind: "preserve" };
|
|
1400
|
+
} else if (resolvedApiKey) {
|
|
1401
|
+
apiKey = resolvedApiKey.key;
|
|
1402
|
+
persistence = {
|
|
1403
|
+
kind: "upsert",
|
|
1404
|
+
credential: resolvedApiKey
|
|
1405
|
+
};
|
|
1406
|
+
} else persistence = { kind: "remove" };
|
|
1407
|
+
const discovery = await discoverWithAccess({
|
|
1408
|
+
baseUrl,
|
|
1409
|
+
apiKey,
|
|
1410
|
+
headers
|
|
1411
|
+
});
|
|
1412
|
+
if (discovery.kind !== "success") {
|
|
1413
|
+
ctx.runtime.error(describeDiscoveryFailure(discovery));
|
|
1414
|
+
ctx.runtime.exit(1);
|
|
1415
|
+
return null;
|
|
1416
|
+
}
|
|
1417
|
+
const requestedModelId = normalizeOptionalSecretInput(ctx.opts.customModelId);
|
|
1418
|
+
const modelId = requestedModelId ?? selectSetupModelId(discovery);
|
|
1419
|
+
if (!modelId || !discovery.models.some((model) => model.config.id === modelId)) {
|
|
1420
|
+
const available = discovery.models.map((model) => model.config.id).join(", ");
|
|
1421
|
+
ctx.runtime.error(requestedModelId ? `llama-server model ${requestedModelId} was not found. Available models: ${available}` : `No llama-server text models were found at ${discovery.endpoint.origin}.`);
|
|
1422
|
+
ctx.runtime.exit(1);
|
|
1423
|
+
return null;
|
|
1424
|
+
}
|
|
1425
|
+
return {
|
|
1426
|
+
discovery,
|
|
1427
|
+
modelId,
|
|
1428
|
+
resetEndpoint: endpointChanged,
|
|
1429
|
+
persistence
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
async function validateLlamaServerNonInteractive(ctx) {
|
|
1433
|
+
return Boolean(await validateNonInteractiveDiscovery(ctx));
|
|
1434
|
+
}
|
|
1435
|
+
/** Non-interactive setup with optional API-key persistence. */
|
|
1436
|
+
async function configureLlamaServerNonInteractive(ctx) {
|
|
1437
|
+
const validated = await validateNonInteractiveDiscovery(ctx);
|
|
1438
|
+
if (!validated) return null;
|
|
1439
|
+
const providerConfig = buildExistingProviderConfig({
|
|
1440
|
+
config: ctx.config,
|
|
1441
|
+
discovery: validated.discovery,
|
|
1442
|
+
resetEndpoint: validated.resetEndpoint,
|
|
1443
|
+
persistence: validated.persistence
|
|
1444
|
+
});
|
|
1445
|
+
let config = {
|
|
1446
|
+
...ctx.config,
|
|
1447
|
+
models: {
|
|
1448
|
+
...ctx.config.models,
|
|
1449
|
+
mode: ctx.config.models?.mode ?? "merge",
|
|
1450
|
+
providers: {
|
|
1451
|
+
...ctx.config.models?.providers,
|
|
1452
|
+
[LLAMA_CPP_PROVIDER_ID]: providerConfig
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
};
|
|
1456
|
+
if (validated.persistence.kind === "upsert") {
|
|
1457
|
+
const credential = ctx.toApiKeyCredential({
|
|
1458
|
+
provider: LLAMA_CPP_PROVIDER_ID,
|
|
1459
|
+
resolved: validated.persistence.credential
|
|
1460
|
+
});
|
|
1461
|
+
if (!credential) return null;
|
|
1462
|
+
await upsertAuthProfileWithLock({
|
|
1463
|
+
profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
|
|
1464
|
+
credential,
|
|
1465
|
+
agentDir: ctx.agentDir
|
|
1466
|
+
});
|
|
1467
|
+
config = applyAuthProfileConfig(config, {
|
|
1468
|
+
profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
|
|
1469
|
+
provider: LLAMA_CPP_PROVIDER_ID,
|
|
1470
|
+
mode: "api_key"
|
|
1471
|
+
});
|
|
1472
|
+
} else if (validated.persistence.kind === "remove") {
|
|
1473
|
+
await removeDefaultAuthProfile(ctx.agentDir);
|
|
1474
|
+
config = removeAuthProfileConfig(config, LLAMA_CPP_DEFAULT_PROFILE_ID);
|
|
1475
|
+
}
|
|
1476
|
+
ctx.runtime.log(`Default ${LLAMA_CPP_PROVIDER_LABEL} model: ${validated.modelId}`);
|
|
1477
|
+
return applyProviderDefaultModel(config, `${LLAMA_CPP_PROVIDER_ID}/${validated.modelId}`);
|
|
1478
|
+
}
|
|
1479
|
+
//#endregion
|
|
1480
|
+
//#region extensions/llama-cpp/src/external-server/stream.ts
|
|
1481
|
+
/** Maps shared structured-output requests to the shape accepted by older llama-server builds. */
|
|
1482
|
+
function normalizeLlamaServerResponseFormat(payload, requestedResponseFormat) {
|
|
1483
|
+
const responseFormat = isRecord(payload.response_format) ? payload.response_format : requestedResponseFormat;
|
|
1484
|
+
if (!responseFormat || responseFormat.type === "text") return;
|
|
1485
|
+
const schema = responseFormat.type === "json_schema" ? isRecord(responseFormat.json_schema) ? responseFormat.json_schema.schema : responseFormat.schema : responseFormat.type === "json_object" ? responseFormat.schema : responseFormat;
|
|
1486
|
+
if (isRecord(schema)) payload.response_format = {
|
|
1487
|
+
type: "json_object",
|
|
1488
|
+
schema
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
/** Keeps the shared OpenAI transport and adjusts llama-server request compatibility. */
|
|
1492
|
+
function wrapLlamaServerStream(ctx) {
|
|
1493
|
+
const underlying = ctx.streamFn ?? streamSimple;
|
|
1494
|
+
return (model, context, options) => {
|
|
1495
|
+
if (model.provider !== "llama-cpp") return underlying(model, context, options);
|
|
1496
|
+
const onPayload = options?.onPayload;
|
|
1497
|
+
return underlying(model, context, {
|
|
1498
|
+
...options,
|
|
1499
|
+
onPayload: async (payload, requestModel) => {
|
|
1500
|
+
const customized = await onPayload?.(payload, requestModel) ?? payload;
|
|
1501
|
+
if (isRecord(customized)) {
|
|
1502
|
+
if (ctx.thinkingLevel === "off") setQwenChatTemplateThinking(customized, false);
|
|
1503
|
+
normalizeLlamaServerResponseFormat(customized, options?.responseFormat);
|
|
1504
|
+
}
|
|
1505
|
+
return customized;
|
|
1506
|
+
}
|
|
1507
|
+
});
|
|
1508
|
+
};
|
|
1509
|
+
}
|
|
1510
|
+
//#endregion
|
|
726
1511
|
//#region extensions/llama-cpp/src/setup.ts
|
|
727
1512
|
const BYTES_PER_GB = 1e9;
|
|
728
1513
|
const BYTES_PER_MB = 1e6;
|
|
@@ -734,13 +1519,20 @@ function formatDownloadProgress(label, params) {
|
|
|
734
1519
|
function formatRamGb(totalmemBytes) {
|
|
735
1520
|
return (totalmemBytes / 1024 ** 3).toFixed(1).replace(/\.0$/u, "");
|
|
736
1521
|
}
|
|
1522
|
+
function describeEmbeddingDownload(isDefault) {
|
|
1523
|
+
return isDefault ? "the local embedding model (about 0.3 GB)" : "your configured local embedding model";
|
|
1524
|
+
}
|
|
737
1525
|
function readPrimaryModel(config) {
|
|
738
1526
|
const model = config.agents?.defaults?.model;
|
|
739
1527
|
return typeof model === "string" ? model : model?.primary;
|
|
740
1528
|
}
|
|
741
|
-
function configuredCandidates(config) {
|
|
1529
|
+
function configuredCandidates(config, scope) {
|
|
742
1530
|
const existing = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
743
|
-
const
|
|
1531
|
+
const managedExisting = existing?.localService ? existing : void 0;
|
|
1532
|
+
const provider = buildLlamaCppProviderConfig({
|
|
1533
|
+
existing: managedExisting,
|
|
1534
|
+
...managedExisting && scope === "detection" ? { modelInventory: managedExisting.models } : {}
|
|
1535
|
+
});
|
|
744
1536
|
const primary = readPrimaryModel(config);
|
|
745
1537
|
const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
|
|
746
1538
|
return provider.models.map((model) => ({
|
|
@@ -776,13 +1568,22 @@ function readConfiguredPort(provider) {
|
|
|
776
1568
|
}
|
|
777
1569
|
}
|
|
778
1570
|
function buildSetupResult(params) {
|
|
1571
|
+
const existing = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1572
|
+
const switchingFromExternal = Boolean(existing && !existing.localService);
|
|
779
1573
|
return {
|
|
780
1574
|
profiles: [],
|
|
781
|
-
defaultModel: params.defaultModel
|
|
782
|
-
configPatch: {
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
1575
|
+
...params.defaultModel ? { defaultModel: params.defaultModel } : {},
|
|
1576
|
+
configPatch: {
|
|
1577
|
+
...buildLlamaCppAuthProfileRemovalPatch(params.config),
|
|
1578
|
+
models: {
|
|
1579
|
+
mode: params.config.models?.mode ?? "merge",
|
|
1580
|
+
providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig({
|
|
1581
|
+
existing: switchingFromExternal ? void 0 : existing,
|
|
1582
|
+
managed: params.managed,
|
|
1583
|
+
...params.plan === "embedding-only" ? { modelInventory: [] } : {}
|
|
1584
|
+
}) }
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
786
1587
|
};
|
|
787
1588
|
}
|
|
788
1589
|
async function detectLlamaCppSetup(ctx) {
|
|
@@ -790,7 +1591,7 @@ async function detectLlamaCppSetup(ctx) {
|
|
|
790
1591
|
const command = existing?.localService?.command;
|
|
791
1592
|
const presetPath = existing?.localService?.args?.find((_, index, args) => args[index - 1] === "--models-preset");
|
|
792
1593
|
if (!command || !path.isAbsolute(command) || !await isFile(command) || !presetPath || !await isFile(presetPath)) return null;
|
|
793
|
-
for (const candidate of configuredCandidates(ctx.config)) if (await resolveCachedCandidate(candidate)) return {
|
|
1594
|
+
for (const candidate of configuredCandidates(ctx.config, "detection")) if (await resolveCachedCandidate(candidate)) return {
|
|
794
1595
|
modelRef: `${LLAMA_CPP_PROVIDER_ID}/${candidate.model.id}`,
|
|
795
1596
|
detail: "Managed llama.cpp server ready"
|
|
796
1597
|
};
|
|
@@ -804,70 +1605,125 @@ async function prepareLlamaCppSetup(ctx) {
|
|
|
804
1605
|
const rootUrl = baseUrl.replace(/\/v1$/u, "");
|
|
805
1606
|
return buildSetupResult({
|
|
806
1607
|
config: ctx.config,
|
|
1608
|
+
plan: "chat",
|
|
807
1609
|
defaultModel: ctx.modelRef,
|
|
808
1610
|
managed: {
|
|
809
1611
|
command: existing.localService.command,
|
|
810
|
-
presetPath: existing.localService.args?.find((_, index, args) => args[index - 1] === "--models-preset") ?? resolveManagedLlamaServerPaths(selectLlamaServerAsset()).presetPath,
|
|
811
1612
|
baseUrl,
|
|
812
1613
|
healthUrl: existing.localService.healthUrl ?? `${rootUrl}/health`,
|
|
813
|
-
args: existing.localService.args ?? []
|
|
814
|
-
backend: selectLlamaServerAsset().backend
|
|
1614
|
+
args: existing.localService.args ?? []
|
|
815
1615
|
}
|
|
816
1616
|
});
|
|
817
1617
|
}
|
|
818
|
-
|
|
1618
|
+
function resolveEmbeddingSetup(config, cacheDir) {
|
|
1619
|
+
const defaults = config.memory?.search;
|
|
1620
|
+
const models = listAgentIds(config).flatMap((agentId) => {
|
|
1621
|
+
const override = resolveAgentConfig(config, agentId)?.memory?.search;
|
|
1622
|
+
if (!(override?.enabled ?? defaults?.enabled ?? true) || (override?.provider ?? defaults?.provider) !== "local") return [];
|
|
1623
|
+
return [resolveLlamaCppEmbeddingModel({
|
|
1624
|
+
modelPath: override?.local?.modelPath ?? defaults?.local?.modelPath,
|
|
1625
|
+
modelCacheDir: cacheDir
|
|
1626
|
+
})];
|
|
1627
|
+
});
|
|
1628
|
+
const model = models[0] ?? resolveLlamaCppEmbeddingModel({ modelCacheDir: cacheDir });
|
|
1629
|
+
return {
|
|
1630
|
+
model,
|
|
1631
|
+
localMemoryIntent: models.length > 0,
|
|
1632
|
+
conflict: models.some((candidate) => candidate.source !== model.source)
|
|
1633
|
+
};
|
|
1634
|
+
}
|
|
1635
|
+
async function resolveSetupPlan(ctx, candidates, embeddingModelIsDefault, localMemoryIntent) {
|
|
1636
|
+
let candidate = candidates[0];
|
|
1637
|
+
const cachedPath = candidate ? await resolveCachedCandidate(candidate) : void 0;
|
|
1638
|
+
if (candidate && cachedPath) return {
|
|
1639
|
+
kind: "chat",
|
|
1640
|
+
candidate,
|
|
1641
|
+
cachedPath
|
|
1642
|
+
};
|
|
1643
|
+
candidate = candidates.find((entry) => entry.model.id === DEFAULT_LLAMA_CPP_MODEL_ID);
|
|
1644
|
+
const totalmemBytes = os.totalmem();
|
|
1645
|
+
if (candidate && meetsLlamaCppDefaultModelRamFloor(totalmemBytes)) {
|
|
1646
|
+
if (await ctx.prompter.confirm({
|
|
1647
|
+
message: `OpenClaw will install a verified llama.cpp server and download Gemma 4 E4B IT Q4_K_M (about 5.0 GB) plus ${describeEmbeddingDownload(embeddingModelIsDefault)}. Continue?`,
|
|
1648
|
+
initialValue: false
|
|
1649
|
+
})) return {
|
|
1650
|
+
kind: "chat",
|
|
1651
|
+
candidate
|
|
1652
|
+
};
|
|
1653
|
+
} else if (!localMemoryIntent) {
|
|
1654
|
+
await ctx.prompter.note(`This Gateway has ${formatRamGb(totalmemBytes)} GB RAM; the recommended model needs 16 GB+. Configure an existing smaller GGUF, use Ollama or LM Studio, or choose a cloud provider.`, "Setup skipped");
|
|
1655
|
+
return;
|
|
1656
|
+
}
|
|
819
1657
|
const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
await ctx.prompter.note(`This Gateway has ${formatRamGb(totalmemBytes)} GB RAM; the recommended model needs 16 GB+. Configure an existing smaller GGUF, use Ollama or LM Studio, or choose a cloud provider.`, "Setup skipped");
|
|
828
|
-
return { profiles: [] };
|
|
829
|
-
}
|
|
830
|
-
if (!await ctx.prompter.confirm({
|
|
831
|
-
message: "OpenClaw will install a verified llama.cpp server and download Gemma 4 E4B IT Q4_K_M (about 5.0 GB) plus the local embedding model (about 0.3 GB). Continue?",
|
|
1658
|
+
if (localMemoryIntent && existing && (!existing.localService || existing.models.length > 0)) {
|
|
1659
|
+
await ctx.prompter.note("Embedding-only setup cannot replace an existing llama.cpp server or configured llama.cpp chat routes. Move those routes to another provider, remove any existing server config, then retry llama.cpp setup.", "Setup skipped");
|
|
1660
|
+
return;
|
|
1661
|
+
}
|
|
1662
|
+
if (localMemoryIntent) {
|
|
1663
|
+
if (await ctx.prompter.confirm({
|
|
1664
|
+
message: `OpenClaw can install a verified llama.cpp server and download only ${describeEmbeddingDownload(embeddingModelIsDefault)}. This will not install or change your chat model. Continue?`,
|
|
832
1665
|
initialValue: false
|
|
833
|
-
})) {
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
1666
|
+
})) return { kind: "embedding-only" };
|
|
1667
|
+
}
|
|
1668
|
+
await ctx.prompter.note("Local model setup skipped.", "Setup skipped");
|
|
1669
|
+
}
|
|
1670
|
+
async function runLlamaCppSetup(ctx) {
|
|
1671
|
+
const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1672
|
+
const managedExisting = existing?.localService ? existing : void 0;
|
|
1673
|
+
const cacheDir = resolveLlamaCppModelCacheDir(managedExisting);
|
|
1674
|
+
const embeddingSetup = resolveEmbeddingSetup(ctx.config, cacheDir);
|
|
1675
|
+
if (embeddingSetup.conflict) {
|
|
1676
|
+
await ctx.prompter.note("Configured agents resolve to different local embedding models. Set memory.search.local.modelPath and any per-agent overrides to the same value, then retry llama.cpp setup.", "Setup skipped");
|
|
1677
|
+
return { profiles: [] };
|
|
837
1678
|
}
|
|
838
|
-
|
|
1679
|
+
const embeddingModel = embeddingSetup.model;
|
|
1680
|
+
const plan = await resolveSetupPlan(ctx, configuredCandidates(ctx.config, "setup"), embeddingModel.isDefault, embeddingSetup.localMemoryIntent);
|
|
1681
|
+
if (!plan) return { profiles: [] };
|
|
839
1682
|
const progress = ctx.prompter.progress("Preparing managed llama.cpp server…");
|
|
840
1683
|
try {
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
1684
|
+
let chatModel;
|
|
1685
|
+
if (plan.kind === "chat") {
|
|
1686
|
+
const chatModelPath = plan.cachedPath ?? await ensureLlamaCppModel({
|
|
1687
|
+
source: resolveLlamaCppModelSource(plan.candidate.model),
|
|
1688
|
+
cacheDir,
|
|
1689
|
+
download: true,
|
|
1690
|
+
signal: ctx.signal,
|
|
1691
|
+
onProgress: (status) => progress.update(formatDownloadProgress("Gemma 4 E4B", status))
|
|
1692
|
+
});
|
|
1693
|
+
const configuredContext = plan.candidate.model.params?.contextSize;
|
|
1694
|
+
chatModel = {
|
|
1695
|
+
mode: "configure",
|
|
1696
|
+
id: plan.candidate.model.id,
|
|
1697
|
+
path: chatModelPath,
|
|
1698
|
+
contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : plan.candidate.model.contextTokens,
|
|
1699
|
+
maxTokens: plan.candidate.model.maxTokens
|
|
1700
|
+
};
|
|
1701
|
+
} else chatModel = { mode: "remove" };
|
|
1702
|
+
const embeddingModelLabel = embeddingModel.isDefault ? "EmbeddingGemma" : "configured embedding model";
|
|
849
1703
|
const embeddingModelPath = await ensureLlamaCppModel({
|
|
850
|
-
source:
|
|
1704
|
+
source: embeddingModel.source,
|
|
851
1705
|
cacheDir,
|
|
852
1706
|
download: true,
|
|
853
1707
|
signal: ctx.signal,
|
|
854
|
-
onProgress: (status) => progress.update(formatDownloadProgress(
|
|
1708
|
+
onProgress: (status) => progress.update(formatDownloadProgress(embeddingModelLabel, status))
|
|
855
1709
|
});
|
|
856
|
-
const configuredContext = selected.model.params?.contextSize;
|
|
857
|
-
const contextSize = typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : selected.model.contextTokens;
|
|
858
1710
|
const managed = await prepareManagedLlamaServer({
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
contextSize,
|
|
862
|
-
maxTokens: selected.model.maxTokens,
|
|
1711
|
+
chatModel,
|
|
1712
|
+
embeddingModelIsDefault: embeddingModel.isDefault,
|
|
863
1713
|
embeddingModelPath,
|
|
864
|
-
port: readConfiguredPort(
|
|
1714
|
+
port: readConfiguredPort(managedExisting)
|
|
865
1715
|
});
|
|
1716
|
+
if (!await removeProviderAuthProfilesWithLock({
|
|
1717
|
+
provider: "llama-cpp",
|
|
1718
|
+
profileIds: [LLAMA_CPP_DEFAULT_PROFILE_ID],
|
|
1719
|
+
agentDir: ctx.agentDir
|
|
1720
|
+
})) throw new Error("Failed to remove the previous llama.cpp endpoint auth profile");
|
|
866
1721
|
progress.stop("Managed llama.cpp server prepared");
|
|
867
1722
|
return buildSetupResult({
|
|
868
1723
|
config: ctx.config,
|
|
869
1724
|
managed,
|
|
870
|
-
|
|
1725
|
+
plan: plan.kind,
|
|
1726
|
+
...plan.kind === "chat" ? { defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${plan.candidate.model.id}` } : {}
|
|
871
1727
|
});
|
|
872
1728
|
} catch (error) {
|
|
873
1729
|
progress.stop("llama.cpp setup failed");
|
|
@@ -876,72 +1732,107 @@ async function runLlamaCppSetup(ctx) {
|
|
|
876
1732
|
}
|
|
877
1733
|
}
|
|
878
1734
|
//#endregion
|
|
1735
|
+
//#region extensions/llama-cpp/src/managed-provider.ts
|
|
1736
|
+
function registerLlamaCppProvider(api) {
|
|
1737
|
+
api.registerProvider({
|
|
1738
|
+
id: LLAMA_CPP_PROVIDER_ID,
|
|
1739
|
+
label: LLAMA_CPP_PROVIDER_LABEL,
|
|
1740
|
+
docsPath: "/plugins/llama-cpp",
|
|
1741
|
+
envVars: [LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR],
|
|
1742
|
+
auth: [{
|
|
1743
|
+
id: "local",
|
|
1744
|
+
label: LLAMA_CPP_PROVIDER_LABEL,
|
|
1745
|
+
hint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
|
|
1746
|
+
kind: "custom",
|
|
1747
|
+
wizard: {
|
|
1748
|
+
choiceId: LLAMA_CPP_PROVIDER_ID,
|
|
1749
|
+
choiceLabel: "Managed local server",
|
|
1750
|
+
choiceHint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
|
|
1751
|
+
groupId: LLAMA_CPP_PROVIDER_ID,
|
|
1752
|
+
groupLabel: "Local llama.cpp",
|
|
1753
|
+
groupHint: "Managed or external llama.cpp server",
|
|
1754
|
+
methodId: "local"
|
|
1755
|
+
},
|
|
1756
|
+
appGuidedSetup: {
|
|
1757
|
+
detect: detectLlamaCppSetup,
|
|
1758
|
+
prepare: prepareLlamaCppSetup
|
|
1759
|
+
},
|
|
1760
|
+
run: runLlamaCppSetup
|
|
1761
|
+
}, {
|
|
1762
|
+
id: "existing-server",
|
|
1763
|
+
label: "Existing llama-server",
|
|
1764
|
+
hint: "Connect to an existing local, private, or remote llama.cpp server",
|
|
1765
|
+
kind: "custom",
|
|
1766
|
+
wizard: {
|
|
1767
|
+
choiceId: "llama-cpp-existing-server",
|
|
1768
|
+
choiceLabel: "Existing llama-server",
|
|
1769
|
+
choiceHint: "Connect to a llama.cpp server managed outside OpenClaw",
|
|
1770
|
+
groupId: LLAMA_CPP_PROVIDER_ID,
|
|
1771
|
+
groupLabel: "Local llama.cpp",
|
|
1772
|
+
groupHint: "Managed or external llama.cpp server",
|
|
1773
|
+
methodId: "existing-server"
|
|
1774
|
+
},
|
|
1775
|
+
appGuidedSetup: {
|
|
1776
|
+
detect: detectLlamaServerSetup,
|
|
1777
|
+
prepare: prepareLlamaServerSetup
|
|
1778
|
+
},
|
|
1779
|
+
run: runLlamaServerSetup,
|
|
1780
|
+
validateNonInteractive: validateLlamaServerNonInteractive,
|
|
1781
|
+
runNonInteractive: async (ctx) => await configureLlamaServerNonInteractive(ctx)
|
|
1782
|
+
}],
|
|
1783
|
+
catalog: {
|
|
1784
|
+
order: "late",
|
|
1785
|
+
run: async (ctx) => {
|
|
1786
|
+
const configured = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1787
|
+
return configured?.localService ? { provider: buildLlamaCppProviderConfig({
|
|
1788
|
+
existing: configured,
|
|
1789
|
+
modelInventory: configured.models
|
|
1790
|
+
}) } : await discoverLlamaServerProvider(ctx);
|
|
1791
|
+
}
|
|
1792
|
+
},
|
|
1793
|
+
staticCatalog: {
|
|
1794
|
+
order: "late",
|
|
1795
|
+
run: async () => ({ provider: buildLlamaCppProviderConfig() })
|
|
1796
|
+
},
|
|
1797
|
+
resolveSyntheticAuth: ({ providerConfig }) => providerConfig?.localService || shouldUseLlamaServerSyntheticAuth(providerConfig) ? {
|
|
1798
|
+
apiKey: resolveLlamaCppSyntheticApiKey(),
|
|
1799
|
+
source: providerConfig?.localService ? "managed local llama.cpp server" : hasLlamaServerAuthorizationHeader(providerConfig?.headers) ? "models.providers.llama-cpp.headers.Authorization" : "models.providers.llama-cpp (synthetic local key)",
|
|
1800
|
+
mode: "api-key"
|
|
1801
|
+
} : void 0,
|
|
1802
|
+
shouldDeferSyntheticProfileAuth: ({ resolvedApiKey }) => resolvedApiKey?.trim() === resolveLlamaCppSyntheticApiKey() || resolvedApiKey?.trim() === CUSTOM_LOCAL_AUTH_MARKER,
|
|
1803
|
+
normalizeConfig: ({ providerConfig }) => providerConfig.localService ? providerConfig : normalizeLlamaServerProviderConfig(providerConfig),
|
|
1804
|
+
prepareDynamicModel: async (ctx) => ctx.config?.models?.providers?.["llama-cpp"]?.localService ? void 0 : await prepareLlamaServerDynamicModel(ctx),
|
|
1805
|
+
wrapStreamFn: (ctx) => {
|
|
1806
|
+
const providerConfig = ctx.config?.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
1807
|
+
if (!providerConfig?.localService) return wrapLlamaServerStream(ctx);
|
|
1808
|
+
const inner = ctx.streamFn;
|
|
1809
|
+
const selectedModel = ctx.model;
|
|
1810
|
+
if (!inner || !selectedModel) return;
|
|
1811
|
+
return async (model, context, options) => {
|
|
1812
|
+
await ensureManagedLlamaServerForChat({
|
|
1813
|
+
provider: providerConfig,
|
|
1814
|
+
model: selectedModel
|
|
1815
|
+
});
|
|
1816
|
+
return inner(model, context, options);
|
|
1817
|
+
};
|
|
1818
|
+
},
|
|
1819
|
+
...buildProviderToolCompatFamilyHooks("llamacpp-gbnf"),
|
|
1820
|
+
wizard: { modelPicker: {
|
|
1821
|
+
label: "llama.cpp",
|
|
1822
|
+
hint: `Use a managed server or connect to ${LLAMA_SERVER_DEFAULT_ORIGIN}`,
|
|
1823
|
+
methodId: "local"
|
|
1824
|
+
} }
|
|
1825
|
+
});
|
|
1826
|
+
}
|
|
1827
|
+
//#endregion
|
|
879
1828
|
//#region extensions/llama-cpp/index.ts
|
|
880
1829
|
var llama_cpp_default = definePluginEntry({
|
|
881
1830
|
id: "llama-cpp",
|
|
882
1831
|
name: "llama.cpp Provider",
|
|
883
|
-
description: "Managed
|
|
1832
|
+
description: "Managed and external llama.cpp servers for GGUF chat and embeddings",
|
|
884
1833
|
register(api) {
|
|
885
1834
|
api.registerEmbeddingProvider(llamaCppEmbeddingProviderAdapter);
|
|
886
|
-
api
|
|
887
|
-
id: LLAMA_CPP_PROVIDER_ID,
|
|
888
|
-
label: LLAMA_CPP_PROVIDER_LABEL,
|
|
889
|
-
docsPath: "/plugins/llama-cpp",
|
|
890
|
-
auth: [{
|
|
891
|
-
id: "local",
|
|
892
|
-
label: LLAMA_CPP_PROVIDER_LABEL,
|
|
893
|
-
hint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
|
|
894
|
-
kind: "custom",
|
|
895
|
-
appGuidedSetup: {
|
|
896
|
-
detect: detectLlamaCppSetup,
|
|
897
|
-
prepare: prepareLlamaCppSetup
|
|
898
|
-
},
|
|
899
|
-
run: runLlamaCppSetup
|
|
900
|
-
}],
|
|
901
|
-
catalog: {
|
|
902
|
-
order: "late",
|
|
903
|
-
run: async (ctx) => ({ provider: buildLlamaCppProviderConfig(ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID]) })
|
|
904
|
-
},
|
|
905
|
-
staticCatalog: {
|
|
906
|
-
order: "late",
|
|
907
|
-
run: async () => ({ provider: buildLlamaCppProviderConfig() })
|
|
908
|
-
},
|
|
909
|
-
resolveSyntheticAuth: () => ({
|
|
910
|
-
apiKey: resolveLlamaCppSyntheticApiKey(),
|
|
911
|
-
source: "managed local llama.cpp server",
|
|
912
|
-
mode: "api-key"
|
|
913
|
-
}),
|
|
914
|
-
wrapStreamFn: (ctx) => {
|
|
915
|
-
const inner = ctx.streamFn;
|
|
916
|
-
const providerConfig = ctx.config?.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
|
|
917
|
-
const selectedModel = ctx.model;
|
|
918
|
-
if (!inner || !providerConfig?.localService || !selectedModel) return;
|
|
919
|
-
return async (model, context, options) => {
|
|
920
|
-
await ensureManagedLlamaServerForChat({
|
|
921
|
-
provider: providerConfig,
|
|
922
|
-
model: selectedModel
|
|
923
|
-
});
|
|
924
|
-
return inner(model, context, options);
|
|
925
|
-
};
|
|
926
|
-
},
|
|
927
|
-
...buildProviderToolCompatFamilyHooks("llamacpp-gbnf"),
|
|
928
|
-
wizard: {
|
|
929
|
-
setup: {
|
|
930
|
-
choiceId: LLAMA_CPP_PROVIDER_ID,
|
|
931
|
-
choiceLabel: LLAMA_CPP_PROVIDER_LABEL,
|
|
932
|
-
choiceHint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
|
|
933
|
-
groupId: LLAMA_CPP_PROVIDER_ID,
|
|
934
|
-
groupLabel: "Local llama.cpp",
|
|
935
|
-
groupHint: "No API key required",
|
|
936
|
-
methodId: "local"
|
|
937
|
-
},
|
|
938
|
-
modelPicker: {
|
|
939
|
-
label: "llama.cpp",
|
|
940
|
-
hint: "Run a GGUF model with OpenClaw's managed local llama.cpp server",
|
|
941
|
-
methodId: "local"
|
|
942
|
-
}
|
|
943
|
-
}
|
|
944
|
-
});
|
|
1835
|
+
registerLlamaCppProvider(api);
|
|
945
1836
|
}
|
|
946
1837
|
});
|
|
947
1838
|
//#endregion
|