@openclaw/llama-cpp-provider 2026.8.1-beta.2 → 2026.8.1-beta.3

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 { A as resolveLlamaCppModelSource, C as buildLlamaCppProviderConfig, D as resolveLegacyLlamaCppModelCacheDir, E as resolveHomePath, O as resolveLlamaCppDataDir, S as LLAMA_CPP_PROVIDER_LABEL, T as resolveCachedLlamaCppModelPath, _ as DEFAULT_LLAMA_CPP_MODEL_SHA256, a as selectLlamaServerAsset, b as LLAMA_CPP_DEFAULT_PORT, c as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL, d as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SHA256, f as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES, g as DEFAULT_LLAMA_CPP_MODEL_REVISION, h as DEFAULT_LLAMA_CPP_MODEL_REF, i as resolveManagedLlamaServerPaths, j as resolveLlamaCppSyntheticApiKey, k as resolveLlamaCppModelCacheDir, l as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID, m as DEFAULT_LLAMA_CPP_MODEL_ID, n as LLAMA_SERVER_COMMIT, p as DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE, r as LLAMA_SERVER_RELEASE, s as DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE, u as DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_REVISION, v as DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES, w as meetsLlamaCppDefaultModelRamFloor, x as LLAMA_CPP_PROVIDER_ID } from "./llama-server-assets-BEF3s_UC.js";
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 = "b10357";
27
+ const LLAMA_SERVER_COMMIT = "689e227db485c6b33d061555e74034c93a867649";
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: "7f464a2d473d53ebb9c1d7d16db1258ec98c371569816491850686e6a4334c52",
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: "8282cf6b30bfab87080044e98b7b78f2896bfc60414926fae6039a89c0fb6ec2",
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: "0653b6aa14de35920824045bca7e48f98f629f41943d0fefab1e317bbe8e22a8",
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: "6b0ba012036e6d727521100158bfcaa73b460fbb31acab2931c9485f347bd16b",
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: "a0d73be8d3151d9401fa193f1b83c6d7401191b41786e75f0a60184058333e86",
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: "6c64cc7db679980fcb34bbbe96b2b1df6127e90ccdad2bd6fbe39532fee2fc4e",
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;
@@ -286,7 +367,6 @@ async function resolveHuggingFaceArtifact(source, signal) {
286
367
  expectedSize = expectedSize ?? (typeof fileRow?.size === "number" ? fileRow.size : void 0);
287
368
  if (!expectedSha256) throw new Error(`Hugging Face did not publish a SHA-256 LFS identity for ${source}`);
288
369
  return {
289
- source,
290
370
  fileName: `hf_${[
291
371
  parsed.user,
292
372
  parsed.repository,
@@ -300,14 +380,12 @@ async function resolveHuggingFaceArtifact(source, signal) {
300
380
  }
301
381
  function defaultArtifact(source) {
302
382
  if (source === "hf:unsloth/gemma-4-E4B-it-GGUF/gemma-4-E4B-it-Q4_K_M.gguf") return {
303
- source,
304
383
  fileName: DEFAULT_LLAMA_CPP_MODEL_CACHE_FILE,
305
384
  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
385
  expectedSize: DEFAULT_LLAMA_CPP_MODEL_SIZE_BYTES,
307
386
  expectedSha256: DEFAULT_LLAMA_CPP_MODEL_SHA256
308
387
  };
309
388
  if (source === "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf") return {
310
- source,
311
389
  fileName: DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE,
312
390
  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
391
  expectedSize: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_SIZE_BYTES,
@@ -336,7 +414,6 @@ async function resolveModelArtifact(source, signal) {
336
414
  const fileName = path.basename(decodeURIComponent(url.pathname));
337
415
  if (!fileName.toLowerCase().includes(".gguf")) throw new Error(`Remote model URL must name a GGUF file: ${source}`);
338
416
  return {
339
- source,
340
417
  fileName,
341
418
  url: source
342
419
  };
@@ -386,23 +463,17 @@ function assertIniValue(value, label) {
386
463
  return value;
387
464
  }
388
465
  function renderLlamaServerPreset(params) {
389
- const chatId = assertIniValue(params.chatModelId, "llama.cpp model id");
390
466
  const embeddingId = assertIniValue(params.embeddingModelId, "llama.cpp embedding model id");
391
- if (chatId.includes("]") || embeddingId.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
392
- return [
393
- "version = 1",
394
- "",
395
- `[${chatId}]`,
396
- `model = ${assertIniValue(params.chatModelPath, "llama.cpp model path")}`,
397
- `ctx-size = ${params.contextSize ?? 65536}`,
398
- `n-predict = ${params.maxTokens ?? 2048}`,
399
- "jinja = true",
400
- "",
401
- `[${embeddingId}]`,
402
- `model = ${assertIniValue(params.embeddingModelPath, "llama.cpp embedding model path")}`,
403
- "embedding = true",
404
- ""
405
- ].join("\n");
467
+ if (embeddingId.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
468
+ const lines = ["version = 1", ""];
469
+ if (params.chatModelId || params.chatModelPath) {
470
+ if (!params.chatModelId || !params.chatModelPath) throw new Error("llama.cpp chat model id and path must be provided together");
471
+ const chatId = assertIniValue(params.chatModelId, "llama.cpp model id");
472
+ if (chatId.includes("]")) throw new Error("llama.cpp model ids cannot contain ]");
473
+ lines.push(`[${chatId}]`, `model = ${assertIniValue(params.chatModelPath, "llama.cpp model path")}`, `ctx-size = ${params.contextSize ?? 65536}`, `n-predict = ${params.maxTokens ?? 2048}`, "jinja = true", "");
474
+ }
475
+ lines.push(`[${embeddingId}]`, `model = ${assertIniValue(params.embeddingModelPath, "llama.cpp embedding model path")}`, "embedding = true", "");
476
+ return lines.join("\n");
406
477
  }
407
478
  async function writePreset(presetPath, contents) {
408
479
  await fsp.mkdir(path.dirname(presetPath), { recursive: true });
@@ -427,8 +498,10 @@ async function prepareManagedLlamaServer(params) {
427
498
  const { command, asset } = await ensureLlamaServerInstalled();
428
499
  const { presetPath } = resolveManagedLlamaServerPaths(asset);
429
500
  await writePreset(presetPath, renderLlamaServerPreset({
430
- chatModelId: params.chatModelId ?? "gemma-4-e4b-it-q4_k_m",
431
- chatModelPath: params.chatModelPath,
501
+ ...params.chatModelPath ? {
502
+ chatModelId: params.chatModelId ?? "gemma-4-e4b-it-q4_k_m",
503
+ chatModelPath: params.chatModelPath
504
+ } : {},
432
505
  contextSize: params.contextSize,
433
506
  maxTokens: params.maxTokens,
434
507
  embeddingModelId: DEFAULT_LLAMA_CPP_EMBEDDING_MODEL_ID,
@@ -438,7 +511,6 @@ async function prepareManagedLlamaServer(params) {
438
511
  const rootUrl = `http://127.0.0.1:${port}`;
439
512
  return {
440
513
  command,
441
- presetPath,
442
514
  baseUrl: `${rootUrl}/v1`,
443
515
  healthUrl: `${rootUrl}/health`,
444
516
  args: [
@@ -452,8 +524,7 @@ async function prepareManagedLlamaServer(params) {
452
524
  "2",
453
525
  "--metrics",
454
526
  "--no-ui"
455
- ],
456
- backend: asset.backend
527
+ ]
457
528
  };
458
529
  }
459
530
  async function ensureManagedLlamaServerForChat(params) {
@@ -597,9 +668,7 @@ function resolveModelIdentity(local, modelPath, dimensions) {
597
668
  };
598
669
  }
599
670
  function resolveConfiguredProvider(options) {
600
- const provider = options.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
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;
671
+ return resolveManagedLlamaCppProviderConfig(options.config);
603
672
  }
604
673
  function resolveProviderPort(provider) {
605
674
  const port = Number(new URL(provider.baseUrl ?? "").port);
@@ -612,30 +681,29 @@ async function prepareEmbeddingServer(options, embeddingSource) {
612
681
  const primaryRef = typeof configuredPrimary === "string" ? configuredPrimary : configuredPrimary?.primary;
613
682
  const primaryId = primaryRef?.startsWith(`llama-cpp/`) ? primaryRef.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
614
683
  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
684
  const cacheDir = resolveLlamaCppModelCacheDir(provider);
617
685
  const key = JSON.stringify([
618
686
  provider.baseUrl,
619
- chatModel.id,
687
+ chatModel?.id ?? null,
620
688
  embeddingSource,
621
689
  cacheDir
622
690
  ]);
623
691
  const pending = preparedEmbeddingServers.get(key) ?? (async () => {
624
- const [chatModelPath, embeddingModelPath] = await Promise.all([ensureLlamaCppModel({
692
+ const [chatModelPath, embeddingModelPath] = await Promise.all([chatModel ? ensureLlamaCppModel({
625
693
  source: resolveLlamaCppModelSource(chatModel),
626
694
  cacheDir,
627
695
  download: false
628
- }), ensureLlamaCppModel({
696
+ }) : Promise.resolve(void 0), ensureLlamaCppModel({
629
697
  source: embeddingSource,
630
698
  cacheDir,
631
699
  download: true
632
700
  })]);
633
- const configuredContext = chatModel.params?.contextSize;
701
+ const configuredContext = chatModel?.params?.contextSize;
634
702
  await prepareManagedLlamaServer({
635
- chatModelId: chatModel.id,
703
+ ...chatModel ? { chatModelId: chatModel.id } : {},
636
704
  chatModelPath,
637
- contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : chatModel.contextTokens,
638
- maxTokens: chatModel.maxTokens,
705
+ contextSize: typeof configuredContext === "number" && configuredContext > 0 ? Math.floor(configuredContext) : chatModel?.contextTokens,
706
+ maxTokens: chatModel?.maxTokens,
639
707
  embeddingModelPath,
640
708
  port: resolveProviderPort(provider)
641
709
  });
@@ -723,6 +791,689 @@ const llamaCppEmbeddingProviderAdapter = {
723
791
  }
724
792
  };
725
793
  //#endregion
794
+ //#region extensions/llama-cpp/src/external-server/auth.ts
795
+ function hasLlamaServerAuthorizationHeader(headers) {
796
+ const record = asOptionalRecord(headers);
797
+ if (!record) return false;
798
+ return Object.entries(record).some(([name, value]) => name.trim().toLowerCase() === "authorization" && hasConfiguredSecretInput(value));
799
+ }
800
+ function shouldUseLlamaServerSyntheticAuth(providerConfig) {
801
+ const apiKey = normalizeOptionalSecretInput(providerConfig?.apiKey)?.trim();
802
+ return !(hasConfiguredSecretInput(providerConfig?.apiKey) && apiKey !== resolveLlamaCppSyntheticApiKey() && apiKey !== CUSTOM_LOCAL_AUTH_MARKER);
803
+ }
804
+ async function resolveLlamaServerProviderHeaders(params) {
805
+ const headers = asOptionalRecord(params.headers);
806
+ if (!headers) return;
807
+ const resolved = {};
808
+ for (const [name, value] of Object.entries(headers)) {
809
+ if (!params.config) {
810
+ if (typeof value === "string" && value.trim()) resolved[name] = value.trim();
811
+ continue;
812
+ }
813
+ const path = `models.providers.${LLAMA_CPP_PROVIDER_ID}.headers.${name}`;
814
+ const header = await resolveConfiguredSecretInputString({
815
+ config: params.config,
816
+ env: params.env ?? process.env,
817
+ value,
818
+ path,
819
+ unresolvedReasonStyle: "detailed"
820
+ });
821
+ if (header.unresolvedRefReason) throw new Error(`${path}: ${header.unresolvedRefReason}`);
822
+ if (header.value) resolved[name] = header.value;
823
+ }
824
+ return Object.keys(resolved).length > 0 ? resolved : void 0;
825
+ }
826
+ async function resolveLlamaServerRuntimeApiKey(params) {
827
+ const apiKey = (await resolveApiKeyForProvider({
828
+ provider: LLAMA_CPP_PROVIDER_ID,
829
+ cfg: params.config,
830
+ agentDir: params.agentDir,
831
+ profileId: params.profileId,
832
+ lockedProfile: params.profileId !== void 0
833
+ })).apiKey?.trim();
834
+ return apiKey && !isNonSecretApiKeyMarker(apiKey) ? apiKey : void 0;
835
+ }
836
+ //#endregion
837
+ //#region extensions/llama-cpp/src/external-server/defaults.ts
838
+ const LLAMA_SERVER_DEFAULT_ORIGIN = "http://127.0.0.1:8080";
839
+ const LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR = "LLAMA_SERVER_API_KEY";
840
+ //#endregion
841
+ //#region extensions/llama-cpp/src/external-server/endpoint.ts
842
+ function toFetchableBaseUrl(value) {
843
+ if (/^[a-z][a-z\d+.-]*:\/\//iu.test(value)) return value;
844
+ return `http://${value}`;
845
+ }
846
+ /** Resolves the server origin and its OpenAI-compatible `/v1` inference base. */
847
+ function resolveLlamaServerEndpoint(configuredBaseUrl) {
848
+ const configured = configuredBaseUrl?.trim() || "http://127.0.0.1:8080";
849
+ const parsed = new URL(toFetchableBaseUrl(configured));
850
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new TypeError(`Unsupported llama-server protocol: ${parsed.protocol}`);
851
+ if (parsed.username || parsed.password) throw new TypeError("llama-server base URL must not contain credentials");
852
+ parsed.pathname = parsed.pathname.replace(/\/+$/u, "").replace(/\/v1$/iu, "") || "/";
853
+ parsed.search = "";
854
+ parsed.hash = "";
855
+ const origin = parsed.toString().replace(/\/$/u, "");
856
+ return {
857
+ origin,
858
+ inferenceBaseUrl: `${origin}/v1`
859
+ };
860
+ }
861
+ /** Canonicalizes persisted provider config for the shared OpenAI transport. */
862
+ function normalizeLlamaServerProviderConfig(provider) {
863
+ const endpoint = resolveLlamaServerEndpoint(provider.baseUrl);
864
+ const request = provider.request ?? {};
865
+ const normalizedRequest = typeof request.allowPrivateNetwork === "boolean" ? request : {
866
+ ...request,
867
+ allowPrivateNetwork: true
868
+ };
869
+ return {
870
+ ...provider,
871
+ baseUrl: endpoint.inferenceBaseUrl,
872
+ api: "openai-completions",
873
+ request: normalizedRequest
874
+ };
875
+ }
876
+ //#endregion
877
+ //#region extensions/llama-cpp/src/external-server/models.ts
878
+ function normalizeStatus(value) {
879
+ switch (value) {
880
+ case "unloaded":
881
+ case "loading":
882
+ case "loaded":
883
+ case "sleeping":
884
+ case "downloading": return value;
885
+ default: return "unknown";
886
+ }
887
+ }
888
+ function resolveContextWindow(props) {
889
+ return asPositiveSafeInteger(props?.default_generation_settings?.n_ctx) ?? asPositiveSafeInteger(props?.n_ctx) ?? SELF_HOSTED_DEFAULT_CONTEXT_WINDOW;
890
+ }
891
+ function resolveMaxTokens(props, contextWindow) {
892
+ const params = props?.default_generation_settings?.params;
893
+ const advertised = asPositiveSafeInteger(params?.max_tokens) ?? asPositiveSafeInteger(params?.n_predict);
894
+ return Math.min(advertised ?? SELF_HOSTED_DEFAULT_MAX_TOKENS, contextWindow);
895
+ }
896
+ function resolveInput(row, props) {
897
+ const advertised = row.architecture?.input_modalities;
898
+ return Array.isArray(advertised) && advertised.includes("image") || props?.modalities?.vision === true ? ["text", "image"] : ["text"];
899
+ }
900
+ function buildCompat(props) {
901
+ const caps = props?.chat_template_caps;
902
+ return {
903
+ supportsStore: false,
904
+ supportsDeveloperRole: false,
905
+ supportsReasoningEffort: false,
906
+ supportsTemperature: true,
907
+ supportsUsageInStreaming: true,
908
+ supportsTools: asBoolean(caps?.supports_tools) === true && asBoolean(caps?.supports_tool_calls) === true,
909
+ supportsStrictMode: false,
910
+ supportsJsonSchemaResponseFormat: true,
911
+ requiresStringContent: !(asBoolean(caps?.supports_typed_content) === true),
912
+ maxTokensField: "max_tokens"
913
+ };
914
+ }
915
+ /** Maps one llama-server model row plus optional runtime properties into OpenClaw config. */
916
+ function mapLlamaServerModel(row, props) {
917
+ const id = typeof row.id === "string" ? row.id.trim() : "";
918
+ if (!id || row.object !== void 0 && row.object !== "model") return null;
919
+ const contextWindow = resolveContextWindow(props);
920
+ return {
921
+ config: {
922
+ id,
923
+ name: id,
924
+ reasoning: false,
925
+ input: resolveInput(row, props),
926
+ cost: { ...SELF_HOSTED_DEFAULT_COST },
927
+ contextWindow,
928
+ contextTokens: contextWindow,
929
+ maxTokens: resolveMaxTokens(props, contextWindow),
930
+ compat: buildCompat(props)
931
+ },
932
+ status: normalizeStatus(row.status?.value),
933
+ failed: row.status?.failed === true
934
+ };
935
+ }
936
+ /** Keeps explicit rows first and appends models discovered from the server. */
937
+ function mergeLlamaServerModels(params) {
938
+ const explicit = Array.isArray(params.explicitModels) ? params.explicitModels : [];
939
+ const merged = [...explicit];
940
+ const seen = new Set(explicit.map((model) => model.id));
941
+ for (const discovered of params.discoveredModels) {
942
+ if (seen.has(discovered.config.id)) continue;
943
+ seen.add(discovered.config.id);
944
+ merged.push(discovered.config);
945
+ }
946
+ return merged;
947
+ }
948
+ function buildLlamaServerProviderConfig(params) {
949
+ return normalizeLlamaServerProviderConfig({
950
+ ...params.configured,
951
+ baseUrl: params.configured?.baseUrl ?? "http://127.0.0.1:8080",
952
+ models: mergeLlamaServerModels({
953
+ explicitModels: params.configured?.models,
954
+ discoveredModels: params.discoveredModels
955
+ })
956
+ });
957
+ }
958
+ //#endregion
959
+ //#region extensions/llama-cpp/src/external-server/discovery.ts
960
+ /** Discovers llama-server models without loading, waking, or unloading them. */
961
+ async function discoverLlamaServer(params) {
962
+ const endpoint = resolveLlamaServerEndpoint(params.baseUrl);
963
+ const apiKey = params.apiKey?.trim();
964
+ const cacheTtlMs = Boolean(apiKey && !isNonSecretApiKeyMarker(apiKey)) || Boolean(params.headers && Object.keys(params.headers).length > 0) ? 0 : Math.max(0, params.cacheTtlMs ?? 3e4);
965
+ return await getCachedLiveCatalogValue({
966
+ keyParts: [
967
+ "llama-cpp",
968
+ "external",
969
+ endpoint.origin
970
+ ],
971
+ ttlMs: cacheTtlMs,
972
+ shouldCache: (result) => result.kind === "success",
973
+ load: async () => {
974
+ const result = await discoverOpenAICompatibleLocalModels({
975
+ baseUrl: endpoint.inferenceBaseUrl,
976
+ serverBaseUrl: endpoint.origin,
977
+ apiKey: params.apiKey,
978
+ headers: params.headers,
979
+ label: "llama-server",
980
+ healthPath: "/health",
981
+ modelsPathOrder: "server-first",
982
+ routerModelProps: true,
983
+ timeoutMs: params.timeoutMs ?? 5e3,
984
+ signal: params.signal,
985
+ rawResult: true
986
+ });
987
+ if (result.kind !== "success") return {
988
+ ...result,
989
+ endpoint
990
+ };
991
+ return {
992
+ kind: "success",
993
+ endpoint,
994
+ models: result.rows.flatMap(({ model, props }) => {
995
+ const mapped = mapLlamaServerModel(model, props);
996
+ return mapped ? [mapped] : [];
997
+ })
998
+ };
999
+ }
1000
+ });
1001
+ }
1002
+ //#endregion
1003
+ //#region extensions/llama-cpp/src/external-server/provider.ts
1004
+ /** Discovers external llama-server models for provider runtime resolution. */
1005
+ async function discoverLlamaServerProvider(ctx) {
1006
+ const configured = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1007
+ const auth = ctx.resolveProviderApiKey(LLAMA_CPP_PROVIDER_ID);
1008
+ const headers = await resolveLlamaServerProviderHeaders({
1009
+ config: ctx.config,
1010
+ env: ctx.env,
1011
+ headers: configured?.headers
1012
+ });
1013
+ const discovery = await discoverLlamaServer({
1014
+ baseUrl: configured?.baseUrl,
1015
+ apiKey: hasLlamaServerAuthorizationHeader(headers) ? void 0 : auth.discoveryApiKey ?? auth.apiKey,
1016
+ headers
1017
+ });
1018
+ if (discovery.kind !== "success") return configured ? { provider: buildLlamaServerProviderConfig({
1019
+ configured,
1020
+ discoveredModels: []
1021
+ }) } : null;
1022
+ return { provider: buildLlamaServerProviderConfig({
1023
+ configured: {
1024
+ ...configured,
1025
+ baseUrl: discovery.endpoint.inferenceBaseUrl,
1026
+ models: configured?.models ?? []
1027
+ },
1028
+ discoveredModels: discovery.models
1029
+ }) };
1030
+ }
1031
+ async function prepareLlamaServerDynamicModel(ctx) {
1032
+ const apiKey = await resolveLlamaServerRuntimeApiKey({
1033
+ config: ctx.config,
1034
+ agentDir: ctx.agentDir,
1035
+ profileId: ctx.authProfileId
1036
+ });
1037
+ const headers = await resolveLlamaServerProviderHeaders({
1038
+ config: ctx.config,
1039
+ env: process.env,
1040
+ headers: ctx.providerConfig?.headers
1041
+ });
1042
+ const discovery = await discoverLlamaServer({
1043
+ baseUrl: ctx.providerConfig?.baseUrl,
1044
+ apiKey: hasLlamaServerAuthorizationHeader(headers) ? void 0 : apiKey,
1045
+ headers,
1046
+ cacheTtlMs: 0
1047
+ });
1048
+ const model = discovery.kind === "success" ? discovery.models.find((entry) => entry.config.id === ctx.modelId) : void 0;
1049
+ if (!model) return;
1050
+ return {
1051
+ ...model.config,
1052
+ provider: LLAMA_CPP_PROVIDER_ID,
1053
+ api: ctx.providerConfig?.api ?? "openai-completions",
1054
+ baseUrl: resolveLlamaServerEndpoint(ctx.providerConfig?.baseUrl).inferenceBaseUrl,
1055
+ input: model.config.input.filter((entry) => entry === "text" || entry === "image")
1056
+ };
1057
+ }
1058
+ //#endregion
1059
+ //#region extensions/llama-cpp/src/auth-config.ts
1060
+ const LLAMA_CPP_DEFAULT_PROFILE_ID = `${LLAMA_CPP_PROVIDER_ID}:default`;
1061
+ function buildLlamaCppAuthProfileRemovalPatch(config) {
1062
+ const profileExists = Boolean(config.auth?.profiles?.[LLAMA_CPP_DEFAULT_PROFILE_ID]);
1063
+ const referencedOrders = Object.entries(config.auth?.order ?? {}).filter(([, ids]) => ids.includes(LLAMA_CPP_DEFAULT_PROFILE_ID));
1064
+ if (!profileExists && referencedOrders.length === 0) return {};
1065
+ const authPatch = {};
1066
+ if (profileExists) Reflect.set(authPatch, "profiles", { [LLAMA_CPP_DEFAULT_PROFILE_ID]: void 0 });
1067
+ if (referencedOrders.length > 0) Reflect.set(authPatch, "order", Object.fromEntries(referencedOrders.map(([providerId, ids]) => {
1068
+ const next = ids.filter((id) => id !== LLAMA_CPP_DEFAULT_PROFILE_ID);
1069
+ return [providerId, next.length > 0 ? next : void 0];
1070
+ })));
1071
+ return { auth: authPatch };
1072
+ }
1073
+ //#endregion
1074
+ //#region extensions/llama-cpp/src/external-server/setup.ts
1075
+ function selectSetupModelId(discovery) {
1076
+ const healthy = discovery.models.filter((model) => !model.failed);
1077
+ const ids = (healthy.length > 0 ? healthy : discovery.models).toSorted((left, right) => {
1078
+ const leftLoaded = left.status === "loaded" || left.status === "sleeping";
1079
+ const rightLoaded = right.status === "loaded" || right.status === "sleeping";
1080
+ return Number(rightLoaded) - Number(leftLoaded);
1081
+ }).map((model) => model.config.id);
1082
+ return selectPreferredLocalModelId(ids) ?? ids[0];
1083
+ }
1084
+ function describeDiscoveryFailure(result) {
1085
+ switch (result.kind) {
1086
+ case "unreachable": return `llama-server could not be reached at ${result.endpoint.origin}.`;
1087
+ case "http-error": return `llama-server returned HTTP ${result.status} for ${result.path} at ${result.endpoint.origin}.`;
1088
+ case "invalid-response": return `llama-server returned an invalid response from ${result.path} at ${result.endpoint.origin}.`;
1089
+ default: throw new Error("Unexpected llama-server discovery result");
1090
+ }
1091
+ }
1092
+ function stripAuthOverrides(provider, removeAuthorization) {
1093
+ if (!provider) return provider;
1094
+ const headers = removeAuthorization ? stripAuthorizationHeader(provider.headers) : provider.headers;
1095
+ return {
1096
+ ...provider,
1097
+ auth: void 0,
1098
+ apiKey: void 0,
1099
+ ...removeAuthorization ? { headers } : {}
1100
+ };
1101
+ }
1102
+ function stripEndpointCredentials(provider) {
1103
+ if (!provider) return;
1104
+ const { localService: _localService, ...external } = provider;
1105
+ if (!provider.localService) return {
1106
+ ...external,
1107
+ auth: void 0,
1108
+ apiKey: void 0,
1109
+ headers: void 0
1110
+ };
1111
+ const { auth: _auth, apiKey: _apiKey, headers: _headers, localService: _managedService, models: _managedModels, params: managedParams, timeoutSeconds: _managedTimeout, ...externalProvider } = provider;
1112
+ const { modelCacheDir: _modelCacheDir, ...params } = managedParams ?? {};
1113
+ return {
1114
+ ...externalProvider,
1115
+ models: [],
1116
+ params: Object.keys(params).length > 0 ? params : void 0
1117
+ };
1118
+ }
1119
+ function hasEndpointChanged(provider, baseUrl) {
1120
+ if (!provider) return false;
1121
+ return resolveLlamaServerEndpoint(provider.baseUrl ?? "http://127.0.0.1:8080").inferenceBaseUrl !== resolveLlamaServerEndpoint(baseUrl).inferenceBaseUrl;
1122
+ }
1123
+ function stripLlamaServerEndpointAuth(config) {
1124
+ const withoutProfile = removeAuthProfileConfig(config, LLAMA_CPP_DEFAULT_PROFILE_ID);
1125
+ const provider = withoutProfile.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1126
+ const endpointSafeProvider = stripEndpointCredentials(provider);
1127
+ if (!endpointSafeProvider) return withoutProfile;
1128
+ return {
1129
+ ...withoutProfile,
1130
+ models: {
1131
+ ...withoutProfile.models,
1132
+ providers: {
1133
+ ...withoutProfile.models?.providers,
1134
+ [LLAMA_CPP_PROVIDER_ID]: endpointSafeProvider
1135
+ }
1136
+ }
1137
+ };
1138
+ }
1139
+ function stripAuthorizationHeader(headers) {
1140
+ const filtered = Object.fromEntries(Object.entries(headers ?? {}).filter(([name]) => name.toLowerCase() !== "authorization"));
1141
+ return Object.keys(filtered).length > 0 ? filtered : void 0;
1142
+ }
1143
+ function buildExistingProviderConfig(params) {
1144
+ const configured = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1145
+ const endpointSafe = params.resetEndpoint ? stripEndpointCredentials(configured) : configured;
1146
+ const existing = params.persistence.kind === "preserve" ? endpointSafe : stripAuthOverrides(endpointSafe, params.persistence.kind === "upsert");
1147
+ return buildLlamaServerProviderConfig({
1148
+ configured: {
1149
+ ...existing,
1150
+ baseUrl: params.discovery.endpoint.inferenceBaseUrl,
1151
+ models: existing?.models ?? []
1152
+ },
1153
+ discoveredModels: params.discovery.models
1154
+ });
1155
+ }
1156
+ function buildSetupResult$1(params) {
1157
+ return {
1158
+ profiles: params.persistence.kind === "upsert" ? [{
1159
+ profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
1160
+ credential: buildApiKeyCredential(LLAMA_CPP_PROVIDER_ID, params.persistence.credential, void 0, { config: params.config })
1161
+ }] : [],
1162
+ defaultModel: `${LLAMA_CPP_PROVIDER_ID}/${params.modelId}`,
1163
+ configPatch: {
1164
+ ...params.persistence.kind === "remove" ? buildLlamaCppAuthProfileRemovalPatch(params.config) : {},
1165
+ models: {
1166
+ mode: params.config.models?.mode ?? "merge",
1167
+ providers: { [LLAMA_CPP_PROVIDER_ID]: buildExistingProviderConfig(params) }
1168
+ }
1169
+ }
1170
+ };
1171
+ }
1172
+ async function removeDefaultAuthProfile(agentDir) {
1173
+ if (!await removeProviderAuthProfilesWithLock({
1174
+ agentDir,
1175
+ provider: "llama-cpp",
1176
+ profileIds: [LLAMA_CPP_DEFAULT_PROFILE_ID]
1177
+ })) throw new Error("Failed to remove the previous llama-server auth profile; wait a moment and retry.");
1178
+ }
1179
+ async function discoverForSetup(params) {
1180
+ const providerConfig = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1181
+ const headers = await resolveLlamaServerProviderHeaders({
1182
+ config: params.config,
1183
+ env: params.env,
1184
+ headers: providerConfig?.headers
1185
+ });
1186
+ const resolvedApiKey = !hasLlamaServerAuthorizationHeader(headers) ? await resolveLlamaServerRuntimeApiKey({ config: params.config }) : void 0;
1187
+ return await discoverLlamaServer({
1188
+ baseUrl: params.baseUrl,
1189
+ apiKey: resolvedApiKey,
1190
+ headers,
1191
+ signal: params.signal,
1192
+ cacheTtlMs: 0
1193
+ });
1194
+ }
1195
+ async function discoverWithAccess(params) {
1196
+ return await discoverLlamaServer({
1197
+ baseUrl: params.baseUrl,
1198
+ apiKey: params.apiKey,
1199
+ headers: params.headers,
1200
+ signal: params.signal,
1201
+ cacheTtlMs: 0
1202
+ });
1203
+ }
1204
+ /** Read-only discovery for the guided local-provider setup ladder. */
1205
+ async function detectLlamaServerSetup(ctx) {
1206
+ const provider = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1207
+ if (provider?.localService) return null;
1208
+ const baseUrl = provider?.baseUrl ?? "http://127.0.0.1:8080";
1209
+ let discovery;
1210
+ try {
1211
+ discovery = await discoverForSetup({
1212
+ config: ctx.config,
1213
+ baseUrl,
1214
+ env: ctx.env,
1215
+ signal: ctx.signal
1216
+ });
1217
+ } catch {
1218
+ return null;
1219
+ }
1220
+ if (discovery.kind !== "success") return null;
1221
+ const modelId = selectSetupModelId(discovery);
1222
+ if (!modelId) return null;
1223
+ return {
1224
+ modelRef: `${LLAMA_CPP_PROVIDER_ID}/${modelId}`,
1225
+ detail: `${modelId} at ${discovery.endpoint.origin}`
1226
+ };
1227
+ }
1228
+ /** Rechecks one guided candidate and returns the config needed for a live probe. */
1229
+ async function prepareLlamaServerSetup(ctx) {
1230
+ const provider = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1231
+ if (provider?.localService) return null;
1232
+ let discovery;
1233
+ try {
1234
+ discovery = await discoverForSetup({
1235
+ config: ctx.config,
1236
+ baseUrl: provider?.baseUrl ?? "http://127.0.0.1:8080",
1237
+ env: ctx.env,
1238
+ signal: ctx.signal
1239
+ });
1240
+ } catch {
1241
+ return null;
1242
+ }
1243
+ if (discovery.kind !== "success") return null;
1244
+ const prefix = `${LLAMA_CPP_PROVIDER_ID}/`;
1245
+ const modelId = ctx.modelRef.startsWith(prefix) ? ctx.modelRef.slice(prefix.length) : "";
1246
+ if (!modelId || !discovery.models.some((model) => model.config.id === modelId)) return null;
1247
+ return buildSetupResult$1({
1248
+ config: ctx.config,
1249
+ discovery,
1250
+ modelId,
1251
+ resetEndpoint: false,
1252
+ persistence: { kind: "preserve" }
1253
+ });
1254
+ }
1255
+ /** Interactive setup for an existing llama-server endpoint. */
1256
+ async function runLlamaServerSetup(ctx) {
1257
+ const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1258
+ const defaultOrigin = resolveLlamaServerEndpoint(existing?.baseUrl).origin;
1259
+ const endpoint = resolveLlamaServerEndpoint(await ctx.prompter.text({
1260
+ message: `${LLAMA_CPP_PROVIDER_LABEL} URL`,
1261
+ initialValue: defaultOrigin,
1262
+ placeholder: LLAMA_SERVER_DEFAULT_ORIGIN,
1263
+ validate: (value) => value?.trim() ? void 0 : "Required"
1264
+ }));
1265
+ const endpointChanged = Boolean(existing?.localService) || hasEndpointChanged(existing, endpoint.inferenceBaseUrl);
1266
+ const resolvedHeaders = endpointChanged ? void 0 : await resolveLlamaServerProviderHeaders({
1267
+ config: ctx.config,
1268
+ env: ctx.env,
1269
+ headers: existing?.headers
1270
+ });
1271
+ const usesApiKey = await ctx.prompter.confirm({
1272
+ message: "Does this llama-server require an API key?",
1273
+ initialValue: false
1274
+ });
1275
+ let apiKey;
1276
+ let headers = resolvedHeaders;
1277
+ let persistence;
1278
+ if (!usesApiKey) persistence = { kind: "remove" };
1279
+ else {
1280
+ const hasConfiguredProfile = Boolean(ctx.config.auth?.profiles?.[LLAMA_CPP_DEFAULT_PROFILE_ID]);
1281
+ const profileApiKey = !endpointChanged && !hasLlamaServerAuthorizationHeader(resolvedHeaders) && hasConfiguredProfile ? await resolveLlamaServerRuntimeApiKey({
1282
+ config: ctx.config,
1283
+ agentDir: ctx.agentDir,
1284
+ profileId: LLAMA_CPP_DEFAULT_PROFILE_ID
1285
+ }) : void 0;
1286
+ if (profileApiKey) {
1287
+ apiKey = profileApiKey;
1288
+ persistence = { kind: "preserve" };
1289
+ } else {
1290
+ let credentialInput;
1291
+ apiKey = await ensureApiKeyFromEnvOrPrompt({
1292
+ config: endpointChanged ? stripLlamaServerEndpointAuth(ctx.config) : ctx.config,
1293
+ env: endpointChanged ? {} : ctx.env,
1294
+ provider: LLAMA_CPP_PROVIDER_ID,
1295
+ envLabel: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
1296
+ promptMessage: "Enter the llama-server API key",
1297
+ normalize: (value) => value.trim(),
1298
+ validate: (value) => value.trim() ? void 0 : "Required",
1299
+ prompter: ctx.prompter,
1300
+ secretInputMode: ctx.secretInputMode,
1301
+ setCredential: async (input) => {
1302
+ credentialInput = input;
1303
+ }
1304
+ });
1305
+ if (credentialInput === void 0) throw new Error("llama-server API-key setup did not produce a credential");
1306
+ headers = stripAuthorizationHeader(resolvedHeaders);
1307
+ persistence = {
1308
+ kind: "upsert",
1309
+ credential: credentialInput
1310
+ };
1311
+ }
1312
+ }
1313
+ const discovery = await discoverWithAccess({
1314
+ baseUrl: endpoint.inferenceBaseUrl,
1315
+ apiKey,
1316
+ headers,
1317
+ signal: ctx.signal
1318
+ });
1319
+ if (discovery.kind !== "success") throw new Error(describeDiscoveryFailure(discovery));
1320
+ const modelId = selectSetupModelId(discovery);
1321
+ if (!modelId) throw new Error(`No llama-server text models were found at ${discovery.endpoint.origin}.`);
1322
+ if (persistence.kind === "remove") await removeDefaultAuthProfile(ctx.agentDir);
1323
+ return buildSetupResult$1({
1324
+ config: ctx.config,
1325
+ discovery,
1326
+ modelId,
1327
+ resetEndpoint: endpointChanged,
1328
+ persistence
1329
+ });
1330
+ }
1331
+ async function validateNonInteractiveDiscovery(ctx) {
1332
+ const configuredProvider = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1333
+ const baseUrl = normalizeOptionalSecretInput(ctx.opts.customBaseUrl) ?? configuredProvider?.baseUrl ?? "http://127.0.0.1:8080";
1334
+ const endpointChanged = Boolean(configuredProvider?.localService) || hasEndpointChanged(configuredProvider, baseUrl);
1335
+ const providerApiKey = normalizeOptionalSecretInput(ctx.opts.llamaServerApiKey);
1336
+ const customApiKey = normalizeOptionalSecretInput(ctx.opts.customApiKey);
1337
+ const authoredApiKey = providerApiKey ?? customApiKey;
1338
+ const hasAuthoredApiKey = authoredApiKey !== void 0;
1339
+ const resolvedApiKey = await ctx.resolveApiKey({
1340
+ provider: LLAMA_CPP_PROVIDER_ID,
1341
+ flagValue: authoredApiKey,
1342
+ flagName: providerApiKey === void 0 ? "--custom-api-key" : "--llama-server-api-key",
1343
+ envVar: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
1344
+ envVarName: LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR,
1345
+ required: false
1346
+ });
1347
+ const resolvedHeaders = endpointChanged ? void 0 : await resolveLlamaServerProviderHeaders({
1348
+ config: ctx.config,
1349
+ env: process.env,
1350
+ headers: configuredProvider?.headers
1351
+ });
1352
+ let apiKey;
1353
+ let headers = resolvedHeaders;
1354
+ let persistence;
1355
+ if (hasAuthoredApiKey && resolvedApiKey) {
1356
+ apiKey = resolvedApiKey.key;
1357
+ headers = stripAuthorizationHeader(resolvedHeaders);
1358
+ persistence = {
1359
+ kind: "upsert",
1360
+ credential: resolvedApiKey
1361
+ };
1362
+ } else if (endpointChanged || hasLlamaServerAuthorizationHeader(resolvedHeaders)) persistence = { kind: "remove" };
1363
+ else if (resolvedApiKey?.source === "profile") {
1364
+ apiKey = resolvedApiKey.key;
1365
+ persistence = { kind: "preserve" };
1366
+ } else if (resolvedApiKey) {
1367
+ apiKey = resolvedApiKey.key;
1368
+ persistence = {
1369
+ kind: "upsert",
1370
+ credential: resolvedApiKey
1371
+ };
1372
+ } else persistence = { kind: "remove" };
1373
+ const discovery = await discoverWithAccess({
1374
+ baseUrl,
1375
+ apiKey,
1376
+ headers
1377
+ });
1378
+ if (discovery.kind !== "success") {
1379
+ ctx.runtime.error(describeDiscoveryFailure(discovery));
1380
+ ctx.runtime.exit(1);
1381
+ return null;
1382
+ }
1383
+ const requestedModelId = normalizeOptionalSecretInput(ctx.opts.customModelId);
1384
+ const modelId = requestedModelId ?? selectSetupModelId(discovery);
1385
+ if (!modelId || !discovery.models.some((model) => model.config.id === modelId)) {
1386
+ const available = discovery.models.map((model) => model.config.id).join(", ");
1387
+ 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}.`);
1388
+ ctx.runtime.exit(1);
1389
+ return null;
1390
+ }
1391
+ return {
1392
+ discovery,
1393
+ modelId,
1394
+ resetEndpoint: endpointChanged,
1395
+ persistence
1396
+ };
1397
+ }
1398
+ async function validateLlamaServerNonInteractive(ctx) {
1399
+ return Boolean(await validateNonInteractiveDiscovery(ctx));
1400
+ }
1401
+ /** Non-interactive setup with optional API-key persistence. */
1402
+ async function configureLlamaServerNonInteractive(ctx) {
1403
+ const validated = await validateNonInteractiveDiscovery(ctx);
1404
+ if (!validated) return null;
1405
+ const providerConfig = buildExistingProviderConfig({
1406
+ config: ctx.config,
1407
+ discovery: validated.discovery,
1408
+ resetEndpoint: validated.resetEndpoint,
1409
+ persistence: validated.persistence
1410
+ });
1411
+ let config = {
1412
+ ...ctx.config,
1413
+ models: {
1414
+ ...ctx.config.models,
1415
+ mode: ctx.config.models?.mode ?? "merge",
1416
+ providers: {
1417
+ ...ctx.config.models?.providers,
1418
+ [LLAMA_CPP_PROVIDER_ID]: providerConfig
1419
+ }
1420
+ }
1421
+ };
1422
+ if (validated.persistence.kind === "upsert") {
1423
+ const credential = ctx.toApiKeyCredential({
1424
+ provider: LLAMA_CPP_PROVIDER_ID,
1425
+ resolved: validated.persistence.credential
1426
+ });
1427
+ if (!credential) return null;
1428
+ await upsertAuthProfileWithLock({
1429
+ profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
1430
+ credential,
1431
+ agentDir: ctx.agentDir
1432
+ });
1433
+ config = applyAuthProfileConfig(config, {
1434
+ profileId: LLAMA_CPP_DEFAULT_PROFILE_ID,
1435
+ provider: LLAMA_CPP_PROVIDER_ID,
1436
+ mode: "api_key"
1437
+ });
1438
+ } else if (validated.persistence.kind === "remove") {
1439
+ await removeDefaultAuthProfile(ctx.agentDir);
1440
+ config = removeAuthProfileConfig(config, LLAMA_CPP_DEFAULT_PROFILE_ID);
1441
+ }
1442
+ ctx.runtime.log(`Default ${LLAMA_CPP_PROVIDER_LABEL} model: ${validated.modelId}`);
1443
+ return applyProviderDefaultModel(config, `${LLAMA_CPP_PROVIDER_ID}/${validated.modelId}`);
1444
+ }
1445
+ //#endregion
1446
+ //#region extensions/llama-cpp/src/external-server/stream.ts
1447
+ /** Maps shared structured-output requests to the shape accepted by older llama-server builds. */
1448
+ function normalizeLlamaServerResponseFormat(payload, requestedResponseFormat) {
1449
+ const responseFormat = isRecord(payload.response_format) ? payload.response_format : requestedResponseFormat;
1450
+ if (!responseFormat || responseFormat.type === "text") return;
1451
+ const schema = responseFormat.type === "json_schema" ? isRecord(responseFormat.json_schema) ? responseFormat.json_schema.schema : responseFormat.schema : responseFormat.type === "json_object" ? responseFormat.schema : responseFormat;
1452
+ if (isRecord(schema)) payload.response_format = {
1453
+ type: "json_object",
1454
+ schema
1455
+ };
1456
+ }
1457
+ /** Keeps the shared OpenAI transport and adjusts llama-server request compatibility. */
1458
+ function wrapLlamaServerStream(ctx) {
1459
+ const underlying = ctx.streamFn ?? streamSimple;
1460
+ return (model, context, options) => {
1461
+ if (model.provider !== "llama-cpp") return underlying(model, context, options);
1462
+ const onPayload = options?.onPayload;
1463
+ return underlying(model, context, {
1464
+ ...options,
1465
+ onPayload: async (payload, requestModel) => {
1466
+ const customized = await onPayload?.(payload, requestModel) ?? payload;
1467
+ if (isRecord(customized)) {
1468
+ if (ctx.thinkingLevel === "off") setQwenChatTemplateThinking(customized, false);
1469
+ normalizeLlamaServerResponseFormat(customized, options?.responseFormat);
1470
+ }
1471
+ return customized;
1472
+ }
1473
+ });
1474
+ };
1475
+ }
1476
+ //#endregion
726
1477
  //#region extensions/llama-cpp/src/setup.ts
727
1478
  const BYTES_PER_GB = 1e9;
728
1479
  const BYTES_PER_MB = 1e6;
@@ -740,7 +1491,7 @@ function readPrimaryModel(config) {
740
1491
  }
741
1492
  function configuredCandidates(config) {
742
1493
  const existing = config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
743
- const provider = buildLlamaCppProviderConfig(existing);
1494
+ const provider = buildLlamaCppProviderConfig(existing?.localService ? existing : void 0);
744
1495
  const primary = readPrimaryModel(config);
745
1496
  const primaryId = primary?.startsWith(`llama-cpp/`) ? primary.slice(LLAMA_CPP_PROVIDER_ID.length + 1) : void 0;
746
1497
  return provider.models.map((model) => ({
@@ -776,13 +1527,18 @@ function readConfiguredPort(provider) {
776
1527
  }
777
1528
  }
778
1529
  function buildSetupResult(params) {
1530
+ const existing = params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1531
+ const switchingFromExternal = Boolean(existing && !existing.localService);
779
1532
  return {
780
1533
  profiles: [],
781
1534
  defaultModel: params.defaultModel ?? DEFAULT_LLAMA_CPP_MODEL_REF,
782
- configPatch: { models: {
783
- mode: params.config.models?.mode ?? "merge",
784
- providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig(params.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID], params.managed) }
785
- } }
1535
+ configPatch: {
1536
+ ...buildLlamaCppAuthProfileRemovalPatch(params.config),
1537
+ models: {
1538
+ mode: params.config.models?.mode ?? "merge",
1539
+ providers: { [LLAMA_CPP_PROVIDER_ID]: buildLlamaCppProviderConfig(switchingFromExternal ? void 0 : existing, params.managed) }
1540
+ }
1541
+ }
786
1542
  };
787
1543
  }
788
1544
  async function detectLlamaCppSetup(ctx) {
@@ -807,16 +1563,15 @@ async function prepareLlamaCppSetup(ctx) {
807
1563
  defaultModel: ctx.modelRef,
808
1564
  managed: {
809
1565
  command: existing.localService.command,
810
- presetPath: existing.localService.args?.find((_, index, args) => args[index - 1] === "--models-preset") ?? resolveManagedLlamaServerPaths(selectLlamaServerAsset()).presetPath,
811
1566
  baseUrl,
812
1567
  healthUrl: existing.localService.healthUrl ?? `${rootUrl}/health`,
813
- args: existing.localService.args ?? [],
814
- backend: selectLlamaServerAsset().backend
1568
+ args: existing.localService.args ?? []
815
1569
  }
816
1570
  });
817
1571
  }
818
1572
  async function runLlamaCppSetup(ctx) {
819
1573
  const existing = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1574
+ const managedExisting = existing?.localService ? existing : void 0;
820
1575
  const candidates = configuredCandidates(ctx.config);
821
1576
  let selected = candidates[0];
822
1577
  let chatModelPath = selected ? await resolveCachedCandidate(selected) : void 0;
@@ -838,7 +1593,7 @@ async function runLlamaCppSetup(ctx) {
838
1593
  if (!selected) throw new Error("llama.cpp setup could not resolve a chat model");
839
1594
  const progress = ctx.prompter.progress("Preparing managed llama.cpp server…");
840
1595
  try {
841
- const cacheDir = resolveLlamaCppModelCacheDir(existing);
1596
+ const cacheDir = resolveLlamaCppModelCacheDir(managedExisting);
842
1597
  chatModelPath ??= await ensureLlamaCppModel({
843
1598
  source: resolveLlamaCppModelSource(selected.model),
844
1599
  cacheDir,
@@ -861,8 +1616,13 @@ async function runLlamaCppSetup(ctx) {
861
1616
  contextSize,
862
1617
  maxTokens: selected.model.maxTokens,
863
1618
  embeddingModelPath,
864
- port: readConfiguredPort(existing)
1619
+ port: readConfiguredPort(managedExisting)
865
1620
  });
1621
+ if (!await removeProviderAuthProfilesWithLock({
1622
+ provider: "llama-cpp",
1623
+ profileIds: [LLAMA_CPP_DEFAULT_PROFILE_ID],
1624
+ agentDir: ctx.agentDir
1625
+ })) throw new Error("Failed to remove the previous llama.cpp endpoint auth profile");
866
1626
  progress.stop("Managed llama.cpp server prepared");
867
1627
  return buildSetupResult({
868
1628
  config: ctx.config,
@@ -876,72 +1636,104 @@ async function runLlamaCppSetup(ctx) {
876
1636
  }
877
1637
  }
878
1638
  //#endregion
1639
+ //#region extensions/llama-cpp/src/managed-provider.ts
1640
+ function registerLlamaCppProvider(api) {
1641
+ api.registerProvider({
1642
+ id: LLAMA_CPP_PROVIDER_ID,
1643
+ label: LLAMA_CPP_PROVIDER_LABEL,
1644
+ docsPath: "/plugins/llama-cpp",
1645
+ envVars: [LLAMA_SERVER_DEFAULT_API_KEY_ENV_VAR],
1646
+ auth: [{
1647
+ id: "local",
1648
+ label: LLAMA_CPP_PROVIDER_LABEL,
1649
+ hint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
1650
+ kind: "custom",
1651
+ wizard: {
1652
+ choiceId: LLAMA_CPP_PROVIDER_ID,
1653
+ choiceLabel: "Managed local server",
1654
+ choiceHint: "Install a verified llama.cpp server and run a private GGUF model managed by OpenClaw",
1655
+ groupId: LLAMA_CPP_PROVIDER_ID,
1656
+ groupLabel: "Local llama.cpp",
1657
+ groupHint: "Managed or external llama.cpp server",
1658
+ methodId: "local"
1659
+ },
1660
+ appGuidedSetup: {
1661
+ detect: detectLlamaCppSetup,
1662
+ prepare: prepareLlamaCppSetup
1663
+ },
1664
+ run: runLlamaCppSetup
1665
+ }, {
1666
+ id: "existing-server",
1667
+ label: "Existing llama-server",
1668
+ hint: "Connect to an existing local, private, or remote llama.cpp server",
1669
+ kind: "custom",
1670
+ wizard: {
1671
+ choiceId: "llama-cpp-existing-server",
1672
+ choiceLabel: "Existing llama-server",
1673
+ choiceHint: "Connect to a llama.cpp server managed outside OpenClaw",
1674
+ groupId: LLAMA_CPP_PROVIDER_ID,
1675
+ groupLabel: "Local llama.cpp",
1676
+ groupHint: "Managed or external llama.cpp server",
1677
+ methodId: "existing-server"
1678
+ },
1679
+ appGuidedSetup: {
1680
+ detect: detectLlamaServerSetup,
1681
+ prepare: prepareLlamaServerSetup
1682
+ },
1683
+ run: runLlamaServerSetup,
1684
+ validateNonInteractive: validateLlamaServerNonInteractive,
1685
+ runNonInteractive: async (ctx) => await configureLlamaServerNonInteractive(ctx)
1686
+ }],
1687
+ catalog: {
1688
+ order: "late",
1689
+ run: async (ctx) => {
1690
+ const configured = ctx.config.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1691
+ return configured?.localService ? { provider: buildLlamaCppProviderConfig(configured) } : await discoverLlamaServerProvider(ctx);
1692
+ }
1693
+ },
1694
+ staticCatalog: {
1695
+ order: "late",
1696
+ run: async () => ({ provider: buildLlamaCppProviderConfig() })
1697
+ },
1698
+ resolveSyntheticAuth: ({ providerConfig }) => providerConfig?.localService || shouldUseLlamaServerSyntheticAuth(providerConfig) ? {
1699
+ apiKey: resolveLlamaCppSyntheticApiKey(),
1700
+ source: providerConfig?.localService ? "managed local llama.cpp server" : hasLlamaServerAuthorizationHeader(providerConfig?.headers) ? "models.providers.llama-cpp.headers.Authorization" : "models.providers.llama-cpp (synthetic local key)",
1701
+ mode: "api-key"
1702
+ } : void 0,
1703
+ shouldDeferSyntheticProfileAuth: ({ resolvedApiKey }) => resolvedApiKey?.trim() === resolveLlamaCppSyntheticApiKey() || resolvedApiKey?.trim() === CUSTOM_LOCAL_AUTH_MARKER,
1704
+ normalizeConfig: ({ providerConfig }) => providerConfig.localService ? providerConfig : normalizeLlamaServerProviderConfig(providerConfig),
1705
+ prepareDynamicModel: async (ctx) => ctx.config?.models?.providers?.["llama-cpp"]?.localService ? void 0 : await prepareLlamaServerDynamicModel(ctx),
1706
+ wrapStreamFn: (ctx) => {
1707
+ const providerConfig = ctx.config?.models?.providers?.[LLAMA_CPP_PROVIDER_ID];
1708
+ if (!providerConfig?.localService) return wrapLlamaServerStream(ctx);
1709
+ const inner = ctx.streamFn;
1710
+ const selectedModel = ctx.model;
1711
+ if (!inner || !selectedModel) return;
1712
+ return async (model, context, options) => {
1713
+ await ensureManagedLlamaServerForChat({
1714
+ provider: providerConfig,
1715
+ model: selectedModel
1716
+ });
1717
+ return inner(model, context, options);
1718
+ };
1719
+ },
1720
+ ...buildProviderToolCompatFamilyHooks("llamacpp-gbnf"),
1721
+ wizard: { modelPicker: {
1722
+ label: "llama.cpp",
1723
+ hint: `Use a managed server or connect to ${LLAMA_SERVER_DEFAULT_ORIGIN}`,
1724
+ methodId: "local"
1725
+ } }
1726
+ });
1727
+ }
1728
+ //#endregion
879
1729
  //#region extensions/llama-cpp/index.ts
880
1730
  var llama_cpp_default = definePluginEntry({
881
1731
  id: "llama-cpp",
882
1732
  name: "llama.cpp Provider",
883
- description: "Managed local llama.cpp server for GGUF chat and embeddings",
1733
+ description: "Managed and external llama.cpp servers for GGUF chat and embeddings",
884
1734
  register(api) {
885
1735
  api.registerEmbeddingProvider(llamaCppEmbeddingProviderAdapter);
886
- api.registerProvider({
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
- });
1736
+ registerLlamaCppProvider(api);
945
1737
  }
946
1738
  });
947
1739
  //#endregion