openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
423 lines (422 loc) • 19.7 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { c as isSecretRef } from "./ref-contract-b8L-9DrQ.mjs";
import "./types.secrets-BmNLLnHp.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { n as findNormalizedProviderValue, r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { u as tryResolveDefaultAgentId } from "./agent-roster-t1ooUdXp.mjs";
import { E as defaultSlotIdForKey, u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs";
import { v as listProviderPolicyOwners } from "./plugin-metadata-snapshot-By9ySblt.mjs";
import { t as getProviderEnvVarsCore } from "./provider-env-vars-DPvuIf4v.mjs";
import { a as resolveManifestOwnerBasePolicyBlock } from "./manifest-owner-policy-B8Brw4Zo.mjs";
import { n as loadPluginManifestRegistryForPluginRegistry } from "./plugin-registry-contributions-iAw3gSDD.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import "./legacy-config-record-shared-D3vIaBh9.mjs";
import { t as loadProviderPolicyArtifacts } from "./provider-public-artifacts-CzxPvvri.mjs";
import "./plugin-registry-BrQav-kR.mjs";
import { t as captureRuntimeConfig } from "./runtime-source-projection-DTwMWCo9.mjs";
import { t as isConfiguredAwsSdkAuthProfileForProvider } from "./order-jOvee2J6.mjs";
import { r as hasAuthProfileStoreSourceForProvider, t as hasAnyAuthProfileStoreSource } from "./source-check-1bfdqQg5.mjs";
import { n as OPENAI_COMPATIBLE_MODEL_APIS, t as OPENAI_COMPATIBLE_EMBEDDING_PROVIDER_ID } from "./embedding-provider-config-CQrHlBC1.mjs";
import { t as resolveEnvApiKey } from "./model-auth-env-kbpGo8fU.mjs";
import { b as resolveUsableCustomProviderApiKey } from "./model-auth-provider-config-Bnc4upRS.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { o as resolveRememberAcrossConversations } from "./config-utils-sHBULYOF.mjs";
import "./config-utils-CoN3l5FQ.mjs";
import "./auth-profiles-VRLhewIH.mjs";
import { t as resolveApiKeyForProviderCore } from "./model-auth-provider-CRnOp_fz.mjs";
import "./model-auth-CEsyk_Yg.mjs";
import { a as getActiveMemoryProviderCore, l as resolveActiveMemoryBackendConfig } from "./memory-runtime-C3z9zu-7.mjs";
import { t as resolveCommandSecretRefsViaGateway } from "./command-secret-gateway-Dh_PhH7v.mjs";
import { s as getMemoryEmbeddingCommandSecretTargetIds } from "./command-secret-targets-CH2XIeV_.mjs";
import { t as hasConfiguredMemorySecretInput } from "./secret-input-B3kjG4l-.mjs";
import { n as resolveMemorySearchConfig } from "./memory-search-dZuH_5z-.mjs";
import "./secret-BEzQavu8.mjs";
import { a as getMissingLocalMemoryEmbeddingProviderMessage } from "./memory-core-bundled-runtime-C30jyiwB.mjs";
import { n as resolveMemoryDoctorAgentScopes, t as formatMemoryDoctorAgentMessage } from "./doctor-memory-scope-ClHQl6Ye.mjs";
import { i as noteWorkspaceMemoryHealth } from "./doctor-workspace-BGlM5rlo.mjs";
import { safeStatSync } from "@openclaw/fs-safe/path";
//#region src/commands/doctor-memory-search-local.ts
function formatLocalRuntimeDoctorNote(e) {
const t = e.backend ?? "unknown";
const n = e.buildInfo ? `, ${e.buildInfo}` : "";
const r = e.model?.id ? `\nModel: ${e.model.id}${e.model.path ? ` (${e.model.path})` : ""}` : "";
const i = e.capabilities ? `\nCapabilities: ${[e.capabilities.vision ? "vision" : null, e.capabilities.draft ? "draft" : null].filter(Boolean).join(", ") || "text only"}` : "";
const a = e.endpoints ? `\nEndpoints: ${Object.entries(e.endpoints).map(([e, t]) => `${e}=${t}`).join(" ")}` : "";
const o = e.loadError ? `\nLoad error: ${e.loadError}` : "";
return `llama.cpp server: ${t}${n}${e.state === "ready" ? "" : ` (${e.state})`}${r}${i}${a}${o}`;
}
function resolveLocalProviderPolicyBlockGuidance(e, t) {
switch (e) {
case "plugins-disabled": return {
message: "Plugin loading is disabled for this config.",
fix: `Fix: ${formatCliCommand("openclaw config set plugins.enabled true --strict-json")}, or select another memory provider.`
};
case "blocked-by-denylist": return {
message: `Installed plugin "${t}" is blocked by plugins.deny.`,
fix: `Fix: Remove "${t}" from plugins.deny, or select another memory provider.`
};
case "plugin-disabled": return {
message: `Installed plugin "${t}" is disabled for this config.`,
fix: `Fix: Enable it: ${formatCliCommand(`openclaw plugins enable ${t} --accept-capabilities`)}, or select another memory provider.`
};
case "not-in-allowlist": return {
message: `Installed plugin "${t}" is omitted from plugins.allow.`,
fix: `Fix: Include "${t}" in plugins.allow, or select another memory provider.`
};
}
return e;
}
//#endregion
//#region src/commands/doctor-memory-search.ts
const MEMORY_EMBEDDING_PROVIDER_AUTH_IDS = /* @__PURE__ */ new Map([
["github-copilot", "github-copilot"],
["openai", "openai"],
["gemini", "google"],
["voyage", "voyage"],
["mistral", "mistral"],
["bedrock", "amazon-bedrock"]
]);
function hasConfiguredAwsSdkAuthForProvider(e, t) {
if (findNormalizedProviderValue(t.models?.providers, e)?.auth === "aws-sdk") return true;
return (findNormalizedProviderValue(t.auth?.order, e) ?? (t.auth?.profiles ? Object.keys(t.auth.profiles) : [])).some((n) => isConfiguredAwsSdkAuthProfileForProvider({
cfg: t,
provider: e,
profileId: n
}));
}
function isOpenAICompatibleMemoryProvider(e, t) {
const n = normalizeProviderId(e);
if (n === "openai-compatible") return true;
if (MEMORY_EMBEDDING_PROVIDER_AUTH_IDS.has(n)) return false;
const r = findNormalizedProviderValue(t.models?.providers, e);
if (!r) return false;
const i = normalizeProviderId(r.api ?? "");
if (i === "openai-compatible" || OPENAI_COMPATIBLE_MODEL_APIS.has(i)) return true;
return !i && Boolean(normalizeOptionalString(r.baseUrl));
}
function hasActiveAlternateMemoryPluginSlot(e) {
const t = normalizePluginsConfig(e.plugins);
const n = t.slots.memory;
if (!t.enabled || !n || n === defaultSlotIdForKey("memory") || t.deny.includes(n) || !Object.hasOwn(t.entries, n)) return false;
const r = t.entries[n];
if (!r || r.enabled === false) return false;
return r.enabled === true || r.config !== void 0;
}
function resolveActiveMemoryConversationRecallSupport(e) {
const t = normalizePluginsConfig(e.plugins);
const n = t.entries["active-memory"];
const r = isRecord(n?.config) ? n.config : void 0;
const i = e.plugins?.entries?.["active-memory"]?.config;
const a = isRecord(i) ? i : void 0;
return {
available: t.enabled && !t.deny.includes("active-memory") && (t.allow.length === 0 || t.allow.includes("active-memory")) && n?.enabled !== false && r?.enabled !== false,
providerSupported: t.slots.memory === defaultSlotIdForKey("memory"),
memorySearchAllowed: !Array.isArray(a?.toolsAllow) || a.toolsAllow.some((e) => typeof e === "string" && e.trim().toLowerCase() === "memory_search")
};
}
function inspectRememberAcrossConversationsHealth(e) {
if (!resolveRememberAcrossConversations(e.cfg, e.agentId)) return false;
const t = resolveActiveMemoryConversationRecallSupport(e.cfg);
if (!t.available) e.report(`Remember across conversations is effectively enabled for agent "${e.agentId}", but the Active Memory plugin is disabled. Enable the plugin or set memory.search.rememberAcrossConversations to false.`);
else if (!t.providerSupported) e.report(`Remember across conversations is effectively enabled for agent "${e.agentId}", but the current memory provider does not support protected private transcript recall. Set memory.search.rememberAcrossConversations to false or use that provider's own recall path; advanced Active Memory can still use its recall tools.`);
else if (!t.memorySearchAllowed) e.report(`Remember across conversations is effectively enabled for agent "${e.agentId}", but Active Memory does not allow memory_search. Add memory_search to the plugin toolsAllow list or set memory.search.rememberAcrossConversations to false.`);
return true;
}
async function noteMemorySearchHealth(e, t) {
await inspectMemorySearchHealth(e, t ?? {}, ({ text: e }) => note(e, "Memory search"));
}
async function collectMemorySearchHealthFindings(e) {
const t = [];
await inspectMemorySearchHealth(e.cfg, {
env: e.env,
includeWorkspaceMemoryHealth: false,
skipAuthProfileResolution: true,
allowExecSecretRefs: e.allowExecSecretRefs === true,
gatewayMemoryProbe: {
checked: false,
ready: false,
skipped: true
}
}, ({ finding: e }) => {
if (e) t.push(e);
});
return t;
}
async function inspectMemorySearchHealth(e, t, n) {
const r = captureRuntimeConfig(e);
const i = resolveMemoryDoctorAgentScopes(r);
const a = tryResolveDefaultAgentId(r);
const o = i.length > 1;
for (const e of i) {
if (t.includeWorkspaceMemoryHealth !== false) await noteWorkspaceMemoryHealth({
agentId: e.agentId,
workspaceDir: e.workspaceDir,
labelAgent: o
});
const report = (t, r = "memory.search.provider", i = false, a = false) => {
const s = formatMemoryDoctorAgentMessage(e.agentId, o, t);
const [c, ...l] = s.split("\n");
const u = l.map((e) => e.trimEnd()).join("\n").trim();
n({
text: s,
finding: a || i && !o ? null : {
checkId: "core/doctor/memory-search",
severity: "warning",
message: (c ?? s).trim(),
path: r,
...u ? { fixHint: u } : {}
}
});
};
await inspectMemorySearchHealthForAgent(r, e, {
...t,
gatewayMemoryProbe: e.agentId === a || t.gatewayMemoryProbe?.skipped ? t.gatewayMemoryProbe : void 0
}, report);
}
}
async function inspectMemorySearchHealthForAgent(e, t, n, r) {
const { agentId: i, agentDir: a } = t;
const o = resolveMemorySearchConfig(e, i);
if (!o) {
const t = inspectRememberAcrossConversationsHealth({
cfg: e,
agentId: i,
report: r
});
r(t ? `Remember across conversations is effectively enabled for agent "${i}", but memory search is disabled. Enable memory search or set memory.search.rememberAcrossConversations to false.` : "Memory search is explicitly disabled (enabled: false).", "memory.search.provider", !t);
return;
}
const s = o.provider;
const c = normalizePluginsConfig(e.plugins);
if (s === "local" && !c.enabled) {
const e = resolveLocalProviderPolicyBlockGuidance("plugins-disabled", s);
r([
e.message,
"",
e.fix,
"",
`Verify: ${formatCliCommand("openclaw memory status --deep")}`
].join("\n"));
return;
}
const l = resolveActiveMemoryBackendConfig({
cfg: e,
agentId: i
});
if (l?.backend === "provider-runtime") {
let t = null;
let a = "unavailable";
let o = "provider unavailable";
try {
const { resolvedConfig: r, diagnostics: s, hadUnresolvedTargets: c } = await resolveCommandSecretRefsViaGateway({
config: e,
commandName: "doctor",
targetIds: getMemoryEmbeddingCommandSecretTargetIds(e),
mode: "read_only_status",
allowLocalExecSecretRefs: n.allowExecSecretRefs === true
});
if (c) throw new Error(s.join("\n"));
const l = await getActiveMemoryProviderCore({
cfg: r,
agentId: i,
purpose: "status",
context: {
authority: {
kind: "host",
operation: "status"
},
assertCurrent() {}
}
});
t = l.provider;
if (t) {
const e = await t.health();
a = e.status;
o = e.message ?? "no provider message";
} else o = l.error ?? o;
} catch (e) {
o = formatErrorMessage(e);
} finally {
await t?.close().catch(() => {});
}
r(a === "ready" ? `Not applicable: ${l.providerId} uses the provider runtime; see its health.\nProvider health: ${a}${o ? ` (${o})` : ""}.` : `Memory provider "${l.providerId}" is ${a}${o ? `: ${o}` : ""}.\nCheck the provider's configuration and service availability.`, "plugins.slots.memory", false, a === "ready");
return;
}
inspectRememberAcrossConversationsHealth({
cfg: e,
agentId: i,
report: r
});
const u = hasConfiguredMemorySecretInput(o.remote?.apiKey);
if (!l) {
if (n?.gatewayMemoryProbe?.checked && n.gatewayMemoryProbe.ready) return;
if (hasActiveAlternateMemoryPluginSlot(e)) return;
r("No active memory plugin is registered for the current config.", "plugins.slots.memory");
return;
}
if (o.sessionSourceExcluded) r(`Memory search for agent "${i}" requests the "sessions" source, but session indexing is disabled. Set memory.search.experimental.sessionMemory to true for this agent, or enable memory.search.rememberAcrossConversations for private cross-conversation recall.`, "memory.search.sources", false, true);
if (s === "none") return;
if (s === "local") {
const t = n?.gatewayMemoryProbe?.runtimeFacts;
if (n?.gatewayMemoryProbe?.checked && n.gatewayMemoryProbe.ready) {
if (t) r(formatLocalRuntimeDoctorNote(t));
return;
}
const a = hasLocalEmbeddings(o.local);
const l = Boolean(normalizeOptionalString(o.local.modelPath)) && !a;
const u = n?.gatewayMemoryProbe?.error?.trim();
const d = u && u !== t?.loadError ? u : null;
const f = n.env ?? process.env;
const p = loadPluginManifestRegistryForPluginRegistry({
config: e,
env: f,
includeDisabled: true
});
const m = listProviderPolicyOwners(s, p);
if (m.length === 0) {
r(getMissingLocalMemoryEmbeddingProviderMessage());
return;
}
const h = m.map((e) => ({
owner: e,
policyBlock: resolveManifestOwnerBasePolicyBlock({
plugin: e,
normalizedConfig: c
})
}));
const g = h.filter(({ policyBlock: e }) => !e).map(({ owner: e }) => e);
const _ = g.length > 0 ? loadProviderPolicyArtifacts(g) : null;
const v = _ ? {
owner: _.owner,
policyBlock: null
} : h.find(({ policyBlock: e }) => e);
if (!v) throw new Error(`Unable to resolve the installed provider owner for "${s}".`);
const { owner: y, policyBlock: b } = v;
const x = _?.surface;
const S = b ? void 0 : x?.inspectEmbeddingProviderSetup;
const C = S ? await S({
config: e,
env: f,
agentId: i,
provider: s
}) : null;
const w = C?.reason.trim();
const T = C?.fixHint?.trim();
const E = !b && !S ? `Fix: Update the installed plugin: ${formatCliCommand(`openclaw plugins update ${y.id}`)}` : null;
const D = b ? resolveLocalProviderPolicyBlockGuidance(b, y.id) : null;
if (n?.gatewayMemoryProbe?.skipped && !l && !C && !D && !E) return;
const O = Boolean(d || t?.loadError);
r([
t ? formatLocalRuntimeDoctorNote(t) : null,
t ? "" : null,
a ? "Memory search provider is set to \"local\" and a local model path is configured, but local embeddings are not confirmed ready." : "Memory search provider is set to \"local\", but local embeddings are not confirmed ready.",
w ? `Setup: ${w}` : null,
D?.message,
E ? `Installed plugin "${y.id}" does not provide current local-memory setup diagnostics.` : null,
d && d !== w ? `Gateway check: ${d}` : null,
"",
D?.fix ?? E ?? (T ? `Fix: ${T}` : l ? "Fix: Set memory.search.local.modelPath to an existing GGUF file, or remove it to use the managed default." : O ? "Fix: Repair the llama.cpp server problem reported by the Gateway." : null),
"",
`Verify: ${formatCliCommand("openclaw memory status --deep")}`
].filter(Boolean).join("\n"));
return;
}
const d = isOpenAICompatibleMemoryProvider(s, e);
const f = d && !(normalizeOptionalString(o.remote?.baseUrl) ?? normalizeOptionalString(findNormalizedProviderValue(e.models?.providers, s)?.baseUrl));
if (d && (f || !normalizeOptionalString(o.model))) {
const e = f ? "memory.search.remote.baseUrl" : "memory.search.model";
const t = f ? "embeddings endpoint" : "embedding model";
const n = f ? "the /v1 endpoint for your embeddings server" : "the embedding model id your server expects";
const i = f ? "http://127.0.0.1:1234/v1" : "text-embedding-bge-m3";
r([
`Memory search provider is set to "${s}" but no OpenAI-compatible ${t} was configured.`,
`Set ${e} to ${n}.`,
"",
"Fix:",
`- ${formatCliCommand(`openclaw config set ${e} ${i}`)}`,
"",
`Verify: ${formatCliCommand("openclaw memory status --deep")}`
].join("\n"), e);
return;
}
if (s === "ollama" || s === "lmstudio" || d) {
if (n?.gatewayMemoryProbe?.checked && n.gatewayMemoryProbe.ready) return;
if (n?.gatewayMemoryProbe?.skipped) return;
const e = buildGatewayProbeWarning(n?.gatewayMemoryProbe);
r([
e ? `Memory search provider "${s}" is configured, but the gateway reports embeddings are not ready.` : `Memory search provider "${s}" is configured, but the gateway could not confirm embeddings are ready.`,
e,
`Verify: ${formatCliCommand("openclaw memory status --deep")}`
].filter(Boolean).join("\n"));
return;
}
if (u || await hasApiKeyForProvider(s, e, a, { skipProfileResolution: n?.skipAuthProfileResolution === true })) return;
if (n?.gatewayMemoryProbe?.checked && n.gatewayMemoryProbe.ready) {
r([
`Memory search provider is set to "${s}" but the API key was not found in the CLI environment.`,
"The running gateway reports memory embeddings are ready for the default agent.",
`Verify: ${formatCliCommand("openclaw memory status --deep")}`
].join("\n"));
return;
}
const p = buildGatewayProbeWarning(n?.gatewayMemoryProbe);
const m = resolvePrimaryMemoryProviderEnvVar(s);
r([
`Memory search provider is set to "${s}" but no API key was found.`,
"Without working primary or fallback embeddings, memory sync stops for explicitly configured providers or existing vector indexes; new and changed memory files are not indexed.",
p ? p : null,
"",
"Fix (pick one):",
`- Set ${m} in your environment`,
`- Configure credentials: ${formatCliCommand("openclaw configure --section model")}`,
`- For keyword-only recall without a key, set memory.search.provider to "none" for this agent (including any agent override), then run ${formatCliCommand(`openclaw memory index --force --agent ${i}`)}`,
"",
`Then rerun: ${formatCliCommand("openclaw doctor")}`
].join("\n"));
}
function hasLocalEmbeddings(e) {
const t = normalizeOptionalString(e.modelPath);
if (!t) return false;
if (/^(hf:|https?:)/i.test(t)) return true;
const n = resolveUserPath(t);
return safeStatSync(n)?.isFile() ?? false;
}
async function hasApiKeyForProvider(e, t, n, r) {
const i = MEMORY_EMBEDDING_PROVIDER_AUTH_IDS.get(e) ?? e;
if (isSecretRef(findNormalizedProviderValue(t.models?.providers, i)?.apiKey) || resolveEnvApiKey(i) || resolveUsableCustomProviderApiKey({
cfg: t,
provider: i
})) return true;
if (r?.skipProfileResolution === true) {
if (i === "amazon-bedrock") return hasConfiguredAwsSdkAuthForProvider(i, t);
const e = findNormalizedProviderValue(t.auth?.order, i);
return e === void 0 ? hasAuthProfileStoreSourceForProvider(i, n) : hasAuthProfileStoreSourceForProvider(i, n, { profileIds: e });
}
if (i !== "amazon-bedrock" && !hasAnyAuthProfileStoreSource(n)) return false;
try {
await resolveApiKeyForProviderCore({
provider: i,
cfg: t,
agentDir: n
});
return true;
} catch {
return false;
}
}
function resolvePrimaryMemoryProviderEnvVar(e) {
if (e === "openai") return "OPENAI_API_KEY";
const t = MEMORY_EMBEDDING_PROVIDER_AUTH_IDS.get(e);
return (t ? getProviderEnvVarsCore(t)[0] : void 0) ?? `${e.toUpperCase()}_API_KEY`;
}
function buildGatewayProbeWarning(e) {
if (!e?.checked || e.ready) return null;
const t = e.error?.trim();
return t ? `Gateway memory check for default agent is not ready: ${t}` : "Gateway memory check for default agent is not ready.";
}
//#endregion
export { collectMemorySearchHealthFindings, noteMemorySearchHealth };