UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

153 lines (152 loc) • 5.28 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { n as formatErrorMessageWithCode } from "./errors-BKzCeTYb.mjs"; import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { n as buildTimeoutAbortSignal } from "./fetch-timeout-D62KciOm.mjs"; import { p as resolvePinnedHostnameWithPolicy } from "./ssrf-DHBNJw0c.mjs"; import { c as shouldUseEnvHttpProxyForUrl } from "./proxy-env-CZP0dXDG.mjs"; import { i as isManagedProxyActive } from "./fetch-guard-BLMw2n18.mjs"; import { t as isLocalProviderBaseUrl } from "./model-provider-local-KHvcGobn.mjs"; import net from "node:net"; import { once } from "node:events"; //#region src/cron/isolated-agent/model-preflight.runtime.ts /** Preflights local model-provider endpoints before scheduled cron runner startup. */ const PREFLIGHT_CACHE_TTL_MS = 3e5; const PREFLIGHT_TIMEOUT_MS = 2500; const MAX_PREFLIGHT_ERROR_CAUSE_DEPTH = 8; const MAX_PREFLIGHT_ERROR_CHARS = 1e3; const preflightCache = /* @__PURE__ */ new Map(); function resolveProviderConfig(e, t) { const n = e.models?.providers; if (!n) return; const r = n[t]; if (r) return r; const i = normalizeProviderId(t); return Object.entries(n).find(([e]) => normalizeProviderId(e) === i)?.[1]; } function normalizeProbeApi(e) { const t = normalizeLowercaseStringOrEmpty(e.api); return t === "ollama" || t === "openai-completions" ? t : void 0; } function readErrorProperty(e, t) { if (typeof e !== "object" && typeof e !== "function" || e === null) return; try { return e[t]; } catch { return; } } function collectPreflightErrorCauseChain(e) { const t = []; const n = /* @__PURE__ */ new Set(); let r = e; while (r !== void 0 && r !== null && t.length < MAX_PREFLIGHT_ERROR_CAUSE_DEPTH && !n.has(r)) { n.add(r); t.push(r); r = readErrorProperty(r, "cause"); } return t; } function isPreflightTimeout(e) { return collectPreflightErrorCauseChain(e).some((e) => readErrorProperty(e, "name") === "TimeoutError"); } function formatPreflightError(e) { const t = formatErrorMessageWithCode(e); const n = isPreflightTimeout(e) ? `Local provider preflight exceeded its configured ${PREFLIGHT_TIMEOUT_MS}ms deadline | ${t}` : t; return n.length <= MAX_PREFLIGHT_ERROR_CHARS ? n : `${truncateUtf16Safe(n, 999)}…`; } function buildUnavailableResult(e) { return { status: "unavailable", provider: e.provider, model: e.model, baseUrl: e.baseUrl, retryAfterMs: PREFLIGHT_CACHE_TTL_MS, reason: [ `This automation uses ${e.provider}/${e.model} but the local provider preflight failed at ${e.baseUrl}.`, `Start the local provider or correct its configured endpoint; OpenClaw will retry its provider preflight on a later scheduled run.`, `Last error: ${formatPreflightError(e.error)}` ].join(" ") }; } async function probeLocalProviderEndpoint(e) { const t = new URL(e); if (t.protocol !== "http:" && t.protocol !== "https:") throw new Error(`Unsupported local provider protocol: ${t.protocol}`); const { signal: n, cleanup: r } = buildTimeoutAbortSignal({ timeoutMs: PREFLIGHT_TIMEOUT_MS, operation: "cron-model-provider-preflight", url: e }); try { const e = await resolvePinnedHostnameWithPolicy(t.hostname, { policy: { hostnameAllowlist: [t.hostname], allowPrivateNetwork: true }, signal: n }); const r = net.connect({ host: e.hostname, port: Number(t.port || (t.protocol === "https:" ? 443 : 80)), lookup: e.lookup }); const i = new Promise((e) => { r.once("close", () => e()); }); try { await once(r, "connect", { signal: n }); } finally { r.destroy(); await i; } } finally { r(); } } /** Checks local model-provider reachability before a scheduled cron run starts. */ async function preflightCronModelProvider(e) { const t = resolveProviderConfig(e.cfg, e.provider); if (!t) return { status: "available" }; const n = normalizeOptionalString(t.baseUrl)?.replace(/\/+$/, ""); const r = normalizeProbeApi(t); if (!n || !r || !isLocalProviderBaseUrl(n) || isManagedProxyActive() && shouldUseEnvHttpProxyForUrl(n)) return { status: "available" }; const i = e.nowMs ?? Date.now(); const a = `${r}\0${n}`; const o = preflightCache.get(a); if (o && i - o.checkedAtMs < PREFLIGHT_CACHE_TTL_MS) { if (o.result.status === "available") return { status: "available" }; return buildUnavailableResult({ provider: e.provider, model: e.model, baseUrl: n, error: o.result.error }); } let s; try { await probeLocalProviderEndpoint(n); s = { status: "available" }; } catch (e) { s = { status: "unavailable", error: e }; } if (s.status === "available" || !isPreflightTimeout(s.error)) preflightCache.set(a, { checkedAtMs: i, result: s }); if (s.status === "available") return { status: "available" }; return buildUnavailableResult({ provider: e.provider, model: e.model, baseUrl: n, error: s.error }); } /** Clears the local-provider preflight cache for deterministic tests. */ function resetCronModelProviderPreflightCacheForTest() { preflightCache.clear(); } //#endregion export { preflightCronModelProvider, resetCronModelProviderPreflightCacheForTest };