Skip to content

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

fix(openclaw): restore peer_role routing (#3252)

Qin Haojieb27e326e4df9
diff --git a/examples/openclaw-plugin/auto-recall.ts b/examples/openclaw-plugin/auto-recall.ts
index 1538945cc..e6143d25a 100644
--- a/examples/openclaw-plugin/auto-recall.ts
+++ b/examples/openclaw-plugin/auto-recall.ts
@@ -313,6 +313,7 @@ export async function buildAutoRecallContext(params: {
queryConfig?: EffectiveQueryConfig;
client: OpenVikingClient;
agentId: string;
+ actorPeerId?: string;
queryText: string;
logger: Logger;
verbose?: (message: string) => void;
@@ -324,14 +325,14 @@ export async function buildAutoRecallContext(params: {
queryTruncated?: boolean;
resourceTypes?: RecallResourceType[];
}): Promise<{ block?: string; memoryCount: number; estimatedTokens: number }> {
- const { cfg, client, agentId, queryText, logger, verbose } = params;
+ const { cfg, client, agentId, actorPeerId, queryText, logger, verbose } = params;
const queryConfig = params.queryConfig;
if (!cfg.autoRecall || queryText.length < 5) {
return { memoryCount: 0, estimatedTokens: 0 };
}
- const precheck = await quickRecallPrecheck(client, agentId);
+ const precheck = await quickRecallPrecheck(client, actorPeerId);
if (!precheck.ok) {
verbose?.(`openviking: skipping auto-recall because precheck failed (${precheck.reason})`);
return { memoryCount: 0, estimatedTokens: 0 };
@@ -369,7 +370,7 @@ export async function buildAutoRecallContext(params: {
limit: candidateLimit,
scoreThreshold: 0,
contextType: search.contextType,
- actorPeerId: agentId,
+ actorPeerId,
});
return {
resourceType: search.resourceType,
@@ -484,7 +485,7 @@ export async function buildAutoRecallContext(params: {
const { lines: memoryLines, estimatedTokens } = await buildMemoryLinesWithBudget(
memories,
- (uri) => client.read(uri, agentId),
+ (uri) => client.read(uri, actorPeerId),
{
recallPreferAbstract,
recallMaxInjectedChars: maxInjectedChars,
diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.ts
index 9eb4cdfc0..576fad0e1 100644
--- a/examples/openclaw-plugin/context-engine.ts
+++ b/examples/openclaw-plugin/context-engine.ts
@@ -283,7 +283,6 @@ export function createMemoryOpenVikingContextEngine(params: {
getClient,
logger,
rememberSessionAgentId,
- resolveAgentId,
isBypassedSession,
});
}
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index d0ccfab0c..822856854 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -41,7 +41,7 @@ import {
import type { CommandDefinition } from "./plugin/command-registration.js";
import type { HttpTransport } from "./adapters/http-transport.js";
-import { formatMessageFaithful, toRoleId } from "./services/context-message-adapter.js";
+import { formatMessageFaithful } from "./services/context-message-adapter.js";
import {
clampScore,
postProcessMemories,
@@ -212,6 +212,7 @@ const contextEnginePlugin = {
resolvePluginSessionRouting,
toQueryConfigContext,
} = createOpenVikingSessionRoutingRuntime({
+ peerRole: cfg.peer_role,
peerPrefix: cfg.peer_prefix,
logFindRequests: cfg.logFindRequests,
logger: api.logger,
@@ -329,8 +330,7 @@ const contextEnginePlugin = {
getClient,
normalizeSessionId: openClawSessionRefToOvStorageId,
createTempSessionId: createMemoryStoreTempSessionId,
- extractSenderId: extractToolSenderId,
- toRoleId,
+ peerRole: cfg.peer_role,
resolvePluginSessionRouting,
isBypassedSession,
makeBypassedToolResult,
diff --git a/examples/openclaw-plugin/plugin/command-registration.ts b/examples/openclaw-plugin/plugin/command-registration.ts
index a414f0576..9d690d5e9 100644
--- a/examples/openclaw-plugin/plugin/command-registration.ts
+++ b/examples/openclaw-plugin/plugin/command-registration.ts
@@ -5,6 +5,8 @@ export type PluginCommandContext = {
sessionId?: string;
agentId?: string;
ovSessionId?: string;
+ senderId?: string;
+ requesterSenderId?: string;
};
export type CommandResult = {
diff --git a/examples/openclaw-plugin/plugin/openviking-archive-tools.ts b/examples/openclaw-plugin/plugin/openviking-archive-tools.ts
index 229812594..6bb11a21a 100644
--- a/examples/openclaw-plugin/plugin/openviking-archive-tools.ts
+++ b/examples/openclaw-plugin/plugin/openviking-archive-tools.ts
@@ -26,7 +26,7 @@ export type OpenVikingArchiveClient = {
grepSessionArchives: (
sessionId: string,
pattern: string,
- options: { archiveId?: string; caseInsensitive: boolean; agentId?: string },
+ options: { archiveId?: string; caseInsensitive: boolean },
) => Promise<{
count?: number;
matches?: OpenVikingArchiveMatch[];
@@ -34,7 +34,6 @@ export type OpenVikingArchiveClient = {
getSessionArchive: (
sessionId: string,
archiveId: string,
- agentId?: string,
) => Promise<{
archive_id: string;
abstract?: string;
@@ -128,7 +127,6 @@ export function registerOpenVikingArchiveTools(deps: OpenVikingArchiveToolsDeps)
const result = await client.grepSessionArchives(ovSessionId, escapedQuery, {
archiveId,
caseInsensitive: true,
- agentId,
});
const traceResults: RecallTraceResult[] = (result.matches ?? []).slice(0, deps.traceRecallMaxResultsPerSearch).map((match) => ({
uri: match.uri,
@@ -263,7 +261,6 @@ export function registerOpenVikingArchiveTools(deps: OpenVikingArchiveToolsDeps)
const detail = await client.getSessionArchive(
session.ovSessionId,
archiveId,
- session.agentId,
);
const header = [
diff --git a/examples/openclaw-plugin/plugin/openviking-command-definitions.ts b/examples/openclaw-plugin/plugin/openviking-command-definitions.ts
index 0c1edb999..6608257e3 100644
--- a/examples/openclaw-plugin/plugin/openviking-command-definitions.ts
+++ b/examples/openclaw-plugin/plugin/openviking-command-definitions.ts
@@ -6,6 +6,7 @@ export type OpenVikingCommandSession = {
sessionKey?: string;
ovSessionId?: string;
agentId: string;
+ actorPeerId?: string;
};
export type OpenVikingCommandToolResult = {
@@ -217,7 +218,7 @@ export function createOpenVikingCommandDefinitions(
}
const session = deps.resolvePluginSessionRouting(ctx);
const input = deps.parseAddResourceCommandArgs(ctx.args ?? "");
- return toCommandResult(await deps.addResourceOpenViking(input, session.agentId));
+ return toCommandResult(await deps.addResourceOpenViking(input, session.actorPeerId));
} catch (err) {
return { text: `OpenViking add resource failed: ${err instanceof Error ? err.message : String(err)}` };
}
@@ -234,7 +235,7 @@ export function createOpenVikingCommandDefinitions(
}
const session = deps.resolvePluginSessionRouting(ctx);
const input = deps.parseAddSkillCommandArgs(ctx.args ?? "");
- return toCommandResult(await deps.addSkillOpenViking(input, session.agentId));
+ return toCommandResult(await deps.addSkillOpenViking(input, session.actorPeerId));
} catch (err) {
return { text: `OpenViking add skill failed: ${err instanceof Error ? err.message : String(err)}` };
}
@@ -251,7 +252,7 @@ export function createOpenVikingCommandDefinitions(
}
const session = deps.resolvePluginSessionRouting(ctx);
const input = deps.parseOVSearchCommandArgs(ctx.args ?? "");
- return toCommandResult(await deps.searchOpenViking(input, session.agentId, session));
+ return toCommandResult(await deps.searchOpenViking(input, session.actorPeerId, session));
} catch (err) {
return { text: `OpenViking search failed: ${err instanceof Error ? err.message : String(err)}` };
}
diff --git a/examples/openclaw-plugin/plugin/openviking-import-tools.ts b/examples/openclaw-plugin/plugin/openviking-import-tools.ts
index 96f8d6cbb..9ae24d35d 100644
--- a/examples/openclaw-plugin/plugin/openviking-import-tools.ts
+++ b/examples/openclaw-plugin/plugin/openviking-import-tools.ts
@@ -12,6 +12,7 @@ export type OpenVikingImportToolContext = {
sessionId?: string;
agentId?: string;
senderId?: string;
+ requesterSenderId?: string;
};
export type OpenVikingImportSession = {
@@ -19,6 +20,7 @@ export type OpenVikingImportSession = {
sessionKey?: string;
ovSessionId?: string;
agentId: string;
+ actorPeerId?: string;
};
export type OpenVikingImportClient = {
@@ -80,7 +82,7 @@ export function registerOpenVikingImportTools(deps: OpenVikingImportToolsDeps):
instruction: typeof params.instruction === "string" ? params.instruction : undefined,
wait: typeof params.wait === "boolean" ? params.wait : undefined,
timeout: typeof params.timeout === "number" ? params.timeout : undefined,
- }, session.agentId);
+ }, session.actorPeerId);
return {
content: [{ type: "text" as const, text: formatResourceImportText(result) }],
details: {
@@ -118,7 +120,7 @@ export function registerOpenVikingImportTools(deps: OpenVikingImportToolsDeps):
data: params.data,
wait: typeof params.wait === "boolean" ? params.wait : undefined,
timeout: typeof params.timeout === "number" ? params.timeout : undefined,
- }, session.agentId);
+ }, session.actorPeerId);
return {
content: [{ type: "text" as const, text: formatSkillImportText(result) }],
details: {
diff --git a/examples/openclaw-plugin/plugin/openviking-memory-recall-tools.ts b/examples/openclaw-plugin/plugin/openviking-memory-recall-tools.ts
index 98b8d02e9..1913e850d 100644
--- a/examples/openclaw-plugin/plugin/openviking-memory-recall-tools.ts
+++ b/examples/openclaw-plugin/plugin/openviking-memory-recall-tools.ts
@@ -15,6 +15,7 @@ export type OpenVikingMemoryRecallToolContext = {
sessionId?: string;
agentId?: string;
senderId?: string;
+ requesterSenderId?: string;
};
export type OpenVikingMemoryRecallSession = {
@@ -22,6 +23,7 @@ export type OpenVikingMemoryRecallSession = {
sessionKey?: string;
ovSessionId?: string;
agentId: string;
+ actorPeerId?: string;
};
export type OpenVikingMemoryRecallClient = {
@@ -163,7 +165,7 @@ export function registerOpenVikingMemoryRecallTools(
const recallClient = await deps.getClient();
if (deps.cfg.logFindRequests) {
deps.logger.info?.(
- `openviking: memory_recall X-OpenViking-Actor-Peer="${session.agentId}" ` +
+ `openviking: memory_recall X-OpenViking-Actor-Peer="${session.actorPeerId ?? "none"}" ` +
`(plugin defaultAgentId="${recallClient.getDefaultAgentId()}" is unused when session context is present)`,
);
}
@@ -177,7 +179,7 @@ export function registerOpenVikingMemoryRecallTools(
targetUri,
limit: requestLimit,
scoreThreshold: 0,
- actorPeerId: session.agentId,
+ actorPeerId: session.actorPeerId,
},
);
const traceResults = [
@@ -207,7 +209,7 @@ export function registerOpenVikingMemoryRecallTools(
limit: requestLimit,
scoreThreshold: 0,
contextType: search.contextType,
- actorPeerId: session.agentId,
+ actorPeerId: session.actorPeerId,
},
),
));
@@ -319,7 +321,7 @@ export function registerOpenVikingMemoryRecallTools(
}
const { lines: memoryLines } = await deps.buildMemoryLinesWithBudget(
memories,
- (uri) => recallClient.read(uri, session.agentId),
+ (uri) => recallClient.read(uri, session.actorPeerId),
{
recallPreferAbstract: false,
recallMaxInjectedChars: queryConfig.maxInjectedChars,
diff --git a/examples/openclaw-plugin/plugin/openviking-memory-tools.ts b/examples/openclaw-plugin/plugin/openviking-memory-tools.ts
index 43d805080..64de6fb42 100644
--- a/examples/openclaw-plugin/plugin/openviking-memory-tools.ts
+++ b/examples/openclaw-plugin/plugin/openviking-memory-tools.ts
@@ -2,6 +2,10 @@ import { Type } from "@sinclair/typebox";
import type { CommitSessionResult, FindResultItem } from "../client.js";
import { clampScore, postProcessMemories } from "../memory-ranking.js";
+import {
+ resolveOpenVikingMessagePeerId,
+ type OpenVikingPeerRole,
+} from "../routing/identity-routing.js";
import { isMemoryUri } from "../routing/memory-uri.js";
export type OpenVikingMemoryToolContext = {
@@ -17,6 +21,7 @@ export type OpenVikingMemorySession = {
sessionKey?: string;
ovSessionId?: string;
agentId: string;
+ actorPeerId?: string;
};
export type OpenVikingMemoryClient = {
@@ -30,7 +35,7 @@ export type OpenVikingMemoryClient = {
) => Promise<void>;
commitSession: (
sessionId: string,
- options: { wait: true; agentId: string; keepRecentCount: number },
+ options: { wait: true; agentId?: string; keepRecentCount: number },
) => Promise<CommitSessionResult>;
deleteUri: (uri: string, agentId?: string) => Promise<void>;
find: (
@@ -45,8 +50,7 @@ export type OpenVikingMemoryToolsDeps = {
getClient: () => Promise<OpenVikingMemoryClient>;
normalizeSessionId: (sessionId: string) => string;
createTempSessionId: () => string;
- extractSenderId: (ctx?: OpenVikingMemoryToolContext) => string | undefined;
- toRoleId: (senderId?: string) => string | undefined;
+ peerRole: OpenVikingPeerRole;
resolvePluginSessionRouting: (ctx?: OpenVikingMemoryToolContext) => OpenVikingMemorySession;
isBypassedSession: (ctx?: OpenVikingMemoryToolContext) => boolean;
makeBypassedToolResult: (toolName: string) => unknown;
@@ -107,18 +111,22 @@ export function registerOpenVikingMemoryTools(deps: OpenVikingMemoryToolsDeps):
sessionId = deps.createTempSessionId();
usedTempSession = true;
}
- const roleId = role === "user" ? deps.toRoleId(deps.extractSenderId(ctx)) : undefined;
+ const peerId = resolveOpenVikingMessagePeerId({
+ peerRole: deps.peerRole,
+ role,
+ personPeerId: session.actorPeerId,
+ assistantPeerId: session.actorPeerId,
+ });
await client.addSessionMessage(
sessionId,
role,
[{ type: "text", text }],
- session.agentId,
undefined,
- roleId,
+ undefined,
+ peerId,
);
const commitResult = await client.commitSession(sessionId, {
wait: true,
- agentId: session.agentId,
keepRecentCount: 0,
});
const memoriesCount = totalCommitMemories(commitResult);
@@ -216,7 +224,7 @@ export function registerOpenVikingMemoryTools(deps: OpenVikingMemoryToolsDeps):
details: { action: "rejected", uri },
};
}
- await client.deleteUri(uri, session.agentId);
+ await client.deleteUri(uri, session.actorPeerId);
return {
content: [{ type: "text", text: `Forgotten: ${uri}` }],
details: { action: "deleted", uri },
@@ -252,7 +260,7 @@ export function registerOpenVikingMemoryTools(deps: OpenVikingMemoryToolsDeps):
limit: requestLimit,
scoreThreshold: 0,
},
- session.agentId,
+ session.actorPeerId,
);
const candidates = postProcessMemories(result.memories ?? [], {
limit: requestLimit,
@@ -272,7 +280,7 @@ export function registerOpenVikingMemoryTools(deps: OpenVikingMemoryToolsDeps):
}
const top = candidates[0];
if (candidates.length === 1 && clampScore(top.score) >= 0.85) {
- await client.deleteUri(top.uri, session.agentId);
+ await client.deleteUri(top.uri, session.actorPeerId);
return {
content: [{ type: "text", text: `Forgotten: ${top.uri}` }],
details: { action: "deleted", uri: top.uri, score: top.score ?? 0 },
diff --git a/examples/openclaw-plugin/plugin/openviking-query-runtime.ts b/examples/openclaw-plugin/plugin/openviking-query-runtime.ts
index c57c50494..c0f6aed68 100644
--- a/examples/openclaw-plugin/plugin/openviking-query-runtime.ts
+++ b/examples/openclaw-plugin/plugin/openviking-query-runtime.ts
@@ -445,7 +445,7 @@ export function createOpenVikingQueryRuntime<TQueryConfigContext>(deps: OpenViki
sessionId: traceCtx?.sessionId,
sessionKey: traceCtx?.sessionKey,
ovSessionId: traceCtx?.ovSessionId,
- agentId,
+ agentId: traceCtx?.agentId,
source: "ov_search",
operationType: "semantic_find",
resourceTypes: [...new Set(searches.map((search) => search.resourceType).filter((resourceType): resourceType is RecallResourceType => resourceType !== "archive"))],
diff --git a/examples/openclaw-plugin/plugin/openviking-query-tools.ts b/examples/openclaw-plugin/plugin/openviking-query-tools.ts
index 582c3c1d6..a0f02270e 100644
--- a/examples/openclaw-plugin/plugin/openviking-query-tools.ts
+++ b/examples/openclaw-plugin/plugin/openviking-query-tools.ts
@@ -5,6 +5,7 @@ export type OpenVikingQueryToolContext = {
sessionId?: string;
agentId?: string;
senderId?: string;
+ requesterSenderId?: string;
};
export type OpenVikingQuerySession = {
@@ -12,6 +13,7 @@ export type OpenVikingQuerySession = {
sessionKey?: string;
ovSessionId?: string;
agentId: string;
+ actorPeerId?: string;
};
export type OVSearchInput = {
@@ -74,7 +76,7 @@ export function registerOpenVikingQueryTools(deps: OpenVikingQueryToolsDeps): vo
query: String((params as { query?: unknown }).query ?? ""),
uri: typeof params.uri === "string" ? params.uri : undefined,
limit: typeof params.limit === "number" ? params.limit : undefined,
- }, session.agentId, session);
+ }, session.actorPeerId, session);
},
}),
{ name: "ov_search" },
@@ -99,7 +101,7 @@ export function registerOpenVikingQueryTools(deps: OpenVikingQueryToolsDeps): vo
const session = deps.resolvePluginSessionRouting(ctx);
return deps.readOpenVikingContent({
uri: String((params as { uri?: unknown }).uri ?? ""),
- }, session.agentId);
+ }, session.actorPeerId);
},
}),
{ name: "ov_read" },
@@ -125,7 +127,7 @@ export function registerOpenVikingQueryTools(deps: OpenVikingQueryToolsDeps): vo
const uris = Array.isArray((params as { uris?: unknown }).uris)
? (params as { uris: unknown[] }).uris.map((uri) => String(uri))
: [];
- return deps.multiReadOpenVikingContent({ uris }, session.agentId);
+ return deps.multiReadOpenVikingContent({ uris }, session.actorPeerId);
},
}),
{ name: "ov_multi_read" },
@@ -153,7 +155,7 @@ export function registerOpenVikingQueryTools(deps: OpenVikingQueryToolsDeps): vo
recursive: typeof params.recursive === "boolean" ? params.recursive : undefined,
simple: typeof params.simple === "boolean" ? params.simple : undefined,
limit: typeof params.limit === "number" ? params.limit : undefined,
- }, session.agentId);
+ }, session.actorPeerId);
},
}),
{ name: "ov_list" },
diff --git a/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts b/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts
index 540eac7ba..82921b099 100644
--- a/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts
+++ b/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts
@@ -26,6 +26,7 @@ export type OpenVikingRecallTraceSession = {
sessionKey?: string;
ovSessionId?: string;
agentId: string;
+ actorPeerId?: string;
};
export type OpenVikingRecallTraceQueryResult = {
@@ -248,11 +249,11 @@ export function createOpenVikingRecallTraceRuntime(deps: OpenVikingRecallTraceRu
for (const fallbackQuery of fallbackIdentities) {
const fallback = await deps.traceRecorder.queryWithFallback(fallbackQuery);
if (fallback.entries.length > 0) {
- return enrichTraceEntriesWithContent(fallback, shouldIncludeTraceContent(input), session.agentId);
+ return enrichTraceEntriesWithContent(fallback, shouldIncludeTraceContent(input), session.actorPeerId);
}
}
}
- return enrichTraceEntriesWithContent(base, shouldIncludeTraceContent(input), session.agentId);
+ return enrichTraceEntriesWithContent(base, shouldIncludeTraceContent(input), session.actorPeerId);
};
const handleUriDetail = async (request?: RecallTraceRouteRequest) => {
@@ -298,7 +299,7 @@ export function createOpenVikingRecallTraceRuntime(deps: OpenVikingRecallTraceRu
}
try {
const client = await deps.getClient();
- const content = await client.read(uri, toString(query.agentId) ?? session.agentId);
+ const content = await client.read(uri, session.actorPeerId);
const text = typeof content === "string" ? content : JSON.stringify(content, null, 2);
const chars = Array.from(text);
const slice = chars.slice(offset, offset + contentLimit).join("");
diff --git a/examples/openclaw-plugin/plugin/openviking-recall-trace-tools.ts b/examples/openclaw-plugin/plugin/openviking-recall-trace-tools.ts
index de294f83c..604d571ec 100644
--- a/examples/openclaw-plugin/plugin/openviking-recall-trace-tools.ts
+++ b/examples/openclaw-plugin/plugin/openviking-recall-trace-tools.ts
@@ -11,6 +11,7 @@ export type OpenVikingRecallTraceToolContext = {
sessionId?: string;
agentId?: string;
senderId?: string;
+ requesterSenderId?: string;
};
export type OpenVikingRecallTraceSession = {
@@ -18,6 +19,7 @@ export type OpenVikingRecallTraceSession = {
sessionKey?: string;
ovSessionId?: string;
agentId: string;
+ actorPeerId?: string;
};
export type RecallTraceToolInput = {
diff --git a/examples/openclaw-plugin/plugin/openviking-session-routing-runtime.ts b/examples/openclaw-plugin/plugin/openviking-session-routing-runtime.ts
index 48fcb1e3c..f6b8cd4ef 100644
--- a/examples/openclaw-plugin/plugin/openviking-session-routing-runtime.ts
+++ b/examples/openclaw-plugin/plugin/openviking-session-routing-runtime.ts
@@ -2,6 +2,9 @@ import type { QueryConfigContext } from "../query-config.js";
import {
createSessionAgentResolver,
openClawSessionToOvStorageId,
+ resolveOpenVikingActorPeerId,
+ sanitizeOpenVikingPeerId,
+ type OpenVikingPeerRole,
} from "../routing/identity-routing.js";
type Logger = {
@@ -10,6 +13,8 @@ type Logger = {
export type SessionAgentLookup = {
agentId?: string;
+ senderId?: string;
+ requesterSenderId?: string;
sessionId?: string;
sessionKey?: string;
ovSessionId?: string;
@@ -20,13 +25,16 @@ export type PluginSessionRouting = {
sessionKey?: string;
ovSessionId?: string;
agentId: string;
+ actorPeerId?: string;
};
export function createOpenVikingSessionRoutingRuntime(options: {
+ peerRole?: OpenVikingPeerRole;
peerPrefix: string;
logFindRequests: boolean;
logger: Logger;
}) {
+ const peerRole = options.peerRole ?? "assistant";
const sessionAgentResolver = createSessionAgentResolver(options.peerPrefix);
const rememberSessionAgentId = (ctx: SessionAgentLookup) => {
@@ -81,11 +89,17 @@ export function createOpenVikingSessionRoutingRuntime(options: {
};
rememberSessionAgentId(session);
+ const agentId = resolveAgentId(session.sessionId, session.sessionKey, session.ovSessionId);
return {
sessionId: session.sessionId,
sessionKey: session.sessionKey,
ovSessionId: session.ovSessionId,
- agentId: resolveAgentId(session.sessionId, session.sessionKey, session.ovSessionId),
+ agentId,
+ actorPeerId: resolveOpenVikingActorPeerId({
+ peerRole,
+ personPeerId: sanitizeOpenVikingPeerId(ctx?.requesterSenderId ?? ctx?.senderId),
+ assistantPeerId: agentId,
+ }),
};
};
diff --git a/examples/openclaw-plugin/plugin/openviking-tool-result-tools.ts b/examples/openclaw-plugin/plugin/openviking-tool-result-tools.ts
index 6a37a98e1..d1896d299 100644
--- a/examples/openclaw-plugin/plugin/openviking-tool-result-tools.ts
+++ b/examples/openclaw-plugin/plugin/openviking-tool-result-tools.ts
@@ -27,7 +27,6 @@ export type OpenVikingToolResultClient = {
sessionId: string,
toolResultId: string,
options: { offset: number; limit: number; includeMetadata: boolean },
- agentId?: string,
) => Promise<{
content: string;
offset: number;
@@ -42,7 +41,6 @@ export type OpenVikingToolResultClient = {
toolResultId: string,
query: string,
options: { limit: number; contextChars: number },
- agentId?: string,
) => Promise<{
tool_result_id: string;
matches?: Array<{ offset: number; snippet: string }>;
@@ -50,7 +48,6 @@ export type OpenVikingToolResultClient = {
listToolResults: (
sessionId: string,
options: { toolName?: string; limit: number },
- agentId?: string,
) => Promise<{
tool_results?: Array<{
storage_uri?: string;
@@ -180,7 +177,6 @@ export function registerOpenVikingToolResultTools({
session.ovSessionId,
parsed.toolResultId,
{ offset, limit, includeMetadata: true },
- session.agentId,
);
const returnedChars = result.content.length;
const nextOffset = result.offset + returnedChars;
@@ -281,7 +277,6 @@ export function registerOpenVikingToolResultTools({
parsed.toolResultId,
query,
{ limit, contextChars },
- session.agentId,
);
const matches = result.matches ?? [];
const text = matches.length
@@ -354,7 +349,6 @@ export function registerOpenVikingToolResultTools({
const result = await client.listToolResults(
session.ovSessionId,
{ toolName, limit },
- session.agentId,
);
const items = result.tool_results ?? [];
const text = items.length
diff --git a/examples/openclaw-plugin/routing/identity-routing.ts b/examples/openclaw-plugin/routing/identity-routing.ts
index e9828e59a..8a075aaca 100644
--- a/examples/openclaw-plugin/routing/identity-routing.ts
+++ b/examples/openclaw-plugin/routing/identity-routing.ts
@@ -15,6 +15,47 @@ export type SessionAgentLookup = {
ovSessionId?: string;
};
+export type OpenVikingPeerRole = "none" | "assistant" | "person";
+
+export function sanitizeOpenVikingPeerId(raw?: string): string | undefined {
+ const normalized = raw
+ ?.trim()
+ .replace(/[^a-zA-Z0-9_-]+/g, "_")
+ .replace(/^_+|_+$/g, "")
+ .replace(/_+/g, "_");
+ return normalized || undefined;
+}
+
+export function resolveOpenVikingMessagePeerId(params: {
+ peerRole: OpenVikingPeerRole;
+ role?: string;
+ personPeerId?: string;
+ assistantPeerId?: string;
+}): string | undefined {
+ if (params.peerRole === "person" && params.role === "user") {
+ return params.personPeerId;
+ }
+ if (params.peerRole === "assistant" && params.role === "assistant") {
+ return params.assistantPeerId;
+ }
+ return undefined;
+}
+
+export function resolveOpenVikingActorPeerId(params: {
+ peerRole: OpenVikingPeerRole;
+ personPeerId?: string;
+ assistantPeerId?: string;
+}): string | undefined {
+ const actorPeerId = resolveOpenVikingMessagePeerId({
+ ...params,
+ role: params.peerRole === "person" ? "user" : "assistant",
+ });
+ if (params.peerRole === "person" && !actorPeerId) {
+ throw new Error("openviking: peer_role=person requires a sender identity");
+ }
+ return actorPeerId;
+}
+
export type SessionAgentResolveBranch =
| "session_resolved"
| "config_only_fallback"
diff --git a/examples/openclaw-plugin/routing/memory-uri.ts b/examples/openclaw-plugin/routing/memory-uri.ts
index 4e9c2e783..cc79441b3 100644
--- a/examples/openclaw-plugin/routing/memory-uri.ts
+++ b/examples/openclaw-plugin/routing/memory-uri.ts
@@ -1,5 +1,6 @@
const MEMORY_URI_PATTERNS = [
/^viking:\/\/user\/(?:[^/]+(?:\/agent\/[^/]+)?\/)?memories(?:\/|$)/,
+ /^viking:\/\/user\/[^/]+\/peers\/[^/]+\/memories(?:\/|$)/,
/^viking:\/\/agent\/(?:[^/]+(?:\/user\/[^/]+)?\/)?memories(?:\/|$)/,
];
diff --git a/examples/openclaw-plugin/services/context-lifecycle-service.ts b/examples/openclaw-plugin/services/context-lifecycle-service.ts
index a714f2c14..dc8a30c92 100644
--- a/examples/openclaw-plugin/services/context-lifecycle-service.ts
+++ b/examples/openclaw-plugin/services/context-lifecycle-service.ts
@@ -3,7 +3,13 @@ import { DEFAULT_PHASE2_POLL_TIMEOUT_MS, type OpenVikingClient, type OVMessage }
import type { EffectiveQueryConfig } from "../query-config.js";
import { buildAutoRecallContext, prepareRecallQuery } from "../auto-recall.js";
import { toJsonLog } from "../memory-ranking.js";
-import { openClawSessionToOvStorageId } from "../routing/identity-routing.js";
+import {
+ openClawSessionToOvStorageId,
+ resolveOpenVikingActorPeerId,
+ resolveOpenVikingMessagePeerId,
+ sanitizeOpenVikingPeerId,
+ type OpenVikingPeerRole,
+} from "../routing/identity-routing.js";
import { extractNewTurnMessages } from "../text-utils.js";
import { estimateAgentMessageTokens, estimateTextTokens } from "../token-estimator.js";
import {
@@ -26,7 +32,6 @@ export type CommitOpenVikingSessionParams = {
sessionKey?: string;
getClient: () => Promise<Pick<OpenVikingClient, "commitSession">>;
logger: ContextEngineLifecycleLogger;
- resolveAgentId: (sessionId: string, sessionKey?: string, ovSessionId?: string) => string;
rememberSessionAgentId?: (ctx: {
agentId?: string;
sessionId?: string;
@@ -131,6 +136,7 @@ export type AfterTurnOpenVikingSessionParams = {
commitTokenThresholdRatio: number;
commitKeepRecentCount: number;
logFindRequests: boolean;
+ peer_role?: OpenVikingPeerRole;
};
getClient: () => Promise<AfterTurnClient>;
logger: ContextEngineLifecycleLogger;
@@ -177,7 +183,6 @@ function sleep(ms: number): Promise<void> {
async function pollPhase2ExtractionOutcome(
client: AfterTurnClient,
taskId: string,
- agentId: string,
logger: ContextEngineLifecycleLogger,
sessionLabel: string,
): Promise<void> {
@@ -185,7 +190,7 @@ async function pollPhase2ExtractionOutcome(
try {
while (Date.now() < deadline) {
await sleep(PHASE2_POLL_INTERVAL_MS);
- const task = await client.getTask(taskId, agentId).catch((e) => {
+ const task = await client.getTask(taskId).catch((e) => {
logger.warn?.(`openviking: phase2 getTask failed task_id=${taskId}: ${String(e)}`);
return null;
});
@@ -340,7 +345,6 @@ export async function commitOpenVikingSession({
sessionKey,
getClient,
logger,
- resolveAgentId,
rememberSessionAgentId,
isBypassedSession,
}: CommitOpenVikingSessionParams): Promise<boolean> {
@@ -358,10 +362,8 @@ export async function commitOpenVikingSession({
sessionKey,
ovSessionId: ovId,
});
- const agentId = resolveAgentId(sessionId, sessionKey, ovId);
const commitResult = await client.commitSession(ovId, {
wait: true,
- agentId,
keepRecentCount: 0,
});
const memCount = totalExtractedMemories(commitResult.memories_extracted);
@@ -492,6 +494,11 @@ export async function assembleOpenVikingSession({
const client = await getClient();
const routingRef = sessionId ?? sessionKey ?? ovSessionId;
const agentId = resolveAgentId(routingRef, sessionKey, ovSessionId);
+ const actorPeerId = resolveOpenVikingActorPeerId({
+ peerRole: cfg.peer_role ?? "assistant",
+ personPeerId: sanitizeOpenVikingPeerId(sender.senderId),
+ assistantPeerId: agentId,
+ });
const queryConfig = await queryConfigStore?.getEffective({
agentId,
sessionId,
@@ -503,6 +510,7 @@ export async function assembleOpenVikingSession({
queryConfig,
client,
agentId,
+ actorPeerId,
queryText: recallQuery.query,
logger,
verbose: (message) => logger.info(message),
@@ -553,9 +561,7 @@ export async function assembleOpenVikingSession({
try {
const client = await getClient();
- const routingRef = sessionId ?? sessionKey ?? ovSessionId;
- const agentId = resolveAgentId(routingRef, sessionKey, ovSessionId);
- const ctx = await client.getSessionContext(ovSessionId, tokenBudget, agentId);
+ const ctx = await client.getSessionContext(ovSessionId, tokenBudget);
const preAbstracts = ctx?.pre_archive_abstracts ?? [];
const hasArchives = !!ctx?.latest_archive_overview || preAbstracts.length > 0;
@@ -899,14 +905,19 @@ export async function afterTurnOpenVikingSession({
ovSessionId,
msg.role,
ovParts,
- agentId,
+ undefined,
createdAt,
- msg.role === "user" ? senderRoleId : undefined,
+ resolveOpenVikingMessagePeerId({
+ peerRole: cfg.peer_role ?? "assistant",
+ role: msg.role,
+ personPeerId: senderRoleId,
+ assistantPeerId: agentId,
+ }),
);
}
}
- const session = await client.getSession(ovSessionId, agentId);
+ const session = await client.getSession(ovSessionId);
const pendingTokens = session.pending_tokens ?? 0;
const commitTokenThreshold = Math.floor(tokenBudget * cfg.commitTokenThresholdRatio);
@@ -926,7 +937,6 @@ export async function afterTurnOpenVikingSession({
const commitResult = await client.commitSession(ovSessionId, {
wait: false,
- agentId,
keepRecentCount: cfg.commitKeepRecentCount,
});
logger.info(
@@ -952,7 +962,7 @@ export async function afterTurnOpenVikingSession({
`openviking: Phase2 memory extraction runs asynchronously on the server (task_id=${commitResult.task_id}). ` +
"memories_extracted appears only after that task completes — not in this immediate response.",
);
- void pollPhase2ExtractionOutcome(client, commitResult.task_id, agentId, logger, ovSessionId);
+ void pollPhase2ExtractionOutcome(client, commitResult.task_id, logger, ovSessionId);
}
} catch (err) {
logger.warn?.(`openviking: afterTurn failed: ${String(err)}`);
@@ -1033,7 +1043,7 @@ export async function compactOpenVikingSession({
let preCommitEstimatedTokens: number | undefined;
if (typeof tokensBeforeOriginal !== "number") {
try {
- const preCtx = await client.getSessionContext(ovSessionId, tokenBudget, agentId);
+ const preCtx = await client.getSessionContext(ovSessionId, tokenBudget);
if (typeof preCtx.estimatedTokens === "number" && Number.isFinite(preCtx.estimatedTokens)) {
preCommitEstimatedTokens = preCtx.estimatedTokens;
}
@@ -1053,7 +1063,6 @@ export async function compactOpenVikingSession({
);
const commitResult = await client.commitSession(ovSessionId, {
wait: true,
- agentId,
keepRecentCount: 0,
});
const memCount = totalExtractedMemories(commitResult.memories_extracted);
@@ -1129,7 +1138,7 @@ export async function compactOpenVikingSession({
let contextFetchError: string | undefined;
try {
- const ctx = await client.getSessionContext(ovSessionId, tokenBudget, agentId);
+ const ctx = await client.getSessionContext(ovSessionId, tokenBudget);
logger.info(
`openviking: compact getSessionContext raw result for ${ovSessionId}: ` +
JSON.stringify(ctx, null, 2),
diff --git a/examples/openclaw-plugin/services/context-message-adapter.ts b/examples/openclaw-plugin/services/context-message-adapter.ts
index bc68a30b4..4900d0064 100644
--- a/examples/openclaw-plugin/services/context-message-adapter.ts
+++ b/examples/openclaw-plugin/services/context-message-adapter.ts
@@ -1,4 +1,5 @@
import type { OVMessage } from "../client.js";
+import { sanitizeOpenVikingPeerId } from "../routing/identity-routing.js";
import { sanitizeToolUseResultPairing } from "../session-transcript-repair.js";
export type AgentMessage = {
@@ -8,15 +9,7 @@ export type AgentMessage = {
};
export function toRoleId(senderId: string | undefined): string | undefined {
- if (!senderId) {
- return undefined;
- }
- const normalized = senderId
- .trim()
- .replace(/[^a-zA-Z0-9_-]+/g, "_")
- .replace(/^_+|_+$/g, "")
- .replace(/_+/g, "_");
- return normalized || undefined;
+ return sanitizeOpenVikingPeerId(senderId);
}
/**
diff --git a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
index 8aefd7db3..80c4643ab 100644
--- a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
+++ b/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
@@ -114,8 +114,7 @@ describe("context-engine assemble()", () => {
tokenBudget: 4096,
});
- expect(resolveAgentId).toHaveBeenCalledWith("session-1", undefined, "session-1");
- expect(client.getSessionContext).toHaveBeenCalledWith("session-1", 4096, "agent:session-1");
+ expect(client.getSessionContext).toHaveBeenCalledWith("session-1", 4096);
expect(result.estimatedTokens).toBe(
roughEstimate(result.messages) + systemPromptTokens(result.systemPromptAddition),
);
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
index 27f10c500..4b2676565 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
@@ -221,7 +221,7 @@ describe("context-engine afterTurn()", () => {
);
});
- it("passes sanitized senderId as role_id", async () => {
+ it("does not attribute user messages to the sender in assistant mode", async () => {
const { engine, client } = makeEngine();
await engine.afterTurn!({
@@ -233,7 +233,8 @@ describe("context-engine afterTurn()", () => {
});
expect(client.addSessionMessage).toHaveBeenCalledTimes(1);
- expect(client.addSessionMessage.mock.calls[0][5]).toBe("telegram_12345");
+ expect(client.addSessionMessage.mock.calls[0][3]).toBeUndefined();
+ expect(client.addSessionMessage.mock.calls[0][5]).toBeUndefined();
});
it("sanitizes <relevant-memories> from user content but not from assistant", async () => {
@@ -436,7 +437,7 @@ describe("context-engine afterTurn()", () => {
expect(assistantParts.map(p => p.text).join(" ")).toContain("export const x = 1");
});
- it("passes agentId to addSessionMessage", async () => {
+ it("does not pass actor peer to addSessionMessage", async () => {
const { engine, client } = makeEngine();
await engine.afterTurn!({
@@ -447,8 +448,7 @@ describe("context-engine afterTurn()", () => {
});
expect(client.addSessionMessage).toHaveBeenCalledTimes(1);
- const agentId = client.addSessionMessage.mock.calls[0][3] as string;
- expect(agentId).toBe("test-agent");
+ expect(client.addSessionMessage.mock.calls[0][3]).toBeUndefined();
});
it("checks pending tokens after addSessionMessage", async () => {
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 9b0660b06..4295a2d8e 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts
@@ -403,15 +403,9 @@ describe("context-engine assemble()", () => {
availableTools: new Set(),
});
- expect(resolveAgentId).toHaveBeenCalledWith(
- "session-main-no-prompt",
- undefined,
- "session-main-no-prompt",
- );
expect(client.getSessionContext).toHaveBeenCalledWith(
"session-main-no-prompt",
4096,
- "agent:session-main-no-prompt",
);
expect(client.find).not.toHaveBeenCalled();
expect(result.messages[0]).toEqual({
@@ -471,8 +465,7 @@ describe("context-engine assemble()", () => {
tokenBudget: 4096,
});
- expect(resolveAgentId).toHaveBeenCalledWith("session-1", undefined, "session-1");
- expect(client.getSessionContext).toHaveBeenCalledWith("session-1", 4096, "agent:session-1");
+ expect(client.getSessionContext).toHaveBeenCalledWith("session-1", 4096);
expect(result.estimatedTokens).toBe(
roughEstimate(result.messages) + systemPromptTokens(result.systemPromptAddition),
);
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
index 8f6b3326a..41e3b5601 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts
@@ -115,7 +115,7 @@ describe("context-engine commitOVSession()", () => {
});
it("uses sessionKey-derived OV session ID for commitOVSession", async () => {
- const { engine, client, resolveAgentId } = makeEngine({
+ const { engine, client } = makeEngine({
status: "completed",
archived: false,
memories_extracted: {},
@@ -128,7 +128,6 @@ describe("context-engine commitOVSession()", () => {
const ovSessionId = openClawSessionToOvStorageId("plain-session", "agent:main:main");
expect(client.commitSession.mock.calls[0][0]).toBe(ovSessionId);
- expect(resolveAgentId).toHaveBeenCalledWith("plain-session", "agent:main:main", ovSessionId);
});
it("logs memories extracted count", async () => {
@@ -394,7 +393,7 @@ describe("context-engine compact()", () => {
expect(resolveAgentId).toHaveBeenCalledWith("plain-session", "agent:top:main", ovSessionId);
});
- it("passes agentId to commitSession", async () => {
+ it("omits actor peer from aggregate session commits", async () => {
const { engine, client } = makeEngine({
status: "completed",
archived: false,
@@ -403,8 +402,9 @@ describe("context-engine compact()", () => {
await engine.compact({ sessionId: "s1", sessionFile: "" });
- expect(client.commitSession.mock.calls[0][1]).toMatchObject({
- agentId: "test-agent",
+ expect(client.commitSession).toHaveBeenCalledWith("s1", {
+ wait: true,
+ keepRecentCount: 0,
});
});
diff --git a/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts
index f0c6f1c0b..85d4c0962 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts
@@ -126,7 +126,7 @@ describe("context-engine lifecycle service seam", () => {
agentId: "runtime-agent",
ovSessionId,
});
- expect(client.getSessionContext).toHaveBeenCalledWith(ovSessionId, 4096, "agent_main");
+ expect(client.getSessionContext).toHaveBeenCalledWith(ovSessionId, 4096);
expect(buildAssembledContext).not.toHaveBeenCalled();
expect(result).toEqual({ messages, estimatedTokens: 42 });
expect(diag).toHaveBeenCalledWith("assemble_result", ovSessionId, expect.objectContaining({
@@ -151,15 +151,12 @@ describe("context-engine lifecycle service seam", () => {
};
const getClient = vi.fn().mockResolvedValue(client);
const rememberSessionAgentId = vi.fn();
- const resolveAgentId = vi.fn().mockReturnValue("agent_main");
-
const ok = await commitOpenVikingSession({
sessionId: "plain-session",
sessionKey: "agent:main:main",
getClient,
logger,
rememberSessionAgentId,
- resolveAgentId,
isBypassedSession: () => false,
});
@@ -170,10 +167,8 @@ describe("context-engine lifecycle service seam", () => {
sessionKey: "agent:main:main",
ovSessionId,
});
- expect(resolveAgentId).toHaveBeenCalledWith("plain-session", "agent:main:main", ovSessionId);
expect(client.commitSession).toHaveBeenCalledWith(ovSessionId, {
wait: true,
- agentId: "agent_main",
keepRecentCount: 0,
});
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining("memories=5"));
@@ -217,10 +212,9 @@ describe("context-engine lifecycle service seam", () => {
});
const ovSessionId = openClawSessionToOvStorageId("plain-session", "agent:main:main");
- expect(client.getSessionContext).toHaveBeenNthCalledWith(1, ovSessionId, 4096, "agent_main");
+ expect(client.getSessionContext).toHaveBeenNthCalledWith(1, ovSessionId, 4096);
expect(client.commitSession).toHaveBeenCalledWith(ovSessionId, {
wait: true,
- agentId: "agent_main",
keepRecentCount: 0,
});
expect(result).toEqual({
@@ -314,14 +308,13 @@ describe("context-engine lifecycle service seam", () => {
ovSessionId,
"user",
[{ type: "text", text: "hello world" }],
- "agent_main",
+ undefined,
"2026-04-01T10:01:00.000Z",
- "telegram_123",
+ undefined,
);
- expect(client.getSession).toHaveBeenCalledWith(ovSessionId, "agent_main");
+ expect(client.getSession).toHaveBeenCalledWith(ovSessionId);
expect(client.commitSession).toHaveBeenCalledWith(ovSessionId, {
wait: false,
- agentId: "agent_main",
keepRecentCount: 7,
});
expect(diag).toHaveBeenCalledWith("afterTurn_commit", ovSessionId, expect.objectContaining({
diff --git a/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts b/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts
index aae9ea48c..f4891fd8a 100644
--- a/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts
+++ b/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts
@@ -82,7 +82,7 @@ describe("plugin module seams", () => {
const queryRecallTraces = vi.fn().mockResolvedValue({ entries: [{ traceId: "trace-1" }], lookupLayer: "memory", warnings: [] });
const formatRecallTraceText = vi.fn().mockReturnValue("trace text");
const deps = {
- resolvePluginSessionRouting: () => ({ agentId: "agent-main", sessionId: "session-1", ovSessionId: "ov-session-1" }),
+ resolvePluginSessionRouting: () => ({ agentId: "agent-main", actorPeerId: "agent-main", sessionId: "session-1", ovSessionId: "ov-session-1" }),
isBypassedSession: () => false,
makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),
parseAddResourceCommandArgs: vi.fn().mockReturnValue({ source: "https://example.com/doc", wait: true }),
@@ -118,6 +118,7 @@ describe("plugin module seams", () => {
await commands[2]!.handler({ args: "docs --uri viking://resources --limit 3" });
expect(searchOpenViking).toHaveBeenCalledWith({ query: "docs", uri: "viking://resources", limit: 3 }, "agent-main", {
agentId: "agent-main",
+ actorPeerId: "agent-main",
sessionId: "session-1",
ovSessionId: "ov-session-1",
});
@@ -131,6 +132,7 @@ describe("plugin module seams", () => {
});
expect(queryRecallTraces).toHaveBeenCalledWith(expect.objectContaining({ source: "ov_search", limit: 5, includeContent: false }), {
agentId: "agent-main",
+ actorPeerId: "agent-main",
sessionId: "session-1",
ovSessionId: "ov-session-1",
});
@@ -200,7 +202,7 @@ describe("plugin module seams", () => {
const read = vi.fn().mockResolvedValue("0123456789abcdefghijklmnopqrstuvwxyz");
const runtime = createOpenVikingRecallTraceRuntime({
getClient: async () => ({ read }),
- resolvePluginSessionRouting: () => ({ agentId: "agent-main", sessionId: "session-1", sessionKey: "session-key-1", ovSessionId: "ov-session-1" }),
+ resolvePluginSessionRouting: () => ({ agentId: "agent-main", actorPeerId: "agent-main", sessionId: "session-1", sessionKey: "session-key-1", ovSessionId: "ov-session-1" }),
traceRecorder,
registerRecallTraceRoutes: vi.fn().mockReturnValue(true),
normalizeResourceTypes: (value) => Array.isArray(value) ? value : [String(value)],
@@ -571,7 +573,6 @@ describe("plugin module seams", () => {
"ov-session-1",
"tr_1",
{ offset: 0, limit: 20_000, includeMetadata: true },
- "agent-main",
);
expect(result.content[0].text).toBe("full tool result");
expect(result.details).toMatchObject({ action: "read", tool_result_id: "tr_1" });
@@ -627,7 +628,6 @@ describe("plugin module seams", () => {
expect(grepSessionArchives).toHaveBeenCalledWith("ov-session-1", "command", {
archiveId: undefined,
caseInsensitive: true,
- agentId: "agent-main",
});
expect(searchResult.content[0].text).toContain("Found 1 match(es)");
expect(searchResult.content[0].text).toContain("important command output");
@@ -642,7 +642,7 @@ describe("plugin module seams", () => {
const expandTool = expandFactory({ sessionId: "session-1" });
const result = await expandTool.execute("call-2", { archiveId: "archive_001" });
- expect(getSessionArchive).toHaveBeenCalledWith("ov-session-1", "archive_001", "agent-main");
+ expect(getSessionArchive).toHaveBeenCalledWith("ov-session-1", "archive_001");
expect(result.content[0].text).toContain("## archive_001");
expect(result.content[0].text).toContain("user: hello");
expect(result.details).toMatchObject({
@@ -661,7 +661,7 @@ describe("plugin module seams", () => {
const deps = {
registerTool,
getClient: async () => ({ addResource, addSkill }),
- resolvePluginSessionRouting: () => ({ agentId: "agent-main" }),
+ resolvePluginSessionRouting: () => ({ agentId: "agent-main", actorPeerId: "agent-main" }),
isBypassedSession: () => false,
makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),
enableAddResourceTool: true,
@@ -708,7 +708,7 @@ describe("plugin module seams", () => {
registerOpenVikingImportTools({
registerTool,
getClient: async () => ({ addResource: vi.fn(), addSkill: vi.fn() }),
- resolvePluginSessionRouting: () => ({ agentId: "agent-main" }),
+ resolvePluginSessionRouting: () => ({ agentId: "agent-main", actorPeerId: "agent-main" }),
isBypassedSession: () => false,
makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),
enableAddResourceTool: false,
@@ -743,6 +743,7 @@ describe("plugin module seams", () => {
listOpenVikingDirectory,
resolvePluginSessionRouting: () => ({
agentId: "agent-main",
+ actorPeerId: "agent-main",
sessionId: "session-1",
ovSessionId: "ov-session-1",
}),
@@ -762,6 +763,7 @@ describe("plugin module seams", () => {
limit: 3,
}, "agent-main", {
agentId: "agent-main",
+ actorPeerId: "agent-main",
sessionId: "session-1",
ovSessionId: "ov-session-1",
});
@@ -814,9 +816,8 @@ describe("plugin module seams", () => {
getClient: async () => ({ addSessionMessage, commitSession, deleteUri, find }),
normalizeSessionId: (sessionId: string) => `normalized:${sessionId}`,
createTempSessionId: () => "memory-store-temp",
- extractSenderId: () => "ou_01@abc",
- toRoleId: (senderId?: string) => senderId?.replace(/[^a-zA-Z0-9_-]/g, "_"),
- resolvePluginSessionRouting: () => ({ agentId: "agent-main" }),
+ peerRole: "person" as const,
+ resolvePluginSessionRouting: () => ({ agentId: "agent-main", actorPeerId: "ou_01_abc" }),
isBypassedSession: () => false,
makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),
defaultTargetUri: "viking://user/default",
@@ -835,13 +836,12 @@ describe("plugin module seams", () => {
"memory-store-temp",
"user",
[{ type: "text", text: "remember this" }],
- "agent-main",
+ undefined,
undefined,
"ou_01_abc",
);
expect(commitSession).toHaveBeenCalledWith("memory-store-temp", {
wait: true,
- agentId: "agent-main",
keepRecentCount: 0,
});
expect(stored.details).toMatchObject({ action: "stored", memoriesCount: 2, usedTempSession: true });
@@ -852,10 +852,11 @@ describe("plugin module seams", () => {
expect(rejected.details).toMatchObject({ action: "rejected", uri: "viking://resources/r1" });
expect(deleteUri).not.toHaveBeenCalled();
- const deleted = await forgetTool.execute("call-3", { uri: "viking://user/default/memories/m1" });
- expect(deleteUri).toHaveBeenCalledWith("viking://user/default/memories/m1", "agent-main");
- expect(deleted.content[0].text).toBe("Forgotten: viking://user/default/memories/m1");
- expect(deleted.details).toMatchObject({ action: "deleted", uri: "viking://user/default/memories/m1" });
+ const memoryUri = "viking://user/default/memories/m1";
+ const deleted = await forgetTool.execute("call-3", { uri: memoryUri });
+ expect(deleteUri).toHaveBeenCalledWith(memoryUri, "ou_01_abc");
+ expect(deleted.content[0].text).toBe(`Forgotten: ${memoryUri}`);
+ expect(deleted.details).toMatchObject({ action: "deleted", uri: memoryUri });
});
it("registers recall trace tool through a dedicated plugin module", async () => {
@@ -873,6 +874,7 @@ describe("plugin module seams", () => {
formatRecallTraceText,
resolvePluginSessionRouting: () => ({
agentId: "agent-main",
+ actorPeerId: "agent-main",
sessionId: "session-1",
ovSessionId: "ov-session-1",
}),
@@ -889,6 +891,7 @@ describe("plugin module seams", () => {
expect(queryRecallTraces).toHaveBeenCalledWith({ source: "ov_search", limit: 5 }, {
agentId: "agent-main",
+ actorPeerId: "agent-main",
sessionId: "session-1",
ovSessionId: "ov-session-1",
});
@@ -935,6 +938,7 @@ describe("plugin module seams", () => {
toQueryConfigContext: (session) => ({ agentId: session.agentId, sessionId: session.sessionId, sessionKey: session.sessionKey, ovSessionId: session.ovSessionId }),
resolvePluginSessionRouting: () => ({
agentId: "agent-main",
+ actorPeerId: "agent-main",
sessionId: "session-1",
sessionKey: "agent:agent-main:session-1",
ovSessionId: "ov-session-1",
diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.ts
index ffed2d702..4ed964823 100644
--- a/examples/openclaw-plugin/tests/ut/tools.test.ts
+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts
@@ -473,7 +473,7 @@ describe("Tool: memory_store (behavioral)", () => {
return okResponse({});
});
- const { factoryTools, api } = setupPlugin();
+ const { factoryTools, api } = setupPlugin(undefined, { peer_role: "person" });
(api as any).openVikingTransport = openVikingTransport;
contextEnginePlugin.register(api as any);
const factory = factoryTools.get("memory_store");