openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
300 lines (299 loc) • 10.8 kB
JavaScript
import { t as normalizeOptionalSecretInput } from "../../normalize-secret-input-Cxkx67Fv.mjs";
import { n as buildApiKeyCredential } from "../../provider-auth-helpers-ByDXB7Po.mjs";
import { t as discoverOpenAICompatibleLocalModels } from "../../provider-self-hosted-discovery-CuVyZrfM.mjs";
import { n as configureOpenAICompatibleSelfHostedProviderNonInteractive } from "../../provider-setup-C508VQAW.mjs";
import { l as selectPreferredLocalModelId } from "../../provider-model-shared-Dg70R9-2.mjs";
import "../../provider-auth-D_oAZ3fr.mjs";
import { t as ensureApiKeyFromEnvOrPrompt } from "../../provider-auth-input-D0pfNbEZ.mjs";
import { _ as runLiveProviderCatalog, g as LiveModelCatalogHttpError, v as buildOpenAICompatibleLiveModels } from "../../provider-catalog-live-runtime-D-M7f_ww.mjs";
import { i as OMLX_PROVIDER_ID, n as OMLX_DEFAULT_BASE_URL, r as OMLX_LOCAL_API_KEY, t as OMLX_API_KEY_ENV_VAR } from "../../defaults-CsYyfrvv.mjs";
import { n as resolveOmlxSecret, r as withoutOmlxAuthentication, t as resolveOmlxHeaders } from "../../connection-Bci0rob8.mjs";
//#region extensions/omlx/setup.ts
function automaticModels(e) {
return e.provider.models.filter((t) => e.rows.some((e) => e.model.id === t.id && typeof e.model.max_model_len === "number" && Number.isSafeInteger(e.model.max_model_len) && e.model.max_model_len >= 16384));
}
function headerPatch(e, t) {
return e ? {
...Object.fromEntries(Object.keys(e).map((e) => [e, void 0])),
...t
} : t;
}
function setupResult(e, t, n) {
const { provider: r } = e;
const i = n.models?.providers?.omlx;
const a = i?.baseUrl.trim().replace(/\/+$/, "") === r.baseUrl ? i : void 0;
return {
profiles: [],
defaultModel: `${OMLX_PROVIDER_ID}/${t}`,
configPatch: { models: { providers: { [OMLX_PROVIDER_ID]: {
...r,
auth: r.auth,
authHeader: r.authHeader,
headers: headerPatch(a?.headers, r.headers),
request: r.request ? {
...r.request,
auth: r.request.auth,
headers: headerPatch(a?.request?.headers, r.request.headers),
proxy: r.request.proxy,
tls: r.request.tls
} : void 0
} } } }
};
}
async function detectOmlxAvailability(e) {
return await listOmlxModels(e) !== null;
}
async function detectOmlx(e) {
const t = await listOmlxModels(e);
const n = t && selectPreferredLocalModelId(automaticModels(t).map((e) => e.id));
return n ? {
modelRef: `${OMLX_PROVIDER_ID}/${n}`,
detail: n
} : null;
}
async function prepareOmlx(e) {
const t = await listOmlxModels(e);
const n = t && automaticModels(t).find((t) => `${"omlx"}/${t.id}` === e.modelRef);
return t && n ? setupResult(t, n.id, e.config) : null;
}
const unavailableMessage = "No oMLX chat models were found. Start oMLX, add a chat model, and check the base URL and API key before running setup again.";
async function configureOmlxInteractive(e) {
const t = await e.prompter.text({
message: "oMLX base URL",
initialValue: e.config.models?.providers?.omlx?.baseUrl,
placeholder: OMLX_DEFAULT_BASE_URL,
validate: (e) => {
if (!e.trim()) return;
try {
const t = new URL(e);
return ["http:", "https:"].includes(t.protocol) ? void 0 : "Use an HTTP or HTTPS URL";
} catch {
return "Enter the oMLX OpenAI-compatible base URL, including /v1";
}
}
});
let n = "";
let r;
const i = await ensureApiKeyFromEnvOrPrompt({
config: e.config,
env: e.env,
workspaceDir: e.workspaceDir,
provider: OMLX_PROVIDER_ID,
envLabel: OMLX_API_KEY_ENV_VAR,
promptMessage: "oMLX API key (leave blank if authentication is disabled)",
normalize: (e) => e.trim(),
validate: () => void 0,
prompter: e.prompter,
secretInputMode: e.secretInputMode ?? (e.allowSecretRefPrompt === false ? "plaintext" : void 0),
setCredential: async (e, t) => {
n = e;
r = t;
}
});
const a = await listOmlxModels({
...e,
env: e.env ?? process.env,
baseUrl: t.trim() || void 0,
apiKey: i,
replaceAuth: true
});
if (!a?.provider.models.length) throw new Error(unavailableMessage);
const o = await e.prompter.select({
message: "oMLX chat model",
initialValue: selectPreferredLocalModelId(a.provider.models.map((e) => e.id)),
options: a.provider.models.map((e) => ({
value: e.id,
label: e.name
}))
});
e.signal?.throwIfAborted();
const s = i ? buildApiKeyCredential(OMLX_PROVIDER_ID, n, void 0, { secretInputMode: r }) : void 0;
a.provider.apiKey = s?.keyRef ?? (i ? "omlx:default" : "omlx-local");
a.provider.auth = s?.keyRef ? "api-key" : a.provider.auth;
const c = setupResult(a, o, e.config);
if (s) c.profiles = [{
profileId: "omlx:default",
credential: s
}];
return c;
}
async function prepareNonInteractive(e) {
const t = normalizeOptionalSecretInput(e.opts.customModelId);
const n = normalizeOptionalSecretInput(e.opts.customBaseUrl);
const r = normalizeOptionalSecretInput(e.opts.customApiKey);
const i = e.opts.customApiKey !== void 0;
const a = e.config.models?.providers?.omlx;
const o = !n || n.replace(/\/+$/, "") === (a?.baseUrl ?? "http://127.0.0.1:8000/v1").trim().replace(/\/+$/, "");
const s = a?.request?.auth;
const c = o && (a?.apiKey !== void 0 || s !== void 0 && s.mode !== "provider-default" || [a?.headers, a?.request?.headers].some((e) => Object.entries(e ?? {}).some(([e, t]) => e.trim().toLowerCase() === "authorization" && Boolean(typeof t === "string" ? t.trim() : t))));
if (!t) {
e.runtime.error("oMLX setup requires --custom-model-id. List model IDs at the server's /v1/models endpoint.");
return null;
}
const l = !i && c || i && !r ? null : await e.resolveApiKey({
provider: OMLX_PROVIDER_ID,
flagValue: r,
flagName: "--custom-api-key",
envVar: OMLX_API_KEY_ENV_VAR,
allowProfile: o,
required: false
});
const u = await listOmlxModels({
config: e.config,
env: process.env,
agentDir: e.agentDir,
baseUrl: n,
apiKey: l?.key ?? (i ? "" : void 0),
replaceAuth: i
});
if (!u?.provider.models.some((e) => e.id === t)) {
e.runtime.error(`${unavailableMessage} Requested model: ${t}.`);
return null;
}
return {
listing: u,
modelId: t,
resolved: l
};
}
async function validateOmlxNonInteractive(e) {
return await prepareNonInteractive(e) !== null;
}
async function configureOmlxNonInteractive(e) {
const t = await prepareNonInteractive(e);
if (!t) {
e.runtime.exit(1);
return null;
}
const { listing: n, modelId: r, resolved: i } = t;
let a;
const o = await configureOpenAICompatibleSelfHostedProviderNonInteractive({
ctx: {
...e,
opts: {
...e.opts,
customApiKey: i?.key ?? "omlx-local"
},
resolveApiKey: async () => i ?? {
key: "omlx-local",
source: "flag"
},
toApiKeyCredential: (t) => {
a = e.toApiKeyCredential(t);
return a;
}
},
providerId: OMLX_PROVIDER_ID,
providerLabel: "oMLX",
defaultBaseUrl: n.provider.baseUrl,
defaultApiKeyEnvVar: OMLX_API_KEY_ENV_VAR,
modelPlaceholder: r
});
if (!o?.models?.providers?.omlx) return null;
o.models.providers.omlx = {
...n.provider,
auth: a?.keyRef ? "api-key" : n.provider.auth,
apiKey: a?.keyRef ?? (i ? i.key === "omlx-local" ? "omlx-local" : i.source === "profile" ? n.provider.apiKey : "omlx:default" : n.provider.apiKey)
};
return o;
}
async function listOmlxModels(e) {
e.signal?.throwIfAborted();
const t = e.config.models?.providers?.[OMLX_PROVIDER_ID];
const n = (e.baseUrl ?? t?.baseUrl ?? "http://127.0.0.1:8000/v1").trim().replace(/\/+$/, "");
let r = (t?.baseUrl ?? "http://127.0.0.1:8000/v1").trim().replace(/\/+$/, "") === n ? t : void 0;
if (e.replaceAuth && r) r = withoutOmlxAuthentication(r);
const i = r?.request ?? (t?.request?.allowPrivateNetwork !== void 0 ? { allowPrivateNetwork: t.request.allowPrivateNetwork } : void 0);
try {
const { headers: t, hasHeaderAuth: a } = await resolveOmlxHeaders(e, r);
const o = e.apiKey === void 0 && !a ? await resolveOmlxSecret(e, r?.apiKey, "models.providers.omlx.apiKey") : void 0;
const s = o && o !== "omlx-local" && typeof r?.apiKey === "string" && (o !== "OMLX_API_KEY" || !e.env["OMLX_API_KEY"]) ? (await (await import("../../plugin-sdk/provider-auth-runtime.js")).resolveApiKeyForProvider({
provider: OMLX_PROVIDER_ID,
cfg: {
...e.config,
models: {
...e.config.models,
providers: {
...e.config.models?.providers,
[OMLX_PROVIDER_ID]: {
...r,
baseUrl: n,
auth: "api-key",
models: r?.models ?? []
}
}
}
},
agentDir: e.agentDir,
allowAuthProfileFallback: o === OMLX_API_KEY_ENV_VAR
})).apiKey : void 0;
const c = e.apiKey ?? s ?? (o === "OMLX_API_KEY" ? e.env["OMLX_API_KEY"] : o) ?? e.env["OMLX_API_KEY"];
const l = await discoverOpenAICompatibleLocalModels({
baseUrl: n,
apiKey: a || c === "omlx-local" ? void 0 : c,
headers: t,
allowPrivateNetwork: i?.allowPrivateNetwork,
label: "oMLX",
discoverRuntimeContext: false,
rawResult: true,
signal: e.signal
});
e.signal?.throwIfAborted();
if (l.kind !== "success") {
if (e.strict) throw l.kind === "http-error" ? new LiveModelCatalogHttpError(OMLX_PROVIDER_ID, l.status) : /* @__PURE__ */ new Error("oMLX model discovery unavailable. Check the server URL and API key.");
return null;
}
const u = {
...r,
baseUrl: n,
api: "openai-completions",
apiKey: r?.apiKey ?? (c ? "OMLX_API_KEY" : "omlx-local"),
...i ? { request: i } : {},
models: r?.models ?? []
};
u.models = buildOpenAICompatibleLiveModels(l.rows.map(({ model: e }) => e), u);
return {
provider: u,
rows: l.rows
};
} catch (t) {
e.signal?.throwIfAborted();
if (e.strict) throw t;
return null;
}
}
async function discoverOmlxProvider(e) {
if (e.providerIds && !e.providerIds.includes("omlx")) return null;
if (!e.providerIds && !e.config.models?.providers?.omlx && !e.env["OMLX_API_KEY"]) return null;
const t = e.config.models?.providers?.omlx?.apiKey;
const n = t === void 0 ? e.resolveProviderApiKey(OMLX_PROVIDER_ID) : void 0;
const r = await runLiveProviderCatalog({
providerId: OMLX_PROVIDER_ID,
run: async () => {
const r = await listOmlxModels({
...e,
apiKey: n?.discoveryApiKey,
strict: true
});
if (!r) throw new Error("oMLX model discovery unavailable");
return {
provider: {
...r.provider,
apiKey: t ?? n?.apiKey ?? r.provider.apiKey
},
outcomes: [{
provider: OMLX_PROVIDER_ID,
status: "ready",
modelIdCatalog: {
baseUrl: r.provider.baseUrl,
modelIds: r.rows.flatMap(({ model: e }) => typeof e.id === "string" ? [e.id] : [])
}
}]
};
}
});
e.signal?.throwIfAborted();
return r;
}
//#endregion
export { configureOmlxInteractive, configureOmlxNonInteractive, detectOmlx, detectOmlxAvailability, discoverOmlxProvider, prepareOmlx, validateOmlxNonInteractive };