openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
320 lines (319 loc) • 10.1 kB
JavaScript
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as normalizeSecretInput } from "./normalize-secret-input-Cxkx67Fv.mjs";
import { n as isHttpUrl } from "./url-protocol-DXxSDuQZ.mjs";
import { s as loadManifestMetadataSnapshot } from "./manifest-contract-eligibility-DoGGge-2.mjs";
import { r as fetchWithTimeout } from "./fetch-timeout-D62KciOm.mjs";
import { t as isLocalProviderBaseUrl } from "./model-provider-local-KHvcGobn.mjs";
import { r as t } from "./i18n-AiHKCZaZ.mjs";
import { t as ensureApiKeyFromEnvOrPrompt } from "./provider-auth-input-D0pfNbEZ.mjs";
import { a as buildOpenAiVerificationProbeRequest, c as normalizeOptionalProviderApiKey, d as resolveCustomModelImageInputInference, f as resolveCustomProviderApi, i as buildEndpointIdFromUrl, n as applyCustomApiConfig, o as discoverCustomApiModelIds, p as resolveCustomProviderId, r as buildAnthropicVerificationProbeRequest, s as normalizeEndpointId, u as resolveCustomModelAliasError } from "./onboard-custom-config-Dmrcrtsp.mjs";
//#region src/commands/onboard-custom.ts
const VERIFY_TIMEOUT_MS = 3e4;
const COMPATIBILITY_OPTIONS = [
{
value: "openai",
labelKey: "wizard.customProvider.compatibilityOpenAi",
hintKey: "wizard.customProvider.compatibilityOpenAiHint"
},
{
value: "openai-responses",
labelKey: "wizard.customProvider.compatibilityOpenAiResponses",
hintKey: "wizard.customProvider.compatibilityOpenAiResponsesHint"
},
{
value: "anthropic",
labelKey: "wizard.customProvider.compatibilityAnthropic",
hintKey: "wizard.customProvider.compatibilityAnthropicHint"
},
{
value: "unknown",
labelKey: "wizard.customProvider.compatibilityUnknown",
hintKey: "wizard.customProvider.compatibilityUnknownHint"
}
];
function isJsonVerificationResponse(e) {
const n = e.headers.get("content-type") ?? "";
if (!n.trim()) return true;
const r = n.split(";", 1)[0]?.trim().toLowerCase();
return r === "application/json" || r !== void 0 && r.endsWith("+json");
}
async function requestVerification(e) {
let n;
try {
n = await fetchWithTimeout(e.endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
...e.headers
},
body: JSON.stringify(e.body)
}, VERIFY_TIMEOUT_MS);
if (n.ok && !isJsonVerificationResponse(n)) return {
ok: false,
error: `Verification returned ${n.headers.get("content-type") || "missing content-type"} instead of JSON. Check the provider base URL; OpenAI-compatible endpoints usually need a /v1 path prefix.`
};
return {
ok: n.ok,
status: n.status
};
} catch (e) {
return {
ok: false,
error: e
};
} finally {
await n?.body?.cancel().catch(() => void 0);
}
}
async function promptBaseUrlAndKey(e) {
const n = (await e.prompter.text({
message: t("wizard.customProvider.apiBaseUrl"),
initialValue: e.initialBaseUrl,
placeholder: "https://api.example.com/v1",
validate: (e) => {
return isHttpUrl(e) ? void 0 : t("wizard.customProvider.validUrl");
}
})).trim();
const r = buildEndpointIdFromUrl(n) || "custom";
for (;;) {
let i;
const a = normalizeSecretInput(await ensureApiKeyFromEnvOrPrompt({
config: e.config,
provider: r,
envLabel: "CUSTOM_API_KEY",
promptMessage: t("wizard.customProvider.apiKeyPrompt"),
normalize: normalizeSecretInput,
validate: () => void 0,
prompter: e.prompter,
secretInputMode: e.secretInputMode,
setCredential: async (e) => {
i = e;
}
}));
if (a.trim()) return {
baseUrl: n,
apiKey: normalizeOptionalProviderApiKey(i),
resolvedApiKey: a,
noAuth: false
};
if (isLocalProviderBaseUrl(n)) return {
baseUrl: n,
apiKey: void 0,
resolvedApiKey: "",
noAuth: false
};
if (await e.prompter.confirm({
message: t("wizard.customProvider.noAuthConfirm"),
initialValue: true
})) return {
baseUrl: n,
resolvedApiKey: "",
noAuth: true
};
}
}
/** Prompts for a custom API provider and prepares its endpoint config without writing it. */
async function promptCustomApiConfig(e) {
const { prompter: n, runtime: r, config: i } = e;
const a = loadManifestMetadataSnapshot({
config: i,
workspaceDir: e.target?.workspaceDir,
env: process.env
}).plugins;
let { baseUrl: o, apiKey: s, resolvedApiKey: c, noAuth: l } = await promptBaseUrlAndKey({
prompter: n,
config: i,
secretInputMode: e.secretInputMode
});
const u = await n.select({
message: t("wizard.customProvider.compatibility"),
options: COMPATIBILITY_OPTIONS.filter((n) => e.verification !== "deferred" || n.value !== "unknown").map((e) => ({
value: e.value,
label: t(e.labelKey),
hint: t(e.hintKey)
}))
});
const selectModel = async () => {
if (u !== "anthropic") {
const e = await discoverCustomApiModelIds({
baseUrl: o,
apiKey: c
});
if (e.length > 0) {
const r = await n.select({
message: t("wizard.customProvider.modelId"),
options: [...e.map((e) => ({
value: e,
label: e
})), {
value: "",
label: t("wizard.customProvider.modelIdManual")
}]
});
if (r) return r;
} else await n.note(t("wizard.customProvider.modelDiscoveryUnavailable"), t("wizard.customProvider.modelId"));
}
return (await n.text({
message: t("wizard.customProvider.modelId"),
placeholder: t("wizard.customProvider.modelIdPlaceholder"),
validate: (e) => e.trim() ? void 0 : t("wizard.customProvider.modelIdRequired")
})).trim();
};
let d = await selectModel();
let f = u === "unknown" ? null : u;
const verifyCompatibility = async (e) => {
const n = {
baseUrl: o,
apiKey: c,
modelId: d,
compatibility: e
};
return await requestVerification(e === "anthropic" ? buildAnthropicVerificationProbeRequest(n) : buildOpenAiVerificationProbeRequest({
...n,
responsesApi: e === "openai-responses"
}));
};
while (e.verification !== "deferred") {
if (!f) {
const e = n.progress(t("wizard.customProvider.detectionProgress"));
const r = {
openai: "wizard.customProvider.detectedOpenAi",
"openai-responses": "wizard.customProvider.detectedOpenAiResponses",
anthropic: "wizard.customProvider.detectedAnthropic"
};
for (const n of [
"openai",
"openai-responses",
"anthropic"
]) if ((await verifyCompatibility(n)).ok) {
e.stop(t(r[n]));
f = n;
break;
}
if (f) break;
e.stop(t("wizard.customProvider.detectionFailed"));
await n.note(t("wizard.customProvider.detectionFailedNote"), t("wizard.customProvider.detectionNoteTitle"));
} else {
const e = n.progress(t("wizard.customProvider.verifying"));
const r = await verifyCompatibility(f);
if (r.ok) {
e.stop(t("wizard.customProvider.verificationSuccessful"));
break;
}
if (r.error !== void 0) e.stop(t("wizard.customProvider.verificationFailedError", { error: formatErrorMessage(r.error) }));
else e.stop(t("wizard.customProvider.verificationFailedStatus", { status: r.status }));
}
const r = await n.select({
message: t("wizard.customProvider.retryChoice"),
options: [
{
value: "baseUrl",
label: t("wizard.customProvider.changeBaseUrl")
},
{
value: "model",
label: t("wizard.customProvider.changeModel")
},
{
value: "both",
label: t("wizard.customProvider.changeBaseUrlAndModel")
}
]
});
if (r === "baseUrl" || r === "both") ({baseUrl: o, apiKey: s, resolvedApiKey: c, noAuth: l} = await promptBaseUrlAndKey({
prompter: n,
config: i,
secretInputMode: e.secretInputMode,
initialBaseUrl: o
}));
if (r === "model" || r === "both") d = await selectModel();
if (u === "unknown") f = null;
}
const p = buildEndpointIdFromUrl(o);
const m = await n.text({
message: t("wizard.customProvider.endpointId"),
initialValue: p,
placeholder: "custom",
validate: (e) => {
if (!normalizeEndpointId(e)) return t("wizard.customProvider.endpointIdRequired");
}
});
const h = await n.text({
message: t("wizard.customProvider.modelAlias"),
placeholder: t("wizard.customProvider.modelAliasPlaceholder"),
initialValue: "",
validate: (n) => {
const r = resolveCustomProviderId({
config: i,
baseUrl: o,
providerId: m
});
return resolveCustomModelAliasError({
raw: n,
cfg: i,
modelRef: {
provider: r.providerId,
model: d
},
manifestPlugins: a,
agentId: e.target?.agentId
});
}
});
const g = resolveCustomModelImageInputInference(d);
const _ = g.confidence === "known" ? g.supportsImageInput : await n.confirm({
message: t("wizard.customProvider.imageInput"),
initialValue: g.supportsImageInput
});
const v = f ?? "openai";
const { providerId: y } = resolveCustomProviderId({
config: i,
baseUrl: o,
providerId: m
});
const b = i.models?.providers?.[y]?.models.find((e) => e.id === d)?.api;
if (l && resolveCustomProviderApi({
baseUrl: o,
compatibility: v,
modelApi: b
}) !== "openai-completions") {
l = false;
let r;
c = await ensureApiKeyFromEnvOrPrompt({
config: i,
provider: buildEndpointIdFromUrl(o) || "custom",
envLabel: "CUSTOM_API_KEY",
promptMessage: t("wizard.customProvider.apiKeyPrompt"),
normalize: normalizeSecretInput,
validate: (e) => e.trim() ? void 0 : t("wizard.customProvider.noAuthCompatKeyRequired"),
prompter: n,
secretInputMode: e.secretInputMode,
setCredential: async (e) => {
r = e;
}
});
s = normalizeOptionalProviderApiKey(r);
}
const x = applyCustomApiConfig({
config: i,
baseUrl: o,
modelId: d,
compatibility: v,
apiKey: s,
...l ? { noAuth: true } : {},
providerId: m,
alias: h,
manifestPlugins: a,
supportsImageInput: _,
...e.target ? { target: e.target } : {},
...e.setAsPrimary === false ? { setAsPrimary: false } : {}
});
if (x.providerIdRenamedFrom) await n.note(t("wizard.customProvider.endpointIdRenamed", {
from: x.providerIdRenamedFrom,
to: x.providerId
}), t("wizard.customProvider.endpointIdTitle"));
r.log(`Prepared custom provider: ${x.providerId}/${x.modelId}`);
return x;
}
//#endregion
export { promptCustomApiConfig as t };