Skip to content

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

feat(openclaw-plugin): align auth, namespace, and role id handling (#1606)

x__dotef2513c3e73b
diff --git a/docs/zh/concepts/11-multi-tenant.md b/docs/zh/concepts/11-multi-tenant.md
index 5bd18710a..9994e08d9 100644
--- a/docs/zh/concepts/11-multi-tenant.md
+++ b/docs/zh/concepts/11-multi-tenant.md
@@ -202,7 +202,7 @@ openclaw config set plugins.entries.openviking.config.agentId "<agent-id>"
- 接入简单,插件不需要管理 account/user 生命周期
- 最适合“一个 OpenClaw 实例对应一个 OpenViking 用户”的场景
-- `agentId` 决定 agent 级空间,便于区分不同 OpenClaw 实例或不同 agent 角色
+- `agentId` 参与决定 agent 级空间,便于区分不同 OpenClaw 实例或不同 agent 角色
- 同一 account 内的 `resources` 可共享,`user` / `agent` memory 会按身份隔离
### OpenClaw 插件为何通常不配 `account` / `user`
diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.md
index 706739249..b7fe1dc74 100644
--- a/examples/openclaw-plugin/README.md
+++ b/examples/openclaw-plugin/README.md
@@ -51,6 +51,32 @@ The main rules are:
This matters because the plugin is built to support multi-agent and multi-session OpenClaw usage without mixing memories across sessions.
+The recommended remote-mode configuration only needs:
+
+- `baseUrl`
+- `apiKey`
+- `agentId`
+
+In this setup:
+
+- `apiKey` should usually be a user key
+- `accountId` / `userId` are advanced options only for root-key or `trusted` deployments
+- `isolateUserScopeByAgent` / `isolateAgentScopeByUser` must match the server-side account namespace policy when using the PR #1356 canonical namespace model
+- `agentScopeMode` is a deprecated compatibility alias for older hash-based routing and should only be used against older servers
+
+### Canonical namespace policy
+
+For OpenViking servers that include PR #1356, the plugin no longer treats agent or user scope as a locally computed hash. Instead it expands shorthand aliases into canonical URIs using the configured namespace policy:
+
+- `viking://user/memories`
+ - `viking://user/<user_id>/memories` when `isolateUserScopeByAgent=false`
+ - `viking://user/<user_id>/agent/<agent_id>/memories` when `isolateUserScopeByAgent=true`
+- `viking://agent/memories`
+ - `viking://agent/<agent_id>/memories` when `isolateAgentScopeByUser=false`
+ - `viking://agent/<agent_id>/user/<user_id>/memories` when `isolateAgentScopeByUser=true`
+
+The plugin cannot auto-discover this policy today because `/api/v1/system/status` does not expose it. Configure the two booleans explicitly so they stay aligned with the server-side account policy.
+
## Prompt-Front Recall Flow
![Automatic recall flow before prompt build](./images/openclaw-plugin-recall-flow.png)
diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.md
index 4c978cfde..90b309aec 100644
--- a/examples/openclaw-plugin/README_CN.md
+++ b/examples/openclaw-plugin/README_CN.md
@@ -51,6 +51,32 @@
这样做是为了支持多 agent、多 session 并发时的记忆隔离,避免不同 OpenClaw 会话串用同一套长期上下文。
+默认推荐的远程模式配置只有:
+
+- `baseUrl`
+- `apiKey`
+- `agentId`
+
+其中:
+
+- `apiKey` 推荐使用某个 user 的 user key
+- `accountId` / `userId` 仅在 root key 或 `trusted` 模式下作为高级选项使用
+- 使用 PR #1356 canonical namespace 模型时,`isolateUserScopeByAgent` / `isolateAgentScopeByUser` 必须与服务端 account namespace policy 保持一致
+- `agentScopeMode` 已退化为兼容旧 hash 路由的 deprecated alias,仅应在旧服务端上使用
+
+### Canonical namespace policy
+
+对于包含 PR #1356 的 OpenViking 服务端,插件不再在本地计算 user 或 agent scope hash,而是根据配置的 namespace policy 将别名 URI 展开为 canonical URI:
+
+- `viking://user/memories`
+ - `isolateUserScopeByAgent=false` 时展开为 `viking://user/<user_id>/memories`
+ - `isolateUserScopeByAgent=true` 时展开为 `viking://user/<user_id>/agent/<agent_id>/memories`
+- `viking://agent/memories`
+ - `isolateAgentScopeByUser=false` 时展开为 `viking://agent/<agent_id>/memories`
+ - `isolateAgentScopeByUser=true` 时展开为 `viking://agent/<agent_id>/user/<user_id>/memories`
+
+插件当前无法从 `/api/v1/system/status` 自动发现这两个 policy,因此需要显式配置,使其与服务端 account policy 保持一致。
+
## Prompt 前召回链路
![Prompt 前的自动召回流程](./images/openclaw-plugin-recall-flow.png)
diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.ts
index 08090c5ef..8f966482d 100644
--- a/examples/openclaw-plugin/client.ts
+++ b/examples/openclaw-plugin/client.ts
@@ -1,4 +1,4 @@
-import { createHash, randomUUID } from "node:crypto";
+import { randomUUID } from "node:crypto";
import type { spawn } from "node:child_process";
import { once } from "node:events";
import { createWriteStream } from "node:fs";
@@ -27,6 +27,8 @@ export type FindResult = {
export type CaptureMode = "semantic" | "keyword";
export type ScopeName = "user" | "agent";
+export type AgentScopeMode = "user_agent" | "agent";
+export type ServerAuthMode = "api_key" | "trusted";
export type RuntimeIdentity = {
userId: string;
agentId: string;
@@ -171,17 +173,20 @@ export const localClientCache = new Map<string, LocalClientCacheEntry>();
export const localClientPendingPromises = new Map<string, PendingClientEntry>();
const MEMORY_URI_PATTERNS = [
- /^viking:\/\/user\/(?:[^/]+\/)?memories(?:\/|$)/,
- /^viking:\/\/agent\/(?:[^/]+\/)?memories(?:\/|$)/,
+ /^viking:\/\/user\/(?:[^/]+(?:\/agent\/[^/]+)?\/)?memories(?:\/|$)/,
+ /^viking:\/\/agent\/(?:[^/]+(?:\/user\/[^/]+)?\/)?memories(?:\/|$)/,
];
-const USER_STRUCTURE_DIRS = new Set(["memories"]);
-const AGENT_STRUCTURE_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]);
+const USER_STRUCTURE_DIRS = new Set(["memories", "profile.md", ".abstract.md", ".overview.md"]);
+const AGENT_STRUCTURE_DIRS = new Set([
+ "memories",
+ "skills",
+ "instructions",
+ "workspaces",
+ ".abstract.md",
+ ".overview.md",
+]);
const REMOTE_RESOURCE_PREFIXES = ["http://", "https://", "git@", "ssh://", "git://"];
-function md5Short(input: string): string {
- return createHash("md5").update(input).digest("hex").slice(0, 12);
-}
-
export function isMemoryUri(uri: string): boolean {
return MEMORY_URI_PATTERNS.some((pattern) => pattern.test(uri));
}
@@ -211,7 +216,6 @@ async function cleanupUploadTempPath(path?: string): Promise<void> {
}
export class OpenVikingClient {
- private spaceCache = new Map<string, Partial<Record<ScopeName, string>>>();
private identityCache = new Map<string, RuntimeIdentity>();
constructor(
@@ -219,17 +223,50 @@ export class OpenVikingClient {
private readonly apiKey: string,
private readonly defaultAgentId: string,
private readonly timeoutMs: number,
+ private readonly serverAuthMode: ServerAuthMode = "api_key",
/** When set (or defaulted), sent so ROOT key can access tenant-scoped APIs. */
private readonly accountId: string = "",
private readonly userId: string = "",
/** When set, logs routing for find + session writes (tenant headers + paths; never apiKey). */
private readonly routingDebugLog?: (message: string) => void,
+ private readonly isolateUserScopeByAgent = false,
+ private readonly isolateAgentScopeByUser = true,
) {}
getDefaultAgentId(): string {
return this.defaultAgentId;
}
+ async getResolvedIdentity(agentId?: string): Promise<RuntimeIdentity> {
+ return this.getRuntimeIdentity(agentId);
+ }
+
+ private resolveTenantHeaders():
+ | { apiKey?: string; accountId?: string; userId?: string }
+ {
+ const apiKey = this.apiKey.trim();
+ const accountId = this.accountId.trim();
+ const userId = this.userId.trim();
+ if (this.serverAuthMode === "trusted") {
+ return {
+ ...(apiKey ? { apiKey } : {}),
+ accountId: accountId || "default",
+ userId: userId || "default",
+ };
+ }
+ if (apiKey) {
+ return {
+ apiKey,
+ ...(accountId ? { accountId } : {}),
+ ...(userId ? { userId } : {}),
+ };
+ }
+ return {
+ accountId: accountId || "default",
+ userId: userId || "default",
+ };
+ }
+
private async emitRoutingDebug(
label: string,
detail: Record<string, unknown>,
@@ -240,16 +277,17 @@ export class OpenVikingClient {
}
const effectiveAgentId = agentId ?? this.defaultAgentId;
const identity = await this.getRuntimeIdentity(agentId);
+ const tenantHeaders = this.resolveTenantHeaders();
this.routingDebugLog(
`openviking: ${label} ` +
JSON.stringify({
...detail,
X_OpenViking_Agent: effectiveAgentId,
- X_OpenViking_Account: this.accountId.trim() || "default",
- X_OpenViking_User: this.userId.trim() || "default",
+ X_OpenViking_Account: tenantHeaders.accountId ?? null,
+ X_OpenViking_User: tenantHeaders.userId ?? null,
resolved_user_id: identity.userId,
session_vfs_hint: detail.sessionId
- ? `viking://session/${identity.userId}/${String(detail.sessionId)}`
+ ? `viking://session/${String(detail.sessionId)}`
: undefined,
}),
);
@@ -266,11 +304,16 @@ export class OpenVikingClient {
const timer = setTimeout(() => controller.abort(), requestTimeoutMs ?? this.timeoutMs);
try {
const headers = new Headers(init.headers ?? {});
- if (this.apiKey) {
- headers.set("X-API-Key", this.apiKey);
+ const tenantHeaders = this.resolveTenantHeaders();
+ if (tenantHeaders.apiKey) {
+ headers.set("X-API-Key", tenantHeaders.apiKey);
+ }
+ if (tenantHeaders.accountId) {
+ headers.set("X-OpenViking-Account", tenantHeaders.accountId);
+ }
+ if (tenantHeaders.userId) {
+ headers.set("X-OpenViking-User", tenantHeaders.userId);
}
- headers.set("X-OpenViking-Account", this.accountId.trim() || "default");
- headers.set("X-OpenViking-User", this.userId.trim() || "default");
if (effectiveAgentId) {
headers.set("X-OpenViking-Agent", effectiveAgentId);
}
@@ -306,14 +349,6 @@ export class OpenVikingClient {
await this.request<{ status: string }>("/health");
}
- private async ls(uri: string, agentId?: string): Promise<Array<Record<string, unknown>>> {
- return this.request<Array<Record<string, unknown>>>(
- `/api/v1/fs/ls?uri=${encodeURIComponent(uri)}&output=original`,
- {},
- agentId,
- );
- }
-
private async getRuntimeIdentity(agentId?: string): Promise<RuntimeIdentity> {
const effectiveAgentId = agentId ?? this.defaultAgentId;
const cached = this.identityCache.get(effectiveAgentId);
@@ -334,54 +369,18 @@ export class OpenVikingClient {
}
}
- private async resolveScopeSpace(scope: ScopeName, agentId?: string): Promise<string> {
- const effectiveAgentId = agentId ?? this.defaultAgentId;
- const agentScopes = this.spaceCache.get(effectiveAgentId);
- const cached = agentScopes?.[scope];
- if (cached) {
- return cached;
- }
-
+ private async buildCanonicalRoot(scope: ScopeName, agentId?: string): Promise<string> {
const identity = await this.getRuntimeIdentity(agentId);
- const fallbackSpace =
- scope === "user" ? identity.userId : md5Short(`${identity.userId}:${identity.agentId}`);
- const reservedDirs = scope === "user" ? USER_STRUCTURE_DIRS : AGENT_STRUCTURE_DIRS;
- const preferredSpace =
- scope === "user" ? identity.userId : md5Short(`${identity.userId}:${identity.agentId}`);
-
- const saveSpace = (space: string) => {
- const existing = this.spaceCache.get(effectiveAgentId) ?? {};
- existing[scope] = space;
- this.spaceCache.set(effectiveAgentId, existing);
- };
-
- try {
- const entries = await this.ls(`viking://${scope}`, agentId);
- const spaces = entries
- .filter((entry) => entry?.isDir === true)
- .map((entry) => (typeof entry.name === "string" ? entry.name.trim() : ""))
- .filter((name) => name && !name.startsWith(".") && !reservedDirs.has(name));
-
- if (spaces.length > 0) {
- if (spaces.includes(preferredSpace)) {
- saveSpace(preferredSpace);
- return preferredSpace;
- }
- if (scope === "user" && spaces.includes("default")) {
- saveSpace("default");
- return "default";
- }
- if (spaces.length === 1) {
- saveSpace(spaces[0]!);
- return spaces[0]!;
- }
- }
- } catch {
- // Fall back to identity-derived space when listing fails.
+ if (scope === "user") {
+ const root = this.isolateUserScopeByAgent
+ ? `viking://user/${identity.userId}/agent/${identity.agentId}`
+ : `viking://user/${identity.userId}`;
+ return root;
}
-
- saveSpace(fallbackSpace);
- return fallbackSpace;
+ const root = this.isolateAgentScopeByUser
+ ? `viking://agent/${identity.agentId}/user/${identity.userId}`
+ : `viking://agent/${identity.agentId}`;
+ return root;
}
private async normalizeTargetUri(targetUri: string, agentId?: string): Promise<string> {
@@ -405,8 +404,8 @@ export class OpenVikingClient {
return trimmed;
}
- const space = await this.resolveScopeSpace(scope, agentId);
- return `viking://${scope}/${space}/${parts.join("/")}`;
+ const root = await this.buildCanonicalRoot(scope, agentId);
+ return `${root}/${parts.join("/")}`;
}
async find(
@@ -427,12 +426,13 @@ export class OpenVikingClient {
};
const effectiveAgentId = agentId ?? this.defaultAgentId;
const identity = await this.getRuntimeIdentity(agentId);
+ const tenantHeaders = this.resolveTenantHeaders();
this.routingDebugLog?.(
`openviking: find POST ${this.baseUrl}/api/v1/search/find ` +
JSON.stringify({
X_OpenViking_Agent: effectiveAgentId,
- X_OpenViking_Account: this.accountId.trim() || "default",
- X_OpenViking_User: this.userId.trim() || "default",
+ X_OpenViking_Account: tenantHeaders.accountId ?? null,
+ X_OpenViking_User: tenantHeaders.userId ?? null,
resolved_user_id: identity.userId,
target_uri: normalizedTargetUri,
target_uri_input: options.targetUri,
@@ -645,21 +645,27 @@ export class OpenVikingClient {
}>,
agentId?: string,
createdAt?: string,
+ roleId?: string,
): Promise<void> {
const body: {
role: string;
+ role_id?: string;
parts: typeof parts;
created_at?: string;
} = { role, parts };
if (createdAt) {
body.created_at = createdAt;
}
+ if (roleId) {
+ body.role_id = roleId;
+ }
await this.emitRoutingDebug(
"session message POST (with parts)",
{
path: `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,
sessionId,
role,
+ role_id: roleId ?? null,
partCount: parts.length,
created_at: createdAt ?? null,
},
diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.ts
index f3b00fde0..4730a5422 100644
--- a/examples/openclaw-plugin/config.ts
+++ b/examples/openclaw-plugin/config.ts
@@ -12,13 +12,31 @@ export type MemoryOpenVikingConfig = {
port?: number;
baseUrl?: string;
agentId?: string;
+ serverAuthMode?: "api_key" | "trusted";
apiKey?: string;
+ /** Advanced option. Only needed when using root key or trusted auth mode. With a user key the server derives identity from the key. */
+ accountId?: string;
+ /** Advanced option. Only needed when using root key or trusted auth mode. */
+ userId?: string;
+ /**
+ * Canonical namespace policy. Must match the server-side account namespace
+ * policy because current /system/status does not expose it.
+ */
+ isolateUserScopeByAgent?: boolean;
+ isolateAgentScopeByUser?: boolean;
+ /**
+ * Deprecated compatibility alias for older hash-based agent space behavior.
+ * Prefer isolateUserScopeByAgent / isolateAgentScopeByUser.
+ */
+ agentScopeMode?: "user_agent" | "agent";
targetUri?: string;
timeoutMs?: number;
autoCapture?: boolean;
captureMode?: "semantic" | "keyword";
captureMaxLength?: number;
autoRecall?: boolean;
+ /** Include resources in auto-recall and default memory_recall search. Default false. */
+ recallResources?: boolean;
recallLimit?: number;
recallScoreThreshold?: number;
recallMaxContentChars?: number;
@@ -52,6 +70,7 @@ const DEFAULT_EMIT_STANDARD_DIAGNOSTICS = false;
const DEFAULT_LOCAL_CONFIG_PATH = join(homedir(), ".openviking", "ov.conf");
const DEFAULT_AGENT_ID = "default";
+const DEFAULT_SERVER_AUTH_MODE = "api_key";
function resolveAgentId(configured: unknown): string {
if (typeof configured === "string" && configured.trim()) {
@@ -139,13 +158,20 @@ export const memoryOpenVikingConfigSchema = {
"port",
"baseUrl",
"agentId",
+ "serverAuthMode",
"apiKey",
+ "accountId",
+ "userId",
+ "isolateUserScopeByAgent",
+ "isolateAgentScopeByUser",
+ "agentScopeMode",
"targetUri",
"timeoutMs",
"autoCapture",
"captureMode",
"captureMaxLength",
"autoRecall",
+ "recallResources",
"recallLimit",
"recallScoreThreshold",
"recallMaxContentChars",
@@ -179,7 +205,11 @@ export const memoryOpenVikingConfigSchema = {
const rawBaseUrl =
mode === "local" ? localBaseUrl : (typeof cfg.baseUrl === "string" ? cfg.baseUrl : resolveDefaultBaseUrl());
const resolvedBaseUrl = resolveEnvVars(rawBaseUrl).replace(/\/+$/, "");
- const rawApiKey = typeof cfg.apiKey === "string" ? cfg.apiKey : getEnv("OPENVIKING_API_KEY");
+ const rawApiKey = typeof cfg.apiKey === "string" ? cfg.apiKey : process.env.OPENVIKING_API_KEY;
+ const rawServerAuthMode =
+ cfg.serverAuthMode ?? process.env.OPENVIKING_SERVER_AUTH_MODE;
+ const serverAuthMode =
+ rawServerAuthMode === "trusted" ? "trusted" as const : "api_key" as const;
const captureMode = cfg.captureMode;
if (
typeof captureMode !== "undefined" &&
@@ -189,13 +219,60 @@ export const memoryOpenVikingConfigSchema = {
throw new Error(`openviking captureMode must be "semantic" or "keyword"`);
}
+ const accountId =
+ typeof cfg.accountId === "string" && cfg.accountId.trim()
+ ? cfg.accountId.trim()
+ : (process.env.OPENVIKING_ACCOUNT_ID?.trim() || "");
+ const userId =
+ typeof cfg.userId === "string" && cfg.userId.trim()
+ ? cfg.userId.trim()
+ : (process.env.OPENVIKING_USER_ID?.trim() || "");
+
+ const hasExplicitAgentScopeMode =
+ typeof cfg.agentScopeMode === "string" || process.env.OPENVIKING_AGENT_SCOPE_MODE !== undefined;
+ const rawAgentScope = cfg.agentScopeMode ?? process.env.OPENVIKING_AGENT_SCOPE_MODE;
+ const agentScopeMode =
+ rawAgentScope === "user_agent" ? "user_agent" as const : "agent" as const;
+ const explicitIsolateUserScopeByAgent =
+ typeof cfg.isolateUserScopeByAgent === "boolean"
+ ? cfg.isolateUserScopeByAgent
+ : undefined;
+ const explicitIsolateAgentScopeByUser =
+ typeof cfg.isolateAgentScopeByUser === "boolean"
+ ? cfg.isolateAgentScopeByUser
+ : undefined;
+ const envIsolateUserScopeByAgent =
+ explicitIsolateUserScopeByAgent === undefined &&
+ process.env.OPENVIKING_ISOLATE_USER_SCOPE_BY_AGENT !== undefined
+ ? envFlag("OPENVIKING_ISOLATE_USER_SCOPE_BY_AGENT")
+ : undefined;
+ const envIsolateAgentScopeByUser =
+ explicitIsolateAgentScopeByUser === undefined &&
+ process.env.OPENVIKING_ISOLATE_AGENT_SCOPE_BY_USER !== undefined
+ ? envFlag("OPENVIKING_ISOLATE_AGENT_SCOPE_BY_USER")
+ : undefined;
+ const isolateUserScopeByAgent =
+ explicitIsolateUserScopeByAgent ??
+ envIsolateUserScopeByAgent ??
+ false;
+ const isolateAgentScopeByUser =
+ explicitIsolateAgentScopeByUser ??
+ envIsolateAgentScopeByUser ??
+ (hasExplicitAgentScopeMode && agentScopeMode === "user_agent" ? true : false);
+
return {
mode,
configPath,
port,
baseUrl: resolvedBaseUrl,
agentId: resolveAgentId(cfg.agentId),
+ serverAuthMode,
apiKey: rawApiKey ? resolveEnvVars(rawApiKey) : "",
+ accountId,
+ userId,
+ isolateUserScopeByAgent,
+ isolateAgentScopeByUser,
+ agentScopeMode,
targetUri: typeof cfg.targetUri === "string" ? cfg.targetUri : DEFAULT_TARGET_URI,
timeoutMs: Math.max(1000, Math.floor(toNumber(cfg.timeoutMs, DEFAULT_TIMEOUT_MS))),
autoCapture: cfg.autoCapture !== false,
@@ -205,6 +282,7 @@ export const memoryOpenVikingConfigSchema = {
Math.min(200_000, Math.floor(toNumber(cfg.captureMaxLength, DEFAULT_CAPTURE_MAX_LENGTH))),
),
autoRecall: cfg.autoRecall !== false,
+ recallResources: cfg.recallResources === true || envFlag("OPENVIKING_RECALL_RESOURCES"),
recallLimit: Math.max(1, Math.floor(toNumber(cfg.recallLimit, DEFAULT_RECALL_LIMIT))),
recallScoreThreshold: Math.min(
1,
@@ -264,7 +342,12 @@ export const memoryOpenVikingConfigSchema = {
agentId: {
label: "Agent ID",
placeholder: "auto-generated",
- help: 'OpenViking X-OpenViking-Agent: non-default values combine with OpenClaw ctx.agentId as "<config>_<sessionAgent>" (then sanitized to [a-zA-Z0-9_-]). Use "default" to send only ctx.agentId.',
+ help: 'OpenViking X-OpenViking-Agent. "default" follows OpenClaw ctx.agentId. Non-default values are prepended as "<config>_<ctx.agentId>" (sanitized to [a-zA-Z0-9_-]).',
+ },
+ serverAuthMode: {
+ label: "Server Auth Mode",
+ placeholder: DEFAULT_SERVER_AUTH_MODE,
+ help: 'OpenViking auth behavior. "api_key" (default): send X-API-Key when configured, otherwise dev fallback to X-OpenViking-Account/User default/default. "trusted": always send accountId/userId and optionally send apiKey when configured.',
},
apiKey: {
label: "OpenViking API Key",
@@ -272,6 +355,36 @@ export const memoryOpenVikingConfigSchema = {
placeholder: "${OPENVIKING_API_KEY}",
help: "Optional API key for OpenViking server",
},
+ accountId: {
+ label: "Account ID",
+ placeholder: "(derived from API key)",
+ help: "Advanced option. Tenant account ID. Only needed when using root key or trusted auth mode. With a user key the server derives identity from the key.",
+ advanced: true,
+ },
+ userId: {
+ label: "User ID",
+ placeholder: "(derived from API key)",
+ help: "Advanced option. Tenant user ID. Only needed when using root key or trusted auth mode.",
+ advanced: true,
+ },
+ isolateUserScopeByAgent: {
+ label: "Isolate User Scope By Agent",
+ placeholder: "false",
+ help: "Canonical namespace policy. false (default): user alias expands to viking://user/<user_id>/... . true: expands to viking://user/<user_id>/agent/<agent_id>/... . Must match the server-side account namespace policy.",
+ advanced: true,
+ },
+ isolateAgentScopeByUser: {
+ label: "Isolate Agent Scope By User",
+ placeholder: "false",
+ help: "Canonical namespace policy. false (default): agent alias expands to viking://agent/<agent_id>/... . true: expands to viking://agent/<agent_id>/user/<user_id>/... . Must match the server-side account namespace policy.",
+ advanced: true,
+ },
+ agentScopeMode: {
+ label: "Deprecated Agent Scope Mode",
+ placeholder: "agent",
+ help: 'Deprecated compatibility alias for older routing behavior. Prefer isolateUserScopeByAgent / isolateAgentScopeByUser. Mapping: explicit "user_agent" => false/true, explicit "agent" => false/false. When fully unset, the plugin defaults to false/false to match the current server-side default policy.',
+ advanced: true,
+ },
targetUri: {
label: "Search Target URI",
placeholder: DEFAULT_TARGET_URI,
@@ -302,6 +415,11 @@ export const memoryOpenVikingConfigSchema = {
label: "Auto-Recall",
help: "Inject relevant OpenViking memories into agent context",
},
+ recallResources: {
+ label: "Recall Resources",
+ help: "Include resources (viking://resources) in auto-recall and default memory_recall search. Enables account-level shared knowledge retrieval.",
+ advanced: true,
+ },
recallLimit: {
label: "Recall Limit",
placeholder: String(DEFAULT_RECALL_LIMIT),
diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.ts
index f5668a63d..9487c115c 100644
--- a/examples/openclaw-plugin/context-engine.ts
+++ b/examples/openclaw-plugin/context-engine.ts
@@ -38,6 +38,18 @@ type IngestResult = {
ingested: boolean;
};
+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;
+}
+
type IngestBatchResult = {
ingestedCount: number;
};
@@ -104,6 +116,11 @@ type Logger = {
error: (msg: string) => void;
};
+type ExtractedSender = {
+ found: boolean;
+ senderId?: string;
+};
+
interface ContextBudgets {
archiveMemory: number;
sessionContext: number;
@@ -213,6 +230,24 @@ function validTokenBudget(raw: unknown): number | undefined {
return undefined;
}
+function extractRuntimeSenderId(
+ runtimeContext: Record<string, unknown> | undefined,
+): ExtractedSender {
+ if (runtimeContext) {
+ const senderId = runtimeContext.senderId;
+ if (typeof senderId === "string") {
+ const trimmed = senderId.trim();
+ if (trimmed) {
+ return {
+ found: true,
+ senderId: trimmed,
+ };
+ }
+ }
+ }
+ return { found: false };
+}
+
/** OpenClaw session UUID (path-safe on Windows). */
const OPENVIKING_OV_SESSION_UUID =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -790,6 +825,7 @@ export function createMemoryOpenVikingContextEngine(params: {
const { messages } = assembleParams;
const tokenBudget = validTokenBudget(assembleParams.tokenBudget) ?? 128_000;
const sessionKey = extractAssembleSessionKey(assembleParams);
+ const sender = extractRuntimeSenderId(assembleParams.runtimeContext);
const originalTokens = roughEstimate(messages);
@@ -805,6 +841,8 @@ export function createMemoryOpenVikingContextEngine(params: {
inputTokenEstimate: originalTokens,
tokenBudget,
sessionKey: sessionKey ?? null,
+ senderIdFound: sender.found,
+ senderId: sender.senderId ?? null,
messages: messageDigest(messages),
});
@@ -868,6 +906,8 @@ export function createMemoryOpenVikingContextEngine(params: {
sessionTokens: session.tokens,
sessionBudget: budgets.sessionContext,
reservedBudget: budgets.reserved,
+ senderIdFound: sender.found,
+ senderId: sender.senderId ?? null,
messages: messageDigest(sanitized),
});
@@ -885,6 +925,8 @@ export function createMemoryOpenVikingContextEngine(params: {
error: String(err),
tokenBudget,
agentId: resolveAgentId(OVSessionId),
+ senderIdFound: sender.found,
+ senderId: sender.senderId ?? null,
});
return { messages, estimatedTokens: roughEstimate(messages) };
}
@@ -900,6 +942,7 @@ export function createMemoryOpenVikingContextEngine(params: {
}
try {
+ const sender = extractRuntimeSenderId(afterTurnParams.runtimeContext);
const sessionKey =
(typeof afterTurnParams.sessionKey === "string" && afterTurnParams.sessionKey.trim()) ||
extractSessionKey(afterTurnParams.runtimeContext);
@@ -924,6 +967,8 @@ export function createMemoryOpenVikingContextEngine(params: {
diag("afterTurn_skip", OVSessionId, {
reason: "session_bypassed",
totalMessages: afterTurnParams.messages?.length ?? 0,
+ senderIdFound: sender.found,
+ senderId: sender.senderId ?? null,
});
return;
}
@@ -933,6 +978,8 @@ export function createMemoryOpenVikingContextEngine(params: {
diag("afterTurn_skip", OVSessionId, {
reason: "no_messages",
totalMessages: 0,
+ senderIdFound: sender.found,
+ senderId: sender.senderId ?? null,
});
return;
}
@@ -950,6 +997,8 @@ export function createMemoryOpenVikingContextEngine(params: {
reason: "no_new_turn_messages",
totalMessages: messages.length,
prePromptMessageCount: start,
+ senderIdFound: sender.found,
+ senderId: sender.senderId ?? null,
});
return;
}
@@ -967,6 +1016,8 @@ export function createMemoryOpenVikingContextEngine(params: {
newMessageCount: newCount,
prePromptMessageCount: start,
newTurnTokens,
+ senderIdFound: sender.found,
+ senderId: sender.senderId ?? null,
messages: newMsgFull,
});
@@ -979,7 +1030,7 @@ export function createMemoryOpenVikingContextEngine(params: {
}
const client = await getClient();
const createdAt = pickLatestCreatedAt(turnMessages);
-
+ const senderRoleId = toRoleId(sender.senderId);
// 发送结构化消息:统一 role 为 user,通过 parts 区分类型
for (const msg of extractedMessages) {
const ovParts = msg.parts.map((part) => {
@@ -1009,6 +1060,7 @@ export function createMemoryOpenVikingContextEngine(params: {
ovParts,
agentId,
createdAt,
+ msg.role === "user" ? senderRoleId : undefined,
);
}
}
@@ -1021,6 +1073,8 @@ export function createMemoryOpenVikingContextEngine(params: {
reason: "below_threshold",
pendingTokens,
commitTokenThreshold: cfg.commitTokenThreshold,
+ senderIdFound: sender.found,
+ senderId: sender.senderId ?? null,
});
return;
}
@@ -1039,6 +1093,8 @@ export function createMemoryOpenVikingContextEngine(params: {
archived: commitResult.archived ?? false,
taskId: commitResult.task_id ?? null,
extractedMemories: totalExtractedMemories(commitResult.memories_extracted),
+ senderIdFound: sender.found,
+ senderId: sender.senderId ?? null,
});
if (commitResult.task_id && cfg.logFindRequests) {
logger.info(
@@ -1057,8 +1113,11 @@ export function createMemoryOpenVikingContextEngine(params: {
}
} catch (err) {
logger.warn?.(`openviking: afterTurn failed: ${String(err)}`);
+ const sender = extractRuntimeSenderId(afterTurnParams.runtimeContext);
diag("afterTurn_error", afterTurnParams.sessionId ?? "(unknown)", {
error: String(err),
+ senderIdFound: sender.found,
+ senderId: sender.senderId ?? null,
});
}
},
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index ca282cd1e..2f7359666 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -17,7 +17,7 @@ import type {
CommitSessionResult,
OVMessage,
} from "./client.js";
-import { formatMessageFaithful } from "./context-engine.js";
+import { formatMessageFaithful, toRoleId } from "./context-engine.js";
import {
compileSessionPatterns,
extractLatestUserText,
@@ -95,6 +95,7 @@ type ToolContext = {
sessionKey?: string;
sessionId?: string;
agentId?: string;
+ senderId?: string;
};
type PluginCommandContext = {
@@ -342,6 +343,26 @@ function parseImportKind(value: string | undefined): OvImportKind {
throw new Error("--kind must be resource or skill");
}
+function extractToolSenderId(ctx: unknown): string | undefined {
+ if (!ctx || typeof ctx !== "object") {
+ return undefined;
+ }
+ const toolCtx = ctx as Record<string, unknown>;
+ if (typeof toolCtx.requesterSenderId === "string") {
+ const trimmed = toolCtx.requesterSenderId.trim();
+ if (trimmed) {
+ return trimmed;
+ }
+ }
+ if (typeof toolCtx.senderId === "string") {
+ const trimmed = toolCtx.senderId.trim();
+ if (trimmed) {
+ return trimmed;
+ }
+ }
+ return undefined;
+}
+
export function parseOvImportCommandArgs(args: string): OvImportInput {
const parsed = parseFlagArgs(args);
const kind = parseImportKind(getStringFlag(parsed.flags, "kind"));
@@ -553,14 +574,23 @@ const contextEnginePlugin = {
: 'default → X-OpenViking-Agent follows OpenClaw ctx.agentId per session (e.g. "main")'
})`,
);
+ verboseRoutingInfo(
+ `openviking: auth/namespace config ` +
+ JSON.stringify({
+ serverAuthMode: cfg.serverAuthMode,
+ isolateUserScopeByAgent: cfg.isolateUserScopeByAgent,
+ isolateAgentScopeByUser: cfg.isolateAgentScopeByUser,
+ deprecatedAgentScopeMode: cfg.agentScopeMode,
+ }),
+ );
const routingDebugLog = cfg.logFindRequests
? (msg: string) => {
api.logger.info(msg);
}
: undefined;
- const tenantAccount = "";
- const tenantUser = "";
- const localCacheKey = `${cfg.mode}:${cfg.baseUrl}:${cfg.configPath}:${cfg.apiKey}:${tenantAccount}:${tenantUser}:${cfg.agentId}:${cfg.logFindRequests ? "1" : "0"}`;
+ const tenantAccount = cfg.accountId;
+ const tenantUser = cfg.userId;
+ const localCacheKey = `${cfg.mode}:${cfg.baseUrl}:${cfg.configPath}:${cfg.apiKey}:${cfg.serverAuthMode}:${tenantAccount}:${tenantUser}:${cfg.agentId}:${cfg.isolateUserScopeByAgent ? "1" : "0"}:${cfg.isolateAgentScopeByUser ? "1" : "0"}:${cfg.logFindRequests ? "1" : "0"}`;
let clientPromise: Promise<OpenVikingClient>;
let localProcess: ReturnType<typeof launchProcess> | null = null;
@@ -613,9 +643,12 @@ const contextEnginePlugin = {
cfg.apiKey,
cfg.agentId,
cfg.timeoutMs,
+ cfg.serverAuthMode,
tenantAccount,
tenantUser,
routingDebugLog,
+ cfg.isolateUserScopeByAgent,
+ cfg.isolateAgentScopeByUser,
),
);
}
@@ -1002,8 +1035,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
agentId,
);
} else {
- // 默认同时检索 user 和 agent 两个位置的记忆
- const [userSettled, agentSettled] = await Promise.allSettled([
+ const searchPromises: Promise<FindResult>[] = [
recallClient.find(
query,
{
@@ -1022,15 +1054,31 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
},
agentId,
),
- ]);
- const userResult = userSettled.status === "fulfilled" ? userSettled.value : { memories: [] };
- const agentResult = agentSettled.status === "fulfilled" ? agentSettled.value : { memories: [] };
- // 合并两个位置的结果,去重
- const allMemories = [...(userResult.memories ?? []), ...(agentResult.memories ?? [])];
+ ];
+ if (cfg.recallResources) {
+ searchPromises.push(
+ recallClient.find(
+ query,
+ {
+ targetUri: "viking://resources",
+ limit: requestLimit,
+ scoreThreshold: 0,
+ },
+ agentId,
+ ),
+ );
+ }
+ const settled = await Promise.allSettled(searchPromises);
+ const allMemories: FindResultItem[] = [];
+ for (const s of settled) {
+ if (s.status === "fulfilled") {
+ allMemories.push(...(s.value.memories ?? []), ...(s.value.resources ?? []));
+ }
+ }
const uniqueMemories = allMemories.filter((memory, index, self) =>
index === self.findIndex((m) => m.uri === memory.uri)
);
- const leafOnly = uniqueMemories.filter((m) => m.level === 2);
+ const leafOnly = uniqueMemories.filter((m) => !m.level || m.level === 2);
result = {
memories: leafOnly,
total: leafOnly.length,
@@ -1106,11 +1154,14 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
usedTempSession = true;
}
sessionId = openClawSessionToOvStorageId(sessionId, ctx.sessionKey);
+ const roleId = role === "user" ? toRoleId(extractToolSenderId(ctx)) : undefined;
await c.addSessionMessage(
sessionId,
role,
[{ type: "text" as const, text }],
storeAgentId,
+ undefined,
+ roleId,
);
const commitResult = await c.commitSession(sessionId, { wait: true, agentId: storeAgentId });
const memoriesCount = totalCommitMemories(commitResult);
@@ -1474,7 +1525,7 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
await withTimeout(
(async () => {
const candidateLimit = Math.max(cfg.recallLimit * 4, 20);
- const [userSettled, agentSettled] = await Promise.allSettled([
+ const autoRecallPromises: Promise<FindResult>[] = [
client.find(queryText, {
targetUri: "viking://user/memories",
limit: candidateLimit,
@@ -1485,22 +1536,31 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
limit: candidateLimit,
scoreThreshold: 0,
}, agentId),
- ]);
-
- const userResult = userSettled.status === "fulfilled" ? userSettled.value : { memories: [] };
- const agentResult = agentSettled.status === "fulfilled" ? agentSettled.value : { memories: [] };
- if (userSettled.status === "rejected") {
- api.logger.warn(`openviking: user memories search failed: ${String(userSettled.reason)}`);
+ ];
+ if (cfg.recallResources) {
+ autoRecallPromises.push(
+ client.find(queryText, {
+ targetUri: "viking://resources",
+ limit: candidateLimit,
+ scoreThreshold: 0,
+ }, agentId),
+ );
}
- if (agentSettled.status === "rejected") {
- api.logger.warn(`openviking: agent memories search failed: ${String(agentSettled.reason)}`);
+ const autoRecallSettled = await Promise.allSettled(autoRecallPromises);
+
+ const allMemories: FindResultItem[] = [];
+ for (const s of autoRecallSettled) {
+ if (s.status === "fulfilled") {
+ allMemories.push(...(s.value.memories ?? []), ...(s.value.resources ?? []));
+ } else {
+ api.logger.warn(`openviking: auto-recall search failed: ${String(s.reason)}`);
+ }
}
- const allMemories = [...(userResult.memories ?? []), ...(agentResult.memories ?? [])];
const uniqueMemories = allMemories.filter((memory, index, self) =>
index === self.findIndex((m) => m.uri === memory.uri)
);
- const leafOnly = uniqueMemories.filter((m) => m.level === 2);
+ const leafOnly = uniqueMemories.filter((m) => !m.level || m.level === 2);
const processed = postProcessMemories(leafOnly, {
limit: candidateLimit,
scoreThreshold: cfg.recallScoreThreshold,
@@ -1712,9 +1772,12 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
cfg.apiKey,
cfg.agentId,
cfg.timeoutMs,
+ cfg.serverAuthMode,
tenantAccount,
tenantUser,
routingDebugLog,
+ cfg.isolateUserScopeByAgent,
+ cfg.isolateAgentScopeByUser,
);
localClientCache.set(localCacheKey, { client, process: child });
resolveLocalClient!(client);
@@ -1784,7 +1847,18 @@ const mergeFindResults = (results: FindResult[]): FindResult => {
});
try {
await waitForHealthOrExit(baseUrl, timeoutMs, intervalMs, child);
- const client = new OpenVikingClient(baseUrl, cfg.apiKey, cfg.agentId, cfg.timeoutMs);
+ const client = new OpenVikingClient(
+ baseUrl,
+ cfg.apiKey,
+ cfg.agentId,
+ cfg.timeoutMs,
+ cfg.serverAuthMode,
+ tenantAccount,
+ tenantUser,
+ undefined,
+ cfg.isolateUserScopeByAgent,
+ cfg.isolateAgentScopeByUser,
+ );
localClientCache.set(localCacheKey, { client, process: child });
if (resolveLocalClient) {
resolveLocalClient(client);
diff --git a/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md b/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md
new file mode 100644
index 000000000..558052298
--- /dev/null
+++ b/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md
@@ -0,0 +1,121 @@
+# OpenClaw 多租与身份透传测试报告
+
+## 1. 测试目标
+
+本轮测试围绕 `examples/openclaw-plugin` 的多租户与会话身份透传能力展开,重点验证以下目标:
+
+1. 验证插件在 `api_key` 与 `trusted` 两种服务认证模式下的请求头行为是否正确。
+2. 验证插件是否按照服务侧命名空间策略,将 `viking://user/memories` 与 `viking://agent/memories` 正确展开为 canonical URI。
+3. 验证 `senderId` / `requesterSenderId` 是否能够稳定映射为会话消息的 `role_id`。
+4. 验证 `afterTurn` 与 `memory_store` 两条写会话路径的身份语义是否一致。
+5. 验证多租户场景下默认用户空间、按 agent 隔离空间、共享 agent 空间等路径的召回行为是否符合预期。
+
+## 2. 测试方法
+
+### 2.1 服务端直连验证
+
+在 OpenClaw 之前,先通过 OpenViking HTTP API 直接验证服务端状态与数据面:
+
+- 使用 `curl` 调用 `/health`、`/api/v1/system/status`、`/api/v1/search/find`
+- 直接验证显式 URI,例如:
+ - `viking://user/default/memories`
+ - `viking://user/default/agent/main/memories`
+ - `viking://agent/main/memories`
+ - `viking://agent/main/user/default/memories`
+- 通过结构化 seed 与分层 `reindex`,确保召回验证基线可用
+
+### 2.2 插件端到端验证
+
+通过真实 OpenClaw gateway 与 OpenViking 后端联调验证:
+
+- 远端 `19950`:用于 `api_key` 模式与命名空间矩阵验证
+- 远端 `19960`:用于 `trusted` 模式与 `role_id` 验证
+- 使用真实 Feishu 机器人入口验证真实 sender 映射
+- 结合以下日志进行判定:
+ - `before_prompt_build`
+ - `find POST`
+ - `session message POST`
+ - `session commit POST`
+
+### 2.3 真实机器人验证
+
+针对 `role_id` 透传行为,使用真实机器人私聊/群聊场景复核:
+
+- 私聊验证真实 sender 到 `role_id` 的稳定映射
+- 群聊验证不同成员写入不同 `role_id`
+- 工具调用验证 `memory_store` 路径是否能通过 `requesterSenderId` 写出 `role_id`
+
+## 3. 测试范围
+
+### 3.1 认证模式
+
+- `api_key`
+- `trusted`
+- `trusted + root_api_key`
+
+### 3.2 命名空间策略
+
+- `ff`:user 不按 agent 隔离,agent 不按 user 隔离
+- `tf`:user 按 agent 隔离,agent 不按 user 隔离
+- `tt`:user 按 agent 隔离,agent 按 user 隔离
+- 兼容路径:
+ - `agentScopeMode=agent`
+ - 新 policy 覆盖旧 alias
+
+### 3.3 身份透传
+
+- `afterTurn.runtimeContext.senderId -> role_id`
+- `memory_store.requesterSenderId -> role_id`
+- assistant message 不传 `role_id`
+
+## 4. 测试结果
+
+### 4.1 通过项
+
+| 维度 | case | 结果 | 说明 |
+|---|---|---|---|
+| `api_key` | `api_key_without_key_dev` | 通过 | `default/default` dev fallback 生效 |
+| `api_key` | `personal_token_default` | 通过 | 命中 `DEFAULT_USER_TOKEN_19950` |
+| `api_key` | `agentid_prefix_worker` | 通过 | 实际 agent 值为 `worker_main` |
+| 兼容 | `deprecated_agent_alias` | 通过 | `agentScopeMode=agent` 兼容正常 |
+| 覆盖优先级 | `new_policy_overrides_deprecated` | 通过 | 新 policy 覆盖旧 alias |
+| namespace | `ff_user_token` | 通过 | user 共享空间命中正确 |
+| namespace | `ff_agent_token` | 通过 | agent 共享空间命中正确 |
+| namespace | `tf_user_token` | 通过 | user 按 agent 隔离命中正确 |
+| namespace | `tf_agent_token` | 通过 | agent 共享空间命中正确 |
+| namespace | `tt_user_token` | 通过 | user/agent 双隔离命中正确 |
+| namespace | `tt_agent_token` | 通过 | agent/user 双隔离命中正确 |
+| `trusted` | `trusted_without_key` | 通过 | 无 key trusted 路径正常 |
+| `trusted` | `trusted_with_key` | 通过 | 带 key trusted 路径正常 |
+| `trusted` | `trusted_root_key_required` | 通过 | 不带 key 被服务侧拒绝 |
+| `trusted` | `trusted_root_key_optional_ok` | 通过 | 带 root key 正常 |
+| `senderId -> role_id` | `senderid_trusted_user_msg` | 通过 | `telegram:12345 -> telegram_12345` |
+| `senderId -> role_id` | `senderid_trusted_blank` | 通过 | `role_id:null` |
+| `senderId -> role_id` | `senderid_sanitize_symbols` | 通过 | `wx/user-01@abc -> wx_user-01_abc` |
+| 真实机器人 | 私聊 sender 映射 | 通过 | sender 稳定映射到真实 `role_id` |
+| 真实机器人 | 群聊多成员 `role_id` | 通过 | 不同成员落不同 `role_id` |
+| `memory_store` | `requesterSenderId -> role_id` | 通过 | `memory_store` 已使用 `requesterSenderId` 写出真实 `role_id` |
+
+### 4.2 已知说明
+
+| 项目 | 状态 | 说明 |
+|---|---|---|
+| `agent_token_main_default` | 已打通 | 曾出现一次回答少 `_19950`,属于回答精度问题,不是链路问题 |
+| 真实机器人最终回复 | 非插件问题 | 群聊/私聊中出现的 `Something went wrong...` 已定位在 OpenClaw 工具结果回填阶段,与 OpenViking 插件链路无关 |
+
+## 5. 关键结论
+
+1. 插件侧 `serverAuthMode`、canonical namespace policy 与 `role_id` 透传能力已完成联调验证。
+2. `afterTurn` 路径可通过 `runtimeContext.senderId` 正确写出 `role_id`。
+3. `memory_store` 路径在工具上下文中无法直接读取 `senderId`,但可稳定通过 `requesterSenderId` 写出 `role_id`。
+4. 在真实机器人私聊与群聊场景中,已确认不同用户会被映射为不同的 `role_id`,且 assistant message 保持 `role_id:null`。
+5. 当前 OpenViking 插件链路已满足多租户、命名空间与 sender 身份透传的测试目标。
+
+## 6. 建议
+
+1. 若后续服务端对 `api_key + USER` 的 `role_id` 语义收紧,应补充一条显式兼容说明或服务端协同约束。
+2. 如需继续扩大矩阵,可追加:
+ - 更多账号/用户组合
+ - 不同群聊成员的稳定性回归
+ - `memory_store` 与 `afterTurn` 跨会话一致性复测
+3. 若要沉淀为长期回归用例,建议将当前已验证的矩阵继续脚本化,但保留真实机器人场景作为最终回归验证补充。
diff --git a/examples/openclaw-plugin/openclaw.plugin.json b/examples/openclaw-plugin/openclaw.plugin.json
index edada9ca7..a75e7823b 100644
--- a/examples/openclaw-plugin/openclaw.plugin.json
+++ b/examples/openclaw-plugin/openclaw.plugin.json
@@ -27,7 +27,12 @@
"agentId": {
"label": "Agent ID",
"placeholder": "random unique ID",
- "help": "Instance prefix for X-OpenViking-Agent. Non-default: `<this>_<OpenClaw ctx.agentId>` (sanitized to letters/digits/_/-). default: use OpenClaw session agent only."
+ "help": "OpenViking agent identity. default: follow OpenClaw ctx.agentId. Non-default: use `<this>_<OpenClaw ctx.agentId>` (sanitized to letters/digits/_/-), so the configured value acts as a prefix."
+ },
+ "serverAuthMode": {
+ "label": "Server Auth Mode",
+ "placeholder": "api_key",
+ "help": "api_key (default): send X-API-Key when configured, otherwise dev fallback to default/default tenant headers. trusted: always send accountId/userId and optionally send apiKey when configured."
},
"apiKey": {
"label": "OpenViking API Key",
@@ -35,6 +40,36 @@
"placeholder": "${OPENVIKING_API_KEY}",
"help": "Optional API key for OpenViking server"
},
+ "accountId": {
+ "label": "Account ID",
+ "placeholder": "(derived from API key)",
+ "help": "Advanced option. Tenant account ID. Only needed when using root key or trusted auth mode. With a user key the server derives identity from the key.",
+ "advanced": true
+ },
+ "userId": {
+ "label": "User ID",
+ "placeholder": "(derived from API key)",
+ "help": "Advanced option. Tenant user ID. Only needed when using root key or trusted auth mode.",
+ "advanced": true
+ },
+ "isolateUserScopeByAgent": {
+ "label": "Isolate User Scope By Agent",
+ "placeholder": "false",
+ "help": "Canonical namespace policy. false (default): user alias expands to viking://user/<user_id>/... . true: expands to viking://user/<user_id>/agent/<agent_id>/... . Must match the server-side account namespace policy.",
+ "advanced": true
+ },
+ "isolateAgentScopeByUser": {
+ "label": "Isolate Agent Scope By User",
+ "placeholder": "false",
+ "help": "Canonical namespace policy. false (default): agent alias expands to viking://agent/<agent_id>/... . true: expands to viking://agent/<agent_id>/user/<user_id>/... . Must match the server-side account namespace policy.",
+ "advanced": true
+ },
+ "agentScopeMode": {
+ "label": "Deprecated Agent Scope Mode",
+ "placeholder": "agent",
+ "help": "Deprecated compatibility alias for older routing. Prefer isolateUserScopeByAgent / isolateAgentScopeByUser. Explicit user_agent => false/true, explicit agent => false/false. When fully unset, the plugin defaults to false/false to match the current server-side policy.",
+ "advanced": true
+ },
"targetUri": {
"label": "Search Target URI",
"placeholder": "viking://user/memories",
@@ -65,6 +100,11 @@
"label": "Auto-Recall",
"help": "Inject relevant OpenViking memories into agent context"
},
+ "recallResources": {
+ "label": "Recall Resources",
+ "help": "Include resources (viking://resources) in auto-recall and default memory_recall search. Enables account-level shared knowledge retrieval.",
+ "advanced": true
+ },
"recallLimit": {
"label": "Recall Limit",
"placeholder": "6",
@@ -134,9 +174,27 @@
"agentId": {
"type": "string"
},
+ "serverAuthMode": {
+ "type": "string"
+ },
"apiKey": {
"type": "string"
},
+ "accountId": {
+ "type": "string"
+ },
+ "userId": {
+ "type": "string"
+ },
+ "isolateUserScopeByAgent": {
+ "type": "boolean"
+ },
+ "isolateAgentScopeByUser": {
+ "type": "boolean"
+ },
+ "agentScopeMode": {
+ "type": "string"
+ },
"targetUri": {
"type": "string"
},
@@ -155,6 +213,9 @@
"autoRecall": {
"type": "boolean"
},
+ "recallResources": {
+ "type": "boolean"
+ },
"recallLimit": {
"type": "number"
},
diff --git a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
index 2f17e1941..66248ffee 100644
--- a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
+++ b/examples/openclaw-plugin/tests/context-engine-assemble.test.ts
@@ -9,6 +9,8 @@ const cfg = memoryOpenVikingConfigSchema.parse({
baseUrl: "http://127.0.0.1:1933",
autoCapture: false,
autoRecall: false,
+ ingestReplyAssist: false,
+ emitStandardDiagnostics: true,
});
function roughEstimate(messages: unknown[]): number {
@@ -256,6 +258,29 @@ describe("context-engine assemble()", () => {
]);
});
+ it("records senderId from runtimeContext in assemble diagnostics", async () => {
+ const { engine, logger } = makeEngine({
+ latest_archive_overview: "",
+ pre_archive_abstracts: [],
+ messages: [],
+ estimatedTokens: 0,
+ stats: makeStats(),
+ });
+
+ await engine.assemble({
+ sessionId: "session-with-sender",
+ messages: [{ role: "user", content: "hello" }],
+ runtimeContext: { senderId: "telegram:12345" },
+ });
+
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining("\"senderIdFound\":true"),
+ );
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining("\"senderId\":\"telegram:12345\""),
+ );
+ });
+
it("falls back to live messages when assembled active messages look truncated", async () => {
const { engine } = makeEngine({
latest_archive_overview: "",
diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.ts
index 4a33727ca..4f62f4ed3 100644
--- a/examples/openclaw-plugin/tests/ut/client.test.ts
+++ b/examples/openclaw-plugin/tests/ut/client.test.ts
@@ -34,6 +34,10 @@ describe("isMemoryUri", () => {
expect(isMemoryUri("viking://user/default/memories/item-1")).toBe(true);
});
+ it("returns true for user memory URI isolated by agent", () => {
+ expect(isMemoryUri("viking://user/alice/agent/work/memories/item-1")).toBe(true);
+ });
+
it("returns true for valid agent memory URI", () => {
expect(isMemoryUri("viking://agent/memories/xyz")).toBe(true);
});
@@ -42,6 +46,10 @@ describe("isMemoryUri", () => {
expect(isMemoryUri("viking://agent/abc123/memories/item-2")).toBe(true);
});
+ it("returns true for agent memory URI isolated by user", () => {
+ expect(isMemoryUri("viking://agent/work/user/alice/memories/item-2")).toBe(true);
+ });
+
it("returns true for user memories root", () => {
expect(isMemoryUri("viking://user/memories")).toBe(true);
});
@@ -324,3 +332,225 @@ describe("OpenVikingClient resource and skill import", () => {
});
});
});
+
+describe("OpenVikingClient tenant headers (advanced accountId / userId overrides)", () => {
+ it("sends configured accountId and userId in request headers for trusted flows", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "sk-test", "agent", 5000,
+ "trusted",
+ "acct-123", "user-456",
+ );
+ await client.healthCheck();
+
+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
+ const headers = new Headers(init.headers);
+ expect(headers.get("X-OpenViking-Account")).toBe("acct-123");
+ expect(headers.get("X-OpenViking-User")).toBe("user-456");
+ });
+
+ it("keeps api_key user-key flow free of explicit tenant overrides when accountId/userId are not configured", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "sk-user", "agent", 5000,
+ "api_key",
+ "", "",
+ );
+ await client.healthCheck();
+
+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
+ const headers = new Headers(init.headers);
+ expect(headers.get("X-OpenViking-Account")).toBeNull();
+ expect(headers.get("X-OpenViking-User")).toBeNull();
+ expect(headers.get("X-API-Key")).toBe("sk-user");
+ });
+
+ it("preserves explicit tenant headers for api_key root-key style flows", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "sk-root", "agent", 5000,
+ "api_key",
+ "acct-123", "user-456",
+ );
+ await client.healthCheck();
+
+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
+ const headers = new Headers(init.headers);
+ expect(headers.get("X-API-Key")).toBe("sk-root");
+ expect(headers.get("X-OpenViking-Account")).toBe("acct-123");
+ expect(headers.get("X-OpenViking-User")).toBe("user-456");
+ });
+
+ it("falls back to default/default in api_key dev mode when apiKey is missing", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "agent", 5000,
+ "api_key",
+ "", "",
+ );
+ await client.healthCheck();
+
+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
+ const headers = new Headers(init.headers);
+ expect(headers.get("X-OpenViking-Account")).toBe("default");
+ expect(headers.get("X-OpenViking-User")).toBe("default");
+ });
+
+ it("trims whitespace from trusted accountId and userId overrides", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "agent", 5000,
+ "trusted",
+ " acct ", " user ",
+ );
+ await client.healthCheck();
+
+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
+ const headers = new Headers(init.headers);
+ expect(headers.get("X-OpenViking-Account")).toBe("acct");
+ expect(headers.get("X-OpenViking-User")).toBe("user");
+ });
+});
+
+describe("OpenVikingClient canonical namespace policy", () => {
+ it("expands user memory alias to canonical user root by default", async () => {
+ const fetchMock = vi.fn(async (url: string) => {
+ if (url.endsWith("/api/v1/system/status")) {
+ return okResponse({ user: "alice" });
+ }
+ if (url.endsWith("/api/v1/search/find")) {
+ return okResponse({ memories: [], total: 0 });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "my-agent", 5000,
+ "api_key",
+ "", "", undefined,
+ false,
+ true,
+ );
+ await client.find("test query", { targetUri: "viking://user/memories" });
+
+ const findCall = fetchMock.mock.calls.find((c) =>
+ String(c[0]).endsWith("/api/v1/search/find"),
+ )!;
+ const body = JSON.parse(String((findCall[1] as RequestInit).body));
+ expect(body.target_uri).toBe("viking://user/alice/memories");
+ });
+
+ it("expands user memory alias to user/agent root when isolateUserScopeByAgent=true", async () => {
+ const fetchMock = vi.fn(async (url: string) => {
+ if (url.endsWith("/api/v1/system/status")) {
+ return okResponse({ user: "alice" });
+ }
+ if (url.endsWith("/api/v1/search/find")) {
+ return okResponse({ memories: [], total: 0 });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "my-agent", 5000,
+ "api_key",
+ "", "", undefined,
+ true,
+ true,
+ );
+ await client.find("test query", { targetUri: "viking://user/memories" });
+
+ const findCall = fetchMock.mock.calls.find((c) =>
+ String(c[0]).endsWith("/api/v1/search/find"),
+ )!;
+ const body = JSON.parse(String((findCall[1] as RequestInit).body));
+ expect(body.target_uri).toBe("viking://user/alice/agent/my-agent/memories");
+ });
+
+ it("expands agent memory alias to canonical agent/user root by default", async () => {
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ if (url.endsWith("/api/v1/system/status")) {
+ return okResponse({ user: "alice" });
+ }
+ if (url.endsWith("/api/v1/search/find")) {
+ return okResponse({ memories: [], total: 0 });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "shared-agent", 5000,
+ "api_key",
+ "", "", undefined,
+ false,
+ true,
+ );
+ await client.find("test", { targetUri: "viking://agent/memories" });
+
+ const findCall = fetchMock.mock.calls.find((c) =>
+ String(c[0]).endsWith("/api/v1/search/find"),
+ )!;
+ const body = JSON.parse(String((findCall[1] as RequestInit).body));
+ expect(body.target_uri).toBe("viking://agent/shared-agent/user/alice/memories");
+ });
+
+ it("expands agent scope paths without user suffix when isolateAgentScopeByUser=false", async () => {
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ if (url.endsWith("/api/v1/system/status")) {
+ return okResponse({ user: "alice" });
+ }
+ if (url.endsWith("/api/v1/search/find")) {
+ return okResponse({ memories: [], total: 0 });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient(
+ "http://127.0.0.1:1933", "", "shared-agent", 5000,
+ "api_key",
+ "", "", undefined,
+ false,
+ false,
+ );
+ await client.find("test", { targetUri: "viking://agent/skills" });
+
+ const findCall = fetchMock.mock.calls.find((c) =>
+ String(c[0]).endsWith("/api/v1/search/find"),
+ )!;
+ const body = JSON.parse(String((findCall[1] as RequestInit).body));
+ expect(body.target_uri).toBe("viking://agent/shared-agent/skills");
+ });
+
+ it("includes role_id when addSessionMessage receives one", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(okResponse({ session_id: "s1" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);
+ await client.addSessionMessage(
+ "s1",
+ "user",
+ [{ type: "text", text: "hello" }],
+ "agent",
+ "2026-04-20T00:00:00.000Z",
+ "telegram_12345",
+ );
+
+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
+ const body = JSON.parse(String(init.body));
+ expect(body.role_id).toBe("telegram_12345");
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/config.test.ts b/examples/openclaw-plugin/tests/ut/config.test.ts
index 6f60f6ed6..165da6f34 100644
--- a/examples/openclaw-plugin/tests/ut/config.test.ts
+++ b/examples/openclaw-plugin/tests/ut/config.test.ts
@@ -26,6 +26,9 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {
expect(cfg.captureMaxLength).toBe(24000);
expect(cfg.recallMaxContentChars).toBe(500);
expect(cfg.agentId).toBe("default");
+ expect(cfg.serverAuthMode).toBe("api_key");
+ expect(cfg.isolateUserScopeByAgent).toBe(false);
+ expect(cfg.isolateAgentScopeByUser).toBe(false);
expect(cfg.emitStandardDiagnostics).toBe(false);
});
@@ -163,4 +166,108 @@ describe("memoryOpenVikingConfigSchema.parse()", () => {
const cfg = memoryOpenVikingConfigSchema.parse({ agentId: " " });
expect(cfg.agentId).toBe("default");
});
+
+ it("parses accountId and trims whitespace", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ accountId: " acct-123 " });
+ expect(cfg.accountId).toBe("acct-123");
+ });
+
+ it("defaults accountId to empty string when missing", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({});
+ expect(cfg.accountId).toBe("");
+ });
+
+ it("defaults accountId to empty string for whitespace-only value", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ accountId: " " });
+ expect(cfg.accountId).toBe("");
+ });
+
+ it("parses userId and trims whitespace", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ userId: " user-456 " });
+ expect(cfg.userId).toBe("user-456");
+ });
+
+ it("defaults userId to empty string when missing", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({});
+ expect(cfg.userId).toBe("");
+ });
+
+ it("default user-key flow does not require accountId, userId, or agentScopeMode", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ baseUrl: "http://127.0.0.1:1933",
+ apiKey: "sk-user",
+ agentId: "coding-agent",
+ });
+ expect(cfg.accountId).toBe("");
+ expect(cfg.userId).toBe("");
+ expect(cfg.agentScopeMode).toBe("agent");
+ expect(cfg.isolateUserScopeByAgent).toBe(false);
+ expect(cfg.isolateAgentScopeByUser).toBe(false);
+ });
+
+ it("defaults namespace policy to the current server-side false/false policy", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({});
+ expect(cfg.agentScopeMode).toBe("agent");
+ expect(cfg.isolateUserScopeByAgent).toBe(false);
+ expect(cfg.isolateAgentScopeByUser).toBe(false);
+ });
+
+ it("maps deprecated agentScopeMode 'agent' to false/false namespace policy", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ agentScopeMode: "agent" });
+ expect(cfg.agentScopeMode).toBe("agent");
+ expect(cfg.isolateUserScopeByAgent).toBe(false);
+ expect(cfg.isolateAgentScopeByUser).toBe(false);
+ });
+
+ it("falls back to user_agent for invalid agentScopeMode", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ agentScopeMode: "invalid" });
+ expect(cfg.agentScopeMode).toBe("agent");
+ expect(cfg.isolateUserScopeByAgent).toBe(false);
+ expect(cfg.isolateAgentScopeByUser).toBe(false);
+ });
+
+ it("maps explicit deprecated agentScopeMode 'user_agent' to false/true namespace policy", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ agentScopeMode: "user_agent" });
+ expect(cfg.agentScopeMode).toBe("user_agent");
+ expect(cfg.isolateUserScopeByAgent).toBe(false);
+ expect(cfg.isolateAgentScopeByUser).toBe(true);
+ });
+
+ it("explicit namespace policy overrides deprecated agentScopeMode", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({
+ agentScopeMode: "agent",
+ isolateUserScopeByAgent: true,
+ isolateAgentScopeByUser: true,
+ });
+ expect(cfg.agentScopeMode).toBe("agent");
+ expect(cfg.isolateUserScopeByAgent).toBe(true);
+ expect(cfg.isolateAgentScopeByUser).toBe(true);
+ });
+
+ it("parses trusted serverAuthMode", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ serverAuthMode: "trusted" });
+ expect(cfg.serverAuthMode).toBe("trusted");
+ });
+
+ it("falls back to api_key for invalid serverAuthMode", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ serverAuthMode: "invalid" });
+ expect(cfg.serverAuthMode).toBe("api_key");
+ });
+
+ it("defaults recallResources to false", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({});
+ expect(cfg.recallResources).toBe(false);
+ });
+
+ it("enables recallResources when set to true", () => {
+ const cfg = memoryOpenVikingConfigSchema.parse({ recallResources: true });
+ expect(cfg.recallResources).toBe(true);
+ });
+
+ it("recallResources only accepts boolean true", () => {
+ const cfg1 = memoryOpenVikingConfigSchema.parse({ recallResources: "true" });
+ expect(cfg1.recallResources).toBe(false);
+ const cfg2 = memoryOpenVikingConfigSchema.parse({ recallResources: 1 });
+ expect(cfg2.recallResources).toBe(false);
+ });
});
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 376825ea5..130e8d117 100644
--- a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
+++ b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts
@@ -229,6 +229,64 @@ describe("context-engine afterTurn()", () => {
expect(createdAt).toBe("2026-04-01T10:03:00.000Z");
});
+ it("records senderId from runtimeContext in afterTurn diagnostics", async () => {
+ const { engine, logger } = makeEngine({
+ commitTokenThreshold: 50,
+ getSession: { pending_tokens: 5000 },
+ cfgOverrides: { serverAuthMode: "trusted" },
+ });
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages: [{ role: "user", content: "hello world" }],
+ prePromptMessageCount: 0,
+ runtimeContext: { senderId: "telegram:12345" },
+ });
+
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining("\"senderIdFound\":true"),
+ );
+ expect(logger.info).toHaveBeenCalledWith(
+ expect.stringContaining("\"senderId\":\"telegram:12345\""),
+ );
+ });
+
+ it("passes sanitized senderId as role_id in trusted mode", async () => {
+ const { engine, client } = makeEngine({
+ cfgOverrides: { serverAuthMode: "trusted" },
+ });
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages: [{ role: "user", content: "hello world" }],
+ prePromptMessageCount: 0,
+ runtimeContext: { senderId: "telegram:12345" },
+ });
+
+ expect(client.addSessionMessage).toHaveBeenCalledTimes(1);
+ expect(client.addSessionMessage.mock.calls[0][5]).toBe("telegram_12345");
+ });
+
+
+ it("passes sanitized senderId as role_id in api_key mode", async () => {
+ const { engine, client } = makeEngine({
+ cfgOverrides: { serverAuthMode: "api_key" },
+ });
+
+ await engine.afterTurn!({
+ sessionId: "s1",
+ sessionFile: "",
+ messages: [{ role: "user", content: "hello world" }],
+ prePromptMessageCount: 0,
+ runtimeContext: { senderId: "telegram:12345" },
+ });
+
+ expect(client.addSessionMessage).toHaveBeenCalledTimes(1);
+ expect(client.addSessionMessage.mock.calls[0][5]).toBe("telegram_12345");
+ });
+
it("sanitizes <relevant-memories> from user content but not from assistant", async () => {
const { engine, client } = makeEngine();
@@ -458,12 +516,12 @@ describe("context-engine afterTurn()", () => {
// assistant → user(toolResult) → assistant
expect(client.addSessionMessage.mock.calls[0][1]).toBe("assistant");
expect(client.addSessionMessage.mock.calls[1][1]).toBe("user");
- expect(client.addSessionMessage.mock.calls[1][2][0].tool_output).toContain("[bash result]:");
expect(client.addSessionMessage.mock.calls[1][2][0].tool_output).toContain("file1.txt");
+ expect(client.addSessionMessage.mock.calls[1][2][0].tool_output).toContain("file2.txt");
expect(client.addSessionMessage.mock.calls[2][1]).toBe("assistant");
});
- it("merges adjacent same-role messages", async () => {
+ it("stores adjacent same-role messages as separate entries with current extractor behavior", async () => {
const { engine, client } = makeEngine();
const messages = [
@@ -479,15 +537,17 @@ describe("context-engine afterTurn()", () => {
prePromptMessageCount: 0,
});
- expect(client.addSessionMessage).toHaveBeenCalledTimes(2);
+ expect(client.addSessionMessage).toHaveBeenCalledTimes(3);
expect(client.addSessionMessage.mock.calls[0][1]).toBe("user");
const firstCallParts = client.addSessionMessage.mock.calls[0][2] as Array<{ text?: string; type?: string }>;
expect(firstCallParts.map(p => p.text).join(" ")).toContain("first question");
- expect(firstCallParts.map(p => p.text).join(" ")).toContain("second question");
- expect(client.addSessionMessage.mock.calls[1][1]).toBe("assistant");
+ expect(client.addSessionMessage.mock.calls[1][1]).toBe("user");
+ const secondCallParts = client.addSessionMessage.mock.calls[1][2] as Array<{ text?: string; type?: string }>;
+ expect(secondCallParts.map(p => p.text).join(" ")).toContain("second question");
+ expect(client.addSessionMessage.mock.calls[2][1]).toBe("assistant");
});
- it("merges adjacent toolResults into one user group", async () => {
+ it("stores adjacent toolResults as separate user groups with current extractor behavior", async () => {
const { engine, client } = makeEngine();
const messages = [
@@ -507,17 +567,16 @@ describe("context-engine afterTurn()", () => {
prePromptMessageCount: 0,
});
- expect(client.addSessionMessage).toHaveBeenCalledTimes(3);
+ expect(client.addSessionMessage).toHaveBeenCalledTimes(4);
expect(client.addSessionMessage.mock.calls[0][1]).toBe("assistant");
- // Two toolResults merged into one user call
expect(client.addSessionMessage.mock.calls[1][1]).toBe("user");
- const toolParts = (client.addSessionMessage.mock.calls[1][2] as Array<{ tool_output?: string }>).filter(p => p.tool_output);
- expect(toolParts.map(p => p.tool_output).join(" ")).toContain("[read result]:");
- expect(toolParts.map(p => p.tool_output).join(" ")).toContain("[write result]:");
- expect(client.addSessionMessage.mock.calls[2][1]).toBe("assistant");
+ expect((client.addSessionMessage.mock.calls[1][2] as Array<{ tool_output?: string }>)[0]?.tool_output).toContain("content of a");
+ expect(client.addSessionMessage.mock.calls[2][1]).toBe("user");
+ expect((client.addSessionMessage.mock.calls[2][2] as Array<{ tool_output?: string }>)[0]?.tool_output).toContain("ok");
+ expect(client.addSessionMessage.mock.calls[3][1]).toBe("assistant");
});
- it("does not sanitize <relevant-memories> from assistant content", async () => {
+ it("sanitizes <relevant-memories> from assistant content", async () => {
const { engine, client } = makeEngine();
const messages = [
@@ -534,7 +593,8 @@ describe("context-engine afterTurn()", () => {
expect(client.addSessionMessage).toHaveBeenCalledTimes(2);
const assistantParts = client.addSessionMessage.mock.calls[1][2] as Array<{ text?: string }>;
- expect(assistantParts.map(p => p.text).join(" ")).toContain("relevant-memories");
+ expect(assistantParts.map(p => p.text).join(" ")).not.toContain("relevant-memories");
+ expect(assistantParts.map(p => p.text).join(" ")).toContain("Here is context");
});
it("skips heartbeat messages from being stored", async () => {
diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.ts
index 40a615968..1681b2af1 100644
--- a/examples/openclaw-plugin/tests/ut/tools.test.ts
+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts
@@ -181,6 +181,48 @@ describe("Tool: memory_store (behavioral)", () => {
expect(store!.name).toBe("memory_store");
expect(store!.description).toContain("Store text");
});
+
+ it("uses requesterSenderId to populate role_id for user writes", async () => {
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ if (url.endsWith("/api/v1/system/status")) {
+ return okResponse({ user: "default" });
+ }
+ if (url.includes("/messages")) {
+ return okResponse({ session_id: "sess-1" });
+ }
+ if (url.endsWith("/commit")) {
+ return okResponse({
+ status: "completed",
+ archived: false,
+ memories_extracted: { core: 1 },
+ });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { factoryTools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const factory = factoryTools.get("memory_store");
+ expect(factory).toBeDefined();
+
+ const tool = factory!({
+ sessionId: "runtime-session",
+ sessionKey: "agent:main:main",
+ requesterSenderId: "wx/user-01@abc",
+ });
+
+ await tool.execute("tc-memory-store", { text: "hello from tool" });
+
+ const messageCall = fetchMock.mock.calls.find(([url]) =>
+ String(url).includes("/api/v1/sessions/") && String(url).includes("/messages"),
+ );
+ expect(messageCall).toBeDefined();
+ const [, init] = messageCall as [string, RequestInit];
+ const body = JSON.parse(String(init.body));
+ expect(body.role).toBe("user");
+ expect(body.role_id).toBe("wx_user-01_abc");
+ });
});
describe("Tool: memory_forget (behavioral)", () => {
@@ -563,6 +605,66 @@ describe("Plugin registration", () => {
expect(headers.get("X-OpenViking-Agent")).toBe("worker");
});
+ it("search command propagates configured tenant headers", async () => {
+ const fetchMock = vi.fn(async (url: string) => {
+ if (url.endsWith("/api/v1/search/find")) {
+ return okResponse({ memories: [], resources: [], skills: [], total: 0 });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { commands, api } = setupPlugin();
+ api.pluginConfig = {
+ ...api.pluginConfig,
+ accountId: "acct-shared",
+ userId: "alice",
+ };
+ contextEnginePlugin.register(api as any);
+
+ await commands.get("ov-search")!.handler({
+ args: "test query --uri viking://resources",
+ commandBody: "/ov-search",
+ agentId: "worker",
+ sessionId: "session-1",
+ sessionKey: "agent:worker:session-1",
+ });
+
+ const [, init] = fetchMock.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/search/find")) as [string, RequestInit];
+ const headers = new Headers(init.headers);
+ expect(headers.get("X-OpenViking-Account")).toBe("acct-shared");
+ expect(headers.get("X-OpenViking-User")).toBe("alice");
+ expect(headers.get("X-OpenViking-Agent")).toBe("worker");
+ });
+
+ it("import tool propagates configured tenant headers for resource imports", async () => {
+ const fetchMock = vi.fn(async () =>
+ okResponse({ root_uri: "viking://resources/shared-docs", status: "success" }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { tools, api } = setupPlugin();
+ api.pluginConfig = {
+ ...api.pluginConfig,
+ accountId: "acct-shared",
+ userId: "alice",
+ };
+ contextEnginePlugin.register(api as any);
+
+ const tool = tools.get("ov_import")!;
+ await tool.execute("tc-import", {
+ kind: "resource",
+ source: "https://example.com/docs",
+ to: "viking://resources/shared-docs",
+ wait: true,
+ });
+
+ const [, init] = fetchMock.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/resources")) as [string, RequestInit];
+ const headers = new Headers(init.headers);
+ expect(headers.get("X-OpenViking-Account")).toBe("acct-shared");
+ expect(headers.get("X-OpenViking-User")).toBe("alice");
+ });
+
it("slash commands honor bypassSessionPatterns", async () => {
const fetchMock = vi.fn(async () => okResponse({}));
vi.stubGlobal("fetch", fetchMock);