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