openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
690 lines (689 loc) • 23.6 kB
JavaScript
import { resolvePluginConfigObject } from "openclaw/plugin-sdk/plugin-config-runtime";
import { isIPv4 } from "node:net";
import { LiveModelCatalogHttpError, runLiveProviderCatalog } from "openclaw/plugin-sdk/provider-catalog-live-runtime";
import { coerceSecretRef } from "openclaw/plugin-sdk/secret-input";
import { fetchWithSsrFGuard, isLoopbackHost } from "openclaw/plugin-sdk/ssrf-runtime";
import { normalizeOptionalString, normalizeUniqueTrimmedStringList } from "openclaw/plugin-sdk/string-coerce-runtime";
import { isCloudModelRef } from "openclaw/plugin-sdk/model-ref-parse";
import { normalizeProviderId } from "openclaw/plugin-sdk/provider-model-metadata";
import { createHash } from "node:crypto";
import { createStaleWhileRevalidateCache } from "openclaw/plugin-sdk/collection-runtime";
import { toErrorObject } from "openclaw/plugin-sdk/error-runtime";
import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
import { isCloudModelRef as isCloudModelRef$1, resolveDefaultModelMaxTokens } from "openclaw/plugin-sdk/provider-model-shared";
//#region extensions/ollama/src/defaults.ts
const OLLAMA_DEFAULT_BASE_URL = "http://127.0.0.1:11434";
const OLLAMA_DEFAULT_API_KEY = "ollama-local";
function isHostedOllamaCloud(e) {
const t = e ? URL.parse(e)?.hostname.toLowerCase() : void 0;
return t !== void 0 && (t === "ollama.com" || t.endsWith(".ollama.com"));
}
const OLLAMA_GLM52_CLOUD_MODEL_ID = "glm-5.2";
/**
* Order is a contract: cloud onboarding merges this list ahead of live discovery and takes
* the first name as `defaultModel` (`setup.runtime.ts`). Reordering this array changes what
* every new setup selects, so keep the intended default at index 0.
*/
const OLLAMA_CLOUD_DEFAULT_MODELS = [
{
id: "minimax-m2.7",
contextWindow: 196608,
maxTokens: 204800,
capabilities: [
"completion",
"thinking",
"tools"
]
},
{
id: "minimax-m3",
contextWindow: 524288,
maxTokens: 524288,
capabilities: [
"completion",
"thinking",
"tools",
"vision"
]
},
{
id: "kimi-k3",
contextWindow: 1048576,
maxTokens: 1048576,
capabilities: [
"completion",
"thinking",
"tools",
"vision"
]
},
{
id: OLLAMA_GLM52_CLOUD_MODEL_ID,
contextWindow: 1e6,
maxTokens: 131072,
capabilities: [
"completion",
"thinking",
"tools"
]
}
];
/** Cloud models are referenced bare, `:cloud`-suffixed, and `-cloud`-suffixed. */
function normalizeOllamaCloudModelId(e) {
return e.trim().toLowerCase().replace(/(?::cloud|-cloud)$/, "");
}
function resolveOllamaCloudDefaultModel(e) {
const t = normalizeOllamaCloudModelId(e);
return OLLAMA_CLOUD_DEFAULT_MODELS.find((e) => e.id === t);
}
/**
* Hosted Ollama output budget. Local models return undefined and take the shared
* context-sized default, which keeps prompt room inside the local num_ctx.
*/
function resolveOllamaOutputBudget(e) {
return e.remote || isCloudModelRef(e.modelId) ? resolveOllamaCloudDefaultModel(e.modelId)?.maxTokens ?? e.contextWindow ?? 128e3 : void 0;
}
const OLLAMA_DEFAULT_CONTEXT_WINDOW = 128e3;
const OLLAMA_LOCAL_CONTEXT_TOKENS = 32768;
const OLLAMA_DEFAULT_COST = {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
};
//#endregion
//#region extensions/ollama/src/model-id.ts
const OLLAMA_PROVIDER_ID$1 = "ollama";
function normalizeOllamaWireModelId(e, t) {
const n = e.trim();
if (!n) return n;
for (const e of normalizeUniqueTrimmedStringList([
t,
normalizeProviderId(t ?? ""),
OLLAMA_PROVIDER_ID$1
])) {
const t = `${e}/`;
if (n.startsWith(t)) return n.slice(t.length);
}
return n;
}
function getOllamaLatestDedupeKey(e) {
const t = e.trim().toLowerCase();
return t.endsWith(":latest") ? t.slice(0, -7) : t;
}
function findAvailableOllamaModelName(e, t) {
const n = getOllamaLatestDedupeKey(e);
for (const e of t) if (getOllamaLatestDedupeKey(e) === n) return e;
}
//#endregion
//#region extensions/ollama/src/provider-base-url.ts
function readProviderBaseUrl(e) {
if (!e) return;
if (Object.hasOwn(e, "baseUrl") && e.baseUrl?.trim()) return e.baseUrl.trim();
const t = e;
if (Object.hasOwn(t, "baseURL") && typeof t.baseURL === "string" && t.baseURL.trim()) return t.baseURL.trim();
}
//#endregion
//#region extensions/ollama/src/model-reasoning.ts
const OLLAMA_THINKING_EFFORTS = [
"minimal",
"low",
"medium",
"high",
"xhigh",
"max"
];
function readOllamaThinkingMapValue(e) {
return e === "false" ? false : e === "true" ? true : OLLAMA_THINKING_EFFORTS.find((t) => t === e);
}
/** Prepare native wire values once, inside the discovery/cache lifecycle. */
async function buildOllamaThinkingLevelMap(e, t) {
if (!t || typeof t !== "object" || !("values" in t) || !Array.isArray(t.values)) return;
const n = t.values;
const r = ["off", ...OLLAMA_THINKING_EFFORTS];
const i = Object.fromEntries(r.map((e) => [e, e === "off" ? n.includes(false) ? "false" : null : n.includes(e) ? e : e === "low" && n.includes(true) ? "true" : null]));
if (!Object.values(i).some((e) => e !== null)) return;
const { clampThinkingLevel: a } = await import("openclaw/plugin-sdk/llm");
const o = {
id: e,
name: e,
provider: "ollama",
api: "ollama",
baseUrl: "",
reasoning: true,
input: ["text"],
cost: OLLAMA_DEFAULT_COST,
contextWindow: OLLAMA_DEFAULT_CONTEXT_WINDOW,
maxTokens: OLLAMA_DEFAULT_CONTEXT_WINDOW,
thinkingLevelMap: i
};
return {
...Object.fromEntries(r.map((e) => [e, i[a(o, e)]])),
minimal: i.minimal,
xhigh: i.xhigh
};
}
const OLLAMA_CLOUD_FULL_THINKING_EFFORT_MODEL_IDS = /* @__PURE__ */ new Set([
"deepseek-v4-flash",
"deepseek-v4-pro",
"deepseek-v4.1-flash",
"glm-5.2",
"glm-5.3",
"glm-5.3-flash",
"kimi-k3"
]);
function supportsOllamaCloudFullThinkingEffort(e) {
return OLLAMA_CLOUD_FULL_THINKING_EFFORT_MODEL_IDS.has(normalizeOllamaCloudModelId(e));
}
//#endregion
//#region extensions/ollama/src/provider-models.ts
const OLLAMA_SHOW_CONCURRENCY = 8;
const OLLAMA_CONTEXT_ENRICH_LIMIT = 200;
const OLLAMA_SHOW_TIMEOUT_MS = 3e3;
const OLLAMA_TAGS_TIMEOUT_MS = 5e3;
const MAX_OLLAMA_DISCOVERY_PROBES = 800;
const ollamaModelShowInfoCache = createStaleWhileRevalidateCache({
maxEntries: 256,
maxPending: Infinity,
ttlMs: Infinity,
cacheable: hasOllamaModelShowInfo
});
const OLLAMA_ALWAYS_BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set(["metadata.google.internal"]);
function buildOllamaBaseUrlSsrFPolicy(e) {
const t = e.trim();
if (!t) return;
const n = URL.parse(t);
if (!n || n.protocol !== "http:" && n.protocol !== "https:" || OLLAMA_ALWAYS_BLOCKED_HOSTNAMES.has(n.hostname)) return;
return {
hostnameAllowlist: [n.hostname],
allowPrivateNetwork: true
};
}
function resolveOllamaApiBase(e) {
if (!e) return OLLAMA_DEFAULT_BASE_URL;
return e.replace(/\/+$/, "").replace(/\/v1$/i, "");
}
const mergeOllamaModelShowInfo = (e, t) => {
const n = t.capabilities === void 0 && e.capabilities !== void 0 && isOllamaRemoteModel(e) && !isOllamaEmbeddingOnlyModel(e);
const r = t.parameterCount ?? e.parameterCount ?? parseOllamaParameterSize(e.details?.parameter_size);
return {
...e,
...t,
...r !== void 0 ? { parameterCount: r } : {},
contextWindow: t.contextWindow ?? e.contextWindow ?? e.details?.context_length,
capabilities: n ? [.../* @__PURE__ */ new Set([
...e.capabilities ?? [],
...t.showInspectionFailed ? [] : ["tools"],
...isReasoningModelHeuristic(e.name) ? ["thinking"] : []
])] : t.capabilities ?? e.capabilities,
...n ? { capabilitiesFromList: true } : {}
};
};
const OLLAMA_FAILED_SHOW_INFO = Object.freeze({ showInspectionFailed: true });
function throwIfOllamaRequestAborted(e) {
if (e?.aborted) throw toErrorObject(e.reason, "Ollama request aborted");
}
function buildOllamaModelShowCacheKey(e, t, n) {
const r = t.digest?.trim() || t.modified_at?.trim();
if (!r) return;
const i = n ? createHash("sha256").update(n).digest("hex") : "anonymous";
return `${resolveOllamaApiBase(e)}|${t.name}|${r}|${i}`;
}
function hasOllamaModelShowInfo(e) {
return e.parameterCount !== void 0 || e.contextWindow !== void 0 || (e.capabilities?.length ?? 0) > 0 || e.thinkingLevelMap !== void 0;
}
function parseOllamaParameterSize(e) {
const t = typeof e === "string" ? e.trim().match(/^(\d+(?:\.\d+)?)\s*([KMBT])$/i) : void 0;
const n = t?.[1];
const r = t?.[2];
if (!n || !r) return;
const i = "KMBT".indexOf(r.toUpperCase()) + 1;
const a = Math.round(Number(n) * 1e3 ** i);
return Number.isSafeInteger(a) && a > 0 ? a : void 0;
}
function parseOllamaNumCtxParameter(e) {
if (typeof e !== "string" || !e.trim()) return;
let t;
for (const n of e.split(/\r?\n/)) {
const e = n.trim().match(/^num_ctx\s+(-?\d+)\b/);
if (!e) continue;
const r = e[1];
if (!r) continue;
const i = Number.parseInt(r, 10);
if (Number.isFinite(i) && i > 0) t = i;
}
return t;
}
async function readOllamaModelShowInfo(e, t, n) {
const r = resolveOllamaApiBase(e);
const i = n?.auditContext ?? "ollama-provider-models.show";
const a = { "Content-Type": "application/json" };
if (n?.apiKey) a.Authorization = `Bearer ${n.apiKey}`;
const { response: o, release: s } = await fetchWithSsrFGuard({
url: `${r}/api/show`,
init: {
method: "POST",
headers: a,
body: JSON.stringify({ model: t })
},
timeoutMs: Math.min(n?.timeoutMs ?? OLLAMA_SHOW_TIMEOUT_MS, OLLAMA_SHOW_TIMEOUT_MS),
...n?.signal ? { signal: n.signal } : {},
policy: buildOllamaBaseUrlSsrFPolicy(r),
auditContext: i
});
try {
if (!o.ok) {
o.body?.cancel().catch(() => void 0);
throw new Error(`Ollama model inspection failed with HTTP ${o.status}`);
}
const e = await readProviderJsonResponse(o, i);
let n;
if (e.model_info) {
for (const [t, r] of Object.entries(e.model_info)) if (t.endsWith(".context_length") && typeof r === "number" && Number.isFinite(r)) {
const e = Math.floor(r);
if (e > 0) {
n = e;
break;
}
}
}
const r = parseOllamaNumCtxParameter(e.parameters);
if (r !== void 0 && (n === void 0 || r > n)) n = r;
const a = Array.isArray(e.capabilities) ? e.capabilities.filter((e) => typeof e === "string") : void 0;
const s = e.model_info?.["general.parameter_count"];
const c = typeof s === "number" && Number.isSafeInteger(s) && s > 0 ? s : parseOllamaParameterSize(e.details?.parameter_size);
const l = await buildOllamaThinkingLevelMap(t, e.thinking);
return {
contextWindow: n,
capabilities: a,
...c !== void 0 ? { parameterCount: c } : {},
...l ? { thinkingLevelMap: l } : {}
};
} finally {
await s();
}
}
async function queryOllamaModelShowInfo(e, t, n) {
try {
return await readOllamaModelShowInfo(e, t, n);
} catch {
throwIfOllamaRequestAborted(n?.signal);
return OLLAMA_FAILED_SHOW_INFO;
}
}
async function queryOllamaModelShowInfoCached(e, t, n) {
const r = resolveOllamaApiBase(e);
const i = buildOllamaModelShowCacheKey(r, t, n?.apiKey);
if (!i || n?.timeoutMs !== void 0 || n?.signal) return await queryOllamaModelShowInfo(r, t.name, n);
const { value: a } = await ollamaModelShowInfoCache.read(i, () => queryOllamaModelShowInfo(r, t.name, n), { allowStale: false });
return a;
}
async function enrichOllamaModelsWithContext(e, t, n) {
const r = [];
for (let i = 0; i < t.length; i += OLLAMA_SHOW_CONCURRENCY) {
throwIfOllamaRequestAborted(n?.signal);
const a = t.slice(i, i + OLLAMA_SHOW_CONCURRENCY).map(async (t) => {
const r = await queryOllamaModelShowInfoCached(e, t, n);
return mergeOllamaModelShowInfo(t, r);
});
try {
r.push(...await Promise.all(a));
} catch (e) {
await Promise.allSettled(a);
throw e;
}
}
return r;
}
async function enrichOllamaCompletionModels(e, t, n) {
const r = [];
const i = Math.min(t.length, MAX_OLLAMA_DISCOVERY_PROBES);
for (let a = 0; a < i && r.length < OLLAMA_CONTEXT_ENRICH_LIMIT; a += OLLAMA_SHOW_CONCURRENCY) {
throwIfOllamaRequestAborted(n?.signal);
const o = await enrichOllamaModelsWithContext(e, t.slice(a, Math.min(a + OLLAMA_SHOW_CONCURRENCY, i)), n);
for (const e of o) {
const t = e.capabilities?.includes("completion");
if (isOllamaEmbeddingOnlyModel(e) || !t && (n?.requireCompletionCapability || e.capabilities && !e.capabilitiesFromList)) continue;
r.push(e);
if (r.length === OLLAMA_CONTEXT_ENRICH_LIMIT) break;
}
}
return r;
}
function isOllamaCloudModel(e) {
return isCloudModelRef$1(e);
}
function isOllamaEmbeddingOnlyModel(e) {
return e.capabilities?.includes("embedding") === true && !e.capabilities.includes("completion");
}
function isOllamaRemoteModel(e) {
return Boolean(e.remote_host?.trim() || e.remote_model?.trim()) || isOllamaCloudModel(e.name);
}
function isReasoningModelHeuristic(e) {
return /r1|reasoning|think|reason/i.test(e);
}
function buildOllamaModelDefinition(e, t, n, r) {
const i = resolveOllamaCloudDefaultModel(e);
const a = t ?? i?.contextWindow ?? 128e3;
return {
id: e,
name: e,
reasoning: r?.thinkingLevelMap ? Object.values(r.thinkingLevelMap).some((e) => Boolean(readOllamaThinkingMapValue(e))) : supportsOllamaCloudFullThinkingEffort(e) || (n === void 0 ? isReasoningModelHeuristic(e) : n.includes("thinking")),
input: n?.includes("vision") ? ["text", "image"] : ["text"],
cost: OLLAMA_DEFAULT_COST,
contextWindow: a,
maxTokens: resolveOllamaOutputBudget({
modelId: e,
contextWindow: a,
remote: r?.remote
}) ?? resolveDefaultModelMaxTokens(Math.min(a, 32768)),
...r?.parameterCount !== void 0 ? { parameterCount: r.parameterCount } : {},
...r?.thinkingLevelMap ? { thinkingLevelMap: r.thinkingLevelMap } : {},
compat: {
supportsTools: n?.includes("tools") ?? r?.showInspectionFailed !== true,
supportsUsageInStreaming: true,
supportsJsonSchemaResponseFormat: !isOllamaCloudModel(e)
}
};
}
function capLocalOllamaModelContext(e, t) {
if (isHostedOllamaCloud(t) || isOllamaCloudModel(e.id) || typeof e.contextWindow !== "number") return e;
return {
...e,
contextTokens: Math.min(OLLAMA_LOCAL_CONTEXT_TOKENS, e.contextWindow)
};
}
function capLocalOllamaProviderContext(e) {
return {
...e,
models: e.models?.map((t) => capLocalOllamaModelContext(t, e.baseUrl))
};
}
async function fetchOllamaModelRows(e) {
try {
const t = resolveOllamaApiBase(e.baseUrl);
const n = `ollama-provider-models.${e.endpoint}`;
const { response: r, release: i } = await fetchWithSsrFGuard({
url: `${t}/api/${e.endpoint}`,
init: { headers: e.opts?.apiKey ? { Authorization: `Bearer ${e.opts.apiKey}` } : void 0 },
timeoutMs: Math.min(e.opts?.timeoutMs ?? OLLAMA_TAGS_TIMEOUT_MS, OLLAMA_TAGS_TIMEOUT_MS),
...e.opts?.signal ? { signal: e.opts.signal } : {},
policy: buildOllamaBaseUrlSsrFPolicy(t),
auditContext: n
});
try {
if (!r.ok) {
r.body?.cancel().catch(() => void 0);
if (e.opts?.discoveryMode === "strict") throw new LiveModelCatalogHttpError("ollama", r.status);
return {
reachable: true,
models: []
};
}
const t = await readProviderJsonResponse(r, n);
const i = Array.isArray(t.models) ? t.models : void 0;
if (e.opts?.discoveryMode === "strict" && !i) throw new Error("Ollama model discovery response must contain models[]");
return {
reachable: true,
models: i ?? []
};
} finally {
await i();
}
} catch (t) {
throwIfOllamaRequestAborted(e.opts?.signal);
if (e.opts?.discoveryMode === "strict") throw t;
return {
reachable: false,
models: []
};
}
}
async function fetchOllamaModels(e, t) {
const n = await fetchOllamaModelRows({
baseUrl: e,
endpoint: "tags",
opts: t
});
return {
reachable: n.reachable,
models: n.models.filter((e) => typeof e.name === "string" && Boolean(e.name))
};
}
async function buildOllamaProvider(e, t) {
const n = resolveOllamaApiBase(e);
const r = t?.apiKey ? { apiKey: t.apiKey } : void 0;
const { reachable: i, models: a } = await fetchOllamaModels(n, t);
if (!i && !t?.quiet) console.warn(`Ollama could not be reached at ${n}.`);
if (i) t?.onListedModels?.(a.map((e) => e.name));
return {
baseUrl: n,
api: "ollama",
models: (await enrichOllamaCompletionModels(n, a, r)).map((e) => buildOllamaModelDefinition(e.name, e.contextWindow, e.capabilities, {
...e,
remote: isHostedOllamaCloud(n) || isOllamaRemoteModel(e)
}))
};
}
//#endregion
//#region extensions/ollama/src/discovery-shared.ts
const OLLAMA_PROVIDER_ID = "ollama";
const getUnlistedOllamaConfiguredModelIds = (e, t) => t.filter((t) => t.provider === "ollama" && (!t.baseUrl || resolveOllamaApiBase(t.baseUrl) === resolveOllamaApiBase(e.baseUrl)) && !findAvailableOllamaModelName(normalizeOllamaWireModelId(t.modelId), e.modelIds)).map((e) => e.modelId);
function readOllamaStringValue(e) {
if (typeof e === "string") return normalizeOptionalString(e);
if (e && typeof e === "object" && "value" in e) return normalizeOptionalString(e.value);
}
function isOllamaApiKeyMarker(e) {
return e === "OLLAMA_API_KEY" || e === "ollama-local";
}
function resolveOllamaRuntimeBaseUrl(e) {
if (e.configuredBaseUrl && e.api && e.api !== "ollama") return e.configuredBaseUrl;
return e.discoveredBaseUrl;
}
const LOCAL_OLLAMA_HOSTNAMES = /* @__PURE__ */ new Set([
"localhost",
"0.0.0.0",
"::1",
"::",
"docker.orb.internal",
"host.docker.internal",
"host.orb.internal"
]);
const LOOPBACK_OLLAMA_HOSTNAMES = /* @__PURE__ */ new Set([
"localhost",
"127.0.0.1",
"0.0.0.0",
"::1",
"::"
]);
function isIpv4PrivateRange(e) {
const [t, n] = e.split(".");
return isIPv4(e) && (t === "10" || t === "172" && Number(n) >= 16 && Number(n) <= 31 || t === "192" && n === "168");
}
function isIpv6LocalRange(e) {
const t = e.toLowerCase();
return /^fe[89ab][0-9a-f]:/.test(t) || /^f[cd][0-9a-f]{2}:/.test(t);
}
function isLocalOllamaBaseUrl(e) {
if (!e) return true;
const t = readOllamaHostname(e);
if (t === void 0) return false;
return LOCAL_OLLAMA_HOSTNAMES.has(t) || isLoopbackHost(t) || t.endsWith(".local") || isIpv4PrivateRange(t) || isIpv6LocalRange(t) || !t.includes(".") && !t.includes(":");
}
function isLoopbackOllamaBaseUrl(e) {
if (!e) return true;
const t = readOllamaHostname(e);
return t !== void 0 && (LOOPBACK_OLLAMA_HOSTNAMES.has(t) || isLoopbackHost(t));
}
function readOllamaHostname(e) {
const t = URL.parse(e)?.hostname.toLowerCase();
return t?.startsWith("[") && t.endsWith("]") ? t.slice(1, -1) : t;
}
function hasExplicitRemoteOllamaApiProvider(e) {
if (!e) return false;
for (const [t, n] of Object.entries(e)) {
if (t === "ollama" || !n) continue;
if (normalizeOptionalString(n.api)?.toLowerCase() !== "ollama") continue;
const e = readProviderBaseUrl(n);
if (e && !isLoopbackOllamaBaseUrl(e)) return true;
}
return false;
}
function shouldUseSyntheticOllamaAuth(e) {
const t = readOllamaStringValue(e?.apiKey);
if (coerceSecretRef(e?.apiKey) || t && !isOllamaApiKeyMarker(t) || !hasMeaningfulExplicitOllamaConfig(e)) return false;
return isLocalOllamaBaseUrl(readProviderBaseUrl(e));
}
function hasMeaningfulExplicitOllamaConfig(e) {
if (!e) return false;
if (e.models?.length) return true;
const t = readProviderBaseUrl(e);
if (t) return resolveOllamaApiBase(t) !== OLLAMA_DEFAULT_BASE_URL;
return Boolean(readOllamaStringValue(e.apiKey) || e.auth || e.authHeader !== void 0 || e.headers && Object.keys(e.headers).length > 0 || e.request || e.injectNumCtxForOpenAICompat !== void 0);
}
async function resolveOllamaDiscoveryResult(e) {
if (e.ctx.providerIds && !e.ctx.providerIds.includes("ollama")) return null;
const t = e.ctx.config.models?.providers?.ollama;
const n = Boolean(t?.models?.length);
const r = hasMeaningfulExplicitOllamaConfig(t);
const i = hasExplicitRemoteOllamaApiProvider(e.ctx.config.models?.providers);
const a = readProviderBaseUrl(t);
const o = e.pluginConfig.discovery?.enabled === false || Boolean(a && isHostedOllamaCloud(a));
if (o && !n) return null;
const s = e.ctx.resolveProviderApiKey(OLLAMA_PROVIDER_ID);
const c = s.apiKey;
const l = typeof c === "string" && c.trim().length > 0;
const u = e.ctx.env;
const d = t?.apiKey;
const resolveOllamaDiscoveryAuth = () => {
const e = normalizeOptionalString(u.OLLAMA_API_KEY);
const t = normalizeOptionalString(s.apiKey);
const n = normalizeOptionalString(s.discoveryApiKey);
const r = coerceSecretRef(d);
const i = r ? n : readOllamaStringValue(d);
if (r && !i) return null;
if (i && (r || !isOllamaApiKeyMarker(i))) return {
apiKey: r ?? i,
discoveryApiKey: i
};
if (!isLocalOllamaBaseUrl(a)) {
if (n) return {
apiKey: t,
discoveryApiKey: n
};
if (t && !isOllamaApiKeyMarker(t)) return {
apiKey: t,
discoveryApiKey: t
};
return e && e !== "ollama-local" ? {
apiKey: "OLLAMA_API_KEY",
discoveryApiKey: e
} : {};
}
if (t && t !== e && !isOllamaApiKeyMarker(t)) return {
apiKey: t,
discoveryApiKey: n ?? t
};
return { apiKey: OLLAMA_DEFAULT_API_KEY };
};
const f = resolveOllamaDiscoveryAuth();
if (!f) return null;
const { apiKey: p, discoveryApiKey: m } = f;
if (o && t) {
const e = resolveOllamaApiBase(a);
const n = t.api ?? "ollama";
return { provider: {
...t,
models: t.models ?? [],
baseUrl: resolveOllamaRuntimeBaseUrl({
api: n,
configuredBaseUrl: a,
discoveredBaseUrl: e
}),
api: n,
...p ? { apiKey: p } : {}
} };
}
if (!r && i) return null;
if (!l && !r) return null;
return await runLiveProviderCatalog({
providerId: OLLAMA_PROVIDER_ID,
profileId: s.profileId,
run: async () => {
let n;
const r = await e.buildProvider(a, {
onListedModels: (e) => {
n = e;
},
discoveryMode: "strict",
...m ? { apiKey: m } : {}
});
const i = t?.api ?? r.api;
const o = new Map(t?.models?.map((e) => [e.id, e]));
return {
...n ? { outcomes: [{
provider: OLLAMA_PROVIDER_ID,
profileId: s.profileId,
status: "ready",
modelIdCatalog: {
baseUrl: resolveOllamaApiBase(a),
modelIds: n
}
}] } : {},
provider: {
...r,
models: r.models.flatMap((e) => {
const t = o.get(e.id);
if (t) {
if (!(!t.baseUrl || resolveOllamaApiBase(t.baseUrl) === resolveOllamaApiBase(r.baseUrl))) return [];
const n = (t.api ?? i) === "ollama" && t.thinkingLevelMap === void 0 ? e.thinkingLevelMap : void 0;
return n || e.parameterCount !== void 0 ? [{
...t,
...n ? { thinkingLevelMap: n } : {},
...e.parameterCount !== void 0 ? { parameterCount: e.parameterCount } : {}
}] : [];
}
return [i !== "ollama" && e.thinkingLevelMap ? Object.assign({}, e, { thinkingLevelMap: void 0 }) : e];
}),
baseUrl: resolveOllamaRuntimeBaseUrl({
api: i,
configuredBaseUrl: a,
discoveredBaseUrl: r.baseUrl
}),
api: i,
...p ? { apiKey: p } : {}
}
};
}
});
}
//#endregion
//#region extensions/ollama/provider-discovery.ts
const ollamaProviderDiscovery = {
id: OLLAMA_PROVIDER_ID,
label: "Ollama",
docsPath: "/providers/ollama",
envVars: ["OLLAMA_API_KEY"],
auth: [],
resolveSyntheticAuth: ({ provider: e, providerConfig: t }) => {
if (!shouldUseSyntheticOllamaAuth(t)) return;
return {
apiKey: OLLAMA_DEFAULT_API_KEY,
source: `models.providers.${e ?? "ollama"} (synthetic local key)`,
mode: "api-key"
};
},
catalog: {
order: "late",
async run(e) {
return await resolveOllamaDiscoveryResult({
ctx: e,
pluginConfig: resolvePluginConfigObject(e.config, "ollama") ?? {},
buildProvider: async (...e) => capLocalOllamaProviderContext(await buildOllamaProvider(...e))
});
},
getUnlistedConfiguredModelIds: getUnlistedOllamaConfiguredModelIds
}
};
//#endregion
export { ollamaProviderDiscovery as default, ollamaProviderDiscovery };