openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
436 lines (435 loc) • 16.9 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { c as isSecretRef } from "./ref-contract-b8L-9DrQ.mjs";
import "./types.secrets-BmNLLnHp.mjs";
import { a as normalizeConfiguredProviderCatalogModelId } from "./model-ref-shared-DqE2RqZv.mjs";
import { t as normalizeOptionalSecretInput } from "./normalize-secret-input-Cxkx67Fv.mjs";
import { r as normalizeAgentModelRefForConfig } from "./model-input-DrM4DWHG.mjs";
import { i as DEFAULT_PROVIDER, o as resolveDefaultModelMaxTokens } from "./defaults-BWyoTPqn.mjs";
import { n as isHttpUrl } from "./url-protocol-DXxSDuQZ.mjs";
import { i as buildModelAliasIndex } from "./model-selection-shared-9Kz63Hhm.mjs";
import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs";
import "./model-selection-C2A4Wyix.mjs";
import { t as materializeSecretInput } from "./resolve-secret-input-string-DjfC9izQ.mjs";
import { t as applyPrimaryModel } from "./provider-model-primary-C2E-I43s.mjs";
import { t as applyAgentModelDefaults } from "./onboard-agent-target-D7VNwjZB.mjs";
import { t as CONTEXT_WINDOW_HARD_MIN_TOKENS } from "./context-window-guard-DvS3S4qo.mjs";
import { t as normalizeAlias } from "./alias-name-o9aqLBJk.mjs";
//#region src/commands/onboard-custom-config.ts
/**
* Wizard default for non-Azure custom APIs when context length is unknown.
* Mirrors the generic persisted custom-model catalog fallback and leaves enough
* room above the default compaction reserve floor in `agent-settings.ts`.
*/
const CUSTOM_PROVIDER_DEFAULT_CONTEXT_WINDOW_TOKENS = 128e3;
const AZURE_DEFAULT_CONTEXT_WINDOW = 4e5;
const AZURE_DEFAULT_MAX_TOKENS = 16384;
function normalizeContextWindowForCustomModel(e) {
const t = typeof e === "number" && Number.isFinite(e) ? Math.floor(e) : 0;
return t > 4e3 ? t : CUSTOM_PROVIDER_DEFAULT_CONTEXT_WINDOW_TOKENS;
}
function customModelInputs(e) {
return e ? ["text", "image"] : ["text"];
}
function resolveCustomModelImageInputInference(e) {
const t = normalizeLowercaseStringOrEmpty(e);
if (!t) return {
supportsImageInput: false,
confidence: "unknown"
};
const n = /\b(?:gpt-4o|gpt-4\.1|gpt-[5-9]|o[134])\b/.test(t) || /\bclaude-(?:3|4|sonnet|opus|haiku)\b/.test(t) || /\bgemini\b/.test(t) || /\b(?:qwen[\w.-]*-?vl|qwen-vl)\b/.test(t) || /\b(?:vision|llava|pixtral|internvl|mllama|minicpm-v|glm-4v)\b/.test(t) || /(?:^|[-_/])vl(?:[-_/]|$)/.test(t);
return {
supportsImageInput: n,
confidence: n || /\b(?:llama\d*|deepseek|mistral|mixtral|kimi|moonshot|codestral|devstral|phi|qwq|codellama)\b/.test(t) || /\bqwen(?!.*(?:vl|vision))/.test(t) ? "known" : "unknown"
};
}
function isAzureUrl(e, t = false) {
try {
const n = new URL(e).hostname.toLowerCase();
return n.endsWith(".openai.azure.com") || !t && n.endsWith(".services.ai.azure.com");
} catch {
return false;
}
}
function transformAzureUrl(e, t) {
const n = e.endsWith("/") ? e.slice(0, -1) : e;
if (n.includes("/openai/deployments/")) return n;
return `${n}/openai/deployments/${t}`;
}
function transformAzureConfigUrl(e) {
const t = e.endsWith("/") ? e.slice(0, -1) : e;
if (t.endsWith("/openai/v1")) return t;
const n = t.indexOf("/openai/deployments/");
return `${n !== -1 ? t.slice(0, n) : t}/openai/v1`;
}
function hasSameHost(e, t) {
try {
return normalizeLowercaseStringOrEmpty(new URL(e).hostname) === normalizeLowercaseStringOrEmpty(new URL(t).hostname);
} catch {
return false;
}
}
function resolveCustomProviderApi(e) {
return e.modelApi ?? (isAzureUrl(e.baseUrl, true) ? "azure-openai-responses" : e.compatibility === "anthropic" ? "anthropic-messages" : e.compatibility === "openai-responses" ? "openai-responses" : "openai-completions");
}
/** Error class used by callers to turn custom API validation failures into CLI UX. */
var CustomApiError = class extends Error {
constructor(e, t) {
super(t);
this.name = "CustomApiError";
this.code = e;
}
};
function normalizeEndpointId(e) {
return normalizeLowercaseStringOrEmpty(e).replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
}
/** Builds a stable custom provider id from an endpoint URL host and port. */
function buildEndpointIdFromUrl(e) {
try {
const t = new URL(e);
return normalizeEndpointId(`custom-${normalizeLowercaseStringOrEmpty(t.hostname.replace(/[^a-z0-9]+/gi, "-"))}${t.port ? `-${t.port}` : ""}`) || "custom";
} catch {
return "custom";
}
}
function configuredAliasModelKey(e, t) {
return modelKey(e.provider, normalizeConfiguredProviderCatalogModelId(e.provider, e.model, { manifestPlugins: t }));
}
function resolveCustomModelAliasError(e) {
const t = e.raw.trim();
if (!t) return;
let n;
try {
n = normalizeAlias(t);
} catch (e) {
return e instanceof Error ? e.message : "Alias is invalid.";
}
const r = buildModelAliasIndex({
cfg: e.cfg,
defaultProvider: DEFAULT_PROVIDER,
agentId: e.agentId,
manifestPlugins: e.manifestPlugins,
allowPluginNormalization: false
});
const i = normalizeLowercaseStringOrEmpty(n);
const a = r.byAlias.get(i);
if (!a) return;
const o = modelKey(a.ref.provider, a.ref.model);
if (configuredAliasModelKey(a.ref, e.manifestPlugins) === configuredAliasModelKey(e.modelRef, e.manifestPlugins)) return;
return `Alias ${n} already points to ${o}.`;
}
/** Normalizes optional provider API key input while preserving secret refs. */
function normalizeOptionalProviderApiKey(e) {
if (isSecretRef(e)) return e;
return normalizeOptionalSecretInput(e);
}
function resolveVerificationEndpoint(e) {
const t = isAzureUrl(e.baseUrl) ? transformAzureUrl(e.baseUrl, e.modelId) : e.baseUrl;
const n = new URL(e.endpointPath, t.endsWith("/") ? t : `${t}/`);
if (isAzureUrl(e.baseUrl)) n.searchParams.set("api-version", "2024-10-21");
return n.href;
}
/** Builds a minimal OpenAI-family request used only to verify custom endpoints. */
function buildOpenAiVerificationProbeRequest(e) {
const t = isAzureUrl(e.baseUrl);
const n = e.apiKey ? t ? { "api-key": e.apiKey } : { Authorization: `Bearer ${e.apiKey}` } : {};
const r = isAzureUrl(e.baseUrl, true) || e.responsesApi === true;
return {
endpoint: r ? new URL("responses", (t ? transformAzureConfigUrl(e.baseUrl) : e.baseUrl).replace(/\/?$/, "/")).href : resolveVerificationEndpoint({
baseUrl: e.baseUrl,
modelId: e.modelId,
endpointPath: "chat/completions"
}),
headers: n,
body: {
model: e.modelId,
...r ? {
input: "Hi",
max_output_tokens: 16
} : {
messages: [{
role: "user",
content: "Hi"
}],
max_tokens: 16
},
stream: false
}
};
}
/** Builds a minimal Anthropic-compatible request used only to verify endpoints. */
function buildAnthropicVerificationProbeRequest(e) {
return {
endpoint: resolveVerificationEndpoint({
baseUrl: /\/v1\/?$/.test(e.baseUrl.trim()) ? e.baseUrl.trim() : e.baseUrl.trim().replace(/\/?$/, "") + "/v1",
modelId: e.modelId,
endpointPath: "messages"
}),
headers: {
"anthropic-version": "2023-06-01",
...e.apiKey ? { "x-api-key": e.apiKey } : {}
},
body: {
model: e.modelId,
max_tokens: 1,
messages: [{
role: "user",
content: "Hi"
}],
stream: false
}
};
}
function isCustomApiCompatibility(e) {
return e === "openai" || e === "openai-responses" || e === "anthropic";
}
function parseCustomApiCompatibility(e) {
const t = normalizeOptionalLowercaseString(e);
if (!t) return "openai";
if (!isCustomApiCompatibility(t)) throw new CustomApiError("invalid_compatibility", "Invalid --custom-compatibility (use \"openai\", \"openai-responses\", or \"anthropic\").");
return t;
}
function assertValidCustomProviderId(e) {
if (e && !normalizeEndpointId(e)) throw new CustomApiError("invalid_provider_id", "Custom provider ID must include letters, numbers, or hyphens.");
}
function resolveCustomProviderId(e) {
const t = e.config.models?.providers ?? {};
const n = e.baseUrl.trim();
const r = e.providerId?.trim();
assertValidCustomProviderId(r);
const i = normalizeEndpointId(r || buildEndpointIdFromUrl(n)) || "custom";
const a = t[i];
if (!a?.baseUrl || a.baseUrl === n || isAzureUrl(n) && hasSameHost(a.baseUrl, n)) return { providerId: i };
let o = 2;
while (t[`${i}-${o}`]) o += 1;
return {
providerId: `${i}-${o}`,
providerIdRenamedFrom: i
};
}
/** Preserve a matching provider's anonymous policy unless a new key replaces it. */
function resolveCustomProviderNoAuth(e) {
return e.noAuth === true || !e.apiKey && e.config.models?.providers?.[e.providerId]?.auth === "none";
}
/** Discovers custom endpoint ids without changing the runtime model catalog. */
async function discoverCustomApiModelIds(e) {
try {
const { discoverOpenAICompatibleLocalModels: t } = await import("./provider-self-hosted-discovery-l1Z9Eh2h.mjs");
const n = isAzureUrl(e.baseUrl);
const r = await t({
baseUrl: n ? transformAzureConfigUrl(e.baseUrl) : e.baseUrl,
apiKey: n ? void 0 : e.apiKey,
headers: n ? {
...buildOpenAiVerificationProbeRequest({
baseUrl: e.baseUrl,
apiKey: e.apiKey ?? "",
modelId: ""
}).headers,
...e.headers
} : e.headers,
label: "custom provider",
rawResult: true,
discoverRuntimeContext: false
});
return r.kind === "success" ? [...new Set(r.rows.flatMap(({ model: e }) => {
const t = normalizeOptionalString(e.id);
return t ? [t] : [];
}))] : [];
} catch {
return [];
}
}
async function resolveNonInteractiveCustomApiModelIds(e) {
let t = e.modelId ? [e.modelId] : e.modelIds;
if (!t) {
const { providerId: n } = resolveCustomProviderId(e);
const r = resolveCustomProviderNoAuth({
...e,
providerId: n
});
let i = r ? void 0 : e.config.models?.providers?.[n]?.apiKey;
const credentialError = () => new CustomApiError("missing_required", "Could not resolve the configured custom provider credential. Check its secret reference or profile, or pass --custom-api-key or --custom-model-id explicitly.");
if (!e.apiKey && typeof i === "string") {
const [{ loadAuthProfileStoreWithoutExternalProfilesAsync: t }, { resolveProviderEntryApiKeyBinding: r, resolveUsableCustomProviderApiKey: a }] = await Promise.all([import("./store-runtime-pgVSsSj7.mjs"), import("./model-auth-provider-config-CHp6_0-g.mjs")]);
const o = await r({
cfg: e.config,
provider: n,
store: await t(e.agentDir),
agentDir: e.agentDir
});
if (o.kind === "profile-resolved") i = o.auth.apiKey;
else if (o.kind === "profile-incompatible" || o.kind === "profile-unresolved") throw credentialError();
else i = a({
cfg: e.config,
provider: n
})?.apiKey ?? i;
}
const a = r ? void 0 : e.apiKey ?? await materializeSecretInput({
config: e.config,
value: i,
env: process.env,
onResolveRefError: () => {
throw credentialError();
}
});
t = await discoverCustomApiModelIds({
...e,
apiKey: a
});
}
if (!t.length) throw new CustomApiError("missing_required", "No models could be discovered from the custom provider. Check the base URL and credentials, or pass --custom-model-id explicitly.");
return t;
}
function parseNonInteractiveCustomApiFlags(e) {
const t = normalizeOptionalString(e.baseUrl) ?? "";
const n = normalizeOptionalString(e.modelId) ?? "";
const r = parseCustomApiCompatibility(e.compatibility);
if (!t || r === "anthropic" && !n) throw new CustomApiError("missing_required", !t ? "Auth choice \"custom-api-key\" requires --custom-base-url." : "Anthropic-compatible custom providers require --custom-model-id.");
const i = normalizeOptionalString(e.apiKey);
const a = normalizeOptionalString(e.providerId);
assertValidCustomProviderId(a);
if (e.noAuth && i) throw new CustomApiError("no_auth_conflict", "Custom provider flags conflict: --custom-no-auth cannot be combined with --custom-api-key. Omit one.");
return {
baseUrl: t,
modelId: n,
compatibility: r,
...i ? { apiKey: i } : {},
...e.noAuth ? { noAuth: true } : {},
...a ? { providerId: a } : {},
...e.supportsImageInput === void 0 ? {} : { supportsImageInput: e.supportsImageInput }
};
}
/** Applies custom provider config and optionally makes its model the primary model. */
function applyCustomApiConfig(e) {
const t = normalizeOptionalString(e.baseUrl) ?? "";
if (!isHttpUrl(t)) throw new CustomApiError("invalid_base_url", "Custom provider base URL must be a valid HTTP or HTTPS URL.");
const n = normalizeOptionalString(e.modelId) ?? "";
if (!n) throw new CustomApiError("invalid_model_id", "Custom provider model ID is required.");
const r = isAzureUrl(t);
const i = resolveCustomProviderApi(e);
const a = r ? transformAzureConfigUrl(t) : t;
const o = resolveCustomProviderId({
config: e.config,
baseUrl: a,
providerId: e.providerId
});
const s = o.providerId;
const c = e.config.models?.providers ?? {};
const l = modelKey(s, n);
const u = normalizeOptionalString(e.alias) ?? "";
const d = resolveCustomModelAliasError({
raw: u,
cfg: e.config,
modelRef: {
provider: s,
model: n
},
manifestPlugins: e.manifestPlugins ?? [],
agentId: e.target?.agentId
});
if (d) throw new CustomApiError("invalid_alias", d);
const f = c[s];
const p = Array.isArray(f?.models) ? f.models : [];
const m = e.modelIds ?? [n];
const h = new Map(p.map((e, t) => [e.id, t]));
const g = [...p];
const _ = /* @__PURE__ */ new Set();
const v = /* @__PURE__ */ new Set();
const y = e.supportsImageInput === void 0 ? void 0 : customModelInputs(e.supportsImageInput);
for (const t of m.toReversed()) {
const n = h.get(t);
const a = n === void 0 ? void 0 : g[n];
v.add(a?.api ?? i);
const o = r && /\b(o[134]|gpt-([5-9]|\d{2,}))\b/i.test(t);
if (o) _.add(t);
const s = {
id: t,
name: `${t} (Custom Provider)`,
contextWindow: r ? AZURE_DEFAULT_CONTEXT_WINDOW : CUSTOM_PROVIDER_DEFAULT_CONTEXT_WINDOW_TOKENS,
maxTokens: r ? AZURE_DEFAULT_MAX_TOKENS : resolveDefaultModelMaxTokens(CUSTOM_PROVIDER_DEFAULT_CONTEXT_WINDOW_TOKENS),
input: y ?? customModelInputs(r ? o : resolveCustomModelImageInputInference(t).supportsImageInput),
cost: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0
},
reasoning: o,
...r ? { compat: { supportsStore: false } } : {}
};
if (a && n !== void 0) g[n] = {
...a,
...r && !e.preserveExistingModelMetadata ? s : {},
...y ? { input: y } : {},
name: a.name ?? s.name,
cost: a.cost ?? s.cost,
contextWindow: normalizeContextWindowForCustomModel(a.contextWindow),
maxTokens: a.maxTokens ?? s.maxTokens
};
else {
h.set(t, g.length);
g.push(s);
}
}
const { apiKey: b, auth: x, ...S } = f ?? {};
const C = e.noAuth === true || e.apiKey !== void 0;
const w = e.noAuth ? "none" : C ? void 0 : x;
if (w === "none" && [...v].some((e) => e !== "openai-completions")) throw new CustomApiError("no_auth_unsupported", "auth: \"none\" requires the openai-completions adapter. Select that adapter or configure an API key.");
const T = e.noAuth ? void 0 : normalizeOptionalProviderApiKey(e.apiKey) ?? normalizeOptionalProviderApiKey(b);
const E = r && T ? { "api-key": T } : void 0;
const D = {
...e.config,
models: {
...e.config.models,
mode: e.config.models?.mode ?? "merge",
providers: {
...c,
[s]: {
...S,
baseUrl: a,
api: i,
...T ? { apiKey: T } : {},
...w ? { auth: w } : {},
...r ? { authHeader: false } : {},
...E ? { headers: E } : {},
models: g
}
}
}
};
const applyModelDefaults = (t) => {
const r = e.setAsPrimary === false ? t : applyPrimaryModel(t, l);
if (!e.modelIds && !_.has(n) && !u) return r;
const i = { ...r.agents?.defaults?.models };
for (const e of m) {
const t = normalizeAgentModelRefForConfig(modelKey(s, e));
const r = i[t];
const a = _.has(e) && !r?.params?.thinking;
i[t] = {
...r,
...a ? { params: {
...r?.params,
thinking: "medium"
} } : {},
...u && e === n ? { alias: u } : {}
};
}
return {
...r,
agents: {
...r.agents,
defaults: {
...r.agents?.defaults,
models: i
}
}
};
};
return {
config: e.target && e.config.agents?.ownership === "explicit" ? applyAgentModelDefaults(D, e.target, applyModelDefaults) : applyModelDefaults(D),
providerId: s,
modelId: n,
...o.providerIdRenamedFrom ? { providerIdRenamedFrom: o.providerIdRenamedFrom } : {}
};
}
//#endregion
export { buildOpenAiVerificationProbeRequest as a, normalizeOptionalProviderApiKey as c, resolveCustomModelImageInputInference as d, resolveCustomProviderApi as f, resolveNonInteractiveCustomApiModelIds as h, buildEndpointIdFromUrl as i, parseNonInteractiveCustomApiFlags as l, resolveCustomProviderNoAuth as m, applyCustomApiConfig as n, discoverCustomApiModelIds as o, resolveCustomProviderId as p, buildAnthropicVerificationProbeRequest as r, normalizeEndpointId as s, CustomApiError as t, resolveCustomModelAliasError as u };