Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(openclaw): configure recall target types (#2590)

Mingjian Que564c7624b859
diff --git a/examples/openclaw-plugin/auto-recall.ts b/examples/openclaw-plugin/auto-recall.ts
index a05c45977..0c553d462 100644
--- a/examples/openclaw-plugin/auto-recall.ts
+++ b/examples/openclaw-plugin/auto-recall.ts
@@ -14,6 +14,7 @@ import type {
RecallTraceEntry,
RecallTraceResult,
} from "./recall-trace.js";
+import { resolveRecallSearchPlan } from "./recall-trace.js";
const RECALL_QUERY_MAX_CHARS = 4_000;
export const AUTO_RECALL_SOURCE_MARKER = "Source: openviking-auto-recall";
@@ -257,7 +258,10 @@ function preview(value: string | undefined | null, maxChars: number): string | u
}
function traceResourceTypeForUri(uri: string | undefined): RecallResourceType {
- return uri?.startsWith("viking://resources") ? "resource" : "user";
+ if (uri?.startsWith("viking://resources")) return "resource";
+ if (uri?.startsWith("viking://agent/")) return "agent";
+ if (uri?.startsWith("viking://session/") || uri?.includes("/sessions/")) return "session";
+ return "user";
}
function toTraceResults(items: FindResultItem[], resourceType: RecallResourceType): RecallTraceResult[] {
@@ -532,51 +536,58 @@ export async function buildLongTermMemoryRecallContext(params: {
return withTimeout(
(async () => {
const candidateLimit = Math.max(cfg.recallLimit * 4, 20);
- const targetUris = [
- "viking://user/memories",
- ...(cfg.recallResources ? ["viking://resources"] : []),
- ];
- const autoRecallPromises = targetUris.map(async (targetUri) => {
+ const searchPlan = resolveRecallSearchPlan(cfg.recallTargetTypes, {
+ ovSessionId: params.ovSessionId,
+ agentId,
+ });
+ const autoRecallPromises = searchPlan.searches.map(async (search) => {
const started = Date.now();
const result = await client.find(queryText, {
- targetUri,
+ targetUri: search.targetUri,
limit: candidateLimit,
scoreThreshold: 0,
peerId,
}, agentId);
return {
- targetUri,
+ search,
result,
durationMs: Date.now() - started,
};
});
- const traceSearches: RecallTraceEntry["searches"] = [];
+ const traceSearches: RecallTraceEntry["searches"] = searchPlan.skipped.map((skipped) => ({
+ resourceType: skipped.resourceType,
+ limit: candidateLimit,
+ scoreThreshold: 0,
+ durationMs: 0,
+ total: 0,
+ results: [],
+ error: skipped.reason,
+ }));
const autoRecallSettled = await Promise.allSettled(autoRecallPromises);
const allMemories: FindResultItem[] = [];
for (let index = 0; index < autoRecallSettled.length; index += 1) {
const s = autoRecallSettled[index]!;
- const targetUri = targetUris[index]!;
- const resourceType = traceResourceTypeForUri(targetUri);
+ const search = searchPlan.searches[index]!;
if (s.status === "fulfilled") {
const result = s.value.result;
const memories = result.memories ?? [];
const resources = result.resources ?? [];
allMemories.push(...memories, ...resources);
traceSearches.push({
- resourceType,
- targetUriInput: targetUri,
- targetUriResolved: targetUri,
+ resourceType: s.value.search.resourceType,
+ targetUriInput: s.value.search.targetUri,
+ targetUriResolved: s.value.search.targetUri,
limit: candidateLimit,
scoreThreshold: 0,
durationMs: s.value.durationMs,
total: result.total ?? memories.length + resources.length + (result.skills?.length ?? 0),
results: [
- ...toTraceResults(memories, resourceType),
+ ...toTraceResults(memories, s.value.search.resourceType),
...toTraceResults(resources, "resource"),
...(result.skills ?? []).map((item): RecallTraceResult => ({
uri: item.uri,
- resourceType,
+ resourceType: s.value.search.resourceType,
category: item.category,
score: item.score,
level: item.level,
@@ -588,9 +599,9 @@ export async function buildLongTermMemoryRecallContext(params: {
} else {
logger.warn?.(`openviking: auto-recall search failed: ${String(s.reason)}`);
traceSearches.push({
- resourceType,
- targetUriInput: targetUri,
- targetUriResolved: targetUri,
+ resourceType: search.resourceType,
+ targetUriInput: search.targetUri,
+ targetUriResolved: search.targetUri,
limit: candidateLimit,
scoreThreshold: 0,
durationMs: 0,
@@ -610,9 +621,6 @@ export async function buildLongTermMemoryRecallContext(params: {
scoreThreshold: cfg.recallScoreThreshold,
});
const memories = pickMemoriesForInjection(processed, cfg.recallLimit, queryText);
- const resourceTypes = [...new Set(traceSearches
- .map((search) => search.resourceType)
- .filter((resourceType): resourceType is RecallResourceType => resourceType !== "archive"))];
const recordTrace = (injectedMemories: FindResultItem[], injectedCount: number, estimatedTokens?: number) => {
params.traceRecorder?.record({
schemaVersion: "1.0",
@@ -624,7 +632,7 @@ export async function buildLongTermMemoryRecallContext(params: {
agentId,
source: "auto_recall",
operationType: "semantic_find",
- resourceTypes: resourceTypes.length > 0 ? resourceTypes : ["user"],
+ resourceTypes: searchPlan.resourceTypes,
trigger: {
rawUserTextPreview: params.rawUserTextPreview,
...boundTraceQuery(queryText, cfg.traceRecallQueryMaxChars),
diff --git a/examples/openclaw-plugin/commands/setup.ts b/examples/openclaw-plugin/commands/setup.ts
index 69cafe16f..ba5e91aaa 100644
--- a/examples/openclaw-plugin/commands/setup.ts
+++ b/examples/openclaw-plugin/commands/setup.ts
@@ -64,6 +64,7 @@ const CONFIG_KEYS_TO_PRESERVE = [
"captureMaxLength",
"autoRecall",
"recallResources",
+ "recallTargetTypes",
"recallLimit",
"recallScoreThreshold",
"recallMaxInjectedChars",
@@ -78,6 +79,8 @@ const CONFIG_KEYS_TO_PRESERVE = [
] as const;
type PeerRole = "none" | "assistant" | "person";
+type RecallTargetType = "resource" | "user" | "agent";
+const ALLOWED_RECALL_TARGET_TYPES = ["resource", "user", "agent"] as const;
type CommandProgram = {
command: (name: string) => CommandBuilder;
@@ -135,6 +138,44 @@ function resolveSetupPeerRole(value: unknown): PeerRole {
throw new Error('peer_role must be "none", "assistant", or "person"');
}
+function normalizeSetupRecallTargetTypes(value: unknown): RecallTargetType[] | undefined {
+ if (value === undefined || value === null || value === "") {
+ return undefined;
+ }
+ const entries = Array.isArray(value)
+ ? value
+ : typeof value === "string"
+ ? value.split(/[,\n]/)
+ : [];
+ const seen = new Set<RecallTargetType>();
+ const normalized: RecallTargetType[] = [];
+ const unknown: string[] = [];
+
+ for (const raw of entries) {
+ if (typeof raw !== "string") {
+ continue;
+ }
+ const entry = raw.trim();
+ if (!entry) {
+ continue;
+ }
+ if ((ALLOWED_RECALL_TARGET_TYPES as readonly string[]).includes(entry)) {
+ const typed = entry as RecallTargetType;
+ if (!seen.has(typed)) {
+ seen.add(typed);
+ normalized.push(typed);
+ }
+ } else {
+ unknown.push(entry);
+ }
+ }
+
+ if (unknown.length > 0) {
+ throw new Error(`recall-target-types contains unknown resource types: ${unknown.join(", ")}`);
+ }
+ return normalized.length > 0 ? normalized : undefined;
+}
+
function preserveCurrentConfig(existing: Record<string, unknown> | null | undefined) {
const config: Record<string, unknown> = {};
if (!existing) {
@@ -454,6 +495,7 @@ type SetupResult = {
peer_prefix?: string;
accountId?: string;
userId?: string;
+ recallTargetTypes?: string[];
};
health?: HealthResult;
keyProbe?: ApiKeyProbeResult;
@@ -539,6 +581,7 @@ export function registerSetupCli(api: any): void {
.option("--peer-prefix <prefix>", "Prefix for assistant peer_id values")
.option("--account-id <id>", "Account ID (required for root API keys)")
.option("--user-id <id>", "User ID (required for root API keys)")
+ .option("--recall-target-types <types>", "Comma-separated recall target types: user, agent, resource")
.option("--allow-offline", "Allow config write even if server is unreachable")
.option("--force-slot", "Replace existing contextEngine slot even if owned by another plugin")
.option("--json", "Output result as JSON (machine-readable)")
@@ -546,11 +589,11 @@ export function registerSetupCli(api: any): void {
const options = (args[0] ?? {}) as Record<string, unknown>;
const {
reconfigure, zh: zhOpt, baseUrl, apiKey, peerRole, peerPrefix,
- accountId, userId, allowOffline, forceSlot, json: jsonOpt,
+ accountId, userId, recallTargetTypes, allowOffline, forceSlot, json: jsonOpt,
} = options as {
reconfigure?: boolean; zh?: boolean; baseUrl?: string;
apiKey?: string; peerRole?: string; peerPrefix?: string; accountId?: string;
- userId?: string; allowOffline?: boolean; forceSlot?: boolean;
+ userId?: string; recallTargetTypes?: string; allowOffline?: boolean; forceSlot?: boolean;
json?: boolean;
};
const zh = detectLangZh(options);
@@ -566,6 +609,7 @@ export function registerSetupCli(api: any): void {
peerPrefix,
accountId,
userId,
+ recallTargetTypes: normalizeSetupRecallTargetTypes(recallTargetTypes),
allowOffline: !!allowOffline,
forceSlot: !!forceSlot,
});
@@ -741,10 +785,20 @@ async function runRemoteCheck(
async function setupNonInteractive(
configPath: string,
- params: { baseUrl: string; apiKey?: string; peerRole?: string; peerPrefix?: string; accountId?: string; userId?: string; allowOffline?: boolean; forceSlot?: boolean },
+ params: {
+ baseUrl: string;
+ apiKey?: string;
+ peerRole?: string;
+ peerPrefix?: string;
+ accountId?: string;
+ userId?: string;
+ recallTargetTypes?: string[];
+ allowOffline?: boolean;
+ forceSlot?: boolean;
+ },
): Promise<SetupResult> {
try {
- const { baseUrl, apiKey, peerPrefix, accountId, userId, allowOffline, forceSlot } = params;
+ const { baseUrl, apiKey, peerPrefix, accountId, userId, recallTargetTypes, allowOffline, forceSlot } = params;
const resolvedPeerRole = resolveSetupPeerRole(params.peerRole);
const resolvedPeerPrefix = (peerPrefix ?? "").trim();
if (!isValidPeerPrefixInput(resolvedPeerPrefix)) {
@@ -793,6 +847,9 @@ async function setupNonInteractive(
if (resolvedPeerPrefix) pluginCfg.peer_prefix = resolvedPeerPrefix;
if (accountId) pluginCfg.accountId = accountId;
if (userId) pluginCfg.userId = userId;
+ if (recallTargetTypes && recallTargetTypes.length > 0) {
+ pluginCfg.recallTargetTypes = recallTargetTypes;
+ }
writeConfig(configPath, pluginCfg);
const slot = activateContextEngineSlot(configPath, !!forceSlot);
@@ -809,6 +866,7 @@ async function setupNonInteractive(
...(resolvedPeerPrefix ? { peer_prefix: resolvedPeerPrefix } : {}),
...(accountId ? { accountId } : {}),
...(userId ? { userId } : {}),
+ ...(recallTargetTypes && recallTargetTypes.length > 0 ? { recallTargetTypes } : {}),
},
health,
keyProbe,
@@ -828,6 +886,7 @@ async function setupNonInteractive(
...(resolvedPeerPrefix ? { peer_prefix: resolvedPeerPrefix } : {}),
...(accountId ? { accountId } : {}),
...(userId ? { userId } : {}),
+ ...(recallTargetTypes && recallTargetTypes.length > 0 ? { recallTargetTypes } : {}),
},
health,
keyProbe,
@@ -856,6 +915,7 @@ function printSetupResult(zh: boolean, result: SetupResult): void {
if (result.config.peer_prefix) console.log(` peer_prefix: ${result.config.peer_prefix}`);
if (result.config.accountId) console.log(` accountId: ${result.config.accountId}`);
if (result.config.userId) console.log(` userId: ${result.config.userId}`);
+ if (result.config.recallTargetTypes) console.log(` recallTargetTypes: ${result.config.recallTargetTypes.join(",")}`);
}
console.log("");
if (result.health?.ok) {
@@ -1091,6 +1151,7 @@ async function setupRemote(
export const __test__ = {
isLegacyLocalMode,
isValidPeerPrefixInput,
+ normalizeSetupRecallTargetTypes,
activateContextEngineSlot,
isContextEngineSlotActive,
getStatus,
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index c03e5467c..133c07f25 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -71,6 +71,8 @@ export type MemoryOpenVikingConfig = {
traceRecallIncludeContentByDefault?: boolean;
/** Whether raw user text preview may be persisted. Default false. */
traceRecallIncludeRawUserPreview?: boolean;
+ /** Auto-recall target resource types. Empty means the backward-compatible memory recall set. */
+ recallTargetTypes?: Array<"resource" | "user" | "agent"> | string;
/** Agent-visible add_resource tool is disabled by default; manual /add-resource remains available. */
enableAddResourceTool?: boolean;
/** Agent-visible tool allowlist. Supports exact tool names or groups such as "memory" and "resource_query". */
@@ -118,6 +120,9 @@ const DEFAULT_TRACE_RECALL_MAX_RESULTS_PER_SEARCH = 20;
const DEFAULT_TRACE_RECALL_PREVIEW_CHARS = 240;
const DEFAULT_TRACE_RECALL_QUERY_MAX_CHARS = 4000;
const DEFAULT_TRACE_RECALL_QUERY_MAX_DAYS = 14;
+const ALLOWED_RECALL_TARGET_TYPES = ["resource", "user", "agent"] as const;
+const DEFAULT_RECALL_TARGET_TYPES = ["user", "agent"] as const;
+type RecallTargetType = typeof ALLOWED_RECALL_TARGET_TYPES[number];
export const OPENVIKING_ADD_RESOURCE_TOOL_NAME = "add_resource" as const;
export const OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES = [
"add_skill",
@@ -237,6 +242,35 @@ function toIntegerInRange(value: unknown, fallback: number, min: number, max: nu
return Math.max(min, Math.min(max, Math.floor(toNumber(value, fallback))));
}
+function normalizeRecallTargetTypes(value: unknown, includeResources = false): RecallTargetType[] {
+ const entries = toStringArray(value, [...DEFAULT_RECALL_TARGET_TYPES]);
+ const seen = new Set<RecallTargetType>();
+ const normalized: RecallTargetType[] = [];
+ const unknown: string[] = [];
+
+ for (const entry of entries) {
+ if ((ALLOWED_RECALL_TARGET_TYPES as readonly string[]).includes(entry)) {
+ const typed = entry as RecallTargetType;
+ if (!seen.has(typed)) {
+ seen.add(typed);
+ normalized.push(typed);
+ }
+ } else {
+ unknown.push(entry);
+ }
+ }
+
+ if (unknown.length > 0) {
+ throw new Error(`openviking recallTargetTypes contains unknown resource types: ${unknown.join(", ")}`);
+ }
+
+ const result = normalized.length > 0 ? normalized : [...DEFAULT_RECALL_TARGET_TYPES];
+ if (includeResources && !seen.has("resource")) {
+ result.push("resource");
+ }
+ return result;
+}
+
function toRecord(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
@@ -377,6 +411,7 @@ export const memoryOpenVikingConfigSchema = {
"traceRecallQueryMaxDays",
"traceRecallIncludeContentByDefault",
"traceRecallIncludeRawUserPreview",
+ "recallTargetTypes",
"enableAddResourceTool",
"enabledTools",
"disabledTools",
@@ -427,6 +462,11 @@ export const memoryOpenVikingConfigSchema = {
),
),
);
+ const recallResources = cfg.recallResources === true || envFlag("OPENVIKING_RECALL_RESOURCES");
+ const recallTargetTypes = normalizeRecallTargetTypes(
+ cfg.recallTargetTypes,
+ !("recallTargetTypes" in cfg) && recallResources,
+ );
const { enabledTools, disabledTools } = normalizeEnabledTools(cfg);
return {
@@ -450,7 +490,7 @@ export const memoryOpenVikingConfigSchema = {
1000,
Math.min(300_000, Math.floor(toNumber(cfg.autoRecallTimeoutMs, DEFAULT_AUTO_RECALL_TIMEOUT_MS))),
),
- recallResources: cfg.recallResources === true || envFlag("OPENVIKING_RECALL_RESOURCES"),
+ recallResources,
recallLimit: Math.max(1, Math.floor(toNumber(cfg.recallLimit, DEFAULT_RECALL_LIMIT))),
recallScoreThreshold: Math.min(
1,
@@ -542,6 +582,7 @@ export const memoryOpenVikingConfigSchema = {
),
traceRecallIncludeContentByDefault: cfg.traceRecallIncludeContentByDefault === true,
traceRecallIncludeRawUserPreview: cfg.traceRecallIncludeRawUserPreview === true,
+ recallTargetTypes,
enableAddResourceTool: cfg.enableAddResourceTool === true,
enabledTools,
disabledTools,
@@ -653,6 +694,12 @@ export const memoryOpenVikingConfigSchema = {
help: "Include resources (viking://resources) in auto-recall and default memory_recall search. Enables account-level shared knowledge retrieval.",
advanced: true,
},
+ recallTargetTypes: {
+ label: "Recall Target Types",
+ placeholder: "user,agent",
+ help: "Comma-separated auto-recall and default memory_recall targets: user, agent, resource. Session history is available through ov_archive_search and ov_archive_expand.",
+ advanced: true,
+ },
recallLimit: {
label: "Recall Limit",
placeholder: String(DEFAULT_RECALL_LIMIT),
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index ef5458a08..a45028a53 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -46,6 +46,7 @@ import {
import {
RecallTraceRecorder,
normalizeResourceTypes,
+ resolveRecallSearchPlan,
type RecallResourceType,
type RecallTraceEntry,
type RecallTraceQuery,
@@ -1655,6 +1656,9 @@ const contextEnginePlugin = {
targetUri: Type.Optional(
Type.String({ description: "Search scope URI (default: plugin config)" }),
),
+ resourceTypes: Type.Optional(
+ Type.Array(Type.String({ description: "resource, user, or agent; used when targetUri is omitted. Use ov_archive_search/ov_archive_expand for session history." })),
+ ),
}),
async execute(_toolCallId: string, params: Record<string, unknown>) {
if (isBypassedSession(ctx)) {
@@ -1675,6 +1679,9 @@ const contextEnginePlugin = {
typeof (params as { targetUri?: string }).targetUri === "string"
? (params as { targetUri: string }).targetUri
: undefined;
+ const requestedResourceTypes = Object.prototype.hasOwnProperty.call(params, "resourceTypes")
+ ? (params as { resourceTypes?: unknown }).resourceTypes
+ : undefined;
const requestLimit = Math.max(limit * 4, 20);
const recallClient = await getClient();
@@ -1717,41 +1724,36 @@ const contextEnginePlugin = {
results: traceResults,
}];
} else {
- const searchPromises: Promise<FindResult>[] = [
+ const searchPlan = resolveRecallSearchPlan(requestedResourceTypes ?? cfg.recallTargetTypes, {
+ ovSessionId: session.ovSessionId,
+ agentId: session.agentId,
+ });
+ memoryRecallSearches.push(...searchPlan.skipped.map((skipped) => ({
+ resourceType: skipped.resourceType,
+ limit: requestLimit,
+ scoreThreshold,
+ durationMs: 0,
+ total: 0,
+ results: [],
+ error: skipped.reason,
+ })));
+ const searchPromises = searchPlan.searches.map((search) =>
recallClient.find(
query,
{
- targetUri: "viking://user/memories",
+ targetUri: search.targetUri,
limit: requestLimit,
scoreThreshold: 0,
peerId,
},
session.agentId,
),
- ];
- if (cfg.recallResources) {
- searchPromises.push(
- recallClient.find(
- query,
- {
- targetUri: "viking://resources",
- limit: requestLimit,
- scoreThreshold: 0,
- peerId,
- },
- session.agentId,
- ),
- );
- }
+ );
const settled = await Promise.allSettled(searchPromises);
const allMemories: FindResultItem[] = [];
- const targetUris = [
- "viking://user/memories",
- ...(cfg.recallResources ? ["viking://resources"] : []),
- ];
for (let index = 0; index < settled.length; index += 1) {
const s = settled[index]!;
- const targetUriResolved = targetUris[index] ?? "viking://user/memories";
+ const search = searchPlan.searches[index]!;
if (s.status === "fulfilled") {
allMemories.push(...(s.value.memories ?? []), ...(s.value.resources ?? []));
const traceResults = [
@@ -1760,9 +1762,9 @@ const contextEnginePlugin = {
...(s.value.skills ?? []).map((item) => toTraceResult(item, "skill")),
].slice(0, cfg.traceRecallMaxResultsPerSearch);
memoryRecallSearches.push({
- resourceType: inferRecallResourceType(targetUriResolved) ?? "user",
- targetUriInput: targetUriResolved,
- targetUriResolved,
+ resourceType: search.resourceType,
+ targetUriInput: search.targetUri,
+ targetUriResolved: search.targetUri,
limit: requestLimit,
scoreThreshold,
durationMs: 0,
@@ -1771,9 +1773,9 @@ const contextEnginePlugin = {
});
} else {
memoryRecallSearches.push({
- resourceType: inferRecallResourceType(targetUriResolved) ?? "user",
- targetUriInput: targetUriResolved,
- targetUriResolved,
+ resourceType: search.resourceType,
+ targetUriInput: search.targetUri,
+ targetUriResolved: search.targetUri,
limit: requestLimit,
scoreThreshold,
durationMs: 0,
@@ -1913,7 +1915,7 @@ const contextEnginePlugin = {
sessionKey: Type.Optional(Type.String({ description: "OpenClaw session key" })),
ovSessionId: Type.Optional(Type.String({ description: "OpenViking session id" })),
source: Type.Optional(Type.String({ description: "auto_recall, memory_recall, ov_search, or ov_archive_search" })),
- resourceTypes: Type.Optional(Type.Array(Type.String({ description: "resource, session, user, or agent" }))),
+ resourceTypes: Type.Optional(Type.Array(Type.String({ description: "resource, user, or agent" }))),
since: Type.Optional(Type.Number({ description: "Unix timestamp lower bound in milliseconds" })),
until: Type.Optional(Type.Number({ description: "Unix timestamp upper bound in milliseconds" })),
includeContent: Type.Optional(Type.Boolean({ description: "Read selected/displayed URI content previews on demand" })),
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index 8792a5d4e..5ab1668d9 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -150,6 +150,12 @@
"help": "Include resources (viking://resources) in auto-recall and default memory_recall search. Enables account-level shared knowledge retrieval.",
"advanced": true
},
+ "recallTargetTypes": {
+ "label": "Recall Target Types",
+ "placeholder": "user,agent",
+ "help": "Comma-separated auto-recall and default memory_recall targets: user, agent, resource. Session history is available through ov_archive_search and ov_archive_expand.",
+ "advanced": true
+ },
"recallLimit": {
"label": "Recall Limit",
"placeholder": "6",
@@ -312,6 +318,24 @@
"recallResources": {
"type": "boolean"
},
+ "recallTargetTypes": {
+ "oneOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "enum": [
+ "resource",
+ "user",
+ "agent"
+ ]
+ }
+ }
+ ]
+ },
"recallLimit": {
"type": "number"
},
diff --git a/examples/openclaw-plugin/recall-trace.ts b/examples/openclaw-plugin/recall-trace.ts
index 2db822d44..6d5cd9e8d 100644
--- a/examples/openclaw-plugin/recall-trace.ts
+++ b/examples/openclaw-plugin/recall-trace.ts
@@ -91,7 +91,7 @@ export type RecallTraceFlushResult = {
warnings: string[];
};
-const ALLOWED_RESOURCE_TYPES: RecallResourceType[] = ["resource", "session", "user", "agent"];
+const ALLOWED_RESOURCE_TYPES: RecallResourceType[] = ["resource", "user", "agent"];
const DEFAULT_RESOURCE_TYPES: RecallResourceType[] = ["user", "agent"];
function toResourceTypeEntries(value: unknown): string[] {
@@ -140,7 +140,7 @@ export function normalizeResourceTypes(value: unknown): RecallResourceType[] {
export function resolveRecallSearchPlan(
resourceTypes: unknown,
- ctx: { ovSessionId?: string; agentId?: string },
+ _ctx: { ovSessionId?: string; agentId?: string },
): {
resourceTypes: RecallResourceType[];
searches: Array<{ resourceType: RecallResourceType; targetUri: string }>;
@@ -153,12 +153,6 @@ export function resolveRecallSearchPlan(
for (const resourceType of normalized) {
if (resourceType === "resource") {
searches.push({ resourceType, targetUri: "viking://resources" });
- } else if (resourceType === "session") {
- if (ctx.ovSessionId) {
- searches.push({ resourceType, targetUri: `viking://session/${ctx.ovSessionId}/history` });
- } else {
- skipped.push({ resourceType, reason: "missing_session" });
- }
} else if (resourceType === "user") {
searches.push({ resourceType, targetUri: "viking://user/memories" });
} else if (resourceType === "agent") {
diff --git a/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts b/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts
index 34c45e7df..1c76a5522 100644
--- a/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts
+++ b/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts
@@ -271,7 +271,7 @@ describe("buildLongTermMemoryRecallContext trace", () => {
}
it("records auto-recall trace without changing the generated section", async () => {
- const cfg = makeCfg();
+ const cfg = makeCfg({ recallTargetTypes: ["user"] });
const memory = makeMemory({
uri: "viking://user/memories/rust-pref",
category: "preferences",
@@ -333,7 +333,7 @@ describe("buildLongTermMemoryRecallContext trace", () => {
});
it("records search errors while still injecting successful recall hits", async () => {
- const cfg = makeCfg({ recallResources: true });
+ const cfg = makeCfg({ recallTargetTypes: ["user", "resource"] });
const client = {
healthCheck: vi.fn().mockResolvedValue(undefined),
find: vi.fn()
diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.ts
index bb3e48265..75b12061b 100644
--- a/examples/openclaw-plugin/tests/ut/config.test.ts
+++ b/examples/openclaw-plugin/tests/ut/config.test.ts
@@ -39,6 +39,7 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {
expect(cfg.traceRecallQueryMaxDays).toBe(14);
expect(cfg.traceRecallIncludeContentByDefault).toBe(false);
expect(cfg.traceRecallIncludeRawUserPreview).toBe(false);
+ expect(cfg.recallTargetTypes).toEqual(["user", "agent"]);
expect(cfg.enableAddResourceTool).toBe(false);
expect(cfg.enabledTools).toContain("ov_search");
expect(cfg.enabledTools).toContain("ov_read");
@@ -363,4 +364,41 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {
const cfg2 = memoryOpenVikingConfigSchema.parse({ recallResources: 1 });
expect(cfg2.recallResources).toBe(false);
});
+
+ it("normalizes recallTargetTypes from arrays and comma-separated strings", () => {
+ const fromArray = memoryOpenVikingConfigSchema.parse({
+ recallTargetTypes: [" user ", "agent", "user", ""],
+ });
+ expect(fromArray.recallTargetTypes).toEqual(["user", "agent"]);
+
+ const fromString = memoryOpenVikingConfigSchema.parse({
+ recallTargetTypes: "resource, user\nagent",
+ });
+ expect(fromString.recallTargetTypes).toEqual(["resource", "user", "agent"]);
+ });
+
+ it("rejects unknown recallTargetTypes instead of falling back to defaults", () => {
+ expect(() =>
+ memoryOpenVikingConfigSchema.parse({ recallTargetTypes: ["user", "project"] }),
+ ).toThrow("recallTargetTypes contains unknown resource types: project");
+ });
+
+ it("rejects session recallTargetTypes because session history is not a semantic recall target", () => {
+ expect(() =>
+ memoryOpenVikingConfigSchema.parse({ recallTargetTypes: ["session"] }),
+ ).toThrow("recallTargetTypes contains unknown resource types: session");
+ });
+
+ it("keeps deprecated recallResources as an additive compatibility switch when recallTargetTypes is unset", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ recallResources: true });
+ expect(cfg.recallTargetTypes).toEqual(["user", "agent", "resource"]);
+ });
+
+ it("does not let deprecated recallResources override explicit resource-only recallTargetTypes", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ recallResources: true,
+ recallTargetTypes: ["resource"],
+ });
+ expect(cfg.recallTargetTypes).toEqual(["resource"]);
+ });
});
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
index a2c4a50bb..324810124 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
@@ -109,6 +109,7 @@ describe("context-engine assemble()", () => {
cfgOverrides: {
autoRecall: true,
recallPreferAbstract: true,
+ recallTargetTypes: ["user"],
},
},
);
@@ -170,6 +171,7 @@ describe("context-engine assemble()", () => {
cfgOverrides: {
autoRecall: true,
recallPreferAbstract: true,
+ recallTargetTypes: ["user"],
},
},
);
diff --git a/examples/openclaw-plugin/tests/ut/recall-trace.test.ts b/examples/openclaw-plugin/tests/ut/recall-trace.test.ts
index a8e8e6b1f..bed6eb097 100644
--- a/examples/openclaw-plugin/tests/ut/recall-trace.test.ts
+++ b/examples/openclaw-plugin/tests/ut/recall-trace.test.ts
@@ -86,30 +86,24 @@ describe("resolveRecallSearchPlan()", () => {
expect(plan.resourceTypes).toEqual(["user", "agent"]);
});
- it("builds session/user/agent searches only when explicitly requested", () => {
- const plan = resolveRecallSearchPlan(["resource", "session", "user", "agent"], {
+ it("builds resource/user/agent searches only when explicitly requested", () => {
+ const plan = resolveRecallSearchPlan(["resource", "user", "agent"], {
ovSessionId: "ov-session-1",
agentId: "agent-1",
});
expect(plan.searches).toEqual([
{ resourceType: "resource", targetUri: "viking://resources" },
- { resourceType: "session", targetUri: "viking://session/ov-session-1/history" },
{ resourceType: "user", targetUri: "viking://user/memories" },
{ resourceType: "agent", targetUri: "viking://agent/memories" },
]);
+ expect(plan.skipped).toEqual([]);
});
- it("skips session search without failing the whole plan when ovSessionId is missing", () => {
- const plan = resolveRecallSearchPlan(["session", "user"], { agentId: "agent-1" });
-
- expect(plan.searches).toEqual([
- { resourceType: "user", targetUri: "viking://user/memories" },
- ]);
- expect(plan.skipped).toEqual([
- { resourceType: "session", reason: "missing_session" },
- ]);
- expect(plan.resourceTypes).toEqual(["session", "user"]);
+ it("rejects session as a semantic recall target", () => {
+ expect(() => resolveRecallSearchPlan(["session", "user"], { agentId: "agent-1" })).toThrow(
+ "invalid resourceTypes: session",
+ );
});
});
diff --git a/examples/openclaw-plugin/tests/ut/setup-command.test.ts b/examples/openclaw-plugin/tests/ut/setup-command.test.ts
index 8f39ce138..3ddbc6e53 100644
--- a/examples/openclaw-plugin/tests/ut/setup-command.test.ts
+++ b/examples/openclaw-plugin/tests/ut/setup-command.test.ts
@@ -17,3 +17,25 @@ describe("openviking setup agent prefix validation", () => {
},
);
});
+
+describe("openviking setup recall target type parsing", () => {
+ it("normalizes comma-separated target types", () => {
+ expect(__test__.normalizeSetupRecallTargetTypes("resource, user\nagent, user")).toEqual([
+ "resource",
+ "user",
+ "agent",
+ ]);
+ });
+
+ it("rejects unknown target types", () => {
+ expect(() => __test__.normalizeSetupRecallTargetTypes("user,project")).toThrow(
+ "unknown resource types: project",
+ );
+ });
+
+ it("rejects session as a recall target type", () => {
+ expect(() => __test__.normalizeSetupRecallTargetTypes("session")).toThrow(
+ "unknown resource types: session",
+ );
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.ts
index acf102aa6..182082481 100644
--- a/examples/openclaw-plugin/tests/ut/tools.test.ts
+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts
@@ -177,6 +177,7 @@ describe("Tool: memory_recall (registration)", () => {
expect(props).toHaveProperty("limit");
expect(props).toHaveProperty("scoreThreshold");
expect(props).toHaveProperty("targetUri");
+ expect(props).toHaveProperty("resourceTypes");
});
it("fills L2 content and filters explicit recall results like auto-recall", async () => {
@@ -239,7 +240,13 @@ describe("Tool: memory_recall (registration)", () => {
const findCalls = fetchMock.mock.calls.filter(([calledUrl]) =>
String(calledUrl).includes("/api/v1/search/find")
);
- expect(findCalls).toHaveLength(1);
+ expect(findCalls).toHaveLength(2);
+ const targetUris = findCalls.map(([, init]) =>
+ JSON.parse(String((init as RequestInit).body)).target_uri,
+ );
+ expect(targetUris).toHaveLength(2);
+ expect(targetUris).toContain("viking://agent/memories");
+ expect(targetUris.some((uri) => String(uri).endsWith("/memories") && String(uri).includes("viking://user/"))).toBe(true);
for (const [, init] of findCalls) {
const body = JSON.parse(String((init as RequestInit).body));
expect(body.limit).toBe(20);
@@ -276,12 +283,60 @@ describe("Tool: memory_recall (registration)", () => {
const findBodies = fetchMock.mock.calls
.filter(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))
.map((call) => JSON.parse(String((call[1] as RequestInit).body)));
- expect(findBodies).toHaveLength(1);
+ expect(findBodies).toHaveLength(2);
for (const body of findBodies) {
expect(body.peer_id).toBe("wx_user-01_abc");
}
});
+ it("lets memory_recall override default targets with resourceTypes", async () => {
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ const requestUrl = new URL(url);
+ if (requestUrl.pathname === "/api/v1/system/status") {
+ return okResponse({ user: "default" });
+ }
+ if (requestUrl.pathname === "/api/v1/search/find") {
+ const body = JSON.parse(String(init?.body ?? "{}"));
+ expect(body.target_uri).toBe("viking://resources");
+ return okResponse({
+ memories: [],
+ resources: [
+ makeMemory({
+ uri: "viking://resources/project/design.md",
+ abstract: "Resource design note",
+ score: 0.9,
+ }),
+ ],
+ skills: [],
+ total: 1,
+ });
+ }
+ if (requestUrl.pathname === "/api/v1/content/read") {
+ return okResponse("Resource design full text");
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { factoryTools, api } = setupPlugin(undefined, {
+ recallLimit: 1,
+ recallScoreThreshold: 0.2,
+ });
+ contextEnginePlugin.register(api as any);
+ const tool = factoryTools.get("memory_recall")!({ sessionId: "test-session" });
+
+ const result = await tool.execute("tc-resource-recall", {
+ query: "design note",
+ resourceTypes: ["resource"],
+ }) as ToolResult;
+
+ expect(result.content[0]!.text).toContain("Resource design full text");
+ const findCalls = fetchMock.mock.calls.filter(([calledUrl]) =>
+ String(calledUrl).includes("/api/v1/search/find")
+ );
+ expect(findCalls).toHaveLength(1);
+ });
+
it("applies recallMaxInjectedChars to explicit memory_recall output", async () => {
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
const requestUrl = new URL(url);
@@ -1277,7 +1332,7 @@ describe("Tool: ov_search (behavioral)", () => {
expect(entry.trigger.queryTruncated).toBe(true);
});
- it("records explicit memory_recall traces without duplicate default searches", async () => {
+ it("records explicit memory_recall traces without duplicate default target searches", async () => {
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
const requestUrl = new URL(url);
if (requestUrl.pathname === "/api/v1/system/status") {
@@ -1311,8 +1366,11 @@ describe("Tool: ov_search (behavioral)", () => {
const findBodies = fetchMock.mock.calls
.filter(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))
.map(([, fetchInit]) => JSON.parse(String((fetchInit as RequestInit).body)));
- expect(findBodies).toHaveLength(1);
- expect(findBodies[0]!.target_uri).toBe("viking://user/default/memories");
+ expect(findBodies).toHaveLength(2);
+ const targetUris = findBodies.map((body) => body.target_uri);
+ expect(new Set(targetUris).size).toBe(2);
+ expect(targetUris).toContain("viking://agent/memories");
+ expect(targetUris).toContain("viking://user/default/memories");
const trace = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });
const result = await trace.execute("tc-trace", { source: "memory_recall", limit: 10 }) as ToolResult;
@@ -1320,13 +1378,12 @@ describe("Tool: ov_search (behavioral)", () => {
expect(result.content[0]!.text).toContain("backend preference");
const entry = (result.details.entries as any[])[0];
- expect(entry.resourceTypes).toEqual(["user"]);
- expect(entry.searches).toHaveLength(1);
- expect(entry.searches[0]).toMatchObject({
- resourceType: "user",
- targetUriResolved: "viking://user/memories",
- total: 1,
- });
+ expect(entry.resourceTypes).toEqual(["user", "agent"]);
+ expect(entry.searches).toHaveLength(2);
+ expect(entry.searches.map((search: any) => search.targetUriResolved)).toEqual([
+ "viking://user/memories",
+ "viking://agent/memories",
+ ]);
expect(entry.selected).toEqual(expect.arrayContaining([
expect.objectContaining({
uri: "viking://user/default/memories/backend-pref",