openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
221 lines (220 loc) • 7.68 kB
JavaScript
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { _ as resolveDefaultAgentId, t as AgentSelectionRequiredError } from "./agent-scope-config-DmXgFGKP.mjs";
import { u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { n as loadBundledPluginPublicArtifactModuleSync } from "./public-surface-loader-DENdCm5a.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { t as respondError } from "./response-C7fEiIN1.mjs";
import { i as withChannelReadAuthority, n as captureChannelReadScope } from "./channel-read-authority-BVl4WY3A.mjs";
import { i as readMemorySearchManagerStatus, s as resolveMemorySearchStaleness } from "./types-Bo5s7TN4.mjs";
import { l as resolveActiveMemoryBackendConfig, o as getActiveMemorySearchManagerCore, s as isActiveMemoryProviderNative } from "./memory-runtime-C3z9zu-7.mjs";
import { n as localStateOwnerChangedError, t as captureLocalStateMutationGuard } from "./local-state-owner-CnxUSfeW.mjs";
//#region src/gateway/server-methods/memory-search.ts
const DEFAULT_MAX_RESULTS = 20;
const MAX_RESULTS = 50;
function resolveSearchMode(e) {
const t = e.custom?.searchMode;
if (t === "hybrid" || t === "fts-only") return t;
return e.provider === "none" || e.vector?.enabled === false ? "fts-only" : "hybrid";
}
function resolveSearchOptions(e, t = false) {
const n = e.maxResults;
if (n !== void 0 && (typeof n !== "number" || !Number.isFinite(n))) return null;
if (t && n !== void 0 && (!Number.isInteger(n) || n < 1)) return null;
const r = Math.min(MAX_RESULTS, Math.max(1, Math.floor(n ?? DEFAULT_MAX_RESULTS)));
const i = e.minScore;
if (i !== void 0 && (typeof i !== "number" || !Number.isFinite(i))) return null;
return {
...t ? n === void 0 ? {} : { maxResults: n } : { maxResults: r },
...i === void 0 ? {} : { minScore: i }
};
}
function hasUsableAgentIdInput(e) {
return normalizeAgentId(`${e}a`) !== "a";
}
async function searchMemory(e, t) {
const { params: n, respond: r, context: i } = e;
if (!t && n?.version === 2) {
const { memoryProviderHandlers: t } = await import("./memory-provider-YRZw9Y9N.mjs");
await t["memory.search"](e);
return;
}
if (n?.version !== void 0 && n.version !== 1) {
respondError(r, ErrorCodes.INVALID_REQUEST, "unsupported memory version");
return;
}
const a = n && typeof n === "object" ? n : {};
const o = typeof a.query === "string" ? a.query : "";
const s = t ? o : o.trim();
if (!o.trim()) {
respondError(r, ErrorCodes.INVALID_REQUEST, "query must be a non-empty string");
return;
}
const c = resolveSearchOptions(a, Boolean(t));
if (!c) {
respondError(r, ErrorCodes.INVALID_REQUEST, t ? "maxResults must be a positive integer and minScore a finite number when provided" : "maxResults and minScore must be finite numbers when provided");
return;
}
const l = i.getRuntimeConfig();
if (t) {
if (normalizePluginsConfig(l.plugins).slots.memory !== "memory-core") {
respondError(r, ErrorCodes.INVALID_REQUEST, `Memory Core search is unavailable for the selected memory slot. Use the selected plugin's memory tools.`);
return;
}
}
const u = Object.hasOwn(a, "agentId");
if (u && typeof a.agentId !== "string") {
respondError(r, ErrorCodes.INVALID_REQUEST, "agentId must be a string");
return;
}
if (u && !hasUsableAgentIdInput(a.agentId)) {
respondError(r, ErrorCodes.INVALID_REQUEST, "unknown agentId");
return;
}
const d = u ? normalizeAgentId(a.agentId) : null;
if (d !== null && !listAgentIds(l).includes(d)) {
respondError(r, ErrorCodes.INVALID_REQUEST, "unknown agentId");
return;
}
let f = d;
if (!f) try {
f = resolveDefaultAgentId(l, {
surface: "memory search",
hint: "Pass agentId to select a configured agent."
});
} catch (e) {
if (!(e instanceof AgentSelectionRequiredError)) throw e;
respondError(r, ErrorCodes.INVALID_REQUEST, e.message);
return;
}
const p = isActiveMemoryProviderNative({
cfg: l,
agentId: f
}) ? resolveActiveMemoryBackendConfig({
cfg: l,
agentId: f
}) : null;
if (p?.backend === "provider-runtime") {
respondError(r, ErrorCodes.INVALID_REQUEST, `memory plugin "${p.providerId}" uses the provider runtime; retry memory.search with version: 2`);
return;
}
let m;
const h = t ? captureChannelReadScope() : void 0;
h?.registerResource({
key: "memory-search-manager",
settle: async () => {
await m?.manager?.close?.();
}
});
try {
m = await getActiveMemorySearchManagerCore({
cfg: l,
agentId: f,
purpose: "cli",
...t ? { inspectSources: true } : {}
});
} catch (e) {
respondError(r, ErrorCodes.UNAVAILABLE, `memory search unavailable: ${formatErrorMessage(e)}`);
return;
}
const { manager: g, error: _ } = m;
if (!g) {
if (t) {
t();
r(true, _?.trim() ? {
agentId: f,
status: "failed",
error: _
} : {
agentId: f,
status: "disabled"
}, void 0);
return;
}
respondError(r, ErrorCodes.UNAVAILABLE, _ ?? "memory search unavailable");
return;
}
let readRebuildWarning = () => void 0;
try {
if (t) {
t();
if (!m.searchForCli) throw new Error("The memory runtime does not support CLI search.");
const e = await m.searchForCli({
manager: g,
cfg: l,
agentId: f,
query: s,
...c,
assertCurrent: t
});
t();
r(true, e, void 0);
return;
}
const { captureMemoryRebuildNotice: e } = loadBundledPluginPublicArtifactModuleSync({
dirName: "memory-core",
artifactBasename: "search-api.js"
});
readRebuildWarning = e(await readMemorySearchManagerStatus(g, { includeCounts: false }));
const n = await g.search(s, c);
const i = await readMemorySearchManagerStatus(g, { includeCounts: false });
const a = resolveMemorySearchStaleness(i, f);
const o = [a?.warning, readRebuildWarning()].filter((e) => typeof e === "string").join(" ");
r(true, {
agentId: f,
provider: i.provider,
searchMode: resolveSearchMode(i),
results: n,
...a,
...o ? { warning: o } : {}
}, void 0);
} catch (e) {
respondError(r, ErrorCodes.UNAVAILABLE, [`memory search failed: ${formatErrorMessage(e)}`, readRebuildWarning()].filter(Boolean).join(" "));
} finally {
if (!h) await g.close?.().catch(() => {});
}
}
/** Operator-scoped search over the active agent memory index. */
const memorySearchHandlers = {
"memory.get": async (e) => {
const { memoryProviderHandlers: t } = await import("./memory-provider-YRZw9Y9N.mjs");
await t["memory.get"](e);
},
"memory.status": async (e) => {
const { memoryProviderHandlers: t } = await import("./memory-provider-YRZw9Y9N.mjs");
await t["memory.status"](e);
},
"memory.search": (e) => searchMemory(e),
"memory.search.owner": async (e) => {
const t = e.params?.expectedOwnerId;
if (typeof t !== "string" || !t.trim()) {
respondError(e.respond, ErrorCodes.INVALID_REQUEST, "expectedOwnerId is required");
return;
}
let n = false;
try {
const r = captureLocalStateMutationGuard(t, e);
await withChannelReadAuthority(r, async () => {
n = true;
let t;
await searchMemory({
...e,
respond: (...e) => {
t = e;
}
}, r);
return t;
}, e.signal, (t) => {
if (t) e.respond(...t);
});
} catch (t) {
e.respond(false, void 0, n ? errorShape(ErrorCodes.UNAVAILABLE, formatErrorMessage(t)) : localStateOwnerChangedError(t));
}
}
};
//#endregion
export { memorySearchHandlers };