openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,050 lines (1,049 loc) • 43.6 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { t as appendConfigPathSegment } from "./dot-path-BJ4tyWKJ.mjs";
import { f as normalizeResolvedSecretInputString } from "./types.secrets-BmNLLnHp.mjs";
import { n as findNormalizedProviderValue, r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { i as parseModelCatalogRef, t as buildModelCatalogMergeKey } from "./model-catalog-refs-Bk2MNoCv.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds, n as listAgentEntries } from "./agent-roster-t1ooUdXp.mjs";
import "./agent-scope-config-DmXgFGKP.mjs";
import { i as readBundledDiscoveryModeMemoized } from "./bundled-discovery-state-Bb0zCvZZ.mjs";
import { t as isPluginEnabledByDefaultForPlatform } from "./default-enablement-DLXVIwwO.mjs";
import { t as normalizePluginPolicyId } from "./plugin-policy-id-CkilMowp.mjs";
import { p as resolveEffectivePluginActivationState, y as resolveSelectedContextEnginePluginIdFromConfig } from "./config-state-B1JlHgba.mjs";
import { i as listModelRefsFromConfigValue, r as collectConfiguredModelRefs } from "./configured-model-refs-DtaDJ1Vw.mjs";
import { t as splitTrailingAuthProfile } from "./model-ref-profile-C7DWqVP0.mjs";
import { n as listPotentialConfiguredChannelIds, t as listExplicitlyDisabledChannelIdsForConfig } from "./config-presence-G9kglnWa.mjs";
import "./plugin-instance-scope-oezVdCr2.mjs";
import { u as listExplicitConfiguredChannelIdsForConfig } from "./channel-presence-policy-6XNqNGJr.mjs";
import { t as collectPluginConfigContractMatches } from "./config-contract-matches-BYS12x_-.mjs";
import { f as isLoopbackIpAddress } from "./ip-BUyyYvdK.mjs";
import { v as requireActivePluginRegistry } from "./runtime-ezCEpumg.mjs";
import { o as resolveConfiguredTalkRealtimeProviderId } from "./talk-CqEDzucG.mjs";
import { t as CORE_BUILT_IN_MODEL_APIS } from "./provider-config-owner-DM1kSvAm.mjs";
import { t as planEffectiveModelCatalogRows } from "./model-catalog-BoLMQ4cy.mjs";
import "./http-body-B9w7rzPz.mjs";
import { i as readResponseWithLimit, n as readResponseTextPrefix } from "./http-response-body-B-i_0116.mjs";
import { h as readProviderJsonResponse, s as createProviderHttpError$1 } from "./provider-http-errors-Dtgw3x-5.mjs";
import { a as redactProviderResponseErrorText } from "./provider-request-header-redaction-Ckk_UIqk.mjs";
import "./provider-request-config-CCij-nof.mjs";
import { n as normalizeHostname } from "./hostname-DQVb2xzD.mjs";
import { h as ssrfPolicyFromHttpBaseUrlAllowedHostname } from "./ssrf-DHBNJw0c.mjs";
import { c as shouldUseEnvHttpProxyForUrl } from "./proxy-env-CZP0dXDG.mjs";
import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs";
import { n as fetchWithRuntimeDispatcher } from "./runtime-fetch-CQQovyS7.mjs";
import { S as resolveMemoryDreamingPluginId, b as resolveMemoryDreamingConfig, s as DEFAULT_MEMORY_DREAMING_PLUGIN_ID, x as resolveMemoryDreamingPluginConfig } from "./dreaming-C72ZWZJr.mjs";
import { n as OPENAI_COMPATIBLE_MODEL_APIS, r as resolveConfiguredGenericEmbeddingProviderId, t as OPENAI_COMPATIBLE_EMBEDDING_PROVIDER_ID } from "./embedding-provider-config-CQrHlBC1.mjs";
import "./provider-network-policy-v5F8YIjz.mjs";
import { t as MEMORY_SEARCH_DEADLINE_CONTROL } from "./search-deadline-control-D-IPgGBJ.mjs";
import { t as attachLocalServiceDiagnostics } from "./provider-local-service-diagnostics-CEOvjZgR.mjs";
import "./config-contracts-mh9qgi0B.mjs";
import { n as isConfigActivationValueEnabled, r as sortUniquePluginIds, t as collectConfiguredSpeechProviderIds } from "./gateway-startup-speech-providers-BTIWPL7P.mjs";
//#region packages/memory-host-sdk/src/host/azure-api-version-request.ts
/** Detect Azure OpenAI-compatible embedding hosts. */
function isAzureOpenAICompatibleHost(e) {
return e.endsWith(".openai.azure.com") || e.endsWith(".services.ai.azure.com") || e.endsWith(".cognitiveservices.azure.com");
}
function resolveAzureApiVersionRequestTarget(e) {
const { url: t, headers: n } = e;
let r;
try {
r = new URL(t);
} catch {
return e;
}
if (!isAzureOpenAICompatibleHost(r.hostname)) return e;
const i = Object.keys(n).find((e) => e.toLowerCase() === "api-version");
if (!i) return e;
const a = n[i]?.trim();
const o = { ...n };
delete o[i];
if (!a) return {
url: t,
headers: o
};
const s = r.searchParams.get("api-version");
if (s === null || s.trim() === "") r.searchParams.set("api-version", a);
return {
url: r.toString(),
headers: o
};
}
//#endregion
//#region packages/memory-host-sdk/src/host/embeddings-debug.ts
const debugEmbeddings = [
"true",
"1",
"on",
"yes"
].includes(normalizeLowercaseStringOrEmpty(process.env.OPENCLAW_DEBUG_MEMORY_EMBEDDINGS));
/** Write embedding debug metadata when OPENCLAW_DEBUG_MEMORY_EMBEDDINGS is enabled. */
function debugEmbeddingsLog(e, t) {
if (!debugEmbeddings) return;
const n = t ? ` ${JSON.stringify(t)}` : "";
console.warn(`${e}${n}`);
}
/** Only numeric HTTP metadata belongs in embedding shape diagnostics. */
function embeddingResponseLogMeta(e) {
const t = Number(e.headers.get("content-length") ?? NaN);
return {
status: e.status,
responseBytes: Number.isSafeInteger(t) && t >= 0 ? t : void 0
};
}
/** Enrich owned response errors without changing the text used by retry policy. */
function addEmbeddingErrorContext(e, t, n) {
if (!(e instanceof Error) || !e.message.startsWith(t) || e.message.startsWith(n)) return e;
return Object.assign(e, {
embeddingErrorMessage: e.message,
message: `${n}${e.message.slice(t.length)}`
});
}
//#endregion
//#region packages/memory-host-sdk/src/host/embedding-vectors.ts
/** Validate provider embeddings and restore their original request order. */
function readEmbeddingVectors(e, t, n) {
const invalid = (e) => Object.assign(/* @__PURE__ */ new Error(`${n}: ${e}`), { code: "INVALID_EMBEDDING_RESPONSE" });
const r = Array.isArray(e) ? asOptionalRecord(e[0]) : void 0;
debugEmbeddingsLog("memory embeddings: remote response shape", {
context: n,
vectorCount: Array.isArray(e) ? e.length : void 0,
firstVectorDimensions: Array.isArray(r?.embedding) ? r.embedding.length : void 0,
firstIndexType: typeof r?.index
});
if (!Array.isArray(e)) throw invalid("missing data array");
if (t !== void 0 && e.length !== t) throw invalid(e.length === 0 ? `empty data array; expected ${t} vectors` : `expected ${t} vectors, got ${e.length}`);
const i = [];
let a;
for (let t = 0; t < e.length; t += 1) {
const n = asOptionalRecord(e[t]);
const r = n?.embedding;
const o = n?.index !== void 0;
if (!Array.isArray(r)) throw invalid(`missing embedding array at position ${t}`);
if (r.length === 0) throw invalid(`empty embedding at position ${t}`);
if (a !== void 0 && a !== o) throw invalid(`missing index at position ${o ? 0 : t} (mixed indexed and positional entries)`);
for (const [e, n] of r.entries()) if (typeof n !== "number" || !Number.isFinite(n)) throw invalid(`${typeof n === "number" ? "non-finite" : "non-numeric"} coordinate at position ${t}, coordinate ${e}`);
a = o;
const s = o ? n?.index : t;
if (typeof s !== "number" || !Number.isInteger(s) || s < 0 || s >= e.length) throw invalid(`invalid index at position ${t}; expected an integer in [0, ${e.length - 1}]`);
if (i[s] !== void 0) throw invalid(`duplicate index ${s} at position ${t}`);
i[s] = r;
}
return i;
}
/** Replace invalid coordinates and L2-normalize non-empty vectors. */
function sanitizeAndNormalizeEmbedding(e) {
const t = e.map((e) => Number.isFinite(e) ? e : 0);
const n = Math.sqrt(t.reduce((e, t) => e + t * t, 0));
if (n < 1e-10) return t;
return t.map((e) => e / n);
}
//#endregion
//#region packages/memory-host-sdk/src/host/openclaw-runtime-network.ts
const createProviderHttpError = async (...e) => {
return (await import("./provider-http-errors-0mSI_vmj.mjs")).createProviderHttpError(...e);
};
//#endregion
//#region packages/memory-host-sdk/src/host/remote-http.ts
/** Proxy mode used only for URLs that the runtime classified as env-proxy safe. */
const MEMORY_REMOTE_TRUSTED_ENV_PROXY_MODE = "trusted_env_proxy";
/** Build an SSRF allow policy from a configured remote base URL. */
const buildRemoteBaseUrlPolicy = ssrfPolicyFromHttpBaseUrlAllowedHostname;
/** Execute a remote HTTP request under SSRF guard and always release the response handle. */
async function withRemoteHttpResponse(e) {
const t = e.fetchWithSsrFGuardImpl ?? fetchWithSsrFGuard;
const n = e.shouldUseEnvHttpProxyForUrlImpl ?? shouldUseEnvHttpProxyForUrl;
const request = async (r) => {
e.signal?.throwIfAborted();
let i = e.init;
if (e.resolveRequestHeaders) {
const t = await e.resolveRequestHeaders({
forceRefresh: r,
signal: e.signal
});
e.signal?.throwIfAborted();
const n = new Headers(i?.headers);
for (const [e, r] of Object.entries(t)) n.set(e, r);
i = {
...i,
headers: n
};
}
const { response: a, release: o, finalUrl: s } = await t({
url: e.url,
fetchImpl: e.fetchImpl,
init: i,
signal: e.signal,
policy: e.ssrfPolicy,
auditContext: e.auditContext ?? "memory-remote",
...n(e.url) ? { mode: MEMORY_REMOTE_TRUSTED_ENV_PROXY_MODE } : {}
});
try {
return await e.onResponse(a, i?.headers);
} catch (t) {
if (!e.resolveRequestHeaders || r || a.status !== 401 || new URL(s).origin !== new URL(e.url).origin || asOptionalRecord(t)?.code !== "token_expired") throw t;
} finally {
await o();
}
return await request(true);
};
return await request(false);
}
//#endregion
//#region packages/memory-host-sdk/src/host/response-snippet.ts
const DEFAULT_ERROR_BODY_MAX_BYTES = 8192;
const DEFAULT_ERROR_BODY_MAX_CHARS = 1e3;
const DEFAULT_JSON_BODY_MAX_BYTES = 67108864;
const TRUNCATED_SUFFIX = "... [truncated]";
/** Read a small collapsed text snippet from a response body. */
async function readMemoryHostResponseTextSnippet(e, t = {}) {
const n = t.maxBytes ?? DEFAULT_ERROR_BODY_MAX_BYTES;
const r = t.maxChars ?? DEFAULT_ERROR_BODY_MAX_CHARS;
if (!e.body || typeof e.body.getReader !== "function") return "";
const i = await readResponseTextPrefix(e, n, { signal: t.signal }).catch((e) => {
throw t.signal?.aborted ? toAbortError(t.signal, "Response snippet body read aborted") : e;
});
const a = i.text.replace(/\s+/g, " ").trim();
if (!a) return "";
if (i.truncated || a.length > r) return `${truncateUtf16Safe(a, r)}${TRUNCATED_SUFFIX}`;
return a;
}
/** Read and parse JSON while enforcing a hard byte limit. */
async function readResponseJsonWithLimit(e, t) {
const n = t.maxBytes ?? DEFAULT_JSON_BODY_MAX_BYTES;
const r = parseContentLength(e.headers.get("content-length"), t.errorPrefix);
if (typeof r === "number" && r > n) {
cancelResponseBody(e);
throw responseTooLarge(t.errorPrefix, r, n);
}
const i = e.body && typeof e.body.getReader === "function" ? await readResponseWithLimit(e, n, {
signal: t.signal,
onOverflow: ({ size: e }) => responseTooLarge(t.errorPrefix, e, n)
}).catch((e) => {
throw t.signal?.aborted ? toAbortError(t.signal, `${t.errorPrefix}: response body read aborted`) : e;
}) : /* @__PURE__ */ new Uint8Array();
const a = new TextDecoder("utf-8", { fatal: true }).decode(i);
try {
return JSON.parse(a);
} catch (e) {
throw new Error(`${t.errorPrefix}: malformed JSON response`, { cause: e });
}
}
function toAbortError(e, t) {
return e.reason instanceof Error ? e.reason : new Error(t);
}
function cancelResponseBody(e) {
const t = e.body;
if (!t || typeof t.cancel !== "function") return;
t.cancel().catch(() => void 0);
}
function parseContentLength(e, t) {
const n = e?.trim();
if (!n) return;
const r = Number(n);
if (!/^\d+$/.test(n) || !Number.isSafeInteger(r)) throw new Error(`${t}: invalid content-length header: ${e}`);
return r;
}
function responseTooLarge(e, t, n) {
return /* @__PURE__ */ new Error(`${e}: response body too large: ${t} bytes (limit: ${n} bytes)`);
}
//#endregion
//#region packages/memory-host-sdk/src/host/post-json.ts
/** POST JSON, parse bounded response JSON, and preserve provider error metadata. */
async function postJson(e) {
return await withRemoteHttpResponse({
url: e.url,
ssrfPolicy: e.ssrfPolicy,
fetchImpl: e.fetchImpl,
resolveRequestHeaders: e.resolveRequestHeaders,
signal: e.signal,
init: {
method: "POST",
headers: e.headers,
body: JSON.stringify(e.body)
},
onResponse: async (t, n) => {
e.onResponse?.(t);
try {
if (!t.ok) throw await createProviderHttpError(t, e.errorPrefix, {
requestHeaders: n,
signal: e.signal,
maxBodyBytes: 8192
});
const r = await readResponseJsonWithLimit(t, {
errorPrefix: e.errorPrefix,
maxBytes: e.maxResponseBytes,
signal: e.signal
});
return await e.parse(r);
} catch (t) {
if (e.signal?.aborted) throw t;
throw e.mapResponseError ? e.mapResponseError(t) : t;
}
}
});
}
//#endregion
//#region packages/memory-host-sdk/src/host/embeddings-remote-fetch.ts
function extractEmbeddingUsage(e) {
const t = asOptionalRecord(asOptionalRecord(e)?.usage);
const n = normalizeUsageCount(t?.prompt_tokens);
const r = normalizeUsageCount(t?.total_tokens);
if (n === void 0 && r === void 0) return;
return {
promptTokens: n ?? r ?? 0,
totalTokens: r ?? n ?? 0
};
}
function normalizeUsageCount(e) {
return typeof e === "number" && Number.isSafeInteger(e) && e >= 0 ? e : void 0;
}
/** POST an embedding request and return validated vectors in request order. */
async function fetchRemoteEmbeddingVectors(e) {
const t = asOptionalRecord(e.body);
const n = Array.isArray(t?.input) ? t.input.length : void 0;
const r = typeof t?.model === "string" ? t.model : "unknown";
const i = `${e.errorPrefix} (model: ${r}, batch size: ${n ?? "unknown"})`;
const a = {
context: i,
inputCount: n
};
debugEmbeddingsLog("memory embeddings: remote request", a);
const o = resolveAzureApiVersionRequestTarget(e);
return await postJson({
...e,
...o,
mapResponseError: (t) => addEmbeddingErrorContext(t, e.errorPrefix, i),
onResponse: (e) => {
debugEmbeddingsLog("memory embeddings: remote response", {
...a,
...embeddingResponseLogMeta(e)
});
},
parse: (t) => {
const r = asOptionalRecord(t)?.data;
const a = readEmbeddingVectors(r, n, i);
e.onUsage?.(extractEmbeddingUsage(t));
return a;
}
});
}
//#endregion
//#region src/plugins/openai-compatible-embedding-provider.ts
const EMBEDDING_ERROR_BODY_MAX_BYTES = 8192;
const EMBEDDING_ERROR_BODY_MAX_CHARS = 1e3;
const EMBEDDING_ERROR_TRUNCATED_SUFFIX = "... [truncated]";
function normalizeBaseUrl(e) {
const t = e?.trim();
if (!t) throw new Error("openai-compatible embeddings: missing remote.baseUrl. Set it to your OpenAI-compatible embeddings server, for example http://127.0.0.1:11434/v1.");
return t.replace(/\/+$/u, "");
}
function normalizeModel(e, t) {
const n = e?.trim();
if (!n) throw new Error("openai-compatible embeddings: missing model. Set it to the embedding model id your server expects.");
const r = new Set([
t?.trim(),
normalizeProviderId(t ?? ""),
OPENAI_COMPATIBLE_EMBEDDING_PROVIDER_ID
].filter((e) => Boolean(e)).map((e) => `${e}/`));
for (const e of r) if (n.startsWith(e)) return n.slice(e.length);
return n;
}
function normalizeDimensions(e) {
if (!Number.isInteger(e) || e <= 0) throw new Error("openai-compatible embeddings: dimensions must be a positive integer.");
return e;
}
function assertRequestedDimensions(e, t, n) {
if (t === void 0) return;
const r = e.findIndex((e) => e.length !== t);
if (r === -1) return;
const i = e[r]?.length;
throw Object.assign(/* @__PURE__ */ new Error(`${n}: expected ${t} dimensions, got ${i} at index ${r}; the endpoint did not honor the requested dimensions. Remove memory.search.outputDimensionality or request dimensions, or use a server that supports them.`), {
code: "INVALID_EMBEDDING_RESPONSE",
expectedDimensions: t,
actualDimensions: i
});
}
function resolveRequestInputType(e, t) {
if (t === "query") return e.queryInputType ?? e.inputType;
if (t === "document") return e.documentInputType ?? e.inputType;
return e.inputType;
}
function buildHeaders(e) {
const t = {
accept: "application/json",
"content-type": "application/json"
};
for (const [n, r] of [["models.providers.*.headers", e.provider], ["memory.search.remote.headers", e.remote]]) for (const [e, i] of Object.entries(r ?? {})) {
const r = e.trim().toLowerCase();
if (!r) continue;
const a = normalizeResolvedSecretInputString({
value: i,
path: `${n}.${r}`
});
if (a) t[r] = a;
}
if (e.apiKey && !t.authorization) t.authorization = `Bearer ${e.apiKey}`;
return t;
}
function isSensitiveHeaderName(e) {
return e === "authorization" || e === "proxy-authorization" || e.includes("api-key") || e.includes("token") || e.includes("secret");
}
function sanitizeCacheHeaders(e, t) {
const n = Object.fromEntries(Object.entries(e).filter(([e]) => e !== t && !isSensitiveHeaderName(e)));
return Object.keys(n).length > 0 ? n : void 0;
}
async function resolveConfiguredProviderApiKey(e) {
if (e.configuredProvider?.localService) {
const { resolveManagedLocalProviderAuth: t } = await import("./model-auth-runtime-PpP9DPQ7.mjs");
const n = t({
cfg: e.options.config,
provider: e.providerId
});
if (n) return n.apiKey;
}
const t = normalizeResolvedSecretInputString({
value: e.configuredProvider?.apiKey,
path: `${appendConfigPathSegment("models.providers", e.providerId)}.apiKey`
});
if (!t) return;
const { resolveAgentDir: n, tryResolveAmbientOwnerAgentId: r } = await import("./agent-scope-config-B1XZecUN.mjs");
const i = r(e.options.config);
const a = e.options.agentDir?.trim() || (i ? n(e.options.config, i) : void 0);
if (!a) return t;
const { resolveScopedAuthProfileStoreAsync: o, resolveProviderEntryApiKeyAuth: s } = await import("./model-auth-provider-CvRdofyx.mjs");
const c = {
provider: e.providerId,
modelApi: e.configuredProvider?.api,
cfg: e.options.config,
agentDir: a
};
const l = await o(c);
const u = await s({
...c,
store: l
});
return u ? u.apiKey : t;
}
function isOpenAICompatibleProviderConfig(e, t) {
return normalizeProviderId(e) === "openai-compatible" || OPENAI_COMPATIBLE_MODEL_APIS.has(normalizeProviderId(t.api ?? "")) || !t.api && typeof t.baseUrl === "string" && t.baseUrl.trim().length > 0;
}
function resolveConfiguredProvider(e) {
const t = e.config.models?.providers;
if (!t) return;
const n = e.provider?.trim() || "openai-compatible";
const r = normalizeProviderId(n);
const i = t[n];
if (i && isOpenAICompatibleProviderConfig(n, i)) return {
providerId: n,
config: i
};
const a = Object.entries(t).find(([e]) => normalizeProviderId(e) === r);
if (!a) return;
const [o, s] = a;
return isOpenAICompatibleProviderConfig(o, s) ? {
providerId: o,
config: s
} : void 0;
}
function isLoopbackBaseUrl(e) {
const t = normalizeHostname(URL.parse(e)?.hostname ?? "");
return t === "localhost" || isLoopbackIpAddress(t);
}
function embeddingInputToText(e) {
if (typeof e === "string") return e;
if (!e.parts || e.parts.length === 0) return e.text;
const t = [];
for (const n of e.parts) {
if (n.type !== "text") throw new Error("openai-compatible embeddings only support text embedding inputs.");
t.push(n.text);
}
return t.join("");
}
async function createEmbeddingHttpError(e, t, n) {
const r = e.body && !e.bodyUsed ? await readResponseTextPrefix(e, EMBEDDING_ERROR_BODY_MAX_BYTES).catch(() => void 0) : void 0;
const i = r?.text ? redactProviderResponseErrorText(r.text, t, { sourceTruncated: r.truncated }) : void 0;
const a = await createProviderHttpError$1(new Response(i, {
status: e.status,
statusText: e.statusText,
headers: e.headers
}), n, { requestHeaders: t });
let o = i;
if (o && o.length > EMBEDDING_ERROR_BODY_MAX_CHARS) o = `${truncateUtf16Safe(o, EMBEDDING_ERROR_BODY_MAX_CHARS)}${EMBEDDING_ERROR_TRUNCATED_SUFFIX}`;
else if (o && r?.truncated) o = `${o}${EMBEDDING_ERROR_TRUNCATED_SUFFIX}`;
a.message = `${n}: HTTP ${e.status}${o ? `: ${o}` : ""}`;
return a;
}
const fetchWithCallerDeadline = (e, t) => fetchWithRuntimeDispatcher(e, {
...t,
dispatcher: t?.dispatcher?.compose((e) => (t, n) => e({
...t,
headersTimeout: 0,
bodyTimeout: 0
}, n))
});
async function postEmbeddingRequest(e) {
const { client: t, input: n, callOptions: r } = e;
const i = r?.[MEMORY_SEARCH_DEADLINE_CONTROL];
const a = "openai-compatible embeddings failed";
const o = `${t.providerId} embeddings failed (model: ${t.model}, batch size: ${n.length})`;
const s = resolveRequestInputType(t, r?.inputType);
const c = {
model: t.model,
input: n,
...typeof t.dimensions === "number" ? { dimensions: t.dimensions } : {},
...s ? { input_type: s } : {}
};
const l = t.localServiceTarget && t.acquireLocalService ? await t.acquireLocalService({
...t.localServiceTarget,
...i ? { onReadinessWait: (e) => i.report(e ? "pause" : "resume") } : {}
}, r?.signal) : void 0;
try {
debugEmbeddingsLog("memory embeddings: remote request", {
context: o,
inputCount: n.length
});
const e = resolveAzureApiVersionRequestTarget({
url: t.endpointUrl,
headers: t.headers
});
return await withRemoteHttpResponse({
url: e.url,
init: {
method: "POST",
headers: e.headers,
body: JSON.stringify(c)
},
signal: r?.signal,
fetchImpl: r?.signal ? fetchWithCallerDeadline : void 0,
ssrfPolicy: t.ssrfPolicy,
auditContext: "embedding-provider:openai-compatible",
onResponse: async (e) => {
debugEmbeddingsLog("memory embeddings: remote response", {
context: o,
...embeddingResponseLogMeta(e)
});
try {
if (!e.ok) throw await createEmbeddingHttpError(e, t.headers, a);
const i = await readProviderJsonResponse(e, a);
const s = readEmbeddingVectors(asOptionalRecord(i)?.data, n.length, o);
assertRequestedDimensions(s, t.dimensions, o);
r?.onUsage?.(extractEmbeddingUsage(i));
return s;
} catch (e) {
if (r?.signal?.aborted) throw e;
throw addEmbeddingErrorContext(e, a, o);
}
}
});
} catch (e) {
throw r?.signal?.aborted ? e : attachLocalServiceDiagnostics(e, l);
} finally {
l?.release();
}
}
/** Creates a normalized OpenAI-compatible embedding client from runtime config. */
async function createOpenAICompatibleEmbeddingClient(e) {
const t = resolveConfiguredProvider(e);
const n = t?.config;
const r = t?.providerId ?? e.provider?.trim() ?? "openai-compatible";
const i = normalizeOptionalString(e.remote?.baseUrl);
const a = normalizeOptionalString(n?.baseUrl);
const o = normalizeBaseUrl(i ?? a);
const { embeddingProviderOwnsDestination: s, resolveEmbeddingEndpointUrl: c, resolveEmbeddingProviderSsrFPolicy: l } = await import("./plugin-sdk/memory-core-host-engine-embeddings.js");
const u = a !== void 0 && s({
baseUrl: o,
providerBaseUrl: a
});
const d = normalizeModel(e.model, e.provider);
const f = normalizeOptionalString(e.inputType);
const p = normalizeOptionalString(e.queryInputType);
const m = normalizeOptionalString(e.documentInputType);
const h = buildHeaders({
apiKey: normalizeResolvedSecretInputString({
value: e.remote?.apiKey,
path: "memory.search.remote.apiKey"
}),
provider: u ? n?.headers : void 0,
remote: e.remote?.headers
});
if (u && !h.authorization) {
const t = await resolveConfiguredProviderApiKey({
providerId: r,
options: e,
configuredProvider: n
});
if (t) h.authorization = `Bearer ${t}`;
}
const g = e;
return {
providerId: r,
baseUrl: o,
endpointUrl: c(o, "embeddings"),
headers: h,
authHeaderName: u && n?.request?.auth?.mode === "header" ? n.request.auth.headerName.trim().toLowerCase() : void 0,
ssrfPolicy: l({
provider: r,
api: n?.api ?? "openai-completions",
baseUrl: o,
allowPrivateNetwork: n?.request?.allowPrivateNetwork
}),
model: d,
...n?.localService && !i ? {
localServiceTarget: {
providerId: r,
baseUrl: o,
headers: h
},
acquireLocalService: g.acquireLocalService
} : {},
...e.dimensions !== void 0 ? { dimensions: normalizeDimensions(e.dimensions) } : {},
...f ? { inputType: f } : {},
...p ? { queryInputType: p } : {},
...m ? { documentInputType: m } : {}
};
}
/** Embedding provider adapter for OpenAI-compatible remote embedding APIs. */
const openAICompatibleEmbeddingProviderAdapter = {
id: OPENAI_COMPATIBLE_EMBEDDING_PROVIDER_ID,
transport: "remote",
create: async (e) => {
const t = await createOpenAICompatibleEmbeddingClient(e);
const embedBatch = async (e, n) => {
if (e.length === 0) return [];
return await postEmbeddingRequest({
client: t,
input: e.map(embeddingInputToText),
callOptions: n
});
};
const n = sanitizeCacheHeaders(t.headers, t.authHeaderName);
const r = {
provider: t.providerId,
baseUrl: t.baseUrl,
model: t.model,
...typeof t.dimensions === "number" ? { dimensions: t.dimensions } : {},
...t.inputType ? { inputType: t.inputType } : {},
...t.queryInputType ? { queryInputType: t.queryInputType } : {},
...t.documentInputType ? { documentInputType: t.documentInputType } : {},
...n ? { headers: n } : {}
};
const i = t.authHeaderName && Object.hasOwn(t.headers, t.authHeaderName) && !isSensitiveHeaderName(t.authHeaderName) ? sanitizeCacheHeaders(t.headers) : void 0;
return {
provider: {
id: OPENAI_COMPATIBLE_EMBEDDING_PROVIDER_ID,
model: t.model,
...typeof t.dimensions === "number" ? { dimensions: t.dimensions } : {},
embed: async (e, t) => {
const [n] = await embedBatch([e], t);
if (!n) throw new Error("openai-compatible embeddings failed: malformed JSON response");
return n;
},
embedBatch
},
runtime: {
id: OPENAI_COMPATIBLE_EMBEDDING_PROVIDER_ID,
inlineBatchTimeoutMs: 6e5,
...isLoopbackBaseUrl(t.baseUrl) ? { inlineIndexConcurrency: 1 } : {},
cacheKeyData: r,
...i ? { indexIdentityAliases: [{
model: t.model,
cacheKeyData: {
...r,
headers: i
}
}] } : {}
}
};
}
};
//#endregion
//#region src/plugins/core-embedding-providers.ts
const CORE_EMBEDDING_PROVIDERS = [{
adapter: openAICompatibleEmbeddingProviderAdapter,
ownerPluginId: "core"
}];
function getCoreEmbeddingProvider(e) {
return CORE_EMBEDDING_PROVIDERS.find((t) => t.adapter.id === e);
}
//#endregion
//#region src/plugins/embedding-providers.ts
function getEmbeddingProviders() {
return requireActivePluginRegistry().embeddingProviders.map((e) => ({
adapter: e.provider,
ownerPluginId: e.pluginId || void 0
}));
}
/** Looks up the registered embedding provider entry, including owner metadata. */
function getRegisteredEmbeddingProvider(e) {
return getCoreEmbeddingProvider(e) ?? getEmbeddingProviders().find((t) => t.adapter.id === e);
}
/** Lists registered embedding providers with core defaults merged first. */
function listRegisteredEmbeddingProviders() {
const e = new Map(CORE_EMBEDDING_PROVIDERS.map((e) => [e.adapter.id, e]));
for (const t of getEmbeddingProviders()) if (!e.has(t.adapter.id)) e.set(t.adapter.id, t);
return Array.from(e.values());
}
//#endregion
//#region src/plugins/gateway-startup-plugin-providers.ts
function collectConfiguredWebSearchProviderIds(e) {
const t = e.tools?.web?.search;
if (t?.enabled === false || typeof t?.provider !== "string") return /* @__PURE__ */ new Set();
const n = normalizeOptionalLowercaseString(t.provider);
return n ? /* @__PURE__ */ new Set([n]) : /* @__PURE__ */ new Set();
}
/** True when web search is enabled without a pinned provider, so auto-detection picks one per call. */
function isWebSearchProviderAutoSelected(e) {
return e.tools?.web?.search?.enabled !== false && collectConfiguredWebSearchProviderIds(e).size === 0;
}
function collectModelProviderIds(e) {
return new Set(listModelRefsFromConfigValue(e).map((e) => {
const t = e.indexOf("/");
return t > 0 ? normalizeProviderId(e.slice(0, t)) : "";
}).filter((e) => Boolean(e)));
}
function buildManifestModelProviderLookup(e, t, n) {
const r = [...n.keys()];
const i = new Set([...n].flatMap(([e, t]) => [...t].map((t) => buildModelCatalogMergeKey(e, t))));
return {
modelApis: new Map(planEffectiveModelCatalogRows({
registry: e,
config: t,
providerFilters: r,
mergeKeyFilter: i
}).rows.flatMap((e) => e.api ? [[e.mergeKey, e.api]] : [])),
cliBackendIds: new Set(e.plugins.flatMap((e) => e.cliBackends.map(normalizeProviderId))),
providerIds: new Set(e.plugins.flatMap((e) => e.providers.map(normalizeProviderId)))
};
}
function collectConfiguredAgentModelProviderIds(e, t) {
const n = /* @__PURE__ */ new Map();
const addModelProviderRefs = (e) => {
for (const t of listModelRefsFromConfigValue(e)) {
const e = parseModelCatalogRef(t);
if (!e) continue;
const r = n.get(e.provider) ?? /* @__PURE__ */ new Set();
r.add(e.modelId);
n.set(e.provider, r);
}
};
const addModelMapProviderIds = (e) => {
if (!isRecord(e)) return;
for (const t of Object.keys(e)) addModelProviderRefs(t);
};
const r = e.agents?.defaults;
addModelProviderRefs(r?.model);
addModelProviderRefs(r?.utilityModel);
addModelMapProviderIds(r?.models);
for (const t of listAgentEntries(e)) {
if (!isRecord(t)) continue;
addModelProviderRefs(t.model);
addModelProviderRefs(t.utilityModel);
addModelMapProviderIds(t.models);
}
if (n.size === 0) return /* @__PURE__ */ new Set();
const i = buildManifestModelProviderLookup(t, e, n);
return new Set([...n].filter(([t, n]) => [...n].some((n) => configuredModelProviderNeedsRuntimePlugin({
config: e,
manifestModelProviders: i,
providerId: t,
modelId: n
}))).map(([e]) => e));
}
function configuredModelProviderNeedsRuntimePlugin(e) {
if (e.manifestModelProviders.cliBackendIds.has(e.providerId)) return true;
const t = e.config.models?.providers?.[e.providerId];
const n = (t?.models?.find((t) => t.id === e.modelId))?.api ?? t?.api ?? e.manifestModelProviders.modelApis.get(buildModelCatalogMergeKey(e.providerId, e.modelId));
if (typeof n === "string") return !CORE_BUILT_IN_MODEL_APIS.has(n);
return e.manifestModelProviders.providerIds.has(e.providerId);
}
function manifestOwnsConfiguredModelProvider(e) {
if (e.configuredModelProviderIds.size === 0) return false;
return [...e.manifest?.providers ?? [], ...e.manifest?.cliBackends ?? []].some((t) => e.configuredModelProviderIds.has(normalizeProviderId(t)));
}
function collectConfiguredGenerationProviderIds(e) {
const t = e.agents?.defaults;
return {
imageGenerationProviders: collectModelProviderIds(t?.mediaModels?.image),
videoGenerationProviders: collectModelProviderIds(t?.mediaModels?.video),
musicGenerationProviders: collectModelProviderIds(t?.mediaModels?.music)
};
}
function collectConfiguredVoiceProviderIds(e) {
const t = collectModelProviderIds(e.agents?.defaults?.voiceModel);
const n = new Set(t);
const r = resolveConfiguredTalkRealtimeProviderId(e);
if (r) n.add(r.toLowerCase());
return {
speechProviders: t,
realtimeTranscriptionProviders: t,
realtimeVoiceProviders: n
};
}
const MEMORY_EMBEDDING_PROVIDER_STARTUP_SKIP_IDS = /* @__PURE__ */ new Set(["auto", "none"]);
function normalizeExplicitMemoryEmbeddingProviderId(e) {
const t = normalizeOptionalLowercaseString(e);
return t && !MEMORY_EMBEDDING_PROVIDER_STARTUP_SKIP_IDS.has(t) ? t : void 0;
}
function readMemorySearchEnabled(e) {
const t = e?.enabled;
return typeof t === "boolean" ? t : void 0;
}
/**
* Resolve a configured memory embedding provider id to the adapter id(s) a
* plugin manifest contract or runtime registry can own. Mirrors runtime
* `getConfiguredMemoryEmbeddingProvider`: the raw id maps to a direct adapter,
* and a custom `models.providers.<id>` entry additionally maps to its `api`
* owner adapter (`provider: "ollama-5080"` with `api: "ollama"` -> "ollama").
* Both candidates are returned so matching covers the direct adapter and the
* API owner without the runtime adapter registry.
*/
function resolveMemoryEmbeddingProviderOwnerIds(e, t) {
const n = [e];
const r = normalizeOptionalLowercaseString(resolveConfiguredGenericEmbeddingProviderId(e, t));
if (r && r !== e) n.push(r);
const i = normalizeOptionalLowercaseString(findNormalizedProviderValue(t.models?.providers, e)?.api);
if (i && i !== e) n.push(i);
return n;
}
function resolveEffectiveMemoryEmbeddingProviderEntries(e, t) {
if (!(readMemorySearchEnabled(t) ?? readMemorySearchEnabled(e) ?? true)) return [];
const n = normalizeOptionalLowercaseString(t?.provider ?? e?.provider);
const r = n === "auto" || !n ? "openai" : n;
if (r === "none") return [];
const i = [];
const a = normalizeExplicitMemoryEmbeddingProviderId(n);
if (a) i.push({
configuredId: a,
source: "provider"
});
const o = normalizeExplicitMemoryEmbeddingProviderId(t?.fallback ?? e?.fallback ?? "none");
if (o && o !== r) i.push({
configuredId: o,
source: "fallback"
});
return i;
}
/**
* Collect explicit memory embedding provider owners required by startup. The
* resolver mirrors runtime memory-search inheritance for enablement, primary
* provider, and fallback provider, then maps custom `models.providers` ids to
* their API-owner adapter ids.
*/
function collectConfiguredMemoryEmbeddingStartupProviderOwners(e) {
if (normalizeOptionalLowercaseString(e.plugins?.slots?.memory) === "none") return [];
const t = /* @__PURE__ */ new Map();
const n = e.memory?.search;
const r = isRecord(n) ? n : void 0;
const addEffectiveProviders = (n, i) => {
for (const { configuredId: a, source: o } of resolveEffectiveMemoryEmbeddingProviderEntries(r, n)) {
const n = `${o}\0${a}`;
const r = t.get(n);
if (r) {
if (i) r.agentIds.add(i);
continue;
}
t.set(n, {
configuredId: a,
ownerIds: new Set(resolveMemoryEmbeddingProviderOwnerIds(a, e)),
agentIds: new Set(i ? [i] : []),
source: o
});
}
};
const i = listAgentEntries(e);
addEffectiveProviders(void 0, i.length === 0 ? listAgentIds(e)[0] : void 0);
for (const e of i) {
const t = isRecord(e.memory) ? e.memory : void 0;
addEffectiveProviders(isRecord(t?.search) ? t.search : void 0, normalizeAgentId(e.id));
}
return [...t.values()];
}
function collectConfiguredMemoryEmbeddingProviderIds(e) {
const t = /* @__PURE__ */ new Set();
for (const n of collectConfiguredMemoryEmbeddingStartupProviderOwners(e)) for (const e of n.ownerIds) t.add(e);
return t;
}
/**
* Report configured memory embedding providers that no loaded plugin can serve.
* A provider is unregistered only when none of its resolved adapter ids (the
* configured id and its `models.providers.<id>.api` owner) was registered, so
* custom providers warn when their API-owner plugin is missing but stay quiet
* once that plugin loads.
*/
function collectUnregisteredConfiguredMemoryEmbeddingProviders(e) {
const t = collectConfiguredMemoryEmbeddingStartupProviderOwners(e.config);
if (t.length === 0) return [];
const n = new Set([...e.registeredProviderIds].map((e) => normalizeOptionalLowercaseString(e)).filter((e) => Boolean(e)));
return t.filter((e) => ![...e.ownerIds].some((e) => n.has(e))).map((e) => ({
configuredId: e.configuredId,
source: e.source
})).toSorted((e, t) => e.configuredId.localeCompare(t.configuredId) || e.source.localeCompare(t.source));
}
function collectRegisteredEmbeddingProviderIds(e) {
const t = [...(e.embeddingProviders ?? []).map((e) => e.provider), ...listRegisteredEmbeddingProviders().map((e) => e.adapter)];
return new Set(t.flatMap(({ id: e, aliases: t }) => [e].concat(t ?? [])));
}
//#endregion
//#region src/plugins/gateway-startup-plugin-config.ts
function readStartupBundledDiscoveryMode(e, t) {
const n = readBundledDiscoveryModeMemoized(t);
if (n) return n;
const r = e.plugins?.bundledDiscovery;
if (r === "compat" || r === "allowlist") return r;
}
function listPotentialEnabledChannelIds(e, t, n) {
const r = new Set(listExplicitlyDisabledChannelIdsForConfig(e));
const i = [...listPotentialConfiguredChannelIds(e, t, {
includePersistedAuthState: false,
ambientEnvTriggers: n
}), ...listExplicitConfiguredChannelIdsForConfig(e)].map((e) => normalizeOptionalLowercaseString(e) ?? "").filter((e) => e && !r.has(e));
return sortUniquePluginIds(i);
}
function blocksPluginStartup(e) {
const t = normalizePluginPolicyId(e.pluginId);
return e.pluginsConfig.deny.includes(t) || e.activationSourcePlugins.deny.includes(t) || e.pluginsConfig.entries[t]?.enabled === false || e.activationSourcePlugins.entries[t]?.enabled === false;
}
function resolveAuthorizedGatewayStartupDreamingPluginIds(e) {
const t = resolveMemoryDreamingConfig({
pluginConfig: resolveMemoryDreamingPluginConfig(e.config),
cfg: e.config
});
const n = resolveMemoryDreamingPluginId(e.config);
const r = DEFAULT_MEMORY_DREAMING_PLUGIN_ID;
if (!t.enabled || !n || n === r || !e.pluginsConfig.enabled || !e.activationSourcePlugins.enabled) return /* @__PURE__ */ new Set();
if (!e.selectedMemoryPluginId || e.selectedMemoryPluginId !== n || e.selectedMemoryPluginId === r || blocksPluginStartup({
pluginId: r,
pluginsConfig: e.pluginsConfig,
activationSourcePlugins: e.activationSourcePlugins
})) return /* @__PURE__ */ new Set();
const i = e.index.plugins.find((t) => t.pluginId === e.selectedMemoryPluginId);
const a = e.index.plugins.find((e) => e.pluginId === r);
if (!i?.startup.memory || !a?.startup.memory) return /* @__PURE__ */ new Set();
return resolveEffectivePluginActivationState({
id: i.pluginId,
origin: i.origin,
channelIds: i.contributions?.channels,
config: e.pluginsConfig,
rootConfig: e.config,
enabledByDefault: isPluginEnabledByDefaultForPlatform(i, e.platform),
activationSource: e.activationSource
}).enabled ? /* @__PURE__ */ new Set([r]) : /* @__PURE__ */ new Set();
}
function resolveMemorySlotStartupPluginId(e) {
const { activationSourceConfig: t, activationSourcePlugins: n, normalizePluginId: r } = e;
const i = t.plugins?.slots?.memory?.trim();
if (i?.toLowerCase() === "none") return;
if (!i) {
const e = n.slots.memory;
if (typeof e !== "string") return;
if (n.allow.length > 0 && !n.allow.includes(e)) return;
return e;
}
return r(i);
}
function resolveContextEngineSlotStartupPluginId(e) {
const { activationSourcePlugins: t, normalizePluginId: n } = e;
const r = t.slots.contextEngine;
if (!r) return;
return resolveSelectedContextEnginePluginIdFromConfig(t, r, e.records, n);
}
function shouldConsiderForGatewayStartup(e) {
return e.manifest?.activation?.onStartup === true || e.contextEngineSlotStartupPluginId === e.plugin.pluginId || e.plugin.startup.memory && (e.startupDreamingPluginIds.has(e.plugin.pluginId) || e.memorySlotStartupPluginId === e.plugin.pluginId);
}
function hasConfiguredActivationPath(e) {
return hasConfiguredActivationPathPatterns({
paths: e.manifest?.activation?.onConfigPaths,
config: e.config
});
}
function hasConfiguredActivationPathPatterns(e) {
const t = e.paths;
if (!t?.length) return false;
return t.some((t) => collectPluginConfigContractMatches({
root: e.config,
pathPattern: t
}).some((e) => isConfigActivationValueEnabled(e.value)));
}
function addConfiguredActivationPathPluginIds(e, t) {
for (const n of t.index.plugins) {
if (n.origin !== "bundled") continue;
if (hasConfiguredActivationPathPatterns({
paths: n.startup.configPaths,
config: t.activationSourceConfig
})) e.add(n.pluginId);
}
}
function addPluginConfigEntryIds(e, t, n) {
for (const [r, i] of Object.entries(t.entries)) if (i?.enabled !== false) e.add(n(r));
}
function addConfiguredSlotPluginIds(e, t) {
const n = resolveMemorySlotStartupPluginId({
activationSourceConfig: t.activationSourceConfig,
activationSourcePlugins: t.activationSourcePlugins,
normalizePluginId: t.lookup.normalizePluginId
});
if (n) e.add(n);
const r = resolveContextEngineSlotStartupPluginId({
records: t.index.plugins.map((e) => ({
id: e.pluginId,
contextEngineIds: e.contextEngineIds
})),
activationSourceConfig: t.activationSourceConfig,
activationSourcePlugins: t.activationSourcePlugins,
normalizePluginId: t.lookup.normalizePluginId
});
if (r) e.add(r);
}
function collectConfiguredStartupChannelIds(e) {
return sortUniquePluginIds(e.configs.flatMap((t) => listPotentialEnabledChannelIds(t, e.env, e.ambientEnvTriggers)));
}
function collectConfiguredProviderIds(e) {
const t = collectConfiguredWebSearchProviderIds(e);
const n = collectConfiguredGenerationProviderIds(e);
const r = collectConfiguredVoiceProviderIds(e);
return sortUniquePluginIds([
...collectConfiguredSpeechProviderIds(e),
...t,
...n.imageGenerationProviders,
...n.videoGenerationProviders,
...n.musicGenerationProviders,
...r.speechProviders,
...r.realtimeTranscriptionProviders,
...r.realtimeVoiceProviders,
...collectConfiguredMemoryEmbeddingProviderIds(e)
]);
}
function collectValidationConfiguredRefs(e) {
const t = [];
const pushProviderId = (e) => {
const n = normalizeOptionalLowercaseString(e);
if (n) t.push(n);
};
const n = e.auth?.profiles;
if (n && typeof n === "object") {
for (const e of Object.values(n)) if (isRecord(e)) pushProviderId(e.provider);
}
const r = e.models?.providers;
if (r && typeof r === "object") for (const e of Object.keys(r)) pushProviderId(e);
const i = [];
for (const t of collectConfiguredModelRefs(e)) {
if (t.capability === "decision") continue;
const e = t.value.indexOf("/");
if (e > 0) pushProviderId(t.value.slice(0, e));
else if (e < 0) i.push(t.value);
}
pushProviderId(e.tools?.web?.search?.provider);
pushProviderId(e.tools?.web?.fetch?.provider);
return {
providerIds: sortUniquePluginIds(t),
shorthandModelRefs: i
};
}
function collectValidationConfiguredShorthandModelIds(e) {
return sortUniquePluginIds(e.map((e) => splitTrailingAuthProfile(e).model.trim()).filter(Boolean));
}
//#endregion
export { readMemoryHostResponseTextSnippet as A, isWebSearchProviderAutoSelected as C, getCoreEmbeddingProvider as D, listRegisteredEmbeddingProviders as E, sanitizeAndNormalizeEmbedding as F, debugEmbeddingsLog as I, buildRemoteBaseUrlPolicy as M, withRemoteHttpResponse as N, fetchRemoteEmbeddingVectors as O, createProviderHttpError as P, collectUnregisteredConfiguredMemoryEmbeddingProviders as S, getRegisteredEmbeddingProvider as T, collectConfiguredMemoryEmbeddingProviderIds as _, collectConfiguredProviderIds as a, collectConfiguredWebSearchProviderIds as b, collectValidationConfiguredShorthandModelIds as c, resolveAuthorizedGatewayStartupDreamingPluginIds as d, resolveContextEngineSlotStartupPluginId as f, collectConfiguredGenerationProviderIds as g, collectConfiguredAgentModelProviderIds as h, blocksPluginStartup as i, readResponseJsonWithLimit as j, postJson as k, hasConfiguredActivationPath as l, shouldConsiderForGatewayStartup as m, addConfiguredSlotPluginIds as n, collectConfiguredStartupChannelIds as o, resolveMemorySlotStartupPluginId as p, addPluginConfigEntryIds as r, collectValidationConfiguredRefs as s, addConfiguredActivationPathPluginIds as t, readStartupBundledDiscoveryMode as u, collectConfiguredMemoryEmbeddingStartupProviderOwners as v, manifestOwnsConfiguredModelProvider as w, collectRegisteredEmbeddingProviderIds as x, collectConfiguredVoiceProviderIds as y };