Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(plugins): use actor peer scope (#2595)
Qin Haojie8353976bc855
diff --git a/examples/claude-code-memory-plugin/README.md b/examples/claude-code-memory-plugin/README.mdindex 253d57ac6..037eaa9ed 100644--- a/examples/claude-code-memory-plugin/README.md+++ b/examples/claude-code-memory-plugin/README.md@@ -167,7 +167,7 @@ All plugin behavior can be set via env vars. Connection / identity vars affect b| `OPENVIKING_USER` | Multi-tenant user (`X-OpenViking-User` header) || `OPENVIKING_PEER_ID` | Optional stable peer for recall and captured session messages |-When `OPENVIKING_PEER_ID` is set, hooks pass it as request-level `peer_id`. Subagent capture falls back to Claude's `agent_id` when no explicit peer is configured, so different subagents can keep separate peer memory by default.+When `OPENVIKING_PEER_ID` is set, data-plane recall/profile requests send it as `X-OpenViking-Actor-Peer`; captured session messages store it as body `peer_id`. Subagent capture falls back to Claude's `agent_id` when no explicit peer is configured, so different subagents can keep separate peer memory by default.#### Recall tuning@@ -319,10 +319,10 @@ Claude Code has a built-in `MEMORY.md` file system. This plugin **complements**|--------------|-----------------------------------|----------------------------------------------------|| Storage | Flat markdown | Vector DB + structured extraction || Search | Loaded into context wholesale | Semantic similarity + ranking + token budget |-| Scope | Per-project | Cross-project, cross-session, cross-agent |+| Scope | Per-project | Cross-project, cross-session, peer-scoped || Capacity | ~200 lines (context limit) | Unlimited (server-side storage) || Extraction | Manual rules | LLM-powered entity / preference / event extraction |-| Subagents | Same as parent | Isolated session + typed agent namespace |+| Subagents | Same as parent | Isolated session + peer-scoped capture |---diff --git a/examples/claude-code-memory-plugin/README_CN.md b/examples/claude-code-memory-plugin/README_CN.mdindex a514e357f..bc987f8d2 100644--- a/examples/claude-code-memory-plugin/README_CN.md+++ b/examples/claude-code-memory-plugin/README_CN.md@@ -167,7 +167,7 @@ claude() {| `OPENVIKING_USER` | 多租户 user(`X-OpenViking-User` 头) || `OPENVIKING_PEER_ID` | 可选的稳定 peer,用于自动召回和 session message 写入 |-设置 `OPENVIKING_PEER_ID` 后,hook 会把它作为请求级 `peer_id` 发送。未显式配置 peer 时,subagent 捕获会回退到 Claude 的 `agent_id`,让不同 subagent 默认落到不同 peer memory。+设置 `OPENVIKING_PEER_ID` 后,数据面的 recall/profile 请求会把它作为 `X-OpenViking-Actor-Peer` 发送;捕获到 session message 时仍写入 body `peer_id`。未显式配置 peer 时,subagent 捕获会回退到 Claude 的 `agent_id`,让不同 subagent 默认落到不同 peer memory。#### 召回调优@@ -319,10 +319,10 @@ Claude Code 自带 `MEMORY.md` 文件系统,本插件**与之互补**:|----------|-----------------------------|-----------------------------------------------|| 存储 | 扁平 markdown | 向量数据库 + 结构化抽取 || 搜索 | 整体加载进上下文 | 语义相似度 + 排序 + token 预算 |-| 范围 | 单项目 | 跨项目、跨会话、跨 agent |+| 范围 | 单项目 | 跨项目、跨会话、peer 维度 || 容量 | ~200 行(受上下文限制) | 不受限(服务端存储) || 抽取 | 手写规则 | LLM 驱动的实体 / 偏好 / 事件抽取 |-| 子 agent | 与父共享 | 隔离 session + 类型化 agent namespace |+| 子 agent | 与父共享 | 隔离 session + peer 维度捕获 |---diff --git a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs b/examples/claude-code-memory-plugin/scripts/auto-recall.mjsindex 14ec792a7..9fd9876a4 100644--- a/examples/claude-code-memory-plugin/scripts/auto-recall.mjs+++ b/examples/claude-code-memory-plugin/scripts/auto-recall.mjs@@ -128,7 +128,11 @@ async function resolveUserSpace() {fallbackSpace = status.result.user.trim();}- const lsRes = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`);+ const lsRes = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId: cfg.peerId },+ );if (lsRes.ok && Array.isArray(lsRes.result)) {const spaces = lsRes.result.filter(e => e?.isDir)@@ -170,11 +174,10 @@ const SOURCES = [async function searchOneSource(query, source, limit) {const resolvedUri = await resolveTargetUri(source.uri);const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };- if (cfg.peerId) body.peer_id = cfg.peerId;const res = await fetchJSON("/api/v1/search/find", {method: "POST",body: JSON.stringify(body),- });+ }, { actorPeerId: cfg.peerId });if (!res.ok) return [];const items = res.result?.[source.bucket] || [];return items.map(item => ({ ...item, _sourceType: source.type }));@@ -214,7 +217,11 @@ async function resolveItemContent(item) {content = (item.abstract || item.overview).trim();} else if (item.level === 2) {try {- const res = await fetchJSON(`/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`);+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(item.uri)}`,+ {},+ { actorPeerId: cfg.peerId },+ );const body = res.ok && typeof res.result === "string" ? res.result.trim() : "";content = body || (item.abstract || item.overview || "").trim() || item.uri;} catch {diff --git a/examples/claude-code-memory-plugin/scripts/debug-recall.mjs b/examples/claude-code-memory-plugin/scripts/debug-recall.mjsindex 1fb8f2073..a4bcf94ba 100755--- a/examples/claude-code-memory-plugin/scripts/debug-recall.mjs+++ b/examples/claude-code-memory-plugin/scripts/debug-recall.mjs@@ -62,7 +62,7 @@ try {// fetchJSON (verbose version — shows response details on error)// ----------------------------------------------------------------------------async function fetchJSON(path, init = {}) {+async function fetchJSON(path, init = {}, options = {}) {const url = `${cfg.baseUrl}${path}`;const controller = new AbortController();const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);@@ -71,6 +71,8 @@ async function fetchJSON(path, init = {}) {if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;+ const actorPeerId = options.actorPeerId ?? "";+ if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;const res = await fetch(url, { ...init, headers, signal: controller.signal });const body = await res.json();if (!res.ok || body.status === "error") {@@ -207,7 +209,11 @@ async function resolveScopeSpace(scope) {const reservedDirs = scope === "user" ? USER_RESERVED_DIRS : AGENT_RESERVED_DIRS;try {- const entries = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent(`viking://${scope}`)}&output=original`);+ const entries = await fetchJSON(+ `/api/v1/fs/ls?uri=${encodeURIComponent(`viking://${scope}`)}&output=original`,+ {},+ { actorPeerId: cfg.peerId },+ );if (Array.isArray(entries)) {const spaces = entries.filter(e => e?.isDir)@@ -248,11 +254,10 @@ async function searchScope(queryText, targetUri, limit) {const resolvedUri = await resolveTargetUri(targetUri);dim(` target: ${targetUri} -> ${resolvedUri}`);const body = { query: queryText, target_uri: resolvedUri, limit, score_threshold: 0 };- if (cfg.peerId) body.peer_id = cfg.peerId;const result = await fetchJSON("/api/v1/search/find", {method: "POST",body: JSON.stringify(body),- });+ }, { actorPeerId: cfg.peerId });return result?.memories || [];}@@ -273,7 +278,11 @@ async function searchUserScope(queryText, limit) {async function readMemoryContent(uri) {try {- const result = await fetchJSON(`/api/v1/content/read?uri=${encodeURIComponent(uri)}`);+ const result = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(uri)}`,+ {},+ { actorPeerId: cfg.peerId },+ );if (result && typeof result === "string" && result.trim()) return result.trim();} catch (err) {warn(` Failed to read content for ${uri}: ${err?.message || err}`);diff --git a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjsindex b50504ce9..eb9da03be 100644--- a/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs+++ b/examples/claude-code-memory-plugin/scripts/lib/ov-session.mjs@@ -83,7 +83,7 @@ export function deriveOvSessionId(ccSessionId, suffix = "") {*/export function makeFetchJSON(cfg, timeoutKey = "timeoutMs") {const timeoutMs = Math.max(1000, cfg[timeoutKey] || cfg.timeoutMs || 10000);- return async function fetchJSON(path, init = {}) {+ return async function fetchJSON(path, init = {}, options = {}) {const controller = new AbortController();const timer = setTimeout(() => controller.abort(), timeoutMs);try {@@ -91,6 +91,8 @@ export function makeFetchJSON(cfg, timeoutKey = "timeoutMs") {if (cfg.apiKey) headers["Authorization"] = `Bearer ${cfg.apiKey}`;if (cfg.accountId) headers["X-OpenViking-Account"] = cfg.accountId;if (cfg.userId) headers["X-OpenViking-User"] = cfg.userId;+ const actorPeerId = options.actorPeerId ?? "";+ if (actorPeerId) headers["X-OpenViking-Actor-Peer"] = actorPeerId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => ({}));if (!res.ok || body.status === "error") {diff --git a/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs b/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjsindex c7ce3dc26..1b4bec26a 100644--- a/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs+++ b/examples/claude-code-memory-plugin/scripts/lib/profile-inject.mjs@@ -24,7 +24,7 @@ let _userSpaceCache = null;* Duplicated rather than imported to avoid coupling session-start to* auto-recall's module-level fetchJSON closure.*/-async function resolveUserSpace(fetchJSON) {+async function resolveUserSpace(fetchJSON, actorPeerId = "") {if (_userSpaceCache) return _userSpaceCache;let fallbackSpace = "default";@@ -35,6 +35,8 @@ async function resolveUserSpace(fetchJSON) {const lsRes = await fetchJSON(`/api/v1/fs/ls?uri=${encodeURIComponent("viking://user")}&output=original`,+ {},+ { actorPeerId },);if (lsRes.ok && Array.isArray(lsRes.result)) {const spaces = lsRes.result@@ -95,8 +97,12 @@ function tokensToCharsBudget(content, maxTokens) {return Math.floor(maxTokens / Math.max(tokensPerChar, 0.25));}-async function readProfile(fetchJSON, profileUri) {- const res = await fetchJSON(`/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`);+async function readProfile(fetchJSON, profileUri, actorPeerId = "") {+ const res = await fetchJSON(+ `/api/v1/content/read?uri=${encodeURIComponent(profileUri)}`,+ {},+ { actorPeerId },+ );if (!res.ok || typeof res.result !== "string") return null;const trimmed = res.result.trim();return trimmed || null;@@ -111,9 +117,9 @@ async function readProfile(fetchJSON, profileUri) {* `rel_path` (e.g. "zhengxiao.wu/pr_workflow.md") is preserved as display name* to keep owner-namespacing visible and unambiguous when multiple owners exist.*/-async function lsDir(fetchJSON, dirUri) {+async function lsDir(fetchJSON, dirUri, actorPeerId = "") {const url = `/api/v1/fs/ls?uri=${encodeURIComponent(dirUri)}&output=agent&recursive=true&abs_limit=512&node_limit=512`;- const res = await fetchJSON(url);+ const res = await fetchJSON(url, {}, { actorPeerId });if (!res.ok || !Array.isArray(res.result)) return [];return res.result.filter((e) => !e.isDir)@@ -233,16 +239,16 @@ function formatListing(headerUri, entries, budgetTokens) {* droppedPref: number, droppedEnt: number,* }>}*/-export async function buildProfileBlock(fetchJSON, totalBudgetTokens) {- const space = await resolveUserSpace(fetchJSON);+export async function buildProfileBlock(fetchJSON, totalBudgetTokens, actorPeerId = "") {+ const space = await resolveUserSpace(fetchJSON, actorPeerId);const profileUri = `viking://user/${space}/memories/profile.md`;const prefUri = `viking://user/${space}/memories/preferences`;const entUri = `viking://user/${space}/memories/entities`;const [profile, prefs, ents] = await Promise.all([- readProfile(fetchJSON, profileUri),- lsDir(fetchJSON, prefUri),- lsDir(fetchJSON, entUri),+ readProfile(fetchJSON, profileUri, actorPeerId),+ lsDir(fetchJSON, prefUri, actorPeerId),+ lsDir(fetchJSON, entUri, actorPeerId),]);if (!profile && prefs.length === 0 && ents.length === 0) return null;diff --git a/examples/claude-code-memory-plugin/scripts/session-start.mjs b/examples/claude-code-memory-plugin/scripts/session-start.mjsindex 8d31cd435..8273047a3 100644--- a/examples/claude-code-memory-plugin/scripts/session-start.mjs+++ b/examples/claude-code-memory-plugin/scripts/session-start.mjs@@ -145,7 +145,7 @@ async function main() {let profile = null;if (!cfg.noAutoInject) {try {- profile = await buildProfileBlock(fetchJSON, cfg.profileTokenBudget);+ profile = await buildProfileBlock(fetchJSON, cfg.profileTokenBudget, cfg.peerId);} catch (err) {logError("profile_inject", err);}diff --git a/examples/codex-memory-plugin/README.md b/examples/codex-memory-plugin/README.mdindex 95e657c4f..59f1efda2 100644--- a/examples/codex-memory-plugin/README.md+++ b/examples/codex-memory-plugin/README.md@@ -94,7 +94,7 @@ The shell function wrapper handles step 1 for you by promoting ovcli.conf fieldsAuth is sent as `Authorization: Bearer <api_key>` to both the REST API (used by hooks) and the `/mcp` endpoint (used by the model).-Set `OPENVIKING_PEER_ID` when multiple Codex peers share the same OpenViking user and should keep separate peer memory. Hooks pass it as request-level `peer_id` for auto-recall and captured session messages. The legacy `codex.peerId` / `codex.peer_id` fields in `ov.conf` are also honored, but env vars are preferred.+Set `OPENVIKING_PEER_ID` when multiple Codex peers share the same OpenViking user and should keep separate peer memory. Recall passes it as `X-OpenViking-Actor-Peer`; captured session messages store it as `peer_id`. The legacy `codex.peerId` / `codex.peer_id` fields in `ov.conf` are also honored, but env vars are preferred.For **unauthenticated local OV** (`ovcli.conf` without `api_key`, or no ovcli.conf at all), `.mcp.json` is rendered *without* `bearer_token_env_var`. Codex 0.130 hard-fails MCP startup with `Environment variable ... is empty` if `bearer_token_env_var` points at an empty/unset env var, so it must be omitted entirely when there's no key.diff --git a/examples/codex-memory-plugin/scripts/auto-recall.mjs b/examples/codex-memory-plugin/scripts/auto-recall.mjsindex 2bbd6ce05..0cf755567 100644--- a/examples/codex-memory-plugin/scripts/auto-recall.mjs+++ b/examples/codex-memory-plugin/scripts/auto-recall.mjs@@ -47,6 +47,7 @@ async function fetchJSON(path, init = {}) {}if (cfg.account) headers["X-OpenViking-Account"] = cfg.account;if (cfg.user) headers["X-OpenViking-User"] = cfg.user;+ if (cfg.peerId) headers["X-OpenViking-Actor-Peer"] = cfg.peerId;const res = await fetch(`${cfg.baseUrl}${path}`, { ...init, headers, signal: controller.signal });const body = await res.json().catch(() => null);if (!body) return null;@@ -218,7 +219,6 @@ async function resolveTargetUri(targetUri) {async function searchScope(query, targetUri, limit, bucket = "memories") {const resolvedUri = await resolveTargetUri(targetUri);const body = { query, target_uri: resolvedUri, limit, score_threshold: 0 };- if (cfg.peerId) body.peer_id = cfg.peerId;const result = await fetchJSON("/api/v1/search/find", {method: "POST",body: JSON.stringify(body),diff --git a/examples/openclaw-plugin/INSTALL-AGENT.md b/examples/openclaw-plugin/INSTALL-AGENT.mdindex 8ac397fcc..000bb4364 100644--- a/examples/openclaw-plugin/INSTALL-AGENT.md+++ b/examples/openclaw-plugin/INSTALL-AGENT.md@@ -96,7 +96,7 @@ openclaw openviking setup \--json```-Assistant peer prefix (optional; only when the user explicitly requests assistant `peer_id`):+Assistant peer prefix (optional; only when the user explicitly requests assistant `peer_id` / actor peer scoping):```bashopenclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --peer-role assistant --peer-prefix <PREFIX> --json@@ -139,8 +139,8 @@ Also inspect:| `health.version` | Records server version || `health.compatibility` | Determines whether to warn || `config.hasApiKey` | Confirms whether an API key was saved |-| `config.peer_role` | Confirms which messages write `peer_id` |-| `config.peer_prefix` | Confirms configured assistant peer prefix when present |+| `config.peer_role` | Confirms which messages write body `peer_id` and which data-plane requests use actor peer scope |+| `config.peer_prefix` | Confirms configured assistant peer / actor peer prefix when present |## Environment Detection@@ -268,8 +268,8 @@ Core fields:| `mode` | Legacy compatibility field. Expected value: `remote`. || `baseUrl` | OpenViking HTTP endpoint || `apiKey` | OpenViking API key |-| `peer_role` | Controls session `peer_id` writes and recall/search `peer_id`: `none`, `assistant`, or `person`. New installs default to `none`. |-| `peer_prefix` | Optional prefix for assistant `peer_id` values when `peer_role=assistant`. |+| `peer_role` | Peer identity mode: `none`, `assistant`, or `person`. New installs default to `none`. Session messages use body `peer_id`; data-plane recall/search uses `X-OpenViking-Actor-Peer`. |+| `peer_prefix` | Optional prefix for assistant `peer_id` / actor peer values when `peer_role=assistant`. || `accountId` | Required for root API keys || `userId` | Required for root API keys |@@ -331,8 +331,8 @@ Existing config fields are preserved during migration. The new plugin reads old- `baseUrl`- `apiKey`-- `peer_role`: optional; default `none`; controls session writes and recall/search `peer_id`-- `peer_prefix`: optional when `peer_role=assistant`+- `peer_role`: optional; default `none`; selects the peer identity mode+- `peer_prefix`: optional assistant `peer_id` / actor peer prefix when `peer_role=assistant`## Backup Path: ov-installdiff --git a/examples/openclaw-plugin/INSTALL-ZH.md b/examples/openclaw-plugin/INSTALL-ZH.mdindex 0e7e250c2..762144dff 100644--- a/examples/openclaw-plugin/INSTALL-ZH.md+++ b/examples/openclaw-plugin/INSTALL-ZH.md@@ -67,7 +67,7 @@ openclaw openviking status --json- 重启 `openclaw gateway`。- 执行 `openclaw openviking status --json` 和 `openclaw config get plugins.slots.contextEngine` 验证。-如果需要把 OpenClaw assistant 说话人写成独立 `peer_id`,可以额外传:+如果需要把 OpenClaw assistant 说话人写成独立 `peer_id`,并让数据面 recall/search 使用对应 actor peer 视图,可以额外传:```bashopenclaw openviking setup \@@ -102,7 +102,7 @@ npm run build- 发送一轮 OpenClaw 对话后,`Session` 下出现原始会话。- 触发 `/compact` 或等待 commit 后,`User/memories` 出现长期记忆。-- 如果配置了 `peer_role=assistant`,recall/search 会携带对应 `peer_id`,可用于区分不同 OpenClaw assistant 说话人。+- 如果配置了 `peer_role=assistant`,数据面 recall/search 会携带对应 `X-OpenViking-Actor-Peer`,session message 仍用 body `peer_id` 做消息归因。- 通过手动 `/add-resource` 导入文档、URL 或目录后,`Resources` 下出现对应知识,并可做目录递归检索。Agent 可见的 `add_resource` 工具默认禁用,只有显式设置 `enableAddResourceTool=true` 后才暴露。## 启动 OpenViking Server@@ -200,7 +200,7 @@ openclaw openviking setup \openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --force-slot --json```-如需给 assistant message 写入带前缀的 `peer_id`(可选;多数用户保持默认 `none` 即可):+如需给 assistant message 写入带前缀的 `peer_id`,并让数据面 recall/search 使用对应 actor peer 视图(可选;多数用户保持默认 `none` 即可):```bashopenclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --peer-role assistant --peer-prefix <PREFIX> --json@@ -264,8 +264,8 @@ plugins.entries.openviking.config| `mode` | `remote` | 兼容旧配置的字段。当前只支持 remote。 || `baseUrl` | `http://127.0.0.1:1933` | OpenViking HTTP 地址 || `apiKey` | 空 | OpenViking API key |-| `peer_role` | `none` | 控制 session message 和 recall/search 请求是否写 `peer_id`:`none`、`assistant` 或 `person`。 |-| `peer_prefix` | 空 | `peer_role=assistant` 时 assistant `peer_id` 的可选前缀。 |+| `peer_role` | `none` | Peer 身份模式:`none`、`assistant` 或 `person`。Session message 使用 body `peer_id`;数据面 recall/search 使用 `X-OpenViking-Actor-Peer`。 |+| `peer_prefix` | 空 | `peer_role=assistant` 时 assistant `peer_id` / actor peer 值的可选前缀。 || `accountId` | 空 | 使用 root API key 时需要 || `userId` | 空 | 使用 root API key 时需要 |@@ -289,8 +289,8 @@ openclaw config get plugins.entries.openviking.config| --- | --- | --- || `baseUrl` | `http://127.0.0.1:1933` | 远端 OpenViking 服务地址 || `apiKey` | 空 | 远端 OpenViking API Key;服务端未开启认证时可不填 |-| `peer_role` | `none` | 控制 session message 和 recall/search 请求是否写 `peer_id`:`none`、`assistant` 或 `person` |-| `peer_prefix` | 空 | `peer_role=assistant` 时 assistant `peer_id` 的可选前缀 |+| `peer_role` | `none` | Peer 身份模式:`none`、`assistant` 或 `person`;session message 使用 body `peer_id`,数据面 recall/search 使用 `X-OpenViking-Actor-Peer` |+| `peer_prefix` | 空 | `peer_role=assistant` 时 assistant `peer_id` / actor peer 值的可选前缀 |常见设置:@@ -352,7 +352,7 @@ ov-install| `--base-url URL` | OpenViking 服务器地址(启用非交互模式) || `--api-key KEY` | OpenViking API key || `--peer-role ROLE` | Peer role:`none`、`assistant` 或 `person` |-| `--peer-prefix PREFIX` | assistant `peer_id` 的前缀 |+| `--peer-prefix PREFIX` | assistant `peer_id` / actor peer 值的前缀 || `--update` | 更新 helper 管理的安装 |面向用户的安装,请先使用 `openclaw plugins install clawhub:@openviking/openclaw-plugin`。只有作为备用路径时才选择 `ov-install`。diff --git a/examples/openclaw-plugin/INSTALL.md b/examples/openclaw-plugin/INSTALL.mdindex 412608980..5a2744b05 100644--- a/examples/openclaw-plugin/INSTALL.md+++ b/examples/openclaw-plugin/INSTALL.md@@ -141,7 +141,7 @@ If another context engine already owns the slot, setup will not replace it by deopenclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --force-slot --json```-If you want assistant messages to carry a prefixed `peer_id` (optional; most users keep the default `none`):+If you want assistant messages to carry a prefixed `peer_id` and data-plane recall/search requests to use the matching actor peer view (optional; most users keep the default `none`):```bashopenclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --peer-role assistant --peer-prefix <PREFIX> --json@@ -205,8 +205,8 @@ Core fields:| `mode` | `remote` | Legacy compatibility field. Only remote mode is supported. || `baseUrl` | `http://127.0.0.1:1933` | OpenViking HTTP endpoint || `apiKey` | empty | OpenViking API key |-| `peer_role` | `none` | Controls session `peer_id` writes and recall/search `peer_id`: `none`, `assistant`, or `person`. |-| `peer_prefix` | empty | Optional prefix for assistant `peer_id` values when `peer_role=assistant`. |+| `peer_role` | `none` | Peer identity mode: `none`, `assistant`, or `person`. Session messages use body `peer_id`; data-plane recall/search uses `X-OpenViking-Actor-Peer`. |+| `peer_prefix` | empty | Optional prefix for assistant `peer_id` / actor peer values when `peer_role=assistant`. || `accountId` | empty | Required when using a root API key || `userId` | empty | Required when using a root API key |@@ -273,7 +273,7 @@ Useful backup/source flags:| `--base-url URL` | OpenViking server URL (enables non-interactive mode) || `--api-key KEY` | OpenViking API key || `--peer-role ROLE` | Peer role: `none`, `assistant`, or `person` |-| `--peer-prefix PREFIX` | Prefix for assistant `peer_id` values |+| `--peer-prefix PREFIX` | Prefix for assistant `peer_id` / actor peer values || `--update` | Update an existing helper-managed install |For user-facing installs, use `openclaw plugins install clawhub:@openviking/openclaw-plugin` first. Choose `ov-install` only as the backup path.@@ -317,8 +317,8 @@ The plugin connects to an existing remote OpenViking server.| --- | --- | --- || `baseUrl` | `http://127.0.0.1:1933` | Remote OpenViking HTTP endpoint || `apiKey` | empty | Optional OpenViking API key |-| `peer_role` | `none` | Controls session `peer_id` writes and recall/search `peer_id`: `none`, `assistant`, or `person` |-| `peer_prefix` | empty | Optional prefix for assistant `peer_id` values when `peer_role=assistant` |+| `peer_role` | `none` | Peer identity mode: `none`, `assistant`, or `person`; session messages use body `peer_id`, while data-plane recall/search uses `X-OpenViking-Actor-Peer` |+| `peer_prefix` | empty | Optional prefix for assistant `peer_id` / actor peer values when `peer_role=assistant` |Common settings:diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.mdindex 9b67521a7..4086dc1a5 100644--- a/examples/openclaw-plugin/README.md+++ b/examples/openclaw-plugin/README.md@@ -123,7 +123,7 @@ The main rules are:- `peer_role=none` is the default and does not write `peer_id` on session messages- `peer_role=assistant` writes assistant messages with `peer_id=<sessionAgent>`; if `peer_prefix` is set, the value becomes `<peer_prefix>_<sessionAgent>`- `peer_role=person` writes user messages with `peer_id` derived from OpenClaw sender identity; assistant messages do not get `peer_id`-- recall/search requests also send the same resolved `peer_id` when `peer_role` is `assistant` or `person`+- data-plane recall/search/read/import/delete sends the same resolved peer identity as `X-OpenViking-Actor-Peer` when `peer_role` is `assistant` or `person`- when OpenClaw does not provide a session agent, use its default agent `main` for local session and assistant peer metadata- only add `X-OpenViking-Account` / `X-OpenViking-User` when `accountId` / `userId` are explicitly configured@@ -142,9 +142,9 @@ In this setup:- new installs default to `peer_role=none`- `accountId` / `userId` are advanced options only when the deployment needs explicit identity headers, such as root-key or trusted-server flows-### Canonical user namespace+### User namespace-The plugin writes and searches user-scoped memory. `viking://user/memories` is expanded to `viking://user/<user_id>/memories` using the identity resolved from the configured user key. `viking://agent/...` is deprecated by OpenViking and is not used by the plugin.+The plugin writes and searches user-scoped memory through `viking://user/...`; OpenViking resolves that alias from the request tenant and actor-peer context. `viking://agent/...` is deprecated by OpenViking and is not used by the plugin.## assemble Recall Flowdiff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.mdindex caac8951c..18e3b7a13 100644--- a/examples/openclaw-plugin/README_CN.md+++ b/examples/openclaw-plugin/README_CN.md@@ -122,7 +122,7 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking- `peer_role=none` 是默认值,session message 不写 `peer_id`。- `peer_role=assistant` 时,assistant message 写入 `peer_id=<sessionAgent>`;如果配置了 `peer_prefix`,则写入 `<peer_prefix>_<sessionAgent>`。- `peer_role=person` 时,user message 使用 OpenClaw sender 身份派生 `peer_id`;assistant message 不写 `peer_id`。-- recall/search 请求也会在 `peer_role=assistant` 或 `peer_role=person` 时发送同一个解析后的 `peer_id`。+- 数据面的 recall/search/read/import/delete 会在 `peer_role=assistant` 或 `peer_role=person` 时把同一个解析后的 peer 身份作为 `X-OpenViking-Actor-Peer` 发送。- OpenClaw 没有提供 session agent 时,使用其默认 agent `main` 作为本地 session 和 assistant peer metadata。- 只有显式配置了 `accountId` / `userId` 时才发送 `X-OpenViking-Account` / `X-OpenViking-User`。@@ -141,9 +141,9 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking- 新安装默认 `peer_role=none`- `accountId` / `userId` 仅在部署需要显式身份 header 时作为高级选项使用,例如 root key 或 trusted server 流程-### Canonical user namespace+### User namespace-插件写入和检索 user-scoped memory。`viking://user/memories` 会根据 user key 解析出的身份展开为 `viking://user/<user_id>/memories`。`viking://agent/...` 已由 OpenViking 废弃,插件不再使用。+插件通过 `viking://user/...` 写入和检索 user-scoped memory;OpenViking 会根据请求里的租户身份和 actor peer context 解析这个别名。`viking://agent/...` 已由 OpenViking 废弃,插件不再使用。## assemble 召回链路diff --git a/examples/openclaw-plugin/auto-recall.ts b/examples/openclaw-plugin/auto-recall.tsindex 0c553d462..2e6fee244 100644--- a/examples/openclaw-plugin/auto-recall.ts+++ b/examples/openclaw-plugin/auto-recall.ts@@ -259,7 +259,6 @@ function preview(value: string | undefined | null, maxChars: number): string | ufunction traceResourceTypeForUri(uri: string | undefined): RecallResourceType {if (uri?.startsWith("viking://resources")) return "resource";- if (uri?.startsWith("viking://agent/")) return "agent";if (uri?.startsWith("viking://session/") || uri?.includes("/sessions/")) return "session";return "user";}@@ -395,18 +394,19 @@ export async function buildAgentExperienceRecallContext(params: {cfg: ParsedMemoryOpenVikingConfig;client: OpenVikingClient;agentId: string;+ peerId?: string;queryText: string;trigger: ExperienceRecallTrigger;logger: Logger;verbose?: (message: string) => void;}): Promise<{ block?: string; count: number; estimatedTokens: number; skippedReason?: string }> {- const { cfg, client, agentId, queryText, trigger, logger, verbose } = params;+ const { cfg, client, agentId, peerId, queryText, trigger, logger, verbose } = params;const expCfg = cfg.agentExperience;if (!expCfg.enabled) {return { count: 0, estimatedTokens: 0, skippedReason: "disabled" };}- const precheck = await quickRecallPrecheck(client, agentId);+ const precheck = await quickRecallPrecheck(client);if (!precheck.ok) {verbose?.(`openviking: skipping agent experience recall because precheck failed (${precheck.reason})`);return { count: 0, estimatedTokens: 0, skippedReason: precheck.reason };@@ -418,7 +418,8 @@ export async function buildAgentExperienceRecallContext(params: {targetUri: "viking://user/memories/experiences",limit: Math.max(expCfg.recallLimit * 4, 12),scoreThreshold: expCfg.scoreThreshold,- }, agentId);+ actorPeerId: peerId,+ });const candidates = (result.memories ?? []).filter(isExperienceMemory)@@ -433,7 +434,7 @@ export async function buildAgentExperienceRecallContext(params: {let chars = 0;for (const item of candidates) {const content = item.level === 2- ? await client.read(item.uri, agentId).catch(() => item.abstract ?? item.uri)+ ? await client.read(item.uri, peerId).catch(() => item.abstract ?? item.uri): item.abstract ?? item.overview ?? item.uri;const exp = renderExperience(item, content);if (!exp) continue;@@ -469,13 +470,14 @@ export async function buildGatedAgentExperienceRecallContext(params: {cfg: ParsedMemoryOpenVikingConfig;client: OpenVikingClient;agentId: string;+ peerId?: string;queryText: string;sessionKey?: string;runtimeContext?: unknown;logger: Logger;verbose?: (message: string) => void;}): Promise<{ block?: string; count: number; estimatedTokens: number; skippedReason?: string }> {- const { cfg, client, agentId, queryText, sessionKey, runtimeContext, logger, verbose } = params;+ const { cfg, client, agentId, peerId, queryText, sessionKey, runtimeContext, logger, verbose } = params;if (!cfg.agentExperience.enabled) {return { count: 0, estimatedTokens: 0, skippedReason: "disabled" };}@@ -499,6 +501,7 @@ export async function buildGatedAgentExperienceRecallContext(params: {cfg,client,agentId,+ peerId,queryText,trigger: decision.trigger ?? "task_start",logger,@@ -527,7 +530,7 @@ export async function buildLongTermMemoryRecallContext(params: {return { memoryCount: 0, estimatedTokens: 0 };}- const precheck = await quickRecallPrecheck(client, agentId);+ const precheck = await quickRecallPrecheck(client);if (!precheck.ok) {verbose?.(`openviking: skipping auto-recall because precheck failed (${precheck.reason})`);return { memoryCount: 0, estimatedTokens: 0 };@@ -546,8 +549,9 @@ export async function buildLongTermMemoryRecallContext(params: {targetUri: search.targetUri,limit: candidateLimit,scoreThreshold: 0,- peerId,- }, agentId);+ contextType: search.contextType,+ actorPeerId: peerId,+ });return {search,result,@@ -576,6 +580,7 @@ export async function buildLongTermMemoryRecallContext(params: {allMemories.push(...memories, ...resources);traceSearches.push({resourceType: s.value.search.resourceType,+ contextType: s.value.search.contextType,targetUriInput: s.value.search.targetUri,targetUriResolved: s.value.search.targetUri,limit: candidateLimit,@@ -600,6 +605,7 @@ export async function buildLongTermMemoryRecallContext(params: {logger.warn?.(`openviking: auto-recall search failed: ${String(s.reason)}`);traceSearches.push({resourceType: search.resourceType,+ contextType: search.contextType,targetUriInput: search.targetUri,targetUriResolved: search.targetUri,limit: candidateLimit,@@ -663,7 +669,7 @@ export async function buildLongTermMemoryRecallContext(params: {const { lines: memoryLines, estimatedTokens } = await buildMemoryLinesWithBudget(memories,- (uri) => client.read(uri, agentId),+ (uri) => client.read(uri, peerId),{recallPreferAbstract: cfg.recallPreferAbstract,recallMaxInjectedChars: cfg.recallMaxInjectedChars,diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.tsindex 93c6f47b4..8466cf27d 100644--- a/examples/openclaw-plugin/client.ts+++ b/examples/openclaw-plugin/client.ts@@ -29,11 +29,6 @@ export type FsListEntry = string | Record<string, unknown>;export type FsListResult = FsListEntry[];export type CaptureMode = "semantic" | "keyword";-export type RuntimeIdentity = {- userId: string;- agentId: string;-};-function userSessionUri(sessionId: string): string {return `viking://user/sessions/${encodeURIComponent(sessionId)}`;}@@ -214,7 +209,6 @@ function sleep(ms: number): Promise<void> {const MEMORY_URI_PATTERNS = [/^viking:\/\/user\/(?:[^/]+\/)?memories(?:\/|$)/,];-const USER_STRUCTURE_DIRS = new Set(["memories", "skills", "profile.md", ".abstract.md", ".overview.md"]);const REMOTE_RESOURCE_PREFIXES = ["http://", "https://", "git@", "ssh://", "git://"];export function isMemoryUri(uri: string): boolean {@@ -246,8 +240,6 @@ async function cleanupUploadTempPath(path?: string): Promise<void> {}export class OpenVikingClient {- private identityCache = new Map<string, RuntimeIdentity>();-constructor(private readonly baseUrl: string,private readonly apiKey: string,@@ -264,19 +256,6 @@ export class OpenVikingClient {return this.defaultAgentId;}- private resolveEffectiveAgentId(agentId?: string): string {- const explicit = agentId?.trim();- if (explicit) {- return explicit;- }- const prefix = this.defaultAgentId.trim();- return prefix ? `${prefix}_main` : "main";- }-- async getResolvedIdentity(agentId?: string): Promise<RuntimeIdentity> {- return this.getRuntimeIdentity(agentId);- }-private resolveTenantHeaders():| { apiKey?: string; accountId?: string; userId?: string }{@@ -290,25 +269,25 @@ export class OpenVikingClient {};}+ private resolveActorPeerHeader(actorPeerId?: string): string | undefined {+ const value = actorPeerId?.trim();+ return value || undefined;+ }+private async emitRoutingDebug(label: string,detail: Record<string, unknown>,- agentId?: string,): Promise<void> {if (!this.routingDebugLog) {return;}- const effectiveAgentId = this.resolveEffectiveAgentId(agentId);- const identity = await this.getRuntimeIdentity(agentId);const tenantHeaders = this.resolveTenantHeaders();this.routingDebugLog(`openviking: ${label} ` +JSON.stringify({...detail,- runtime_agent_id: effectiveAgentId,X_OpenViking_Account: tenantHeaders.accountId ?? null,X_OpenViking_User: tenantHeaders.userId ?? null,- resolved_user_id: identity.userId,session_vfs_hint: detail.sessionId? userSessionUri(String(detail.sessionId)): undefined,@@ -319,10 +298,9 @@ export class OpenVikingClient {private async request<T>(path: string,init: RequestInit = {},- agentId?: string,requestTimeoutMs?: number,+ actorPeerId?: string,): Promise<T> {- void agentId;const controller = new AbortController();const timer = setTimeout(() => controller.abort(), requestTimeoutMs ?? this.timeoutMs);try {@@ -337,6 +315,10 @@ export class OpenVikingClient {if (tenantHeaders.userId) {headers.set("X-OpenViking-User", tenantHeaders.userId);}+ const actorPeerHeader = this.resolveActorPeerHeader(actorPeerId);+ if (actorPeerHeader) {+ headers.set("X-OpenViking-Actor-Peer", actorPeerHeader);+ }if (init.body && !(init.body instanceof FormData) && !headers.has("Content-Type")) {headers.set("Content-Type", "application/json");}@@ -365,14 +347,13 @@ export class OpenVikingClient {}}- async healthCheck(agentId?: string, requestTimeoutMs?: number): Promise<void> {- await this.request<{ status: string }>("/health", {}, agentId, requestTimeoutMs);+ async healthCheck(requestTimeoutMs?: number): Promise<void> {+ await this.request<{ status: string }>("/health", {}, requestTimeoutMs);}async createSession(sessionId: string,options?: { memoryPolicy?: OVMemoryPolicy },- agentId?: string,): Promise<{ session_id: string; user?: unknown }> {const body: Record<string, unknown> = { session_id: sessionId };if (options?.memoryPolicy) {@@ -381,17 +362,15 @@ export class OpenVikingClient {return this.request<{ session_id: string; user?: unknown }>("/api/v1/sessions",{ method: "POST", body: JSON.stringify(body) },- agentId,);}async ensureSession(sessionId: string,options?: { memoryPolicy?: OVMemoryPolicy },- agentId?: string,): Promise<boolean> {try {- await this.createSession(sessionId, options, agentId);+ await this.createSession(sessionId, options);return true;} catch (err) {const message = err instanceof Error ? err.message : String(err);@@ -402,113 +381,63 @@ export class OpenVikingClient {}}- private async getRuntimeIdentity(agentId?: string): Promise<RuntimeIdentity> {- const effectiveAgentId = this.resolveEffectiveAgentId(agentId);- const cached = this.identityCache.get(effectiveAgentId);- if (cached) {- return cached;- }- const fallback: RuntimeIdentity = { userId: "default", agentId: effectiveAgentId };- try {- const status = await this.request<{ user?: unknown }>("/api/v1/system/status", {}, agentId);- const userId =- typeof status.user === "string" && status.user.trim() ? status.user.trim() : "default";- const identity: RuntimeIdentity = { userId, agentId: effectiveAgentId };- this.identityCache.set(effectiveAgentId, identity);- return identity;- } catch {- this.identityCache.set(effectiveAgentId, fallback);- return fallback;- }- }-- private async buildCanonicalRoot(agentId?: string): Promise<string> {- const identity = await this.getRuntimeIdentity(agentId);- return `viking://user/${identity.userId}`;- }-- private async normalizeTargetUri(targetUri: string, agentId?: string): Promise<string> {- const trimmed = targetUri.trim().replace(/\/+$/, "");- const match = trimmed.match(/^viking:\/\/user(?:\/(.*))?$/);- if (!match) {- return trimmed;- }- const rawRest = (match[1] ?? "").trim();- if (!rawRest) {- return trimmed;- }- const parts = rawRest.split("/").filter(Boolean);- if (parts.length === 0) {- return trimmed;- }-- let suffix = parts;- if (!USER_STRUCTURE_DIRS.has(suffix[0]!)) {- return trimmed;- }-- const root = await this.buildCanonicalRoot(agentId);- return `${root}/${suffix.join("/")}`;- }-async find(query: string,options: {- targetUri: string;+ targetUri?: string;limit?: number;scoreThreshold?: number;- peerId?: string;+ contextType?: string | string[];+ actorPeerId?: string;},- agentId?: string,): Promise<FindResult> {- const normalizedTargetUri = await this.normalizeTargetUri(options.targetUri, agentId);+ const targetUri = options.targetUri?.trim().replace(/\/+$/, "") ?? "";const body: {query: string;- target_uri: string;+ target_uri?: string;limit?: number;score_threshold?: number;- peer_id?: string;+ context_type?: string | string[];} = {query,- target_uri: normalizedTargetUri,limit: options.limit,score_threshold: options.scoreThreshold,+ context_type: options.contextType,};- if (options.peerId) {- body.peer_id = options.peerId;+ if (targetUri) {+ body.target_uri = targetUri;}- const effectiveAgentId = this.resolveEffectiveAgentId(agentId);- const identity = await this.getRuntimeIdentity(agentId);+ const actorPeerId = this.resolveActorPeerHeader(options.actorPeerId);const tenantHeaders = this.resolveTenantHeaders();this.routingDebugLog?.(`openviking: find POST ${this.baseUrl}/api/v1/search/find ` +JSON.stringify({- runtime_agent_id: effectiveAgentId,X_OpenViking_Account: tenantHeaders.accountId ?? null,X_OpenViking_User: tenantHeaders.userId ?? null,- resolved_user_id: identity.userId,- target_uri: normalizedTargetUri,+ X_OpenViking_Actor_Peer: actorPeerId ?? null,+ target_uri: targetUri || null,target_uri_input: options.targetUri,- peer_id: options.peerId ?? null,query:query.length > 4000? `${query.slice(0, 4000)}…(+${query.length - 4000} more chars)`: query,limit: body.limit,score_threshold: body.score_threshold ?? null,+ context_type: body.context_type ?? null,}),);return this.request<FindResult>("/api/v1/search/find", {method: "POST",body: JSON.stringify(body),- }, agentId);+ }, undefined, actorPeerId);}- async read(uri: string, agentId?: string): Promise<string> {+ async read(uri: string, actorPeerId?: string): Promise<string> {return this.request<string>(`/api/v1/content/read?uri=${encodeURIComponent(uri)}`,{},- agentId,+ undefined,+ actorPeerId,);}@@ -521,10 +450,10 @@ export class OpenVikingClient {absLimit?: number;showAllHidden?: boolean;nodeLimit?: number;+ actorPeerId?: string;},- agentId?: string,): Promise<FsListResult> {- const normalizedUri = await this.normalizeTargetUri(uri, agentId);+ const normalizedUri = uri.trim().replace(/\/+$/, "");const params = new URLSearchParams({uri: normalizedUri,recursive: String(options?.recursive ?? false),@@ -534,14 +463,18 @@ export class OpenVikingClient {show_all_hidden: String(options?.showAllHidden ?? false),node_limit: String(options?.nodeLimit ?? 1000),});- return this.request<FsListResult>(`/api/v1/fs/ls?${params.toString()}`, {}, agentId);+ return this.request<FsListResult>(+ `/api/v1/fs/ls?${params.toString()}`,+ {},+ undefined,+ options?.actorPeerId,+ );}async readToolResult(sessionId: string,toolResultId: string,options?: { offset?: number; limit?: number; includeMetadata?: boolean },- agentId?: string,): Promise<ToolResultReadResult> {const params = new URLSearchParams();if (options?.offset !== undefined) params.set("offset", String(options.offset));@@ -553,7 +486,6 @@ export class OpenVikingClient {return this.request<ToolResultReadResult>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/tool-results/${encodeURIComponent(toolResultId)}${query ? `?${query}` : ""}`,{},- agentId,);}@@ -562,7 +494,6 @@ export class OpenVikingClient {toolResultId: string,queryText: string,options?: { limit?: number; contextChars?: number },- agentId?: string,): Promise<ToolResultSearchResult> {const params = new URLSearchParams({ q: queryText });if (options?.limit !== undefined) params.set("limit", String(options.limit));@@ -572,14 +503,12 @@ export class OpenVikingClient {return this.request<ToolResultSearchResult>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/tool-results/${encodeURIComponent(toolResultId)}/search?${params.toString()}`,{},- agentId,);}async listToolResults(sessionId: string,options?: { toolName?: string; limit?: number },- agentId?: string,): Promise<ToolResultListResult> {const params = new URLSearchParams();if (options?.toolName) params.set("tool_name", options.toolName);@@ -588,11 +517,10 @@ export class OpenVikingClient {return this.request<ToolResultListResult>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/tool-results${query ? `?${query}` : ""}`,{},- agentId,);}- async uploadTempFile(filePath: string, agentId?: string): Promise<string> {+ async uploadTempFile(filePath: string, actorPeerId?: string): Promise<string> {const fileBytes = await readFile(filePath);const form = new FormData();form.append(@@ -603,7 +531,8 @@ export class OpenVikingClient {const result = await this.request<{ temp_file_id: string }>("/api/v1/resources/temp_upload",{ method: "POST", body: form },- agentId,+ undefined,+ actorPeerId,);if (!result.temp_file_id) {throw new Error("OpenViking temp upload did not return temp_file_id");@@ -668,7 +597,7 @@ export class OpenVikingClient {return zipPath;}- async addResource(input: AddResourceInput, agentId?: string): Promise<AddResourceResult> {+ async addResource(input: AddResourceInput, actorPeerId?: string): Promise<AddResourceResult> {const pathOrUrl = input.pathOrUrl.trim();if (!pathOrUrl) {throw new Error("pathOrUrl is required");@@ -709,20 +638,20 @@ export class OpenVikingClient {} else if (!localStats.isFile()) {throw new Error(`Path is not a file or directory: ${pathOrUrl}`);}- body.temp_file_id = await this.uploadTempFile(uploadPath, agentId);+ body.temp_file_id = await this.uploadTempFile(uploadPath, actorPeerId);}return this.request<AddResourceResult>("/api/v1/resources",{ method: "POST", body: JSON.stringify(body) },- agentId,requestTimeoutMs,+ actorPeerId,);} finally {await cleanupUploadTempPath(cleanupPath);}}- async addSkill(input: AddSkillInput, agentId?: string): Promise<AddSkillResult> {+ async addSkill(input: AddSkillInput, actorPeerId?: string): Promise<AddSkillResult> {const hasPath = typeof input.path === "string" && input.path.trim().length > 0;const hasData = input.data !== undefined && input.data !== null;if (hasPath === hasData) {@@ -747,15 +676,15 @@ export class OpenVikingClient {} else if (!localStats.isFile()) {throw new Error(`Path is not a file or directory: ${skillPath}`);}- body.temp_file_id = await this.uploadTempFile(uploadPath, agentId);+ body.temp_file_id = await this.uploadTempFile(uploadPath, actorPeerId);} else {body.data = input.data;}return this.request<AddSkillResult>("/api/v1/skills",{ method: "POST", body: JSON.stringify(body) },- agentId,requestTimeoutMs,+ actorPeerId,);} finally {await cleanupUploadTempPath(cleanupPath);@@ -791,7 +720,6 @@ export class OpenVikingClient {abstract?: string;context_type?: "memory" | "resource" | "skill";}>,- agentId?: string,createdAt?: string,peerId?: string,): Promise<void> {@@ -817,7 +745,6 @@ export class OpenVikingClient {partCount: parts.length,created_at: createdAt ?? null,},- agentId,);await this.request<{ session_id: string }>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,@@ -825,12 +752,11 @@ export class OpenVikingClient {method: "POST",body: JSON.stringify(body),},- agentId,);}/** GET session — server auto-creates if absent; returns session meta including message stats and token usage. */- async getSession(sessionId: string, agentId?: string): Promise<{+ async getSession(sessionId: string): Promise<{message_count?: number;commit_count?: number;last_commit_at?: string;@@ -846,7 +772,6 @@ export class OpenVikingClient {}>(`/api/v1/sessions/${encodeURIComponent(sessionId)}`,{ method: "GET" },- agentId,);}@@ -862,7 +787,6 @@ export class OpenVikingClient {options?: {wait?: boolean;timeoutMs?: number;- agentId?: string;/*** WM v2: number of most-recent messages to keep live after commit.* Forwarded as `keep_recent_count` in the POST body. 0 (default)@@ -883,7 +807,6 @@ export class OpenVikingClient {wait: options?.wait ?? false,keepRecentCount,},- options?.agentId,);const body: Record<string, unknown> = {};if (keepRecentCount > 0) {@@ -892,7 +815,6 @@ export class OpenVikingClient {const result = await this.request<CommitSessionResult>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,{ method: "POST", body: JSON.stringify(body) },- options?.agentId,);if (!options?.wait || !result.task_id) {@@ -904,7 +826,7 @@ export class OpenVikingClient {const pollInterval = 500;while (Date.now() < deadline) {await sleep(pollInterval);- const task = await this.getTask(result.task_id, options.agentId).catch(() => null);+ const task = await this.getTask(result.task_id).catch(() => null);if (!task) break;if (task.status === "completed") {const taskResult = (task.result ?? {}) as Record<string, unknown>;@@ -924,35 +846,30 @@ export class OpenVikingClient {}/** Poll a background task by ID. */- async getTask(taskId: string, agentId?: string): Promise<TaskResult> {+ async getTask(taskId: string): Promise<TaskResult> {return this.request<TaskResult>(`/api/v1/tasks/${encodeURIComponent(taskId)}`,{ method: "GET" },- agentId,);}async getSessionContext(sessionId: string,tokenBudget: number = 128_000,- agentId?: string,): Promise<SessionContextResult> {return this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/context?token_budget=${tokenBudget}`,{ method: "GET" },- agentId,);}async getSessionArchive(sessionId: string,archiveId: string,- agentId?: string,): Promise<SessionArchiveResult> {return this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/archives/${encodeURIComponent(archiveId)}`,{ method: "GET" },- agentId,);}@@ -964,7 +881,6 @@ export class OpenVikingClient {caseInsensitive?: boolean;nodeLimit?: number;levelLimit?: number;- agentId?: string;} = {},): Promise<{matches: Array<{ line: number; uri: string; content: string }>;@@ -986,16 +902,15 @@ export class OpenVikingClient {...(options.levelLimit !== undefined ? { level_limit: options.levelLimit } : {}),}),},- options.agentId,);}- async deleteSession(sessionId: string, agentId?: string): Promise<void> {- await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" }, agentId);+ async deleteSession(sessionId: string): Promise<void> {+ await this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" });}- async deleteUri(uri: string, agentId?: string): Promise<void> {+ async deleteUri(uri: string, actorPeerId?: string): Promise<void> {await this.request(`/api/v1/fs?uri=${encodeURIComponent(uri)}&recursive=false`, {method: "DELETE",- }, agentId);+ }, undefined, actorPeerId);}}diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.tsindex 28c8ec33b..f0a5bbee3 100644--- a/examples/openclaw-plugin/context-engine.ts+++ b/examples/openclaw-plugin/context-engine.ts@@ -72,10 +72,10 @@ export function resolveMessagePeerId(params: {assistantPeerId?: string;}): string | undefined {if (params.peerRole === "person" && params.role === "user") {- return params.personPeerId;+ return toPeerId(params.personPeerId);}if (params.peerRole === "assistant" && params.role === "assistant") {- return params.assistantPeerId;+ return toPeerId(params.assistantPeerId);}return undefined;}@@ -1038,7 +1038,6 @@ const PHASE2_POLL_MAX_MS = DEFAULT_PHASE2_POLL_TIMEOUT_MS;async function pollPhase2ExtractionOutcome(getClient: () => Promise<OpenVikingClient>,taskId: string,- agentId: string,logger: Logger,sessionLabel: string,): Promise<void> {@@ -1047,7 +1046,7 @@ async function pollPhase2ExtractionOutcome(const client = await getClient();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;});@@ -1136,10 +1135,8 @@ export function createMemoryOpenVikingContextEngine(params: {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);@@ -1415,6 +1412,7 @@ export function createMemoryOpenVikingContextEngine(params: {cfg,client,agentId,+ peerId,queryText: recallQuery.query,sessionKey,runtimeContext: assembleParams.runtimeContext,@@ -1476,9 +1474,7 @@ export function createMemoryOpenVikingContextEngine(params: {try {const client = await getClient();- const routingRef = assembleParams.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;@@ -1568,10 +1564,10 @@ export function createMemoryOpenVikingContextEngine(params: {try {const sender = extractRuntimeSenderId(afterTurnParams.runtimeContext);const { sessionKey, ovSessionId: OVSessionId } = resolveSessionIdentity(afterTurnParams);- const runtimeAgentId = extractRuntimeAgentId(afterTurnParams.runtimeContext);- if (runtimeAgentId) {+ const runtimeAgentPeerSource = extractRuntimeAgentId(afterTurnParams.runtimeContext);+ if (runtimeAgentPeerSource) {rememberSessionAgentId?.({- agentId: runtimeAgentId,+ agentId: runtimeAgentPeerSource,sessionId: afterTurnParams.sessionId,sessionKey,ovSessionId: OVSessionId,@@ -1647,7 +1643,6 @@ export function createMemoryOpenVikingContextEngine(params: {await client.ensureSession(OVSessionId,{ memoryPolicy: defaultMemoryPolicy },- agentId,);}// 发送结构化消息:统一 role 为 user,通过 parts 区分类型@@ -1680,14 +1675,13 @@ export function createMemoryOpenVikingContextEngine(params: {OVSessionId,msg.role,ovParts,- agentId,createdAt,peerId,);}}- const session = await client.getSession(OVSessionId, agentId);+ const session = await client.getSession(OVSessionId);const pendingTokens = session.pending_tokens ?? 0;if (pendingTokens < cfg.commitTokenThreshold) {@@ -1703,7 +1697,6 @@ export function createMemoryOpenVikingContextEngine(params: {const commitResult = await client.commitSession(OVSessionId, {wait: false,- agentId,keepRecentCount: cfg.commitKeepRecentCount,});logger.info(@@ -1730,7 +1723,6 @@ export function createMemoryOpenVikingContextEngine(params: {void pollPhase2ExtractionOutcome(getClient,commitResult.task_id,- agentId,logger,OVSessionId,);@@ -1777,7 +1769,7 @@ export function createMemoryOpenVikingContextEngine(params: {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)@@ -1800,7 +1792,6 @@ export function createMemoryOpenVikingContextEngine(params: {);const commitResult = await client.commitSession(OVSessionId, {wait: true,- agentId,keepRecentCount: 0,});const memCount = totalExtractedMemories(commitResult.memories_extracted);@@ -1903,7 +1894,7 @@ export function createMemoryOpenVikingContextEngine(params: {let ctx: Awaited<ReturnType<typeof client.getSessionContext>> | undefined;try {- ctx = await client.getSessionContext(OVSessionId, tokenBudget, agentId);+ ctx = await client.getSessionContext(OVSessionId, tokenBudget);// 打印完整的 getSessionContext 结果logger.info(`openviking: compact getSessionContext raw result for ${OVSessionId}: ` +diff --git a/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md b/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.mdindex 8740f9a08..0d5d90fd8 100644--- a/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md+++ b/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md@@ -76,7 +76,7 @@ OpenClaw 的 `sessionId/sessionKey` 不能总是直接作为 OpenViking 存储实现位置:`context-engine.ts:342`。-插件仍会从 OpenClaw runtime/session context 解析一个稳定的 agent id,用于 `viking://agent/memories` 的兼容检索目标和 `peer_role=assistant` 时的 assistant `peer_id`。`peer_prefix` 非空时,assistant peer id 会变成 `<peer_prefix>_<agentId>`;当前实现不发送 `X-OpenViking-Agent` header。+插件仍会从 OpenClaw runtime/session context 解析一个稳定的 agent id,用于 `peer_role=assistant` 时的 assistant `peer_id` 和数据面 actor peer 视图。`peer_prefix` 非空时,assistant peer id 会变成 `<peer_prefix>_<agentId>`;当前实现不发送 `X-OpenViking-Agent` header,也不再使用废弃的 `viking://agent/...` 命名空间。### 4.3 `assemble`:回复前组装上下文@@ -104,7 +104,7 @@ transformContext auto recall 流程:1. 从最新 user message 提取查询文本。2. 清洗 metadata、心跳、已注入记忆块等噪音。3. 快速 precheck,OpenViking 不可用时跳过召回,避免拖慢模型请求。-4. 按 `recallTargetTypes` 并行搜索召回目标;默认搜索 `viking://user/memories`、`viking://agent/memories`,显式设为 `resource` 时只搜索 `viking://resources`;旧字段 `recallResources=true` 仅在未显式配置 `recallTargetTypes` 时把 `resource` 追加到默认集合。+4. 按 `recallTargetTypes` 生成搜索计划;默认使用 `context_type=memory` 检索当前 user 的 memory 视图。配置了 `peer_role` 时,数据面请求会发送 `X-OpenViking-Actor-Peer`,由服务端把 peer 集合限制到当前 actor peer;显式设为 `resource` 时使用 `context_type=resource`;旧字段 `recallResources=true` 仅在未显式配置 `recallTargetTypes` 时把 `resource` 追加到默认集合。5. 去重、阈值过滤、leaf 优先、偏好/时间问题 boost、词面重合度 boost。6. 在 `recallMaxInjectedChars` 限制内构建完整记忆行,不截断单条记忆。7. 用 `<relevant-memories>` 块 prepend 到最新 user message。@@ -235,7 +235,7 @@ transformContext auto recall 流程:| `X-OpenViking-Account` | `accountId` / `OPENVIKING_ACCOUNT_ID` | Root key 或 trusted 部署需要的租户 account || `X-OpenViking-User` | `userId` / `OPENVIKING_USER_ID` | Root key 或 trusted 部署需要的用户 |-`peer_role=assistant/person` 时,插件通过请求 body 的 `peer_id` 字段隔离 session 写入和 recall/search;当前实现不发送 `X-OpenViking-Agent` header。+`peer_role=assistant/person` 时,session message 仍通过请求 body 的 `peer_id` 做消息归因;recall/search/read/import/delete 等数据面请求通过 `X-OpenViking-Actor-Peer` 进入当前 actor peer 视图。当前实现不发送 `X-OpenViking-Agent` header。### 6.2 OpenViking 官方 API 完整清单与插件映射@@ -339,13 +339,12 @@ transformContext auto recall 流程:| URI | 含义 || --- | --- || `viking://user/memories` | 当前用户长期记忆别名 |-| `viking://agent/memories` | 当前 agent 长期记忆别名 || `viking://resources` | account/resource 知识库 || `viking://user/skills` | 当前用户 skill 空间 || `viking://user/sessions/{sessionId}/history` | session archive 历史 || `viking://user/sessions/{sessionId}/tool-results/{id}` | 外置工具结果 |-`viking://agent/memories` 仍可作为 agent 记忆检索目标;session 消息和 recall/search 的说话人隔离由 `peer_role` / `peer_prefix` 解析出的 `peer_id` 控制。+`viking://agent/...` 已由 OpenViking 废弃,当前插件不再把它作为检索目标。session 消息的说话人归因由 `peer_role` / `peer_prefix` 解析出的 `peer_id` 控制;recall/search/read/import/delete 的 peer 视图由 `X-OpenViking-Actor-Peer` 控制。---@@ -683,7 +682,7 @@ openclaw config get plugins.slots.contextEngine| `apiKey` | 环境变量或空 | OpenViking API Key || `accountId` | 空 | Root key/trusted 部署需要 || `userId` | 空 | Root key/trusted 部署需要 |-| `peer_role` | `none` | 控制 session message 和 recall/search 请求是否写 `peer_id`:`none`、`assistant` 或 `person` |+| `peer_role` | `none` | 控制哪些 session message 写 `peer_id`,并为数据面请求提供 actor peer 视图:`none`、`assistant` 或 `person` || `peer_prefix` | 空 | `peer_role=assistant` 时 assistant `peer_id` 的可选前缀 || `targetUri` | `viking://user/memories` | 默认 memory search 目标 || `timeoutMs` | `15000` | HTTP 请求超时 |@@ -730,12 +729,12 @@ openclaw config get plugins.slots.contextEngine| `apiKey` | 所有搜索/召回请求 | 空 | 是 | 是 | `OPENVIKING_API_KEY` | HTTP 认证 key;不配通常只能访问关闭认证的本地服务:`config.ts:202` || `accountId` | 多租户搜索路由 | 空 | 是 | 是 | `OPENVIKING_ACCOUNT_ID` | Root key / trusted 部署下显式指定 account,影响搜索命中空间:`config.ts:212` || `userId` | 多租户搜索路由 | 空 | 是 | 是 | `OPENVIKING_USER_ID` | Root key / trusted 部署下显式指定 user,影响 user memory 检索范围:`config.ts:216` |-| `peer_role` | session 写入和 recall/search peer 路由 | `none` | 是 | 否 | — | `none` 不写 `peer_id`;`assistant` 使用 runtime agent;`person` 使用 OpenClaw sender 身份:`config.ts:430` |+| `peer_role` | session 归因和数据面 actor peer 视图 | `none` | 是 | 否 | — | `none` 不写 `peer_id`;`assistant` 使用 runtime agent;`person` 使用 OpenClaw sender 身份:`config.ts:430` || `peer_prefix` | assistant peer id 前缀 | 空 | 是 | 否 | — | `peer_role=assistant` 时可把 assistant `peer_id` 写成 `<peer_prefix>_<agentId>`:`config.ts:431` || `targetUri` | `memory_recall` / `memory_forget` 默认搜索范围 | `viking://user/memories` | 是 | 否 | — | 未显式传 `targetUri` 时的默认 memory 搜索位置:`config.ts:275`、`index.ts:1366` || `timeoutMs` | 所有搜索/读取请求超时 | `15000` | 是 | 否 | — | 控制 `find/read/grep/session` 等 HTTP 请求超时:`config.ts:276` || `autoRecall` | 自动召回总开关 | `true` | 是 | 否 | — | 关闭后插件不再在 `assemble()` 阶段自动发起 recall:`config.ts:283`、`context-engine.ts:1132` |-| `recallTargetTypes` | 自动召回 + 默认 `memory_recall` 资源类型集合 | `["user","agent"]` | 是 | 安装脚本/setup 参数支持 | `OPENVIKING_RECALL_TARGET_TYPES`(安装脚本写入 setup 参数) | 当前默认只查 `user` + `agent` 记忆。设置为 `["resource"]` 才会切成 resource-only;可组合 `resource,user,agent`:`config.ts:174`、`config.ts:360` |+| `recallTargetTypes` | 自动召回 + 默认 `memory_recall` 资源类型集合 | `["user","agent"]` | 是 | 安装脚本/setup 参数支持 | `OPENVIKING_RECALL_TARGET_TYPES`(安装脚本写入 setup 参数) | `user` / `agent` 为兼容配置项,当前会合并为一次 `context_type=memory` 检索;配置了 actor peer 时由服务端限制 peer 视图。设置为 `["resource"]` 才会切成 resource-only;可组合 `resource,user,agent`:`config.ts:174`、`config.ts:360` || `recallResources` | 自动召回 + 默认 `memory_recall` resources 兼容开关 | `false` | 是 | 是 | `OPENVIKING_RECALL_RESOURCES` | 旧兼容字段;只有未显式配置 `recallTargetTypes` 时才把 `resource` 追加到默认 `user` + `agent`,不会覆盖显式 resource-only:`config.ts:360` || `recallLimit` | 自动召回 / `memory_recall` 返回条数 | `6` | 是 | 否 | — | 最终注入或展示的 recall 条数上限;内部请求会放大到 `max(limit*4, 20)` 先召回再重排:`config.ts:285`、`auto-recall.ts:181` || `recallScoreThreshold` | 自动召回 / `memory_recall` 过滤阈值 | `0.15` | 是 | 否 | — | 低于阈值的结果会在后处理阶段被丢弃:`config.ts:286`、`auto-recall.ts:218`、`index.ts:1132` |@@ -787,7 +786,7 @@ openclaw config get plugins.slots.contextEngine#### 9.3.1 Resource-only 召回配置-当前默认召回目标是用户记忆 + Agent 记忆:`["user","agent"]`。如果你的场景主要是“导入文档 / 知识库问答”,并希望默认召回只查 `viking://resources`,需要显式配置 `recallTargetTypes`:+当前默认召回目标是 memory 类型视图:`["user","agent"]` 作为兼容配置会合并为一次 `context_type=memory` 检索;配置了 actor peer 时由 `X-OpenViking-Actor-Peer` 限制当前 peer 视图。如果你的场景主要是“导入文档 / 知识库问答”,并希望默认召回只查 resources,需要显式配置 `recallTargetTypes`:```bashopenclaw config set plugins.entries.openviking.config.recallTargetTypes '["resource"]'@@ -796,7 +795,7 @@ openclaw gateway restart安装后也可以通过 `openclaw config set` 显式写入;本示例不包含 TOS 安装脚本参数。-注意:`recallResources=true` 是旧兼容加法开关,只会在未显式配置 `recallTargetTypes` 时把 `resource` 追加到默认 `user` + `agent`,不会把默认召回改成 resource-only。+注意:`recallResources=true` 是旧兼容加法开关,只会在未显式配置 `recallTargetTypes` 时把 `resource` 追加到默认 memory 视图,默认不会改成 resource-only。#### 9.3.2 仅通过环境变量快速打开“额外可搜 resources 的自动召回”@@ -856,7 +855,7 @@ export OPENVIKING_RECALL_RESOURCES=1| --- | --- | --- || `memory_recall` 能搜到 memory,但自动回复前没有注入 | `autoRecall`、`recallScoreThreshold`、`recallMaxInjectedChars` | recall 命中了,但因阈值或预算被过滤掉 || `memory_recall` 默认搜不到 resources | `recallResources` | 默认是 `false`,不会自动查 `viking://resources` |-| 同样的 query 在不同 agent / user 命中不一致 | `accountId`、`userId`、`peer_role`、`peer_prefix` | 租户或 `peer_id` 路由不一致 |+| 同样的 query 在不同 agent / user 命中不一致 | `accountId`、`userId`、`peer_role`、`peer_prefix` | 租户或 actor peer 视图不一致 || `/ov-search` 查不到刚导入的内容 | `baseUrl`、`apiKey`、服务端队列状态 | 导入后语义/向量处理还没完成,或连到了错误服务 || 明明命中结果很多,但注入数量少 | `recallLimit`、`recallMaxInjectedChars`、`recallPreferAbstract` | limit 太小或预算太紧,必要时改成 abstract 优先 || 不知道插件到底向哪个 target_uri 发了检索 | `logFindRequests` | 开启后查看插件日志中的 `find POST` |@@ -890,7 +889,7 @@ openclaw gateway restartOPENVIKING_LOG_ROUTING=1 openclaw gateway restart```-日志会打印 account/user header 是否设置、target_uri、`peer_id`、query preview、session commit 等信息,但不会打印 apiKey。+日志会打印 account/user header 是否设置、actor peer header、target_uri、query preview、session commit 等信息,但不会打印 apiKey。### 10.3 打开标准诊断日志@@ -1003,7 +1002,7 @@ openviking: inject-detail {"count":2,"memories":[{"uri":"viking://user/default/m如果想把“命中的路径”直接展示给 Agent 或用户,可以让 Agent 显式调用工具:```text-# 查长期记忆,默认查 user/agent memories;recallTargetTypes 可切换默认范围+# 查长期记忆,默认查 memory 类型视图;recallTargetTypes 可切换默认范围memory_recall(query="用户问题关键词", limit=10)# 查导入的文档、URL、目录、仓库资源@@ -1110,7 +1109,7 @@ curl -sS "$OPENVIKING_BASE_URL/api/v1/content/read?uri=$(python3 -c 'import urll- 如果文档是通过 **auto recall** 进入模型上下文:看 `inject-detail` 中 `category=resource` 或 `uri` 以 `viking://resources` 开头的条目。- 如果文档是通过 **显式工具** 进入模型上下文:看 `ov_search` 工具结果里的 `uri` 和工具 `details.resources[]`。- 如果只看到了 `find POST` 但没有 `injecting` / `inject-detail`:说明插件发起了检索,但最终可能因为分数阈值、去重、leaf 过滤或 `recallMaxInjectedChars` 预算没有注入模型。-- 如果未显式配置 `recallTargetTypes`,自动召回默认只查 `viking://user/memories` 和 `viking://agent/memories`,不会把 `viking://resources` 文档自动注入;resource-only 用 `recallTargetTypes=["resource"]`,默认记忆 + resources 用 `recallResources=true` 或 `recallTargetTypes=["user","agent","resource"]`。+- 如果未显式配置 `recallTargetTypes`,自动召回默认使用 `context_type=memory` 查当前 user 的 memory 视图,不会把 `viking://resources` 文档自动注入;resource-only 用 `recallTargetTypes=["resource"]`,默认 memory 视图 + resources 用 `recallResources=true` 或 `recallTargetTypes=["user","agent","resource"]`。- 如果没查到 recall trace,先检查 `traceRecall=true` 是否已配置并重启 Gateway;`recallTargetTypes` / `recallResources` 不负责启用 trace。- 当前插件没有单独生成“模型最终引用/采纳哪些文档”的 citation 文件;最可靠的依据是本轮注入内容、工具调用结果、OpenViking API 返回和模型回复本身。@@ -1122,7 +1121,7 @@ curl -sS "$OPENVIKING_BASE_URL/api/v1/content/read?uri=$(python3 -c 'import urll| `setup` 成功但 gateway 中没调用插件 | `openclaw gateway restart` | Gateway 未重启,仍用旧插件状态 || `status` 服务不可达 | `baseUrl`、`curl /health` | OpenViking 未启动、端口/网络错误 || Root key 报 tenant 错误 | `accountId/userId` | Root key 需要显式租户上下文 |-| 不同说话人记忆串用 | `logFindRequests` 中的 `peer_id` | `peer_role` / `peer_prefix` 或 sender 解析不符合预期 |+| 不同说话人记忆串用 | `logFindRequests` 中的 actor peer header 和 session `peer_id` | `peer_role` / `peer_prefix` 或 sender 解析不符合预期 || 搜不到刚保存的记忆 | 服务端 task 状态和日志 | afterTurn commit 是异步 Phase 2,记忆抽取可能还未完成或服务端失败 || summary 有但细节没有 | `ov_archive_search` / `ov_archive_expand` | Working Memory 是有损摘要,需要 archive 回查 || auto recall 没注入 | `autoRecall`、precheck、阈值、预算 | OpenViking 不可达、query 太短、阈值太高、记忆超预算 |diff --git a/examples/openclaw-plugin/docs/openviking-plugin-reference.md b/examples/openclaw-plugin/docs/openviking-plugin-reference.mdindex b80d8cf53..c5abdba2b 100644--- a/examples/openclaw-plugin/docs/openviking-plugin-reference.md+++ b/examples/openclaw-plugin/docs/openviking-plugin-reference.md@@ -75,7 +75,7 @@ $OPENCLAW_STATE_DIR/openclaw.json| 参数 | 类型 | 默认值 | 环境变量 | 说明 || --- | --- | --- | --- | --- |-| `peer_role` | `"none"` \| `"assistant"` \| `"person"` | `"none"` | — | 控制 session message 和 recall/search 请求是否写入 `peer_id`。 |+| `peer_role` | `"none"` \| `"assistant"` \| `"person"` | `"none"` | — | 控制哪些 session message 写入 `peer_id`,并为数据面 recall/search/read/import/delete 提供 actor peer 视图。 || `peer_prefix` | string | 空 | — | `peer_role=assistant` 时 assistant `peer_id` 的可选前缀;仅允许字母、数字、`_`、`-`。 |### 3.3 自动捕获与提交@@ -94,7 +94,7 @@ $OPENCLAW_STATE_DIR/openclaw.json| --- | --- | --- | --- | --- || `autoRecall` | boolean | `true` | — | 是否在 assemble 阶段自动召回并注入上下文。 || `targetUri` | string | `viking://user/memories` | — | `memory_recall` / `memory_forget` 默认搜索范围。 |-| `recallTargetTypes` | string[] | `["user", "agent"]` | — | 自动召回和默认 `memory_recall` 的搜索类型。允许 `resource`、`user`、`agent`。 |+| `recallTargetTypes` | string[] | `["user", "agent"]` | — | 自动召回和默认 `memory_recall` 的搜索类型。允许 `resource`、`user`、`agent`;`user` / `agent` 为兼容项,当前合并为一次 `context_type=memory` 检索。 || `recallResources` | boolean | `false` | `OPENVIKING_RECALL_RESOURCES` | 旧兼容开关;仅在未显式配置 `recallTargetTypes` 时追加 `resource`。 || `recallLimit` | number | `6` | — | 最终召回条数下限为 `1`。内部请求通常放大为 `max(limit * 4, 20)`。 || `recallScoreThreshold` | number | `0.15` | — | 召回结果分数阈值,范围 `0` 到 `1`。 |@@ -502,7 +502,7 @@ curl 'http://127.0.0.1:<gateway-port>/api/openviking/recall-traces/ov_search-178| `X-OpenViking-Account` | `accountId` | 租户 account。 || `X-OpenViking-User` | `userId` | 租户 user。 |-`peer_role=assistant/person` 时,插件通过请求 body 的 `peer_id` 字段隔离 session 写入和 recall/search;当前实现不发送 `X-OpenViking-Agent` header。+`peer_role=assistant/person` 时,插件通过请求 body 的 `peer_id` 字段做 session message 归因;recall/search/read/import/delete 等数据面请求通过 `X-OpenViking-Actor-Peer` 进入当前 actor peer 视图。当前实现不发送 `X-OpenViking-Agent` header。后端 API 封装清单:diff --git a/examples/openclaw-plugin/docs/openviking-recall-trace-api.md b/examples/openclaw-plugin/docs/openviking-recall-trace-api.mdindex 782f0da20..8f0cf22af 100644--- a/examples/openclaw-plugin/docs/openviking-recall-trace-api.md+++ b/examples/openclaw-plugin/docs/openviking-recall-trace-api.md@@ -91,9 +91,9 @@ Trace 会记录实际召回范围,但召回范围本身由 `recallTargetTypes`| resourceType | target URI | 说明 || --- | --- | --- |-| `resource` | `viking://resources` | 全局资源库。 |-| `user` | `viking://user/memories` | 当前用户长期记忆。 |-| `agent` | `viking://agent/memories` | 当前 Agent 长期记忆。 |+| `resource` | `context_type=resource` | resource 知识库;target URI 可为空,由服务端解析当前可检索 resource 范围。 |+| `user` | `context_type=memory` | 兼容目标类型;与 `agent` 合并为一次 memory 类型检索。 |+| `agent` | `context_type=memory` + `X-OpenViking-Actor-Peer` | 兼容目标类型;不再依赖废弃的 `viking://agent/...` 目录。 |Session history is not a semantic recall target because the server does not vector-index session archives. Use `ov_archive_search` and `ov_archive_expand` for exact session-history recovery.@@ -541,7 +541,7 @@ curl 'http://127.0.0.1:<gateway-port>/api/openviking/recall-traces/ov_search-178/ov-recall-trace --turn all --source memory_recall --limit 5```-重点查看 `resourceTypes` 和 `searches[].targetUriResolved`,确认是否默认查了 `viking://user/memories` 与 `viking://agent/memories`,或是否按请求 `resourceTypes` 改变范围。+重点查看 `resourceTypes`、`searches[].contextType` 和 `searches[].targetUriResolved`,确认是否使用 `context_type=memory` / `context_type=resource`,或是否按请求 `resourceTypes` 改变范围。### 9.3 排查 `/ov-search` 或 `ov_search` 为什么结果不符合预期diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.tsindex a45028a53..932cef492 100644--- a/examples/openclaw-plugin/index.ts+++ b/examples/openclaw-plugin/index.ts@@ -445,9 +445,6 @@ function inferRecallResourceType(uri: string | undefined): RecallResourceType |if (uri.startsWith("viking://session/") || uri.includes("/sessions/")) {return "session";}- if (uri.startsWith("viking://agent/")) {- return "agent";- }if (uri.startsWith("viking://user/")) {return "user";}@@ -857,7 +854,7 @@ const contextEnginePlugin = {const enrichTraceEntriesWithContent = async (result: { entries: RecallTraceEntry[]; lookupLayer: "memory" | "persistent"; warnings: string[] },includeContent: boolean,- agentId?: string,+ actorPeerId?: string,): Promise<{ entries: RecallTraceEntry[]; lookupLayer: "memory" | "persistent"; warnings: string[] }> => {if (!includeContent || result.entries.length === 0) {return result;@@ -867,7 +864,7 @@ const contextEnginePlugin = {const entries = await Promise.all(result.entries.map(async (entry) => {const selected = await Promise.all(entry.selected.map(async (item) => {try {- const content = await client.read(item.uri, agentId);+ const content = await client.read(item.uri, actorPeerId);return {...item,contentPreview: previewText(content, cfg.recallMaxContentChars),@@ -886,11 +883,12 @@ const contextEnginePlugin = {const queryRecallTraces = async (input: RecallTraceToolInput,session: PluginSessionRouting,+ actorPeerId?: string,): Promise<{ entries: RecallTraceEntry[]; lookupLayer: "memory" | "persistent"; warnings: string[] }> => {const base = traceRecorder? await traceRecorder.queryWithFallback(parseRecallTraceInput(input, session)): { entries: [], lookupLayer: "memory" as const, warnings: ["traceRecall is disabled"] };- return enrichTraceEntriesWithContent(base, shouldIncludeTraceContent(input), session.agentId);+ return enrichTraceEntriesWithContent(base, shouldIncludeTraceContent(input), actorPeerId);};const registerRecallTraceRoutes = (ctx?: unknown): boolean => {@@ -944,7 +942,7 @@ const contextEnginePlugin = {until: toNumber(query.until),includeContent: toBoolean(query.includeContent),limit: toNumber(query.limit),- }, session);+ }, session, resolveToolSearchPeerId(query, session));return { status: 200, body: { ok: true, ...result } };};routeAdapter.registerRoute({ method: "GET", path: "/api/openviking/recall-traces", handler: handle });@@ -975,6 +973,7 @@ const contextEnginePlugin = {`traceId: ${entry.traceId}`,`query: ${entry.trigger.query}`,`resourceTypes: ${entry.resourceTypes.join(", ")}`,+ `searches: ${entry.searches.map((search) => search.contextType ?? search.resourceType).join(", ")}`,`stats: candidates=${entry.stats.candidateCount}, selected=${entry.stats.selectedCount}, injected=${entry.stats.injectedCount}`,selected ? `selected:\n${selected}` : "selected: (none)",].join("\n");@@ -997,9 +996,9 @@ const contextEnginePlugin = {return `Imported OpenViking skill${name}.${uri}`.trim();};- const importResource = async (input: AddResourceInput, agentId?: string) => {+ const importResource = async (input: AddResourceInput, actorPeerId?: string) => {const client = await getClient();- const result = await client.addResource(input, agentId);+ const result = await client.addResource(input, actorPeerId);return {content: [{ type: "text" as const, text: formatResourceImportText(result) }],details: {@@ -1009,9 +1008,9 @@ const contextEnginePlugin = {};};- const importSkill = async (input: AddSkillInput, agentId?: string) => {+ const importSkill = async (input: AddSkillInput, actorPeerId?: string) => {const client = await getClient();- const result = await client.addSkill(input, agentId);+ const result = await client.addSkill(input, actorPeerId);return {content: [{ type: "text" as const, text: formatSkillImportText(result) }],details: {@@ -1021,7 +1020,7 @@ const contextEnginePlugin = {};};- const addResourceOpenViking = (input: AddResourceToolInput, agentId?: string) =>+ const addResourceOpenViking = (input: AddResourceToolInput, actorPeerId?: string) =>importResource({pathOrUrl: input.source ?? "",to: input.to,@@ -1030,15 +1029,15 @@ const contextEnginePlugin = {instruction: input.instruction,wait: input.wait,timeout: input.timeout,- }, agentId);+ }, actorPeerId);- const addSkillOpenViking = (input: AddSkillToolInput, agentId?: string) =>+ const addSkillOpenViking = (input: AddSkillToolInput, actorPeerId?: string) =>importSkill({path: input.source,data: input.data,wait: input.wait,timeout: input.timeout,- }, agentId);+ }, actorPeerId);const mergeFindResults = (results: FindResult[]): FindResult => {const deduplicate = (items: FindResultItem[]): FindResultItem[] => {@@ -1164,9 +1163,8 @@ const contextEnginePlugin = {const searchOpenViking = async (input: OVSearchInput,- agentId?: string,- peerId?: string,traceCtx?: PluginSessionRouting,+ actorPeerId?: string,) => {const query = input.query.trim();if (!query) {@@ -1178,7 +1176,7 @@ const contextEnginePlugin = {const searches: RecallTraceEntry["searches"] = [];if (input.uri) {const started = Date.now();- result = await client.find(query, { targetUri: input.uri, limit, peerId }, agentId);+ result = await client.find(query, { targetUri: input.uri, limit, actorPeerId });const items = [...(result.memories ?? []).map((item) => toTraceResult(item, "memory")),...(result.resources ?? []).map((item) => toTraceResult(item, "resource")),@@ -1194,17 +1192,22 @@ const contextEnginePlugin = {results: items,});} else {- const runSearch = async (targetUri: string): Promise<FindResult> => {+ const runSearch = async (+ targetUri: string | undefined,+ contextType: "resource" | "skill",+ ): Promise<FindResult> => {+ const resourceType: RecallResourceType = contextType === "skill" ? "user" : "resource";const started = Date.now();try {- const found = await client.find(query, { targetUri, limit, peerId }, agentId);+ const found = await client.find(query, { targetUri, limit, contextType, actorPeerId });const items = [...(found.memories ?? []).map((item) => toTraceResult(item, "memory")),...(found.resources ?? []).map((item) => toTraceResult(item, "resource")),...(found.skills ?? []).map((item) => toTraceResult(item, "skill")),].slice(0, cfg.traceRecallMaxResultsPerSearch);searches.push({- resourceType: inferRecallResourceType(targetUri) ?? "resource",+ resourceType,+ contextType,targetUriResolved: targetUri,limit,durationMs: Date.now() - started,@@ -1214,7 +1217,8 @@ const contextEnginePlugin = {return found;} catch (err) {searches.push({- resourceType: inferRecallResourceType(targetUri) ?? "resource",+ resourceType,+ contextType,targetUriResolved: targetUri,limit,durationMs: Date.now() - started,@@ -1226,8 +1230,8 @@ const contextEnginePlugin = {}};const [resourcesSettled, skillsSettled] = await Promise.allSettled([- runSearch("viking://resources"),- runSearch("viking://user/skills"),+ runSearch(undefined, "resource"),+ runSearch(undefined, "skill"),]);const successful: FindResult[] = [];if (resourcesSettled.status === "fulfilled") {@@ -1286,7 +1290,7 @@ const contextEnginePlugin = {sessionId: traceCtx?.sessionId,sessionKey: traceCtx?.sessionKey,ovSessionId: traceCtx?.ovSessionId,- agentId,+ agentId: traceCtx?.agentId,source: "ov_search",operationType: "semantic_find",resourceTypes: [...new Set(searches@@ -1307,7 +1311,7 @@ const contextEnginePlugin = {action: "searched",query,uri: input.uri,- peer_id: peerId ?? null,+ peer_id: actorPeerId ?? null,memories: result.memories ?? [],resources: result.resources ?? [],skills: result.skills ?? [],@@ -1316,13 +1320,16 @@ const contextEnginePlugin = {};};- const readOpenViking = async (input: OVReadInput, agentId?: string) => {+ const readOpenViking = async (+ input: OVReadInput,+ actorPeerId?: string,+ ) => {const uri = input.uri.trim();if (!uri) {throw new Error("uri is required");}const client = await getClient();- const content = await client.read(uri, agentId);+ const content = await client.read(uri, actorPeerId);return {content: [{ type: "text" as const, text: formatOVReadText(uri, content) }],details: {@@ -1333,7 +1340,10 @@ const contextEnginePlugin = {};};- const multiReadOpenViking = async (input: OVMultiReadInput, agentId?: string) => {+ const multiReadOpenViking = async (+ input: OVMultiReadInput,+ actorPeerId?: string,+ ) => {const uris = input.uris.map((uri) => (typeof uri === "string" ? uri.trim() : "")).filter((uri) => uri.length > 0);@@ -1344,7 +1354,7 @@ const contextEnginePlugin = {const results = await Promise.all(uris.map(async (uri) => {try {- const content = await client.read(uri, agentId);+ const content = await client.read(uri, actorPeerId);return {uri,content,@@ -1373,7 +1383,10 @@ const contextEnginePlugin = {};};- const listOpenViking = async (input: OVListInput, agentId?: string) => {+ const listOpenViking = async (+ input: OVListInput,+ actorPeerId?: string,+ ) => {const uri = input.uri.trim();if (!uri) {throw new Error("uri is required");@@ -1386,8 +1399,8 @@ const contextEnginePlugin = {recursive: input.recursive ?? false,simple: input.simple ?? false,nodeLimit: limit,+ actorPeerId,},- agentId,);return {content: [{ type: "text" as const, text: formatOVListText(uri, entries) }],@@ -1435,7 +1448,7 @@ const contextEnginePlugin = {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);+ }, resolveToolSearchPeerId(ctx, session));},}),{ name: "add_resource" },@@ -1460,12 +1473,15 @@ const contextEnginePlugin = {return makeBypassedToolResult("add_skill");}const session = resolvePluginSessionRouting(ctx);- return addSkillOpenViking({- source: typeof params.source === "string" ? params.source : undefined,- data: params.data,- wait: typeof params.wait === "boolean" ? params.wait : undefined,- timeout: typeof params.timeout === "number" ? params.timeout : undefined,- }, session.agentId);+ return addSkillOpenViking(+ {+ source: typeof params.source === "string" ? params.source : undefined,+ data: params.data,+ wait: typeof params.wait === "boolean" ? params.wait : undefined,+ timeout: typeof params.timeout === "number" ? params.timeout : undefined,+ },+ resolveToolSearchPeerId(ctx, session),+ );},}),{ name: "add_skill" },@@ -1481,7 +1497,7 @@ const contextEnginePlugin = {"When a result is part of a split document or a multi-step procedure, call ov_list on the parent URI to inspect sibling chunks and overview files before answering.",parameters: Type.Object({query: Type.String({ description: "Search query" }),- uri: Type.Optional(Type.String({ description: "Optional search URI. Defaults to resources plus user skills." })),+ uri: Type.Optional(Type.String({ description: "Optional search URI. Defaults to all resource and skill contexts." })),limit: Type.Optional(Type.Number({ description: "Max results per search scope. Default: 10" })),}),async execute(_toolCallId: string, params: Record<string, unknown>) {@@ -1494,7 +1510,7 @@ const contextEnginePlugin = {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, peerId, session);+ }, session, peerId);},}),{ name: "ov_search" },@@ -1516,9 +1532,10 @@ const contextEnginePlugin = {return makeBypassedToolResult("ov_read");}const session = resolvePluginSessionRouting(ctx);+ const actorPeerId = resolveToolSearchPeerId(ctx, session);return readOpenViking({uri: String((params as { uri?: unknown }).uri ?? ""),- }, session.agentId);+ }, actorPeerId);},}),{ name: "ov_read" },@@ -1541,10 +1558,11 @@ const contextEnginePlugin = {return makeBypassedToolResult("ov_multi_read");}const session = resolvePluginSessionRouting(ctx);+ const actorPeerId = resolveToolSearchPeerId(ctx, session);const uris = Array.isArray((params as { uris?: unknown }).uris)? (params as { uris: unknown[] }).uris.map((uri) => String(uri)): [];- return multiReadOpenViking({ uris }, session.agentId);+ return multiReadOpenViking({ uris }, actorPeerId);},}),{ name: "ov_multi_read" },@@ -1567,12 +1585,13 @@ const contextEnginePlugin = {return makeBypassedToolResult("ov_list");}const session = resolvePluginSessionRouting(ctx);+ const actorPeerId = resolveToolSearchPeerId(ctx, session);return listOpenViking({uri: String((params as { uri?: unknown }).uri ?? ""),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);+ }, actorPeerId);},}),{ name: "ov_list" },@@ -1590,7 +1609,7 @@ const contextEnginePlugin = {}const session = resolvePluginSessionRouting(ctx);const input = parseAddResourceCommandArgs(ctx.args ?? "");- const result = await addResourceOpenViking(input, session.agentId);+ const result = await addResourceOpenViking(input, resolveToolSearchPeerId(ctx, session));return { text: result.content[0]!.text, details: result.details };} catch (err) {return { text: `OpenViking add resource failed: ${err instanceof Error ? err.message : String(err)}` };@@ -1610,7 +1629,7 @@ const contextEnginePlugin = {}const session = resolvePluginSessionRouting(ctx);const input = parseAddSkillCommandArgs(ctx.args ?? "");- const result = await addSkillOpenViking(input, session.agentId);+ const result = await addSkillOpenViking(input, resolveToolSearchPeerId(ctx, session));return { text: result.content[0]!.text, details: result.details };} catch (err) {return { text: `OpenViking add skill failed: ${err instanceof Error ? err.message : String(err)}` };@@ -1631,7 +1650,7 @@ const contextEnginePlugin = {const session = resolvePluginSessionRouting(ctx);const input = parseOVSearchCommandArgs(ctx.args ?? "");const peerId = resolveToolSearchPeerId(ctx, session);- const result = await searchOpenViking(input, session.agentId, peerId, session);+ const result = await searchOpenViking(input, session, peerId);return { text: result.content[0]!.text, details: result.details };} catch (err) {return { text: `OpenViking search failed: ${err instanceof Error ? err.message : String(err)}` };@@ -1687,14 +1706,15 @@ const contextEnginePlugin = {const recallClient = await getClient();if (cfg.logFindRequests) {api.logger.info(- `openviking: memory_recall runtime_agent_id="${session.agentId}" ` ++ `openviking: memory_recall assistant_peer_id="${session.agentId}" ` +`peer_id="${peerId ?? ""}" ` +- `(plugin defaultAgentId="${recallClient.getDefaultAgentId()}" is unused when session context is present)`,+ `(plugin defaultAgentId="${recallClient.getDefaultAgentId()}" is not sent as an OpenViking agent identity)`,);}let result: FindResult;let memoryRecallSearches: RecallTraceEntry["searches"] = [];+ let requestedTraceResourceTypes: RecallResourceType[] | undefined;if (targetUri) {// 如果指定了目标 URI,只检索该位置const started = Date.now();@@ -1704,9 +1724,8 @@ const contextEnginePlugin = {targetUri,limit: requestLimit,scoreThreshold: 0,- peerId,+ actorPeerId: peerId,},- session.agentId,);const traceResults = [...(result.memories ?? []).map((item) => toTraceResult(item, "memory")),@@ -1728,6 +1747,7 @@ const contextEnginePlugin = {ovSessionId: session.ovSessionId,agentId: session.agentId,});+ requestedTraceResourceTypes = searchPlan.resourceTypes;memoryRecallSearches.push(...searchPlan.skipped.map((skipped) => ({resourceType: skipped.resourceType,limit: requestLimit,@@ -1744,9 +1764,9 @@ const contextEnginePlugin = {targetUri: search.targetUri,limit: requestLimit,scoreThreshold: 0,- peerId,+ contextType: search.contextType,+ actorPeerId: peerId,},- session.agentId,),);const settled = await Promise.allSettled(searchPromises);@@ -1763,6 +1783,7 @@ const contextEnginePlugin = {].slice(0, cfg.traceRecallMaxResultsPerSearch);memoryRecallSearches.push({resourceType: search.resourceType,+ contextType: search.contextType,targetUriInput: search.targetUri,targetUriResolved: search.targetUri,limit: requestLimit,@@ -1774,6 +1795,7 @@ const contextEnginePlugin = {} else {memoryRecallSearches.push({resourceType: search.resourceType,+ contextType: search.contextType,targetUriInput: search.targetUri,targetUriResolved: search.targetUri,limit: requestLimit,@@ -1805,7 +1827,7 @@ const contextEnginePlugin = {.map((item) => toTraceResult(item, inferRecallResourceType(item.uri) === "resource" ? "resource" : "memory")).slice(0, cfg.traceRecallMaxResultsPerSearch);const traceResourceTypes = [...new Set(- (targetUri ? [inferRecallResourceType(targetUri)] : memoryRecallSearches.map((search) => search.resourceType))+ (requestedTraceResourceTypes ?? (targetUri ? [inferRecallResourceType(targetUri)] : memoryRecallSearches.map((search) => search.resourceType))).filter((resourceType): resourceType is RecallResourceType => Boolean(resourceType) && resourceType !== "archive"),)];const recordMemoryRecallTrace = async (injectedUris: Set<string>) => {@@ -1823,8 +1845,9 @@ const contextEnginePlugin = {trigger: boundTraceQuery(query, cfg.traceRecallQueryMaxChars),searches: memoryRecallSearches.length > 0 ? memoryRecallSearches : [{resourceType: inferRecallResourceType(targetUri) ?? "user",+ contextType: targetUri ? undefined : "memory",targetUriInput: targetUri,- targetUriResolved: targetUri ?? "viking://user/memories",+ targetUriResolved: targetUri,limit: requestLimit,scoreThreshold,durationMs: 0,@@ -1856,7 +1879,7 @@ const contextEnginePlugin = {}const { lines: memoryLines } = await buildMemoryLinesWithBudget(memories,- (uri) => recallClient.read(uri, session.agentId),+ (uri) => recallClient.read(uri, peerId),{recallPreferAbstract: false,recallMaxInjectedChars: cfg.recallMaxInjectedChars,@@ -1926,7 +1949,11 @@ const contextEnginePlugin = {return makeBypassedToolResult("ov_recall_trace");}const session = resolvePluginSessionRouting(ctx);- const result = await queryRecallTraces(params as RecallTraceToolInput, session);+ const result = await queryRecallTraces(+ params as RecallTraceToolInput,+ session,+ resolveToolSearchPeerId(ctx, session),+ );return {content: [{ type: "text" as const, text: formatRecallTraceText(result) }],details: {@@ -1967,7 +1994,7 @@ const contextEnginePlugin = {includeContent: getBoolFlag(flags, "include-content"),limit: getNumberFlag(flags, "limit"),};- const result = await queryRecallTraces(input, session);+ const result = await queryRecallTraces(input, session, resolveToolSearchPeerId(ctx, session));return {text: formatRecallTraceText(result),details: {@@ -2034,20 +2061,17 @@ const contextEnginePlugin = {await c.ensureSession(sessionId,{ memoryPolicy: defaultMemoryPolicy },- session.agentId,);}await c.addSessionMessage(sessionId,role,[{ type: "text" as const, text }],- session.agentId,undefined,peerId,);const commitResult = await c.commitSession(sessionId, {wait: true,- agentId: session.agentId,keepRecentCount: 0,});const memoriesCount = totalCommitMemories(commitResult);@@ -2165,7 +2189,7 @@ const contextEnginePlugin = {details: { action: "rejected", uri },};}- await client.deleteUri(uri, session.agentId);+ await client.deleteUri(uri, peerId);return {content: [{ type: "text", text: `Forgotten: ${uri}` }],details: { action: "deleted", uri },@@ -2200,9 +2224,8 @@ const contextEnginePlugin = {targetUri,limit: requestLimit,scoreThreshold: 0,- peerId,+ actorPeerId: peerId,},- session.agentId,);const candidates = postProcessMemories(result.memories ?? [], {limit: requestLimit,@@ -2222,7 +2245,7 @@ const contextEnginePlugin = {}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, peerId);return {content: [{ type: "text", text: `Forgotten: ${top.uri}` }],details: { action: "deleted", uri: top.uri, score: top.score ?? 0 },@@ -2298,12 +2321,10 @@ const contextEnginePlugin = {try {const client = await getClient();- const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);const started = Date.now();const result = await client.grepSessionArchives(ovSessionId, escapedQuery, {archiveId,caseInsensitive: true,- agentId,});const traceResults: RecallTraceResult[] = (result.matches ?? []).slice(0, cfg.traceRecallMaxResultsPerSearch)@@ -2321,7 +2342,7 @@ const contextEnginePlugin = {sessionId: ctx.sessionId,sessionKey: ctx.sessionKey,ovSessionId,- agentId,+ agentId: ctx.agentId,source: "ov_archive_search",operationType: "archive_grep",resourceTypes: ["session"],@@ -2444,7 +2465,6 @@ const contextEnginePlugin = {const detail = await client.getSessionArchive(session.ovSessionId,archiveId,- session.agentId,);const header = [@@ -2544,7 +2564,6 @@ const contextEnginePlugin = {session.ovSessionId,parsed.toolResultId,{ offset, limit, includeMetadata: true },- session.agentId,);const returnedChars = result.content.length;const nextOffset = result.offset + returnedChars;@@ -2645,7 +2664,6 @@ const contextEnginePlugin = {parsed.toolResultId,query,{ limit, contextChars },- session.agentId,);const matches = result.matches ?? [];const text = matches.length@@ -2718,7 +2736,6 @@ const contextEnginePlugin = {const result = await client.listToolResults(session.ovSessionId,{ toolName, limit },- session.agentId,);const items = result.tool_results ?? [];const text = items.lengthdiff --git a/examples/openclaw-plugin/process-manager.ts b/examples/openclaw-plugin/process-manager.tsindex 0dcb12431..3ccecd8ab 100644--- a/examples/openclaw-plugin/process-manager.ts+++ b/examples/openclaw-plugin/process-manager.ts@@ -18,11 +18,10 @@ export function withTimeout<T>(promise: Promise<T>, timeoutMs: number, timeoutMeexport async function quickHealthCheck(client: OpenVikingClient,- agentId: string | undefined,timeoutMs: number,): Promise<boolean> {try {- await client.healthCheck(agentId, timeoutMs);+ await client.healthCheck(timeoutMs);return true;} catch {return false;@@ -31,9 +30,8 @@ export async function quickHealthCheck(export async function quickRecallPrecheck(client: OpenVikingClient,- agentId?: string,): Promise<{ ok: true } | { ok: false; reason: string }> {- const healthOk = await quickHealthCheck(client, agentId, 500);+ const healthOk = await quickHealthCheck(client, 500);if (healthOk) {return { ok: true };}diff --git a/examples/openclaw-plugin/recall-trace.ts b/examples/openclaw-plugin/recall-trace.tsindex 6d5cd9e8d..6b5f22afe 100644--- a/examples/openclaw-plugin/recall-trace.ts+++ b/examples/openclaw-plugin/recall-trace.ts@@ -36,6 +36,7 @@ export type RecallTraceEntry = {};searches: Array<{resourceType: RecallResourceType | "archive";+ contextType?: "memory" | "resource" | "skill";targetUriInput?: string;targetUriResolved?: string;limit: number;@@ -143,20 +144,20 @@ export function resolveRecallSearchPlan(_ctx: { ovSessionId?: string; agentId?: string },): {resourceTypes: RecallResourceType[];- searches: Array<{ resourceType: RecallResourceType; targetUri: string }>;+ searches: Array<{ resourceType: RecallResourceType; targetUri?: string; contextType: "memory" | "resource" }>;skipped: Array<{ resourceType: RecallResourceType; reason: "missing_session" }>;} {const normalized = normalizeResourceTypes(resourceTypes);- const searches: Array<{ resourceType: RecallResourceType; targetUri: string }> = [];+ const searches: Array<{ resourceType: RecallResourceType; targetUri?: string; contextType: "memory" | "resource" }> = [];const skipped: Array<{ resourceType: RecallResourceType; reason: "missing_session" }> = [];+ let addedMemorySearch = false;for (const resourceType of normalized) {if (resourceType === "resource") {- searches.push({ resourceType, targetUri: "viking://resources" });- } else if (resourceType === "user") {- searches.push({ resourceType, targetUri: "viking://user/memories" });- } else if (resourceType === "agent") {- searches.push({ resourceType, targetUri: "viking://agent/memories" });+ searches.push({ resourceType, contextType: "resource" });+ } else if ((resourceType === "user" || resourceType === "agent") && !addedMemorySearch) {+ searches.push({ resourceType: "user", contextType: "memory" });+ addedMemorySearch = true;}}diff --git a/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md b/examples/openclaw-plugin/skills/openviking-context-database/SKILL.mdindex 540cbf63d..690af4b17 100644--- a/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md+++ b/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md@@ -71,7 +71,7 @@ Core config lives under `plugins.entries.openviking.config`:| `captureMode` | `semantic` | `semantic` or `keyword`; affects server-side extraction filtering. || `captureMaxLength` | `24000` | Max sanitized text length per captured turn. || `autoRecall` | `true` | Run recall before replies and inject relevant context. |-| `recallTargetTypes` | `user,agent` | Default target types when `targetUri` is omitted. Allowed: `resource`, `user`, `agent`. Use archive tools for session history. |+| `recallTargetTypes` | `user,agent` | Default target types when `targetUri` is omitted. Allowed: `resource`, `user`, `agent`; `user` and `agent` are compatibility values that merge into a `context_type=memory` search under the current actor peer view. Use archive tools for session history. || `recallResources` | `false` | Compatibility shortcut that appends `resource` to default recall targets when `recallTargetTypes` is unset. || `recallLimit` | `6` | Max selected recall items. || `recallScoreThreshold` | `0.15` | Min score after post-processing. |@@ -132,7 +132,7 @@ Semantic search over memories/resources. Session history is not a semantic recal| `targetUri` | No | Exact search URI. If set, only this URI is searched. || `resourceTypes` | No | Array of `resource`, `user`, `agent`; used only when `targetUri` is omitted. |-Notes: when `targetUri` is omitted, the plugin resolves a search plan from `resourceTypes` or configured `recallTargetTypes`, fetches more candidates than requested, deduplicates, filters leaf memories, reranks, and respects `recallMaxInjectedChars`.+Notes: when `targetUri` is omitted, the plugin resolves a search plan from `resourceTypes` or configured `recallTargetTypes`, uses `context_type` filters for memory/resource searches, fetches more candidates than requested, deduplicates, filters leaf memories, reranks, and respects `recallMaxInjectedChars`.### `memory_store`@@ -150,7 +150,7 @@ Delete a memory.| Parameter | Required | Description ||---|---|---|-| `uri` | No | Exact `viking://user/.../memories/...` or `viking://agent/.../memories/...` memory URI. Non-memory URIs are refused. |+| `uri` | No | Exact `viking://user/.../memories/...` memory URI. Non-memory URIs are refused. || `query` | No | Search query when `uri` is unknown. || `targetUri` | No | Search scope URI, default `targetUri`. || `limit` | No | Search limit, default `5`. |diff --git a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/context-engine-assemble.test.tsindex 874d4ccf1..385242824 100644--- a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts+++ b/examples/openclaw-plugin/tests/context-engine-assemble.test.ts@@ -115,8 +115,8 @@ 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(resolveAgentId).not.toHaveBeenCalled();+ 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/build-memory-lines.test.ts b/examples/openclaw-plugin/tests/ut/build-memory-lines.test.tsindex 1c76a5522..5b2677046 100644--- a/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts+++ b/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts@@ -317,9 +317,10 @@ describe("buildLongTermMemoryRecallContext trace", () => {expect(recorded.searches).toHaveLength(1);expect(recorded.searches[0]).toMatchObject({resourceType: "user",- targetUriInput: "viking://user/memories",total: 1,});+ expect(recorded.searches[0]!.targetUriInput).toBeUndefined();+ expect(recorded.searches[0]!.targetUriResolved).toBeUndefined();expect(recorded.searches[0]!.results[0]).toMatchObject({uri: "viking://user/memories/rust-pref",resourceType: "user",@@ -366,14 +367,16 @@ describe("buildLongTermMemoryRecallContext trace", () => {expect(recorded.searches).toHaveLength(2);expect(recorded.searches[0]).toMatchObject({resourceType: "user",- targetUriInput: "viking://user/memories",error: "Error: user search failed",});+ expect(recorded.searches[0]!.targetUriInput).toBeUndefined();+ expect(recorded.searches[0]!.targetUriResolved).toBeUndefined();expect(recorded.searches[1]).toMatchObject({resourceType: "resource",- targetUriInput: "viking://resources",total: 1,});+ expect(recorded.searches[1]!.targetUriInput).toBeUndefined();+ expect(recorded.searches[1]!.targetUriResolved).toBeUndefined();expect(recorded.selected[0]).toMatchObject({ injected: true });expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("auto-recall search failed"));});diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.tsindex 5445a114e..ce4229383 100644--- a/examples/openclaw-plugin/tests/ut/client.test.ts+++ b/examples/openclaw-plugin/tests/ut/client.test.ts@@ -472,13 +472,13 @@ describe("OpenVikingClient canonical user namespace", () => {"http://127.0.0.1:1933", "", "my-agent", 5000,"", "", undefined,);- await client.find("test query", { targetUri: "viking://user/memories" }, "my-agent");+ 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");+ expect(body.target_uri).toBe("viking://user/memories");});it("expands user memory alias to canonical user root", async () => {@@ -497,13 +497,13 @@ describe("OpenVikingClient canonical user namespace", () => {"http://127.0.0.1:1933", "", "my-agent", 5000,"", "", undefined,);- await client.find("test query", { targetUri: "viking://user/memories" }, "my-agent");+ 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");+ expect(body.target_uri).toBe("viking://user/memories");});it("expands user memory alias to canonical user root by default", async () => {@@ -524,13 +524,13 @@ describe("OpenVikingClient canonical user namespace", () => {false,true,);- await client.find("test", { targetUri: "viking://user/memories" }, "shared-agent");+ await client.find("test", { 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");+ expect(body.target_uri).toBe("viking://user/memories");});it("expands user skill alias to canonical user root", async () => {@@ -551,16 +551,16 @@ describe("OpenVikingClient canonical user namespace", () => {false,false,);- await client.find("test", { targetUri: "viking://user/skills" }, "shared-agent");+ await client.find("test", { targetUri: "viking://user/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://user/alice/skills");+ expect(body.target_uri).toBe("viking://user/skills");});- it("includes peer_id when find receives peerId", async () => {+ it("sends actor peer header when find receives peerId", async () => {const fetchMock = vi.fn(async (url: string) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "alice" });@@ -575,14 +575,16 @@ describe("OpenVikingClient canonical user namespace", () => {const client = new OpenVikingClient("http://127.0.0.1:1933", "", "shared-agent", 5000);await client.find("test", {targetUri: "viking://user/memories",- peerId: "telegram_12345",- }, "shared-agent");+ actorPeerId: "telegram_12345",+ });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.peer_id).toBe("telegram_12345");+ const headers = new Headers((findCall[1] as RequestInit).headers);+ expect(body.peer_id).toBeUndefined();+ expect(headers.get("X-OpenViking-Actor-Peer")).toBe("telegram_12345");});it("includes peer_id when addSessionMessage receives one", async () => {@@ -594,7 +596,6 @@ describe("OpenVikingClient canonical user namespace", () => {"s1","user",[{ type: "text", text: "hello" }],- "agent","2026-04-20T00:00:00.000Z","telegram_12345",);@@ -612,7 +613,6 @@ describe("OpenVikingClient canonical user namespace", () => {await client.grepSessionArchives("s1", "needle", {archiveId: "archive_001",caseInsensitive: true,- agentId: "agent",});const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];diff --git a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.tsindex 42138f354..8ec6b8acf 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts@@ -197,7 +197,7 @@ describe("context-engine afterTurn()", () => {// user + assistant + toolResult(→user) = 3 calls (toolResult merges with no adjacent user)expect(client.addSessionMessage).toHaveBeenCalled();const lastCallIdx = client.addSessionMessage.mock.calls.length - 1;- const createdAt = client.addSessionMessage.mock.calls[lastCallIdx][4] as string;+ const createdAt = client.addSessionMessage.mock.calls[lastCallIdx][3] as string;expect(createdAt).toBe("2026-04-01T10:03:00.000Z");});@@ -235,7 +235,7 @@ describe("context-engine afterTurn()", () => {});expect(client.addSessionMessage).toHaveBeenCalledTimes(1);- expect(client.addSessionMessage.mock.calls[0][5]).toBeUndefined();+ expect(client.addSessionMessage.mock.calls[0][4]).toBeUndefined();});it("passes sanitized senderId as peer_id when peer_role is person", async () => {@@ -252,7 +252,7 @@ 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][4]).toBe("telegram_12345");expect(client.ensureSession).toHaveBeenCalledWith("s1",{@@ -261,7 +261,6 @@ describe("context-engine afterTurn()", () => {peer: { enabled: true },},},- "test-agent",);});@@ -283,9 +282,9 @@ describe("context-engine afterTurn()", () => {expect(client.addSessionMessage).toHaveBeenCalledTimes(2);expect(client.addSessionMessage.mock.calls[0][1]).toBe("user");- expect(client.addSessionMessage.mock.calls[0][5]).toBeUndefined();+ expect(client.addSessionMessage.mock.calls[0][4]).toBeUndefined();expect(client.addSessionMessage.mock.calls[1][1]).toBe("assistant");- expect(client.addSessionMessage.mock.calls[1][5]).toBe("test-agent");+ expect(client.addSessionMessage.mock.calls[1][4]).toBe("test-agent");});it("sanitizes injected context blocks from user content", async () => {@@ -485,7 +484,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 agentId to addSessionMessage by default", async () => {const { engine, client } = makeEngine();await engine.afterTurn!({@@ -496,8 +495,8 @@ 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();+ expect(client.addSessionMessage.mock.calls[0][4]).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.tsindex 324810124..9d25acc64 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts@@ -139,7 +139,7 @@ describe("context-engine assemble()", () => {messages: sourceMessages,});- expect(client.healthCheck).toHaveBeenCalledWith("agent:session-transform", 500);+ expect(client.healthCheck).toHaveBeenCalledWith(500);expect(client.getSessionContext).not.toHaveBeenCalled();expect(result.messages).toHaveLength(sourceMessages.length);expect(result.messages[0]).toBe(sourceMessages[0]);@@ -238,9 +238,10 @@ describe("context-engine assemble()", () => {messages: sourceMessages,});- expect(client.find).toHaveBeenCalledTimes(2);+ expect(client.find).toHaveBeenCalledTimes(1);for (const call of client.find.mock.calls) {- expect(call[1]).toMatchObject({ peerId: "wx_user-01_abc" });+ expect(call[1]).toMatchObject({ actorPeerId: "wx_user-01_abc", contextType: "memory" });+ expect(call[1].targetUri).toBeUndefined();}} finally {vi.unstubAllGlobals();@@ -415,9 +416,10 @@ describe("context-engine assemble()", () => {messages: sourceMessages,});- expect(client.find).toHaveBeenCalledTimes(2);+ expect(client.find).toHaveBeenCalledTimes(1);for (const call of client.find.mock.calls) {- expect(call[1]).toMatchObject({ peerId: "agent:session-assistant-peer" });+ expect(call[1]).toMatchObject({ actorPeerId: "agent_session-assistant-peer", contextType: "memory" });+ expect(call[1].targetUri).toBeUndefined();}} finally {vi.unstubAllGlobals();@@ -772,15 +774,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({@@ -840,8 +836,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.tsindex b4cebe671..0d2ee6cd0 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts@@ -152,7 +152,7 @@ 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);+ expect(resolveAgentId).not.toHaveBeenCalled();});it("logs memories extracted count", async () => {@@ -436,7 +436,7 @@ describe("context-engine compact()", () => {expect(resolveAgentId).toHaveBeenCalledWith("plain-session", "agent:top:main", ovSessionId);});- it("passes agentId to commitSession", async () => {+ it("does not pass agentId to commitSession", async () => {const { engine, client } = makeEngine({status: "completed",archived: false,@@ -446,8 +446,10 @@ describe("context-engine compact()", () => {await engine.compact({ sessionId: "s1", sessionFile: "" });expect(client.commitSession.mock.calls[0][1]).toMatchObject({- agentId: "test-agent",+ wait: true,+ keepRecentCount: 0,});+ expect(client.commitSession.mock.calls[0][1]).not.toHaveProperty("agentId");});it("returns ok=false with reason=commit_error when commit throws", async () => {diff --git a/examples/openclaw-plugin/tests/ut/recall-trace.test.ts b/examples/openclaw-plugin/tests/ut/recall-trace.test.tsindex bed6eb097..8ce34bf1e 100644--- a/examples/openclaw-plugin/tests/ut/recall-trace.test.ts+++ b/examples/openclaw-plugin/tests/ut/recall-trace.test.ts@@ -79,8 +79,7 @@ describe("resolveRecallSearchPlan()", () => {});expect(plan.searches).toEqual([- { resourceType: "user", targetUri: "viking://user/memories" },- { resourceType: "agent", targetUri: "viking://agent/memories" },+ { resourceType: "user", contextType: "memory" },]);expect(plan.skipped).toEqual([]);expect(plan.resourceTypes).toEqual(["user", "agent"]);@@ -93,9 +92,8 @@ describe("resolveRecallSearchPlan()", () => {});expect(plan.searches).toEqual([- { resourceType: "resource", targetUri: "viking://resources" },- { resourceType: "user", targetUri: "viking://user/memories" },- { resourceType: "agent", targetUri: "viking://agent/memories" },+ { resourceType: "resource", contextType: "resource" },+ { resourceType: "user", contextType: "memory" },]);expect(plan.skipped).toEqual([]);});diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.tsindex 182082481..12484534f 100644--- a/examples/openclaw-plugin/tests/ut/tools.test.ts+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts@@ -189,22 +189,21 @@ describe("Tool: memory_recall (registration)", () => {if (requestUrl.pathname === "/api/v1/search/find") {const body = JSON.parse(String(init?.body ?? "{}"));- const targetUri = String(body.target_uri ?? "");+ expect(body.context_type).toBe("memory");+ expect(body.target_uri).toBeUndefined();const memories =- targetUri.includes("user")- ? [- makeMemory({- uri: "viking://user/default/memories/high",- abstract: "Abstract only text",- score: 0.92,- }),- makeMemory({- uri: "viking://user/default/memories/low",- abstract: "Low score text",- score: 0.05,- }),- ]- : [];+ [+ makeMemory({+ uri: "viking://user/default/memories/high",+ abstract: "Abstract only text",+ score: 0.92,+ }),+ makeMemory({+ uri: "viking://user/default/memories/low",+ abstract: "Low score text",+ score: 0.05,+ }),+ ];return okResponse({ memories, total: memories.length });}@@ -240,21 +239,17 @@ describe("Tool: memory_recall (registration)", () => {const findCalls = fetchMock.mock.calls.filter(([calledUrl]) =>String(calledUrl).includes("/api/v1/search/find"));- expect(findCalls).toHaveLength(2);- const targetUris = findCalls.map(([, init]) =>- JSON.parse(String((init as RequestInit).body)).target_uri,- );- expect(targetUris).toHaveLength(2);- expect(targetUris).toContain("viking://agent/memories");- expect(targetUris.some((uri) => String(uri).endsWith("/memories") && String(uri).includes("viking://user/"))).toBe(true);+ expect(findCalls).toHaveLength(1);for (const [, init] of findCalls) {const body = JSON.parse(String((init as RequestInit).body));expect(body.limit).toBe(20);expect(body.score_threshold).toBe(0);+ expect(body.context_type).toBe("memory");+ expect(body.target_uri).toBeUndefined();}});- it("passes sender peer_id to memory_recall when peer_role is person", async () => {+ it("passes sender actor peer header to memory_recall when peer_role is person", async () => {const fetchMock = vi.fn(async (url: string) => {const requestUrl = new URL(url);if (requestUrl.pathname === "/api/v1/system/status") {@@ -280,12 +275,15 @@ describe("Tool: memory_recall (registration)", () => {query: "backend preference",}) as ToolResult;- const findBodies = fetchMock.mock.calls+ const findRequests = fetchMock.mock.calls.filter(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))- .map((call) => JSON.parse(String((call[1] as RequestInit).body)));- expect(findBodies).toHaveLength(2);- for (const body of findBodies) {- expect(body.peer_id).toBe("wx_user-01_abc");+ .map((call) => call[1] as RequestInit);+ expect(findRequests).toHaveLength(1);+ for (const init of findRequests) {+ const body = JSON.parse(String(init.body));+ const headers = new Headers(init.headers);+ expect(body.peer_id).toBeUndefined();+ expect(headers.get("X-OpenViking-Actor-Peer")).toBe("wx_user-01_abc");}});@@ -297,7 +295,8 @@ describe("Tool: memory_recall (registration)", () => {}if (requestUrl.pathname === "/api/v1/search/find") {const body = JSON.parse(String(init?.body ?? "{}"));- expect(body.target_uri).toBe("viking://resources");+ expect(body.context_type).toBe("resource");+ expect(body.target_uri).toBeUndefined();return okResponse({memories: [],resources: [@@ -346,22 +345,21 @@ describe("Tool: memory_recall (registration)", () => {if (requestUrl.pathname === "/api/v1/search/find") {const body = JSON.parse(String(init?.body ?? "{}"));- const targetUri = String(body.target_uri ?? "");+ expect(body.context_type).toBe("memory");+ expect(body.target_uri).toBeUndefined();const memories =- targetUri.includes("user")- ? [- makeMemory({- uri: "viking://user/default/memories/large",- abstract: "Large abstract",- score: 0.95,- }),- makeMemory({- uri: "viking://user/default/memories/small",- abstract: "Small abstract",- score: 0.9,- }),- ]- : [];+ [+ makeMemory({+ uri: "viking://user/default/memories/large",+ abstract: "Large abstract",+ score: 0.95,+ }),+ makeMemory({+ uri: "viking://user/default/memories/small",+ abstract: "Small abstract",+ score: 0.9,+ }),+ ];return okResponse({ memories, total: memories.length });}@@ -1106,7 +1104,7 @@ describe("Tool: ov_search (behavioral)", () => {}if (url.endsWith("/api/v1/search/find")) {const body = JSON.parse(String(init?.body ?? "{}"));- if (body.target_uri === "viking://resources") {+ if (body.context_type === "resource") {return okResponse({memories: [],resources: [@@ -1126,6 +1124,7 @@ describe("Tool: ov_search (behavioral)", () => {total: 1,});}+ expect(body.context_type).toBe("skill");return okResponse({memories: [],resources: [],@@ -1166,8 +1165,9 @@ describe("Tool: ov_search (behavioral)", () => {const findBodies = fetchMock.mock.calls.filter((call) => String(call[0]).endsWith("/api/v1/search/find")).map((call) => JSON.parse(String((call[1] as RequestInit).body)));- expect(findBodies.some((body) => body.target_uri === "viking://resources")).toBe(true);- expect(findBodies.some((body) => String(body.target_uri).startsWith("viking://user/") && String(body.target_uri).endsWith("/skills"))).toBe(true);+ expect(findBodies).toHaveLength(2);+ expect(findBodies.map((body) => body.context_type).sort()).toEqual(["resource", "skill"]);+ expect(findBodies.every((body) => body.target_uri === undefined)).toBe(true);});it("records ov_search recall traces when traceRecall is enabled", async () => {@@ -1182,12 +1182,10 @@ describe("Tool: ov_search (behavioral)", () => {const body = JSON.parse(String(init?.body ?? "{}"));return okResponse({memories: [],- resources: [+ resources: body.context_type === "resource" ? [{context_type: "resource",- uri: body.target_uri === "viking://resources"- ? "viking://resources/trace-design.md"- : "viking://user/skills/trace-skill",+ uri: "viking://resources/trace-design.md",level: 2,score: 0.88,category: "",@@ -1196,8 +1194,12 @@ describe("Tool: ov_search (behavioral)", () => {abstract: "Trace design note",overview: null,},- ],- skills: [],+ ] : [],+ skills: body.context_type === "skill" ? [makeMemory({+ uri: "viking://user/skills/trace-skill",+ abstract: "Trace skill",+ score: 0.75,+ })] : [],total: 1,});}@@ -1219,7 +1221,10 @@ describe("Tool: ov_search (behavioral)", () => {expect(result.details.count).toBe(1);const entry = (result.details.entries as any[])[0];expect(entry.source).toBe("ov_search");+ expect(entry.resourceTypes).toEqual(["resource", "user"]);expect(entry.searches.length).toBeGreaterThan(0);+ expect(entry.searches.map((search: any) => search.resourceType).sort()).toEqual(["resource", "user"]);+ expect(entry.searches.map((search: any) => search.contextType).sort()).toEqual(["resource", "skill"]);expect(entry.selected[0].uri).toContain("trace");});@@ -1340,9 +1345,11 @@ describe("Tool: ov_search (behavioral)", () => {}if (requestUrl.pathname === "/api/v1/search/find") {const body = JSON.parse(String(init?.body ?? "{}"));+ expect(body.context_type).toBe("memory");+ expect(body.target_uri).toBeUndefined();return okResponse({memories: [makeMemory({- uri: `${body.target_uri}/backend-pref`,+ uri: "viking://user/default/memories/backend-pref",abstract: "Backend preference",score: 0.91,})],@@ -1366,11 +1373,9 @@ describe("Tool: ov_search (behavioral)", () => {const findBodies = fetchMock.mock.calls.filter(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find")).map(([, fetchInit]) => JSON.parse(String((fetchInit as RequestInit).body)));- expect(findBodies).toHaveLength(2);- const targetUris = findBodies.map((body) => body.target_uri);- expect(new Set(targetUris).size).toBe(2);- expect(targetUris).toContain("viking://agent/memories");- expect(targetUris).toContain("viking://user/default/memories");+ expect(findBodies).toHaveLength(1);+ expect(findBodies[0]).toMatchObject({ context_type: "memory" });+ expect(findBodies[0].target_uri).toBeUndefined();const trace = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });const result = await trace.execute("tc-trace", { source: "memory_recall", limit: 10 }) as ToolResult;@@ -1379,11 +1384,9 @@ describe("Tool: ov_search (behavioral)", () => {const entry = (result.details.entries as any[])[0];expect(entry.resourceTypes).toEqual(["user", "agent"]);- expect(entry.searches).toHaveLength(2);- expect(entry.searches.map((search: any) => search.targetUriResolved)).toEqual([- "viking://user/memories",- "viking://agent/memories",- ]);+ expect(entry.searches).toHaveLength(1);+ expect(entry.searches[0].contextType).toBe("memory");+ expect(entry.searches[0].targetUriResolved).toBeUndefined();expect(entry.selected).toEqual(expect.arrayContaining([expect.objectContaining({uri: "viking://user/default/memories/backend-pref",@@ -1438,7 +1441,7 @@ describe("Tool: ov_search (behavioral)", () => {]));});- it("passes assistant peer_id to ov_search when peer_role is assistant", async () => {+ it("passes assistant actor peer header to ov_search when peer_role is assistant", async () => {const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "default" });@@ -1462,12 +1465,15 @@ describe("Tool: ov_search (behavioral)", () => {await search.execute("tc-ov-search-peer", { query: "OpenViking install" }) as ToolResult;- const findBodies = fetchMock.mock.calls+ const findRequests = fetchMock.mock.calls.filter((call) => String(call[0]).endsWith("/api/v1/search/find"))- .map((call) => JSON.parse(String((call[1] as RequestInit).body)));- expect(findBodies).toHaveLength(2);- for (const body of findBodies) {- expect(body.peer_id).toBe("worker");+ .map((call) => call[1] as RequestInit);+ expect(findRequests).toHaveLength(2);+ for (const init of findRequests) {+ const body = JSON.parse(String(init.body));+ const headers = new Headers(init.headers);+ expect(body.peer_id).toBeUndefined();+ expect(headers.get("X-OpenViking-Actor-Peer")).toBe("worker");}});@@ -1481,7 +1487,7 @@ describe("Tool: ov_search (behavioral)", () => {}if (url.endsWith("/api/v1/search/find")) {const body = JSON.parse(String(init?.body ?? "{}"));- if (body.target_uri === "viking://resources") {+ if (body.context_type === "resource") {return okResponse({memories: [],resources: [diff --git a/examples/opencode-memory-plugin/INSTALL-ZH.md b/examples/opencode-memory-plugin/INSTALL-ZH.mdindex 6c40783e2..c193bc13c 100644--- a/examples/opencode-memory-plugin/INSTALL-ZH.md+++ b/examples/opencode-memory-plugin/INSTALL-ZH.md@@ -111,7 +111,7 @@ cp examples/opencode-memory-plugin/.gitignore ~/.config/opencode/plugins/.gitign- `endpoint`: OpenViking 服务地址- `apiKey`: 可留空,推荐用环境变量提供- `account` / `user`: 多租户身份头-- `peerId`: 可选;作为请求级 `peer_id` 用于 recall/search 和 session message 写入+- `peerId`: 可选;作为 `X-OpenViking-Actor-Peer` 用于数据面的 recall/search,session message 仍写入 body `peer_id`- `enabled`: 是否启用插件- `timeoutMs`: 普通请求超时时间- `autoCommit.intervalMinutes`: 自动提交 session 的周期diff --git a/examples/opencode-memory-plugin/README.md b/examples/opencode-memory-plugin/README.mdindex 2017ec3a8..6e074c315 100644--- a/examples/opencode-memory-plugin/README.md+++ b/examples/opencode-memory-plugin/README.md@@ -100,7 +100,7 @@ Example config:````account` and `user` are sent as `X-OpenViking-Account` and `X-OpenViking-User` tenant headers on every plugin API request; leave them empty to omit the headers.-`peerId` is sent as request-level `peer_id` for memory recall/search and captured session messages; leave it empty to preserve existing behavior.+`peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory requests; captured session messages store it as body `peer_id`. Leave it empty to preserve existing behavior.The environment variables `OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_PEER_ID` take precedence over the config file.diff --git a/examples/opencode-memory-plugin/README_CN.md b/examples/opencode-memory-plugin/README_CN.mdindex 61786acd2..755b61e96 100644--- a/examples/opencode-memory-plugin/README_CN.md+++ b/examples/opencode-memory-plugin/README_CN.md@@ -100,7 +100,7 @@ export OPENVIKING_USER="opencode"````account` 和 `user` 会作为 `X-OpenViking-Account` 与 `X-OpenViking-User` 租户头随每次插件 API 请求发送;留空则不会附加这些头。-`peerId` 会作为请求级 `peer_id` 用于 memory recall/search 和 session message 写入;留空则保持现有行为。+`peerId` 会作为 `X-OpenViking-Actor-Peer` 用于数据面的 memory 请求;捕获 session message 时仍写入 body `peer_id`。留空则保持现有行为。环境变量 `OPENVIKING_API_KEY`、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER` 和 `OPENVIKING_PEER_ID` 优先于配置文件。diff --git a/examples/opencode-memory-plugin/openviking-memory.ts b/examples/opencode-memory-plugin/openviking-memory.tsindex 21770e2fc..fbcad1f92 100644--- a/examples/opencode-memory-plugin/openviking-memory.ts+++ b/examples/opencode-memory-plugin/openviking-memory.ts@@ -502,9 +502,14 @@ interface HttpRequestOptions {body?: anytimeoutMs?: numberabortSignal?: AbortSignal+ actorPeerId?: string}-function buildOpenVikingHeaders(config: OpenVikingConfig, includeContentType = true): Record<string, string> {+function buildOpenVikingHeaders(+ config: OpenVikingConfig,+ includeContentType = true,+ actorPeerId = "",+): Record<string, string> {const headers: Record<string, string> = {}if (includeContentType) {@@ -520,13 +525,17 @@ function buildOpenVikingHeaders(config: OpenVikingConfig, includeContentType = tif (config.user) {headers["X-OpenViking-User"] = config.user}+ const peerId = actorPeerId.trim()+ if (peerId) {+ headers["X-OpenViking-Actor-Peer"] = peerId+ }return headers}async function makeRequest<T = any>(config: OpenVikingConfig, options: HttpRequestOptions): Promise<T> {const url = `${config.endpoint}${options.endpoint}`- const headers = buildOpenVikingHeaders(config)+ const headers = buildOpenVikingHeaders(config, true, options.actorPeerId)const controller = new AbortController()const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? config.timeoutMs)@@ -1655,15 +1664,11 @@ function extractMessageText(parts: { type: string; text?: string }[]): string |/** Perform search against OpenViking with a timeout guard. Returns empty on any failure. */async function performRecallSearch(config: OpenVikingConfig, query: string): Promise<RecallSearchItem[]> {try {- const body: { query: string; limit: number; mode: string; peer_id?: string } = {+ const body: { query: string; limit: number; mode: string } = {query: query.slice(0, 4000),limit: 20,mode: "auto",}- const peerId = config.peerId.trim()- if (peerId) {- body.peer_id = peerId- }const response = await makeRequest<OpenVikingResponse<{ memories?: RecallSearchItem[]; results?: RecallSearchItem[] }>>(config,{@@ -1671,6 +1676,7 @@ async function performRecallSearch(config: OpenVikingConfig, query: string): Proendpoint: "/api/v1/search/find",body,timeoutMs: AUTO_RECALL_TIMEOUT_MS,+ actorPeerId: config.peerId.trim(),},)const result = unwrapResponse(response)@@ -2053,6 +2059,7 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>method: "GET",endpoint: `/api/v1/fs/stat?uri=${encodeURIComponent(args.uri)}`,abortSignal: context.abort,+ actorPeerId: config.peerId.trim(),})const statResult = unwrapResponse(statResponse)level = statResult?.isDir ? "overview" : "read"@@ -2065,6 +2072,7 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>method: "GET",endpoint: `/api/v1/content/${level}?uri=${encodeURIComponent(args.uri)}`,abortSignal: context.abort,+ actorPeerId: config.peerId.trim(),})const content = unwrapResponse(response)@@ -2114,6 +2122,7 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>method: "GET",endpoint: `/api/v1/fs/stat?uri=${encodedUri}`,abortSignal: context.abort,+ actorPeerId: config.peerId.trim(),})const result = unwrapResponse(response)return JSON.stringify({ view, item: result }, null, 2)@@ -2126,6 +2135,7 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>method: "GET",endpoint,abortSignal: context.abort,+ actorPeerId: config.peerId.trim(),})const result = unwrapResponse(response)@@ -2331,7 +2341,6 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>target_uri?: stringsession_id?: stringscore_threshold?: number- peer_id?: string} = {query: args.query,limit: args.limit ?? 10,@@ -2339,8 +2348,6 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>if (args.target_uri) requestBody.target_uri = args.target_uriif (args.score_threshold !== undefined) requestBody.score_threshold = args.score_thresholdif (mode === "deep" && sessionId) requestBody.session_id = sessionId- const peerId = config.peerId.trim()- if (peerId) requestBody.peer_id = peerIdtry {const response = await makeRequest<OpenVikingResponse<SearchResult>>(config, {@@ -2348,6 +2355,7 @@ export const OpenVikingMemoryPlugin = async (input: PluginInput): Promise<Hooks>endpoint: mode === "deep" ? "/api/v1/search/search" : "/api/v1/search/find",body: requestBody,abortSignal: context.abort,+ actorPeerId: config.peerId.trim(),})const result = unwrapResponse(response) ?? { memories: [], resources: [], skills: [], total: 0 }diff --git a/examples/opencode-plugin/INSTALL-ZH.md b/examples/opencode-plugin/INSTALL-ZH.mdindex b14e486b3..f87bd2e24 100644--- a/examples/opencode-plugin/INSTALL-ZH.md+++ b/examples/opencode-plugin/INSTALL-ZH.md@@ -121,8 +121,7 @@ export OPENVIKING_API_KEY="your-api-key-here"`apiKey` 会作为 `X-API-Key` 发送。`account` 和 `user` 是 trusted mode身份头,会作为 `X-OpenViking-Account`、`X-OpenViking-User` 发送;使用user/admin API key 的 API_KEY mode 时应留空。-`peerId` 会作为请求级 `peer_id` 用于 memory recall/search 和 session message 写入;-需要 peer 维度路由时请显式配置。+`peerId` 会作为 `X-OpenViking-Actor-Peer` 用于数据面的 memory/resource 请求;捕获 session message 时仍写入 body `peer_id`。需要 peer 维度路由时请显式配置。`OPENVIKING_API_KEY`、`OPENVIKING_ACCOUNT`、`OPENVIKING_USER`、`OPENVIKING_PEER_ID`diff --git a/examples/opencode-plugin/INSTALL.md b/examples/opencode-plugin/INSTALL.mdindex 33b5a7f3e..b4ea0c1e5 100644--- a/examples/opencode-plugin/INSTALL.md+++ b/examples/opencode-plugin/INSTALL.md@@ -118,7 +118,7 @@ It is recommended to provide the API key through an environment variable insteadexport OPENVIKING_API_KEY="your-api-key-here"```-`apiKey` is sent as `X-API-Key`. `account` and `user` are trusted-mode identity headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them empty when using API-key mode with user/admin API keys. `peerId` is sent as request-level `peer_id` for memory recall/search and captured session messages; configure it explicitly when peer-scoped memory routing is needed.+`apiKey` is sent as `X-API-Key`. `account` and `user` are trusted-mode identity headers sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them empty when using API-key mode with user/admin API keys. `peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory/resource requests; captured session messages store it as body `peer_id`. Configure it explicitly when peer-scoped memory routing is needed.`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`, and `OPENVIKING_PEER_ID` take precedence over the corresponding values in `openviking-config.json`.diff --git a/examples/opencode-plugin/README.md b/examples/opencode-plugin/README.mdindex 12bf978e1..a252031f7 100644--- a/examples/opencode-plugin/README.md+++ b/examples/opencode-plugin/README.md@@ -128,9 +128,9 @@ Create `~/.config/opencode/openviking-config.json`:`apiKey` is sent as `X-API-Key`. `account` and `user` are trusted-mode identityheaders sent as `X-OpenViking-Account` and `X-OpenViking-User`; leave them emptywhen using API-key mode with user/admin API keys.-`peerId` is sent as request-level `peer_id` for memory recall/search and-captured session messages. Configure `peerId` explicitly when peer-scoped-memory routing is needed.+`peerId` is sent as `X-OpenViking-Actor-Peer` on data-plane memory/resource+requests; captured session messages store it as body `peer_id`. Configure+`peerId` explicitly when peer-scoped memory routing is needed.`OPENVIKING_API_KEY`, `OPENVIKING_ACCOUNT`, `OPENVIKING_USER`,and `OPENVIKING_PEER_ID` takediff --git a/examples/opencode-plugin/lib/memadd-local.mjs b/examples/opencode-plugin/lib/memadd-local.mjsindex e84390adf..ce62d4980 100644--- a/examples/opencode-plugin/lib/memadd-local.mjs+++ b/examples/opencode-plugin/lib/memadd-local.mjs@@ -71,7 +71,7 @@ export function buildAddResourceBody(args, source, tempFileId) {return body}-export async function uploadLocalResource(config, source, abortSignal) {+export async function uploadLocalResource(config, source, abortSignal, actorPeerId) {const bytes = await fs.promises.readFile(source.path)const form = new FormData()form.append("file", new Blob([bytes], { type: "application/octet-stream" }), source.filename)@@ -81,6 +81,7 @@ export async function uploadLocalResource(config, source, abortSignal) {endpoint: "/api/v1/resources/temp_upload",body: form,abortSignal,+ actorPeerId,})const tempFileId = unwrapResponse(uploadResponse)?.temp_file_idif (!tempFileId) {@@ -89,11 +90,13 @@ export async function uploadLocalResource(config, source, abortSignal) {return tempFileId}-export async function addMemaddResource(config, args, projectDirectory, abortSignal) {+export async function addMemaddResource(config, args, projectDirectory, abortSignal, actorPeerId) {const source = resolveMemaddSource(args.path, projectDirectory)if (source.kind === "error") return { error: source.error }- const tempFileId = source.kind === "local" ? await uploadLocalResource(config, source, abortSignal) : undefined+ const tempFileId = source.kind === "local"+ ? await uploadLocalResource(config, source, abortSignal, actorPeerId)+ : undefinedconst body = buildAddResourceBody(args, source, tempFileId)const addResponse = await makeRequest(config, {method: "POST",@@ -101,6 +104,7 @@ export async function addMemaddResource(config, args, projectDirectory, abortSigbody,abortSignal,timeoutMs: args.wait ? Math.max(config.timeoutMs, (args.timeout ?? 300) * 1000) : config.timeoutMs,+ actorPeerId,})return { addResponse, source }}diff --git a/examples/opencode-plugin/lib/memory-recall.mjs b/examples/opencode-plugin/lib/memory-recall.mjsindex 2d81cd2de..ca4b1e98d 100644--- a/examples/opencode-plugin/lib/memory-recall.mjs+++ b/examples/opencode-plugin/lib/memory-recall.mjs@@ -43,13 +43,12 @@ export function createMemoryRecall({ config }) {async function performRecallSearch(query) {try {const body = { query: query.slice(0, 4000), limit: 20, mode: "auto" }- const peerId = effectivePeerId(config)- if (peerId) body.peer_id = peerIdconst response = await makeRequest(config, {method: "POST",endpoint: "/api/v1/search/find",body,timeoutMs: AUTO_RECALL_TIMEOUT_MS,+ actorPeerId: effectivePeerId(config),})const result = unwrapResponse(response)return result?.memories ?? result?.results ?? []diff --git a/examples/opencode-plugin/lib/memory-tools.mjs b/examples/opencode-plugin/lib/memory-tools.mjsindex b66bc41ef..da9cecdec 100644--- a/examples/opencode-plugin/lib/memory-tools.mjs+++ b/examples/opencode-plugin/lib/memory-tools.mjs@@ -11,6 +11,7 @@ import {const z = tool.schemaexport function createMemoryTools({ config, sessionManager, projectDirectory }) {+ const actorPeerId = effectivePeerId(config)return {memsearch: tool({description:@@ -38,14 +39,12 @@ export function createMemoryTools({ config, sessionManager, projectDirectory })if (args.target_uri) body.target_uri = args.target_uriif (args.score_threshold !== undefined) body.score_threshold = args.score_thresholdif (mode === "deep" && sessionId) body.session_id = sessionId- const peerId = effectivePeerId(config)- if (peerId) body.peer_id = peerId-const response = await makeRequest(config, {method: "POST",endpoint: mode === "deep" ? "/api/v1/search/search" : "/api/v1/search/find",body,abortSignal: context.abort,+ actorPeerId,})return formatSearchResults(unwrapResponse(response), args.query, { mode })} catch (error) {@@ -69,12 +68,13 @@ export function createMemoryTools({ config, sessionManager, projectDirectory })try {let level = args.level ?? "auto"if (level === "auto") {- level = await resolveReadLevel(config, args.uri, context.abort)+ level = await resolveReadLevel(config, args.uri, context.abort, actorPeerId)}const response = await makeRequest(config, {method: "GET",endpoint: `/api/v1/content/${level}?uri=${encodeURIComponent(args.uri)}`,abortSignal: context.abort,+ actorPeerId,})const content = unwrapResponse(response)return typeof content === "string" ? content : JSON.stringify(content, null, 2)@@ -109,7 +109,12 @@ export function createMemoryTools({ config, sessionManager, projectDirectory })} else {endpoint = `/api/v1/fs/ls?uri=${encodedUri}&recursive=${args.recursive ? "true" : "false"}&simple=${args.simple ? "true" : "false"}`}- const response = await makeRequest(config, { method: "GET", endpoint, abortSignal: context.abort })+ const response = await makeRequest(config, {+ method: "GET",+ endpoint,+ abortSignal: context.abort,+ actorPeerId,+ })return JSON.stringify({ view, result: unwrapResponse(response) }, null, 2)} catch (error) {log("ERROR", "membrowse", "Browse failed", { error: error?.message, uri: args.uri })@@ -168,6 +173,7 @@ export function createMemoryTools({ config, sessionManager, projectDirectory })endpoint: "/api/v1/search/grep",body,abortSignal: context.abort,+ actorPeerId,})return JSON.stringify(unwrapResponse(response), null, 2)} catch (error) {@@ -198,6 +204,7 @@ export function createMemoryTools({ config, sessionManager, projectDirectory })endpoint: "/api/v1/search/glob",body,abortSignal: context.abort,+ actorPeerId,})return JSON.stringify(unwrapResponse(response), null, 2)} catch (error) {@@ -226,7 +233,7 @@ export function createMemoryTools({ config, sessionManager, projectDirectory })if (args.parent && !args.parent.startsWith("viking://resources")) return "Error: `parent` must be under viking://resources/."try {- const result = await addMemaddResource(config, args, projectDirectory, context.abort)+ const result = await addMemaddResource(config, args, projectDirectory, context.abort, actorPeerId)if (result.error) return result.errorconst queue = await getQueueStatus(config, context.abort)return JSON.stringify({ add_resource: unwrapResponse(result.addResponse), queue }, null, 2)@@ -257,6 +264,7 @@ export function createMemoryTools({ config, sessionManager, projectDirectory })method: "DELETE",endpoint: `/api/v1/fs?uri=${encodeURIComponent(args.uri)}&recursive=${args.recursive ? "true" : "false"}`,abortSignal: context.abort,+ actorPeerId,})return JSON.stringify(unwrapResponse(response), null, 2)} catch (error) {@@ -282,12 +290,13 @@ export function createMemoryTools({ config, sessionManager, projectDirectory })}}-async function resolveReadLevel(config, uri, abortSignal) {+async function resolveReadLevel(config, uri, abortSignal, actorPeerId) {try {const statResponse = await makeRequest(config, {method: "GET",endpoint: `/api/v1/fs/stat?uri=${encodeURIComponent(uri)}`,abortSignal,+ actorPeerId,})return unwrapResponse(statResponse)?.isDir ? "overview" : "read"} catch {diff --git a/examples/opencode-plugin/lib/repo-context.mjs b/examples/opencode-plugin/lib/repo-context.mjsindex 91e122bea..3a32e57d1 100644--- a/examples/opencode-plugin/lib/repo-context.mjs+++ b/examples/opencode-plugin/lib/repo-context.mjs@@ -1,4 +1,4 @@-import { log, makeRequest, unwrapResponse } from "./utils.mjs"+import { effectivePeerId, log, makeRequest, unwrapResponse } from "./utils.mjs"export function createRepoContext({ config }) {let cachedRepos = null@@ -18,6 +18,7 @@ export function createRepoContext({ config }) {method: "GET",endpoint: `/api/v1/fs/ls?uri=${encodeURIComponent("viking://resources/")}&recursive=false&simple=false`,timeoutMs: 8000,+ actorPeerId: effectivePeerId(config),})const result = unwrapResponse(response)const items = Array.isArray(result) ? result : []diff --git a/examples/opencode-plugin/lib/utils.mjs b/examples/opencode-plugin/lib/utils.mjsindex b975cd921..e451f6b59 100644--- a/examples/opencode-plugin/lib/utils.mjs+++ b/examples/opencode-plugin/lib/utils.mjs@@ -185,7 +185,11 @@ export function effectivePeerId(config) {export async function makeRequest(config, options) {const url = `${normalizeEndpoint(config.endpoint)}${options.endpoint}`- const headers = makeAuthHeaders(config, { "Content-Type": "application/json", ...(options.headers ?? {}) })+ const headers = makeAuthHeaders(+ config,+ { "Content-Type": "application/json", ...(options.headers ?? {}) },+ options.actorPeerId,+ )const controller = new AbortController()const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? config.timeoutMs)@@ -236,7 +240,7 @@ export async function makeRequest(config, options) {export async function makeMultipartRequest(config, options) {const url = `${normalizeEndpoint(config.endpoint)}${options.endpoint}`- const headers = makeAuthHeaders(config, options.headers ?? {})+ const headers = makeAuthHeaders(config, options.headers ?? {}, options.actorPeerId)const controller = new AbortController()const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? config.timeoutMs)@@ -285,11 +289,13 @@ export async function makeMultipartRequest(config, options) {}}-function makeAuthHeaders(config, headers = {}) {+function makeAuthHeaders(config, headers = {}, actorPeerId = "") {const result = { ...headers }if (config.apiKey) result["X-API-Key"] = config.apiKeyif (config.account) result["X-OpenViking-Account"] = config.accountif (config.user) result["X-OpenViking-User"] = config.user+ const peerId = String(actorPeerId || "").trim()+ if (peerId) result["X-OpenViking-Actor-Peer"] = peerIdreturn result}