Skip to content

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

feat(openclaw): assemble auto-recall context server-side (#4450)

starslittle4e3770d4f2b2
diff --git a/examples/memory-plugin-shared/sync.mjs b/examples/memory-plugin-shared/sync.mjs
index b00ecab16..cef22ca73 100644
--- a/examples/memory-plugin-shared/sync.mjs
+++ b/examples/memory-plugin-shared/sync.mjs
@@ -32,6 +32,10 @@ const AGENT_PLUGINS_SHARED_FILES = [
"mcp-proxy-config.mjs",
"workspace-peer.mjs",
];
+const OPENCLAW_SHARED_FILES = [
+ "recall-compress-core.mjs",
+ "recall-core.mjs",
+];
const TARGETS = [
{ dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: DOCTOR_SHARED_FILES },
{ dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: DOCTOR_SHARED_FILES },
@@ -40,6 +44,7 @@ const TARGETS = [
{ dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },
{ dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") , files: ZCODE_SHARED_FILES },
{ dir: join(ROOT, "agent-plugins", "servers", "shared"), files: AGENT_PLUGINS_SHARED_FILES },
+ { dir: join(ROOT, "examples", "openclaw-plugin", "shared"), files: OPENCLAW_SHARED_FILES },
];
const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";
diff --git a/examples/memory-plugin-shared/sync.test.mjs b/examples/memory-plugin-shared/sync.test.mjs
index 58ee3c51e..27f5c4894 100644
--- a/examples/memory-plugin-shared/sync.test.mjs
+++ b/examples/memory-plugin-shared/sync.test.mjs
@@ -27,6 +27,10 @@ const AGENT_PLUGINS_SHARED_FILES = [
"mcp-proxy-core.mjs",
"workspace-peer.mjs",
];
+const OPENCLAW_SHARED_FILES = [
+ "recall-compress-core.mjs",
+ "recall-core.mjs",
+];
const TARGETS = [
{ dir: join(ROOT, "examples", "claude-code-memory-plugin", "scripts", "shared"), files: DOCTOR_SHARED_FILES },
{ dir: join(ROOT, "examples", "codex-memory-plugin", "scripts", "shared"), files: DOCTOR_SHARED_FILES },
@@ -35,6 +39,7 @@ const TARGETS = [
{ dir: join(ROOT, "examples", "pi-coding-agent-extension", "shared"), files: HARNESS_SHARED_FILES },
{ dir: join(ROOT, "examples", "zcode-memory-plugin", "scripts", "shared") , files: ZCODE_SHARED_FILES },
{ dir: join(ROOT, "agent-plugins", "servers", "shared"), files: AGENT_PLUGINS_SHARED_FILES },
+ { dir: join(ROOT, "examples", "openclaw-plugin", "shared"), files: OPENCLAW_SHARED_FILES },
];
const GENERATED_HEADER = "// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.\n";
const SKILLS_DIR = join(ROOT, "examples", "skills");
diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.md
index 3d1e3352b..fbcab2878 100644
--- a/examples/openclaw-plugin/README.md
+++ b/examples/openclaw-plugin/README.md
@@ -164,16 +164,9 @@ During recall, the plugin:
1. Extracts query text from the latest user message.
2. Resolves the agent routing for the current `sessionId/sessionKey`.
3. Runs a quick availability precheck so model requests do not stall when OpenViking is unavailable.
-4. Queries the configured `recallTargetTypes` (`user,agent` by default; optionally `resource`; use `ov_archive_search` and `ov_archive_expand` for session history).
-5. Deduplicates, threshold-filters, reranks, and trims the results under a token budget.
-6. Prepends the selected memories as a `## Long-term Memories` section inside `<openviking-context>` to the current user message; it does not append a standalone synthetic user message.
-
-The reranking logic is not pure vector-score sorting. The current implementation also considers:
-
-- whether a result is a leaf memory with `level == 2`
-- whether it looks like a preference memory
-- whether it looks like an event memory
-- lexical overlap with the current query
+4. Sends one session-aware context search for the configured `recallTargetTypes` (`user,agent` by default; optionally `resource`; use `ov_archive_search` and `ov_archive_expand` to inspect raw session history).
+5. Lets OpenViking expand the query from session history, filter and rank candidates, apply cross-turn deduplication, select detail tiers, and assemble the result under the injection budget.
+6. Prepends the server-rendered context inside `<relevant-memories>` to the current user message; it does not append a standalone synthetic user message.
## Session Lifecycle
diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.md
index 3ad96c963..4c6ee0ed0 100644
--- a/examples/openclaw-plugin/README_CN.md
+++ b/examples/openclaw-plugin/README_CN.md
@@ -192,16 +192,9 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking
1. 从最后一条 user message 提取查询文本。
2. 基于当前 `sessionId/sessionKey` 解析本轮的 agent 路由。
3. 先做一次快速可用性检查,避免在 OpenViking 不可用时拖慢模型请求。
-4. 检索配置的 `recallTargetTypes`(默认 `user,agent`;可选 `resource`;session 历史请使用 `ov_archive_search` 和 `ov_archive_expand`)。
-5. 在插件侧做去重、阈值筛选、重排和 token budget 裁剪。
-6. 把最终记忆块以 `<relevant-memories>` 形式 prepend 到当前 user message;不会追加独立 synthetic user message。
-
-这里的重排不是单纯依赖向量分数。当前实现还会额外考虑:
-
-- 是否是 `level == 2` 的叶子记忆
-- 是否属于偏好类记忆
-- 是否属于事件类记忆
-- 与当前 query 的词面重合度
+4. 按配置的 `recallTargetTypes` 发起一次带 session 上下文的 context search(默认 `user,agent`;可选 `resource`;原始 session 历史仍可用 `ov_archive_search` 和 `ov_archive_expand` 查看)。
+5. 由 OpenViking 服务端结合 session 历史扩展查询,完成候选过滤与排序、跨轮去重、内容层级选择和预算内组装。
+6. 把服务端渲染的上下文以 `<relevant-memories>` 形式 prepend 到当前 user message;不会追加独立 synthetic user message。
## Session 生命周期
diff --git a/examples/openclaw-plugin/auto-recall.ts b/examples/openclaw-plugin/auto-recall.ts
index e6143d25a..71505ad56 100644
--- a/examples/openclaw-plugin/auto-recall.ts
+++ b/examples/openclaw-plugin/auto-recall.ts
@@ -1,12 +1,7 @@
-import type { FindResult, FindResultItem, OpenVikingClient } from "./client.js";
+import type { FindResultItem, OpenVikingClient, SearchContextEntry } from "./client.js";
import type { MemoryOpenVikingConfig } from "./config.js";
import type { EffectiveQueryConfig } from "./query-config.js";
-import {
- pickMemoriesForInjection,
- postProcessMemories,
- summarizeInjectionMemories,
- toJsonLog,
-} from "./memory-ranking.js";
+import { toJsonLog } from "./memory-ranking.js";
import { quickRecallPrecheck, withTimeout } from "./process-manager.js";
import {
resolveRecallSearchPlan,
@@ -20,6 +15,8 @@ import { sanitizeUserTextForCapture } from "./text-utils.js";
import { estimateTextTokens } from "./token-estimator.js";
const RECALL_QUERY_MAX_CHARS = 4_000;
+const AUTO_RECALL_DEDUP_TURNS = 5;
+const LEGACY_CHARS_PER_TOKEN = 4;
export const AUTO_RECALL_SOURCE_MARKER = "Source: openviking-auto-recall";
type Logger = {
@@ -231,16 +228,26 @@ function preview(value: string | undefined, maxChars: number): string | undefine
return trimmed.length > maxChars ? trimmed.slice(0, maxChars) : trimmed;
}
-function toTraceResults(items: FindResultItem[], resourceType: RecallResourceType): RecallTraceResult[] {
- return items.map((item) => ({
- uri: item.uri,
+function traceResourceType(entry: SearchContextEntry): RecallResourceType {
+ if (entry.category === "resources" || entry.uri.startsWith("viking://resources")) {
+ return "resource";
+ }
+ if (entry.origin === "actor_peer") {
+ return "agent";
+ }
+ return "user";
+}
+
+function toTraceResult(entry: SearchContextEntry): RecallTraceResult {
+ const resourceType = traceResourceType(entry);
+ return {
+ uri: entry.uri,
resourceType,
- category: item.category,
- score: item.score,
- level: item.level,
- abstractPreview: preview(item.abstract ?? item.overview, 240),
+ category: entry.category,
+ score: entry.score,
+ abstractPreview: preview(entry.text, 240),
resultType: resourceType === "resource" ? "resource" : "memory",
- }));
+ };
}
function boundTraceQuery(query: string, maxChars: number): { query: string; queryTruncated?: boolean } {
@@ -340,7 +347,6 @@ export async function buildAutoRecallContext(params: {
return withTimeout(
(async () => {
- const candidateLimit = queryConfig?.candidateLimit ?? Math.max(cfg.recallLimit * 4, 20);
const scoreThreshold = queryConfig?.scoreThreshold ?? cfg.recallScoreThreshold;
const recallLimit = queryConfig?.recallLimit ?? cfg.recallLimit;
const maxInjectedChars = queryConfig?.maxInjectedChars ?? cfg.recallMaxInjectedChars;
@@ -349,98 +355,88 @@ export async function buildAutoRecallContext(params: {
ovSessionId: params.ovSessionId,
agentId,
});
- const traceSearches: RecallTraceEntry["searches"] = searchPlan.skipped.map((skipped) => ({
- resourceType: skipped.resourceType,
- limit: candidateLimit,
- scoreThreshold: 0,
- durationMs: 0,
- total: 0,
- results: [],
- error: skipped.reason,
- }));
- const autoRecallPromises: Promise<{
- resourceType: RecallResourceType;
- targetUri?: string;
- result?: FindResult;
- durationMs: number;
- }>[] = searchPlan.searches.map(async (search) => {
- const start = Date.now();
- const result = await client.find(queryText, {
- targetUri: search.targetUri,
- limit: candidateLimit,
- scoreThreshold: 0,
- contextType: search.contextType,
+ const contextTypes = [...new Set(searchPlan.searches.map((search) => search.contextType))];
+ const maxTokens = Math.min(
+ 32_000,
+ Math.max(64, Math.round(maxInjectedChars / LEGACY_CHARS_PER_TOKEN)),
+ );
+ const startedAt = Date.now();
+ let contextResult: Awaited<ReturnType<OpenVikingClient["searchContext"]>> | undefined;
+ let requestError: unknown;
+
+ try {
+ contextResult = await client.searchContext(queryText, {
+ sessionId: params.ovSessionId,
+ limit: recallLimit,
+ scoreThreshold,
+ contextType: contextTypes.length === 1 ? contextTypes[0] : contextTypes,
+ queryExpansion: "auto",
+ maxTokens,
+ detail: recallPreferAbstract ? "abstract" : undefined,
+ dedupTurns: params.ovSessionId ? AUTO_RECALL_DEDUP_TURNS : undefined,
+ peerScope: "actor",
actorPeerId,
+ requestTimeoutMs: cfg.autoRecallTimeoutMs,
});
- return {
- resourceType: search.resourceType,
- targetUri: search.targetUri,
- result,
- durationMs: Date.now() - start,
- };
- });
- const autoRecallSettled = await Promise.allSettled(autoRecallPromises);
-
- const allMemories: FindResultItem[] = [];
- for (const s of autoRecallSettled) {
- if (s.status === "fulfilled") {
- const result = s.value.result ?? {};
- const memories = result.memories ?? [];
- const resources = result.resources ?? [];
- allMemories.push(...memories, ...resources);
- traceSearches.push({
- resourceType: s.value.resourceType,
- targetUriInput: s.value.targetUri,
- limit: candidateLimit,
- scoreThreshold: 0,
- durationMs: s.value.durationMs,
- total: result.total ?? memories.length + resources.length + (result.skills?.length ?? 0),
- results: [
- ...toTraceResults(memories, s.value.resourceType),
- ...toTraceResults(resources, "resource"),
- ...(result.skills ?? []).map((item): RecallTraceResult => ({
- uri: item.uri,
- resourceType: s.value.resourceType,
- category: item.category,
- score: item.score,
- level: item.level,
- abstractPreview: preview(item.abstract ?? item.overview, 240),
- resultType: "skill",
- })),
- ].slice(0, cfg.traceRecallMaxResultsPerSearch),
- });
- } else {
- logger.warn?.(`openviking: auto-recall search failed: ${String(s.reason)}`);
- const failedIndex = traceSearches.length;
- const search = searchPlan.searches[failedIndex - searchPlan.skipped.length];
- traceSearches.push({
- resourceType: search?.resourceType ?? "user",
- targetUriInput: search?.targetUri,
- limit: candidateLimit,
- scoreThreshold: 0,
- durationMs: 0,
- total: 0,
- results: [],
- error: String(s.reason),
- });
- }
+ } catch (error) {
+ requestError = error;
}
- const uniqueMemories = allMemories.filter((memory, index, self) =>
- index === self.findIndex((m) => m.uri === memory.uri)
- );
- const leafOnly = uniqueMemories.filter((m) => !m.level || m.level === 2);
- const processed = postProcessMemories(leafOnly, {
- limit: candidateLimit,
- scoreThreshold,
- });
- const memories = pickMemoriesForInjection(processed, recallLimit, queryText, scoreThreshold, queryConfig ? {
- weights: queryConfig.rankingWeights,
- categoryWeights: queryConfig.categoryWeights,
- resourceTypeWeights: queryConfig.resourceTypeWeights,
- } : undefined);
+ const durationMs = Date.now() - startedAt;
+ const entries = (contextResult?.entries ?? []).filter((entry) => Boolean(entry.uri));
+ const rawRetrievalErrors = contextResult?.stats?.retrieval_errors;
+ const retrievalErrors = Array.isArray(rawRetrievalErrors)
+ ? rawRetrievalErrors.map((error) => String(error))
+ : [];
+ const searchError = requestError
+ ? String(requestError)
+ : retrievalErrors.length > 0
+ ? retrievalErrors.join("; ")
+ : undefined;
+
+ if (searchError) {
+ logger.warn?.(`openviking: auto-recall context search failed: ${searchError}`);
+ }
- const recordTrace = async (injectedMemories: FindResultItem[], injectedCount: number, estimatedTokens?: number) => {
+ const traceSearches: RecallTraceEntry["searches"] = [
+ ...searchPlan.skipped.map((skipped) => ({
+ resourceType: skipped.resourceType,
+ limit: recallLimit,
+ scoreThreshold,
+ durationMs: 0,
+ total: 0,
+ results: [],
+ error: skipped.reason,
+ })),
+ ...searchPlan.searches.map((search) => {
+ const matchingEntries = entries.filter((entry) =>
+ search.contextType === "resource"
+ ? traceResourceType(entry) === "resource"
+ : traceResourceType(entry) !== "resource"
+ );
+ return {
+ resourceType: search.resourceType,
+ contextType: search.contextType,
+ limit: recallLimit,
+ scoreThreshold,
+ durationMs,
+ total: matchingEntries.length,
+ results: matchingEntries
+ .map(toTraceResult)
+ .slice(0, cfg.traceRecallMaxResultsPerSearch),
+ error: searchError,
+ };
+ }),
+ ];
+
+ const candidateCount = typeof contextResult?.stats?.candidates === "number"
+ ? contextResult.stats.candidates
+ : entries.length;
+ const recordTrace = async (
+ injectedEntries: SearchContextEntry[],
+ injectedCount: number,
+ estimatedTokens?: number,
+ ) => {
const entry: RecallTraceEntry = {
schemaVersion: "1.0",
traceId: newTraceId(),
@@ -459,17 +455,17 @@ export async function buildAutoRecallContext(params: {
queryTruncated: params.queryTruncated || queryText.length > cfg.traceRecallQueryMaxChars,
},
searches: traceSearches,
- selected: injectedMemories.map((memory) => ({
- uri: memory.uri,
- resourceType: memory.uri.startsWith("viking://resources") ? "resource" : undefined,
- category: memory.category,
- score: memory.score,
- abstractPreview: preview(memory.abstract ?? memory.overview, cfg.traceRecallPreviewChars),
+ selected: injectedEntries.map((contextEntry) => ({
+ uri: contextEntry.uri,
+ resourceType: traceResourceType(contextEntry),
+ category: contextEntry.category,
+ score: contextEntry.score,
+ abstractPreview: preview(contextEntry.text, cfg.traceRecallPreviewChars),
injected: true,
})),
stats: {
- candidateCount: allMemories.length,
- selectedCount: injectedMemories.length,
+ candidateCount,
+ selectedCount: injectedEntries.length,
injectedCount,
estimatedTokens,
},
@@ -478,39 +474,34 @@ export async function buildAutoRecallContext(params: {
params.traceRecorder?.record(entry);
};
- if (memories.length === 0) {
- await recordTrace([], 0, 0);
- return { memoryCount: 0, estimatedTokens: 0 };
- }
-
- const { lines: memoryLines, estimatedTokens } = await buildMemoryLinesWithBudget(
- memories,
- (uri) => client.read(uri, actorPeerId),
- {
- recallPreferAbstract,
- recallMaxInjectedChars: maxInjectedChars,
- includeUri: true,
- },
- );
-
- if (memoryLines.length === 0) {
- verbose?.(
- `openviking: skipping auto-recall injection; no complete memories fit maxInjectedChars=${maxInjectedChars}`,
- );
+ const rendered = contextResult?.rendered?.trim() ?? "";
+ if (requestError || entries.length === 0 || !rendered) {
await recordTrace([], 0, 0);
return { memoryCount: 0, estimatedTokens: 0 };
}
- const block = buildRecallContextBlock(memoryLines);
+ const usedTokens = contextResult?.stats?.used_tokens;
+ const estimatedTokens = typeof usedTokens === "number" && Number.isFinite(usedTokens)
+ ? Math.max(0, Math.ceil(usedTokens))
+ : estimateTokenCount(rendered);
+ const block = buildRecallContextBlock([rendered]);
verbose?.(
- `openviking: injecting ${memoryLines.length} memories (${block.length} chars, ~${estimatedTokens} tokens, maxInjectedChars=${maxInjectedChars})`,
+ `openviking: injecting ${entries.length} memories (${block.length} chars, ~${estimatedTokens} tokens, serverMaxTokens=${maxTokens})`,
);
verbose?.(
- `openviking: inject-detail ${toJsonLog({ count: memories.length, memories: summarizeInjectionMemories(memories) })}`,
+ `openviking: inject-detail ${toJsonLog({
+ count: entries.length,
+ entries: entries.map((contextEntry) => ({
+ uri: contextEntry.uri,
+ category: contextEntry.category,
+ score: contextEntry.score,
+ detail: contextEntry.detail,
+ })),
+ })}`,
);
- await recordTrace(memories.slice(0, memoryLines.length), memoryLines.length, estimatedTokens);
- return { block, memoryCount: memoryLines.length, estimatedTokens };
+ await recordTrace(entries, entries.length, estimatedTokens);
+ return { block, memoryCount: entries.length, estimatedTokens };
})(),
cfg.autoRecallTimeoutMs,
"openviking: auto-recall search timeout",
diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.ts
index 84e354e81..bfc99af2a 100644
--- a/examples/openclaw-plugin/client.ts
+++ b/examples/openclaw-plugin/client.ts
@@ -12,6 +12,11 @@ import {
defaultResourcePackager,
type ResourcePackager,
} from "./adapters/resource-packager.js";
+import {
+ buildContextSearchBody,
+ contextRequestTimeoutMs,
+ normalizeContextEntry,
+} from "./shared/recall-core.mjs";
export type FindResultItem = {
uri: string;
@@ -30,6 +35,36 @@ export type FindResult = {
total?: number;
};
+export type SearchContextEntry = {
+ uri: string;
+ category?: string;
+ score?: number;
+ detail?: string;
+ text?: string;
+ origin?: string;
+};
+
+export type SearchContextResult = {
+ entries?: SearchContextEntry[];
+ rendered?: string;
+ digest?: string;
+ stats?: Record<string, unknown>;
+};
+
+export type SearchContextOptions = {
+ sessionId?: string;
+ limit?: number;
+ scoreThreshold?: number;
+ contextType?: string | string[];
+ queryExpansion?: "off" | "auto";
+ maxTokens?: number;
+ detail?: "abstract" | "overview" | "full";
+ dedupTurns?: number;
+ peerScope?: "actor" | "all";
+ actorPeerId?: string;
+ requestTimeoutMs?: number;
+};
+
export type FsListEntry = string | Record<string, unknown>;
export type FsListResult = FsListEntry[];
@@ -488,6 +523,66 @@ export class OpenVikingClient {
}, undefined, actorPeerId);
}
+ async searchContext(
+ query: string,
+ options: SearchContextOptions = {},
+ ): Promise<SearchContextResult> {
+ const contractConfig = {
+ recallLimit: options.limit,
+ recallLimitConfigured: options.limit !== undefined,
+ recallMaxTokens: options.maxTokens,
+ recallMaxTokensConfigured: options.maxTokens !== undefined,
+ scoreThreshold: options.scoreThreshold,
+ recallQueryExpansion: options.queryExpansion,
+ recallQueryExpansionConfigured: options.queryExpansion !== undefined,
+ recallDedupTurns: options.dedupTurns,
+ recallPeerScope: options.peerScope,
+ recallContextTimeoutMs: options.requestTimeoutMs,
+ timeoutMs: this.timeoutMs,
+ };
+ const body = {
+ ...buildContextSearchBody(contractConfig, { sessionId: options.sessionId }),
+ query,
+ ...(options.contextType !== undefined ? { context_type: options.contextType } : {}),
+ ...(options.detail !== undefined ? { detail: options.detail } : {}),
+ };
+ const requestTimeoutMs = contextRequestTimeoutMs(contractConfig, body);
+ const actorPeerId = this.resolveActorPeerHeader(options.actorPeerId);
+ const tenantHeaders = this.resolveTenantHeaders();
+ this.routingDebugLog?.(
+ `openviking: context search POST ${this.baseUrl}/api/v1/search/search ` +
+ JSON.stringify({
+ X_OpenViking_Account: tenantHeaders.accountId ?? null,
+ X_OpenViking_User: tenantHeaders.userId ?? null,
+ X_OpenViking_Actor_Peer: actorPeerId ?? null,
+ session_id: body.session_id ?? null,
+ query:
+ query.length > 4000
+ ? `${query.slice(0, 4000)}…(+${query.length - 4000} more chars)`
+ : query,
+ purpose: body.purpose,
+ quotas: body.quotas ?? null,
+ score_threshold: body.score_threshold,
+ context_type: body.context_type ?? null,
+ query_expansion: body.query_expansion ?? null,
+ max_tokens: body.max_tokens ?? null,
+ detail: body.detail ?? null,
+ dedup_turns: body.dedup_turns ?? 0,
+ peer_scope: body.peer_scope ?? null,
+ }),
+ );
+ const result = await this.request<SearchContextResult>("/api/v1/search/search", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }, requestTimeoutMs, actorPeerId);
+ return {
+ ...result,
+ entries: Array.isArray(result.entries)
+ ? result.entries.map((entry) => ({ ...entry, ...normalizeContextEntry(entry) }))
+ : result.entries,
+ };
+ }
+
async read(uri: string, actorPeerId?: string): Promise<string> {
return this.request<string>(
`/api/v1/content/read?uri=${encodeURIComponent(uri)}`,
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index fe0cc01e9..fa4c2fdac 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -45,13 +45,13 @@ export type MemoryOpenVikingConfig = {
captureMode?: "semantic" | "keyword";
captureMaxLength?: number;
autoRecall?: boolean;
- /** Outer time budget for the whole auto-recall flow, including search, ranking, and reads. */
+ /** Outer time budget for the whole server-assembled auto-recall flow. */
autoRecallTimeoutMs?: number;
/** Include resources in auto-recall and default memory_recall search. Default false. */
recallResources?: boolean;
recallLimit?: number;
recallScoreThreshold?: number;
- /** Maximum total characters injected by auto-recall. */
+ /** Legacy character budget, converted to the server context token budget. */
recallMaxInjectedChars?: number;
/** @deprecated Auto-recall no longer truncates individual memories. */
recallMaxContentChars?: number;
@@ -140,7 +140,9 @@ const DEFAULT_TARGET_URI = "viking://~/memories";
const DEFAULT_TIMEOUT_MS = 15000;
const DEFAULT_CAPTURE_MODE = "semantic";
const DEFAULT_CAPTURE_MAX_LENGTH = 24000;
-const DEFAULT_AUTO_RECALL_TIMEOUT_MS = 5000;
+// Session-aware context search may spend up to 5 seconds on query expansion
+// before returning its server-side fallback, so leave headroom for retrieval.
+const DEFAULT_AUTO_RECALL_TIMEOUT_MS = 15000;
const DEFAULT_RECALL_LIMIT = 6;
const DEFAULT_RECALL_SCORE_THRESHOLD = 0.15;
const DEFAULT_RECALL_MAX_CONTENT_CHARS = 5000;
@@ -843,7 +845,7 @@ export const memoryOpenVikingConfigSchema = {
label: "Auto-Recall Timeout (ms)",
placeholder: String(DEFAULT_AUTO_RECALL_TIMEOUT_MS),
advanced: true,
- help: "Outer time budget for the whole auto-recall flow, including search, ranking, and memory reads.",
+ help: "Outer time budget for the server-assembled context search, including session-aware query expansion.",
},
recallResources: {
label: "Recall Resources",
@@ -870,7 +872,7 @@ export const memoryOpenVikingConfigSchema = {
label: "Recall Max Injected Chars",
placeholder: String(DEFAULT_RECALL_MAX_INJECTED_CHARS),
advanced: true,
- help: "Maximum total characters for auto-recall memory injection. Complete memories that do not fit are skipped, not truncated.",
+ help: "Legacy auto-recall character budget. It is converted to the server context token budget at four characters per token.",
},
recallMaxContentChars: {
label: "Deprecated Recall Max Content Chars",
@@ -881,7 +883,7 @@ export const memoryOpenVikingConfigSchema = {
recallPreferAbstract: {
label: "Recall Prefer Abstract",
advanced: true,
- help: "Use memory abstract instead of fetching full content when abstract is available. Reduces token usage.",
+ help: "Pin server-assembled auto-recall entries to abstract detail. When disabled, the server chooses each category's default detail tier.",
},
recallTokenBudget: {
label: "Deprecated Recall Token Budget",
diff --git a/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md b/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md
index 8ee126179..a44e3e2c4 100644
--- a/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md
+++ b/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md
@@ -48,7 +48,7 @@
| `client.ts` | OpenViking HTTP Client;统一添加认证/租户/agent header;封装 session、search、resource、skill、tool-result API |
| `config.ts` | 插件配置 schema、默认值、环境变量解析、peer identity routing 配置 |
| `auto-recall.ts` | 自动召回查询清洗、召回超时控制、记忆块构建与注入 |
-| `memory-ranking.ts` | 召回结果去重、阈值过滤、偏好/事件/词面重合度重排 |
+| `memory-ranking.ts` | 显式 `memory_recall` 的结果去重、阈值过滤和本地重排;自动召回由服务端组装 |
| `text-utils.ts` | 会话文本清洗、metadata/心跳/命令过滤、增量 turn 消息提取、bypass session pattern |
| `commands/setup.ts` | setup/status CLI,配置写入、health check、root/user key 探测、slot 激活 |
| `session-transcript-repair.ts` | 修复 toolCall/toolResult 配对、去重、孤儿 tool result 等 transcript 结构问题 |
@@ -104,12 +104,12 @@ transformContext auto recall 流程:
1. 从最新 user message 提取查询文本。
2. 清洗 metadata、心跳、已注入记忆块等噪音。
3. 快速 precheck,OpenViking 不可用时跳过召回,避免拖慢模型请求。
-4. 按 `recallTargetTypes` 并行搜索召回目标;默认搜索 `viking://user/memories`、`agent recall target`,显式设为 `resource` 时只搜索 `viking://resources`;旧字段 `recallResources=true` 仅在未显式配置 `recallTargetTypes` 时把 `resource` 追加到默认集合。
-5. 去重、阈值过滤、leaf 优先、偏好/时间问题 boost、词面重合度 boost。
-6. 在 `recallMaxInjectedChars` 限制内构建完整记忆行,不截断单条记忆。
-7. 用 `<relevant-memories>` 块 prepend 到最新 user message。
+4. 向 `POST /api/v1/search/search` 发送一次 `mode="context"` 请求,并把映射后的 OpenViking session ID、Actor Peer 和 `recallTargetTypes` 一并传入。
+5. 服务端结合 session 历史扩展查询,完成阈值过滤、排序、5 轮跨轮去重和内容层级选择。
+6. `recallMaxInjectedChars` 按 4 字符/token 转成服务端 `max_tokens`,由服务端在预算内生成 `rendered` 上下文。
+7. 插件只保留 `<relevant-memories>` 外层标记并 prepend 到最新 user message,不再逐条 `read` 或本地重排。
-自动召回实现入口:`context-engine.ts:1125`、`auto-recall.ts:159`。
+自动召回实现入口:`services/context-lifecycle-service.ts` 的 transformContext assemble 路径,以及 `auto-recall.ts` 的 `buildAutoRecallContext()`。
### 4.4 `afterTurn`:每轮对话后自动捕获
@@ -277,7 +277,7 @@ transformContext auto recall 流程:
| `DELETE /api/v1/fs?uri=...&recursive=...` | 删除资源/目录 | `memory_forget`、`deleteUri` | 插件默认 `recursive=false`,用于删除具体 memory URI:`client.ts:934` |
| `GET /api/v1/content/abstract?uri=...` | 读取 L0 abstract | 暂未封装 | 约 100 token 摘要,适合快速判断目录/文件主题 |
| `GET /api/v1/content/overview?uri=...` | 读取 L1 overview | 暂未封装 | 目录级结构化概览,适合介于 abstract 和 full content 之间的排查 |
-| `GET /api/v1/content/read?uri=...&offset=...&limit=...` | 读取 L2 full content | 自动召回读取 level=2 命中内容、`ov_read` | `ov_read` 暴露 `uri` 参数,未暴露 `offset/limit`:`client.ts:470` |
+| `GET /api/v1/content/read?uri=...&offset=...&limit=...` | 读取 L2 full content | 显式 `memory_recall`、`ov_read` | 自动召回的分层读取已由服务端 context search 完成;`ov_read` 暴露 `uri` 参数,未暴露 `offset/limit`。 |
#### 6.2.4 Resources / Skills Import
@@ -722,6 +722,7 @@ openclaw config get plugins.slots.contextEngine
| `captureMode` | `semantic` | `semantic` 全量候选;`keyword` 先过触发词 |
| `captureMaxLength` | `24000` | 自动捕获文本最大长度 |
| `autoRecall` | `true` | 是否回复前自动召回 |
+| `autoRecallTimeoutMs` | `15000` | 服务端组装自动召回的总超时;为 session query expansion 和检索留出预算 |
| `recallTargetTypes` | `["user","agent"]` | 自动召回和默认显式召回目标类型;可选 `resource`、`user`、`agent` |
| `recallResources` | `false` | 旧兼容开关;仅在未显式配置 `recallTargetTypes` 时追加 `resource` |
| `recallLimit` | `6` | 召回条数 |
@@ -757,27 +758,28 @@ openclaw config get plugins.slots.contextEngine
| 配置项 | 作用范围 | 默认值 | 可否写入插件配置文件 | 可否用环境变量 | 环境变量名 | 说明 |
| --- | --- | --- | --- | --- | --- | --- |
-| `baseUrl` | 所有搜索/召回请求 | `http://127.0.0.1:1933` | 是 | 是 | `OPENVIKING_BASE_URL` / `OPENVIKING_URL` | OpenViking 服务地址;所有 `find/read/grep/session` 都依赖它:`config.ts:139` |
+| `baseUrl` | 所有搜索/召回请求 | `http://127.0.0.1:1933` | 是 | 是 | `OPENVIKING_BASE_URL` / `OPENVIKING_URL` | OpenViking 服务地址;所有 context search、`find/read/grep/session` 都依赖它:`config.ts:139` |
| `apiKey` | 所有搜索/召回请求 | 空 | 是 | 是 | `OPENVIKING_API_KEY` | HTTP 认证 key;不配通常只能访问关闭认证的本地服务:`config.ts:202` |
| `accountId` | 多租户搜索路由 | 空 | 是 | 是 | `OPENVIKING_ACCOUNT_ID` | Root key / trusted 部署下显式指定 account,影响搜索命中空间:`config.ts:212` |
| `userId` | 多租户搜索路由 | 空 | 是 | 是 | `OPENVIKING_USER_ID` | Root key / trusted 部署下显式指定 user,影响 user memory 检索范围:`config.ts:216` |
| `peer_role` | session peer 归因和 actor-peer 路由 | `assistant` | 是 | 安装脚本/setup 参数支持 | `OPENVIKING_PEER_ROLE`(安装脚本写入 setup 参数) | `none` 关闭 peer 路由;`assistant` 使用 runtime agent;`person` 使用 sender 身份 |
| `peer_prefix` | assistant peer 前缀 | 空 | 是 | 间接支持 | 可通过配置值写 `${ENV}` | 非空时拼成 `<prefix>_<ctx.agentId>`,用于 assistant `peer_id` 与 `X-OpenViking-Actor-Peer` |
| `targetUri` | `memory_recall` / `memory_forget` 默认搜索范围 | `viking://user/memories` | 是 | 否 | — | 未显式传 `targetUri` 时的默认 memory 搜索位置:`config.ts:275`、`index.ts:1366` |
-| `timeoutMs` | 所有搜索/读取请求超时 | `15000` | 是 | 否 | — | 控制 `find/read/grep/session` 等 HTTP 请求超时:`config.ts:276` |
+| `timeoutMs` | 所有搜索/读取请求超时 | `15000` | 是 | 否 | — | 控制 context search、`find/read/grep/session` 等 HTTP 请求超时:`config.ts:276` |
| `autoRecall` | 自动召回总开关 | `true` | 是 | 否 | — | 关闭后插件不再在 `assemble()` 阶段自动发起 recall:`config.ts:283`、`context-engine.ts:1132` |
+| `autoRecallTimeoutMs` | 自动召回总超时 | `15000` | 是 | 否 | — | 覆盖单次服务端 context search;默认值为最长 5 秒的 session query expansion 及后续检索保留余量。显式配置的值仍会按 `1000..300000` ms 限制。 |
| `recallTargetTypes` | 自动召回 + 默认 `memory_recall` 资源类型集合 | `["user","agent"]` | 是 | 安装脚本/setup 参数支持 | `OPENVIKING_RECALL_TARGET_TYPES`(安装脚本写入 setup 参数) | 当前默认只查 `user` + `agent` 记忆。设置为 `["resource"]` 才会切成 resource-only;可组合 `resource,user,agent`:`config.ts:174`、`config.ts:360` |
| `recallResources` | 自动召回 + 默认 `memory_recall` resources 兼容开关 | `false` | 是 | 是 | `OPENVIKING_RECALL_RESOURCES` | 旧兼容字段;只有未显式配置 `recallTargetTypes` 时才把 `resource` 追加到默认 `user` + `agent`,不会覆盖显式 resource-only:`config.ts:360` |
-| `recallLimit` | 自动召回 / `memory_recall` 返回条数 | `6` | 是 | 否 | — | 最终注入或展示的 recall 条数上限;内部请求会放大到 `max(limit*4, 20)` 先召回再重排:`config.ts:285`、`auto-recall.ts:181` |
-| `recallScoreThreshold` | 自动召回 / `memory_recall` 过滤阈值 | `0.15` | 是 | 否 | — | 低于阈值的结果会在后处理阶段被丢弃:`config.ts:286`、`auto-recall.ts:218`、`index.ts:1132` |
-| `recallMaxInjectedChars` | 自动召回 / `memory_recall` 注入预算 | `4000` | 是 | 否 | — | 控制最终可注入/展示的总字符数;放不下的完整 memory 会被跳过,不再截断单条:`config.ts:252`、`auto-recall.ts:228` |
-| `recallPreferAbstract` | 自动召回读取策略 | `false` | 是 | 否 | — | 为 `true` 时优先使用 abstract,不强制回源读取 L2 全文,能减少 token 和读取耗时:`config.ts:294`、`auto-recall.ts:232` |
+| `recallLimit` | 自动召回 / `memory_recall` 返回条数 | `6` | 是 | 否 | — | 自动召回按共享 context-search 契约映射为 coding quotas;显式 `memory_recall` 仍按该值做最终选择。 |
+| `recallScoreThreshold` | 自动召回 / `memory_recall` 过滤阈值 | `0.15` | 是 | 否 | — | 自动召回交给服务端过滤;显式 `memory_recall` 保留本地后处理。 |
+| `recallMaxInjectedChars` | 自动召回 / `memory_recall` 注入预算 | `4000` | 是 | 否 | — | 自动召回按 4 字符/token 换算为服务端 `max_tokens`;显式 `memory_recall` 仍使用字符预算。 |
+| `recallPreferAbstract` | 自动召回读取策略 | `false` | 是 | 否 | — | 为 `true` 时把服务端 detail 固定为 `abstract`;否则由服务端按类别选择默认层级。 |
| `recallTokenBudget` | 自动召回预算旧别名 | 跟随 `recallMaxInjectedChars` | 是 | 否 | — | 已废弃,仅兼容旧配置;解析时会折叠为 `recallMaxInjectedChars`:`config.ts:257`、`config.ts:299` |
| `recallMaxContentChars` | 旧版单条截断兼容项 | `5000` | 是 | 否 | — | 已废弃;当前自动召回不再裁剪单条 memory 内容:`config.ts:290` |
| `captureMode` | 间接影响可搜索记忆的入库方式 | `semantic` | 是 | 否 | — | 虽然不是“搜索参数”,但它决定哪些用户内容会先被写入 session 并进入后续可检索空间:`config.ts:203`、`config.ts:278` |
| `captureMaxLength` | 间接影响可搜索记忆来源长度 | `24000` | 是 | 否 | — | 超过该长度的用户文本不会完整进入自动捕获链路:`config.ts:279` |
| `bypassSessionPatterns` | 绕过搜索/召回 | `[]` | 是 | 否 | — | 命中指定 sessionId / sessionKey 时,插件整条 OpenViking 链路直接跳过,包括 recall、store、archive search:`config.ts:311` |
-| `logFindRequests` | 搜索调试日志 | `false` | 是 | 是 | `OPENVIKING_LOG_ROUTING` / `OPENVIKING_DEBUG` | 打开后会记录 `POST /api/v1/search/find`、session 写入和 commit 路由信息,便于排查检索空间错误:`config.ts:322` |
+| `logFindRequests` | 搜索调试日志 | `false` | 是 | 是 | `OPENVIKING_LOG_ROUTING` / `OPENVIKING_DEBUG` | 打开后会记录 context search、`find`、session 写入和 commit 路由信息,便于排查检索空间错误。 |
| `enabledTools` | Agent 可见工具白名单 | `default` 工具组 | 是 | 否 | — | 支持工具名或分组:`default`、`all`、`memory`、`resource_query`、`import`、`recall_trace`、`archive`、`tool_result`。例如只保留资源查询:`["resource_query"]`。`add_resource` 即使被选中仍需 `enableAddResourceTool=true`:`config.ts:119`、`index.ts:688` |
| `disabledTools` | Agent 可见工具黑名单 | `[]`(`add_resource` 默认仍禁用) | 是 | 否 | — | 在 `enabledTools` 之后应用,支持同样的工具名或分组。例如保留默认工具但隐藏记忆相关工具:`["memory"]`,会禁用 `memory_recall` / `memory_store` / `memory_forget`:`config.ts:136`、`config.ts:268` |
@@ -899,7 +901,7 @@ export OPENVIKING_RECALL_RESOURCES=1
| 同样的 query 在不同 agent / user 命中不一致 | `accountId`、`userId`、`peer_role`、`peer_prefix` | actor peer 或租户身份不一致 |
| `/ov-search` 查不到刚导入的内容 | `baseUrl`、`apiKey`、服务端队列状态 | 导入后语义/向量处理还没完成,或连到了错误服务 |
| 明明命中结果很多,但注入数量少 | `recallLimit`、`recallMaxInjectedChars`、`recallPreferAbstract` | limit 太小或预算太紧,必要时改成 abstract 优先 |
-| 不知道插件到底向哪个 target_uri 发了检索 | `logFindRequests` | 开启后查看插件日志中的 `find POST` |
+| 不知道插件自动召回使用了哪些范围 | `logFindRequests` | 开启后查看插件日志中的 context search routing;显式检索仍记录 `find POST` |
---
@@ -1093,9 +1095,10 @@ OPENVIKING_DEBUG=1 openclaw gateway restart
| 日志/字段 | 含义 | 关键路径 |
| --- | --- | --- |
-| `openviking: find POST .../api/v1/search/find {...}` | 插件向 OpenViking 发起了语义检索 | `target_uri` / `target_uri_input` / `query` / `X_OpenViking_Agent` |
+| `openviking: context search POST .../api/v1/search/search {...}` | 自动召回向 OpenViking 发起服务端组装检索 | `purpose` / `quotas` / `session_id` / `context_type` / `query_expansion` / `max_tokens` / `peer_scope` / actor 与租户路由 |
+| `openviking: find POST .../api/v1/search/find {...}` | 显式 recall/search 工具发起底层语义检索 | `target_uri` / `target_uri_input` / `query` / `X_OpenViking_Agent` |
| `openviking: injecting N memories ...` | 插件决定向本轮 prompt 注入 N 条召回内容 | `N`、注入字符数、估算 token |
-| `openviking: inject-detail {...}` | 本轮实际注入模型的召回条目摘要 | `memories[].uri`、`category`、`score`、`abstract`、`is_leaf` |
+| `openviking: inject-detail {...}` | 本轮实际注入模型的服务端组装条目摘要 | `entries[].uri`、`category`、`score`、`detail` |
| `openviking: diag {"stage":"assemble_result"...}` | assemble 阶段是否发生自动召回 | `phase=transform_context`、`autoRecallMemoryCount` |
其中 `inject-detail` 是排查“本轮模型实际看到了哪些 OpenViking 召回内容”的首选入口。它会列出每条被注入内容的 `uri`,例如:
@@ -1199,8 +1202,9 @@ curl -sS "$OPENVIKING_BASE_URL/api/v1/content/read?uri=$(python3 -c 'import urll
| --- | --- | --- | --- |
| 健康检查 | `GET /health` | `openclaw openviking status` | 判断服务是否可达 |
| 身份/用户探测 | `GET /api/v1/system/status` | `client.getRuntimeIdentity` | 解析服务端当前 user,辅助 canonical URI 展开 |
-| 语义检索 | `POST /api/v1/search/find` | auto recall / `memory_recall` / `ov_search` | 返回 `memories[]`、`resources[]`、`skills[]`,每项含 `uri`、`score`、`abstract`、`level` |
-| 内容读取 | `GET /api/v1/content/read?uri=...` | 自动召回读取 L2 内容 / `ov_read` / 手工排查 | 根据命中的 `viking://...` URI 读取完整内容 |
+| 服务端上下文组装 | `POST /api/v1/search/search` + `mode="context"` | auto recall | 结合 session 历史返回 `entries`、`rendered` 和预算/去重统计 |
+| 语义检索 | `POST /api/v1/search/find` | `memory_recall` / `ov_search` | 返回 `memories[]`、`resources[]`、`skills[]`,每项含 `uri`、`score`、`abstract`、`level` |
+| 内容读取 | `GET /api/v1/content/read?uri=...` | `memory_recall` / `ov_read` / 手工排查 | 根据命中的 `viking://...` URI 读取完整内容 |
| 写入 session 消息 | `POST /api/v1/sessions/{sessionId}/messages` | `afterTurn` | 保存 OpenClaw 本轮 user/assistant/tool 片段 |
| 获取 session 元信息 | `GET /api/v1/sessions/{sessionId}` | `afterTurn` | 查看 `pending_tokens`、message count、commit count |
| 获取组装上下文 | `GET /api/v1/sessions/{sessionId}/context?token_budget=...` | 主 assemble / compact | 获取 archive summary + active messages |
@@ -1219,8 +1223,8 @@ curl -sS "$OPENVIKING_BASE_URL/api/v1/content/read?uri=$(python3 -c 'import urll
- 如果文档是通过 **auto recall** 进入模型上下文:看 `inject-detail` 中 `category=resource` 或 `uri` 以 `viking://resources` 开头的条目。
- 如果文档是通过 **显式工具** 进入模型上下文:看 `ov_search` 工具结果里的 `uri` 和工具 `details.resources[]`。
-- 如果只看到了 `find POST` 但没有 `injecting` / `inject-detail`:说明插件发起了检索,但最终可能因为分数阈值、去重、leaf 过滤或 `recallMaxInjectedChars` 预算没有注入模型。
-- 如果未显式配置 `recallTargetTypes`,自动召回默认只查 `viking://user/memories` 和 `agent recall target`,不会把 `viking://resources` 文档自动注入;resource-only 用 `recallTargetTypes=["resource"]`,默认记忆 + resources 用 `recallResources=true` 或 `recallTargetTypes=["user","agent","resource"]`。
+- 如果自动召回只看到了 `context search POST` 但没有 `injecting` / `inject-detail`:说明请求已发出,但服务端可能没有返回可注入内容,或发生了超时/检索错误;结合 warning、trace 和返回 stats 排查。
+- 如果未显式配置 `recallTargetTypes`,自动召回默认只查当前用户及 actor scope 内的 memory,不会把 `viking://resources` 文档自动注入;resource-only 用 `recallTargetTypes=["resource"]`,默认记忆 + resources 用 `recallResources=true` 或 `recallTargetTypes=["user","agent","resource"]`。
- 如果没查到 recall trace,先检查 `traceRecall=true` 是否已配置并重启 Gateway;`recallTargetTypes` / `recallResources` 不负责启用 trace。
- 当前插件没有单独生成“模型最终引用/采纳哪些文档”的 citation 文件;最可靠的依据是本轮注入内容、工具调用结果、OpenViking API 返回和模型回复本身。
diff --git a/examples/openclaw-plugin/docs/openviking-plugin-reference.md b/examples/openclaw-plugin/docs/openviking-plugin-reference.md
index d16d20473..a421eb43e 100644
--- a/examples/openclaw-plugin/docs/openviking-plugin-reference.md
+++ b/examples/openclaw-plugin/docs/openviking-plugin-reference.md
@@ -94,13 +94,14 @@ $OPENCLAW_STATE_DIR/openclaw.json
| 参数 | 类型 | 默认值 | 环境变量 | 说明 |
| --- | --- | --- | --- | --- |
| `autoRecall` | boolean | `true` | — | 是否在 assemble 阶段自动召回并注入上下文。 |
+| `autoRecallTimeoutMs` | number | `15000` | — | 服务端组装 context search 的总超时,范围 `1000` 到 `300000` ms。 |
| `targetUri` | string | `viking://user/memories` | — | `memory_recall` / `memory_forget` 默认搜索范围。 |
| `recallTargetTypes` | string[] | `["user", "agent"]` | — | 自动召回和默认 `memory_recall` 的搜索类型。允许 `resource`、`user`、`agent`。 |
| `recallResources` | boolean | `false` | `OPENVIKING_RECALL_RESOURCES` | 旧兼容开关;仅在未显式配置 `recallTargetTypes` 时追加 `resource`。 |
-| `recallLimit` | number | `6` | — | 最终召回条数下限为 `1`。内部请求通常放大为 `max(limit * 4, 20)`。 |
-| `recallScoreThreshold` | number | `0.15` | — | 召回结果分数阈值,范围 `0` 到 `1`。 |
-| `recallMaxInjectedChars` | number | `4000` | — | 自动召回注入模型上下文的总字符预算,范围 `100` 到 `50000`。 |
-| `recallPreferAbstract` | boolean | `false` | — | 是否优先使用 abstract,减少读取完整内容的成本。 |
+| `recallLimit` | number | `6` | — | 自动召回按共享 context-search 契约映射为 coding quotas;显式 `memory_recall` 保留本地候选扩展。 |
+| `recallScoreThreshold` | number | `0.15` | — | 自动召回交给服务端过滤;显式 `memory_recall` 保留本地后处理。范围 `0` 到 `1`。 |
+| `recallMaxInjectedChars` | number | `4000` | — | 自动召回按 4 字符/token 换算为服务端 `max_tokens`;显式召回仍使用字符预算。范围 `100` 到 `50000`。 |
+| `recallPreferAbstract` | boolean | `false` | — | 自动召回为 true 时请求服务端 abstract detail;否则由服务端按类别选择层级。 |
| `recallMaxContentChars` | number | `5000` | — | 已废弃兼容项。 |
| `recallTokenBudget` | number | 跟随 `recallMaxInjectedChars` | — | 已废弃别名;未配置 `recallMaxInjectedChars` 时可作为 fallback。 |
diff --git a/examples/openclaw-plugin/docs/openviking-recall-trace-api.md b/examples/openclaw-plugin/docs/openviking-recall-trace-api.md
index 85b0a3ac6..b5f326d3b 100644
--- a/examples/openclaw-plugin/docs/openviking-recall-trace-api.md
+++ b/examples/openclaw-plugin/docs/openviking-recall-trace-api.md
@@ -87,19 +87,19 @@ Trace 会记录实际召回范围,但召回范围本身由 `recallTargetTypes`
| `recallTargetTypes` | 默认 `['user', 'agent']` | 允许值:`resource`、`user`、`agent`;空值回退默认集合。实现见 `config.ts:176`、`recall-trace.ts:113`。 |
| `recallResources` | 默认 `false` | 兼容旧配置;仅在未显式配置 `recallTargetTypes` 时,把 `resource` 追加到默认召回集合。实现见 `config.ts:363`。 |
-目标类型会被解析为以下搜索计划:`resolveRecallSearchPlan` 实现见 `recall-trace.ts:141`。
+目标类型会被解析为 context type 搜索计划;自动召回把该计划合并进一次服务端 context search:
-| resourceType | target URI | 说明 |
+| resourceType | context type | 说明 |
| --- | --- | --- |
-| `resource` | `viking://resources` | 全局资源库。 |
-| `user` | `viking://user/memories` | 当前用户长期记忆。 |
-| `agent` | `agent recall target` | 当前 Agent 长期记忆。 |
+| `resource` | `resource` | 资源库。 |
+| `user` | `memory` | 当前用户长期记忆。 |
+| `agent` | `memory` | 当前 actor 的长期记忆;与 `user` 合并为一个 memory context type,由 actor routing 限定范围。 |
## 3. Trace 记录来源
| source | operationType | 触发方式 | selected 语义 | 关键实现 |
| --- | --- | --- | --- | --- |
-| `auto_recall` | `semantic_find` | Context Engine 在回复前自动召回 | 被注入 `<relevant-memories>` 的记忆或资源,`injected: true` | `auto-recall.ts:194`、`auto-recall.ts:313` |
+| `auto_recall` | `semantic_find`(兼容值) | Context Engine 在回复前发起服务端 context search | 服务端组装并注入 `<relevant-memories>` 的记忆或资源,`injected: true` | `auto-recall.ts` 的 `buildAutoRecallContext()` |
| `memory_recall` | `semantic_find` | Agent 调用 `memory_recall` 工具 | 工具返回给模型的记忆,通常 `injected: true` 且 `displayed: true` | `index.ts:1391`、`index.ts:1542` |
| `ov_search` | `semantic_find` | Agent 调用 `ov_search` 工具或用户执行 `/ov-search` | 搜索结果列表中展示的资源/技能/记忆,`displayed: true` | trace 记录在 `index.ts` 的 `searchOpenViking` 流程中,工具注册见 `index.ts:1371` |
| `ov_archive_search` | `archive_grep` | Agent 调用 `ov_archive_search` 工具 | 展示的归档匹配行,包含 `line`,`displayed: true` | `index.ts:1992`、`index.ts:2008` |
@@ -126,7 +126,7 @@ Trace 会记录实际召回范围,但召回范围本身由 `recallTargetTypes`
| `trigger.derivedKeywords` | string[]? | 派生关键词;归档搜索通常保存原 query。 |
| `trigger.rawUserTextPreview` | string? | 原始用户输入预览;默认不持久化。 |
| `trigger.queryTruncated` | boolean? | `query` 是否因过长被截断。 |
-| `searches` | array | 本次 trace 中每个目标 URI 的搜索明细。 |
+| `searches` | array | 本次 trace 中每个逻辑 context type 的搜索明细。 |
| `selected` | array | 最终被注入或展示的结果。 |
| `stats` | object | 候选数、选中数、注入数、估算 token。 |
@@ -139,8 +139,8 @@ Trace 会记录实际召回范围,但召回范围本身由 `recallTargetTypes`
| `resourceType` | `resource` \| `user` \| `agent` \| `archive` | 当前子搜索类型。 |
| `targetUriInput` | string? | 输入或计划中的目标 URI。 |
| `targetUriResolved` | string? | 解析后的目标 URI。 |
-| `limit` | number | 请求 limit。自动召回和显式召回通常使用 `max(recallLimit * 4, 20)`。 |
-| `scoreThreshold` | number? | 分数阈值。搜索阶段常以 `0` 取候选,后处理再过滤。 |
+| `limit` | number | 请求 limit。自动召回直接使用 `recallLimit`;显式 `memory_recall` 可先扩大候选数。 |
+| `scoreThreshold` | number? | 分数阈值。自动召回由服务端应用;显式 `memory_recall` 仍可在本地后处理。 |
| `durationMs` | number | 子搜索耗时,毫秒。 |
| `total` | number | OpenViking 返回或插件统计的候选总数。 |
| `results` | array | 候选结果摘要,最多 `traceRecallMaxResultsPerSearch` 条。 |
diff --git a/examples/openclaw-plugin/docs/openviking-runtime-query-config.md b/examples/openclaw-plugin/docs/openviking-runtime-query-config.md
index 6d0414f8c..4b698e0c4 100644
--- a/examples/openclaw-plugin/docs/openviking-runtime-query-config.md
+++ b/examples/openclaw-plugin/docs/openviking-runtime-query-config.md
@@ -34,17 +34,19 @@ For command compatibility, `--scope claw` is accepted as an alias for `peer`.
| Field | Purpose |
| --- | --- |
| `recallLimit` | Number of final recall results to inject or display. |
-| `candidateLimit` | Number of candidates requested before local ranking/filtering. |
-| `candidateMultiplier` | Multiplier used to derive candidate count from recall limit when `candidateLimit` is not explicit. |
-| `scoreThreshold` | Client-side minimum score after semantic search. |
-| `maxInjectedChars` | Character budget for automatic recall injection. |
-| `recallPreferAbstract` | Prefer abstracts over full content when injecting recalled context. |
+| `candidateLimit` | Number of candidates requested before local ranking/filtering by explicit `memory_recall`. |
+| `candidateMultiplier` | Multiplier used to derive the explicit `memory_recall` candidate count when `candidateLimit` is not explicit. |
+| `scoreThreshold` | Minimum score; auto-recall sends it to context search, while explicit `memory_recall` also applies local post-processing. |
+| `maxInjectedChars` | Injection budget; auto-recall converts it to server `max_tokens` at four characters per token. |
+| `recallPreferAbstract` | Pin server-assembled auto-recall to abstract detail; explicit `memory_recall` prefers abstracts locally. |
| `resourceTypes` | Default semantic recall target types: `user`, `agent`, `resource`. |
| `targetUri` | Force a single `viking://` target URI for search. |
| `ovSearchLimit` | Default result count for `ov_search`. |
-| `rankingWeights` | Local ranking weights, such as base score and lexical overlap. |
-| `categoryWeights` | Optional category-specific ranking adjustments. |
-| `resourceTypeWeights` | Optional resource type ranking adjustments. |
+| `rankingWeights` | Local ranking weights for explicit `memory_recall`, such as base score and lexical overlap. |
+| `categoryWeights` | Optional category-specific adjustments for explicit `memory_recall`. |
+| `resourceTypeWeights` | Optional resource-type adjustments for explicit `memory_recall`. |
+
+Automatic recall uses one session-aware context search and consumes `recallLimit`, `scoreThreshold`, `maxInjectedChars`, `recallPreferAbstract`, and `resourceTypes`. Candidate expansion and local ranking-weight fields remain available to explicit `memory_recall`, but no longer alter automatic recall assembly.
Session history is not a semantic recall target. Use `ov_archive_search` and `ov_archive_expand` for session archive recovery.
diff --git a/examples/openclaw-plugin/install-manifest.json b/examples/openclaw-plugin/install-manifest.json
index 03708430d..de6eee496 100644
--- a/examples/openclaw-plugin/install-manifest.json
+++ b/examples/openclaw-plugin/install-manifest.json
@@ -26,6 +26,7 @@
"adapters/",
"registries/",
"routing/",
+ "shared/",
"plugin/",
"services/",
"commands/setup.ts",
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index bc8069993..7a3d29684 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -144,9 +144,9 @@
},
"autoRecallTimeoutMs": {
"label": "Auto-Recall Timeout (ms)",
- "placeholder": "5000",
+ "placeholder": "15000",
"advanced": true,
- "help": "Outer time budget for the whole auto-recall flow, including search, ranking, and memory reads."
+ "help": "Outer time budget for the server-assembled context search, including session-aware query expansion."
},
"recallResources": {
"label": "Recall Resources",
diff --git a/examples/openclaw-plugin/package.json b/examples/openclaw-plugin/package.json
index b53ef3016..91fbb7c92 100644
--- a/examples/openclaw-plugin/package.json
+++ b/examples/openclaw-plugin/package.json
@@ -26,6 +26,7 @@
"config/feature-gates.json",
"registries/",
"routing/",
+ "shared/",
"plugin/",
"services/",
"!vitest.config.ts",
diff --git a/examples/openclaw-plugin/shared/recall-compress-core.mjs b/examples/openclaw-plugin/shared/recall-compress-core.mjs
new file mode 100644
index 000000000..6f8fe485b
--- /dev/null
+++ b/examples/openclaw-plugin/shared/recall-compress-core.mjs
@@ -0,0 +1,195 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { createHash } from "node:crypto";
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { dirname } from "node:path";
+
+export const NO_RELEVANT_MEMORY = "NO_RELEVANT_MEMORY";
+export const DIGEST_HEADER = "OpenViking memory digest:";
+const COMPRESS_OK = "ok";
+const COMPRESS_EMPTY = "empty";
+const COMPRESS_FAILED = "failed";
+
+// Medium-constraint prompt: state the goal and two structural floors, but no hard
+// bullet-length contract. Hard per-bullet limits pin the digest to headline
+// density; leaving it unconstrained lets small models rewrite long URIs into dead
+// links, which the URI repair below cleans up.
+export function buildRecallCompressionPrompt({ query, rendered, maxBullets = 6 }) {
+ return `You are a memory relevance compressor utility.
+Do not use any tools. Do not investigate. Only transform the given text.
+
+User query:
+${query}
+
+Retrieved OpenViking context fragments:
+${rendered}
+
+Write a memory digest for a coding agent about to answer that query. Keep the
+concrete facts (paths, identifiers, decisions, constraints); drop pleasantries
+and conversational filler.
+
+Format rules:
+- Group related facts by topic, one bullet per topic, at most ${maxBullets} bullets.
+- Start every bullet with "- ".
+- End every bullet with its source, copied verbatim from the fragments above:
+ "来源:viking://..." or "source: viking://...". Never edit, shorten, or invent a URI.
+- Output the digest body only. No preamble, no closing remark.
+
+If nothing above is relevant to the query, output exactly: ${NO_RELEVANT_MEMORY}`;
+}
+
+function editDistance(a, b) {
+ if (a === b) return 0;
+ const rows = a.length + 1;
+ const cols = b.length + 1;
+ let prev = Array.from({ length: cols }, (_, i) => i);
+ for (let i = 1; i < rows; i += 1) {
+ const cur = [i];
+ for (let j = 1; j < cols; j += 1) {
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
+ cur[j] = Math.min(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
+ }
+ prev = cur;
+ }
+ return prev[cols - 1];
+}
+
+function nearestUri(candidate, validUris) {
+ let best = "";
+ let bestDistance = Infinity;
+ for (const uri of validUris) {
+ const distance = editDistance(candidate, uri);
+ if (distance < bestDistance) {
+ best = uri;
+ bestDistance = distance;
+ }
+ }
+ // Only repair near-misses; an unrelated hallucination is dropped instead.
+ const tolerance = Math.max(4, Math.floor(candidate.length * 0.25));
+ return bestDistance <= tolerance ? best : "";
+}
+
+/**
+ * Small models occasionally mangle long URIs. Snap every cited URI back onto the
+ * set the server actually returned, and drop bullets whose citation cannot be
+ * recovered so the digest never carries a dead link.
+ */
+export function repairDigestUris(digest, validUris = []) {
+ const text = String(digest || "");
+ if (!text) return "";
+ const valid = validUris.map((uri) => String(uri || "").trim()).filter(Boolean);
+ if (!valid.length) return text;
+ const validSet = new Set(valid);
+
+ const lines = [];
+ for (const line of text.split(/\r?\n/)) {
+ if (!line.trim().startsWith("- ")) {
+ lines.push(line);
+ continue;
+ }
+ let dropped = false;
+ const repaired = line.replace(/viking:\/\/[^\s<>"')\]]+/g, (uri) => {
+ if (validSet.has(uri)) return uri;
+ const nearest = nearestUri(uri, valid);
+ if (nearest) return nearest;
+ dropped = true;
+ return uri;
+ });
+ if (!dropped) lines.push(repaired);
+ }
+ return lines.join("\n").trim();
+}
+
+export function normalizeCompressedContext(raw, maxChars = 4000, maxBullets = 6) {
+ const text = String(raw || "").trim();
+ if (!text) return null;
+ if (text.toUpperCase() === NO_RELEVANT_MEMORY) return "";
+ const bullets = text.split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter((line) => /^[-*]\s+/.test(line) && line.includes("viking://"))
+ .slice(0, Math.max(1, maxBullets))
+ .map((line) => `- ${line.replace(/^[-*]\s+/, "").slice(0, 500).trim()}`);
+ if (!bullets.length) return null;
+ return (`${DIGEST_HEADER}\n${bullets.join("\n")}`).slice(0, Math.max(100, maxChars));
+}
+
+export function recallDigestCacheKey({
+ query = "",
+ rendered = "",
+ entries = [],
+ maxInputChars = 18000,
+ maxBullets = 6,
+} = {}) {
+ const uris = entries.map((entry) => String(entry?.uri || "").trim()).filter(Boolean).sort();
+ const source = JSON.stringify({
+ version: 2,
+ query: String(query),
+ rendered: String(rendered).slice(0, maxInputChars),
+ uris,
+ maxInputChars,
+ maxBullets,
+ });
+ return createHash("sha256").update(source).digest("hex");
+}
+
+async function readCache(path) {
+ if (!path) return null;
+ try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
+}
+
+async function writeCache(path, value) {
+ if (!path) return;
+ try {
+ await mkdir(dirname(path), { recursive: true });
+ const tmp = `${path}.tmp`;
+ await writeFile(tmp, JSON.stringify(value));
+ await rename(tmp, path);
+ } catch { /* best effort */ }
+}
+
+export async function compressRecallContext({
+ query,
+ rendered,
+ entries = [],
+ cfg = {},
+ runCompressor,
+ cachePath = "",
+ now = 0,
+}) {
+ const input = String(rendered || "").trim();
+ if (!input) return { status: COMPRESS_EMPTY, context: "" };
+ const minChars = Math.max(0, Number(cfg.recallCompressMinInputChars ?? 1500));
+ if (input.length < minChars) return { status: COMPRESS_OK, context: input };
+
+ const maxInputChars = Math.max(1000, Number(cfg.recallCompressMaxInputChars || 18000));
+ const maxBullets = Math.max(1, Number(cfg.recallCompressMaxBullets || 6));
+ const key = recallDigestCacheKey({
+ query,
+ rendered: input,
+ entries,
+ maxInputChars,
+ maxBullets,
+ });
+ const cached = await readCache(cachePath);
+ if (cached?.key === key && typeof cached.digest === "string") {
+ return { status: COMPRESS_OK, context: cached.digest };
+ }
+
+ const prompt = buildRecallCompressionPrompt({
+ query,
+ rendered: input.slice(0, maxInputChars),
+ maxBullets,
+ });
+ const raw = await runCompressor(prompt);
+ const normalized = normalizeCompressedContext(raw, 4000, maxBullets);
+ if (normalized === null) return { status: COMPRESS_FAILED, context: "" };
+ if (!normalized) return { status: COMPRESS_EMPTY, context: "" };
+
+ const validUris = entries.map((entry) => entry?.uri).filter(Boolean);
+ const digest = repairDigestUris(normalized, validUris.length
+ ? validUris
+ : (input.match(/viking:\/\/[^\s<>"']+/g) || []));
+ if (!digest) return { status: COMPRESS_FAILED, context: "" };
+
+ await writeCache(cachePath, { key, digest, updatedAt: now || 0 });
+ return { status: COMPRESS_OK, context: digest };
+}
diff --git a/examples/openclaw-plugin/shared/recall-core.d.mts b/examples/openclaw-plugin/shared/recall-core.d.mts
new file mode 100644
index 000000000..cdddc3260
--- /dev/null
+++ b/examples/openclaw-plugin/shared/recall-core.d.mts
@@ -0,0 +1,39 @@
+export type ContextSearchBody = {
+ query: string;
+ mode: "context";
+ purpose: "coding";
+ score_threshold: number;
+ quotas?: Record<string, number>;
+ max_tokens?: number;
+ peer_scope?: "actor";
+ session_id?: string;
+ query_expansion?: "off" | "auto";
+ dedup_turns?: number;
+ exclude_uris?: string[];
+ rewrite?: boolean | "auto";
+ rewrite_max_bullets?: number;
+};
+
+export type NormalizedContextEntry = {
+ uri: string;
+ category: string;
+ detail: string;
+ score: number;
+ text: string;
+};
+
+export function buildContextSearchBody(
+ cfg?: Record<string, unknown>,
+ options?: {
+ sessionId?: string;
+ excludeUris?: string[];
+ localCompressorAvailable?: boolean;
+ },
+): ContextSearchBody;
+
+export function contextRequestTimeoutMs(
+ cfg?: Record<string, unknown>,
+ body?: Record<string, unknown>,
+): number | undefined;
+
+export function normalizeContextEntry(entry?: unknown): NormalizedContextEntry;
diff --git a/examples/openclaw-plugin/shared/recall-core.mjs b/examples/openclaw-plugin/shared/recall-core.mjs
new file mode 100644
index 000000000..e1b0df802
--- /dev/null
+++ b/examples/openclaw-plugin/shared/recall-core.mjs
@@ -0,0 +1,613 @@
+// GENERATED FROM examples/memory-plugin-shared/lib. DO NOT EDIT.
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { dirname, join } from "node:path";
+
+import { compressRecallContext } from "./recall-compress-core.mjs";
+
+const PREFERENCE_QUERY_RE = /prefer|preference|favorite|favourite|like|偏好|喜欢|爱好|更倾向/i;
+const TEMPORAL_QUERY_RE = /when|what time|date|day|month|year|yesterday|today|tomorrow|last|next|什么时候|何时|哪天|几月|几年|昨天|今天|明天/i;
+const QUERY_TOKEN_RE = /[a-z0-9一-龥]{2,}/gi;
+const STOPWORDS = new Set([
+ "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "did", "does",
+ "is", "are", "was", "were", "the", "and", "for", "with", "from", "that", "this", "your", "you",
+]);
+const USER_RESERVED_DIRS = new Set(["memories", "skills"]);
+const SOURCES = [
+ { type: "memory", uri: "viking://~/memories", bucket: "memories" },
+ { type: "skill", uri: "viking://~/skills", bucket: "skills" },
+];
+const DEFAULT_CONTEXT_LIMIT = 10;
+const DEFAULT_CONTEXT_MAX_TOKENS = 1600;
+const DEFAULT_REWRITE_MAX_BULLETS = 6;
+const CODING_QUOTA_WEIGHTS = {
+ events: 1,
+ entities: 2,
+ preferences: 1,
+ experiences: 1,
+ resources: 3,
+ skills: 2,
+};
+
+let userSpaceCache = "";
+
+export function estimateTokens(text) {
+ return text ? Math.ceil(String(text).length / 4) : 0;
+}
+
+function scaleQuotas(limit, weights) {
+ const slots = Math.max(1, Math.floor(Number(limit) || DEFAULT_CONTEXT_LIMIT));
+ const order = Object.keys(weights);
+ const quotas = Object.fromEntries(order.map((key) => [key, 0]));
+ if (slots < order.length) {
+ for (const key of order) quotas[key] = 1;
+ return quotas;
+ }
+
+ for (const key of order) quotas[key] = 1;
+ const totalWeight = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
+ const ideals = Object.fromEntries(
+ order.map((key) => [key, slots * weights[key] / totalWeight]),
+ );
+ while (order.reduce((sum, key) => sum + quotas[key], 0) < slots) {
+ const key = order.reduce((best, candidate) => (
+ ideals[candidate] - quotas[candidate] > ideals[best] - quotas[best]
+ ? candidate
+ : best
+ ));
+ quotas[key] += 1;
+ }
+ return quotas;
+}
+
+function legacyMemoryQuotas(limit) {
+ return {
+ ...scaleQuotas(limit, { events: 10, entities: 10, preferences: 3 }),
+ experiences: 0,
+ };
+}
+
+function codingQuotas(limit) {
+ return scaleQuotas(limit, CODING_QUOTA_WEIGHTS);
+}
+
+export function buildRecallEndpointBody(cfg = {}) {
+ const limit = Math.max(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT), 1);
+ const body = {
+ query: "",
+ quotas: legacyMemoryQuotas(limit),
+ max_chars: Math.max(Number(cfg.recallMaxContentChars || 0) * limit, 1000),
+ min_score: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
+ render: true,
+ };
+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";
+ return body;
+}
+
+/**
+ * Body for the server-side context face. The plugin declares intent (coding
+ * purpose, budget, session) and leaves the mechanics — quota ratios, tier
+ * degradation, cross-turn dedup — to the server's defaults.
+ */
+export function buildContextSearchBody(cfg = {}, options = {}) {
+ const rewriteMode = String(cfg.recallRewrite || "off").toLowerCase();
+ const limit = Math.max(1, Math.floor(Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT)));
+ const maxTokens = Math.max(
+ 64,
+ Math.floor(Number(cfg.recallMaxTokens || DEFAULT_CONTEXT_MAX_TOKENS)),
+ );
+ const body = {
+ query: "",
+ mode: "context",
+ purpose: "coding",
+ score_threshold: Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35,
+ };
+ const limitConfigured = cfg.recallLimitConfigured === true;
+ const maxTokensConfigured = cfg.recallMaxTokensConfigured === true;
+ if (limitConfigured) body.quotas = codingQuotas(limit);
+ if (maxTokensConfigured) body.max_tokens = maxTokens;
+ if (cfg.recallPeerScope === "actor") body.peer_scope = "actor";
+
+ const sessionId = String(options.sessionId || "").trim();
+ if (sessionId) {
+ body.session_id = sessionId;
+ const queryExpansionConfigured = cfg.recallQueryExpansionConfigured === true;
+ if (queryExpansionConfigured) {
+ body.query_expansion = cfg.recallQueryExpansion === "off" ? "off" : "auto";
+ }
+ const dedupTurns = Number(cfg.recallDedupTurns);
+ const resolvedDedupTurns = Number.isFinite(dedupTurns)
+ ? Math.max(0, Math.floor(dedupTurns))
+ : 5;
+ if (resolvedDedupTurns > 0) body.dedup_turns = resolvedDedupTurns;
+ }
+
+ const excludeUris = Array.isArray(options.excludeUris) ? options.excludeUris.slice(0, 200) : [];
+ if (excludeUris.length) body.exclude_uris = excludeUris;
+
+ if (rewriteMode === "server") body.rewrite = true;
+ else if (rewriteMode === "auto" && !options.localCompressorAvailable) body.rewrite = "auto";
+ const rewriteMaxBullets = Math.max(
+ 1,
+ Math.floor(Number(cfg.recallCompressMaxBullets || DEFAULT_REWRITE_MAX_BULLETS)),
+ );
+ const rewriteMaxBulletsConfigured = cfg.recallCompressMaxBulletsConfigured === true;
+ if (body.rewrite !== undefined && rewriteMaxBulletsConfigured) {
+ body.rewrite_max_bullets = rewriteMaxBullets;
+ }
+ return body;
+}
+
+// The server pipeline is serial and each optional stage has its own fuse. A
+// request is aborted client-side unless its deadline covers every stage it
+// asked for, and aborting discards the whole response rather than just the
+// stage that ran long.
+//
+// session_id -> query expansion (retrieval.recall_intent_timeout_s, 5s)
+// always -> retrieval, body reads, budget planning
+// rewrite -> digest (retrieval.recall_rewrite_timeout_s, 30s)
+//
+// Both budgets stay inside the 60s prompt-hook allowance, the rewrite one with
+// a quarter to spare.
+const EXPANSION_REQUEST_TIMEOUT_MS = 15000;
+const SERVER_REWRITE_REQUEST_TIMEOUT_MS = 45000;
+
+/**
+ * HTTP deadline for one context request, or undefined to keep the caller's own.
+ *
+ * Derived from the request body, because the body is what states which server
+ * stages will run: reading `cfg` alone cannot tell a bare retrieval from one
+ * that also spends the expansion or rewrite fuse.
+ */
+export function contextRequestTimeoutMs(cfg = {}, body = {}) {
+ const wantsRewrite = body.rewrite !== undefined;
+ // `query_expansion` defaults to "auto" server-side, so only an explicit "off"
+ // takes the expansion fuse back out of the budget.
+ const wantsExpansion = Boolean(body.session_id) && body.query_expansion !== "off";
+ const configured = Number(cfg.recallContextTimeoutMs);
+ if (Number.isFinite(configured) && configured > 0) return Math.max(1000, Math.floor(configured));
+ if (!wantsRewrite && !wantsExpansion) return undefined;
+ const floor = wantsRewrite ? SERVER_REWRITE_REQUEST_TIMEOUT_MS : EXPANSION_REQUEST_TIMEOUT_MS;
+ return Math.max(Number(cfg.timeoutMs) || 0, floor);
+}
+
+/**
+ * Strip the context-face fields a pre-context server rejects, converting the
+ * token budget back to v1's character budget.
+ */
+export function downgradeToRecallBody(contextBody = {}, cfg = {}) {
+ const body = buildRecallEndpointBody(cfg);
+ body.query = contextBody.query || "";
+ body.max_chars = Math.max(1000, Math.floor(Number(contextBody.max_tokens || 1600) * 4));
+ if (contextBody.peer_scope) body.peer_scope = contextBody.peer_scope;
+ return body;
+}
+
+function clampScore(v) {
+ if (typeof v !== "number" || Number.isNaN(v)) return 0;
+ return Math.max(0, Math.min(1, v));
+}
+
+function buildQueryProfile(query) {
+ const text = query.trim();
+ const allTokens = text.toLowerCase().match(QUERY_TOKEN_RE) || [];
+ return {
+ tokens: allTokens.filter((t) => !STOPWORDS.has(t)),
+ wantsPreference: PREFERENCE_QUERY_RE.test(text),
+ wantsTemporal: TEMPORAL_QUERY_RE.test(text),
+ };
+}
+
+function lexicalOverlapBoost(tokens, text) {
+ if (tokens.length === 0 || !text) return 0;
+ const haystack = ` ${text.toLowerCase()} `;
+ let matched = 0;
+ for (const token of tokens.slice(0, 8)) {
+ if (haystack.includes(token)) matched += 1;
+ }
+ return Math.min(0.2, (matched / Math.min(tokens.length, 4)) * 0.2);
+}
+
+function rankItem(item, profile) {
+ const base = clampScore(item.score);
+ const abstract = (item.abstract || item.overview || "").trim();
+ const cat = (item.category || "").toLowerCase();
+ const uri = (item.uri || "").toLowerCase();
+ const leafBoost = (item.level === 2 || uri.endsWith(".md")) ? 0.12 : 0;
+ const eventBoost = profile.wantsTemporal && (cat === "events" || uri.includes("/events/")) ? 0.1 : 0;
+ const prefBoost = profile.wantsPreference && (cat === "preferences" || uri.includes("/preferences/")) ? 0.08 : 0;
+ const overlapBoost = lexicalOverlapBoost(profile.tokens, `${item.uri} ${abstract}`);
+ return base + leafBoost + eventBoost + prefBoost + overlapBoost;
+}
+
+function isEventOrCaseItem(item) {
+ const cat = (item.category || "").toLowerCase();
+ const uri = (item.uri || "").toLowerCase();
+ return cat === "events" || cat === "cases" || uri.includes("/events/") || uri.includes("/cases/");
+}
+
+function dedupeItems(items) {
+ const seen = new Set();
+ const out = [];
+ for (const item of items) {
+ const key = isEventOrCaseItem(item)
+ ? `uri:${item.uri}`
+ : ((item.abstract || item.overview || "").trim().toLowerCase() || `uri:${item.uri}`);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(item);
+ }
+ return out;
+}
+
+async function resolveUserSpace(fetchJSON, actorPeerId = "") {
+ if (userSpaceCache) return userSpaceCache;
+
+ let fallbackSpace = "default";
+ const status = await fetchJSON("/api/v1/system/status");
+ if (status.ok && typeof status.result?.user === "string" && status.result.user.trim()) {
+ fallbackSpace = status.result.user.trim();
+ }
+
+ const lsRes = await fetchJSON(
+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,
+ {},
+ { actorPeerId },
+ );
+ if (lsRes.ok && Array.isArray(lsRes.result)) {
+ const spaces = lsRes.result
+ .filter((e) => e?.isDir)
+ .map((e) => (typeof e.name === "string" ? e.name.trim() : ""))
+ .filter((n) => n && !n.startsWith(".") && !USER_RESERVED_DIRS.has(n));
+ if (spaces.length > 0) {
+ if (spaces.includes(fallbackSpace)) { userSpaceCache = fallbackSpace; return fallbackSpace; }
+ if (spaces.includes("default")) { userSpaceCache = "default"; return "default"; }
+ if (spaces.length === 1) { userSpaceCache = spaces[0]; return spaces[0]; }
+ }
+ }
+ userSpaceCache = fallbackSpace;
+ return fallbackSpace;
+}
+
+async function resolveTargetUri(fetchJSON, targetUri, actorPeerId = "") {
+ const trimmed = targetUri.trim().replace(/\/+$/, "");
+ // viking://~ is the home alias: the server expands it to the caller's own user
+ // space, so it needs no client-side rewrite.
+ if (trimmed === "viking://~" || trimmed.startsWith("viking://~/")) return trimmed;
+ // Legacy compat: uid-less viking://user/<reserved> URIs may still sit in plugin
+ // configs. Newer servers reject them, so rewrite to an explicit-uid URI here.
+ const m = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);
+ if (!m) return trimmed;
+ const rawRest = (m[1] ?? "").trim();
+ if (!rawRest) return trimmed;
+ const parts = rawRest.split("/").filter(Boolean);
+ if (parts.length === 0) return trimmed;
+ if (!USER_RESERVED_DIRS.has(parts[0])) return trimmed;
+ const space = await resolveUserSpace(fetchJSON, actorPeerId);
+ return `viking://user/${space}/${parts.join("/")}`;
+}
+
+async function searchOneSource(fetchJSON, query, source, limit, actorPeerId = "") {
+ const resolvedUri = await resolveTargetUri(fetchJSON, source.uri, actorPeerId);
+ const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };
+ const res = await fetchJSON("/api/v1/search/find", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }, { actorPeerId });
+ if (!res.ok) return [];
+ const items = res.result?.[source.bucket] || [];
+ return items.map((item) => ({ ...item, _sourceType: source.type }));
+}
+
+async function searchAllSources(fetchJSON, query, perSourceLimit, actorPeerId = "", log = () => {}) {
+ const results = await Promise.all(
+ SOURCES.map((src) => searchOneSource(fetchJSON, query, src, perSourceLimit, actorPeerId)),
+ );
+ const all = results.flat();
+ log("recall_search_summary", {
+ counts: SOURCES.map((src, i) => ({ type: src.type, uri: src.uri, count: results[i].length })),
+ total: all.length,
+ });
+ return all;
+}
+
+async function resolveItemContent(fetchJSON, item, cfg, actorPeerId = "") {
+ let content;
+
+ if (cfg.recallPreferAbstract && (item.abstract || item.overview || "").trim()) {
+ content = (item.abstract || item.overview).trim();
+ } else if (item.level === 2) {
+ try {
+ const res = await fetchJSON(
+ `/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,
+ {},
+ { actorPeerId },
+ );
+ const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";
+ content = body || (item.abstract || item.overview || "").trim() || item.uri;
+ } catch {
+ content = (item.abstract || item.overview || "").trim() || item.uri;
+ }
+ } else {
+ content = (item.abstract || item.overview || "").trim() || item.uri;
+ }
+
+ const maxChars = Math.max(50, Number(cfg.recallMaxContentChars || 500));
+ if (content.length > maxChars) content = `${content.slice(0, maxChars)}...`;
+ return content;
+}
+
+async function buildFallbackInjectionBlock(fetchJSON, items, cfg, actorPeerId = "", log = () => {}) {
+ if (items.length === 0) return null;
+
+ let budgetRemaining = Math.max(200, Number(cfg.recallTokenBudget || 2000));
+ const lines = [
+ "<openviking-context>",
+ "Relevant context from OpenViking. Use the read MCP tool to expand URIs.",
+ ];
+ let contentCount = 0;
+ let hintCount = 0;
+
+ for (const item of items) {
+ const score = (clampScore(item.score) * 100).toFixed(0);
+ const uriLine = `- [${item._sourceType} ${score}%] ${item.uri}`;
+
+ if (budgetRemaining > 0) {
+ const content = await resolveItemContent(fetchJSON, item, cfg, actorPeerId);
+ const contentLine = `- [${item._sourceType} ${score}%] ${content}`;
+ const lineTokens = estimateTokens(contentLine);
+
+ if (lineTokens > budgetRemaining && contentCount > 0) {
+ lines.push(uriLine);
+ hintCount++;
+ } else {
+ lines.push(contentLine);
+ budgetRemaining -= lineTokens;
+ contentCount++;
+ }
+ } else {
+ lines.push(uriLine);
+ hintCount++;
+ }
+ }
+
+ lines.push("</openviking-context>");
+
+ const budgetUsed = Math.max(200, Number(cfg.recallTokenBudget || 2000)) - budgetRemaining;
+ log("recall_injection_built", {
+ contentItems: contentCount,
+ hintItems: hintCount,
+ budgetUsed,
+ budgetTotal: Math.max(200, Number(cfg.recallTokenBudget || 2000)),
+ });
+
+ return lines.join("\n");
+}
+
+const LEGACY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
+
+function stateFile(name) {
+ const override = String(process.env.OPENVIKING_STATE_DIR || "").trim();
+ return override ? join(override, name) : join(homedir(), ".openviking", "state", name);
+}
+
+async function readJsonFile(path) {
+ try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
+}
+
+async function writeJsonFile(path, value) {
+ try {
+ await mkdir(dirname(path), { recursive: true });
+ const tmp = `${path}.tmp`;
+ await writeFile(tmp, JSON.stringify(value));
+ await rename(tmp, path);
+ } catch { /* best effort */ }
+}
+
+/**
+ * Hooks are one-shot processes, so "this server has no context face" has to be
+ * remembered on disk or every turn pays for a rejected request.
+ */
+export async function isContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
+ const cached = await readJsonFile(path);
+ return Boolean(cached?.legacyUntil && Number(cached.legacyUntil) > now);
+}
+
+export async function markContextFaceLegacy(path = stateFile("context-face.json"), now = Date.now()) {
+ await writeJsonFile(path, { legacyUntil: now + LEGACY_CACHE_TTL_MS });
+}
+
+function looksLikeUnknownField(res) {
+ const text = JSON.stringify(res?.error ?? res?.result ?? res?.detail ?? "").toLowerCase();
+ return text.includes("extra") || text.includes("mode") || text.includes("unexpected");
+}
+
+function wrapContext(body) {
+ return [
+ "<openviking-context>",
+ "Relevant memory from OpenViking. Use the search/read MCP tools to expand URIs.",
+ body,
+ "</openviking-context>",
+ ].join("\n");
+}
+
+/**
+ * Server-assembled context: the context face when the deployment has it, else
+ * the deprecated /recall preset. Returns the injection block, "" when there was
+ * nothing relevant, or null when no server-side path was usable at all.
+ */
+export async function buildServerAssembledBlock(fetchJSON, cfg, query, options = {}) {
+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
+ const log = options.log || (() => {});
+
+ const block = await recallViaContextFace(fetchJSON, cfg, query, { ...options, actorPeerId }, log);
+ if (block !== null) return block;
+ return recallViaEndpoint(fetchJSON, cfg, query, actorPeerId, log);
+}
+
+/**
+ * Raw server-assembled context, or null when the deployment has no context face.
+ * Returns `{ rendered, entries, digest, stats }` — callers that need the entries
+ * (their own compression, their own envelope) use this instead of the block
+ * builders below.
+ */
+export async function fetchAssembledContext(fetchJSON, cfg, query, options = {}) {
+ const actorPeerId = options.actorPeerId || "";
+ const log = options.log || (() => {});
+ if (await isContextFaceLegacy(options.legacyCachePath)) return null;
+
+ const body = buildContextSearchBody(cfg, options);
+ body.query = query;
+ const res = await fetchJSON("/api/v1/search/search", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }, { actorPeerId, timeoutMs: contextRequestTimeoutMs(cfg, body) });
+
+ if (!res.ok) {
+ const status = res.status || 0;
+ if ((status === 400 || status === 422) && looksLikeUnknownField(res)) {
+ await markContextFaceLegacy(options.legacyCachePath);
+ log("recall_context_face_unsupported", { status });
+ } else {
+ log("recall_context_face_error", { status });
+ }
+ return null;
+ }
+
+ const result = res.result || {};
+ const stats = result.stats || {};
+ log("recall_context_assembled", {
+ entries: Array.isArray(result.entries) ? result.entries.length : 0,
+ usedTokens: stats.used_tokens || 0,
+ tiers: stats.tier_counts || {},
+ rewrite: stats.rewrite || "off",
+ });
+ return {
+ rendered: String(result.rendered || "").trim(),
+ entries: Array.isArray(result.entries) ? result.entries : [],
+ digest: String(result.digest || "").trim(),
+ stats,
+ };
+}
+
+/**
+ * Entry field compatibility: the context face returns `category`/`text`, while
+ * the deprecated /recall v1 shape used `type` plus `content`/`summary`.
+ */
+export function normalizeContextEntry(entry = {}) {
+ return {
+ uri: String(entry.uri || "").trim(),
+ category: String(entry.category || entry.type || "memory").trim() || "memory",
+ detail: String(entry.detail || entry.mode || "").trim(),
+ score: Number(entry.score) || 0,
+ text: String(
+ entry.text || entry.content || entry.summary || entry.abstract || entry.uri || "",
+ ).trim(),
+ };
+}
+
+async function recallViaContextFace(fetchJSON, cfg, query, options, log) {
+ const assembled = await fetchAssembledContext(fetchJSON, cfg, query, { ...options, log });
+ if (assembled === null) return null;
+
+ const { rendered, entries } = assembled;
+ let digest = assembled.digest;
+ const mode = String(cfg.recallRewrite || "off").toLowerCase();
+ if (String(assembled.stats?.rewrite || "").toLowerCase() === "no_relevant") {
+ log("recall_server_compression", { status: "empty" });
+ return "";
+ }
+ const wantsLocal = mode === "client" || (mode === "auto" && !digest);
+ if (wantsLocal && rendered && typeof options.runCompressor === "function") {
+ try {
+ const compression = await compressRecallContext({
+ query,
+ rendered,
+ entries,
+ cfg,
+ runCompressor: options.runCompressor,
+ cachePath: options.digestCachePath || stateFile("recall-digest.json"),
+ now: Date.now(),
+ });
+ log("recall_local_compression", { status: compression.status });
+ if (compression.status === "ok") digest = compression.context;
+ if (compression.status === "empty") return "";
+ } catch (err) {
+ log("recall_local_compression_failed", { error: String(err?.message || err) });
+ }
+ }
+
+ const injected = digest || rendered;
+ if (!injected) return "";
+ return wrapContext(injected);
+}
+
+async function recallViaEndpoint(fetchJSON, cfg, query, actorPeerId = "", log = () => {}) {
+ const body = buildRecallEndpointBody(cfg);
+ body.query = query;
+ const res = await postRecall(fetchJSON, body, { actorPeerId, log });
+ if (!res.ok) {
+ log("recall_endpoint_fallback", { status: res.status || 0 });
+ return null;
+ }
+ const rendered = String(res.result?.rendered || "").trim();
+ if (!rendered) return "";
+ return wrapContext(rendered);
+}
+
+export async function postRecall(fetchJSON, body, opts = {}) {
+ const actorPeerId = opts.actorPeerId || "";
+ const log = opts.log || (() => {});
+ const request = { ...body };
+ const res = await fetchJSON("/api/v1/search/recall", {
+ method: "POST",
+ body: JSON.stringify(request),
+ }, { actorPeerId });
+ if (!request.peer_scope || (res.status !== 400 && res.status !== 422)) {
+ return res;
+ }
+
+ const downgraded = { ...request };
+ delete downgraded.peer_scope;
+ log("recall_peer_scope_downgrade", { status: res.status || 0 });
+ return fetchJSON("/api/v1/search/recall", {
+ method: "POST",
+ body: JSON.stringify(downgraded),
+ }, { actorPeerId });
+}
+
+export async function buildRecallBlock(fetchJSON, cfg, query, options = {}) {
+ const actorPeerId = options.actorPeerId ?? cfg.peerId ?? "";
+ const log = options.log || (() => {});
+ const trimmed = String(query || "").trim();
+ if (!trimmed) return null;
+
+ // Assembly happens server-side when the deployment offers the context face;
+ // older servers fall through to /recall, then to raw find.
+ const serverBlock = await buildServerAssembledBlock(fetchJSON, cfg, trimmed, {
+ ...options,
+ actorPeerId,
+ log,
+ });
+ if (serverBlock !== null) return serverBlock || null;
+
+ const recallLimit = Math.max(1, Number(cfg.recallLimit || DEFAULT_CONTEXT_LIMIT));
+ const perSourceLimit = Math.max(recallLimit * 2, 8);
+ const raw = await searchAllSources(fetchJSON, trimmed, perSourceLimit, actorPeerId, log);
+ if (raw.length === 0) return null;
+
+ const profile = buildQueryProfile(trimmed);
+ const scoreThreshold = Number.isFinite(Number(cfg.scoreThreshold)) ? Number(cfg.scoreThreshold) : 0.35;
+ const filtered = raw.filter((it) => clampScore(it.score) >= scoreThreshold);
+ filtered.sort((a, b) => rankItem(b, profile) - rankItem(a, profile));
+ const picked = dedupeItems(filtered).slice(0, recallLimit);
+ log("recall_picked", {
+ rawCount: raw.length,
+ filteredCount: filtered.length,
+ pickedCount: picked.length,
+ items: picked.map((it) => ({ type: it._sourceType, uri: it.uri, score: clampScore(it.score) })),
+ });
+
+ if (picked.length === 0) return null;
+ return buildFallbackInjectionBlock(fetchJSON, picked, cfg, actorPeerId, log);
+}
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 9c19c86b7..56bafcf4b 100644
--- a/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts
+++ b/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts
@@ -270,16 +270,23 @@ describe("buildAutoRecallContext trace", () => {
it("records auto-recall trace without changing the generated context block", async () => {
const cfg = makeCfg({ recallTargetTypes: ["user"] });
- const memory = makeMemory({
+ const entry = {
uri: "viking://user/memories/rust-pref",
category: "preferences",
- abstract: "User prefers Rust for backend tasks.",
+ text: "User prefers Rust for backend tasks.",
score: 0.91,
- });
+ detail: "abstract",
+ origin: "self",
+ };
const makeClient = () => ({
healthCheck: vi.fn().mockResolvedValue(undefined),
- find: vi.fn().mockResolvedValue({ memories: [memory], total: 1 }),
- read: vi.fn().mockResolvedValue("unused"),
+ searchContext: vi.fn().mockResolvedValue({
+ entries: [entry],
+ rendered: '<memory uri="viking://user/memories/rust-pref">User prefers Rust for backend tasks.</memory>',
+ stats: { candidates: 1, used_tokens: 18 },
+ }),
+ find: vi.fn(),
+ read: vi.fn(),
});
const logger = { info: vi.fn(), warn: vi.fn() };
@@ -332,20 +339,22 @@ describe("buildAutoRecallContext trace", () => {
it("defaults auto-recall to backward-compatible user and agent memory recall", async () => {
const cfg = makeCfg();
- const userMemory = makeMemory({
+ const userMemory = {
uri: "viking://user/memories/project-docs",
category: "memory",
- abstract: "Project documentation preference.",
+ text: "Project documentation preference.",
score: 0.9,
- });
+ origin: "self",
+ };
const client = {
healthCheck: vi.fn().mockResolvedValue(undefined),
- find: vi.fn(async (_query: string, options: { contextType?: string }) => ({
- memories: options.contextType === "memory" ? [userMemory] : [],
- resources: [],
- total: options.contextType === "memory" ? 1 : 0,
- })),
- read: vi.fn().mockResolvedValue("unused"),
+ searchContext: vi.fn().mockResolvedValue({
+ entries: [userMemory],
+ rendered: '<memory uri="viking://user/memories/project-docs">Project documentation preference.</memory>',
+ stats: { candidates: 1, used_tokens: 16 },
+ }),
+ find: vi.fn(),
+ read: vi.fn(),
};
const traces = new RecallTraceMemoryStore(10);
@@ -360,35 +369,47 @@ describe("buildAutoRecallContext trace", () => {
ovSessionId: "ov-1",
});
- expect(client.find).toHaveBeenCalledTimes(1);
- expect(client.find.mock.calls[0]?.[1]).toMatchObject({
+ expect(client.searchContext).toHaveBeenCalledTimes(1);
+ expect(client.searchContext.mock.calls[0]?.[1]).toMatchObject({
+ sessionId: "ov-1",
+ limit: 6,
+ scoreThreshold: 0.15,
contextType: "memory",
- targetUri: undefined,
+ queryExpansion: "auto",
+ maxTokens: 1000,
+ detail: "abstract",
+ dedupTurns: 5,
+ peerScope: "actor",
+ requestTimeoutMs: 15000,
});
+ expect(client.find).not.toHaveBeenCalled();
+ expect(client.read).not.toHaveBeenCalled();
const recorded = traces.query({ turn: "latest", sessionId: "session-resource-only", limit: 10 }).entries[0]!;
expect(recorded.resourceTypes).toEqual(["user", "agent"]);
expect(recorded.searches.map((search) => search.resourceType)).toEqual(["user"]);
});
- it("uses configured autoRecallTimeoutMs as the outer timeout budget", async () => {
+ it("uses configured autoRecallTimeoutMs for both the request and outer budget", async () => {
vi.useFakeTimers();
try {
const cfg = makeCfg({ autoRecallTimeoutMs: 30000, recallTargetTypes: ["user"] });
const client = {
healthCheck: vi.fn().mockResolvedValue(undefined),
- find: vi.fn().mockImplementation(() =>
+ searchContext: vi.fn().mockImplementation(() =>
new Promise((resolve) => {
setTimeout(() => resolve({
- memories: [makeMemory({
+ entries: [{
uri: "viking://user/memories/slow-backend",
- abstract: "Slow local backend recall still completes within the configured budget.",
+ text: "Slow local backend recall still completes within the configured budget.",
score: 0.9,
- })],
- total: 1,
+ }],
+ rendered: '<memory uri="viking://user/memories/slow-backend">Slow local backend recall still completes within the configured budget.</memory>',
+ stats: { candidates: 1, used_tokens: 20 },
}), 10000);
})
),
- read: vi.fn().mockResolvedValue("unused"),
+ find: vi.fn(),
+ read: vi.fn(),
};
const resultPromise = buildAutoRecallContext({
@@ -405,6 +426,7 @@ describe("buildAutoRecallContext trace", () => {
});
const result = await resultPromise;
expect(result.block).toContain("Slow local backend recall still completes within the configured budget.");
+ expect(client.searchContext.mock.calls[0]?.[1]).toMatchObject({ requestTimeoutMs: 30000 });
} finally {
vi.useRealTimers();
}
@@ -414,17 +436,18 @@ describe("buildAutoRecallContext trace", () => {
const cfg = makeCfg({ recallTargetTypes: ["resource", "user"] });
const client = {
healthCheck: vi.fn().mockResolvedValue(undefined),
- find: vi.fn()
- .mockRejectedValueOnce(new Error("resource search failed"))
- .mockResolvedValueOnce({
- memories: [makeMemory({
- uri: "viking://user/memories/backend-pref",
- abstract: "Agent recommends TypeScript for this service.",
- score: 0.88,
- })],
- total: 1,
- }),
- read: vi.fn().mockResolvedValue("unused"),
+ searchContext: vi.fn().mockResolvedValue({
+ entries: [{
+ uri: "viking://user/memories/backend-pref",
+ text: "Agent recommends TypeScript for this service.",
+ score: 0.88,
+ origin: "self",
+ }],
+ rendered: '<memory uri="viking://user/memories/backend-pref">Agent recommends TypeScript for this service.</memory>',
+ stats: { candidates: 1, used_tokens: 18, retrieval_errors: ["resource search failed"] },
+ }),
+ find: vi.fn(),
+ read: vi.fn(),
};
const logger = { info: vi.fn(), warn: vi.fn() };
const traces = new RecallTraceMemoryStore(10);
@@ -444,13 +467,47 @@ describe("buildAutoRecallContext trace", () => {
expect(recorded.searches).toHaveLength(2);
expect(recorded.searches[0]).toMatchObject({
resourceType: "resource",
- error: "Error: resource search failed",
+ error: "resource search failed",
});
expect(recorded.searches[1]).toMatchObject({
resourceType: "user",
total: 1,
});
expect(recorded.selected[0]).toMatchObject({ injected: true });
- expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("auto-recall search failed"));
+ expect(client.searchContext).toHaveBeenCalledTimes(1);
+ expect(client.searchContext.mock.calls[0]?.[1]).toMatchObject({
+ contextType: ["resource", "memory"],
+ });
+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("auto-recall context search failed"));
+ });
+
+ it("records a rejected context request and skips injection", async () => {
+ const cfg = makeCfg({ recallTargetTypes: ["user"] });
+ const client = {
+ healthCheck: vi.fn().mockResolvedValue(undefined),
+ searchContext: vi.fn().mockRejectedValue(new Error("backend unavailable")),
+ };
+ const logger = { info: vi.fn(), warn: vi.fn() };
+ const traces = new RecallTraceMemoryStore(10);
+
+ const result = await buildAutoRecallContext({
+ cfg,
+ client: client as any,
+ agentId: "agent-1",
+ queryText: "which backend preference should be applied?",
+ logger,
+ traceRecorder: traces,
+ sessionId: "session-failed-request",
+ });
+
+ expect(result).toEqual({ memoryCount: 0, estimatedTokens: 0 });
+ const recorded = traces.query({ turn: "latest", sessionId: "session-failed-request", limit: 10 }).entries[0]!;
+ expect(recorded.searches[0]).toMatchObject({
+ resourceType: "user",
+ total: 0,
+ error: "Error: backend unavailable",
+ });
+ expect(recorded.stats.injectedCount).toBe(0);
+ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("backend unavailable"));
});
});
diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.ts
index 530636326..6d9547e5a 100644
--- a/examples/openclaw-plugin/tests/ut/client.test.ts
+++ b/examples/openclaw-plugin/tests/ut/client.test.ts
@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { OpenVikingClient } from "../../client.js";
import type { ResourcePackager } from "../../adapters/resource-packager.js";
import { isMemoryUri } from "../../routing/memory-uri.js";
+import { buildContextSearchBody } from "../../shared/recall-core.mjs";
function okResponse(result: unknown): Response {
return new Response(JSON.stringify({ status: "ok", result }), {
@@ -553,6 +554,115 @@ describe("OpenVikingClient tenant headers (advanced accountId / userId overrides
});
describe("OpenVikingClient canonical namespace policy", () => {
+ it("keeps server-assembled context requests aligned with the shared contract", async () => {
+ const transport = vi.fn().mockResolvedValue(okResponse({
+ entries: [{ uri: "viking://user/memories/events/a.md" }],
+ rendered: '<memory uri="viking://user/memories/events/a.md">body</memory>',
+ stats: { used_tokens: 12 },
+ }));
+ const routingDebugLog = vi.fn();
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "agent", 5000,
+ "acct-123", "user-456", routingDebugLog, false, true, { transport },
+ );
+
+ const result = await client.searchContext("continue the refactor", {
+ sessionId: "ov-session-1",
+ limit: 6,
+ scoreThreshold: 0.15,
+ contextType: ["memory", "resource"],
+ queryExpansion: "auto",
+ maxTokens: 1000,
+ detail: "abstract",
+ dedupTurns: 5,
+ peerScope: "actor",
+ actorPeerId: "agent-main",
+ });
+
+ expect(result.stats).toEqual({ used_tokens: 12 });
+ expect(transport).toHaveBeenCalledTimes(1);
+ const [url, init] = transport.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe("http://127.0.0.1:1933/api/v1/search/search");
+ const requestBody = JSON.parse(String(init.body));
+ const { context_type: contextType, detail, ...sharedRequestBody } = requestBody;
+ expect(sharedRequestBody).toEqual({
+ ...buildContextSearchBody({
+ recallLimit: 6,
+ recallLimitConfigured: true,
+ recallMaxTokens: 1000,
+ recallMaxTokensConfigured: true,
+ scoreThreshold: 0.15,
+ recallQueryExpansion: "auto",
+ recallQueryExpansionConfigured: true,
+ recallDedupTurns: 5,
+ recallPeerScope: "actor",
+ timeoutMs: 5000,
+ }, { sessionId: "ov-session-1" }),
+ query: "continue the refactor",
+ });
+ expect(contextType).toEqual(["memory", "resource"]);
+ expect(detail).toBe("abstract");
+ expect(requestBody).not.toHaveProperty("limit");
+ expect(new Headers(init.headers).get("X-OpenViking-Actor-Peer")).toBe("agent-main");
+ expect(new Headers(init.headers).get("X-OpenViking-Account")).toBe("acct-123");
+ expect(new Headers(init.headers).get("X-OpenViking-User")).toBe("user-456");
+ expect(routingDebugLog).toHaveBeenCalledWith(expect.stringContaining('"query_expansion":"auto"'));
+ });
+
+ it("normalizes context entries through the shared response contract", async () => {
+ const transport = vi.fn().mockResolvedValue(okResponse({
+ entries: [{
+ uri: "viking://user/memories/events/legacy.md",
+ type: "events",
+ mode: "abstract",
+ content: "legacy response body",
+ score: "0.82",
+ origin: "self",
+ }],
+ rendered: "legacy response body",
+ }));
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "agent", 5000,
+ "", "", undefined, false, true, { transport },
+ );
+
+ const result = await client.searchContext("legacy response");
+
+ expect(result.entries?.[0]).toMatchObject({
+ uri: "viking://user/memories/events/legacy.md",
+ category: "events",
+ detail: "abstract",
+ text: "legacy response body",
+ score: 0.82,
+ origin: "self",
+ });
+ });
+
+ it("uses the shared session-aware timeout floor", async () => {
+ vi.useFakeTimers();
+ let requestSignal: AbortSignal | undefined;
+ const transport = vi.fn((_url: string, init: RequestInit) => {
+ requestSignal = init.signal ?? undefined;
+ return new Promise<Response>((_resolve, reject) => {
+ requestSignal?.addEventListener("abort", () => {
+ reject(new DOMException("The operation was aborted", "AbortError"));
+ });
+ });
+ });
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "agent", 5000,
+ "", "", undefined, false, true, { transport },
+ );
+
+ const pending = client.searchContext("session-aware timeout", { sessionId: "ov-session-1" });
+ const rejection = expect(pending).rejects.toMatchObject({ name: "AbortError" });
+ await vi.advanceTimersByTimeAsync(5001);
+ expect(requestSignal?.aborted).toBe(false);
+ await vi.advanceTimersByTimeAsync(9999);
+ expect(requestSignal?.aborted).toBe(true);
+ await rejection;
+ });
+
it("keeps user memory alias unchanged and routes by actor peer by default", async () => {
const transport = vi.fn(async (url: string) => {
if (url.endsWith("/api/v1/system/status")) {
diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.ts
index 5dac6da33..e06f578bc 100644
--- a/examples/openclaw-plugin/tests/ut/config.test.ts
+++ b/examples/openclaw-plugin/tests/ut/config.test.ts
@@ -22,7 +22,7 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {
expect(cfg.commitTokenThresholdRatio).toBe(0.5);
expect(cfg.captureMode).toBe("semantic");
expect(cfg.captureMaxLength).toBe(24000);
- expect(cfg.autoRecallTimeoutMs).toBe(5000);
+ expect(cfg.autoRecallTimeoutMs).toBe(15000);
expect(cfg.recallMaxContentChars).toBe(5000);
expect(cfg.peer_role).toBe("assistant");
expect(cfg.peer_prefix).toBe("");
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 75eb9caaa..ceac50377 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
@@ -52,6 +52,7 @@ function makeEngine(
const client = {
healthCheck: vi.fn().mockResolvedValue(undefined),
getSessionContext: vi.fn().mockResolvedValue(contextResult),
+ searchContext: vi.fn().mockResolvedValue({ entries: [], rendered: "", stats: {} }),
find: vi.fn().mockResolvedValue({ memories: [], resources: [], total: 0 }),
read: vi.fn().mockResolvedValue(""),
} as unknown as OpenVikingClient;
@@ -81,6 +82,7 @@ function makeEngine(
client: client as unknown as {
getSessionContext: ReturnType<typeof vi.fn>;
healthCheck: ReturnType<typeof vi.fn>;
+ searchContext: ReturnType<typeof vi.fn>;
find: ReturnType<typeof vi.fn>;
read: ReturnType<typeof vi.fn>;
},
@@ -114,20 +116,16 @@ describe("context-engine assemble()", () => {
},
},
);
- client.find
- .mockResolvedValueOnce({
- memories: [
- {
- uri: "viking://user/default/memories/rust-pref",
- level: 2,
- category: "preferences",
- abstract: "User prefers Rust for backend tasks.",
- score: 0.93,
- },
- ],
- total: 1,
- })
- .mockResolvedValueOnce({ memories: [], total: 0 });
+ client.searchContext.mockResolvedValueOnce({
+ entries: [{
+ uri: "viking://user/default/memories/rust-pref",
+ category: "preferences",
+ text: "User prefers Rust for backend tasks.",
+ score: 0.93,
+ }],
+ rendered: '<memory uri="viking://user/default/memories/rust-pref">User prefers Rust for backend tasks.</memory>',
+ stats: { candidates: 1, used_tokens: 18 },
+ });
const sourceMessages = [
{ role: "user", content: "[Session History Summary]\nOlder archive summary." },
@@ -171,17 +169,15 @@ describe("context-engine assemble()", () => {
},
},
);
- client.find.mockResolvedValueOnce({
- memories: [
- {
- uri: "viking://user/default/memories/typescript-pref",
- level: 2,
- category: "preferences",
- abstract: "Use TypeScript for gateway plugins.",
- score: 0.9,
- },
- ],
- total: 1,
+ client.searchContext.mockResolvedValueOnce({
+ entries: [{
+ uri: "viking://user/default/memories/typescript-pref",
+ category: "preferences",
+ text: "Use TypeScript for gateway plugins.",
+ score: 0.9,
+ }],
+ rendered: '<memory uri="viking://user/default/memories/typescript-pref">Use TypeScript for gateway plugins.</memory>',
+ stats: { candidates: 1, used_tokens: 16 },
});
await engine.assemble({
@@ -215,29 +211,28 @@ describe("context-engine assemble()", () => {
},
},
);
- client.find.mockImplementation(async (_query: string, options: { contextType?: string }) => ({
- resources: [],
- memories: options.contextType === "memory"
- ? [{
- uri: "viking://user/memories/project-docs",
- level: 2,
- category: "memory",
- abstract: "Memory docs for the gateway plugin.",
- score: 0.9,
- }]
- : [],
- total: options.contextType === "memory" ? 1 : 0,
- }));
+ client.searchContext.mockResolvedValue({
+ entries: [{
+ uri: "viking://user/memories/project-docs",
+ category: "memory",
+ text: "Memory docs for the gateway plugin.",
+ score: 0.9,
+ }],
+ rendered: '<memory uri="viking://user/memories/project-docs">Memory docs for the gateway plugin.</memory>',
+ stats: { candidates: 1, used_tokens: 14 },
+ });
await engine.assemble({
sessionId: "session-transform-resource-default",
messages: [{ role: "user", content: "where are the gateway plugin docs?" }],
});
- expect(client.find).toHaveBeenCalledTimes(1);
- expect(client.find.mock.calls[0]?.[1]).toMatchObject({
+ expect(client.searchContext).toHaveBeenCalledTimes(1);
+ expect(client.searchContext.mock.calls[0]?.[1]).toMatchObject({
+ sessionId: "session-transform-resource-default",
contextType: "memory",
- targetUri: undefined,
+ queryExpansion: "auto",
+ dedupTurns: 5,
});
const recorded = traces.query({ turn: "latest", sessionId: "session-transform-resource-default", limit: 10 }).entries[0]!;
expect(recorded.resourceTypes).toEqual(["user", "agent"]);
@@ -277,24 +272,15 @@ describe("context-engine assemble()", () => {
queryConfigStore,
},
);
- client.find.mockResolvedValueOnce({
- memories: [
- {
- uri: "viking://user/default/memories/high",
- level: 2,
- category: "preferences",
- abstract: "High-confidence dynamic query memory.",
- score: 0.9,
- },
- {
- uri: "viking://user/default/memories/low",
- level: 2,
- category: "facts",
- abstract: "Low-confidence memory should be filtered.",
- score: 0.1,
- },
- ],
- total: 2,
+ client.searchContext.mockResolvedValueOnce({
+ entries: [{
+ uri: "viking://user/default/memories/high",
+ category: "preferences",
+ text: "High-confidence dynamic query memory.",
+ score: 0.9,
+ }],
+ rendered: '<memory uri="viking://user/default/memories/high">High-confidence dynamic query memory.</memory>',
+ stats: { candidates: 1, used_tokens: 12 },
});
const result = await engine.assemble({
@@ -302,11 +288,12 @@ describe("context-engine assemble()", () => {
messages: [{ role: "user", content: "which dynamic query memory applies?" }],
});
- expect(client.find).toHaveBeenCalledTimes(1);
- expect(client.find.mock.calls[0]?.[1]).toMatchObject({
+ expect(client.searchContext).toHaveBeenCalledTimes(1);
+ expect(client.searchContext.mock.calls[0]?.[1]).toMatchObject({
contextType: "memory",
- targetUri: undefined,
- limit: 3,
+ limit: 1,
+ scoreThreshold: 0.5,
+ maxTokens: 250,
});
expect(String(result.messages[0]?.content)).toContain("High-confidence dynamic query memory.");
expect(String(result.messages[0]?.content)).not.toContain("Low-confidence memory should be filtered.");
@@ -407,7 +394,7 @@ describe("context-engine assemble()", () => {
"session-main-no-prompt",
4096,
);
- expect(client.find).not.toHaveBeenCalled();
+ expect(client.searchContext).not.toHaveBeenCalled();
expect(result.messages[0]).toEqual({
role: "user",
content: "[Session History Summary]\n# Session Summary\nPreviously discussed repository setup.",
diff --git a/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts b/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts
index 6151f1454..f9d5727fc 100644
--- a/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts
+++ b/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts
@@ -134,6 +134,7 @@ describe("OpenClaw 5.5 package runtime contract", () => {
expect(packageJson.scripts?.build).toContain("tsc -p tsconfig.build.json");
expect(packageJson.scripts?.prepack).toBe("npm run build");
expect(packageJson.files).toContain("dist/");
+ expect(packageJson.files).toContain("shared/");
expect(packageJson.files).toContain("install-manifest.json");
});
@@ -149,6 +150,7 @@ describe("OpenClaw 5.5 package runtime contract", () => {
"index.ts",
"recall-trace.ts",
"commands/setup.ts",
+ "shared/",
"tsconfig.json",
"tsconfig.build.json",
"package.json",
diff --git a/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts b/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts
index 0df1c76e4..cd2a47209 100644
--- a/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts
+++ b/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts
@@ -46,6 +46,7 @@ describe("OpenClaw plugin package and install contract", () => {
"adapters/",
"registries/",
"routing/",
+ "shared/",
"plugin/",
"services/",
"commands/setup.ts",
@@ -71,6 +72,7 @@ describe("OpenClaw plugin package and install contract", () => {
"config/feature-gates.json",
"registries/",
"routing/",
+ "shared/",
"plugin/",
"services/",
"install-manifest.json",
diff --git a/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts b/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts
index a01fb728c..d239fb719 100644
--- a/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts
+++ b/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts
@@ -60,18 +60,18 @@ describe("plugin normal flow with healthy backend", () => {
return;
}
- if (method === "POST" && url.pathname === "/api/v1/search/find") {
+ if (method === "POST" && url.pathname === "/api/v1/search/search") {
json(res, 200, {
result: {
- memories: [
- {
- uri: "viking://user/default/memories/rust-pref",
- level: 2,
- abstract: "User prefers Rust for backend tasks.",
- score: 0.91,
- },
- ],
- total: 1,
+ entries: [{
+ uri: "viking://user/default/memories/rust-pref",
+ category: "preferences",
+ detail: "abstract",
+ text: "User prefers Rust for backend tasks.",
+ score: 0.91,
+ }],
+ rendered: '<memory uri="viking://user/default/memories/rust-pref">User prefers Rust for backend tasks.</memory>',
+ stats: { candidates: 1, used_tokens: 18 },
},
status: "ok",
});
@@ -267,8 +267,31 @@ describe("plugin normal flow with healthy backend", () => {
expect(requests.some((entry) => entry.method === "GET" && entry.path === "/health")).toBe(true);
expect(
- requests.some((entry) => entry.method === "POST" && entry.path === "/api/v1/search/find"),
+ requests.some((entry) => entry.method === "POST" && entry.path === "/api/v1/search/search"),
).toBe(true);
+ const contextSearchRequest = requests.find(
+ (entry) => entry.method === "POST" && entry.path === "/api/v1/search/search",
+ );
+ const contextSearchBody = JSON.parse(contextSearchRequest?.body ?? "{}");
+ expect(contextSearchBody).toMatchObject({
+ mode: "context",
+ purpose: "coding",
+ quotas: {
+ events: 1,
+ entities: 1,
+ preferences: 1,
+ experiences: 1,
+ resources: 1,
+ skills: 1,
+ },
+ session_id: "session-normal",
+ context_type: "memory",
+ query_expansion: "auto",
+ max_tokens: 1000,
+ dedup_turns: 5,
+ peer_scope: "actor",
+ });
+ expect(contextSearchBody).not.toHaveProperty("limit");
expect(
requests.some((entry) => entry.method === "GET" && entry.path.startsWith("/api/v1/sessions/session-normal/context")),
).toBe(true);
diff --git a/examples/openclaw-plugin/tsconfig.build.json b/examples/openclaw-plugin/tsconfig.build.json
index 4b52ba731..3798c11e3 100644
--- a/examples/openclaw-plugin/tsconfig.build.json
+++ b/examples/openclaw-plugin/tsconfig.build.json
@@ -1,10 +1,16 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
+ "allowJs": true,
"noEmit": false,
"outDir": "dist",
"rootDir": "."
},
+ "include": [
+ "*.ts",
+ "commands/**/*.ts",
+ "shared/**/*.mjs"
+ ],
"exclude": [
"dist",
"node_modules",