openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
368 lines (367 loc) • 13.3 kB
JavaScript
import { l as normalizeOptionalString, p as normalizeStringifiedOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { _ as readResponseTextLimited } from "./provider-http-errors-Dtgw3x-5.mjs";
import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./ssrf-runtime-B6q6NM4E.mjs";
import "./text-utility-runtime-Ds8jsG0J.mjs";
import "./error-runtime-BM740gJj.mjs";
import { t as expectDefined } from "./expect-runtime-DT3P17Ul.mjs";
import "./provider-http-LcawLneq.mjs";
import { _ as requiresFoundryEntraIdClaudeAuth, a as FOUNDRY_ANTHROPIC_SCOPE, d as extractFoundryEndpoint, i as DEFAULT_GPT5_API, r as DEFAULT_API, t as ANTHROPIC_MESSAGES_API, u as buildFoundryProviderBaseUrl, v as requiresFoundryMandatoryAdaptiveClaudeThinking, w as usesFoundryResponsesByDefault, y as requiresFoundryMaxCompletionTokens } from "./shared-DiLOhEpP.mjs";
import { a as getLoggedInAccount, n as execAz, r as getAccessTokenResult, t as azLoginDeviceCodeWithOptions } from "./cli-BYOdN2ZS.mjs";
//#region extensions/microsoft-foundry/onboard.ts
const FOUNDRY_CONNECTION_TEST_ERROR_BODY_LIMIT_BYTES = 8192;
function listFoundryResources(e) {
try {
const t = JSON.parse(execAz([
"cognitiveservices",
"account",
"list",
...e ? ["--subscription", e] : [],
"--query",
"[].{id:id,name:name,kind:kind,location:location,resourceGroup:resourceGroup,endpoint:properties.endpoint,customSubdomain:properties.customSubDomainName,projects:properties.associatedProjects}",
"--output",
"json"
]));
const n = [];
for (const e of t) {
if (!e.resourceGroup) continue;
if (e.kind !== "OpenAI" && e.kind !== "AIServices") continue;
const t = e.kind === "AIServices" ? normalizeOptionalString(e.customSubdomain) : void 0;
const r = e.kind === "OpenAI" ? extractFoundryEndpoint(e.endpoint) : t ? `https://${t}.services.ai.azure.com` : void 0;
if (!r) continue;
n.push({
id: e.id,
accountName: e.name,
kind: e.kind,
location: e.location,
resourceGroup: e.resourceGroup,
endpoint: r,
projects: e.kind === "AIServices" && Array.isArray(e.projects) ? e.projects.filter((e) => typeof e === "string") : []
});
}
return n;
} catch {
return [];
}
}
function listResourceDeployments(e, t) {
try {
return JSON.parse(execAz([
"cognitiveservices",
"account",
"deployment",
"list",
...t ? ["--subscription", t] : [],
"-g",
e.resourceGroup,
"-n",
e.accountName,
"--query",
"[].{name:name,modelName:properties.model.name,modelVersion:properties.model.version,state:properties.provisioningState,sku:sku.name}",
"--output",
"json"
])).filter((e) => e.state === "Succeeded");
} catch {
return [];
}
}
function buildCreateFoundryHint(e) {
return [
`No Azure AI Foundry or Azure OpenAI resources were found in subscription ${e.name} (${e.id}).`,
"Create one in Azure AI Foundry or Azure Portal, then rerun onboard.",
"Azure AI Foundry: https://ai.azure.com",
"Azure OpenAI docs: https://learn.microsoft.com/azure/ai-foundry/openai/how-to/create-resource"
].join("\n");
}
async function selectFoundryResource(e, t) {
const n = listFoundryResources(t.id);
if (n.length === 0) throw new Error(buildCreateFoundryHint(t));
if (n.length === 1) {
const t = expectDefined(n[0], "single Microsoft Foundry resource");
await e.prompter.note(`Using ${t.kind === "AIServices" ? "Azure AI Foundry" : "Azure OpenAI"} resource: ${t.accountName}`, "Foundry Resource");
return t;
}
const r = await e.prompter.select({
message: "Select Azure AI Foundry / Azure OpenAI resource",
options: n.map((e) => ({
value: e.id,
label: `${e.accountName} (${e.kind === "AIServices" ? "Azure AI Foundry" : "Azure OpenAI"}${e.location ? `, ${e.location}` : ""})`,
hint: [`RG: ${e.resourceGroup}`, e.projects.length > 0 ? `${e.projects.length} project(s)` : void 0].filter(Boolean).join(" | ")
}))
});
return n.find((e) => e.id === r) ?? expectDefined(n[0], "fallback Microsoft Foundry resource");
}
async function selectFoundryDeployment(e, t, n) {
if (n.length === 0) throw new Error([`No model deployments were found in ${t.accountName}.`, "Deploy a model in Microsoft Foundry or Azure OpenAI, then rerun onboard."].join("\n"));
if (n.length === 1) {
const t = expectDefined(n[0], "single Microsoft Foundry deployment");
await e.prompter.note(`Using deployment: ${t.name}`, "Model Deployment");
return {
selected: t,
supported: n
};
}
const r = await e.prompter.select({
message: "Select model deployment",
options: n.map((e) => ({
value: e.name,
label: e.name,
hint: [
e.modelName,
e.modelVersion,
e.sku
].filter(Boolean).join(" | ")
}))
});
return {
selected: n.find((e) => e.name === r) ?? expectDefined(n[0], "fallback Microsoft Foundry deployment"),
supported: n
};
}
async function promptEndpointAndModelManually(e, t) {
const n = (await e.prompter.text({
message: "Microsoft Foundry endpoint URL",
placeholder: "https://xxx.services.ai.azure.com or https://xxx.openai.azure.com",
...t?.endpointInitialValue ? { initialValue: t.endpointInitialValue } : {},
validate: (e) => {
const t = normalizeStringifiedOptionalString(e) ?? "";
if (!t) return "Endpoint URL is required";
return URL.canParse(t) ? void 0 : "Invalid URL";
}
})).trim();
const r = (await e.prompter.text({
message: "Default model/deployment name",
...t?.modelInitialValue ? { initialValue: t.modelInitialValue } : {},
placeholder: "claude-fable-5",
validate: (e) => {
if (!(normalizeStringifiedOptionalString(e) ?? "")) return "Model ID is required";
}
})).trim();
const i = t?.modelFamilyInitialValue ?? "claude";
const a = await e.prompter.select({
message: "Model family",
options: [
{
value: "claude",
label: "Claude",
hint: "Use for Anthropic Claude deployments"
},
{
value: "reasoning-family",
label: "GPT-5 series / o-series / Codex",
hint: "Use for Azure OpenAI reasoning and Codex deployments"
},
{
value: "mai-image",
label: "MAI image model",
hint: "Use for Microsoft MAI image deployments"
},
{
value: "other-chat",
label: "Other chat model",
hint: "Use for other chat/completions style Foundry models"
}
],
initialValue: i
});
if (a === "mai-image") return {
endpoint: n,
modelId: r,
modelNameHint: await e.prompter.select({
message: "MAI image base model",
options: [
{
value: "MAI-Image-2.5-Flash",
label: "MAI-Image-2.5-Flash",
hint: "Latest fast MAI image deployment"
},
{
value: "MAI-Image-2.5",
label: "MAI-Image-2.5",
hint: "Latest MAI image deployment"
},
{
value: "MAI-Image-2e",
label: "MAI-Image-2e",
hint: "Efficient MAI image deployment"
},
{
value: "MAI-Image-2",
label: "MAI-Image-2",
hint: "MAI image deployment"
}
],
initialValue: "MAI-Image-2.5-Flash"
}),
api: DEFAULT_API
};
if (a === "claude") {
const i = t?.allowEntraOnlyClaudeModels ?? true;
return {
endpoint: n,
modelId: r,
modelNameHint: (await e.prompter.text({
message: "Claude base model",
initialValue: "claude-fable-5",
placeholder: "claude-fable-5",
validate: (e) => {
const t = normalizeStringifiedOptionalString(e) ?? "";
if (!t) return "Claude base model is required";
if (!t.toLowerCase().startsWith("claude-")) return "Use a Claude model name such as claude-fable-5";
if (!i && requiresFoundryEntraIdClaudeAuth(t)) return "Claude Mythos deployments require Microsoft Entra ID auth; choose Entra ID auth or use a Claude model that supports API-key auth.";
}
})).trim(),
api: ANTHROPIC_MESSAGES_API
};
}
const o = a === "reasoning-family" ? usesFoundryResponsesByDefault(r) || requiresFoundryMaxCompletionTokens(r) ? r : "gpt-5" : void 0;
const s = await e.prompter.select({
message: "Select request API",
options: [
{
value: ANTHROPIC_MESSAGES_API,
label: "Anthropic Messages API",
hint: "Use for Claude deployments through Microsoft Foundry /anthropic"
},
{
value: DEFAULT_GPT5_API,
label: "Responses API",
hint: "Recommended for Azure OpenAI GPT, o-series, and Codex deployments"
},
{
value: "openai-completions",
label: "Chat Completions API",
hint: "Use for Foundry models that only expose chat/completions semantics"
}
],
initialValue: a === "reasoning-family" ? DEFAULT_GPT5_API : DEFAULT_API
});
return {
endpoint: n,
modelId: r,
...o ? { modelNameHint: o } : {},
api: s
};
}
async function promptApiKeyEndpointAndModel(e) {
return promptEndpointAndModelManually(e, {
endpointInitialValue: process.env.AZURE_OPENAI_ENDPOINT,
modelInitialValue: "gpt-4o",
modelFamilyInitialValue: "other-chat",
allowEntraOnlyClaudeModels: false
});
}
function extractTenantSuggestions(e) {
const t = [];
const n = /* @__PURE__ */ new Set();
for (const r of e.matchAll(/([0-9a-fA-F-]{36})(?:\s+'([^'\r\n]+)')?/g)) {
const e = normalizeOptionalString(r[1]);
if (!e || n.has(e)) continue;
n.add(e);
const i = normalizeOptionalString(r[2]);
t.push({
id: e,
...i ? { label: i } : {}
});
}
return t;
}
function isValidTenantIdentifier(e) {
const t = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(e);
const n = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/.test(e);
return t || n;
}
async function promptTenantId(e, t) {
const n = t.suggestions && t.suggestions.length > 0 ? t.suggestions.map((e) => `- ${e.id}${e.label ? ` (${e.label})` : ""}`) : [];
await e.prompter.note([t.reason, ...n.length > 0 ? ["Suggested tenants:", ...n] : []].join("\n"), "Azure Tenant");
return (await e.prompter.text({
message: "Azure tenant ID",
placeholder: t.suggestions?.[0]?.id ?? "00000000-0000-0000-0000-000000000000",
validate: (e) => {
const t = normalizeStringifiedOptionalString(e) ?? "";
if (!t) return "Tenant ID is required";
return isValidTenantIdentifier(t) ? void 0 : "Enter a valid tenant ID or tenant domain";
}
})).trim() || void 0;
}
async function loginWithTenantFallback(e) {
try {
await azLoginDeviceCodeWithOptions({});
return { account: getLoggedInAccount() };
} catch (t) {
const n = formatErrorMessage(t);
if (!(/AADSTS\d+/i.test(n) || /no subscriptions found/i.test(n) || /Please provide a valid tenant/i.test(n) || /tenant.*not found/i.test(n))) throw t;
const r = await promptTenantId(e, {
suggestions: extractTenantSuggestions(n),
reason: "Azure login needs a tenant-scoped retry. This often happens when your tenant requires MFA or your account has no Azure subscriptions."
});
await azLoginDeviceCodeWithOptions({
tenantId: r,
allowNoSubscriptions: true
});
return {
account: getLoggedInAccount(),
tenantId: r
};
}
}
async function testFoundryConnection(e) {
try {
const { accessToken: t } = getAccessTokenResult({
scope: e.api === "anthropic-messages" ? FOUNDRY_ANTHROPIC_SCOPE : void 0,
subscriptionId: e.subscriptionId,
tenantId: e.tenantId
});
const n = buildFoundryProviderBaseUrl(e.endpoint, e.modelId, e.modelNameHint, e.api);
let r;
let i;
if (e.api === "openai-responses") {
r = `${n}/responses`;
i = {
model: e.modelId,
input: "hi",
max_output_tokens: 16
};
} else {
const t = e.api === ANTHROPIC_MESSAGES_API;
r = `${n}/${t ? "v1/messages" : "chat/completions"}`;
i = {
model: e.modelId,
messages: [{
role: "user",
content: "hi"
}],
max_tokens: 1,
...t && requiresFoundryMandatoryAdaptiveClaudeThinking(e.modelNameHint ?? e.modelId) ? { thinking: { type: "adaptive" } } : {}
};
}
const { response: a, release: o } = await fetchWithSsrFGuard({
url: r,
init: {
method: "POST",
headers: {
Authorization: `Bearer ${t}`,
"Content-Type": "application/json",
...e.api === "anthropic-messages" ? { "anthropic-version": "2023-06-01" } : {}
},
body: JSON.stringify(i)
},
timeoutMs: 15e3
});
try {
if (!a.ok) {
const t = await readResponseTextLimited(a, FOUNDRY_CONNECTION_TEST_ERROR_BODY_LIMIT_BYTES).catch(() => "");
await e.ctx.prompter.note(a.status === 400 ? `Endpoint is reachable but returned 400 Bad Request - check your deployment name and API version.\n${truncateUtf16Safe(t, 200)}` : `Warning: test request returned ${a.status}. ${truncateUtf16Safe(t, 200)}\nProceeding anyway - you can fix the endpoint later.`, "Connection Test");
} else await e.ctx.prompter.note("Connection test successful!", "✓");
} finally {
await o();
}
} catch (t) {
await e.ctx.prompter.note(`Warning: connection test failed: ${String(t)}\nProceeding anyway.`, "Connection Test");
}
}
//#endregion
export { promptTenantId as a, testFoundryConnection as c, promptEndpointAndModelManually as i, loginWithTenantFallback as n, selectFoundryDeployment as o, promptApiKeyEndpointAndModel as r, selectFoundryResource as s, listResourceDeployments as t };