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
refactor(openclaw): add setup and routing modules (#2654)
Mingjian Qued9e40b09743e
diff --git a/examples/openclaw-plugin/INSTALL-AGENT.md b/examples/openclaw-plugin/INSTALL-AGENT.mdindex 881125ccf..9286f7d1f 100644--- a/examples/openclaw-plugin/INSTALL-AGENT.md+++ b/examples/openclaw-plugin/INSTALL-AGENT.md@@ -96,10 +96,10 @@ openclaw openviking setup \--json```-Assistant peer prefix (optional; only when the user explicitly requests assistant `peer_id` / actor peer scoping):+Custom agent routing prefix (optional; only when the user explicitly requests a prefix):```bash-openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --peer-role assistant --peer-prefix <PREFIX> --json+openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --peer-prefix <PREFIX> --json```Slot replacement retry, only after user approval:@@ -139,8 +139,7 @@ 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 body `peer_id` and which data-plane requests use actor peer scope |-| `config.peer_prefix` | Confirms configured assistant peer / actor peer prefix when present |+| `config.peer_prefix` | Confirms configured peer prefix when present |## Environment Detection@@ -268,8 +267,7 @@ Core fields:| `mode` | Legacy compatibility field. Expected value: `remote`. || `baseUrl` | OpenViking HTTP endpoint || `apiKey` | OpenViking API key |-| `peer_role` | Peer identity mode: `none`, `assistant`, or `person`. New installs default to `assistant`. 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`. |+| `peer_prefix` | Optional; prefix for OpenClaw agent IDs when set. Interactive setup accepts only letters, digits, `_`, and `-`. If unset, the plugin follows session agent IDs. || `accountId` | Required for root API keys || `userId` | Required for root API keys |@@ -331,8 +329,7 @@ Existing config fields are preserved during migration. The new plugin reads old- `baseUrl`- `apiKey`-- `peer_role`: optional; default `assistant`; selects the peer identity mode-- `peer_prefix`: optional assistant `peer_id` / actor peer prefix when `peer_role=assistant`+- `peer_prefix`: optional; interactive setup accepts only letters, digits, `_`, and `-`## Backup Path: ov-installdiff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.mdindex d2ad32856..ba5d3d9ca 100644--- a/examples/openclaw-plugin/README_CN.md+++ b/examples/openclaw-plugin/README_CN.md@@ -1,6 +1,13 @@# OpenViking for OpenClaw-将 [OpenViking](https://github.com/volcengine/OpenViking) 作为 OpenClaw 的长期上下文引擎:自动召回、会话归档、记忆抽取、语义检索和 RAG,连接远程 OpenViking 服务。+将 [OpenViking](https://github.com/volcengine/OpenViking) 作为 OpenClaw 的远程上下文引擎:会话归档、基于阈值或 `/compact` 的记忆抽取、自动召回、resource/skill 检索、召回链路追踪,以及大工具结果的引用式分页读取。++当前实现重点:++- **仅远程模式**:插件是已有 OpenViking 服务的 HTTP 客户端,不会启动本地 OpenViking server 进程。+- **生命周期集成**:`assemble` 重建压缩会话历史并注入相关记忆;`afterTurn` 增量写入本轮消息并按阈值异步 commit;`compact` 执行阻塞 commit 和结果回读。+- **导入与检索**:Agent 可导入 resources 和 Agent Skills,检索它们,并在召回中选择 `resource`、`user`、`agent` 等目标。+- **可调试性**:可选的 recall trace 可通过 `ov_recall_trace` 或 `/ov-recall-trace` 查询;超大工具输出会外置存储,并可按 ref 列表、搜索和读取。## 快速开始@@ -13,6 +20,32 @@ openclaw openviking status --json四步完成。`setup` 命令会自动激活 context-engine slot 并验证连接。+常用 setup 变体:++```bash+# 可选 agent 命名空间前缀+openclaw openviking setup --base-url http://my-server:1933 --api-key sk-xxx --peer-prefix openclaw-prod --json++# root/trusted key 部署,需要显式租户身份 header+openclaw openviking setup --base-url http://my-server:1933 --api-key root-xxx --account-id acc_123 --user-id user_456 --json++# 默认只召回 account 级共享知识资源+openclaw openviking setup --base-url http://my-server:1933 --api-key sk-xxx --recall-target-types resource --json+```++### 火山 OpenViking Service 一键接入++如果使用火山控制台托管的 OpenViking Service,可直接注入控制台提供的 server url 和 API Key:++```bash+OPENVIKING_BASE_URL="https://api.vikingdb.cn-beijing.volces.com/openviking" \+OPENVIKING_API_KEY="<your-openviking-service-api-key>" \+OPENVIKING_PEER_PREFIX="openclaw-prod" \+bash scripts/install.sh --json+```++脚本默认从 TOS `prod/latest` 安装插件,并完成 `openviking.env` 写入、`openclaw openviking setup`、Gateway 重启和状态验证。安装脚本依赖 bash,请不要用 `sh` 执行;下载包场景可使用 `bash output/install.sh --source tarball --tarball output/openviking.tgz`。+### 或者直接让 Agent 安装> 帮我安装 OpenViking 远程记忆插件 @openviking/openclaw-plugin。我的服务器地址是 `http://my-server:1933`,API key 是 `sk-xxx`。@@ -23,42 +56,40 @@ Agent 会自动完成安装 → 配置 → 重启 → 验证。详见 [INSTALL-A| 阶段 | 行为 ||------|------|-| **每轮对话后** (`afterTurn`) | 新消息追加到 OpenViking session;commit/抽取由阈值触发 |-| **明确要求记住** (`memory_store`) | 重要长期事实可立即写入并提交 |-| **`/compact` 时** (`compact`) | 待提交 session 消息被 commit 并抽取为长期记忆 |+| **每轮对话后** (`afterTurn`) | 消息自动归档到 OpenViking session |+| **`/compact` 时** (`compact`) | 归档消息被抽取为长期记忆 || **回复前** (`assemble`) | 自动检索相关记忆并注入上下文 |## 工具-安装后,插件为 Agent 提供以下工具:+安装后,插件默认为 Agent 提供以下工具:| 工具 | 用途 ||------|------|-| `memory_recall` | 显式检索长期记忆 |-| `memory_store` | 立即持久化明确的长期事实 |-| `memory_forget` | 按 URI 或查询删除记忆 |-| `ov_archive_search` | 按关键词搜索历史 archive |-| `ov_archive_expand` | 展开某个 archive 的原始消息 |-| `ov_recall_trace` | 查看召回/检索为什么命中或注入某些结果 |-| `add_resource` | 显式开启后导入文档、URL 或 Git 仓库 |-| `add_skill` | 导入 agent 技能 |+| `memory_recall` | 在 `user`、`agent`、`resource` 目标中显式语义召回 |+| `memory_store` | 将重要文本写入 session,并立即触发记忆抽取 |+| `memory_forget` | 按精确 URI 删除记忆,或搜索并删除唯一高置信匹配 |+| `ov_archive_search` | 对当前 session 已归档的原始对话消息做关键词 grep |+| `ov_archive_expand` | 按 archive ID 展开原始消息 |+| `ov_recall_trace` | 查看 auto-recall 和显式 recall/search 记录的召回链路 |+| `add_skill` | 将 `SKILL.md`、skill 目录、原始 skill 内容或 MCP tool dict 导入 `viking://user/skills/...` || `ov_search` | 检索已导入的 resources 和 skills |-| `ov_read` | 读取一个精确 OpenViking URI 的完整原文 |-| `ov_multi_read` | 读取多个 OpenViking URI 的完整原文 |-| `ov_list` | 在检索后列出 OpenViking 目录,补查同级切片和 overview 文件 |-| `openviking_tool_result_read` | 还原被 OpenViking 外置的工具结果的完整原始内容 |-| `openviking_tool_result_search` | 按关键词在外置的工具结果中检索 |-| `openviking_tool_result_list` | 列出当前会话中外置的工具结果 |+| `ov_read` | 读取 `ov_search` / trace 返回的 `viking://...` OpenViking 虚拟 URI 完整内容 |+| `ov_multi_read` | 一次读取多个精确 `viking://...` URI,适合同时读取 overview 和同级切片 |+| `ov_list` | 在检索后列出 OpenViking 目录,补查同级切片和 `.overview.md` 文件 |+| `openviking_tool_result_list` | 列出当前 session 中被外置的大工具输出 |+| `openviking_tool_result_search` | 在外置工具输出中按关键词搜索 |+| `openviking_tool_result_read` | 通过 `viking://session/.../tool-results/...` ref 分页读取外置工具输出 |-`add_resource` 默认不暴露给 Agent(`enableAddResourceTool=false`),但手动 `/add-resource` 仍然可用。可通过 `recallTargetTypes` 配置默认召回目标(`user`、`agent`、`resource`);旧配置 `recallResources=true` 只会在未显式设置 `recallTargetTypes` 时追加 `resource`。+插件还提供手动 slash command:`/add-resource`、`/add-skill`、`/ov-search`、`/ov-recall-trace`。Agent 可见的 `add_resource` 工具默认禁用(`enableAddResourceTool=false`),避免搜索/检索阶段误触发资源导入;如确实要允许 Agent 导入资源,可显式设置 `enableAddResourceTool=true`,否则使用手动 `/add-resource`。## 数据流与隐私- **发送内容**:每轮 user/assistant 消息文本(已剥离注入的记忆块和元数据噪音)。- **发送去向**:仅发往你配置的 OpenViking 服务(`baseUrl`)。插件本身只与该服务通信;服务端对 embedding、VLM 等模型的调用取决于服务端配置。-- **存储位置**:所有数据存储在你的 OpenViking 服务上,路径为 `viking://user/*`(包含 `viking://user/sessions/*`)和 `viking://resources/*`。+- **存储位置**:所有数据存储在你的 OpenViking 服务上,命名空间包括 `viking://user/*`、`viking://session/*`、`viking://resources/*` 等。- **API Key**:通过 `X-API-Key` header 发送,不会被日志记录或转发。-- **多租户隔离**:支持 `accountId`、`userId`。可选的 `peer_role` / `peer_prefix` 控制是否把 OpenClaw 说话人写入 OpenViking `peer_id`。+- **多租户隔离**:支持 `accountId`、`userId`。可选的 `peer_role` / `peer_prefix` 控制是否把 OpenClaw 说话人写入 OpenViking `peer_id`,并在数据面使用 `X-OpenViking-Actor-Peer`。## 验证@@ -74,6 +105,7 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking| [INSTALL-ZH.md](./INSTALL-ZH.md) | 完整安装、升级、卸载指南 || [INSTALL.md](./INSTALL.md) | English install guide || [INSTALL-AGENT.md](./INSTALL-AGENT.md) | Agent 专用操作文档 |+| [docs/openviking-websocket-rpc-api.md](./docs/openviking-websocket-rpc-api.md) | 通过 OpenClaw Gateway WebSocket RPC 调用 OpenViking 工具 |> **插件 vs Skill**:本页面是 `@openviking/openclaw-plugin`(context-engine 插件)。**不要**使用 `clawhub install openviking`——那安装的是另一个 AgentSkill。@@ -105,14 +137,14 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking- OpenClaw 在左侧,仍然是主运行时;插件并不接管 agent 执行本身。- 插件中间层把 Hook、Context Engine、Tools、Runtime Manager 四部分合并在一个注册单元里。-- 所有 HTTP 调用最终都走 `OpenVikingClient`,由 client 层统一补租户 header 和路由日志。-- OpenViking 服务端承接 session、memory、archive 和 Phase 2 抽取,底层存储落在 `viking://user/*`(包含 `viking://user/sessions/*`)和 `viking://resources/*`。+- 所有 HTTP 调用最终都走 `OpenVikingClient`,由 client 层统一补 `X-OpenViking-*` 头和路由日志。+- OpenViking 服务端承接 session、memory、archive 和 Phase 2 抽取,底层存储落在 `viking://user/*`(包含 `viking://user/sessions/*`)、`viking://session/*` 和 `viking://resources/*`。这套拆分的意义,是让 OpenClaw 继续专注推理与编排,让 OpenViking 成为长期上下文的事实源。## 身份与路由-插件会把 OpenClaw 会话身份保留在 session 和 peer metadata 里,但不会向 OpenViking 发送 agent 身份,也不会创建 agent namespace。+插件会把 OpenClaw 会话身份保留在 session 和 peer metadata 里;OpenViking 的租户身份仍然是 account/user 级,OpenClaw agent/sender 身份作为 peer 归因和 actor-peer 数据面路由使用。核心规则如下:@@ -143,7 +175,7 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking### User namespace-插件通过 `viking://user/...` 写入和检索 user-scoped memory;OpenViking 会根据请求里的租户身份和 actor peer context 解析这个别名。`viking://agent/...` 已由 OpenViking 废弃,插件不再使用。+插件通过 `viking://user/...` 写入和检索 user-scoped memory;OpenViking 会根据请求里的租户身份和 actor peer context 解析这个别名。legacy agent URI namespace 已由 OpenViking 废弃,插件不再使用。## assemble 召回链路@@ -161,7 +193,7 @@ openclaw config get plugins.slots.contextEngine # 应输出:openviking3. 先做一次快速可用性检查,避免在 OpenViking 不可用时拖慢模型请求。4. 检索配置的 `recallTargetTypes`(默认 `user,agent`;可选 `resource`;session 历史请使用 `ov_archive_search` 和 `ov_archive_expand`)。5. 在插件侧做去重、阈值筛选、重排和 token budget 裁剪。-6. 把最终记忆以 `## Long-term Memories` section 放进 `<openviking-context>`,再 prepend 到当前 user message;不会追加独立 synthetic user message。+6. 把最终记忆块以 `<relevant-memories>` 形式 prepend 到当前 user message;不会追加独立 synthetic user message。这里的重排不是单纯依赖向量分数。当前实现还会额外考虑:@@ -196,7 +228,7 @@ preflight 阶段的 `assemble()` 并不是简单地把旧聊天记录塞回来- 只切出本轮新增消息,不重写整段对话- 只保留 `user` / `assistant` 相关文本内容- 会把 `toolCall` / `toolResult` 格式化进 capture 文本-- 会先剥掉注入过的 `<openviking-context>`、历史 `<relevant-memories>` 和元数据噪音+- 会先剥掉注入过的 `<relevant-memories>` 和元数据噪音- 最终把清洗后的增量内容追加到 OpenViking session之后插件会读取 session 的 `pending_tokens`。当它超过 `commitTokenThreshold` 时,会触发一次 `commit(wait=false)`:@@ -205,18 +237,6 @@ preflight 阶段的 `assemble()` 并不是简单地把旧聊天记录塞回来- 当前 turn 不会因为等待抽取而阻塞- 如果打开 `logFindRequests`,日志里能看到 task id 和后续抽取结果-这条自动路径是 best-effort,并且依赖 commit。短但重要的事实可能会先停留在 live session 里,直到阈值 commit、`/compact` 或显式存储发生后,才进入长期记忆抽取流程。--### 显式长期记忆写入--当用户明确要求 agent “记住”“保存”“存一下”某个重要长期事实、偏好、项目或决定时,应优先使用 `memory_store`,而不是等待普通 auto-capture 自然触发。`memory_store` 会把文本写入 OpenViking session 并调用 `commit(wait=true)`,因此是集成侧让重要事实尽快进入长期记忆的可靠路径。--它是 auto-capture 的补充,不是替代:--- auto-capture 继续负责普通对话流,并通过批处理平衡成本和延迟-- `memory_store` 面向明确的长期记忆意图,例如“记住我的主项目是 X”或“保存这个偏好”-- 如果 `memory_store` 已提交但抽取出 0 条记忆,应检查 OpenViking 服务端抽取模型/配置;显式路径已经触发抽取,但 extractor 没有产出记忆-### `compact()` 负责什么`compact()` 走的是另一条更严格的同步边界:@@ -230,32 +250,49 @@ preflight 阶段的 `assemble()` 并不是简单地把旧聊天记录塞回来## 工具层与可展开能力-这套插件除了自动行为,还直接暴露了以下工具:+这套插件除了自动行为,默认直接暴露 12 个工具;当 `enableAddResourceTool=true` 时才额外暴露 opt-in 的 `add_resource` 导入工具。Agent 可见工具可以通过 `enabledTools` 和 `disabledTools` 灵活裁剪:-- `memory_recall`:显式检索长期记忆-- `memory_store`:把明确的长期事实写入 OpenViking session 并立即触发 commit+- `memory_recall`:在 memory/resource 目标上显式语义召回+- `memory_store`:把文本写入 OpenViking session 并触发阻塞 commit/抽取- `memory_forget`:按 URI 删除,或先搜索再删除唯一高置信候选+- `ov_archive_search`:按关键词 grep 已归档的原始对话消息- `ov_archive_expand`:展开某个 archive 的原始消息-- `ov_recall_trace`:在开启 `traceRecall` 后查看最近召回/检索 trace-- `add_resource`:显式开启后把文档、目录、URL 或 Git 仓库导入为 OpenViking resource-- `add_skill`:导入或注册 OpenViking skill+- `ov_recall_trace`:查询 auto-recall 和显式 recall/search 调用的召回链路记录+- `add_skill`:导入或注册 OpenViking agent skill- `ov_search`:检索 OpenViking resources 和 skills,尤其用于导入后的确认和消费-- `ov_read`:读取 `ov_search` 或 `ov_list` 返回的一个精确 `viking://` URI-- `ov_multi_read`:读取多个精确 `viking://` URI,适合同时读取 overview 和同级切片+- `ov_read`:读取 `ov_search` 或 recall trace 返回的 `viking://...` OpenViking 虚拟 URI 完整内容+- `ov_multi_read`:读取多个精确 `viking://...` URI,适合同时读取 overview 和同级切片- `ov_list`:在 `ov_search` 命中后列出父目录,用来补齐同级切片、`.overview.md` 和同源文档上下文+- `openviking_tool_result_list`:列出当前 session 中被外置的大工具输出+- `openviking_tool_result_search`:在外置工具输出中按关键词搜索+- `openviking_tool_result_read`:通过 ref 和 offset/limit 分页读取外置工具输出++工具选择器支持精确工具名,也支持分组:`default`、`all`、`memory`、`resource_query`、`import`、`recall_trace`、`archive`、`tool_result`。例如,禁用记忆并只保留资源查询工具:++```json+{+ "autoCapture": false,+ "autoRecall": false,+ "enabledTools": ["resource_query"]+}+```++如果希望保留默认工具集但移除记忆相关操作,可设置 `"disabledTools": ["memory"]`。`add_resource` 仍然是双重 opt-in:必须同时被 `enabledTools` 选中并设置 `enableAddResourceTool=true` 才会注册。它们各自的作用不同:- 自动 recall 解决"模型不知道该先查什么"的默认场景。- `memory_recall` 给模型一个显式补查入口。-- `memory_store` 适合在用户表达长期记忆意图时,把明确的重要信息立刻落入记忆管线。-- `ov_archive_expand` 负责在 summary 不够细时回到 archive 级原文。-- `add_resource` 让 agent 在用户明确提出文档或仓库导入需求时直接完成操作,不要求用户记住 slash command。-- `add_skill` 把 skill 导入 OpenViking,`add_resource` 把文档、目录、URL 或 Git 仓库导入为 resource。-- `ov_search` 补齐导入后的使用闭环,让用户或 agent 可以确认并消费 resources 和 skills。-- `ov_read` 把检索命中的 ranked hit 转成原文证据,适合精确文档、代码库、配置和操作步骤问答。+- `memory_store` 适合把一段明确的重要信息立刻落入记忆管线。+- `ov_archive_search` 和 `ov_archive_expand` 负责在 summary 不够细时回到 archive 级原文。+- `ov_recall_trace` 用来解释某次召回/检索为什么命中或没有命中某些内容。+- 手动 `/add-resource` 用于把文档、目录、URL 或 Git 仓库导入为 resource;Agent 可见的 `add_resource` 是 opt-in 工具,不能在搜索、检索、URI 读取或搜索结果优化阶段使用。+- `add_skill` 把 skill 导入 OpenViking。+- `ov_search` 补齐导入后的确认闭环;它返回的 `viking://...` 是 OpenViking 虚拟 URI,不是本地文件路径。+- `ov_read` 通过 OpenViking `/api/v1/content/read` 消费精确的 `viking://...` 命中 URI,避免模型把虚拟 URI 当成本地文件路径读取。- `ov_multi_read` 能一次读取 overview 和多个同级切片,适合拆分文档需要补上下文的场景。- `ov_list` 补齐 `ov_search` 的结构浏览能力,避免只拿到某个切片时遗漏同一目录下的连续步骤。+- `openviking_tool_result_*` 避免超大外部工具输出撑爆上下文,同时保留完整内容的可恢复能力。其中 `ov_archive_expand` 是 `assemble()` 的重要补充,因为 `assemble()` 默认给的是压缩后的索引和摘要,而不是完整历史正文。@@ -273,12 +310,19 @@ Resource 和 skill 保持两个入口,因为它们落在不同 OpenViking 命/add-skill ./skills/install-openviking-memory --wait/ov-search "OpenViking install" --uri viking://resources/openviking-readme/ov-search "memory install skill" --uri viking://user/skills+/ov-recall-trace --turn latest --include-content```Resource 导入支持远程 URL、Git URL、本地文件、本地目录和 zip。OpenViking 内置 parser 覆盖常见文档和媒体类型,例如 Markdown、纯文本、PDF、HTML、Word、PowerPoint、Excel、EPUB、图片、音频和视频。目录导入还支持常见代码、文档和配置扩展名,例如 `.py`、`.js`、`.ts`、`.go`、`.rs`、`.java`、`.cpp`、`.json`、`.yaml`、`.toml`、`.csv`、`.rst`、`.proto`、`.tf`、`.vue`。出于 HTTP 安全边界,插件不会把本地文件系统路径直接发送给 OpenViking 服务端。本地文件和目录会先通过 `/api/v1/resources/temp_upload` 上传;目录会先在本地使用纯 JavaScript zip 实现打包后再上传。+### Recall Trace 与工具结果引用++Recall trace 默认关闭。可通过插件配置 `traceRecall`、`traceRecallPersist`、`traceRecallDir` 等开启,然后使用 `ov_recall_trace` 或 `/ov-recall-trace` 查询。持久化 trace 默认写入 `~/.openclaw/openviking/recall-traces`,并可通过保留天数和查询上限控制扫描范围。++当 OpenViking 将超大工具输出外置时,可见 preview 会包含 `viking://session/<session_id>/tool-results/<tool_result_id>` 引用。使用 `openviking_tool_result_list` 发现 ref,使用 `openviking_tool_result_search` 定位片段,再使用 `openviking_tool_result_read` 结合 `offset`/`limit` 读取原始内容。+## 运行模式diff --git a/examples/openclaw-plugin/adapters/http-transport.ts b/examples/openclaw-plugin/adapters/http-transport.tsnew file mode 100644index 000000000..018e3e1b2--- /dev/null+++ b/examples/openclaw-plugin/adapters/http-transport.ts@@ -0,0 +1,3 @@+export type HttpTransport = (url: string, init: RequestInit) => Promise<Response>;++export const defaultHttpTransport: HttpTransport = (url, init) => fetch(url, init);diff --git a/examples/openclaw-plugin/adapters/resource-packager.ts b/examples/openclaw-plugin/adapters/resource-packager.tsnew file mode 100644index 000000000..3c0a7a05f--- /dev/null+++ b/examples/openclaw-plugin/adapters/resource-packager.ts@@ -0,0 +1,141 @@+import { randomUUID } from "node:crypto";+import { once } from "node:events";+import { createWriteStream } from "node:fs";+import { mkdtemp, readdir, readFile, rm, stat } from "node:fs/promises";+import { tmpdir } from "node:os";+import { basename, dirname, join, relative } from "node:path";++import { Zip, ZipDeflate } from "fflate";++const REMOTE_RESOURCE_PREFIXES = ["http://", "https://", "git@", "ssh://", "git://"];++export type PackagedResourceSource =+ | { kind: "remote"; path: string }+ | { kind: "upload"; uploadPath: string; sourceName?: string; cleanupPath?: string };++export type ResourcePackager = {+ prepareResourceSource(pathOrUrl: string): Promise<PackagedResourceSource>;+ prepareLocalUploadSource(path: string): Promise<PackagedResourceSource>;+ createTempUploadBody(uploadPath: string): Promise<BodyInit>;+ cleanup(source?: PackagedResourceSource): Promise<void>;+};++function toBlobPart(value: Buffer): ArrayBuffer {+ return value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength) as ArrayBuffer;+}++export function isRemoteResourceSource(source: string): boolean {+ return REMOTE_RESOURCE_PREFIXES.some((prefix) => source.startsWith(prefix));+}++export async function cleanupUploadTempPath(path?: string): Promise<void> {+ if (!path) {+ return;+ }+ await rm(path, { force: true }).catch(() => undefined);+ await rm(dirname(path), { recursive: true, force: true }).catch(() => undefined);+}++export async function zipDirectoryForUpload(dirPath: string): Promise<string> {+ const rootStats = await stat(dirPath);+ if (!rootStats.isDirectory()) {+ throw new Error(`Not a directory: ${dirPath}`);+ }++ const zipDir = await mkdtemp(join(tmpdir(), "openviking-openclaw-upload-"));+ const zipPath = join(zipDir, `${basename(dirPath).replace(/[^a-zA-Z0-9._-]/g, "_")}-${randomUUID()}.zip`);+ const output = createWriteStream(zipPath);+ const outputClosed = once(output, "close");+ const outputErrored = once(output, "error").then(([err]) => Promise.reject(err));+ const zip = new Zip((err, chunk, final) => {+ if (err) {+ output.destroy(err);+ return;+ }+ if (chunk?.length) {+ output.write(Buffer.from(chunk));+ }+ if (final) {+ output.end();+ }+ });++ const walk = async (currentDir: string) => {+ const entries = await readdir(currentDir, { withFileTypes: true });+ for (const entry of entries) {+ const fullPath = join(currentDir, entry.name);+ if (entry.isDirectory()) {+ await walk(fullPath);+ continue;+ }+ if (!entry.isFile()) {+ continue;+ }+ const relPath = relative(dirPath, fullPath).split("\\").join("/");+ if (!relPath || relPath.startsWith("../") || relPath.includes("/../")) {+ throw new Error(`Unsafe relative path while zipping: ${relPath}`);+ }+ const file = new ZipDeflate(relPath);+ zip.add(file);+ file.push(new Uint8Array(await readFile(fullPath)), true);+ }+ };+ try {+ await walk(dirPath);+ zip.end();+ await Promise.race([outputClosed, outputErrored]);+ } catch (err) {+ zip.terminate();+ output.destroy(err as Error);+ await cleanupUploadTempPath(zipPath);+ throw err;+ }+ return zipPath;+}++async function prepareLocalUploadSource(path: string, includeSourceName = false): Promise<PackagedResourceSource> {+ const localStats = await stat(path);+ if (localStats.isDirectory()) {+ const uploadPath = await zipDirectoryForUpload(path);+ return {+ kind: "upload",+ uploadPath,+ cleanupPath: uploadPath,+ ...(includeSourceName ? { sourceName: basename(path) } : {}),+ };+ }+ if (!localStats.isFile()) {+ throw new Error(`Path is not a file or directory: ${path}`);+ }+ return { kind: "upload", uploadPath: path };+}++export const defaultResourcePackager: ResourcePackager = {+ async prepareResourceSource(pathOrUrl: string): Promise<PackagedResourceSource> {+ if (isRemoteResourceSource(pathOrUrl)) {+ return { kind: "remote", path: pathOrUrl };+ }+ return prepareLocalUploadSource(pathOrUrl, true);+ },++ async prepareLocalUploadSource(path: string): Promise<PackagedResourceSource> {+ return prepareLocalUploadSource(path, false);+ },++ async createTempUploadBody(uploadPath: string): Promise<BodyInit> {+ const fileBytes = await readFile(uploadPath);+ const form = new FormData();+ form.append(+ "file",+ new Blob([toBlobPart(fileBytes)], { type: "application/octet-stream" }),+ basename(uploadPath),+ );+ return form;+ },++ async cleanup(source?: PackagedResourceSource): Promise<void> {+ if (source?.kind === "upload") {+ await cleanupUploadTempPath(source.cleanupPath);+ }+ },+};diff --git a/examples/openclaw-plugin/auto-recall.ts b/examples/openclaw-plugin/auto-recall.tsindex bfaafbd59..1fe88fa6a 100644--- a/examples/openclaw-plugin/auto-recall.ts+++ b/examples/openclaw-plugin/auto-recall.ts@@ -1,5 +1,5 @@import type { FindResult, FindResultItem, OpenVikingClient } from "./client.js";-import type { ParsedMemoryOpenVikingConfig } from "./config.js";+import type { MemoryOpenVikingConfig } from "./config.js";import type { EffectiveQueryConfig } from "./query-config.js";import {pickMemoriesForInjection,@@ -8,18 +8,20 @@ import {toJsonLog,} from "./memory-ranking.js";import { quickRecallPrecheck, withTimeout } from "./process-manager.js";+import {+ resolveRecallSearchPlan,+ type RecallResourceType,+} from "./registries/recall-resource-types.js";+import {+ type RecallTraceEntry,+ type RecallTraceResult,+} from "./recall-trace.js";import { sanitizeUserTextForCapture } from "./text-utils.js";import { estimateTextTokens } from "./token-estimator.js";-import type {- RecallResourceType,- RecallTraceEntry,- RecallTraceResult,-} from "./recall-trace.js";-import { resolveRecallSearchPlan } from "./recall-trace.js";+const AUTO_RECALL_TIMEOUT_MS = 5_000;const RECALL_QUERY_MAX_CHARS = 4_000;export const AUTO_RECALL_SOURCE_MARKER = "Source: openviking-auto-recall";-export const OPENVIKING_CONTEXT_TAG = "openviking-context";type Logger = {info: (msg: string) => void;@@ -125,16 +127,6 @@ function formatMemoryLine(].join("\n");}-function isExperienceMemory(item: FindResultItem): boolean {- const category = (item.category ?? "").toLowerCase();- return (- item.uri.includes("/memories/experiences/") ||- item.uri.includes("/experiences/") ||- category === "experience" ||- category === "experiences"- );-}-async function resolveMemoryContent(item: FindResultItem,readFn: (uri: string) => Promise<string>,@@ -220,48 +212,24 @@ export async function buildMemoryLinesWithBudget(return { lines, estimatedTokens: totalTokens };}-export function buildLongTermMemorySection(memoryLines: string[]): string {+export function buildRecallContextBlock(memoryLines: string[]): string {return [- "## Long-term Memories",- "",+ "<relevant-memories>",AUTO_RECALL_SOURCE_MARKER,"The following OpenViking memories may be relevant:",...memoryLines,- ].join("\n");-}--export function buildOpenVikingContextBlock(params: {- sections: Array<string | undefined>;-}): string {- const sections = params.sections- .map((section) => section?.trim())- .filter((section): section is string => Boolean(section));- if (sections.length === 0) {- return "";- }- return [- `<${OPENVIKING_CONTEXT_TAG}>`,- sections.join("\n\n"),- `</${OPENVIKING_CONTEXT_TAG}>`,+ "</relevant-memories>",].join("\n");}function newTraceId(): string {- return `auto_recall_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;+ return `recall_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;}-function preview(value: string | undefined | null, maxChars: number): string | undefined {- const normalized = typeof value === "string" ? value.trim().replace(/\s+/g, " ") : "";- if (!normalized) {- return undefined;- }- return normalized.length > maxChars ? normalized.slice(0, maxChars) : normalized;-}--function traceResourceTypeForUri(uri: string | undefined): RecallResourceType {- if (uri?.startsWith("viking://resources")) return "resource";- if (uri?.startsWith("viking://session/") || uri?.includes("/sessions/")) return "session";- return "user";+function preview(value: string | undefined, maxChars: number): string | undefined {+ const trimmed = value?.trim();+ if (!trimmed) return undefined;+ return trimmed.length > maxChars ? trimmed.slice(0, maxChars) : trimmed;}function toTraceResults(items: FindResultItem[], resourceType: RecallResourceType): RecallTraceResult[] {@@ -277,9 +245,10 @@ function toTraceResults(items: FindResultItem[], resourceType: RecallResourceTyp}function boundTraceQuery(query: string, maxChars: number): { query: string; queryTruncated?: boolean } {- return query.length <= maxChars- ? { query }- : { query: query.slice(0, maxChars), queryTruncated: true };+ if (query.length <= maxChars) {+ return { query };+ }+ return { query: query.slice(0, maxChars), queryTruncated: true };}function runtimeFlag(runtimeContext: unknown, key: string): unknown {@@ -340,199 +309,30 @@ export function shouldRecallAgentExperience(input: {return { recall: false, score, reason: score < 0 ? "non_execution" : "below_threshold" };}-function sectionAfter(markdown: string, heading: string): string {- const re = new RegExp(`(?:^|\\n)##\\s+${heading}\\s*\\n([\\s\\S]*?)(?=\\n##\\s+|$)`, "i");- return markdown.match(re)?.[1]?.trim() ?? "";-}--function bulletize(text: string, fallback: string): string[] {- const cleaned = text- .split(/\n+/)- .map((line) => line.replace(/^[-*]\s*/, "").trim())- .filter(Boolean);- const lines = cleaned.length > 0 ? cleaned : [fallback];- return lines.slice(0, 5).map((line) => `- ${line}`);-}--function titleFromUri(uri: string): string {- const raw = decodeURIComponent(uri.split("/").pop() ?? "experience").replace(/\.md$/i, "");- return raw || "experience";-}--function renderExperience(item: FindResultItem, content: string): string | null {- const situation = sectionAfter(content, "Situation");- const approach = sectionAfter(content, "Approach");- const reflect = sectionAfter(content, "Reflect");- const hasStructuredExperience = Boolean(situation || approach || reflect);- if (!hasStructuredExperience && !isExperienceMemory(item)) {- return null;- }-- const score = typeof item.score === "number" ? item.score.toFixed(3) : "n/a";- return [- `### Experience: ${titleFromUri(item.uri)}`,- `Source: ${item.uri}`,- `Score: ${score}`,- "",- "Trigger:",- ...bulletize(situation, item.abstract?.trim() || content.slice(0, 240).trim() || "Similar execution situation."),- "",- "Do:",- ...bulletize(approach, "Use the proven execution path from this experience."),- "",- "Avoid:",- ...bulletize(reflect, "Avoid repeating failure modes called out by this experience."),- "",- "Scope:",- ...bulletize(situation, "Applies to similar agent execution tasks."),- "",- "Check:",- ...bulletize(reflect || approach, "Verify the task outcome before final response."),- ].join("\n");-}--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, 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);- if (!precheck.ok) {- verbose?.(`openviking: skipping agent experience recall because precheck failed (${precheck.reason})`);- return { count: 0, estimatedTokens: 0, skippedReason: precheck.reason };- }-- return withTimeout(- (async () => {- const result = await client.find(queryText, {- targetUri: "viking://user/memories/experiences",- limit: Math.max(expCfg.recallLimit * 4, 12),- scoreThreshold: expCfg.scoreThreshold,- actorPeerId: peerId,- });-- const candidates = (result.memories ?? [])- .filter(isExperienceMemory)- .filter((item, index, self) => index === self.findIndex((m) => m.uri === item.uri))- .slice(0, expCfg.recallLimit);-- if (candidates.length === 0) {- return { count: 0, estimatedTokens: 0, skippedReason: "no_hits" };- }-- const rendered: string[] = [];- let chars = 0;- for (const item of candidates) {- const content = item.level === 2- ? 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;- const projected = chars + (rendered.length > 0 ? 2 : 0) + exp.length;- if (projected > expCfg.maxInjectedChars) continue;- rendered.push(exp);- chars = projected;- }-- if (rendered.length === 0) {- return { count: 0, estimatedTokens: 0, skippedReason: "no_structured_hits" };- }-- const block = [- "## Agent Experiences",- "",- "These are prior execution lessons learned by this agent. Use them as task guidance, not as user facts.",- "",- ...rendered,- ].join("\n");- verbose?.(`openviking: injecting ${rendered.length} agent experiences for trigger=${trigger}`);- return { block, count: rendered.length, estimatedTokens: estimateTokenCount(block) };- })(),- cfg.autoRecallTimeoutMs,- "openviking: agent experience recall timeout",- ).catch((err) => {- logger.warn?.(`openviking: agent experience recall failed: ${String(err)}`);- return { count: 0, estimatedTokens: 0, skippedReason: "failed" };- });-}--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, peerId, queryText, sessionKey, runtimeContext, logger, verbose } = params;- if (!cfg.agentExperience.enabled) {- return { count: 0, estimatedTokens: 0, skippedReason: "disabled" };- }-- const triggerHint = isCronSession(sessionKey, runtimeContext)- ? "cron_start"- : "task_start";- const decision = shouldRecallAgentExperience({- latestUserText: queryText,- sessionKey,- runtimeContext,- triggerHint,- minQueryChars: cfg.agentExperience.minQueryChars,- isBypassed: false,- });- if (!decision.recall) {- return { count: 0, estimatedTokens: 0, skippedReason: decision.reason };- }-- return buildAgentExperienceRecallContext({- cfg,- client,- agentId,- peerId,- queryText,- trigger: decision.trigger ?? "task_start",- logger,- verbose,- });-}--export async function buildLongTermMemoryRecallContext(params: {- cfg: ParsedMemoryOpenVikingConfig;+export async function buildAutoRecallContext(params: {+ cfg: Required<MemoryOpenVikingConfig>;+ queryConfig?: EffectiveQueryConfig;client: OpenVikingClient;agentId: string;- peerId?: string;queryText: string;logger: Logger;verbose?: (message: string) => void;- traceRecorder?: { record(entry: RecallTraceEntry): void };+ traceRecorder?: { record(entry: RecallTraceEntry): void; recordAndFlush?: (entry: RecallTraceEntry) => Promise<unknown> };sessionId?: string;sessionKey?: string;ovSessionId?: string;rawUserTextPreview?: string;queryTruncated?: boolean;- queryConfig?: EffectiveQueryConfig;-}): Promise<{ section?: string; memoryCount: number; estimatedTokens: number }> {- const { cfg, client, agentId, peerId, queryText, logger, verbose } = params;+ resourceTypes?: RecallResourceType[];+}): Promise<{ block?: string; memoryCount: number; estimatedTokens: number }> {+ const { cfg, client, agentId, queryText, logger, verbose } = params;+ const queryConfig = params.queryConfig;if (!cfg.autoRecall || queryText.length < 5) {return { memoryCount: 0, estimatedTokens: 0 };}- const precheck = await quickRecallPrecheck(client);+ const precheck = await quickRecallPrecheck(client, agentId);if (!precheck.ok) {verbose?.(`openviking: skipping auto-recall because precheck failed (${precheck.reason})`);return { memoryCount: 0, estimatedTokens: 0 };@@ -540,66 +340,67 @@ export async function buildLongTermMemoryRecallContext(params: {return withTimeout((async () => {- const queryConfig = params.queryConfig;const candidateLimit = queryConfig?.candidateLimit ?? Math.max(cfg.recallLimit * 4, 20);const scoreThreshold = queryConfig?.scoreThreshold ?? cfg.recallScoreThreshold;const recallLimit = queryConfig?.recallLimit ?? cfg.recallLimit;const maxInjectedChars = queryConfig?.maxInjectedChars ?? cfg.recallMaxInjectedChars;const recallPreferAbstract = queryConfig?.recallPreferAbstract ?? cfg.recallPreferAbstract;- const searchPlan = resolveRecallSearchPlan(queryConfig?.resourceTypes ?? cfg.recallTargetTypes, {+ const searchPlan = resolveRecallSearchPlan(params.resourceTypes ?? queryConfig?.resourceTypes ?? cfg.recallTargetTypes, {ovSessionId: params.ovSessionId,agentId,});- const autoRecallPromises = searchPlan.searches.map(async (search) => {- const started = Date.now();+ const traceSearches: RecallTraceEntry["searches"] = searchPlan.skipped.map((skipped) => ({+ resourceType: skipped.resourceType,+ limit: candidateLimit,+ scoreThreshold: 0,+ durationMs: 0,+ total: 0,+ results: [],+ error: skipped.reason,+ }));+ const autoRecallPromises: Promise<{+ resourceType: RecallResourceType;+ targetUri?: string;+ result?: FindResult;+ durationMs: number;+ }>[] = searchPlan.searches.map(async (search) => {+ const start = Date.now();const result = await client.find(queryText, {targetUri: search.targetUri,limit: candidateLimit,scoreThreshold: 0,contextType: search.contextType,- actorPeerId: peerId,+ actorPeerId: agentId,});return {- search,+ resourceType: search.resourceType,+ targetUri: search.targetUri,result,- durationMs: Date.now() - started,+ durationMs: Date.now() - start,};});- const traceSearches: RecallTraceEntry["searches"] = searchPlan.skipped.map((skipped) => ({- resourceType: skipped.resourceType,- limit: candidateLimit,- scoreThreshold: 0,- durationMs: 0,- total: 0,- results: [],- error: skipped.reason,- }));const autoRecallSettled = await Promise.allSettled(autoRecallPromises);const allMemories: FindResultItem[] = [];- for (let index = 0; index < autoRecallSettled.length; index += 1) {- const s = autoRecallSettled[index]!;- const search = searchPlan.searches[index]!;+ for (const s of autoRecallSettled) {if (s.status === "fulfilled") {- const result = s.value.result;+ const result = s.value.result ?? {};const memories = result.memories ?? [];const resources = result.resources ?? [];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,+ resourceType: s.value.resourceType,+ targetUriInput: s.value.targetUri,limit: candidateLimit,scoreThreshold: 0,durationMs: s.value.durationMs,total: result.total ?? memories.length + resources.length + (result.skills?.length ?? 0),results: [- ...toTraceResults(memories, s.value.search.resourceType),+ ...toTraceResults(memories, s.value.resourceType),...toTraceResults(resources, "resource"),...(result.skills ?? []).map((item): RecallTraceResult => ({uri: item.uri,- resourceType: s.value.search.resourceType,+ resourceType: s.value.resourceType,category: item.category,score: item.score,level: item.level,@@ -610,11 +411,11 @@ export async function buildLongTermMemoryRecallContext(params: {});} else {logger.warn?.(`openviking: auto-recall search failed: ${String(s.reason)}`);+ const failedIndex = traceSearches.length;+ const search = searchPlan.searches[failedIndex - searchPlan.skipped.length];traceSearches.push({- resourceType: search.resourceType,- contextType: search.contextType,- targetUriInput: search.targetUri,- targetUriResolved: search.targetUri,+ resourceType: search?.resourceType ?? "user",+ targetUriInput: search?.targetUri,limit: candidateLimit,scoreThreshold: 0,durationMs: 0,@@ -628,7 +429,7 @@ export async function buildLongTermMemoryRecallContext(params: {const uniqueMemories = allMemories.filter((memory, index, self) =>index === self.findIndex((m) => m.uri === memory.uri));- const leafOnly = uniqueMemories.filter((m) => (!m.level || m.level === 2) && !isExperienceMemory(m));+ const leafOnly = uniqueMemories.filter((m) => !m.level || m.level === 2);const processed = postProcessMemories(leafOnly, {limit: candidateLimit,scoreThreshold,@@ -638,8 +439,9 @@ export async function buildLongTermMemoryRecallContext(params: {categoryWeights: queryConfig.categoryWeights,resourceTypeWeights: queryConfig.resourceTypeWeights,} : undefined);- const recordTrace = (injectedMemories: FindResultItem[], injectedCount: number, estimatedTokens?: number) => {- params.traceRecorder?.record({++ const recordTrace = async (injectedMemories: FindResultItem[], injectedCount: number, estimatedTokens?: number) => {+ const entry: RecallTraceEntry = {schemaVersion: "1.0",traceId: newTraceId(),ts: Date.now(),@@ -653,12 +455,13 @@ export async function buildLongTermMemoryRecallContext(params: {trigger: {rawUserTextPreview: params.rawUserTextPreview,...boundTraceQuery(queryText, cfg.traceRecallQueryMaxChars),+ derivedKeywords: [],queryTruncated: params.queryTruncated || queryText.length > cfg.traceRecallQueryMaxChars,},searches: traceSearches,selected: injectedMemories.map((memory) => ({uri: memory.uri,- resourceType: traceResourceTypeForUri(memory.uri),+ resourceType: memory.uri.startsWith("viking://resources") ? "resource" : undefined,category: memory.category,score: memory.score,abstractPreview: preview(memory.abstract ?? memory.overview, cfg.traceRecallPreviewChars),@@ -670,17 +473,19 @@ export async function buildLongTermMemoryRecallContext(params: {injectedCount,estimatedTokens,},- });+ };+ // Trace persistence is diagnostic best-effort; never put JSONL flush latency on the auto-recall critical path.+ params.traceRecorder?.record(entry);};if (memories.length === 0) {- recordTrace([], 0, 0);+ await recordTrace([], 0, 0);return { memoryCount: 0, estimatedTokens: 0 };}const { lines: memoryLines, estimatedTokens } = await buildMemoryLinesWithBudget(memories,- (uri) => client.read(uri, peerId),+ (uri) => client.read(uri, agentId),{recallPreferAbstract,recallMaxInjectedChars: maxInjectedChars,@@ -692,22 +497,22 @@ export async function buildLongTermMemoryRecallContext(params: {verbose?.(`openviking: skipping auto-recall injection; no complete memories fit maxInjectedChars=${maxInjectedChars}`,);- recordTrace([], 0, 0);+ await recordTrace([], 0, 0);return { memoryCount: 0, estimatedTokens: 0 };}- const section = buildLongTermMemorySection(memoryLines);+ const block = buildRecallContextBlock(memoryLines);verbose?.(- `openviking: injecting ${memoryLines.length} memories (${section.length} chars, ~${estimatedTokens} tokens, maxInjectedChars=${maxInjectedChars})`,+ `openviking: injecting ${memoryLines.length} memories (${block.length} chars, ~${estimatedTokens} tokens, maxInjectedChars=${maxInjectedChars})`,);verbose?.(`openviking: inject-detail ${toJsonLog({ count: memories.length, memories: summarizeInjectionMemories(memories) })}`,);- recordTrace(memories.slice(0, memoryLines.length), memoryLines.length, estimatedTokens);- return { section, memoryCount: memoryLines.length, estimatedTokens };+ await recordTrace(memories.slice(0, memoryLines.length), memoryLines.length, estimatedTokens);+ return { block, memoryCount: memoryLines.length, estimatedTokens };})(),- cfg.autoRecallTimeoutMs,+ AUTO_RECALL_TIMEOUT_MS,"openviking: auto-recall search timeout",);}diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.tsindex 8466cf27d..d6d2f932b 100644--- a/examples/openclaw-plugin/client.ts+++ b/examples/openclaw-plugin/client.ts@@ -7,6 +7,12 @@ import { basename, dirname, join, relative } from "node:path";import { Zip, ZipDeflate } from "fflate";+import { defaultHttpTransport, type HttpTransport } from "./adapters/http-transport.js";+import {+ defaultResourcePackager,+ type ResourcePackager,+} from "./adapters/resource-packager.js";+export type FindResultItem = {uri: string;level?: number;@@ -33,6 +39,13 @@ function userSessionUri(sessionId: string): string {return `viking://user/sessions/${encodeURIComponent(sessionId)}`;}+export type OpenVikingClientOptions = {+ transport?: HttpTransport;+ resourcePackager?: ResourcePackager;+ now?: () => number;+ sleep?: (ms: number) => Promise<void>;+};+export type CommitSessionResult = {session_id: string;/** "accepted" (async), "completed", "failed", or "timeout" (wait mode). */@@ -240,6 +253,11 @@ async function cleanupUploadTempPath(path?: string): Promise<void> {}export class OpenVikingClient {+ private readonly transport: HttpTransport;+ private readonly now: () => number;+ private readonly sleep: (ms: number) => Promise<void>;+ private readonly resourcePackager: ResourcePackager;+constructor(private readonly baseUrl: string,private readonly apiKey: string,@@ -250,7 +268,19 @@ export class OpenVikingClient {private readonly userId: string = "",/** When set, logs routing for find + session writes (tenant headers + paths; never apiKey). */private readonly routingDebugLog?: (message: string) => void,- ) {}+ optionsOrLegacyUserScope: OpenVikingClientOptions | boolean = {},+ _legacyAgentScope?: boolean,+ legacyOptions?: OpenVikingClientOptions,+ ) {+ const options =+ typeof optionsOrLegacyUserScope === "object" && optionsOrLegacyUserScope !== null+ ? optionsOrLegacyUserScope+ : (legacyOptions ?? {});+ this.transport = options.transport ?? defaultHttpTransport;+ this.now = options.now ?? Date.now;+ this.sleep = options.sleep ?? sleep;+ this.resourcePackager = options.resourcePackager ?? defaultResourcePackager;+ }getDefaultAgentId(): string {return this.defaultAgentId;@@ -274,20 +304,28 @@ export class OpenVikingClient {return value || undefined;}+ private resolveDefaultActorPeerHeader(): string {+ const peerPrefix = this.defaultAgentId.trim();+ return peerPrefix ? `${peerPrefix}_main` : "main";+ }+private async emitRoutingDebug(label: string,detail: Record<string, unknown>,+ actorPeerId?: string,): Promise<void> {if (!this.routingDebugLog) {return;}const tenantHeaders = this.resolveTenantHeaders();+ const actorPeerHeader = this.resolveActorPeerHeader(actorPeerId);this.routingDebugLog(`openviking: ${label} ` +JSON.stringify({...detail,X_OpenViking_Account: tenantHeaders.accountId ?? null,X_OpenViking_User: tenantHeaders.userId ?? null,+ X_OpenViking_Actor_Peer: actorPeerHeader ?? null,session_vfs_hint: detail.sessionId? userSessionUri(String(detail.sessionId)): undefined,@@ -323,7 +361,7 @@ export class OpenVikingClient {headers.set("Content-Type", "application/json");}- const response = await fetch(`${this.baseUrl}${path}`, {+ const response = await this.transport(`${this.baseUrl}${path}`, {...init,headers,signal: controller.signal,@@ -347,8 +385,13 @@ export class OpenVikingClient {}}- async healthCheck(requestTimeoutMs?: number): Promise<void> {- await this.request<{ status: string }>("/health", {}, requestTimeoutMs);+ async healthCheck(requestTimeoutMs?: number, actorPeerId?: string): Promise<void> {+ await this.request<{ status: string }>(+ "/health",+ {},+ requestTimeoutMs,+ actorPeerId ?? this.resolveDefaultActorPeerHeader(),+ );}async createSession(@@ -390,6 +433,7 @@ export class OpenVikingClient {contextType?: string | string[];actorPeerId?: string;},+ legacyActorPeerId?: string,): Promise<FindResult> {const targetUri = options.targetUri?.trim().replace(/\/+$/, "") ?? "";const body: {@@ -407,7 +451,7 @@ export class OpenVikingClient {if (targetUri) {body.target_uri = targetUri;}- const actorPeerId = this.resolveActorPeerHeader(options.actorPeerId);+ const actorPeerId = this.resolveActorPeerHeader(options.actorPeerId ?? legacyActorPeerId);const tenantHeaders = this.resolveTenantHeaders();this.routingDebugLog?.(`openviking: find POST ${this.baseUrl}/api/v1/search/find ` +@@ -521,13 +565,7 @@ export class OpenVikingClient {}async uploadTempFile(filePath: string, actorPeerId?: string): Promise<string> {- const fileBytes = await readFile(filePath);- const form = new FormData();- form.append(- "file",- new Blob([toBlobPart(fileBytes)], { type: "application/octet-stream" }),- basename(filePath),- );+ const form = await this.resourcePackager.createTempUploadBody(filePath);const result = await this.request<{ temp_file_id: string }>("/api/v1/resources/temp_upload",{ method: "POST", body: form },@@ -622,23 +660,18 @@ export class OpenVikingClient {body.preserve_structure = input.preserveStructure;}- let cleanupPath: string | undefined;+ let packagedSource: Awaited<ReturnType<ResourcePackager["prepareResourceSource"]>> | undefined;const requestTimeoutMs =input.wait ? resolveWaitRequestTimeoutMs(this.timeoutMs, input.timeout) : undefined;try {- if (isRemoteResourceSource(pathOrUrl)) {- body.path = pathOrUrl;+ packagedSource = await this.resourcePackager.prepareResourceSource(pathOrUrl);+ if (packagedSource.kind === "remote") {+ body.path = packagedSource.path;} else {- const localStats = await stat(pathOrUrl);- let uploadPath = pathOrUrl;- if (localStats.isDirectory()) {- uploadPath = await this.zipDirectoryForUpload(pathOrUrl);- cleanupPath = uploadPath;- body.source_name = basename(pathOrUrl);- } else if (!localStats.isFile()) {- throw new Error(`Path is not a file or directory: ${pathOrUrl}`);+ if (packagedSource.sourceName) {+ body.source_name = packagedSource.sourceName;}- body.temp_file_id = await this.uploadTempFile(uploadPath, actorPeerId);+ body.temp_file_id = await this.uploadTempFile(packagedSource.uploadPath, actorPeerId);}return this.request<AddResourceResult>("/api/v1/resources",@@ -647,7 +680,7 @@ export class OpenVikingClient {actorPeerId,);} finally {- await cleanupUploadTempPath(cleanupPath);+ await this.resourcePackager.cleanup(packagedSource);}}@@ -662,21 +695,17 @@ export class OpenVikingClient {wait: input.wait ?? false,timeout: input.timeout,};- let cleanupPath: string | undefined;+ let packagedSource: Awaited<ReturnType<ResourcePackager["prepareLocalUploadSource"]>> | undefined;const requestTimeoutMs =input.wait ? resolveWaitRequestTimeoutMs(this.timeoutMs, input.timeout) : undefined;try {if (hasPath) {const skillPath = input.path!.trim();- const localStats = await stat(skillPath);- let uploadPath = skillPath;- if (localStats.isDirectory()) {- uploadPath = await this.zipDirectoryForUpload(skillPath);- cleanupPath = uploadPath;- } else if (!localStats.isFile()) {+ packagedSource = await this.resourcePackager.prepareLocalUploadSource(skillPath);+ if (packagedSource.kind !== "upload") {throw new Error(`Path is not a file or directory: ${skillPath}`);}- body.temp_file_id = await this.uploadTempFile(uploadPath, actorPeerId);+ body.temp_file_id = await this.uploadTempFile(packagedSource.uploadPath, actorPeerId);} else {body.data = input.data;}@@ -687,7 +716,7 @@ export class OpenVikingClient {actorPeerId,);} finally {- await cleanupUploadTempPath(cleanupPath);+ await this.resourcePackager.cleanup(packagedSource);}}@@ -720,20 +749,21 @@ export class OpenVikingClient {abstract?: string;context_type?: "memory" | "resource" | "skill";}>,+ actorPeerId?: string,createdAt?: string,- peerId?: string,+ roleId?: string,): Promise<void> {const body: {role: string;- peer_id?: string;+ role_id?: string;parts: typeof parts;created_at?: string;} = { role, parts };if (createdAt) {body.created_at = createdAt;}- if (peerId) {- body.peer_id = peerId;+ if (roleId) {+ body.role_id = roleId;}await this.emitRoutingDebug("session message POST (with parts)",@@ -741,10 +771,11 @@ export class OpenVikingClient {path: `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,sessionId,role,- peer_id: peerId ?? null,+ role_id: roleId ?? null,partCount: parts.length,created_at: createdAt ?? null,},+ actorPeerId,);await this.request<{ session_id: string }>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`,@@ -752,11 +783,13 @@ export class OpenVikingClient {method: "POST",body: JSON.stringify(body),},+ undefined,+ actorPeerId,);}/** GET session — server auto-creates if absent; returns session meta including message stats and token usage. */- async getSession(sessionId: string): Promise<{+ async getSession(sessionId: string, actorPeerId?: string): Promise<{message_count?: number;commit_count?: number;last_commit_at?: string;@@ -772,6 +805,8 @@ export class OpenVikingClient {}>(`/api/v1/sessions/${encodeURIComponent(sessionId)}`,{ method: "GET" },+ undefined,+ actorPeerId,);}@@ -791,8 +826,9 @@ export class OpenVikingClient {* WM v2: number of most-recent messages to keep live after commit.* Forwarded as `keep_recent_count` in the POST body. 0 (default)* preserves the pre-v2 "archive everything" behavior.- */+ */keepRecentCount?: number;+ agentId?: string;},): Promise<CommitSessionResult> {const keepRecentCount =@@ -807,6 +843,7 @@ export class OpenVikingClient {wait: options?.wait ?? false,keepRecentCount,},+ options?.agentId,);const body: Record<string, unknown> = {};if (keepRecentCount > 0) {@@ -815,6 +852,8 @@ export class OpenVikingClient {const result = await this.request<CommitSessionResult>(`/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`,{ method: "POST", body: JSON.stringify(body) },+ undefined,+ options?.agentId,);if (!options?.wait || !result.task_id) {@@ -822,11 +861,11 @@ export class OpenVikingClient {}// Client-side poll until Phase 2 finishes- const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_PHASE2_POLL_TIMEOUT_MS);+ const deadline = this.now() + (options.timeoutMs ?? DEFAULT_PHASE2_POLL_TIMEOUT_MS);const pollInterval = 500;- while (Date.now() < deadline) {- await sleep(pollInterval);- const task = await this.getTask(result.task_id).catch(() => null);+ while (this.now() < deadline) {+ await this.sleep(pollInterval);+ const task = await this.getTask(result.task_id, options.agentId).catch(() => null);if (!task) break;if (task.status === "completed") {const taskResult = (task.result ?? {}) as Record<string, unknown>;@@ -846,30 +885,38 @@ export class OpenVikingClient {}/** Poll a background task by ID. */- async getTask(taskId: string): Promise<TaskResult> {+ async getTask(taskId: string, actorPeerId?: string): Promise<TaskResult> {return this.request<TaskResult>(`/api/v1/tasks/${encodeURIComponent(taskId)}`,{ method: "GET" },+ undefined,+ actorPeerId,);}async getSessionContext(sessionId: string,tokenBudget: number = 128_000,+ actorPeerId?: string,): Promise<SessionContextResult> {return this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/context?token_budget=${tokenBudget}`,{ method: "GET" },+ undefined,+ actorPeerId,);}async getSessionArchive(sessionId: string,archiveId: string,+ actorPeerId?: string,): Promise<SessionArchiveResult> {return this.request(`/api/v1/sessions/${encodeURIComponent(sessionId)}/archives/${encodeURIComponent(archiveId)}`,{ method: "GET" },+ undefined,+ actorPeerId,);}diff --git a/examples/openclaw-plugin/config.ts b/examples/openclaw-plugin/config.tsindex e01c2e700..59d63b995 100644--- a/examples/openclaw-plugin/config.ts+++ b/examples/openclaw-plugin/config.ts@@ -92,9 +92,10 @@ export type MemoryOpenVikingConfig = {/** Runtime config after memoryOpenVikingConfigSchema.parse() has applied defaults. */export type ParsedMemoryOpenVikingConfig = Required<- Omit<MemoryOpenVikingConfig, "agentExperience">+ Omit<MemoryOpenVikingConfig, "agentExperience" | "recallTargetTypes">> & {agentExperience: Required<NonNullable<MemoryOpenVikingConfig["agentExperience"]>>;+ recallTargetTypes: Array<"resource" | "user" | "agent">;};const DEFAULT_BASE_URL = "http://127.0.0.1:1933";diff --git a/examples/openclaw-plugin/context-engine.ts b/examples/openclaw-plugin/context-engine.tsindex 8379ef6c2..9e1899bb5 100644--- a/examples/openclaw-plugin/context-engine.ts+++ b/examples/openclaw-plugin/context-engine.ts@@ -1,41 +1,24 @@-import { createHash } from "node:crypto";-import { DEFAULT_PHASE2_POLL_TIMEOUT_MS } from "./client.js";-import type { OpenVikingClient, OVMemoryPolicy, OVMessage } from "./client.js";-import type { MemoryOpenVikingConfig, ParsedMemoryOpenVikingConfig } from "./config.js";+import type { OpenVikingClient } from "./client.js";+import type { MemoryOpenVikingConfig } from "./config.js";import type { RuntimeQueryConfigStore } from "./query-config.js";import {AUTO_RECALL_SOURCE_MARKER,- buildGatedAgentExperienceRecallContext,- buildLongTermMemoryRecallContext,- buildOpenVikingContextBlock,- prepareRecallQuery,} from "./auto-recall.js";import {compileSessionPatterns,getCaptureDecision,- extractNewTurnMessages,- stripOpenVikingContextInjection,shouldBypassSession,} from "./text-utils.js";-import {- trimForLog,- toJsonLog,-} from "./memory-ranking.js";import type { RecallTraceEntry } from "./recall-trace.js";-import { sanitizeToolUseResultPairing } from "./session-transcript-repair.js";+import { estimateAgentMessageTokens, estimateAgentMessagesTokens } from "./token-estimator.js";+import { openClawSessionToOvStorageId } from "./routing/identity-routing.js";+import type { AgentMessage } from "./services/context-message-adapter.js";import {- estimateAgentMessageTokens,- estimateAgentMessagesTokens,- estimateTextTokens,-} from "./token-estimator.js";--type AgentMessage = {- role?: string;- content?: unknown;- timestamp?: unknown;-};--type ExtractedTurnMessage = ReturnType<typeof extractNewTurnMessages>["messages"][number];+ assembleOpenVikingSession,+ afterTurnOpenVikingSession,+ compactOpenVikingSession,+ commitOpenVikingSession,+} from "./services/context-lifecycle-service.js";type ContextEngineInfo = {id: string;@@ -54,61 +37,6 @@ type IngestResult = {ingested: boolean;};-export function toPeerId(senderId: string | undefined): string | undefined {- if (!senderId) {- return undefined;- }- const normalized = senderId- .trim()- .replace(/[^a-zA-Z0-9_-]+/g, "_")- .replace(/^_+|_+$/g, "")- .replace(/_+/g, "_");- return normalized || undefined;-}--export function resolveMessagePeerId(params: {- peerRole: Required<MemoryOpenVikingConfig>["peer_role"];- role?: string;- personPeerId?: string;- assistantPeerId?: string;-}): string | undefined {- if (params.peerRole === "person" && params.role === "user") {- return toPeerId(params.personPeerId);- }- if (params.peerRole === "assistant" && params.role === "assistant") {- return toPeerId(params.assistantPeerId);- }- return undefined;-}--export function resolveSearchPeerId(params: {- peerRole: Required<MemoryOpenVikingConfig>["peer_role"];- personPeerId?: string;- assistantPeerId?: string;-}): string | undefined {- const role = params.peerRole === "person"- ? "user"- : params.peerRole === "assistant"- ? "assistant"- : undefined;- return resolveMessagePeerId({- ...params,- role,- });-}--export function defaultMemoryPolicyForPeerRole(- peerRole: Required<MemoryOpenVikingConfig>["peer_role"],-): OVMemoryPolicy | undefined {- if (peerRole === "none") {- return undefined;- }- return {- self: { enabled: true },- peer: { enabled: true },- };-}-type IngestBatchResult = {ingestedCount: number;};@@ -181,52 +109,6 @@ type Logger = {error: (msg: string) => void;};-type ExtractedSender = {- found: boolean;- senderId?: string;-};--type ResolvedSender = ExtractedSender & {- source: "runtimeContext" | "promptMetadata" | "none";- senderName?: string;-};--type PromptMetadata = {- senderId?: string;- senderName?: string;-};--type RecallQueryInput = {- text: string;- source: "latestUserMessage" | "prompt" | "none";-};--type AssembleRecall = Awaited<ReturnType<typeof buildLongTermMemoryRecallContext>> & {- queryChars: number;-};--interface ContextBudgets {- archiveMemory: number;- sessionContext: number;- reserved: number;-}--const BUDGET_UNLIMITED = -1;-const ARCHIVE_BUDGET_RATIO = 0.15;-const ARCHIVE_BUDGET_CAP = 8_000;-const RESERVED_MIN = 20_000;-const RESERVED_RATIO = 0.15;-const ARCHIVE_INDEX_TRIM_LIMIT = 10;--function allocateContextBudget(totalBudget: number, instructionTokens = 0): ContextBudgets {- const reserveFloor = totalBudget >= RESERVED_MIN * 2 ? RESERVED_MIN : 0;- const reserved = Math.min(totalBudget, Math.max(totalBudget * RESERVED_RATIO, reserveFloor));- const usableBudget = Math.max(totalBudget - reserved - instructionTokens, 0);- const archiveMemory = Math.min(usableBudget * ARCHIVE_BUDGET_RATIO, ARCHIVE_BUDGET_CAP);- const sessionContext = Math.max(usableBudget - archiveMemory, 0);- return { archiveMemory, sessionContext, reserved };-}-function roughEstimate(messages: AgentMessage[]): number {return estimateAgentMessagesTokens(messages);}@@ -235,29 +117,6 @@ function msgTokenEstimate(msg: AgentMessage): number {return estimateAgentMessageTokens(msg);}-function normalizeTimestamp(value: unknown): string | undefined {- if (typeof value === "number" && Number.isFinite(value)) {- const timestampMs = Math.abs(value) < 100_000_000_000 ? value * 1000 : value;- return new Date(timestampMs).toISOString();- }- return undefined;-}--function pickLatestCreatedAt(messages: AgentMessage[]): string | undefined {- for (let i = messages.length - 1; i >= 0; i -= 1) {- const message = messages[i] as Record<string, unknown>;- const role = typeof message.role === "string" ? message.role : "";- if (!role || role === "system") {- continue;- }- const normalized = normalizeTimestamp(message.timestamp);- if (normalized) {- return normalized;- }- }- return undefined;-}-function messageDigest(messages: AgentMessage[], maxCharsPerMsg = 2000): Array<{role: string; content: string; tokens: number; truncated: boolean}> {return messages.map((msg) => {const m = msg as Record<string, unknown>;@@ -315,11 +174,7 @@ function extractAgentMessageText(message: AgentMessage | undefined): string {}function hasAutoRecallBlock(message: AgentMessage | undefined): boolean {- const text = extractAgentMessageText(message);- return (- text.includes(AUTO_RECALL_SOURCE_MARKER) ||- /<openviking-context\b/i.test(text)- );+ return extractAgentMessageText(message).includes(AUTO_RECALL_SOURCE_MARKER);}function prependTextToMessageContent(content: unknown, text: string): unknown {@@ -350,20 +205,18 @@ function prependTextToMessageContent(content: unknown, text: string): unknown {return text;}-function prependRecallAtIndex(messages: AgentMessage[], index: number, recallBlock: string): AgentMessage[] {- return messages.map((msg, msgIndex) =>- msgIndex === index- ? { ...msg, content: prependTextToMessageContent(msg.content, recallBlock) }- : msg- );-}-function prependRecallToLatestUserMessage(messages: AgentMessage[], recallBlock: string): AgentMessage[] {const latest = messages.at(-1);if (!latest || latest.role !== "user" || hasAutoRecallBlock(latest)) {return messages;}- return prependRecallAtIndex(messages, messages.length - 1, recallBlock);+ return [+ ...messages.slice(0, -1),+ {+ ...latest,+ content: prependTextToMessageContent(latest.content, recallBlock),+ },+ ];}function emitDiag(log: Logger, stage: string, sessionId: string, data: Record<string, unknown>, enabled = true): void {@@ -371,13 +224,6 @@ function emitDiag(log: Logger, stage: string, sessionId: string, data: Record<stlog.info(`openviking: diag ${JSON.stringify({ ts: Date.now(), stage, sessionId, data })}`);}-function totalExtractedMemories(memories?: Record<string, number>): number {- if (!memories || typeof memories !== "object") {- return 0;- }- return Object.values(memories).reduce((sum, count) => sum + (count ?? 0), 0);-}-function validTokenBudget(raw: unknown): number | undefined {if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) {return raw;@@ -385,704 +231,11 @@ function validTokenBudget(raw: unknown): number | undefined {return undefined;}-function extractRuntimeSenderId(- runtimeContext: Record<string, unknown> | undefined,-): ExtractedSender {- if (runtimeContext) {- const senderId = runtimeContext.senderId;- if (typeof senderId === "string") {- const trimmed = senderId.trim();- if (trimmed) {- return {- found: true,- senderId: trimmed,- };- }- }- }- return { found: false };-}--function readStringField(record: Record<string, unknown>, ...keys: string[]): string | undefined {- for (const key of keys) {- const value = record[key];- if (typeof value === "string" && value.trim()) {- return value.trim();- }- }- return undefined;-}--function safeJsonRecord(text: string): Record<string, unknown> | undefined {- try {- const parsed = JSON.parse(text);- return parsed && typeof parsed === "object" && !Array.isArray(parsed)- ? parsed as Record<string, unknown>- : undefined;- } catch {- return undefined;- }-}--function extractJsonFenceAfterLabel(text: string, label: string): Record<string, unknown> | undefined {- const labelIndex = text.indexOf(label);- if (labelIndex < 0) {- return undefined;- }- const rest = text.slice(labelIndex + label.length);- const match = rest.match(/```json\s*([\s\S]*?)\s*```/i);- if (!match?.[1]) {- return undefined;- }- return safeJsonRecord(match[1]);-}--function uniqueString(values: Array<string | undefined>): string | undefined {- const unique = new Set(values.map((value) => value?.trim()).filter(Boolean) as string[]);- return unique.size === 1 ? [...unique][0] : undefined;-}--function extractPromptMetadata(prompt: unknown): PromptMetadata {- if (typeof prompt !== "string" || !prompt.trim()) {- return {};- }-- // Only inspect the OpenClaw-generated metadata preamble before the actual- // message body. This avoids treating user-authored text as identity data.- const bodyMarker = prompt.search(/\n?\[message_id:/i);- const preamble = bodyMarker >= 0 ? prompt.slice(0, bodyMarker) : prompt.slice(0, 3000);- const conversation = extractJsonFenceAfterLabel(preamble, "Conversation info");- const sender = extractJsonFenceAfterLabel(preamble, "Sender");-- const senderId = uniqueString([- conversation ? readStringField(conversation, "sender_id", "senderId") : undefined,- sender ? readStringField(sender, "id", "sender_id", "senderId") : undefined,- ]);- const senderName = uniqueString([- conversation ? readStringField(conversation, "sender", "sender_name", "senderName") : undefined,- sender ? readStringField(sender, "name", "label", "username") : undefined,- ]);-- return { senderId, senderName };-}--function resolveSender(params: {- runtimeContext?: Record<string, unknown>;- prompt?: unknown;-}): ResolvedSender {- const metadata = extractPromptMetadata(params.prompt);- const runtime = extractRuntimeSenderId(params.runtimeContext);- if (runtime.found) {- return { ...runtime, senderName: metadata.senderName, source: "runtimeContext" };- }-- if (metadata.senderId) {- return {- found: true,- senderId: metadata.senderId,- senderName: metadata.senderName,- source: "promptMetadata",- };- }-- return {- found: false,- senderName: metadata.senderName,- source: "none",- };-}--function stripSpeakerPrefix(text: string): string {- return text.replace(/^[^\n::]{1,80}[::]\s*/, "").trim();-}--function expandShortRecallQuery(text: string, senderName?: string): string {- return text.length < 5 && senderName- ? `${senderName} ${text}`- : text;-}--function extractPromptMessageText(prompt: unknown): string {- if (typeof prompt !== "string" || !prompt.trim()) {- return "";- }- const matches = [...prompt.matchAll(/\[message_id:[^\]]+\]\s*([\s\S]*?)(?=\n\s*\[System:|\s+\[System:|$)/gi)];- const raw = matches.at(-1)?.[1]?.trim();- return raw ? stripSpeakerPrefix(raw) : prompt.trim();-}--function resolveRecallQueryInput(params: {- latestMessage?: AgentMessage;- prompt?: unknown;- senderName?: string;- preferPrompt?: boolean;-}): RecallQueryInput {- const promptText = extractPromptMessageText(params.prompt);- if (params.preferPrompt && promptText) {- return { text: expandShortRecallQuery(promptText, params.senderName), source: "prompt" };- }-- if (params.latestMessage?.role === "user") {- const text = extractAgentMessageText(params.latestMessage);- if (text.trim()) {- return { text, source: "latestUserMessage" };- }- }-- if (promptText) {- return { text: expandShortRecallQuery(promptText, params.senderName), source: "prompt" };- }-- return { text: "", source: "none" };-}--/** OpenClaw session UUID (path-safe on Windows). */-const OPENVIKING_OV_SESSION_UUID =- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;--const WINDOWS_BAD_SESSION_SEGMENT = /[:<>"\\/|?\u0000-\u001f]/;--/**- * Map OpenClaw session identity to an OpenViking session_id that is safe as a single- * AGFS path segment on Windows (no `:` etc.). Prefer UUID sessionId when present;- * otherwise derive a stable sha256 from sessionKey.- */-export function openClawSessionToOvStorageId(- sessionId: string | undefined,- sessionKey: string | undefined,-): string {- const sid = typeof sessionId === "string" ? sessionId.trim() : "";- const key = typeof sessionKey === "string" ? sessionKey.trim() : "";-- if (sid && OPENVIKING_OV_SESSION_UUID.test(sid)) {- return sid.toLowerCase();- }- if (key) {- return createHash("sha256").update(key, "utf8").digest("hex");- }- if (sid) {- if (WINDOWS_BAD_SESSION_SEGMENT.test(sid)) {- return createHash("sha256").update(`openclaw-session:${sid}`, "utf8").digest("hex");- }- return sid;- }- throw new Error("openviking: need sessionId or sessionKey for OV session path");-}--/** Normalize a hook/tool session ref (uuid, sessionKey, or already-safe id) for OV storage. */-export function openClawSessionRefToOvStorageId(ref: string): string {- const t = ref.trim();- if (!t) {- throw new Error("openviking: empty session ref");- }- if (OPENVIKING_OV_SESSION_UUID.test(t)) {- return t.toLowerCase();- }- if (WINDOWS_BAD_SESSION_SEGMENT.test(t)) {- return createHash("sha256").update(t, "utf8").digest("hex");- }- return t;-}--/**- * Convert an OpenViking stored message (parts-based format) into one or more- * OpenClaw AgentMessages (content-blocks format).- *- * For assistant messages with ToolParts, this produces:- * 1. The assistant message with canonical toolCall blocks in its content array- * 2. A separate toolResult message per ToolPart (carrying tool_output)- */-export function convertToAgentMessages(msg: { role: string; parts: unknown[] }): AgentMessage[] {- const parts = msg.parts ?? [];- const contentBlocks: Record<string, unknown>[] = [];- const toolCallBlocks: Record<string, unknown>[] = [];- const toolResults: AgentMessage[] = [];-- for (const part of parts) {- if (!part || typeof part !== "object") continue;- const p = part as Record<string, unknown>;-- if (p.type === "text" && typeof p.text === "string") {- contentBlocks.push({ type: "text", text: p.text });- } else if (p.type === "context") {- if (typeof p.abstract === "string" && p.abstract) {- contentBlocks.push({ type: "text", text: p.abstract });- }- } else if (p.type === "tool") {- const toolId = typeof p.tool_id === "string" ? p.tool_id : "";- const toolName = typeof p.tool_name === "string" ? p.tool_name : undefined;- const status = typeof p.tool_status === "string" ? p.tool_status : "unknown";- const output = typeof p.tool_output === "string" ? p.tool_output : "";- const ref = typeof p.tool_output_ref === "string" ? p.tool_output_ref : "";- const originalChars = typeof p.tool_output_original_chars === "number"- ? p.tool_output_original_chars- : undefined;-- if (toolId) {- // Structured path: emit canonical toolCall + toolResult pair (works for any role)- toolCallBlocks.push({- type: "toolCall",- id: toolId,- name: toolName ?? "unknown",- arguments: p.tool_input ?? {},- });-- let resultText = (status === "completed" || status === "error")- ? (output || "(no output)")- : "(interrupted — tool did not complete)";- if (ref && !resultText.includes(ref)) {- const suffix = originalChars !== undefined- ? `\n[tool-result-ref] ${ref} original_chars=${originalChars}`- : `\n[tool-result-ref] ${ref}`;- resultText += suffix;- }- const resultPayload: Record<string, unknown> = {- role: "toolResult",- toolCallId: toolId,- content: [{ type: "text", text: resultText }],- isError: status === "error",- };- if (toolName) {- resultPayload.toolName = toolName;- }- toolResults.push(resultPayload as unknown as AgentMessage);- } else {- // No tool_id: degrade to text block- const fallbackName = toolName ?? "unknown";- const segments = [`[${fallbackName}] (${status})`];- if (p.tool_input) {- try {- segments.push(`Input: ${JSON.stringify(p.tool_input)}`);- } catch {- // non-serializable input, skip- }- }- if (output) {- segments.push(`Output: ${output}`);- }- contentBlocks.push({ type: "text", text: segments.join("\n") });- }- }- }-- const result: AgentMessage[] = [];-- if (msg.role === "assistant") {- // Assistant: text + toolCall in one message, then toolResults- result.push({ role: "assistant", content: [...contentBlocks, ...toolCallBlocks] });- result.push(...toolResults);- } else {- // Non-assistant: emit text as original role, then synthesize assistant(toolCall) + toolResult- const texts = contentBlocks- .filter((b) => b.type === "text")- .map((b) => b.text as string);- if (texts.length > 0) {- result.push({ role: msg.role, content: texts.join("\n") });- } else if (toolCallBlocks.length === 0) {- result.push({ role: msg.role, content: "" });- }- if (toolCallBlocks.length > 0) {- result.push({ role: "assistant", content: toolCallBlocks });- result.push(...toolResults);- }- }-- return result;-}--function isToolOnlyMessage(msg: ExtractedTurnMessage): boolean {- return msg.role === "user" && msg.parts.length > 0 && msg.parts.every((part) => part.type === "tool");-}--function coalesceConsecutiveToolMessages(messages: ExtractedTurnMessage[]): ExtractedTurnMessage[] {- const result: ExtractedTurnMessage[] = [];- let pendingTools: ExtractedTurnMessage | undefined;-- const flush = () => {- if (pendingTools) {- result.push(pendingTools);- pendingTools = undefined;- }- };-- for (const msg of messages) {- if (isToolOnlyMessage(msg)) {- if (!pendingTools) {- pendingTools = { role: "user", parts: [] };- }- pendingTools.parts.push(...msg.parts);- continue;- }- flush();- result.push(msg);- }- flush();- return result;-}--function normalizeAssistantContent(messages: AgentMessage[]): void {- for (let i = 0; i < messages.length; i++) {- const msg = messages[i];- if (msg?.role === "assistant" && typeof msg.content === "string") {- messages[i] = {- ...msg,- content: [{ type: "text", text: msg.content }],- };- }- }-}--function canonicalizeAssistantBlock(block: unknown): unknown {- if (!block || typeof block !== "object") {- return block;- }-- const rec = block as Record<string, unknown>;- const type = typeof rec.type === "string" ? rec.type : "";- if (type === "toolCall") {- if (rec.arguments !== undefined) {- return rec;- }- return {- ...rec,- arguments: rec.input ?? rec.toolInput ?? {},- };- }-- if (type === "toolUse" || type === "functionCall" || type === "tool_call") {- return {- type: "toolCall",- id: rec.id ?? rec.toolCallId ?? rec.toolUseId,- name: rec.name,- arguments: rec.arguments ?? rec.input ?? rec.toolInput ?? {},- };- }-- return rec;-}--function canonicalizeAgentMessages(messages: AgentMessage[]): AgentMessage[] {- let changed = false;- const next = messages.map((msg) => {- if (!msg || typeof msg !== "object") {- return msg;- }-- if (msg.role === "assistant") {- const content = Array.isArray(msg.content)- ? msg.content.map((block) => canonicalizeAssistantBlock(block))- : typeof msg.content === "string"- ? [{ type: "text", text: msg.content }]- : msg.content;-- if (content !== msg.content) {- changed = true;- return { ...msg, content };- }- return msg;- }-- if (msg.role === "toolResult") {- const raw = msg as Record<string, unknown>;- const toolCallId =- (typeof raw.toolCallId === "string" && raw.toolCallId) ||- (typeof raw.toolUseId === "string" && raw.toolUseId) ||- undefined;- const toolName =- typeof raw.toolName === "string" && raw.toolName.trim()- ? raw.toolName.trim()- : undefined;-- const nextMsg = {- ...msg,- ...(toolCallId ? { toolCallId } : {}),- ...(toolName ? { toolName } : {}),- } as AgentMessage;-- if (nextMsg !== msg) {- changed = true;- }- return nextMsg;- }-- return msg;- });-- return changed ? next : messages;-}--export function formatMessageFaithful(msg: OVMessage): string {- const roleTag = `[${msg.role}]`;- if (!msg.parts || msg.parts.length === 0) {- return `${roleTag}: (empty)`;- }-- const sections: string[] = [];- for (const part of msg.parts) {- if (!part || typeof part !== "object") continue;- switch (part.type) {- case "text":- if (part.text) sections.push(part.text);- break;- case "tool": {- const status = part.tool_status ?? "unknown";- const header = `[Tool: ${part.tool_name ?? "unknown"}] (${status})`;- const inputStr = part.tool_input- ? `Input: ${JSON.stringify(part.tool_input, null, 2)}`- : "";- const outputStr = part.tool_output ? `Output:\n${part.tool_output}` : "";- sections.push([header, inputStr, outputStr].filter(Boolean).join("\n"));- break;- }- case "context":- sections.push(- `[Context: ${part.uri ?? "?"}]${part.abstract ? ` ${part.abstract}` : ""}`,- );- break;- default:- sections.push(`[${part.type}]: ${JSON.stringify(part)}`);- }- }-- return `${roleTag}:\n${sections.join("\n\n")}`;-}--function buildSystemPromptAddition(): string {- return [- "## Session Context Guide",- "",- "Your conversation history includes two layers:",- "",- "1. **[Session History Summary]** — A compressed summary of all prior turns",- " in this session. It is organized into structured sections (Key Facts,",- " Timeline, People, etc.). Use it for background and continuity.",- " The summary is lossy: specific details (exact dates, numbers, names,",- " small events) may have been compressed away.",- "",- "2. **Active messages** — The most recent uncompressed turns.",- "",- "**Rules:**",- "- When active messages conflict with the Summary, trust active messages",- " as the newer source of truth.",- "- Do not fabricate details the Summary does not state explicitly.",- "- **CRITICAL: Before answering 'no information' or 'not mentioned',",- " you MUST carefully re-read EVERY section of the [Session History Summary].",- " The answer may be expressed with different wording than the question.",- " Look for synonyms, related facts, and indirect references.**",- "- If the Summary mentions a topic but lacks the specific detail asked,",- " use the `ov_archive_search` tool to grep the original archived messages",- " for the exact detail. Try 2-3 different keywords extracted from the question.",- "- Only conclude information is unavailable AFTER both checking the Summary",- " thoroughly AND searching the archives with at least 2 keyword variations.",- ].join("\n");-}--function buildInstructionPrompt(): { text: string; tokens: number } {- const text = buildSystemPromptAddition();- return { text, tokens: estimateTextTokens(text) };-}--function buildArchiveMemory(- archiveOverview: string | undefined,- _preAbstracts: Array<{ archive_id: string; abstract: string }>,- _budget: number,-): { messages: AgentMessage[]; tokens: number } {- const messages: AgentMessage[] = [];-- if (archiveOverview) {- messages.push({- role: "user",- content: `[Session History Summary]\n${archiveOverview}`,- });- }-- return { messages, tokens: roughEstimate(messages) };-}--/** Merge consecutive assistant messages by concatenating their content arrays. */-export function mergeConsecutiveAssistants(messages: AgentMessage[]): AgentMessage[] {- const result: AgentMessage[] = [];- for (const msg of messages) {- const prev = result[result.length - 1];- if (msg.role === "assistant" && prev?.role === "assistant") {- const prevContent = Array.isArray(prev.content) ? prev.content : [{ type: "text", text: prev.content }];- const currContent = Array.isArray(msg.content) ? msg.content : [{ type: "text", text: msg.content }];- prev.content = [...prevContent, ...currContent] as typeof prev.content;- } else {- result.push({ ...msg });- }- }- return result;-}--/**- * Hoist tool_result blocks to the front of a content array.- *- * The Anthropic / Bedrock / Gemini APIs require tool_result blocks to appear- * at the START of a user message's content array (a tool_result must follow- * the assistant tool_use that produced it). When mergeConsecutiveUsers- * merges two user messages, the previous content's text blocks may end up- * before tool_results from the second message — this function fixes the order.- *- * Same pattern as Claude Code's hoistToolResults in src/utils/messages.ts.- */-function hoistToolResults<T>(content: T[]): T[] {- const toolResults: T[] = [];- const others: T[] = [];- for (const block of content) {- if (- block &&- typeof block === "object" &&- "type" in block &&- (block as { type?: string }).type === "tool_result"- ) {- toolResults.push(block);- } else {- others.push(block);- }- }- return [...toolResults, ...others];-}--/**- * Merge consecutive user messages by concatenating their content arrays.- *- * Mirror of mergeConsecutiveAssistants. Required because Gemini and Anthropic- * APIs reject consecutive same-role messages with stopReason=stop payloads=0- * (empty response). Three independent sources can inject role: "user":- *- * 1. Archive commit: "[Session History Summary]" via buildArchiveMemory- * 2. OpenClaw yield events: "[sessions_yield interrupt]" / "Turn yielded. ..."- * 3. Audio/Telegram metadata: "[Audio] User text: [Telegram <name>...]"- *- * Without merging, these can stack into 2-5 consecutive user turns. The- * 1P Anthropic API would merge server-side, but Bedrock/Gemini won't —- * we merge client-side for wire-format consistency.- *- * Note: this MUST run AFTER sanitizeToolUseResultPairing because that pass- * may strip orphaned tool_use / tool_result blocks and thereby create new- * user-user adjacencies that didn't exist in the input.- *- * Tracks issue #1724.- */-export function mergeConsecutiveUsers(messages: AgentMessage[]): AgentMessage[] {- const result: AgentMessage[] = [];- for (const msg of messages) {- const prev = result[result.length - 1];- if (msg.role === "user" && prev?.role === "user") {- const prevContent = Array.isArray(prev.content) ? prev.content : [{ type: "text", text: prev.content }];- const currContent = Array.isArray(msg.content) ? msg.content : [{ type: "text", text: msg.content }];- prev.content = hoistToolResults([...prevContent, ...currContent]) as typeof prev.content;- } else {- result.push({ ...msg });- }- }- return result;-}--/**- * Defensive role-alternation invariant check.- *- * After mergeConsecutiveUsers + mergeConsecutiveAssistants, the message stream- * should already alternate user/assistant. But sanitizeToolUseResultPairing- * can in rare cases strip a user_with_tool_result message that was the only- * thing separating two assistant messages, leaving an assistant-assistant- * adjacency that upstream merge passes can't fix.- *- * When detected, we insert a placeholder user message — matching Claude Code's- * NO_CONTENT_MESSAGE pattern (see CC src/utils/messages.ts:5375-5388) — to- * preserve the alternation contract that Gemini / Anthropic require.- */-export function ensureAlternation(messages: AgentMessage[]): AgentMessage[] {- const result: AgentMessage[] = [];- for (const msg of messages) {- const prev = result[result.length - 1];- if (prev && prev.role === "assistant" && msg.role === "assistant") {- result.push({- role: "user",- content: "(no content)",- });- }- result.push(msg);- }- return result;-}--function buildSessionContext(- ovMessages: OVMessage[],- budget: number,-): { messages: AgentMessage[]; tokens: number } {- const raw = ovMessages.flatMap((m) => convertToAgentMessages(m));- const messages = mergeConsecutiveAssistants(raw);- const tokens = roughEstimate(messages);- if (budget === BUDGET_UNLIMITED || tokens <= budget) {- return { messages, tokens };- }- const trimmed = [...messages];- while (trimmed.length > 0 && roughEstimate(trimmed) > budget) {- trimmed.shift();- }- return { messages: trimmed, tokens: roughEstimate(trimmed) };-}--function sleep(ms: number): Promise<void> {- return new Promise((resolve) => setTimeout(resolve, ms));-}--const PHASE2_POLL_INTERVAL_MS = 800;-const PHASE2_POLL_MAX_MS = DEFAULT_PHASE2_POLL_TIMEOUT_MS;--/**- * After wait=false commit, Phase2 runs on the server. Poll task until completed/failed/timeout- * so logs show memories_extracted (otherwise it looks like "nothing was saved").- */-async function pollPhase2ExtractionOutcome(- getClient: () => Promise<OpenVikingClient>,- taskId: string,- logger: Logger,- sessionLabel: string,-): Promise<void> {- const deadline = Date.now() + PHASE2_POLL_MAX_MS;- try {- const client = await getClient();- while (Date.now() < deadline) {- await sleep(PHASE2_POLL_INTERVAL_MS);- const task = await client.getTask(taskId).catch((e) => {- logger.warn?.(`openviking: phase2 getTask failed task_id=${taskId}: ${String(e)}`);- return null;- });- if (!task) {- return;- }- const { status } = task;- if (status === "completed") {- logger.info(- `openviking: phase2 completed task_id=${taskId} session=${sessionLabel} ` +- `result=${toJsonLog(task.result ?? {})}`,- );- return;- }- if (status === "failed") {- logger.warn?.(- `openviking: phase2 failed task_id=${taskId} session=${sessionLabel} error=${task.error ?? "unknown"}`,- );- return;- }- }- logger.warn?.(- `openviking: phase2 poll timeout (${PHASE2_POLL_MAX_MS / 1000}s) task_id=${taskId} session=${sessionLabel} — ` +- `check GET /api/v1/tasks/${taskId}`,- );- } catch (e) {- logger.warn?.(`openviking: phase2 poll exception task_id=${taskId}: ${String(e)}`);- }-}-export function createMemoryOpenVikingContextEngine(params: {id: string;name: string;version?: string;- cfg: ParsedMemoryOpenVikingConfig;+ cfg: Required<MemoryOpenVikingConfig>;logger: Logger;getClient: () => Promise<OpenVikingClient>;/** Extra args help match hook-populated routing when OpenClaw provides sessionKey / OV session id. */@@ -1094,7 +247,7 @@ export function createMemoryOpenVikingContextEngine(params: {ovSessionId?: string;}) => void;queryConfigStore?: RuntimeQueryConfigStore;- traceRecorder?: { record(entry: RecallTraceEntry): void };+ traceRecorder?: { record(entry: RecallTraceEntry): void; recordAndFlush?: (entry: RecallTraceEntry) => Promise<unknown> };}): ContextEngineWithCommit {const {id,@@ -1111,7 +264,6 @@ export function createMemoryOpenVikingContextEngine(params: {const diagEnabled = cfg.emitStandardDiagnostics;const bypassSessionPatterns = compileSessionPatterns(cfg.bypassSessionPatterns);- const defaultMemoryPolicy = defaultMemoryPolicyForPeerRole(cfg.peer_role);const diag = (stage: string, sessionId: string, data: Record<string, unknown>) =>emitDiag(logger, stage, sessionId, data, diagEnabled);@@ -1124,41 +276,16 @@ export function createMemoryOpenVikingContextEngine(params: {runtimeContext?: Record<string, unknown>;}): Promise<boolean> {const { sessionId } = params;- const { sessionKey, ovSessionId: ovId } = resolveSessionIdentity(params);- if (isBypassedSession({ sessionId, sessionKey })) {- logger.warn?.(- `openviking: commit skipped because session is bypassed (sessionId=${sessionId}, sessionKey=${sessionKey ?? "none"})`,- );- return false;- }- try {- const client = await getClient();- rememberSessionAgentId?.({- sessionId,- sessionKey,- ovSessionId: ovId,- });- const commitResult = await client.commitSession(ovId, {- wait: true,- keepRecentCount: 0,- });- const memCount = totalExtractedMemories(commitResult.memories_extracted);- if (commitResult.status === "failed") {- logger.warn?.(`openviking: commit Phase 2 failed for session=${sessionId}: ${commitResult.error ?? "unknown"}`);- return false;- }- if (commitResult.status === "timeout") {- logger.warn?.(`openviking: commit Phase 2 timed out for session=${sessionId}, task_id=${commitResult.task_id ?? "none"}`);- return false;- }- logger.info(- `openviking: committed OV session=${sessionId} ovId=${ovId}, archived=${commitResult.archived ?? false}, memories=${memCount}, task_id=${commitResult.task_id ?? "none"}, trace_id=${commitResult.trace_id ?? "none"}`,- );- return true;- } catch (err) {- logger.warn?.(`openviking: commit failed for session=${sessionId}: ${String(err)}`);- return false;- }+ const { sessionKey } = resolveSessionIdentity(params);+ return commitOpenVikingSession({+ sessionId,+ sessionKey,+ getClient,+ logger,+ rememberSessionAgentId,+ resolveAgentId,+ isBypassedSession,+ });}function extractSessionKey(runtimeContext: Record<string, unknown> | undefined): string | undefined {@@ -1192,122 +319,6 @@ export function createMemoryOpenVikingContextEngine(params: {};}- function extractRuntimeAgentId(- runtimeContext: Record<string, unknown> | undefined,- ): string | undefined {- if (!runtimeContext) {- return undefined;- }- const agentId = runtimeContext.agentId;- return typeof agentId === "string" && agentId.trim() ? agentId.trim() : undefined;- }-- function assemblePassthrough(- ovSessionId: string,- reason: string,- liveMessages: AgentMessage[],- originalTokens: number,- extra?: Record<string, unknown>,- ): AssembleResult {- diag("assemble_result", ovSessionId, {- passthrough: true,- reason,- outputMessagesCount: liveMessages.length,- inputTokenEstimate: originalTokens,- estimatedTokens: originalTokens,- tokensSaved: 0,- savingPct: 0,- ...extra,- });- return { messages: liveMessages, estimatedTokens: originalTokens };- }-- function buildAssembledContext(- overview: string | undefined,- preAbstracts: Array<{ archive_id: string; abstract: string }>,- ovMessages: OVMessage[],- tokenBudget: number,- ovSessionId: string,- ): {- sanitized: AgentMessage[];- archive: { messages: AgentMessage[]; tokens: number };- session: { messages: AgentMessage[]; tokens: number };- budgets: ContextBudgets;- instruction: { text: string; tokens: number };- } {- const hasArchives = Boolean(overview) || preAbstracts.length > 0;- const instruction = hasArchives ? buildInstructionPrompt() : { text: "", tokens: 0 };-- // 4-layer context partitioning:- // Instruction — system prompt guide (Archive Index / Session History usage)- // Archive — session history summary + per-archive one-line abstracts- // Session — active OV messages converted to AgentMessage format- // Reserved — headroom for model output (not consumed here)- const budgets = allocateContextBudget(tokenBudget, instruction.tokens);- const archive = buildArchiveMemory(overview, preAbstracts, budgets.archiveMemory);- const sessionBudget = Math.max(- tokenBudget - budgets.reserved - instruction.tokens - archive.tokens,- 0,- );- const session = buildSessionContext(ovMessages, sessionBudget);- const assembled = [...archive.messages, ...session.messages];-- logger.info(- `openviking: assemble entering session content for ${ovSessionId}: ` +- JSON.stringify(assembled.map((m) => ({- role: m.role,- content: typeof m.content === "string" ? m.content.substring(0, 100) : "[complex]",- })), null, 2),- );-- normalizeAssistantContent(assembled);- const canonical = canonicalizeAgentMessages(assembled);- // Defense in depth (issue #1724):- // 1) sanitizeToolUseResultPairing may strip orphaned tool_use/tool_result,- // potentially creating new user-user or assistant-assistant adjacencies.- // 2) mergeConsecutiveUsers fixes user-user (mirror of mergeConsecutiveAssistants- // already running inside buildSessionContext).- // 3) ensureAlternation is a final invariant check for the rare- // assistant-assistant case that the merges can't reach.- const sanitized = ensureAlternation(- mergeConsecutiveUsers(- sanitizeToolUseResultPairing(canonical as never[]) as AgentMessage[],- ),- );-- return { sanitized, archive, session, budgets, instruction };- }-- function recallDiagFields(params: {- recall: AssembleRecall;- queryInput: RecallQueryInput;- peerId?: string;- sender?: ResolvedSender;- }): Record<string, unknown> {- return {- autoRecallMemoryCount: params.recall.memoryCount,- autoRecallTokens: params.recall.estimatedTokens,- querySource: params.queryInput.source,- queryChars: params.recall.queryChars,- peerId: params.peerId ?? null,- ...(params.sender- ? {- senderIdFound: params.sender.found,- senderId: params.sender.senderId ?? null,- senderSource: params.sender.source,- }- : {}),- };- }-- function resolveAssembleRecallPeerId(agentId: string, sender: ResolvedSender): string | undefined {- return resolveSearchPeerId({- peerRole: cfg.peer_role,- personPeerId: toPeerId(sender.senderId),- assistantPeerId: agentId,- });- }-return {info: {id,@@ -1329,713 +340,69 @@ export function createMemoryOpenVikingContextEngine(params: {},async assemble(assembleParams): Promise<AssembleResult> {- const { messages } = assembleParams;const tokenBudget = validTokenBudget(assembleParams.tokenBudget) ?? 128_000;- const { sessionKey, ovSessionId: OVSessionId } = resolveSessionIdentity(assembleParams);- const sender = resolveSender({- runtimeContext: assembleParams.runtimeContext,- prompt: assembleParams.prompt,- });- const latestMessage = messages.at(-1);const isMainAssemble =Object.prototype.hasOwnProperty.call(assembleParams, "availableTools") ||Object.prototype.hasOwnProperty.call(assembleParams, "citationsMode") ||Object.prototype.hasOwnProperty.call(assembleParams, "prompt");- const isTransformContextAssemble = !isMainAssemble;-- const originalTokens = roughEstimate(messages);-- rememberSessionAgentId?.({+ return assembleOpenVikingSession({sessionId: assembleParams.sessionId,- sessionKey,- agentId: extractRuntimeAgentId(assembleParams.runtimeContext),- ovSessionId: OVSessionId,- });- diag("assemble_entry", OVSessionId, {- messagesCount: messages.length,- inputTokenEstimate: originalTokens,+ sessionKey: resolveSessionKey(assembleParams),+ messages: assembleParams.messages,tokenBudget,- sessionKey: sessionKey ?? null,- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- senderSource: sender.source,- messages: messageDigest(messages),+ runtimeContext: assembleParams.runtimeContext,+ isMainAssemble,+ cfg,+ getClient,+ logger,+ resolveAgentId,+ rememberSessionAgentId,+ isBypassedSession,+ queryConfigStore,+ traceRecorder,+ diag,+ roughEstimate,+ messageDigest,+ extractAgentMessageText,+ hasAutoRecallBlock,+ prependRecallToLatestUserMessage,});-- if (isBypassedSession({ sessionId: assembleParams.sessionId, sessionKey })) {- return assemblePassthrough(OVSessionId, "session_bypassed", messages, originalTokens);- }-- if (isTransformContextAssemble) {- if (latestMessage?.role !== "user") {- return assemblePassthrough(OVSessionId, "transform_context_non_user_tail", messages, originalTokens, {- latestRole: latestMessage?.role ?? null,- });- }- const longTermRecallEnabled = cfg.autoRecall;- const experienceRecallEnabled = cfg.agentExperience.enabled;- if (!longTermRecallEnabled && !experienceRecallEnabled) {- return assemblePassthrough(OVSessionId, "transform_context_auto_recall_disabled", messages, originalTokens);- }- if (hasAutoRecallBlock(latestMessage)) {- return assemblePassthrough(OVSessionId, "transform_context_recall_already_injected", messages, originalTokens);- }-- const recallQueryInput = resolveRecallQueryInput({- latestMessage,- senderName: sender.senderName,- });- if (recallQueryInput.source === "none") {- return assemblePassthrough(OVSessionId, "transform_context_empty_recall_query", messages, originalTokens);- }-- try {- const client = await getClient();- const routingRef = assembleParams.sessionId ?? sessionKey ?? OVSessionId;- const agentId = resolveAgentId(routingRef, sessionKey, OVSessionId);- const peerId = resolveAssembleRecallPeerId(agentId, sender);- const recallQuery = prepareRecallQuery(recallQueryInput.text);- if (!recallQuery.query || recallQuery.query.length < 5) {- diag("assemble_recall_skip", OVSessionId, {- reason: "empty_or_short_query",- querySource: recallQueryInput.source,- queryChars: recallQuery.finalChars,- peerId: peerId ?? null,- });- return assemblePassthrough(OVSessionId, "transform_context_empty_recall_query", messages, originalTokens);- }- if (recallQuery.truncated) {- logger.info(- `openviking: recall query truncated (` +- `chars=${recallQuery.originalChars}->${recallQuery.finalChars})`,- );- }- const effectiveQuery = queryConfigStore- ? await queryConfigStore.getEffective({- peerId: agentId,- sessionId: assembleParams.sessionId,- sessionKey,- ovSessionId: OVSessionId,- })- : undefined;- const experienceRecall = experienceRecallEnabled- ? await buildGatedAgentExperienceRecallContext({- cfg,- client,- agentId,- peerId,- queryText: recallQuery.query,- sessionKey,- runtimeContext: assembleParams.runtimeContext,- logger,- verbose: (message) => logger.info(message),- })- : { count: 0, estimatedTokens: 0, skippedReason: "disabled" };- const longTermRecall = longTermRecallEnabled- ? await buildLongTermMemoryRecallContext({- cfg,- client,- agentId,- peerId,- queryText: recallQuery.query,- logger,- verbose: (message) => logger.info(message),- traceRecorder,- sessionId: assembleParams.sessionId,- sessionKey,- ovSessionId: OVSessionId,- rawUserTextPreview: recallQuery.query,- queryTruncated: recallQuery.truncated,- queryConfig: effectiveQuery,- })- : { memoryCount: 0, estimatedTokens: 0 };- const longTermRecallWithQuery: AssembleRecall = { ...longTermRecall, queryChars: recallQuery.finalChars };-- const combinedBlock = buildOpenVikingContextBlock({- sections: [experienceRecall.block, longTermRecallWithQuery.section],- });-- if (!combinedBlock) {- return assemblePassthrough(OVSessionId, "transform_context_no_recall_hits", messages, originalTokens, {- ...recallDiagFields({ recall: longTermRecallWithQuery, queryInput: recallQueryInput, peerId }),- experienceCount: experienceRecall.count,- });- }-- const withRecall = prependRecallToLatestUserMessage(messages, combinedBlock);- const estimatedTokens = roughEstimate(withRecall);- diag("assemble_result", OVSessionId, {- passthrough: false,- phase: "transform_context",- outputMessagesCount: withRecall.length,- inputTokenEstimate: originalTokens,- estimatedTokens,- ...recallDiagFields({ recall: longTermRecallWithQuery, queryInput: recallQueryInput, peerId, sender }),- autoRecallExperienceCount: experienceRecall.count,- autoRecallExperienceTokens: experienceRecall.estimatedTokens,- messages: messageDigest(withRecall),- });- return { messages: withRecall, estimatedTokens };- } catch (err) {- logger.warn?.(`openviking: auto-recall failed: ${String(err)}`);- return assemblePassthrough(OVSessionId, "transform_context_recall_failed", messages, originalTokens, {- error: String(err),- });- }- }-- try {- const client = await getClient();- const ctx = await client.getSessionContext(OVSessionId, tokenBudget);-- const preAbstracts = ctx?.pre_archive_abstracts ?? [];- const hasArchives = !!ctx?.latest_archive_overview || preAbstracts.length > 0;- const activeCount = ctx?.messages?.length ?? 0;-- if (!ctx || (!hasArchives && activeCount === 0)) {- return assemblePassthrough(OVSessionId, "no_ov_data", messages, originalTokens, {- archiveCount: 0, activeCount: 0,- });- }- if (!hasArchives && ctx.messages.length < messages.length) {- return assemblePassthrough(OVSessionId, "ov_msgs_fewer_than_input", messages, originalTokens, {- archiveCount: 0, activeCount,- });- }-- const { sanitized, archive, session, budgets, instruction } = buildAssembledContext(- ctx.latest_archive_overview,- preAbstracts,- ctx.messages,- tokenBudget,- OVSessionId,- );-- if (sanitized.length === 0 && messages.length > 0) {- return assemblePassthrough(OVSessionId, "sanitized_empty", messages, originalTokens, {- archiveCount: preAbstracts.length, activeCount,- });- }-- const outputMessages = sanitized;- const assembledTokens = roughEstimate(outputMessages) + instruction.tokens;- const tokensSaved = originalTokens - assembledTokens;- const savingPct = originalTokens > 0 ? Math.round((tokensSaved / originalTokens) * 100) : 0;-- diag("assemble_result", OVSessionId, {- passthrough: false,- archiveCount: preAbstracts.length,- activeCount,- outputMessagesCount: outputMessages.length,- inputTokenEstimate: originalTokens,- estimatedTokens: assembledTokens,- tokensSaved,- savingPct,- archiveTokens: archive.tokens,- archiveBudget: budgets.archiveMemory,- sessionTokens: session.tokens,- sessionBudget: budgets.sessionContext,- reservedBudget: budgets.reserved,- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- senderSource: sender.source,- messages: messageDigest(outputMessages),- });-- return {- messages: outputMessages,- estimatedTokens: assembledTokens,- ...(instruction.text ? { systemPromptAddition: instruction.text } : {}),- };- } catch (err) {- logger.warn?.(- `openviking: assemble failed for session=${OVSessionId}, ` +- `tokenBudget=${tokenBudget}, agentId=${resolveAgentId(OVSessionId)}: ${String(err)}`,- );- diag("assemble_error", OVSessionId, {- error: String(err),- tokenBudget,- agentId: resolveAgentId(OVSessionId),- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- senderSource: sender.source,- });- return { messages, estimatedTokens: roughEstimate(messages) };- }},async afterTurn(afterTurnParams): Promise<void> {- if (!cfg.autoCapture) {- return;- }-- if (afterTurnParams.isHeartbeat) {- return;- }-- try {- const sender = extractRuntimeSenderId(afterTurnParams.runtimeContext);- const { sessionKey, ovSessionId: OVSessionId } = resolveSessionIdentity(afterTurnParams);- const runtimeAgentPeerSource = extractRuntimeAgentId(afterTurnParams.runtimeContext);- if (runtimeAgentPeerSource) {- rememberSessionAgentId?.({- agentId: runtimeAgentPeerSource,- sessionId: afterTurnParams.sessionId,- sessionKey,- ovSessionId: OVSessionId,- });- }- const routingRef =- afterTurnParams.sessionId ?? sessionKey ?? OVSessionId;- const agentId = resolveAgentId(routingRef, sessionKey, OVSessionId);-- if (isBypassedSession({ sessionId: afterTurnParams.sessionId, sessionKey })) {- diag("afterTurn_skip", OVSessionId, {- reason: "session_bypassed",- totalMessages: afterTurnParams.messages?.length ?? 0,- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- });- return;- }-- const messages = afterTurnParams.messages ?? [];- if (messages.length === 0) {- diag("afterTurn_skip", OVSessionId, {- reason: "no_messages",- totalMessages: 0,- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- });- return;- }-- const start =- typeof afterTurnParams.prePromptMessageCount === "number" &&- afterTurnParams.prePromptMessageCount >= 0- ? afterTurnParams.prePromptMessageCount- : 0;-- const { messages: extractedMessagesRaw, newCount } = extractNewTurnMessages(messages, start);- const extractedMessages = coalesceConsecutiveToolMessages(extractedMessagesRaw);-- if (extractedMessages.length === 0) {- diag("afterTurn_skip", OVSessionId, {- reason: "no_new_turn_messages",- totalMessages: messages.length,- prePromptMessageCount: start,- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- });- return;- }-- const turnMessages = messages.slice(start) as AgentMessage[];- const newMessages = turnMessages.filter((m: any) => {- const r = (m as Record<string, unknown>).role as string;- return r === "user" || r === "assistant";- }) as AgentMessage[];- const newMsgFull = messageDigest(newMessages);- const newTurnTokens = newMsgFull.reduce((s, d) => s + d.tokens, 0);-- diag("afterTurn_entry", OVSessionId, {- totalMessages: messages.length,- newMessageCount: newCount,- prePromptMessageCount: start,- newTurnTokens,- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- messages: newMsgFull,- });-- const client = await getClient();- const createdAt = pickLatestCreatedAt(turnMessages);- const senderPeerId = toPeerId(sender.senderId);- if (defaultMemoryPolicy) {- await client.ensureSession(- OVSessionId,- { memoryPolicy: defaultMemoryPolicy },- );- }- // 发送结构化消息:统一 role 为 user,通过 parts 区分类型- for (const msg of extractedMessages) {- const ovParts = msg.parts.map((part) => {- if (part.type === "text") {- // Strip OpenViking-injected context blocks.- const cleaned = stripOpenVikingContextInjection(part.text);- return { type: "text" as const, text: cleaned };- } else {- return {- type: "tool" as const,- tool_id: part.toolCallId,- tool_name: part.toolName,- tool_input: part.toolInput,- tool_output: part.toolOutput,- tool_status: part.toolStatus,- };- }- });-- if (ovParts.length > 0) {- const peerId = resolveMessagePeerId({- peerRole: cfg.peer_role,- role: msg.role,- personPeerId: senderPeerId,- assistantPeerId: agentId,- });- await client.addSessionMessage(- OVSessionId,- msg.role,- ovParts,- createdAt,- peerId,- );- }- }-- const session = await client.getSession(OVSessionId);- const pendingTokens = session.pending_tokens ?? 0;-- if (pendingTokens < cfg.commitTokenThreshold) {- diag("afterTurn_skip", OVSessionId, {- reason: "below_threshold",- pendingTokens,- commitTokenThreshold: cfg.commitTokenThreshold,- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- });- return;- }-- const commitResult = await client.commitSession(OVSessionId, {- wait: false,- keepRecentCount: cfg.commitKeepRecentCount,- });- logger.info(- `openviking: committed session=${OVSessionId}, ` +- `status=${commitResult.status}, archived=${commitResult.archived ?? false}, ` +- `task_id=${commitResult.task_id ?? "none"}, trace_id=${commitResult.trace_id ?? "none"}`,- );-- diag("afterTurn_commit", OVSessionId, {- pendingTokens,- commitTokenThreshold: cfg.commitTokenThreshold,- status: commitResult.status,- archived: commitResult.archived ?? false,- taskId: commitResult.task_id ?? null,- extractedMemories: totalExtractedMemories(commitResult.memories_extracted),- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- });- if (commitResult.task_id && cfg.logFindRequests) {- logger.info(- `openviking: Phase2 memory extraction runs asynchronously on the server (task_id=${commitResult.task_id}). ` +- "memories_extracted appears only after that task completes — not in this immediate response.",- );- void pollPhase2ExtractionOutcome(- getClient,- commitResult.task_id,- logger,- OVSessionId,- );- }- } catch (err) {- logger.warn?.(`openviking: afterTurn failed: ${String(err)}`);- const sender = extractRuntimeSenderId(afterTurnParams.runtimeContext);- diag("afterTurn_error", afterTurnParams.sessionId ?? "(unknown)", {- error: String(err),- senderIdFound: sender.found,- senderId: sender.senderId ?? null,- });- }+ await afterTurnOpenVikingSession({+ sessionId: afterTurnParams.sessionId,+ sessionKey: resolveSessionKey(afterTurnParams),+ messages: afterTurnParams.messages,+ prePromptMessageCount: afterTurnParams.prePromptMessageCount,+ isHeartbeat: afterTurnParams.isHeartbeat,+ runtimeContext: afterTurnParams.runtimeContext,+ cfg,+ getClient,+ logger,+ resolveAgentId,+ rememberSessionAgentId,+ isBypassedSession,+ diag,+ });},async compact(compactParams): Promise<CompactResult> {- const { sessionKey, ovSessionId: OVSessionId } = resolveSessionIdentity(compactParams);const tokenBudget = validTokenBudget(compactParams.tokenBudget) ?? 128_000;- diag("compact_entry", OVSessionId, {+ return compactOpenVikingSession({+ sessionId: compactParams.sessionId,+ sessionKey: resolveSessionKey(compactParams),tokenBudget,- force: compactParams.force ?? false,- currentTokenCount: compactParams.currentTokenCount ?? null,- compactionTarget: compactParams.compactionTarget ?? null,- hasCustomInstructions: typeof compactParams.customInstructions === "string" &&- compactParams.customInstructions.trim().length > 0,+ currentTokenCount: compactParams.currentTokenCount,+ force: compactParams.force,+ compactionTarget: compactParams.compactionTarget,+ customInstructions: compactParams.customInstructions,+ getClient,+ logger,+ resolveAgentId,+ isBypassedSession,+ diag,});-- if (isBypassedSession({ sessionId: compactParams.sessionId, sessionKey })) {- diag("compact_result", OVSessionId, {- ok: true,- compacted: false,- reason: "session_bypassed",- });- return {- ok: true,- compacted: false,- reason: "session_bypassed",- };- }-- const client = await getClient();- const agentId = resolveAgentId(compactParams.sessionId, sessionKey, OVSessionId);- const tokensBeforeOriginal = validTokenBudget(compactParams.currentTokenCount);- let preCommitEstimatedTokens: number | undefined;- if (typeof tokensBeforeOriginal !== "number") {- try {- const preCtx = await client.getSessionContext(OVSessionId, tokenBudget);- if (- typeof preCtx.estimatedTokens === "number" &&- Number.isFinite(preCtx.estimatedTokens)- ) {- preCommitEstimatedTokens = preCtx.estimatedTokens;- }- } catch (preCtxErr) {- logger.info(- `openviking: compact pre-ctx fetch failed for session=${OVSessionId}, ` +- `tokenBudget=${tokenBudget}, agentId=${agentId}: ${String(preCtxErr)}`,- );- }- }-- const tokensBefore = tokensBeforeOriginal ?? preCommitEstimatedTokens ?? -1;-- try {- logger.info(- `openviking: compact committing session=${OVSessionId} (wait=true, tokenBudget=${tokenBudget})`,- );- const commitResult = await client.commitSession(OVSessionId, {- wait: true,- keepRecentCount: 0,- });- const memCount = totalExtractedMemories(commitResult.memories_extracted);-- if (commitResult.status === "failed") {- logger.warn?.(- `openviking: compact commit Phase 2 failed for session=${OVSessionId}: ${commitResult.error ?? "unknown"}`,- );- diag("compact_result", OVSessionId, {- ok: false,- compacted: false,- reason: "commit_failed",- status: commitResult.status,- archived: commitResult.archived ?? false,- taskId: commitResult.task_id ?? null,- error: commitResult.error ?? null,- });- return {- ok: false,- compacted: false,- reason: "commit_failed",- result: {- summary: "",- firstKeptEntryId: "",- tokensBefore: tokensBefore,- tokensAfter: undefined,- details: {- commit: commitResult,- },- },- };- }-- if (commitResult.status === "timeout") {- logger.warn?.(- `openviking: compact commit Phase 2 timed out for session=${OVSessionId}, task_id=${commitResult.task_id ?? "none"}`,- );- diag("compact_result", OVSessionId, {- ok: false,- compacted: false,- reason: "commit_timeout",- status: commitResult.status,- archived: commitResult.archived ?? false,- taskId: commitResult.task_id ?? null,- });- return {- ok: false,- compacted: false,- reason: "commit_timeout",- result: {- summary: "",- firstKeptEntryId: "",- tokensBefore: tokensBefore,- tokensAfter: undefined,- details: {- commit: commitResult,- },- },- };- }-- logger.info(- `openviking: compact committed session=${OVSessionId}, archived=${commitResult.archived ?? false}, memories=${memCount}, task_id=${commitResult.task_id ?? "none"}, trace_id=${commitResult.trace_id ?? "none"}`,- );-- if (!commitResult.archived) {- logger.info(- `openviking: compact no archive for session=${OVSessionId}, ` +- `tokensBefore=${tokensBefore}, tokensAfter=${tokensBefore}`,- );- diag("compact_result", OVSessionId, {- ok: true,- compacted: false,- reason: "commit_no_archive",- status: commitResult.status,- archived: commitResult.archived ?? false,- taskId: commitResult.task_id ?? null,- memories: memCount,- tokensBefore: tokensBefore,- });- return {- ok: true,- compacted: false,- reason: "commit_no_archive",- result: {- summary: "",- tokensBefore: tokensBefore,- tokensAfter: tokensBefore >= 0 ? tokensBefore : undefined,- details: {- commit: commitResult,- },- },- };- }-- let summary = "";- let firstKeptEntryId = commitResult.archive_uri?.split("/").pop() ?? "";- let tokensAfter: number | undefined;- let contextFetchError: string | undefined;-- let ctx: Awaited<ReturnType<typeof client.getSessionContext>> | undefined;- try {- ctx = await client.getSessionContext(OVSessionId, tokenBudget);- // 打印完整的 getSessionContext 结果- logger.info(- `openviking: compact getSessionContext raw result for ${OVSessionId}: ` +- JSON.stringify(ctx, null, 2),- );- if (typeof ctx.latest_archive_overview === "string") {- summary = ctx.latest_archive_overview.trim();- }- if (- typeof ctx.estimatedTokens === "number" &&- Number.isFinite(ctx.estimatedTokens)- ) {- tokensAfter = ctx.estimatedTokens;- }- // 打印 compact 后重新写入 session 的完整内容- logger.info(- `openviking: compact restored session content for ${OVSessionId}: ` +- `messages=${ctx.messages?.length ?? 0}, ` +- `latestArchiveOverview=${summary.length > 0 ? "present" : "empty"} (${summary.length} chars), ` +- `preArchiveAbstracts=${ctx.pre_archive_abstracts?.length ?? 0}, ` +- `estimatedTokens=${ctx.estimatedTokens}`,- );- if (summary.length > 0) {- logger.info(- `openviking: compact latest_archive_overview for ${OVSessionId}: ${summary.substring(0, 200)}...`,- );- }- if (ctx.messages && ctx.messages.length > 0) {- // 打印所有消息的 role 和 content 摘要- const msgSummary = ctx.messages.map((m: { role?: string; content?: string; parts?: Array<{ type?: string; text?: string }> }) => {- const role = m.role ?? "unknown";- let textPreview = "";- if (m.content) {- textPreview = m.content.substring(0, 80);- } else if (m.parts && m.parts.length > 0) {- const textPart = m.parts.find((p: { type?: string }) => p.type === "text");- textPreview = textPart?.text?.substring(0, 80) ?? JSON.stringify(m.parts).substring(0, 80);- }- return { role, textPreview };- });- logger.info(- `openviking: compact restored messages for ${OVSessionId}: ` +- JSON.stringify(msgSummary),- );- }- } catch (ctxErr) {- contextFetchError = String(ctxErr);- logger.info(- `openviking: compact context fetch failed for session=${OVSessionId}, ` +- `tokenBudget=${tokenBudget}, agentId=${agentId}: ${contextFetchError}`,- );- }-- logger.info(- `openviking: compact tokens session=${OVSessionId}, ` +- `tokensBefore=${tokensBefore}, tokensAfter=${tokensAfter ?? "unknown"}, ` +- `latestArchiveId=${firstKeptEntryId || "none"}`,- );-- diag("compact_result", OVSessionId, {- ok: true,- compacted: true,- reason: "commit_completed",- status: commitResult.status,- archived: commitResult.archived ?? false,- taskId: commitResult.task_id ?? null,- memories: memCount,- tokensBefore: tokensBefore,- tokensAfter: tokensAfter ?? null,- latestArchiveId: firstKeptEntryId || null,- summaryPresent: summary.length > 0,- });- return {- ok: true,- compacted: true,- reason: "commit_completed",- result: {- summary,- firstKeptEntryId,- tokensBefore,- tokensAfter,- details: contextFetchError- ? {- commit: commitResult,- contextError: contextFetchError,- }- : {- commit: commitResult,- },- },- };- } catch (err) {- const errorMessage = String(err);- if (errorMessage.includes("[NOT_FOUND]") && errorMessage.includes("Session not found")) {- logger.info(- `openviking: compact skipped because OV session does not exist ` +- `(session=${OVSessionId}, agentId=${agentId})`,- );- diag("compact_result", OVSessionId, {- ok: true,- compacted: false,- reason: "session_not_found",- error: errorMessage,- });- return {- ok: true,- compacted: false,- reason: "session_not_found",- };- }- logger.warn?.(`openviking: compact commit failed for session=${OVSessionId}: ${errorMessage}`);- diag("compact_error", OVSessionId, {- error: errorMessage,- });- return {- ok: false,- compacted: false,- reason: "commit_error",- result: {- summary: "",- firstKeptEntryId: "",- tokensBefore: tokensBefore,- tokensAfter: undefined,- details: {- error: errorMessage,- },- },- };- }},};}diff --git a/examples/openclaw-plugin/docs/openviking-dynamic-query-config-test-report.md b/examples/openclaw-plugin/docs/openviking-dynamic-query-config-test-report.mdnew file mode 100644index 000000000..632b63b4f--- /dev/null+++ b/examples/openclaw-plugin/docs/openviking-dynamic-query-config-test-report.md@@ -0,0 +1,405 @@+# OpenViking 动态查询配置变更与测试报告++> 日期:2026-06-04+> 分支:`feat/sharClawWithOpenViKing`+> 仓库:`iaasng/arkclaw-openviking-plugin`+> 结论:本次动态查询配置能力、URI 详情 API、最近 ov_search 简化清单 API 已完成实现与二次验收;全量测试、类型检查、生产构建、生产风格稳定性模拟均通过。++## 1. 本次变更总结++本次变更围绕 OpenViking 插件的“查询参数运行期动态配置”展开,目标是支持不重启 OpenClaw 即可调整召回数量、候选数量、阈值、资源范围和排序权重,并支持 claw 与 session 两级粒度。整体能力由新增运行期配置存储、召回链路接入、命令入口、Gateway 查询接口和测试保障共同组成。++### 1.1 核心能力++| 能力 | 说明 | 关键实现位置 |+|---|---|---|+| 运行期动态配置 | 新增 `RuntimeQueryConfigStore`,负责参数归一化、分层合并、持久化、热加载、异常容错 | `query-config.ts:173` |+| 分层优先级 | 合并顺序为 request > session > claw > static config > default,并输出字段来源 `sources` | `query-config.ts:263` |+| claw / session 粒度 | claw 以 `agentId` 为 key;session 优先 `ovSessionId`,其次 `sessionId`,再次 `sessionKey` | `query-config.ts:158`、`query-config.ts:367` |+| 自动召回接入 | assemble 阶段获取有效查询配置,传入自动召回链路 | `context-engine.ts:891` |+| 显式工具接入 | `memory_recall`、`ov_search` 使用运行期有效配置作为默认值,请求参数仍可覆盖 | `index.ts:1218` |+| 排序权重参数化 | `rankingWeights`、`categoryWeights`、`resourceTypeWeights` 参与客户端侧排序 | `memory-ranking.ts` |+| CLI 管理入口 | 新增 `/ov-query-config` get/set/unset/reset | `index.ts:1225`、`index.ts:1748` |+| Gateway URI 详情 | 新增只读详情接口,不重新触发搜索 | `index.ts:945`、`index.ts:1132` |+| Gateway 最近 ov_search 清单 | 从 recall trace 中扁平化最近一次 `ov_search` 结果 | `index.ts:1019`、`index.ts:1133` |+| 安装脚本修复 | 修复 resource-only recall 自动配置的 JSON 传参,以及 env 单引号转义 | `scripts/install.sh:242`、`scripts/install.sh:404` |++### 1.2 本次重点修复++| 问题 | 影响 | 修复说明 | 测试覆盖 |+|---|---|---|---|+| session 只设置 `recallLimit` 时错误覆盖 claw 显式 `candidateLimit` | 低优先级显式候选数被高优先级派生值覆盖 | `applyLayer()` 增加 `candidateLimitExplicit` 跟踪 | `tests/ut/query-config.test.ts:78` |+| `/ov-query-config` 不能设置权重参数 | 用户无法运行期调整排序权重 | 增加 `--weight`、`--categoryWeight`、`--resourceTypeWeight`、`--recallPreferAbstract` 解析 | `tests/ut/tools.test.ts:415` |+| 空 patch 覆盖已有配置 | 用户传未知参数会把已有 scope 配置清空 | 空归一化结果直接报错,不落库 | `tests/ut/tools.test.ts:443` |+| install.sh JSON 转义错误 | `openclaw config set` 收到非法 JSON 字符串 | 改为传入 `'["resource"]'` 的实际 JSON 文本 | `tests/ut/package-install-contract.test.ts` |+| 初始 load 与 set 并发竞态 | 插件注册后首次写入可能被旧文件覆盖 | 写操作等待 in-flight initial load | `tests/ut/query-config.test.ts:116` |+| 持久化队列失败后不可恢复 | 一次磁盘/权限错误会让后续写入永久失败 | rejected queue 自动恢复,当前失败仍向调用方抛出 | `tests/ut/query-config.test.ts:141` |+| env 文件单引号转义错误 | 包含单引号的 API key / URL 可能生成不可 source 的 env 文件 | 使用 shell 单引号规范转义 `'\\''` 等价片段(实际输出为 ` '\'' `) | `tests/ut/package-install-contract.test.ts` |++## 2. 新增动态配置规则++### 2.1 生效优先级++每次自动召回、`memory_recall`、`ov_search` 执行前都会生成一次有效配置。字段级优先级如下:++```text+request 覆盖参数+ > session 运行期配置+ > claw 运行期配置+ > plugins.entries.openviking.config 静态配置+ > 代码默认值+```++说明:++- request 级参数只影响当前调用,不写入运行期配置。+- session 级配置只影响当前会话,优先匹配 `ovSessionId`,再匹配 `sessionId`,最后匹配 `sessionKey`。+- claw 级配置以当前 `agentId` 为作用域,影响该 claw 下后续所有 session。+- `sources` 会标记字段来源,便于排查“为什么当前召回数量/阈值/权重是这个值”。++### 2.2 字段合并规则++| 类型 | 规则 |+|---|---|+| 标量字段 | 高优先级覆盖低优先级,如 `recallLimit`、`scoreThreshold` |+| 数组字段 | 整体覆盖,不拼接,如 `resourceTypes` |+| 对象字段 | 浅合并,如 `rankingWeights`、`categoryWeights`、`resourceTypeWeights` |+| `candidateLimit` | 显式设置优先于 `recallLimit * candidateMultiplier` 派生值;且最终保证 `candidateLimit >= recallLimit` |+| 非法数值 | 归一化时 clamp 到允许范围;非法 `targetUri` 会报错 |+| 持久化文件损坏 | 保留 last known-good 内存配置,不阻断查询链路 |++### 2.3 支持字段与范围++| 字段 | 语义 | 范围/约束 | 默认来源 |+|---|---|---|---|+| `recallLimit` | 最终注入或展示结果数 | 1-50 | 静态 `recallLimit` |+| `candidateLimit` | 每个 target URI 的候选检索数 | 1-200 | 派生值 |+| `candidateMultiplier` | 候选数倍数,候选数 = `recallLimit * candidateMultiplier` | 1-20 | 4 |+| `scoreThreshold` | 客户端后处理分数阈值 | 0-1 | 静态 `recallScoreThreshold` |+| `maxInjectedChars` | 自动召回注入字符预算 | 100-50000 | 静态 `recallMaxInjectedChars` |+| `recallPreferAbstract` | 是否优先使用 abstract 注入 | boolean | 静态 `recallPreferAbstract` |+| `resourceTypes` | 默认搜索范围 | `resource` / `user` / `agent` | 静态 `recallTargetTypes` |+| `targetUri` | 强制搜索单一 URI | 必须以 `viking://` 开头 | 无 |+| `ovSearchLimit` | `ov_search` 默认返回数 | 1-100 | 10 |+| `rankingWeights.baseScore` | 语义分权重 | 0-2 | 1 |+| `rankingWeights.leaf` | 叶子节点加权 | 0-2 | 0.12 |+| `rankingWeights.event` | 事件类加权 | 0-2 | 0.1 |+| `rankingWeights.preference` | 偏好类加权 | 0-2 | 0.08 |+| `rankingWeights.lexicalOverlapMax` | 词面重叠最大加权 | 0-2 | 0.2 |+| `resourceTypeWeights` | 按资源类型加权 | -1 到 2 | 空对象 |+| `categoryWeights` | 按 category 加权 | -1 到 2 | 空对象 |++### 2.4 持久化与热加载++运行期配置可以配置持久化路径:++```json+{+ "plugins": {+ "entries": {+ "openviking": {+ "config": {+ "runtimeQueryConfigPath": "/path/to/runtime-query-config.json"+ }+ }+ }+ }+}+```++文件结构:++```json+{+ "schemaVersion": "1.0",+ "updatedAt": 1780520000000,+ "claws": {+ "main": {+ "params": { "recallLimit": 8, "candidateLimit": 80 },+ "updatedAt": 1780520000000,+ "updatedBy": "command",+ "agentId": "main"+ }+ },+ "sessions": {+ "session:oc-session-123": {+ "params": { "scoreThreshold": 0.08 },+ "updatedAt": 1780520000000,+ "updatedBy": "command",+ "agentId": "main"+ }+ }+}+```++## 3. 使用方式++### 3.1 查看当前有效配置++```text+/ov-query-config get --scope session+```++返回内容包含:++- `scope`:当前查看的作用域。+- `effective`:合并后的最终配置。+- `effective.sources`:字段来源,如 `session` / `claw` / `static` / `default`。+- `effective.warnings`:归一化或降级警告。++### 3.2 设置 claw 级默认召回策略++```text+/ov-query-config set --scope claw \+ --recallLimit 4 \+ --candidateLimit 40 \+ --scoreThreshold 0.2 \+ --resourceTypes user,agent+```++效果:当前 claw 下所有 session 默认继承该配置;session 级配置仍可覆盖。++### 3.3 设置 session 级临时策略++```text+/ov-query-config set --scope session \+ --recallLimit 10 \+ --candidateLimit 80 \+ --scoreThreshold 0.08 \+ --resourceTypes resource,user+```++效果:仅当前 session 生效,不影响同 claw 下其他 session。++### 3.4 调整排序权重++```text+/ov-query-config set --scope claw \+ --weight baseScore=0.8,leaf=0.2,preference=0.18,event=0.04,lexicalOverlapMax=0.25 \+ --categoryWeight preferences=0.3,events=-0.1 \+ --resourceTypeWeight user=0.2,resource=0.1+```++说明:++- `--weight` 对应 `rankingWeights`。+- `--categoryWeight` 对应 `categoryWeights`。+- `--resourceTypeWeight` 对应 `resourceTypeWeights`。+- 权重只影响插件客户端侧排序,不改变 OpenViking 服务端搜索算法。++### 3.5 清理字段覆盖++```text+/ov-query-config unset recallLimit scoreThreshold rankingWeights --scope session+```++效果:删除当前 session 的指定字段覆盖,下一次查询回退到 claw 或静态配置。++### 3.6 重置作用域配置++```text+/ov-query-config reset --scope session+/ov-query-config reset --scope claw+```++效果:删除该作用域整条运行期配置。++## 4. API 接口整理++### 4.1 `GET /api/openviking/uri-detail`++用途:按完整 `viking://` URI 查询详情和正文片段。该接口只调用读取能力,不重新发起搜索。++#### 请求示例++```bash+curl --get 'http://127.0.0.1:<gateway-port>/api/openviking/uri-detail' \+ --data-urlencode 'uri=viking://resources/project/spec.md' \+ --data 'includeContent=true' \+ --data 'contentLimit=12000' \+ --data 'offset=0'+```++#### Query 参数++| 参数 | 类型 | 必填 | 默认值 | 说明 |+|---|---|---|---|---|+| `uri` | string | 是 | 无 | 完整 `viking://` URI,必须 URL encode |+| `includeContent` | boolean | 否 | `true` | 是否读取正文 |+| `offset` | number | 否 | 0 | 内容分页起始偏移 |+| `contentLimit` | number | 否 | 20000 | 返回正文最大字符数,范围 1-100000 |+| `agentId` | string | 否 | 当前上下文 agent | 读取时的 agent 路由 |+| `sessionId` | string | 否 | 当前上下文 session | trace / session 上下文关联 |+| `sessionKey` | string | 否 | 当前上下文 sessionKey | trace / session 上下文关联 |+| `ovSessionId` | string | 否 | 当前上下文 ovSessionId | trace / session 上下文关联 |+| `traceId` | string | 否 | 无 | 用于从指定 trace 补充摘要、分数、category 等元信息 |+| `preferTracePreview` | boolean | 否 | `true` | 是否优先复用 trace 预览信息 |++#### 响应字段++| 字段 | 说明 |+|---|---|+| `ok` | 是否成功 |+| `uri` | 请求的完整 URI |+| `uriType` | URI 类型,如 `resource` / `session` / `user_memory` / `agent_memory` / `skill` / `archive` / `unknown` |+| `abstractPreview` | trace 或读取结果摘要预览 |+| `metadata` | category、score、level、resultType、sourceTraceId、source 等展示元信息 |+| `content.text` | 正文片段 |+| `content.offset` | 本次分页起始偏移 |+| `content.limit` | 本次分页限制 |+| `content.returnedChars` | 本次返回字符数 |+| `content.totalChars` | 正文总字符数 |+| `content.hasMore` | 是否还有后续内容 |+| `readStatus` | `not_requested` / `ok` / `read_failed` |+| `warnings` | 非致命警告 |+| `error` | 错误码和错误消息 |++#### 状态码++| 状态码 | 场景 |+|---|---|+| 200 | URI 合法且读取成功,或 `includeContent=false` 只返回元信息 |+| 400 | URI 缺失、非 `viking://`、URI 被展示截断、分页参数非法 |+| 502 | OpenViking read 调用失败 |++### 4.2 `GET /api/openviking/recall-traces/latest-ov-search-list`++用途:获取当前会话最近一次 `ov_search` trace 的扁平化 URI 清单,方便前端展示“上次搜索到了哪些资源”。该接口不会重新发起 `ov_search`。++#### 请求示例++```bash+curl --get 'http://127.0.0.1:<gateway-port>/api/openviking/recall-traces/latest-ov-search-list' \+ --data-urlencode 'sessionId=oc-session-123' \+ --data 'limit=20' \+ --data 'includeSelected=true' \+ --data 'dedupe=true'+```++#### Query 参数++| 参数 | 类型 | 必填 | 默认值 | 说明 |+|---|---|---|---|---|+| `sessionId` | string | 否 | 当前上下文 session | OpenClaw sessionId |+| `sessionKey` | string | 否 | 当前上下文 sessionKey | OpenClaw sessionKey |+| `ovSessionId` | string | 否 | 当前上下文 ovSessionId | OpenViking storage session id |+| `agentId` | string | 否 | 当前上下文 agent | 过滤同 session 下不同 agent 的 trace |+| `limit` | number | 否 | 20 | 返回条数,范围 1-100 |+| `lookup` | string | 否 | `auto` | 当前响应会回显;trace 查询走内存/持久化 fallback |+| `includeSelected` | boolean | 否 | `true` | 是否合并 selected/displayed 结果 |+| `dedupe` | boolean | 否 | `true` | 是否按 URI 去重;selected 优先 |+| `includeSkills` | boolean | 否 | `true` | 是否包含 skill 结果 |+| `strict` | boolean | 否 | `false` | 未找到 trace 时是否返回 404 |++#### 响应字段++| 字段 | 说明 |+|---|---|+| `ok` | 是否成功;非 strict 且无 trace 时仍为 true |+| `lookupLayer` | 查询来源:`memory` / `persistent` / `none` |+| `fallbackUsed` | 是否使用持久化 fallback |+| `query` | 回显查询条件 |+| `trace.traceId` | 命中的 trace ID |+| `trace.ts` / `trace.isoTime` | trace 时间 |+| `trace.triggerQuery` | 触发 ov_search 的 query |+| `items[]` | 扁平化条目 |+| `items[].uri` | 完整 URI |+| `items[].abstractPreview` | 摘要预览 |+| `items[].resourceType` | 资源类型 |+| `items[].resultType` | `memory` / `resource` / `skill` / `archive_match` |+| `items[].category` | 记忆或资源 category |+| `items[].score` | 相关性分数 |+| `items[].source` | `search_result` / `selected` |+| `items[].targetUri` | 来源搜索 target URI |+| `items[].detailUrl` | 可直接打开 URI 详情的 Gateway URL |+| `totalItems` | 返回条目数 |+| `warnings` | 非致命警告 |++#### 状态码++| 状态码 | 场景 |+|---|---|+| 200 | 查询成功;默认未找到 trace 也返回空列表加 warning |+| 400 | `limit` 等参数非法 |+| 404 | `strict=true` 且未找到最近 `ov_search` trace |++## 5. 本次测试范围++### 5.1 覆盖范围++| 范围 | 覆盖内容 |+|---|---|+| 单元测试 | 参数归一化、clamp、分层合并、字段来源、持久化、热加载、unset/reset、session alias 匹配 |+| 命令测试 | `/ov-query-config` set/get/unset/reset、权重参数、空 patch 拒绝 |+| 工具链路测试 | session 配置影响后续 `memory_recall`、`ov_search` 默认 limit/targetUri |+| 自动召回场景测试 | context engine assemble 阶段使用 session 有效配置 |+| 排序测试 | rankingWeights、categoryWeights、resourceTypeWeights 对入选排序生效 |+| Gateway API 测试 | URI detail route、latest ov_search list route、skill 过滤、detailUrl 生成 |+| 安装脚本契约测试 | standalone package contract、resource-only recall 配置、JSON 传参、env 单引号转义 |+| 类型检查 | `tsc -p tsconfig.json` |+| 生产构建 | `tsc -p tsconfig.build.json` |+| 稳定性模拟 | in-flight load serialization、100 session 并发写入、配置文件损坏恢复、写队列失败恢复 |++### 5.2 未执行范围说明++仓库中的 Python e2e 脚本依赖真实 OpenClaw Gateway、OpenViking 服务、LLM 后端和有效 token。当前本地验收环境未提供这些外部运行前提,因此本次未执行会访问真实外部服务的 Python e2e。对应风险已通过全量 Vitest、真实 server 单测、生产风格稳定性模拟和 install dry-run 覆盖本次变更相关链路。++## 6. 测试用例执行情况++### 6.1 聚焦回归测试++| 命令 | 结果 |+|---|---|+| `npm test -- tests/ut/query-config.test.ts` | 通过:9 tests passed |+| `npm test -- tests/ut/tools.test.ts -t "ov-query-config"` | 通过:4 tests passed |+| `npm test -- tests/ut/package-install-contract.test.ts` | 通过:6 tests passed |+| `bash -n scripts/install.sh` | 通过:无语法错误 |++### 6.2 全量测试 / 类型 / 构建++| 命令 | 结果 |+|---|---|+| `npm test` | 通过:29 test files passed,562 tests passed |+| `npm run typecheck` | 通过 |+| `npm run build` | 通过 |++### 6.3 生产风格稳定性模拟++验证命令覆盖以下行为:++1. `load()` 与 `set()` 并发时,写操作等待初始加载,不会被旧文件覆盖。+2. 100 个 session 并发写入后,session 与 claw 配置仍按优先级正确合并。+3. 配置文件被破坏为非法 JSON 后,`reloadIfChanged({ force: true })` 保留 last known-good 内存配置。+4. 持久化路径临时不可写导致一次写入失败后,修复路径后下一次写入可以恢复。+5. install.sh dry-run 对包含单引号的 URL/API key 不崩溃,resource-only recall 配置输出正确。++执行结果:++```text+production-style runtime config stability check passed: in-flight load serialization + 100 concurrent session writes + corrupt-file recovery + write-queue recovery+```++## 7. 质量与风险结论++### 7.1 已关闭风险++- 动态配置优先级已通过单测与场景测试验证。+- `candidateLimit` 显式配置优先级已修复并回归。+- 权重参数 CLI 设置已补齐。+- 空 patch 不再覆盖已有配置。+- 持久化写入采用临时文件 + rename,写队列失败后可恢复。+- 配置文件损坏时保留 last known-good,不影响查询链路。+- install.sh 的 JSON 参数与 env 单引号转义均已覆盖。++### 7.2 后续建议++| 建议 | 优先级 | 说明 |+|---|---|---|+| 增加 Gateway query-config 写接口 | P2 | 当前已实现 CLI 与内部 store;如前端需要可继续补齐 `GET/PUT/DELETE /api/openviking/query-config` |+| 支持 TTL/过期清理 | P2 | 设计文档预留 `expiresAt`,当前主要覆盖 set/unset/reset,不做自动 TTL 管理 |+| 增加真实环境 e2e 流水线 | P2 | 需要 OpenClaw Gateway、OpenViking、LLM、token 的稳定测试环境 |+| 多实例集中配置 | P3 | 当前为单进程/本地文件模型;多 gateway 实例可后续接远程配置服务 |++## 8. 最终结论++本次变更已完成“OpenViking 查询参数动态配置”主链路:支持 claw/session 粒度、支持运行期即时生效、支持配置持久化与热加载、支持召回数量/候选数量/阈值/资源类型/排序权重调整,并新增 URI 详情与最近 ov_search 简化清单 API。经过二次验收和追加复审后,发现的问题均已修复,当前自动化验证全部通过,可以进入提测/评审阶段。diff --git a/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md b/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.mdindex 34e95056c..766811fb0 100644--- a/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md+++ b/examples/openclaw-plugin/docs/openviking-openclaw-plugin-guide.md@@ -19,8 +19,8 @@| 会话历史压缩后细节丢失 | summary 不含原命令、路径、配置值时难以追溯 | `ov_archive_search` / `ov_archive_expand` 回查归档原文 || 大工具结果污染上下文 | 大量工具输出挤占模型窗口 | OpenViking 支持 tool result 外置存储,插件提供读/搜/列工具 || 文档、仓库、URL 无法沉淀为知识库 | Agent 临时读取,跨会话不可复用 | 手动 `/add-resource` 导入 resource,`ov_search` / `ov_read` 检索消费;Agent 可见 `add_resource` 默认禁用 |-| Skill 难以沉淀和语义发现 | 技能依赖本地或手工注入 | `add_skill` 导入到 OpenViking user skill 空间 |-| 多租户/多说话人记忆串用 | 不同 user/peer 可能共用错误上下文 | 插件支持 account/user header,并可用 `peer_role` / `peer_prefix` 把 OpenClaw 说话人写入 OpenViking `peer_id` |+| Skill 难以沉淀和语义发现 | 技能依赖本地或手工注入 | `add_skill` 导入到 OpenViking agent skill 空间 |+| 多租户/多 Agent 记忆串用 | 不同 session/agent 可能共用错误上下文 | 插件按 `sessionId/sessionKey/agentId/peer_prefix` 解析 `X-OpenViking-Actor-Peer`,并支持 account/user header 与 peer identity routing |---@@ -45,8 +45,8 @@| --- | --- || `index.ts` | 插件注册入口;解析配置;注册工具、命令、hook、context engine 和 service || `context-engine.ts` | 实现 ContextEngine:`assemble`、`afterTurn`、`compact`、session ID 映射、消息转换、工作记忆组装 |-| `client.ts` | OpenViking HTTP Client;统一添加认证/租户 header;封装 session、search、resource、skill、tool-result API |-| `config.ts` | 插件配置 schema、默认值、环境变量解析、peer 配置 |+| `client.ts` | OpenViking HTTP Client;统一添加认证/租户/agent header;封装 session、search、resource、skill、tool-result API |+| `config.ts` | 插件配置 schema、默认值、环境变量解析、peer identity routing 配置 || `auto-recall.ts` | 自动召回查询清洗、召回超时控制、记忆块构建与注入 || `memory-ranking.ts` | 召回结果去重、阈值过滤、偏好/事件/词面重合度重排 || `text-utils.ts` | 会话文本清洗、metadata/心跳/命令过滤、增量 turn 消息提取、bypass session pattern |@@ -61,11 +61,11 @@1. OpenClaw 根据插件入口加载 `index.ts` 的默认导出。2. `register(api)` 读取 `api.pluginConfig`,用 `memoryOpenVikingConfigSchema.parse` 解析配置;解析失败时只注册 setup CLI,提示用户运行 setup:`index.ts:558`、`index.ts:576`。-3. 创建 `OpenVikingClient`,注入 `baseUrl`、`apiKey`、超时与租户配置:`index.ts:625`。+3. 创建 `OpenVikingClient`,注入 `baseUrl`、`apiKey`、`peer_prefix`、超时、租户与 peer policy:`index.ts:625`。4. 注册工具、slash command、hook、context engine 与 service:`index.ts:872`、`index.ts:962`、`index.ts:1913`、`index.ts:1945`、`index.ts:1970`。5. Service 启动时调用 `/health` 做一次非阻塞 health check,并输出初始化日志:`index.ts:1970`。-### 4.2 会话 ID 与 peer 路由流程+### 4.2 会话 ID 与 Agent 路由流程OpenClaw 的 `sessionId/sessionKey` 不能总是直接作为 OpenViking 存储路径。插件用 `openClawSessionToOvStorageId` 生成安全稳定的 OpenViking session id:@@ -76,7 +76,7 @@ OpenClaw 的 `sessionId/sessionKey` 不能总是直接作为 OpenViking 存储实现位置:`context-engine.ts:342`。-插件仍会从 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/...` 命名空间。+Agent 路由由 `createSessionAgentResolver` 维护,优先从 session context 解析/记忆 agent,然后根据 `peer_prefix` 生成 `X-OpenViking-Actor-Peer`:`index.ts:470`。字符会经过 `sanitizeOpenVikingAgentIdHeader` 清洗,保证只包含 `[a-zA-Z0-9_-]`:`index.ts:226`。### 4.3 `assemble`:回复前组装上下文@@ -104,7 +104,7 @@ transformContext auto recall 流程:1. 从最新 user message 提取查询文本。2. 清洗 metadata、心跳、已注入记忆块等噪音。3. 快速 precheck,OpenViking 不可用时跳过召回,避免拖慢模型请求。-4. 按 `recallTargetTypes` 生成搜索计划;默认使用 `context_type=memory` 检索当前 user 的 memory 视图。配置了 `peer_role` 时,数据面请求会发送 `X-OpenViking-Actor-Peer`,由服务端把 peer 集合限制到当前 actor peer;显式设为 `resource` 时使用 `context_type=resource`;旧字段 `recallResources=true` 仅在未显式配置 `recallTargetTypes` 时把 `resource` 追加到默认集合。+4. 按 `recallTargetTypes` 并行搜索召回目标;默认搜索 `viking://user/memories`、`agent recall target`,显式设为 `resource` 时只搜索 `viking://resources`;旧字段 `recallResources=true` 仅在未显式配置 `recallTargetTypes` 时把 `resource` 追加到默认集合。5. 去重、阈值过滤、leaf 优先、偏好/时间问题 boost、词面重合度 boost。6. 在 `recallMaxInjectedChars` 限制内构建完整记忆行,不截断单条记忆。7. 用 `<relevant-memories>` 块 prepend 到最新 user message。@@ -202,14 +202,14 @@ transformContext auto recall 流程:| --- | --- | --- || `/add-resource`(手动)/ `add_resource`(opt-in) | 导入本地文件、目录、URL、Git 仓库、媒体附件;`add_resource` 默认不注册,需 `enableAddResourceTool=true` | `viking://resources/...` || `add_skill` / `/add-skill` | 导入 `SKILL.md` 或 skill 目录 | `viking://user/skills/...` |-| `ov_search` / `/ov-search` | 搜索 resources 和 skills | 默认同时搜 resources + user skills |+| `ov_search` / `/ov-search` | 搜索 resources 和 skills | 默认同时搜 resources + agent skills || `ov_read` | 读取 `ov_search` / trace 命中的完整内容 | 只接受精确 `viking://...` OpenViking 虚拟 URI |本地文件/目录不会把原路径直接传给服务端,而是先 temp upload;目录会用纯 JS zip 打包后上传:`client.ts:609`、`client.ts:552`。### 5.6 外置 Tool Result 回读-当 OpenViking 服务端将大工具结果外置为 `viking://user/sessions/.../tool-results/...` 时,插件提供:+当 OpenViking 服务端将大工具结果外置为 `viking://session/.../tool-results/...` 时,插件提供:| 工具 | 用途 || --- | --- |@@ -234,8 +234,9 @@ transformContext auto recall 流程:| `X-API-Key` | `apiKey` / `OPENVIKING_API_KEY` | OpenViking API Key || `X-OpenViking-Account` | `accountId` / `OPENVIKING_ACCOUNT_ID` | Root key 或 trusted 部署需要的租户 account || `X-OpenViking-User` | `userId` / `OPENVIKING_USER_ID` | Root key 或 trusted 部署需要的用户 |+| `X-OpenViking-Actor-Peer` | 当前 session 解析出的 agentId | 用于 peer scope 隔离 |-`peer_role=assistant/person` 时,session message 仍通过请求 body 的 `peer_id` 做消息归因;recall/search/read/import/delete 等数据面请求通过 `X-OpenViking-Actor-Peer` 进入当前 actor peer 视图。当前实现不发送 `X-OpenViking-Agent` header。+注意:配置说明中历史文档可能提到 `X-OpenViking-Key`,当前代码实际发送的是 `X-API-Key`:`client.ts:325`。### 6.2 OpenViking 官方 API 完整清单与插件映射@@ -261,7 +262,7 @@ transformContext auto recall 流程:| --- | --- | --- | --- || `POST /api/v1/search/find` | 快速语义检索,不依赖 session context | 自动召回、`memory_recall`、`ov_search`、`memory_forget` | body: `query`、`target_uri`、`limit`、`score_threshold`;返回 `memories[]`、`resources[]`、`skills[]`,每项含 `uri`、`level`、`abstract`、`score`、`category`、`relations`:`client.ts:428` || `POST /api/v1/search/search` | 带 session context 和 intent analysis 的检索 | 暂未使用 | body 可带 `session_id`;返回 `query_plan` / `query_results`。当前插件为了稳定和低延迟统一用 `find()`,session context 由插件自己组装 |-| `POST /api/v1/search/grep` | 正则/关键词内容搜索 | `ov_archive_search` | body: `uri`、`pattern`、`case_insensitive`、`node_limit`;插件限定在 `viking://user/sessions/{id}/history` 内搜 archive:`client.ts:897` |+| `POST /api/v1/search/grep` | 正则/关键词内容搜索 | `ov_archive_search` | body: `uri`、`pattern`、`case_insensitive`、`node_limit`;插件限定在 `viking://session/{id}/history` 内搜 archive:`client.ts:897` || `POST /api/v1/search/glob` | glob 文件匹配 | 暂未封装 | body: `pattern`、`uri`、`node_limit`;适合按 `**/*.md`、`src/**/*.ts` 找资源路径 |#### 6.2.3 Filesystem / Content@@ -330,7 +331,7 @@ transformContext auto recall 流程:| `PUT /api/v1/admin/accounts/{account_id}/users/{user_id}/role` | ROOT | 修改角色 | 运维使用 || `POST /api/v1/admin/accounts/{account_id}/users/{user_id}/key` | ROOT/ADMIN | 重置用户 API key | key 泄露/轮换时使用 |-认证方式:OpenViking HTTP 支持 `X-API-Key: <key>` 和 `Authorization: Bearer <key>`;插件固定使用 `X-API-Key`。如果服务端启用了多租户且当前 key 需要显式租户上下文,插件还会附加 `X-OpenViking-Account`、`X-OpenViking-User`。+认证方式:OpenViking HTTP 支持 `X-API-Key: <key>` 和 `Authorization: Bearer <key>`;插件固定使用 `X-API-Key`。如果服务端启用了多租户且当前 key 需要显式租户上下文,插件还会附加 `X-OpenViking-Account`、`X-OpenViking-User`、`X-OpenViking-Actor-Peer`。### 6.3 URI 与命名空间@@ -340,11 +341,11 @@ transformContext auto recall 流程:| --- | --- || `viking://user/memories` | 当前用户长期记忆别名 || `viking://resources` | account/resource 知识库 |-| `viking://user/skills` | 当前用户 skill 空间 |-| `viking://user/sessions/{sessionId}/history` | session archive 历史 |-| `viking://user/sessions/{sessionId}/tool-results/{id}` | 外置工具结果 |+| `viking://user/skills` | 当前 agent skill 空间 |+| `viking://session/{sessionId}/history` | session archive 历史 |+| `viking://session/{sessionId}/tool-results/{id}` | 外置工具结果 |-`viking://agent/...` 已由 OpenViking 废弃,当前插件不再把它作为检索目标。session 消息的说话人归因由 `peer_role` / `peer_prefix` 解析出的 `peer_id` 控制;recall/search/read/import/delete 的 peer 视图由 `X-OpenViking-Actor-Peer` 控制。+插件通过 `viking://user/...` 写入和检索 user-scoped memory;OpenViking 会根据请求里的租户身份和 actor peer context 解析这个别名。agent 维度通过 `peer_id` / `X-OpenViking-Actor-Peer` 表达,不再使用旧 agent URI namespace。---@@ -372,7 +373,20 @@ openclaw config get plugins.slots.contextEngine期望结果:`status` 中 `configured=true`、`slotActive=true`、`health.ok=true`,并且 `plugins.slots.contextEngine` 输出 `openviking`。-本仓库示例仅保留 ClawHub / 本地开发安装说明;TOS release 包安装、上传、下载和回滚流程不在 `examples/openclaw-plugin` 范围内。+如果你安装的是 TOS release 包,而不是 ClawHub 包,使用一键安装脚本:++```bash+# 安装 prod 最新版本+curl -fsSL https://arkclaw-openviking.tos-cn-beijing.volces.com/prod/latest.json+bash install.sh --source tos --channel prod --latest \+ --openviking-base-url http://127.0.0.1:1933 \+ --openviking-api-key <OPENVIKING_API_KEY>++# 安装指定版本 / 回滚到指定版本+bash install.sh --source tos --channel prod --version 2026.6.2+```++`scripts/install.sh` 会下载 `latest.json` / `manifest.json`、校验 `openviking.tgz` SHA256、展开插件到 `~/.openclaw/extensions/openviking`、部署随包 skills、更新 `~/.openclaw/openclaw.json`,然后自动尝试 `openclaw gateway restart` 和 `openclaw openviking status --json`:`scripts/install.sh:300`、`scripts/install.sh:175`、`scripts/install.sh:468`。### 7.1 前置要求@@ -620,11 +634,33 @@ openclaw config get plugins.slots.contextEngine- `health.ok=true`- `plugins.slots.contextEngine` 输出 `openviking`-### 7.8 本地安装脚本边界+### 7.8 TOS release 安装脚本用法-`examples/openclaw-plugin` 不包含 TOS release 安装脚本。需要验证本地包时,优先使用 ClawHub 安装或在插件目录内运行 `npm run build` 后用 OpenClaw 本地插件能力加载;TOS 下载、校验、灰度和回滚流程已从本示例中排除。+`scripts/install.sh` 支持四种来源,适合正式安装、灰度、回滚、本地包验证:-构建和安装时应确认运行时依赖 `@sinclair/typebox` 位于 `dependencies`,避免 OpenClaw 加载插件时报缺失依赖。+| 来源 | 命令 | 适用场景 |+| --- | --- | --- |+| `tos` | `bash install.sh --source tos --channel prod --latest` | 从 TOS 安装某环境最新 release |+| `tos + version` | `bash install.sh --source tos --channel prod --version 2026.6.2` | 安装或回滚到指定版本 |+| `tarball` | `bash install.sh --tarball ./output/openviking.tgz` | 安装本地构建产物 |+| `local` | `bash install.sh --source local --tarball ./output/openviking.tgz` | 本地包调试,等价 tarball 路径 |+| `existing` | `bash install.sh --source existing --openviking-base-url ... --openviking-api-key ...` | 不覆盖插件文件,只写配置并重启验证 |++常用参数:++| 参数 | 说明 |+| --- | --- |+| `--channel stg|ppe|prod` | 选择 release 环境 / TOS 前缀,默认 `prod` |+| `--latest` | 使用 `<channel>/latest.json` 指向的版本,默认行为 |+| `--version <version>` / `--rollback-to <version>` | 使用 `<channel>/releases/<version>/manifest.json` |+| `--manifest-url <url>` | 直接指定 manifest 地址,用于临时验证 |+| `--verify-only` | 只下载并校验,不部署、不重启 |+| `--dry-run` | 打印将执行的命令,不真实执行 setup/restart |+| `--openviking-base-url` / `--openviking-api-key` | 安装后直接执行非交互 setup |+| `--recall-target-types resource` | 安装时把默认召回切到 resource-only |+| `--force-slot` | 已有其他 context engine 时强制切换到 `openviking` |++安装脚本会强校验包内运行时依赖 `node_modules/@sinclair/typebox`,避免 OpenClaw 加载插件时报缺失依赖:`scripts/install.sh:187`、`scripts/install.sh:193`。---@@ -682,8 +718,7 @@ openclaw config get plugins.slots.contextEngine| `apiKey` | 环境变量或空 | OpenViking API Key || `accountId` | 空 | Root key/trusted 部署需要 || `userId` | 空 | Root key/trusted 部署需要 |-| `peer_role` | `assistant` | 控制哪些 session message 写 `peer_id`,并为数据面请求提供 actor peer 视图:`none`、`assistant` 或 `person` |-| `peer_prefix` | 空 | `peer_role=assistant` 时 assistant `peer_id` 的可选前缀 |+| `peer_prefix` | 空 | Peer 路由前缀;非空时形成 `<prefix>_<ctx.agentId>` || `targetUri` | `viking://user/memories` | 默认 memory search 目标 || `timeoutMs` | `15000` | HTTP 请求超时 || `autoCapture` | `true` | 是否每轮后写入 OpenViking session |@@ -729,12 +764,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 归因和数据面 actor peer 视图 | `assistant` | 是 | 否 | — | `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` |+| `peer_role` | session peer 归因和 actor-peer 路由 | `assistant` | 是 | 安装脚本/setup 参数支持 | `OPENVIKING_PEER_ROLE`(安装脚本写入 setup 参数) | `none` 关闭 peer 路由;`assistant` 使用 runtime agent;`person` 使用 sender 身份 |+| `peer_prefix` | assistant peer 前缀 | 空 | 是 | 间接支持 | 可通过配置值写 `${ENV}` | 非空时拼成 `<prefix>_<ctx.agentId>`,用于 assistant `peer_id` 与 `X-OpenViking-Actor-Peer` || `targetUri` | `memory_recall` / `memory_forget` 默认搜索范围 | `viking://user/memories` | 是 | 否 | — | 未显式传 `targetUri` 时的默认 memory 搜索位置:`config.ts:275`、`index.ts:1366` || `timeoutMs` | 所有搜索/读取请求超时 | `15000` | 是 | 否 | — | 控制 `find/read/grep/session` 等 HTTP 请求超时:`config.ts:276` || `autoRecall` | 自动召回总开关 | `true` | 是 | 否 | — | 关闭后插件不再在 `assemble()` 阶段自动发起 recall:`config.ts:283`、`context-engine.ts:1132` |-| `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` |+| `recallTargetTypes` | 自动召回 + 默认 `memory_recall` 资源类型集合 | `["user","agent"]` | 是 | 安装脚本/setup 参数支持 | `OPENVIKING_RECALL_TARGET_TYPES`(安装脚本写入 setup 参数) | 当前默认只查 `user` + `agent` 记忆。设置为 `["resource"]` 才会切成 resource-only;可组合 `resource,user,agent`:`config.ts:174`、`config.ts:360` || `recallResources` | 自动召回 + 默认 `memory_recall` resources 兼容开关 | `false` | 是 | 是 | `OPENVIKING_RECALL_RESOURCES` | 旧兼容字段;只有未显式配置 `recallTargetTypes` 时才把 `resource` 追加到默认 `user` + `agent`,不会覆盖显式 resource-only:`config.ts:360` || `recallLimit` | 自动召回 / `memory_recall` 返回条数 | `6` | 是 | 否 | — | 最终注入或展示的 recall 条数上限;内部请求会放大到 `max(limit*4, 20)` 先召回再重排:`config.ts:285`、`auto-recall.ts:181` || `recallScoreThreshold` | 自动召回 / `memory_recall` 过滤阈值 | `0.15` | 是 | 否 | — | 低于阈值的结果会在后处理阶段被丢弃:`config.ts:286`、`auto-recall.ts:218`、`index.ts:1132` |@@ -760,6 +795,8 @@ openclaw config get plugins.slots.contextEngine| `OPENVIKING_API_KEY` | `apiKey` | 指定 OpenViking API key || `OPENVIKING_ACCOUNT_ID` | `accountId` | 指定租户 account || `OPENVIKING_USER_ID` | `userId` | 指定租户 user |+| `OPENVIKING_PEER_ROLE` | `peer_role` | 安装脚本/setup 写入的 peer 身份模式 |+| `OPENVIKING_PEER_PREFIX` | `peer_prefix` | 安装脚本/setup 写入的 assistant peer 前缀 || `OPENVIKING_RECALL_RESOURCES` | `recallResources` | 是否把 resources 纳入自动召回和默认 memory_recall || `OPENVIKING_LOG_ROUTING` | `logFindRequests` | 打开检索/路由日志 || `OPENVIKING_DEBUG` | `logFindRequests` | 同时作为调试总开关,当前也会打开 routing/find 日志 |@@ -786,16 +823,23 @@ openclaw config get plugins.slots.contextEngine#### 9.3.1 Resource-only 召回配置-当前默认召回目标是 memory 类型视图:`["user","agent"]` 作为兼容配置会合并为一次 `context_type=memory` 检索;配置了 actor peer 时由 `X-OpenViking-Actor-Peer` 限制当前 peer 视图。如果你的场景主要是“导入文档 / 知识库问答”,并希望默认召回只查 resources,需要显式配置 `recallTargetTypes`:+当前默认召回目标是用户记忆 + Agent 记忆:`["user","agent"]`。如果你的场景主要是“导入文档 / 知识库问答”,并希望默认召回只查 `viking://resources`,需要显式配置 `recallTargetTypes`:```bashopenclaw config set plugins.entries.openviking.config.recallTargetTypes '["resource"]'openclaw gateway restart```-安装后也可以通过 `openclaw config set` 显式写入;本示例不包含 TOS 安装脚本参数。+安装时也可以直接写入:++```bash+bash install.sh --source tos --channel prod --latest \+ --openviking-base-url http://127.0.0.1:1933 \+ --openviking-api-key <OPENVIKING_API_KEY> \+ --recall-target-types resource+```-注意:`recallResources=true` 是旧兼容加法开关,只会在未显式配置 `recallTargetTypes` 时把 `resource` 追加到默认 memory 视图,默认不会改成 resource-only。+注意:`recallResources=true` 是旧兼容加法开关,只会在未显式配置 `recallTargetTypes` 时把 `resource` 追加到默认 `user` + `agent`,不会把默认召回改成 resource-only。#### 9.3.2 仅通过环境变量快速打开“额外可搜 resources 的自动召回”@@ -855,7 +899,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` | 租户或 actor peer 视图不一致 |+| 同样的 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` |@@ -889,7 +933,7 @@ openclaw gateway restartOPENVIKING_LOG_ROUTING=1 openclaw gateway restart```-日志会打印 account/user header 是否设置、actor peer header、target_uri、query preview、session commit 等信息,但不会打印 apiKey。+日志会打印 `X-OpenViking-Actor-Peer`、account/user header 是否设置、target_uri、query preview、session commit 等信息,但不会打印 apiKey。### 10.3 打开标准诊断日志@@ -949,6 +993,74 @@ GET /api/openviking/recall-traces/<traceId>| `traceRecall=true && traceRecallPersist=false` | 只查当前 gateway 进程内的 ring buffer;重启后丢失 || `traceRecall=true && traceRecallPersist=true` | trace 追加写入按日期分片的 JSONL;重启后按配置预加载最近记录,并可查询 retention 范围内文件 |+#### 10.4.0.1 安装后验证真实 session 的 trace 查询++安装或升级后,建议用 OpenClaw 当前真实 `sessionKey` 验证 `ov_recall_trace`,不要用日期或时间戳人为拼一个 session key 代替线上会话。真实 web session 的 trace 通常同时保存:++- `entry.sessionKey`:OpenClaw 会话 key,例如 `agent:main:web-...`。+- `entry.sessionId` / `entry.ovSessionId`:OpenClaw 会话 UUID。++验证命令:++```bash+SK="$(openclaw status --json | jq -r '+ .sessionKey //+ .session.key //+ .currentSession.key //+ .current_session.key //+ empty+')"++if [ -z "$SK" ]; then+ echo "未从 openclaw status --json 取到 sessionKey" >&2+ openclaw status --json | jq .+ exit 1+fi++TRACE_PARAMS="$(jq -cn \+ --arg sk "$SK" \+ '{+ name: "ov_recall_trace",+ sessionKey: $sk,+ args: {+ turn: "all",+ limit: 5+ }+ }'+)"++TRACE_RESULT="$(openclaw gateway call tools.invoke \+ --params "$TRACE_PARAMS" \+ --json+)"++echo "$TRACE_RESULT" | jq .+COUNT="$(echo "$TRACE_RESULT" | jq -r '.output.details.count // 0')"++if [ "$COUNT" -gt 0 ]; then+ echo "trace 查询验证成功,count=$COUNT"+else+ echo "trace 查询验证失败,count=$COUNT" >&2+ exit 1+fi+```++如果升级前线上仍是旧版本,可临时把业务过滤参数也显式带上,绕过旧版本没有默认使用外层 `params.sessionKey` 的问题:++```json+{+ "name": "ov_recall_trace",+ "sessionKey": "<real-session-key>",+ "args": {+ "turn": "all",+ "limit": 5,+ "sessionKey": "<real-session-key>"+ }+}+```++当前版本默认使用外层 `params.sessionKey` 查询当前 session trace;如果未命中且调用方没有显式设置 `args.sessionKey/sessionId/ovSessionId/traceId`,会继续 fallback 到当前 session 的 `sessionId/ovSessionId`,以兼容已落盘的历史 JSONL。+#### 10.4.1 先打开插件侧可观测配置```bash@@ -1002,13 +1114,13 @@ openviking: inject-detail {"count":2,"memories":[{"uri":"viking://user/default/m如果想把“命中的路径”直接展示给 Agent 或用户,可以让 Agent 显式调用工具:```text-# 查长期记忆,默认查 memory 类型视图;recallTargetTypes 可切换默认范围+# 查长期记忆,默认查 user/agent memories;recallTargetTypes 可切换默认范围memory_recall(query="用户问题关键词", limit=10)# 查导入的文档、URL、目录、仓库资源ov_search(query="用户问题关键词", uri="viking://resources", limit=10)-# 查 OpenViking skills+# 查 agent skillsov_search(query="用户问题关键词", uri="viking://user/skills", limit=10)```@@ -1023,6 +1135,7 @@ ov_search(query="用户问题关键词", uri="viking://user/skills", limit=10)```bashexport OPENVIKING_BASE_URL="http://127.0.0.1:1933"export OPENVIKING_API_KEY="<your-api-key>"+export OPENVIKING_AGENT="<X-OpenViking-Actor-Peer-from-log>"# root key / trusted server 场景按需补充export OPENVIKING_ACCOUNT_ID="<account-id>"@@ -1035,6 +1148,7 @@ export OPENVIKING_USER_ID="<user-id>"headers=(-H "Content-Type: application/json"-H "X-API-Key: $OPENVIKING_API_KEY"+ -H "X-OpenViking-Actor-Peer: $OPENVIKING_AGENT")if [ -n "${OPENVIKING_ACCOUNT_ID:-}" ]; then@@ -1109,7 +1223,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`,自动召回默认使用 `context_type=memory` 查当前 user 的 memory 视图,不会把 `viking://resources` 文档自动注入;resource-only 用 `recallTargetTypes=["resource"]`,默认 memory 视图 + resources 用 `recallResources=true` 或 `recallTargetTypes=["user","agent","resource"]`。+- 如果未显式配置 `recallTargetTypes`,自动召回默认只查 `viking://user/memories` 和 `agent recall target`,不会把 `viking://resources` 文档自动注入;resource-only 用 `recallTargetTypes=["resource"]`,默认记忆 + resources 用 `recallResources=true` 或 `recallTargetTypes=["user","agent","resource"]`。- 如果没查到 recall trace,先检查 `traceRecall=true` 是否已配置并重启 Gateway;`recallTargetTypes` / `recallResources` 不负责启用 trace。- 当前插件没有单独生成“模型最终引用/采纳哪些文档”的 citation 文件;最可靠的依据是本轮注入内容、工具调用结果、OpenViking API 返回和模型回复本身。@@ -1121,7 +1235,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` 中的 actor peer header 和 session `peer_id` | `peer_role` / `peer_prefix` 或 sender 解析不符合预期 |+| 不同 peer 记忆串用 | `logFindRequests` 中的 `X-OpenViking-Actor-Peer` | `peer_prefix` 或 session agent 解析不符合预期 || 搜不到刚保存的记忆 | 服务端 task 状态和日志 | afterTurn commit 是异步 Phase 2,记忆抽取可能还未完成或服务端失败 || summary 有但细节没有 | `ov_archive_search` / `ov_archive_expand` | Working Memory 是有损摘要,需要 archive 回查 || auto recall 没注入 | `autoRecall`、precheck、阈值、预算 | OpenViking 不可达、query 太短、阈值太高、记忆超预算 |@@ -1163,7 +1277,7 @@ npm run build| 测试文件 | 覆盖重点 || --- | --- |-| `tests/ut/config.test.ts` | 配置默认值、环境变量、peer 配置 |+| `tests/ut/config.test.ts` | 配置默认值、环境变量、peer policy || `tests/ut/setup-command.test.ts` / `setup-cli.test.ts` | setup/status、slot 激活、root key 探测 || `tests/ut/context-engine-*.test.ts` | assemble/afterTurn/compact、消息合并、预算、工具配对 || `tests/ut/memory-ranking.test.ts` | 召回排序、去重、阈值 |@@ -1196,7 +1310,7 @@ python health_check_tools/ov-healthcheck.py5. 新开一轮问“我之前偏好什么语言回复技术文档?”。6. 观察最新 user message 是否注入 `<relevant-memories>`,或用 `memory_recall` 显式查。7. 用 OpenViking Console/TUI 检查 `viking://user/.../memories` 是否产生 leaf memory。-8. 对长工具输出场景,确认 preview 中有 `viking://user/sessions/.../tool-results/...`,再用 tool-result 工具读取完整内容。+8. 对长工具输出场景,确认 preview 中有 `viking://session/.../tool-results/...`,再用 tool-result 工具读取完整内容。---@@ -1207,7 +1321,7 @@ python health_check_tools/ov-healthcheck.py3. **不要装错包**:`@openviking/openclaw-plugin` 是插件;`clawhub install openviking` 是 AgentSkill。4. **API Key 不进日志**:插件路由日志不会打印 key,但仍应避免把 key 写入公开文档或命令历史。5. **Root Key 需要租户上下文**:若服务端要求 account/user header,必须配置 `accountId` 和 `userId`。-6. **peer 配置要一致**:需要说话人隔离时,确认 `peer_role` / `peer_prefix` 与预期一致,否则会导致写查不一致。+6. **peer 配置要一致**:确认 `peer_role` / `peer_prefix` 与期望的 OpenClaw 会话身份一致,否则写入和召回会落在不同 actor peer 视角。7. **afterTurn commit 是异步抽取**:立即返回不代表长期记忆已可检索;看 task 或服务端日志。8. **compact 是同步边界**:需要明确压缩和抽取完成时用 compact,但它会阻塞等待服务端 Phase 2。9. **记忆注入有预算**:`recallMaxInjectedChars` 会跳过放不下的完整记忆,而不是截断。@@ -1241,7 +1355,7 @@ python health_check_tools/ov-healthcheck.py- [ ] Gateway 已重启。- [ ] `plugins.entries.openviking.config.baseUrl` 指向正确服务。- [ ] root key 场景已配置 `accountId/userId`。-- [ ] 需要说话人隔离时,`peer_role` / `peer_prefix` 与预期一致。+- [ ] `X-OpenViking-Actor-Peer` 与预期 agent/session 一致。- [ ] `autoCapture/autoRecall` 未被关闭。- [ ] 当前 session 没有命中 `bypassSessionPatterns`。- [ ] `pending_tokens` 是否达到 `commitTokenThreshold`。@@ -1250,9 +1364,9 @@ python health_check_tools/ov-healthcheck.py----## 15. 构建、测试和本地验证流程+## 15. 构建、测试、发布、上线全流程-本章面向维护者,按“改代码 → 本地验证 → 构建 → 本地加载验证”的顺序给出最短路径。TOS 上传、下载、灰度、发布和回滚流程不属于本示例范围。+本章面向维护者和发布同学,按“改代码 → 本地验证 → 打包 → 发布到 TOS → 安装/灰度 → 上线验证 → 回滚”的顺序给出最短路径。### 15.1 本地开发准备@@ -1270,7 +1384,7 @@ npm install| `npm run typecheck` | 使用 `tsconfig.json` 做类型检查 || `npm test` | 运行 Vitest 单测 || `npm run build` | 使用 `tsconfig.build.json` 生成 `dist/` |-| `npm run build` | 使用 `tsconfig.build.json` 生成可由 OpenClaw 加载的 `dist/` |+| `bash build.sh` | 完整发布包构建:安装依赖、类型检查、单测、编译、打 tgz、生成安装脚本 |### 15.2 本地测试@@ -1282,26 +1396,170 @@ npm testnpm run build```-构建后应确认 `dist/index.js` 和 `dist/commands/setup.js` 存在,且 `package.json` 中的 OpenClaw 入口指向 `dist/`。+完整发布前检查:++```bash+bash build.sh+```-重要契约:运行时依赖必须留在 `dependencies`,例如 `@sinclair/typebox` 和 `fflate`,避免 OpenClaw 运行时加载插件失败。+`build.sh` 会依次执行 `npm install`、`npm run typecheck`、`npm test`、`npm run build`,并要求存在 `dist/index.js`、`dist/commands/setup.js`、`openclaw.plugin.json`、`install-manifest.json`、`skills/` 和安装脚本:`build.sh:76`、`build.sh:82`、`build.sh:87`。-### 15.3 本地加载验证+打包产物:++| 文件 | 说明 |+| --- | --- |+| `output/openviking.tgz` | 插件独立安装包 |+| `output/install.sh` | TOS / tarball / local 安装脚本 |+| `output/volcengine-install.sh` | 火山一键安装脚本 |++重要契约:构建包会在 staging package 中安装生产依赖,并强校验 `node_modules/@sinclair/typebox` 存在,避免 OpenClaw 运行时加载插件失败:`build.sh:114`、`build.sh:116`。++### 15.3 用本地包安装验证```bash-npm run build-openclaw openviking setup --base-url http://127.0.0.1:1933 --api-key <OPENVIKING_API_KEY> --json+bash build.sh++bash output/install.sh --source tarball --tarball output/openviking.tgz \+ --openviking-base-url http://127.0.0.1:1933 \+ --openviking-api-key <OPENVIKING_API_KEY> \+ --json+```++只想校验包是否完整,不安装:++```bash+bash output/install.sh --source tarball --tarball output/openviking.tgz --verify-only```安装后检查:```bash+openclaw gateway restartopenclaw openviking status --jsonopenclaw config get plugins.entries.openviking.configopenclaw config get plugins.slots.contextEngine```-### 15.4 运行后 Debug Checklist+### 15.4 Release 版本规则++发布脚本入口是 `scripts/release-to-tos.sh`。版本解析逻辑由 `scripts/resolve-release-version.mjs` 控制:++| 场景 | 版本结果 |+| --- | --- |+| 默认 beta 发布 | 从 `package.json` 取基础版本,例如 `2026.6.2`,在目标环境已有版本基础上生成下一个 `2026.6.2-beta.N` |+| `--stable` | 发布基础版本本身,例如 `2026.6.2` |+| `--version <version>` | 完全使用显式版本 |+| `--tag <tag>` | 显式指定 Git tag;默认是 `v<resolved-version>` |++解析规则见 `scripts/resolve-release-version.mjs:28`、`scripts/resolve-release-version.mjs:38`、`scripts/resolve-release-version.mjs:56`。++### 15.5 Dry-run 发布检查++发布前先 dry-run,确认版本、manifest、checksum、latest 指针内容:++```bash+scripts/release-to-tos.sh --env stg --dry-run++# 稳定版本 dry-run+scripts/release-to-tos.sh --env prod --stable --dry-run+```++dry-run 会真实执行 `build.sh` 并生成:++| 文件 | 说明 |+| --- | --- |+| `output/manifest.json` | release 元数据,包含环境、版本、Git hash、artifact 路径和 SHA256 |+| `output/checksums.sha256` | artifact 校验和 |+| `output/latest.json` | 当前环境 latest 指针候选内容 |+| `output/release-notes.md` | 未传 `--notes` 时自动生成的 release notes |++dry-run 不上传 TOS:`scripts/release-to-tos.sh:178`。++### 15.6 发布到 TOS++非 dry-run 需要 TOS 凭证:++```bash+export TOS_ACCESS_KEY=<tos-access-key>+export TOS_SECRET_KEY=<tos-secret-key>++# 可选,默认如下+export TOS_BUCKET=arkclaw-openviking+export TOS_REGION=cn-beijing+export TOS_ENDPOINT=tos-cn-beijing.volces.com+```++发布 beta 到 stg / ppe:++```bash+scripts/release-to-tos.sh --env stg --notes ./release-notes.md+scripts/release-to-tos.sh --env ppe --notes ./release-notes.md+```++发布稳定版本到 prod:++```bash+scripts/release-to-tos.sh --env prod --stable --notes ./release-notes.md+```++脚本会完成以下动作:++1. 校验环境只能是 `stg|ppe|prod`。+2. prod 发布要求 Git 工作区干净,防止脏代码上线:`scripts/release-to-tos.sh:106`。+3. 解析版本和 tag。+4. 用 `BUILD_VERSION=<version> bash build.sh` 构建包。+5. 生成 manifest / checksums / latest。+6. 上传 `openviking.tgz`、`install.sh`、`manifest.json`、`checksums.sha256`、`release-notes.md`。+7. 下载远端对象并校验 SHA256。+8. 默认更新 `<env>/latest.json`;如传 `--no-latest` 则只上传不可变 release 对象,不切 latest。++TOS 对象不可变策略:release artifact、manifest、checksums、release notes 默认拒绝覆盖;只有 `<env>/latest.json` 是可变指针:`scripts/tos-release-client.mjs:49`、`scripts/tos-release-client.mjs:65`、`scripts/tos-release-client.mjs:80`。++### 15.7 TOS 产物结构++发布成功后,TOS 中的结构如下:++```text+<env>/latest.json+<env>/releases/<version>/openviking.tgz+<env>/releases/<version>/install.sh+<env>/releases/<version>/manifest.json+<env>/releases/<version>/checksums.sha256+<env>/releases/<version>/release-notes.md+```++`manifest.json` 中每个 artifact 都包含 `path`、`size`、`sha256`;安装脚本会读取 manifest 中 `openviking.tgz` 的路径和 SHA256 后下载校验:`scripts/generate-release-manifest.mjs:73`、`scripts/install.sh:315`、`scripts/install.sh:318`。++### 15.8 灰度、上线与回滚++推荐发布流:++1. **stg**:`scripts/release-to-tos.sh --env stg --dry-run`,确认产物;再去掉 `--dry-run` 发布。+2. **stg 安装验证**:`bash install.sh --source tos --channel stg --latest --verify-only`,再真实安装到测试 OpenClaw。+3. **ppe**:复用相同 release notes 发布到 ppe,验证安装、setup、gateway、status、一次真实召回。+4. **prod dry-run**:确认 prod 稳定版本、manifest 和最新 Git hash。+5. **prod 发布**:工作区干净后执行 `scripts/release-to-tos.sh --env prod --stable --notes ./release-notes.md`。+6. **线上验证**:安装 prod latest 或指定版本,检查 `openclaw openviking status --json`、slot、OpenViking `/health`、一次 `memory_recall` 或 `ov_search`。++回滚方式:++```bash+# 客户端回滚安装指定版本+bash install.sh --source tos --channel prod --version <previous-version>++# 或使用别名+bash install.sh --source tos --channel prod --rollback-to <previous-version>+```++如果只想发布某版本但不更新 latest 指针:++```bash+scripts/release-to-tos.sh --env prod --stable --no-latest --notes ./release-notes.md+```++这种方式适合先上传不可变产物,待外部审批通过后再单独更新 latest 指针。++### 15.9 上线后 Debug Checklist```bashopenclaw openviking status --json@@ -1328,11 +1586,15 @@ openclaw gateway restart然后使用 `ov_recall_trace` / `/ov-recall-trace` 查询。注意:`traceRecall=true` 是 trace 总开关,配置召回范围(如 `recallTargetTypes=["resource"]`)不会自动打开 trace。-### 15.5 常见问题+### 15.10 发布失败常见原因| 现象 | 原因 | 处理 || --- | --- | --- |-| OpenClaw 加载失败并提示缺依赖 | 包内缺运行时依赖 | 重新运行 `npm install` 和 `npm run build`,确认 `@sinclair/typebox` 位于 `dependencies` |+| prod 发布被拒绝 | Git 工作区不干净 | 提交或还原本地修改后重试 |+| 非 dry-run 提示 TOS 凭证缺失 | 没有设置 `TOS_ACCESS_KEY` / `TOS_SECRET_KEY` | 导出凭证后重试 |+| TOS 上传拒绝覆盖 | 同版本 release 对象已存在且不可变 | 换新版本;不要覆盖已发布对象 |+| 安装包校验失败 | 下载的 `openviking.tgz` SHA256 与 manifest 不一致 | 停止安装,检查 TOS 对象和 CDN/代理缓存 |+| OpenClaw 加载失败并提示缺依赖 | 包内缺运行时依赖 | 重新运行当前 `build.sh`,确认包内有 `node_modules/@sinclair/typebox` || status 不健康 | OpenViking Server 不可达或 key/租户错误 | 检查 `baseUrl`、`apiKey`、`accountId`、`userId`、服务端 `/health` |---diff --git a/examples/openclaw-plugin/docs/openviking-plugin-reference.md b/examples/openclaw-plugin/docs/openviking-plugin-reference.mdindex 36904e064..e50e24034 100644--- a/examples/openclaw-plugin/docs/openviking-plugin-reference.md+++ b/examples/openclaw-plugin/docs/openviking-plugin-reference.md@@ -71,12 +71,12 @@ $OPENCLAW_STATE_DIR/openclaw.json| `userId` | string | 空 | `OPENVIKING_USER_ID` | 高级租户路由字段;请求时写入 `X-OpenViking-User`。Root key 或 trusted 部署通常需要。 || `timeoutMs` | number | `15000` | — | OpenViking HTTP 请求超时,最低会 clamp 到 `1000`。 |-### 3.2 Peer 与检索隔离+### 3.2 Peer 身份与数据面路由| 参数 | 类型 | 默认值 | 环境变量 | 说明 || --- | --- | --- | --- | --- |-| `peer_role` | `"none"` \| `"assistant"` \| `"person"` | `"assistant"` | — | 控制哪些 session message 写入 `peer_id`,并为数据面 recall/search/read/import/delete 提供 actor peer 视图。 |-| `peer_prefix` | string | 空 | — | `peer_role=assistant` 时 assistant `peer_id` 的可选前缀;仅允许字母、数字、`_`、`-`。 |+| `peer_role` | `"none"` \| `"assistant"` \| `"person"` | `assistant` | — | Peer 身份模式。Session message 使用 body `peer_id`;数据面 recall/search 使用 `X-OpenViking-Actor-Peer`。 |+| `peer_prefix` | string | 空 | — | `peer_role=assistant` 时 assistant `peer_id` / actor peer 值的可选前缀。交互式 setup 仅允许字母、数字、`_`、`-`。 |### 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`;`user` / `agent` 为兼容项,当前合并为一次 `context_type=memory` 检索。 |+| `recallTargetTypes` | string[] | `["user", "agent"]` | — | 自动召回和默认 `memory_recall` 的搜索类型。允许 `resource`、`user`、`agent`。 || `recallResources` | boolean | `false` | `OPENVIKING_RECALL_RESOURCES` | 旧兼容开关;仅在未显式配置 `recallTargetTypes` 时追加 `resource`。 || `recallLimit` | number | `6` | — | 最终召回条数下限为 `1`。内部请求通常放大为 `max(limit * 4, 20)`。 || `recallScoreThreshold` | number | `0.15` | — | 召回结果分数阈值,范围 `0` 到 `1`。 |@@ -139,10 +139,10 @@ $OPENCLAW_STATE_DIR/openclaw.json| 分组 | 包含工具 || --- | --- |-| `default` | 默认 12 个 Agent tools。 |-| `all` | `add_resource` + 默认 12 个 Agent tools。注意 `add_resource` 仍需 `enableAddResourceTool=true`。 |+| `default` | 默认 14 个 Agent tools。 |+| `all` | `add_resource` + 默认 14 个 Agent tools。注意 `add_resource` 仍需 `enableAddResourceTool=true`。 || `memory` | `memory_recall`、`memory_store`、`memory_forget`。 |-| `resource_query` | `ov_search`、`ov_read`。 |+| `resource_query` | `ov_search`、`ov_read`、`ov_multi_read`、`ov_list`。 || `import` | `add_resource`、`add_skill`。 || `recall_trace` | `ov_recall_trace`。 || `archive` | `ov_archive_search`、`ov_archive_expand`。 |@@ -164,6 +164,8 @@ $OPENCLAW_STATE_DIR/openclaw.json- `ov_search`- `ov_read`+- `ov_multi_read`+- `ov_list`不会注册:@@ -227,7 +229,7 @@ openclaw openviking setup [options]| `--zh` | 使用中文提示。 || `--base-url <url>` | OpenViking Server URL。传入后进入非交互模式。 || `--api-key <key>` | API Key。 |-| `--agent-prefix <prefix>` | Agent 路由前缀。 |+| `--peer-prefix <prefix>` | Peer 路由前缀。 || `--account-id <id>` | Root API Key 场景下的 Account ID。 || `--user-id <id>` | Root API Key 场景下的 User ID。 || `--recall-target-types <types>` | 逗号分隔的召回类型,例如 `resource` 或 `user,agent,resource`。 |@@ -379,7 +381,7 @@ Manifest 中声明了 runtime slash alias:| 参数 | 必填 | 说明 || --- | --- | --- || `<query>` | 是 | 搜索 query。支持多词 query。 |-| `--uri URI` | 否 | 搜索目标 URI。未指定时默认搜索 resources 和 user skills。 |+| `--uri URI` | 否 | 搜索目标 URI。未指定时默认搜索 resources 和 agent skills。 || `--limit N` | 否 | 每个搜索范围返回条数,默认 `10`。 |示例:@@ -426,10 +428,12 @@ Manifest 中声明了 runtime slash alias:| Tool | 参数 | 用途 || --- | --- | --- |-| `add_skill` | `source?`、`data?`、`wait?`、`timeout?` | 导入或注册 OpenViking skill。 |+| `add_skill` | `source?`、`data?`、`wait?`、`timeout?` | 导入或注册 OpenViking agent skill。 || `ov_search` | `query`、`uri?`、`limit?` | 搜索 OpenViking resources 和 skills。 || `ov_read` | `uri` | 读取精确 `viking://...` OpenViking URI 的完整内容。 |-| `memory_recall` | `query`、`limit?`、`scoreThreshold?`、`targetUri?`、`resourceTypes?` | 显式召回长期记忆或资源。 |+| `ov_multi_read` | `uris` | 一次读取多个精确 `viking://...` URI,适合 overview + 同级切片。 |+| `ov_list` | `uri`、`recursive?`、`simple?`、`limit?` | 列出 OpenViking 目录,用于补齐同级切片和 `.overview.md`。 |+| `memory_recall` | `query`、`limit?`、`scoreThreshold?`、`targetUri?`、`resourceTypes?` | 显式召回长期记忆或资源;session 历史请用 archive 工具。 || `ov_recall_trace` | `turn?`、`traceId?`、`sessionId?`、`sessionKey?`、`ovSessionId?`、`source?`、`resourceTypes?`、`since?`、`until?`、`includeContent?`、`limit?` | 查询 recall trace。 || `memory_store` | `text`、`role?`、`sessionId?` | 将文本写入 session 并触发记忆抽取。 || `memory_forget` | `uri?`、`query?`、`targetUri?`、`limit?`、`scoreThreshold?` | 删除记忆 URI,或先搜索后删除唯一高置信候选。 |@@ -501,8 +505,7 @@ curl 'http://127.0.0.1:<gateway-port>/api/openviking/recall-traces/ov_search-178| `X-API-Key` | `apiKey` | API Key。 || `X-OpenViking-Account` | `accountId` | 租户 account。 || `X-OpenViking-User` | `userId` | 租户 user。 |--`peer_role=assistant/person` 时,插件通过请求 body 的 `peer_id` 字段做 session message 归因;recall/search/read/import/delete 等数据面请求通过 `X-OpenViking-Actor-Peer` 进入当前 actor peer 视图。当前实现不发送 `X-OpenViking-Agent` header。+| `X-OpenViking-Actor-Peer` | 当前解析出的 actor peer | Actor peer 数据面路由。 |后端 API 封装清单:diff --git a/examples/openclaw-plugin/docs/openviking-recall-trace-api.md b/examples/openclaw-plugin/docs/openviking-recall-trace-api.mdindex 8f0cf22af..85b0a3ac6 100644--- a/examples/openclaw-plugin/docs/openviking-recall-trace-api.md+++ b/examples/openclaw-plugin/docs/openviking-recall-trace-api.md@@ -6,10 +6,10 @@Recall Trace 是 OpenViking 插件的召回可观测能力。启用后,插件会把每一次自动召回、显式记忆召回、资源搜索、归档搜索记录成结构化 trace,便于回答以下问题:-- 本轮到底搜索了哪些语义召回范围:`resource`、`user`、`agent`?归档搜索会单独记录为 session archive trace。+- 本轮到底搜索了哪些范围:`resource`、`user`、`agent`?- 每个范围请求的目标 URI、limit、阈值和耗时是多少?- 候选结果有哪些?最终哪些被注入 prompt 或展示给用户?-- 为什么没有召回?是低于分数阈值、预算不足,还是搜索失败?+- 为什么没有召回?是没有 session 上下文、低于分数阈值、预算不足,还是搜索失败?- Gateway 重启后,是否还能从 JSONL 持久化文件查到近期 trace?核心实现位于 `recall-trace.ts:20`、`index.ts:704`、`index.ts:774` 和 `index.ts:784`。@@ -91,11 +91,9 @@ Trace 会记录实际召回范围,但召回范围本身由 `recallTargetTypes`| resourceType | target URI | 说明 || --- | --- | --- |-| `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.+| `resource` | `viking://resources` | 全局资源库。 |+| `user` | `viking://user/memories` | 当前用户长期记忆。 |+| `agent` | `agent recall target` | 当前 Agent 长期记忆。 |## 3. Trace 记录来源@@ -123,7 +121,7 @@ Session history is not a semantic recall target because the server does not vect| `agentId` | string? | 实际发送到 OpenViking 的 agent ID。 || `source` | enum | `auto_recall`、`memory_recall`、`ov_search`、`ov_archive_search`。 || `operationType` | enum | `semantic_find` 或 `archive_grep`。 |-| `resourceTypes` | array | 本次 trace 覆盖的召回类型:semantic recall 使用 `resource`、`user`、`agent`;`ov_archive_search` trace 会标记为 `session`。 |+| `resourceTypes` | array | 本次 trace 覆盖的召回类型:`resource`、`user`、`agent`。 || `trigger.query` | string | 触发搜索的查询文本,受 `traceRecallQueryMaxChars` 限制。 || `trigger.derivedKeywords` | string[]? | 派生关键词;归档搜索通常保存原 query。 || `trigger.rawUserTextPreview` | string? | 原始用户输入预览;默认不持久化。 |@@ -148,7 +146,7 @@ Session history is not a semantic recall target because the server does not vect| `results` | array | 候选结果摘要,最多 `traceRecallMaxResultsPerSearch` 条。 || `archiveId` | string? | 归档搜索指定 archive 时存在。 || `caseInsensitive` | boolean? | 归档 grep 是否大小写不敏感。 |-| `error` | string? | 子搜索失败原因。 |+| `error` | string? | 子搜索失败或跳过原因。 |### 4.3 `results[]`@@ -541,7 +539,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[].contextType` 和 `searches[].targetUriResolved`,确认是否使用 `context_type=memory` / `context_type=resource`,或是否按请求 `resourceTypes` 改变范围。+重点查看 `resourceTypes` 和 `searches[].targetUriResolved`,确认是否默认查了 `viking://user/memories` 与 `agent recall target`,或是否按请求 `resourceTypes` 改变范围。### 9.3 排查 `/ov-search` 或 `ov_search` 为什么结果不符合预期@@ -565,7 +563,7 @@ curl 'http://127.0.0.1:<gateway-port>/api/openviking/recall-traces/ov_search-178重点查看:- `operationType` 是否为 `archive_grep`。-- `searches[].targetUriResolved` 是否指向正确 session history 或 archive。+- `searches[].targetUriResolved` 是否指向正确 session archive。- `searches[].caseInsensitive` 是否为 true。- `stats.candidateCount` 与 `selected[].line`。diff --git a/examples/openclaw-plugin/docs/workmemory-v2-design.md b/examples/openclaw-plugin/docs/workmemory-v2-design.mdindex e6746b020..bb3d80a71 100644--- a/examples/openclaw-plugin/docs/workmemory-v2-design.md+++ b/examples/openclaw-plugin/docs/workmemory-v2-design.md@@ -307,7 +307,7 @@ OpenViking 在插件侧暴露两个独立的 archive 回查工具。- **插件工具**:`ov_archive_search`,参数 `query: string` + 可选 `archiveId: string`- **客户端封装**:`client.grepSessionArchives(sessionId, pattern, options)`-- **服务端 API**:`POST /api/v1/search/grep`,body `{uri, pattern, case_insensitive}`。`uri` 默认 `viking://user/sessions/{sessionId}/history`(覆盖所有 archive);指定 `archiveId` 时收窄为 `viking://user/sessions/{sessionId}/history/{archiveId}`+- **服务端 API**:`POST /api/v1/search/grep`,body `{uri, pattern, case_insensitive}`。`uri` 默认 `viking://session/{sessionId}/history`(覆盖所有 archive);指定 `archiveId` 时收窄为 `viking://session/{sessionId}/history/{archiveId}`- **工具输出给 LLM**:最多 12 条命中消息,每条最多 1500 字符,附 archive 标签(如 `archive_005`)和行号- **行为约束**:- 默认遍历所有 archive(新到旧)diff --git a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.md b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.mdindex c46a35920..a777c7015 100644--- a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.md+++ b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK-ZH.md@@ -136,6 +136,7 @@ Phase 3 会等待异步 commit 完成(默认最多 300 秒)。这是正常| `--openviking <url>` | 自动 | OpenViking 地址 || `--token <token>` | 自动 | Gateway bearer token || `--openviking-api-key <key>` | 自动 | OpenViking API key |+| `--actor-peer <id>` | `main` | OpenViking 直连检查请求使用的 actor peer || `--user-id <id>` | 随机 | 测试会话的 user id || `--openclaw-config <path>` | 自动 | `openclaw.json` 路径 || `--chat-timeout <秒>` | `120` | 每次 Gateway 聊天请求的超时 |diff --git a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.md b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.mdindex 824a142a1..a558f359f 100644--- a/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.md+++ b/examples/openclaw-plugin/health_check_tools/HEALTHCHECK.md@@ -136,6 +136,7 @@ This confirms the full async pipeline: conversation archiving, overview generati| `--openviking <url>` | auto | OpenViking base URL || `--token <token>` | auto | Gateway bearer token || `--openviking-api-key <key>` | auto | OpenViking API key |+| `--actor-peer <id>` | `main` | OpenViking actor peer for direct inspection requests || `--user-id <id>` | random | User id for the test session || `--openclaw-config <path>` | auto | Path to `openclaw.json` || `--chat-timeout <seconds>` | `120` | Timeout per Gateway chat request |diff --git a/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py b/examples/openclaw-plugin/health_check_tools/ov-healthcheck.pyindex 06307ea02..b59171ed7 100644--- a/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py+++ b/examples/openclaw-plugin/health_check_tools/ov-healthcheck.py@@ -17,6 +17,7 @@ from typing import AnyDEFAULT_GATEWAY_URL = "http://127.0.0.1:19789"DEFAULT_OPENVIKING_URL = "http://127.0.0.1:1933"+DEFAULT_ACTOR_PEER = "main"DEFAULT_SESSION_SCAN_LIMIT = 0META_FILE_SUFFIXES = (".abstract.md", ".overview.md")@@ -195,6 +196,11 @@ def parse_args() -> argparse.Namespace:default="",help="OpenViking API key. Auto-discovered from plugin config when possible.",)+ parser.add_argument(+ "--actor-peer",+ default="",+ help=f"OpenViking actor peer for direct inspection requests (default: {DEFAULT_ACTOR_PEER})",+ )parser.add_argument("--user-id", default="", help="User id for the real conversation session.")parser.add_argument("--openclaw-config",@@ -657,15 +663,20 @@ def wait_for_commit_visibility(class OpenVikingInspector:- def __init__(self, base_url: str, api_key: str, *, insecure: bool = False) -> None:+ def __init__(+ self, base_url: str, api_key: str, actor_peer: str, *, insecure: bool = False+ ) -> None:self.base_url = base_url.rstrip("/")self.api_key = api_key+ self.actor_peer = actor_peer or DEFAULT_ACTOR_PEERself.insecure = insecuredef headers(self) -> dict[str, str]:headers: dict[str, str] = {}if self.api_key:headers["X-API-Key"] = self.api_key+ if self.actor_peer:+ headers["X-OpenViking-Actor-Peer"] = self.actor_peerreturn headersdef health(self) -> bool:@@ -1127,6 +1138,9 @@ def main() -> int:)or str(os.environ.get("OPENVIKING_API_KEY", "")).strip())+ actor_peer = (+ args.actor_peer or str(plugin_config.get("peer_prefix", "")).strip() or DEFAULT_ACTOR_PEER+ )user_id = args.user_id or f"ov-healthcheck-{uuid.uuid4().hex[:8]}"probe = f"probe-{uuid.uuid4().hex[:8]}"run_facts = build_run_facts(probe)@@ -1195,7 +1209,9 @@ def main() -> int:else:recorder.add("WARN", "Gateway token not found", "continuing without Authorization header")- inspector = OpenVikingInspector(openviking_url, openviking_api_key, insecure=args.insecure)+ inspector = OpenVikingInspector(+ openviking_url, openviking_api_key, actor_peer, insecure=args.insecure+ )try:sessions_before_probe = collect_session_ids(inspector.list_sessions())except Exception:diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.tsindex b1ac52932..d0ccfab0c 100644--- a/examples/openclaw-plugin/index.ts+++ b/examples/openclaw-plugin/index.ts@@ -1,31 +1,47 @@-import { Type } from "@sinclair/typebox";import { memoryOpenVikingConfigSchema } from "./config.js";import { registerSetupCli } from "./commands/setup.js";-import { registerOpenVikingFeatureGatesMethod } from "./plugin/openviking-feature-gates.js";--import { OpenVikingClient, isMemoryUri } from "./client.js";-import type {- AddResourceInput,- AddResourceResult,- AddSkillInput,- AddSkillResult,- FindResult,- FindResultItem,- CommitSessionResult,- OVMessage,-} from "./client.js";+import { createOpenVikingBypassRuntime } from "./plugin/openviking-bypass-runtime.js";+import { createOpenVikingClientRuntime } from "./plugin/openviking-client-runtime.js";+import { createOpenVikingCommandDefinitions } from "./plugin/openviking-command-definitions.js";import {- defaultMemoryPolicyForPeerRole,- formatMessageFaithful,- resolveMessagePeerId,- resolveSearchPeerId,- toPeerId,-} from "./context-engine.js";+ parseAddResourceCommandArgs,+ parseAddSkillCommandArgs,+ parseOVSearchCommandArgs,+} from "./plugin/openviking-command-args.js";+import { createOpenVikingContextEngineRef } from "./plugin/openviking-context-engine-ref.js";+import { registerOpenVikingContextEngine } from "./plugin/openviking-context-engine-registration.js";+import { registerOpenVikingFeatureGatesMethod } from "./plugin/openviking-feature-gates.js";+import { createOpenVikingQueryConfigCommandHandler } from "./plugin/openviking-query-config-command.js";+import { createOpenVikingQueryRuntime } from "./plugin/openviking-query-runtime.js";+import { createOpenVikingRecallTraceRuntime } from "./plugin/openviking-recall-trace-runtime.js";+import { createOpenVikingToolRegistrationRuntime } from "./plugin/tool-registration.js";+import { registerOpenVikingCommands } from "./plugin/command-registration.js";+import { registerRecallTraceRoutes as registerRecallTraceRouteAdapters } from "./plugin/recall-trace-routes.js";+import { createOpenVikingService } from "./plugin/openviking-services.js";+import { registerOpenVikingArchiveTools } from "./plugin/openviking-archive-tools.js";+import { createOpenVikingImportRuntime } from "./plugin/openviking-import-runtime.js";+import { registerOpenVikingImportTools } from "./plugin/openviking-import-tools.js";+import { registerOpenVikingLifecycleHooks } from "./plugin/openviking-lifecycle-hooks.js";+import { registerOpenVikingMemoryRecallTools } from "./plugin/openviking-memory-recall-tools.js";+import { registerOpenVikingMemoryTools } from "./plugin/openviking-memory-tools.js";+import { registerOpenVikingQueryTools } from "./plugin/openviking-query-tools.js";+import { registerOpenVikingRecallTraceTools } from "./plugin/openviking-recall-trace-tools.js";+import { createOpenVikingRuntimeState } from "./plugin/openviking-runtime-state.js";+import { createOpenVikingSessionRoutingRuntime } from "./plugin/openviking-session-routing-runtime.js";+import { registerOpenVikingToolResultTools } from "./plugin/openviking-tool-result-tools.js";import {- compileSessionPatterns,- shouldBypassSession,- extractNewTurnMessages,-} from "./text-utils.js";+ boundTraceQuery,+ createMemoryStoreTempSessionId,+ createTraceId,+ extractToolSenderId,+ inferRecallResourceType,+ makeBypassedToolResult,+ previewText,+} from "./plugin/openviking-runtime-utils.js";+import type { CommandDefinition } from "./plugin/command-registration.js";++import type { HttpTransport } from "./adapters/http-transport.js";+import { formatMessageFaithful, toRoleId } from "./services/context-message-adapter.js";import {clampScore,postProcessMemories,@@ -34,55 +50,21 @@ import {import { withTimeout } from "./process-manager.js";import {createMemoryOpenVikingContextEngine,- openClawSessionToOvStorageId,- openClawSessionRefToOvStorageId,} from "./context-engine.js";-import type { ContextEngineWithCommit } from "./context-engine.js";import {- buildMemoryLines,+ openClawSessionRefToOvStorageId,+ openClawSessionToOvStorageId,+} from "./routing/identity-routing.js";+import {buildMemoryLinesWithBudget,- estimateTokenCount,- prepareRecallQuery,} from "./auto-recall.js";import {- RecallTraceRecorder,- normalizeResourceTypes,+ normalizeRecallResourceTypes as normalizeResourceTypes,resolveRecallSearchPlan,- type RecallResourceType,- type RecallTraceEntry,- type RecallTraceQuery,- type RecallTraceResult,- type RecallTraceSource,-} from "./recall-trace.js";+} from "./registries/recall-resource-types.js";import {- RuntimeQueryConfigStore,normalizeRuntimeQueryParams,- type QueryConfigContext,- type RuntimeQueryParams,} from "./query-config.js";-import {- formatOVListText,- formatOVMultiReadText,- formatOVReadText,- formatOVSearchText,-} from "./plugin/openviking-query-formatters.js";-export {- buildMemoryLines,- buildMemoryLinesWithBudget,- estimateTokenCount,- prepareRecallQuery,-};-export {- estimateAgentMessageTokens,- estimateAgentMessagesTokens,- estimateSerializedTokens,- estimateTextTokens,-} from "./token-estimator.js";-export type {- BuildMemoryLinesOptions,- BuildMemoryLinesWithBudgetOptions,- PreparedRecallQuery,-} from "./auto-recall.js";type PluginLogger = {debug?: (message: string) => void;@@ -97,34 +79,6 @@ type HookAgentContext = {sessionKey?: string;};-type SessionAgentLookup = {- agentId?: string;- sessionId?: string;- sessionKey?: string;- ovSessionId?: string;-};--type PluginSessionRouting = {- sessionId?: string;- sessionKey?: string;- ovSessionId?: string;- agentId: string;-};--type SessionAgentResolveBranch =- | "session_resolved"- | "config_only_fallback"- | "default_no_session";--export type SessionAgentResolveResult = {- resolved: string;- resolvedBeforeSanitize: string;- branch: SessionAgentResolveBranch;- mappedResolvedAgentId: string | null;- aliases: string[];- fromExplicitBinding: boolean;-};-type ToolDefinition = {name: string;label: string;@@ -140,130 +94,9 @@ type ToolContext = {senderId?: string;};-type PluginCommandContext = {- args?: string;- commandBody: string;- sessionKey?: string;- sessionId?: string;- agentId?: string;- ovSessionId?: string;-};--type CommandResult = {- text: string;- details?: Record<string, unknown>;-};--type CommandDefinition = {- name: string;- description: string;- acceptsArgs?: boolean;- requireAuth?: boolean;- handler: (ctx: PluginCommandContext) => CommandResult | Promise<CommandResult>;-};--type AddResourceToolInput = {- source?: string;- to?: string;- parent?: string;- reason?: string;- instruction?: string;- wait?: boolean;- timeout?: number;-};--type AddSkillToolInput = {- source?: string;- data?: unknown;- wait?: boolean;- timeout?: number;-};--type OVSearchInput = {- query: string;- uri?: string;- limit?: number;-};--type OVListInput = {- uri: string;- recursive?: boolean;- simple?: boolean;- limit?: number;-};--type OVReadInput = {- uri: string;-};--type OVMultiReadInput = {- uris: string[];-};--type RecallTraceToolInput = {- turn?: "latest" | "all";- traceId?: string;- sessionId?: string;- sessionKey?: string;- ovSessionId?: string;- source?: RecallTraceSource;- resourceTypes?: RecallResourceType[] | string;- since?: number;- until?: number;- includeContent?: boolean;- limit?: number;-};--type ToolResultRef = {- sessionId: string;- toolResultId: string;- ref: string;-};--function userSessionUri(sessionId: string): string {- return `viking://user/sessions/${encodeURIComponent(sessionId)}`;-}--function toolResultRef(sessionId: string, toolResultId: string): string {- return `${userSessionUri(sessionId)}/tool-results/${encodeURIComponent(toolResultId)}`;-}--function parseToolResultRef(value: unknown): ToolResultRef | null {- const raw = typeof value === "string" ? value.trim() : "";- if (!raw) {- return null;- }- const match =- raw.match(/^viking:\/\/user\/(?:(?:[^/]+)\/)?sessions\/([^/]+)\/tool-results\/([^/?#]+)(?:[?#].*)?$/) ??- raw.match(/^viking:\/\/session\/([^/]+)\/tool-results\/([^/?#]+)(?:[?#].*)?$/);- if (!match) {- return null;- }- const sessionId = decodeURIComponent(match[1]!);- const toolResultId = decodeURIComponent(match[2]!);- if (!sessionId || !toolResultId) {- return null;- }- return {- sessionId,- toolResultId,- ref: toolResultRef(sessionId, toolResultId),- };-}--function getOptionalInteger(value: unknown, fallback: number): number {- if (typeof value !== "number" || !Number.isFinite(value)) {- return fallback;- }- return Math.floor(value);-}--function getPositiveInteger(value: unknown, fallback: number): number {- return Math.max(1, getOptionalInteger(value, fallback));-}-type OpenClawPluginApi = {pluginConfig?: unknown;+ openVikingTransport?: HttpTransport;logger: PluginLogger;registerTool: {(tool: ToolDefinition, opts?: { name?: string; names?: string[] }): void;@@ -286,6 +119,16 @@ type OpenClawPluginApi = {respond: (success: boolean, data: unknown) => void;}) => void | Promise<void>,) => void;+ registerHttpRoute?: (route: {+ path: string;+ auth: "gateway" | "plugin";+ match?: "exact" | "prefix";+ handler: (req: { method?: string; url?: string }, res: {+ statusCode?: number;+ setHeader?: (name: string, value: string) => void;+ end?: (body?: string) => void;+ }) => Promise<boolean> | boolean;+ }) => void;registerCli?: (factory: (ctx: { program: unknown; workspaceDir?: string }) => void,opts?: { commands?: string[] },@@ -301,454 +144,11 @@ type RecallTraceRouteAdapter = {registerRoute?: (route: {method: "GET";path: string;- handler: (request?: {- query?: Record<string, unknown>;- params?: Record<string, unknown>;- url?: string;- }) => Promise<unknown>;+ handler: (request?: { query?: Record<string, unknown>; params?: Record<string, unknown>; url?: string }) => Promise<unknown>;}) => void;- registerHttpRoute?: (route: {- path: string;- auth: "plugin";- match: "exact" | "prefix";- handler: (- req: { method?: string; url?: string },- res: {- statusCode?: number;- setHeader?: (name: string, value: string) => void;- end?: (body?: string) => void;- },- ) => Promise<boolean>;- }) => void;-};--const DEFAULT_OPENCLAW_AGENT_ID = "main";--/**- * OpenClaw ids may contain ":" (e.g. session keys), while OpenViking- * peer/session metadata is path-friendly.- */-export function sanitizeRuntimeAgentId(raw: string): string {- const trimmed = raw.trim();- if (!trimmed) {- return "default";- }- const normalized = trimmed- .replace(/[^a-zA-Z0-9_-]/g, "_")- .replace(/_+/g, "_")- .replace(/^_|_$/g, "");- return normalized.length > 0 ? normalized : "ov_agent";-}--export function tokenizeCommandArgs(args: string): string[] {- const tokens: string[] = [];- let current = "";- let quote: "'" | '"' | null = null;- let escaping = false;-- for (let i = 0; i < args.length; i += 1) {- const ch = args[i]!;- const next = args[i + 1];- if (escaping) {- current += ch;- escaping = false;- continue;- }- if (ch === "\\") {- const shouldEscape =- quote === '"'- ? next === '"' || next === "\\"- : !quote && Boolean(next && (/\s/.test(next) || next === '"' || next === "'"));- if (shouldEscape) {- escaping = true;- continue;- }- current += ch;- continue;- }- if ((ch === '"' || ch === "'") && (!quote || quote === ch)) {- quote = quote ? null : ch;- continue;- }- if (!quote && /\s/.test(ch)) {- if (current) {- tokens.push(current);- current = "";- }- continue;- }- current += ch;- }-- if (escaping) {- current += "\\";- }- if (quote) {- throw new Error("Unterminated quoted argument");- }- if (current) {- tokens.push(current);- }- return tokens;-}--type ParsedFlagArgs = {- positionals: string[];- flags: Map<string, string | boolean>;+ registerHttpRoute?: OpenClawPluginApi["registerHttpRoute"];};-function parseFlagArgs(args: string): ParsedFlagArgs {- const tokens = tokenizeCommandArgs(args);- const positionals: string[] = [];- const flags = new Map<string, string | boolean>();-- for (let i = 0; i < tokens.length; i += 1) {- const token = tokens[i]!;- if (!token.startsWith("--")) {- positionals.push(token);- continue;- }- const raw = token.slice(2);- if (!raw) {- continue;- }- const eqIndex = raw.indexOf("=");- if (eqIndex >= 0) {- flags.set(raw.slice(0, eqIndex), raw.slice(eqIndex + 1));- continue;- }- const next = tokens[i + 1];- if (next && !next.startsWith("--")) {- flags.set(raw, next);- i += 1;- } else {- flags.set(raw, true);- }- }-- return { positionals, flags };-}--function getStringFlag(flags: Map<string, string | boolean>, name: string): string | undefined {- const value = flags.get(name);- return typeof value === "string" && value.trim() ? value.trim() : undefined;-}--function getNumberFlag(flags: Map<string, string | boolean>, name: string): number | undefined {- const raw = getStringFlag(flags, name);- if (!raw) {- return undefined;- }- const value = Number(raw);- if (!Number.isFinite(value)) {- throw new Error(`--${name} must be a number`);- }- return value;-}--function getBoolFlag(flags: Map<string, string | boolean>, name: string): boolean {- return flags.get(name) === true;-}--function getOptionalBoolFlag(flags: Map<string, string | boolean>, name: string): boolean | undefined {- const value = flags.get(name);- if (value === undefined) return undefined;- if (value === true) return true;- if (value === false) return false;- const normalized = value.trim().toLowerCase();- if (["1", "true", "yes", "on"].includes(normalized)) return true;- if (["0", "false", "no", "off"].includes(normalized)) return false;- throw new Error(`--${name} must be a boolean`);-}--function parseNumberMapFlag(flags: Map<string, string | boolean>, name: string): Record<string, number> | undefined {- const raw = getStringFlag(flags, name);- if (!raw) return undefined;- const result: Record<string, number> = {};- for (const item of raw.split(",")) {- const [key, rawValue, ...rest] = item.split("=");- const trimmedKey = key?.trim();- const trimmedValue = rawValue?.trim();- if (!trimmedKey || !trimmedValue || rest.length > 0) {- throw new Error(`--${name} must use key=value pairs separated by commas`);- }- const value = Number(trimmedValue);- if (!Number.isFinite(value)) {- throw new Error(`--${name} value for ${trimmedKey} must be a number`);- }- result[trimmedKey] = value;- }- return result;-}--function parseQueryConfigPatch(flags: Map<string, string | boolean>): RuntimeQueryParams {- const patch: RuntimeQueryParams = {};- const numberFields: Array<[string, keyof RuntimeQueryParams]> = [- ["recallLimit", "recallLimit"],- ["candidateLimit", "candidateLimit"],- ["candidateMultiplier", "candidateMultiplier"],- ["scoreThreshold", "scoreThreshold"],- ["maxInjectedChars", "maxInjectedChars"],- ["ovSearchLimit", "ovSearchLimit"],- ];- for (const [flag, field] of numberFields) {- if (flags.has(flag)) {- (patch as Record<string, unknown>)[field] = getNumberFlag(flags, flag);- }- }- const resourceTypes = getStringFlag(flags, "resourceTypes");- if (resourceTypes) patch.resourceTypes = resourceTypes;- const targetUri = getStringFlag(flags, "targetUri");- if (targetUri) patch.targetUri = targetUri;- const recallPreferAbstract = getOptionalBoolFlag(flags, "recallPreferAbstract");- if (recallPreferAbstract !== undefined) patch.recallPreferAbstract = recallPreferAbstract;-- const rankingWeights = parseNumberMapFlag(flags, "weight") ?? parseNumberMapFlag(flags, "rankingWeights");- if (rankingWeights) patch.rankingWeights = rankingWeights;- const categoryWeights = parseNumberMapFlag(flags, "categoryWeight") ?? parseNumberMapFlag(flags, "categoryWeights");- if (categoryWeights) patch.categoryWeights = categoryWeights;- const resourceTypeWeights = parseNumberMapFlag(flags, "resourceTypeWeight") ?? parseNumberMapFlag(flags, "resourceTypeWeights");- if (resourceTypeWeights) patch.resourceTypeWeights = resourceTypeWeights as RuntimeQueryParams["resourceTypeWeights"];- return patch;-}--function createTraceId(source: RecallTraceSource): string {- return `${source}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;-}--function previewText(value: string | undefined | null, maxChars: number): string | undefined {- const normalized = typeof value === "string" ? value.trim().replace(/\s+/g, " ") : "";- if (!normalized) {- return undefined;- }- return normalized.length > maxChars ? normalized.slice(0, maxChars) : normalized;-}--function boundTraceQuery(query: string, maxChars: number): { query: string; queryTruncated?: boolean } {- return query.length <= maxChars- ? { query }- : { query: query.slice(0, maxChars), queryTruncated: true };-}--function inferRecallResourceType(uri: string | undefined): RecallResourceType | undefined {- if (!uri) {- return undefined;- }- if (uri.startsWith("viking://resources")) {- return "resource";- }- if (uri.startsWith("viking://session/") || uri.includes("/sessions/")) {- return "session";- }- if (uri.startsWith("viking://user/")) {- return "user";- }- return undefined;-}--function extractToolSenderId(ctx: unknown): string | undefined {- if (!ctx || typeof ctx !== "object") {- return undefined;- }- const toolCtx = ctx as Record<string, unknown>;- if (typeof toolCtx.requesterSenderId === "string") {- const trimmed = toolCtx.requesterSenderId.trim();- if (trimmed) {- return trimmed;- }- }- if (typeof toolCtx.senderId === "string") {- const trimmed = toolCtx.senderId.trim();- if (trimmed) {- return trimmed;- }- }- return undefined;-}--export function parseAddResourceCommandArgs(args: string): AddResourceToolInput {- const parsed = parseFlagArgs(args);- const source =- parsed.positionals.length <= 1 ? parsed.positionals[0] : parsed.positionals.join(" ").trim();- if (!source) {- throw new Error("Usage: /add-resource <source> [--to URI] [--parent URI] [--reason TEXT] [--instruction TEXT] [--wait] [--timeout SEC]");- }- const to = getStringFlag(parsed.flags, "to");- const parent = getStringFlag(parsed.flags, "parent");- if (to && parent) {- throw new Error("Cannot specify both --to and --parent.");- }- return {- source,- to,- parent,- reason: getStringFlag(parsed.flags, "reason"),- instruction: getStringFlag(parsed.flags, "instruction"),- wait: getBoolFlag(parsed.flags, "wait"),- timeout: getNumberFlag(parsed.flags, "timeout"),- };-}--export function parseAddSkillCommandArgs(args: string): AddSkillToolInput {- const parsed = parseFlagArgs(args);- const source =- parsed.positionals.length <= 1 ? parsed.positionals[0] : parsed.positionals.join(" ").trim();- if (!source) {- throw new Error("Usage: /add-skill <source> [--wait] [--timeout SEC]");- }- if (parsed.flags.has("to") || parsed.flags.has("parent") || parsed.flags.has("reason") || parsed.flags.has("instruction")) {- throw new Error("--to, --parent, --reason, and --instruction are resource-only options.");- }- return {- source,- wait: getBoolFlag(parsed.flags, "wait"),- timeout: getNumberFlag(parsed.flags, "timeout"),- };-}--export function parseOVSearchCommandArgs(args: string): OVSearchInput {- const parsed = parseFlagArgs(args);- // `/ov-search` only accepts a single query string, so positional segments are- // always re-joined to preserve unquoted multi-word searches.- const query = parsed.positionals.join(" ").trim();- if (!query) {- throw new Error('Usage: /ov-search "<query>" [--uri URI] [--limit N]');- }- return {- query,- uri: getStringFlag(parsed.flags, "uri"),- limit: getNumberFlag(parsed.flags, "limit"),- };-}--function extractAgentIdFromSessionKey(sessionKey?: string): string | undefined {- const raw = typeof sessionKey === "string" ? sessionKey.trim() : "";- if (!raw) {- return undefined;- }-- const match = raw.match(/^agent:([^:]+):/);- const agentId = match?.[1]?.trim();- return agentId || undefined;-}--function collectSessionAgentAliases(- sessionId?: string,- sessionKey?: string,- ovSessionId?: string,-): string[] {- const aliases = new Set<string>();- const sid = typeof sessionId === "string" ? sessionId.trim() : "";- const sk = typeof sessionKey === "string" ? sessionKey.trim() : "";- const ovSid = typeof ovSessionId === "string" ? ovSessionId.trim() : "";-- if (sid) {- aliases.add(sid);- }- if (sk) {- aliases.add(sk);- }- if (ovSid) {- aliases.add(ovSid);- }-- if (!ovSid && (sid || sk)) {- try {- aliases.add(- openClawSessionToOvStorageId(- sid || undefined,- sk || undefined,- ),- );- } catch {- /* need a resolvable OpenClaw session identity */- }- }-- return [...aliases];-}--export function createSessionAgentResolver(configAgentId: string) {- const configAgentPrefix = configAgentId.trim() === "default" ? "" : configAgentId.trim();- const sessionAgentIds = new Map<string, string>();-- const remember = (ctx: SessionAgentLookup): void => {- const sessionScopedAgentId =- extractAgentIdFromSessionKey(ctx.sessionKey) ||- extractAgentIdFromSessionKey(ctx.sessionId);- const rawAgentId =- (typeof ctx.agentId === "string" ? ctx.agentId.trim() : "") ||- sessionScopedAgentId ||- "";- if (!rawAgentId) {- return;- }-- const prefix = configAgentPrefix;- const resolvedBeforeSanitize = prefix ? `${prefix}_${rawAgentId}` : rawAgentId;- const resolved = sanitizeRuntimeAgentId(resolvedBeforeSanitize);- for (const alias of collectSessionAgentAliases(ctx.sessionId, ctx.sessionKey, ctx.ovSessionId)) {- sessionAgentIds.set(alias, resolved);- }- };-- const resolve = (- sessionId?: string,- sessionKey?: string,- ovSessionId?: string,- ): SessionAgentResolveResult => {- const aliases = collectSessionAgentAliases(sessionId, sessionKey, ovSessionId);- const mappedAlias = aliases.find((alias) => sessionAgentIds.has(alias));- const mappedResolvedAgentId = mappedAlias ? sessionAgentIds.get(mappedAlias) : undefined;- const sessionScopedAgentId =- extractAgentIdFromSessionKey(sessionKey) ||- extractAgentIdFromSessionKey(sessionId);-- let resolvedBeforeSanitize: string;- let resolved: string;- let branch: SessionAgentResolveBranch;- const prefix = configAgentPrefix;-- if (mappedResolvedAgentId) {- resolvedBeforeSanitize = mappedResolvedAgentId;- resolved = mappedResolvedAgentId;- branch = "session_resolved";- } else if (sessionScopedAgentId) {- resolvedBeforeSanitize = prefix ? `${prefix}_${sessionScopedAgentId}` : sessionScopedAgentId;- resolved = sanitizeRuntimeAgentId(resolvedBeforeSanitize);- branch = "session_resolved";- } else if (!prefix) {- resolvedBeforeSanitize = DEFAULT_OPENCLAW_AGENT_ID;- resolved = DEFAULT_OPENCLAW_AGENT_ID;- branch = "default_no_session";- } else {- resolvedBeforeSanitize = `${prefix}_${DEFAULT_OPENCLAW_AGENT_ID}`;- resolved = sanitizeRuntimeAgentId(resolvedBeforeSanitize);- branch = "config_only_fallback";- }-- return {- resolved,- resolvedBeforeSanitize,- branch,- mappedResolvedAgentId: mappedResolvedAgentId ?? null,- aliases,- fromExplicitBinding: !!(mappedResolvedAgentId || sessionScopedAgentId),- };- };-- return {- remember,- resolve,- };-}--function totalCommitMemories(r: CommitSessionResult): number {- const m = r.memories_extracted;- if (!m || typeof m !== "object") return 0;- return Object.values(m).reduce((sum, n) => sum + (n ?? 0), 0);-}-const contextEnginePlugin = {id: "openviking",name: "Context Engine (OpenViking)",@@ -788,2613 +188,220 @@ const contextEnginePlugin = {return;}- const bypassSessionPatterns = compileSessionPatterns(cfg.bypassSessionPatterns);- const rawPeerPrefix = rawCfg.peer_prefix;- if (cfg.logFindRequests) {- api.logger.info(- "openviking: routing debug logging enabled (config logFindRequests, or env OPENVIKING_LOG_ROUTING=1 / OPENVIKING_DEBUG=1)",- );- }- const verboseRoutingInfo = (message: string) => {- if (cfg.logFindRequests) {- api.logger.info(message);- }- };- verboseRoutingInfo(- `openviking: loaded plugin config peer_role="${cfg.peer_role}" peer_prefix="${cfg.peer_prefix}" ` +- `(raw peer_prefix=${JSON.stringify(rawPeerPrefix ?? "(missing)")}; ` +- `${- cfg.peer_prefix- ? 'non-empty → assistant peer_id is <peer_prefix>_<ctx.agentId> when peer_role="assistant", or <peer_prefix>_main when ctx.agentId is unknown'- : 'empty → assistant peer_id follows OpenClaw ctx.agentId when peer_role="assistant", or "main" when ctx.agentId is unknown'- })`,- );- const routingDebugLog = cfg.logFindRequests- ? (msg: string) => {- api.logger.info(msg);- }- : undefined;- const defaultMemoryPolicy = defaultMemoryPolicyForPeerRole(cfg.peer_role);- const tenantAccount = cfg.accountId;- const tenantUser = cfg.userId;- const enabledToolNames = new Set<string>(cfg.enabledTools);- const registerOpenVikingTool = (- toolOrFactory: ToolDefinition | ((ctx: ToolContext) => ToolDefinition),- opts: { name: string; names?: string[] },- ) => {- const names = opts.names ?? [opts.name];- if (!names.some((name) => enabledToolNames.has(name))) {- api.logger.debug?.(`openviking: tool ${opts.name} disabled by config`);- return;- }- if (typeof toolOrFactory === "function") {- api.registerTool(toolOrFactory, opts);- } else {- api.registerTool(toolOrFactory, opts);- }- };-- const clientPromise = Promise.resolve(- new OpenVikingClient(- cfg.baseUrl,- cfg.apiKey,- cfg.peer_prefix,- cfg.timeoutMs,- tenantAccount,- tenantUser,- routingDebugLog,- ),- );-- const getClient = (): Promise<OpenVikingClient> => clientPromise;-- const traceRecorder = cfg.traceRecall- ? new RecallTraceRecorder({- memoryMaxEntries: cfg.traceRecallMaxEntries,- persist: cfg.traceRecallPersist,- traceDir: cfg.traceRecallDir,- includeRawUserPreview: cfg.traceRecallIncludeRawUserPreview,- retentionDays: cfg.traceRecallRetentionDays,- queryMaxDays: cfg.traceRecallQueryMaxDays,- })- : undefined;- const queryConfigStore = new RuntimeQueryConfigStore({- staticConfig: cfg,- path: cfg.runtimeQueryConfigPath || undefined,+ const { isBypassedSession } = createOpenVikingBypassRuntime({ cfg });+ const { getClient, verboseRoutingInfo } = createOpenVikingClientRuntime({+ cfg,+ rawPeerPrefix: rawCfg.peer_prefix,+ logger: api.logger,+ transport: api.openVikingTransport,+ });+ const { registerOpenVikingTool } = createOpenVikingToolRegistrationRuntime({+ api: api as { registerTool: (toolOrFactory: unknown, opts: { name: string }) => void },+ cfg,+ logger: api.logger,});- const queryConfigReady = queryConfigStore.load();- const toQueryConfigContext = (session: PluginSessionRouting): QueryConfigContext => ({- peerId: session.agentId,- sessionId: session.sessionId,- sessionKey: session.sessionKey,- ovSessionId: session.ovSessionId,- });-- const isBypassedSession = (ctx?: {- sessionId?: string;- sessionKey?: string;- }): boolean => shouldBypassSession(ctx ?? {}, bypassSessionPatterns);- const makeBypassedToolResult = (toolName: string) => ({- content: [- {- type: "text" as const,- text: `OpenViking is bypassed for this session by bypassSessionPatterns; ${toolName} was skipped.`,- },- ],- details: {- action: "bypassed",- reason: "session_bypassed",- toolName,- },+ const { queryConfigStore, traceRecorder } = createOpenVikingRuntimeState({+ cfg,+ logger: api.logger,});- const resolvePluginSessionRouting = (ctx?: SessionAgentLookup): PluginSessionRouting => {- const sessionId = typeof ctx?.sessionId === "string" ? ctx.sessionId.trim() : "";- const sessionKey = typeof ctx?.sessionKey === "string" ? ctx.sessionKey.trim() : "";- let ovSessionId = typeof ctx?.ovSessionId === "string" ? ctx.ovSessionId.trim() : "";-- if (!ovSessionId && (sessionId || sessionKey)) {- ovSessionId = openClawSessionToOvStorageId(- sessionId || undefined,- sessionKey || undefined,- );- }-- const session = {- agentId: ctx?.agentId,- sessionId: sessionId || undefined,- sessionKey: sessionKey || undefined,- ovSessionId: ovSessionId || undefined,- };- rememberSessionAgentId(session);-- return {- sessionId: session.sessionId,- sessionKey: session.sessionKey,- ovSessionId: session.ovSessionId,- agentId: resolveAgentId(session.sessionId, session.sessionKey, session.ovSessionId),- };- };-- const resolveToolSearchPeerId = (- ctx: unknown,- session: PluginSessionRouting,- ): string | undefined =>- resolveSearchPeerId({- peerRole: cfg.peer_role,- personPeerId: toPeerId(extractToolSenderId(ctx)),- assistantPeerId: session.agentId,- });-- const toTraceResult = (- item: FindResultItem,- resultType: RecallTraceResult["resultType"],- ): RecallTraceResult => ({- uri: item.uri,- resourceType: inferRecallResourceType(item.uri),- category: item.category,- score: item.score,- level: item.level,- abstractPreview: previewText(item.abstract || item.overview, cfg.traceRecallPreviewChars),- resultType,+ const {+ rememberSessionAgentId,+ resolveAgentId,+ resolvePluginSessionRouting,+ toQueryConfigContext,+ } = createOpenVikingSessionRoutingRuntime({+ peerPrefix: cfg.peer_prefix,+ logFindRequests: cfg.logFindRequests,+ logger: api.logger,});- const hasExplicitRecallTraceIdentityFilter = (input: RecallTraceToolInput): boolean => [- input.traceId,- input.sessionId,- input.sessionKey,- input.ovSessionId,- ].some((value) => typeof value === "string" && value.trim());-- const parseRecallTraceInput = (- input: RecallTraceToolInput,- ctx: { sessionId?: string; sessionKey?: string; ovSessionId?: string },- ): RecallTraceQuery => {- const traceId = typeof input.traceId === "string" && input.traceId.trim() ? input.traceId.trim() : undefined;- const explicitSessionId = typeof input.sessionId === "string" && input.sessionId.trim() ? input.sessionId.trim() : undefined;- const explicitSessionKey = typeof input.sessionKey === "string" && input.sessionKey.trim() ? input.sessionKey.trim() : undefined;- const explicitOvSessionId = typeof input.ovSessionId === "string" && input.ovSessionId.trim() ? input.ovSessionId.trim() : undefined;- const hasExplicitIdentityFilter = !!(traceId || explicitSessionId || explicitSessionKey || explicitOvSessionId);- const defaultSessionKey = !hasExplicitIdentityFilter ? ctx.sessionKey : undefined;- const defaultSessionId = !hasExplicitIdentityFilter && !defaultSessionKey ? ctx.sessionId : undefined;- const defaultOvSessionId = !hasExplicitIdentityFilter && !defaultSessionKey && !defaultSessionId ? ctx.ovSessionId : undefined;- return {- turn: input.turn === "all" ? "all" : "latest",- traceId,- sessionId: explicitSessionId ?? defaultSessionId,- sessionKey: explicitSessionKey ?? defaultSessionKey,- ovSessionId: explicitOvSessionId ?? defaultOvSessionId,- source: typeof input.source === "string" && input.source.trim() ? input.source as RecallTraceSource : undefined,- resourceTypes: input.resourceTypes ? normalizeResourceTypes(input.resourceTypes) : undefined,- since: typeof input.since === "number" ? input.since : undefined,- until: typeof input.until === "number" ? input.until : undefined,- limit: getPositiveInteger(input.limit, 20),- };- };-- const shouldIncludeTraceContent = (input?: { includeContent?: boolean }): boolean =>- typeof input?.includeContent === "boolean" ? input.includeContent : cfg.traceRecallIncludeContentByDefault;-- const enrichTraceEntriesWithContent = async (- result: { entries: RecallTraceEntry[]; lookupLayer: "memory" | "persistent"; warnings: string[] },- includeContent: boolean,- actorPeerId?: string,- ): Promise<{ entries: RecallTraceEntry[]; lookupLayer: "memory" | "persistent"; warnings: string[] }> => {- if (!includeContent || result.entries.length === 0) {- return result;- }- const client = await getClient();- const warnings = [...result.warnings];- 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, actorPeerId);- return {- ...item,- contentPreview: previewText(content, cfg.recallMaxContentChars),- };- } catch (err) {- const readError = err instanceof Error ? err.message : String(err);- warnings.push(`Failed to read recall trace content ${item.uri}: ${readError}`);- return { ...item, readError };- }- }));- return { ...entry, selected };- }));- return { ...result, entries, warnings };- };-- const queryRecallTraces = async (- input: RecallTraceToolInput,- session: PluginSessionRouting,- actorPeerId?: string,- ): Promise<{ entries: RecallTraceEntry[]; lookupLayer: "memory" | "persistent"; warnings: string[] }> => {- const query = parseRecallTraceInput(input, session);- const base = traceRecorder- ? await traceRecorder.queryWithFallback(query)- : { entries: [], lookupLayer: "memory" as const, warnings: ["traceRecall is disabled"] };- if (- traceRecorder &&- base.entries.length === 0 &&- !hasExplicitRecallTraceIdentityFilter(input) &&- query.sessionKey- ) {- const fallbackIdentities: RecallTraceQuery[] = [];- if (session.sessionId) {- fallbackIdentities.push({ ...query, sessionKey: undefined, sessionId: session.sessionId, ovSessionId: undefined });- }- if (session.ovSessionId) {- fallbackIdentities.push({ ...query, sessionKey: undefined, sessionId: undefined, ovSessionId: session.ovSessionId });- }- for (const fallbackQuery of fallbackIdentities) {- const fallback = await traceRecorder.queryWithFallback(fallbackQuery);- if (fallback.entries.length > 0) {- return enrichTraceEntriesWithContent(fallback, shouldIncludeTraceContent(input), actorPeerId);- }- }- }- return enrichTraceEntriesWithContent(base, shouldIncludeTraceContent(input), actorPeerId);- };-- const registerRecallTraceRoutes = (ctx?: unknown): boolean => {- const routeAdapter = ctx as RecallTraceRouteAdapter | undefined;- const canRegisterLegacyRoute = typeof routeAdapter?.registerRoute === "function";- const canRegisterHttpRoute = typeof routeAdapter?.registerHttpRoute === "function";- if (!canRegisterLegacyRoute && !canRegisterHttpRoute) {- return false;- }- const toQueryObject = (request?: {- query?: Record<string, unknown>;- params?: Record<string, unknown>;- url?: string;- }) => {- const query: Record<string, unknown> = { ...(request?.query ?? {}) };- if (request?.url) {- const parsed = new URL(request.url, "http://openclaw.local");- for (const [key, value] of parsed.searchParams.entries()) {- query[key] = value;- }- }- return { ...query, ...(request?.params ?? {}) };- };- const toBoolean = (value: unknown): boolean | undefined => {- if (typeof value === "boolean") return value;- if (typeof value !== "string") return undefined;- return ["1", "true", "yes"].includes(value.trim().toLowerCase());- };- const toNumber = (value: unknown): number | undefined => {- if (typeof value === "number") return value;- if (typeof value === "string" && value.trim()) {- const parsed = Number(value);- return Number.isFinite(parsed) ? parsed : undefined;- }- return undefined;- };- const toString = (value: unknown): string | undefined =>- typeof value === "string" && value.trim() ? value.trim() : undefined;- const queryValue = (query: Record<string, unknown>, ...keys: string[]): unknown => {- for (const key of keys) {- if (query[key] !== undefined) {- return query[key];- }- }- return undefined;- };- const toSessionKey = (query: Record<string, unknown>): string | undefined =>- toString(queryValue(query, "sessionKey", "sessionkey", "session_key", "session-key"));- const toLimitedInteger = (- value: unknown,- fallback: number,- min: number,- max: number,- ): number | undefined => {- const parsed = toNumber(value);- const raw = parsed === undefined ? fallback : Math.floor(parsed);- return Number.isFinite(raw) && raw >= min && raw <= max ? raw : undefined;- };- const inferUriType = (uri: string): string => {- if (uri.startsWith("viking://resources") || uri.startsWith("viking://resource")) return "resource";- if (uri.startsWith("viking://user/skills") || uri.startsWith("viking://skills")) return "skill";- if (uri.startsWith("viking://user/")) return "user_memory";- if (uri.startsWith("viking://session/")) return "session";- if (uri.includes("/archive") || uri.includes("/history/")) return "archive";- return "unknown";- };- const findTraceItem = (entry: RecallTraceEntry, uri: string) => {- const selected = entry.selected.find((item) => item.uri === uri);- const searchResult = entry.searches.flatMap((search) => search.results).find((item) => item.uri === uri);- if (!selected && !searchResult) {- return undefined;- }- return {- category: selected?.category ?? searchResult?.category,- score: selected?.score ?? searchResult?.score,- level: searchResult?.level,- abstractPreview: selected?.abstractPreview ?? searchResult?.abstractPreview,- resultType: searchResult?.resultType,- sourceTraceId: entry.traceId,- source: entry.source,- };- };- const handleRecallTraces = async (request?: {- query?: Record<string, unknown>;- params?: Record<string, unknown>;- url?: string;- }) => {- const query = toQueryObject(request);- const session = resolvePluginSessionRouting(query as SessionAgentLookup);- const result = await queryRecallTraces({- turn: query.turn === "all" ? "all" : "latest",- traceId: toString(queryValue(query, "traceId", "trace-id", "trace_id")),- sessionId: toString(query.sessionId),- sessionKey: toSessionKey(query),- ovSessionId: toString(query.ovSessionId),- source: toString(query.source) as RecallTraceSource | undefined,- resourceTypes: typeof query.resourceTypes === "string" ? query.resourceTypes : undefined,- since: toNumber(query.since),- until: toNumber(query.until),- includeContent: toBoolean(queryValue(query, "includeContent", "include-content", "include_content")),- limit: toNumber(query.limit),- }, session, resolveToolSearchPeerId(query, session));- return { status: 200, body: { ok: true, ...result } };- };- const handleUriDetail = async (request?: {- query?: Record<string, unknown>;- params?: Record<string, unknown>;- url?: string;- }) => {- const query = toQueryObject(request);- const uri = toString(query.uri);- if (!uri || !uri.startsWith("viking://") || uri.endsWith("...") || uri.includes("…")) {- return {- status: 400,- body: {- ok: false,- uri: uri ?? "",- readStatus: "not_requested",- warnings: [],- error: { code: "invalid_uri", message: "uri must be a complete viking:// URI" },- },- };- }- const offset = toLimitedInteger(query.offset, 0, 0, 1_000_000_000);- const contentLimit = toLimitedInteger(- queryValue(query, "contentLimit", "content-limit", "content_limit"),- 20_000,- 1,- 100_000,- );- if (offset === undefined || contentLimit === undefined) {- return {- status: 400,- body: {- ok: false,- uri,- readStatus: "not_requested",- warnings: [],- error: { code: "invalid_param", message: "offset or contentLimit is invalid" },- },- };- }- const includeContent = toBoolean(queryValue(query, "includeContent", "include-content", "include_content")) ?? true;- const preferTracePreview = toBoolean(- queryValue(query, "preferTracePreview", "prefer-trace-preview", "prefer_trace_preview"),- ) ?? true;- const session = resolvePluginSessionRouting(query as SessionAgentLookup);- const traceId = toString(queryValue(query, "traceId", "trace-id", "trace_id"));- const actorPeerId = resolveToolSearchPeerId(query, session);- let traceMetadata:- | {- category?: string;- score?: number;- level?: number;- abstractPreview?: string;- resultType?: RecallTraceResult["resultType"];- sourceTraceId?: string;- source?: RecallTraceSource;- }- | undefined;- const warnings: string[] = [];- if (preferTracePreview && traceId && traceRecorder) {- const traceResult = await traceRecorder.queryWithFallback({- turn: "latest",- traceId,- limit: 1,- });- warnings.push(...traceResult.warnings);- traceMetadata = traceResult.entries[0] ? findTraceItem(traceResult.entries[0], uri) : undefined;- }- const baseBody = {- ok: true,- uri,- uriType: inferUriType(uri),- abstractPreview: traceMetadata?.abstractPreview,- metadata: {- category: traceMetadata?.category,- score: traceMetadata?.score,- level: traceMetadata?.level,- resultType: traceMetadata?.resultType,- sourceTraceId: traceMetadata?.sourceTraceId,- source: traceMetadata?.source,- },- readStatus: "not_requested" as const,- warnings,- };- if (!includeContent) {- return { status: 200, body: baseBody };- }- try {- const client = await getClient();- const content = await client.read(uri, actorPeerId);- const text = typeof content === "string" ? content : JSON.stringify(content, null, 2);- const chars = Array.from(text);- const slice = chars.slice(offset, offset + contentLimit).join("");- return {- status: 200,- body: {- ...baseBody,- content: {- text: slice,- offset,- limit: contentLimit,- returnedChars: Array.from(slice).length,- totalChars: chars.length,- hasMore: offset + contentLimit < chars.length,- },- readStatus: "ok" as const,- },- };- } catch (err) {- return {- status: 502,- body: {- ...baseBody,- ok: false,- readStatus: "read_failed" as const,- error: { code: "read_failed", message: err instanceof Error ? err.message : String(err) },- },- };- }- };- const handleLatestOvSearchList = async (request?: {- query?: Record<string, unknown>;- params?: Record<string, unknown>;- url?: string;- }) => {- const query = toQueryObject(request);- const session = resolvePluginSessionRouting(query as SessionAgentLookup);- const limit = toLimitedInteger(query.limit, 20, 1, 100);- if (limit === undefined) {- return {- status: 400,- body: {- ok: false,- items: [],- totalItems: 0,- warnings: [],- error: { code: "invalid_param", message: "limit is invalid" },- },- };- }- const includeSelected = toBoolean(query.includeSelected) ?? true;- const dedupe = toBoolean(query.dedupe) ?? true;- const includeSkills = toBoolean(query.includeSkills) ?? true;- const strict = toBoolean(query.strict) ?? false;- const traceQuery = parseRecallTraceInput({- turn: "latest",- source: "ov_search",- sessionId: toString(query.sessionId),- sessionKey: toSessionKey(query),- ovSessionId: toString(query.ovSessionId),- limit: 1,- }, session);- const result = traceRecorder- ? await traceRecorder.queryWithFallback(traceQuery)- : { entries: [], lookupLayer: "memory" as const, warnings: ["traceRecall is disabled"] };- const agentId = toString(query.agentId);- const entry = agentId ? result.entries.find((candidate) => candidate.agentId === agentId) : result.entries[0];- if (!entry) {- const body = {- ok: !strict,- lookupLayer: "none" as const,- fallbackUsed: false,- query: {- sessionId: toString(query.sessionId),- sessionKey: toSessionKey(query),- ovSessionId: toString(query.ovSessionId),- agentId,- limit,- lookup: toString(query.lookup) ?? "auto",- },- items: [],- totalItems: 0,- warnings: [...result.warnings, "no ov_search trace found for latest interaction"],- ...(strict ? { error: { code: "not_found", message: "no ov_search trace found for latest interaction" } } : {}),- };- return { status: strict ? 404 : 200, body };- }- const searchResultByUri = new Map<string, RecallTraceResult & { targetUri?: string }>();- for (const search of entry.searches) {- for (const item of search.results) {- searchResultByUri.set(item.uri, { ...item, targetUri: search.targetUriResolved ?? search.targetUriInput });- }- }- const items: Array<Record<string, unknown>> = [];- const addItem = (- item: {- uri: string;- resourceType?: RecallResourceType | "archive";- category?: string;- score?: number;- abstractPreview?: string;- },- source: "search_result" | "selected",- ) => {- const matched = searchResultByUri.get(item.uri);- const inferredType = inferUriType(item.uri);- const resultType = matched?.resultType- ?? (inferredType === "skill" ? "skill" : inferredType.includes("memory") ? "memory" : "resource");- if (!includeSkills && resultType === "skill") {- return;- }- const row = {- uri: item.uri,- abstractPreview: item.abstractPreview ?? matched?.abstractPreview,- resourceType: item.resourceType ?? matched?.resourceType,- resultType,- category: item.category ?? matched?.category,- score: item.score ?? matched?.score,- source,- targetUri: matched?.targetUri,- detailUrl: `/api/openviking/uri-detail?uri=${encodeURIComponent(item.uri)}&traceId=${encodeURIComponent(entry.traceId)}`,- };- if (dedupe) {- const existing = items.findIndex((candidate) => candidate.uri === item.uri);- if (existing >= 0) {- if (source === "selected") {- items[existing] = row;- }- return;- }- }- items.push(row);- };- if (includeSelected) {- entry.selected.forEach((item) => addItem(item, "selected"));- }- for (const search of entry.searches) {- search.results.forEach((item) => addItem(item, "search_result"));- }- const limited = items.slice(0, limit);- return {- status: 200,- body: {- ok: true,- lookupLayer: result.lookupLayer,- fallbackUsed: result.lookupLayer === "persistent",- query: {- sessionId: toString(query.sessionId),- sessionKey: toSessionKey(query),- ovSessionId: toString(query.ovSessionId),- agentId,- limit,- lookup: toString(query.lookup) ?? "auto",- },- trace: {- traceId: entry.traceId,- ts: entry.ts,- isoTime: new Date(entry.ts).toISOString(),- triggerQuery: entry.trigger.query,- totalSearches: entry.searches.length,- },- items: limited,- totalItems: limited.length,- warnings: result.warnings,- },- };- };- const routes = [- { method: "GET" as const, path: "/api/openviking/recall-traces", handler: handleRecallTraces },- { method: "GET" as const, path: "/api/openviking/uri-detail", handler: handleUriDetail },- { method: "GET" as const, path: "/api/openviking/recall-traces/latest-ov-search-list", handler: handleLatestOvSearchList },- {- method: "GET" as const,- path: "/api/openviking/recall-traces/:traceId",- handler: (request?: {- query?: Record<string, unknown>;- params?: Record<string, unknown>;- url?: string;- }) => handleRecallTraces({- ...request,- query: {- ...(request?.query ?? {}),- traceId: typeof request?.params?.traceId === "string" ? request.params.traceId : undefined,- },- }),- },- ];- if (canRegisterLegacyRoute) {- for (const route of routes) {- routeAdapter.registerRoute?.(route);- }- }- if (canRegisterHttpRoute) {- const sendJson = (- res: {- statusCode?: number;- setHeader?: (name: string, value: string) => void;- end?: (body?: string) => void;- },- status: number,- body: unknown,- ) => {- res.statusCode = status;- res.setHeader?.("Cache-Control", "no-store");- res.setHeader?.("Content-Type", "application/json; charset=utf-8");- res.end?.(JSON.stringify(body));- };- const makeHttpHandler = (- route: (typeof routes)[number],- getParams?: (url: string) => Record<string, unknown>,- ) => async (- req: { method?: string; url?: string },- res: {- statusCode?: number;- setHeader?: (name: string, value: string) => void;- end?: (body?: string) => void;- },- ): Promise<boolean> => {- if ((req.method ?? "GET").toUpperCase() !== route.method) {- sendJson(res, 405, {- ok: false,- error: { code: "method_not_allowed", message: `${route.method} is required` },- });- return true;- }- const url = req.url ?? route.path;- const result = await route.handler({ url, params: getParams?.(url) });- const response = result as { status?: number; body?: unknown };- sendJson(res, typeof response.status === "number" ? response.status : 200, response.body ?? response);- return true;- };- for (const route of routes) {- if (route.path === "/api/openviking/recall-traces/:traceId") {- const prefix = "/api/openviking/recall-traces/";- routeAdapter.registerHttpRoute?.({- path: "/api/openviking/recall-traces",- auth: "plugin",- match: "prefix",- handler: makeHttpHandler(route, (url) => {- const pathname = new URL(url, "http://openclaw.local").pathname;- const traceId = pathname.startsWith(prefix)- ? decodeURIComponent(pathname.slice(prefix.length))- : "";- return traceId ? { traceId } : {};- }),- });- } else {- routeAdapter.registerHttpRoute?.({- path: route.path,- auth: "plugin",- match: "exact",- handler: makeHttpHandler(route),- });- }- }- }- return true;- };-- const formatRecallTraceText = (result: { entries: RecallTraceEntry[]; lookupLayer: string; warnings: string[] }): string => {- if (result.entries.length === 0) {- return `No OpenViking recall traces found (lookupLayer=${result.lookupLayer}).`;- }- const blocks = result.entries.map((entry, index) => {- const selected = entry.selected.slice(0, 8)- .map((item) => ` - ${item.uri}${item.score !== undefined ? ` (${(clampScore(item.score) * 100).toFixed(0)}%)` : ""}`)- .join("\n");- return [- `## Trace ${index + 1}: ${entry.source}`,- `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");- });- const warnings = result.warnings.length > 0- ? `\n\nWarnings:\n${result.warnings.map((warning) => `- ${warning}`).join("\n")}`- : "";- return `${blocks.join("\n\n")}${warnings}`;- };-- const formatResourceImportText = (result: AddResourceResult): string => {- const root = result.root_uri ? ` ${result.root_uri}` : "";- const warnings = result.warnings?.length ? ` Warnings: ${result.warnings.join("; ")}` : "";- return `Imported OpenViking resource.${root}${warnings}`.trim();- };-- const formatSkillImportText = (result: AddSkillResult): string => {- const uri = result.uri ? ` ${result.uri}` : "";- const name = result.name ? ` (${result.name})` : "";- return `Imported OpenViking skill${name}.${uri}`.trim();- };-- const importResource = async (input: AddResourceInput, actorPeerId?: string) => {- const client = await getClient();- const result = await client.addResource(input, actorPeerId);- return {- content: [{ type: "text" as const, text: formatResourceImportText(result) }],- details: {- action: "resource_imported",- ...result,- },- };- };-- const importSkill = async (input: AddSkillInput, actorPeerId?: string) => {- const client = await getClient();- const result = await client.addSkill(input, actorPeerId);- return {- content: [{ type: "text" as const, text: formatSkillImportText(result) }],- details: {- action: "skill_imported",- ...result,- },- };- };-- const addResourceOpenViking = (input: AddResourceToolInput, actorPeerId?: string) =>- importResource({- pathOrUrl: input.source ?? "",- to: input.to,- parent: input.parent,- reason: input.reason,- instruction: input.instruction,- wait: input.wait,- timeout: input.timeout,- }, actorPeerId);-- const addSkillOpenViking = (input: AddSkillToolInput, actorPeerId?: string) =>- importSkill({- path: input.source,- data: input.data,- wait: input.wait,- timeout: input.timeout,- }, actorPeerId);-- const mergeFindResults = (results: FindResult[]): FindResult => {- const deduplicate = (items: FindResultItem[]): FindResultItem[] => {- const seen = new Map<string, FindResultItem>();- for (const item of items) {- if (!seen.has(item.uri)) {- seen.set(item.uri, item);- }- }- return Array.from(seen.values());- };- const memories = deduplicate(results.flatMap((result) => result.memories ?? []));- const resources = deduplicate(results.flatMap((result) => result.resources ?? []));- const skills = deduplicate(results.flatMap((result) => result.skills ?? []));- return {- memories,- resources,- skills,- total: memories.length + resources.length + skills.length,- };- };-- const searchOpenViking = async (- input: OVSearchInput,- traceCtx?: PluginSessionRouting,- actorPeerId?: string,- ) => {- const query = input.query.trim();- if (!query) {- throw new Error("query is required");- }- const effectiveQuery = traceCtx- ? await queryConfigStore.getEffective(toQueryConfigContext(traceCtx), {- ovSearchLimit: input.limit,- targetUri: input.uri,- })- : undefined;- const limit = Math.max(1, Math.floor(input.limit ?? effectiveQuery?.ovSearchLimit ?? 10));- const searchUri = input.uri ?? effectiveQuery?.targetUri;- const client = await getClient();- let result: FindResult;- const searches: RecallTraceEntry["searches"] = [];- if (searchUri) {- const started = Date.now();- result = await client.find(query, { targetUri: searchUri, limit, actorPeerId });- const items = [- ...(result.memories ?? []).map((item) => toTraceResult(item, "memory")),- ...(result.resources ?? []).map((item) => toTraceResult(item, "resource")),- ...(result.skills ?? []).map((item) => toTraceResult(item, "skill")),- ].slice(0, cfg.traceRecallMaxResultsPerSearch);- searches.push({- resourceType: inferRecallResourceType(searchUri) ?? "resource",- targetUriInput: searchUri,- targetUriResolved: searchUri,- limit,- durationMs: Date.now() - started,- total: result.total ?? items.length,- results: items,- });- } else {- 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, 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,- contextType,- targetUriResolved: targetUri,- limit,- durationMs: Date.now() - started,- total: found.total ?? items.length,- results: items,- });- return found;- } catch (err) {- searches.push({- resourceType,- contextType,- targetUriResolved: targetUri,- limit,- durationMs: Date.now() - started,- total: 0,- results: [],- error: err instanceof Error ? err.message : String(err),- });- throw err;- }- };- const [resourcesSettled, skillsSettled] = await Promise.allSettled([- runSearch(undefined, "resource"),- runSearch(undefined, "skill"),- ]);- const successful: FindResult[] = [];- if (resourcesSettled.status === "fulfilled") {- successful.push(resourcesSettled.value);- }- if (skillsSettled.status === "fulfilled") {- successful.push(skillsSettled.value);- }- if (successful.length === 0) {- const firstError =- resourcesSettled.status === "rejected"- ? resourcesSettled.reason- : skillsSettled.status === "rejected"- ? skillsSettled.reason- : "Both searches failed";- throw firstError instanceof Error ? firstError : new Error(String(firstError));- }- if (resourcesSettled.status === "rejected") {- api.logger.warn?.(`openviking: resource search failed: ${String(resourcesSettled.reason)}`);- }- if (skillsSettled.status === "rejected") {- api.logger.warn?.(`openviking: skill search failed: ${String(skillsSettled.reason)}`);- }- result = mergeFindResults(successful);- }- const selected = [- ...(result.memories ?? []).map((item) => ({- uri: item.uri,- resourceType: inferRecallResourceType(item.uri),- category: item.category,- score: item.score,- abstractPreview: previewText(item.abstract || item.overview, cfg.traceRecallPreviewChars),- displayed: true,- })),- ...(result.resources ?? []).map((item) => ({- uri: item.uri,- resourceType: inferRecallResourceType(item.uri),- category: item.category,- score: item.score,- abstractPreview: previewText(item.abstract || item.overview, cfg.traceRecallPreviewChars),- displayed: true,- })),- ...(result.skills ?? []).map((item) => ({- uri: item.uri,- resourceType: inferRecallResourceType(item.uri),- category: item.category,- score: item.score,- abstractPreview: previewText(item.abstract || item.overview, cfg.traceRecallPreviewChars),- displayed: true,- })),- ];- await traceRecorder?.recordAndFlush({- schemaVersion: "1.0",- traceId: createTraceId("ov_search"),- ts: Date.now(),- sessionId: traceCtx?.sessionId,- sessionKey: traceCtx?.sessionKey,- ovSessionId: traceCtx?.ovSessionId,- agentId: traceCtx?.agentId,- source: "ov_search",- operationType: "semantic_find",- resourceTypes: [...new Set(searches- .map((search) => search.resourceType)- .filter((resourceType): resourceType is RecallResourceType => resourceType !== "archive"))],- trigger: boundTraceQuery(query, cfg.traceRecallQueryMaxChars),- searches,- selected,- stats: {- candidateCount: searches.reduce((sum, search) => sum + search.results.length, 0),- selectedCount: selected.length,- injectedCount: 0,- },- });- return {- content: [{ type: "text" as const, text: formatOVSearchText(query, searchUri, result) }],- details: {- action: "searched",- query,- uri: searchUri,- peer_id: actorPeerId ?? null,- queryConfig: effectiveQuery,- memories: result.memories ?? [],- resources: result.resources ?? [],- skills: result.skills ?? [],- total: result.total ?? 0,- },- };- };-- 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, actorPeerId);- return {- content: [{ type: "text" as const, text: formatOVReadText(uri, content) }],- details: {- action: "read",- uri,- chars: content.length,- },- };- };-- const multiReadOpenViking = async (- input: OVMultiReadInput,- actorPeerId?: string,- ) => {- const uris = input.uris- .map((uri) => (typeof uri === "string" ? uri.trim() : ""))- .filter((uri) => uri.length > 0);- if (uris.length === 0) {- throw new Error("uris is required");- }- const client = await getClient();- const results = await Promise.all(- uris.map(async (uri) => {- try {- const content = await client.read(uri, actorPeerId);- return {- uri,- content,- success: true,- chars: content.length,- };- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- return {- uri,- content: message,- success: false,- chars: 0,- };- }- }),- );- return {- content: [{ type: "text" as const, text: formatOVMultiReadText(results) }],- details: {- action: "multi_read",- count: results.length,- success_count: results.filter((result) => result.success).length,- results,- },- };- };-- const listOpenViking = async (- input: OVListInput,- actorPeerId?: string,- ) => {- const uri = input.uri.trim();- if (!uri) {- throw new Error("uri is required");- }- const limit = Math.max(1, Math.floor(input.limit ?? 100));- const client = await getClient();- const entries = await client.list(- uri,- {- recursive: input.recursive ?? false,- simple: input.simple ?? false,- nodeLimit: limit,- actorPeerId,- },- );- return {- content: [{ type: "text" as const, text: formatOVListText(uri, entries) }],- details: {- action: "listed",- uri,- recursive: input.recursive ?? false,- simple: input.simple ?? false,- count: entries.length,- entries,- },- };- };-- if (cfg.enableAddResourceTool) {- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "add_resource",- label: "Add Resource (OpenViking)",- description:- "Use only when the user explicitly asks to import, add, upload, save, or index a document, directory, URL, Git repository, or OpenClaw media attachment into OpenViking resources. " +- "Never use this during search, retrieval, URI reading, or search-result optimization; use ov_search, ov_list, ov_read, and ov_multi_read for those flows. " +- "For a '[media attached: /path ...]' document, set source to that exact local media path. " +- "Set either to for an exact target URI or parent for a parent directory, never both. " +- "Do not invent OpenViking upload REST endpoints.",- parameters: Type.Object({- source: Type.String({ description: "Local path, OpenClaw media attachment path, directory path, public URL, or Git URL" }),- to: Type.Optional(Type.String({ description: "Exact target URI, e.g. viking://resources/project-docs. Mutually exclusive with parent." })),- parent: Type.Optional(Type.String({ description: "Parent URI under viking://resources. Mutually exclusive with to." })),- reason: Type.Optional(Type.String({ description: "Reason or note for adding this resource" })),- instruction: Type.Optional(Type.String({ description: "Processing instruction for semantic extraction" })),- wait: Type.Optional(Type.Boolean({ description: "Wait for processing to complete" })),- timeout: Type.Optional(Type.Number({ description: "Timeout in seconds when wait is true" })),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("add_resource");- }- const session = resolvePluginSessionRouting(ctx);- return addResourceOpenViking({- source: typeof params.source === "string" ? params.source : undefined,- to: typeof params.to === "string" ? params.to : undefined,- parent: typeof params.parent === "string" ? params.parent : undefined,- reason: typeof params.reason === "string" ? params.reason : undefined,- instruction: typeof params.instruction === "string" ? params.instruction : undefined,- wait: typeof params.wait === "boolean" ? params.wait : undefined,- timeout: typeof params.timeout === "number" ? params.timeout : undefined,- }, resolveToolSearchPeerId(ctx, session));- },- }),- { name: "add_resource" },- );- }-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "add_skill",- label: "Add Skill (OpenViking)",- description:- "Use only when the user explicitly asks to import, add, install, or register a skill into OpenViking. " +- "Set source to a local SKILL.md file or skill directory, or data to raw SKILL.md content or an MCP tool dict.",- parameters: Type.Object({- source: Type.Optional(Type.String({ description: "Local SKILL.md path or skill directory path" })),- data: Type.Optional(Type.Any({ description: "Raw SKILL.md content or MCP tool dict" })),- wait: Type.Optional(Type.Boolean({ description: "Wait for processing to complete" })),- timeout: Type.Optional(Type.Number({ description: "Timeout in seconds when wait is true" })),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- 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,- },- resolveToolSearchPeerId(ctx, session),- );- },- }),- { name: "add_skill" },- );-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "ov_search",- label: "Search (OpenViking)",- description:- "Search OpenViking resources and skills. Use after importing, or when the user asks to search OpenViking resources or skills. " +- "Search only returns ranked snippets; call ov_read on exact hit URIs before answering precise questions. " +- "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 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>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("ov_search");- }- const session = resolvePluginSessionRouting(ctx);- const peerId = resolveToolSearchPeerId(ctx, session);- return searchOpenViking({- query: String((params as { query?: unknown }).query ?? ""),- uri: typeof params.uri === "string" ? params.uri : undefined,- limit: typeof params.limit === "number" ? params.limit : undefined,- }, session, peerId);- },- }),- { name: "ov_search" },- );-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "ov_read",- label: "Read (OpenViking)",- description:- "Read the full original content of one exact OpenViking URI returned by ov_search or ov_list. " +- "Use after ov_search before answering precise documentation, codebase, configuration, or procedural questions. " +- "Do not use filesystem read/cat for viking:// URIs.",- parameters: Type.Object({- uri: Type.String({ description: "Exact OpenViking URI to read, e.g. viking://resources/project/docs/step-1.md" }),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("ov_read");- }- const session = resolvePluginSessionRouting(ctx);- const actorPeerId = resolveToolSearchPeerId(ctx, session);- return readOpenViking({- uri: String((params as { uri?: unknown }).uri ?? ""),- }, actorPeerId);- },- }),- { name: "ov_read" },- );-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "ov_multi_read",- label: "Multi Read (OpenViking)",- description:- "Read the full original content of multiple exact OpenViking URIs concurrently. " +- "Use after ov_search and ov_list to read an overview plus sibling chunks for split documents or multi-step procedures.",- parameters: Type.Object({- uris: Type.Array(Type.String({ description: "Exact OpenViking URI to read" }), {- description: "Exact OpenViking URIs to read",- }),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- 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 }, actorPeerId);- },- }),- { name: "ov_multi_read" },- );-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "ov_list",- label: "List (OpenViking)",- description:- "List files and directories under an OpenViking URI. Use after ov_search to inspect a hit's parent directory, sibling chunks, or .overview.md files when search only returns ranked snippets.",- parameters: Type.Object({- uri: Type.String({ description: "OpenViking directory URI to list, e.g. viking://resources/project/docs" }),- recursive: Type.Optional(Type.Boolean({ description: "List nested entries recursively. Default: false" })),- simple: Type.Optional(Type.Boolean({ description: "Return only URI entries from OpenViking. Default: false" })),- limit: Type.Optional(Type.Number({ description: "Maximum entries to list. Default: 100" })),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- 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,- }, actorPeerId);- },- }),- { name: "ov_list" },- );-- api.registerCommand?.({- name: "add-resource",- description: "Add a resource into OpenViking.",- acceptsArgs: true,- handler: async (ctx: PluginCommandContext) => {- try {- if (isBypassedSession(ctx)) {- const bypassed = makeBypassedToolResult("add_resource");- return { text: bypassed.content[0]!.text, details: bypassed.details };- }- const session = resolvePluginSessionRouting(ctx);- const input = parseAddResourceCommandArgs(ctx.args ?? "");- 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)}` };- }- },+ const recallTraceRuntime = createOpenVikingRecallTraceRuntime({+ getClient,+ resolvePluginSessionRouting,+ traceRecorder,+ registerRecallTraceRoutes: registerRecallTraceRouteAdapters,+ normalizeResourceTypes,+ clampScore,+ previewText,+ cfg,});+ const { queryRecallTraces, formatRecallTraceText, registerRecallTraceRoutes } = recallTraceRuntime;- api.registerCommand?.({- name: "add-skill",- description: "Add a skill into OpenViking.",- acceptsArgs: true,- handler: async (ctx: PluginCommandContext) => {- try {- if (isBypassedSession(ctx)) {- const bypassed = makeBypassedToolResult("add_skill");- return { text: bypassed.content[0]!.text, details: bypassed.details };- }- const session = resolvePluginSessionRouting(ctx);- const input = parseAddSkillCommandArgs(ctx.args ?? "");- 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)}` };- }- },+ const handleQueryConfigCommand = createOpenVikingQueryConfigCommandHandler({+ resolvePluginSessionRouting,+ toQueryConfigContext,+ queryConfigStore,+ normalizeRuntimeQueryParams,});- api.registerCommand?.({- name: "ov-search",- description: "Search OpenViking resources and skills.",- acceptsArgs: true,- handler: async (ctx: PluginCommandContext) => {- try {- if (isBypassedSession(ctx)) {- const bypassed = makeBypassedToolResult("ov_search");- return { text: bypassed.content[0]!.text, details: bypassed.details };- }- const session = resolvePluginSessionRouting(ctx);- const input = parseOVSearchCommandArgs(ctx.args ?? "");- const peerId = resolveToolSearchPeerId(ctx, 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)}` };- }- },+ const { addResourceOpenViking, addSkillOpenViking } = createOpenVikingImportRuntime({+ getClient,});- api.registerCommand?.({- name: "ov-query-config",- description: "Get or update OpenViking runtime query config.",- acceptsArgs: true,- handler: async (ctx: PluginCommandContext) => {- try {- if (isBypassedSession(ctx)) {- const bypassed = makeBypassedToolResult("ov-query-config");- return { text: bypassed.content[0]!.text, details: bypassed.details };- }- const parsed = parseFlagArgs(ctx.args ?? "");- const action = parsed.positionals[0] ?? "get";- const rawScope = getStringFlag(parsed.flags, "scope");- const scope: "claw" | "session" =- rawScope === "peer" || rawScope === "claw" ? "claw" : "session";- const session = resolvePluginSessionRouting(ctx);- const queryCtx = toQueryConfigContext(session);-- if (action === "get") {- const effective = await queryConfigStore.getEffective(queryCtx);- return { text: JSON.stringify({ scope, effective }, null, 2), details: { scope, effective } };- }- if (action === "set") {- const patch = parseQueryConfigPatch(parsed.flags);- const { params, warnings } = normalizeRuntimeQueryParams(patch as RuntimeQueryParams & Record<string, unknown>);- if (Object.keys(params).length === 0) {- throw new Error("No query config parameters provided for /ov-query-config set");- }- await queryConfigStore.set(scope, queryCtx, params);- const effective = await queryConfigStore.getEffective(queryCtx);- return {- text: `Updated OpenViking query config (${scope}).${warnings.length ? ` Warnings: ${warnings.join("; ")}` : ""}`,- details: { scope, params, warnings, effective },- };- }- if (action === "unset") {- const fields = parsed.positionals.slice(1);- if (fields.length === 0) {- throw new Error("Usage: /ov-query-config unset <field...> [--scope session|peer]");- }- await queryConfigStore.unset(scope, queryCtx, fields);- const effective = await queryConfigStore.getEffective(queryCtx);- return {- text: `Unset OpenViking query config fields (${scope}): ${fields.join(", ")}`,- details: { scope, fields, effective },- };- }- if (action === "reset") {- await queryConfigStore.reset(scope, queryCtx);- const effective = await queryConfigStore.getEffective(queryCtx);- return { text: `Reset OpenViking query config (${scope}).`, details: { scope, effective } };- }- throw new Error("Usage: /ov-query-config get|set|unset|reset [--scope session|peer] [--recallLimit N] [--candidateLimit N] [--scoreThreshold N] [--resourceTypes user,resource]");- } catch (err) {- return { text: `OpenViking query config failed: ${err instanceof Error ? err.message : String(err)}` };- }- },+ const queryRuntime = createOpenVikingQueryRuntime({+ getClient,+ queryConfigStore,+ toQueryConfigContext,+ traceRecorder,+ inferRecallResourceType,+ createTraceId,+ boundTraceQuery,+ previewText,+ logger: api.logger,+ cfg,});-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "memory_recall",- label: "Memory Recall (OpenViking)",- description:- "Search long-term memories from OpenViking. Use when you need past user preferences, facts, or decisions.",- parameters: Type.Object({- query: Type.String({ description: "Search query" }),- limit: Type.Optional(- Type.Number({ description: "Max results (default: plugin config)" }),- ),- scoreThreshold: Type.Optional(- Type.Number({ description: "Minimum score (0-1, default: plugin config)" }),- ),- targetUri: Type.Optional(- Type.String({ description: "Search scope URI (default: plugin config)" }),- ),- resourceTypes: Type.Optional(- Type.Array(Type.String({ description: "resource, user, or agent; used when targetUri is omitted. Use ov_archive_search/ov_archive_expand for session history." })),- ),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("memory_recall");- }- const session = resolvePluginSessionRouting(ctx);- const peerId = resolveToolSearchPeerId(ctx, session);- const { query } = params as { query: string };- const requestOverrides: RuntimeQueryParams = {};- if (typeof (params as { limit?: number }).limit === "number") {- requestOverrides.recallLimit = (params as { limit: number }).limit;- }- if (typeof (params as { scoreThreshold?: number }).scoreThreshold === "number") {- requestOverrides.scoreThreshold = (params as { scoreThreshold: number }).scoreThreshold;- }- if (typeof (params as { targetUri?: string }).targetUri === "string") {- requestOverrides.targetUri = (params as { targetUri: string }).targetUri;- }- if (Object.prototype.hasOwnProperty.call(params, "resourceTypes")) {- requestOverrides.resourceTypes = (params as { resourceTypes?: unknown }).resourceTypes as RuntimeQueryParams["resourceTypes"];- }- const effectiveQuery = await queryConfigStore.getEffective(- toQueryConfigContext(session),- requestOverrides,- );- const limit = effectiveQuery.recallLimit;- const scoreThreshold = effectiveQuery.scoreThreshold;- const targetUri = effectiveQuery.targetUri;- const requestedResourceTypes = effectiveQuery.resourceTypes;- const requestLimit = effectiveQuery.candidateLimit;- const recallPreferAbstract = effectiveQuery.sources.recallPreferAbstract === "static"- ? false- : effectiveQuery.recallPreferAbstract;-- const recallClient = await getClient();- if (cfg.logFindRequests) {- api.logger.info(- `openviking: memory_recall assistant_peer_id="${session.agentId}" ` +- `peer_id="${peerId ?? ""}" ` +- `(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();- result = await recallClient.find(- query,- {- targetUri,- limit: requestLimit,- scoreThreshold: 0,- actorPeerId: peerId,- },- );- const traceResults = [- ...(result.memories ?? []).map((item) => toTraceResult(item, "memory")),- ...(result.resources ?? []).map((item) => toTraceResult(item, "resource")),- ...(result.skills ?? []).map((item) => toTraceResult(item, "skill")),- ].slice(0, cfg.traceRecallMaxResultsPerSearch);- memoryRecallSearches = [{- resourceType: inferRecallResourceType(targetUri) ?? "resource",- targetUriInput: targetUri,- targetUriResolved: targetUri,- limit: requestLimit,- scoreThreshold,- durationMs: Date.now() - started,- total: result.total ?? traceResults.length,- results: traceResults,- }];- } else {- const searchPlan = resolveRecallSearchPlan(requestedResourceTypes ?? cfg.recallTargetTypes, {- ovSessionId: session.ovSessionId,- agentId: session.agentId,- });- requestedTraceResourceTypes = searchPlan.resourceTypes;- memoryRecallSearches.push(...searchPlan.skipped.map((skipped) => ({- resourceType: skipped.resourceType,- limit: requestLimit,- scoreThreshold,- durationMs: 0,- total: 0,- results: [],- error: skipped.reason,- })));- const searchPromises = searchPlan.searches.map((search) =>- recallClient.find(- query,- {- targetUri: search.targetUri,- limit: requestLimit,- scoreThreshold: 0,- contextType: search.contextType,- actorPeerId: peerId,- },- ),- );- const settled = await Promise.allSettled(searchPromises);- const allMemories: FindResultItem[] = [];- for (let index = 0; index < settled.length; index += 1) {- const s = settled[index]!;- const search = searchPlan.searches[index]!;- if (s.status === "fulfilled") {- allMemories.push(...(s.value.memories ?? []), ...(s.value.resources ?? []));- const traceResults = [- ...(s.value.memories ?? []).map((item) => toTraceResult(item, "memory")),- ...(s.value.resources ?? []).map((item) => toTraceResult(item, "resource")),- ...(s.value.skills ?? []).map((item) => toTraceResult(item, "skill")),- ].slice(0, cfg.traceRecallMaxResultsPerSearch);- memoryRecallSearches.push({- resourceType: search.resourceType,- contextType: search.contextType,- targetUriInput: search.targetUri,- targetUriResolved: search.targetUri,- limit: requestLimit,- scoreThreshold,- durationMs: 0,- total: s.value.total ?? traceResults.length,- results: traceResults,- });- } else {- memoryRecallSearches.push({- resourceType: search.resourceType,- contextType: search.contextType,- targetUriInput: search.targetUri,- targetUriResolved: search.targetUri,- limit: requestLimit,- scoreThreshold,- durationMs: 0,- total: 0,- results: [],- error: s.reason instanceof Error ? s.reason.message : String(s.reason),- });- }- }- const uniqueMemories = allMemories.filter((memory, index, self) =>- index === self.findIndex((m) => m.uri === memory.uri)- );- const leafOnly = uniqueMemories.filter((m) => !m.level || m.level === 2);- result = {- memories: leafOnly,- total: leafOnly.length,- };- }-- const leafOnly = (result.memories ?? []).filter((m) => !m.level || m.level === 2);- const processed = postProcessMemories(leafOnly, {- limit: requestLimit,- scoreThreshold,- });- const memories = pickMemoriesForInjection(processed, limit, query, scoreThreshold, {- weights: effectiveQuery.rankingWeights,- categoryWeights: effectiveQuery.categoryWeights,- resourceTypeWeights: effectiveQuery.resourceTypeWeights,- });- const candidateTraceResults = leafOnly- .map((item) => toTraceResult(item, inferRecallResourceType(item.uri) === "resource" ? "resource" : "memory"))- .slice(0, cfg.traceRecallMaxResultsPerSearch);- const traceResourceTypes = [...new Set(- (requestedTraceResourceTypes ?? (targetUri ? [inferRecallResourceType(targetUri)] : memoryRecallSearches.map((search) => search.resourceType)))- .filter((resourceType): resourceType is RecallResourceType => Boolean(resourceType) && resourceType !== "archive"),- )];- const recordMemoryRecallTrace = async (injectedUris: Set<string>) => {- await traceRecorder?.recordAndFlush({- schemaVersion: "1.0",- traceId: createTraceId("memory_recall"),- ts: Date.now(),- sessionId: session.sessionId,- sessionKey: session.sessionKey,- ovSessionId: session.ovSessionId,- agentId: session.agentId,- source: "memory_recall",- operationType: "semantic_find",- resourceTypes: traceResourceTypes.length > 0 ? traceResourceTypes : ["user"],- trigger: boundTraceQuery(query, cfg.traceRecallQueryMaxChars),- searches: memoryRecallSearches.length > 0 ? memoryRecallSearches : [{- resourceType: inferRecallResourceType(targetUri) ?? "user",- contextType: targetUri ? undefined : "memory",- targetUriInput: targetUri,- targetUriResolved: targetUri,- limit: requestLimit,- scoreThreshold,- durationMs: 0,- total: result.total ?? leafOnly.length,- results: candidateTraceResults,- }],- selected: memories.map((item) => ({- uri: item.uri,- resourceType: inferRecallResourceType(item.uri),- category: item.category,- score: item.score,- abstractPreview: previewText(item.abstract || item.overview, cfg.traceRecallPreviewChars),- injected: injectedUris.has(item.uri),- displayed: injectedUris.has(item.uri),- })),- stats: {- candidateCount: leafOnly.length,- selectedCount: memories.length,- injectedCount: injectedUris.size,- },- });- };- if (memories.length === 0) {- await recordMemoryRecallTrace(new Set());- return {- content: [{ type: "text", text: "No relevant OpenViking memories found." }],- details: { count: 0, total: result.total ?? 0, scoreThreshold },- };- }- const { lines: memoryLines } = await buildMemoryLinesWithBudget(- memories,- (uri) => recallClient.read(uri, peerId),- {- recallPreferAbstract,- recallMaxInjectedChars: effectiveQuery.maxInjectedChars,- },- );- if (memoryLines.length === 0) {- await recordMemoryRecallTrace(new Set());- return {- content: [- {- type: "text",- text: `No complete OpenViking memories fit recallMaxInjectedChars=${effectiveQuery.maxInjectedChars}.`,- },- ],- details: {- count: 0,- memories,- total: result.total ?? memories.length,- scoreThreshold,- requestLimit,- recallMaxInjectedChars: effectiveQuery.maxInjectedChars,- queryConfig: effectiveQuery,- },- };- }- await recordMemoryRecallTrace(new Set(memories.slice(0, memoryLines.length).map((item) => item.uri)));- return {- content: [- {- type: "text",- text: `Found ${memoryLines.length} memories:\n\n${memoryLines.join("\n")}`,- },- ],- details: {- count: memoryLines.length,- memories,- total: result.total ?? memories.length,- scoreThreshold,- requestLimit,- recallMaxInjectedChars: effectiveQuery.maxInjectedChars,- queryConfig: effectiveQuery,- },- };- },- }),- { name: "memory_recall" },- );-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "ov_recall_trace",- label: "Recall Trace (OpenViking)",- description: "Query OpenViking recall trace records captured by auto-recall and explicit recall/search tools.",- parameters: Type.Object({- turn: Type.Optional(Type.String({ description: "latest or all (default: latest)" })),- traceId: Type.Optional(Type.String({ description: "Exact trace id" })),- sessionId: Type.Optional(Type.String({ description: "OpenClaw session id" })),- sessionKey: Type.Optional(Type.String({ description: "OpenClaw session key" })),- ovSessionId: Type.Optional(Type.String({ description: "OpenViking session id" })),- source: Type.Optional(Type.String({ description: "auto_recall, memory_recall, ov_search, or ov_archive_search" })),- resourceTypes: Type.Optional(Type.Array(Type.String({ description: "resource, user, or agent" }))),- since: Type.Optional(Type.Number({ description: "Unix timestamp lower bound in milliseconds" })),- until: Type.Optional(Type.Number({ description: "Unix timestamp upper bound in milliseconds" })),- includeContent: Type.Optional(Type.Boolean({ description: "Read selected/displayed URI content previews on demand" })),- limit: Type.Optional(Type.Number({ description: "Maximum traces to return (default: 20)" })),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("ov_recall_trace");- }- const session = resolvePluginSessionRouting(ctx);- const result = await queryRecallTraces(- params as RecallTraceToolInput,- session,- resolveToolSearchPeerId(ctx, session),- );- return {- content: [{ type: "text" as const, text: formatRecallTraceText(result) }],- details: {- action: "queried",- count: result.entries.length,- lookupLayer: result.lookupLayer,- warnings: result.warnings,- entries: result.entries,- },- };- },- }),- { name: "ov_recall_trace" },- );-- api.registerCommand?.({- name: "ov-recall-trace",- description: "Query OpenViking recall trace records.",- acceptsArgs: true,- handler: async (ctx: PluginCommandContext) => {- try {- if (isBypassedSession(ctx)) {- const bypassed = makeBypassedToolResult("ov_recall_trace");- return { text: bypassed.content[0]!.text, details: bypassed.details };- }- const session = resolvePluginSessionRouting(ctx);- const flags = parseFlagArgs(ctx.args ?? "").flags;- const input: RecallTraceToolInput = {- turn: getStringFlag(flags, "turn") as "latest" | "all" | undefined,- traceId: getStringFlag(flags, "trace-id"),- sessionId: getStringFlag(flags, "session-id"),- sessionKey: getStringFlag(flags, "session-key"),- ovSessionId: getStringFlag(flags, "ov-session-id"),- source: getStringFlag(flags, "source") as RecallTraceSource | undefined,- resourceTypes: getStringFlag(flags, "resource-types"),- since: getNumberFlag(flags, "since"),- until: getNumberFlag(flags, "until"),- includeContent: getBoolFlag(flags, "include-content"),- limit: getNumberFlag(flags, "limit"),- };- const result = await queryRecallTraces(input, session, resolveToolSearchPeerId(ctx, session));- return {- text: formatRecallTraceText(result),- details: {- count: result.entries.length,- lookupLayer: result.lookupLayer,- warnings: result.warnings,- entries: result.entries,- },- };- } catch (err) {- return { text: `OpenViking recall trace query failed: ${err instanceof Error ? err.message : String(err)}` };- }- },+ const {+ searchOpenViking,+ readOpenVikingContent,+ multiReadOpenVikingContent,+ listOpenVikingDirectory,+ } = queryRuntime;++ registerOpenVikingImportTools({+ registerTool: registerOpenVikingTool,+ getClient,+ resolvePluginSessionRouting,+ isBypassedSession,+ makeBypassedToolResult,+ enableAddResourceTool: cfg.enableAddResourceTool,});- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "memory_store",- label: "Memory Store (OpenViking)",- description:- "Store text in OpenViking memory pipeline by writing to a session and running memory extraction. Use when the user explicitly asks to remember, save, or store an important long-term fact, preference, project, or decision; automatic capture is threshold/commit dependent.",- parameters: Type.Object({- text: Type.String({ description: "Information to store as memory source text" }),- role: Type.Optional(Type.String({ description: "Session role, default user" })),- sessionId: Type.Optional(Type.String({ description: "Existing OpenViking session ID" })),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("memory_store");- }- const session = resolvePluginSessionRouting(ctx);- const { text } = params as { text: string };- const role =- typeof (params as { role?: string }).role === "string"- ? (params as { role: string }).role- : "user";- const explicitSessionId =- typeof (params as { sessionId?: unknown }).sessionId === "string" &&- (params as { sessionId: string }).sessionId.trim()- ? openClawSessionRefToOvStorageId((params as { sessionId: string }).sessionId)- : undefined;-- if (cfg.logFindRequests) {- api.logger.info?.(- `openviking: memory_store invoked (textLength=${text?.length ?? 0}, sessionId=${explicitSessionId ?? "auto"})`,- );- }-- let sessionId = explicitSessionId;- let usedTempSession = false;- try {- const c = await getClient();- if (!sessionId) {- sessionId = `memory-store-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;- usedTempSession = true;- }- const peerId = resolveMessagePeerId({- peerRole: cfg.peer_role,- role,- personPeerId: toPeerId(extractToolSenderId(ctx)),- assistantPeerId: session.agentId,- });- if (defaultMemoryPolicy) {- await c.ensureSession(- sessionId,- { memoryPolicy: defaultMemoryPolicy },- );- }- await c.addSessionMessage(- sessionId,- role,- [{ type: "text" as const, text }],- undefined,- peerId,- );- const commitResult = await c.commitSession(sessionId, {- wait: true,- keepRecentCount: 0,- });- const memoriesCount = totalCommitMemories(commitResult);- if (commitResult.status === "failed") {- api.logger.warn(- `openviking: memory_store commit failed (sessionId=${sessionId}): ${commitResult.error ?? "unknown"}`,- );- return {- content: [{ type: "text", text: `Memory extraction failed for session ${sessionId}: ${commitResult.error ?? "unknown"}` }],- details: {- action: "failed",- sessionId,- status: "failed",- error: commitResult.error,- usedTempSession,- },- };- }- if (commitResult.status === "timeout") {- api.logger.warn(- `openviking: memory_store commit timed out (sessionId=${sessionId}), task_id=${commitResult.task_id ?? "none"}. Memories may still be extracting in background.`,- );- return {- content: [{ type: "text", text: `Memory extraction timed out for session ${sessionId}. It may still complete in the background (task_id=${commitResult.task_id ?? "none"}).` }],- details: {- action: "timeout",- sessionId,- status: "timeout",- taskId: commitResult.task_id,- usedTempSession,- },- };- }- if (memoriesCount === 0) {- api.logger.warn(- `openviking: memory_store committed but 0 memories extracted (sessionId=${sessionId}). ` +- "No OpenViking-managed long-term memory was created. Check memory.extraction_enabled, VLM configuration/API keys, or whether the text was judged not durable.",- );- return {- content: [- {- type: "text",- text:- `Memory extraction completed for session ${sessionId}, but produced 0 memories. ` +- "No OpenViking-managed long-term memory was stored. Check memory.extraction_enabled, VLM configuration/API keys, or whether the text is durable enough to remember.",- },- ],- details: {- action: "failed",- sessionId,- status: commitResult.status,- error: "no_memories_extracted",- memoriesCount,- archived: commitResult.archived ?? false,- usedTempSession,- },- };- } else {- api.logger.info?.(`openviking: memory_store committed, memories=${memoriesCount}`);- }- return {- content: [- {- type: "text",- text: `Stored in OpenViking session ${sessionId} and committed ${memoriesCount} memories.`,- },- ],- details: {- action: "stored",- sessionId,- memoriesCount,- status: commitResult.status,- archived: commitResult.archived ?? false,- usedTempSession,- },- };- } catch (err) {- api.logger.warn(`openviking: memory_store failed: ${String(err)}`);- throw err;- }- },- }),- { name: "memory_store" },- );-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "memory_forget",- label: "Memory Forget (OpenViking)",- description:- "Forget memory by URI, or search then delete when a strong single match is found.",- parameters: Type.Object({- uri: Type.Optional(Type.String({ description: "Exact memory URI to delete" })),- query: Type.Optional(Type.String({ description: "Search query to find memory URI" })),- targetUri: Type.Optional(- Type.String({ description: "Search scope URI (default: plugin config)" }),- ),- limit: Type.Optional(Type.Number({ description: "Search limit (default: 5)" })),- scoreThreshold: Type.Optional(- Type.Number({ description: "Minimum score (0-1, default: plugin config)" }),- ),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("memory_forget");- }- const session = resolvePluginSessionRouting(ctx);- const peerId = resolveToolSearchPeerId(ctx, session);- const client = await getClient();- const uri = (params as { uri?: string }).uri;- if (uri) {- if (!isMemoryUri(uri)) {- return {- content: [{ type: "text", text: `Refusing to delete non-memory URI: ${uri}` }],- details: { action: "rejected", uri },- };- }- await client.deleteUri(uri, peerId);- return {- content: [{ type: "text", text: `Forgotten: ${uri}` }],- details: { action: "deleted", uri },- };- }-- const query = (params as { query?: string }).query;- if (!query) {- return {- content: [{ type: "text", text: "Provide uri or query." }],- details: { error: "missing_param" },- };- }-- const limit =- typeof (params as { limit?: number }).limit === "number"- ? Math.max(1, Math.floor((params as { limit: number }).limit))- : 5;- const scoreThreshold =- typeof (params as { scoreThreshold?: number }).scoreThreshold === "number"- ? Math.max(0, Math.min(1, (params as { scoreThreshold: number }).scoreThreshold))- : cfg.recallScoreThreshold;- const targetUri =- typeof (params as { targetUri?: string }).targetUri === "string"- ? (params as { targetUri: string }).targetUri- : cfg.targetUri;- const requestLimit = Math.max(limit * 4, 20);-- const result = await client.find(- query,- {- targetUri,- limit: requestLimit,- scoreThreshold: 0,- actorPeerId: peerId,- },- );- const candidates = postProcessMemories(result.memories ?? [], {- limit: requestLimit,- scoreThreshold,- leafOnly: true,- }).filter((item) => isMemoryUri(item.uri));- if (candidates.length === 0) {- return {- content: [- {- type: "text",- text: "No matching leaf memory candidates found. Try a more specific query.",- },- ],- details: { action: "none", scoreThreshold },- };- }- const top = candidates[0];- if (candidates.length === 1 && clampScore(top.score) >= 0.85) {- await client.deleteUri(top.uri, peerId);- return {- content: [{ type: "text", text: `Forgotten: ${top.uri}` }],- details: { action: "deleted", uri: top.uri, score: top.score ?? 0 },- };- }-- const list = candidates- .map((item) => `- ${item.uri} (${(clampScore(item.score) * 100).toFixed(0)}%)`)- .join("\n");-- return {- content: [- {- type: "text",- text: `Found ${candidates.length} candidates. Specify uri:\n${list}`,- },- ],- details: { action: "candidates", candidates, scoreThreshold, requestLimit },- };- },- }),- { name: "memory_forget" },- );-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "ov_archive_search",- label: "Archive Search (OpenViking)",- description:- "Keyword-grep across all archived original conversation messages of the current session. " +- "Use this whenever the [Session History Summary] does not contain the specific detail " +- "the user is asking about. Extract 2-3 concrete entity words from the question " +- "(names, places, objects, dates) and search each separately. " +- "Only conclude information is unavailable after trying at least 2 different keyword variations.",- parameters: Type.Object({- query: Type.String({- description:- "A single keyword or short phrase to grep. Use concrete nouns, names, dates, " +- "or distinctive phrases. Case-insensitive. Prefer entity words over full sentences.",- }),- archiveId: Type.Optional(- Type.String({- description: 'Optional: limit search to one archive (e.g. "archive_005")',- }),- ),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("ov_archive_search");- }- rememberSessionAgentId(ctx);- const sessionId = ctx.sessionId ?? "";- const sessionKey = ctx.sessionKey ?? "";- if (!sessionId && !sessionKey) {- return {- content: [{ type: "text", text: "Error: no active session." }],- details: { error: "no_session" },- };- }- const ovSessionId = openClawSessionToOvStorageId(ctx.sessionId, ctx.sessionKey);- const query = String((params as { query?: string }).query ?? "").trim();- const archiveId = (params as { archiveId?: string }).archiveId;-- if (!query) {- return {- content: [{ type: "text", text: "Error: query is required." }],- details: { error: "missing_param", param: "query" },- };- }-- const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");- api.logger.info?.(`openviking: ov_archive_search query="${query}" escaped="${escapedQuery}" archive=${archiveId ?? "all"} session=${ovSessionId}`);-- try {- const client = await getClient();- const started = Date.now();- const result = await client.grepSessionArchives(ovSessionId, escapedQuery, {- archiveId,- caseInsensitive: true,- });- const traceResults: RecallTraceResult[] = (result.matches ?? [])- .slice(0, cfg.traceRecallMaxResultsPerSearch)- .map((match) => ({- uri: match.uri,- resourceType: "archive",- abstractPreview: previewText(match.content, cfg.traceRecallPreviewChars),- resultType: "archive_match",- }));- const recordArchiveTrace = async (displayed: Array<{ uri: string; line: number; content: string }>) => {- await traceRecorder?.recordAndFlush({- schemaVersion: "1.0",- traceId: createTraceId("ov_archive_search"),- ts: Date.now(),- sessionId: ctx.sessionId,- sessionKey: ctx.sessionKey,- ovSessionId,- agentId: ctx.agentId,- source: "ov_archive_search",- operationType: "archive_grep",- resourceTypes: ["session"],- trigger: {- ...boundTraceQuery(query, cfg.traceRecallQueryMaxChars),- derivedKeywords: [query],- },- searches: [{- resourceType: "archive",- targetUriResolved: archiveId- ? `${userSessionUri(ovSessionId)}/history/${archiveId}`- : `${userSessionUri(ovSessionId)}/history`,- limit: cfg.traceRecallMaxResultsPerSearch,- durationMs: Date.now() - started,- total: result.matches?.length ?? result.count ?? 0,- results: traceResults,- archiveId,- caseInsensitive: true,- }],- selected: displayed.map((match) => ({- uri: match.uri,- resourceType: "archive",- line: match.line,- abstractPreview: previewText(match.content, cfg.traceRecallPreviewChars),- displayed: true,- })),- stats: {- candidateCount: result.matches?.length ?? result.count ?? 0,- selectedCount: displayed.length,- injectedCount: 0,- },- });- };-- if (!result.matches || result.matches.length === 0) {- await recordArchiveTrace([]);- return {- content: [{- type: "text",- text: `No matches found for "${query}". Try a different keyword — ` +- "the original conversation may use different wording than the question. " +- "Try synonyms, related terms, or shorter fragments.",- }],- details: { query, matchCount: 0 },- };- }-- const MAX_MATCHES = 12;- const MAX_LINE_LEN = 1500;- const shown = result.matches.slice(0, MAX_MATCHES);- await recordArchiveTrace(shown);- const blocks = shown.map((m, i) => {- const archiveTag = m.uri.match(/archive_\d+/)?.[0] ?? "unknown";- const truncated = m.content.length > MAX_LINE_LEN- ? m.content.slice(0, MAX_LINE_LEN) + "…(truncated)"- : m.content;- return `## Match ${i + 1}: ${archiveTag} (line ${m.line})\n${truncated}`;- });-- const header = `Found ${result.matches.length} match(es) for "${query}"` +- (result.matches.length > MAX_MATCHES ? ` (showing first ${MAX_MATCHES})` : "") + ":";-- return {- content: [{ type: "text", text: header + "\n\n" + blocks.join("\n\n") }],- details: { query, matchCount: result.matches.length },- };- } catch (err: unknown) {- const msg = err instanceof Error ? err.message : String(err);- api.logger.error?.(`openviking: ov_archive_search error: ${msg}`);- return {- content: [{ type: "text", text: `Archive search failed: ${msg}` }],- details: { error: msg },- };- }- },- }),- { name: "ov_archive_search" },- );-- registerOpenVikingTool((ctx: ToolContext) => ({- name: "ov_archive_expand",- label: "Archive Expand (OpenViking)",- description:- "Retrieve original messages from a compressed session archive. " +- "Use when a session summary lacks specific details " +- "such as exact commands, file paths, code snippets, or config values. " +- "Check [Archive Index] to find the right archive ID.",- parameters: Type.Object({- archiveId: Type.String({- description:- 'Archive ID from [Archive Index] (e.g. "archive_002")',- }),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("ov_archive_expand");- }- const session = resolvePluginSessionRouting(ctx);- const archiveId = String((params as { archiveId?: string }).archiveId ?? "").trim();- const sessionId = session.sessionId ?? "";- api.logger.info?.(`openviking: ov_archive_expand invoked (archiveId=${archiveId || "(empty)"}, sessionId=${sessionId || "(empty)"})`);-- if (!archiveId) {- api.logger.warn?.(`openviking: ov_archive_expand missing archiveId`);- return {- content: [{ type: "text", text: "Error: archiveId is required." }],- details: { error: "missing_param", param: "archiveId" },- };- }-- if (!session.ovSessionId) {- return {- content: [{ type: "text", text: "Error: no active session." }],- details: { error: "no_session" },- };- }-- try {- const client = await getClient();- const detail = await client.getSessionArchive(- session.ovSessionId,- archiveId,- );-- const header = [- `## ${detail.archive_id}`,- detail.abstract ? `**Summary**: ${detail.abstract}` : "",- `**Messages**: ${detail.messages.length}`,- "",- ].filter(Boolean).join("\n");-- const body = detail.messages- .map((m: OVMessage) => formatMessageFaithful(m))- .join("\n\n");-- api.logger.info?.(`openviking: ov_archive_expand expanded ${detail.archive_id}, messages=${detail.messages.length}, chars=${body.length}, sessionId=${sessionId}`);- return {- content: [{ type: "text", text: `${header}\n${body}` }],- details: {- action: "expanded",- archiveId: detail.archive_id,- messageCount: detail.messages.length,- sessionId,- ovSessionId: session.ovSessionId,- },- };- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- api.logger.warn?.(`openviking: ov_archive_expand failed (archiveId=${archiveId}, sessionId=${sessionId}): ${msg}`);- return {- content: [{ type: "text", text: `Failed to expand ${archiveId}: ${msg}` }],- details: { error: msg, archiveId, sessionId, ovSessionId: session.ovSessionId },- };- }- },- }), { name: "ov_archive_expand" });-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "openviking_tool_result_read",- label: "Tool Result Read (OpenViking)",- description:- "Restore the full original content of a tool result that was externalized by OpenViking. " +- "Use when a previous tool result was externalized and only a preview is visible — " +- "the preview contains a [tool-result-ref] or viking://user/sessions/.../tool-results/... URI. " +- "\"Read\" tool returns the same truncated preview; this tool returns the complete content. " +- "To read all content: pass offset=0 and a limit large enough to cover the whole result " +- "(e.g. limit=100000). Use offset/limit for paging only when you need a specific section.",- parameters: Type.Object({- tool_output_ref: Type.String({- description:- "Exact OV URI from the preview, e.g. viking://user/sessions/<session_id>/tool-results/<tool_result_id>",- }),- offset: Type.Optional(Type.Number({ description: "Unicode character offset. Default: 0" })),- limit: Type.Optional(Type.Number({ description: "Maximum Unicode characters to read. Default: 20000" })),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("openviking_tool_result_read");- }- const session = resolvePluginSessionRouting(ctx);- if (!session.ovSessionId) {- return {- content: [{ type: "text", text: "Error: no active session." }],- details: { error: "no_session" },- };- }-- const parsed = parseToolResultRef(params.tool_output_ref ?? params.ref ?? params.uri);- if (!parsed) {- return {- content: [{ type: "text", text: "Error: tool_output_ref must be a viking://user/sessions/.../tool-results/... URI." }],- details: { error: "invalid_tool_output_ref" },- };- }- if (parsed.sessionId !== session.ovSessionId) {- return {- content: [{ type: "text", text: "Error: refusing to read a tool result from another session." }],- details: {- error: "session_mismatch",- requestedSessionId: parsed.sessionId,- currentSessionId: session.ovSessionId,- },- };- }-- const offset = Math.max(0, getOptionalInteger(params.offset, 0));- const limit = getOptionalInteger(params.limit, 20_000);- if (limit < -1) {- return {- content: [{ type: "text", text: "Error: limit must be -1 or greater than or equal to 0." }],- details: { error: "invalid_limit", limit },- };- }-- try {- const client = await getClient();- const result = await client.readToolResult(- session.ovSessionId,- parsed.toolResultId,- { offset, limit, includeMetadata: true },- );- const returnedChars = result.content.length;- const nextOffset = result.offset + returnedChars;- const text = result.content || "(empty tool result chunk)";- return {- content: [{ type: "text", text }],- details: {- action: "read",- tool_output_ref: parsed.ref,- tool_result_id: result.tool_result_id,- offset: result.offset,- limit: result.limit,- returned_chars: returnedChars,- total_chars: result.total_chars,- has_more: result.has_more,- next_offset: result.has_more ? nextOffset : null,- metadata: result.metadata ?? null,- },- };- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- api.logger.warn?.(`openviking: openviking_tool_result_read failed: ${msg}`);- return {- content: [{ type: "text", text: `Failed to read tool result: ${msg}` }],- details: { error: msg, tool_output_ref: parsed.ref },- };- }- },- }),- { name: "openviking_tool_result_read" },- );-- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "openviking_tool_result_search",- label: "Tool Result Search (OpenViking)",- description:- "Search inside an externalized tool result for a keyword. " +- "Use when you need to find specific content in a large externalized result, " +- "before reading it with openviking_tool_result_read. " +- "Returns matching snippets with their character offsets.",- parameters: Type.Object({- tool_output_ref: Type.String({- description:- "Exact OV URI from the preview, e.g. viking://user/sessions/<session_id>/tool-results/<tool_result_id>",- }),- query: Type.String({ description: "Keyword or exact text to search for" }),- limit: Type.Optional(Type.Number({ description: "Maximum matches. Default: 20" })),- context_chars: Type.Optional(Type.Number({ description: "Characters around each match. Default: 300" })),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("openviking_tool_result_search");- }- const session = resolvePluginSessionRouting(ctx);- if (!session.ovSessionId) {- return {- content: [{ type: "text", text: "Error: no active session." }],- details: { error: "no_session" },- };- }-- const parsed = parseToolResultRef(params.tool_output_ref ?? params.ref ?? params.uri);- if (!parsed) {- return {- content: [{ type: "text", text: "Error: tool_output_ref must be a viking://user/sessions/.../tool-results/... URI." }],- details: { error: "invalid_tool_output_ref" },- };- }- if (parsed.sessionId !== session.ovSessionId) {- return {- content: [{ type: "text", text: "Error: refusing to search a tool result from another session." }],- details: {- error: "session_mismatch",- requestedSessionId: parsed.sessionId,- currentSessionId: session.ovSessionId,- },- };- }+ registerOpenVikingQueryTools({+ registerTool: registerOpenVikingTool,+ searchOpenViking,+ readOpenVikingContent,+ multiReadOpenVikingContent,+ listOpenVikingDirectory,+ resolvePluginSessionRouting,+ isBypassedSession,+ makeBypassedToolResult,+ });- const query = String(params.query ?? "").trim();- if (!query) {- return {- content: [{ type: "text", text: "Error: query is required." }],- details: { error: "missing_param", param: "query" },- };- }- const limit = getPositiveInteger(params.limit, 20);- const contextChars = Math.max(- 0,- getOptionalInteger(params.context_chars ?? params.contextChars, 300),- );+ registerOpenVikingMemoryRecallTools({+ registerTool: registerOpenVikingTool,+ getClient,+ queryConfigStore,+ toQueryConfigContext,+ resolvePluginSessionRouting,+ isBypassedSession,+ makeBypassedToolResult,+ resolveRecallSearchPlan,+ postProcessMemories,+ pickMemoriesForInjection,+ buildMemoryLinesWithBudget,+ inferRecallResourceType,+ createTraceId,+ boundTraceQuery,+ previewText,+ traceRecorder,+ cfg,+ logger: api.logger,+ });- try {- const client = await getClient();- const result = await client.searchToolResult(- session.ovSessionId,- parsed.toolResultId,- query,- { limit, contextChars },- );- const matches = result.matches ?? [];- const text = matches.length- ? [- `Found ${matches.length} match(es) for "${query}" in ${parsed.ref}:`,- "",- ...matches.map((match, index) =>- `## Match ${index + 1} (offset ${match.offset})\n${match.snippet}`,- ),- ].join("\n")- : `No matches found for "${query}" in ${parsed.ref}.`;- return {- content: [{ type: "text", text }],- details: {- action: "searched",- tool_output_ref: parsed.ref,- tool_result_id: result.tool_result_id,- query,- match_count: matches.length,- matches,- },- };- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- api.logger.warn?.(`openviking: openviking_tool_result_search failed: ${msg}`);- return {- content: [{ type: "text", text: `Failed to search tool result: ${msg}` }],- details: { error: msg, tool_output_ref: parsed.ref, query },- };- }- },- }),- { name: "openviking_tool_result_search" },- );+ registerOpenVikingRecallTraceTools({+ registerTool: registerOpenVikingTool,+ queryRecallTraces,+ formatRecallTraceText,+ resolvePluginSessionRouting,+ isBypassedSession,+ makeBypassedToolResult,+ });- registerOpenVikingTool(- (ctx: ToolContext) => ({- name: "openviking_tool_result_list",- label: "Tool Result List (OpenViking)",- description:- "List externalized tool results for the current session. " +- "Use to discover available refs before calling openviking_tool_result_read. " +- "Optionally filter by tool_name to narrow down results.",- parameters: Type.Object({- tool_name: Type.Optional(Type.String({ description: "Optional exact tool name filter" })),- limit: Type.Optional(Type.Number({ description: "Maximum results. Default: 50" })),- }),- async execute(_toolCallId: string, params: Record<string, unknown>) {- if (isBypassedSession(ctx)) {- return makeBypassedToolResult("openviking_tool_result_list");- }- const session = resolvePluginSessionRouting(ctx);- if (!session.ovSessionId) {- return {- content: [{ type: "text", text: "Error: no active session." }],- details: { error: "no_session" },- };- }+ registerOpenVikingCommands(api, createOpenVikingCommandDefinitions({+ resolvePluginSessionRouting,+ isBypassedSession,+ makeBypassedToolResult,+ parseAddResourceCommandArgs,+ parseAddSkillCommandArgs,+ parseOVSearchCommandArgs,+ addResourceOpenViking,+ addSkillOpenViking,+ searchOpenViking,+ handleQueryConfigCommand,+ queryRecallTraces,+ formatRecallTraceText,+ }));++ registerOpenVikingMemoryTools({+ registerTool: registerOpenVikingTool,+ getClient,+ normalizeSessionId: openClawSessionRefToOvStorageId,+ createTempSessionId: createMemoryStoreTempSessionId,+ extractSenderId: extractToolSenderId,+ toRoleId,+ resolvePluginSessionRouting,+ isBypassedSession,+ makeBypassedToolResult,+ defaultTargetUri: cfg.targetUri,+ defaultRecallScoreThreshold: cfg.recallScoreThreshold,+ logFindRequests: cfg.logFindRequests,+ logger: api.logger,+ });- const toolName =- typeof params.tool_name === "string" && params.tool_name.trim()- ? params.tool_name.trim()- : typeof params.toolName === "string" && params.toolName.trim()- ? params.toolName.trim()- : undefined;- const limit = getPositiveInteger(params.limit, 50);+ registerOpenVikingArchiveTools({+ registerTool: registerOpenVikingTool,+ getClient,+ rememberSessionAgentId,+ toOvSessionId: openClawSessionToOvStorageId,+ resolveAgentId,+ resolvePluginSessionRouting,+ isBypassedSession,+ makeBypassedToolResult,+ formatMessage: formatMessageFaithful,+ traceRecorder,+ traceRecallMaxResultsPerSearch: cfg.traceRecallMaxResultsPerSearch,+ traceRecallPreviewChars: cfg.traceRecallPreviewChars,+ createTraceId,+ logger: api.logger,+ });- try {- const client = await getClient();- const result = await client.listToolResults(- session.ovSessionId,- { toolName, limit },- );- const items = result.tool_results ?? [];- const text = items.length- ? [- `Found ${items.length} externalized tool result(s) in current session:`,- "",- ...items.map((item, index) => {- const ref = typeof item.storage_uri === "string" ? item.storage_uri : "(missing ref)";- const name = typeof item.tool_name === "string" ? item.tool_name : "tool";- const chars = typeof item.original_chars === "number" ? item.original_chars : "unknown";- const created = typeof item.created_at === "string" ? ` created_at=${item.created_at}` : "";- return `${index + 1}. ${name} original_chars=${chars}${created}\nref: ${ref}`;- }),- ].join("\n")- : toolName- ? `No externalized tool results found for tool "${toolName}" in current session.`- : "No externalized tool results found in current session.";- return {- content: [{ type: "text", text }],- details: {- action: "listed",- session_id: session.ovSessionId,- tool_name: toolName ?? null,- count: items.length,- tool_results: items,- },- };- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- api.logger.warn?.(`openviking: openviking_tool_result_list failed: ${msg}`);- return {- content: [{ type: "text", text: `Failed to list tool results: ${msg}` }],- details: { error: msg, session_id: session.ovSessionId, tool_name: toolName ?? null },- };- }- },- }),- { name: "openviking_tool_result_list" },- );+ registerOpenVikingToolResultTools({+ registerTool: registerOpenVikingTool,+ getClient,+ resolvePluginSessionRouting,+ isBypassedSession,+ makeBypassedToolResult,+ logger: api.logger,+ });- let contextEngineRef: ContextEngineWithCommit | null = null;- const sessionAgentResolver = createSessionAgentResolver(cfg.peer_prefix);- const rememberSessionAgentId = (ctx: SessionAgentLookup) => {- sessionAgentResolver.remember(ctx);- };- const resolveAgentId = (- sessionId?: string,- sessionKey?: string,- ovSessionId?: string,- ): string => {- const sid = typeof sessionId === "string" ? sessionId.trim() : "";- const sk = typeof sessionKey === "string" ? sessionKey.trim() : "";- const ovSid = typeof ovSessionId === "string" ? ovSessionId.trim() : "";- const result = sessionAgentResolver.resolve(sid, sk, ovSid);- if (cfg.logFindRequests) {- api.logger.info(- `openviking: resolveAgentId ${JSON.stringify({- sessionId: sid || "(empty)",- sessionKey: sk || "(empty)",- ovSessionId: ovSid || "(empty)",- parsedConfigPeerPrefix: cfg.peer_prefix,- peerRole: cfg.peer_role,- mappedResolvedAgentId: result.mappedResolvedAgentId,- resolvedBeforeSanitize: result.resolvedBeforeSanitize,- resolved: result.resolved,- branch: result.branch,- aliases: result.aliases,- fromExplicitBinding: result.fromExplicitBinding,- })}`,- );- }- return result.resolved;- };+ const { getContextEngine, setContextEngineRef } = createOpenVikingContextEngineRef();- api.on("session_start", async (_event: unknown, ctx?: HookAgentContext) => {- rememberSessionAgentId(ctx ?? {});- });- api.on("session_end", async (_event: unknown, ctx?: HookAgentContext) => {- rememberSessionAgentId(ctx ?? {});- });- api.on("before_reset", async (_event: unknown, ctx?: HookAgentContext) => {- if (isBypassedSession(ctx)) {- verboseRoutingInfo(- `openviking: bypassing before_reset due to session pattern match (sessionKey=${ctx?.sessionKey ?? "none"}, sessionId=${ctx?.sessionId ?? "none"})`,- );- return;- }- const sessionId = ctx?.sessionId;- if (sessionId && contextEngineRef) {- try {- const ok = await contextEngineRef.commitOVSession({- sessionId,- sessionKey: ctx?.sessionKey,- });- if (ok) {- api.logger.info(`openviking: committed OV session on reset for session=${sessionId}`);- }- } catch (err) {- api.logger.warn(`openviking: failed to commit OV session on reset: ${String(err)}`);- }- }- });- api.on("after_compaction", async (_event: unknown, _ctx?: HookAgentContext) => {- // Reserved hook registration for future post-compaction memory integration.+ registerOpenVikingLifecycleHooks({+ api,+ rememberSessionAgentId,+ isBypassedSession,+ verboseRoutingInfo,+ getContextEngine,+ logger: api.logger,});- if (typeof api.registerContextEngine === "function") {- api.registerContextEngine(contextEnginePlugin.id, () => {- contextEngineRef = createMemoryOpenVikingContextEngine({- id: contextEnginePlugin.id,- name: contextEnginePlugin.name,- version: "0.1.0",- cfg,- logger: api.logger,- getClient,- resolveAgentId,- rememberSessionAgentId,- queryConfigStore,- traceRecorder,- });- return contextEngineRef;- });- api.logger.info(- "openviking: registered context-engine (assemble=archive+active+auto-recall, afterTurn=auto-capture, session→OV id=uuid-or-sha256 + diag/Phase2 options)",- );- } else {- api.logger.warn(- "openviking: registerContextEngine is unavailable; context-engine behavior will not run",- );- }+ registerOpenVikingContextEngine({+ api,+ plugin: contextEnginePlugin,+ version: "0.1.0",+ cfg,+ logger: api.logger,+ getClient,+ resolveAgentId,+ rememberSessionAgentId,+ queryConfigStore,+ traceRecorder,+ createContextEngine: createMemoryOpenVikingContextEngine,+ setContextEngineRef,+ });registerSetupCli(api);-- api.registerService({- id: "openviking",- start: async (ctx?: unknown) => {- await queryConfigReady;- const routeRegistered = registerRecallTraceRoutes(ctx);- await (await getClient()).healthCheck().catch(() => {});- api.logger.info(- `openviking: initialized (url: ${cfg.baseUrl}, targetUri: ${cfg.targetUri}, search: hybrid endpoint)`,- );- if (routeRegistered) {- api.logger.info("openviking: registered recall trace Gateway routes");- } else {- api.logger.warn?.("openviking: recall trace Gateway route adapter unavailable; use ov_recall_trace tool or /ov-recall-trace command");- }- },- stop: () => {- api.logger.info("openviking: stopped");- },- });+ const recallTraceHttpRoutesRegistered = registerRecallTraceRoutes(api);++ api.registerService(createOpenVikingService({+ cfg,+ getClient,+ logger: api.logger,+ recallTraceHttpRoutesRegistered,+ registerRecallTraceRoutes,+ }));},};diff --git a/examples/openclaw-plugin/install-manifest.json b/examples/openclaw-plugin/install-manifest.jsonindex 297aef3b5..4b9396585 100644--- a/examples/openclaw-plugin/install-manifest.json+++ b/examples/openclaw-plugin/install-manifest.json@@ -22,9 +22,12 @@"runtime-utils.ts","recall-trace.ts","query-config.ts",- "plugin/openviking-query-formatters.ts",+ "adapters/",+ "registries/",+ "routing/",+ "plugin/",+ "services/","commands/setup.ts",- "plugin/openviking-feature-gates.ts","config/feature-gates.json","tsconfig.json","tsconfig.build.json",diff --git a/examples/openclaw-plugin/memory-ranking.ts b/examples/openclaw-plugin/memory-ranking.tsindex b5fb99fb6..62ea28f62 100644--- a/examples/openclaw-plugin/memory-ranking.ts+++ b/examples/openclaw-plugin/memory-ranking.ts@@ -215,11 +215,7 @@ function buildRecallQueryProfile(query: string): RecallQueryProfile {};}-function lexicalOverlapBoost(- tokens: string[],- text: string,- maxBoost = DEFAULT_RANKING_WEIGHTS.lexicalOverlapMax,-): number {+function lexicalOverlapBoost(tokens: string[], text: string, maxBoost = DEFAULT_RANKING_WEIGHTS.lexicalOverlapMax): number {if (tokens.length === 0 || !text) {return 0;}@@ -236,16 +232,12 @@ function lexicalOverlapBoost(function inferResourceType(item: FindResultItem): string | undefined {if (item.uri.startsWith("viking://resources")) return "resource";if (item.uri.startsWith("viking://session/")) return "session";+ if (item.uri.startsWith("viking://user/skills") || item.uri.startsWith("viking://skills")) return "agent";if (item.uri.startsWith("viking://user/")) return "user";- if (item.uri.startsWith("viking://agent/")) return "agent";return undefined;}-function rankForInjection(- item: FindResultItem,- query: RecallQueryProfile,- options?: RankingOptions,-): number {+function rankForInjection(item: FindResultItem, query: RecallQueryProfile, options?: RankingOptions): number {// Keep ranking simple and stable: semantic score + light query-aware boosts.const weights = { ...DEFAULT_RANKING_WEIGHTS, ...(options?.weights ?? {}) };const baseScore = clampScore(item.score) * weights.baseScore;@@ -255,9 +247,7 @@ function rankForInjection(const preferenceBoost = query.wantsPreference && isPreferencesMemory(item) ? weights.preference : 0;const overlapBoost = lexicalOverlapBoost(query.tokens, `${item.uri} ${abstract}`, weights.lexicalOverlapMax);const category = (item.category ?? "").toLowerCase();- const categoryBoost = category- ? (options?.categoryWeights?.[category] ?? options?.categoryWeights?.[item.category ?? ""] ?? 0)- : 0;+ const categoryBoost = category ? (options?.categoryWeights?.[category] ?? options?.categoryWeights?.[item.category ?? ""] ?? 0) : 0;const resourceType = inferResourceType(item);const resourceTypeBoost = resourceType ? (options?.resourceTypeWeights?.[resourceType] ?? 0) : 0;return baseScore + leafBoost + eventBoost + preferenceBoost + overlapBoost + categoryBoost + resourceTypeBoost;@@ -275,9 +265,7 @@ export function pickMemoriesForInjection(}const query = buildRecallQueryProfile(queryText);- const sorted = [...items].sort((a, b) =>- rankForInjection(b, query, rankingOptions) - rankForInjection(a, query, rankingOptions)- );+ const sorted = [...items].sort((a, b) => rankForInjection(b, query, rankingOptions) - rankForInjection(a, query, rankingOptions));const deduped: FindResultItem[] = [];const seen = new Set<string>();for (const item of sorted) {diff --git a/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md b/examples/openclaw-plugin/openclaw-multi-tenant-test-report.mdindex 8c10e5913..e869f02d6 100644--- a/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md+++ b/examples/openclaw-plugin/openclaw-multi-tenant-test-report.md@@ -5,10 +5,10 @@本轮测试围绕 `examples/openclaw-plugin` 的多租户与会话身份透传能力展开,重点验证以下目标:1. 验证插件在 `api_key` 与 `trusted` 两种服务认证模式下的请求头行为是否正确。-2. 验证插件是否按照服务侧命名空间策略,将 `viking://user/memories` 与 `viking://user/memories` 正确展开为 canonical URI。-3. 验证 `senderId` / `requesterSenderId` 是否能够稳定映射为会话消息的 `peer_id`。+2. 验证插件是否在 account/user 租户身份外,按 `peer_role` / `peer_prefix` 生成一致的 `peer_id` 与 `X-OpenViking-Actor-Peer`。+3. 验证 `senderId` / `requesterSenderId` 是否能够稳定映射为会话消息的 `role_id`。4. 验证 `afterTurn` 与 `memory_store` 两条写会话路径的身份语义是否一致。-5. 验证多租户场景下用户空间、共享资源与 peer/session metadata 的召回行为是否符合预期。+5. 验证多租户场景下默认用户空间与不同 actor peer 视角下的召回行为是否符合预期。## 2. 测试方法@@ -19,16 +19,17 @@- 使用 `curl` 调用 `/health`、`/api/v1/system/status`、`/api/v1/search/find`- 直接验证显式 URI,例如:- `viking://user/default/memories`- - `viking://user/default/skills`- `viking://resources`+ - `viking://user/skills`+ - `viking://session/<session_id>/history`- 通过结构化 seed 与分层 `reindex`,确保召回验证基线可用### 2.2 插件端到端验证通过真实 OpenClaw gateway 与 OpenViking 后端联调验证:-- 远端 `19950`:用于 `api_key` 模式与用户空间验证-- 远端 `19960`:用于 `trusted` 模式与 `peer_id` 验证+- 远端 `19950`:用于 `api_key` 模式与命名空间矩阵验证+- 远端 `19960`:用于 `trusted` 模式与 `role_id` 验证- 使用真实 Feishu 机器人入口验证真实 sender 映射- 结合以下日志进行判定:- `before_prompt_build`@@ -38,11 +39,11 @@### 2.3 真实机器人验证-针对 `peer_id` 透传行为,使用真实机器人私聊/群聊场景复核:+针对 `role_id` 透传行为,使用真实机器人私聊/群聊场景复核:-- 私聊验证真实 sender 到 `peer_id` 的稳定映射-- 群聊验证不同成员写入不同 `peer_id`-- 工具调用验证 `memory_store` 路径是否能通过 `requesterSenderId` 写出 `peer_id`+- 私聊验证真实 sender 到 `role_id` 的稳定映射+- 群聊验证不同成员写入不同 `role_id`+- 工具调用验证 `memory_store` 路径是否能通过 `requesterSenderId` 写出 `role_id`## 3. 测试范围@@ -54,15 +55,18 @@### 3.2 命名空间策略-- user-scoped memory:`viking://user/<user_id>/memories`-- user-scoped skills:`viking://user/<user_id>/skills`-- shared resources:`viking://resources`+- `ff`:user 不按 actor peer 归因,agent 不按 user 隔离+- `tf`:user 按 actor peer 归因,agent 不按 user 隔离+- `tt`:user 按 actor peer 归因,agent 按 user 隔离+- 兼容路径:+ - `legacy peer scope mode=agent`+ - 新 policy 覆盖旧 alias### 3.3 身份透传-- `afterTurn.runtimeContext.senderId -> peer_id`-- `memory_store.requesterSenderId -> peer_id`-- assistant message 不传 `peer_id`+- `afterTurn.runtimeContext.senderId -> role_id`+- `memory_store.requesterSenderId -> role_id`+- assistant message 不传 `role_id`## 4. 测试结果@@ -72,39 +76,44 @@|---|---|---|---|| `api_key` | `api_key_without_key_dev` | 通过 | 不再合成 `default/default` 租户 header || `api_key` | `personal_token_default` | 通过 | 命中 `DEFAULT_USER_TOKEN_19950` |-| `api_key` | `runtime_peer_worker` | 通过 | runtime agent 只参与 peer/session metadata |-| namespace | `user_memory_token` | 通过 | user memory 空间命中正确 |-| namespace | `user_skill_token` | 通过 | user skill 空间命中正确 |-| namespace | `resource_token` | 通过 | shared resource 空间命中正确 |+| `api_key` | `peer_prefix_worker` | 通过 | 实际 agent 值为 `worker_main` |+| 兼容 | `deprecated_agent_alias` | 通过 | `legacy peer scope mode=agent` 兼容正常 |+| 覆盖优先级 | `new_policy_overrides_deprecated` | 通过 | 新 policy 覆盖旧 alias |+| namespace | `ff_user_token` | 通过 | user 共享空间命中正确 |+| namespace | `ff_agent_token` | 通过 | agent 共享空间命中正确 |+| namespace | `tf_user_token` | 通过 | user 按 actor peer 归因命中正确 |+| namespace | `tf_agent_token` | 通过 | agent 共享空间命中正确 |+| namespace | `tt_user_token` | 通过 | user/agent 双隔离命中正确 |+| namespace | `tt_agent_token` | 通过 | agent/user 双隔离命中正确 || `trusted` | `trusted_without_key` | 通过 | 无 key trusted 路径正常 || `trusted` | `trusted_with_key` | 通过 | 带 key trusted 路径正常 || `trusted` | `trusted_root_key_required` | 通过 | 不带 key 被服务侧拒绝 || `trusted` | `trusted_root_key_optional_ok` | 通过 | 带 root key 正常 |-| `senderId -> peer_id` | `senderid_trusted_user_msg` | 通过 | `telegram:12345 -> telegram_12345` |-| `senderId -> peer_id` | `senderid_trusted_blank` | 通过 | `peer_id:null` |-| `senderId -> peer_id` | `senderid_sanitize_symbols` | 通过 | `wx/user-01@abc -> wx_user-01_abc` |-| 真实机器人 | 私聊 sender 映射 | 通过 | sender 稳定映射到真实 `peer_id` |-| 真实机器人 | 群聊多成员 `peer_id` | 通过 | 不同成员落不同 `peer_id` |-| `memory_store` | `requesterSenderId -> peer_id` | 通过 | `memory_store` 已使用 `requesterSenderId` 写出真实 `peer_id` |+| `senderId -> role_id` | `senderid_trusted_user_msg` | 通过 | `telegram:12345 -> telegram_12345` |+| `senderId -> role_id` | `senderid_trusted_blank` | 通过 | `role_id:null` |+| `senderId -> role_id` | `senderid_sanitize_symbols` | 通过 | `wx/user-01@abc -> wx_user-01_abc` |+| 真实机器人 | 私聊 sender 映射 | 通过 | sender 稳定映射到真实 `role_id` |+| 真实机器人 | 群聊多成员 `role_id` | 通过 | 不同成员落不同 `role_id` |+| `memory_store` | `requesterSenderId -> role_id` | 通过 | `memory_store` 已使用 `requesterSenderId` 写出真实 `role_id` |### 4.2 已知说明| 项目 | 状态 | 说明 ||---|---|---|-| `user_token_main_default` | 已打通 | 曾出现一次回答少 `_19950`,属于回答精度问题,不是链路问题 |+| `agent_token_main_default` | 已打通 | 曾出现一次回答少 `_19950`,属于回答精度问题,不是链路问题 || 真实机器人最终回复 | 非插件问题 | 群聊/私聊中出现的 `Something went wrong...` 已定位在 OpenClaw 工具结果回填阶段,与 OpenViking 插件链路无关 |## 5. 关键结论-1. 插件侧 user namespace、显式租户 header 与 `peer_id` 透传能力已完成联调验证。-2. `afterTurn` 路径可通过 `runtimeContext.senderId` 正确写出 `peer_id`。-3. `memory_store` 路径在工具上下文中无法直接读取 `senderId`,但可稳定通过 `requesterSenderId` 写出 `peer_id`。-4. 在真实机器人私聊与群聊场景中,已确认不同用户会被映射为不同的 `peer_id`,且 assistant message 保持 `peer_id:null`。+1. 插件侧 peer identity routing、显式租户 header 与 `role_id` 透传能力已完成联调验证。+2. `afterTurn` 路径可通过 `runtimeContext.senderId` 正确写出 `role_id`。+3. `memory_store` 路径在工具上下文中无法直接读取 `senderId`,但可稳定通过 `requesterSenderId` 写出 `role_id`。+4. 在真实机器人私聊与群聊场景中,已确认不同用户会被映射为不同的 `role_id`,且 assistant message 保持 `role_id:null`。5. 当前 OpenViking 插件链路已满足多租户、命名空间与 sender 身份透传的测试目标。## 6. 建议-1. 若后续服务端对 `api_key + USER` 的 `peer_id` 语义收紧,应补充一条显式兼容说明或服务端协同约束。+1. 若后续服务端对 `api_key + USER` 的 `role_id` 语义收紧,应补充一条显式兼容说明或服务端协同约束。2. 如需继续扩大矩阵,可追加:- 更多账号/用户组合- 不同群聊成员的稳定性回归diff --git a/examples/openclaw-plugin/package.json b/examples/openclaw-plugin/package.jsonindex d9b68ad75..bee1ee326 100644--- a/examples/openclaw-plugin/package.json+++ b/examples/openclaw-plugin/package.json@@ -21,10 +21,13 @@"files": ["dist/","*.ts",+ "adapters/","commands/setup.ts",- "plugin/openviking-feature-gates.ts",- "plugin/openviking-query-formatters.ts","config/feature-gates.json",+ "registries/",+ "routing/",+ "plugin/",+ "services/","!vitest.config.ts","install-manifest.json","openclaw.plugin.json",@@ -37,7 +40,7 @@"skills/"],"scripts": {- "build": "tsc -p tsconfig.build.json",+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json","prepack": "npm run build","test": "vitest run","typecheck": "tsc -p tsconfig.json",diff --git a/examples/openclaw-plugin/plugin/command-registration.ts b/examples/openclaw-plugin/plugin/command-registration.tsnew file mode 100644index 000000000..a414f0576--- /dev/null+++ b/examples/openclaw-plugin/plugin/command-registration.ts@@ -0,0 +1,34 @@+export type PluginCommandContext = {+ args?: string;+ commandBody?: string;+ sessionKey?: string;+ sessionId?: string;+ agentId?: string;+ ovSessionId?: string;+};++export type CommandResult = {+ text: string;+ details?: Record<string, unknown>;+};++export type CommandDefinition = {+ name: string;+ description: string;+ acceptsArgs?: boolean;+ requireAuth?: boolean;+ handler: (ctx: PluginCommandContext) => CommandResult | Promise<CommandResult>;+};++export type OpenVikingCommandRegistrationApi = {+ registerCommand?: (command: CommandDefinition) => void;+};++export function registerOpenVikingCommands(+ api: OpenVikingCommandRegistrationApi,+ commands: CommandDefinition[],+): void {+ for (const command of commands) {+ api.registerCommand?.(command);+ }+}diff --git a/examples/openclaw-plugin/plugin/openviking-archive-tools.ts b/examples/openclaw-plugin/plugin/openviking-archive-tools.tsnew file mode 100644index 000000000..229812594--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-archive-tools.ts@@ -0,0 +1,301 @@+import { Type } from "@sinclair/typebox";+import type { OVMessage } from "../client.js";+import type { RecallTraceEntry, RecallTraceResult } from "../recall-trace.js";++export type OpenVikingArchiveToolContext = {+ sessionKey?: string;+ sessionId?: string;+ agentId?: string;+ senderId?: string;+};++export type OpenVikingArchiveSession = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++type OpenVikingArchiveMatch = {+ uri: string;+ line: number;+ content: string;+};++export type OpenVikingArchiveClient = {+ grepSessionArchives: (+ sessionId: string,+ pattern: string,+ options: { archiveId?: string; caseInsensitive: boolean; agentId?: string },+ ) => Promise<{+ count?: number;+ matches?: OpenVikingArchiveMatch[];+ }>;+ getSessionArchive: (+ sessionId: string,+ archiveId: string,+ agentId?: string,+ ) => Promise<{+ archive_id: string;+ abstract?: string;+ messages: OVMessage[];+ }>;+};++export type OpenVikingArchiveToolsDeps = {+ registerTool: (toolOrFactory: unknown, opts: { name: string }) => void;+ getClient: () => Promise<OpenVikingArchiveClient>;+ rememberSessionAgentId: (ctx: OpenVikingArchiveToolContext) => void;+ toOvSessionId: (sessionId?: string, sessionKey?: string) => string;+ resolveAgentId: (sessionId?: string, sessionKey?: string, ovSessionId?: string) => string;+ resolvePluginSessionRouting: (ctx?: OpenVikingArchiveToolContext) => OpenVikingArchiveSession;+ isBypassedSession: (ctx?: OpenVikingArchiveToolContext) => boolean;+ makeBypassedToolResult: (toolName: string) => unknown;+ formatMessage: (message: OVMessage) => string;+ traceRecorder?: { recordAndFlush: (trace: RecallTraceEntry) => Promise<unknown> | unknown };+ traceRecallMaxResultsPerSearch: number;+ traceRecallPreviewChars: number;+ createTraceId: (source: string) => string;+ logger?: {+ info?: (message: string) => void;+ warn?: (message: string) => void;+ error?: (message: string) => void;+ };+};++function previewText(value: unknown, maxChars: number): string | undefined {+ const text = typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";+ if (!text) {+ return undefined;+ }+ return text.length <= maxChars ? text : `${text.slice(0, Math.max(0, maxChars - 1))}…`;+}++export function registerOpenVikingArchiveTools(deps: OpenVikingArchiveToolsDeps): void {+ deps.registerTool(+ (ctx: OpenVikingArchiveToolContext) => ({+ name: "ov_archive_search",+ label: "Archive Search (OpenViking)",+ description:+ "Keyword-grep across all archived original conversation messages of the current session. " ++ "Use this whenever the [Session History Summary] does not contain the specific detail " ++ "the user is asking about. Extract 2-3 concrete entity words from the question " ++ "(names, places, objects, dates) and search each separately. " ++ "Only conclude information is unavailable after trying at least 2 different keyword variations.",+ parameters: Type.Object({+ query: Type.String({+ description:+ "A single keyword or short phrase to grep. Use concrete nouns, names, dates, " ++ "or distinctive phrases. Case-insensitive. Prefer entity words over full sentences.",+ }),+ archiveId: Type.Optional(+ Type.String({+ description: 'Optional: limit search to one archive (e.g. "archive_005")',+ }),+ ),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("ov_archive_search");+ }+ deps.rememberSessionAgentId(ctx);+ const sessionId = ctx.sessionId ?? "";+ const sessionKey = ctx.sessionKey ?? "";+ if (!sessionId && !sessionKey) {+ return {+ content: [{ type: "text", text: "Error: no active session." }],+ details: { error: "no_session" },+ };+ }+ const ovSessionId = deps.toOvSessionId(ctx.sessionId, ctx.sessionKey);+ const query = String((params as { query?: string }).query ?? "").trim();+ const archiveId = (params as { archiveId?: string }).archiveId;++ if (!query) {+ return {+ content: [{ type: "text", text: "Error: query is required." }],+ details: { error: "missing_param", param: "query" },+ };+ }++ const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ deps.logger?.info?.(`openviking: ov_archive_search query="${query}" escaped="${escapedQuery}" archive=${archiveId ?? "all"} session=${ovSessionId}`);++ try {+ const client = await deps.getClient();+ const agentId = deps.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, deps.traceRecallMaxResultsPerSearch).map((match) => ({+ uri: match.uri,+ resourceType: "archive",+ abstractPreview: previewText(match.content, deps.traceRecallPreviewChars),+ resultType: "archive_match",+ }));++ const recordArchiveTrace = async (displayed: OpenVikingArchiveMatch[]) => {+ await deps.traceRecorder?.recordAndFlush({+ schemaVersion: "1.0",+ traceId: deps.createTraceId("ov_archive_search"),+ ts: Date.now(),+ sessionId: ctx.sessionId,+ sessionKey: ctx.sessionKey,+ ovSessionId,+ agentId,+ source: "ov_archive_search",+ operationType: "archive_grep",+ resourceTypes: ["session"],+ trigger: { query, derivedKeywords: [query] },+ searches: [{+ resourceType: "archive",+ targetUriResolved: archiveId ? `viking://session/${ovSessionId}/history/${archiveId}` : `viking://session/${ovSessionId}/history`,+ limit: deps.traceRecallMaxResultsPerSearch,+ durationMs: Date.now() - started,+ total: result.matches?.length ?? result.count ?? 0,+ results: traceResults,+ archiveId,+ caseInsensitive: true,+ }],+ selected: displayed.map((match) => ({+ uri: match.uri,+ resourceType: "archive",+ line: match.line,+ abstractPreview: previewText(match.content, deps.traceRecallPreviewChars),+ displayed: true,+ })),+ stats: {+ candidateCount: result.matches?.length ?? result.count ?? 0,+ selectedCount: displayed.length,+ injectedCount: 0,+ },+ });+ };++ if (!result.matches || result.matches.length === 0) {+ await recordArchiveTrace([]);+ return {+ content: [{+ type: "text",+ text: `No matches found for "${query}". Try a different keyword — ` ++ "the original conversation may use different wording than the question. " ++ "Try synonyms, related terms, or shorter fragments.",+ }],+ details: { query, matchCount: 0 },+ };+ }++ const MAX_MATCHES = 12;+ const MAX_LINE_LEN = 1500;+ const shown = result.matches.slice(0, MAX_MATCHES);+ await recordArchiveTrace(shown);+ const blocks = shown.map((m, i) => {+ const archiveTag = m.uri.match(/archive_\d+/)?.[0] ?? "unknown";+ const truncated = m.content.length > MAX_LINE_LEN+ ? m.content.slice(0, MAX_LINE_LEN) + "…(truncated)"+ : m.content;+ return `## Match ${i + 1}: ${archiveTag} (line ${m.line})\n${truncated}`;+ });++ const header = `Found ${result.matches.length} match(es) for "${query}"` ++ (result.matches.length > MAX_MATCHES ? ` (showing first ${MAX_MATCHES})` : "") + ":";++ return {+ content: [{ type: "text", text: header + "\n\n" + blocks.join("\n\n") }],+ details: { query, matchCount: result.matches.length },+ };+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ deps.logger?.error?.(`openviking: ov_archive_search error: ${msg}`);+ return {+ content: [{ type: "text", text: `Archive search failed: ${msg}` }],+ details: { error: msg },+ };+ }+ },+ }),+ { name: "ov_archive_search" },+ );++ deps.registerTool((ctx: OpenVikingArchiveToolContext) => ({+ name: "ov_archive_expand",+ label: "Archive Expand (OpenViking)",+ description:+ "Retrieve original messages from a compressed session archive. " ++ "Use when a session summary lacks specific details " ++ "such as exact commands, file paths, code snippets, or config values. " ++ "Check [Archive Index] to find the right archive ID.",+ parameters: Type.Object({+ archiveId: Type.String({+ description:+ 'Archive ID from [Archive Index] (e.g. "archive_002")',+ }),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("ov_archive_expand");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const archiveId = String((params as { archiveId?: string }).archiveId ?? "").trim();+ const sessionId = session.sessionId ?? "";+ deps.logger?.info?.(`openviking: ov_archive_expand invoked (archiveId=${archiveId || "(empty)"}, sessionId=${sessionId || "(empty)"})`);++ if (!archiveId) {+ deps.logger?.warn?.("openviking: ov_archive_expand missing archiveId");+ return {+ content: [{ type: "text", text: "Error: archiveId is required." }],+ details: { error: "missing_param", param: "archiveId" },+ };+ }++ if (!session.ovSessionId) {+ return {+ content: [{ type: "text", text: "Error: no active session." }],+ details: { error: "no_session" },+ };+ }++ try {+ const client = await deps.getClient();+ const detail = await client.getSessionArchive(+ session.ovSessionId,+ archiveId,+ session.agentId,+ );++ const header = [+ `## ${detail.archive_id}`,+ detail.abstract ? `**Summary**: ${detail.abstract}` : "",+ `**Messages**: ${detail.messages.length}`,+ "",+ ].filter(Boolean).join("\n");++ const body = detail.messages+ .map((message) => deps.formatMessage(message))+ .join("\n\n");++ deps.logger?.info?.(`openviking: ov_archive_expand expanded ${detail.archive_id}, messages=${detail.messages.length}, chars=${body.length}, sessionId=${sessionId}`);+ return {+ content: [{ type: "text", text: `${header}\n${body}` }],+ details: {+ action: "expanded",+ archiveId: detail.archive_id,+ messageCount: detail.messages.length,+ sessionId,+ ovSessionId: session.ovSessionId,+ },+ };+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ deps.logger?.warn?.(`openviking: ov_archive_expand failed (archiveId=${archiveId}, sessionId=${sessionId}): ${msg}`);+ return {+ content: [{ type: "text", text: `Failed to expand ${archiveId}: ${msg}` }],+ details: { error: msg, archiveId, sessionId, ovSessionId: session.ovSessionId },+ };+ }+ },+ }), { name: "ov_archive_expand" });+}diff --git a/examples/openclaw-plugin/plugin/openviking-bypass-runtime.ts b/examples/openclaw-plugin/plugin/openviking-bypass-runtime.tsnew file mode 100644index 000000000..d0bc44419--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-bypass-runtime.ts@@ -0,0 +1,26 @@+import {+ compileSessionPatterns,+ shouldBypassSession,+} from "../text-utils.js";++type BypassRuntimeConfig = {+ bypassSessionPatterns: string[];+};++type SessionBypassContext = {+ sessionId?: string;+ sessionKey?: string;+};++export function createOpenVikingBypassRuntime<TConfig extends BypassRuntimeConfig>(options: {+ cfg: TConfig;+}) {+ const bypassSessionPatterns = compileSessionPatterns(options.cfg.bypassSessionPatterns);++ const isBypassedSession = (ctx?: SessionBypassContext): boolean =>+ shouldBypassSession(ctx ?? {}, bypassSessionPatterns);++ return {+ isBypassedSession,+ };+}diff --git a/examples/openclaw-plugin/plugin/openviking-client-runtime.ts b/examples/openclaw-plugin/plugin/openviking-client-runtime.tsnew file mode 100644index 000000000..c3cd4df3f--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-client-runtime.ts@@ -0,0 +1,74 @@+import { OpenVikingClient } from "../client.js";+import type { HttpTransport } from "../adapters/http-transport.js";++type Logger = {+ info: (message: string) => void;+};++type ClientRuntimeConfig = {+ baseUrl: string;+ apiKey: string;+ peer_role: "none" | "assistant" | "person";+ peer_prefix: string;+ timeoutMs: number;+ accountId?: string;+ userId?: string;+ logFindRequests: boolean;+};++export function createOpenVikingClientRuntime(options: {+ cfg: ClientRuntimeConfig;+ rawPeerPrefix: unknown;+ logger: Logger;+ transport?: HttpTransport;+}) {+ const { cfg, logger } = options;++ if (cfg.logFindRequests) {+ logger.info(+ "openviking: routing debug logging enabled (config logFindRequests, or env OPENVIKING_LOG_ROUTING=1 / OPENVIKING_DEBUG=1)",+ );+ }++ const verboseRoutingInfo = (message: string) => {+ if (cfg.logFindRequests) {+ logger.info(message);+ }+ };++ verboseRoutingInfo(+ `openviking: loaded plugin config peer_role="${cfg.peer_role}" peer_prefix="${cfg.peer_prefix}" ` ++ `(raw peer_prefix=${JSON.stringify(options.rawPeerPrefix ?? "(missing)")}; ` ++ `${+ cfg.peer_prefix+ ? 'non-empty → assistant peer_id is <peer_prefix>_<ctx.agentId> when peer_role="assistant", or <peer_prefix>_main when ctx.agentId is unknown'+ : 'empty → assistant peer_id follows OpenClaw ctx.agentId when peer_role="assistant", or "main" when ctx.agentId is unknown'+ })`,+ );++ const routingDebugLog = cfg.logFindRequests+ ? (msg: string) => {+ logger.info(msg);+ }+ : undefined;++ const clientPromise = Promise.resolve(+ new OpenVikingClient(+ cfg.baseUrl,+ cfg.apiKey,+ cfg.peer_prefix,+ cfg.timeoutMs,+ cfg.accountId,+ cfg.userId,+ routingDebugLog,+ { transport: options.transport },+ ),+ );++ const getClient = (): Promise<OpenVikingClient> => clientPromise;++ return {+ getClient,+ verboseRoutingInfo,+ };+}diff --git a/examples/openclaw-plugin/plugin/openviking-command-args.ts b/examples/openclaw-plugin/plugin/openviking-command-args.tsnew file mode 100644index 000000000..022ca7279--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-command-args.ts@@ -0,0 +1,187 @@+export type AddResourceCommandArgs = {+ source?: string;+ to?: string;+ parent?: string;+ reason?: string;+ instruction?: string;+ wait?: boolean;+ timeout?: number;+};++export type AddSkillCommandArgs = {+ source?: string;+ data?: unknown;+ wait?: boolean;+ timeout?: number;+};++export type OVSearchCommandArgs = {+ query: string;+ uri?: string;+ limit?: number;+};++export function tokenizeCommandArgs(args: string): string[] {+ const tokens: string[] = [];+ let current = "";+ let quote: "'" | '"' | null = null;+ let escaping = false;++ for (let i = 0; i < args.length; i += 1) {+ const ch = args[i]!;+ const next = args[i + 1];+ if (escaping) {+ current += ch;+ escaping = false;+ continue;+ }+ if (ch === "\\") {+ const shouldEscape =+ quote === '"'+ ? next === '"' || next === "\\"+ : !quote && Boolean(next && (/\s/.test(next) || next === '"' || next === "'"));+ if (shouldEscape) {+ escaping = true;+ continue;+ }+ current += ch;+ continue;+ }+ if ((ch === '"' || ch === "'") && (!quote || quote === ch)) {+ quote = quote ? null : ch;+ continue;+ }+ if (!quote && /\s/.test(ch)) {+ if (current) {+ tokens.push(current);+ current = "";+ }+ continue;+ }+ current += ch;+ }++ if (escaping) {+ current += "\\";+ }+ if (quote) {+ throw new Error("Unterminated quoted argument");+ }+ if (current) {+ tokens.push(current);+ }+ return tokens;+}++type ParsedFlagArgs = {+ positionals: string[];+ flags: Map<string, string | boolean>;+};++function parseFlagArgs(args: string): ParsedFlagArgs {+ const tokens = tokenizeCommandArgs(args);+ const positionals: string[] = [];+ const flags = new Map<string, string | boolean>();++ for (let i = 0; i < tokens.length; i += 1) {+ const token = tokens[i]!;+ if (!token.startsWith("--")) {+ positionals.push(token);+ continue;+ }+ const raw = token.slice(2);+ if (!raw) {+ continue;+ }+ const eqIndex = raw.indexOf("=");+ if (eqIndex >= 0) {+ flags.set(raw.slice(0, eqIndex), raw.slice(eqIndex + 1));+ continue;+ }+ const next = tokens[i + 1];+ if (next && !next.startsWith("--")) {+ flags.set(raw, next);+ i += 1;+ } else {+ flags.set(raw, true);+ }+ }++ return { positionals, flags };+}++function getStringFlag(flags: Map<string, string | boolean>, name: string): string | undefined {+ const value = flags.get(name);+ return typeof value === "string" && value.trim() ? value.trim() : undefined;+}++function getNumberFlag(flags: Map<string, string | boolean>, name: string): number | undefined {+ const raw = getStringFlag(flags, name);+ if (!raw) {+ return undefined;+ }+ const value = Number(raw);+ if (!Number.isFinite(value)) {+ throw new Error(`--${name} must be a number`);+ }+ return value;+}++function getBoolFlag(flags: Map<string, string | boolean>, name: string): boolean {+ return flags.get(name) === true;+}++export function parseAddResourceCommandArgs(args: string): AddResourceCommandArgs {+ const parsed = parseFlagArgs(args);+ const source =+ parsed.positionals.length <= 1 ? parsed.positionals[0] : parsed.positionals.join(" ").trim();+ if (!source) {+ throw new Error("Usage: /add-resource <source> [--to URI] [--parent URI] [--reason TEXT] [--instruction TEXT] [--wait] [--timeout SEC]");+ }+ const to = getStringFlag(parsed.flags, "to");+ const parent = getStringFlag(parsed.flags, "parent");+ if (to && parent) {+ throw new Error("Cannot specify both --to and --parent.");+ }+ return {+ source,+ to,+ parent,+ reason: getStringFlag(parsed.flags, "reason"),+ instruction: getStringFlag(parsed.flags, "instruction"),+ wait: getBoolFlag(parsed.flags, "wait"),+ timeout: getNumberFlag(parsed.flags, "timeout"),+ };+}++export function parseAddSkillCommandArgs(args: string): AddSkillCommandArgs {+ const parsed = parseFlagArgs(args);+ const source =+ parsed.positionals.length <= 1 ? parsed.positionals[0] : parsed.positionals.join(" ").trim();+ if (!source) {+ throw new Error("Usage: /add-skill <source> [--wait] [--timeout SEC]");+ }+ if (parsed.flags.has("to") || parsed.flags.has("parent") || parsed.flags.has("reason") || parsed.flags.has("instruction")) {+ throw new Error("--to, --parent, --reason, and --instruction are resource-only options.");+ }+ return {+ source,+ wait: getBoolFlag(parsed.flags, "wait"),+ timeout: getNumberFlag(parsed.flags, "timeout"),+ };+}++export function parseOVSearchCommandArgs(args: string): OVSearchCommandArgs {+ const parsed = parseFlagArgs(args);+ // `/ov-search` only accepts a single query string, so positional segments are+ // always re-joined to preserve unquoted multi-word searches.+ const query = parsed.positionals.join(" ").trim();+ if (!query) {+ throw new Error('Usage: /ov-search "<query>" [--uri URI] [--limit N]');+ }+ return {+ query,+ uri: getStringFlag(parsed.flags, "uri"),+ limit: getNumberFlag(parsed.flags, "limit"),+ };+}diff --git a/examples/openclaw-plugin/plugin/openviking-command-definitions.ts b/examples/openclaw-plugin/plugin/openviking-command-definitions.tsnew file mode 100644index 000000000..0c1edb999--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-command-definitions.ts@@ -0,0 +1,294 @@+import type { CommandDefinition, CommandResult, PluginCommandContext } from "./command-registration.js";+import type { RecallTraceEntry, RecallTraceSource } from "../recall-trace.js";++export type OpenVikingCommandSession = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++export type OpenVikingCommandToolResult = {+ content: Array<{ type: "text"; text: string }>;+ details?: Record<string, unknown>;+};++export type AddResourceCommandInput = {+ source?: string;+ to?: string;+ parent?: string;+ reason?: string;+ instruction?: string;+ wait?: boolean;+ timeout?: number;+};++export type AddSkillCommandInput = {+ source?: string;+ data?: unknown;+ wait?: boolean;+ timeout?: number;+};++export type OVSearchCommandInput = {+ query: string;+ uri?: string;+ limit?: number;+};++export type RecallTraceCommandInput = {+ turn?: "latest" | "all";+ traceId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ source?: RecallTraceSource;+ resourceTypes?: string;+ since?: number;+ until?: number;+ includeContent?: boolean;+ limit?: number;+};++export type RecallTraceCommandResult = {+ entries: RecallTraceEntry[];+ lookupLayer: string;+ warnings: string[];+};++export type OpenVikingCommandDefinitionsDeps = {+ resolvePluginSessionRouting: (ctx?: PluginCommandContext) => OpenVikingCommandSession;+ isBypassedSession: (ctx?: PluginCommandContext) => boolean;+ makeBypassedToolResult: (toolName: string) => OpenVikingCommandToolResult;+ parseAddResourceCommandArgs: (args: string) => AddResourceCommandInput;+ parseAddSkillCommandArgs: (args: string) => AddSkillCommandInput;+ parseOVSearchCommandArgs: (args: string) => OVSearchCommandInput;+ addResourceOpenViking: (input: AddResourceCommandInput, agentId?: string) => Promise<OpenVikingCommandToolResult>;+ addSkillOpenViking: (input: AddSkillCommandInput, agentId?: string) => Promise<OpenVikingCommandToolResult>;+ searchOpenViking: (+ input: OVSearchCommandInput,+ agentId?: string,+ traceCtx?: OpenVikingCommandSession,+ ) => Promise<OpenVikingCommandToolResult>;+ handleQueryConfigCommand: (ctx: PluginCommandContext) => Promise<CommandResult>;+ queryRecallTraces: (+ input: RecallTraceCommandInput,+ session: OpenVikingCommandSession,+ ) => Promise<RecallTraceCommandResult>;+ formatRecallTraceText: (result: RecallTraceCommandResult) => string;+};++function tokenizeCommandArgs(args: string): string[] {+ const tokens: string[] = [];+ let current = "";+ let quote: "'" | '"' | null = null;+ let escaping = false;++ for (let i = 0; i < args.length; i += 1) {+ const ch = args[i]!;+ const next = args[i + 1];+ if (escaping) {+ current += ch;+ escaping = false;+ continue;+ }+ if (ch === "\\") {+ const shouldEscape =+ quote === '"'+ ? next === '"' || next === "\\"+ : !quote && Boolean(next && (/\s/.test(next) || next === '"' || next === "'"));+ if (shouldEscape) {+ escaping = true;+ continue;+ }+ current += ch;+ continue;+ }+ if ((ch === '"' || ch === "'") && (!quote || quote === ch)) {+ quote = quote ? null : ch;+ continue;+ }+ if (!quote && /\s/.test(ch)) {+ if (current) {+ tokens.push(current);+ current = "";+ }+ continue;+ }+ current += ch;+ }++ if (escaping) {+ current += "\\";+ }+ if (quote) {+ throw new Error("Unterminated quoted argument");+ }+ if (current) {+ tokens.push(current);+ }+ return tokens;+}++function parseFlagArgs(args: string): { flags: Map<string, string | boolean> } {+ const tokens = tokenizeCommandArgs(args);+ const flags = new Map<string, string | boolean>();++ for (let i = 0; i < tokens.length; i += 1) {+ const token = tokens[i]!;+ if (!token.startsWith("--")) {+ continue;+ }+ const raw = token.slice(2);+ if (!raw) {+ continue;+ }+ const eqIndex = raw.indexOf("=");+ if (eqIndex >= 0) {+ flags.set(raw.slice(0, eqIndex), raw.slice(eqIndex + 1));+ continue;+ }+ const next = tokens[i + 1];+ if (next && !next.startsWith("--")) {+ flags.set(raw, next);+ i += 1;+ } else {+ flags.set(raw, true);+ }+ }++ return { flags };+}++function getStringFlag(flags: Map<string, string | boolean>, name: string): string | undefined {+ const value = flags.get(name);+ return typeof value === "string" && value.trim() ? value.trim() : undefined;+}++function getNumberFlag(flags: Map<string, string | boolean>, name: string): number | undefined {+ const raw = getStringFlag(flags, name);+ if (!raw) {+ return undefined;+ }+ const value = Number(raw);+ if (!Number.isFinite(value)) {+ throw new Error(`--${name} must be a number`);+ }+ return value;+}++function getBoolFlag(flags: Map<string, string | boolean>, name: string): boolean {+ return flags.get(name) === true;+}++function parseRecallTraceCommandArgs(args: string): RecallTraceCommandInput {+ const flags = parseFlagArgs(args).flags;+ return {+ turn: getStringFlag(flags, "turn") as "latest" | "all" | undefined,+ traceId: getStringFlag(flags, "trace-id"),+ sessionId: getStringFlag(flags, "session-id"),+ sessionKey: getStringFlag(flags, "session-key"),+ ovSessionId: getStringFlag(flags, "ov-session-id"),+ source: getStringFlag(flags, "source") as RecallTraceSource | undefined,+ resourceTypes: getStringFlag(flags, "resource-types"),+ since: getNumberFlag(flags, "since"),+ until: getNumberFlag(flags, "until"),+ includeContent: getBoolFlag(flags, "include-content"),+ limit: getNumberFlag(flags, "limit"),+ };+}++function toCommandResult(result: OpenVikingCommandToolResult): CommandResult {+ return { text: result.content[0]!.text, details: result.details };+}++export function createOpenVikingCommandDefinitions(+ deps: OpenVikingCommandDefinitionsDeps,+): CommandDefinition[] {+ return [+ {+ name: "add-resource",+ description: "Add a resource into OpenViking.",+ acceptsArgs: true,+ handler: async (ctx: PluginCommandContext) => {+ try {+ if (deps.isBypassedSession(ctx)) {+ return toCommandResult(deps.makeBypassedToolResult("add_resource"));+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const input = deps.parseAddResourceCommandArgs(ctx.args ?? "");+ return toCommandResult(await deps.addResourceOpenViking(input, session.agentId));+ } catch (err) {+ return { text: `OpenViking add resource failed: ${err instanceof Error ? err.message : String(err)}` };+ }+ },+ },+ {+ name: "add-skill",+ description: "Add a skill into OpenViking.",+ acceptsArgs: true,+ handler: async (ctx: PluginCommandContext) => {+ try {+ if (deps.isBypassedSession(ctx)) {+ return toCommandResult(deps.makeBypassedToolResult("add_skill"));+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const input = deps.parseAddSkillCommandArgs(ctx.args ?? "");+ return toCommandResult(await deps.addSkillOpenViking(input, session.agentId));+ } catch (err) {+ return { text: `OpenViking add skill failed: ${err instanceof Error ? err.message : String(err)}` };+ }+ },+ },+ {+ name: "ov-search",+ description: "Search OpenViking resources and skills.",+ acceptsArgs: true,+ handler: async (ctx: PluginCommandContext) => {+ try {+ if (deps.isBypassedSession(ctx)) {+ return toCommandResult(deps.makeBypassedToolResult("ov_search"));+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const input = deps.parseOVSearchCommandArgs(ctx.args ?? "");+ return toCommandResult(await deps.searchOpenViking(input, session.agentId, session));+ } catch (err) {+ return { text: `OpenViking search failed: ${err instanceof Error ? err.message : String(err)}` };+ }+ },+ },+ {+ name: "ov-query-config",+ description: "Get or set runtime OpenViking query parameters for the current claw/session.",+ acceptsArgs: true,+ handler: async (ctx: PluginCommandContext) => {+ try {+ return await deps.handleQueryConfigCommand(ctx);+ } catch (err) {+ return { text: `OpenViking query config failed: ${err instanceof Error ? err.message : String(err)}` };+ }+ },+ },+ {+ name: "ov-recall-trace",+ description: "Query OpenViking recall trace records.",+ acceptsArgs: true,+ handler: async (ctx: PluginCommandContext) => {+ try {+ if (deps.isBypassedSession(ctx)) {+ return toCommandResult(deps.makeBypassedToolResult("ov_recall_trace"));+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const input = parseRecallTraceCommandArgs(ctx.args ?? "");+ const result = await deps.queryRecallTraces(input, session);+ return {+ text: deps.formatRecallTraceText(result),+ details: { count: result.entries.length, lookupLayer: result.lookupLayer, warnings: result.warnings, entries: result.entries },+ };+ } catch (err) {+ return { text: `OpenViking recall trace query failed: ${err instanceof Error ? err.message : String(err)}` };+ }+ },+ },+ ];+}diff --git a/examples/openclaw-plugin/plugin/openviking-context-engine-ref.ts b/examples/openclaw-plugin/plugin/openviking-context-engine-ref.tsnew file mode 100644index 000000000..5cd26b3a4--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-context-engine-ref.ts@@ -0,0 +1,16 @@+import type { ContextEngineWithCommit } from "../context-engine.js";++export function createOpenVikingContextEngineRef() {+ let contextEngineRef: ContextEngineWithCommit | null = null;++ const getContextEngine = (): ContextEngineWithCommit | null => contextEngineRef;++ const setContextEngineRef = (engine: ContextEngineWithCommit): void => {+ contextEngineRef = engine;+ };++ return {+ getContextEngine,+ setContextEngineRef,+ };+}diff --git a/examples/openclaw-plugin/plugin/openviking-context-engine-registration.ts b/examples/openclaw-plugin/plugin/openviking-context-engine-registration.tsnew file mode 100644index 000000000..b79ae28e5--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-context-engine-registration.ts@@ -0,0 +1,97 @@+export type OpenVikingContextEngineRegistrationApi = {+ registerContextEngine?: (id: string, factory: () => unknown) => void;+};++export type OpenVikingContextEngineLogger = {+ info: (message: string) => void;+ warn: (message: string) => void;+};++export type OpenVikingContextEnginePluginInfo = {+ id: string;+ name: string;+};++export type OpenVikingContextEngineCreateParams<+ TCfg = unknown,+ TClient = unknown,+ TQueryConfigStore = unknown,+ TTraceRecorder = unknown,+ TLogger extends OpenVikingContextEngineLogger = OpenVikingContextEngineLogger,+> = {+ id: string;+ name: string;+ version: string;+ cfg: TCfg;+ logger: TLogger;+ getClient: () => Promise<TClient>;+ resolveAgentId: (sessionId: string, sessionKey?: string, ovSessionId?: string) => string;+ rememberSessionAgentId: (ctx: {+ agentId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ }) => void;+ queryConfigStore: TQueryConfigStore;+ traceRecorder: TTraceRecorder;+};++export type OpenVikingContextEngineRegistrationDeps<+ TEngine,+ TCfg = unknown,+ TClient = unknown,+ TQueryConfigStore = unknown,+ TTraceRecorder = unknown,+ TLogger extends OpenVikingContextEngineLogger = OpenVikingContextEngineLogger,+> = {+ api: OpenVikingContextEngineRegistrationApi;+ plugin: OpenVikingContextEnginePluginInfo;+ version: string;+ cfg: TCfg;+ logger: TLogger;+ getClient: () => Promise<TClient>;+ resolveAgentId: (sessionId: string, sessionKey?: string, ovSessionId?: string) => string;+ rememberSessionAgentId: OpenVikingContextEngineCreateParams["rememberSessionAgentId"];+ queryConfigStore: TQueryConfigStore;+ traceRecorder: TTraceRecorder;+ createContextEngine: (params: OpenVikingContextEngineCreateParams<TCfg, TClient, TQueryConfigStore, TTraceRecorder, TLogger>) => TEngine;+ setContextEngineRef: (engine: TEngine) => void;+};++export function registerOpenVikingContextEngine<+ TEngine,+ TCfg,+ TClient,+ TQueryConfigStore,+ TTraceRecorder,+ TLogger extends OpenVikingContextEngineLogger,+>(+ deps: OpenVikingContextEngineRegistrationDeps<TEngine, TCfg, TClient, TQueryConfigStore, TTraceRecorder, TLogger>,+): void {+ if (typeof deps.api.registerContextEngine !== "function") {+ deps.logger.warn(+ "openviking: registerContextEngine is unavailable; context-engine behavior will not run",+ );+ return;+ }++ deps.api.registerContextEngine(deps.plugin.id, () => {+ const contextEngine = deps.createContextEngine({+ id: deps.plugin.id,+ name: deps.plugin.name,+ version: deps.version,+ cfg: deps.cfg,+ logger: deps.logger,+ getClient: deps.getClient,+ resolveAgentId: deps.resolveAgentId,+ rememberSessionAgentId: deps.rememberSessionAgentId,+ queryConfigStore: deps.queryConfigStore,+ traceRecorder: deps.traceRecorder,+ });+ deps.setContextEngineRef(contextEngine);+ return contextEngine;+ });+ deps.logger.info(+ "openviking: registered context-engine (assemble=archive+active+auto-recall, afterTurn=auto-capture, session→OV id=uuid-or-sha256 + diag/Phase2 options)",+ );+}diff --git a/examples/openclaw-plugin/plugin/openviking-import-runtime.ts b/examples/openclaw-plugin/plugin/openviking-import-runtime.tsnew file mode 100644index 000000000..eee6970f3--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-import-runtime.ts@@ -0,0 +1,105 @@+import type {+ AddResourceInput,+ AddResourceResult,+ AddSkillInput,+ AddSkillResult,+} from "../client.js";++export type OpenVikingImportRuntimeResourceInput = {+ source?: string;+ to?: string;+ parent?: string;+ reason?: string;+ instruction?: string;+ wait?: boolean;+ timeout?: number;+};++export type OpenVikingImportRuntimeSkillInput = {+ source?: string;+ data?: unknown;+ wait?: boolean;+ timeout?: number;+};++export type OpenVikingImportRuntimeToolResult = {+ content: Array<{ type: "text"; text: string }>;+ details?: Record<string, unknown>;+};++export type OpenVikingImportRuntimeClient = {+ addResource: (input: AddResourceInput, agentId?: string) => Promise<AddResourceResult>;+ addSkill: (input: AddSkillInput, agentId?: string) => Promise<AddSkillResult>;+};++export type OpenVikingImportRuntimeDeps = {+ getClient: () => Promise<OpenVikingImportRuntimeClient>;+};++function formatResourceImportText(result: AddResourceResult): string {+ const root = result.root_uri ? ` ${result.root_uri}` : "";+ const warnings = result.warnings?.length ? ` Warnings: ${result.warnings.join("; ")}` : "";+ return `Imported OpenViking resource.${root}${warnings}`.trim();+}++function formatSkillImportText(result: AddSkillResult): string {+ const uri = result.uri ? ` ${result.uri}` : "";+ const name = result.name ? ` (${result.name})` : "";+ return `Imported OpenViking skill${name}.${uri}`.trim();+}++export function createOpenVikingImportRuntime(deps: OpenVikingImportRuntimeDeps): {+ addResourceOpenViking: (+ input: OpenVikingImportRuntimeResourceInput,+ agentId?: string,+ ) => Promise<OpenVikingImportRuntimeToolResult>;+ addSkillOpenViking: (+ input: OpenVikingImportRuntimeSkillInput,+ agentId?: string,+ ) => Promise<OpenVikingImportRuntimeToolResult>;+} {+ const importResource = async (input: AddResourceInput, agentId?: string): Promise<OpenVikingImportRuntimeToolResult> => {+ const client = await deps.getClient();+ const result = await client.addResource(input, agentId);+ return {+ content: [{ type: "text", text: formatResourceImportText(result) }],+ details: {+ action: "resource_imported",+ ...result,+ },+ };+ };++ const importSkill = async (input: AddSkillInput, agentId?: string): Promise<OpenVikingImportRuntimeToolResult> => {+ const client = await deps.getClient();+ const result = await client.addSkill(input, agentId);+ return {+ content: [{ type: "text", text: formatSkillImportText(result) }],+ details: {+ action: "skill_imported",+ ...result,+ },+ };+ };++ const addResourceOpenViking = (input: OpenVikingImportRuntimeResourceInput, agentId?: string) =>+ importResource({+ pathOrUrl: input.source ?? "",+ to: input.to,+ parent: input.parent,+ reason: input.reason,+ instruction: input.instruction,+ wait: input.wait,+ timeout: input.timeout,+ }, agentId);++ const addSkillOpenViking = (input: OpenVikingImportRuntimeSkillInput, agentId?: string) =>+ importSkill({+ path: input.source,+ data: input.data,+ wait: input.wait,+ timeout: input.timeout,+ }, agentId);++ return { addResourceOpenViking, addSkillOpenViking };+}diff --git a/examples/openclaw-plugin/plugin/openviking-import-tools.ts b/examples/openclaw-plugin/plugin/openviking-import-tools.tsnew file mode 100644index 000000000..96f8d6cbb--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-import-tools.ts@@ -0,0 +1,133 @@+import { Type } from "@sinclair/typebox";++import type {+ AddResourceInput,+ AddResourceResult,+ AddSkillInput,+ AddSkillResult,+} from "../client.js";++export type OpenVikingImportToolContext = {+ sessionKey?: string;+ sessionId?: string;+ agentId?: string;+ senderId?: string;+};++export type OpenVikingImportSession = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++export type OpenVikingImportClient = {+ addResource: (input: AddResourceInput, agentId?: string) => Promise<AddResourceResult>;+ addSkill: (input: AddSkillInput, agentId?: string) => Promise<AddSkillResult>;+};++export type OpenVikingImportToolsDeps = {+ registerTool: (toolOrFactory: unknown, opts: { name: string }) => void;+ getClient: () => Promise<OpenVikingImportClient>;+ resolvePluginSessionRouting: (ctx?: OpenVikingImportToolContext) => OpenVikingImportSession;+ isBypassedSession: (ctx?: OpenVikingImportToolContext) => boolean;+ makeBypassedToolResult: (toolName: string) => unknown;+ enableAddResourceTool: boolean;+};++function formatResourceImportText(result: AddResourceResult): string {+ const root = result.root_uri ? ` ${result.root_uri}` : "";+ const warnings = result.warnings?.length ? ` Warnings: ${result.warnings.join("; ")}` : "";+ return `Imported OpenViking resource.${root}${warnings}`.trim();+}++function formatSkillImportText(result: AddSkillResult): string {+ const uri = result.uri ? ` ${result.uri}` : "";+ const name = result.name ? ` (${result.name})` : "";+ return `Imported OpenViking skill${name}.${uri}`.trim();+}++export function registerOpenVikingImportTools(deps: OpenVikingImportToolsDeps): void {+ if (deps.enableAddResourceTool) {+ deps.registerTool(+ (ctx: OpenVikingImportToolContext) => ({+ name: "add_resource",+ label: "Add Resource (OpenViking)",+ description:+ "Use only when the user explicitly asks to import, add, upload, save, or index a document, directory, URL, Git repository, or OpenClaw media attachment into OpenViking resources. " ++ "Never use this during search, retrieval, URI reading, or search-result optimization; use ov_search and ov_read for those flows. " ++ "For a '[media attached: /path ...]' document, set source to that exact local media path. Do not invent OpenViking upload REST endpoints.",+ parameters: Type.Object({+ source: Type.String({ description: "Local path, OpenClaw media attachment path, directory path, public URL, or Git URL" }),+ to: Type.Optional(Type.String({ description: "Exact target URI, e.g. viking://resources/project-docs" })),+ parent: Type.Optional(Type.String({ description: "Parent URI under viking://resources" })),+ reason: Type.Optional(Type.String({ description: "Reason or note for adding this resource" })),+ instruction: Type.Optional(Type.String({ description: "Processing instruction for semantic extraction" })),+ wait: Type.Optional(Type.Boolean({ description: "Wait for processing to complete" })),+ timeout: Type.Optional(Type.Number({ description: "Timeout in seconds when wait is true" })),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("add_resource");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const client = await deps.getClient();+ const result = await client.addResource({+ pathOrUrl: typeof params.source === "string" ? params.source : "",+ to: typeof params.to === "string" ? params.to : undefined,+ parent: typeof params.parent === "string" ? params.parent : undefined,+ reason: typeof params.reason === "string" ? params.reason : undefined,+ 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);+ return {+ content: [{ type: "text" as const, text: formatResourceImportText(result) }],+ details: {+ action: "resource_imported",+ ...result,+ },+ };+ },+ }),+ { name: "add_resource" },+ );+ }++ deps.registerTool(+ (ctx: OpenVikingImportToolContext) => ({+ name: "add_skill",+ label: "Add Skill (OpenViking)",+ description:+ "Use only when the user explicitly asks to import, add, install, or register a skill into OpenViking. " ++ "Set source to a local SKILL.md file or skill directory, or data to raw SKILL.md content or an MCP tool dict.",+ parameters: Type.Object({+ source: Type.Optional(Type.String({ description: "Local SKILL.md path or skill directory path" })),+ data: Type.Optional(Type.Any({ description: "Raw SKILL.md content or MCP tool dict" })),+ wait: Type.Optional(Type.Boolean({ description: "Wait for processing to complete" })),+ timeout: Type.Optional(Type.Number({ description: "Timeout in seconds when wait is true" })),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("add_skill");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const client = await deps.getClient();+ const result = await client.addSkill({+ path: 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 {+ content: [{ type: "text" as const, text: formatSkillImportText(result) }],+ details: {+ action: "skill_imported",+ ...result,+ },+ };+ },+ }),+ { name: "add_skill" },+ );+}diff --git a/examples/openclaw-plugin/plugin/openviking-lifecycle-hooks.ts b/examples/openclaw-plugin/plugin/openviking-lifecycle-hooks.tsnew file mode 100644index 000000000..ae0050bec--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-lifecycle-hooks.ts@@ -0,0 +1,65 @@+export type OpenVikingHookContext = {+ agentId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+};++export type ContextEngineCommitPort = {+ commitOVSession: (ctx: { sessionId: string; sessionKey?: string }) => Promise<boolean>;+};++export type OpenVikingLifecycleHookApi = {+ on: (+ hookName: string,+ handler: (event: unknown, ctx?: OpenVikingHookContext) => unknown,+ opts?: { priority?: number },+ ) => void;+};++export type OpenVikingLifecycleHooksDeps = {+ api: OpenVikingLifecycleHookApi;+ rememberSessionAgentId: (ctx: OpenVikingHookContext) => void;+ isBypassedSession: (ctx?: OpenVikingHookContext) => boolean;+ verboseRoutingInfo: (message: string) => void;+ getContextEngine: () => ContextEngineCommitPort | null;+ logger: {+ info: (message: string) => void;+ warn: (message: string) => void;+ };+};++export function registerOpenVikingLifecycleHooks(deps: OpenVikingLifecycleHooksDeps): void {+ deps.api.on("session_start", async (_event: unknown, ctx?: OpenVikingHookContext) => {+ deps.rememberSessionAgentId(ctx ?? {});+ });+ deps.api.on("session_end", async (_event: unknown, ctx?: OpenVikingHookContext) => {+ deps.rememberSessionAgentId(ctx ?? {});+ });+ deps.api.on("before_reset", async (_event: unknown, ctx?: OpenVikingHookContext) => {+ if (deps.isBypassedSession(ctx)) {+ deps.verboseRoutingInfo(+ `openviking: bypassing before_reset due to session pattern match (sessionKey=${ctx?.sessionKey ?? "none"}, sessionId=${ctx?.sessionId ?? "none"})`,+ );+ return;+ }+ const sessionId = ctx?.sessionId;+ const contextEngine = deps.getContextEngine();+ if (sessionId && contextEngine) {+ try {+ const ok = await contextEngine.commitOVSession({+ sessionId,+ sessionKey: ctx?.sessionKey,+ });+ if (ok) {+ deps.logger.info(`openviking: committed OV session on reset for session=${sessionId}`);+ }+ } catch (err) {+ deps.logger.warn(`openviking: failed to commit OV session on reset: ${String(err)}`);+ }+ }+ });+ deps.api.on("after_compaction", async (_event: unknown, _ctx?: OpenVikingHookContext) => {+ // Reserved hook registration for future post-compaction memory integration.+ });+}diff --git a/examples/openclaw-plugin/plugin/openviking-memory-recall-tools.ts b/examples/openclaw-plugin/plugin/openviking-memory-recall-tools.tsnew file mode 100644index 000000000..98b8d02e9--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-memory-recall-tools.ts@@ -0,0 +1,368 @@+import { Type } from "@sinclair/typebox";++import type { FindResult, FindResultItem } from "../client.js";+import type { BuildMemoryLinesWithBudgetOptions } from "../auto-recall.js";+import type { RankingOptions } from "../memory-ranking.js";+import type { EffectiveQueryConfig, QueryConfigContext, RuntimeQueryParams } from "../query-config.js";+import type { RecallResourceType } from "../registries/recall-resource-types.js";+import type {+ RecallTraceEntry,+ RecallTraceResult,+} from "../recall-trace.js";++export type OpenVikingMemoryRecallToolContext = {+ sessionKey?: string;+ sessionId?: string;+ agentId?: string;+ senderId?: string;+};++export type OpenVikingMemoryRecallSession = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++export type OpenVikingMemoryRecallClient = {+ find: (+ query: string,+ options: {+ targetUri?: string;+ limit: number;+ scoreThreshold: number;+ contextType?: "memory" | "resource";+ actorPeerId?: string;+ },+ ) => Promise<FindResult>;+ read: (uri: string, agentId?: string) => Promise<string>;+ getDefaultAgentId: () => string;+};++export type OpenVikingMemoryRecallToolsDeps = {+ registerTool: (toolOrFactory: unknown, opts: { name: string }) => void;+ getClient: () => Promise<OpenVikingMemoryRecallClient>;+ queryConfigStore: {+ getEffective: (+ ctx: QueryConfigContext,+ request?: RuntimeQueryParams,+ ) => Promise<EffectiveQueryConfig>;+ };+ toQueryConfigContext: (session: OpenVikingMemoryRecallSession) => QueryConfigContext;+ resolvePluginSessionRouting: (+ ctx?: OpenVikingMemoryRecallToolContext,+ ) => OpenVikingMemoryRecallSession;+ isBypassedSession: (ctx?: OpenVikingMemoryRecallToolContext) => boolean;+ makeBypassedToolResult: (toolName: string) => unknown;+ resolveRecallSearchPlan: (+ resourceTypes: unknown,+ ctx: { ovSessionId?: string; agentId?: string },+ ) => {+ resourceTypes: RecallResourceType[];+ searches: Array<{ resourceType: RecallResourceType; targetUri?: string; contextType: "memory" | "resource" }>;+ skipped: Array<{ resourceType: RecallResourceType; reason: "missing_session" }>;+ };+ postProcessMemories: (+ items: FindResultItem[],+ options: { limit: number; scoreThreshold: number },+ ) => FindResultItem[];+ pickMemoriesForInjection: (+ items: FindResultItem[],+ limit: number,+ queryText: string,+ scoreThreshold: number,+ rankingOptions?: RankingOptions,+ ) => FindResultItem[];+ buildMemoryLinesWithBudget: (+ memories: FindResultItem[],+ readFn: (uri: string) => Promise<string>,+ options: BuildMemoryLinesWithBudgetOptions,+ ) => Promise<{ lines: string[]; estimatedTokens: number }>;+ inferRecallResourceType: (uri: string) => RecallResourceType | undefined;+ createTraceId: (source: string) => string;+ boundTraceQuery: (query: string, maxChars: number) => { query: string; queryTruncated?: boolean };+ previewText: (value: unknown, maxChars: number) => string | undefined;+ traceRecorder?: { recordAndFlush?: (entry: RecallTraceEntry) => Promise<unknown> };+ cfg: {+ recallTargetTypes: RecallResourceType[];+ traceRecallMaxResultsPerSearch: number;+ traceRecallPreviewChars: number;+ traceRecallQueryMaxChars: number;+ logFindRequests: boolean;+ };+ logger: {+ info?: (message: string) => void;+ };+};++function toTraceResult(+ item: FindResultItem,+ resultType: RecallTraceResult["resultType"],+ deps: OpenVikingMemoryRecallToolsDeps,+): RecallTraceResult {+ return {+ uri: item.uri,+ resourceType: deps.inferRecallResourceType(item.uri),+ category: item.category,+ score: item.score,+ level: item.level,+ abstractPreview: deps.previewText(item.abstract || item.overview, deps.cfg.traceRecallPreviewChars),+ resultType,+ };+}++export function registerOpenVikingMemoryRecallTools(+ deps: OpenVikingMemoryRecallToolsDeps,+): void {+ deps.registerTool(+ (ctx: OpenVikingMemoryRecallToolContext) => ({+ name: "memory_recall",+ label: "Memory Recall (OpenViking)",+ description:+ "Search long-term memories from OpenViking. Use when you need past user preferences, facts, or decisions.",+ parameters: Type.Object({+ query: Type.String({ description: "Search query" }),+ limit: Type.Optional(+ Type.Number({ description: "Max results (default: plugin config)" }),+ ),+ scoreThreshold: Type.Optional(+ Type.Number({ description: "Minimum score (0-1, default: plugin config)" }),+ ),+ targetUri: Type.Optional(+ Type.String({ description: "Search scope URI (default: plugin config)" }),+ ),+ resourceTypes: Type.Optional(+ Type.Array(Type.String({ description: "resource, user, or agent; used when targetUri is omitted" })),+ ),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("memory_recall");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const { query } = params as { query: string };+ const queryConfig = await deps.queryConfigStore.getEffective(deps.toQueryConfigContext(session), {+ recallLimit: typeof (params as { limit?: number }).limit === "number" ? (params as { limit: number }).limit : undefined,+ scoreThreshold: typeof (params as { scoreThreshold?: number }).scoreThreshold === "number" ? (params as { scoreThreshold: number }).scoreThreshold : undefined,+ targetUri: typeof (params as { targetUri?: string }).targetUri === "string" ? (params as { targetUri: string }).targetUri : undefined,+ resourceTypes: Object.prototype.hasOwnProperty.call(params, "resourceTypes")+ ? (params as { resourceTypes?: unknown }).resourceTypes as RuntimeQueryParams["resourceTypes"]+ : undefined,+ });+ const limit = queryConfig.recallLimit;+ const scoreThreshold = queryConfig.scoreThreshold;+ const targetUri =+ typeof (params as { targetUri?: string }).targetUri === "string"+ ? (params as { targetUri: string }).targetUri+ : queryConfig.targetUri;+ const requestedResourceTypes = Object.prototype.hasOwnProperty.call(params, "resourceTypes")+ ? (params as { resourceTypes?: unknown }).resourceTypes+ : queryConfig.resourceTypes;+ const requestLimit = queryConfig.candidateLimit;++ const recallClient = await deps.getClient();+ if (deps.cfg.logFindRequests) {+ deps.logger.info?.(+ `openviking: memory_recall X-OpenViking-Actor-Peer="${session.agentId}" ` ++ `(plugin defaultAgentId="${recallClient.getDefaultAgentId()}" is unused when session context is present)`,+ );+ }++ let result: FindResult;+ let memoryRecallSearches: RecallTraceEntry["searches"] = [];+ if (targetUri) {+ result = await recallClient.find(+ query,+ {+ targetUri,+ limit: requestLimit,+ scoreThreshold: 0,+ actorPeerId: session.agentId,+ },+ );+ const traceResults = [+ ...(result.memories ?? []).map((item) => toTraceResult(item, "memory", deps)),+ ...(result.resources ?? []).map((item) => toTraceResult(item, "resource", deps)),+ ].slice(0, deps.cfg.traceRecallMaxResultsPerSearch);+ memoryRecallSearches = [{+ resourceType: deps.inferRecallResourceType(targetUri) ?? "resource",+ targetUriInput: targetUri,+ targetUriResolved: targetUri,+ limit: requestLimit,+ scoreThreshold,+ durationMs: 0,+ total: result.total ?? traceResults.length,+ results: traceResults,+ }];+ } else {+ const searchPlan = deps.resolveRecallSearchPlan(requestedResourceTypes ?? deps.cfg.recallTargetTypes, {+ ovSessionId: session.ovSessionId,+ agentId: session.agentId,+ });+ const settled = await Promise.allSettled(searchPlan.searches.map((search) =>+ recallClient.find(+ query,+ {+ targetUri: search.targetUri,+ limit: requestLimit,+ scoreThreshold: 0,+ contextType: search.contextType,+ actorPeerId: session.agentId,+ },+ ),+ ));+ const allMemories: FindResultItem[] = [];+ for (let index = 0; index < settled.length; index += 1) {+ const s = settled[index]!;+ const search = searchPlan.searches[index]!;+ if (s.status === "fulfilled") {+ allMemories.push(...(s.value.memories ?? []), ...(s.value.resources ?? []));+ memoryRecallSearches.push({+ resourceType: search.resourceType,+ targetUriInput: search.targetUri,+ targetUriResolved: search.targetUri,+ limit: requestLimit,+ scoreThreshold,+ durationMs: 0,+ total: s.value.total ?? ((s.value.memories ?? []).length + (s.value.resources ?? []).length),+ results: [+ ...(s.value.memories ?? []).map((item) => toTraceResult(item, "memory", deps)),+ ...(s.value.resources ?? []).map((item) => toTraceResult(item, "resource", deps)),+ ].slice(0, deps.cfg.traceRecallMaxResultsPerSearch),+ });+ } else {+ memoryRecallSearches.push({+ resourceType: search.resourceType,+ targetUriInput: search.targetUri,+ targetUriResolved: search.targetUri,+ limit: requestLimit,+ scoreThreshold,+ durationMs: 0,+ total: 0,+ results: [],+ error: s.reason instanceof Error ? s.reason.message : String(s.reason),+ });+ }+ }+ const uniqueMemories = allMemories.filter((memory, index, self) =>+ index === self.findIndex((m) => m.uri === memory.uri)+ );+ const leafOnly = uniqueMemories.filter((m) => !m.level || m.level === 2);+ result = {+ memories: leafOnly,+ total: leafOnly.length,+ };+ }++ const leafOnly = (result.memories ?? []).filter((m) => !m.level || m.level === 2);+ const processed = deps.postProcessMemories(leafOnly, {+ limit: requestLimit,+ scoreThreshold,+ });+ const memories = deps.pickMemoriesForInjection(processed, limit, query, scoreThreshold, {+ weights: queryConfig.rankingWeights,+ categoryWeights: queryConfig.categoryWeights,+ resourceTypeWeights: queryConfig.resourceTypeWeights,+ });+ const candidateTraceResults = leafOnly+ .map((item) => toTraceResult(item, deps.inferRecallResourceType(item.uri) === "resource" ? "resource" : "memory", deps))+ .slice(0, deps.cfg.traceRecallMaxResultsPerSearch);+ const traceResourceTypes = [...new Set(+ (targetUri ? [deps.inferRecallResourceType(targetUri)] : memoryRecallSearches.map((search) => search.resourceType))+ .filter((resourceType): resourceType is RecallResourceType => Boolean(resourceType)),+ )];+ const recordMemoryRecallTrace = async (injectedUris: Set<string>) => {+ await deps.traceRecorder?.recordAndFlush?.({+ schemaVersion: "1.0",+ traceId: deps.createTraceId("memory_recall"),+ ts: Date.now(),+ sessionId: session.sessionId,+ sessionKey: session.sessionKey,+ ovSessionId: session.ovSessionId,+ agentId: session.agentId,+ source: "memory_recall",+ operationType: "semantic_find",+ resourceTypes: traceResourceTypes.length > 0 ? traceResourceTypes : ["resource"],+ trigger: deps.boundTraceQuery(query, deps.cfg.traceRecallQueryMaxChars),+ searches: memoryRecallSearches.length > 0 ? memoryRecallSearches : [{+ resourceType: "resource",+ targetUriInput: targetUri,+ targetUriResolved: targetUri ?? "viking://resources",+ limit: requestLimit,+ scoreThreshold,+ durationMs: 0,+ total: result.total ?? leafOnly.length,+ results: candidateTraceResults,+ }],+ selected: memories.map((item) => ({+ uri: item.uri,+ resourceType: deps.inferRecallResourceType(item.uri),+ category: item.category,+ score: item.score,+ abstractPreview: deps.previewText(item.abstract || item.overview, deps.cfg.traceRecallPreviewChars),+ injected: injectedUris.has(item.uri),+ displayed: injectedUris.has(item.uri),+ })),+ stats: {+ candidateCount: leafOnly.length,+ selectedCount: memories.length,+ injectedCount: injectedUris.size,+ },+ });+ };+ if (memories.length === 0) {+ await recordMemoryRecallTrace(new Set());+ return {+ content: [{ type: "text", text: "No relevant OpenViking memories found." }],+ details: { count: 0, total: result.total ?? 0, scoreThreshold },+ };+ }+ const { lines: memoryLines } = await deps.buildMemoryLinesWithBudget(+ memories,+ (uri) => recallClient.read(uri, session.agentId),+ {+ recallPreferAbstract: false,+ recallMaxInjectedChars: queryConfig.maxInjectedChars,+ },+ );+ if (memoryLines.length === 0) {+ await recordMemoryRecallTrace(new Set());+ return {+ content: [+ {+ type: "text",+ text: `No complete OpenViking memories fit recallMaxInjectedChars=${queryConfig.maxInjectedChars}.`,+ },+ ],+ details: {+ count: 0,+ memories,+ total: result.total ?? memories.length,+ scoreThreshold,+ requestLimit,+ recallMaxInjectedChars: queryConfig.maxInjectedChars,+ },+ };+ }+ await recordMemoryRecallTrace(new Set(memories.slice(0, memoryLines.length).map((item) => item.uri)));+ return {+ content: [+ {+ type: "text",+ text: `Found ${memoryLines.length} memories:\n\n${memoryLines.join("\n")}`,+ },+ ],+ details: {+ count: memoryLines.length,+ memories,+ total: result.total ?? memories.length,+ scoreThreshold,+ requestLimit,+ recallMaxInjectedChars: queryConfig.maxInjectedChars,+ },+ };+ },+ }),+ { name: "memory_recall" },+ );+}diff --git a/examples/openclaw-plugin/plugin/openviking-memory-tools.ts b/examples/openclaw-plugin/plugin/openviking-memory-tools.tsnew file mode 100644index 000000000..8ee346aaa--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-memory-tools.ts@@ -0,0 +1,299 @@+import { Type } from "@sinclair/typebox";++import type { CommitSessionResult, FindResultItem } from "../client.js";+import { clampScore, postProcessMemories } from "../memory-ranking.js";+import { isMemoryUri } from "../routing/memory-uri.js";++export type OpenVikingMemoryToolContext = {+ sessionKey?: string;+ sessionId?: string;+ agentId?: string;+ senderId?: string;+ requesterSenderId?: string;+};++export type OpenVikingMemorySession = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++export type OpenVikingMemoryClient = {+ addSessionMessage: (+ sessionId: string,+ role: string,+ parts: Array<{ type: "text"; text: string }>,+ agentId?: string,+ createdAt?: string,+ roleId?: string,+ ) => Promise<void>;+ commitSession: (+ sessionId: string,+ options: { wait: true; agentId: string; keepRecentCount: number },+ ) => Promise<CommitSessionResult>;+ deleteUri: (uri: string, agentId?: string) => Promise<void>;+ find: (+ query: string,+ options: { targetUri: string; limit: number; scoreThreshold: number },+ agentId?: string,+ ) => Promise<{ memories?: FindResultItem[] }>;+};++export type OpenVikingMemoryToolsDeps = {+ registerTool: (toolOrFactory: unknown, opts: { name: string }) => void;+ getClient: () => Promise<OpenVikingMemoryClient>;+ normalizeSessionId: (sessionId: string) => string;+ createTempSessionId: () => string;+ extractSenderId: (ctx?: OpenVikingMemoryToolContext) => string | undefined;+ toRoleId: (senderId?: string) => string | undefined;+ resolvePluginSessionRouting: (ctx?: OpenVikingMemoryToolContext) => OpenVikingMemorySession;+ isBypassedSession: (ctx?: OpenVikingMemoryToolContext) => boolean;+ makeBypassedToolResult: (toolName: string) => unknown;+ defaultTargetUri: string;+ defaultRecallScoreThreshold: number;+ logFindRequests: boolean;+ logger: {+ info?: (message: string) => void;+ warn: (message: string) => void;+ };+};++function totalCommitMemories(r: CommitSessionResult): number {+ const m = r.memories_extracted;+ if (!m || typeof m !== "object") return 0;+ return Object.values(m).reduce((sum, n) => sum + (n ?? 0), 0);+}++export function registerOpenVikingMemoryTools(deps: OpenVikingMemoryToolsDeps): void {+ deps.registerTool(+ (ctx: OpenVikingMemoryToolContext) => ({+ name: "memory_store",+ label: "Memory Store (OpenViking)",+ description:+ "Store text in OpenViking memory pipeline by writing to a session and running memory extraction.",+ parameters: Type.Object({+ text: Type.String({ description: "Information to store as memory source text" }),+ role: Type.Optional(Type.String({ description: "Session role, default user" })),+ sessionId: Type.Optional(Type.String({ description: "Existing OpenViking session ID" })),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("memory_store");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const { text } = params as { text: string };+ const role =+ typeof (params as { role?: string }).role === "string"+ ? (params as { role: string }).role+ : "user";+ const explicitSessionId =+ typeof (params as { sessionId?: unknown }).sessionId === "string" &&+ (params as { sessionId: string }).sessionId.trim()+ ? deps.normalizeSessionId((params as { sessionId: string }).sessionId)+ : undefined;++ if (deps.logFindRequests) {+ deps.logger.info?.(+ `openviking: memory_store invoked (textLength=${text?.length ?? 0}, sessionId=${explicitSessionId ?? "auto"})`,+ );+ }++ let sessionId = explicitSessionId;+ let usedTempSession = false;+ try {+ const client = await deps.getClient();+ if (!sessionId) {+ sessionId = deps.createTempSessionId();+ usedTempSession = true;+ }+ const roleId = role === "user" ? deps.toRoleId(deps.extractSenderId(ctx)) : undefined;+ await client.addSessionMessage(+ sessionId,+ role,+ [{ type: "text", text }],+ session.agentId,+ undefined,+ roleId,+ );+ const commitResult = await client.commitSession(sessionId, {+ wait: true,+ agentId: session.agentId,+ keepRecentCount: 0,+ });+ const memoriesCount = totalCommitMemories(commitResult);+ if (commitResult.status === "failed") {+ deps.logger.warn(+ `openviking: memory_store commit failed (sessionId=${sessionId}): ${commitResult.error ?? "unknown"}`,+ );+ return {+ content: [{ type: "text", text: `Memory extraction failed for session ${sessionId}: ${commitResult.error ?? "unknown"}` }],+ details: {+ action: "failed",+ sessionId,+ status: "failed",+ error: commitResult.error,+ usedTempSession,+ },+ };+ }+ if (commitResult.status === "timeout") {+ deps.logger.warn(+ `openviking: memory_store commit timed out (sessionId=${sessionId}), task_id=${commitResult.task_id ?? "none"}. Memories may still be extracting in background.`,+ );+ return {+ content: [{ type: "text", text: `Memory extraction timed out for session ${sessionId}. It may still complete in the background (task_id=${commitResult.task_id ?? "none"}).` }],+ details: {+ action: "timeout",+ sessionId,+ status: "timeout",+ taskId: commitResult.task_id,+ usedTempSession,+ },+ };+ }+ if (memoriesCount === 0) {+ deps.logger.warn(+ `openviking: memory_store committed but 0 memories extracted (sessionId=${sessionId}). ` ++ "Check OpenViking server logs for embedding/extract errors (e.g. 401 API key, or extraction pipeline).",+ );+ } else {+ deps.logger.info?.(`openviking: memory_store committed, memories=${memoriesCount}`);+ }+ return {+ content: [+ {+ type: "text",+ text: `Stored in OpenViking session ${sessionId} and committed ${memoriesCount} memories.`,+ },+ ],+ details: {+ action: "stored",+ sessionId,+ memoriesCount,+ status: commitResult.status,+ archived: commitResult.archived ?? false,+ usedTempSession,+ },+ };+ } catch (err) {+ deps.logger.warn(`openviking: memory_store failed: ${String(err)}`);+ throw err;+ }+ },+ }),+ { name: "memory_store" },+ );++ deps.registerTool(+ (ctx: OpenVikingMemoryToolContext) => ({+ name: "memory_forget",+ label: "Memory Forget (OpenViking)",+ description:+ "Forget memory by URI, or search then delete when a strong single match is found.",+ parameters: Type.Object({+ uri: Type.Optional(Type.String({ description: "Exact memory URI to delete" })),+ query: Type.Optional(Type.String({ description: "Search query to find memory URI" })),+ targetUri: Type.Optional(+ Type.String({ description: "Search scope URI (default: plugin config)" }),+ ),+ limit: Type.Optional(Type.Number({ description: "Search limit (default: 5)" })),+ scoreThreshold: Type.Optional(+ Type.Number({ description: "Minimum score (0-1, default: plugin config)" }),+ ),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("memory_forget");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const client = await deps.getClient();+ const uri = (params as { uri?: string }).uri;+ if (uri) {+ if (!isMemoryUri(uri)) {+ return {+ content: [{ type: "text", text: `Refusing to delete non-memory URI: ${uri}` }],+ details: { action: "rejected", uri },+ };+ }+ await client.deleteUri(uri, session.agentId);+ return {+ content: [{ type: "text", text: `Forgotten: ${uri}` }],+ details: { action: "deleted", uri },+ };+ }++ const query = (params as { query?: string }).query;+ if (!query) {+ return {+ content: [{ type: "text", text: "Provide uri or query." }],+ details: { error: "missing_param" },+ };+ }++ const limit =+ typeof (params as { limit?: number }).limit === "number"+ ? Math.max(1, Math.floor((params as { limit: number }).limit))+ : 5;+ const scoreThreshold =+ typeof (params as { scoreThreshold?: number }).scoreThreshold === "number"+ ? Math.max(0, Math.min(1, (params as { scoreThreshold: number }).scoreThreshold))+ : deps.defaultRecallScoreThreshold;+ const targetUri =+ typeof (params as { targetUri?: string }).targetUri === "string"+ ? (params as { targetUri: string }).targetUri+ : deps.defaultTargetUri;+ const requestLimit = Math.max(limit * 4, 20);++ const result = await client.find(+ query,+ {+ targetUri,+ limit: requestLimit,+ scoreThreshold: 0,+ },+ session.agentId,+ );+ const candidates = postProcessMemories(result.memories ?? [], {+ limit: requestLimit,+ scoreThreshold,+ leafOnly: true,+ }).filter((item) => isMemoryUri(item.uri));+ if (candidates.length === 0) {+ return {+ content: [+ {+ type: "text",+ text: "No matching leaf memory candidates found. Try a more specific query.",+ },+ ],+ details: { action: "none", scoreThreshold },+ };+ }+ const top = candidates[0];+ if (candidates.length === 1 && clampScore(top.score) >= 0.85) {+ await client.deleteUri(top.uri, session.agentId);+ return {+ content: [{ type: "text", text: `Forgotten: ${top.uri}` }],+ details: { action: "deleted", uri: top.uri, score: top.score ?? 0 },+ };+ }++ const list = candidates+ .map((item) => `- ${item.uri} (${(clampScore(item.score) * 100).toFixed(0)}%)`)+ .join("\n");++ return {+ content: [+ {+ type: "text",+ text: `Found ${candidates.length} candidates. Specify uri:\n${list}`,+ },+ ],+ details: { action: "candidates", candidates, scoreThreshold, requestLimit },+ };+ },+ }),+ { name: "memory_forget" },+ );+}diff --git a/examples/openclaw-plugin/plugin/openviking-query-config-command.ts b/examples/openclaw-plugin/plugin/openviking-query-config-command.tsnew file mode 100644index 000000000..7dce14896--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-query-config-command.ts@@ -0,0 +1,230 @@+import type { RuntimeQueryParams } from "../query-config.js";+import type { CommandResult, PluginCommandContext } from "./command-registration.js";++type RuntimeScope = "claw" | "session";++type ParsedFlagArgs = {+ positionals: string[];+ flags: Map<string, string | boolean>;+};++export type OpenVikingQueryConfigCommandDeps<TSession, TQueryConfigContext, TEffectiveConfig> = {+ resolvePluginSessionRouting: (ctx?: PluginCommandContext) => TSession;+ toQueryConfigContext: (session: TSession) => TQueryConfigContext;+ queryConfigStore: {+ getEffective: (ctx: TQueryConfigContext) => Promise<TEffectiveConfig>;+ set: (scope: RuntimeScope, ctx: TQueryConfigContext, params: RuntimeQueryParams) => Promise<unknown>;+ unset: (scope: RuntimeScope, ctx: TQueryConfigContext, fields: string[]) => Promise<unknown>;+ reset: (scope: RuntimeScope, ctx: TQueryConfigContext) => Promise<unknown>;+ };+ normalizeRuntimeQueryParams: (patch: RuntimeQueryParams & Record<string, unknown>) => {+ params: RuntimeQueryParams;+ warnings: string[];+ };+};++function tokenizeCommandArgs(args: string): string[] {+ const tokens: string[] = [];+ let current = "";+ let quote: "'" | '"' | null = null;+ let escaping = false;++ for (let i = 0; i < args.length; i += 1) {+ const ch = args[i]!;+ const next = args[i + 1];+ if (escaping) {+ current += ch;+ escaping = false;+ continue;+ }+ if (ch === "\\") {+ const shouldEscape =+ quote === '"'+ ? next === '"' || next === "\\"+ : !quote && Boolean(next && (/\s/.test(next) || next === '"' || next === "'"));+ if (shouldEscape) {+ escaping = true;+ continue;+ }+ current += ch;+ continue;+ }+ if ((ch === '"' || ch === "'") && (!quote || quote === ch)) {+ quote = quote ? null : ch;+ continue;+ }+ if (!quote && /\s/.test(ch)) {+ if (current) {+ tokens.push(current);+ current = "";+ }+ continue;+ }+ current += ch;+ }++ if (escaping) {+ current += "\\";+ }+ if (quote) {+ throw new Error("Unterminated quoted argument");+ }+ if (current) {+ tokens.push(current);+ }+ return tokens;+}++function parseFlagArgs(args: string): ParsedFlagArgs {+ const tokens = tokenizeCommandArgs(args);+ const positionals: string[] = [];+ const flags = new Map<string, string | boolean>();++ for (let i = 0; i < tokens.length; i += 1) {+ const token = tokens[i]!;+ if (!token.startsWith("--")) {+ positionals.push(token);+ continue;+ }+ const raw = token.slice(2);+ if (!raw) {+ continue;+ }+ const eqIndex = raw.indexOf("=");+ if (eqIndex >= 0) {+ flags.set(raw.slice(0, eqIndex), raw.slice(eqIndex + 1));+ continue;+ }+ const next = tokens[i + 1];+ if (next && !next.startsWith("--")) {+ flags.set(raw, next);+ i += 1;+ } else {+ flags.set(raw, true);+ }+ }++ return { positionals, flags };+}++function getStringFlag(flags: Map<string, string | boolean>, name: string): string | undefined {+ const value = flags.get(name);+ return typeof value === "string" && value.trim() ? value.trim() : undefined;+}++function getNumberFlag(flags: Map<string, string | boolean>, name: string): number | undefined {+ const raw = getStringFlag(flags, name);+ if (!raw) {+ return undefined;+ }+ const value = Number(raw);+ if (!Number.isFinite(value)) {+ throw new Error(`--${name} must be a number`);+ }+ return value;+}++function getOptionalBoolFlag(flags: Map<string, string | boolean>, name: string): boolean | undefined {+ const value = flags.get(name);+ if (value === undefined) return undefined;+ if (value === true) return true;+ if (value === false) return false;+ const normalized = value.trim().toLowerCase();+ if (["1", "true", "yes", "on"].includes(normalized)) return true;+ if (["0", "false", "no", "off"].includes(normalized)) return false;+ throw new Error(`--${name} must be a boolean`);+}++function parseNumberMapFlag(flags: Map<string, string | boolean>, name: string): Record<string, number> | undefined {+ const raw = getStringFlag(flags, name);+ if (!raw) return undefined;+ const result: Record<string, number> = {};+ for (const item of raw.split(",")) {+ const [key, rawValue, ...rest] = item.split("=");+ const trimmedKey = key?.trim();+ const trimmedValue = rawValue?.trim();+ if (!trimmedKey || !trimmedValue || rest.length > 0) {+ throw new Error(`--${name} must use key=value pairs separated by commas`);+ }+ const value = Number(trimmedValue);+ if (!Number.isFinite(value)) {+ throw new Error(`--${name} value for ${trimmedKey} must be a number`);+ }+ result[trimmedKey] = value;+ }+ return result;+}++function parseQueryConfigPatch(flags: Map<string, string | boolean>): RuntimeQueryParams {+ const patch: RuntimeQueryParams = {};+ const numberFields: Array<[string, keyof RuntimeQueryParams]> = [+ ["recallLimit", "recallLimit"],+ ["candidateLimit", "candidateLimit"],+ ["candidateMultiplier", "candidateMultiplier"],+ ["scoreThreshold", "scoreThreshold"],+ ["maxInjectedChars", "maxInjectedChars"],+ ["ovSearchLimit", "ovSearchLimit"],+ ];+ for (const [flag, field] of numberFields) {+ if (flags.has(flag)) {+ (patch as Record<string, unknown>)[field] = getNumberFlag(flags, flag);+ }+ }+ const resourceTypes = getStringFlag(flags, "resourceTypes");+ if (resourceTypes) patch.resourceTypes = resourceTypes;+ const targetUri = getStringFlag(flags, "targetUri");+ if (targetUri) patch.targetUri = targetUri;+ const recallPreferAbstract = getOptionalBoolFlag(flags, "recallPreferAbstract");+ if (recallPreferAbstract !== undefined) patch.recallPreferAbstract = recallPreferAbstract;++ const rankingWeights = parseNumberMapFlag(flags, "weight") ?? parseNumberMapFlag(flags, "rankingWeights");+ if (rankingWeights) patch.rankingWeights = rankingWeights;+ const categoryWeights = parseNumberMapFlag(flags, "categoryWeight") ?? parseNumberMapFlag(flags, "categoryWeights");+ if (categoryWeights) patch.categoryWeights = categoryWeights;+ const resourceTypeWeights = parseNumberMapFlag(flags, "resourceTypeWeight") ?? parseNumberMapFlag(flags, "resourceTypeWeights");+ if (resourceTypeWeights) patch.resourceTypeWeights = resourceTypeWeights as RuntimeQueryParams["resourceTypeWeights"];+ return patch;+}++export function createOpenVikingQueryConfigCommandHandler<TSession, TQueryConfigContext, TEffectiveConfig>(+ deps: OpenVikingQueryConfigCommandDeps<TSession, TQueryConfigContext, TEffectiveConfig>,+): (ctx: PluginCommandContext) => Promise<CommandResult> {+ return async (ctx: PluginCommandContext): Promise<CommandResult> => {+ const parsed = parseFlagArgs(ctx.args ?? "");+ const action = parsed.positionals[0] ?? "get";+ const session = deps.resolvePluginSessionRouting(ctx);+ const scope: RuntimeScope = getStringFlag(parsed.flags, "scope") === "claw" ? "claw" : "session";+ const queryCtx = deps.toQueryConfigContext(session);++ if (action === "get") {+ const effective = await deps.queryConfigStore.getEffective(queryCtx);+ return { text: JSON.stringify({ scope, effective }, null, 2), details: { scope, effective } };+ }+ if (action === "set") {+ const patch = parseQueryConfigPatch(parsed.flags);+ const { params, warnings } = deps.normalizeRuntimeQueryParams(patch as RuntimeQueryParams & Record<string, unknown>);+ if (Object.keys(params).length === 0) {+ throw new Error("No query config parameters provided for /ov-query-config set");+ }+ await deps.queryConfigStore.set(scope, queryCtx, params);+ const effective = await deps.queryConfigStore.getEffective(queryCtx);+ return {+ text: `Updated OpenViking query config (${scope}).${warnings.length ? ` Warnings: ${warnings.join("; ")}` : ""}`,+ details: { scope, params, warnings, effective },+ };+ }+ if (action === "unset") {+ const fields = parsed.positionals.slice(1);+ if (fields.length === 0) throw new Error("Usage: /ov-query-config unset <field...> [--scope session|claw]");+ await deps.queryConfigStore.unset(scope, queryCtx, fields);+ const effective = await deps.queryConfigStore.getEffective(queryCtx);+ return { text: `Unset OpenViking query config fields (${scope}): ${fields.join(", ")}`, details: { scope, fields, effective } };+ }+ if (action === "reset") {+ await deps.queryConfigStore.reset(scope, queryCtx);+ const effective = await deps.queryConfigStore.getEffective(queryCtx);+ return { text: `Reset OpenViking query config (${scope}).`, details: { scope, effective } };+ }+ throw new Error("Usage: /ov-query-config get|set|unset|reset [--scope session|claw] [--recallLimit N] [--candidateLimit N] [--scoreThreshold N] [--resourceTypes user,agent]");+ };+}diff --git a/examples/openclaw-plugin/plugin/openviking-query-runtime.ts b/examples/openclaw-plugin/plugin/openviking-query-runtime.tsnew file mode 100644index 000000000..c57c50494--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-query-runtime.ts@@ -0,0 +1,476 @@+import type { FindResult, FindResultItem, FsListResult } from "../client.js";+import type { RecallResourceType } from "../registries/recall-resource-types.js";+import type { RecallTraceEntry, RecallTraceResult } from "../recall-trace.js";++export type OpenVikingSearchInput = {+ query: string;+ uri?: string;+ limit?: number;+};++export type OpenVikingReadInput = {+ uri: string;+};++export type OpenVikingMultiReadInput = {+ uris: string[];+};++export type OpenVikingListInput = {+ uri: string;+ recursive?: boolean;+ simple?: boolean;+ limit?: number;+};++export type OpenVikingQuerySession = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++export type OpenVikingQueryToolResult = {+ content: Array<{ type: "text"; text: string }>;+ details?: Record<string, unknown>;+};++type OpenVikingQueryConfigOverrides = {+ ovSearchLimit?: number;+ targetUri?: string;+};++type OpenVikingQueryConfig = {+ ovSearchLimit?: number;+ targetUri?: string;+};++type OpenVikingQueryClient = {+ find: (+ query: string,+ options: { targetUri: string; limit: number; scoreThreshold?: number },+ agentId?: string,+ ) => Promise<FindResult>;+ read: (uri: string, agentId?: string) => Promise<unknown>;+ list: (+ uri: string,+ options?: { recursive?: boolean; simple?: boolean; nodeLimit?: number },+ agentId?: string,+ ) => Promise<FsListResult>;+};++export type OpenVikingQueryRuntimeDeps<TQueryConfigContext> = {+ getClient: () => Promise<OpenVikingQueryClient>;+ queryConfigStore: {+ getEffective: (ctx: TQueryConfigContext, overrides?: OpenVikingQueryConfigOverrides) => Promise<OpenVikingQueryConfig>;+ };+ toQueryConfigContext: (session: OpenVikingQuerySession) => TQueryConfigContext;+ traceRecorder?: {+ recordAndFlush?: (entry: RecallTraceEntry) => Promise<unknown>;+ };+ inferRecallResourceType: (uri: string) => RecallResourceType | undefined;+ createTraceId: (source: string) => string;+ boundTraceQuery: (query: string, maxChars: number) => { query: string; queryTruncated?: boolean };+ previewText: (value: unknown, maxChars: number) => string | undefined;+ logger: { warn?: (message: string) => void };+ cfg: {+ traceRecallMaxResultsPerSearch: number;+ traceRecallPreviewChars: number;+ traceRecallQueryMaxChars: number;+ };+};++function mergeFindResults(results: FindResult[]): FindResult {+ const deduplicate = (items: FindResultItem[]): FindResultItem[] => {+ const seen = new Map<string, FindResultItem>();+ for (const item of items) {+ if (!seen.has(item.uri)) {+ seen.set(item.uri, item);+ }+ }+ return Array.from(seen.values());+ };+ const memories = deduplicate(results.flatMap((result) => result.memories ?? []));+ const resources = deduplicate(results.flatMap((result) => result.resources ?? []));+ const skills = deduplicate(results.flatMap((result) => result.skills ?? []));+ return {+ memories,+ resources,+ skills,+ total: memories.length + resources.length + skills.length,+ };+}++function formatOVSearchRows(result: FindResult): string[] {+ const truncateSummary = (value: string, maxChars = 220): string => {+ const collapsed = value.replace(/\s+/g, " ").trim();+ if (collapsed.length <= maxChars) {+ return collapsed;+ }+ return `${collapsed.slice(0, maxChars - 3)}...`;+ };+ const items = [+ ...(result.memories ?? []).map((item) => ({ contextType: "memory", item })),+ ...(result.resources ?? []).map((item) => ({ contextType: "resource", item })),+ ...(result.skills ?? []).map((item) => ({ contextType: "skill", item })),+ ];+ if (items.length === 0) {+ return [];+ }+ const numberHeader = "no";+ const numberWidth = Math.max(numberHeader.length, String(items.length).length);+ const typeWidth = Math.max("type".length, ...items.map(({ contextType }) => contextType.length));+ const uriWidth = Math.max("uri".length, ...items.map(({ item }) => item.uri.length));+ const levelWidth = Math.max("level".length, ...items.map(({ item }) => String(item.level ?? "").length));+ const scoreWidth = Math.max(+ "score".length,+ ...items.map(({ item }) => (typeof item.score === "number" ? item.score.toFixed(2).length : 0)),+ );+ return [+ `${numberHeader.padEnd(numberWidth)} ${"type".padEnd(typeWidth)} ${"uri".padEnd(uriWidth)} ${"level".padEnd(levelWidth)} ${"score".padEnd(scoreWidth)} abstract`,+ ...items.map(({ contextType, item }, index) => {+ const score = typeof item.score === "number" ? item.score.toFixed(2) : "";+ const summary = truncateSummary(item.abstract || item.overview || "(no summary)");+ return `${String(index + 1).padEnd(numberWidth)} ${contextType.padEnd(typeWidth)} ${item.uri.padEnd(uriWidth)} ${String(item.level ?? "").padEnd(levelWidth)} ${score.padEnd(scoreWidth)} ${summary}`;+ }),+ ];+}++function formatOVSearchText(query: string, uri: string | undefined, result: FindResult): string {+ if ((result.total ?? 0) <= 0) {+ const scope = uri ? ` under ${uri}` : "";+ return `No OpenViking resource or skill results found for "${query}"${scope}.`;+ }+ const scope = uri ? ` under ${uri}` : "";+ const lines = [+ `Found ${result.total ?? 0} OpenViking results for "${query}"${scope}`,+ "Tip: search results are ranked snippets. Use ov_read on exact hit URIs before answering precise questions. Use ov_list on a hit's parent URI to inspect sibling chunks or overview files before answering procedural or multi-step questions.",+ "",+ ...formatOVSearchRows(result),+ "",+ "Note: result URIs are OpenViking virtual URIs, not local file paths. Use the ov_read tool with the exact viking:// URI to read full content; do not use filesystem read tools for these URIs.",+ ].filter((line, index, all) => line || (all[index - 1] && all[index + 1]));+ return lines.join("\n");+}++function validateOpenVikingUri(toolName: string, uri: string): void {+ if (!uri) {+ throw new Error("uri is required");+ }+ if (!uri.startsWith("viking://")) {+ throw new Error(`${toolName} only accepts OpenViking viking:// URIs, not local file paths or openviking:// display aliases`);+ }+ if (uri.endsWith("...") || uri.includes("…")) {+ throw new Error(+ `${toolName} received a truncated display URI. Use the exact full viking:// URI from ov_search details/results; do not shorten it with ... or ….`,+ );+ }+}++function formatOVListEntry(entry: unknown): string {+ if (typeof entry === "string") {+ return entry;+ }+ if (!entry || typeof entry !== "object") {+ return String(entry);+ }+ const item = entry as Record<string, unknown>;+ const uri = typeof item.uri === "string" ? item.uri : "";+ const name = typeof item.name === "string" ? item.name : "";+ const isDir = item.isDir === true || item.type === "directory";+ const marker = isDir ? "[dir]" : "[file]";+ const summary =+ typeof item.abstract === "string" && item.abstract.trim()+ ? item.abstract.trim().replace(/\s+/g, " ")+ : typeof item.overview === "string" && item.overview.trim()+ ? item.overview.trim().replace(/\s+/g, " ")+ : "";+ const label = uri || name || JSON.stringify(item);+ return summary ? `${marker} ${label} - ${summary}` : `${marker} ${label}`;+}++function formatOVListText(uri: string, entries: FsListResult): string {+ if (entries.length === 0) {+ return `No OpenViking entries found under ${uri}.`;+ }+ return [+ `Listed ${entries.length} OpenViking entr${entries.length === 1 ? "y" : "ies"} under ${uri}`,+ "",+ ...entries.map((entry) => formatOVListEntry(entry)),+ ].join("\n");+}++function formatOVReadText(uri: string, content: string): string {+ const body = content || "(empty OpenViking content)";+ return [`--- START OF ${uri} ---`, body, `--- END OF ${uri} ---`].join("\n");+}++function formatOVMultiReadText(results: Array<{ uri: string; content: string; success: boolean }>): string {+ return [+ `Multi-read results for ${results.length} OpenViking resource${results.length === 1 ? "" : "s"}:`,+ "",+ ...results.flatMap((result) => [+ `--- START OF ${result.uri} ---`,+ result.success ? (result.content || "(empty OpenViking content)") : `ERROR: ${result.content}`,+ `--- END OF ${result.uri} ---`,+ "",+ ]),+ ].join("\n").trimEnd();+}++export function createOpenVikingQueryRuntime<TQueryConfigContext>(deps: OpenVikingQueryRuntimeDeps<TQueryConfigContext>): {+ readOpenVikingContent: (input: OpenVikingReadInput, agentId?: string) => Promise<OpenVikingQueryToolResult>;+ multiReadOpenVikingContent: (input: OpenVikingMultiReadInput, agentId?: string) => Promise<OpenVikingQueryToolResult>;+ listOpenVikingDirectory: (input: OpenVikingListInput, agentId?: string) => Promise<OpenVikingQueryToolResult>;+ searchOpenViking: (input: OpenVikingSearchInput, agentId?: string, traceCtx?: OpenVikingQuerySession) => Promise<OpenVikingQueryToolResult>;+} {+ const toTraceResult = (+ item: FindResultItem,+ resultType: RecallTraceResult["resultType"],+ ): RecallTraceResult => ({+ uri: item.uri,+ resourceType: deps.inferRecallResourceType(item.uri),+ category: item.category,+ score: item.score,+ level: item.level,+ abstractPreview: deps.previewText(item.abstract || item.overview, deps.cfg.traceRecallPreviewChars),+ resultType,+ });++ const readOpenVikingContent = async (input: OpenVikingReadInput, agentId?: string) => {+ const uri = input.uri.trim();+ validateOpenVikingUri("ov_read", uri);+ const client = await deps.getClient();+ const content = await client.read(uri, agentId);+ const text = typeof content === "string" ? content : JSON.stringify(content, null, 2);+ return {+ content: [{ type: "text" as const, text: formatOVReadText(uri, text) }],+ details: {+ action: "read",+ uri,+ chars: text.length,+ },+ };+ };++ const multiReadOpenVikingContent = async (input: OpenVikingMultiReadInput, agentId?: string) => {+ const uris = input.uris+ .map((uri) => (typeof uri === "string" ? uri.trim() : ""))+ .filter((uri) => uri.length > 0);+ if (uris.length === 0) {+ throw new Error("uris is required");+ }+ for (const uri of uris) {+ validateOpenVikingUri("ov_multi_read", uri);+ }+ const client = await deps.getClient();+ const results = await Promise.all(+ uris.map(async (uri) => {+ try {+ const content = await client.read(uri, agentId);+ const text = typeof content === "string" ? content : JSON.stringify(content, null, 2);+ return {+ uri,+ content: text,+ success: true,+ chars: text.length,+ };+ } catch (err) {+ return {+ uri,+ content: err instanceof Error ? err.message : String(err),+ success: false,+ chars: 0,+ };+ }+ }),+ );+ return {+ content: [{ type: "text" as const, text: formatOVMultiReadText(results) }],+ details: {+ action: "multi_read",+ count: results.length,+ success_count: results.filter((result) => result.success).length,+ results,+ },+ };+ };++ const listOpenVikingDirectory = async (input: OpenVikingListInput, agentId?: string) => {+ const uri = input.uri.trim();+ validateOpenVikingUri("ov_list", uri);+ const limit = Math.max(1, Math.floor(input.limit ?? 100));+ const client = await deps.getClient();+ const entries = await client.list(uri, {+ recursive: input.recursive ?? false,+ simple: input.simple ?? false,+ nodeLimit: limit,+ }, agentId);+ return {+ content: [{ type: "text" as const, text: formatOVListText(uri, entries) }],+ details: {+ action: "listed",+ uri,+ recursive: input.recursive ?? false,+ simple: input.simple ?? false,+ count: entries.length,+ entries,+ },+ };+ };++ const searchOpenViking = async (input: OpenVikingSearchInput, agentId?: string, traceCtx?: OpenVikingQuerySession) => {+ const query = input.query.trim();+ if (!query) {+ throw new Error("query is required");+ }+ const queryConfig = traceCtx+ ? await deps.queryConfigStore.getEffective(deps.toQueryConfigContext(traceCtx), {+ ovSearchLimit: typeof input.limit === "number" ? input.limit : undefined,+ targetUri: input.uri,+ })+ : undefined;+ const limit = Math.max(1, Math.floor(input.limit ?? queryConfig?.ovSearchLimit ?? 10));+ const searchUri = input.uri ?? queryConfig?.targetUri;+ const client = await deps.getClient();+ let result: FindResult;+ const searches: RecallTraceEntry["searches"] = [];+ if (searchUri) {+ const started = Date.now();+ result = await client.find(query, { targetUri: searchUri, limit }, agentId);+ const items = [+ ...(result.memories ?? []).map((item) => toTraceResult(item, "memory")),+ ...(result.resources ?? []).map((item) => toTraceResult(item, "resource")),+ ...(result.skills ?? []).map((item) => toTraceResult(item, "skill")),+ ].slice(0, deps.cfg.traceRecallMaxResultsPerSearch);+ searches.push({+ resourceType: deps.inferRecallResourceType(searchUri) ?? "resource",+ targetUriInput: searchUri,+ targetUriResolved: searchUri,+ limit,+ durationMs: Date.now() - started,+ total: result.total ?? items.length,+ results: items,+ });+ } else {+ const runSearch = async (targetUri: string) => {+ const started = Date.now();+ try {+ const found = await client.find(query, { targetUri, limit }, agentId);+ 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, deps.cfg.traceRecallMaxResultsPerSearch);+ searches.push({+ resourceType: deps.inferRecallResourceType(targetUri) ?? "resource",+ targetUriResolved: targetUri,+ limit,+ durationMs: Date.now() - started,+ total: found.total ?? items.length,+ results: items,+ });+ return found;+ } catch (err) {+ searches.push({+ resourceType: deps.inferRecallResourceType(targetUri) ?? "resource",+ targetUriResolved: targetUri,+ limit,+ durationMs: Date.now() - started,+ total: 0,+ results: [],+ error: err instanceof Error ? err.message : String(err),+ });+ throw err;+ }+ };+ const [resourcesSettled, skillsSettled] = await Promise.allSettled([+ runSearch("viking://resources"),+ runSearch("viking://user/skills"),+ ]);+ const successful: FindResult[] = [];+ if (resourcesSettled.status === "fulfilled") {+ successful.push(resourcesSettled.value);+ }+ if (skillsSettled.status === "fulfilled") {+ successful.push(skillsSettled.value);+ }+ if (successful.length === 0) {+ const firstError =+ resourcesSettled.status === "rejected"+ ? resourcesSettled.reason+ : skillsSettled.status === "rejected"+ ? skillsSettled.reason+ : "Both searches failed";+ throw firstError instanceof Error ? firstError : new Error(String(firstError));+ }+ if (resourcesSettled.status === "rejected") {+ deps.logger.warn?.(`openviking: resource search failed: ${String(resourcesSettled.reason)}`);+ }+ if (skillsSettled.status === "rejected") {+ deps.logger.warn?.(`openviking: skill search failed: ${String(skillsSettled.reason)}`);+ }+ result = mergeFindResults(successful);+ }+ const selected = [+ ...(result.memories ?? []).map((item) => ({+ uri: item.uri,+ resourceType: deps.inferRecallResourceType(item.uri),+ category: item.category,+ score: item.score,+ abstractPreview: deps.previewText(item.abstract || item.overview, deps.cfg.traceRecallPreviewChars),+ displayed: true,+ })),+ ...(result.resources ?? []).map((item) => ({+ uri: item.uri,+ resourceType: deps.inferRecallResourceType(item.uri),+ category: item.category,+ score: item.score,+ abstractPreview: deps.previewText(item.abstract || item.overview, deps.cfg.traceRecallPreviewChars),+ displayed: true,+ })),+ ...(result.skills ?? []).map((item) => ({+ uri: item.uri,+ resourceType: deps.inferRecallResourceType(item.uri),+ category: item.category,+ score: item.score,+ abstractPreview: deps.previewText(item.abstract || item.overview, deps.cfg.traceRecallPreviewChars),+ displayed: true,+ })),+ ];+ await deps.traceRecorder?.recordAndFlush?.({+ schemaVersion: "1.0",+ traceId: deps.createTraceId("ov_search"),+ ts: Date.now(),+ sessionId: traceCtx?.sessionId,+ sessionKey: traceCtx?.sessionKey,+ ovSessionId: traceCtx?.ovSessionId,+ agentId,+ source: "ov_search",+ operationType: "semantic_find",+ resourceTypes: [...new Set(searches.map((search) => search.resourceType).filter((resourceType): resourceType is RecallResourceType => resourceType !== "archive"))],+ trigger: deps.boundTraceQuery(query, deps.cfg.traceRecallQueryMaxChars),+ searches,+ selected,+ stats: {+ candidateCount: searches.reduce((sum, search) => sum + search.results.length, 0),+ selectedCount: selected.length,+ injectedCount: 0,+ },+ });+ return {+ content: [{ type: "text" as const, text: formatOVSearchText(query, searchUri, result) }],+ details: {+ action: "searched",+ query,+ uri: searchUri,+ memories: result.memories ?? [],+ resources: result.resources ?? [],+ skills: result.skills ?? [],+ total: result.total ?? 0,+ },+ };+ };++ return { readOpenVikingContent, multiReadOpenVikingContent, listOpenVikingDirectory, searchOpenViking };+}diff --git a/examples/openclaw-plugin/plugin/openviking-query-tools.ts b/examples/openclaw-plugin/plugin/openviking-query-tools.tsnew file mode 100644index 000000000..582c3c1d6--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-query-tools.ts@@ -0,0 +1,161 @@+import { Type } from "@sinclair/typebox";++export type OpenVikingQueryToolContext = {+ sessionKey?: string;+ sessionId?: string;+ agentId?: string;+ senderId?: string;+};++export type OpenVikingQuerySession = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++export type OVSearchInput = {+ query: string;+ uri?: string;+ limit?: number;+};++export type OVReadInput = {+ uri: string;+};++export type OVMultiReadInput = {+ uris: string[];+};++export type OVListInput = {+ uri: string;+ recursive?: boolean;+ simple?: boolean;+ limit?: number;+};++export type OpenVikingQueryToolsDeps = {+ registerTool: (toolOrFactory: unknown, opts: { name: string }) => void;+ searchOpenViking: (+ input: OVSearchInput,+ agentId?: string,+ traceCtx?: OpenVikingQuerySession,+ ) => Promise<unknown>;+ readOpenVikingContent: (input: OVReadInput, agentId?: string) => Promise<unknown>;+ multiReadOpenVikingContent: (input: OVMultiReadInput, agentId?: string) => Promise<unknown>;+ listOpenVikingDirectory: (input: OVListInput, agentId?: string) => Promise<unknown>;+ resolvePluginSessionRouting: (ctx?: OpenVikingQueryToolContext) => OpenVikingQuerySession;+ isBypassedSession: (ctx?: OpenVikingQueryToolContext) => boolean;+ makeBypassedToolResult: (toolName: string) => unknown;+};++export function registerOpenVikingQueryTools(deps: OpenVikingQueryToolsDeps): void {+ deps.registerTool(+ (ctx: OpenVikingQueryToolContext) => ({+ name: "ov_search",+ label: "Search (OpenViking)",+ description:+ "Search OpenViking resources and skills. Use after importing, or when the user asks to search OpenViking resources or skills. " ++ "Search only returns ranked snippets; call ov_read on exact hit URIs before answering precise questions. " ++ "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. " ++ "Returned viking:// URIs are OpenViking virtual URIs, not local file paths.",+ parameters: Type.Object({+ query: Type.String({ description: "Search query" }),+ uri: Type.Optional(Type.String({ description: "Optional search URI. Defaults to resources plus agent skills." })),+ limit: Type.Optional(Type.Number({ description: "Max results per search scope. Default: 10" })),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("ov_search");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ return deps.searchOpenViking({+ query: String((params as { query?: unknown }).query ?? ""),+ uri: typeof params.uri === "string" ? params.uri : undefined,+ limit: typeof params.limit === "number" ? params.limit : undefined,+ }, session.agentId, session);+ },+ }),+ { name: "ov_search" },+ );++ deps.registerTool(+ (ctx: OpenVikingQueryToolContext) => ({+ name: "ov_read",+ label: "Read (OpenViking)",+ description:+ "Read the full original content of one exact OpenViking viking:// URI returned by ov_search, ov_list, or recall traces. " ++ "Use after ov_search before answering precise documentation, codebase, configuration, or procedural questions. " ++ "OpenViking URIs are virtual context-database identifiers, not local file paths; do not use filesystem read tools for them. " ++ "Never pass shortened or display-truncated URIs ending with ... or containing …. Use the exact full URI.",+ parameters: Type.Object({+ uri: Type.String({ description: "Exact viking:// URI returned by ov_search; pass the full URI, e.g. viking://resources/project-docs/api.md#chunk-3; do not use shortened display text with ... or …." }),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("ov_read");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ return deps.readOpenVikingContent({+ uri: String((params as { uri?: unknown }).uri ?? ""),+ }, session.agentId);+ },+ }),+ { name: "ov_read" },+ );++ deps.registerTool(+ (ctx: OpenVikingQueryToolContext) => ({+ name: "ov_multi_read",+ label: "Multi Read (OpenViking)",+ description:+ "Read the full original content of multiple exact OpenViking URIs concurrently. " ++ "Use after ov_search and ov_list to read an overview plus sibling chunks for split documents or multi-step procedures.",+ parameters: Type.Object({+ uris: Type.Array(Type.String({ description: "Exact OpenViking viking:// URI to read" }), {+ description: "Exact OpenViking viking:// URIs to read",+ }),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("ov_multi_read");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const uris = Array.isArray((params as { uris?: unknown }).uris)+ ? (params as { uris: unknown[] }).uris.map((uri) => String(uri))+ : [];+ return deps.multiReadOpenVikingContent({ uris }, session.agentId);+ },+ }),+ { name: "ov_multi_read" },+ );++ deps.registerTool(+ (ctx: OpenVikingQueryToolContext) => ({+ name: "ov_list",+ label: "List (OpenViking)",+ description:+ "List files and directories under an OpenViking URI. Use after ov_search to inspect a hit's parent directory, sibling chunks, or .overview.md files when search only returns ranked snippets.",+ parameters: Type.Object({+ uri: Type.String({ description: "OpenViking directory URI to list, e.g. viking://resources/project/docs" }),+ recursive: Type.Optional(Type.Boolean({ description: "List nested entries recursively. Default: false" })),+ simple: Type.Optional(Type.Boolean({ description: "Return only URI entries from OpenViking. Default: false" })),+ limit: Type.Optional(Type.Number({ description: "Maximum entries to list. Default: 100" })),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("ov_list");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ return deps.listOpenVikingDirectory({+ 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);+ },+ }),+ { name: "ov_list" },+ );+}diff --git a/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts b/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.tsnew file mode 100644index 000000000..540eac7ba--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-recall-trace-runtime.ts@@ -0,0 +1,482 @@+import type {+ RecallTraceEntry,+ RecallTraceQuery,+ RecallTraceResult,+ RecallTraceSource,+} from "../recall-trace.js";+import type { RecallResourceType } from "../registries/recall-resource-types.js";+import type { RecallTraceRouteHandlers, RecallTraceRouteRequest } from "./recall-trace-routes.js";++export type OpenVikingRecallTraceInput = {+ turn?: "latest" | "all";+ traceId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ source?: RecallTraceSource;+ resourceTypes?: RecallResourceType[] | string;+ since?: number;+ until?: number;+ includeContent?: boolean;+ limit?: number;+};++export type OpenVikingRecallTraceSession = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++export type OpenVikingRecallTraceQueryResult = {+ entries: RecallTraceEntry[];+ lookupLayer: "memory" | "persistent";+ warnings: string[];+};++export type OpenVikingRecallTraceRuntimeDeps = {+ getClient: () => Promise<{ read: (uri: string, agentId?: string) => Promise<unknown> }>;+ resolvePluginSessionRouting: (ctx?: {+ agentId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ }) => OpenVikingRecallTraceSession;+ traceRecorder?: {+ queryWithFallback: (query: RecallTraceQuery) => Promise<OpenVikingRecallTraceQueryResult>;+ };+ registerRecallTraceRoutes: (ctx: unknown, handlers: RecallTraceRouteHandlers) => boolean;+ normalizeResourceTypes: (value: unknown) => RecallResourceType[];+ clampScore: (score: number) => number;+ previewText: (value: unknown, maxChars: number) => string | undefined;+ cfg: {+ traceRecallIncludeContentByDefault: boolean;+ traceRecallPreviewChars: number;+ recallMaxContentChars: number;+ };+};++function getOptionalInteger(value: unknown, fallback: number): number {+ if (typeof value !== "number" || !Number.isFinite(value)) {+ return fallback;+ }+ return Math.floor(value);+}++function getPositiveInteger(value: unknown, fallback: number): number {+ return Math.max(1, getOptionalInteger(value, fallback));+}++function toQueryObject(request?: RecallTraceRouteRequest): Record<string, unknown> {+ const query: Record<string, unknown> = { ...(request?.query ?? {}) };+ if (request?.url) {+ const parsed = new URL(request.url, "http://openclaw.local");+ for (const [key, value] of parsed.searchParams.entries()) {+ query[key] = value;+ }+ }+ return { ...query, ...(request?.params ?? {}) };+}++function toBoolean(value: unknown): boolean | undefined {+ if (typeof value === "boolean") return value;+ if (typeof value !== "string") return undefined;+ return ["1", "true", "yes"].includes(value.trim().toLowerCase());+}++function toNumber(value: unknown): number | undefined {+ if (typeof value === "number") return value;+ if (typeof value === "string" && value.trim()) {+ const parsed = Number(value);+ return Number.isFinite(parsed) ? parsed : undefined;+ }+ return undefined;+}++function toString(value: unknown): string | undefined {+ return typeof value === "string" && value.trim() ? value.trim() : undefined;+}++function queryValue(query: Record<string, unknown>, ...keys: string[]): unknown {+ for (const key of keys) {+ if (query[key] !== undefined) {+ return query[key];+ }+ }+ return undefined;+}++function toSessionKey(query: Record<string, unknown>): string | undefined {+ return toString(queryValue(query, "sessionKey", "sessionkey", "session_key", "session-key"));+}++function toLimitedInteger(value: unknown, fallback: number, min: number, max: number): number | undefined {+ const parsed = toNumber(value);+ const raw = parsed === undefined ? fallback : Math.floor(parsed);+ return Number.isFinite(raw) && raw >= min && raw <= max ? raw : undefined;+}++function inferUriType(uri: string): string {+ if (uri.startsWith("viking://resources") || uri.startsWith("viking://resource")) return "resource";+ if (uri.startsWith("viking://session/")) return "session";+ if (uri.startsWith("viking://user/skills") || uri.startsWith("viking://skills")) return "skill";+ if (uri.startsWith("viking://user/")) return "user_memory";+ if (uri.includes("/archive") || uri.includes("/history/")) return "archive";+ return "unknown";+}++function hasExplicitRecallTraceIdentityFilter(input: OpenVikingRecallTraceInput): boolean {+ const traceId = typeof input.traceId === "string" && input.traceId.trim();+ const sessionId = typeof input.sessionId === "string" && input.sessionId.trim();+ const sessionKey = typeof input.sessionKey === "string" && input.sessionKey.trim();+ const ovSessionId = typeof input.ovSessionId === "string" && input.ovSessionId.trim();+ return !!(traceId || sessionId || sessionKey || ovSessionId);+}++function findTraceItem(entry: RecallTraceEntry, uri: string): {+ category?: string;+ score?: number;+ level?: number;+ abstractPreview?: string;+ resultType?: RecallTraceResult["resultType"];+ sourceTraceId?: string;+ source?: RecallTraceSource;+} | undefined {+ const selected = entry.selected.find((item) => item.uri === uri);+ const searchResult = entry.searches.flatMap((search) => search.results).find((item) => item.uri === uri);+ if (!selected && !searchResult) {+ return undefined;+ }+ return {+ category: selected?.category ?? searchResult?.category,+ score: selected?.score ?? searchResult?.score,+ level: searchResult?.level,+ abstractPreview: selected?.abstractPreview ?? searchResult?.abstractPreview,+ resultType: searchResult?.resultType,+ sourceTraceId: entry.traceId,+ source: entry.source,+ };+}++export function createOpenVikingRecallTraceRuntime(deps: OpenVikingRecallTraceRuntimeDeps): {+ queryRecallTraces: (input: OpenVikingRecallTraceInput, session: OpenVikingRecallTraceSession) => Promise<OpenVikingRecallTraceQueryResult>;+ formatRecallTraceText: (result: { entries: RecallTraceEntry[]; lookupLayer: string; warnings: string[] }) => string;+ routeHandlers: RecallTraceRouteHandlers;+ registerRecallTraceRoutes: (ctx?: unknown) => boolean;+} {+ const parseRecallTraceInput = (+ input: OpenVikingRecallTraceInput,+ ctx: { sessionId?: string; sessionKey?: string; ovSessionId?: string },+ ): RecallTraceQuery => {+ const traceId = typeof input.traceId === "string" && input.traceId.trim() ? input.traceId.trim() : undefined;+ const explicitSessionId = typeof input.sessionId === "string" && input.sessionId.trim() ? input.sessionId.trim() : undefined;+ const explicitSessionKey = typeof input.sessionKey === "string" && input.sessionKey.trim() ? input.sessionKey.trim() : undefined;+ const explicitOvSessionId = typeof input.ovSessionId === "string" && input.ovSessionId.trim() ? input.ovSessionId.trim() : undefined;+ const hasExplicitIdentityFilter = !!(traceId || explicitSessionId || explicitSessionKey || explicitOvSessionId);+ const defaultSessionKey = !hasExplicitIdentityFilter ? ctx.sessionKey : undefined;+ const defaultSessionId = !hasExplicitIdentityFilter && !defaultSessionKey ? ctx.sessionId : undefined;+ const defaultOvSessionId = !hasExplicitIdentityFilter && !defaultSessionKey && !defaultSessionId ? ctx.ovSessionId : undefined;+ return {+ turn: input.turn === "all" ? "all" : "latest",+ traceId,+ sessionId: explicitSessionId ?? defaultSessionId,+ sessionKey: explicitSessionKey ?? defaultSessionKey,+ ovSessionId: explicitOvSessionId ?? defaultOvSessionId,+ source: typeof input.source === "string" && input.source.trim() ? input.source as RecallTraceSource : undefined,+ resourceTypes: input.resourceTypes ? deps.normalizeResourceTypes(input.resourceTypes) : undefined,+ since: typeof input.since === "number" ? input.since : undefined,+ until: typeof input.until === "number" ? input.until : undefined,+ limit: getPositiveInteger(input.limit, 20),+ };+ };++ const shouldIncludeTraceContent = (input?: { includeContent?: boolean }): boolean =>+ typeof input?.includeContent === "boolean" ? input.includeContent : deps.cfg.traceRecallIncludeContentByDefault;++ const enrichTraceEntriesWithContent = async (+ result: OpenVikingRecallTraceQueryResult,+ includeContent: boolean,+ agentId?: string,+ ): Promise<OpenVikingRecallTraceQueryResult> => {+ if (!includeContent || result.entries.length === 0) {+ return result;+ }+ const client = await deps.getClient();+ const warnings = [...result.warnings];+ 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 text = typeof content === "string" ? content : JSON.stringify(content);+ return { ...item, contentPreview: deps.previewText(text, deps.cfg.recallMaxContentChars) };+ } catch (err) {+ const readError = err instanceof Error ? err.message : String(err);+ warnings.push(`Failed to read recall trace content ${item.uri}: ${readError}`);+ return { ...item, readError };+ }+ }));+ return { ...entry, selected };+ }));+ return { ...result, entries, warnings };+ };++ const queryTraceForRoute = async (query: OpenVikingRecallTraceInput, session: OpenVikingRecallTraceSession) => deps.traceRecorder+ ? deps.traceRecorder.queryWithFallback(parseRecallTraceInput(query, session))+ : Promise.resolve({ entries: [], lookupLayer: "memory" as const, warnings: ["traceRecall is disabled"] });++ const queryRecallTraces = async (+ input: OpenVikingRecallTraceInput,+ session: OpenVikingRecallTraceSession,+ ): Promise<OpenVikingRecallTraceQueryResult> => {+ const query = parseRecallTraceInput(input, session);+ const base = deps.traceRecorder+ ? await deps.traceRecorder.queryWithFallback(query)+ : { entries: [], lookupLayer: "memory" as const, warnings: ["traceRecall is disabled"] };+ if (+ deps.traceRecorder &&+ base.entries.length === 0 &&+ !hasExplicitRecallTraceIdentityFilter(input) &&+ query.sessionKey+ ) {+ const fallbackIdentities: RecallTraceQuery[] = [];+ if (session.sessionId) {+ fallbackIdentities.push({ ...query, sessionKey: undefined, sessionId: session.sessionId, ovSessionId: undefined });+ }+ if (session.ovSessionId) {+ fallbackIdentities.push({ ...query, sessionKey: undefined, sessionId: undefined, ovSessionId: session.ovSessionId });+ }+ for (const fallbackQuery of fallbackIdentities) {+ const fallback = await deps.traceRecorder.queryWithFallback(fallbackQuery);+ if (fallback.entries.length > 0) {+ return enrichTraceEntriesWithContent(fallback, shouldIncludeTraceContent(input), session.agentId);+ }+ }+ }+ return enrichTraceEntriesWithContent(base, shouldIncludeTraceContent(input), session.agentId);+ };++ const handleUriDetail = async (request?: RecallTraceRouteRequest) => {+ const query = toQueryObject(request);+ const uri = toString(query.uri);+ if (!uri || !uri.startsWith("viking://") || uri.endsWith("...") || uri.includes("…")) {+ return { status: 400, body: { ok: false, uri: uri ?? "", readStatus: "not_requested", warnings: [], error: { code: "invalid_uri", message: "uri must be a complete viking:// URI" } } };+ }+ const offset = toLimitedInteger(query.offset, 0, 0, 1_000_000_000);+ const contentLimit = toLimitedInteger(queryValue(query, "contentLimit", "content-limit", "content_limit"), 20_000, 1, 100_000);+ if (offset === undefined || contentLimit === undefined) {+ return { status: 400, body: { ok: false, uri, readStatus: "not_requested", warnings: [], error: { code: "invalid_param", message: "offset or contentLimit is invalid" } } };+ }+ const includeContent = toBoolean(queryValue(query, "includeContent", "include-content", "include_content")) ?? true;+ const preferTracePreview = toBoolean(queryValue(query, "preferTracePreview", "prefer-trace-preview", "prefer_trace_preview")) ?? true;+ const session = deps.resolvePluginSessionRouting(query);+ const traceId = toString(queryValue(query, "traceId", "trace-id", "trace_id"));+ let traceMetadata: ReturnType<typeof findTraceItem> | undefined;+ const warnings: string[] = [];+ if (preferTracePreview && traceId && deps.traceRecorder) {+ const traceResult = await queryTraceForRoute({ traceId, turn: "latest", limit: 1 }, session);+ warnings.push(...traceResult.warnings);+ traceMetadata = traceResult.entries[0] ? findTraceItem(traceResult.entries[0], uri) : undefined;+ }+ const baseBody = {+ ok: true,+ uri,+ uriType: inferUriType(uri),+ abstractPreview: traceMetadata?.abstractPreview,+ metadata: {+ category: traceMetadata?.category,+ score: traceMetadata?.score,+ level: traceMetadata?.level,+ resultType: traceMetadata?.resultType,+ sourceTraceId: traceMetadata?.sourceTraceId,+ source: traceMetadata?.source,+ },+ readStatus: "not_requested" as const,+ warnings,+ };+ if (!includeContent) {+ return { status: 200, body: baseBody };+ }+ try {+ const client = await deps.getClient();+ const content = await client.read(uri, toString(query.agentId) ?? session.agentId);+ const text = typeof content === "string" ? content : JSON.stringify(content, null, 2);+ const chars = Array.from(text);+ const slice = chars.slice(offset, offset + contentLimit).join("");+ return {+ status: 200,+ body: {+ ...baseBody,+ content: {+ text: slice,+ offset,+ limit: contentLimit,+ returnedChars: Array.from(slice).length,+ totalChars: chars.length,+ hasMore: offset + contentLimit < chars.length,+ },+ readStatus: "ok" as const,+ },+ };+ } catch (err) {+ return {+ status: 502,+ body: {+ ...baseBody,+ ok: false,+ readStatus: "read_failed" as const,+ error: { code: "read_failed", message: err instanceof Error ? err.message : String(err) },+ },+ };+ }+ };++ const handleLatestOvSearchList = async (request?: RecallTraceRouteRequest) => {+ const query = toQueryObject(request);+ const session = deps.resolvePluginSessionRouting(query);+ const limit = toLimitedInteger(query.limit, 20, 1, 100);+ if (limit === undefined) {+ return { status: 400, body: { ok: false, items: [], totalItems: 0, warnings: [], error: { code: "invalid_param", message: "limit is invalid" } } };+ }+ const includeSelected = toBoolean(query.includeSelected) ?? true;+ const dedupe = toBoolean(query.dedupe) ?? true;+ const includeSkills = toBoolean(query.includeSkills) ?? true;+ const strict = toBoolean(query.strict) ?? false;+ const result = await queryTraceForRoute({+ turn: "latest",+ source: "ov_search",+ sessionId: toString(query.sessionId),+ sessionKey: toSessionKey(query),+ ovSessionId: toString(query.ovSessionId),+ limit: 1,+ }, session);+ const agentId = toString(query.agentId);+ const entry = agentId ? result.entries.find((candidate) => candidate.agentId === agentId) : result.entries[0];+ if (!entry) {+ const body = {+ ok: !strict,+ lookupLayer: "none" as const,+ fallbackUsed: false,+ query: { sessionId: toString(query.sessionId), sessionKey: toString(query.sessionKey), ovSessionId: toString(query.ovSessionId), agentId, limit, lookup: toString(query.lookup) ?? "auto" },+ items: [],+ totalItems: 0,+ warnings: [...result.warnings, "no ov_search trace found for latest interaction"],+ ...(strict ? { error: { code: "not_found", message: "no ov_search trace found for latest interaction" } } : {}),+ };+ return { status: strict ? 404 : 200, body };+ }+ const searchResultByUri = new Map<string, RecallTraceResult & { targetUri?: string }>();+ for (const search of entry.searches) {+ for (const item of search.results) {+ searchResultByUri.set(item.uri, { ...item, targetUri: search.targetUriResolved ?? search.targetUriInput });+ }+ }+ const items: Array<Record<string, unknown>> = [];+ const addItem = (item: { uri: string; resourceType?: unknown; category?: string; score?: number; abstractPreview?: string }, source: "search_result" | "selected") => {+ const matched = searchResultByUri.get(item.uri);+ const resultType = matched?.resultType ?? (inferUriType(item.uri) === "skill" ? "skill" : inferUriType(item.uri).includes("memory") ? "memory" : "resource");+ if (!includeSkills && resultType === "skill") {+ return;+ }+ const row = {+ uri: item.uri,+ abstractPreview: item.abstractPreview ?? matched?.abstractPreview,+ resourceType: item.resourceType ?? matched?.resourceType,+ resultType,+ category: item.category ?? matched?.category,+ score: item.score ?? matched?.score,+ source,+ targetUri: matched?.targetUri,+ detailUrl: `/api/openviking/uri-detail?uri=${encodeURIComponent(item.uri)}&traceId=${encodeURIComponent(entry.traceId)}`,+ };+ if (dedupe) {+ const existing = items.findIndex((candidate) => candidate.uri === item.uri);+ if (existing >= 0) {+ if (source === "selected") items[existing] = row;+ return;+ }+ }+ items.push(row);+ };+ if (includeSelected) {+ entry.selected.forEach((item) => addItem(item, "selected"));+ }+ for (const search of entry.searches) {+ search.results.forEach((item) => addItem(item, "search_result"));+ }+ const limited = items.slice(0, limit);+ return {+ status: 200,+ body: {+ ok: true,+ lookupLayer: result.lookupLayer,+ fallbackUsed: result.lookupLayer === "persistent",+ query: { sessionId: toString(query.sessionId), sessionKey: toString(query.sessionKey), ovSessionId: toString(query.ovSessionId), agentId, limit, lookup: toString(query.lookup) ?? "auto" },+ trace: {+ traceId: entry.traceId,+ ts: entry.ts,+ isoTime: new Date(entry.ts).toISOString(),+ triggerQuery: entry.trigger.query,+ totalSearches: entry.searches.length,+ },+ items: limited,+ totalItems: limited.length,+ warnings: result.warnings,+ },+ };+ };++ const handleRecallTraces = async (request?: RecallTraceRouteRequest) => {+ const query = toQueryObject(request);+ const session = deps.resolvePluginSessionRouting(query);+ const result = await queryRecallTraces({+ turn: query.turn === "all" ? "all" : "latest",+ traceId: toString(queryValue(query, "traceId", "trace-id", "trace_id")),+ sessionId: typeof query.sessionId === "string" ? query.sessionId : undefined,+ sessionKey: toSessionKey(query),+ ovSessionId: typeof query.ovSessionId === "string" ? query.ovSessionId : undefined,+ source: typeof query.source === "string" ? query.source as RecallTraceSource : undefined,+ resourceTypes: typeof query.resourceTypes === "string" ? query.resourceTypes : undefined,+ since: toNumber(query.since),+ until: toNumber(query.until),+ includeContent: toBoolean(queryValue(query, "includeContent", "include-content", "include_content")),+ limit: toNumber(query.limit),+ }, session);+ return { status: 200, body: { ok: true, ...result } };+ };++ const formatRecallTraceText = (result: { entries: RecallTraceEntry[]; lookupLayer: string; warnings: string[] }): string => {+ if (result.entries.length === 0) {+ return `No OpenViking recall traces found (lookupLayer=${result.lookupLayer}).`;+ }+ const blocks = result.entries.map((entry, index) => {+ const selected = entry.selected.slice(0, 8)+ .map((item) => ` - ${item.uri}${item.score !== undefined ? ` (${(deps.clampScore(item.score) * 100).toFixed(0)}%)` : ""}`)+ .join("\n");+ return [+ `## Trace ${index + 1}: ${entry.source}`,+ `traceId: ${entry.traceId}`,+ `query: ${entry.trigger.query}`,+ `resourceTypes: ${entry.resourceTypes.join(", ")}`,+ `stats: candidates=${entry.stats.candidateCount}, selected=${entry.stats.selectedCount}, injected=${entry.stats.injectedCount}`,+ selected ? `selected:\n${selected}` : "selected: (none)",+ ].join("\n");+ });+ const warnings = result.warnings.length > 0+ ? `\n\nWarnings:\n${result.warnings.map((w) => `- ${w}`).join("\n")}`+ : "";+ return `${blocks.join("\n\n")}${warnings}`;+ };++ const routeHandlers = {+ handleRecallTraces,+ handleUriDetail,+ handleLatestOvSearchList,+ };++ return {+ queryRecallTraces,+ formatRecallTraceText,+ routeHandlers,+ registerRecallTraceRoutes: (ctx?: unknown) => deps.registerRecallTraceRoutes(ctx, routeHandlers),+ };+}diff --git a/examples/openclaw-plugin/plugin/openviking-recall-trace-tools.ts b/examples/openclaw-plugin/plugin/openviking-recall-trace-tools.tsnew file mode 100644index 000000000..de294f83c--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-recall-trace-tools.ts@@ -0,0 +1,99 @@+import { Type } from "@sinclair/typebox";++import type { RecallResourceType } from "../registries/recall-resource-types.js";+import type {+ RecallTraceEntry,+ RecallTraceSource,+} from "../recall-trace.js";++export type OpenVikingRecallTraceToolContext = {+ sessionKey?: string;+ sessionId?: string;+ agentId?: string;+ senderId?: string;+};++export type OpenVikingRecallTraceSession = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++export type RecallTraceToolInput = {+ turn?: "latest" | "all";+ traceId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ source?: RecallTraceSource;+ resourceTypes?: RecallResourceType[] | string;+ since?: number;+ until?: number;+ includeContent?: boolean;+ limit?: number;+};++export type RecallTraceToolResult = {+ entries: RecallTraceEntry[];+ lookupLayer: string;+ warnings: string[];+};++export type OpenVikingRecallTraceToolsDeps = {+ registerTool: (toolOrFactory: unknown, opts: { name: string }) => void;+ queryRecallTraces: (+ input: RecallTraceToolInput,+ session: OpenVikingRecallTraceSession,+ ) => Promise<RecallTraceToolResult>;+ formatRecallTraceText: (result: RecallTraceToolResult) => string;+ resolvePluginSessionRouting: (+ ctx?: OpenVikingRecallTraceToolContext,+ ) => OpenVikingRecallTraceSession;+ isBypassedSession: (ctx?: OpenVikingRecallTraceToolContext) => boolean;+ makeBypassedToolResult: (toolName: string) => unknown;+};++export function registerOpenVikingRecallTraceTools(+ deps: OpenVikingRecallTraceToolsDeps,+): void {+ deps.registerTool(+ (ctx: OpenVikingRecallTraceToolContext) => ({+ name: "ov_recall_trace",+ label: "Recall Trace (OpenViking)",+ description:+ "Query OpenViking recall trace records captured by auto-recall and explicit recall/search tools.",+ parameters: Type.Object({+ turn: Type.Optional(Type.String({ description: "latest or all (default: latest)" })),+ traceId: Type.Optional(Type.String({ description: "Exact trace id" })),+ sessionId: Type.Optional(Type.String({ description: "OpenClaw session id" })),+ sessionKey: Type.Optional(Type.String({ description: "OpenClaw session key" })),+ ovSessionId: Type.Optional(Type.String({ description: "OpenViking session id" })),+ source: Type.Optional(Type.String({ description: "auto_recall, memory_recall, ov_search, or ov_archive_search" })),+ resourceTypes: Type.Optional(Type.Array(Type.String({ description: "resource, user, or agent" }))),+ since: Type.Optional(Type.Number({ description: "Unix timestamp lower bound in milliseconds" })),+ until: Type.Optional(Type.Number({ description: "Unix timestamp upper bound in milliseconds" })),+ includeContent: Type.Optional(Type.Boolean({ description: "Read selected/displayed URI content previews on demand" })),+ limit: Type.Optional(Type.Number({ description: "Maximum traces to return (default: 20)" })),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (deps.isBypassedSession(ctx)) {+ return deps.makeBypassedToolResult("ov_recall_trace");+ }+ const session = deps.resolvePluginSessionRouting(ctx);+ const result = await deps.queryRecallTraces(params as RecallTraceToolInput, session);+ return {+ content: [{ type: "text" as const, text: deps.formatRecallTraceText(result) }],+ details: {+ action: "queried",+ count: result.entries.length,+ lookupLayer: result.lookupLayer,+ warnings: result.warnings,+ entries: result.entries,+ },+ };+ },+ }),+ { name: "ov_recall_trace" },+ );+}diff --git a/examples/openclaw-plugin/plugin/openviking-runtime-state.ts b/examples/openclaw-plugin/plugin/openviking-runtime-state.tsnew file mode 100644index 000000000..d4bca8a1d--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-runtime-state.ts@@ -0,0 +1,52 @@+import type { MemoryOpenVikingConfig } from "../config.js";+import { RuntimeQueryConfigStore } from "../query-config.js";+import { RecallTraceRecorder } from "../recall-trace.js";++type Logger = {+ warn?: (message: string) => void;+};++type RuntimeStateConfig = Required<+ Pick<+ MemoryOpenVikingConfig,+ | "runtimeQueryConfigPath"+ | "traceRecall"+ | "traceRecallMaxEntries"+ | "traceRecallPersist"+ | "traceRecallDir"+ | "traceRecallIncludeRawUserPreview"+ | "traceRecallRetentionDays"+ | "traceRecallQueryMaxDays"+ >+>;++export function createOpenVikingRuntimeState(options: {+ cfg: Required<MemoryOpenVikingConfig> & RuntimeStateConfig;+ logger: Logger;+}) {+ const { cfg, logger } = options;++ const queryConfigStore = new RuntimeQueryConfigStore({+ staticConfig: cfg,+ path: cfg.runtimeQueryConfigPath || undefined,+ });+ void queryConfigStore.load().catch((err) => {+ logger.warn?.(`openviking: failed to load runtime query config: ${String(err)}`);+ });++ const traceRecorder = cfg.traceRecall+ ? new RecallTraceRecorder({+ memoryMaxEntries: cfg.traceRecallMaxEntries,+ persist: cfg.traceRecallPersist,+ traceDir: cfg.traceRecallDir,+ includeRawUserPreview: cfg.traceRecallIncludeRawUserPreview,+ retentionDays: cfg.traceRecallRetentionDays,+ queryMaxDays: cfg.traceRecallQueryMaxDays,+ })+ : undefined;++ return {+ queryConfigStore,+ traceRecorder,+ };+}diff --git a/examples/openclaw-plugin/plugin/openviking-runtime-utils.ts b/examples/openclaw-plugin/plugin/openviking-runtime-utils.tsnew file mode 100644index 000000000..8e07ee3ba--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-runtime-utils.ts@@ -0,0 +1,67 @@+import type { RecallResourceType } from "../registries/recall-resource-types.js";++export function previewText(value: unknown, maxChars: number): string | undefined {+ const text = typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";+ if (!text) {+ return undefined;+ }+ return text.length <= maxChars ? text : `${text.slice(0, Math.max(0, maxChars - 1))}…`;+}++export function inferRecallResourceType(uri: string): RecallResourceType | undefined {+ if (uri.startsWith("viking://resources")) return "resource";+ if (uri.startsWith("viking://user/skills") || uri.startsWith("viking://skills")) return "agent";+ if (uri.startsWith("viking://user/")) return "user";+ return undefined;+}++export function createTraceId(source: string): string {+ return `${source}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;+}++export function createMemoryStoreTempSessionId(): string {+ return `memory-store-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+}++export function boundTraceQuery(query: string, maxChars: number): { query: string; queryTruncated?: boolean } {+ if (query.length <= maxChars) {+ return { query };+ }+ return { query: query.slice(0, maxChars), queryTruncated: true };+}++export function extractToolSenderId(ctx: unknown): string | undefined {+ if (!ctx || typeof ctx !== "object") {+ return undefined;+ }+ const toolCtx = ctx as Record<string, unknown>;+ if (typeof toolCtx.requesterSenderId === "string") {+ const trimmed = toolCtx.requesterSenderId.trim();+ if (trimmed) {+ return trimmed;+ }+ }+ if (typeof toolCtx.senderId === "string") {+ const trimmed = toolCtx.senderId.trim();+ if (trimmed) {+ return trimmed;+ }+ }+ return undefined;+}++export function makeBypassedToolResult(toolName: string) {+ return {+ content: [+ {+ type: "text" as const,+ text: `OpenViking is bypassed for this session by bypassSessionPatterns; ${toolName} was skipped.`,+ },+ ],+ details: {+ action: "bypassed",+ reason: "session_bypassed",+ toolName,+ },+ };+}diff --git a/examples/openclaw-plugin/plugin/openviking-services.ts b/examples/openclaw-plugin/plugin/openviking-services.tsnew file mode 100644index 000000000..203c74dc8--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-services.ts@@ -0,0 +1,49 @@+export type OpenVikingServiceLogger = {+ info: (message: string) => void;+ warn?: (message: string) => void;+};++export type OpenVikingServiceConfig = {+ baseUrl: string;+ targetUri: string;+};++export type OpenVikingServiceClient = {+ healthCheck: () => Promise<unknown>;+};++export type OpenVikingServiceOptions = {+ cfg: OpenVikingServiceConfig;+ getClient: () => Promise<OpenVikingServiceClient>;+ logger: OpenVikingServiceLogger;+ recallTraceHttpRoutesRegistered: boolean;+ registerRecallTraceRoutes: (ctx?: unknown) => boolean;+};++export function createOpenVikingService({+ cfg,+ getClient,+ logger,+ recallTraceHttpRoutesRegistered,+ registerRecallTraceRoutes,+}: OpenVikingServiceOptions) {+ return {+ id: "openviking",+ start: async (ctx?: unknown) => {+ const runtimeRouteRegistered = registerRecallTraceRoutes(ctx);+ const routeRegistered = recallTraceHttpRoutesRegistered || runtimeRouteRegistered;+ await (await getClient()).healthCheck().catch(() => {});+ logger.info(+ `openviking: initialized (url: ${cfg.baseUrl}, targetUri: ${cfg.targetUri}, search: hybrid endpoint)`,+ );+ if (routeRegistered) {+ logger.info("openviking: registered recall trace Gateway routes");+ } else {+ logger.warn?.("openviking: recall trace Gateway route adapter unavailable; use ov_recall_trace tool or /ov-recall-trace command");+ }+ },+ stop: () => {+ logger.info("openviking: stopped");+ },+ };+}diff --git a/examples/openclaw-plugin/plugin/openviking-session-routing-runtime.ts b/examples/openclaw-plugin/plugin/openviking-session-routing-runtime.tsnew file mode 100644index 000000000..48fcb1e3c--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-session-routing-runtime.ts@@ -0,0 +1,105 @@+import type { QueryConfigContext } from "../query-config.js";+import {+ createSessionAgentResolver,+ openClawSessionToOvStorageId,+} from "../routing/identity-routing.js";++type Logger = {+ info: (message: string) => void;+};++export type SessionAgentLookup = {+ agentId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+};++export type PluginSessionRouting = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++export function createOpenVikingSessionRoutingRuntime(options: {+ peerPrefix: string;+ logFindRequests: boolean;+ logger: Logger;+}) {+ const sessionAgentResolver = createSessionAgentResolver(options.peerPrefix);++ const rememberSessionAgentId = (ctx: SessionAgentLookup) => {+ sessionAgentResolver.remember(ctx);+ };++ const resolveAgentId = (+ sessionId?: string,+ sessionKey?: string,+ ovSessionId?: string,+ ): string => {+ const sid = typeof sessionId === "string" ? sessionId.trim() : "";+ const sk = typeof sessionKey === "string" ? sessionKey.trim() : "";+ const ovSid = typeof ovSessionId === "string" ? ovSessionId.trim() : "";+ const result = sessionAgentResolver.resolve(sid, sk, ovSid);+ if (options.logFindRequests) {+ options.logger.info(+ `openviking: resolveAgentId ${JSON.stringify({+ sessionId: sid || "(empty)",+ sessionKey: sk || "(empty)",+ ovSessionId: ovSid || "(empty)",+ parsedConfigPeerPrefix: options.peerPrefix,+ mappedResolvedAgentId: result.mappedResolvedAgentId,+ resolvedBeforeSanitize: result.resolvedBeforeSanitize,+ resolved: result.resolved,+ branch: result.branch,+ aliases: result.aliases,+ fromExplicitBinding: result.fromExplicitBinding,+ })}`,+ );+ }+ return result.resolved;+ };++ const resolvePluginSessionRouting = (ctx?: SessionAgentLookup): PluginSessionRouting => {+ const sessionId = typeof ctx?.sessionId === "string" ? ctx.sessionId.trim() : "";+ const sessionKey = typeof ctx?.sessionKey === "string" ? ctx.sessionKey.trim() : "";+ let ovSessionId = typeof ctx?.ovSessionId === "string" ? ctx.ovSessionId.trim() : "";++ if (!ovSessionId && (sessionId || sessionKey)) {+ ovSessionId = openClawSessionToOvStorageId(+ sessionId || undefined,+ sessionKey || undefined,+ );+ }++ const session = {+ agentId: ctx?.agentId,+ sessionId: sessionId || undefined,+ sessionKey: sessionKey || undefined,+ ovSessionId: ovSessionId || undefined,+ };+ rememberSessionAgentId(session);++ return {+ sessionId: session.sessionId,+ sessionKey: session.sessionKey,+ ovSessionId: session.ovSessionId,+ agentId: resolveAgentId(session.sessionId, session.sessionKey, session.ovSessionId),+ };+ };++ const toQueryConfigContext = (session: PluginSessionRouting): QueryConfigContext => ({+ peerId: session.agentId,+ sessionId: session.sessionId,+ sessionKey: session.sessionKey,+ ovSessionId: session.ovSessionId,+ });++ return {+ rememberSessionAgentId,+ resolveAgentId,+ resolvePluginSessionRouting,+ toQueryConfigContext,+ };+}diff --git a/examples/openclaw-plugin/plugin/openviking-tool-result-tools.ts b/examples/openclaw-plugin/plugin/openviking-tool-result-tools.tsnew file mode 100644index 000000000..6a37a98e1--- /dev/null+++ b/examples/openclaw-plugin/plugin/openviking-tool-result-tools.ts@@ -0,0 +1,397 @@+import { Type } from "@sinclair/typebox";++export type OpenVikingToolResultToolContext = {+ sessionKey?: string;+ sessionId?: string;+ agentId?: string;+ senderId?: string;+};++export type OpenVikingToolResultSession = {+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ agentId: string;+};++export type OpenVikingToolResultToolDefinition = {+ name: string;+ label: string;+ description: string;+ parameters: unknown;+ execute: (_toolCallId: string, params: Record<string, unknown>) => Promise<unknown>;+};++export type OpenVikingToolResultClient = {+ readToolResult: (+ sessionId: string,+ toolResultId: string,+ options: { offset: number; limit: number; includeMetadata: boolean },+ agentId?: string,+ ) => Promise<{+ content: string;+ offset: number;+ limit: number;+ total_chars: number;+ has_more: boolean;+ tool_result_id: string;+ metadata?: unknown;+ }>;+ searchToolResult: (+ sessionId: string,+ toolResultId: string,+ query: string,+ options: { limit: number; contextChars: number },+ agentId?: string,+ ) => Promise<{+ tool_result_id: string;+ matches?: Array<{ offset: number; snippet: string }>;+ }>;+ listToolResults: (+ sessionId: string,+ options: { toolName?: string; limit: number },+ agentId?: string,+ ) => Promise<{+ tool_results?: Array<{+ storage_uri?: string;+ tool_name?: string;+ original_chars?: number;+ created_at?: string;+ }>;+ }>;+};++export type OpenVikingToolResultToolsDeps = {+ registerTool: (toolOrFactory: unknown, opts: { name: string }) => void;+ getClient: () => Promise<OpenVikingToolResultClient>;+ resolvePluginSessionRouting: (ctx?: OpenVikingToolResultToolContext) => OpenVikingToolResultSession;+ isBypassedSession: (ctx?: OpenVikingToolResultToolContext) => boolean;+ makeBypassedToolResult: (toolName: string) => unknown;+ logger?: { warn?: (message: string) => void };+};++type ToolResultRef = {+ sessionId: string;+ toolResultId: string;+ ref: string;+};++export function parseToolResultRef(value: unknown): ToolResultRef | null {+ const raw = typeof value === "string" ? value.trim() : "";+ if (!raw) {+ return null;+ }+ const match = raw.match(/^viking:\/\/session\/([^/]+)\/tool-results\/([^/?#]+)(?:[?#].*)?$/);+ if (!match) {+ return null;+ }+ const sessionId = decodeURIComponent(match[1]!);+ const toolResultId = decodeURIComponent(match[2]!);+ if (!sessionId || !toolResultId) {+ return null;+ }+ return {+ sessionId,+ toolResultId,+ ref: `viking://session/${encodeURIComponent(sessionId)}/tool-results/${encodeURIComponent(toolResultId)}`,+ };+}++function getOptionalInteger(value: unknown, fallback: number): number {+ if (typeof value !== "number" || !Number.isFinite(value)) {+ return fallback;+ }+ return Math.floor(value);+}++function getPositiveInteger(value: unknown, fallback: number): number {+ return Math.max(1, getOptionalInteger(value, fallback));+}++export function registerOpenVikingToolResultTools({+ registerTool,+ getClient,+ resolvePluginSessionRouting,+ isBypassedSession,+ makeBypassedToolResult,+ logger,+}: OpenVikingToolResultToolsDeps): void {+ registerTool(+ (ctx: OpenVikingToolResultToolContext): OpenVikingToolResultToolDefinition => ({+ name: "openviking_tool_result_read",+ label: "Tool Result Read (OpenViking)",+ description:+ "Restore the full original content of a tool result that was externalized by OpenViking. " ++ "Use when a previous tool result was externalized and only a preview is visible — " ++ "the preview contains a [tool-result-ref] or viking://session/.../tool-results/... URI. " ++ "\"Read\" tool returns the same truncated preview; this tool returns the complete content. " ++ "To read all content: pass offset=0 and a limit large enough to cover the whole result " ++ "(e.g. limit=100000). Use offset/limit for paging only when you need a specific section.",+ parameters: Type.Object({+ tool_output_ref: Type.String({+ description:+ "Exact OV URI from the preview, e.g. viking://session/<session_id>/tool-results/<tool_result_id>",+ }),+ offset: Type.Optional(Type.Number({ description: "Unicode character offset. Default: 0" })),+ limit: Type.Optional(Type.Number({ description: "Maximum Unicode characters to read. Default: 20000" })),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (isBypassedSession(ctx)) {+ return makeBypassedToolResult("openviking_tool_result_read");+ }+ const session = resolvePluginSessionRouting(ctx);+ if (!session.ovSessionId) {+ return {+ content: [{ type: "text", text: "Error: no active session." }],+ details: { error: "no_session" },+ };+ }++ const parsed = parseToolResultRef(params.tool_output_ref ?? params.ref ?? params.uri);+ if (!parsed) {+ return {+ content: [{ type: "text", text: "Error: tool_output_ref must be a viking://session/.../tool-results/... URI." }],+ details: { error: "invalid_tool_output_ref" },+ };+ }+ if (parsed.sessionId !== session.ovSessionId) {+ return {+ content: [{ type: "text", text: "Error: refusing to read a tool result from another session." }],+ details: {+ error: "session_mismatch",+ requestedSessionId: parsed.sessionId,+ currentSessionId: session.ovSessionId,+ },+ };+ }++ const offset = Math.max(0, getOptionalInteger(params.offset, 0));+ const limit = getOptionalInteger(params.limit, 20_000);+ if (limit < -1) {+ return {+ content: [{ type: "text", text: "Error: limit must be -1 or greater than or equal to 0." }],+ details: { error: "invalid_limit", limit },+ };+ }++ try {+ const client = await getClient();+ const result = await client.readToolResult(+ session.ovSessionId,+ parsed.toolResultId,+ { offset, limit, includeMetadata: true },+ session.agentId,+ );+ const returnedChars = result.content.length;+ const nextOffset = result.offset + returnedChars;+ const text = result.content || "(empty tool result chunk)";+ return {+ content: [{ type: "text", text }],+ details: {+ action: "read",+ tool_output_ref: parsed.ref,+ tool_result_id: result.tool_result_id,+ offset: result.offset,+ limit: result.limit,+ returned_chars: returnedChars,+ total_chars: result.total_chars,+ has_more: result.has_more,+ next_offset: result.has_more ? nextOffset : null,+ metadata: result.metadata ?? null,+ },+ };+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ logger?.warn?.(`openviking: openviking_tool_result_read failed: ${msg}`);+ return {+ content: [{ type: "text", text: `Failed to read tool result: ${msg}` }],+ details: { error: msg, tool_output_ref: parsed.ref },+ };+ }+ },+ }),+ { name: "openviking_tool_result_read" },+ );++ registerTool(+ (ctx: OpenVikingToolResultToolContext): OpenVikingToolResultToolDefinition => ({+ name: "openviking_tool_result_search",+ label: "Tool Result Search (OpenViking)",+ description:+ "Search inside an externalized tool result for a keyword. " ++ "Use when you need to find specific content in a large externalized result, " ++ "before reading it with openviking_tool_result_read. " ++ "Returns matching snippets with their character offsets.",+ parameters: Type.Object({+ tool_output_ref: Type.String({+ description:+ "Exact OV URI from the preview, e.g. viking://session/<session_id>/tool-results/<tool_result_id>",+ }),+ query: Type.String({ description: "Keyword or exact text to search for" }),+ limit: Type.Optional(Type.Number({ description: "Maximum matches. Default: 20" })),+ context_chars: Type.Optional(Type.Number({ description: "Characters around each match. Default: 300" })),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (isBypassedSession(ctx)) {+ return makeBypassedToolResult("openviking_tool_result_search");+ }+ const session = resolvePluginSessionRouting(ctx);+ if (!session.ovSessionId) {+ return {+ content: [{ type: "text", text: "Error: no active session." }],+ details: { error: "no_session" },+ };+ }++ const parsed = parseToolResultRef(params.tool_output_ref ?? params.ref ?? params.uri);+ if (!parsed) {+ return {+ content: [{ type: "text", text: "Error: tool_output_ref must be a viking://session/.../tool-results/... URI." }],+ details: { error: "invalid_tool_output_ref" },+ };+ }+ if (parsed.sessionId !== session.ovSessionId) {+ return {+ content: [{ type: "text", text: "Error: refusing to search a tool result from another session." }],+ details: {+ error: "session_mismatch",+ requestedSessionId: parsed.sessionId,+ currentSessionId: session.ovSessionId,+ },+ };+ }++ const query = String(params.query ?? "").trim();+ if (!query) {+ return {+ content: [{ type: "text", text: "Error: query is required." }],+ details: { error: "missing_param", param: "query" },+ };+ }+ const limit = getPositiveInteger(params.limit, 20);+ const contextChars = Math.max(+ 0,+ getOptionalInteger(params.context_chars ?? params.contextChars, 300),+ );++ try {+ const client = await getClient();+ const result = await client.searchToolResult(+ session.ovSessionId,+ parsed.toolResultId,+ query,+ { limit, contextChars },+ session.agentId,+ );+ const matches = result.matches ?? [];+ const text = matches.length+ ? [+ `Found ${matches.length} match(es) for "${query}" in ${parsed.ref}:`,+ "",+ ...matches.map((match, index) =>+ `## Match ${index + 1} (offset ${match.offset})\n${match.snippet}`,+ ),+ ].join("\n")+ : `No matches found for "${query}" in ${parsed.ref}.`;+ return {+ content: [{ type: "text", text }],+ details: {+ action: "searched",+ tool_output_ref: parsed.ref,+ tool_result_id: result.tool_result_id,+ query,+ match_count: matches.length,+ matches,+ },+ };+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ logger?.warn?.(`openviking: openviking_tool_result_search failed: ${msg}`);+ return {+ content: [{ type: "text", text: `Failed to search tool result: ${msg}` }],+ details: { error: msg, tool_output_ref: parsed.ref, query },+ };+ }+ },+ }),+ { name: "openviking_tool_result_search" },+ );++ registerTool(+ (ctx: OpenVikingToolResultToolContext): OpenVikingToolResultToolDefinition => ({+ name: "openviking_tool_result_list",+ label: "Tool Result List (OpenViking)",+ description:+ "List externalized tool results for the current session. " ++ "Use to discover available refs before calling openviking_tool_result_read. " ++ "Optionally filter by tool_name to narrow down results.",+ parameters: Type.Object({+ tool_name: Type.Optional(Type.String({ description: "Optional exact tool name filter" })),+ limit: Type.Optional(Type.Number({ description: "Maximum results. Default: 50" })),+ }),+ async execute(_toolCallId: string, params: Record<string, unknown>) {+ if (isBypassedSession(ctx)) {+ return makeBypassedToolResult("openviking_tool_result_list");+ }+ const session = resolvePluginSessionRouting(ctx);+ if (!session.ovSessionId) {+ return {+ content: [{ type: "text", text: "Error: no active session." }],+ details: { error: "no_session" },+ };+ }++ const toolName =+ typeof params.tool_name === "string" && params.tool_name.trim()+ ? params.tool_name.trim()+ : typeof params.toolName === "string" && params.toolName.trim()+ ? params.toolName.trim()+ : undefined;+ const limit = getPositiveInteger(params.limit, 50);++ try {+ const client = await getClient();+ const result = await client.listToolResults(+ session.ovSessionId,+ { toolName, limit },+ session.agentId,+ );+ const items = result.tool_results ?? [];+ const text = items.length+ ? [+ `Found ${items.length} externalized tool result(s) in current session:`,+ "",+ ...items.map((item, index) => {+ const ref = typeof item.storage_uri === "string" ? item.storage_uri : "(missing ref)";+ const name = typeof item.tool_name === "string" ? item.tool_name : "tool";+ const chars = typeof item.original_chars === "number" ? item.original_chars : "unknown";+ const created = typeof item.created_at === "string" ? ` created_at=${item.created_at}` : "";+ return `${index + 1}. ${name} original_chars=${chars}${created}\nref: ${ref}`;+ }),+ ].join("\n")+ : toolName+ ? `No externalized tool results found for tool "${toolName}" in current session.`+ : "No externalized tool results found in current session.";+ return {+ content: [{ type: "text", text }],+ details: {+ action: "listed",+ session_id: session.ovSessionId,+ tool_name: toolName ?? null,+ count: items.length,+ tool_results: items,+ },+ };+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ logger?.warn?.(`openviking: openviking_tool_result_list failed: ${msg}`);+ return {+ content: [{ type: "text", text: `Failed to list tool results: ${msg}` }],+ details: { error: msg, session_id: session.ovSessionId, tool_name: toolName ?? null },+ };+ }+ },+ }),+ { name: "openviking_tool_result_list" },+ );+}diff --git a/examples/openclaw-plugin/plugin/recall-trace-routes.ts b/examples/openclaw-plugin/plugin/recall-trace-routes.tsnew file mode 100644index 000000000..1da9910fe--- /dev/null+++ b/examples/openclaw-plugin/plugin/recall-trace-routes.ts@@ -0,0 +1,133 @@+export type RecallTraceRouteRequest = {+ query?: Record<string, unknown>;+ params?: Record<string, unknown>;+ url?: string;+};++export type RecallTraceRouteResult = {+ status?: number;+ body?: unknown;+};++export type RecallTraceRouteHandler = (request?: RecallTraceRouteRequest) => Promise<RecallTraceRouteResult | unknown>;++export type RecallTraceRoute = {+ method: "GET";+ path: string;+ handler: RecallTraceRouteHandler;+};++export type RecallTraceRouteAdapter = {+ registerRoute?: (route: RecallTraceRoute) => void;+ registerHttpRoute?: (route: {+ path: string;+ auth: "plugin";+ match: "exact" | "prefix";+ handler: (req: { method?: string; url?: string }, res: {+ statusCode?: number;+ setHeader?: (name: string, value: string) => void;+ end?: (body?: string) => void;+ }) => Promise<boolean>;+ }) => void;+};++export type RecallTraceRouteHandlers = {+ handleRecallTraces: RecallTraceRouteHandler;+ handleUriDetail: RecallTraceRouteHandler;+ handleLatestOvSearchList: RecallTraceRouteHandler;+};++export const RECALL_TRACE_ROUTE_PATHS = [+ "/api/openviking/recall-traces",+ "/api/openviking/uri-detail",+ "/api/openviking/recall-traces/latest-ov-search-list",+ "/api/openviking/recall-traces/:traceId",+] as const;++export function registerRecallTraceRoutes(+ ctx: unknown,+ handlers: RecallTraceRouteHandlers,+): boolean {+ const routeAdapter = ctx as RecallTraceRouteAdapter | undefined;+ const canRegisterLegacyRoute = typeof routeAdapter?.registerRoute === "function";+ const canRegisterHttpRoute = typeof routeAdapter?.registerHttpRoute === "function";+ if (!canRegisterLegacyRoute && !canRegisterHttpRoute) {+ return false;+ }++ const handle = handlers.handleRecallTraces;+ const routes: RecallTraceRoute[] = [+ { method: "GET", path: RECALL_TRACE_ROUTE_PATHS[0], handler: handle },+ { method: "GET", path: RECALL_TRACE_ROUTE_PATHS[1], handler: handlers.handleUriDetail },+ { method: "GET", path: RECALL_TRACE_ROUTE_PATHS[2], handler: handlers.handleLatestOvSearchList },+ {+ method: "GET",+ path: RECALL_TRACE_ROUTE_PATHS[3],+ handler: (request?: RecallTraceRouteRequest) => handle({+ ...request,+ query: {+ ...(request?.query ?? {}),+ traceId: typeof request?.params?.traceId === "string" ? request.params.traceId : undefined,+ },+ }),+ },+ ];++ for (const route of routes) {+ routeAdapter?.registerRoute?.(route);+ }++ if (canRegisterHttpRoute) {+ const sendJson = (+ res: { statusCode?: number; setHeader?: (name: string, value: string) => void; end?: (body?: string) => void },+ status: number,+ body: unknown,+ ) => {+ res.statusCode = status;+ res.setHeader?.("Cache-Control", "no-store");+ res.setHeader?.("Content-Type", "application/json; charset=utf-8");+ res.end?.(JSON.stringify(body));+ };+ const makeHttpHandler = (+ route: RecallTraceRoute,+ getParams?: (url: string) => Record<string, unknown>,+ ) => async (+ req: { method?: string; url?: string },+ res: { statusCode?: number; setHeader?: (name: string, value: string) => void; end?: (body?: string) => void },+ ) => {+ if ((req.method ?? "GET").toUpperCase() !== route.method) {+ sendJson(res, 405, { ok: false, error: { code: "method_not_allowed", message: `${route.method} is required` } });+ return true;+ }+ const url = req.url ?? route.path;+ const result = await route.handler({ url, params: getParams?.(url) });+ const response = result as { status?: number; body?: unknown };+ sendJson(res, typeof response.status === "number" ? response.status : 200, response.body ?? response);+ return true;+ };+ for (const route of routes) {+ if (route.path === RECALL_TRACE_ROUTE_PATHS[3]) {+ const prefix = "/api/openviking/recall-traces/";+ routeAdapter?.registerHttpRoute?.({+ path: "/api/openviking/recall-traces",+ auth: "plugin",+ match: "prefix",+ handler: makeHttpHandler(route, (url) => {+ const pathname = new URL(url, "http://openclaw.local").pathname;+ const traceId = pathname.startsWith(prefix) ? decodeURIComponent(pathname.slice(prefix.length)) : "";+ return traceId ? { traceId } : {};+ }),+ });+ } else {+ routeAdapter?.registerHttpRoute?.({+ path: route.path,+ auth: "plugin",+ match: "exact",+ handler: makeHttpHandler(route),+ });+ }+ }+ }++ return true;+}diff --git a/examples/openclaw-plugin/plugin/tool-registration.ts b/examples/openclaw-plugin/plugin/tool-registration.tsnew file mode 100644index 000000000..192608674--- /dev/null+++ b/examples/openclaw-plugin/plugin/tool-registration.ts@@ -0,0 +1,51 @@+export type OpenVikingToolRegistrationApi = {+ registerTool: (toolOrFactory: unknown, opts: { name: string }) => void;+};++export type OpenVikingToolRegistrationLogger = {+ debug?: (message: string) => void;+};++export type OpenVikingToolRegistrarOptions = {+ api: OpenVikingToolRegistrationApi;+ enabledToolNames: ReadonlySet<string>;+ logger?: OpenVikingToolRegistrationLogger;+};++export type OpenVikingToolRegistrationRuntimeConfig = {+ enabledTools: string[] | string;+};++export function createOpenVikingToolRegistrar({+ api,+ enabledToolNames,+ logger,+}: OpenVikingToolRegistrarOptions) {+ return (toolOrFactory: unknown, opts: { name: string }): void => {+ if (!enabledToolNames.has(opts.name)) {+ logger?.debug?.(`openviking: tool ${opts.name} disabled by config`);+ return;+ }+ api.registerTool(toolOrFactory, opts);+ };+}++export function createOpenVikingToolRegistrationRuntime<TConfig extends OpenVikingToolRegistrationRuntimeConfig>(options: {+ api: OpenVikingToolRegistrationApi;+ cfg: TConfig;+ logger?: OpenVikingToolRegistrationLogger;+}) {+ const enabledTools = Array.isArray(options.cfg.enabledTools)+ ? options.cfg.enabledTools+ : [options.cfg.enabledTools];+ const enabledToolNames = new Set<string>(enabledTools);+ const registerOpenVikingTool = createOpenVikingToolRegistrar({+ api: options.api,+ enabledToolNames,+ logger: options.logger,+ });++ return {+ registerOpenVikingTool,+ };+}diff --git a/examples/openclaw-plugin/process-manager.ts b/examples/openclaw-plugin/process-manager.tsindex 3ccecd8ab..2bbd56d8d 100644--- a/examples/openclaw-plugin/process-manager.ts+++ b/examples/openclaw-plugin/process-manager.ts@@ -18,10 +18,11 @@ 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(timeoutMs);+ await client.healthCheck(timeoutMs, agentId);return true;} catch {return false;@@ -30,8 +31,9 @@ export async function quickHealthCheck(export async function quickRecallPrecheck(client: OpenVikingClient,+ agentId?: string,): Promise<{ ok: true } | { ok: false; reason: string }> {- const healthOk = await quickHealthCheck(client, 500);+ const healthOk = await quickHealthCheck(client, agentId, 500);if (healthOk) {return { ok: true };}diff --git a/examples/openclaw-plugin/query-config.ts b/examples/openclaw-plugin/query-config.tsindex f7b43a788..031d6f6ee 100644--- a/examples/openclaw-plugin/query-config.ts+++ b/examples/openclaw-plugin/query-config.ts@@ -2,7 +2,7 @@ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";import { dirname } from "node:path";import type { MemoryOpenVikingConfig } from "./config.js";-import { normalizeResourceTypes, type RecallResourceType } from "./recall-trace.js";+import { normalizeRecallResourceTypes, type RecallResourceType } from "./registries/recall-resource-types.js";export type RuntimeQueryParams = {recallLimit?: number;@@ -133,7 +133,7 @@ export function normalizeRuntimeQueryParams(value: RuntimeQueryParamsPatch): { pif (ovSearchLimit !== undefined) params.ovSearchLimit = ovSearchLimit;if (typeof value.recallPreferAbstract === "boolean") params.recallPreferAbstract = value.recallPreferAbstract;- if (value.resourceTypes !== undefined) params.resourceTypes = normalizeResourceTypes(value.resourceTypes);+ if (value.resourceTypes !== undefined) params.resourceTypes = normalizeRecallResourceTypes(value.resourceTypes);if (typeof value.targetUri === "string" && value.targetUri.trim()) {const targetUri = value.targetUri.trim();if (!targetUri.startsWith("viking://")) throw new Error("targetUri must start with viking://");@@ -271,7 +271,7 @@ export class RuntimeQueryConfigStore {scoreThreshold: cfg.recallScoreThreshold,maxInjectedChars: cfg.recallMaxInjectedChars,recallPreferAbstract: cfg.recallPreferAbstract,- resourceTypes: normalizeResourceTypes(cfg.recallTargetTypes),+ resourceTypes: normalizeRecallResourceTypes(cfg.recallTargetTypes),ovSearchLimit: DEFAULT_OV_SEARCH_LIMIT,rankingWeights: { ...DEFAULT_RANKING_WEIGHTS },resourceTypeWeights: {},@@ -344,7 +344,7 @@ export class RuntimeQueryConfigStore {effective.sources.recallPreferAbstract = source;}if (params.resourceTypes !== undefined) {- effective.resourceTypes = Array.isArray(params.resourceTypes) ? [...params.resourceTypes] : normalizeResourceTypes(params.resourceTypes);+ effective.resourceTypes = Array.isArray(params.resourceTypes) ? [...params.resourceTypes] : normalizeRecallResourceTypes(params.resourceTypes);effective.sources.resourceTypes = source;}if (params.targetUri !== undefined) {diff --git a/examples/openclaw-plugin/registries/openviking-tools.ts b/examples/openclaw-plugin/registries/openviking-tools.tsnew file mode 100644index 000000000..6bf1bc607--- /dev/null+++ b/examples/openclaw-plugin/registries/openviking-tools.ts@@ -0,0 +1,84 @@+export type OpenVikingToolGroup =+ | "memory"+ | "resource_query"+ | "import"+ | "recall_trace"+ | "archive"+ | "tool_result";++export type OpenVikingToolName =+ | "add_resource"+ | "add_skill"+ | "ov_search"+ | "ov_read"+ | "ov_multi_read"+ | "ov_list"+ | "memory_recall"+ | "ov_recall_trace"+ | "memory_store"+ | "memory_forget"+ | "ov_archive_search"+ | "ov_archive_expand"+ | "openviking_tool_result_read"+ | "openviking_tool_result_search"+ | "openviking_tool_result_list";++export type OpenVikingToolSpec = {+ name: OpenVikingToolName;+ group: OpenVikingToolGroup;+ defaultEnabled: boolean;+ requiresLegacyFlag?: "enableAddResourceTool";+};++export const OPENVIKING_ADD_RESOURCE_TOOL_NAME = "add_resource" as const;++export const OPENVIKING_TOOL_SPECS = [+ {+ name: OPENVIKING_ADD_RESOURCE_TOOL_NAME,+ group: "import",+ defaultEnabled: false,+ requiresLegacyFlag: "enableAddResourceTool",+ },+ { name: "add_skill", group: "import", defaultEnabled: true },+ { name: "ov_search", group: "resource_query", defaultEnabled: true },+ { name: "ov_read", group: "resource_query", defaultEnabled: true },+ { name: "ov_multi_read", group: "resource_query", defaultEnabled: true },+ { name: "ov_list", group: "resource_query", defaultEnabled: true },+ { name: "memory_recall", group: "memory", defaultEnabled: true },+ { name: "ov_recall_trace", group: "recall_trace", defaultEnabled: true },+ { name: "memory_store", group: "memory", defaultEnabled: true },+ { name: "memory_forget", group: "memory", defaultEnabled: true },+ { name: "ov_archive_search", group: "archive", defaultEnabled: true },+ { name: "ov_archive_expand", group: "archive", defaultEnabled: true },+ { name: "openviking_tool_result_read", group: "tool_result", defaultEnabled: true },+ { name: "openviking_tool_result_search", group: "tool_result", defaultEnabled: true },+ { name: "openviking_tool_result_list", group: "tool_result", defaultEnabled: true },+] as const satisfies readonly OpenVikingToolSpec[];++export const OPENVIKING_ALL_TOOL_NAMES = OPENVIKING_TOOL_SPECS.map((spec) => spec.name) as OpenVikingToolName[];++export const OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES = OPENVIKING_TOOL_SPECS+ .filter((spec) => spec.defaultEnabled)+ .map((spec) => spec.name) as OpenVikingToolName[];++const OPENVIKING_TOOL_GROUP_ORDER: readonly OpenVikingToolGroup[] = [+ "memory",+ "resource_query",+ "import",+ "recall_trace",+ "archive",+ "tool_result",+];++export const OPENVIKING_TOOL_GROUPS: Record<string, readonly OpenVikingToolName[]> = {+ all: OPENVIKING_ALL_TOOL_NAMES,+ default: OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES,+ ...Object.fromEntries(+ OPENVIKING_TOOL_GROUP_ORDER.map((group) => [+ group,+ OPENVIKING_TOOL_SPECS+ .filter((spec) => spec.group === group)+ .map((spec) => spec.name),+ ]),+ ),+};diff --git a/examples/openclaw-plugin/registries/recall-resource-types.ts b/examples/openclaw-plugin/registries/recall-resource-types.tsnew file mode 100644index 000000000..1ab794837--- /dev/null+++ b/examples/openclaw-plugin/registries/recall-resource-types.ts@@ -0,0 +1,74 @@+export const ALLOWED_RECALL_RESOURCE_TYPES = ["resource", "user", "agent"] as const;+export type RecallResourceType = typeof ALLOWED_RECALL_RESOURCE_TYPES[number];+export const DEFAULT_RECALL_RESOURCE_TYPES: readonly RecallResourceType[] = ["user", "agent"];++export type RecallSearchPlan = {+ resourceTypes: RecallResourceType[];+ searches: Array<{ resourceType: RecallResourceType; contextType: "memory" | "resource"; targetUri?: string }>;+ skipped: Array<{ resourceType: RecallResourceType; reason: "missing_session" }>;+};++function toResourceTypeEntries(value: unknown): string[] {+ if (Array.isArray(value)) {+ return value+ .filter((entry): entry is string => typeof entry === "string")+ .map((entry) => entry.trim())+ .filter(Boolean);+ }+ if (typeof value === "string") {+ return value+ .split(/[,\n]/)+ .map((entry) => entry.trim())+ .filter(Boolean);+ }+ return [];+}++export function normalizeRecallResourceTypes(value: unknown): RecallResourceType[] {+ const entries = toResourceTypeEntries(value);+ if (entries.length === 0) {+ return [...DEFAULT_RECALL_RESOURCE_TYPES];+ }++ const seen = new Set<RecallResourceType>();+ const normalized: RecallResourceType[] = [];+ const invalid: string[] = [];+ for (const entry of entries) {+ if ((ALLOWED_RECALL_RESOURCE_TYPES as readonly string[]).includes(entry)) {+ const typed = entry as RecallResourceType;+ if (!seen.has(typed)) {+ seen.add(typed);+ normalized.push(typed);+ }+ } else {+ invalid.push(entry);+ }+ }++ if (invalid.length > 0) {+ throw new Error(`invalid resourceTypes: ${invalid.join(", ")}`);+ }++ return normalized.length > 0 ? normalized : [...DEFAULT_RECALL_RESOURCE_TYPES];+}++export function resolveRecallSearchPlan(+ resourceTypes: unknown,+ _ctx: { ovSessionId?: string; agentId?: string },+): RecallSearchPlan {+ const normalized = normalizeRecallResourceTypes(resourceTypes);+ const searches: RecallSearchPlan["searches"] = [];+ const skipped: RecallSearchPlan["skipped"] = [];+ let addedMemorySearch = false;++ for (const resourceType of normalized) {+ if (resourceType === "resource") {+ searches.push({ resourceType, contextType: "resource" });+ } else if ((resourceType === "user" || resourceType === "agent") && !addedMemorySearch) {+ searches.push({ resourceType: "user", contextType: "memory" });+ addedMemorySearch = true;+ }+ }++ return { resourceTypes: normalized, searches, skipped };+}diff --git a/examples/openclaw-plugin/routing/identity-routing.ts b/examples/openclaw-plugin/routing/identity-routing.tsnew file mode 100644index 000000000..e9828e59a--- /dev/null+++ b/examples/openclaw-plugin/routing/identity-routing.ts@@ -0,0 +1,210 @@+import { createHash } from "node:crypto";++const DEFAULT_OPENCLAW_AGENT_ID = "main";++/** OpenClaw session UUID (path-safe on Windows). */+const OPENVIKING_OV_SESSION_UUID =+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++const WINDOWS_BAD_SESSION_SEGMENT = /[:<>"\\/|?\u0000-\u001f]/;++export type SessionAgentLookup = {+ agentId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+};++export type SessionAgentResolveBranch =+ | "session_resolved"+ | "config_only_fallback"+ | "default_no_session";++export type SessionAgentResolveResult = {+ resolved: string;+ resolvedBeforeSanitize: string;+ branch: SessionAgentResolveBranch;+ mappedResolvedAgentId: string | null;+ aliases: string[];+ fromExplicitBinding: boolean;+};++/**+ * Map OpenClaw session identity to an OpenViking session_id that is safe as a single+ * AGFS path segment on Windows (no `:` etc.). Prefer UUID sessionId when present;+ * otherwise derive a stable sha256 from sessionKey.+ */+export function openClawSessionToOvStorageId(+ sessionId: string | undefined,+ sessionKey: string | undefined,+): string {+ const sid = typeof sessionId === "string" ? sessionId.trim() : "";+ const key = typeof sessionKey === "string" ? sessionKey.trim() : "";++ if (sid && OPENVIKING_OV_SESSION_UUID.test(sid)) {+ return sid.toLowerCase();+ }+ if (key) {+ return createHash("sha256").update(key, "utf8").digest("hex");+ }+ if (sid) {+ if (WINDOWS_BAD_SESSION_SEGMENT.test(sid)) {+ return createHash("sha256").update(`openclaw-session:${sid}`, "utf8").digest("hex");+ }+ return sid;+ }+ throw new Error("openviking: need sessionId or sessionKey for OV session path");+}++/** Normalize a hook/tool session ref (uuid, sessionKey, or already-safe id) for OV storage. */+export function openClawSessionRefToOvStorageId(ref: string): string {+ const t = ref.trim();+ if (!t) {+ throw new Error("openviking: empty session ref");+ }+ if (OPENVIKING_OV_SESSION_UUID.test(t)) {+ return t.toLowerCase();+ }+ if (WINDOWS_BAD_SESSION_SEGMENT.test(t)) {+ return createHash("sha256").update(t, "utf8").digest("hex");+ }+ return t;+}++/**+ * OpenViking peer identifiers allow only [a-zA-Z0-9_-].+ * OpenClaw ids may contain ":"; never send raw colons in X-OpenViking-Actor-Peer.+ */+export function sanitizeOpenVikingAgentIdHeader(raw: string): string {+ const trimmed = raw.trim();+ if (!trimmed) {+ return "default";+ }+ const normalized = trimmed+ .replace(/[^a-zA-Z0-9_-]/g, "_")+ .replace(/_+/g, "_")+ .replace(/^_|_$/g, "");+ return normalized.length > 0 ? normalized : "ov_agent";+}++function extractAgentIdFromSessionKey(sessionKey?: string): string | undefined {+ const raw = typeof sessionKey === "string" ? sessionKey.trim() : "";+ if (!raw) {+ return undefined;+ }++ const match = raw.match(/^agent:([^:]+):/);+ const agentId = match?.[1]?.trim();+ return agentId || undefined;+}++function collectSessionAgentAliases(+ sessionId?: string,+ sessionKey?: string,+ ovSessionId?: string,+): string[] {+ const aliases = new Set<string>();+ const sid = typeof sessionId === "string" ? sessionId.trim() : "";+ const sk = typeof sessionKey === "string" ? sessionKey.trim() : "";+ const ovSid = typeof ovSessionId === "string" ? ovSessionId.trim() : "";++ if (sid) {+ aliases.add(sid);+ }+ if (sk) {+ aliases.add(sk);+ }+ if (ovSid) {+ aliases.add(ovSid);+ }++ if (!ovSid && (sid || sk)) {+ try {+ aliases.add(+ openClawSessionToOvStorageId(+ sid || undefined,+ sk || undefined,+ ),+ );+ } catch {+ /* need a resolvable OpenClaw session identity */+ }+ }++ return [...aliases];+}++export function createSessionAgentResolver(configAgentId: string) {+ const configAgentPrefix = configAgentId.trim() === "default" ? "" : configAgentId.trim();+ const sessionAgentIds = new Map<string, string>();++ const remember = (ctx: SessionAgentLookup): void => {+ const sessionScopedAgentId =+ extractAgentIdFromSessionKey(ctx.sessionKey) ||+ extractAgentIdFromSessionKey(ctx.sessionId);+ const rawAgentId =+ (typeof ctx.agentId === "string" ? ctx.agentId.trim() : "") ||+ sessionScopedAgentId ||+ "";+ if (!rawAgentId) {+ return;+ }++ const prefix = configAgentPrefix;+ const resolvedBeforeSanitize = prefix ? `${prefix}_${rawAgentId}` : rawAgentId;+ const resolved = sanitizeOpenVikingAgentIdHeader(resolvedBeforeSanitize);+ for (const alias of collectSessionAgentAliases(ctx.sessionId, ctx.sessionKey, ctx.ovSessionId)) {+ sessionAgentIds.set(alias, resolved);+ }+ };++ const resolve = (+ sessionId?: string,+ sessionKey?: string,+ ovSessionId?: string,+ ): SessionAgentResolveResult => {+ const aliases = collectSessionAgentAliases(sessionId, sessionKey, ovSessionId);+ const mappedAlias = aliases.find((alias) => sessionAgentIds.has(alias));+ const mappedResolvedAgentId = mappedAlias ? sessionAgentIds.get(mappedAlias) : undefined;+ const sessionScopedAgentId =+ extractAgentIdFromSessionKey(sessionKey) ||+ extractAgentIdFromSessionKey(sessionId);++ let resolvedBeforeSanitize: string;+ let resolved: string;+ let branch: SessionAgentResolveBranch;+ const prefix = configAgentPrefix;++ if (mappedResolvedAgentId) {+ resolvedBeforeSanitize = mappedResolvedAgentId;+ resolved = mappedResolvedAgentId;+ branch = "session_resolved";+ } else if (sessionScopedAgentId) {+ resolvedBeforeSanitize = prefix ? `${prefix}_${sessionScopedAgentId}` : sessionScopedAgentId;+ resolved = sanitizeOpenVikingAgentIdHeader(resolvedBeforeSanitize);+ branch = "session_resolved";+ } else if (!prefix) {+ resolvedBeforeSanitize = DEFAULT_OPENCLAW_AGENT_ID;+ resolved = DEFAULT_OPENCLAW_AGENT_ID;+ branch = "default_no_session";+ } else {+ resolvedBeforeSanitize = `${prefix}_${DEFAULT_OPENCLAW_AGENT_ID}`;+ resolved = sanitizeOpenVikingAgentIdHeader(resolvedBeforeSanitize);+ branch = "config_only_fallback";+ }++ return {+ resolved,+ resolvedBeforeSanitize,+ branch,+ mappedResolvedAgentId: mappedResolvedAgentId ?? null,+ aliases,+ fromExplicitBinding: !!(mappedResolvedAgentId || sessionScopedAgentId),+ };+ };++ return {+ remember,+ resolve,+ };+}diff --git a/examples/openclaw-plugin/routing/memory-uri.ts b/examples/openclaw-plugin/routing/memory-uri.tsnew file mode 100644index 000000000..4e9c2e783--- /dev/null+++ b/examples/openclaw-plugin/routing/memory-uri.ts@@ -0,0 +1,8 @@+const MEMORY_URI_PATTERNS = [+ /^viking:\/\/user\/(?:[^/]+(?:\/agent\/[^/]+)?\/)?memories(?:\/|$)/,+ /^viking:\/\/agent\/(?:[^/]+(?:\/user\/[^/]+)?\/)?memories(?:\/|$)/,+];++export function isMemoryUri(uri: string): boolean {+ return MEMORY_URI_PATTERNS.some((pattern) => pattern.test(uri));+}diff --git a/examples/openclaw-plugin/services/context-lifecycle-service.ts b/examples/openclaw-plugin/services/context-lifecycle-service.tsnew file mode 100644index 000000000..7a3956d5c--- /dev/null+++ b/examples/openclaw-plugin/services/context-lifecycle-service.ts@@ -0,0 +1,1209 @@+// Canonical ContextEngine lifecycle service: assemble / afterTurn / compact / commit orchestration.+import { DEFAULT_PHASE2_POLL_TIMEOUT_MS, type OpenVikingClient, type OVMessage } from "../client.js";+import type { EffectiveQueryConfig } from "../query-config.js";+import { buildAutoRecallContext, prepareRecallQuery } from "../auto-recall.js";+import { toJsonLog } from "../memory-ranking.js";+import { openClawSessionToOvStorageId } from "../routing/identity-routing.js";+import { extractNewTurnMessages } from "../text-utils.js";+import { estimateAgentMessageTokens, estimateTextTokens } from "../token-estimator.js";+import {+ convertToAgentMessages,+ mergeConsecutiveAssistants,+ sanitizeAgentMessagesForProvider,+ toRoleId,+ type AgentMessage,+} from "./context-message-adapter.js";++type ExtractedTurnMessage = ReturnType<typeof extractNewTurnMessages>["messages"][number];++export type ContextEngineLifecycleLogger = {+ info: (msg: string) => void;+ warn?: (msg: string) => void;+};++export type CommitOpenVikingSessionParams = {+ sessionId: string;+ sessionKey?: string;+ getClient: () => Promise<Pick<OpenVikingClient, "commitSession">>;+ logger: ContextEngineLifecycleLogger;+ resolveAgentId: (sessionId: string, sessionKey?: string, ovSessionId?: string) => string;+ rememberSessionAgentId?: (ctx: {+ agentId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ }) => void;+ isBypassedSession: (params: { sessionId?: string; sessionKey?: string }) => boolean;+};++export type CompactOpenVikingSessionResult = {+ ok: boolean;+ compacted: boolean;+ reason?: string;+ result?: {+ summary?: string;+ firstKeptEntryId?: string;+ tokensBefore: number;+ tokensAfter?: number;+ details?: unknown;+ };+};++export type AssembleOpenVikingSessionResult = {+ messages: AgentMessage[];+ estimatedTokens: number;+ systemPromptAddition?: string;+};++type AssembleBuiltContext = {+ sanitized: AgentMessage[];+ archive: { messages: AgentMessage[]; tokens: number };+ session: { messages: AgentMessage[]; tokens: number };+ budgets: { archiveMemory: number; sessionContext: number; reserved: number };+ instruction: { text: string; tokens: number };+};++export type AssembleOpenVikingSessionParams = {+ sessionId: string;+ sessionKey?: string;+ messages: AgentMessage[];+ tokenBudget: number;+ runtimeContext?: Record<string, unknown>;+ isMainAssemble: boolean;+ cfg: any;+ getClient: () => Promise<OpenVikingClient>;+ logger: ContextEngineLifecycleLogger;+ resolveAgentId: (sessionId: string, sessionKey?: string, ovSessionId?: string) => string;+ rememberSessionAgentId?: (ctx: {+ agentId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ }) => void;+ isBypassedSession: (params: { sessionId?: string; sessionKey?: string }) => boolean;+ queryConfigStore?: {+ getEffective(params: {+ agentId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ }): Promise<EffectiveQueryConfig>;+ };+ traceRecorder?: unknown;+ diag: (stage: string, sessionId: string, data: Record<string, unknown>) => void;+ roughEstimate: (messages: AgentMessage[]) => number;+ messageDigest: (messages: AgentMessage[]) => Array<{role: string; content: string; tokens: number; truncated: boolean}>;+ extractAgentMessageText: (message: AgentMessage | undefined) => string;+ hasAutoRecallBlock: (message: AgentMessage | undefined) => boolean;+ prependRecallToLatestUserMessage: (messages: AgentMessage[], recallBlock: string) => AgentMessage[];+};++type CompactClient = Pick<OpenVikingClient, "commitSession" | "getSessionContext">;++export type CompactOpenVikingSessionParams = {+ sessionId: string;+ sessionKey?: string;+ tokenBudget: number;+ currentTokenCount?: unknown;+ force?: boolean;+ compactionTarget?: "budget" | "threshold";+ customInstructions?: string;+ getClient: () => Promise<CompactClient>;+ logger: ContextEngineLifecycleLogger;+ resolveAgentId: (sessionId: string, sessionKey?: string, ovSessionId?: string) => string;+ isBypassedSession: (params: { sessionId?: string; sessionKey?: string }) => boolean;+ diag: (stage: string, sessionId: string, data: Record<string, unknown>) => void;+};++type AfterTurnClient = Pick<OpenVikingClient, "addSessionMessage" | "getSession" | "commitSession" | "getTask">;++export type AfterTurnOpenVikingSessionParams = {+ sessionId: string;+ sessionKey?: string;+ messages?: AgentMessage[];+ prePromptMessageCount?: number;+ isHeartbeat?: boolean;+ runtimeContext?: Record<string, unknown>;+ cfg: {+ autoCapture: boolean;+ commitTokenThreshold: number;+ commitKeepRecentCount: number;+ logFindRequests: boolean;+ };+ getClient: () => Promise<AfterTurnClient>;+ logger: ContextEngineLifecycleLogger;+ resolveAgentId: (sessionId: string, sessionKey?: string, ovSessionId?: string) => string;+ rememberSessionAgentId?: (ctx: {+ agentId?: string;+ sessionId?: string;+ sessionKey?: string;+ ovSessionId?: string;+ }) => void;+ isBypassedSession: (params: { sessionId?: string; sessionKey?: string }) => boolean;+ diag: (stage: string, sessionId: string, data: Record<string, unknown>) => void;+};++export function totalExtractedMemories(memories?: Record<string, number>): number {+ if (!memories || typeof memories !== "object") {+ return 0;+ }+ return Object.values(memories).reduce((sum, count) => sum + (count ?? 0), 0);+}++type ContextBudgets = {+ archiveMemory: number;+ sessionContext: number;+ reserved: number;+};++const BUDGET_UNLIMITED = -1;+const ARCHIVE_BUDGET_RATIO = 0.15;+const ARCHIVE_BUDGET_CAP = 8_000;+const RESERVED_MIN = 20_000;+const RESERVED_RATIO = 0.15;+const PHASE2_POLL_INTERVAL_MS = 800;+const PHASE2_POLL_MAX_MS = DEFAULT_PHASE2_POLL_TIMEOUT_MS;++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++/**+ * After wait=false commit, Phase2 runs on the server. Poll task until completed/failed/timeout+ * so logs show memories_extracted (otherwise it looks like "nothing was saved").+ */+async function pollPhase2ExtractionOutcome(+ client: AfterTurnClient,+ taskId: string,+ agentId: string,+ logger: ContextEngineLifecycleLogger,+ sessionLabel: string,+): Promise<void> {+ const deadline = Date.now() + PHASE2_POLL_MAX_MS;+ try {+ while (Date.now() < deadline) {+ await sleep(PHASE2_POLL_INTERVAL_MS);+ const task = await client.getTask(taskId, agentId).catch((e) => {+ logger.warn?.(`openviking: phase2 getTask failed task_id=${taskId}: ${String(e)}`);+ return null;+ });+ if (!task) {+ return;+ }+ const { status } = task;+ if (status === "completed") {+ logger.info(+ `openviking: phase2 completed task_id=${taskId} session=${sessionLabel} ` ++ `result=${toJsonLog(task.result ?? {})}`,+ );+ return;+ }+ if (status === "failed") {+ logger.warn?.(+ `openviking: phase2 failed task_id=${taskId} session=${sessionLabel} error=${task.error ?? "unknown"}`,+ );+ return;+ }+ }+ logger.warn?.(+ `openviking: phase2 poll timeout (${PHASE2_POLL_MAX_MS / 1000}s) task_id=${taskId} session=${sessionLabel} — ` ++ `check GET /api/v1/tasks/${taskId}`,+ );+ } catch (e) {+ logger.warn?.(`openviking: phase2 poll exception task_id=${taskId}: ${String(e)}`);+ }+}++function allocateContextBudget(totalBudget: number, instructionTokens = 0): ContextBudgets {+ const reserveFloor = totalBudget >= RESERVED_MIN * 2 ? RESERVED_MIN : 0;+ const reserved = Math.min(totalBudget, Math.max(totalBudget * RESERVED_RATIO, reserveFloor));+ const usableBudget = Math.max(totalBudget - reserved - instructionTokens, 0);+ const archiveMemory = Math.min(usableBudget * ARCHIVE_BUDGET_RATIO, ARCHIVE_BUDGET_CAP);+ const sessionContext = Math.max(usableBudget - archiveMemory, 0);+ return { archiveMemory, sessionContext, reserved };+}++function buildSystemPromptAddition(): string {+ return [+ "## Session Context Guide",+ "",+ "Your conversation history includes two layers:",+ "",+ "1. **[Session History Summary]** — A compressed summary of all prior turns",+ " in this session. It is organized into structured sections (Key Facts,",+ " Timeline, People, etc.). Use it for background and continuity.",+ " The summary is lossy: specific details (exact dates, numbers, names,",+ " small events) may have been compressed away.",+ "",+ "2. **Active messages** — The most recent uncompressed turns.",+ "",+ "**Rules:**",+ "- When active messages conflict with the Summary, trust active messages",+ " as the newer source of truth.",+ "- Do not fabricate details the Summary does not state explicitly.",+ "- **CRITICAL: Before answering 'no information' or 'not mentioned',",+ " you MUST carefully re-read EVERY section of the [Session History Summary].",+ " The answer may be expressed with different wording than the question.",+ " Look for synonyms, related facts, and indirect references.**",+ "- If the Summary mentions a topic but lacks the specific detail asked,",+ " use the `ov_archive_search` tool to grep the original archived messages",+ " for the exact detail. Try 2-3 different keywords extracted from the question.",+ "- Only conclude information is unavailable AFTER both checking the Summary",+ " thoroughly AND searching the archives with at least 2 keyword variations.",+ ].join("\n");+}++function buildInstructionPrompt(): { text: string; tokens: number } {+ const text = buildSystemPromptAddition();+ return { text, tokens: estimateTextTokens(text) };+}++function buildArchiveMemory(+ archiveOverview: string | undefined,+ _preAbstracts: Array<{ archive_id: string; abstract: string }>,+ _budget: number,+ roughEstimate: (messages: AgentMessage[]) => number,+): { messages: AgentMessage[]; tokens: number } {+ const messages: AgentMessage[] = [];++ if (archiveOverview) {+ messages.push({+ role: "user",+ content: `[Session History Summary]\n${archiveOverview}`,+ });+ }++ return { messages, tokens: roughEstimate(messages) };+}++function buildSessionContext(+ ovMessages: OVMessage[],+ budget: number,+ roughEstimate: (messages: AgentMessage[]) => number,+): { messages: AgentMessage[]; tokens: number } {+ const raw = ovMessages.flatMap((m) => convertToAgentMessages(m));+ const messages = mergeConsecutiveAssistants(raw);+ const tokens = roughEstimate(messages);+ if (budget === BUDGET_UNLIMITED || tokens <= budget) {+ return { messages, tokens };+ }+ const trimmed = [...messages];+ while (trimmed.length > 0 && roughEstimate(trimmed) > budget) {+ trimmed.shift();+ }+ return { messages: trimmed, tokens: roughEstimate(trimmed) };+}++function buildAssembledContext(+ overview: string | undefined,+ preAbstracts: Array<{ archive_id: string; abstract: string }>,+ ovMessages: OVMessage[],+ tokenBudget: number,+ ovSessionId: string,+ logger: ContextEngineLifecycleLogger,+ roughEstimate: (messages: AgentMessage[]) => number,+): AssembleBuiltContext {+ const hasArchives = Boolean(overview) || preAbstracts.length > 0;+ const instruction = hasArchives ? buildInstructionPrompt() : { text: "", tokens: 0 };++ // 4-layer context partitioning:+ // Instruction — system prompt guide (Archive Index / Session History usage)+ // Archive — session history summary + per-archive one-line abstracts+ // Session — active OV messages converted to AgentMessage format+ // Reserved — headroom for model output (not consumed here)+ const budgets = allocateContextBudget(tokenBudget, instruction.tokens);+ const archive = buildArchiveMemory(overview, preAbstracts, budgets.archiveMemory, roughEstimate);+ const sessionBudget = Math.max(+ tokenBudget - budgets.reserved - instruction.tokens - archive.tokens,+ 0,+ );+ const session = buildSessionContext(ovMessages, sessionBudget, roughEstimate);+ const assembled = [...archive.messages, ...session.messages];++ logger.info(+ `openviking: assemble entering session content for ${ovSessionId}: ` ++ JSON.stringify(assembled.map((m) => ({+ role: m.role,+ content: typeof m.content === "string" ? m.content.substring(0, 100) : "[complex]",+ })), null, 2),+ );++ const sanitized = sanitizeAgentMessagesForProvider(assembled);++ return { sanitized, archive, session, budgets, instruction };+}++export async function commitOpenVikingSession({+ sessionId,+ sessionKey,+ getClient,+ logger,+ resolveAgentId,+ rememberSessionAgentId,+ isBypassedSession,+}: CommitOpenVikingSessionParams): Promise<boolean> {+ const ovId = openClawSessionToOvStorageId(sessionId, sessionKey);+ if (isBypassedSession({ sessionId, sessionKey })) {+ logger.warn?.(+ `openviking: commit skipped because session is bypassed (sessionId=${sessionId}, sessionKey=${sessionKey ?? "none"})`,+ );+ return false;+ }+ try {+ const client = await getClient();+ rememberSessionAgentId?.({+ sessionId,+ 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);+ if (commitResult.status === "failed") {+ logger.warn?.(`openviking: commit Phase 2 failed for session=${sessionId}: ${commitResult.error ?? "unknown"}`);+ return false;+ }+ if (commitResult.status === "timeout") {+ logger.warn?.(`openviking: commit Phase 2 timed out for session=${sessionId}, task_id=${commitResult.task_id ?? "none"}`);+ return false;+ }+ logger.info(+ `openviking: committed OV session=${sessionId} ovId=${ovId}, archived=${commitResult.archived ?? false}, memories=${memCount}, task_id=${commitResult.task_id ?? "none"}, trace_id=${commitResult.trace_id ?? "none"}`,+ );+ return true;+ } catch (err) {+ logger.warn?.(`openviking: commit failed for session=${sessionId}: ${String(err)}`);+ return false;+ }+}++function assemblePassthrough(+ params: Pick<AssembleOpenVikingSessionParams, "diag"> & {+ ovSessionId: string;+ reason: string;+ liveMessages: AgentMessage[];+ originalTokens: number;+ extra?: Record<string, unknown>;+ },+): AssembleOpenVikingSessionResult {+ const { diag, ovSessionId, reason, liveMessages, originalTokens, extra } = params;+ diag("assemble_result", ovSessionId, {+ passthrough: true,+ reason,+ outputMessagesCount: liveMessages.length,+ inputTokenEstimate: originalTokens,+ estimatedTokens: originalTokens,+ tokensSaved: 0,+ savingPct: 0,+ ...extra,+ });+ return { messages: liveMessages, estimatedTokens: originalTokens };+}++export async function assembleOpenVikingSession({+ sessionId,+ sessionKey,+ messages,+ tokenBudget,+ runtimeContext,+ isMainAssemble,+ cfg,+ getClient,+ logger,+ resolveAgentId,+ rememberSessionAgentId,+ isBypassedSession,+ queryConfigStore,+ traceRecorder,+ diag,+ roughEstimate,+ messageDigest,+ extractAgentMessageText,+ hasAutoRecallBlock,+ prependRecallToLatestUserMessage,+}: AssembleOpenVikingSessionParams): Promise<AssembleOpenVikingSessionResult> {+ const ovSessionId = openClawSessionToOvStorageId(sessionId, sessionKey);+ const sender = extractRuntimeSenderId(runtimeContext);+ const latestMessage = messages.at(-1);+ const isTransformContextAssemble = !isMainAssemble;+ const originalTokens = roughEstimate(messages);++ rememberSessionAgentId?.({+ sessionId,+ sessionKey,+ agentId: extractRuntimeAgentId(runtimeContext),+ ovSessionId,+ });+ diag("assemble_entry", ovSessionId, {+ messagesCount: messages.length,+ inputTokenEstimate: originalTokens,+ tokenBudget,+ sessionKey: sessionKey ?? null,+ senderIdFound: sender.found,+ senderId: sender.senderId ?? null,+ messages: messageDigest(messages),+ });++ if (isBypassedSession({ sessionId, sessionKey })) {+ return assemblePassthrough({ diag, ovSessionId, reason: "session_bypassed", liveMessages: messages, originalTokens });+ }++ if (isTransformContextAssemble) {+ if (latestMessage?.role !== "user") {+ return assemblePassthrough({+ diag,+ ovSessionId,+ reason: "transform_context_non_user_tail",+ liveMessages: messages,+ originalTokens,+ extra: { latestRole: latestMessage?.role ?? null },+ });+ }+ if (!cfg.autoRecall) {+ return assemblePassthrough({ diag, ovSessionId, reason: "transform_context_auto_recall_disabled", liveMessages: messages, originalTokens });+ }+ if (hasAutoRecallBlock(latestMessage)) {+ return assemblePassthrough({ diag, ovSessionId, reason: "transform_context_recall_already_injected", liveMessages: messages, originalTokens });+ }++ const recallQuery = prepareRecallQuery(extractAgentMessageText(latestMessage));+ if (!recallQuery.query || recallQuery.query.length < 5) {+ return assemblePassthrough({ diag, ovSessionId, reason: "transform_context_empty_recall_query", liveMessages: messages, originalTokens });+ }+ if (recallQuery.truncated) {+ logger.info(+ `openviking: recall query truncated (` ++ `chars=${recallQuery.originalChars}->${recallQuery.finalChars})`,+ );+ }++ try {+ const client = await getClient();+ const routingRef = sessionId ?? sessionKey ?? ovSessionId;+ const agentId = resolveAgentId(routingRef, sessionKey, ovSessionId);+ const queryConfig = await queryConfigStore?.getEffective({+ agentId,+ sessionId,+ sessionKey,+ ovSessionId,+ });+ const recall = await buildAutoRecallContext({+ cfg,+ queryConfig,+ client,+ agentId,+ queryText: recallQuery.query,+ logger,+ verbose: (message) => logger.info(message),+ traceRecorder: traceRecorder as never,+ sessionId,+ sessionKey,+ ovSessionId,+ queryTruncated: recallQuery.truncated,+ rawUserTextPreview: recallQuery.query,+ });++ if (!recall.block) {+ return assemblePassthrough({+ diag,+ ovSessionId,+ reason: "transform_context_no_recall_hits",+ liveMessages: messages,+ originalTokens,+ extra: { memoryCount: recall.memoryCount },+ });+ }++ const withRecall = prependRecallToLatestUserMessage(messages, recall.block);+ const estimatedTokens = roughEstimate(withRecall);+ diag("assemble_result", ovSessionId, {+ passthrough: false,+ phase: "transform_context",+ outputMessagesCount: withRecall.length,+ inputTokenEstimate: originalTokens,+ estimatedTokens,+ autoRecallMemoryCount: recall.memoryCount,+ autoRecallTokens: recall.estimatedTokens,+ messages: messageDigest(withRecall),+ });+ return { messages: withRecall, estimatedTokens };+ } catch (err) {+ logger.warn?.(`openviking: auto-recall failed: ${String(err)}`);+ return assemblePassthrough({+ diag,+ ovSessionId,+ reason: "transform_context_recall_failed",+ liveMessages: messages,+ originalTokens,+ extra: { error: String(err) },+ });+ }+ }++ try {+ const client = await getClient();+ const routingRef = sessionId ?? sessionKey ?? ovSessionId;+ const agentId = resolveAgentId(routingRef, sessionKey, ovSessionId);+ const ctx = await client.getSessionContext(ovSessionId, tokenBudget, agentId);++ const preAbstracts = ctx?.pre_archive_abstracts ?? [];+ const hasArchives = !!ctx?.latest_archive_overview || preAbstracts.length > 0;+ const activeCount = ctx?.messages?.length ?? 0;++ if (!ctx || (!hasArchives && activeCount === 0)) {+ return assemblePassthrough({+ diag,+ ovSessionId,+ reason: "no_ov_data",+ liveMessages: messages,+ originalTokens,+ extra: { archiveCount: 0, activeCount: 0 },+ });+ }+ if (!hasArchives && ctx.messages.length < messages.length) {+ return assemblePassthrough({+ diag,+ ovSessionId,+ reason: "ov_msgs_fewer_than_input",+ liveMessages: messages,+ originalTokens,+ extra: { archiveCount: 0, activeCount },+ });+ }++ const { sanitized, archive, session, budgets, instruction } = buildAssembledContext(+ ctx.latest_archive_overview,+ preAbstracts,+ ctx.messages,+ tokenBudget,+ ovSessionId,+ logger,+ roughEstimate,+ );++ if (sanitized.length === 0 && messages.length > 0) {+ return assemblePassthrough({+ diag,+ ovSessionId,+ reason: "sanitized_empty",+ liveMessages: messages,+ originalTokens,+ extra: { archiveCount: preAbstracts.length, activeCount },+ });+ }++ const assembledTokens = roughEstimate(sanitized) + instruction.tokens;+ const tokensSaved = originalTokens - assembledTokens;+ const savingPct = originalTokens > 0 ? Math.round((tokensSaved / originalTokens) * 100) : 0;++ diag("assemble_result", ovSessionId, {+ passthrough: false,+ archiveCount: preAbstracts.length,+ activeCount,+ outputMessagesCount: sanitized.length,+ inputTokenEstimate: originalTokens,+ estimatedTokens: assembledTokens,+ tokensSaved,+ savingPct,+ archiveTokens: archive.tokens,+ archiveBudget: budgets.archiveMemory,+ sessionTokens: session.tokens,+ sessionBudget: budgets.sessionContext,+ reservedBudget: budgets.reserved,+ senderIdFound: sender.found,+ senderId: sender.senderId ?? null,+ messages: messageDigest(sanitized),+ });++ return {+ messages: sanitized,+ estimatedTokens: assembledTokens,+ ...(instruction.text ? { systemPromptAddition: instruction.text } : {}),+ };+ } catch (err) {+ logger.warn?.(+ `openviking: assemble failed for session=${ovSessionId}, ` ++ `tokenBudget=${tokenBudget}, agentId=${resolveAgentId(ovSessionId)}: ${String(err)}`,+ );+ diag("assemble_error", ovSessionId, {+ error: String(err),+ tokenBudget,+ agentId: resolveAgentId(ovSessionId),+ senderIdFound: sender.found,+ senderId: sender.senderId ?? null,+ });+ return { messages, estimatedTokens: roughEstimate(messages) };+ }+}++function normalizeTimestamp(value: unknown): string | undefined {+ if (typeof value === "number" && Number.isFinite(value)) {+ const timestampMs = Math.abs(value) < 100_000_000_000 ? value * 1000 : value;+ return new Date(timestampMs).toISOString();+ }+ return undefined;+}++function pickLatestCreatedAt(messages: AgentMessage[]): string | undefined {+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ const message = messages[i] as Record<string, unknown>;+ const role = typeof message.role === "string" ? message.role : "";+ if (!role || role === "system") {+ continue;+ }+ const normalized = normalizeTimestamp(message.timestamp);+ if (normalized) {+ return normalized;+ }+ }+ return undefined;+}++function extractRuntimeSenderId(runtimeContext: Record<string, unknown> | undefined): {+ found: boolean;+ senderId?: string;+} {+ if (runtimeContext) {+ const senderId = runtimeContext.senderId;+ if (typeof senderId === "string") {+ const trimmed = senderId.trim();+ if (trimmed) {+ return { found: true, senderId: trimmed };+ }+ }+ }+ return { found: false };+}++function extractRuntimeAgentId(runtimeContext: Record<string, unknown> | undefined): string | undefined {+ if (!runtimeContext) {+ return undefined;+ }+ const agentId = runtimeContext.agentId;+ return typeof agentId === "string" && agentId.trim() ? agentId.trim() : undefined;+}++function isToolOnlyMessage(msg: ExtractedTurnMessage): boolean {+ return msg.role === "user" && msg.parts.length > 0 && msg.parts.every((part) => part.type === "tool");+}++function coalesceConsecutiveToolMessages(messages: ExtractedTurnMessage[]): ExtractedTurnMessage[] {+ const result: ExtractedTurnMessage[] = [];+ let pendingTools: ExtractedTurnMessage | undefined;++ const flush = () => {+ if (pendingTools) {+ result.push(pendingTools);+ pendingTools = undefined;+ }+ };++ for (const msg of messages) {+ if (isToolOnlyMessage(msg)) {+ if (!pendingTools) {+ pendingTools = { role: "user", parts: [] };+ }+ pendingTools.parts.push(...msg.parts);+ continue;+ }+ flush();+ result.push(msg);+ }+ flush();+ return result;+}++function messageDigest(messages: AgentMessage[], maxCharsPerMsg = 2000): Array<{role: string; content: string; tokens: number; truncated: boolean}> {+ return messages.map((msg) => {+ const m = msg as Record<string, unknown>;+ const role = String(m.role ?? "unknown");+ const raw = m.content;+ let text: string;+ if (typeof raw === "string") {+ text = raw;+ } else if (Array.isArray(raw)) {+ text = (raw as Record<string, unknown>[])+ .map((b) => {+ if (b.type === "text") return String(b.text ?? "");+ if (b.type === "toolCall") return `[toolCall: ${String(b.name)}(${JSON.stringify(b.arguments ?? {}).slice(0, 200)})]`;+ if (b.type === "toolResult") return `[toolResult: ${JSON.stringify(b.content ?? "").slice(0, 200)}]`;+ return `[${String(b.type)}]`;+ })+ .join("\n");+ } else {+ text = JSON.stringify(raw) ?? "";+ }+ const truncated = text.length > maxCharsPerMsg;+ return {+ role,+ content: truncated ? text.slice(0, maxCharsPerMsg) + "..." : text,+ tokens: estimateAgentMessageTokens(msg),+ truncated,+ };+ });+}++export async function afterTurnOpenVikingSession({+ sessionId,+ sessionKey,+ messages: rawMessages,+ prePromptMessageCount,+ isHeartbeat,+ runtimeContext,+ cfg,+ getClient,+ logger,+ resolveAgentId,+ rememberSessionAgentId,+ isBypassedSession,+ diag,+}: AfterTurnOpenVikingSessionParams): Promise<void> {+ if (!cfg.autoCapture) {+ return;+ }++ if (isHeartbeat) {+ return;+ }++ try {+ const sender = extractRuntimeSenderId(runtimeContext);+ const ovSessionId = openClawSessionToOvStorageId(sessionId, sessionKey);+ const runtimeAgentId = extractRuntimeAgentId(runtimeContext);+ if (runtimeAgentId) {+ rememberSessionAgentId?.({+ agentId: runtimeAgentId,+ sessionId,+ sessionKey,+ ovSessionId,+ });+ }+ const routingRef = sessionId ?? sessionKey ?? ovSessionId;+ const agentId = resolveAgentId(routingRef, sessionKey, ovSessionId);++ if (isBypassedSession({ sessionId, sessionKey })) {+ diag("afterTurn_skip", ovSessionId, {+ reason: "session_bypassed",+ totalMessages: rawMessages?.length ?? 0,+ senderIdFound: sender.found,+ senderId: sender.senderId ?? null,+ });+ return;+ }++ const messages = rawMessages ?? [];+ if (messages.length === 0) {+ diag("afterTurn_skip", ovSessionId, {+ reason: "no_messages",+ totalMessages: 0,+ senderIdFound: sender.found,+ senderId: sender.senderId ?? null,+ });+ return;+ }++ const start =+ typeof prePromptMessageCount === "number" && prePromptMessageCount >= 0+ ? prePromptMessageCount+ : 0;++ const { messages: extractedMessagesRaw, newCount } = extractNewTurnMessages(messages, start);+ const extractedMessages = coalesceConsecutiveToolMessages(extractedMessagesRaw);++ if (extractedMessages.length === 0) {+ diag("afterTurn_skip", ovSessionId, {+ reason: "no_new_turn_messages",+ totalMessages: messages.length,+ prePromptMessageCount: start,+ senderIdFound: sender.found,+ senderId: sender.senderId ?? null,+ });+ return;+ }++ const turnMessages = messages.slice(start) as AgentMessage[];+ const newMessages = turnMessages.filter((m: AgentMessage) => {+ const role = (m as Record<string, unknown>).role as string;+ return role === "user" || role === "assistant";+ }) as AgentMessage[];+ const newMsgFull = messageDigest(newMessages);+ const newTurnTokens = newMsgFull.reduce((sum, digest) => sum + digest.tokens, 0);++ diag("afterTurn_entry", ovSessionId, {+ totalMessages: messages.length,+ newMessageCount: newCount,+ prePromptMessageCount: start,+ newTurnTokens,+ senderIdFound: sender.found,+ senderId: sender.senderId ?? null,+ messages: newMsgFull,+ });++ const client = await getClient();+ const createdAt = pickLatestCreatedAt(turnMessages);+ const senderRoleId = toRoleId(sender.senderId);+ for (const msg of extractedMessages) {+ const ovParts = msg.parts.map((part) => {+ if (part.type === "text") {+ const cleaned = part.text+ .replace(/<relevant-memories>[\s\S]*?<\/relevant-memories>/gi, " ")+ .replace(/\s+/g, " ")+ .trim();+ return { type: "text" as const, text: cleaned };+ }+ return {+ type: "tool" as const,+ tool_id: part.toolCallId,+ tool_name: part.toolName,+ tool_input: part.toolInput,+ tool_output: part.toolOutput,+ tool_status: part.toolStatus,+ };+ });++ if (ovParts.length > 0) {+ await client.addSessionMessage(+ ovSessionId,+ msg.role,+ ovParts,+ agentId,+ createdAt,+ msg.role === "user" ? senderRoleId : undefined,+ );+ }+ }++ const session = await client.getSession(ovSessionId, agentId);+ const pendingTokens = session.pending_tokens ?? 0;++ if (pendingTokens < cfg.commitTokenThreshold) {+ diag("afterTurn_skip", ovSessionId, {+ reason: "below_threshold",+ pendingTokens,+ commitTokenThreshold: cfg.commitTokenThreshold,+ senderIdFound: sender.found,+ senderId: sender.senderId ?? null,+ });+ return;+ }++ const commitResult = await client.commitSession(ovSessionId, {+ wait: false,+ agentId,+ keepRecentCount: cfg.commitKeepRecentCount,+ });+ logger.info(+ `openviking: committed session=${ovSessionId}, ` ++ `status=${commitResult.status}, archived=${commitResult.archived ?? false}, ` ++ `task_id=${commitResult.task_id ?? "none"}, trace_id=${commitResult.trace_id ?? "none"}`,+ );++ diag("afterTurn_commit", ovSessionId, {+ pendingTokens,+ commitTokenThreshold: cfg.commitTokenThreshold,+ status: commitResult.status,+ archived: commitResult.archived ?? false,+ taskId: commitResult.task_id ?? null,+ extractedMemories: totalExtractedMemories(commitResult.memories_extracted),+ senderIdFound: sender.found,+ senderId: sender.senderId ?? null,+ });+ if (commitResult.task_id && cfg.logFindRequests) {+ logger.info(+ `openviking: Phase2 memory extraction runs asynchronously on the server (task_id=${commitResult.task_id}). ` ++ "memories_extracted appears only after that task completes — not in this immediate response.",+ );+ void pollPhase2ExtractionOutcome(client, commitResult.task_id, agentId, logger, ovSessionId);+ }+ } catch (err) {+ logger.warn?.(`openviking: afterTurn failed: ${String(err)}`);+ const sender = extractRuntimeSenderId(runtimeContext);+ diag("afterTurn_error", sessionId ?? "(unknown)", {+ error: String(err),+ senderIdFound: sender.found,+ senderId: sender.senderId ?? null,+ });+ }+}++function validTokenCount(value: unknown): number | undefined {+ return typeof value === "number" && Number.isFinite(value) && value > 0+ ? value+ : undefined;+}++function compactFailureResult(+ reason: string,+ tokensBefore: number,+ details: unknown,+): CompactOpenVikingSessionResult {+ return {+ ok: false,+ compacted: false,+ reason,+ result: {+ summary: "",+ firstKeptEntryId: "",+ tokensBefore,+ tokensAfter: undefined,+ details,+ },+ };+}++export async function compactOpenVikingSession({+ sessionId,+ sessionKey,+ tokenBudget,+ currentTokenCount,+ force,+ compactionTarget,+ customInstructions,+ getClient,+ logger,+ resolveAgentId,+ isBypassedSession,+ diag,+}: CompactOpenVikingSessionParams): Promise<CompactOpenVikingSessionResult> {+ const ovSessionId = openClawSessionToOvStorageId(sessionId, sessionKey);+ diag("compact_entry", ovSessionId, {+ tokenBudget,+ force: force ?? false,+ currentTokenCount: currentTokenCount ?? null,+ compactionTarget: compactionTarget ?? null,+ hasCustomInstructions: typeof customInstructions === "string" &&+ customInstructions.trim().length > 0,+ });++ if (isBypassedSession({ sessionId, sessionKey })) {+ diag("compact_result", ovSessionId, {+ ok: true,+ compacted: false,+ reason: "session_bypassed",+ });+ return {+ ok: true,+ compacted: false,+ reason: "session_bypassed",+ };+ }++ const client = await getClient();+ const agentId = resolveAgentId(sessionId, sessionKey, ovSessionId);+ const tokensBeforeOriginal = validTokenCount(currentTokenCount);+ let preCommitEstimatedTokens: number | undefined;+ if (typeof tokensBeforeOriginal !== "number") {+ try {+ const preCtx = await client.getSessionContext(ovSessionId, tokenBudget, agentId);+ if (typeof preCtx.estimatedTokens === "number" && Number.isFinite(preCtx.estimatedTokens)) {+ preCommitEstimatedTokens = preCtx.estimatedTokens;+ }+ } catch (preCtxErr) {+ logger.info(+ `openviking: compact pre-ctx fetch failed for session=${ovSessionId}, ` ++ `tokenBudget=${tokenBudget}, agentId=${agentId}: ${String(preCtxErr)}`,+ );+ }+ }++ const tokensBefore = tokensBeforeOriginal ?? preCommitEstimatedTokens ?? -1;++ try {+ logger.info(+ `openviking: compact committing session=${ovSessionId} (wait=true, tokenBudget=${tokenBudget})`,+ );+ const commitResult = await client.commitSession(ovSessionId, {+ wait: true,+ agentId,+ keepRecentCount: 0,+ });+ const memCount = totalExtractedMemories(commitResult.memories_extracted);++ if (commitResult.status === "failed") {+ logger.warn?.(+ `openviking: compact commit Phase 2 failed for session=${ovSessionId}: ${commitResult.error ?? "unknown"}`,+ );+ diag("compact_result", ovSessionId, {+ ok: false,+ compacted: false,+ reason: "commit_failed",+ status: commitResult.status,+ archived: commitResult.archived ?? false,+ taskId: commitResult.task_id ?? null,+ error: commitResult.error ?? null,+ });+ return compactFailureResult("commit_failed", tokensBefore, { commit: commitResult });+ }++ if (commitResult.status === "timeout") {+ logger.warn?.(+ `openviking: compact commit Phase 2 timed out for session=${ovSessionId}, task_id=${commitResult.task_id ?? "none"}`,+ );+ diag("compact_result", ovSessionId, {+ ok: false,+ compacted: false,+ reason: "commit_timeout",+ status: commitResult.status,+ archived: commitResult.archived ?? false,+ taskId: commitResult.task_id ?? null,+ });+ return compactFailureResult("commit_timeout", tokensBefore, { commit: commitResult });+ }++ logger.info(+ `openviking: compact committed session=${ovSessionId}, archived=${commitResult.archived ?? false}, memories=${memCount}, task_id=${commitResult.task_id ?? "none"}, trace_id=${commitResult.trace_id ?? "none"}`,+ );++ if (!commitResult.archived) {+ logger.info(+ `openviking: compact no archive for session=${ovSessionId}, ` ++ `tokensBefore=${tokensBefore}, tokensAfter=${tokensBefore}`,+ );+ diag("compact_result", ovSessionId, {+ ok: true,+ compacted: false,+ reason: "commit_no_archive",+ status: commitResult.status,+ archived: commitResult.archived ?? false,+ taskId: commitResult.task_id ?? null,+ memories: memCount,+ tokensBefore,+ });+ return {+ ok: true,+ compacted: false,+ reason: "commit_no_archive",+ result: {+ summary: "",+ tokensBefore,+ tokensAfter: tokensBefore >= 0 ? tokensBefore : undefined,+ details: {+ commit: commitResult,+ },+ },+ };+ }++ let summary = "";+ const firstKeptEntryId = commitResult.archive_uri?.split("/").pop() ?? "";+ let tokensAfter: number | undefined;+ let contextFetchError: string | undefined;++ try {+ const ctx = await client.getSessionContext(ovSessionId, tokenBudget, agentId);+ logger.info(+ `openviking: compact getSessionContext raw result for ${ovSessionId}: ` ++ JSON.stringify(ctx, null, 2),+ );+ if (typeof ctx.latest_archive_overview === "string") {+ summary = ctx.latest_archive_overview.trim();+ }+ if (typeof ctx.estimatedTokens === "number" && Number.isFinite(ctx.estimatedTokens)) {+ tokensAfter = ctx.estimatedTokens;+ }+ logger.info(+ `openviking: compact restored session content for ${ovSessionId}: ` ++ `messages=${ctx.messages?.length ?? 0}, ` ++ `latestArchiveOverview=${summary.length > 0 ? "present" : "empty"} (${summary.length} chars), ` ++ `preArchiveAbstracts=${ctx.pre_archive_abstracts?.length ?? 0}, ` ++ `estimatedTokens=${ctx.estimatedTokens}`,+ );+ if (summary.length > 0) {+ logger.info(+ `openviking: compact latest_archive_overview for ${ovSessionId}: ${summary.substring(0, 200)}...`,+ );+ }+ if (ctx.messages && ctx.messages.length > 0) {+ const msgSummary = ctx.messages.map((m: { role?: string; content?: string; parts?: Array<{ type?: string; text?: string }> }) => {+ const role = m.role ?? "unknown";+ let textPreview = "";+ if (m.content) {+ textPreview = m.content.substring(0, 80);+ } else if (m.parts && m.parts.length > 0) {+ const textPart = m.parts.find((p: { type?: string }) => p.type === "text");+ textPreview = textPart?.text?.substring(0, 80) ?? JSON.stringify(m.parts).substring(0, 80);+ }+ return { role, textPreview };+ });+ logger.info(+ `openviking: compact restored messages for ${ovSessionId}: ` ++ JSON.stringify(msgSummary),+ );+ }+ } catch (ctxErr) {+ contextFetchError = String(ctxErr);+ logger.info(+ `openviking: compact context fetch failed for session=${ovSessionId}, ` ++ `tokenBudget=${tokenBudget}, agentId=${agentId}: ${contextFetchError}`,+ );+ }++ logger.info(+ `openviking: compact tokens session=${ovSessionId}, ` ++ `tokensBefore=${tokensBefore}, tokensAfter=${tokensAfter ?? "unknown"}, ` ++ `latestArchiveId=${firstKeptEntryId || "none"}`,+ );++ diag("compact_result", ovSessionId, {+ ok: true,+ compacted: true,+ reason: "commit_completed",+ status: commitResult.status,+ archived: commitResult.archived ?? false,+ taskId: commitResult.task_id ?? null,+ memories: memCount,+ tokensBefore,+ tokensAfter: tokensAfter ?? null,+ latestArchiveId: firstKeptEntryId || null,+ summaryPresent: summary.length > 0,+ });++ return {+ ok: true,+ compacted: true,+ reason: "commit_completed",+ result: {+ summary,+ firstKeptEntryId,+ tokensBefore,+ tokensAfter,+ details: contextFetchError+ ? {+ commit: commitResult,+ contextError: contextFetchError,+ }+ : {+ commit: commitResult,+ },+ },+ };+ } catch (err) {+ const errorMessage = String(err);+ if (errorMessage.includes("[NOT_FOUND]") && errorMessage.includes("Session not found")) {+ logger.info(+ `openviking: compact skipped because OV session does not exist ` ++ `(session=${ovSessionId}, agentId=${agentId})`,+ );+ diag("compact_result", ovSessionId, {+ ok: true,+ compacted: false,+ reason: "session_not_found",+ error: errorMessage,+ });+ return {+ ok: true,+ compacted: false,+ reason: "session_not_found",+ };+ }+ logger.warn?.(`openviking: compact commit failed for session=${ovSessionId}: ${errorMessage}`);+ diag("compact_error", ovSessionId, {+ error: errorMessage,+ });+ return compactFailureResult("commit_error", tokensBefore, { error: errorMessage });+ }+}diff --git a/examples/openclaw-plugin/services/context-message-adapter.ts b/examples/openclaw-plugin/services/context-message-adapter.tsnew file mode 100644index 000000000..bc68a30b4--- /dev/null+++ b/examples/openclaw-plugin/services/context-message-adapter.ts@@ -0,0 +1,375 @@+import type { OVMessage } from "../client.js";+import { sanitizeToolUseResultPairing } from "../session-transcript-repair.js";++export type AgentMessage = {+ role?: string;+ content?: unknown;+ timestamp?: unknown;+};++export function toRoleId(senderId: string | undefined): string | undefined {+ if (!senderId) {+ return undefined;+ }+ const normalized = senderId+ .trim()+ .replace(/[^a-zA-Z0-9_-]+/g, "_")+ .replace(/^_+|_+$/g, "")+ .replace(/_+/g, "_");+ return normalized || undefined;+}++/**+ * Convert an OpenViking stored message (parts-based format) into one or more+ * OpenClaw AgentMessages (content-blocks format).+ *+ * For assistant messages with ToolParts, this produces:+ * 1. The assistant message with canonical toolCall blocks in its content array+ * 2. A separate toolResult message per ToolPart (carrying tool_output)+ */+export function convertToAgentMessages(msg: { role: string; parts: unknown[] }): AgentMessage[] {+ const parts = msg.parts ?? [];+ const contentBlocks: Record<string, unknown>[] = [];+ const toolCallBlocks: Record<string, unknown>[] = [];+ const toolResults: AgentMessage[] = [];++ for (const part of parts) {+ if (!part || typeof part !== "object") continue;+ const p = part as Record<string, unknown>;++ if (p.type === "text" && typeof p.text === "string") {+ contentBlocks.push({ type: "text", text: p.text });+ } else if (p.type === "context") {+ if (typeof p.abstract === "string" && p.abstract) {+ contentBlocks.push({ type: "text", text: p.abstract });+ }+ } else if (p.type === "tool") {+ const toolId = typeof p.tool_id === "string" ? p.tool_id : "";+ const toolName = typeof p.tool_name === "string" ? p.tool_name : undefined;+ const status = typeof p.tool_status === "string" ? p.tool_status : "unknown";+ const output = typeof p.tool_output === "string" ? p.tool_output : "";+ const ref = typeof p.tool_output_ref === "string" ? p.tool_output_ref : "";+ const originalChars = typeof p.tool_output_original_chars === "number"+ ? p.tool_output_original_chars+ : undefined;++ if (toolId) {+ toolCallBlocks.push({+ type: "toolCall",+ id: toolId,+ name: toolName ?? "unknown",+ arguments: p.tool_input ?? {},+ });++ let resultText = (status === "completed" || status === "error")+ ? (output || "(no output)")+ : "(interrupted — tool did not complete)";+ if (ref && !resultText.includes(ref)) {+ const suffix = originalChars !== undefined+ ? `\n[tool-result-ref] ${ref} original_chars=${originalChars}`+ : `\n[tool-result-ref] ${ref}`;+ resultText += suffix;+ }+ const resultPayload: Record<string, unknown> = {+ role: "toolResult",+ toolCallId: toolId,+ content: [{ type: "text", text: resultText }],+ isError: status === "error",+ };+ if (toolName) {+ resultPayload.toolName = toolName;+ }+ toolResults.push(resultPayload as unknown as AgentMessage);+ } else {+ const fallbackName = toolName ?? "unknown";+ const segments = [`[${fallbackName}] (${status})`];+ if (p.tool_input) {+ try {+ segments.push(`Input: ${JSON.stringify(p.tool_input)}`);+ } catch {+ // non-serializable input, skip+ }+ }+ if (output) {+ segments.push(`Output: ${output}`);+ }+ contentBlocks.push({ type: "text", text: segments.join("\n") });+ }+ }+ }++ const result: AgentMessage[] = [];++ if (msg.role === "assistant") {+ result.push({ role: "assistant", content: [...contentBlocks, ...toolCallBlocks] });+ result.push(...toolResults);+ } else {+ const texts = contentBlocks+ .filter((b) => b.type === "text")+ .map((b) => b.text as string);+ if (texts.length > 0) {+ result.push({ role: msg.role, content: texts.join("\n") });+ } else if (toolCallBlocks.length === 0) {+ result.push({ role: msg.role, content: "" });+ }+ if (toolCallBlocks.length > 0) {+ result.push({ role: "assistant", content: toolCallBlocks });+ result.push(...toolResults);+ }+ }++ return result;+}++export function formatMessageFaithful(msg: OVMessage): string {+ const roleTag = `[${msg.role}]`;+ if (!msg.parts || msg.parts.length === 0) {+ return `${roleTag}: (empty)`;+ }++ const sections: string[] = [];+ for (const part of msg.parts) {+ if (!part || typeof part !== "object") continue;+ switch (part.type) {+ case "text":+ if (part.text) sections.push(part.text);+ break;+ case "tool": {+ const status = part.tool_status ?? "unknown";+ const header = `[Tool: ${part.tool_name ?? "unknown"}] (${status})`;+ const inputStr = part.tool_input+ ? `Input: ${JSON.stringify(part.tool_input, null, 2)}`+ : "";+ const outputStr = part.tool_output ? `Output:\n${part.tool_output}` : "";+ sections.push([header, inputStr, outputStr].filter(Boolean).join("\n"));+ break;+ }+ case "context":+ sections.push(+ `[Context: ${part.uri ?? "?"}]${part.abstract ? ` ${part.abstract}` : ""}`,+ );+ break;+ default:+ sections.push(`[${part.type}]: ${JSON.stringify(part)}`);+ }+ }++ return `${roleTag}:\n${sections.join("\n\n")}`;+}++/** Merge consecutive assistant messages by concatenating their content arrays. */+export function mergeConsecutiveAssistants(messages: AgentMessage[]): AgentMessage[] {+ const result: AgentMessage[] = [];+ for (const msg of messages) {+ const prev = result[result.length - 1];+ if (msg.role === "assistant" && prev?.role === "assistant") {+ const prevContent = Array.isArray(prev.content) ? prev.content : [{ type: "text", text: prev.content }];+ const currContent = Array.isArray(msg.content) ? msg.content : [{ type: "text", text: msg.content }];+ prev.content = [...prevContent, ...currContent] as typeof prev.content;+ } else {+ result.push({ ...msg });+ }+ }+ return result;+}++/**+ * Hoist tool_result blocks to the front of a content array.+ *+ * The Anthropic / Bedrock / Gemini APIs require tool_result blocks to appear+ * at the START of a user message's content array (a tool_result must follow+ * the assistant tool_use that produced it). When mergeConsecutiveUsers+ * merges two user messages, the previous content's text blocks may end up+ * before tool_results from the second message — this function fixes the order.+ *+ * Same pattern as Claude Code's hoistToolResults in src/utils/messages.ts.+ */+function hoistToolResults<T>(content: T[]): T[] {+ const toolResults: T[] = [];+ const others: T[] = [];+ for (const block of content) {+ if (+ block &&+ typeof block === "object" &&+ "type" in block &&+ (block as { type?: string }).type === "tool_result"+ ) {+ toolResults.push(block);+ } else {+ others.push(block);+ }+ }+ return [...toolResults, ...others];+}++/**+ * Merge consecutive user messages by concatenating their content arrays.+ *+ * Mirror of mergeConsecutiveAssistants. Required because Gemini and Anthropic+ * APIs reject consecutive same-role messages with stopReason=stop payloads=0+ * (empty response). Three independent sources can inject role: "user":+ *+ * 1. Archive commit: "[Session History Summary]" via buildArchiveMemory+ * 2. OpenClaw yield events: "[sessions_yield interrupt]" / "Turn yielded. ..."+ * 3. Audio/Telegram metadata: "[Audio] User text: [Telegram <name>...]"+ *+ * Without merging, these can stack into 2-5 consecutive user turns. The+ * 1P Anthropic API would merge server-side, but Bedrock/Gemini won't —+ * we merge client-side for wire-format consistency.+ *+ * Note: this MUST run AFTER sanitizeToolUseResultPairing because that pass+ * may strip orphaned tool_use / tool_result blocks and thereby create new+ * user-user adjacencies that didn't exist in the input.+ *+ * Tracks issue #1724.+ */+export function mergeConsecutiveUsers(messages: AgentMessage[]): AgentMessage[] {+ const result: AgentMessage[] = [];+ for (const msg of messages) {+ const prev = result[result.length - 1];+ if (msg.role === "user" && prev?.role === "user") {+ const prevContent = Array.isArray(prev.content) ? prev.content : [{ type: "text", text: prev.content }];+ const currContent = Array.isArray(msg.content) ? msg.content : [{ type: "text", text: msg.content }];+ prev.content = hoistToolResults([...prevContent, ...currContent]) as typeof prev.content;+ } else {+ result.push({ ...msg });+ }+ }+ return result;+}++/**+ * Defensive role-alternation invariant check.+ *+ * After mergeConsecutiveUsers + mergeConsecutiveAssistants, the message stream+ * should already alternate user/assistant. But sanitizeToolUseResultPairing+ * can in rare cases strip a user_with_tool_result message that was the only+ * thing separating two assistant messages, leaving an assistant-assistant+ * adjacency that upstream merge passes can't fix.+ *+ * When detected, we insert a placeholder user message — matching Claude Code's+ * NO_CONTENT_MESSAGE pattern (see CC src/utils/messages.ts:5375-5388) — to+ * preserve the alternation contract that Gemini / Anthropic require.+ */+export function ensureAlternation(messages: AgentMessage[]): AgentMessage[] {+ const result: AgentMessage[] = [];+ for (const msg of messages) {+ const prev = result[result.length - 1];+ if (prev && prev.role === "assistant" && msg.role === "assistant") {+ result.push({+ role: "user",+ content: "(no content)",+ });+ }+ result.push(msg);+ }+ return result;+}++function normalizeAssistantContent(messages: AgentMessage[]): void {+ for (let i = 0; i < messages.length; i++) {+ const msg = messages[i];+ if (msg?.role === "assistant" && typeof msg.content === "string") {+ messages[i] = {+ ...msg,+ content: [{ type: "text", text: msg.content }],+ };+ }+ }+}++function canonicalizeAssistantBlock(block: unknown): unknown {+ if (!block || typeof block !== "object") {+ return block;+ }++ const rec = block as Record<string, unknown>;+ const type = typeof rec.type === "string" ? rec.type : "";+ if (type === "toolCall") {+ if (rec.arguments !== undefined) {+ return rec;+ }+ return {+ ...rec,+ arguments: rec.input ?? rec.toolInput ?? {},+ };+ }++ if (type === "toolUse" || type === "functionCall" || type === "tool_call") {+ return {+ type: "toolCall",+ id: rec.id ?? rec.toolCallId ?? rec.toolUseId,+ name: rec.name,+ arguments: rec.arguments ?? rec.input ?? rec.toolInput ?? {},+ };+ }++ return rec;+}++function canonicalizeAgentMessages(messages: AgentMessage[]): AgentMessage[] {+ let changed = false;+ const next = messages.map((msg) => {+ if (!msg || typeof msg !== "object") {+ return msg;+ }++ if (msg.role === "assistant") {+ const content = Array.isArray(msg.content)+ ? msg.content.map((block) => canonicalizeAssistantBlock(block))+ : typeof msg.content === "string"+ ? [{ type: "text", text: msg.content }]+ : msg.content;++ if (content !== msg.content) {+ changed = true;+ return { ...msg, content };+ }+ return msg;+ }++ if (msg.role === "toolResult") {+ const raw = msg as Record<string, unknown>;+ const toolCallId =+ (typeof raw.toolCallId === "string" && raw.toolCallId) ||+ (typeof raw.toolUseId === "string" && raw.toolUseId) ||+ undefined;+ const toolName =+ typeof raw.toolName === "string" && raw.toolName.trim()+ ? raw.toolName.trim()+ : undefined;++ const nextMsg = {+ ...msg,+ ...(toolCallId ? { toolCallId } : {}),+ ...(toolName ? { toolName } : {}),+ } as AgentMessage;++ if (nextMsg !== msg) {+ changed = true;+ }+ return nextMsg;+ }++ return msg;+ });++ return changed ? next : messages;+}++export function sanitizeAgentMessagesForProvider(messages: AgentMessage[]): AgentMessage[] {+ normalizeAssistantContent(messages);+ const canonical = canonicalizeAgentMessages(messages);+ // Defense in depth (issue #1724):+ // 1) sanitizeToolUseResultPairing may strip orphaned tool_use/tool_result,+ // potentially creating new user-user or assistant-assistant adjacencies.+ // 2) mergeConsecutiveUsers fixes user-user (mirror of mergeConsecutiveAssistants+ // already running inside buildSessionContext).+ // 3) ensureAlternation is a final invariant check for the rare+ // assistant-assistant case that the merges can't reach.+ return ensureAlternation(+ mergeConsecutiveUsers(+ sanitizeToolUseResultPairing(canonical as never[]) as AgentMessage[],+ ),+ );+}diff --git a/examples/openclaw-plugin/services/setup/config-writer.ts b/examples/openclaw-plugin/services/setup/config-writer.tsnew file mode 100644index 000000000..02529fb9d--- /dev/null+++ b/examples/openclaw-plugin/services/setup/config-writer.ts@@ -0,0 +1,125 @@+import * as fs from "node:fs";+import * as path from "node:path";++export type SlotActivationResult = {+ activated: boolean;+ previousOwner?: string;+ replaced: boolean;+};++export type SetupIO = {+ readConfig: (configPath: string) => Record<string, unknown>;+ writeConfig: (configPath: string, config: Record<string, unknown>) => void;+ backupConfig: (configPath: string) => string | null;+};++export const defaultSetupIO: SetupIO = {+ readConfig: readOpenClawConfig,+ writeConfig: writeOpenClawConfigFile,+ backupConfig,+};++export function readOpenClawConfig(configPath: string): Record<string, unknown> {+ if (!fs.existsSync(configPath)) return {};+ try {+ return JSON.parse(fs.readFileSync(configPath, "utf-8"));+ } catch {+ return {};+ }+}++function writeOpenClawConfigFile(configPath: string, config: Record<string, unknown>): void {+ const configDir = path.dirname(configPath);+ if (!fs.existsSync(configDir)) fs.mkdirSync(configDir, { recursive: true });+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");+}++export function backupConfig(configPath: string): string | null {+ if (!fs.existsSync(configPath)) return null;+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);+ const backupPath = `${configPath}.bak.${timestamp}`;+ try {+ fs.copyFileSync(configPath, backupPath);+ return backupPath;+ } catch {+ return null;+ }+}++export function getExistingPluginConfig(config: Record<string, unknown>): Record<string, unknown> | null {+ const plugins = config.plugins as Record<string, unknown> | undefined;+ if (!plugins) return null;+ const entries = plugins.entries as Record<string, unknown> | undefined;+ if (!entries) return null;+ const entry = entries.openviking as Record<string, unknown> | undefined;+ if (!entry) return null;+ const cfg = entry.config as Record<string, unknown> | undefined;+ return cfg && cfg.mode ? cfg : null;+}++export function ensureInstallRecord(plugins: Record<string, unknown>): void {+ const installs = plugins.installs as Record<string, unknown> | undefined;+ if (installs && typeof installs === "object") {+ delete installs.openviking;+ }++ if (!plugins.allow) plugins.allow = [];+ const allow = plugins.allow as string[];+ if (!allow.includes("openviking")) {+ allow.push("openviking");+ }+}++export function writeOpenVikingConfig(+ configPath: string,+ pluginCfg: Record<string, unknown>,+ io: SetupIO = defaultSetupIO,+): void {+ io.backupConfig(configPath);++ const config = io.readConfig(configPath);++ if (!config.plugins) config.plugins = {};+ const plugins = config.plugins as Record<string, unknown>;+ if (!plugins.entries) plugins.entries = {};+ const entries = plugins.entries as Record<string, unknown>;++ const existingEntry = (entries.openviking as Record<string, unknown>) ?? {};+ entries.openviking = { ...existingEntry, config: pluginCfg };++ ensureInstallRecord(plugins);++ io.writeConfig(configPath, config);+}++export function activateContextEngineSlot(+ configPath: string,+ force: boolean,+ io: SetupIO = defaultSetupIO,+): SlotActivationResult {+ const config = io.readConfig(configPath);+ if (!config.plugins) config.plugins = {};+ const plugins = config.plugins as Record<string, unknown>;+ if (!plugins.slots) plugins.slots = {};+ const slots = plugins.slots as Record<string, unknown>;++ const current = slots.contextEngine as string | undefined;++ if (current === "openviking") return { activated: false, replaced: false };++ if (current && current !== "openviking" && !force) {+ return { activated: false, previousOwner: current, replaced: false };+ }++ slots.contextEngine = "openviking";+ io.writeConfig(configPath, config);+ return { activated: true, previousOwner: current || undefined, replaced: !!current };+}++export function isContextEngineSlotActive(configPath: string, io: SetupIO = defaultSetupIO): boolean {+ const config = io.readConfig(configPath);+ const plugins = config.plugins as Record<string, unknown> | undefined;+ if (!plugins) return false;+ const slots = plugins.slots as Record<string, unknown> | undefined;+ return slots?.contextEngine === "openviking";+}diff --git a/examples/openclaw-plugin/services/setup/exit-utils.ts b/examples/openclaw-plugin/services/setup/exit-utils.tsnew file mode 100644index 000000000..32e267861--- /dev/null+++ b/examples/openclaw-plugin/services/setup/exit-utils.ts@@ -0,0 +1,5 @@+export function setExitCodeOnFailure(result: { success: boolean }): void {+ if (!result.success) {+ process.exitCode = 1;+ }+}diff --git a/examples/openclaw-plugin/services/setup/package-metadata.ts b/examples/openclaw-plugin/services/setup/package-metadata.tsnew file mode 100644index 000000000..9a9b58ba0--- /dev/null+++ b/examples/openclaw-plugin/services/setup/package-metadata.ts@@ -0,0 +1,56 @@+import * as fs from "node:fs";+import * as path from "node:path";+import { fileURLToPath } from "node:url";++export type SetupCompatibilityRange = {+ min: string;+ max: string;+};++export function findPluginPackageRoot(fromDir = path.dirname(fileURLToPath(import.meta.url))): string | null {+ let current = path.resolve(fromDir);+ for (let depth = 0; depth < 5; depth += 1) {+ if (+ fs.existsSync(path.join(current, "package.json")) &&+ fs.existsSync(path.join(current, "openclaw.plugin.json"))+ ) {+ return current;+ }++ const parent = path.dirname(current);+ if (parent === current) break;+ current = parent;+ }+ return null;+}++export function readPluginVersion(): string {+ try {+ const packageRoot = findPluginPackageRoot();+ if (!packageRoot) return "unknown";+ const pkgPath = path.join(packageRoot, "package.json");+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));+ return String(pkg.version ?? "unknown");+ } catch {+ return "unknown";+ }+}++export function readCompatRangeFromManifest(): SetupCompatibilityRange {+ try {+ const packageRoot = findPluginPackageRoot();+ if (!packageRoot) return { min: "", max: "" };+ const manifestPath = path.join(packageRoot, "install-manifest.json");+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));+ const compat = manifest?.compatibility ?? {};+ return {+ min: String(compat.minOpenvikingVersion ?? ""),+ max: String(compat.maxOpenvikingVersion ?? ""),+ };+ } catch {+ return { min: "", max: "" };+ }+}++export const PLUGIN_VERSION = readPluginVersion();+export const { min: COMPATIBLE_SERVER_MIN, max: COMPATIBLE_SERVER_MAX } = readCompatRangeFromManifest();diff --git a/examples/openclaw-plugin/services/setup/probe-service.ts b/examples/openclaw-plugin/services/setup/probe-service.tsnew file mode 100644index 000000000..88c18b77d--- /dev/null+++ b/examples/openclaw-plugin/services/setup/probe-service.ts@@ -0,0 +1,143 @@+export type SetupNetworkTransport = (url: string, init: RequestInit) => Promise<Response>;++export type SetupVersionCompatibility = "compatible" | "server_too_old" | "server_too_new" | "unknown";++export type SetupHealthResult = {+ ok: boolean;+ version: string;+ error: string;+ compatibility: SetupVersionCompatibility;+ pluginVersion: string;+ compatRange: string;+};++export type SetupApiKeyProbeResult = {+ keyType: "user_key" | "root_key" | "no_key" | "unknown";+ needsAccountId: boolean;+ needsUserId: boolean;+ detail: string;+};++export type SetupNetworkProbeOptions = {+ pluginVersion: string;+ compatRange: string;+ checkVersionCompatibility: (serverVersion: string) => SetupVersionCompatibility;+ transport?: SetupNetworkTransport;+ timeoutMs?: number;+};++export type SetupNetworkProbes = {+ probeApiKeyType: (baseUrl: string, apiKey?: string) => Promise<SetupApiKeyProbeResult>;+ checkServiceHealth: (baseUrl: string, apiKey?: string) => Promise<SetupHealthResult>;+};++export const defaultSetupNetworkTransport: SetupNetworkTransport = (url, init) => fetch(url, init);++export function createSetupNetworkProbes({+ pluginVersion,+ compatRange,+ checkVersionCompatibility,+ transport = defaultSetupNetworkTransport,+ timeoutMs = 10_000,+}: SetupNetworkProbeOptions): SetupNetworkProbes {+ return {+ async probeApiKeyType(baseUrl: string, apiKey?: string): Promise<SetupApiKeyProbeResult> {+ if (!apiKey) {+ return { keyType: "no_key", needsAccountId: false, needsUserId: false, detail: "No API key configured" };+ }++ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);+ const sessionsUrl = `${baseUrl.replace(/\/+$/, "")}/api/v1/sessions?limit=1`;+ try {+ const headers: Record<string, string> = { "X-API-Key": apiKey };+ const response = await transport(sessionsUrl, {+ headers,+ signal: controller.signal,+ });++ if (response.ok) {+ return { keyType: "user_key", needsAccountId: false, needsUserId: false, detail: "API key has full user context" };+ }++ if ([400, 401, 403, 422].includes(response.status)) {+ let body = "";+ try {+ body = await response.text();+ } catch { /* ignore parse errors */ }+ const lower = body.toLowerCase();+ const needsAccount = /x-openviking-account|account[_ ]?id|account context|tenant/.test(lower);+ const needsUser = /x-openviking-user|user[_ ]?id|user context|user key/.test(lower);+ if (needsAccount || needsUser) {+ return {+ keyType: "root_key",+ needsAccountId: needsAccount,+ needsUserId: needsUser,+ detail: body.slice(0, 200),+ };+ }++ try {+ const probeHeaders: Record<string, string> = {+ "X-API-Key": apiKey,+ "X-OpenViking-Account": "__probe__",+ "X-OpenViking-User": "__probe__",+ };+ const probe2 = await transport(sessionsUrl, {+ headers: probeHeaders,+ signal: controller.signal,+ });+ if (probe2.status !== response.status) {+ return {+ keyType: "root_key",+ needsAccountId: true,+ needsUserId: true,+ detail: body.slice(0, 200) || `HTTP ${response.status} -> ${probe2.status} after adding tenant headers`,+ };+ }+ } catch { /* ignore probe errors, fall through to unknown */ }++ if (response.status === 401 || response.status === 403) {+ return { keyType: "unknown", needsAccountId: false, needsUserId: false, detail: `HTTP ${response.status} - authentication failed, verify your API key` };+ }+ return { keyType: "unknown", needsAccountId: false, needsUserId: false, detail: `HTTP ${response.status}${body ? ` - ${body.slice(0, 160)}` : ""}` };+ }++ return { keyType: "unknown", needsAccountId: false, needsUserId: false, detail: `HTTP ${response.status}` };+ } catch (err) {+ return { keyType: "unknown", needsAccountId: false, needsUserId: false, detail: String(err instanceof Error ? err.message : err) };+ } finally {+ clearTimeout(timeoutId);+ }+ },++ async checkServiceHealth(baseUrl: string, apiKey?: string): Promise<SetupHealthResult> {+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);+ try {+ const headers: Record<string, string> = {};+ if (apiKey) headers["X-API-Key"] = apiKey;+ const response = await transport(`${baseUrl.replace(/\/+$/, "")}/health`, {+ headers,+ signal: controller.signal,+ });+ if (response.ok) {+ try {+ const data = await response.json() as Record<string, unknown>;+ const result = (data.result ?? data) as Record<string, unknown>;+ const version = String(result.version ?? data.version ?? "");+ const compatibility = checkVersionCompatibility(version);+ return { ok: true, version, error: "", compatibility, pluginVersion, compatRange };+ } catch {+ return { ok: true, version: "", error: "", compatibility: "unknown", pluginVersion, compatRange };+ }+ }+ return { ok: false, version: "", error: `HTTP ${response.status}`, compatibility: "unknown", pluginVersion, compatRange };+ } catch (err) {+ return { ok: false, version: "", error: String(err instanceof Error ? err.message : err), compatibility: "unknown", pluginVersion, compatRange };+ } finally {+ clearTimeout(timeoutId);+ }+ },+ };+}diff --git a/examples/openclaw-plugin/services/setup/setup-flow.ts b/examples/openclaw-plugin/services/setup/setup-flow.tsnew file mode 100644index 000000000..dec9efb17--- /dev/null+++ b/examples/openclaw-plugin/services/setup/setup-flow.ts@@ -0,0 +1,306 @@+import {+ activateContextEngineSlot,+ getExistingPluginConfig,+ isContextEngineSlotActive,+ writeOpenVikingConfig,+ type SetupIO,+ type SlotActivationResult,+} from "./config-writer.js";++export type { SetupIO, SlotActivationResult };++export type VersionCompatibility = "compatible" | "server_too_old" | "server_too_new" | "unknown";++export type HealthResult = {+ ok: boolean;+ version: string;+ error: string;+ compatibility: VersionCompatibility;+ pluginVersion: string;+ compatRange: string;+};++export type ApiKeyProbeResult = {+ keyType: "user_key" | "root_key" | "no_key" | "unknown";+ needsAccountId: boolean;+ needsUserId: boolean;+ detail: string;+};++export type SetupResult = {+ success: boolean;+ action: "configured" | "existing" | "error" | "slot_blocked";+ config?: {+ mode: string;+ baseUrl: string;+ apiKey?: string;+ peer_role?: "none" | "assistant" | "person";+ peer_prefix?: string;+ accountId?: string;+ userId?: string;+ recallTargetTypes?: string[];+ };+ health?: HealthResult;+ keyProbe?: ApiKeyProbeResult;+ slot: SlotActivationResult;+ error?: string;+};++export type StatusResult = {+ configured: boolean;+ config?: {+ mode: string;+ baseUrl: string;+ hasApiKey: boolean;+ peer_role?: "none" | "assistant" | "person";+ peer_prefix?: string;+ hasAccountId: boolean;+ hasUserId: boolean;+ };+ health?: HealthResult;+ keyProbe?: ApiKeyProbeResult;+ slotActive: boolean;+};++export type SetupParams = {+ baseUrl: string;+ apiKey?: string;+ peerRole?: "none" | "assistant" | "person";+ peerPrefix?: string;+ accountId?: string;+ userId?: string;+ recallTargetTypes?: string[];+ allowOffline?: boolean;+ forceSlot?: boolean;+};++export type InteractiveRemoteConfigParams = {+ existing?: Record<string, unknown> | null;+ baseUrl: string;+ apiKey?: string;+ peerRole?: "none" | "assistant" | "person";+ peerPrefix?: string;+ accountId?: string;+ userId?: string;+ forceSlot?: boolean;+};++export type InteractiveRemoteConfigResult = {+ config: Record<string, unknown>;+ slot: SlotActivationResult;+};++export type OpenVikingSetupService = {+ setupNonInteractive: (configPath: string, params: SetupParams) => Promise<SetupResult>;+ saveInteractiveRemoteConfig: (configPath: string, params: InteractiveRemoteConfigParams) => Promise<InteractiveRemoteConfigResult>;+ useExistingRemoteConfig: (configPath: string, existing: Record<string, unknown>) => Promise<SetupResult>;+ getStatus: (configPath: string) => Promise<StatusResult>;+};++export type OpenVikingSetupServiceDependencies = {+ io: SetupIO;+ defaultRemoteUrl?: string;+ checkServiceHealth: (baseUrl: string, apiKey?: string) => Promise<HealthResult>;+ probeApiKeyType: (baseUrl: string, apiKey?: string) => Promise<ApiKeyProbeResult>;+};++export function maskKey(key: string): string {+ if (key.length <= 8) return "****";+ return `${key.slice(0, 4)}...${key.slice(-4)}`;+}++export function isLegacyLocalMode(existing: Record<string, unknown>): boolean {+ const mode = existing.mode;+ return mode !== "remote";+}++export function buildInteractiveRemotePluginConfig({+ existing,+ baseUrl,+ apiKey,+ peerRole,+ peerPrefix,+ accountId,+ userId,+}: InteractiveRemoteConfigParams): Record<string, unknown> {+ const pluginCfg: Record<string, unknown> = {+ ...(existing ?? {}),+ mode: "remote",+ baseUrl,+ };+ if (apiKey) pluginCfg.apiKey = apiKey;+ else delete pluginCfg.apiKey;+ if (peerRole) pluginCfg.peer_role = peerRole;+ else delete pluginCfg.peer_role;+ if (peerPrefix) pluginCfg.peer_prefix = peerPrefix;+ else delete pluginCfg.peer_prefix;+ if (accountId) pluginCfg.accountId = accountId;+ else delete pluginCfg.accountId;+ if (userId) pluginCfg.userId = userId;+ else delete pluginCfg.userId;+ delete pluginCfg.configPath;+ delete pluginCfg.port;+ return pluginCfg;+}++export function createOpenVikingSetupService({+ io,+ defaultRemoteUrl = "http://127.0.0.1:1933",+ checkServiceHealth,+ probeApiKeyType,+}: OpenVikingSetupServiceDependencies): OpenVikingSetupService {+ return {+ async setupNonInteractive(configPath: string, params: SetupParams): Promise<SetupResult> {+ try {+ const { baseUrl, apiKey, peerRole, peerPrefix, accountId, userId, recallTargetTypes, allowOffline, forceSlot } = params;++ const health = await checkServiceHealth(baseUrl, apiKey);++ if (!health.ok && !allowOffline) {+ return {+ success: false,+ action: "error",+ config: { mode: "remote", baseUrl },+ health,+ slot: { activated: false, replaced: false },+ error: `Server unreachable: ${health.error}. Use --allow-offline to save config anyway.`,+ };+ }++ const keyProbe = health.ok ? await probeApiKeyType(baseUrl, apiKey) : undefined;++ if (keyProbe?.keyType === "root_key" && (!accountId || !userId)) {+ const missing: string[] = [];+ if (!accountId) missing.push("--account-id");+ if (!userId) missing.push("--user-id");+ return {+ success: false,+ action: "error",+ config: {+ mode: "remote",+ baseUrl,+ ...(apiKey ? { apiKey: maskKey(apiKey) } : {}),+ },+ health,+ keyProbe,+ slot: { activated: false, replaced: false },+ error: `Root API key detected. Missing: ${missing.join(", ")}. Re-run with: ${missing.map(f => `${f} <value>`).join(" ")}`,+ };+ }++ const pluginCfg: Record<string, unknown> = { mode: "remote", baseUrl };+ if (apiKey) pluginCfg.apiKey = apiKey;+ if (peerRole) pluginCfg.peer_role = peerRole;+ if (peerPrefix) pluginCfg.peer_prefix = peerPrefix;+ if (accountId) pluginCfg.accountId = accountId;+ if (userId) pluginCfg.userId = userId;+ if (recallTargetTypes && recallTargetTypes.length > 0) pluginCfg.recallTargetTypes = recallTargetTypes;++ writeOpenVikingConfig(configPath, pluginCfg, io);+ const slot = activateContextEngineSlot(configPath, !!forceSlot, io);++ const resultConfig = {+ mode: "remote",+ baseUrl,+ ...(apiKey ? { apiKey: maskKey(apiKey) } : {}),+ ...(peerRole ? { peer_role: peerRole } : {}),+ ...(peerPrefix ? { peer_prefix: peerPrefix } : {}),+ ...(accountId ? { accountId } : {}),+ ...(userId ? { userId } : {}),+ ...(recallTargetTypes && recallTargetTypes.length > 0 ? { recallTargetTypes } : {}),+ };++ if (!slot.activated && slot.previousOwner) {+ return {+ success: false,+ action: "slot_blocked",+ config: resultConfig,+ health,+ keyProbe,+ slot,+ error: `contextEngine slot is owned by "${slot.previousOwner}". Config was saved but slot was NOT changed. Use --force-slot to replace.`,+ };+ }++ return {+ success: true,+ action: "configured",+ config: resultConfig,+ health,+ keyProbe,+ slot,+ };+ } catch (err) {+ return {+ success: false,+ action: "error",+ slot: { activated: false, replaced: false },+ error: String(err instanceof Error ? err.message : err),+ };+ }+ },++ async saveInteractiveRemoteConfig(+ configPath: string,+ params: InteractiveRemoteConfigParams,+ ): Promise<InteractiveRemoteConfigResult> {+ const pluginCfg = buildInteractiveRemotePluginConfig(params);+ writeOpenVikingConfig(configPath, pluginCfg, io);+ const slot = activateContextEngineSlot(configPath, !!params.forceSlot, io);+ return { config: pluginCfg, slot };+ },++ async useExistingRemoteConfig(configPath: string, existing: Record<string, unknown>): Promise<SetupResult> {+ const baseUrl = String(existing.baseUrl ?? defaultRemoteUrl);+ const apiKey = existing.apiKey ? String(existing.apiKey) : undefined;+ const health = await checkServiceHealth(baseUrl, apiKey);+ const slot = activateContextEngineSlot(configPath, false, io);+ return {+ success: true,+ action: "existing",+ config: {+ mode: String(existing.mode ?? "remote"),+ baseUrl,+ ...(apiKey ? { apiKey: maskKey(apiKey) } : {}),+ ...(existing.peer_role ? { peer_role: String(existing.peer_role) as "none" | "assistant" | "person" } : {}),+ ...(existing.peer_prefix ? { peer_prefix: String(existing.peer_prefix) } : {}),+ ...(existing.accountId ? { accountId: String(existing.accountId) } : {}),+ ...(existing.userId ? { userId: String(existing.userId) } : {}),+ },+ health,+ slot,+ };+ },++ async getStatus(configPath: string): Promise<StatusResult> {+ const config = io.readConfig(configPath);+ const existing = getExistingPluginConfig(config);+ const slotActive = isContextEngineSlotActive(configPath, io);++ if (!existing) {+ return { configured: false, slotActive };+ }++ const baseUrl = String(existing.baseUrl ?? defaultRemoteUrl);+ const apiKey = existing.apiKey ? String(existing.apiKey) : undefined;+ const health = await checkServiceHealth(baseUrl, apiKey);+ const keyProbe = health.ok ? await probeApiKeyType(baseUrl, apiKey) : undefined;++ return {+ configured: true,+ config: {+ mode: String(existing.mode ?? "remote"),+ baseUrl,+ hasApiKey: !!existing.apiKey,+ ...(existing.peer_role ? { peer_role: String(existing.peer_role) as "none" | "assistant" | "person" } : {}),+ ...(existing.peer_prefix ? { peer_prefix: String(existing.peer_prefix) } : {}),+ hasAccountId: !!existing.accountId,+ hasUserId: !!existing.userId,+ },+ health,+ keyProbe,+ slotActive,+ };+ },+ };+}diff --git a/examples/openclaw-plugin/services/setup/version-compatibility.ts b/examples/openclaw-plugin/services/setup/version-compatibility.tsnew file mode 100644index 000000000..20ea1b32b--- /dev/null+++ b/examples/openclaw-plugin/services/setup/version-compatibility.ts@@ -0,0 +1,41 @@+export type VersionCompatibility = "compatible" | "server_too_old" | "server_too_new" | "unknown";++export type VersionCompatibilityRange = {+ min?: string;+ max?: string;+};++export function parseVersionTuple(v: string): number[] | null {+ const cleaned = v.replace(/^v/i, "").split("-")[0];+ const parts = cleaned.split(".").map(Number);+ if (parts.some(isNaN)) return null;+ return parts;+}++export function compareVersions(a: number[], b: number[]): number {+ const len = Math.max(a.length, b.length);+ for (let i = 0; i < len; i++) {+ const diff = (a[i] ?? 0) - (b[i] ?? 0);+ if (diff !== 0) return diff;+ }+ return 0;+}++export function checkVersionCompatibility(+ serverVersion: string,+ { min, max }: VersionCompatibilityRange,+): VersionCompatibility {+ if (!serverVersion) return "unknown";+ const sv = parseVersionTuple(serverVersion);+ if (!sv) return "unknown";++ if (min) {+ const minV = parseVersionTuple(min);+ if (minV && compareVersions(sv, minV) < 0) return "server_too_old";+ }+ if (max) {+ const maxV = parseVersionTuple(max);+ if (maxV && compareVersions(sv, maxV) > 0) return "server_too_new";+ }+ return "compatible";+}diff --git a/examples/openclaw-plugin/session-transcript-repair.ts b/examples/openclaw-plugin/session-transcript-repair.tsindex ec5ab6b0d..9fe19cda3 100644--- a/examples/openclaw-plugin/session-transcript-repair.ts+++ b/examples/openclaw-plugin/session-transcript-repair.ts@@ -191,8 +191,6 @@ function normalizeToolResultName(return message;}-export { makeMissingToolResult };-export type ToolCallInputRepairReport = {messages: AgentMessage[];droppedToolCalls: number;diff --git a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.mdindex f94a6e036..17b6c7b79 100644--- a/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md+++ b/examples/openclaw-plugin/skills/install-openviking-memory/SKILL.md@@ -13,7 +13,7 @@ description: >The user does NOT need to know any CLI commands — the agent runs everything and only asks for a few values.This skill assumes the OpenViking server is already running. If the server is not ready, the skilltells the user to contact their admin or set it up via the OpenViking docs — it does NOT install the server.-version: 2026.6.12+version: 2026.6.5metadata:openclaw:requires:@@ -109,7 +109,7 @@ Send this message:> 我需要 3 条信息,不知道的可以问你的管理员:> 1. **OpenViking 服务地址** —— 例如 `https://ov.example.com` 或 `http://192.168.1.100:1933`,本机服务可以直接说"本机"> 2. **API Key** —— 用来鉴权;服务没开认证可以说"没有"-> 3. **Peer 标识设置**(可选) —— 需要区分多个 assistant/sender 时才配置;默认不用填+> 3. **Agent 标识前缀**(可选) —— 用于区分多个 agent 的记忆命名空间,留空就用默认>> 先告诉我服务地址吧?@@ -118,7 +118,7 @@ Send this message:> I need 3 things (ask your admin if unsure):> 1. **OpenViking server URL** — e.g. `https://ov.example.com` or `http://192.168.1.100:1933`. For a local server, just say "local".> 2. **API Key** — for auth. Say "none" if the server has no auth.-> 3. **Peer identity settings** (optional) — configure only if you need to separate multiple assistants/senders. Leave blank for default.+> 3. **peer prefix** (optional) — used to namespace memories across agents. Leave blank for default.>> What's the server URL?@@ -141,23 +141,16 @@ Collect 3 values through natural conversation. Be flexible: if the user gives se> (CN) API Key 是什么?服务没开认证就直接说"没有"。> (EN) What's the API Key? Say "none" if the server has no auth.-- If the user says "none", "no key", "没有", or "不开认证", leave it empty.-- If they paste a key, keep it in memory only for command execution. Do **not** echo it back.-- If they are unsure whether the key is a root key, continue. STEP 7 detects that and asks for tenant IDs if needed.+- "no" / "none" / "没有" / "空" / empty → `API_KEY=""` (you will skip the flag later).+- Otherwise store as-is.-### 4c. `PEER_ROLE` / `PEER_PREFIX` (OPTIONAL)+### 4c. `PEER_PREFIX` (OPTIONAL)-Default to assistant peer scoping: `peer_role=assistant` and empty `peer_prefix`.+> (CN) 想给这个 agent 一个记忆前缀吗?留空就用默认。只能用字母、数字、`_`、`-`。+> (EN) Want to set an peer prefix? Leave blank for the default. Letters, digits, `_`, `-` only.-Only collect peer settings when the user explicitly wants multiple OpenClaw assistants or senders to be separated:--- For assistant-specific memory routing, use `--peer-role assistant`.-- To disable peer routing, use `--peer-role none`.-- For sender-specific memory routing, use `--peer-role person`.-- If they provide a prefix such as `openclaw-prod`, pass it as `--peer-prefix openclaw-prod`.-- `peer_prefix` may contain only letters, digits, `_`, and `-`.--Do not use legacy agent routing flags. Current plugin config uses `peer_role` / `peer_prefix`.+- Empty / "default" / "默认" → leave unset (plugin defaults to `""`).+- Otherwise validate against `/^[A-Za-z0-9_-]+$/`. If invalid, ask again.### 4d. (Conditional) Multi-Tenant Root-Key Fields@@ -269,14 +262,14 @@ Tell the user:Run the installer with `npx` (no global install needed):```bash-npx -y openclaw-openviking-setup-helper@latest --base-url BASE_URL [--api-key API_KEY] [--peer-role PEER_ROLE] [--peer-prefix PEER_PREFIX] [--account-id ACCOUNT_ID] [--user-id USER_ID]+npx -y openclaw-openviking-setup-helper@latest --base-url BASE_URL [--api-key API_KEY] [--peer-prefix PEER_PREFIX] [--account-id ACCOUNT_ID] [--user-id USER_ID]```Build the flag list according to what the user gave you:- Always pass `--base-url BASE_URL`.- Pass `--api-key API_KEY` only if `API_KEY` is non-empty.-- Pass `--peer-role` / `--peer-prefix` only if the user explicitly wants peer IDs. Default is no peer IDs.+- Pass `--peer-prefix PEER_PREFIX` only if the user gave one.- `--account-id` / `--user-id` only if the root-key path requires them.`ov-install` will, in one shot:@@ -297,14 +290,14 @@ If `ov-install` exits non-zero, capture the last 30 lines of its output, show thRun the setup wizard non-interactively. Build flags from collected values:```bash-openclaw openviking setup --base-url BASE_URL --json [--api-key API_KEY] [--peer-role PEER_ROLE] [--peer-prefix PEER_PREFIX] [--account-id ACCOUNT_ID] [--user-id USER_ID] [--allow-offline] [--force-slot]+openclaw openviking setup --base-url BASE_URL --json [--api-key API_KEY] [--peer-prefix PEER_PREFIX] [--account-id ACCOUNT_ID] [--user-id USER_ID] [--allow-offline] [--force-slot]```Rules:- `--base-url BASE_URL` is **required** under `--json`. Without it, the wizard prints `--json requires --base-url for non-interactive mode`.- `--api-key` only if `API_KEY` is non-empty.-- `--peer-role` / `--peer-prefix` only if the user explicitly wants peer IDs. Default is `--peer-role none`.+- `--peer-prefix` only if the user gave one. Use **`--peer-prefix`** for assistant peer prefixes; the old ID-style setup flag is no longer supported.- `--account-id` / `--user-id` only after STEP 7 root-key detection (see below).- `--allow-offline` only if the user explicitly approved it in STEP 5.- `--force-slot` **never** in the first attempt. Add only after the user confirms (see slot_blocked handling below).@@ -317,10 +310,10 @@ The wizard prints a single JSON object:{"success": true | false,"action": "configured" | "existing" | "error" | "slot_blocked",- "config": { "mode": "remote", "baseUrl": "...", "apiKey": "...", "peer_role": "none|assistant|person", "peer_prefix": "...", "accountId": "...", "userId": "..." },- "health": { "ok": true, "status": 200 },- "keyProbe": { "keyType": "user_key" | "root_key" | "none", "ok": true },- "slot": { "ok": true, "owner": "openviking" },+ "config": { "mode": "remote", "baseUrl": "...", "apiKey": "...", "peer_prefix": "...", "accountId": "...", "userId": "..." },+ "health": { "ok": true, "version": "...", "compatibility": "compatible" | "server_too_old" | "server_too_new" | "unknown" },+ "keyProbe": { "keyType": "user_key" | "root_key" | "no_key" | "unknown", "needsAccountId": false, "needsUserId": false, "detail": "..." },+ "slot": { "activated": true, "replaced": false, "previousOwner": "openviking" },"error": "..."}```@@ -333,7 +326,7 @@ The wizard prints a single JSON object:| `success: false` and `action: "slot_blocked"` | **Slot conflict — see below.** || `success: false` and `error` contains `"Server unreachable"` | Connectivity broke between STEP 5 and STEP 7. Offer `--allow-offline`; if accepted, retry. Otherwise back to STEP 4a. || `success: false` and `error` contains `"Root API key detected"` and `"Missing: --account-id, --user-id"` | **Root-key path — see below.** |-| `success: false` and `error` contains `"Invalid API key"` / `keyProbe.keyType: "none"` with `ok: false` | API key wrong. Back to STEP 4b. |+| `success: false` and `error` contains `"Invalid API key"` / `keyProbe.keyType: "unknown"` after auth failure detail | API key wrong. Back to STEP 4b. || `success: false` and any other `action: "error"` | Show `error` to the user, stop. Do NOT pretend success. |### Slot conflict (`slot_blocked`)@@ -404,7 +397,7 @@ Expected output:"configured": true,"slotActive": true,"health": { "ok": true },- "config": { "baseUrl": "...", "peer_role": "assistant", "peer_prefix": "..." }+ "config": { "baseUrl": "...", "peer_prefix": "..." }}```@@ -420,22 +413,20 @@ Expected output:> (CN) 🎉 全部搞定!OpenViking 长期记忆已经接好了。>> 工作方式:-> - **每一轮**:你的对话会被自动追加到 OpenViking session 里;自动抽取依赖阈值 commit 或 `/compact`-> - **明确要记住时**:如果你说“记住/保存/存一下”某个长期事实,我会用 `memory_store` 立即提交到记忆管线-> - **`/compact` 时**:待提交的 session 消息会被抽取成长期记忆,写到 `~/.openviking/data/` 下+> - **每一轮**:你的对话会被自动归档到 OpenViking session 里+> - **`/compact` 时**:归档消息会在 OpenViking 服务端被抽取成长期记忆> - **后续会话**:每次回复前我都会自动搜一下相关记忆并带进上下文>-> 想验证一下吗?可以直接说“记住我的邮箱是 [email protected]”,让我通过 `memory_store` 立即提交;或者先聊几句包含可记忆事实的话,再调一下 `/compact`。之后开新对话问“我的邮箱是?”,应该就能召回了。+> 想验证一下吗?跟我聊几句包含可记忆事实的话(例如"我的邮箱是 [email protected]"),然后调一下 `/compact`,再开新对话问"我的邮箱是?",应该就能召回了。> (EN) 🎉 All set! OpenViking long-term memory is connected.>> How it works:-> - **Every turn**: our messages are appended to an OpenViking session; automatic extraction depends on a threshold commit or `/compact`-> - **Explicit remember requests**: if you ask me to remember/save/store a long-term fact, I can use `memory_store` to commit it immediately-> - **On `/compact`**: pending session messages are extracted into long-term memories under `~/.openviking/data/`+> - **Every turn**: our messages are auto-archived into an OpenViking session+> - **On `/compact`**: archived messages are extracted into long-term memories on the OpenViking server> - **Future sessions**: relevant memories are auto-retrieved and injected before my replies>-> Want to verify? Say "remember my email is [email protected]" so I can commit it via `memory_store`, or tell me a few memory-worthy facts and run `/compact`. Then start a new chat and ask "what's my email?" — it should recall.+> Want to verify? Tell me a few facts (e.g. "my email is [email protected]"), run `/compact`, then start a new chat and ask "what's my email?" — it should recall.---@@ -443,25 +434,15 @@ Expected output:## How It Works-The context-engine pipeline has three distinct stages plus one explicit write path — keep them apart, especially when telling users when memories actually appear in `~/.openviking/data/`:+The context-engine pipeline has three distinct stages — keep them apart, especially when telling users when memories become searchable long-term memory on the OpenViking server:-- **Archive / capture (context-engine `afterTurn`)**: at the end of a user turn, the plugin appends user/assistant messages to the OpenViking session via `POST /api/v1/sessions/.../messages`. This is **session capture only** unless `pending_tokens` crosses `commitTokenThreshold`; below the threshold, no memory extraction runs yet. You'll see session message counts grow on the server, but no new files under `viking://user/.../memories/`.-- **Memory extraction (threshold commit or `/compact`)**: memory extraction runs after a session commit. The commit can be triggered asynchronously when `afterTurn` crosses `commitTokenThreshold`, synchronously when the user invokes OpenClaw's `/compact` command, or explicitly by `memory_store`. The server-side extraction pipeline reads the archived session and writes new memories.+- **Archive / capture (context-engine `afterTurn`)**: at the end of a user turn, the plugin commits user/assistant messages to the OpenViking session via `POST /api/v1/sessions/.../messages`. This is **archive only** — no memory extraction yet. You'll see session message counts grow on the server, but no new files under `viking://user/.../memories/`.+- **Memory extraction (on `/compact`)**: memory extraction runs when the user invokes OpenClaw's `/compact` command. The server-side extraction pipeline reads the archived session and writes new memories. The plugin's `after_compaction` hook is currently reserved; the extraction itself is driven by the server. **No `/compact`, no new memory files.**- `captureMode: "semantic"` (default): server extraction pipeline filters all qualifying text.- `captureMode: "keyword"`: only text matching trigger words (e.g. "remember", "preference") is considered.- **Auto-Recall (context-engine `assemble()`)**: before prompt context is assembled, the plugin queries OpenViking for relevant memories and injects them into context. Recall works even when there are no extracted memories yet — you just won't see anything come back.-**Practical implication for testing**: if you write down a short fact and immediately try to recall it without a threshold commit, `/compact`, or `memory_store`, the plugin may only retrieve it as recent session context, not as a long-term memory. To verify long-term memory cross-session deterministically, run `/compact` or use `memory_store` for the fact being tested.--### Explicit long-term memory writes--Auto-capture is best-effort and commit-dependent. When the user explicitly says to remember, save, or store an important long-term fact, preference, project, or decision, the agent should call `memory_store` instead of waiting for ordinary auto-capture.--Use `memory_store` as the integration-side reliable path for durable-memory intent:--- It writes the supplied text into an OpenViking session and calls `commit(wait=true)`.-- It complements auto-capture; it does not replace normal session capture.-- If it commits but extracts 0 memories, the explicit path has done its job. Treat that as a server-side extraction/model/configuration issue and check OpenViking logs.+**Practical implication for testing**: if you write down a fact and immediately try to recall it without `/compact`, the plugin will only retrieve it as recent session context (archived messages), not as a long-term memory. To verify long-term memory cross-session, you must run `/compact` first.## Available Tools@@ -474,7 +455,8 @@ These are the plugin tools the agent can call once installed.| `query` | Yes | Search query text || `limit` | No | Maximum number of results (defaults to plugin config) || `scoreThreshold` | No | Minimum relevance score 0–1 (defaults to plugin config) |-| `targetUri` | No | Search scope URI (defaults to plugin config) |+| `targetUri` | No | Exact search scope URI. If provided, only that URI is searched. |+| `resourceTypes` | No | Array of target types used when `targetUri` is omitted: `resource`, `user`, `agent`. Defaults to plugin `recallTargetTypes`. |Example: user asks "What programming language did I say I like?"@@ -486,8 +468,6 @@ Example: user asks "What programming language did I say I like?"| `role` | No | Session role (default `user`) || `sessionId` | No | Existing OpenViking session ID |-Use this when the user explicitly asks to remember/save/store a long-term fact, preference, project, or decision.-Example: user says "Remember my email is [email protected]".### `memory_forget` — Delete Memories@@ -502,6 +482,87 @@ Example: user says "Remember my email is [email protected]".Example: user says "Forget my phone number".+### `ov_archive_search` — Search Archived Original Messages++| Parameter | Required | Description |+|---|---|---|+| `query` | Yes | A single keyword or short phrase. Prefer concrete names, dates, commands, paths, or distinctive nouns. |+| `archiveId` | No | Optional archive ID such as `archive_002`. |++Use when `[Session History Summary]` is too coarse. Try at least two keyword variants before concluding the detail is unavailable.++### `ov_archive_expand` — Expand An Archive++| Parameter | Required | Description |+|---|---|---|+| `archiveId` | Yes | Archive ID from `[Archive Index]`, e.g. `archive_002`. |++### `add_resource` — Import Resource++The agent-visible `add_resource` tool is disabled by default (`enableAddResourceTool=false`). Use manual `/add-resource` for resource ingestion unless you explicitly opt in. Even when enabled, never use `add_resource` during search, retrieval, URI reading, or search-result optimization; use `ov_search` and `ov_read` for those flows.++| Parameter | Required | Description |+|---|---|---|+| `source` | Yes | Local path, OpenClaw media attachment path, directory path, public URL, or Git URL. |+| `to` | No | Exact target URI under `viking://resources`; mutually exclusive with `parent`. |+| `parent` | No | Parent URI under `viking://resources`; mutually exclusive with `to`. |+| `reason` | No | Reason or note for import. |+| `instruction` | No | Processing instruction for semantic extraction. |+| `wait` | No | Wait for processing completion. |+| `timeout` | No | Timeout in seconds when `wait=true`. |++### `add_skill` — Import Agent Skill++| Parameter | Required | Description |+|---|---|---|+| `source` | No | Local `SKILL.md` path or skill directory. Exactly one of `source` or `data` is required. |+| `data` | No | Raw `SKILL.md` content or MCP tool dict. Exactly one of `source` or `data` is required. |+| `wait` | No | Wait for processing completion. |+| `timeout` | No | Timeout in seconds when `wait=true`. |++Agent Skill best practice: verify frontmatter has a precise `name`, a trigger-oriented `description`, useful `tags`, explicit scope boundaries, and concrete execution steps. Do not include secrets in skill content.++### `ov_search` — Search Resources and Skills++| Parameter | Required | Description |+|---|---|---|+| `query` | Yes | Search query. |+| `uri` | No | Optional search URI. Defaults to resources plus agent skills. |+| `limit` | No | Max results per search scope. Default: 10. |++Important: `ov_search` result URIs are OpenViking virtual URIs, not local file paths. If full content is needed, call `ov_read` with the exact `viking://...` URI returned by search or trace results; do not use filesystem read tools.++### `ov_read` — Read OpenViking Content++| Parameter | Required | Description |+|---|---|---|+| `uri` | Yes | Exact `viking://...` URI returned by `ov_search` or recall trace results. Local file paths and `openviking://...` display aliases are refused. |++### `ov_recall_trace` — Query Recall Trace++| Parameter | Required | Description |+|---|---|---|+| `turn` | No | `latest` or `all`; default `latest`. |+| `traceId` | No | Exact trace ID. |+| `sessionId` / `sessionKey` / `ovSessionId` | No | Session filters. |+| `source` | No | `auto_recall`, `memory_recall`, `ov_search`, or `ov_archive_search`. |+| `resourceTypes` | No | Target type filters: `resource`, `user`, `agent`. |+| `since` / `until` | No | Unix timestamp bounds in milliseconds. |+| `includeContent` | No | Read selected/displayed URI content previews on demand. |+| `limit` | No | Maximum traces to return. Default: 20. |++Requires `traceRecall=true`; persisted lookup also requires `traceRecallPersist=true`.++### Externalized Tool Result Tools++Use these when a preview contains a `viking://session/<session_id>/tool-results/<tool_result_id>` ref.++| Tool | Parameters |+|---|---|+| `openviking_tool_result_list` | `tool_name?`, `limit?` (default 50) |+| `openviking_tool_result_search` | `tool_output_ref`, `query`, `limit?` (default 20), `context_chars?` (default 300) |+| `openviking_tool_result_read` | `tool_output_ref`, `offset?` (default 0), `limit?` (default 20000) |+## Configuration SchemaThese are the keys under `plugins.entries.openviking.config` in `openclaw.json`. The setup wizard / `ov-install` sets the first few; the rest are tunables.@@ -511,26 +572,32 @@ These are the keys under `plugins.entries.openviking.config` in `openclaw.json`.| `mode` | `"remote"` (forced by plugin) | Always remote in this skill. Don't set manually. || `baseUrl` | `http://127.0.0.1:1933` | OpenViking server URL. || `apiKey` | — | API key. Optional if server has no auth. |-| `peer_role` | `"assistant"` | Controls whether session messages include `peer_id`: `none`, `assistant`, or `person`. |-| `peer_prefix` | `""` | Optional prefix for assistant `peer_id` values when `peer_role=assistant`. |+| `peer_role` | `assistant` | Peer identity mode: `none`, `assistant`, or `person`. 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`. Letters / digits / `_` / `-`. || `accountId` | — | Required when `apiKey` is a root key. || `userId` | — | Required when `apiKey` is a root key. || `targetUri` | `viking://user/memories` | Default search scope URI. || `timeoutMs` | (plugin default) | HTTP timeout for OpenViking calls. |-| `autoCapture` | `true` | Auto-append turn messages to the OpenViking session at `afterTurn`; extraction runs only after a threshold commit, `/compact`, or explicit `memory_store`. |+| `autoCapture` | `true` | Auto-archive turn messages to OpenViking session at `afterTurn` (extraction itself runs on `/compact`, not here). || `captureMode` | `"semantic"` | Filter mode used by the server-side extraction pipeline: `semantic` or `keyword`. || `captureMaxLength` | `24000` | Max text length per archived turn. || `autoRecall` | `true` | Auto-recall and inject memories before reply. |-| `autoRecallTimeoutMs` | `5000` | Outer timeout for the whole auto-recall flow. Increase for slow local embedding hardware. |+| `recallTargetTypes` | `user,agent` | Default target types when `targetUri` is omitted. Allowed: `resource`, `user`, `agent`. |+| `recallResources` | `false` | Compatibility shortcut that appends `resource` to default recall targets when `recallTargetTypes` is unset. || `recallLimit` | `6` | Max memories injected per recall. || `recallScoreThreshold` | `0.15` | Min relevance score to inject. |-| `recallMaxInjectedChars` | (plugin default) | Hard cap on injected character count. |+| `recallMaxInjectedChars` | `4000` | Hard cap on injected character count. Complete memories that do not fit are skipped, not truncated. || `recallPreferAbstract` | (plugin default) | Prefer abstract memories over raw. |-| `recallTokenBudget` | (plugin default) | Token budget for injected memories. |+| `recallTokenBudget` | deprecated | Compatibility alias for `recallMaxInjectedChars`. |+| `commitTokenThreshold` | `20000` | Pending-token threshold for async commit after turns; `0` commits every turn. |+| `commitKeepRecentCount` | `10` | Recent messages kept live after afterTurn commit. Compact always uses `0`. || `bypassSessionPatterns` | — | Glob patterns for sessions skipped by capture. || `ingestReplyAssist` | (plugin default) | Reply-assist ingestion toggle. |-| `emitStandardDiagnostics` | (plugin default) | Verbose diagnostic logs. |-| `logFindRequests` | (plugin default) | Log retrieval requests. |+| `emitStandardDiagnostics` | `false` | Emit structured `openviking: diag {...}` lines. |+| `logFindRequests` | `false` | Log routing for find/session writes. Also enabled by `OPENVIKING_LOG_ROUTING=1` or `OPENVIKING_DEBUG=1`. |+| `traceRecall` | `false` | Record recall traces in memory. |+| `traceRecallPersist` | `false` | Persist recall traces to JSONL files. |+| `traceRecallDir` | `~/.openclaw/openviking/recall-traces` | Recall trace directory. |To change a value:@@ -665,7 +732,7 @@ Match against actual stderr / JSON `error` strings.| `Server unreachable: …. Use --allow-offline to save config anyway.` | Setup couldn't reach server | Offer `--allow-offline`. || `contextEngine slot is owned by "<x>". … Use --force-slot to replace.` | Slot conflict | Ask user, then retry with `--force-slot`. || `Root API key detected. Missing: --account-id, --user-id` | Multi-tenant key | Collect both, retry with `--account-id` `--user-id`. |-| `openviking: config parse failed` (in gateway log) | Bad value in `openclaw.json` | Show user; check `peer_role`, `peer_prefix` charset, URL format. |+| `openviking: config parse failed` (in gateway log) | Bad value in `openclaw.json` | Show user; check `peer_prefix` charset, URL format. || `extracted 0 memories` after a turn | Server VLM/embedding misconfigured | **Out of scope.** Tell user this is a server-side issue — ask their OpenViking admin to check VLM / embedding config. || `401` / `403` on plugin requests, but `/health` works | Server requires auth on API endpoints | Re-run STEP 7 with the correct `--api-key`. || Plugin doesn't appear in `openclaw plugins list` after Path A | Install didn't actually finish | Re-run Path A; use Path B only if the failure is registry/rate-limit related. |@@ -677,7 +744,7 @@ Match against actual stderr / JSON `error` strings.3. **Never silently use `--force-slot`.** Slot replacement disables another plugin — always confirm with the user first.4. **Never invent values.** If the user can't provide a required value, stop and tell them what to ask their admin.5. **Never claim success without STEP 10.** Only after `openclaw openviking status --json` shows `configured: true && slotActive: true && health.ok: true` may you tell the user it's done.-6. **Use `--peer-role` / `--peer-prefix` only for explicit peer routing.**+6. **Use `--peer-prefix` for assistant peer prefixes.** The old ID-style setup flag is no longer supported by the schema.7. **For Windows, use PowerShell equivalents.** Don't rely on `nohup`, `&`, `mkdir -p`, `source`, etc.8. **Switch to Path B (ov-install) only for ClawHub/rate-limit/registry availability failures.** Don't use it to hide version conflicts or package validation errors.9. **Do NOT install or operate the OpenViking server.** This skill assumes the server is already running. If it isn't, tell the user to contact their admin or follow the OpenViking docs.diff --git a/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md b/examples/openclaw-plugin/skills/openviking-context-database/SKILL.mdindex cd0c52adf..66c2d577d 100644--- a/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md+++ b/examples/openclaw-plugin/skills/openviking-context-database/SKILL.md@@ -2,15 +2,16 @@name: openviking-context-databasedescription: >Use OpenViking from OpenClaw through @openviking/openclaw-plugin: long-term memory,- session archives, resource and skill import, semantic recall, recall trace debugging,+ session archives, resource and Agent Skill import, semantic recall, recall trace debugging,and externalized tool-result recovery. Prefer this skill when the user wants to use, query,debug, or operate OpenViking context from an OpenClaw agent. For first-time plugin installation,use the install-openviking-memory skill instead.-version: 2026.6.12+version: 2026.6.5metadata:openclaw:requires:plugin: "@openviking/openclaw-plugin"+ emoji: "🦣"tags:- openviking- context-engine@@ -28,9 +29,9 @@ Use this skill after `@openviking/openclaw-plugin` is installed and configured.- The plugin is **remote-only**. It talks to an existing OpenViking server through HTTP and does not start or manage `openviking-server`.- Do not invent OpenViking REST endpoints. Use the registered OpenClaw tools and commands described below.-- The agent-visible `add_resource` tool is disabled by default (`enableAddResourceTool=false`). Do not use `add_resource` during search, retrieval, URI reading, or search-result optimization. Use `ov_search`, `ov_list`, `ov_read`, and `ov_multi_read` in those flows.+- The agent-visible `add_resource` tool is disabled by default (`enableAddResourceTool=false`). Do not use `add_resource` during search, retrieval, URI reading, or search-result optimization. Use `ov_search` and `ov_read` in those flows.- Use manual `/add-resource`, or `add_resource` only when it is explicitly enabled and the user explicitly asks to import, add, upload, save, or index a resource.-- Use `add_skill` only when the user explicitly asks to import, add, install, or register a skill into OpenViking.+- Use `add_skill` only when the user explicitly asks to import, add, install, or register an Agent Skill into OpenViking.- For local files and directories, pass the local path to the plugin tool. The plugin uploads them through `/api/v1/resources/temp_upload`; do not send raw local filesystem paths to a remote server yourself.- Never log or echo API keys. The plugin sends API keys as `X-API-Key` / setup probe headers and masks them in setup output.@@ -63,15 +64,15 @@ Core config lives under `plugins.entries.openviking.config`:|---|---:|---|| `baseUrl` | `http://127.0.0.1:1933` | OpenViking HTTP endpoint. Can also come from `OPENVIKING_BASE_URL` / `OPENVIKING_URL`. || `apiKey` | empty | Optional API key. Can also come from `OPENVIKING_API_KEY`. |-| `peer_role` | `assistant` | Controls which speaker identity is sent as OpenViking `peer_id`: `none`, `assistant`, or `person`. |-| `peer_prefix` | empty | Optional prefix for assistant `peer_id` values when `peer_role=assistant`; final value is `<prefix>_<OpenClaw ctx.agentId>`, sanitized. |+| `peer_role` | `assistant` | 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` / `userId` | empty | Advanced tenant identity headers for root-key or trusted deployments. || `targetUri` | `viking://user/memories` | Default search scope for legacy targeted memory search. || `autoCapture` | `true` | Append sanitized turn text to OpenViking sessions. || `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`; `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. |+| `recallTargetTypes` | `user,agent` | Default target types when `targetUri` is omitted. Allowed: `resource`, `user`, `agent`. || `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. |@@ -94,7 +95,7 @@ openclaw openviking setup --base-url <OPENVIKING_URL> --api-key <API_KEY> --jsonUseful variants:```bash-openclaw openviking setup --base-url <URL> --api-key <KEY> --peer-role assistant --peer-prefix openclaw-prod --json+openclaw openviking setup --base-url <URL> --api-key <KEY> --peer-prefix openclaw-prod --jsonopenclaw openviking setup --base-url <URL> --api-key <ROOT_KEY> --account-id <ACCOUNT_ID> --user-id <USER_ID> --jsonopenclaw openviking setup --base-url <URL> --api-key <KEY> --recall-target-types resource --jsonopenclaw openviking setup --base-url <URL> --api-key <KEY> --allow-offline --json@@ -110,11 +111,9 @@ openclaw openviking setup --base-url <URL> --api-key <KEY> --force-slot --json| “Forget X” | `memory_forget` || Summary lacks an exact command/path/snippet from old chat | `ov_archive_search`, then `ov_archive_expand` if needed || Import docs, PDFs, local dirs, URLs, Git repos, media attachments | manual `/add-resource`; `add_resource` only if `enableAddResourceTool=true` |-| Import/register a skill | `add_skill` |+| Import/register an Agent Skill | `add_skill` || Search imported resources or skills | `ov_search` |-| Inspect folders or sibling chunks from a search hit | `ov_list` || Read an exact `viking://...` hit from `ov_search` or recall trace | `ov_read` |-| Read several exact `viking://...` hits together | `ov_multi_read` || Explain why recall/search returned something | `ov_recall_trace` || A previous tool result shows only a preview/ref | `openviking_tool_result_list`, `openviking_tool_result_search`, `openviking_tool_result_read` |@@ -122,7 +121,7 @@ openclaw openviking setup --base-url <URL> --api-key <KEY> --force-slot --json### `memory_recall`-Semantic search over memories/resources. Session history is not a semantic recall target; use `ov_archive_search` and `ov_archive_expand` for archived conversation history.+Semantic search over memories/resources. Use archive tools for session history.| Parameter | Required | Description ||---|---|---|@@ -132,7 +131,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`, uses `context_type` filters for memory/resource searches, 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`, fetches more candidates than requested, deduplicates, filters leaf memories, reranks, and respects `recallMaxInjectedChars`.### `memory_store`@@ -197,7 +196,7 @@ The current OpenClaw tool exposes the parameters above. The underlying client al### `add_skill`-Import skills into `viking://user/skills/...`.+Import Agent Skills into `viking://user/skills/...`.| Parameter | Required | Description ||---|---|---|@@ -206,31 +205,20 @@ Import skills into `viking://user/skills/...`.| `wait` | No | Wait for processing completion. || `timeout` | No | Timeout in seconds when `wait=true`. |-Skill best practice: a skill should have precise frontmatter (`name`, trigger-oriented `description`, useful `tags`), clear scope boundaries, explicit “when not to use” guidance if needed, and executable steps with concrete parameters. Keep secrets out of skill content.+Agent Skill best practice: a skill should have precise frontmatter (`name`, trigger-oriented `description`, useful `tags`), clear scope boundaries, explicit “when not to use” guidance if needed, and executable steps with concrete parameters. Keep secrets out of skill content.### `ov_search`| Parameter | Required | Description ||---|---|---|| `query` | Yes | Search query. |-| `uri` | No | Search URI. Defaults to resources plus user skills. |+| `uri` | No | Search URI. Defaults to resources plus agent skills. || `limit` | No | Max results per scope, default `10`. |Use after importing resources/skills, or when the user asks to search OpenViking-managed knowledge.Important: `ov_search` returns OpenViking virtual URIs such as `viking://resources/project-docs/api.md#chunk-3`. These are not local file paths. Do not use filesystem read tools for them; call `ov_read` with the exact URI when full content is needed.-### `ov_list`--List entries under an OpenViking virtual URI. Use it after `ov_search` when a hit is part of a split document or when you need sibling chunks, overview files, or a quick directory inspection before reading exact content.--| Parameter | Required | Description |-|---|---|---|-| `uri` | Yes | Exact OpenViking URI to list, usually a parent under `viking://resources` or `viking://user/skills`. |-| `recursive` | No | Recursively list descendants. Default `false`. |-| `simple` | No | Request simplified listing output. Default `false`. |-| `limit` | No | Node limit. Default `100`. |-### `ov_read`Read full content for one exact OpenViking virtual URI through `/api/v1/content/read`.@@ -239,14 +227,6 @@ Read full content for one exact OpenViking virtual URI through `/api/v1/content/|---|---|---|| `uri` | Yes | Exact `viking://...` URI returned by `ov_search` or recall trace results. `openviking://...` aliases and local file paths are refused. |-### `ov_multi_read`--Read full content for several exact OpenViking virtual URIs. Use it when `ov_search` or `ov_list` returns several sibling chunks that must be read together before answering.--| Parameter | Required | Description |-|---|---|---|-| `uris` | Yes | Array of exact `viking://...` URIs. |-### `ov_recall_trace`| Parameter | Required | Description |@@ -255,7 +235,7 @@ Read full content for several exact OpenViking virtual URIs. Use it when `ov_sea| `traceId` | No | Exact trace ID. || `sessionId` / `sessionKey` / `ovSessionId` | No | Filter by OpenClaw/OpenViking session. || `source` | No | `auto_recall`, `memory_recall`, `ov_search`, or `ov_archive_search`. |-| `resourceTypes` | No | Array/string containing `resource`, `user`, or `agent`. Archive traces may still display `session` as a recorded trace category. |+| `resourceTypes` | No | Array/string containing `resource`, `user`, `agent`. || `since` / `until` | No | Unix timestamp bounds in milliseconds. || `includeContent` | No | Read selected/displayed URI content previews on demand. || `limit` | No | Maximum traces to return, default `20`. |@@ -264,7 +244,7 @@ Trace records exist only when `traceRecall=true`; persisted lookup requires `tra### Externalized tool-result tools-Use when a preview contains `viking://user/sessions/<session_id>/tool-results/<tool_result_id>`.+Use when a preview contains `viking://session/<session_id>/tool-results/<tool_result_id>`.| Tool | Parameters ||---|---|diff --git a/examples/openclaw-plugin/tests/context-bloat-730.test.ts b/examples/openclaw-plugin/tests/context-bloat-730.test.tsindex e2be3078f..456eda3d1 100644--- a/examples/openclaw-plugin/tests/context-bloat-730.test.ts+++ b/examples/openclaw-plugin/tests/context-bloat-730.test.ts@@ -2,6 +2,11 @@ import { describe, it, expect, vi } from "vitest";import type { FindResultItem } from "../client.js";import { postProcessMemories, pickMemoriesForInjection } from "../memory-ranking.js";import { memoryOpenVikingConfigSchema } from "../config.js";+import {+ buildMemoryLines,+ buildMemoryLinesWithBudget,+ estimateTokenCount,+} from "../auto-recall.js";/** Helper: create a mock FindResultItem */function mockMemory(overrides: Partial<FindResultItem> & { uri: string }): FindResultItem {@@ -53,8 +58,6 @@ describe("Slice A: recallScoreThreshold default", () => {describe("Slice B: prefer abstract over full content fetch", () => {it("should use abstract when available instead of calling read()", async () => {- const { buildMemoryLines } = await import("../index.js");-const mockRead = vi.fn().mockResolvedValue("Full long content from read()");const memories: FindResultItem[] = [@@ -86,8 +89,6 @@ describe("Slice B: prefer abstract over full content fetch", () => {describe("Slice D: individual memory integrity", () => {it("should keep full memory content intact", async () => {- const { buildMemoryLines } = await import("../index.js");-const longContent = "A".repeat(2000);const mockRead = vi.fn().mockResolvedValue(longContent);@@ -111,8 +112,6 @@ describe("Slice D: individual memory integrity", () => {describe("Slice E: character budget enforcement", () => {it("should stop injecting before the character budget is exceeded", async () => {- const { buildMemoryLinesWithBudget } = await import("../index.js");-// Each memory ~200 chars -> ~50 tokens per line (200 chars + "- [memory] " prefix)const memories: FindResultItem[] = Array.from({ length: 10 }, (_, i) =>mockMemory({@@ -139,14 +138,11 @@ describe("Slice E: character budget enforcement", () => {expect(estimatedTokens).toBeLessThanOrEqual(53);});- it("should estimate tokens with CJK-aware fallback weights", async () => {- const { estimateTokenCount } = await import("../index.js");+ it("should estimate tokens as ceil(chars/4)", async () => {expect(estimateTokenCount("")).toBe(0);expect(estimateTokenCount("abcd")).toBe(1);expect(estimateTokenCount("abcde")).toBe(2);expect(estimateTokenCount("A".repeat(100))).toBe(25);- expect(estimateTokenCount("\u4f60\u597d\u4e16\u754c")).toBe(6);- expect(estimateTokenCount("A\u4f60\ud83d\ude42")).toBe(4);});it("should have recallMaxInjectedChars in parsed config with default 4000-character budget", () => {diff --git a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/context-engine-assemble.test.tsindex 385242824..8aefd7db3 100644--- a/examples/openclaw-plugin/tests/context-engine-assemble.test.ts+++ b/examples/openclaw-plugin/tests/context-engine-assemble.test.ts@@ -3,7 +3,6 @@ import { describe, expect, it, vi } from "vitest";import type { OpenVikingClient } from "../client.js";import { memoryOpenVikingConfigSchema } from "../config.js";import { createMemoryOpenVikingContextEngine } from "../context-engine.js";-import { estimateAgentMessagesTokens, estimateTextTokens } from "../token-estimator.js";const cfg = memoryOpenVikingConfigSchema.parse({mode: "remote",@@ -15,11 +14,11 @@ const cfg = memoryOpenVikingConfigSchema.parse({});function roughEstimate(messages: unknown[]): number {- return estimateAgentMessagesTokens(messages);+ return Math.ceil(JSON.stringify(messages).length / 4);}function systemPromptTokens(text?: string): number {- return estimateTextTokens(text);+ return text ? Math.ceil(text.length / 4) : 0;}function makeLogger() {@@ -115,8 +114,8 @@ describe("context-engine assemble()", () => {tokenBudget: 4096,});- expect(resolveAgentId).not.toHaveBeenCalled();- expect(client.getSessionContext).toHaveBeenCalledWith("session-1", 4096);+ expect(resolveAgentId).toHaveBeenCalledWith("session-1", undefined, "session-1");+ expect(client.getSessionContext).toHaveBeenCalledWith("session-1", 4096, "agent:session-1");expect(result.estimatedTokens).toBe(roughEstimate(result.messages) + systemPromptTokens(result.systemPromptAddition),);diff --git a/examples/openclaw-plugin/tests/e2e/test-archive-expand.py b/examples/openclaw-plugin/tests/e2e/test-archive-expand.pyindex a638b1231..441011bc3 100644--- a/examples/openclaw-plugin/tests/e2e/test-archive-expand.py+++ b/examples/openclaw-plugin/tests/e2e/test-archive-expand.py@@ -205,6 +205,8 @@ USER_ID = f"xiaojie-{uuid.uuid4().hex[:8]}"DISPLAY_NAME = "小杰"DEFAULT_GATEWAY = "http://127.0.0.1:19789"DEFAULT_OPENVIKING = "http://127.0.0.1:2934"+AGENT_ID = "main"+console = Console(force_terminal=True)# ── 测试结果收集 ──────────────────────────────────────────────────────────@@ -376,11 +378,14 @@ def extract_reply_text(data: dict) -> str:class OVInspector:- def __init__(self, base_url: str):+ def __init__(self, base_url: str, agent_id: str = AGENT_ID):self.base_url = base_url.rstrip("/")+ self.agent_id = agent_iddef _headers(self) -> dict:h: dict[str, str] = {"Content-Type": "application/json"}+ if self.agent_id:+ h["X-OpenViking-Actor-Peer"] = self.agent_idreturn hdef _get(self, path: str, timeout: int = 10):@@ -1028,6 +1033,7 @@ def main():)parser.add_argument("--delay", type=float, default=3.0, help="轮次间等待秒数 (默认: 3)")parser.add_argument("--token", default="", help="Gateway auth token (默认: 自动发现)")+ parser.add_argument("--agent-id", default=AGENT_ID, help=f"Agent ID (默认: {AGENT_ID})")parser.add_argument("--gateway-restart-cmd",default="",diff --git a/examples/openclaw-plugin/tests/e2e/test-memory-chain.py b/examples/openclaw-plugin/tests/e2e/test-memory-chain.pyindex 2b431f1da..d43d15372 100644--- a/examples/openclaw-plugin/tests/e2e/test-memory-chain.py+++ b/examples/openclaw-plugin/tests/e2e/test-memory-chain.py@@ -148,6 +148,7 @@ USER_ID = f"test-chain-{uuid.uuid4().hex[:8]}"DISPLAY_NAME = "测试用户"DEFAULT_GATEWAY = "http://127.0.0.1:19789"DEFAULT_OPENVIKING = "http://127.0.0.1:2934"+AGENT_ID = "main"console = Console(force_terminal=True)@@ -320,14 +321,17 @@ def extract_reply_text(data: dict) -> str:class OpenVikingInspector:"""OpenViking 内部状态检查器。"""- def __init__(self, base_url: str, api_key: str = ""):+ def __init__(self, base_url: str, api_key: str = "", agent_id: str = AGENT_ID):self.base_url = base_url.rstrip("/")self.api_key = api_key+ self.agent_id = agent_iddef _headers(self) -> dict:h: dict[str, str] = {"Content-Type": "application/json"}if self.api_key:h["X-API-Key"] = self.api_key+ if self.agent_id:+ h["X-OpenViking-Actor-Peer"] = self.agent_idreturn hdef _get(self, path: str, timeout: int = 10) -> dict | None:@@ -1132,6 +1136,7 @@ def run_full_test(gateway_url: str, openviking_url: str, user_id: str, delay: fldef main():+ global AGENT_IDparser = argparse.ArgumentParser(description="OpenClaw 记忆链路完整测试",formatter_class=argparse.RawDescriptionHelpFormatter,@@ -1177,6 +1182,11 @@ def main():default="",help="Gateway auth token (默认: 自动从 openclaw.json 发现)",)+ parser.add_argument(+ "--agent-id",+ default=AGENT_ID,+ help=f"OpenViking agent ID (默认: {AGENT_ID})",+ )parser.add_argument("--verbose","-v",@@ -1192,6 +1202,8 @@ def main():token = args.token or discover_gateway_token()set_gateway_token(token)+ AGENT_ID = args.agent_id+console.print("[bold]OpenClaw 记忆链路测试[/bold]")console.print(f"[yellow]Gateway:[/yellow] {gateway_url}")console.print(f"[yellow]OpenViking:[/yellow] {openviking_url}")@@ -1204,17 +1216,17 @@ def main():elif args.phase == "afterTurn":_, _, _ = run_phase_after_turn(openviking_url, user_id, args.verbose)elif args.phase == "commit":- inspector = OpenVikingInspector(openviking_url)+ inspector = OpenVikingInspector(openviking_url, agent_id=AGENT_ID)sid = inspector.find_session_for_user(user_id) or user_idsession_info = inspector.get_session(sid)ac = (session_info.get("commit_count", 0) > 0) if session_info else Falserun_phase_commit(openviking_url, sid, args.verbose, ac)elif args.phase == "assemble":- inspector = OpenVikingInspector(openviking_url)+ inspector = OpenVikingInspector(openviking_url, agent_id=AGENT_ID)sid = inspector.find_session_for_user(user_id) or user_idrun_phase_assemble(gateway_url, openviking_url, user_id, sid, args.delay, args.verbose)elif args.phase == "session-id":- inspector = OpenVikingInspector(openviking_url)+ inspector = OpenVikingInspector(openviking_url, agent_id=AGENT_ID)sid = inspector.find_session_for_user(user_id) or user_idrun_phase_session_id(openviking_url, user_id, sid, args.verbose)elif args.phase == "recall":diff --git a/examples/openclaw-plugin/tests/e2e/test-tool-capture.py b/examples/openclaw-plugin/tests/e2e/test-tool-capture.pyindex 98e07a449..8332e4464 100644--- a/examples/openclaw-plugin/tests/e2e/test-tool-capture.py+++ b/examples/openclaw-plugin/tests/e2e/test-tool-capture.py@@ -112,6 +112,8 @@ if sys.platform == "win32":GATEWAY_URL = "http://127.0.0.1:19789"OPENVIKING_URL = "http://127.0.0.1:2934"+AGENT_ID = "main"+console = Console(force_terminal=True)assertions: list[dict] = []@@ -190,11 +192,14 @@ def has_tool_use_in_output(data: dict) -> bool:class OVInspector:- def __init__(self, base_url: str):+ def __init__(self, base_url: str, agent_id: str = AGENT_ID):self.base_url = base_url.rstrip("/")+ self.agent_id = agent_iddef _headers(self) -> dict:h: dict[str, str] = {"Content-Type": "application/json"}+ if self.agent_id:+ h["X-OpenViking-Actor-Peer"] = self.agent_idreturn hdef _get(self, path: str, timeout: int = 10):@@ -278,10 +283,11 @@ def run_test(delay: float,verbose: bool,token: str = "",+ agent_id: str = "",):if not token:token = load_gateway_token()- inspector = OVInspector(openviking_url)+ inspector = OVInspector(openviking_url, agent_id=agent_id or AGENT_ID)console.print(Panel(@@ -541,6 +547,9 @@ def main():parser.add_argument("--gateway", default=GATEWAY_URL, help="Gateway 地址")parser.add_argument("--openviking", default=OPENVIKING_URL, help="OpenViking 地址")parser.add_argument("--token", default="", help="Gateway auth token (默认: 自动发现)")+ parser.add_argument(+ "--agent-id", default=AGENT_ID, help=f"OpenViking agent ID (默认: {AGENT_ID})"+ )parser.add_argument("--delay", type=float, default=3.0, help="消息间延迟秒数")parser.add_argument("--verbose", "-v", action="store_true", help="详细输出")args = parser.parse_args()@@ -554,6 +563,7 @@ def main():delay=args.delay,verbose=args.verbose,token=args.token,+ agent_id=args.agent_id,)diff --git a/examples/openclaw-plugin/tests/test-memory-chain.py b/examples/openclaw-plugin/tests/test-memory-chain.pyindex 640e9f69c..01b04728c 100644--- a/examples/openclaw-plugin/tests/test-memory-chain.py+++ b/examples/openclaw-plugin/tests/test-memory-chain.py@@ -57,6 +57,8 @@ USER_ID = f"test-chain-{uuid.uuid4().hex[:8]}"DISPLAY_NAME = "测试用户"DEFAULT_GATEWAY = "http://127.0.0.1:18790"DEFAULT_OPENVIKING = "http://127.0.0.1:8000"+AGENT_ID = "openclaw"+console = Console()# ── 测试结果收集 ──────────────────────────────────────────────────────────@@ -149,14 +151,17 @@ def extract_reply_text(data: dict) -> str:class OpenVikingInspector:"""OpenViking 内部状态检查器。"""- def __init__(self, base_url: str, api_key: str = ""):+ def __init__(self, base_url: str, api_key: str = "", agent_id: str = AGENT_ID):self.base_url = base_url.rstrip("/")self.api_key = api_key+ self.agent_id = agent_iddef _headers(self) -> dict:h: dict[str, str] = {"Content-Type": "application/json"}if self.api_key:h["X-API-Key"] = self.api_key+ if self.agent_id:+ h["X-OpenViking-Actor-Peer"] = self.agent_idreturn hdef _get(self, path: str, timeout: int = 10) -> dict | None:diff --git a/examples/openclaw-plugin/tests/test-tool-capture.py b/examples/openclaw-plugin/tests/test-tool-capture.pyindex 47a2dfebd..dc3b0b627 100644--- a/examples/openclaw-plugin/tests/test-tool-capture.py+++ b/examples/openclaw-plugin/tests/test-tool-capture.py@@ -33,6 +33,8 @@ from rich.table import TableGATEWAY_URL = "http://127.0.0.1:18789"OPENVIKING_URL = "http://127.0.0.1:1933"+AGENT_ID = "openclaw"+console = Console()assertions: list[dict] = []@@ -99,11 +101,14 @@ def has_tool_use_in_output(data: dict) -> bool:class OVInspector:- def __init__(self, base_url: str):+ def __init__(self, base_url: str, agent_id: str = AGENT_ID):self.base_url = base_url.rstrip("/")+ self.agent_id = agent_iddef _headers(self) -> dict:h: dict[str, str] = {"Content-Type": "application/json"}+ if self.agent_id:+ h["X-OpenViking-Actor-Peer"] = self.agent_idreturn hdef _get(self, path: str, timeout: int = 10):diff --git a/examples/openclaw-plugin/tests/ut/architecture-boundaries.test.ts b/examples/openclaw-plugin/tests/ut/architecture-boundaries.test.tsnew file mode 100644index 000000000..3b8c9b3a6--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/architecture-boundaries.test.ts@@ -0,0 +1,997 @@+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { join, relative } from "node:path";+import { describe, expect, it } from "vitest";++const rootDir = join(__dirname, "../..");++function collectTypeScriptFiles(dir: string): string[] {+ if (!existsSync(dir)) {+ return [];+ }++ const files: string[] = [];+ for (const entry of readdirSync(dir)) {+ const fullPath = join(dir, entry);+ const stat = statSync(fullPath);+ if (stat.isDirectory()) {+ files.push(...collectTypeScriptFiles(fullPath));+ continue;+ }+ if (entry.endsWith(".ts")) {+ files.push(fullPath);+ }+ }+ return files;+}++function collectSourceFiles(dir: string, extensions: string[]): string[] {+ if (!existsSync(dir)) {+ return [];+ }++ const files: string[] = [];+ for (const entry of readdirSync(dir)) {+ const fullPath = join(dir, entry);+ const stat = statSync(fullPath);+ if (stat.isDirectory()) {+ files.push(...collectSourceFiles(fullPath, extensions));+ continue;+ }+ if (extensions.some((extension) => entry.endsWith(extension))) {+ files.push(fullPath);+ }+ }+ return files;+}++function importSpecifiers(source: string): string[] {+ const staticImports = Array.from(+ source.matchAll(/\b(?:import|export)\s+(?:type\s+)?(?:[^"']+\s+from\s+)?["']([^"']+)["']/g),+ (match) => match[1],+ );+ const dynamicImports = Array.from(+ source.matchAll(/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g),+ (match) => match[1],+ );+ const requires = Array.from(+ source.matchAll(/\brequire\s*\(\s*["']([^"']+)["']\s*\)/g),+ (match) => match[1],+ );+ return [...new Set([...staticImports, ...dynamicImports, ...requires])];+}++describe("architecture boundaries", () => {+ it("keeps the test suite off global fetch stubbing", () => {+ const violations = collectSourceFiles(join(rootDir, "tests"), [".ts", ".tsx", ".js", ".mjs", ".cjs"])+ .filter((file) => readFileSync(file, "utf8").match(/vi\.stubGlobal\(\s*["']fetch["']/m))+ .map((file) => relative(rootDir, file));++ expect(violations).toEqual([]);+ });++ it("keeps tests from carrying stale global fetch cleanup after transport seam migration", () => {+ const violations = collectSourceFiles(join(rootDir, "tests"), [".ts", ".tsx", ".js", ".mjs", ".cjs"])+ .flatMap((file) => {+ const source = readFileSync(file, "utf8");+ const relativePath = relative(rootDir, file);+ if (relativePath === "tests/ut/architecture-boundaries.test.ts") {+ return [];+ }+ const fileViolations: string[] = [];+ if (source.match(/vi\.unstubAllGlobals\(\)/) && !source.match(/vi\.stubGlobal\(/)) {+ fileViolations.push(`${relativePath} removes globals without stubbing globals`);+ }+ if (source.match(/mock(?: at the)? fetch|mock fetch|override the global fetch/i)) {+ fileViolations.push(`${relativePath} still documents global fetch mocking`);+ }+ return fileViolations;+ });++ expect(violations).toEqual([]);+ });++ it("parses dynamic import and require edges for boundary checks", () => {+ const imports = importSpecifiers(`+ import { readOpenClawConfig } from "../services/setup/config-writer.js";+ export * from "../routing/identity-routing.js";+ const root = await import("../index.js");+ const client = require("../client.js");+ `);++ expect(imports).toEqual(expect.arrayContaining([+ "../services/setup/config-writer.js",+ "../routing/identity-routing.js",+ "../index.js",+ "../client.js",+ ]));+ });++ it("keeps extracted architecture modules from importing the composition root", () => {+ const checkedDirs = ["registries", "routing", "plugin", "services", "adapters"];+ const violations: string[] = [];++ for (const dir of checkedDirs) {+ for (const file of collectTypeScriptFiles(join(rootDir, dir))) {+ const imports = importSpecifiers(readFileSync(file, "utf8"));+ for (const specifier of imports) {+ if (specifier === "../index.js" || specifier.endsWith("/index.js")) {+ violations.push(`${relative(rootDir, file)} -> ${specifier}`);+ }+ }+ }+ }++ expect(violations).toEqual([]);+ });++ it("keeps registry modules independent from runtime composition and client modules", () => {+ const violations: string[] = [];++ for (const file of collectTypeScriptFiles(join(rootDir, "registries"))) {+ const imports = importSpecifiers(readFileSync(file, "utf8"));+ for (const specifier of imports) {+ if (specifier === "../index.js" || specifier.endsWith("/index.js") || specifier === "../client.js" || specifier.endsWith("/client.js")) {+ violations.push(`${relative(rootDir, file)} -> ${specifier}`);+ }+ }+ }++ expect(violations).toEqual([]);+ });++ it("keeps recall resource type consumers wired to the registry instead of the recall-trace compatibility facade", () => {+ const violations = collectTypeScriptFiles(rootDir)+ .filter((file) => {+ const relativePath = relative(rootDir, file);+ return !relativePath.startsWith("tests/") && relativePath !== "recall-trace.ts";+ })+ .filter((file) => {+ const source = readFileSync(file, "utf8");+ return Array.from(source.matchAll(/import\s+\{([^{}]*?)\}\s+from\s+["']\.\/recall-trace\.js["']/g))+ .concat(Array.from(source.matchAll(/import\s+type\s+\{([^{}]*?)\}\s+from\s+["']\.\.\/recall-trace\.js["']/g)))+ .some((match) => match[1]?.match(/\b(?:normalizeResourceTypes|resolveRecallSearchPlan|RecallResourceType)\b/));+ })+ .map((file) => `${relative(rootDir, file)} imports recall resource helpers from recall-trace.js`);++ expect(violations).toEqual([]);+ });++ it("keeps dead recall-trace resource helper compatibility exports removed", () => {+ const recallTraceSource = readFileSync(join(rootDir, "recall-trace.ts"), "utf8");+ const recallResourceTestSource = readFileSync(join(rootDir, "tests/ut/recall-resource-types.test.ts"), "utf8");+ const recallTraceTestSource = readFileSync(join(rootDir, "tests/ut/recall-trace.test.ts"), "utf8");++ expect(recallTraceSource).not.toMatch(/export\s+type\s+\{\s*RecallResourceType\s*\}/);+ expect(recallTraceSource).not.toMatch(/export\s+function\s+normalizeResourceTypes\b/);+ expect(recallTraceSource).not.toMatch(/export\s+function\s+resolveRecallSearchPlan\b/);+ expect(recallResourceTestSource).not.toMatch(/from\s+["']\.\.\/\.\.\/recall-trace\.js["']/);+ expect(recallTraceTestSource).not.toMatch(/\b(?:normalizeResourceTypes|resolveRecallSearchPlan)\b/);+ });++ it("keeps tool registry consumers wired to the registry instead of config compatibility exports", () => {+ const violations = collectSourceFiles(rootDir, [".ts"])+ .filter((file) => relative(rootDir, file) !== "config.ts")+ .flatMap((file) => {+ const source = readFileSync(file, "utf8");+ return Array.from(source.matchAll(/import\s+\{([^{}]*?OPENVIKING_[^{}]*?)\}\s+from\s+["'][^"']*config\.js["']/g))+ .map(() => relative(rootDir, file));+ });++ expect(violations).toEqual([]);+ });++ it("keeps production code off context-engine compatibility exports for message and routing helpers", () => {+ const compatibilityHelpers = [+ "convertToAgentMessages",+ "ensureAlternation",+ "formatMessageFaithful",+ "mergeConsecutiveAssistants",+ "mergeConsecutiveUsers",+ "toRoleId",+ "openClawSessionRefToOvStorageId",+ "openClawSessionToOvStorageId",+ ];+ const violations = collectTypeScriptFiles(rootDir)+ .filter((file) => {+ const relativePath = relative(rootDir, file);+ return !relativePath.startsWith("tests/") && relativePath !== "context-engine.ts";+ })+ .flatMap((file) => {+ const source = readFileSync(file, "utf8");+ return Array.from(source.matchAll(/import\s+\{([^{}]*?)\}\s+from\s+["']\.\/context-engine\.js["']/g))+ .flatMap((match) => {+ const importedNames = match[1] ?? "";+ return compatibilityHelpers+ .filter((helper) => importedNames.match(new RegExp(`\\b${helper}\\b`)))+ .map((helper) => `${relative(rootDir, file)} imports ${helper} from ./context-engine.js`);+ });+ });++ expect(violations).toEqual([]);+ });++ it("keeps tests off context-engine helper re-exports", () => {+ const compatibilityHelpers = [+ "convertToAgentMessages",+ "ensureAlternation",+ "formatMessageFaithful",+ "mergeConsecutiveAssistants",+ "mergeConsecutiveUsers",+ "toRoleId",+ "openClawSessionRefToOvStorageId",+ "openClawSessionToOvStorageId",+ ];+ const violations = collectSourceFiles(join(rootDir, "tests"), [".ts", ".tsx"])+ .flatMap((file) => {+ const source = readFileSync(file, "utf8");+ return Array.from(source.matchAll(/import\s+\{([^{}]*?)\}\s+from\s+["'][^"']*context-engine\.js["']/g))+ .flatMap((match) => {+ const importedNames = match[1] ?? "";+ return compatibilityHelpers+ .filter((helper) => importedNames.match(new RegExp(`\\b${helper}\\b`)))+ .map((helper) => `${relative(rootDir, file)} imports ${helper} from context-engine.js`);+ });+ });++ expect(violations).toEqual([]);+ });++ it("keeps dead context-engine helper compatibility re-exports removed", () => {+ const contextEngineSource = readFileSync(join(rootDir, "context-engine.ts"), "utf8");++ expect(contextEngineSource).not.toMatch(/export\s*\{[\s\S]*(?:convertToAgentMessages|ensureAlternation|formatMessageFaithful|mergeConsecutiveAssistants|mergeConsecutiveUsers|toRoleId)[\s\S]*\}\s*from\s*["']\.\/services\/context-message-adapter\.js["']/);+ expect(contextEngineSource).not.toMatch(/export\s*\{[\s\S]*(?:openClawSessionRefToOvStorageId|openClawSessionToOvStorageId)[\s\S]*\}\s*from\s*["']\.\/routing\/identity-routing\.js["']/);+ });++ it("keeps services independent from plugin adapters", () => {+ const violations: string[] = [];++ for (const file of collectTypeScriptFiles(join(rootDir, "services"))) {+ const imports = importSpecifiers(readFileSync(file, "utf8"));+ for (const specifier of imports) {+ if (specifier.includes("/plugin/") || specifier.startsWith("../plugin/")) {+ violations.push(`${relative(rootDir, file)} -> ${specifier}`);+ }+ }+ }++ expect(violations).toEqual([]);+ });++ it("keeps services independent from filesystem and network adapters", () => {+ const violations: string[] = [];++ for (const file of collectTypeScriptFiles(join(rootDir, "services"))) {+ const imports = importSpecifiers(readFileSync(file, "utf8"));+ for (const specifier of imports) {+ if (specifier.includes("/adapters/") || specifier.startsWith("../adapters/")) {+ violations.push(`${relative(rootDir, file)} -> ${specifier}`);+ }+ }+ }++ expect(violations).toEqual([]);+ });++ it("keeps adapters independent from business services", () => {+ const violations: string[] = [];++ for (const file of collectTypeScriptFiles(join(rootDir, "adapters"))) {+ const imports = importSpecifiers(readFileSync(file, "utf8"));+ for (const specifier of imports) {+ if (specifier.includes("/services/") || specifier.startsWith("../services/")) {+ violations.push(`${relative(rootDir, file)} -> ${specifier}`);+ }+ }+ }++ expect(violations).toEqual([]);+ });++ it("keeps setup CLI free of direct network fetch logic", () => {+ const setupSource = readFileSync(join(rootDir, "commands/setup.ts"), "utf8");++ expect(setupSource).not.toMatch(/\bfetch\s*\(/);+ expect(setupSource).not.toMatch(/\bAbortController\b/);+ });++ it("keeps setup tests off the legacy __test__ aggregate export", () => {+ const violations = collectSourceFiles(join(rootDir, "tests"), [".ts", ".tsx"])+ .filter((file) => readFileSync(file, "utf8").match(/import\s+\{\s*__test__\s*\}\s+from\s+["'][^"']*commands\/setup\.js["']/))+ .map((file) => relative(rootDir, file));++ expect(violations).toEqual([]);+ });++ it("keeps setup service helper tests off the setup command compatibility facade", () => {+ const setupCommandSource = readFileSync(join(rootDir, "commands/setup.ts"), "utf8");+ const setupCliTestSource = readFileSync(join(rootDir, "tests/ut/setup-cli.test.ts"), "utf8");++ expect(setupCommandSource).not.toMatch(/export\s*\{\s*isLegacyLocalMode\s*\}\s*from\s*["']\.\.\/services\/setup\/setup-flow\.js["']/);+ expect(setupCommandSource).not.toMatch(/export\s*\{[\s\S]*activateContextEngineSlot[\s\S]*\}\s*from\s*["']\.\.\/services\/setup\/config-writer\.js["']/);+ expect(setupCliTestSource).not.toMatch(/import\s*\{[\s\S]*(?:isLegacyLocalMode|activateContextEngineSlot|ensureInstallRecord|isContextEngineSlotActive)[\s\S]*\}\s*from\s*["']\.\.\/\.\.\/commands\/setup\.js["']/);+ });++ it("keeps non-interactive setup tests on the setup service seam", () => {+ const setupCommandSource = readFileSync(join(rootDir, "commands/setup.ts"), "utf8");+ const setupCommandTestSource = readFileSync(join(rootDir, "tests/ut/setup-command.test.ts"), "utf8");++ expect(setupCommandSource).not.toMatch(/export\s+const\s+setupNonInteractive\b/);+ expect(setupCommandTestSource).not.toMatch(/import\s*\{\s*setupNonInteractive\s*\}\s*from\s*["']\.\.\/\.\.\/commands\/setup\.js["']/);+ expect(setupCommandTestSource).toContain("createOpenVikingSetupService");+ });++ it("keeps setup pure helper tests on concrete setup modules", () => {+ const setupCommandSource = readFileSync(join(rootDir, "commands/setup.ts"), "utf8");+ const setupCliTestSource = readFileSync(join(rootDir, "tests/ut/setup-cli.test.ts"), "utf8");+ const helperNames = [+ "findPluginPackageRoot",+ "parseVersionTuple",+ "compareVersions",+ "checkVersionCompatibility",+ "setExitCodeOnFailure",+ ];++ for (const helperName of helperNames) {+ expect(setupCommandSource).not.toMatch(new RegExp(`export\\s+function\\s+${helperName}\\b`));+ }+ expect(setupCliTestSource).not.toMatch(/import\s*\{[\s\S]*(?:findPluginPackageRoot|parseVersionTuple|compareVersions|checkVersionCompatibility|setExitCodeOnFailure)[\s\S]*\}\s*from\s*["']\.\.\/\.\.\/commands\/setup\.js["']/);+ expect(setupCliTestSource).toContain("../../services/setup/package-metadata.js");+ expect(setupCliTestSource).toContain("../../services/setup/version-compatibility.js");+ });++ it("keeps temp upload body construction inside the resource packager seam", () => {+ const clientSource = readFileSync(join(rootDir, "client.ts"), "utf8");+ const packagerSource = readFileSync(join(rootDir, "adapters/resource-packager.ts"), "utf8");++ expect(clientSource).not.toMatch(/\breadFile\s*\(/);+ expect(clientSource).not.toMatch(/new\s+FormData\s*\(/);+ expect(clientSource).not.toMatch(/new\s+Blob\s*\(/);+ expect(clientSource).not.toMatch(/function\s+toBlobPart\s*\(/);+ expect(packagerSource).toContain("createTempUploadBody");+ });++ it("keeps memory URI classification on the routing seam instead of the client facade", () => {+ const clientSource = readFileSync(join(rootDir, "client.ts"), "utf8");+ const memoryToolSource = readFileSync(join(rootDir, "plugin/openviking-memory-tools.ts"), "utf8");+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");++ expect(clientSource).not.toMatch(/export\s+function\s+isMemoryUri\b/);+ expect(memoryToolSource).toContain("../routing/memory-uri.js");+ expect(memoryToolSource).not.toMatch(/import\s*\{[\s\S]*isMemoryUri[\s\S]*\}\s*from\s*["']\.\.\/client\.js["']/);+ expect(clientTestSource).not.toMatch(/import\s*\{[\s\S]*isMemoryUri[\s\S]*\}\s*from\s*["']\.\.\/\.\.\/client\.js["']/);+ expect(clientTestSource).toContain("../../routing/memory-uri.js");+ });++ it("keeps client request happy-path tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('it("addResource posts remote URL as path"');+ const end = clientTestSource.indexOf(' it("addResource uploads local file before posting temp_file_id"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const happyPathBlock = clientTestSource.slice(start, end);+ expect(happyPathBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(happyPathBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps local file addResource happy-path tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('it("addResource uploads local file before posting temp_file_id"');+ const end = clientTestSource.indexOf(' it("addResource zips local directory before upload"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const happyPathBlock = clientTestSource.slice(start, end);+ expect(happyPathBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(happyPathBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps local directory addResource tests on injected transport and resource packager seams", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('it("addResource zips local directory before upload"');+ const end = clientTestSource.indexOf(' it("addSkill uploads local SKILL.md file"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const directoryBlock = clientTestSource.slice(start, end);+ expect(directoryBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(directoryBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport[\s\S]*resourcePackager[\s\S]*\}/);+ expect(directoryBlock).toContain("prepareResourceSource");+ expect(directoryBlock).toContain("cleanup");+ });++ it("keeps local file addSkill tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('it("addSkill uploads local SKILL.md file"');+ const end = clientTestSource.indexOf(' it("addSkill removes temporary zip directory after uploading a skill directory"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const localSkillBlock = clientTestSource.slice(start, end);+ expect(localSkillBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(localSkillBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps local directory addSkill tests on injected transport and resource packager seams", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('it("addSkill removes temporary zip directory after uploading a skill directory"');+ const end = clientTestSource.indexOf(' it("addSkill posts raw skill data directly"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const directorySkillBlock = clientTestSource.slice(start, end);+ expect(directorySkillBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(directorySkillBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport[\s\S]*resourcePackager[\s\S]*\}/);+ expect(directorySkillBlock).toContain("prepareLocalUploadSource");+ expect(directorySkillBlock).toContain("cleanup");+ });++ it("keeps inline addSkill data tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('it("addSkill posts raw skill data directly"');+ const end = clientTestSource.indexOf(' it("addSkill posts MCP tool dict directly"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const inlineSkillBlock = clientTestSource.slice(start, end);+ expect(inlineSkillBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(inlineSkillBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps MCP addSkill data tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('it("addSkill posts MCP tool dict directly"');+ const end = clientTestSource.indexOf(' it("surfaces OpenViking error responses"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const mcpSkillBlock = clientTestSource.slice(start, end);+ expect(mcpSkillBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(mcpSkillBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps OpenViking error response client tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('it("surfaces OpenViking error responses"');+ const end = clientTestSource.indexOf(' it("uses an extended request timeout for wait=true imports"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const errorResponseBlock = clientTestSource.slice(start, end);+ expect(errorResponseBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(errorResponseBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps import timeout client tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const waitStart = clientTestSource.indexOf('it("uses an extended request timeout for wait=true imports"');+ const waitEnd = clientTestSource.indexOf(' it("still uses the default request timeout for non-wait imports"', waitStart);+ const nonWaitEnd = clientTestSource.indexOf(' it("keeps polling wait=true commit long enough for slow Phase 2 completion"', waitEnd);++ expect(waitStart).toBeGreaterThanOrEqual(0);+ expect(waitEnd).toBeGreaterThan(waitStart);+ expect(nonWaitEnd).toBeGreaterThan(waitEnd);++ const timeoutBlock = clientTestSource.slice(waitStart, nonWaitEnd);+ expect(timeoutBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(timeoutBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps commit polling client tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('it("keeps polling wait=true commit long enough for slow Phase 2 completion"');+ const end = clientTestSource.indexOf('});\n\ndescribe("OpenVikingClient tenant headers', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const commitPollingBlock = clientTestSource.slice(start, end);+ expect(commitPollingBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(commitPollingBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps tenant header client tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('describe("OpenVikingClient tenant headers');+ const end = clientTestSource.indexOf('describe("OpenVikingClient canonical namespace policy"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const tenantHeaderBlock = clientTestSource.slice(start, end);+ expect(tenantHeaderBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(tenantHeaderBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps canonical namespace client tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('describe("OpenVikingClient canonical namespace policy"');+ const end = clientTestSource.indexOf(' it("includes role_id when addSessionMessage receives one"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const canonicalNamespaceBlock = clientTestSource.slice(start, end);+ expect(canonicalNamespaceBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(canonicalNamespaceBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps addSessionMessage client tests on the injected transport seam", () => {+ const clientTestSource = readFileSync(join(rootDir, "tests/ut/client.test.ts"), "utf8");+ const start = clientTestSource.indexOf('it("includes role_id when addSessionMessage receives one"');+ const end = clientTestSource.indexOf('\n});', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const addSessionMessageBlock = clientTestSource.slice(start, end);+ expect(addSessionMessageBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(addSessionMessageBlock).toMatch(/new OpenVikingClient\([\s\S]*\{\s*transport\s*\}/);+ });++ it("keeps memory_recall L2 content tests on the plugin-injected transport seam", () => {+ const toolsTestSource = readFileSync(join(rootDir, "tests/ut/tools.test.ts"), "utf8");+ const start = toolsTestSource.indexOf('it("fills L2 content and filters explicit recall results like auto-recall"');+ const end = toolsTestSource.indexOf(' it("applies recallMaxInjectedChars to explicit memory_recall output"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const recallL2Block = toolsTestSource.slice(start, end);+ expect(recallL2Block).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(recallL2Block).toContain("openVikingTransport");+ });++ it("keeps memory_recall injected char budget tests on the plugin-injected transport seam", () => {+ const toolsTestSource = readFileSync(join(rootDir, "tests/ut/tools.test.ts"), "utf8");+ const start = toolsTestSource.indexOf('it("applies recallMaxInjectedChars to explicit memory_recall output"');+ const end = toolsTestSource.indexOf(' it("applies /ov-query-config session settings to subsequent memory_recall"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const recallBudgetBlock = toolsTestSource.slice(start, end);+ expect(recallBudgetBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(recallBudgetBlock).toContain("openVikingTransport");+ });++ it("keeps memory_recall runtime query config tests on the plugin-injected transport seam", () => {+ const toolsTestSource = readFileSync(join(rootDir, "tests/ut/tools.test.ts"), "utf8");+ const start = toolsTestSource.indexOf('it("applies /ov-query-config session settings to subsequent memory_recall"');+ const end = toolsTestSource.indexOf(' it("supports /ov-query-config get, unset, and reset for session scope"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const runtimeQueryConfigBlock = toolsTestSource.slice(start, end);+ expect(runtimeQueryConfigBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(runtimeQueryConfigBlock).toContain("openVikingTransport");+ });++ it("keeps memory_store behavioral tests on the plugin-injected transport seam", () => {+ const toolsTestSource = readFileSync(join(rootDir, "tests/ut/tools.test.ts"), "utf8");+ const start = toolsTestSource.indexOf('describe("Tool: memory_store (behavioral)"');+ const end = toolsTestSource.indexOf('describe("Tool: memory_forget (behavioral)"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const memoryStoreBlock = toolsTestSource.slice(start, end);+ expect(memoryStoreBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(memoryStoreBlock).toContain("openVikingTransport");+ });++ it("keeps OpenViking tool result access tests on the plugin-injected transport seam", () => {+ const toolsTestSource = readFileSync(join(rootDir, "tests/ut/tools.test.ts"), "utf8");+ const start = toolsTestSource.indexOf('describe("Tool: OpenViking tool result access"');+ const end = toolsTestSource.indexOf('describe("Tool: add_resource, add_skill, and ov_search (registration)"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const toolResultBlock = toolsTestSource.slice(start, end);+ expect(toolResultBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(toolResultBlock).toContain("openVikingTransport");+ });++ it("keeps ov_search behavioral tests on the plugin-injected transport seam", () => {+ const toolsTestSource = readFileSync(join(rootDir, "tests/ut/tools.test.ts"), "utf8");+ const start = toolsTestSource.indexOf('describe("Tool: ov_search (behavioral)"');+ const end = toolsTestSource.indexOf('describe("Tool: ov_recall_trace"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const ovSearchBlock = toolsTestSource.slice(start, end);+ expect(ovSearchBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(ovSearchBlock).toContain("openVikingTransport");+ });++ it("keeps ov_recall_trace tests on the plugin-injected transport seam", () => {+ const toolsTestSource = readFileSync(join(rootDir, "tests/ut/tools.test.ts"), "utf8");+ const start = toolsTestSource.indexOf('describe("Tool: ov_recall_trace"');+ const end = toolsTestSource.indexOf('describe("Plugin registration"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const recallTraceBlock = toolsTestSource.slice(start, end);+ expect(recallTraceBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(recallTraceBlock).toContain("openVikingTransport");+ });++ it("keeps plugin registration command and import tests on the plugin-injected transport seam", () => {+ const toolsTestSource = readFileSync(join(rootDir, "tests/ut/tools.test.ts"), "utf8");+ const start = toolsTestSource.indexOf('describe("Plugin registration"');+ const end = toolsTestSource.indexOf('describe("Tool: memory_forget (error paths)"', start);++ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);++ const pluginRegistrationBlock = toolsTestSource.slice(start, end);+ expect(pluginRegistrationBlock).not.toMatch(/vi\.stubGlobal\("fetch"/);+ expect(pluginRegistrationBlock).toContain("openVikingTransport");+ });++ it("keeps setup modules wired to concrete setup subservices instead of compatibility barrels and adapters", () => {+ const checkedFiles = ["commands/setup.ts"];+ const violations: string[] = [];++ for (const file of checkedFiles) {+ const imports = importSpecifiers(readFileSync(join(rootDir, file), "utf8"));+ for (const specifier of imports) {+ if (+ specifier.endsWith("/services/setup-service.js") ||+ specifier === "../services/setup-service.js" ||+ specifier.endsWith("/adapters/setup-network.js") ||+ specifier === "../adapters/setup-network.js" ||+ specifier.endsWith("/adapters/setup-io.js") ||+ specifier === "../adapters/setup-io.js"+ ) {+ violations.push(`${file} -> ${specifier}`);+ }+ }+ }++ expect(violations).toEqual([]);+ });++ it("keeps setup modules off the legacy setup-service compatibility barrel", () => {+ const violations: string[] = [];+ const legacyBarrel = join(rootDir, "services/setup-service.ts");++ if (existsSync(legacyBarrel)) {+ violations.push(relative(rootDir, legacyBarrel));+ }++ for (const dir of ["commands", "tests/ut"]) {+ for (const file of collectTypeScriptFiles(join(rootDir, dir))) {+ const imports = importSpecifiers(readFileSync(file, "utf8"));+ for (const specifier of imports) {+ if (+ specifier === "../services/setup-service.js" ||+ specifier === "../../services/setup-service.js" ||+ specifier.endsWith("/services/setup-service.js")+ ) {+ violations.push(`${relative(rootDir, file)} -> ${specifier}`);+ }+ }+ }+ }++ expect(violations).toEqual([]);+ });++ it("keeps context-engine wired to the service message adapter instead of the legacy adapter path", () => {+ const contextEngineImports = importSpecifiers(readFileSync(join(rootDir, "context-engine.ts"), "utf8"));++ expect(contextEngineImports).toContain("./services/context-message-adapter.js");+ expect(contextEngineImports).not.toContain("./adapters/context-engine-message-adapter.js");+ });++ it("keeps context-engine wired to the canonical lifecycle service module", () => {+ const contextEngineImports = importSpecifiers(readFileSync(join(rootDir, "context-engine.ts"), "utf8"));++ expect(contextEngineImports).toContain("./services/context-lifecycle-service.js");+ expect(contextEngineImports).not.toContain("./services/context-engine-lifecycle.js");+ });++ it("keeps lifecycle service reusing message adapter role normalization", () => {+ const lifecycleSource = readFileSync(join(rootDir, "services/context-lifecycle-service.ts"), "utf8");+ const lifecycleImports = importSpecifiers(lifecycleSource);++ expect(lifecycleImports).toContain("./context-message-adapter.js");+ expect(lifecycleSource).not.toMatch(/function\s+toRoleId\s*\(/);+ });++ it("keeps provider message sanitation owned by the message adapter seam", () => {+ const contextEngineSource = readFileSync(join(rootDir, "context-engine.ts"), "utf8");+ const contextEngineImports = importSpecifiers(contextEngineSource);+ const messageAdapterSource = readFileSync(join(rootDir, "services/context-message-adapter.ts"), "utf8");+ const messageAdapterImports = importSpecifiers(messageAdapterSource);++ expect(contextEngineImports).not.toContain("./session-transcript-repair.js");+ expect(contextEngineSource).not.toMatch(/function\s+(normalizeAssistantContent|canonicalizeAgentMessages)\s*\(/);+ expect(messageAdapterImports).toContain("../session-transcript-repair.js");+ expect(messageAdapterSource).toContain("sanitizeAgentMessagesForProvider");+ });++ it("keeps synthetic missing tool-result construction private to transcript repair", () => {+ const repairSource = readFileSync(join(rootDir, "session-transcript-repair.ts"), "utf8");+ const repairTestSource = readFileSync(join(rootDir, "tests/ut/session-transcript-repair.test.ts"), "utf8");++ expect(repairSource).not.toMatch(/export\s*\{\s*makeMissingToolResult\s*\}/);+ expect(repairTestSource).not.toMatch(/import\s*\{[\s\S]*makeMissingToolResult[\s\S]*\}\s*from\s*["']\.\.\/\.\.\/session-transcript-repair\.js["']/);+ expect(repairTestSource).toContain("repairToolUseResultPairing");+ });++ it("keeps assembled context construction inside the lifecycle service", () => {+ const contextEngineSource = readFileSync(join(rootDir, "context-engine.ts"), "utf8");+ const lifecycleSource = readFileSync(join(rootDir, "services/context-lifecycle-service.ts"), "utf8");++ expect(contextEngineSource).not.toMatch(/function\s+buildAssembledContext\s*\(/);+ expect(contextEngineSource).not.toContain("buildAssembledContext,");+ expect(lifecycleSource).toMatch(/function\s+buildAssembledContext\s*\(/);+ });++ it("keeps Phase 2 polling lifecycle inside the lifecycle service", () => {+ const contextEngineSource = readFileSync(join(rootDir, "context-engine.ts"), "utf8");+ const lifecycleSource = readFileSync(join(rootDir, "services/context-lifecycle-service.ts"), "utf8");++ expect(contextEngineSource).not.toMatch(/function\s+pollPhase2ExtractionOutcome\s*\(/);+ expect(contextEngineSource).not.toContain("DEFAULT_PHASE2_POLL_TIMEOUT_MS");+ expect(contextEngineSource).not.toContain("getTask(");+ expect(lifecycleSource).toMatch(/function\s+pollPhase2ExtractionOutcome\s*\(/);+ });++ it("keeps externalized tool-result handlers out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("registerOpenVikingToolResultTools");+ expect(indexSource).not.toMatch(/name:\s*"openviking_tool_result_/);+ expect(indexSource).not.toContain("ToolResultRef");+ expect(indexSource).not.toContain("parseToolResultRef");+ });++ it("keeps archive handlers out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("registerOpenVikingArchiveTools");+ expect(indexSource).not.toMatch(/name:\s*"ov_archive_(search|expand)"/);+ expect(indexSource).not.toContain("grepSessionArchives");+ });++ it("keeps memory store and forget handlers out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("registerOpenVikingMemoryTools");+ expect(indexSource).not.toMatch(/name:\s*"memory_(store|forget)"/);+ });++ it("keeps memory recall handler out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("registerOpenVikingMemoryRecallTools");+ expect(indexSource).not.toMatch(/name:\s*"memory_recall"/);+ });++ it("keeps import tool handlers out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("registerOpenVikingImportTools");+ expect(indexSource).not.toMatch(/name:\s*"add_(resource|skill)"/);+ });++ it("keeps import runtime out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("createOpenVikingImportRuntime");+ expect(indexSource).not.toContain("formatResourceImportText");+ expect(indexSource).not.toContain("formatSkillImportText");+ expect(indexSource).not.toContain("resource_imported");+ expect(indexSource).not.toContain("skill_imported");+ });++ it("keeps query tool handlers out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("registerOpenVikingQueryTools");+ expect(indexSource).not.toMatch(/name:\s*"ov_(search|read)"/);+ });++ it("keeps tool enabled-set construction out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("createOpenVikingToolRegistrationRuntime");+ expect(indexSource).not.toContain("new Set<string>(cfg.enabledTools)");+ expect(indexSource).not.toContain("enabledToolNames");+ });++ it("keeps OpenViking query runtime out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("createOpenVikingQueryRuntime");+ expect(indexSource).not.toContain("mergeFindResults");+ expect(indexSource).not.toContain("formatOVSearchRows");+ expect(indexSource).not.toContain("formatOVSearchText");+ expect(indexSource).not.toContain("readOpenVikingContent = async");+ expect(indexSource).not.toContain("searchOpenViking = async");+ });++ it("keeps recall trace tool handler out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("registerOpenVikingRecallTraceTools");+ expect(indexSource).not.toMatch(/name:\s*"ov_recall_trace"/);+ });++ it("keeps recall trace query and route runtime out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("createOpenVikingRecallTraceRuntime");+ expect(indexSource).not.toContain("parseRecallTraceInput");+ expect(indexSource).not.toContain("queryTraceForRoute");+ expect(indexSource).not.toContain("handleUriDetail");+ expect(indexSource).not.toContain("handleLatestOvSearchList");+ expect(indexSource).not.toContain("findTraceItem");+ expect(indexSource).not.toContain("toQueryObject");+ });++ it("keeps OpenViking command handlers out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("createOpenVikingCommandDefinitions");+ expect(indexSource).not.toContain("openVikingCommands.push");+ expect(indexSource).not.toContain("OpenViking add resource failed");+ expect(indexSource).not.toContain("OpenViking recall trace query failed");+ });++ it("keeps slash-command argument parsing out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");+ const toolsTestSource = readFileSync(join(rootDir, "tests/ut/tools.test.ts"), "utf8");++ expect(indexSource).toContain("./plugin/openviking-command-args.js");+ expect(indexSource).not.toMatch(/function\s+tokenizeCommandArgs\s*\(/);+ expect(indexSource).not.toMatch(/function\s+parseAddResourceCommandArgs\s*\(/);+ expect(indexSource).not.toMatch(/function\s+parseAddSkillCommandArgs\s*\(/);+ expect(indexSource).not.toMatch(/function\s+parseOVSearchCommandArgs\s*\(/);+ expect(toolsTestSource).toContain("../../plugin/openviking-command-args.js");+ });++ it("keeps auto-recall helper tests off the index compatibility facade", () => {+ const violations = [+ "tests/ut/build-memory-lines.test.ts",+ "tests/context-bloat-730.test.ts",+ "tests/ut/index-utils.test.ts",+ ].flatMap((file) => {+ const source = readFileSync(join(rootDir, file), "utf8");+ const importsFromIndex = source.match(/from\s+["'](?:\.\.\/|\.\.\/\.\.\/)index\.js["']|import\s*\(\s*["'](?:\.\.\/|\.\.\/\.\.\/)index\.js["']\s*\)/g) ?? [];+ const mentionsAutoRecallHelpers = source.match(/\b(?:buildMemoryLines|buildMemoryLinesWithBudget|estimateTokenCount|prepareRecallQuery)\b/);+ return importsFromIndex.length > 0 && mentionsAutoRecallHelpers ? [file] : [];+ });++ expect(violations).toEqual([]);+ });++ it("keeps identity-routing tests off the index compatibility facade", () => {+ const source = readFileSync(join(rootDir, "tests/ut/identity-routing.test.ts"), "utf8");++ expect(source).toContain("../../routing/identity-routing.js");+ expect(source).not.toMatch(/from\s+["']\.\.\/\.\.\/index\.js["']/);+ });++ it("keeps dead helper compatibility re-exports out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).not.toMatch(/export\s*\{[\s\S]*buildMemoryLines/);+ expect(indexSource).not.toContain("estimateAgentMessageTokens");+ expect(indexSource).not.toContain("SessionAgentResolveResult");+ expect(indexSource).not.toContain("tokenizeCommandArgs");+ expect(indexSource).not.toContain("estimateTokenCount");+ expect(indexSource).not.toContain("prepareRecallQuery");+ });++ it("keeps OpenViking runtime utility helpers out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("./plugin/openviking-runtime-utils.js");+ expect(indexSource).not.toMatch(/function\s+previewText\s*\(/);+ expect(indexSource).not.toMatch(/function\s+inferRecallResourceType\s*\(/);+ expect(indexSource).not.toMatch(/function\s+createTraceId\s*\(/);+ expect(indexSource).not.toMatch(/function\s+boundTraceQuery\s*\(/);+ expect(indexSource).not.toMatch(/function\s+extractToolSenderId\s*\(/);+ expect(indexSource).not.toMatch(/const\s+makeBypassedToolResult\s*=/);+ expect(indexSource).not.toContain("memory-store-${Date.now()}");+ expect(indexSource).not.toContain("Math.random().toString(36)");+ });++ it("keeps OpenViking session routing runtime out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("./plugin/openviking-session-routing-runtime.js");+ expect(indexSource).toContain("createOpenVikingSessionRoutingRuntime");+ expect(indexSource).not.toMatch(/const\s+resolvePluginSessionRouting\s*=/);+ expect(indexSource).not.toMatch(/const\s+toQueryConfigContext\s*=/);+ expect(indexSource).not.toMatch(/const\s+rememberSessionAgentId\s*=/);+ expect(indexSource).not.toMatch(/const\s+resolveAgentId\s*=/);+ expect(indexSource).not.toContain("sessionAgentResolver.resolve");+ });++ it("keeps OpenViking client runtime creation out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("./plugin/openviking-client-runtime.js");+ expect(indexSource).toContain("createOpenVikingClientRuntime");+ expect(indexSource).not.toContain("new OpenVikingClient");+ expect(indexSource).not.toMatch(/const\s+clientPromise\s*=/);+ expect(indexSource).not.toMatch(/const\s+getClient\s*=/);+ expect(indexSource).not.toMatch(/const\s+routingDebugLog\s*=/);+ expect(indexSource).not.toMatch(/const\s+verboseRoutingInfo\s*=/);+ });++ it("keeps OpenViking runtime state construction out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("./plugin/openviking-runtime-state.js");+ expect(indexSource).toContain("createOpenVikingRuntimeState");+ expect(indexSource).not.toContain("new RuntimeQueryConfigStore");+ expect(indexSource).not.toContain("new RecallTraceRecorder");+ expect(indexSource).not.toContain("queryConfigStore.load().catch");+ });++ it("keeps bypass-session runtime construction out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("./plugin/openviking-bypass-runtime.js");+ expect(indexSource).toContain("createOpenVikingBypassRuntime");+ expect(indexSource).not.toContain("compileSessionPatterns");+ expect(indexSource).not.toContain("shouldBypassSession(ctx ?? {}, bypassSessionPatterns)");+ expect(indexSource).not.toMatch(/const\s+isBypassedSession\s*=/);+ });++ it("keeps query config command handling out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("createOpenVikingQueryConfigCommandHandler");+ expect(indexSource).not.toContain("parseQueryConfigPatch");+ expect(indexSource).not.toContain("No query config parameters provided for /ov-query-config set");+ expect(indexSource).not.toContain("Reset OpenViking query config");+ });++ it("keeps lifecycle hook handlers out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("registerOpenVikingLifecycleHooks");+ expect(indexSource).not.toContain('api.on("session_start"');+ expect(indexSource).not.toContain('api.on("before_reset"');+ expect(indexSource).not.toContain("committed OV session on reset");+ });++ it("keeps context-engine registration out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("registerOpenVikingContextEngine");+ expect(indexSource).not.toContain("api.registerContextEngine(contextEnginePlugin.id");+ expect(indexSource).not.toContain("createMemoryOpenVikingContextEngine({");+ expect(indexSource).not.toContain("registerContextEngine is unavailable");+ });++ it("keeps context-engine ref state out of the composition root", () => {+ const indexSource = readFileSync(join(rootDir, "index.ts"), "utf8");++ expect(indexSource).toContain("./plugin/openviking-context-engine-ref.js");+ expect(indexSource).toContain("createOpenVikingContextEngineRef");+ expect(indexSource).not.toMatch(/let\s+contextEngineRef\s*:/);+ expect(indexSource).not.toContain("contextEngineRef = engine");+ expect(indexSource).not.toContain("getContextEngine: () => contextEngineRef");+ });+});diff --git a/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts b/examples/openclaw-plugin/tests/ut/build-memory-lines.test.tsindex 5b2677046..bbc1ebf22 100644--- a/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts+++ b/examples/openclaw-plugin/tests/ut/build-memory-lines.test.ts@@ -4,8 +4,8 @@ import {estimateTokenCount,buildMemoryLines,buildMemoryLinesWithBudget,-} from "../../index.js";-import { buildLongTermMemoryRecallContext } from "../../auto-recall.js";+} from "../../auto-recall.js";+import { buildAutoRecallContext } from "../../auto-recall.js";import type { FindResultItem } from "../../client.js";import { memoryOpenVikingConfigSchema } from "../../config.js";import { RecallTraceMemoryStore } from "../../recall-trace.js";@@ -33,8 +33,8 @@ describe("estimateTokenCount", () => {});it("uses CJK-aware weighting for non-Latin text and emoji", () => {- expect(estimateTokenCount("\u4f60\u597d\u4e16\u754c")).toBe(6);- expect(estimateTokenCount("A\u4f60\ud83d\ude42")).toBe(4);+ expect(estimateTokenCount("你好世界")).toBe(6);+ expect(estimateTokenCount("A你🙂")).toBe(4);});it("handles long text", () => {@@ -259,18 +259,16 @@ describe("buildMemoryLinesWithBudget", () => {});});-describe("buildLongTermMemoryRecallContext trace", () => {+describe("buildAutoRecallContext trace", () => {function makeCfg(overrides: Record<string, unknown> = {}) {return memoryOpenVikingConfigSchema.parse({- mode: "remote",- baseUrl: "http://127.0.0.1:1933",autoRecall: true,recallPreferAbstract: true,...overrides,});}- it("records auto-recall trace without changing the generated section", async () => {+ it("records auto-recall trace without changing the generated context block", async () => {const cfg = makeCfg({ recallTargetTypes: ["user"] });const memory = makeMemory({uri: "viking://user/memories/rust-pref",@@ -285,7 +283,7 @@ describe("buildLongTermMemoryRecallContext trace", () => {});const logger = { info: vi.fn(), warn: vi.fn() };- const withoutTrace = await buildLongTermMemoryRecallContext({+ const withoutTrace = await buildAutoRecallContext({cfg,client: makeClient() as any,agentId: "agent-1",@@ -293,7 +291,7 @@ describe("buildLongTermMemoryRecallContext trace", () => {logger,});const traces = new RecallTraceMemoryStore(10);- const withTrace = await buildLongTermMemoryRecallContext({+ const withTrace = await buildAutoRecallContext({cfg,client: makeClient() as any,agentId: "agent-1",@@ -305,7 +303,7 @@ describe("buildLongTermMemoryRecallContext trace", () => {queryTruncated: false,});- expect(withTrace.section).toBe(withoutTrace.section);+ expect(withTrace.block).toBe(withoutTrace.block);const recorded = traces.query({ turn: "latest", sessionId: "session-1", limit: 10 }).entries[0]!;expect(recorded.source).toBe("auto_recall");expect(recorded.operationType).toBe("semantic_find");@@ -320,7 +318,6 @@ describe("buildLongTermMemoryRecallContext trace", () => {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",@@ -333,16 +330,56 @@ describe("buildLongTermMemoryRecallContext trace", () => {expect(recorded.stats.injectedCount).toBe(1);});+ it("defaults auto-recall to backward-compatible user and agent memory recall", async () => {+ const cfg = makeCfg();+ const userMemory = makeMemory({+ uri: "viking://user/memories/project-docs",+ category: "memory",+ abstract: "Project documentation preference.",+ score: 0.9,+ });+ const client = {+ healthCheck: vi.fn().mockResolvedValue(undefined),+ find: vi.fn(async (_query: string, options: { contextType?: string }) => ({+ memories: options.contextType === "memory" ? [userMemory] : [],+ resources: [],+ total: options.contextType === "memory" ? 1 : 0,+ })),+ read: vi.fn().mockResolvedValue("unused"),+ };+ const traces = new RecallTraceMemoryStore(10);++ await buildAutoRecallContext({+ cfg,+ client: client as any,+ agentId: "agent-1",+ queryText: "where are the project docs?",+ logger: { info: vi.fn(), warn: vi.fn() },+ traceRecorder: traces,+ sessionId: "session-resource-only",+ ovSessionId: "ov-1",+ });++ expect(client.find).toHaveBeenCalledTimes(1);+ expect(client.find.mock.calls[0]?.[1]).toMatchObject({+ contextType: "memory",+ targetUri: undefined,+ });+ const recorded = traces.query({ turn: "latest", sessionId: "session-resource-only", limit: 10 }).entries[0]!;+ expect(recorded.resourceTypes).toEqual(["user", "agent"]);+ expect(recorded.searches.map((search) => search.resourceType)).toEqual(["user"]);+ });+it("records search errors while still injecting successful recall hits", async () => {- const cfg = makeCfg({ recallTargetTypes: ["user", "resource"] });+ const cfg = makeCfg({ recallTargetTypes: ["resource", "user"] });const client = {healthCheck: vi.fn().mockResolvedValue(undefined),find: vi.fn()- .mockRejectedValueOnce(new Error("user search failed"))+ .mockRejectedValueOnce(new Error("resource search failed")).mockResolvedValueOnce({- resources: [makeMemory({- uri: "viking://resources/backend-pref",- abstract: "Use TypeScript for this service.",+ memories: [makeMemory({+ uri: "viking://user/memories/backend-pref",+ abstract: "Agent recommends TypeScript for this service.",score: 0.88,})],total: 1,@@ -352,7 +389,7 @@ describe("buildLongTermMemoryRecallContext trace", () => {const logger = { info: vi.fn(), warn: vi.fn() };const traces = new RecallTraceMemoryStore(10);- const result = await buildLongTermMemoryRecallContext({+ const result = await buildAutoRecallContext({cfg,client: client as any,agentId: "agent-1",@@ -362,21 +399,17 @@ describe("buildLongTermMemoryRecallContext trace", () => {sessionId: "session-err",});- expect(result.section).toContain("Use TypeScript for this service.");+ expect(result.block).toContain("Agent recommends TypeScript for this service.");const recorded = traces.query({ turn: "latest", sessionId: "session-err", limit: 10 }).entries[0]!;expect(recorded.searches).toHaveLength(2);expect(recorded.searches[0]).toMatchObject({- resourceType: "user",- error: "Error: user search failed",+ resourceType: "resource",+ error: "Error: resource search failed",});- expect(recorded.searches[0]!.targetUriInput).toBeUndefined();- expect(recorded.searches[0]!.targetUriResolved).toBeUndefined();expect(recorded.searches[1]).toMatchObject({- resourceType: "resource",+ resourceType: "user",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-adapters.test.ts b/examples/openclaw-plugin/tests/ut/client-adapters.test.tsnew file mode 100644index 000000000..2d08aa3d0--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/client-adapters.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it, vi } from "vitest";++import { OpenVikingClient } from "../../client.js";+import type { HttpTransport } from "../../adapters/http-transport.js";+import type { ResourcePackager } from "../../adapters/resource-packager.js";++function okResponse(result: unknown): Response {+ return new Response(JSON.stringify({ status: "ok", result }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+}++function errorResponse(message: string, code = "INVALID_ARGUMENT"): Response {+ return new Response(JSON.stringify({ status: "error", error: { code, message } }), {+ status: 400,+ headers: { "Content-Type": "application/json" },+ });+}++describe("OpenVikingClient adapter seams", () => {+ it("uses injected HTTP transport while preserving tenant, agent, body, and timeout headers", async () => {+ const transport = vi.fn<HttpTransport>().mockResolvedValue(okResponse({ status: "ok" }));+ const client = new OpenVikingClient(+ "http://127.0.0.1:1933",+ "sk-root",+ "agent-prefix",+ 5_000,+ "acct-1",+ "user-1",+ undefined,+ { transport },+ );++ await client.healthCheck(12_000, "runtime-agent");++ expect(transport).toHaveBeenCalledTimes(1);+ const [url, init] = transport.mock.calls[0]!;+ const headers = new Headers(init.headers);+ expect(url).toBe("http://127.0.0.1:1933/health");+ expect(headers.get("X-API-Key")).toBe("sk-root");+ expect(headers.get("X-OpenViking-Account")).toBe("acct-1");+ expect(headers.get("X-OpenViking-User")).toBe("user-1");+ expect(headers.get("X-OpenViking-Actor-Peer")).toBe("runtime-agent");+ expect(init.signal).toBeInstanceOf(AbortSignal);+ });++ it("surfaces injected HTTP transport error payloads unchanged", async () => {+ const transport = vi.fn<HttpTransport>().mockResolvedValue(errorResponse("bad import"));+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5_000, "", "", undefined, { transport });++ await expect(client.healthCheck()).rejects.toThrow("OpenViking request failed [INVALID_ARGUMENT]: bad import");+ });++ it("uses injected resource packager so remote URLs do not trigger local packaging", async () => {+ const transport = vi.fn<HttpTransport>().mockResolvedValue(okResponse({ root_uri: "viking://resources/site" }));+ const packager: ResourcePackager = {+ prepareResourceSource: vi.fn().mockResolvedValue({ kind: "remote", path: "https://example.com/docs" }),+ prepareLocalUploadSource: vi.fn(),+ createTempUploadBody: vi.fn(),+ cleanup: vi.fn(),+ };+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5_000, "", "", undefined, {+ transport,+ resourcePackager: packager,+ });++ await client.addResource({ pathOrUrl: "https://example.com/docs", wait: true });++ expect(packager.prepareResourceSource).toHaveBeenCalledWith("https://example.com/docs");+ expect(packager.prepareLocalUploadSource).not.toHaveBeenCalled();+ expect(packager.cleanup).toHaveBeenCalledWith({ kind: "remote", path: "https://example.com/docs" });+ expect(transport).toHaveBeenCalledTimes(1);+ const [, init] = transport.mock.calls[0]!;+ expect(JSON.parse(String(init.body))).toMatchObject({+ path: "https://example.com/docs",+ wait: true,+ });+ });++ it("uses injected resource packager for local directories before temp upload", async () => {+ const uploadPath = "/fake-packager/resource-dir.zip";+ const uploadBody = new FormData();+ uploadBody.append("file", new Blob(["zip-bytes"]), "resource-dir.zip");+ const transport = vi+ .fn<HttpTransport>()+ .mockResolvedValueOnce(okResponse({ temp_file_id: "upload_resource.zip" }))+ .mockResolvedValueOnce(okResponse({ root_uri: "viking://resources/dir" }));+ const packaged = {+ kind: "upload" as const,+ uploadPath,+ sourceName: "resource-dir",+ cleanupPath: uploadPath,+ };+ const packager: ResourcePackager = {+ prepareResourceSource: vi.fn().mockResolvedValue(packaged),+ prepareLocalUploadSource: vi.fn(),+ createTempUploadBody: vi.fn().mockResolvedValue(uploadBody),+ cleanup: vi.fn(),+ };+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5_000, "", "", undefined, {+ transport,+ resourcePackager: packager,+ });++ await client.addResource({ pathOrUrl: "/workspace/resource-dir" });++ expect(packager.prepareResourceSource).toHaveBeenCalledWith("/workspace/resource-dir");+ expect(packager.createTempUploadBody).toHaveBeenCalledWith(uploadPath);+ expect(packager.cleanup).toHaveBeenCalledWith(packaged);+ expect(transport.mock.calls[0]![0]).toBe("http://127.0.0.1:1933/api/v1/resources/temp_upload");+ expect(JSON.parse(String(transport.mock.calls[1]![1].body))).toMatchObject({+ temp_file_id: "upload_resource.zip",+ source_name: "resource-dir",+ });+ });++ it("uses injected clock and sleep for wait=true commit polling", async () => {+ let now = 0;+ const sleeps: number[] = [];+ const transport = vi+ .fn<HttpTransport>()+ .mockResolvedValueOnce(okResponse({ status: "pending", task_id: "task-1" }))+ .mockResolvedValueOnce(okResponse({ status: "running" }))+ .mockResolvedValueOnce(okResponse({ status: "completed", result: { memories_extracted: { user: 2 } } }));+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5_000, "", "", undefined, {+ transport,+ now: () => now,+ sleep: async (ms) => {+ sleeps.push(ms);+ now += ms;+ },+ });++ const result = await client.commitSession("session-1", { wait: true, timeoutMs: 2_000, agentId: "runtime-agent" });++ expect(result).toMatchObject({+ status: "completed",+ task_id: "task-1",+ memories_extracted: { user: 2 },+ });+ expect(sleeps).toEqual([500, 500]);+ expect(transport.mock.calls.map(([url]) => url)).toEqual([+ "http://127.0.0.1:1933/api/v1/sessions/session-1/commit",+ "http://127.0.0.1:1933/api/v1/tasks/task-1",+ "http://127.0.0.1:1933/api/v1/tasks/task-1",+ ]);+ });++ it("uses injected clock deadline for wait=true commit polling timeout", async () => {+ let now = 0;+ const transport = vi+ .fn<HttpTransport>()+ .mockResolvedValueOnce(okResponse({ status: "pending", task_id: "task-timeout" }))+ .mockResolvedValue(okResponse({ status: "running" }));+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5_000, "", "", undefined, {+ transport,+ now: () => now,+ sleep: async (ms) => {+ now += ms;+ },+ });++ const result = await client.commitSession("slow-session", { wait: true, timeoutMs: 1_000 });++ expect(result).toMatchObject({ status: "timeout", task_id: "task-timeout" });+ expect(transport.mock.calls.map(([url]) => url)).toEqual([+ "http://127.0.0.1:1933/api/v1/sessions/slow-session/commit",+ "http://127.0.0.1:1933/api/v1/tasks/task-timeout",+ "http://127.0.0.1:1933/api/v1/tasks/task-timeout",+ ]);+ });+});diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.tsindex ce4229383..3b485b429 100644--- a/examples/openclaw-plugin/tests/ut/client.test.ts+++ b/examples/openclaw-plugin/tests/ut/client.test.ts@@ -1,10 +1,12 @@-import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";+import { mkdtemp, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";-import { OpenVikingClient, isMemoryUri } from "../../client.js";+import { OpenVikingClient } from "../../client.js";+import type { ResourcePackager } from "../../adapters/resource-packager.js";+import { isMemoryUri } from "../../routing/memory-uri.js";function okResponse(result: unknown): Response {return new Response(JSON.stringify({ status: "ok", result }), {@@ -34,20 +36,20 @@ describe("isMemoryUri", () => {expect(isMemoryUri("viking://user/default/memories/item-1")).toBe(true);});- it("returns false for deprecated user memory URI with agent segment", () => {- expect(isMemoryUri("viking://user/alice/agent/work/memories/item-1")).toBe(false);+ it("returns true for user memory URI isolated by agent", () => {+ expect(isMemoryUri("viking://user/alice/agent/work/memories/item-1")).toBe(true);});- it("returns false for deprecated agent memory alias", () => {- expect(isMemoryUri("viking://agent/memories/xyz")).toBe(false);+ it("returns true for valid agent memory URI", () => {+ expect(isMemoryUri("viking://user/memories/xyz")).toBe(true);});- it("returns false for deprecated agent memory URI with space prefix", () => {- expect(isMemoryUri("viking://agent/abc123/memories/item-2")).toBe(false);+ it("returns true for agent memory URI with space prefix", () => {+ expect(isMemoryUri("viking://user/abc123/memories/item-2")).toBe(true);});- it("returns false for deprecated agent memory URI with user segment", () => {- expect(isMemoryUri("viking://agent/work/user/alice/memories/item-2")).toBe(false);+ it("returns true for agent memory URI isolated by user", () => {+ expect(isMemoryUri("viking://user/work/memories/item-2")).toBe(true);});it("returns true for user memories root", () => {@@ -62,8 +64,8 @@ describe("isMemoryUri", () => {expect(isMemoryUri("viking://user/skills/abc")).toBe(false);});- it("returns false for deprecated agent instructions URI", () => {- expect(isMemoryUri("viking://agent/instructions/rule-1")).toBe(false);+ it("returns false for agent instructions URI", () => {+ expect(isMemoryUri("viking://user/instructions/rule-1")).toBe(false);});it("returns false for empty string", () => {@@ -81,12 +83,11 @@ describe("isMemoryUri", () => {describe("OpenVikingClient resource and skill import", () => {it("addResource posts remote URL as path", async () => {- const fetchMock = vi.fn().mockResolvedValue(+ const transport = vi.fn().mockResolvedValue(okResponse({ root_uri: "viking://resources/site", status: "success" }),);- vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport });const result = await client.addResource({pathOrUrl: "https://example.com/docs",to: "viking://resources/site",@@ -94,8 +95,8 @@ describe("OpenVikingClient resource and skill import", () => {});expect(result.root_uri).toBe("viking://resources/site");- expect(fetchMock).toHaveBeenCalledTimes(1);- const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ expect(transport).toHaveBeenCalledTimes(1);+ const [, init] = transport.mock.calls[0] as [string, RequestInit];expect(JSON.parse(String(init.body))).toMatchObject({path: "https://example.com/docs",to: "viking://resources/site",@@ -107,7 +108,7 @@ describe("OpenVikingClient resource and skill import", () => {const tempDir = await mkdtemp(join(tmpdir(), "ov-client-test-"));const filePath = join(tempDir, "resource.md");await writeFile(filePath, "# Demo\n");- const fetchMock = vi+ const transport = vi.fn().mockResolvedValueOnce(okResponse({ temp_file_id: "upload_resource.md" })).mockResolvedValueOnce(okResponse({@@ -115,103 +116,122 @@ describe("OpenVikingClient resource and skill import", () => {status: "success",queue_status: { completed: true },}));- vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport });const result = await client.addResource({ pathOrUrl: filePath, wait: true });expect(result.queue_status).toEqual({ completed: true });- expect(fetchMock).toHaveBeenCalledTimes(2);- expect(fetchMock.mock.calls[0]![0]).toBe("http://127.0.0.1:1933/api/v1/resources/temp_upload");- expect((fetchMock.mock.calls[0]![1] as RequestInit).body).toBeInstanceOf(FormData);- expect(JSON.parse(String((fetchMock.mock.calls[1]![1] as RequestInit).body))).toMatchObject({+ expect(transport).toHaveBeenCalledTimes(2);+ expect(transport.mock.calls[0]![0]).toBe("http://127.0.0.1:1933/api/v1/resources/temp_upload");+ expect((transport.mock.calls[0]![1] as RequestInit).body).toBeInstanceOf(FormData);+ expect(JSON.parse(String((transport.mock.calls[1]![1] as RequestInit).body))).toMatchObject({temp_file_id: "upload_resource.md",wait: true,});});it("addResource zips local directory before upload", async () => {- const tempDir = await mkdtemp(join(tmpdir(), "ov-client-test-"));- const dirPath = join(tempDir, "resource-dir");- const uploadPrefix = "openviking-openclaw-upload-";- const beforeDirs = (await readdir(tmpdir())).filter((name) => name.startsWith(uploadPrefix));- await mkdir(dirPath, { recursive: true });- await writeFile(join(dirPath, "README.md"), "# Demo\n");- const fetchMock = vi+ const dirPath = "/workspace/resource-dir";+ const uploadBody = new FormData();+ uploadBody.append("file", new Blob(["zip-bytes"]), "resource-dir.zip");+ const packaged = {+ kind: "upload" as const,+ uploadPath: "/virtual/resource-dir.zip",+ sourceName: "resource-dir",+ cleanupPath: "/virtual/resource-dir.zip",+ };+ const resourcePackager: ResourcePackager = {+ prepareResourceSource: vi.fn().mockResolvedValue(packaged),+ prepareLocalUploadSource: vi.fn(),+ createTempUploadBody: vi.fn().mockResolvedValue(uploadBody),+ cleanup: vi.fn(),+ };+ const transport = vi.fn().mockResolvedValueOnce(okResponse({ temp_file_id: "upload_resource.zip" })).mockResolvedValueOnce(okResponse({ root_uri: "viking://resources/resource-dir" }));- vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport, resourcePackager });await client.addResource({ pathOrUrl: dirPath });- expect(fetchMock).toHaveBeenCalledTimes(2);- expect((fetchMock.mock.calls[0]![1] as RequestInit).body).toBeInstanceOf(FormData);- expect(JSON.parse(String((fetchMock.mock.calls[1]![1] as RequestInit).body))).toMatchObject({+ expect(resourcePackager.prepareResourceSource).toHaveBeenCalledWith(dirPath);+ expect(resourcePackager.createTempUploadBody).toHaveBeenCalledWith("/virtual/resource-dir.zip");+ expect(resourcePackager.cleanup).toHaveBeenCalledWith(packaged);+ expect(transport).toHaveBeenCalledTimes(2);+ expect((transport.mock.calls[0]![1] as RequestInit).body).toBeInstanceOf(FormData);+ expect(JSON.parse(String((transport.mock.calls[1]![1] as RequestInit).body))).toMatchObject({temp_file_id: "upload_resource.zip",source_name: "resource-dir",});- const afterDirs = (await readdir(tmpdir())).filter((name) => name.startsWith(uploadPrefix));- expect(afterDirs).toEqual(beforeDirs);});it("addSkill uploads local SKILL.md file", async () => {const tempDir = await mkdtemp(join(tmpdir(), "ov-client-test-"));const filePath = join(tempDir, "SKILL.md");await writeFile(filePath, "---\nname: demo\ndescription: demo\n---\n\n# Demo\n");- const fetchMock = vi+ const transport = vi.fn().mockResolvedValueOnce(okResponse({ temp_file_id: "upload_skill.md" })).mockResolvedValueOnce(okResponse({ uri: "viking://user/skills/demo", name: "demo" }));- vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport });const result = await client.addSkill({ path: filePath, wait: true });expect(result.uri).toBe("viking://user/skills/demo");- expect(JSON.parse(String((fetchMock.mock.calls[1]![1] as RequestInit).body))).toMatchObject({+ expect(transport).toHaveBeenCalledTimes(2);+ expect(transport.mock.calls[0]![0]).toBe("http://127.0.0.1:1933/api/v1/resources/temp_upload");+ expect((transport.mock.calls[0]![1] as RequestInit).body).toBeInstanceOf(FormData);+ expect(JSON.parse(String((transport.mock.calls[1]![1] as RequestInit).body))).toMatchObject({temp_file_id: "upload_skill.md",wait: true,});});it("addSkill removes temporary zip directory after uploading a skill directory", async () => {- const tempDir = await mkdtemp(join(tmpdir(), "ov-client-test-"));- const dirPath = join(tempDir, "skill-dir");- const uploadPrefix = "openviking-openclaw-upload-";- const beforeDirs = (await readdir(tmpdir())).filter((name) => name.startsWith(uploadPrefix));- await mkdir(dirPath, { recursive: true });- await writeFile(join(dirPath, "SKILL.md"), "---\nname: demo\ndescription: demo\n---\n\n# Demo\n");- const fetchMock = vi+ const dirPath = "/workspace/skill-dir";+ const uploadBody = new FormData();+ uploadBody.append("file", new Blob(["zip-bytes"]), "skill-dir.zip");+ const packaged = {+ kind: "upload" as const,+ uploadPath: "/virtual/skill-dir.zip",+ cleanupPath: "/virtual/skill-dir.zip",+ };+ const resourcePackager: ResourcePackager = {+ prepareResourceSource: vi.fn(),+ prepareLocalUploadSource: vi.fn().mockResolvedValue(packaged),+ createTempUploadBody: vi.fn().mockResolvedValue(uploadBody),+ cleanup: vi.fn(),+ };+ const transport = vi.fn().mockResolvedValueOnce(okResponse({ temp_file_id: "upload_skill.zip" })).mockResolvedValueOnce(okResponse({ uri: "viking://user/skills/demo", name: "demo" }));- vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport, resourcePackager });await client.addSkill({ path: dirPath, wait: true });- expect(JSON.parse(String((fetchMock.mock.calls[1]![1] as RequestInit).body))).toMatchObject({+ expect(resourcePackager.prepareLocalUploadSource).toHaveBeenCalledWith(dirPath);+ expect(resourcePackager.createTempUploadBody).toHaveBeenCalledWith("/virtual/skill-dir.zip");+ expect(resourcePackager.cleanup).toHaveBeenCalledWith(packaged);+ expect(transport).toHaveBeenCalledTimes(2);+ expect((transport.mock.calls[0]![1] as RequestInit).body).toBeInstanceOf(FormData);+ expect(JSON.parse(String((transport.mock.calls[1]![1] as RequestInit).body))).toMatchObject({temp_file_id: "upload_skill.zip",wait: true,});- const afterDirs = (await readdir(tmpdir())).filter((name) => name.startsWith(uploadPrefix));- expect(afterDirs).toEqual(beforeDirs);});it("addSkill posts raw skill data directly", async () => {const data = "---\nname: inline\ndescription: inline\n---\n\n# Inline\n";- const fetchMock = vi.fn().mockResolvedValue(+ const transport = vi.fn().mockResolvedValue(okResponse({ uri: "viking://user/skills/inline", name: "inline" }),);- vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport });await client.addSkill({ data });- expect(fetchMock).toHaveBeenCalledTimes(1);- expect(JSON.parse(String((fetchMock.mock.calls[0]![1] as RequestInit).body))).toMatchObject({+ expect(transport).toHaveBeenCalledTimes(1);+ expect(JSON.parse(String((transport.mock.calls[0]![1] as RequestInit).body))).toMatchObject({data,wait: false,});@@ -223,24 +243,22 @@ describe("OpenVikingClient resource and skill import", () => {description: "demo",inputSchema: { type: "object", properties: {} },};- const fetchMock = vi.fn().mockResolvedValue(+ const transport = vi.fn().mockResolvedValue(okResponse({ uri: "viking://user/skills/demo-tool", name: "demo-tool" }),);- vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport });await client.addSkill({ data });- expect(JSON.parse(String((fetchMock.mock.calls[0]![1] as RequestInit).body))).toMatchObject({+ expect(JSON.parse(String((transport.mock.calls[0]![1] as RequestInit).body))).toMatchObject({data,});});it("surfaces OpenViking error responses", async () => {- const fetchMock = vi.fn().mockResolvedValue(errorResponse("bad import"));- vi.stubGlobal("fetch", fetchMock);+ const transport = vi.fn().mockResolvedValue(errorResponse("bad import"));- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport });await expect(client.addResource({ pathOrUrl: "https://example.com/bad" })).rejects.toThrow("OpenViking request failed [INVALID_ARGUMENT]: bad import",);@@ -248,15 +266,14 @@ describe("OpenVikingClient resource and skill import", () => {it("uses an extended request timeout for wait=true imports", async () => {vi.useFakeTimers();- const fetchMock = vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((resolve, reject) => {+ const transport = vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((resolve, reject) => {init?.signal?.addEventListener("abort", () => reject(new Error("aborted")));setTimeout(() => {resolve(okResponse({ root_uri: "viking://resources/site", status: "success" }));}, 20_000);}));- vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 15_000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 15_000, "", "", undefined, false, true, { transport });const pending = client.addResource({pathOrUrl: "https://example.com/docs",wait: true,@@ -273,15 +290,14 @@ describe("OpenVikingClient resource and skill import", () => {it("still uses the default request timeout for non-wait imports", async () => {vi.useFakeTimers();- const fetchMock = vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((resolve, reject) => {+ const transport = vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((resolve, reject) => {init?.signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));setTimeout(() => {resolve(okResponse({ root_uri: "viking://resources/site", status: "success" }));}, 20_000);}));- vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 15_000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 15_000, "", "", undefined, false, true, { transport });const pending = client.addResource({pathOrUrl: "https://example.com/docs",wait: false,@@ -295,7 +311,7 @@ describe("OpenVikingClient resource and skill import", () => {it("keeps polling wait=true commit long enough for slow Phase 2 completion", async () => {vi.useFakeTimers();- const fetchMock = vi.fn((url: string) => {+ const transport = vi.fn((url: string) => {if (url.endsWith("/api/v1/sessions/slow-session/commit")) {return Promise.resolve(okResponse({session_id: "slow-session",@@ -317,9 +333,8 @@ describe("OpenVikingClient resource and skill import", () => {}throw new Error(`Unexpected URL: ${url}`);});- vi.stubGlobal("fetch", fetchMock);- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5_000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5_000, "", "", undefined, false, true, { transport });const pending = client.commitSession("slow-session", { wait: true });await vi.advanceTimersByTimeAsync(200_500);@@ -331,74 +346,48 @@ describe("OpenVikingClient resource and skill import", () => {memories_extracted: { core: 1 },});});+});- it("sends memory_policy when creating a session", async () => {- const fetchMock = vi.fn().mockResolvedValue(okResponse({ session_id: "s1" }));- vi.stubGlobal("fetch", fetchMock);-- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);- await client.createSession("s1", {- memoryPolicy: {- self: { enabled: true },- peer: { enabled: true },- },- });-- const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];- expect(url).toBe("http://127.0.0.1:1933/api/v1/sessions");- expect(JSON.parse(String(init.body))).toEqual({- session_id: "s1",- memory_policy: {- self: { enabled: true },- peer: { enabled: true },- },- });- });-- it("does not send memory_policy when committing a session", async () => {- const fetchMock = vi.fn().mockResolvedValue(okResponse({- session_id: "s1",- status: "accepted",- archived: true,- }));- vi.stubGlobal("fetch", fetchMock);+describe("OpenVikingClient tenant headers (advanced accountId / userId overrides)", () => {+ it.each([+ ["prefix", "prefix_main"],+ ["", "main"],+ ])("sends OpenClaw default agent for health checks with prefix %j", async (prefix, expected) => {+ const transport = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);- await client.commitSession("s1");+ const client = new OpenVikingClient("http://127.0.0.1:1933", "sk-test", prefix, 5000, "", "", undefined, false, true, { transport });+ await client.healthCheck();- const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];- expect(JSON.parse(String(init.body))).toEqual({});+ const [, init] = transport.mock.calls[0] as [string, RequestInit];+ const headers = new Headers(init.headers);+ expect(headers.get("X-OpenViking-Actor-Peer")).toBe(expected);});-});-describe("OpenVikingClient tenant headers (advanced accountId / userId overrides)", () => {it("sends explicitly configured accountId and userId in request headers", async () => {- const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));- vi.stubGlobal("fetch", fetchMock);+ const transport = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));const client = new OpenVikingClient("http://127.0.0.1:1933", "sk-test", "agent", 5000,- "acct-123", "user-456",+ "acct-123", "user-456", undefined, false, true, { transport },);await client.healthCheck();- const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ const [, init] = transport.mock.calls[0] as [string, RequestInit];const headers = new Headers(init.headers);expect(headers.get("X-OpenViking-Account")).toBe("acct-123");expect(headers.get("X-OpenViking-User")).toBe("user-456");});it("keeps api_key user-key flow free of explicit tenant overrides when accountId/userId are not configured", async () => {- const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));- vi.stubGlobal("fetch", fetchMock);+ const transport = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));const client = new OpenVikingClient("http://127.0.0.1:1933", "sk-user", "agent", 5000,- "", "",+ "", "", undefined, false, true, { transport },);await client.healthCheck();- const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ const [, init] = transport.mock.calls[0] as [string, RequestInit];const headers = new Headers(init.headers);expect(headers.get("X-OpenViking-Account")).toBeNull();expect(headers.get("X-OpenViking-User")).toBeNull();@@ -406,16 +395,15 @@ describe("OpenVikingClient tenant headers (advanced accountId / userId overrides});it("preserves explicit tenant headers for api_key root-key style flows", async () => {- const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));- vi.stubGlobal("fetch", fetchMock);+ const transport = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));const client = new OpenVikingClient("http://127.0.0.1:1933", "sk-root", "agent", 5000,- "acct-123", "user-456",+ "acct-123", "user-456", undefined, false, true, { transport },);await client.healthCheck();- const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ const [, init] = transport.mock.calls[0] as [string, RequestInit];const headers = new Headers(init.headers);expect(headers.get("X-API-Key")).toBe("sk-root");expect(headers.get("X-OpenViking-Account")).toBe("acct-123");@@ -423,41 +411,39 @@ describe("OpenVikingClient tenant headers (advanced accountId / userId overrides});it("does not synthesize tenant headers when apiKey is missing", async () => {- const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));- vi.stubGlobal("fetch", fetchMock);+ const transport = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000,- "", "",+ "", "", undefined, false, true, { transport },);await client.healthCheck();- const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ const [, init] = transport.mock.calls[0] as [string, RequestInit];const headers = new Headers(init.headers);expect(headers.get("X-OpenViking-Account")).toBeNull();expect(headers.get("X-OpenViking-User")).toBeNull();});it("trims whitespace from accountId and userId overrides", async () => {- const fetchMock = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));- vi.stubGlobal("fetch", fetchMock);+ const transport = vi.fn().mockResolvedValue(okResponse({ status: "ok" }));const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000,- " acct ", " user ",+ " acct ", " user ", undefined, false, true, { transport },);await client.healthCheck();- const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ const [, init] = transport.mock.calls[0] as [string, RequestInit];const headers = new Headers(init.headers);expect(headers.get("X-OpenViking-Account")).toBe("acct");expect(headers.get("X-OpenViking-User")).toBe("user");});});-describe("OpenVikingClient canonical user namespace", () => {- it("expands user memory alias to canonical user root by default", async () => {- const fetchMock = vi.fn(async (url: string) => {+describe("OpenVikingClient canonical namespace policy", () => {+ it("keeps user memory alias unchanged and routes by actor peer by default", async () => {+ const transport = vi.fn(async (url: string) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "alice" });}@@ -466,23 +452,27 @@ describe("OpenVikingClient canonical user namespace", () => {}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const client = new OpenVikingClient("http://127.0.0.1:1933", "", "my-agent", 5000,"", "", undefined,+ false,+ true,+ { transport },);- await client.find("test query", { targetUri: "viking://user/memories" });+ await client.find("test query", { targetUri: "viking://user/memories" }, "my-agent");- const findCall = fetchMock.mock.calls.find((c) =>+ const findCall = transport.mock.calls.find((c) =>String(c[0]).endsWith("/api/v1/search/find"),)!;const body = JSON.parse(String((findCall[1] as RequestInit).body));+ const headers = new Headers((findCall[1] as RequestInit).headers);expect(body.target_uri).toBe("viking://user/memories");+ expect(headers.get("X-OpenViking-Actor-Peer")).toBe("my-agent");});- it("expands user memory alias to canonical user root", async () => {- const fetchMock = vi.fn(async (url: string) => {+ it("ignores legacy isolateUserScopeByAgent and routes by actor peer", async () => {+ const transport = vi.fn(async (url: string) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "alice" });}@@ -491,23 +481,27 @@ describe("OpenVikingClient canonical user namespace", () => {}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const client = new OpenVikingClient("http://127.0.0.1:1933", "", "my-agent", 5000,"", "", undefined,+ true,+ true,+ { transport },);- await client.find("test query", { targetUri: "viking://user/memories" });+ await client.find("test query", { targetUri: "viking://user/memories" }, "my-agent");- const findCall = fetchMock.mock.calls.find((c) =>+ const findCall = transport.mock.calls.find((c) =>String(c[0]).endsWith("/api/v1/search/find"),)!;const body = JSON.parse(String((findCall[1] as RequestInit).body));+ const headers = new Headers((findCall[1] as RequestInit).headers);expect(body.target_uri).toBe("viking://user/memories");+ expect(headers.get("X-OpenViking-Actor-Peer")).toBe("my-agent");});- it("expands user memory alias to canonical user root by default", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ it("expands agent memory alias to canonical agent/user root by default", async () => {+ const transport = vi.fn(async (url: string, init?: RequestInit) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "alice" });}@@ -516,25 +510,25 @@ describe("OpenVikingClient canonical user namespace", () => {}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const client = new OpenVikingClient("http://127.0.0.1:1933", "", "shared-agent", 5000,"", "", undefined,false,true,+ { transport },);- await client.find("test", { targetUri: "viking://user/memories" });+ await client.find("test", { targetUri: "viking://user/memories" }, "shared-agent");- const findCall = fetchMock.mock.calls.find((c) =>+ const findCall = transport.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/memories");});- it("expands user skill alias to canonical user root", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ it("keeps user skill target URI unchanged while using actor peer routing", async () => {+ const transport = vi.fn(async (url: string, init?: RequestInit) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "alice" });}@@ -543,82 +537,38 @@ describe("OpenVikingClient canonical user namespace", () => {}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const client = new OpenVikingClient("http://127.0.0.1:1933", "", "shared-agent", 5000,"", "", undefined,false,false,+ { transport },);- await client.find("test", { targetUri: "viking://user/skills" });+ await client.find("test", { targetUri: "viking://user/skills" }, "shared-agent");- const findCall = fetchMock.mock.calls.find((c) =>+ const findCall = transport.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/skills");});- 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" });- }- if (url.endsWith("/api/v1/search/find")) {- return okResponse({ memories: [], total: 0 });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "shared-agent", 5000);- await client.find("test", {- targetUri: "viking://user/memories",- 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));- 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 () => {- const fetchMock = vi.fn().mockResolvedValue(okResponse({ session_id: "s1" }));- vi.stubGlobal("fetch", fetchMock);+ it("includes role_id when addSessionMessage receives one", async () => {+ const transport = vi.fn().mockResolvedValue(okResponse({ session_id: "s1" }));- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000, "", "", undefined, false, true, { transport });await client.addSessionMessage("s1","user",[{ type: "text", text: "hello" }],+ "agent","2026-04-20T00:00:00.000Z","telegram_12345",);- const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];- const body = JSON.parse(String(init.body));- expect(body.peer_id).toBe("telegram_12345");- });-- it("greps session archives through the user session alias", async () => {- const fetchMock = vi.fn().mockResolvedValue(okResponse({ matches: [], count: 0 }));- vi.stubGlobal("fetch", fetchMock);-- const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);- await client.grepSessionArchives("s1", "needle", {- archiveId: "archive_001",- caseInsensitive: true,- });-- const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ const [, init] = transport.mock.calls[0] as [string, RequestInit];const body = JSON.parse(String(init.body));- expect(body.uri).toBe("viking://user/sessions/s1/history/archive_001");- expect(body.pattern).toBe("needle");- expect(body.case_insensitive).toBe(true);+ expect(body.role_id).toBe("telegram_12345");});});diff --git a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.tsindex 8ec6b8acf..f756ef148 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-afterTurn.test.ts@@ -35,7 +35,6 @@ function makeEngine(opts?: {: vi.fn().mockResolvedValue(undefined);const client = {- ensureSession: vi.fn().mockResolvedValue(true),addSessionMessage,commitSession: vi.fn().mockResolvedValue({status: "accepted",@@ -71,7 +70,6 @@ function makeEngine(opts?: {return {engine,client: client as unknown as {- ensureSession: ReturnType<typeof vi.fn>;addSessionMessage: ReturnType<typeof vi.fn>;commitSession: ReturnType<typeof vi.fn>;getSession: ReturnType<typeof vi.fn>;@@ -197,7 +195,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][3] as string;+ const createdAt = client.addSessionMessage.mock.calls[lastCallIdx][4] as string;expect(createdAt).toBe("2026-04-01T10:03:00.000Z");});@@ -223,7 +221,7 @@ describe("context-engine afterTurn()", () => {);});- it("does not pass peer_id by default", async () => {+ it("passes sanitized senderId as role_id", async () => {const { engine, client } = makeEngine();await engine.afterTurn!({@@ -235,65 +233,16 @@ describe("context-engine afterTurn()", () => {});expect(client.addSessionMessage).toHaveBeenCalledTimes(1);- expect(client.addSessionMessage.mock.calls[0][4]).toBeUndefined();+ expect(client.addSessionMessage.mock.calls[0][5]).toBe("telegram_12345");});- it("passes sanitized senderId as peer_id when peer_role is person", async () => {- const { engine, client } = makeEngine({- cfgOverrides: { peer_role: "person" },- });-- await engine.afterTurn!({- sessionId: "s1",- sessionFile: "",- messages: [{ role: "user", content: "hello world" }],- prePromptMessageCount: 0,- runtimeContext: { senderId: "telegram:12345" },- });-- expect(client.addSessionMessage).toHaveBeenCalledTimes(1);- expect(client.addSessionMessage.mock.calls[0][4]).toBe("telegram_12345");- expect(client.ensureSession).toHaveBeenCalledWith(- "s1",- {- memoryPolicy: {- self: { enabled: true },- peer: { enabled: true },- },- },- );- });-- it("passes runtime agent as peer_id only for assistant messages when peer_role is assistant", async () => {- const { engine, client } = makeEngine({- cfgOverrides: { peer_role: "assistant" },- });-- await engine.afterTurn!({- sessionId: "s1",- sessionFile: "",- messages: [- { role: "user", content: "hello world" },- { role: "assistant", content: "hi there" },- ],- prePromptMessageCount: 0,- runtimeContext: { senderId: "telegram:12345" },- });-- expect(client.addSessionMessage).toHaveBeenCalledTimes(2);- expect(client.addSessionMessage.mock.calls[0][1]).toBe("user");- expect(client.addSessionMessage.mock.calls[0][4]).toBeUndefined();- expect(client.addSessionMessage.mock.calls[1][1]).toBe("assistant");- expect(client.addSessionMessage.mock.calls[1][4]).toBe("test-agent");- });-- it("sanitizes injected context blocks from user content", async () => {+ it("sanitizes <relevant-memories> from user content but not from assistant", async () => {const { engine, client } = makeEngine();const messages = [{role: "user",- content: "my question <openviking-context>injected memory data</openviking-context> more text",+ content: "my question <relevant-memories>injected memory data</relevant-memories> more text",},];@@ -307,7 +256,7 @@ describe("context-engine afterTurn()", () => {expect(client.addSessionMessage).toHaveBeenCalledTimes(1);expect(client.addSessionMessage.mock.calls[0][1]).toBe("user");const storedContent = (client.addSessionMessage.mock.calls[0][2] as Array<{ text?: string }>)[0].text;- expect(storedContent).not.toContain("openviking-context");+ expect(storedContent).not.toContain("relevant-memories");expect(storedContent).not.toContain("injected memory data");expect(storedContent).toContain("my question");});@@ -356,26 +305,29 @@ describe("context-engine afterTurn()", () => {expect(commitCall[1]).toMatchObject({ wait: false });});- it("passes peer memory policy to commit when peer_role is person", async () => {+ it("keeps afterTurn write and commit enabled when recall target types default to resources only", async () => {const { engine, client } = makeEngine({- commitTokenThreshold: 100,- getSession: { pending_tokens: 5000 },- cfgOverrides: { peer_role: "person" },+ commitTokenThreshold: 20000,+ getSession: { pending_tokens: 25000 },+ cfgOverrides: {+ recallTargetTypes: [],+ },});await engine.afterTurn!({sessionId: "s1",sessionFile: "",- messages: [{ role: "user", content: "remember my table tennis preference" }],+ messages: [+ { role: "user", content: "persist this user turn even with resource-only recall" },+ { role: "assistant", content: "persist this assistant turn too" },+ ],prePromptMessageCount: 0,- runtimeContext: { senderId: "openclaw-tui" },});+ expect(client.addSessionMessage).toHaveBeenCalledTimes(2);+ expect(client.addSessionMessage.mock.calls[0][1]).toBe("user");+ expect(client.addSessionMessage.mock.calls[1][1]).toBe("assistant");expect(client.commitSession).toHaveBeenCalledTimes(1);- expect(client.commitSession.mock.calls[0][1]).toMatchObject({- wait: false,- });- expect(client.commitSession.mock.calls[0][1]).not.toHaveProperty("memoryPolicy");});it("catches errors without throwing", async () => {@@ -484,7 +436,7 @@ describe("context-engine afterTurn()", () => {expect(assistantParts.map(p => p.text).join(" ")).toContain("export const x = 1");});- it("does not pass agentId to addSessionMessage by default", async () => {+ it("passes agentId to addSessionMessage", async () => {const { engine, client } = makeEngine();await engine.afterTurn!({@@ -495,8 +447,8 @@ describe("context-engine afterTurn()", () => {});expect(client.addSessionMessage).toHaveBeenCalledTimes(1);- expect(client.addSessionMessage.mock.calls[0][3]).toBeUndefined();- expect(client.addSessionMessage.mock.calls[0][4]).toBeUndefined();+ const agentId = client.addSessionMessage.mock.calls[0][3] as string;+ expect(agentId).toBe("test-agent");});it("checks pending tokens after addSessionMessage", async () => {@@ -599,12 +551,12 @@ describe("context-engine afterTurn()", () => {expect(client.addSessionMessage.mock.calls[2][1]).toBe("assistant");});- it("sanitizes injected context blocks from assistant content", async () => {+ it("sanitizes <relevant-memories> from assistant content", async () => {const { engine, client } = makeEngine();const messages = [{ role: "user", content: "question" },- { role: "assistant", content: "Here is context <openviking-context>data</openviking-context> end" },+ { role: "assistant", content: "Here is context <relevant-memories>data</relevant-memories> end" },];await engine.afterTurn!({@@ -616,7 +568,7 @@ describe("context-engine afterTurn()", () => {expect(client.addSessionMessage).toHaveBeenCalledTimes(2);const assistantParts = client.addSessionMessage.mock.calls[1][2] as Array<{ text?: string }>;- expect(assistantParts.map(p => p.text).join(" ")).not.toContain("openviking-context");+ expect(assistantParts.map(p => p.text).join(" ")).not.toContain("relevant-memories");expect(assistantParts.map(p => p.text).join(" ")).toContain("Here is context");});diff --git a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.tsindex 5161c7a7d..9b0660b06 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-assemble.test.ts@@ -5,7 +5,6 @@ import { memoryOpenVikingConfigSchema } from "../../config.js";import { createMemoryOpenVikingContextEngine } from "../../context-engine.js";import { RuntimeQueryConfigStore } from "../../query-config.js";import { RecallTraceMemoryStore } from "../../recall-trace.js";-import { estimateAgentMessagesTokens, estimateTextTokens } from "../../token-estimator.js";const cfg = memoryOpenVikingConfigSchema.parse({mode: "remote",@@ -15,11 +14,11 @@ const cfg = memoryOpenVikingConfigSchema.parse({});function roughEstimate(messages: unknown[]): number {- return estimateAgentMessagesTokens(messages);+ return Math.ceil(JSON.stringify(messages).length / 4);}function systemPromptTokens(text?: string): number {- return estimateTextTokens(text);+ return text ? Math.ceil(text.length / 4) : 0;}function makeLogger() {@@ -80,8 +79,8 @@ function makeEngine(return {engine,client: client as unknown as {- healthCheck: ReturnType<typeof vi.fn>;getSessionContext: ReturnType<typeof vi.fn>;+ healthCheck: ReturnType<typeof vi.fn>;find: ReturnType<typeof vi.fn>;read: ReturnType<typeof vi.fn>;},@@ -93,630 +92,178 @@ function makeEngine(describe("context-engine assemble()", () => {it("prepends auto-recall to the latest user message during transformContext", async () => {- const { engine, client } = makeEngine(- {- latest_archive_overview: "This OV context must not be rebuilt during transformContext.",- pre_archive_abstracts: [],- messages: [- {- id: "stored-current-user",- role: "user",- created_at: "2026-04-30T00:00:00Z",- parts: [{ type: "text", text: "stale stored prompt" }],- },- ],- estimatedTokens: 12,- stats: makeStats(),- },- {- cfgOverrides: {- autoRecall: true,- recallPreferAbstract: true,- recallTargetTypes: ["user"],- },- },- );- client.find- .mockResolvedValueOnce({- memories: [- {- uri: "viking://user/default/memories/rust-pref",- level: 2,- category: "preferences",- abstract: "User prefers Rust for backend tasks.",- score: 0.93,- },- ],- total: 1,- })- .mockResolvedValueOnce({ memories: [], total: 0 });-- const sourceMessages = [- { role: "user", content: "[Session History Summary]\nOlder archive summary." },- { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },- { role: "user", content: "what backend language should we use?" },- ];-- const result = await engine.assemble({- sessionId: "session-transform",- messages: sourceMessages,- });-- expect(client.healthCheck).toHaveBeenCalledWith(500);- expect(client.getSessionContext).not.toHaveBeenCalled();- expect(result.messages).toHaveLength(sourceMessages.length);- expect(result.messages[0]).toBe(sourceMessages[0]);- expect(result.messages[1]).toBe(sourceMessages[1]);- expect(result.messages[2]?.role).toBe("user");- expect(result.messages[2]?.content).toMatch(/^<openviking-context>/);- expect(result.messages[2]?.content).toContain("## Long-term Memories");- expect(result.messages[2]?.content).toContain("Source: openviking-auto-recall");- expect(result.messages[2]?.content).toContain(- "<uri>viking://user/default/memories/rust-pref</uri>",- );- expect(result.messages[2]?.content).toContain("User prefers Rust for backend tasks.");- expect(result.messages[2]?.content).toContain("what backend language should we use?");- expect(result.systemPromptAddition).toBeUndefined();- });-- it("passes session metadata into auto-recall trace recording during transformContext", async () => {- const traces = new RecallTraceMemoryStore(10);- const { engine, client } = makeEngine(- {- latest_archive_overview: "unused",- pre_archive_abstracts: [],- messages: [],- estimatedTokens: 0,- stats: makeStats(),- },- {- traceRecorder: traces,- cfgOverrides: {- autoRecall: true,- recallPreferAbstract: true,- recallTargetTypes: ["user"],- },- },- );- client.find.mockResolvedValueOnce({- memories: [- {- uri: "viking://user/default/memories/typescript-pref",- level: 2,- category: "preferences",- abstract: "Use TypeScript for gateway plugins.",- score: 0.9,- },- ],- total: 1,- });-- await engine.assemble({- sessionId: "session-transform-trace",- messages: [{ role: "user", content: "which language should the gateway plugin use?" }],- });-- const recorded = traces.query({ turn: "latest", sessionId: "session-transform-trace", limit: 10 }).entries[0]!;- expect(recorded.sessionId).toBe("session-transform-trace");- expect(recorded.ovSessionId).toBe("session-transform-trace");- expect(recorded.agentId).toBe("agent:session-transform-trace");- expect(recorded.trigger.query).toBe("which language should the gateway plugin use?");- expect(recorded.resourceTypes).toEqual(["user"]);- });-- it("uses one memory context-type search for default auto-recall targets", async () => {- const traces = new RecallTraceMemoryStore(10);- const { engine, client } = makeEngine(- {- latest_archive_overview: "unused",- pre_archive_abstracts: [],- messages: [],- estimatedTokens: 0,- stats: makeStats(),- },- {- traceRecorder: traces,- cfgOverrides: {- autoRecall: true,- recallPreferAbstract: true,- },- },- );- client.find.mockImplementation(async (_query: string, options: { contextType?: string; targetUri?: string }) => {- if (options.contextType === "memory" && options.targetUri === undefined) {- return {- memories: [- {- uri: "viking://user/default/memories/gateway-docs",- level: 2,- category: "memory",- abstract: "Gateway plugin docs live in the user memory store.",- score: 0.9,- },- ],- total: 1,- };- }- throw new Error(- `unexpected auto-recall target: ${options.targetUri ?? "none"} contextType=${options.contextType ?? "none"}`,- );- });-- await engine.assemble({- sessionId: "session-transform-default-targets",- messages: [{ role: "user", content: "where are the gateway plugin docs?" }],- });-- expect(client.find).toHaveBeenCalledTimes(1);- expect(client.find.mock.calls[0]![1]).toMatchObject({ contextType: "memory" });- expect(client.find.mock.calls[0]![1].targetUri).toBeUndefined();- expect(client.find.mock.calls[0]![1].actorPeerId).toBe("agent_session-transform-default-targets");-- const recorded = traces.query({- turn: "latest",- sessionId: "session-transform-default-targets",- limit: 10,- }).entries[0]!;- expect(recorded.searches).toHaveLength(1);- expect(recorded.searches[0]).toMatchObject({ contextType: "memory" });- expect(recorded.searches[0]!.targetUriResolved).toBeUndefined();- });-- it("applies session effective query config to transformContext auto-recall", async () => {- const localCfg = memoryOpenVikingConfigSchema.parse({- ...cfg,- autoRecall: true,- recallPreferAbstract: true,- });- const queryConfigStore = RuntimeQueryConfigStore.createInMemory(localCfg);- await queryConfigStore.set(- "session",- { peerId: "agent:session-dynamic-query", sessionId: "session-dynamic-query" },- {- recallLimit: 1,- candidateLimit: 3,- scoreThreshold: 0.5,- resourceTypes: ["user"],- maxInjectedChars: 1000,- },- );- const { engine, client } = makeEngine(- {- latest_archive_overview: "unused",- pre_archive_abstracts: [],- messages: [],- estimatedTokens: 0,- stats: makeStats(),- },- {- cfgOverrides: {- autoRecall: true,- recallPreferAbstract: true,- },- queryConfigStore,- },- );- client.find.mockResolvedValueOnce({- memories: [- {- uri: "viking://user/default/memories/high",- level: 2,- category: "preferences",- abstract: "High-confidence dynamic query memory.",- score: 0.9,- },- {- uri: "viking://user/default/memories/low",- level: 2,- category: "facts",- abstract: "Low-confidence memory should be filtered.",- score: 0.1,- },- ],- total: 2,- });-- const result = await engine.assemble({- sessionId: "session-dynamic-query",- messages: [{ role: "user", content: "which dynamic query memory applies?" }],- });-- expect(client.find).toHaveBeenCalledTimes(1);- expect(client.find.mock.calls[0]?.[1]).toMatchObject({- contextType: "memory",- limit: 3,- });- expect(client.find.mock.calls[0]?.[1].targetUri).toBeUndefined();- expect(String(result.messages[0]?.content)).toContain("High-confidence dynamic query memory.");- expect(String(result.messages[0]?.content)).not.toContain("Low-confidence memory should be filtered.");- });-- it("passes sender peer_id to transformContext auto-recall when peer_role is person", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: true,- json: async () => ({ status: "ok" }),- }),- );- try {const { engine, client } = makeEngine({- latest_archive_overview: "",- pre_archive_abstracts: [],- messages: [],- estimatedTokens: 0,- stats: makeStats(),- },- {- cfgOverrides: {- autoRecall: true,- peer_role: "person",- recallResources: true,- },- },- );-- const sourceMessages = [- { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },- { role: "user", content: "what backend language should we use?" },- ];-- await engine.assemble({- sessionId: "session-person-peer",- runtimeContext: { senderId: "wx/user-01@abc" },- messages: sourceMessages,- });-- expect(client.find).toHaveBeenCalledTimes(1);- for (const call of client.find.mock.calls) {- expect(call[1]).toMatchObject({ actorPeerId: "wx_user-01_abc", contextType: "memory" });- expect(call[1].targetUri).toBeUndefined();- }- } finally {- vi.unstubAllGlobals();- }- });-- it("does not auto-recall during main assemble from prompt metadata", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: true,- json: async () => ({ status: "ok" }),- }),- );- try {- const { engine, client } = makeEngine(- new Error("should be replaced"),- {- cfgOverrides: {- autoRecall: true,- peer_role: "person",- recallPreferAbstract: true,- },- },- );- client.getSessionContext.mockRejectedValueOnce(- new Error("OpenViking request failed [NOT_FOUND]: Session not found"),- );-- const prompt = [- "Conversation info (untrusted metadata):",- "```json",- JSON.stringify({- message_id: "om_1",- sender_id: "ou_bcc",- sender: "Dana Tester",- is_group_chat: true,- }),- "```",- "",- "Sender (untrusted metadata):",- "```json",- JSON.stringify({- id: "ou_bcc",- name: "Dana Tester",- }),- "```",- "",- "[message_id: om_1]",- "Dana Tester: who am I?",- "",- "[System: mention metadata]",- ].join("\n");- const liveMessages = [{ role: "user", content: "live main assemble prompt" }];-- const result = await engine.assemble({- sessionId: "session-main-prompt-peer",- sessionKey: "agent:main:feishu:group:oc_123",- messages: liveMessages,- prompt,- });-- expect(client.getSessionContext).toHaveBeenCalled();- expect(client.find).not.toHaveBeenCalled();- expect(result.messages).toEqual(liveMessages);- expect(result.messages[0]?.content).not.toContain("Source: openviking-auto-recall");- expect(result.messages[0]?.content).not.toContain("<openviking-context>");- expect(result.messages[0]?.content).not.toContain("## Long-term Memories");- } finally {- vi.unstubAllGlobals();- }- });-- it("does not inject auto-recall into main assemble OV context", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: true,- json: async () => ({ status: "ok" }),- }),- );- try {- const { engine, client } = makeEngine(- {- latest_archive_overview: "",+ latest_archive_overview: "This OV context must not be rebuilt during transformContext.",pre_archive_abstracts: [],messages: [{- id: "stored-main-user",+ id: "stored-current-user",role: "user",created_at: "2026-04-30T00:00:00Z",- parts: [{ type: "text", text: "Stored OpenViking prompt." }],+ parts: [{ type: "text", text: "stale stored prompt" }],},],estimatedTokens: 12,- stats: {- ...makeStats(),- activeTokens: 12,- },- },- {- cfgOverrides: {- autoRecall: true,- peer_role: "person",- },- },- );-- const liveMessages = [{ role: "user", content: "live prompt" }];- const result = await engine.assemble({- sessionId: "session-main-runtime-peer",- runtimeContext: { senderId: "trusted/runtime-user" },- messages: liveMessages,- prompt: [- "Conversation info (untrusted metadata):",- "```json",- JSON.stringify({ sender_id: "fake-prompt-user", sender: "Prompt User" }),- "```",- "",- "[message_id: om_1]",- "Prompt User: 我喜欢什么水果?",- ].join("\n"),- });-- expect(client.getSessionContext).toHaveBeenCalled();- expect(client.find).not.toHaveBeenCalled();- expect(result.messages[0]).toEqual({- role: "user",- content: "Stored OpenViking prompt.",- });- expect(result.messages[0]?.content).not.toContain("Source: openviking-auto-recall");- expect(result.messages[0]?.content).not.toContain("<openviking-context>");- expect(result.messages[0]?.content).not.toContain("## Long-term Memories");- } finally {- vi.unstubAllGlobals();- }- });-- it("passes assistant peer_id to transformContext auto-recall when peer_role is assistant", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: true,- json: async () => ({ status: "ok" }),- }),- );- try {- const { engine, client } = makeEngine(- {- latest_archive_overview: "",- pre_archive_abstracts: [],- messages: [],- estimatedTokens: 0,stats: makeStats(),},{cfgOverrides: {autoRecall: true,- peer_role: "assistant",- recallResources: true,+ recallPreferAbstract: true,},},);+ client.find+ .mockResolvedValueOnce({+ memories: [+ {+ uri: "viking://user/default/memories/rust-pref",+ level: 2,+ category: "preferences",+ abstract: "User prefers Rust for backend tasks.",+ score: 0.93,+ },+ ],+ total: 1,+ })+ .mockResolvedValueOnce({ memories: [], total: 0 });const sourceMessages = [+ { role: "user", content: "[Session History Summary]\nOlder archive summary." },{ role: "assistant", content: [{ type: "text", text: "Previous answer." }] },{ role: "user", content: "what backend language should we use?" },];- await engine.assemble({- sessionId: "session-assistant-peer",+ const result = await engine.assemble({+ sessionId: "session-transform",messages: sourceMessages,});- expect(client.find).toHaveBeenCalledTimes(1);- for (const call of client.find.mock.calls) {- expect(call[1]).toMatchObject({ actorPeerId: "agent_session-assistant-peer", contextType: "memory" });- expect(call[1].targetUri).toBeUndefined();- }- } finally {- vi.unstubAllGlobals();- }+ expect(client.getSessionContext).not.toHaveBeenCalled();+ expect(result.messages).toHaveLength(sourceMessages.length);+ expect(result.messages[0]).toBe(sourceMessages[0]);+ expect(result.messages[1]).toBe(sourceMessages[1]);+ expect(result.messages[2]?.role).toBe("user");+ expect(result.messages[2]?.content).toMatch(/^<relevant-memories>/);+ expect(result.messages[2]?.content).toContain("Source: openviking-auto-recall");+ expect(result.messages[2]?.content).toContain("User prefers Rust for backend tasks.");+ expect(result.messages[2]?.content).toContain("what backend language should we use?");+ expect(result.systemPromptAddition).toBeUndefined();});- it("keeps experience memories out of Long-term Memories and renders them in Agent Experiences", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: true,- json: async () => ({ status: "ok" }),- }),- );- try {+ it("passes session metadata into auto-recall trace recording during transformContext", async () => {+ const traces = new RecallTraceMemoryStore(10);const { engine, client } = makeEngine({- latest_archive_overview: "",+ latest_archive_overview: "unused",pre_archive_abstracts: [],messages: [],estimatedTokens: 0,stats: makeStats(),},{+ traceRecorder: traces,cfgOverrides: {autoRecall: true,recallPreferAbstract: true,- agentExperience: {- enabled: true,- recallLimit: 3,- scoreThreshold: 0.35,- maxInjectedChars: 6000,- minQueryChars: 12,- },+ recallTargetTypes: ["user"],},},);-- const experienceHit = {- uri: "viking://user/default/memories/experiences/openclaw-plugin-file-write-guard.md",- level: 2,- category: "experience",- abstract: "经验摘要",- score: 0.91,- };- const longTermHit = {- uri: "viking://user/default/memories/profile.md",- level: 2,- category: "profile",- abstract: "张明的主要技术栈是 Elixir 和 Zig。",- score: 0.83,- };-- client.find- .mockResolvedValueOnce({- memories: [experienceHit],- total: 1,- })- .mockResolvedValueOnce({- memories: [longTermHit],- total: 1,- })- .mockResolvedValueOnce({- memories: [experienceHit],- total: 1,- });-- client.read.mockImplementation(async (uri: string) => {- if (uri === experienceHit.uri) {- return [- "## Situation",- "- 当修改 OpenClaw 插件 afterTurn 写回逻辑时。",- "",- "## Approach",- "- 在写回 OV session 前剥离注入上下文块。",- "",- "## Reflect",- "- 避免把注入经验再次写回 transcript。",- ].join("\n");- }- if (uri === longTermHit.uri) {- return "张明的主要技术栈是 Elixir 和 Zig。";- }- return "";- });-- const result = await engine.assemble({- sessionId: "session-transform-experience",- messages: [- { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },- { role: "user", content: "修一下 OpenClaw 插件里 afterTurn 写回 session 的问题,并告诉我张明的技术栈。" },+ client.find.mockResolvedValueOnce({+ memories: [+ {+ uri: "viking://user/default/memories/typescript-pref",+ level: 2,+ category: "preferences",+ abstract: "Use TypeScript for gateway plugins.",+ score: 0.9,+ },],+ total: 1,});- expect(client.find.mock.calls[0]?.[1]).toMatchObject({- targetUri: "viking://user/memories/experiences",+ await engine.assemble({+ sessionId: "session-transform-trace",+ messages: [{ role: "user", content: "which language should the gateway plugin use?" }],});- const injected = String(result.messages[1]?.content ?? "");- expect(injected).toMatch(/^<openviking-context>/);- expect(injected).not.toContain("<relevant-memories>");- expect(injected).toContain("## Agent Experiences");- expect(injected).toContain("### Experience: openclaw-plugin-file-write-guard");- expect(injected).toContain("## Long-term Memories");- expect(injected).toContain("张明的主要技术栈是 Elixir 和 Zig。");-- const longTermSection = injected.split("## Long-term Memories")[1] ?? "";- expect(longTermSection).not.toContain("### Experience:");- expect(longTermSection).not.toContain("剥离注入上下文块");- } finally {- vi.unstubAllGlobals();- }++ const recorded = traces.query({ turn: "latest", sessionId: "session-transform-trace", limit: 10 }).entries[0]!;+ expect(recorded.sessionId).toBe("session-transform-trace");+ expect(recorded.ovSessionId).toBe("session-transform-trace");+ expect(recorded.agentId).toBe("agent:session-transform-trace");+ expect(recorded.trigger.query).toBe("which language should the gateway plugin use?");+ expect(recorded.resourceTypes).toEqual(["user"]);});- it("keeps task gating enabled when agent experience is enabled", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: true,- json: async () => ({ status: "ok" }),- }),- );- try {+ it("uses backward-compatible user and agent auto-recall by default during transformContext", async () => {+ const traces = new RecallTraceMemoryStore(10);const { engine, client } = makeEngine({- latest_archive_overview: "",+ latest_archive_overview: "unused",pre_archive_abstracts: [],messages: [],estimatedTokens: 0,stats: makeStats(),},{+ traceRecorder: traces,cfgOverrides: {- autoRecall: false,- agentExperience: {- enabled: true,- },+ autoRecall: true,+ recallPreferAbstract: true,},},);+ client.find.mockImplementation(async (_query: string, options: { contextType?: string }) => ({+ resources: [],+ memories: options.contextType === "memory"+ ? [{+ uri: "viking://user/memories/project-docs",+ level: 2,+ category: "memory",+ abstract: "Memory docs for the gateway plugin.",+ score: 0.9,+ }]+ : [],+ total: options.contextType === "memory" ? 1 : 0,+ }));- const result = await engine.assemble({- sessionId: "session-transform-experience-gated",- messages: [- { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },- { role: "user", content: "preflight assemble 和 transformcontext assemble是什么区别" },- ],+ await engine.assemble({+ sessionId: "session-transform-resource-default",+ messages: [{ role: "user", content: "where are the gateway plugin docs?" }],});- expect(client.find).not.toHaveBeenCalled();- expect(result.messages[1]?.content).toBe("preflight assemble 和 transformcontext assemble是什么区别");- } finally {- vi.unstubAllGlobals();- }+ expect(client.find).toHaveBeenCalledTimes(1);+ expect(client.find.mock.calls[0]?.[1]).toMatchObject({+ contextType: "memory",+ targetUri: undefined,+ });+ const recorded = traces.query({ turn: "latest", sessionId: "session-transform-resource-default", limit: 10 }).entries[0]!;+ expect(recorded.resourceTypes).toEqual(["user", "agent"]);});- it("does not recall agent experiences by default", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- ok: true,- json: async () => ({ status: "ok" }),- }),- );- try {+ it("applies session effective query config to transformContext auto-recall", async () => {+ const localCfg = memoryOpenVikingConfigSchema.parse({+ ...cfg,+ autoRecall: true,+ recallPreferAbstract: true,+ });+ const queryConfigStore = RuntimeQueryConfigStore.createInMemory(localCfg);+ await queryConfigStore.set(+ "session",+ { agentId: "agent:session-dynamic-query", sessionId: "session-dynamic-query" },+ {+ recallLimit: 1,+ candidateLimit: 3,+ scoreThreshold: 0.5,+ resourceTypes: ["user"],+ maxInjectedChars: 1000,+ },+ );const { engine, client } = makeEngine({- latest_archive_overview: "",+ latest_archive_overview: "unused",pre_archive_abstracts: [],messages: [],estimatedTokens: 0,@@ -724,66 +271,45 @@ describe("context-engine assemble()", () => {},{cfgOverrides: {- autoRecall: false,+ autoRecall: true,+ recallPreferAbstract: true,},+ queryConfigStore,},);-- const result = await engine.assemble({- sessionId: "session-experience-default-off",- messages: [- { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },- { role: "user", content: "修一下 OpenClaw 插件里 afterTurn 写回 session 的问题" },+ client.find.mockResolvedValueOnce({+ memories: [+ {+ uri: "viking://user/default/memories/high",+ level: 2,+ category: "preferences",+ abstract: "High-confidence dynamic query memory.",+ score: 0.9,+ },+ {+ uri: "viking://user/default/memories/low",+ level: 2,+ category: "facts",+ abstract: "Low-confidence memory should be filtered.",+ score: 0.1,+ },],+ total: 2,});- expect(client.find).not.toHaveBeenCalled();- expect(result.messages[1]?.content).toBe("修一下 OpenClaw 插件里 afterTurn 写回 session 的问题");- } finally {- vi.unstubAllGlobals();- }- });-- it("does not inject again when latest user message already has an OpenViking context block", async () => {- const { engine, getClient } = makeEngine(- {- latest_archive_overview: "unused",- pre_archive_abstracts: [],- messages: [],- estimatedTokens: 0,- stats: makeStats(),- },- {- cfgOverrides: {- autoRecall: true,- agentExperience: {- enabled: true,- },- },- },- );- const sourceMessages = [- { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },- {- role: "user",- content: [- "<openviking-context>",- "already injected OpenViking context",- "</openviking-context>",- "",- "修一下 OpenClaw 插件里 afterTurn 写回 session 的问题",- ].join("\n"),- },- ];-- const result = await engine.assemble({- sessionId: "session-existing-openviking-context-block",- messages: sourceMessages,- });+ const result = await engine.assemble({+ sessionId: "session-dynamic-query",+ messages: [{ role: "user", content: "which dynamic query memory applies?" }],+ });- expect(getClient).not.toHaveBeenCalled();- expect(result.messages).toBe(sourceMessages);- expect(result.estimatedTokens).toBe(roughEstimate(sourceMessages));+ expect(client.find).toHaveBeenCalledTimes(1);+ expect(client.find.mock.calls[0]?.[1]).toMatchObject({+ contextType: "memory",+ targetUri: undefined,+ limit: 3,+ });+ expect(String(result.messages[0]?.content)).toContain("High-confidence dynamic query memory.");+ expect(String(result.messages[0]?.content)).not.toContain("Low-confidence memory should be filtered.");});it("passes through transformContext messages when the latest message is not user", async () => {@@ -826,10 +352,6 @@ describe("context-engine assemble()", () => {messages: [],estimatedTokens: 0,stats: makeStats(),- }, {- cfgOverrides: {- autoRecall: false,- },});const sourceMessages = [{ role: "assistant", content: [{ type: "text", text: "Previous answer." }] },@@ -846,29 +368,6 @@ describe("context-engine assemble()", () => {expect(result.estimatedTokens).toBe(roughEstimate(sourceMessages));});- it("does not underestimate CJK messages when passing through transformContext", async () => {- const { engine, getClient } = makeEngine({- latest_archive_overview: "unused",- pre_archive_abstracts: [],- messages: [],- estimatedTokens: 0,- stats: makeStats(),- });- const sourceMessages = [- { role: "assistant", content: [{ type: "text", text: "Previous answer." }] },- { role: "user", content: "\u4f60\u597d".repeat(100) },- ];-- const result = await engine.assemble({- sessionId: "session-cjk-estimate",- messages: sourceMessages,- });-- expect(getClient).not.toHaveBeenCalled();- expect(result.messages).toBe(sourceMessages);- expect(result.estimatedTokens).toBeGreaterThanOrEqual(300);- });-it("treats prompt-less assemble with availableTools as main assemble", async () => {const { engine, client, resolveAgentId } = makeEngine({latest_archive_overview: "# Session Summary\nPreviously discussed repository setup.",@@ -904,9 +403,15 @@ 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({@@ -966,7 +471,8 @@ describe("context-engine assemble()", () => {tokenBudget: 4096,});- expect(client.getSessionContext).toHaveBeenCalledWith("session-1", 4096);+ expect(resolveAgentId).toHaveBeenCalledWith("session-1", undefined, "session-1");+ expect(client.getSessionContext).toHaveBeenCalledWith("session-1", 4096, "agent:session-1");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 0d2ee6cd0..8f6b3326a 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-compact.test.ts@@ -2,10 +2,8 @@ import { describe, expect, it, vi } from "vitest";import type { OpenVikingClient } from "../../client.js";import { memoryOpenVikingConfigSchema } from "../../config.js";-import {- createMemoryOpenVikingContextEngine,- openClawSessionToOvStorageId,-} from "../../context-engine.js";+import { createMemoryOpenVikingContextEngine } from "../../context-engine.js";+import { openClawSessionToOvStorageId } from "../../routing/identity-routing.js";function makeLogger() {return {@@ -15,16 +13,12 @@ function makeLogger() {};}-function makeEngine(- commitResult: unknown,- opts?: { throwError?: Error; cfgOverrides?: Record<string, unknown> },-) {+function makeEngine(commitResult: unknown, opts?: { throwError?: Error }) {const cfg = memoryOpenVikingConfigSchema.parse({mode: "remote",baseUrl: "http://127.0.0.1:1933",autoCapture: false,autoRecall: false,- ...(opts?.cfgOverrides ?? {}),});const logger = makeLogger();@@ -120,24 +114,6 @@ describe("context-engine commitOVSession()", () => {expect(client.commitSession.mock.calls[0][1]).toMatchObject({ wait: true });});- it("does not pass memory policy when committing peer-role sessions", async () => {- const { engine, client } = makeEngine(- {- status: "completed",- archived: false,- memories_extracted: {},- },- { cfgOverrides: { peer_role: "person" } },- );-- await engine.commitOVSession({ sessionId: "s1" });-- expect(client.commitSession.mock.calls[0][1]).toMatchObject({- wait: true,- });- expect(client.commitSession.mock.calls[0][1]).not.toHaveProperty("memoryPolicy");- });-it("uses sessionKey-derived OV session ID for commitOVSession", async () => {const { engine, client, resolveAgentId } = makeEngine({status: "completed",@@ -152,7 +128,7 @@ describe("context-engine commitOVSession()", () => {const ovSessionId = openClawSessionToOvStorageId("plain-session", "agent:main:main");expect(client.commitSession.mock.calls[0][0]).toBe(ovSessionId);- expect(resolveAgentId).not.toHaveBeenCalled();+ expect(resolveAgentId).toHaveBeenCalledWith("plain-session", "agent:main:main", ovSessionId);});it("logs memories extracted count", async () => {@@ -325,24 +301,6 @@ describe("context-engine compact()", () => {expect(client.commitSession.mock.calls[0][1]).toMatchObject({ wait: true });});- it("compact does not pass memory policy when committing peer-role sessions", async () => {- const { engine, client } = makeEngine(- {- status: "completed",- archived: true,- memories_extracted: {},- },- { cfgOverrides: { peer_role: "person" } },- );-- await engine.compact({ sessionId: "s1", sessionFile: "" });-- expect(client.commitSession.mock.calls[0][1]).toMatchObject({- wait: true,- });- expect(client.commitSession.mock.calls[0][1]).not.toHaveProperty("memoryPolicy");- });-it("logs memory extraction count on success", async () => {const { engine, logger } = makeEngine({status: "completed",@@ -436,7 +394,7 @@ describe("context-engine compact()", () => {expect(resolveAgentId).toHaveBeenCalledWith("plain-session", "agent:top:main", ovSessionId);});- it("does not pass agentId to commitSession", async () => {+ it("passes agentId to commitSession", async () => {const { engine, client } = makeEngine({status: "completed",archived: false,@@ -446,10 +404,8 @@ describe("context-engine compact()", () => {await engine.compact({ sessionId: "s1", sessionFile: "" });expect(client.commitSession.mock.calls[0][1]).toMatchObject({- wait: true,- keepRecentCount: 0,+ agentId: "test-agent",});- 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/context-engine-merge-consecutive.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-merge-consecutive.test.tsindex 7e003d58d..c055579e3 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-merge-consecutive.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-merge-consecutive.test.ts@@ -4,7 +4,7 @@ import {mergeConsecutiveAssistants,mergeConsecutiveUsers,ensureAlternation,-} from "../../context-engine.js";+} from "../../services/context-message-adapter.js";// Local AgentMessage type matches the (lax) one used inside context-engine.ts.type AgentMessage = {diff --git a/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-modules.test.tsnew file mode 100644index 000000000..1b557c173--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/context-engine-modules.test.ts@@ -0,0 +1,337 @@+import { describe, expect, it, vi } from "vitest";++import {+ convertToAgentMessages,+ ensureAlternation,+ formatMessageFaithful,+ mergeConsecutiveAssistants,+ mergeConsecutiveUsers,+ toRoleId,+} from "../../services/context-message-adapter.js";+import { assembleOpenVikingSession, afterTurnOpenVikingSession, commitOpenVikingSession, compactOpenVikingSession } from "../../services/context-lifecycle-service.js";+import { openClawSessionToOvStorageId } from "../../routing/identity-routing.js";++describe("context-engine message adapter seam", () => {+ it("sanitizes role ids in the concrete message adapter", () => {+ expect(toRoleId(" Alice:Build Bot ")).toBe("Alice_Build_Bot");+ expect(toRoleId("@#$")).toBeUndefined();+ });++ it("formats OpenViking messages in the concrete message adapter", () => {+ const message = {+ role: "assistant",+ parts: [+ { type: "text", text: "hello" },+ { type: "tool", tool_name: "read_file", tool_status: "completed", tool_input: { path: "a.ts" }, tool_output: "ok" },+ { type: "context", uri: "viking://mem/1", abstract: "remember this" },+ ],+ };++ expect(formatMessageFaithful(message as any)).toContain("[Tool: read_file] (completed)");+ });++ it("converts structured tool round-trips in the concrete message adapter", () => {+ const message = {+ role: "assistant",+ parts: [{+ type: "tool",+ tool_id: "toolu_1",+ tool_name: "search",+ tool_input: { query: "phase 5" },+ tool_output: "result text",+ tool_status: "completed",+ }],+ };++ expect(convertToAgentMessages(message)).toEqual([+ { role: "assistant", content: [{ type: "toolCall", id: "toolu_1", name: "search", arguments: { query: "phase 5" } }] },+ { role: "toolResult", toolCallId: "toolu_1", content: [{ type: "text", text: "result text" }], isError: false, toolName: "search" },+ ]);+ });++ it("normalizes role alternation in the concrete message adapter", () => {+ const messages = [+ { role: "assistant", content: [{ type: "text", text: "a" }] },+ { role: "assistant", content: [{ type: "text", text: "b" }] },+ { role: "user", content: "u1" },+ { role: "user", content: [{ type: "tool_result", content: "ok" }, { type: "text", text: "u2" }] },+ { role: "assistant", content: "c" },+ { role: "assistant", content: "d" },+ ];++ expect(mergeConsecutiveAssistants(messages)).toHaveLength(4);+ expect(mergeConsecutiveAssistants(messages)[0]).toEqual({+ role: "assistant",+ content: [{ type: "text", text: "a" }, { type: "text", text: "b" }],+ });+ expect(mergeConsecutiveUsers(messages)).toHaveLength(5);+ expect(mergeConsecutiveUsers(messages)[2]).toEqual({+ role: "user",+ content: [{ type: "tool_result", content: "ok" }, { type: "text", text: "u1" }, { type: "text", text: "u2" }],+ });+ expect(ensureAlternation(messages)).toEqual([+ { role: "assistant", content: [{ type: "text", text: "a" }] },+ { role: "user", content: "(no content)" },+ { role: "assistant", content: [{ type: "text", text: "b" }] },+ { role: "user", content: "u1" },+ { role: "user", content: [{ type: "tool_result", content: "ok" }, { type: "text", text: "u2" }] },+ { role: "assistant", content: "c" },+ { role: "user", content: "(no content)" },+ { role: "assistant", content: "d" },+ ]);+ });+});++describe("context-engine lifecycle service seam", () => {+ it("assembles through the lifecycle service seam and preserves no-data passthrough diagnostics", async () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };+ const messages = [{ role: "user", content: "hello world" }];+ const client = {+ getSessionContext: vi.fn().mockResolvedValue({+ latest_archive_overview: "",+ pre_archive_abstracts: [],+ messages: [],+ }),+ };+ const diag = vi.fn();+ const rememberSessionAgentId = vi.fn();+ const buildAssembledContext = vi.fn();++ const result = await assembleOpenVikingSession({+ sessionId: "plain-session",+ sessionKey: "agent:main:main",+ messages,+ tokenBudget: 4096,+ runtimeContext: { senderId: "telegram:123", agentId: "runtime-agent" },+ isMainAssemble: true,+ cfg: { autoRecall: false },+ getClient: vi.fn().mockResolvedValue(client),+ logger,+ resolveAgentId: vi.fn().mockReturnValue("agent_main"),+ rememberSessionAgentId,+ isBypassedSession: () => false,+ diag,+ roughEstimate: () => 42,+ messageDigest: () => [{ role: "user", content: "hello world", tokens: 42, truncated: false }],+ extractAgentMessageText: () => "hello world",+ hasAutoRecallBlock: () => false,+ prependRecallToLatestUserMessage: vi.fn(),+ buildAssembledContext,+ });++ const ovSessionId = openClawSessionToOvStorageId("plain-session", "agent:main:main");+ expect(rememberSessionAgentId).toHaveBeenCalledWith({+ sessionId: "plain-session",+ sessionKey: "agent:main:main",+ agentId: "runtime-agent",+ ovSessionId,+ });+ expect(client.getSessionContext).toHaveBeenCalledWith(ovSessionId, 4096, "agent_main");+ expect(buildAssembledContext).not.toHaveBeenCalled();+ expect(result).toEqual({ messages, estimatedTokens: 42 });+ expect(diag).toHaveBeenCalledWith("assemble_result", ovSessionId, expect.objectContaining({+ passthrough: true,+ reason: "no_ov_data",+ estimatedTokens: 42,+ archiveCount: 0,+ activeCount: 0,+ }));+ });++ it("commits an OpenViking session with stable identity, agent resolution, and memory-count logging", async () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };+ const client = {+ commitSession: vi.fn().mockResolvedValue({+ status: "completed",+ archived: true,+ memories_extracted: { core: 2, preference: 3 },+ task_id: "task-1",+ trace_id: "trace-1",+ }),+ };+ const getClient = vi.fn().mockResolvedValue(client);+ const rememberSessionAgentId = vi.fn();+ const resolveAgentId = vi.fn().mockReturnValue("agent_main");++ const ok = await commitOpenVikingSession({+ sessionId: "plain-session",+ sessionKey: "agent:main:main",+ getClient,+ logger,+ rememberSessionAgentId,+ resolveAgentId,+ isBypassedSession: () => false,+ });++ const ovSessionId = openClawSessionToOvStorageId("plain-session", "agent:main:main");+ expect(ok).toBe(true);+ expect(rememberSessionAgentId).toHaveBeenCalledWith({+ sessionId: "plain-session",+ sessionKey: "agent:main:main",+ ovSessionId,+ });+ expect(resolveAgentId).toHaveBeenCalledWith("plain-session", "agent:main:main", ovSessionId);+ expect(client.commitSession).toHaveBeenCalledWith(ovSessionId, {+ wait: true,+ agentId: "agent_main",+ keepRecentCount: 0,+ });+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining("memories=5"));+ });++ it("compacts an OpenViking session behind the lifecycle service seam", async () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };+ const client = {+ getSessionContext: vi.fn()+ .mockResolvedValueOnce({ estimatedTokens: 321 })+ .mockResolvedValueOnce({+ latest_archive_overview: " compact summary ",+ estimatedTokens: 123,+ messages: [{ role: "user", content: "kept" }],+ pre_archive_abstracts: [],+ }),+ commitSession: vi.fn().mockResolvedValue({+ status: "completed",+ archived: true,+ archive_uri: "ov://archive/archive-9",+ memories_extracted: { core: 4 },+ task_id: "task-9",+ trace_id: "trace-9",+ }),+ };+ const diag = vi.fn();++ const result = await compactOpenVikingSession({+ sessionId: "plain-session",+ sessionKey: "agent:main:main",+ tokenBudget: 4096,+ currentTokenCount: undefined,+ force: true,+ compactionTarget: "budget",+ customInstructions: "keep decisions",+ getClient: vi.fn().mockResolvedValue(client),+ logger,+ resolveAgentId: vi.fn().mockReturnValue("agent_main"),+ isBypassedSession: () => false,+ diag,+ });++ const ovSessionId = openClawSessionToOvStorageId("plain-session", "agent:main:main");+ expect(client.getSessionContext).toHaveBeenNthCalledWith(1, ovSessionId, 4096, "agent_main");+ expect(client.commitSession).toHaveBeenCalledWith(ovSessionId, {+ wait: true,+ agentId: "agent_main",+ keepRecentCount: 0,+ });+ expect(result).toEqual({+ ok: true,+ compacted: true,+ reason: "commit_completed",+ result: {+ summary: "compact summary",+ firstKeptEntryId: "archive-9",+ tokensBefore: 321,+ tokensAfter: 123,+ details: {+ commit: {+ status: "completed",+ archived: true,+ archive_uri: "ov://archive/archive-9",+ memories_extracted: { core: 4 },+ task_id: "task-9",+ trace_id: "trace-9",+ },+ },+ },+ });+ expect(diag).toHaveBeenCalledWith("compact_entry", ovSessionId, expect.objectContaining({+ tokenBudget: 4096,+ force: true,+ compactionTarget: "budget",+ hasCustomInstructions: true,+ }));+ expect(diag).toHaveBeenCalledWith("compact_result", ovSessionId, expect.objectContaining({+ ok: true,+ compacted: true,+ reason: "commit_completed",+ memories: 4,+ tokensBefore: 321,+ tokensAfter: 123,+ latestArchiveId: "archive-9",+ summaryPresent: true,+ }));+ });++ it("captures afterTurn messages and commits behind the lifecycle service seam", async () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };+ const client = {+ addSessionMessage: vi.fn().mockResolvedValue(undefined),+ getSession: vi.fn().mockResolvedValue({ pending_tokens: 25000 }),+ commitSession: vi.fn().mockResolvedValue({+ status: "accepted",+ archived: false,+ task_id: "task-after-1",+ trace_id: "trace-after-1",+ memories_extracted: { core: 2 },+ }),+ };+ const diag = vi.fn();+ const rememberSessionAgentId = vi.fn();++ await afterTurnOpenVikingSession({+ sessionId: "plain-session",+ sessionKey: "agent:main:main",+ messages: [{+ role: "user",+ content: "hello <relevant-memories>hidden</relevant-memories> world",+ timestamp: 1775037660000,+ }],+ prePromptMessageCount: 0,+ runtimeContext: { senderId: "telegram:123", agentId: "runtime-agent" },+ cfg: {+ autoCapture: true,+ commitTokenThreshold: 20000,+ commitKeepRecentCount: 7,+ logFindRequests: false,+ },+ getClient: vi.fn().mockResolvedValue(client),+ logger,+ resolveAgentId: vi.fn().mockReturnValue("agent_main"),+ rememberSessionAgentId,+ isBypassedSession: () => false,+ diag,+ });++ const ovSessionId = openClawSessionToOvStorageId("plain-session", "agent:main:main");+ expect(rememberSessionAgentId).toHaveBeenCalledWith({+ agentId: "runtime-agent",+ sessionId: "plain-session",+ sessionKey: "agent:main:main",+ ovSessionId,+ });+ expect(client.addSessionMessage).toHaveBeenCalledWith(+ ovSessionId,+ "user",+ [{ type: "text", text: "hello world" }],+ "agent_main",+ "2026-04-01T10:01:00.000Z",+ "telegram_123",+ );+ expect(client.getSession).toHaveBeenCalledWith(ovSessionId, "agent_main");+ expect(client.commitSession).toHaveBeenCalledWith(ovSessionId, {+ wait: false,+ agentId: "agent_main",+ keepRecentCount: 7,+ });+ expect(diag).toHaveBeenCalledWith("afterTurn_commit", ovSessionId, expect.objectContaining({+ pendingTokens: 25000,+ commitTokenThreshold: 20000,+ status: "accepted",+ archived: false,+ taskId: "task-after-1",+ extractedMemories: 2,+ senderIdFound: true,+ senderId: "telegram:123",+ }));+ });+});diff --git a/examples/openclaw-plugin/tests/ut/context-engine-utils.test.ts b/examples/openclaw-plugin/tests/ut/context-engine-utils.test.tsindex 47e1bdcc9..901878f88 100644--- a/examples/openclaw-plugin/tests/ut/context-engine-utils.test.ts+++ b/examples/openclaw-plugin/tests/ut/context-engine-utils.test.ts@@ -3,8 +3,10 @@ import { describe, expect, it } from "vitest";import {openClawSessionToOvStorageId,openClawSessionRefToOvStorageId,+} from "../../routing/identity-routing.js";+import {formatMessageFaithful,-} from "../../context-engine.js";+} from "../../services/context-message-adapter.js";describe("openClawSessionToOvStorageId", () => {it("passes through UUID sessionId as lowercase", () => {diff --git a/examples/openclaw-plugin/tests/ut/identity-routing.test.ts b/examples/openclaw-plugin/tests/ut/identity-routing.test.tsnew file mode 100644index 000000000..e1a06f885--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/identity-routing.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";++import {+ createSessionAgentResolver,+ openClawSessionRefToOvStorageId,+ openClawSessionToOvStorageId,+ sanitizeOpenVikingAgentIdHeader,+} from "../../routing/identity-routing.js";++describe("identity routing registry", () => {+ it("keeps OpenClaw session to OpenViking storage id behavior byte-compatible", () => {+ const uuid = "A1B2C3D4-E5F6-7890-ABCD-EF1234567890";+ expect(openClawSessionToOvStorageId(uuid, undefined)).toBe(uuid.toLowerCase());+ expect(openClawSessionToOvStorageId("plain-session", undefined)).toBe("plain-session");+ expect(openClawSessionToOvStorageId(undefined, "agent:myagent:session123")).toMatch(/^[a-f0-9]{64}$/);+ expect(openClawSessionToOvStorageId("C:\\Users\\test", undefined)).toMatch(/^[a-f0-9]{64}$/);+ expect(() => openClawSessionToOvStorageId("", "")).toThrow("need sessionId or sessionKey");+ });++ it("normalizes hook/tool session refs in the concrete routing module", () => {+ expect(openClawSessionRefToOvStorageId(" A1B2C3D4-E5F6-7890-ABCD-EF1234567890 ")).toBe(+ "a1b2c3d4-e5f6-7890-abcd-ef1234567890",+ );+ expect(openClawSessionRefToOvStorageId("safe-session")).toBe("safe-session");+ expect(openClawSessionRefToOvStorageId("C:\\bad\\path")).toMatch(/^[a-f0-9]{64}$/);+ expect(() => openClawSessionRefToOvStorageId(" ")).toThrow("empty session ref");+ });++ it("sanitizes OpenViking actor peer headers in the concrete routing module", () => {+ expect(sanitizeOpenVikingAgentIdHeader("agent:role:v1")).toBe("agent_role_v1");+ expect(sanitizeOpenVikingAgentIdHeader(" ")).toBe("default");+ expect(sanitizeOpenVikingAgentIdHeader("@#$%")).toBe("ov_agent");+ });++ it("resolves session-scoped agents with aliases and config prefix unchanged", () => {+ const resolver = createSessionAgentResolver("prefix");+ resolver.remember({ sessionId: "s1", sessionKey: "agent:worker:session123", agentId: "agent-abc" });++ expect(resolver.resolve("s1")).toMatchObject({+ resolved: "prefix_agent-abc",+ branch: "session_resolved",+ fromExplicitBinding: true,+ });+ expect(resolver.resolve(undefined, "agent:worker:session123")).toMatchObject({+ resolved: "prefix_agent-abc",+ branch: "session_resolved",+ });+ expect(createSessionAgentResolver("default").resolve()).toMatchObject({+ resolved: "main",+ branch: "default_no_session",+ });+ expect(createSessionAgentResolver("prefix").resolve(undefined, "agent:worker:session123")).toMatchObject({+ resolved: "prefix_worker",+ branch: "session_resolved",+ });+ });+});diff --git a/examples/openclaw-plugin/tests/ut/index-utils.test.ts b/examples/openclaw-plugin/tests/ut/index-utils.test.tsindex 97cb05eda..2adbeada2 100644--- a/examples/openclaw-plugin/tests/ut/index-utils.test.ts+++ b/examples/openclaw-plugin/tests/ut/index-utils.test.ts@@ -1,46 +1,46 @@import { describe, expect, it } from "vitest";+import { prepareRecallQuery } from "../../auto-recall.js";import {- prepareRecallQuery,- sanitizeRuntimeAgentId,createSessionAgentResolver,-} from "../../index.js";+ sanitizeOpenVikingAgentIdHeader,+} from "../../routing/identity-routing.js";-describe("sanitizeRuntimeAgentId", () => {+describe("sanitizeOpenVikingAgentIdHeader", () => {it("keeps clean alphanumeric+dash+underscore strings", () => {- expect(sanitizeRuntimeAgentId("my-agent_v2")).toBe("my-agent_v2");+ expect(sanitizeOpenVikingAgentIdHeader("my-agent_v2")).toBe("my-agent_v2");});it("replaces special characters with underscore", () => {- expect(sanitizeRuntimeAgentId("agent:role:v1")).toBe("agent_role_v1");+ expect(sanitizeOpenVikingAgentIdHeader("agent:role:v1")).toBe("agent_role_v1");});it("collapses multiple underscores", () => {- expect(sanitizeRuntimeAgentId("a::b:::c")).toBe("a_b_c");+ expect(sanitizeOpenVikingAgentIdHeader("a::b:::c")).toBe("a_b_c");});it("strips leading/trailing underscores", () => {- expect(sanitizeRuntimeAgentId("_agent_")).toBe("agent");+ expect(sanitizeOpenVikingAgentIdHeader("_agent_")).toBe("agent");});it("returns 'default' for empty string", () => {- expect(sanitizeRuntimeAgentId("")).toBe("default");+ expect(sanitizeOpenVikingAgentIdHeader("")).toBe("default");});it("returns 'default' for whitespace-only", () => {- expect(sanitizeRuntimeAgentId(" ")).toBe("default");+ expect(sanitizeOpenVikingAgentIdHeader(" ")).toBe("default");});it("returns 'ov_agent' for all-symbol input", () => {- expect(sanitizeRuntimeAgentId("@#$%")).toBe("ov_agent");+ expect(sanitizeOpenVikingAgentIdHeader("@#$%")).toBe("ov_agent");});it("handles spaces by replacing with underscore", () => {- expect(sanitizeRuntimeAgentId("my agent")).toBe("my_agent");+ expect(sanitizeOpenVikingAgentIdHeader("my agent")).toBe("my_agent");});it("preserves mixed case", () => {- expect(sanitizeRuntimeAgentId("MyAgent")).toBe("MyAgent");+ expect(sanitizeOpenVikingAgentIdHeader("MyAgent")).toBe("MyAgent");});});diff --git a/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts b/examples/openclaw-plugin/tests/ut/manifest-contracts.test.tsindex 45f272b77..1248d28c2 100644--- a/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts+++ b/examples/openclaw-plugin/tests/ut/manifest-contracts.test.ts@@ -11,6 +11,7 @@ const manifest = JSON.parse() as {activation?: { onStartup?: boolean; onCapabilities?: string[] };contracts?: { tools?: string[] };+ configSchema?: { properties?: Record<string, unknown> };};const packageJson = JSON.parse(readFileSync(resolve(pluginRoot, "package.json"), "utf8"),@@ -73,11 +74,30 @@ describe("OpenClaw 5.2 manifest contracts", () => {expect(manifest.activation?.onStartup).toBe(true);expect(manifest.activation?.onCapabilities?.toSorted()).toEqual(["hook", "tool"]);});++ it("declares recall trace configuration schema keys", () => {+ expect(Object.keys(manifest.configSchema?.properties ?? {})).toEqual(expect.arrayContaining([+ "traceRecall",+ "traceRecallPersist",+ "traceRecallDir",+ "traceRecallRetentionDays",+ "traceRecallLoadRecentDays",+ "traceRecallMaxEntries",+ "traceRecallMaxResultsPerSearch",+ "traceRecallPreviewChars",+ "traceRecallQueryMaxChars",+ "traceRecallQueryMaxDays",+ "traceRecallIncludeContentByDefault",+ "traceRecallIncludeRawUserPreview",+ "recallTargetTypes",+ ]));+ });});describe("OpenClaw 5.5 package runtime contract", () => {it("builds and publishes compiled runtime output for TypeScript entries", () => {- expect(packageJson.scripts?.build).toBe("tsc -p tsconfig.build.json");+ expect(packageJson.scripts?.build).toContain("rmSync('dist'");+ expect(packageJson.scripts?.build).toContain("tsc -p tsconfig.build.json");expect(packageJson.scripts?.prepack).toBe("npm run build");expect(packageJson.files).toContain("dist/");expect(packageJson.files).toContain("install-manifest.json");@@ -93,12 +113,12 @@ describe("OpenClaw 5.5 package runtime contract", () => {});expect(installManifest.files?.required).toEqual(expect.arrayContaining(["index.ts",+ "recall-trace.ts","commands/setup.ts","tsconfig.json","tsconfig.build.json","package.json","openclaw.plugin.json",- "recall-trace.ts",]));expect(installManifest.compatibility?.minOpenclawVersion).toBe("2026.4.8");});diff --git a/examples/openclaw-plugin/tests/ut/openviking-tools-registry.test.ts b/examples/openclaw-plugin/tests/ut/openviking-tools-registry.test.tsnew file mode 100644index 000000000..ad28b1d05--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/openviking-tools-registry.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from "vitest";++import { memoryOpenVikingConfigSchema } from "../../config.js";+import {+ OPENVIKING_ADD_RESOURCE_TOOL_NAME,+ OPENVIKING_ALL_TOOL_NAMES,+ OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES,+ OPENVIKING_TOOL_GROUPS,+ OPENVIKING_TOOL_SPECS,+} from "../../registries/openviking-tools.js";++const DEFAULT_TOOL_NAMES = [+ "add_skill",+ "ov_search",+ "ov_read",+ "ov_multi_read",+ "ov_list",+ "memory_recall",+ "ov_recall_trace",+ "memory_store",+ "memory_forget",+ "ov_archive_search",+ "ov_archive_expand",+ "openviking_tool_result_read",+ "openviking_tool_result_search",+ "openviking_tool_result_list",+] as const;++describe("openviking tool registry", () => {+ it("defines every tool once in registration order", () => {+ expect(OPENVIKING_ADD_RESOURCE_TOOL_NAME).toBe("add_resource");+ expect(OPENVIKING_ALL_TOOL_NAMES).toEqual(["add_resource", ...DEFAULT_TOOL_NAMES]);+ expect(OPENVIKING_TOOL_SPECS.map((spec) => spec.name)).toEqual(OPENVIKING_ALL_TOOL_NAMES);+ expect(new Set(OPENVIKING_TOOL_SPECS.map((spec) => spec.name)).size).toBe(OPENVIKING_TOOL_SPECS.length);+ });++ it("derives default enabled tools and groups from ToolSpec", () => {+ expect(OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES).toEqual(DEFAULT_TOOL_NAMES);+ expect(OPENVIKING_TOOL_SPECS.filter((spec) => spec.defaultEnabled).map((spec) => spec.name)).toEqual(+ OPENVIKING_DEFAULT_ENABLED_TOOL_NAMES,+ );+ expect(OPENVIKING_TOOL_GROUPS).toEqual({+ all: ["add_resource", ...DEFAULT_TOOL_NAMES],+ default: DEFAULT_TOOL_NAMES,+ memory: ["memory_recall", "memory_store", "memory_forget"],+ resource_query: ["ov_search", "ov_read", "ov_multi_read", "ov_list"],+ import: ["add_resource", "add_skill"],+ recall_trace: ["ov_recall_trace"],+ archive: ["ov_archive_search", "ov_archive_expand"],+ tool_result: [+ "openviking_tool_result_read",+ "openviking_tool_result_search",+ "openviking_tool_result_list",+ ],+ });+ });++ it("keeps add_resource behind the legacy enableAddResourceTool flag", () => {+ expect(OPENVIKING_TOOL_SPECS.find((spec) => spec.name === "add_resource")).toMatchObject({+ defaultEnabled: false,+ requiresLegacyFlag: "enableAddResourceTool",+ });++ expect(memoryOpenVikingConfigSchema.parse({}).enabledTools).not.toContain("add_resource");+ expect(memoryOpenVikingConfigSchema.parse({ enableAddResourceTool: true }).enabledTools).toContain("add_resource");+ });+});diff --git a/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts b/examples/openclaw-plugin/tests/ut/package-install-contract.test.tsindex d2706df62..81156ff59 100644--- a/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts+++ b/examples/openclaw-plugin/tests/ut/package-install-contract.test.ts@@ -15,7 +15,8 @@ describe("OpenClaw plugin package and install contract", () => {expect(packageJson.openclaw.extensions).toEqual(["./dist/index.js"]);expect(packageJson.openclaw.setupEntry).toBe("./dist/commands/setup.js");- expect(packageJson.scripts.build).toBe("tsc -p tsconfig.build.json");+ expect(packageJson.scripts.build).toContain("rmSync('dist'");+ expect(packageJson.scripts.build).toContain("tsc -p tsconfig.build.json");});it("keeps source install manifest aligned with required source files", () => {@@ -40,7 +41,14 @@ describe("OpenClaw plugin package and install contract", () => {"session-transcript-repair.ts","runtime-utils.ts","recall-trace.ts",+ "query-config.ts",+ "adapters/",+ "registries/",+ "routing/",+ "plugin/",+ "services/","commands/setup.ts",+ "config/feature-gates.json","tsconfig.json","tsconfig.build.json","package.json",@@ -57,7 +65,13 @@ describe("OpenClaw plugin package and install contract", () => {expect(packageJson.files).toEqual(expect.arrayContaining(["dist/","*.ts",+ "adapters/","commands/setup.ts",+ "config/feature-gates.json",+ "registries/",+ "routing/",+ "plugin/",+ "services/","install-manifest.json","openclaw.plugin.json","package.json",diff --git a/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts b/examples/openclaw-plugin/tests/ut/plugin-modules.test.tsnew file mode 100644index 000000000..aae9ea48c--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/plugin-modules.test.ts@@ -0,0 +1,1008 @@+import { describe, expect, it, vi } from "vitest";++import {+ createOpenVikingCommandDefinitions,+} from "../../plugin/openviking-command-definitions.js";+import { registerOpenVikingContextEngine } from "../../plugin/openviking-context-engine-registration.js";+import { createOpenVikingQueryConfigCommandHandler } from "../../plugin/openviking-query-config-command.js";+import { createOpenVikingQueryRuntime } from "../../plugin/openviking-query-runtime.js";+import { createOpenVikingRecallTraceRuntime } from "../../plugin/openviking-recall-trace-runtime.js";+import {+ createOpenVikingToolRegistrar,+} from "../../plugin/tool-registration.js";+import {+ registerOpenVikingCommands,+} from "../../plugin/command-registration.js";+import {+ RECALL_TRACE_ROUTE_PATHS,+ registerRecallTraceRoutes,+} from "../../plugin/recall-trace-routes.js";+import { createOpenVikingService } from "../../plugin/openviking-services.js";+import { registerOpenVikingArchiveTools } from "../../plugin/openviking-archive-tools.js";+import { registerOpenVikingImportTools } from "../../plugin/openviking-import-tools.js";+import { createOpenVikingImportRuntime } from "../../plugin/openviking-import-runtime.js";+import { registerOpenVikingLifecycleHooks } from "../../plugin/openviking-lifecycle-hooks.js";+import { registerOpenVikingMemoryTools } from "../../plugin/openviking-memory-tools.js";+import { registerOpenVikingMemoryRecallTools } from "../../plugin/openviking-memory-recall-tools.js";+import { registerOpenVikingQueryTools } from "../../plugin/openviking-query-tools.js";+import { registerOpenVikingRecallTraceTools } from "../../plugin/openviking-recall-trace-tools.js";+import { registerOpenVikingToolResultTools } from "../../plugin/openviking-tool-result-tools.js";++describe("plugin module seams", () => {+ it("registers only enabled OpenViking tools through the tool-registration seam", () => {+ const api = { registerTool: vi.fn() };+ const logger = { debug: vi.fn() };+ const registrar = createOpenVikingToolRegistrar({+ api,+ enabledToolNames: new Set(["ov_search"]),+ logger,+ });+ const toolFactory = () => ({ name: "ov_search" });+ const disabledFactory = () => ({ name: "memory_store" });++ registrar(toolFactory, { name: "ov_search" });+ registrar(disabledFactory, { name: "memory_store" });++ expect(api.registerTool).toHaveBeenCalledTimes(1);+ expect(api.registerTool).toHaveBeenCalledWith(toolFactory, { name: "ov_search" });+ expect(logger.debug).toHaveBeenCalledWith("openviking: tool memory_store disabled by config");+ });++ it("registers command definitions without changing names or handlers", async () => {+ const command = {+ name: "ov-search",+ description: "Search OpenViking resources and skills.",+ acceptsArgs: true,+ handler: vi.fn().mockResolvedValue({ text: "ok" }),+ };+ const api = { registerCommand: vi.fn() };++ registerOpenVikingCommands(api, [command]);++ expect(api.registerCommand).toHaveBeenCalledWith(command);+ const registered = api.registerCommand.mock.calls[0]?.[0];+ await expect(registered.handler({ args: "query" })).resolves.toEqual({ text: "ok" });+ expect(command.handler).toHaveBeenCalledWith({ args: "query" });+ });++ it("builds OpenViking command definitions through a dedicated plugin module", async () => {+ const addResourceOpenViking = vi.fn().mockResolvedValue({+ content: [{ type: "text" as const, text: "resource imported" }],+ details: { action: "resource_imported" },+ });+ const addSkillOpenViking = vi.fn().mockResolvedValue({+ content: [{ type: "text" as const, text: "skill imported" }],+ details: { action: "skill_imported" },+ });+ const searchOpenViking = vi.fn().mockResolvedValue({+ content: [{ type: "text" as const, text: "search result" }],+ details: { action: "searched" },+ });+ const handleQueryConfigCommand = vi.fn().mockResolvedValue({ text: "query config", details: { action: "query_config" } });+ const queryRecallTraces = vi.fn().mockResolvedValue({ entries: [{ traceId: "trace-1" }], lookupLayer: "memory", warnings: [] });+ const formatRecallTraceText = vi.fn().mockReturnValue("trace text");+ const deps = {+ resolvePluginSessionRouting: () => ({ agentId: "agent-main", sessionId: "session-1", ovSessionId: "ov-session-1" }),+ isBypassedSession: () => false,+ makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),+ parseAddResourceCommandArgs: vi.fn().mockReturnValue({ source: "https://example.com/doc", wait: true }),+ parseAddSkillCommandArgs: vi.fn().mockReturnValue({ source: "skill.md" }),+ parseOVSearchCommandArgs: vi.fn().mockReturnValue({ query: "docs", uri: "viking://resources", limit: 3 }),+ addResourceOpenViking,+ addSkillOpenViking,+ searchOpenViking,+ handleQueryConfigCommand,+ queryRecallTraces,+ formatRecallTraceText,+ };++ const commands = createOpenVikingCommandDefinitions(deps);++ expect(commands.map((command) => command.name)).toEqual([+ "add-resource",+ "add-skill",+ "ov-search",+ "ov-query-config",+ "ov-recall-trace",+ ]);++ await expect(commands[0]!.handler({ args: "https://example.com/doc", sessionId: "session-1" })).resolves.toEqual({+ text: "resource imported",+ details: { action: "resource_imported" },+ });+ expect(addResourceOpenViking).toHaveBeenCalledWith({ source: "https://example.com/doc", wait: true }, "agent-main");++ await commands[1]!.handler({ args: "skill.md" });+ expect(addSkillOpenViking).toHaveBeenCalledWith({ source: "skill.md" }, "agent-main");++ await commands[2]!.handler({ args: "docs --uri viking://resources --limit 3" });+ expect(searchOpenViking).toHaveBeenCalledWith({ query: "docs", uri: "viking://resources", limit: 3 }, "agent-main", {+ agentId: "agent-main",+ sessionId: "session-1",+ ovSessionId: "ov-session-1",+ });++ await expect(commands[3]!.handler({ args: "get" })).resolves.toEqual({ text: "query config", details: { action: "query_config" } });+ expect(handleQueryConfigCommand).toHaveBeenCalledWith({ args: "get" });++ await expect(commands[4]!.handler({ args: "--source ov_search --limit 5" })).resolves.toEqual({+ text: "trace text",+ details: { count: 1, lookupLayer: "memory", warnings: [], entries: [{ traceId: "trace-1" }] },+ });+ expect(queryRecallTraces).toHaveBeenCalledWith(expect.objectContaining({ source: "ov_search", limit: 5, includeContent: false }), {+ agentId: "agent-main",+ sessionId: "session-1",+ ovSessionId: "ov-session-1",+ });+ expect(formatRecallTraceText).toHaveBeenCalledWith({ entries: [{ traceId: "trace-1" }], lookupLayer: "memory", warnings: [] });+ });++ it("keeps recall trace route paths stable across legacy and HTTP adapters", () => {+ expect(RECALL_TRACE_ROUTE_PATHS).toEqual([+ "/api/openviking/recall-traces",+ "/api/openviking/uri-detail",+ "/api/openviking/recall-traces/latest-ov-search-list",+ "/api/openviking/recall-traces/:traceId",+ ]);++ const adapter = {+ registerRoute: vi.fn(),+ registerHttpRoute: vi.fn(),+ };+ const handlers = {+ handleRecallTraces: vi.fn().mockResolvedValue({ status: 200, body: { ok: true } }),+ handleUriDetail: vi.fn().mockResolvedValue({ status: 200, body: { ok: true } }),+ handleLatestOvSearchList: vi.fn().mockResolvedValue({ status: 200, body: { ok: true } }),+ };++ const registered = registerRecallTraceRoutes(adapter, handlers);++ expect(registered).toBe(true);+ expect(adapter.registerRoute.mock.calls.map(([route]) => route.path)).toEqual(RECALL_TRACE_ROUTE_PATHS);+ expect(adapter.registerHttpRoute.mock.calls.map(([route]) => route.path)).toEqual([+ "/api/openviking/recall-traces",+ "/api/openviking/uri-detail",+ "/api/openviking/recall-traces/latest-ov-search-list",+ "/api/openviking/recall-traces",+ ]);+ });++ it("creates recall trace route handlers through a dedicated runtime module", async () => {+ const entry = {+ schemaVersion: "1.0" as const,+ traceId: "trace-1",+ ts: Date.UTC(2026, 0, 1),+ sessionId: "session-1",+ sessionKey: "session-key-1",+ ovSessionId: "ov-session-1",+ agentId: "agent-main",+ source: "ov_search" as const,+ operationType: "semantic_find" as const,+ resourceTypes: ["resource" as const],+ trigger: { query: "project spec" },+ searches: [{+ resourceType: "resource" as const,+ targetUriResolved: "viking://resources",+ limit: 5,+ durationMs: 1,+ total: 2,+ results: [+ { uri: "viking://resources/project/spec.md", resourceType: "resource" as const, category: "doc", score: 0.91, abstractPreview: "Search abstract", resultType: "resource" as const },+ { uri: "viking://user/skills/debugger", resourceType: "agent" as const, category: "skill", score: 0.8, abstractPreview: "Skill abstract", resultType: "skill" as const },+ ],+ }],+ selected: [{ uri: "viking://resources/project/spec.md", resourceType: "resource" as const, category: "selected-doc", score: 0.95, abstractPreview: "Selected abstract" }],+ stats: { candidateCount: 2, selectedCount: 1, injectedCount: 0 },+ };+ const traceRecorder = {+ queryWithFallback: vi.fn().mockResolvedValue({ entries: [entry], lookupLayer: "memory", warnings: [] }),+ };+ const read = vi.fn().mockResolvedValue("0123456789abcdefghijklmnopqrstuvwxyz");+ const runtime = createOpenVikingRecallTraceRuntime({+ getClient: async () => ({ read }),+ resolvePluginSessionRouting: () => ({ agentId: "agent-main", sessionId: "session-1", sessionKey: "session-key-1", ovSessionId: "ov-session-1" }),+ traceRecorder,+ registerRecallTraceRoutes: vi.fn().mockReturnValue(true),+ normalizeResourceTypes: (value) => Array.isArray(value) ? value : [String(value)],+ clampScore: (value) => value,+ previewText: (value, maxChars) => typeof value === "string" ? value.slice(0, maxChars) : undefined,+ cfg: { traceRecallIncludeContentByDefault: true, traceRecallPreviewChars: 80, recallMaxContentChars: 100 },+ });++ const list = await runtime.routeHandlers.handleLatestOvSearchList({ query: { sessionkey: "session-key-1", includeSkills: "false", limit: "5" } }) as { status: number; body: any };+ expect(list.status).toBe(200);+ expect(list.body.items).toHaveLength(1);+ expect(list.body.items[0]).toMatchObject({+ uri: "viking://resources/project/spec.md",+ abstractPreview: "Selected abstract",+ source: "selected",+ targetUri: "viking://resources",+ });++ const detail = await runtime.routeHandlers.handleUriDetail({ query: { uri: "viking://resources/project/spec.md", traceId: "trace-1", offset: "10", contentLimit: "5" } }) as { status: number; body: any };+ expect(detail.status).toBe(200);+ expect(detail.body.uriType).toBe("resource");+ expect(detail.body.metadata).toMatchObject({ category: "selected-doc", sourceTraceId: "trace-1", source: "ov_search" });+ expect(detail.body.content).toMatchObject({ text: "abcde", offset: 10, limit: 5, hasMore: true });++ read.mockClear();+ const kebabDetail = await runtime.routeHandlers.handleUriDetail({ query: { uri: "viking://resources/project/spec.md", "trace-id": "trace-1", offset: "10", "content-limit": "5", "include-content": "false" } }) as { status: number; body: any };+ expect(kebabDetail.status).toBe(200);+ expect(kebabDetail.body.metadata).toMatchObject({ category: "selected-doc", sourceTraceId: "trace-1", source: "ov_search" });+ expect(kebabDetail.body).not.toHaveProperty("content");+ expect(read).not.toHaveBeenCalled();++ traceRecorder.queryWithFallback.mockClear();+ read.mockClear();+ const traces = await runtime.routeHandlers.handleRecallTraces({ query: { "trace-id": "trace-1", "session-key": "session-key-1", "include-content": "false", limit: "1" } }) as { status: number; body: any };+ expect(traces.status).toBe(200);+ expect(traceRecorder.queryWithFallback).toHaveBeenCalledWith(expect.objectContaining({+ traceId: "trace-1",+ sessionKey: "session-key-1",+ limit: 1,+ }));+ expect(read).not.toHaveBeenCalled();+ });++ it("creates OpenViking query runtime for search/read behavior", async () => {+ const find = vi.fn(async (_query: string, options: { targetUri?: string }) => {+ if (options.targetUri === "viking://resources") {+ return {+ memories: [],+ resources: [{ uri: "viking://resources/spec.md", abstract: "Spec abstract", score: 0.91, category: "doc" }],+ skills: [],+ total: 1,+ };+ }+ return {+ memories: [],+ resources: [],+ skills: [{ uri: "viking://user/skills/debugger", overview: "Debugger overview", score: 0.8, category: "skill" }],+ total: 1,+ };+ });+ const read = vi.fn().mockResolvedValue({ text: "full content" });+ const recordAndFlush = vi.fn();+ const runtime = createOpenVikingQueryRuntime({+ getClient: async () => ({ find, read, list: vi.fn().mockResolvedValue([]) }),+ queryConfigStore: { getEffective: vi.fn().mockResolvedValue({ ovSearchLimit: 2 }) },+ toQueryConfigContext: (session) => session,+ traceRecorder: { recordAndFlush },+ inferRecallResourceType: (uri) => uri.includes("skills") ? "agent" : "resource",+ createTraceId: () => "trace-query-1",+ boundTraceQuery: (query) => ({ query }),+ previewText: (value) => typeof value === "string" ? value : undefined,+ logger: { warn: vi.fn() },+ cfg: { traceRecallMaxResultsPerSearch: 5, traceRecallPreviewChars: 80, traceRecallQueryMaxChars: 120 },+ });++ const search = await runtime.searchOpenViking({ query: "spec" }, "agent-main", { agentId: "agent-main", sessionId: "session-1" }) as any;+ expect(find.mock.calls.map(([, options]) => options.targetUri)).toEqual(["viking://resources", "viking://user/skills"]);+ expect(search.content[0].text).toContain("Found 2 OpenViking results for \"spec\"");+ expect(search.details).toMatchObject({ action: "searched", total: 2 });+ expect(recordAndFlush).toHaveBeenCalledWith(expect.objectContaining({+ traceId: "trace-query-1",+ source: "ov_search",+ agentId: "agent-main",+ stats: { candidateCount: 2, selectedCount: 2, injectedCount: 0 },+ }));++ const readResult = await runtime.readOpenVikingContent({ uri: "viking://resources/spec.md" }, "agent-main") as any;+ expect(read).toHaveBeenCalledWith("viking://resources/spec.md", "agent-main");+ expect(readResult.content[0].text).toContain("--- START OF viking://resources/spec.md ---");+ });++ it("handles OpenViking query config commands through a dedicated module", async () => {+ const session = { agentId: "agent-main", sessionId: "session-1", sessionKey: "key-1", ovSessionId: "ov-session-1" };+ const queryCtx = { agentId: "agent-main", sessionId: "session-1", sessionKey: "key-1", ovSessionId: "ov-session-1" };+ const effective = { ovSearchLimit: 7, targetUri: "viking://resources", warnings: [] };+ const queryConfigStore = {+ getEffective: vi.fn().mockResolvedValue(effective),+ set: vi.fn().mockResolvedValue(undefined),+ unset: vi.fn().mockResolvedValue(undefined),+ reset: vi.fn().mockResolvedValue(undefined),+ };+ const normalizeRuntimeQueryParams = vi.fn().mockReturnValue({ params: { ovSearchLimit: 3 }, warnings: ["normalized"] });+ const handler = createOpenVikingQueryConfigCommandHandler({+ resolvePluginSessionRouting: vi.fn().mockReturnValue(session),+ toQueryConfigContext: vi.fn().mockReturnValue(queryCtx),+ queryConfigStore,+ normalizeRuntimeQueryParams,+ });++ await expect(handler({ args: "get --scope claw" })).resolves.toEqual({+ text: JSON.stringify({ scope: "claw", effective }, null, 2),+ details: { scope: "claw", effective },+ });++ await expect(handler({ args: "set --ovSearchLimit 3 --scope session" })).resolves.toMatchObject({+ text: "Updated OpenViking query config (session). Warnings: normalized",+ details: { scope: "session", params: { ovSearchLimit: 3 }, warnings: ["normalized"], effective },+ });+ expect(normalizeRuntimeQueryParams).toHaveBeenCalledWith({ ovSearchLimit: 3 });+ expect(queryConfigStore.set).toHaveBeenCalledWith("session", queryCtx, { ovSearchLimit: 3 });++ await expect(handler({ args: "unset ovSearchLimit targetUri --scope claw" })).resolves.toMatchObject({+ text: "Unset OpenViking query config fields (claw): ovSearchLimit, targetUri",+ details: { scope: "claw", fields: ["ovSearchLimit", "targetUri"], effective },+ });+ expect(queryConfigStore.unset).toHaveBeenCalledWith("claw", queryCtx, ["ovSearchLimit", "targetUri"]);++ await expect(handler({ args: "reset" })).resolves.toMatchObject({+ text: "Reset OpenViking query config (session).",+ details: { scope: "session", effective },+ });+ expect(queryConfigStore.reset).toHaveBeenCalledWith("session", queryCtx);+ });++ it("creates OpenViking import runtime for command import behavior", async () => {+ const addResource = vi.fn().mockResolvedValue({+ root_uri: "viking://resources/project-docs",+ warnings: ["kept existing metadata"],+ task_id: "task-resource-1",+ });+ const addSkill = vi.fn().mockResolvedValue({+ uri: "viking://user/skills/debugger",+ name: "debugger",+ task_id: "task-skill-1",+ });+ const runtime = createOpenVikingImportRuntime({+ getClient: async () => ({ addResource, addSkill }),+ });++ await expect(runtime.addResourceOpenViking({+ source: "./docs",+ to: "viking://resources/project-docs",+ parent: "viking://resources",+ reason: "project docs",+ instruction: "extract API notes",+ wait: true,+ timeout: 30,+ }, "agent-main")).resolves.toEqual({+ content: [{ type: "text", text: "Imported OpenViking resource. viking://resources/project-docs Warnings: kept existing metadata" }],+ details: {+ action: "resource_imported",+ root_uri: "viking://resources/project-docs",+ warnings: ["kept existing metadata"],+ task_id: "task-resource-1",+ },+ });+ expect(addResource).toHaveBeenCalledWith({+ pathOrUrl: "./docs",+ to: "viking://resources/project-docs",+ parent: "viking://resources",+ reason: "project docs",+ instruction: "extract API notes",+ wait: true,+ timeout: 30,+ }, "agent-main");++ await expect(runtime.addSkillOpenViking({+ source: "./skills/debugger/SKILL.md",+ data: "skill body",+ wait: false,+ timeout: 5,+ }, "agent-main")).resolves.toEqual({+ content: [{ type: "text", text: "Imported OpenViking skill (debugger). viking://user/skills/debugger" }],+ details: {+ action: "skill_imported",+ uri: "viking://user/skills/debugger",+ name: "debugger",+ task_id: "task-skill-1",+ },+ });+ expect(addSkill).toHaveBeenCalledWith({+ path: "./skills/debugger/SKILL.md",+ data: "skill body",+ wait: false,+ timeout: 5,+ }, "agent-main");+ });++ it("creates the OpenViking lifecycle service without changing start/stop behavior", async () => {+ const healthCheck = vi.fn().mockResolvedValue({ ok: true });+ const logger = { info: vi.fn(), warn: vi.fn() };+ const registerRecallTraceRoutes = vi.fn().mockReturnValue(true);+ const service = createOpenVikingService({+ cfg: { baseUrl: "http://127.0.0.1:1933", targetUri: "viking://resources" },+ getClient: async () => ({ healthCheck }),+ logger,+ recallTraceHttpRoutesRegistered: false,+ registerRecallTraceRoutes,+ });++ expect(service.id).toBe("openviking");+ await service.start({ registerRoute: vi.fn() });+ service.stop();++ expect(registerRecallTraceRoutes).toHaveBeenCalled();+ expect(healthCheck).toHaveBeenCalled();+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining("openviking: initialized"));+ expect(logger.info).toHaveBeenCalledWith("openviking: registered recall trace Gateway routes");+ expect(logger.info).toHaveBeenCalledWith("openviking: stopped");+ });++ it("registers lifecycle hooks through a dedicated plugin module", async () => {+ const handlers = new Map<string, Function>();+ const api = {+ on: vi.fn((hookName: string, handler: Function) => {+ handlers.set(hookName, handler);+ }),+ };+ const rememberSessionAgentId = vi.fn();+ const verboseRoutingInfo = vi.fn();+ const commitOVSession = vi.fn().mockResolvedValue(true);+ const logger = { info: vi.fn(), warn: vi.fn() };++ registerOpenVikingLifecycleHooks({+ api,+ rememberSessionAgentId,+ isBypassedSession: (ctx) => ctx?.sessionKey === "bypass",+ verboseRoutingInfo,+ getContextEngine: () => ({ commitOVSession }),+ logger,+ });++ expect(api.on.mock.calls.map(([hookName]) => hookName)).toEqual([+ "session_start",+ "session_end",+ "before_reset",+ "after_compaction",+ ]);++ await handlers.get("session_start")?.({}, { sessionId: "session-1", agentId: "agent-main" });+ await handlers.get("session_end")?.({}, { sessionId: "session-2", agentId: "agent-main" });+ expect(rememberSessionAgentId).toHaveBeenCalledWith({ sessionId: "session-1", agentId: "agent-main" });+ expect(rememberSessionAgentId).toHaveBeenCalledWith({ sessionId: "session-2", agentId: "agent-main" });++ await handlers.get("before_reset")?.({}, { sessionId: "session-3", sessionKey: "key-3" });+ expect(commitOVSession).toHaveBeenCalledWith({ sessionId: "session-3", sessionKey: "key-3" });+ expect(logger.info).toHaveBeenCalledWith("openviking: committed OV session on reset for session=session-3");++ await handlers.get("before_reset")?.({}, { sessionId: "session-4", sessionKey: "bypass" });+ expect(verboseRoutingInfo).toHaveBeenCalledWith(expect.stringContaining("bypassing before_reset"));+ expect(commitOVSession).toHaveBeenCalledTimes(1);+ });++ it("registers the context engine through a dedicated plugin module", () => {+ const engine = { id: "openviking", commitOVSession: vi.fn() };+ const api = { registerContextEngine: vi.fn() };+ const logger = { info: vi.fn(), warn: vi.fn() };+ const getClient = vi.fn();+ const resolveAgentId = vi.fn();+ const rememberSessionAgentId = vi.fn();+ const queryConfigStore = { get: vi.fn() };+ const traceRecorder = { record: vi.fn() };+ const createContextEngine = vi.fn().mockReturnValue(engine);+ const setContextEngineRef = vi.fn();++ registerOpenVikingContextEngine({+ api,+ plugin: { id: "openviking", name: "OpenViking" },+ version: "0.1.0",+ cfg: { baseUrl: "http://127.0.0.1:1933" },+ logger,+ getClient,+ resolveAgentId,+ rememberSessionAgentId,+ queryConfigStore,+ traceRecorder,+ createContextEngine,+ setContextEngineRef,+ });++ expect(api.registerContextEngine).toHaveBeenCalledWith("openviking", expect.any(Function));+ expect(createContextEngine).not.toHaveBeenCalled();+ const registeredFactory = api.registerContextEngine.mock.calls[0]?.[1];++ expect(registeredFactory()).toBe(engine);+ expect(createContextEngine).toHaveBeenCalledWith({+ id: "openviking",+ name: "OpenViking",+ version: "0.1.0",+ cfg: { baseUrl: "http://127.0.0.1:1933" },+ logger,+ getClient,+ resolveAgentId,+ rememberSessionAgentId,+ queryConfigStore,+ traceRecorder,+ });+ expect(setContextEngineRef).toHaveBeenCalledWith(engine);+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining("registered context-engine"));+ });++ it("warns when the context-engine registration API is unavailable", () => {+ const logger = { info: vi.fn(), warn: vi.fn() };++ registerOpenVikingContextEngine({+ api: {},+ plugin: { id: "openviking", name: "OpenViking" },+ version: "0.1.0",+ cfg: {},+ logger,+ getClient: vi.fn(),+ resolveAgentId: vi.fn(),+ rememberSessionAgentId: vi.fn(),+ queryConfigStore: {},+ traceRecorder: {},+ createContextEngine: vi.fn(),+ setContextEngineRef: vi.fn(),+ });++ expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining("registerContextEngine is unavailable"));+ expect(logger.info).not.toHaveBeenCalled();+ });++ it("registers externalized tool-result tools through a dedicated plugin module", async () => {+ const registerTool = vi.fn();+ const readToolResult = vi.fn().mockResolvedValue({+ content: "full tool result",+ offset: 0,+ limit: 20_000,+ total_chars: 16,+ has_more: false,+ tool_result_id: "tr_1",+ metadata: { tool_name: "ov_search" },+ });+ const deps = {+ registerTool,+ getClient: async () => ({ readToolResult }),+ resolvePluginSessionRouting: () => ({ agentId: "agent-main", ovSessionId: "ov-session-1" }),+ isBypassedSession: () => false,+ makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),+ logger: { warn: vi.fn() },+ };++ registerOpenVikingToolResultTools(deps);++ expect(registerTool.mock.calls.map(([, opts]) => opts.name)).toEqual([+ "openviking_tool_result_read",+ "openviking_tool_result_search",+ "openviking_tool_result_list",+ ]);+ const readFactory = registerTool.mock.calls[0]?.[0];+ const readTool = readFactory({ sessionId: "session-1" });+ const result = await readTool.execute("call-1", {+ tool_output_ref: "viking://session/ov-session-1/tool-results/tr_1",+ });++ expect(readToolResult).toHaveBeenCalledWith(+ "ov-session-1",+ "tr_1",+ { offset: 0, limit: 20_000, includeMetadata: true },+ "agent-main",+ );+ expect(result.content[0].text).toBe("full tool result");+ expect(result.details).toMatchObject({ action: "read", tool_result_id: "tr_1" });+ });++ it("registers archive search and expansion through a dedicated plugin module", async () => {+ const registerTool = vi.fn();+ const recordAndFlush = vi.fn().mockResolvedValue(undefined);+ const grepSessionArchives = vi.fn().mockResolvedValue({+ count: 1,+ matches: [{+ uri: "viking://session/ov-session-1/history/archive_001#L12",+ line: 12,+ content: "important command output",+ }],+ });+ const getSessionArchive = vi.fn().mockResolvedValue({+ archive_id: "archive_001",+ abstract: "Compressed summary",+ messages: [{ id: "m1", role: "user", parts: [{ type: "text", text: "hello" }], created_at: "2026-06-10T00:00:00Z" }],+ });+ const deps = {+ registerTool,+ getClient: async () => ({ grepSessionArchives, getSessionArchive }),+ rememberSessionAgentId: vi.fn(),+ toOvSessionId: () => "ov-session-1",+ resolveAgentId: () => "agent-main",+ resolvePluginSessionRouting: () => ({+ agentId: "agent-main",+ sessionId: "session-1",+ ovSessionId: "ov-session-1",+ }),+ isBypassedSession: () => false,+ makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),+ formatMessage: (message: { role: string; parts: Array<{ text?: string }> }) => `${message.role}: ${message.parts[0]?.text ?? ""}`,+ traceRecorder: { recordAndFlush },+ traceRecallMaxResultsPerSearch: 10,+ traceRecallPreviewChars: 20,+ createTraceId: () => "trace-archive-search",+ logger: { info: vi.fn(), warn: vi.fn() },+ };++ registerOpenVikingArchiveTools(deps);++ expect(registerTool.mock.calls.map(([, opts]) => opts.name)).toEqual([+ "ov_archive_search",+ "ov_archive_expand",+ ]);+ const searchFactory = registerTool.mock.calls[0]?.[0];+ const searchTool = searchFactory({ sessionId: "session-1", sessionKey: "session-key" });+ const searchResult = await searchTool.execute("call-1", { query: "command" });++ expect(grepSessionArchives).toHaveBeenCalledWith("ov-session-1", "command", {+ archiveId: undefined,+ caseInsensitive: true,+ agentId: "agent-main",+ });+ expect(searchResult.content[0].text).toContain("Found 1 match(es)");+ expect(searchResult.content[0].text).toContain("important command output");+ expect(searchResult.details).toMatchObject({ query: "command", matchCount: 1 });+ expect(recordAndFlush).toHaveBeenCalledWith(expect.objectContaining({+ traceId: "trace-archive-search",+ source: "ov_archive_search",+ operationType: "archive_grep",+ }));++ const expandFactory = registerTool.mock.calls[1]?.[0];+ const expandTool = expandFactory({ sessionId: "session-1" });+ const result = await expandTool.execute("call-2", { archiveId: "archive_001" });++ expect(getSessionArchive).toHaveBeenCalledWith("ov-session-1", "archive_001", "agent-main");+ expect(result.content[0].text).toContain("## archive_001");+ expect(result.content[0].text).toContain("user: hello");+ expect(result.details).toMatchObject({+ action: "expanded",+ archiveId: "archive_001",+ messageCount: 1,+ sessionId: "session-1",+ ovSessionId: "ov-session-1",+ });+ });++ it("registers import tools through a dedicated plugin module", async () => {+ const registerTool = vi.fn();+ const addResource = vi.fn().mockResolvedValue({ root_uri: "viking://resources/docs", warnings: ["warn"] });+ const addSkill = vi.fn().mockResolvedValue({ uri: "viking://user/skills/demo", name: "demo" });+ const deps = {+ registerTool,+ getClient: async () => ({ addResource, addSkill }),+ resolvePluginSessionRouting: () => ({ agentId: "agent-main" }),+ isBypassedSession: () => false,+ makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),+ enableAddResourceTool: true,+ };++ registerOpenVikingImportTools(deps);++ expect(registerTool.mock.calls.map(([, opts]) => opts.name)).toEqual(["add_resource", "add_skill"]);+ const addResourceFactory = registerTool.mock.calls[0]?.[0];+ const addResourceTool = addResourceFactory({ sessionId: "session-1" });+ const resourceResult = await addResourceTool.execute("call-1", {+ source: "https://example.com/docs",+ to: "viking://resources/docs",+ wait: true,+ timeout: 30,+ });+ expect(addResource).toHaveBeenCalledWith({+ pathOrUrl: "https://example.com/docs",+ to: "viking://resources/docs",+ parent: undefined,+ reason: undefined,+ instruction: undefined,+ wait: true,+ timeout: 30,+ }, "agent-main");+ expect(resourceResult.content[0].text).toBe("Imported OpenViking resource. viking://resources/docs Warnings: warn");+ expect(resourceResult.details).toMatchObject({ action: "resource_imported", root_uri: "viking://resources/docs" });++ const addSkillFactory = registerTool.mock.calls[1]?.[0];+ const addSkillTool = addSkillFactory({ sessionId: "session-1" });+ const skillResult = await addSkillTool.execute("call-2", { data: "name: demo\n" });+ expect(addSkill).toHaveBeenCalledWith({+ path: undefined,+ data: "name: demo\n",+ wait: undefined,+ timeout: undefined,+ }, "agent-main");+ expect(skillResult.content[0].text).toBe("Imported OpenViking skill (demo). viking://user/skills/demo");+ expect(skillResult.details).toMatchObject({ action: "skill_imported", uri: "viking://user/skills/demo" });+ });++ it("keeps add_resource import tool behind explicit opt-in", () => {+ const registerTool = vi.fn();+ registerOpenVikingImportTools({+ registerTool,+ getClient: async () => ({ addResource: vi.fn(), addSkill: vi.fn() }),+ resolvePluginSessionRouting: () => ({ agentId: "agent-main" }),+ isBypassedSession: () => false,+ makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),+ enableAddResourceTool: false,+ });++ expect(registerTool.mock.calls.map(([, opts]) => opts.name)).toEqual(["add_skill"]);+ });++ it("registers query tools through a dedicated plugin module", async () => {+ const registerTool = vi.fn();+ const searchOpenViking = vi.fn().mockResolvedValue({+ content: [{ type: "text" as const, text: "search result" }],+ details: { action: "searched", total: 1 },+ });+ const readOpenVikingContent = vi.fn().mockResolvedValue({+ content: [{ type: "text" as const, text: "read result" }],+ details: { action: "read", uri: "viking://resources/doc" },+ });+ const multiReadOpenVikingContent = vi.fn().mockResolvedValue({+ content: [{ type: "text" as const, text: "multi read result" }],+ details: { action: "multi_read", count: 2 },+ });+ const listOpenVikingDirectory = vi.fn().mockResolvedValue({+ content: [{ type: "text" as const, text: "list result" }],+ details: { action: "listed", count: 2 },+ });+ const deps = {+ registerTool,+ searchOpenViking,+ readOpenVikingContent,+ multiReadOpenVikingContent,+ listOpenVikingDirectory,+ resolvePluginSessionRouting: () => ({+ agentId: "agent-main",+ sessionId: "session-1",+ ovSessionId: "ov-session-1",+ }),+ isBypassedSession: () => false,+ makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),+ };++ registerOpenVikingQueryTools(deps);++ expect(registerTool.mock.calls.map(([, opts]) => opts.name)).toEqual(["ov_search", "ov_read", "ov_multi_read", "ov_list"]);+ const searchFactory = registerTool.mock.calls[0]?.[0];+ const searchTool = searchFactory({ sessionId: "session-1" });+ const searched = await searchTool.execute("call-1", { query: "docs", uri: "viking://resources", limit: 3 });+ expect(searchOpenViking).toHaveBeenCalledWith({+ query: "docs",+ uri: "viking://resources",+ limit: 3,+ }, "agent-main", {+ agentId: "agent-main",+ sessionId: "session-1",+ ovSessionId: "ov-session-1",+ });+ expect(searched.details).toMatchObject({ action: "searched", total: 1 });++ const readFactory = registerTool.mock.calls[1]?.[0];+ const readTool = readFactory({ sessionId: "session-1" });+ const read = await readTool.execute("call-2", { uri: "viking://resources/doc" });+ expect(readOpenVikingContent).toHaveBeenCalledWith({ uri: "viking://resources/doc" }, "agent-main");+ expect(read.content[0].text).toBe("read result");++ const multiReadFactory = registerTool.mock.calls[2]?.[0];+ const multiReadTool = multiReadFactory({ sessionId: "session-1" });+ const multiRead = await multiReadTool.execute("call-3", { uris: ["viking://resources/a.md", "viking://resources/b.md"] });+ expect(multiReadOpenVikingContent).toHaveBeenCalledWith({+ uris: ["viking://resources/a.md", "viking://resources/b.md"],+ }, "agent-main");+ expect(multiRead.content[0].text).toBe("multi read result");++ const listFactory = registerTool.mock.calls[3]?.[0];+ const listTool = listFactory({ sessionId: "session-1" });+ const list = await listTool.execute("call-4", {+ uri: "viking://resources/doc",+ recursive: true,+ simple: true,+ limit: 5,+ });+ expect(listOpenVikingDirectory).toHaveBeenCalledWith({+ uri: "viking://resources/doc",+ recursive: true,+ simple: true,+ limit: 5,+ }, "agent-main");+ expect(list.content[0].text).toBe("list result");+ });++ it("registers memory store and forget through a dedicated plugin module", async () => {+ const registerTool = vi.fn();+ const addSessionMessage = vi.fn().mockResolvedValue(undefined);+ const commitSession = vi.fn().mockResolvedValue({+ session_id: "memory-store-temp",+ status: "completed",+ archived: false,+ memories_extracted: { core: 2 },+ });+ const deleteUri = vi.fn().mockResolvedValue(undefined);+ const find = vi.fn().mockResolvedValue({ memories: [], total: 0 });+ const deps = {+ registerTool,+ getClient: async () => ({ addSessionMessage, commitSession, deleteUri, find }),+ normalizeSessionId: (sessionId: string) => `normalized:${sessionId}`,+ createTempSessionId: () => "memory-store-temp",+ extractSenderId: () => "ou_01@abc",+ toRoleId: (senderId?: string) => senderId?.replace(/[^a-zA-Z0-9_-]/g, "_"),+ resolvePluginSessionRouting: () => ({ agentId: "agent-main" }),+ isBypassedSession: () => false,+ makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),+ defaultTargetUri: "viking://user/default",+ defaultRecallScoreThreshold: 0.25,+ logFindRequests: true,+ logger: { info: vi.fn(), warn: vi.fn() },+ };++ registerOpenVikingMemoryTools(deps);++ expect(registerTool.mock.calls.map(([, opts]) => opts.name)).toEqual(["memory_store", "memory_forget"]);+ const storeFactory = registerTool.mock.calls[0]?.[0];+ const storeTool = storeFactory({ sessionId: "session-1", requesterSenderId: "ou_01@abc" });+ const stored = await storeTool.execute("call-1", { text: "remember this" });+ expect(addSessionMessage).toHaveBeenCalledWith(+ "memory-store-temp",+ "user",+ [{ type: "text", text: "remember this" }],+ "agent-main",+ undefined,+ "ou_01_abc",+ );+ expect(commitSession).toHaveBeenCalledWith("memory-store-temp", {+ wait: true,+ agentId: "agent-main",+ keepRecentCount: 0,+ });+ expect(stored.details).toMatchObject({ action: "stored", memoriesCount: 2, usedTempSession: true });++ const forgetFactory = registerTool.mock.calls[1]?.[0];+ const forgetTool = forgetFactory({ sessionId: "session-1" });+ const rejected = await forgetTool.execute("call-2", { uri: "viking://resources/r1" });+ expect(rejected.details).toMatchObject({ action: "rejected", uri: "viking://resources/r1" });+ expect(deleteUri).not.toHaveBeenCalled();++ const deleted = await forgetTool.execute("call-3", { uri: "viking://user/default/memories/m1" });+ expect(deleteUri).toHaveBeenCalledWith("viking://user/default/memories/m1", "agent-main");+ expect(deleted.content[0].text).toBe("Forgotten: viking://user/default/memories/m1");+ expect(deleted.details).toMatchObject({ action: "deleted", uri: "viking://user/default/memories/m1" });+ });++ it("registers recall trace tool through a dedicated plugin module", async () => {+ const registerTool = vi.fn();+ const traceResult = {+ entries: [{ traceId: "trace-1", source: "ov_search" }],+ lookupLayer: "memory",+ warnings: ["warn"],+ };+ const queryRecallTraces = vi.fn().mockResolvedValue(traceResult);+ const formatRecallTraceText = vi.fn().mockReturnValue("formatted trace");+ const deps = {+ registerTool,+ queryRecallTraces,+ formatRecallTraceText,+ resolvePluginSessionRouting: () => ({+ agentId: "agent-main",+ sessionId: "session-1",+ ovSessionId: "ov-session-1",+ }),+ isBypassedSession: () => false,+ makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),+ };++ registerOpenVikingRecallTraceTools(deps);++ expect(registerTool.mock.calls.map(([, opts]) => opts.name)).toEqual(["ov_recall_trace"]);+ const traceFactory = registerTool.mock.calls[0]?.[0];+ const traceTool = traceFactory({ sessionId: "session-1" });+ const result = await traceTool.execute("call-1", { source: "ov_search", limit: 5 });++ expect(queryRecallTraces).toHaveBeenCalledWith({ source: "ov_search", limit: 5 }, {+ agentId: "agent-main",+ sessionId: "session-1",+ ovSessionId: "ov-session-1",+ });+ expect(formatRecallTraceText).toHaveBeenCalledWith(traceResult);+ expect(result.content[0].text).toBe("formatted trace");+ expect(result.details).toMatchObject({+ action: "queried",+ count: 1,+ lookupLayer: "memory",+ warnings: ["warn"],+ entries: traceResult.entries,+ });+ });++ it("registers memory recall tool through a dedicated plugin module", async () => {+ const registerTool = vi.fn();+ const memory = {+ uri: "viking://user/default/memories/m1",+ category: "preferences",+ abstract: "User prefers TDD.",+ score: 0.93,+ level: 2,+ };+ const find = vi.fn().mockResolvedValue({ memories: [memory], total: 1 });+ const read = vi.fn().mockResolvedValue("User prefers TDD.");+ const getDefaultAgentId = vi.fn().mockReturnValue("default-agent");+ const recordAndFlush = vi.fn().mockResolvedValue(undefined);+ const getEffective = vi.fn().mockResolvedValue({+ recallLimit: 1,+ scoreThreshold: 0.5,+ targetUri: "viking://user/default",+ resourceTypes: ["user"],+ candidateLimit: 4,+ maxInjectedChars: 500,+ rankingWeights: {},+ categoryWeights: {},+ resourceTypeWeights: {},+ });++ registerOpenVikingMemoryRecallTools({+ registerTool,+ getClient: async () => ({ find, read, getDefaultAgentId }),+ queryConfigStore: { getEffective },+ toQueryConfigContext: (session) => ({ agentId: session.agentId, sessionId: session.sessionId, sessionKey: session.sessionKey, ovSessionId: session.ovSessionId }),+ resolvePluginSessionRouting: () => ({+ agentId: "agent-main",+ sessionId: "session-1",+ sessionKey: "agent:agent-main:session-1",+ ovSessionId: "ov-session-1",+ }),+ isBypassedSession: () => false,+ makeBypassedToolResult: (toolName: string) => ({ content: [{ type: "text" as const, text: `bypassed ${toolName}` }], details: { toolName } }),+ resolveRecallSearchPlan: vi.fn(),+ postProcessMemories: (items) => items,+ pickMemoriesForInjection: (items) => items.slice(0, 1),+ buildMemoryLinesWithBudget: vi.fn(async (items, readFn) => {+ await readFn(items[0].uri);+ return { lines: ["1. [preferences] User prefers TDD. (93%)"], estimatedTokens: 8 };+ }),+ inferRecallResourceType: (uri) => uri.startsWith("viking://user/") ? "user" : "resource",+ createTraceId: () => "memory_recall-trace-1",+ boundTraceQuery: (query) => ({ query }),+ previewText: (value) => typeof value === "string" ? value : undefined,+ traceRecorder: { recordAndFlush },+ cfg: {+ recallTargetTypes: ["user"],+ traceRecallMaxResultsPerSearch: 5,+ traceRecallPreviewChars: 120,+ traceRecallQueryMaxChars: 200,+ logFindRequests: true,+ },+ logger: { info: vi.fn() },+ });++ expect(registerTool.mock.calls.map(([, opts]) => opts.name)).toEqual(["memory_recall"]);+ const recallFactory = registerTool.mock.calls[0]?.[0];+ const recallTool = recallFactory({ sessionId: "session-1" });+ const result = await recallTool.execute("call-1", { query: "TDD preference", limit: 2, scoreThreshold: 0.5 });++ expect(getEffective).toHaveBeenCalledWith({+ agentId: "agent-main",+ sessionId: "session-1",+ sessionKey: "agent:agent-main:session-1",+ ovSessionId: "ov-session-1",+ }, {+ recallLimit: 2,+ scoreThreshold: 0.5,+ targetUri: undefined,+ resourceTypes: undefined,+ });+ expect(find).toHaveBeenCalledWith("TDD preference", {+ targetUri: "viking://user/default",+ limit: 4,+ scoreThreshold: 0,+ actorPeerId: "agent-main",+ });+ expect(read).toHaveBeenCalledWith("viking://user/default/memories/m1", "agent-main");+ expect(recordAndFlush).toHaveBeenCalledWith(expect.objectContaining({+ traceId: "memory_recall-trace-1",+ sessionId: "session-1",+ sessionKey: "agent:agent-main:session-1",+ ovSessionId: "ov-session-1",+ agentId: "agent-main",+ source: "memory_recall",+ resourceTypes: ["user"],+ stats: { candidateCount: 1, selectedCount: 1, injectedCount: 1 },+ }));+ expect(result.content[0].text).toContain("Found 1 memories");+ expect(result.details).toMatchObject({+ count: 1,+ total: 1,+ scoreThreshold: 0.5,+ requestLimit: 4,+ recallMaxInjectedChars: 500,+ });+ });+});diff --git a/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts b/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.tsindex e400d6447..dba0d3347 100644--- a/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts+++ b/examples/openclaw-plugin/tests/ut/plugin-normal-flow-real-server.test.ts@@ -113,18 +113,6 @@ describe("plugin normal flow with healthy backend", () => {return;}- if (- method === "POST" &&- url.pathname === "/api/v1/sessions"- ) {- const parsed = JSON.parse(body ?? "{}") as Record<string, unknown>;- json(res, 200, {- result: { session_id: parsed.session_id ?? "session-normal" },- status: "ok",- });- return;- }-if (method === "POST" &&/^\/api\/v1\/sessions\/[^/]+\/messages$/.test(url.pathname)@@ -244,20 +232,14 @@ describe("plugin normal flow with healthy backend", () => {messages: [{ role: "user", content: "fallback" }],});- expect(assembled.messages[0]?.role).toBe("user");- const firstAssembledMessage = String(assembled.messages[0]?.content);- expect(firstAssembledMessage).not.toContain("Source: openviking-auto-recall");- expect(firstAssembledMessage).not.toContain("User prefers Rust for backend tasks.");- expect(firstAssembledMessage).toContain(- "[Session History Summary]\nEarlier work focused on backend stack choices.",- );+ expect(assembled.messages[0]).toEqual({+ role: "user",+ content: "[Session History Summary]\nEarlier work focused on backend stack choices.",+ });expect(assembled.messages[1]).toEqual({role: "assistant",content: [{ type: "text", text: "Stored answer from OpenViking." }],});- expect(- requests.some((entry) => entry.method === "POST" && entry.path === "/api/v1/search/find"),- ).toBe(false);const transformed = await contextEngine.assemble({sessionId: "session-normal",@@ -290,17 +272,6 @@ describe("plugin normal flow with healthy backend", () => {expect(requests.some((entry) => entry.method === "GET" && entry.path.startsWith("/api/v1/sessions/session-normal/context")),).toBe(true);- const createSessionRequest = requests.find(- (entry) => entry.method === "POST" && entry.path === "/api/v1/sessions",- );- expect(createSessionRequest).toBeTruthy();- expect(JSON.parse(createSessionRequest!.body ?? "{}")).toMatchObject({- session_id: "session-normal",- memory_policy: {- self: { enabled: true },- peer: { enabled: true },- },- });expect(requests.some((entry) => entry.method === "POST" && entry.path === "/api/v1/sessions/session-normal/messages"),).toBe(true);diff --git a/examples/openclaw-plugin/tests/ut/recall-resource-types.test.ts b/examples/openclaw-plugin/tests/ut/recall-resource-types.test.tsnew file mode 100644index 000000000..b5a710417--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/recall-resource-types.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";++import {+ ALLOWED_RECALL_RESOURCE_TYPES,+ DEFAULT_RECALL_RESOURCE_TYPES,+ normalizeRecallResourceTypes,+ resolveRecallSearchPlan,+} from "../../registries/recall-resource-types.js";++describe("recall resource type registry", () => {+ it("defines the single allowed and default resource type source", () => {+ expect(ALLOWED_RECALL_RESOURCE_TYPES).toEqual(["resource", "user", "agent"]);+ expect(DEFAULT_RECALL_RESOURCE_TYPES).toEqual(["user", "agent"]);+ });++ it("normalizes arrays and comma/newline-separated strings without changing legacy behavior", () => {+ expect(normalizeRecallResourceTypes(undefined)).toEqual(["user", "agent"]);+ expect(normalizeRecallResourceTypes([])).toEqual(["user", "agent"]);+ expect(normalizeRecallResourceTypes(" resource,\nuser,agent,user ")).toEqual([+ "resource",+ "user",+ "agent",+ ]);+ expect(() => normalizeRecallResourceTypes(["user", "project"])).toThrow("invalid resourceTypes: project");+ });++ it("builds context-type search plans without deprecated agent/session URI paths", () => {+ expect(resolveRecallSearchPlan(["resource", "user", "agent"], { ovSessionId: "ov-1" })).toEqual({+ resourceTypes: ["resource", "user", "agent"],+ searches: [+ { resourceType: "resource", contextType: "resource" },+ { resourceType: "user", contextType: "memory" },+ ],+ skipped: [],+ });++ expect(resolveRecallSearchPlan(["agent", "user"], {})).toEqual({+ resourceTypes: ["agent", "user"],+ searches: [{ resourceType: "user", contextType: "memory" }],+ skipped: [],+ });+ });+});diff --git a/examples/openclaw-plugin/tests/ut/session-transcript-repair.test.ts b/examples/openclaw-plugin/tests/ut/session-transcript-repair.test.tsindex d6fa380e7..637622838 100644--- a/examples/openclaw-plugin/tests/ut/session-transcript-repair.test.ts+++ b/examples/openclaw-plugin/tests/ut/session-transcript-repair.test.ts@@ -3,7 +3,6 @@ import { describe, expect, it } from "vitest";import {sanitizeToolUseResultPairing,repairToolUseResultPairing,- makeMissingToolResult,stripToolResultDetails,repairToolCallInputs,sanitizeToolCallInputs,@@ -48,7 +47,9 @@ describe("sanitizeToolUseResultPairing", () => {const report = repairToolUseResultPairing(messages);expect(report.added).toHaveLength(1);expect(report.added[0]!.toolCallId).toBe("tc_orphan");+ expect(report.added[0]!.toolName).toBe("bash");expect(report.added[0]!.isError).toBe(true);+ expect((report.added[0]!.content as any)[0].text).toContain("missing tool result");const repaired = report.messages;expect(repaired[0]!.role).toBe("assistant");@@ -165,24 +166,20 @@ describe("sanitizeToolUseResultPairing", () => {const report = repairToolUseResultPairing(messages);expect(report.added).toHaveLength(0);});-});-describe("makeMissingToolResult", () => {- it("creates synthetic error toolResult", () => {- const result = makeMissingToolResult({- toolCallId: "test-id",- toolName: "my_tool",- });- expect(result.role).toBe("toolResult");- expect(result.toolCallId).toBe("test-id");- expect(result.toolName).toBe("my_tool");- expect(result.isError).toBe(true);- expect((result.content as any)[0].text).toContain("missing tool result");- });+ it("defaults synthesized missing toolResult names to unknown when the tool call lacks a name", () => {+ const messages: AgentMessage[] = [+ {+ role: "assistant",+ content: [{ type: "toolUse", id: "tc_without_name", input: { cmd: "ls" } }],+ },+ ];- it("defaults toolName to 'unknown'", () => {- const result = makeMissingToolResult({ toolCallId: "x" });- expect(result.toolName).toBe("unknown");+ const report = repairToolUseResultPairing(messages);++ expect(report.added).toHaveLength(1);+ expect(report.added[0]!.toolCallId).toBe("tc_without_name");+ expect(report.added[0]!.toolName).toBe("unknown");});});diff --git a/examples/openclaw-plugin/tests/ut/setup-cli.test.ts b/examples/openclaw-plugin/tests/ut/setup-cli.test.tsindex e78c2f365..cccb09d9b 100644--- a/examples/openclaw-plugin/tests/ut/setup-cli.test.ts+++ b/examples/openclaw-plugin/tests/ut/setup-cli.test.ts@@ -4,23 +4,33 @@ import * as path from "node:path";import * as os from "node:os";import { fileURLToPath } from "node:url";-import { __test__ } from "../../commands/setup.js";--const {+import {+ COMPATIBLE_SERVER_MAX,+ COMPATIBLE_SERVER_MIN,+ findPluginPackageRoot,+} from "../../services/setup/package-metadata.js";+import {parseVersionTuple,compareVersions,- checkVersionCompatibility,- isLegacyLocalMode,+ checkVersionCompatibility as checkVersionCompatibilityForRange,+} from "../../services/setup/version-compatibility.js";+import { setExitCodeOnFailure } from "../../services/setup/exit-utils.js";+import { isLegacyLocalMode } from "../../services/setup/setup-flow.js";+import {activateContextEngineSlot,- isContextEngineSlotActive,ensureInstallRecord,- findPluginPackageRoot,- setExitCodeOnFailure,-} = __test__;+ isContextEngineSlotActive,+} from "../../services/setup/config-writer.js";const pluginRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");let tmpDir: string;+const checkVersionCompatibility = (serverVersion: string) =>+ checkVersionCompatibilityForRange(serverVersion, {+ min: COMPATIBLE_SERVER_MIN,+ max: COMPATIBLE_SERVER_MAX,+ });+beforeEach(() => {tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "ov-setup-test-"));});diff --git a/examples/openclaw-plugin/tests/ut/setup-command.test.ts b/examples/openclaw-plugin/tests/ut/setup-command.test.tsindex 3ddbc6e53..05bea4033 100644--- a/examples/openclaw-plugin/tests/ut/setup-command.test.ts+++ b/examples/openclaw-plugin/tests/ut/setup-command.test.ts@@ -1,41 +1,65 @@-import { describe, expect, it } from "vitest";+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";-import { __test__ } from "../../commands/setup.js";+import { defaultSetupIO } from "../../services/setup/config-writer.js";+import { createOpenVikingSetupService } from "../../services/setup/setup-flow.js";describe("openviking setup agent prefix validation", () => {+ const tempDirs: string[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ for (const dir of tempDirs.splice(0)) {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ });+it.each(["", " ", "main", "foo_main", "foo-main", "Foo_123"])("accepts valid agent prefix %j",(value) => {- expect(__test__.isValidPeerPrefixInput(value)).toBe(true);+ expect(/^[a-zA-Z0-9_-]*$/.test(value.trim())).toBe(true);},);it.each(["foo.bar", "foo/bar", "foo bar", "中文", "foo:bar"])("rejects invalid agent prefix %j",(value) => {- expect(__test__.isValidPeerPrefixInput(value)).toBe(false);+ expect(/^[a-zA-Z0-9_-]*$/.test(value.trim())).toBe(false);},);-});-describe("openviking setup recall target type parsing", () => {- it("normalizes comma-separated target types", () => {- expect(__test__.normalizeSetupRecallTargetTypes("resource, user\nagent, user")).toEqual([- "resource",- "user",- "agent",- ]);- });+ it("non-interactive setup can persist resource-only recallTargetTypes for post-install opt-in", async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openviking-setup-"));+ tempDirs.push(dir);+ const configPath = path.join(dir, "openclaw.json");+ const { setupNonInteractive } = createOpenVikingSetupService({+ io: defaultSetupIO,+ checkServiceHealth: async () => ({+ ok: false,+ version: "",+ error: "offline",+ compatibility: "unknown",+ pluginVersion: "test",+ compatRange: "any",+ }),+ probeApiKeyType: async () => ({+ keyType: "unknown",+ needsAccountId: false,+ needsUserId: false,+ detail: "not probed",+ }),+ });- it("rejects unknown target types", () => {- expect(() => __test__.normalizeSetupRecallTargetTypes("user,project")).toThrow(- "unknown resource types: project",- );- });+ const result = await setupNonInteractive(configPath, {+ baseUrl: "http://127.0.0.1:1933",+ allowOffline: true,+ recallTargetTypes: ["resource"],+ });- it("rejects session as a recall target type", () => {- expect(() => __test__.normalizeSetupRecallTargetTypes("session")).toThrow(- "unknown resource types: session",- );+ const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));+ expect(result.success).toBe(true);+ expect(config.plugins.entries.openviking.config.recallTargetTypes).toEqual(["resource"]);});});diff --git a/examples/openclaw-plugin/tests/ut/setup-config-writer.test.ts b/examples/openclaw-plugin/tests/ut/setup-config-writer.test.tsnew file mode 100644index 000000000..47ed2ba4f--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/setup-config-writer.test.ts@@ -0,0 +1,104 @@+import { describe, expect, it } from "vitest";++import {+ activateContextEngineSlot,+ ensureInstallRecord,+ getExistingPluginConfig,+ isContextEngineSlotActive,+ writeOpenVikingConfig,+ type SetupIO,+} from "../../services/setup/config-writer.js";++function createMemoryIO(initialConfig: Record<string, unknown> = {}): SetupIO & {+ config: Record<string, unknown>;+ backups: string[];+} {+ return {+ config: structuredClone(initialConfig),+ backups: [],+ readConfig() {+ return structuredClone(this.config);+ },+ writeConfig(_configPath: string, config: Record<string, unknown>) {+ this.config = structuredClone(config);+ },+ backupConfig(configPath: string) {+ const backupPath = `${configPath}.bak`;+ this.backups.push(backupPath);+ return backupPath;+ },+ };+}++describe("setup config writer service", () => {+ it("writes OpenViking plugin config while preserving entry metadata and cleaning stale install records", () => {+ const io = createMemoryIO({+ plugins: {+ allow: ["other"],+ installs: { openviking: { path: "/legacy" }, other: { path: "/other" } },+ entries: {+ openviking: { enabled: true, config: { mode: "local", port: 1933 } },+ },+ },+ });++ writeOpenVikingConfig("/tmp/openclaw.json", {+ mode: "remote",+ baseUrl: "http://127.0.0.1:1933",+ }, io);++ expect(io.backups).toEqual(["/tmp/openclaw.json.bak"]);+ expect(io.config).toMatchObject({+ plugins: {+ allow: ["other", "openviking"],+ installs: { other: { path: "/other" } },+ entries: {+ openviking: {+ enabled: true,+ config: {+ mode: "remote",+ baseUrl: "http://127.0.0.1:1933",+ },+ },+ },+ },+ });+ });++ it("protects an occupied contextEngine slot unless forced", () => {+ const io = createMemoryIO({ plugins: { slots: { contextEngine: "other-engine" } } });++ expect(activateContextEngineSlot("/tmp/openclaw.json", false, io)).toEqual({+ activated: false,+ previousOwner: "other-engine",+ replaced: false,+ });+ expect(isContextEngineSlotActive("/tmp/openclaw.json", io)).toBe(false);++ expect(activateContextEngineSlot("/tmp/openclaw.json", true, io)).toEqual({+ activated: true,+ previousOwner: "other-engine",+ replaced: true,+ });+ expect(isContextEngineSlotActive("/tmp/openclaw.json", io)).toBe(true);+ });++ it("detects existing plugin config only when a mode is present", () => {+ expect(getExistingPluginConfig({ plugins: { entries: { openviking: { config: { mode: "remote" } } } } })).toEqual({+ mode: "remote",+ });+ expect(getExistingPluginConfig({ plugins: { entries: { openviking: { config: { baseUrl: "http://x" } } } } })).toBeNull();+ });++ it("ensures openviking is allowed without duplicating allow entries", () => {+ const plugins: Record<string, unknown> = {+ allow: ["openviking"],+ installs: { openviking: { path: "/legacy" } },+ };++ ensureInstallRecord(plugins);++ expect(plugins.allow).toEqual(["openviking"]);+ expect(plugins.installs).toEqual({});+ });+});diff --git a/examples/openclaw-plugin/tests/ut/setup-flow-service.test.ts b/examples/openclaw-plugin/tests/ut/setup-flow-service.test.tsnew file mode 100644index 000000000..30d497b53--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/setup-flow-service.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from "vitest";++import { createOpenVikingSetupService, maskKey, type SetupIO } from "../../services/setup/setup-flow.js";++function createMemoryIO(initialConfig: Record<string, unknown> = {}): SetupIO & { config: Record<string, unknown> } {+ return {+ config: structuredClone(initialConfig),+ readConfig() {+ return structuredClone(this.config);+ },+ writeConfig(_configPath: string, config: Record<string, unknown>) {+ this.config = structuredClone(config);+ },+ backupConfig() {+ return null;+ },+ };+}++describe("setup flow service", () => {+ it("masks API keys without exposing full secrets", () => {+ expect(maskKey("short")).toBe("****");+ expect(maskKey("sk-root-secret")).toBe("sk-r...cret");+ });++ it("refuses root keys without tenant identity before writing config", async () => {+ const io = createMemoryIO();+ const service = createOpenVikingSetupService({+ io,+ checkServiceHealth: async () => ({+ ok: true,+ version: "2026.6.1",+ error: "",+ compatibility: "compatible",+ pluginVersion: "2026.6.5",+ compatRange: "any",+ }),+ probeApiKeyType: async () => ({+ keyType: "root_key",+ needsAccountId: true,+ needsUserId: true,+ detail: "tenant context required",+ }),+ });++ const result = await service.setupNonInteractive("/tmp/openclaw.json", {+ baseUrl: "http://127.0.0.1:1933",+ apiKey: "sk-root-secret",+ });++ expect(result).toMatchObject({+ success: false,+ action: "error",+ config: { mode: "remote", baseUrl: "http://127.0.0.1:1933", apiKey: "sk-r...cret" },+ slot: { activated: false, replaced: false },+ });+ expect(result.error).toContain("Missing: --account-id, --user-id");+ expect(io.config).toEqual({});+ });++ it("saves interactive remote config through injected setup IO", async () => {+ const io = createMemoryIO();+ const service = createOpenVikingSetupService({+ io,+ checkServiceHealth: async () => ({+ ok: true,+ version: "2026.6.1",+ error: "",+ compatibility: "compatible",+ pluginVersion: "2026.6.5",+ compatRange: "any",+ }),+ probeApiKeyType: async () => ({+ keyType: "user_key",+ needsAccountId: false,+ needsUserId: false,+ detail: "ok",+ }),+ });++ const result = await service.saveInteractiveRemoteConfig("/tmp/openclaw.json", {+ baseUrl: "http://remote:1933",+ apiKey: "sk-user-secret",+ peerRole: "assistant",+ peerPrefix: "main",+ });++ expect(result).toMatchObject({+ config: {+ mode: "remote",+ baseUrl: "http://remote:1933",+ apiKey: "sk-user-secret",+ peer_role: "assistant",+ peer_prefix: "main",+ },+ slot: { activated: true, replaced: false },+ });+ expect(io.config).toMatchObject({+ plugins: {+ entries: { openviking: { config: result.config } },+ slots: { contextEngine: "openviking" },+ },+ });+ });+});diff --git a/examples/openclaw-plugin/tests/ut/setup-modules.test.ts b/examples/openclaw-plugin/tests/ut/setup-modules.test.tsnew file mode 100644index 000000000..cc311f3db--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/setup-modules.test.ts@@ -0,0 +1,347 @@+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ activateContextEngineSlot,+ isContextEngineSlotActive,+ readOpenClawConfig,+ writeOpenVikingConfig,+ type SetupIO,+} from "../../services/setup/config-writer.js";+import { createOpenVikingSetupService } from "../../services/setup/setup-flow.js";++describe("setup IO seam", () => {+ const tempDirs: string[] = [];++ afterEach(() => {+ for (const dir of tempDirs.splice(0)) {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ });++ function tempConfigPath(): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openviking-setup-io-"));+ tempDirs.push(dir);+ return path.join(dir, "openclaw.json");+ }++ it("writes OpenViking plugin config while preserving entry metadata and install allow-list behavior", () => {+ const configPath = tempConfigPath();+ fs.writeFileSync(configPath, JSON.stringify({+ plugins: {+ allow: ["other"],+ installs: { openviking: { path: "/legacy" }, other: { path: "/other" } },+ entries: {+ openviking: { enabled: true, config: { mode: "local", port: 1933 } },+ },+ },+ }, null, 2));++ writeOpenVikingConfig(configPath, {+ mode: "remote",+ baseUrl: "http://127.0.0.1:1933",+ recallTargetTypes: ["resource"],+ });++ const config = readOpenClawConfig(configPath);+ expect(config.plugins).toMatchObject({+ allow: ["other", "openviking"],+ installs: { other: { path: "/other" } },+ entries: {+ openviking: {+ enabled: true,+ config: {+ mode: "remote",+ baseUrl: "http://127.0.0.1:1933",+ recallTargetTypes: ["resource"],+ },+ },+ },+ });+ });++ it("activates contextEngine slot without replacing another owner unless forced", () => {+ const configPath = tempConfigPath();+ fs.writeFileSync(configPath, JSON.stringify({+ plugins: { slots: { contextEngine: "other-engine" } },+ }, null, 2));++ expect(activateContextEngineSlot(configPath)).toEqual({+ activated: false,+ previousOwner: "other-engine",+ replaced: false,+ });+ expect(isContextEngineSlotActive(configPath)).toBe(false);++ expect(activateContextEngineSlot(configPath, true)).toEqual({+ activated: true,+ previousOwner: "other-engine",+ replaced: true,+ });+ expect(isContextEngineSlotActive(configPath)).toBe(true);+ });+});++describe("setup service seam", () => {+ function createMemoryIO(initialConfig: Record<string, unknown> = {}): SetupIO & { config: Record<string, unknown> } {+ return {+ config: structuredClone(initialConfig),+ readConfig() {+ return structuredClone(this.config);+ },+ writeConfig(_configPath: string, config: Record<string, unknown>) {+ this.config = structuredClone(config);+ },+ backupConfig() {+ return null;+ },+ };+ }++ it("non-interactive setup refuses root keys without tenant identity before writing config", async () => {+ const io = createMemoryIO();+ const service = createOpenVikingSetupService({+ io,+ checkServiceHealth: async () => ({+ ok: true,+ version: "2026.6.1",+ error: "",+ compatibility: "compatible",+ pluginVersion: "2026.6.5",+ compatRange: "any",+ }),+ probeApiKeyType: async () => ({+ keyType: "root_key",+ needsAccountId: true,+ needsUserId: true,+ detail: "tenant context required",+ }),+ });++ const result = await service.setupNonInteractive("/tmp/openclaw.json", {+ baseUrl: "http://127.0.0.1:1933",+ apiKey: "sk-root-secret",+ });++ expect(result).toMatchObject({+ success: false,+ action: "error",+ config: { mode: "remote", baseUrl: "http://127.0.0.1:1933", apiKey: "sk-r...cret" },+ keyProbe: { keyType: "root_key" },+ slot: { activated: false, replaced: false },+ });+ expect(result.error).toContain("Missing: --account-id, --user-id");+ expect(io.config).toEqual({});+ });++ it("non-interactive setup can persist offline config and activate an empty contextEngine slot", async () => {+ const io = createMemoryIO();+ const service = createOpenVikingSetupService({+ io,+ checkServiceHealth: async () => ({+ ok: false,+ version: "",+ error: "offline",+ compatibility: "unknown",+ pluginVersion: "2026.6.5",+ compatRange: "any",+ }),+ probeApiKeyType: async () => {+ throw new Error("probe should be skipped when health is not ok");+ },+ });++ const result = await service.setupNonInteractive("/tmp/openclaw.json", {+ baseUrl: "http://127.0.0.1:1933",+ allowOffline: true,+ peerRole: "assistant",+ peerPrefix: "main",+ recallTargetTypes: ["resource"],+ });++ expect(result).toMatchObject({+ success: true,+ action: "configured",+ config: {+ mode: "remote",+ baseUrl: "http://127.0.0.1:1933",+ peer_role: "assistant",+ peer_prefix: "main",+ recallTargetTypes: ["resource"],+ },+ slot: { activated: true, replaced: false },+ });+ expect(io.config).toMatchObject({+ plugins: {+ allow: ["openviking"],+ entries: {+ openviking: {+ config: {+ mode: "remote",+ baseUrl: "http://127.0.0.1:1933",+ peer_role: "assistant",+ peer_prefix: "main",+ recallTargetTypes: ["resource"],+ },+ },+ },+ slots: { contextEngine: "openviking" },+ },+ });+ });++ it("interactive remote config save preserves existing fields, removes local-only fields, and activates slot", async () => {+ const io = createMemoryIO({+ plugins: {+ entries: {+ openviking: {+ enabled: true,+ config: {+ mode: "local",+ port: 1933,+ configPath: "/tmp/openviking",+ customFlag: "keep-me",+ apiKey: "old-key",+ peer_role: "assistant",+ peer_prefix: "old-prefix",+ accountId: "old-account",+ userId: "old-user",+ },+ },+ },+ },+ });+ const service = createOpenVikingSetupService({+ io,+ checkServiceHealth: async () => ({+ ok: true,+ version: "2026.6.1",+ error: "",+ compatibility: "compatible",+ pluginVersion: "2026.6.5",+ compatRange: "any",+ }),+ probeApiKeyType: async () => ({+ keyType: "user_key",+ needsAccountId: false,+ needsUserId: false,+ detail: "ok",+ }),+ });++ const result = await service.saveInteractiveRemoteConfig("/tmp/openclaw.json", {+ existing: {+ mode: "local",+ port: 1933,+ configPath: "/tmp/openviking",+ customFlag: "keep-me",+ apiKey: "old-key",+ peer_role: "assistant",+ peer_prefix: "old-prefix",+ accountId: "old-account",+ userId: "old-user",+ },+ baseUrl: "http://remote:1933",+ apiKey: "",+ peerRole: undefined,+ peerPrefix: "",+ accountId: "",+ userId: "new-user",+ });++ expect(result).toEqual({+ config: {+ mode: "remote",+ baseUrl: "http://remote:1933",+ customFlag: "keep-me",+ userId: "new-user",+ },+ slot: { activated: true, replaced: false },+ });+ expect(io.config).toMatchObject({+ plugins: {+ entries: {+ openviking: {+ enabled: true,+ config: {+ mode: "remote",+ baseUrl: "http://remote:1933",+ customFlag: "keep-me",+ userId: "new-user",+ },+ },+ },+ slots: { contextEngine: "openviking" },+ },+ });+ const saved = (((io.config.plugins as Record<string, unknown>).entries as Record<string, unknown>).openviking as Record<string, unknown>).config as Record<string, unknown>;+ expect(saved).not.toHaveProperty("port");+ expect(saved).not.toHaveProperty("configPath");+ expect(saved).not.toHaveProperty("apiKey");+ expect(saved).not.toHaveProperty("peer_prefix");+ expect(saved).not.toHaveProperty("accountId");+ });++ it("existing remote config flow checks health, masks secrets, and activates the slot via the service seam", async () => {+ const io = createMemoryIO({+ plugins: {+ entries: {+ openviking: {+ config: {+ mode: "remote",+ baseUrl: "http://127.0.0.1:1933",+ apiKey: "sk-existing-secret",+ peer_role: "assistant",+ peer_prefix: "main",+ },+ },+ },+ },+ });+ const health = {+ ok: true,+ version: "2026.6.1",+ error: "",+ compatibility: "compatible" as const,+ pluginVersion: "2026.6.5",+ compatRange: "any",+ };+ const checkServiceHealth = vi.fn().mockResolvedValue(health);+ const service = createOpenVikingSetupService({+ io,+ checkServiceHealth,+ probeApiKeyType: async () => {+ throw new Error("existing config flow should not probe API keys");+ },+ });++ const existing = {+ mode: "remote",+ baseUrl: "http://127.0.0.1:1933",+ apiKey: "sk-existing-secret",+ peer_role: "assistant",+ peer_prefix: "main",+ };+ const result = await service.useExistingRemoteConfig("/tmp/openclaw.json", existing);++ expect(checkServiceHealth).toHaveBeenCalledWith("http://127.0.0.1:1933", "sk-existing-secret");+ expect(result).toMatchObject({+ success: true,+ action: "existing",+ config: {+ mode: "remote",+ baseUrl: "http://127.0.0.1:1933",+ apiKey: "sk-e...cret",+ peer_role: "assistant",+ peer_prefix: "main",+ },+ health,+ slot: { activated: true, replaced: false },+ });+ expect(io.config).toMatchObject({+ plugins: { slots: { contextEngine: "openviking" } },+ });+ });+});diff --git a/examples/openclaw-plugin/tests/ut/setup-probe-service.test.ts b/examples/openclaw-plugin/tests/ut/setup-probe-service.test.tsnew file mode 100644index 000000000..deb2f1769--- /dev/null+++ b/examples/openclaw-plugin/tests/ut/setup-probe-service.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it, vi } from "vitest";++import { createSetupNetworkProbes, type SetupNetworkTransport } from "../../services/setup/probe-service.js";++function response(status: number, body: unknown = ""): Response {+ return {+ ok: status >= 200 && status < 300,+ status,+ async json() {+ if (typeof body === "string") throw new Error("not json");+ return body;+ },+ async text() {+ return typeof body === "string" ? body : JSON.stringify(body);+ },+ } as Response;+}++describe("setup probe service", () => {+ it("checks health through an injected transport and maps server version compatibility", async () => {+ const transport = vi.fn<SetupNetworkTransport>().mockResolvedValue(+ response(200, { result: { version: "2026.6.1" } }),+ );+ const probes = createSetupNetworkProbes({+ pluginVersion: "2026.6.5",+ compatRange: ">= 2026.6.0",+ checkVersionCompatibility: (version) => version === "2026.6.1" ? "compatible" : "unknown",+ transport,+ });++ const result = await probes.checkServiceHealth("http://127.0.0.1:1933/", "sk-user-secret");++ expect(transport).toHaveBeenCalledWith("http://127.0.0.1:1933/health", {+ headers: { "X-API-Key": "sk-user-secret" },+ signal: expect.any(AbortSignal),+ });+ expect(result).toEqual({+ ok: true,+ version: "2026.6.1",+ error: "",+ compatibility: "compatible",+ pluginVersion: "2026.6.5",+ compatRange: ">= 2026.6.0",+ });+ });++ it("classifies root API keys when tenant context is required", async () => {+ const transport = vi.fn<SetupNetworkTransport>().mockResolvedValue(+ response(400, "missing X-OpenViking-Account and X-OpenViking-User context"),+ );+ const probes = createSetupNetworkProbes({+ pluginVersion: "2026.6.5",+ compatRange: "any",+ checkVersionCompatibility: () => "compatible",+ transport,+ });++ const result = await probes.probeApiKeyType("http://127.0.0.1:1933", "sk-root-secret");++ expect(transport).toHaveBeenCalledWith("http://127.0.0.1:1933/api/v1/sessions?limit=1", {+ headers: { "X-API-Key": "sk-root-secret" },+ signal: expect.any(AbortSignal),+ });+ expect(result).toEqual({+ keyType: "root_key",+ needsAccountId: true,+ needsUserId: true,+ detail: "missing X-OpenViking-Account and X-OpenViking-User context",+ });+ });++ it("does not hit the network when no API key is configured", async () => {+ const transport = vi.fn<SetupNetworkTransport>();+ const probes = createSetupNetworkProbes({+ pluginVersion: "2026.6.5",+ compatRange: "any",+ checkVersionCompatibility: () => "compatible",+ transport,+ });++ await expect(probes.probeApiKeyType("http://127.0.0.1:1933")).resolves.toEqual({+ keyType: "no_key",+ needsAccountId: false,+ needsUserId: false,+ detail: "No API key configured",+ });+ expect(transport).not.toHaveBeenCalled();+ });+});diff --git a/examples/openclaw-plugin/tests/ut/text-utils.test.ts b/examples/openclaw-plugin/tests/ut/text-utils.test.tsindex 983da5934..29c9b0ff5 100644--- a/examples/openclaw-plugin/tests/ut/text-utils.test.ts+++ b/examples/openclaw-plugin/tests/ut/text-utils.test.ts@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";import {sanitizeUserTextForCapture,- stripOpenVikingContextInjection,getCaptureDecision,extractNewTurnMessages,extractNewTurnTexts,@@ -20,14 +19,6 @@ describe("sanitizeUserTextForCapture", () => {expect(result).toContain("world");});- it("strips <openviking-context> blocks", () => {- const input = "hello <openviking-context>context</openviking-context> world";- const result = sanitizeUserTextForCapture(input);- expect(result).not.toContain("openviking-context");- expect(result).toContain("hello");- expect(result).toContain("world");- });-it("strips metadata JSON blocks with ≥3 metadata keys", () => {const input = 'prefix ```json\n{"session":"s1","userId":"u1","agentId":"a1","channel":"ch"}\n``` suffix';const result = sanitizeUserTextForCapture(input);@@ -57,16 +48,6 @@ describe("sanitizeUserTextForCapture", () => {expect(sanitizeUserTextForCapture(" ")).toBe("");});- it("drops legacy synthetic tool placeholders", () => {- expect(sanitizeUserTextForCapture("[tool: exec]")).toBe("");- expect(sanitizeUserTextForCapture(" [toolUse: grep] ")).toBe("");- });-- it("preserves ordinary text that mentions a tool placeholder", () => {- const input = "The model echoed [tool: exec] in a previous answer.";- expect(sanitizeUserTextForCapture(input)).toBe(input);- });-it("strips leading timestamp prefix", () => {const input = "[2026-03-29T10:00:00Z] actual content here";const result = sanitizeUserTextForCapture(input);@@ -80,19 +61,6 @@ describe("sanitizeUserTextForCapture", () => {});});-describe("stripOpenVikingContextInjection", () => {- it("strips OpenViking context and relevant memories injected blocks", () => {- const input = [- "hello",- "<openviking-context>ctx</openviking-context>",- "<relevant-memories>legacy</relevant-memories>",- "world",- ].join(" ");- const result = stripOpenVikingContextInjection(input);- expect(result).toBe("hello world");- });-});-describe("getCaptureDecision", () => {it("semantic mode: normal text → shouldCapture=true", () => {const result = getCaptureDecision("我喜欢用 Python 写代码,平时也用 Go", "semantic", 24000);@@ -255,7 +223,7 @@ describe("extractNewTurnTexts", () => {});describe("extractNewTurnMessages", () => {- it("drops assistant toolCall messages that have no text block", () => {+ it("keeps assistant toolCall messages that have no text block", () => {const messages = [{role: "assistant",@@ -269,10 +237,15 @@ describe("extractNewTurnMessages", () => {const { messages: extracted, newCount } = extractNewTurnMessages(messages, 0);expect(newCount).toBe(1);- expect(extracted).toEqual([]);+ expect(extracted).toEqual([+ {+ role: "assistant",+ parts: [{ type: "text", text: "[tool: read_file]" }],+ },+ ]);});- it("drops assistant toolUse messages that have no text block", () => {+ it("keeps assistant toolUse messages that have no text block", () => {const messages = [{role: "assistant",@@ -286,10 +259,15 @@ describe("extractNewTurnMessages", () => {const { messages: extracted, newCount } = extractNewTurnMessages(messages, 0);expect(newCount).toBe(1);- expect(extracted).toEqual([]);+ expect(extracted).toEqual([+ {+ role: "assistant",+ parts: [{ type: "text", text: "[tool: grep]" }],+ },+ ]);});- it("does not synthesize placeholders for multiple textless assistant tool calls", () => {+ it("keeps multiple textless assistant tool calls in one placeholder", () => {const messages = [{role: "assistant",@@ -302,7 +280,12 @@ describe("extractNewTurnMessages", () => {const { messages: extracted } = extractNewTurnMessages(messages, 0);- expect(extracted).toEqual([]);+ expect(extracted).toEqual([+ {+ role: "assistant",+ parts: [{ type: "text", text: "[tool: read_file, grep]" }],+ },+ ]);});it("does not create a placeholder for textless assistant messages without tool calls", () => {diff --git a/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts b/examples/openclaw-plugin/tests/ut/tool-round-trip.test.tsindex 918aacdbc..31e0c30cd 100644--- a/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts+++ b/examples/openclaw-plugin/tests/ut/tool-round-trip.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { extractNewTurnMessages } from "../../text-utils.js";-import { convertToAgentMessages, mergeConsecutiveAssistants } from "../../context-engine.js";+import { convertToAgentMessages, mergeConsecutiveAssistants } from "../../services/context-message-adapter.js";describe("extractNewTurnMessages: toolCallId propagation", () => {it("propagates toolCallId from toolResult to extracted tool part", () => {@@ -145,7 +145,7 @@ describe("convertToAgentMessages: structured tool round-trip", () => {tool_status: "completed",tool_input: { path: "/tmp/big.txt" },tool_output: "preview only",- tool_output_ref: "viking://user/sessions/s1/tool-results/tr_call_big_abc",+ tool_output_ref: "viking://session/s1/tool-results/tr_call_big_abc",tool_output_original_chars: 120000,},],@@ -155,7 +155,7 @@ describe("convertToAgentMessages: structured tool round-trip", () => {const toolResult = result[1] as Record<string, unknown>;const content = toolResult.content as Array<Record<string, string>>;expect(content[0]!.text).toContain("preview only");- expect(content[0]!.text).toContain("viking://user/sessions/s1/tool-results/tr_call_big_abc");+ expect(content[0]!.text).toContain("viking://session/s1/tool-results/tr_call_big_abc");expect(content[0]!.text).toContain("original_chars=120000");});diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.tsindex 8c6c2f80b..4d50e9a7f 100644--- a/examples/openclaw-plugin/tests/ut/tools.test.ts+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts@@ -1,15 +1,17 @@-import { afterEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import { mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";-import contextEnginePlugin, {+import contextEnginePlugin from "../../index.js";+import {parseAddResourceCommandArgs,parseAddSkillCommandArgs,parseOVSearchCommandArgs,tokenizeCommandArgs,-} from "../../index.js";+} from "../../plugin/openviking-command-args.js";import type { FindResultItem } from "../../client.js";+import { openClawSessionToOvStorageId } from "../../routing/identity-routing.js";type ToolDef = {name: string;@@ -44,10 +46,6 @@ function okResponse(result: unknown): Response {});}-afterEach(() => {- vi.unstubAllGlobals();-});-function setupPlugin(clientOverrides?: Record<string, unknown>,pluginConfigOverrides?: Record<string, unknown>,@@ -66,6 +64,7 @@ function setupPlugin(memories_extracted: { core: 2 },}),deleteUri: vi.fn().mockResolvedValue(undefined),+ list: vi.fn().mockResolvedValue([]),getSessionArchive: vi.fn().mockResolvedValue({archive_id: "archive_001",abstract: "Test archive",@@ -114,31 +113,12 @@ function setupPlugin(const cmd = command as CommandDef;commands.set(cmd.name, cmd);}),+ registerHttpRoute: vi.fn(),registerService: vi.fn(),registerContextEngine: vi.fn(),on: vi.fn(),};- // Patch the module-level getClient- const originalRegister = contextEnginePlugin.register.bind(contextEnginePlugin);-- // We need to intercept the getClient inside register. Since register() creates- // the client promise internally, we mock the global module state.- // For remote mode, it creates: clientPromise = Promise.resolve(new OpenVikingClient(...))- // We can't easily mock that. Instead, let's rely on the fact that remote mode- // creates a real client. We'll mock at the fetch level or just test the logic.-- // Simpler approach: since the tools are closures, we need to register the plugin- // and then replace the client. But that's hard with closures.-- // Best approach: Test the tool execute functions by extracting them from the- // captured registerTool calls. The getClient() inside them will try to create- // a real client for remote mode. We need to mock fetch or accept that these- // tests focus on the logic, not the HTTP calls.-- // Actually, for testing, we can override the global fetch to return mock responses.- // But let's keep it simple and test the execution flow with proper mocking.-return { tools, factoryTools, commands, mockClient, api };}@@ -177,11 +157,10 @@ describe("Tool: memory_recall (registration)", () => {expect(props).toHaveProperty("limit");expect(props).toHaveProperty("scoreThreshold");expect(props).toHaveProperty("targetUri");- expect(props).toHaveProperty("resourceTypes");});it("fills L2 content and filters explicit recall results like auto-recall", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {const requestUrl = new URL(url);if (requestUrl.pathname === "/api/v1/system/status") {return okResponse({ user: "default" });@@ -189,21 +168,22 @@ describe("Tool: memory_recall (registration)", () => {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();+ const contextType = String(body.context_type ?? "");const memories =- [- 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,- }),- ];+ contextType === "memory"+ ? [+ 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 });}@@ -214,13 +194,14 @@ describe("Tool: memory_recall (registration)", () => {return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const { factoryTools, api } = setupPlugin(undefined, {recallLimit: 1,recallPreferAbstract: true,recallScoreThreshold: 0.2,+ recallTargetTypes: ["user", "agent"],});+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const factory = factoryTools.get("memory_recall");expect(factory).toBeDefined();@@ -236,7 +217,7 @@ describe("Tool: memory_recall (registration)", () => {expect(result.content[0]!.text).not.toContain("Abstract only text");expect(result.content[0]!.text).not.toContain("Low score text");- const findCalls = fetchMock.mock.calls.filter(([calledUrl]) =>+ const findCalls = openVikingTransport.mock.calls.filter(([calledUrl]) =>String(calledUrl).includes("/api/v1/search/find"));expect(findCalls).toHaveLength(1);@@ -249,95 +230,8 @@ describe("Tool: memory_recall (registration)", () => {}});- 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") {- return okResponse({ user: "default" });- }- if (requestUrl.pathname === "/api/v1/search/find") {- return okResponse({ memories: [], resources: [], skills: [], total: 0 });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { factoryTools, api } = setupPlugin(undefined, {- peer_role: "person",- });- contextEnginePlugin.register(api as any);- const tool = factoryTools.get("memory_recall")!({- sessionId: "test-session",- requesterSenderId: "wx/user-01@abc",- });-- await tool.execute("tc-memory-recall-peer", {- query: "backend preference",- }) as ToolResult;-- const findRequests = fetchMock.mock.calls- .filter(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))- .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");- }- });-- it("lets memory_recall override default targets with resourceTypes", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {- const requestUrl = new URL(url);- if (requestUrl.pathname === "/api/v1/system/status") {- return okResponse({ user: "default" });- }- if (requestUrl.pathname === "/api/v1/search/find") {- const body = JSON.parse(String(init?.body ?? "{}"));- expect(body.context_type).toBe("resource");- expect(body.target_uri).toBeUndefined();- return okResponse({- memories: [],- resources: [- makeMemory({- uri: "viking://resources/project/design.md",- abstract: "Resource design note",- score: 0.9,- }),- ],- skills: [],- total: 1,- });- }- if (requestUrl.pathname === "/api/v1/content/read") {- return okResponse("Resource design full text");- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { factoryTools, api } = setupPlugin(undefined, {- recallLimit: 1,- recallScoreThreshold: 0.2,- });- contextEnginePlugin.register(api as any);- const tool = factoryTools.get("memory_recall")!({ sessionId: "test-session" });-- const result = await tool.execute("tc-resource-recall", {- query: "design note",- resourceTypes: ["resource"],- }) as ToolResult;-- expect(result.content[0]!.text).toContain("Resource design full text");- const findCalls = fetchMock.mock.calls.filter(([calledUrl]) =>- String(calledUrl).includes("/api/v1/search/find")- );- expect(findCalls).toHaveLength(1);- });-it("applies recallMaxInjectedChars to explicit memory_recall output", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {const requestUrl = new URL(url);if (requestUrl.pathname === "/api/v1/system/status") {return okResponse({ user: "default" });@@ -345,21 +239,22 @@ describe("Tool: memory_recall (registration)", () => {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();+ const contextType = String(body.context_type ?? "");const memories =- [- 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,- }),- ];+ contextType === "memory"+ ? [+ 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 });}@@ -370,13 +265,14 @@ describe("Tool: memory_recall (registration)", () => {return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const { factoryTools, api } = setupPlugin(undefined, {recallLimit: 2,recallMaxInjectedChars: 20,recallScoreThreshold: 0.2,+ recallTargetTypes: ["user", "agent"],});+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const factory = factoryTools.get("memory_recall");expect(factory).toBeDefined();@@ -395,44 +291,44 @@ describe("Tool: memory_recall (registration)", () => {});it("applies /ov-query-config session settings to subsequent memory_recall", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {const requestUrl = new URL(url);if (requestUrl.pathname === "/api/v1/system/status") {return okResponse({ user: "default" });}+if (requestUrl.pathname === "/api/v1/search/find") {const body = JSON.parse(String(init?.body ?? "{}"));- expect(body.context_type).toBe("memory");- expect(body.target_uri).toBeUndefined();- return okResponse({- memories: [- makeMemory({- uri: "viking://user/default/memories/high",- abstract: "High score runtime memory",- score: 0.92,- }),- makeMemory({- uri: "viking://user/default/memories/low",- abstract: "Low score runtime memory",- score: 0.1,- }),- ],- resources: [],- skills: [],- total: 2,- });+ const contextType = String(body.context_type ?? "");+ const memories = contextType === "memory"+ ? [+ makeMemory({+ uri: "viking://user/default/memories/high",+ abstract: "High score runtime memory",+ score: 0.92,+ }),+ makeMemory({+ uri: "viking://user/default/memories/low",+ abstract: "Low score runtime memory",+ score: 0.1,+ }),+ ]+ : [];+ return okResponse({ memories, total: memories.length });}+if (requestUrl.pathname === "/api/v1/content/read") {return okResponse("High score runtime memory content");}+return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const { factoryTools, commands, api } = setupPlugin(undefined, {recallLimit: 6,recallTargetTypes: ["user", "agent"],});+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const command = commands.get("ov-query-config");expect(command).toBeDefined();@@ -451,7 +347,7 @@ describe("Tool: memory_recall (registration)", () => {expect(result.content[0]!.text).toContain("High score runtime memory content");expect(result.content[0]!.text).not.toContain("Low score runtime memory");- const findCalls = fetchMock.mock.calls.filter(([calledUrl]) =>+ const findCalls = openVikingTransport.mock.calls.filter(([calledUrl]) =>String(calledUrl).includes("/api/v1/search/find"));expect(findCalls).toHaveLength(1);@@ -461,52 +357,6 @@ describe("Tool: memory_recall (registration)", () => {expect(body.limit).toBe(3);});- it("applies /ov-query-config session settings to subsequent ov_search", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {- const requestUrl = new URL(url);- if (requestUrl.pathname === "/api/v1/system/status") {- return okResponse({ user: "default" });- }- if (requestUrl.pathname === "/api/v1/search/find") {- const body = JSON.parse(String(init?.body ?? "{}"));- expect(body.target_uri).toBe("viking://resources/project");- expect(body.limit).toBe(2);- return okResponse({- memories: [],- resources: [makeMemory({- uri: "viking://resources/project/spec.md",- abstract: "Project spec",- score: 0.9,- })],- skills: [],- total: 1,- });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { factoryTools, commands, api } = setupPlugin();- contextEnginePlugin.register(api as any);- const command = commands.get("ov-query-config");- expect(command).toBeDefined();-- await command!.handler({- args: "set --scope session --ovSearchLimit 2 --targetUri viking://resources/project",- commandBody: "",- sessionId: "runtime-search-session",- agentId: "main",- });-- const search = factoryTools.get("ov_search")!({ sessionId: "runtime-search-session", agentId: "main" });- const result = await search.execute("tc-ov-search-runtime", {- query: "project spec",- }) as ToolResult;-- expect(result.details.uri).toBe("viking://resources/project");- expect(result.details.total).toBe(1);- });-it("supports /ov-query-config get, unset, and reset for session scope", async () => {const { commands, api } = setupPlugin(undefined, {recallLimit: 6,@@ -515,6 +365,7 @@ describe("Tool: memory_recall (registration)", () => {contextEnginePlugin.register(api as any);const command = commands.get("ov-query-config");expect(command).toBeDefined();+const ctx = {commandBody: "",sessionId: "runtime-session-config",@@ -543,6 +394,53 @@ describe("Tool: memory_recall (registration)", () => {expect((resetResult.details?.effective as any).recallLimit).toBe(6);expect((resetResult.details?.effective as any).scoreThreshold).toBe(0.15);});++ it("supports /ov-query-config weight parameters and recallPreferAbstract", async () => {+ const { commands, api } = setupPlugin(undefined, {+ recallPreferAbstract: true,+ });+ contextEnginePlugin.register(api as any);+ const command = commands.get("ov-query-config");+ expect(command).toBeDefined();++ const result = await command!.handler({+ args: "set --scope session --weight baseScore=0.5,leaf=0.7 --categoryWeight preferences=1.5 --resourceTypeWeight user=0.25 --recallPreferAbstract false",+ commandBody: "",+ sessionId: "runtime-weight-session",+ agentId: "main",+ });++ const effective = result.details?.effective as any;+ expect(effective.rankingWeights).toMatchObject({ baseScore: 0.5, leaf: 0.7 });+ expect(effective.categoryWeights).toMatchObject({ preferences: 1.5 });+ expect(effective.resourceTypeWeights).toMatchObject({ user: 0.25 });+ expect(effective.recallPreferAbstract).toBe(false);+ expect(result.details?.params).toMatchObject({+ rankingWeights: { baseScore: 0.5, leaf: 0.7 },+ categoryWeights: { preferences: 1.5 },+ resourceTypeWeights: { user: 0.25 },+ recallPreferAbstract: false,+ });+ });++ it("rejects empty /ov-query-config set patches without overwriting existing config", async () => {+ const { commands, api } = setupPlugin(undefined, { recallLimit: 6 });+ contextEnginePlugin.register(api as any);+ const command = commands.get("ov-query-config");+ expect(command).toBeDefined();+ const ctx = {+ commandBody: "",+ sessionId: "runtime-empty-patch-session",+ agentId: "main",+ };++ await command!.handler({ ...ctx, args: "set --scope session --recallLimit 2" });+ const emptyResult = await command!.handler({ ...ctx, args: "set --scope session --unknown 1" });+ const getResult = await command!.handler({ ...ctx, args: "get --scope session" });++ expect(emptyResult.text).toContain("No query config parameters provided");+ expect((getResult.details?.effective as any).recallLimit).toBe(2);+ });});describe("Tool: memory_store (behavioral)", () => {@@ -553,12 +451,10 @@ describe("Tool: memory_store (behavioral)", () => {expect(store).toBeDefined();expect(store!.name).toBe("memory_store");expect(store!.description).toContain("Store text");- expect(store!.description).toContain("explicitly asks to remember");- expect(store!.description).toContain("threshold/commit dependent");});- it("uses requesterSenderId to populate peer_id for user writes", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ it("uses requesterSenderId to populate role_id for user writes", async () => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "default" });}@@ -574,9 +470,9 @@ describe("Tool: memory_store (behavioral)", () => {}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);- const { factoryTools, api } = setupPlugin(undefined, { peer_role: "person" });+ const { factoryTools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const factory = factoryTools.get("memory_store");expect(factory).toBeDefined();@@ -587,115 +483,20 @@ describe("Tool: memory_store (behavioral)", () => {requesterSenderId: "wx/user-01@abc",});- const result = await tool.execute("tc-memory-store", { text: "hello from tool" }) as ToolResult;-- const messageCall = fetchMock.mock.calls.find(([url]) =>- String(url).includes("/api/v1/sessions/") && String(url).includes("/messages"),- );- expect(messageCall).toBeDefined();- const [, init] = messageCall as [string, RequestInit];- const body = JSON.parse(String(init.body));- expect(body.role).toBe("user");- expect(body.peer_id).toBe("wx_user-01_abc");- expect(result.content[0]!.text).toContain("committed 1 memories");- expect(result.details.action).toBe("stored");- expect(result.details.memoriesCount).toBe(1);-- const createCall = fetchMock.mock.calls.find(([url]) =>- String(url).endsWith("/api/v1/sessions"),- );- expect(createCall).toBeDefined();- expect(JSON.parse(String((createCall![1] as RequestInit).body))).toMatchObject({- memory_policy: {- self: { enabled: true },- peer: { enabled: true },- },- });-- const commitCall = fetchMock.mock.calls.find(([url]) =>- String(url).endsWith("/commit"),- );- expect(commitCall).toBeDefined();- expect(JSON.parse(String((commitCall![1] as RequestInit).body))).not.toHaveProperty(- "memory_policy",- );- });-- it("does not populate peer_id for user writes by default", async () => {- const fetchMock = vi.fn(async (url: string) => {- if (url.endsWith("/api/v1/system/status")) {- return okResponse({ user: "default" });- }- if (url.includes("/messages")) {- return okResponse({ session_id: "sess-1" });- }- if (url.endsWith("/commit")) {- return okResponse({ status: "completed", archived: false, memories_extracted: { core: 1 } });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { factoryTools, api } = setupPlugin();- contextEnginePlugin.register(api as any);- const tool = factoryTools.get("memory_store")!({- sessionId: "runtime-session",- sessionKey: "agent:main:main",- requesterSenderId: "wx/user-01@abc",- });-- await tool.execute("tc-memory-store-default-peer", { text: "hello from tool" });+ await tool.execute("tc-memory-store", { text: "hello from tool" });- const messageCall = fetchMock.mock.calls.find(([url]) =>+ const messageCall = openVikingTransport.mock.calls.find(([url]) =>String(url).includes("/api/v1/sessions/") && String(url).includes("/messages"),);expect(messageCall).toBeDefined();const [, init] = messageCall as [string, RequestInit];const body = JSON.parse(String(init.body));expect(body.role).toBe("user");- expect(body.peer_id).toBeUndefined();- });-- it("uses runtime agent as peer_id for assistant writes when peer_role is assistant", async () => {- const fetchMock = vi.fn(async (url: string) => {- if (url.endsWith("/api/v1/system/status")) {- return okResponse({ user: "default" });- }- if (url.includes("/messages")) {- return okResponse({ session_id: "sess-1" });- }- if (url.endsWith("/commit")) {- return okResponse({ status: "completed", archived: false, memories_extracted: { core: 1 } });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { factoryTools, api } = setupPlugin(undefined, { peer_role: "assistant" });- contextEnginePlugin.register(api as any);- const tool = factoryTools.get("memory_store")!({- sessionId: "runtime-session",- sessionKey: "agent:worker:main",- requesterSenderId: "wx/user-01@abc",- });-- await tool.execute("tc-memory-store-assistant-peer", {- text: "assistant note",- role: "assistant",- });-- const messageCall = fetchMock.mock.calls.find(([url]) =>- String(url).includes("/api/v1/sessions/") && String(url).includes("/messages"),- );- expect(messageCall).toBeDefined();- const [, init] = messageCall as [string, RequestInit];- const body = JSON.parse(String(init.body));- expect(body.role).toBe("assistant");- expect(body.peer_id).toBe("worker");+ expect(body.role_id).toBe("wx_user-01_abc");});it("uses a temporary session by default instead of the current tool session", async () => {- const fetchMock = vi.fn(async (url: string) => {+ const openVikingTransport = vi.fn(async (url: string) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "default" });}@@ -703,13 +504,13 @@ describe("Tool: memory_store (behavioral)", () => {return okResponse({ session_id: "sess-1" });}if (url.endsWith("/commit")) {- return okResponse({ status: "completed", archived: false, memories_extracted: { core: 1 } });+ return okResponse({ status: "completed", archived: false, memories_extracted: {} });}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const { factoryTools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const tool = factoryTools.get("memory_store")!({sessionId: "runtime-session",@@ -718,14 +519,14 @@ describe("Tool: memory_store (behavioral)", () => {await tool.execute("tc-memory-store", { text: "hello from tool" });- const messageCall = fetchMock.mock.calls.find(([url]) =>+ const messageCall = openVikingTransport.mock.calls.find(([url]) =>String(url).includes("/api/v1/sessions/") && String(url).includes("/messages"),);expect(String(messageCall?.[0])).toContain("/api/v1/sessions/memory-store-");});it("normalizes explicit memory_store sessionId without using current sessionKey", async () => {- const fetchMock = vi.fn(async (url: string) => {+ const openVikingTransport = vi.fn(async (url: string) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "default" });}@@ -733,13 +534,13 @@ describe("Tool: memory_store (behavioral)", () => {return okResponse({ session_id: "sess-1" });}if (url.endsWith("/commit")) {- return okResponse({ status: "completed", archived: false, memories_extracted: { core: 1 } });+ return okResponse({ status: "completed", archived: false, memories_extracted: {} });}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const { factoryTools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const tool = factoryTools.get("memory_store")!({sessionId: "runtime-session",@@ -751,143 +552,38 @@ describe("Tool: memory_store (behavioral)", () => {sessionId: "C:\\Users\\test",});- const messageCall = fetchMock.mock.calls.find(([url]) =>+ const messageCall = openVikingTransport.mock.calls.find(([url]) =>String(url).includes("/api/v1/sessions/") && String(url).includes("/messages"),);expect(String(messageCall?.[0])).not.toContain("runtime-session");expect(String(messageCall?.[0])).not.toContain("agent%3Amain%3Amain");expect(String(messageCall?.[0])).toMatch(/\/api\/v1\/sessions\/[a-f0-9]{64}\/messages$/);});+});- it("returns a tool-visible failure when commit extracts zero memories", async () => {- const fetchMock = vi.fn(async (url: string) => {- if (url.endsWith("/api/v1/system/status")) {- return okResponse({ user: "default" });- }- if (url.includes("/messages")) {- return okResponse({ session_id: "sess-1" });- }- if (url.endsWith("/commit")) {- return okResponse({ status: "completed", archived: true, memories_extracted: {} });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);+describe("Tool: memory_forget (behavioral)", () => {+ it("registers with correct name and description", () => {+ const { tools, api } = setupPlugin();+ contextEnginePlugin.register(api as any);+ const forget = tools.get("memory_forget");+ expect(forget).toBeDefined();+ expect(forget!.name).toBe("memory_forget");+ expect(forget!.description).toContain("Forget memory");+ });+});+describe("Tool: ov_archive_expand (behavioral)", () => {+ it("registers as factory tool with correct name", () => {const { factoryTools, api } = setupPlugin();contextEnginePlugin.register(api as any);- const tool = factoryTools.get("memory_store")!({- sessionId: "runtime-session",- sessionKey: "agent:main:main",- });-- const result = await tool.execute("tc-memory-store-zero", {- text: "Remember this important thing",- }) as ToolResult;-- expect(result.content[0]!.text).toContain("produced 0 memories");- expect(result.content[0]!.text).toContain("No OpenViking-managed long-term memory was stored");- expect(result.details.action).toBe("failed");- expect(result.details.error).toBe("no_memories_extracted");- expect(result.details.memoriesCount).toBe(0);- expect(result.details.archived).toBe(true);+ const factory = factoryTools.get("ov_archive_expand");+ expect(factory).toBeDefined();+ const tool = factory!({ sessionId: "test-session", sessionKey: "sk" });+ expect(tool.name).toBe("ov_archive_expand");+ expect(tool.description).toContain("archive");});- it("returns commit failure details to the model", async () => {- const fetchMock = vi.fn(async (url: string) => {- if (url.endsWith("/api/v1/system/status")) {- return okResponse({ user: "default" });- }- if (url.includes("/messages")) {- return okResponse({ session_id: "sess-1" });- }- if (url.endsWith("/commit")) {- return okResponse({- status: "failed",- error: "memory extraction provider unavailable",- });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { factoryTools, api } = setupPlugin();- contextEnginePlugin.register(api as any);- const tool = factoryTools.get("memory_store")!({- sessionId: "runtime-session",- sessionKey: "agent:main:main",- });-- const result = await tool.execute("tc-memory-store-failed", {- text: "Remember this important thing",- }) as ToolResult;-- expect(result.content[0]!.text).toContain("Memory extraction failed");- expect(result.content[0]!.text).toContain("memory extraction provider unavailable");- expect(result.details.action).toBe("failed");- expect(result.details.status).toBe("failed");- expect(result.details.error).toBe("memory extraction provider unavailable");- });-- it("returns commit timeout details to the model", async () => {- const fetchMock = vi.fn(async (url: string) => {- if (url.endsWith("/api/v1/system/status")) {- return okResponse({ user: "default" });- }- if (url.includes("/messages")) {- return okResponse({ session_id: "sess-1" });- }- if (url.endsWith("/commit")) {- return okResponse({- status: "timeout",- });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { factoryTools, api } = setupPlugin();- contextEnginePlugin.register(api as any);- const tool = factoryTools.get("memory_store")!({- sessionId: "runtime-session",- sessionKey: "agent:main:main",- });-- const result = await tool.execute("tc-memory-store-timeout", {- text: "Remember this important thing",- }) as ToolResult;-- expect(result.content[0]!.text).toContain("Memory extraction timed out");- expect(result.content[0]!.text).toContain("task_id=none");- expect(result.details.action).toBe("timeout");- expect(result.details.status).toBe("timeout");- expect(result.details.taskId).toBeUndefined();- });-});--describe("Tool: memory_forget (behavioral)", () => {- it("registers with correct name and description", () => {- const { tools, api } = setupPlugin();- contextEnginePlugin.register(api as any);- const forget = tools.get("memory_forget");- expect(forget).toBeDefined();- expect(forget!.name).toBe("memory_forget");- expect(forget!.description).toContain("Forget memory");- });-});--describe("Tool: ov_archive_expand (behavioral)", () => {- it("registers as factory tool with correct name", () => {- const { factoryTools, api } = setupPlugin();- contextEnginePlugin.register(api as any);- const factory = factoryTools.get("ov_archive_expand");- expect(factory).toBeDefined();- const tool = factory!({ sessionId: "test-session", sessionKey: "sk" });- expect(tool.name).toBe("ov_archive_expand");- expect(tool.description).toContain("archive");- });-- it("factory-created tool returns error when archiveId is empty", async () => {+ it("factory-created tool returns error when archiveId is empty", async () => {const { factoryTools, api } = setupPlugin();contextEnginePlugin.register(api as any);const factory = factoryTools.get("ov_archive_expand");@@ -921,7 +617,7 @@ describe("Tool: OpenViking tool result access", () => {});it("reads an externalized tool result chunk for the current session", async () => {- const fetchMock = vi.fn(async (url: string) => {+ const openVikingTransport = vi.fn(async (url: string) => {expect(url).toContain("/api/v1/sessions/test-session/tool-results/tr_call_abc");expect(url).toContain("offset=5");expect(url).toContain("limit=10");@@ -935,19 +631,19 @@ describe("Tool: OpenViking tool result access", () => {total_chars: 42,has_more: true,metadata: {- storage_uri: "viking://user/sessions/test-session/tool-results/tr_call_abc",+ storage_uri: "viking://session/test-session/tool-results/tr_call_abc",tool_name: "read_file",},});});- vi.stubGlobal("fetch", fetchMock);const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const tool = tools.get("openviking_tool_result_read")!;const result = await tool.execute("tc-read", {- tool_output_ref: "viking://user/sessions/test-session/tool-results/tr_call_abc",+ tool_output_ref: "viking://session/test-session/tool-results/tr_call_abc",offset: 5,limit: 10,}) as ToolResult;@@ -955,7 +651,7 @@ describe("Tool: OpenViking tool result access", () => {expect(result.content[0]!.text).toBe("raw");expect(result.details).toMatchObject({action: "read",- tool_output_ref: "viking://user/sessions/test-session/tool-results/tr_call_abc",+ tool_output_ref: "viking://session/test-session/tool-results/tr_call_abc",tool_result_id: "tr_call_abc",offset: 5,limit: 10,@@ -967,7 +663,7 @@ describe("Tool: OpenViking tool result access", () => {});it("searches within an externalized tool result", async () => {- const fetchMock = vi.fn(async (url: string) => {+ const openVikingTransport = vi.fn(async (url: string) => {expect(url).toContain("/api/v1/sessions/test-session/tool-results/tr_call_abc/search?");expect(url).toContain("q=needle");expect(url).toContain("limit=2");@@ -983,14 +679,14 @@ describe("Tool: OpenViking tool result access", () => {],});});- vi.stubGlobal("fetch", fetchMock);const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const tool = tools.get("openviking_tool_result_search")!;const result = await tool.execute("tc-search", {- tool_output_ref: "viking://user/default/sessions/test-session/tool-results/tr_call_abc",+ tool_output_ref: "viking://session/test-session/tool-results/tr_call_abc",query: "needle",limit: 2,context_chars: 15,@@ -1001,7 +697,7 @@ describe("Tool: OpenViking tool result access", () => {expect(result.content[0]!.text).toContain("hay needle stack");expect(result.details).toMatchObject({action: "searched",- tool_output_ref: "viking://user/sessions/test-session/tool-results/tr_call_abc",+ tool_output_ref: "viking://session/test-session/tool-results/tr_call_abc",tool_result_id: "tr_call_abc",query: "needle",match_count: 1,@@ -1009,7 +705,7 @@ describe("Tool: OpenViking tool result access", () => {});it("lists externalized tool results for the current session", async () => {- const fetchMock = vi.fn(async (url: string) => {+ const openVikingTransport = vi.fn(async (url: string) => {expect(url).toContain("/api/v1/sessions/test-session/tool-results?");expect(url).toContain("tool_name=read_file");expect(url).toContain("limit=5");@@ -1017,7 +713,7 @@ describe("Tool: OpenViking tool result access", () => {tool_results: [{tool_result_id: "tr_call_abc",- storage_uri: "viking://user/sessions/test-session/tool-results/tr_call_abc",+ storage_uri: "viking://session/test-session/tool-results/tr_call_abc",tool_name: "read_file",original_chars: 42000,created_at: "2026-05-15T00:00:00Z",@@ -1025,9 +721,9 @@ describe("Tool: OpenViking tool result access", () => {],});});- vi.stubGlobal("fetch", fetchMock);const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const tool = tools.get("openviking_tool_result_list")!;@@ -1038,7 +734,7 @@ describe("Tool: OpenViking tool result access", () => {expect(result.content[0]!.text).toContain("read_file");expect(result.content[0]!.text).toContain("original_chars=42000");- expect(result.content[0]!.text).toContain("viking://user/sessions/test-session/tool-results/tr_call_abc");+ expect(result.content[0]!.text).toContain("viking://session/test-session/tool-results/tr_call_abc");expect(result.details).toMatchObject({action: "listed",session_id: "test-session",@@ -1059,61 +755,28 @@ describe("Tool: OpenViking tool result access", () => {expect(result.content[0]!.text).toContain("another session");expect(result.details.error).toBe("session_mismatch");});-- it("accepts legacy tool result refs as input", async () => {- const fetchMock = vi.fn(async () =>- okResponse({- tool_result_id: "tr_call_abc",- content: "raw",- offset: 0,- limit: 20000,- offset_unit: "unicode_code_point",- total_chars: 3,- has_more: false,- }),- );- vi.stubGlobal("fetch", fetchMock);-- const { tools, api } = setupPlugin();- contextEnginePlugin.register(api as any);- const tool = tools.get("openviking_tool_result_read")!;-- const result = await tool.execute("tc-read", {- tool_output_ref: "viking://session/test-session/tool-results/tr_call_abc",- }) as ToolResult;-- expect(result.content[0]!.text).toBe("raw");- expect(result.details.tool_output_ref).toBe(- "viking://user/sessions/test-session/tool-results/tr_call_abc",- );- });});describe("Tool: add_resource, add_skill, and ov_search (registration)", () => {- it("does not register add_resource by default", () => {+ it("does not register add_resource tool by default", () => {const { tools, api } = setupPlugin();contextEnginePlugin.register(api as any);expect(tools.get("add_resource")).toBeUndefined();});- it("registers add_resource tool with expected parameters when explicitly enabled", () => {+ it("registers add_resource tool with expected parameters only when explicitly enabled", () => {const { tools, api } = setupPlugin(undefined, { enableAddResourceTool: true });contextEnginePlugin.register(api as any);const tool = tools.get("add_resource");expect(tool).toBeDefined();expect(tool!.description).toContain("explicitly asks");- expect(tool!.description).toContain("Never use this during search");expect(tool!.description).toContain("[media attached: /path");- expect(tool!.description).toContain("Set either to");- expect(tool!.description).toContain("never both");expect(tool!.description).toContain("Do not invent OpenViking upload REST endpoints");const props = (tool!.parameters as any).properties;expect(props).toHaveProperty("source");expect(props.source.description).toContain("OpenClaw media attachment path");expect(props).toHaveProperty("to");- expect(props.to.description).toContain("Mutually exclusive with parent");expect(props).toHaveProperty("parent");- expect(props.parent.description).toContain("Mutually exclusive with to");expect(props).toHaveProperty("reason");expect(props).toHaveProperty("instruction");expect(props).toHaveProperty("wait");@@ -1154,163 +817,16 @@ describe("Tool: add_resource, add_skill, and ov_search (registration)", () => {expect(props).toHaveProperty("limit");});- it("registers ov_recall_trace tool and command", () => {- const { tools, commands, api } = setupPlugin(undefined, { traceRecall: true });+ it("registers ov_read and ov_multi_read tools with OpenViking URI guidance", () => {+ const { tools, api } = setupPlugin();contextEnginePlugin.register(api as any);-- const tool = tools.get("ov_recall_trace");+ const tool = tools.get("ov_read");expect(tool).toBeDefined();- expect(tool!.description).toContain("recall trace");+ expect(tool!.description).toContain("viking:// URI");+ expect(tool!.description).toContain("not local file paths");const props = (tool!.parameters as any).properties;- expect(props).toHaveProperty("traceId");- expect(props).toHaveProperty("source");- expect(props).toHaveProperty("resourceTypes");- expect(props).toHaveProperty("includeContent");- expect(props).toHaveProperty("limit");- expect(commands.get("ov-recall-trace")).toMatchObject({- acceptsArgs: true,- description: "Query OpenViking recall trace records.",- });- });-- it("registers recall trace gateway routes when a route adapter is available", async () => {- const { api } = setupPlugin(undefined, { traceRecall: true });- contextEnginePlugin.register(api as any);- const service = (api.registerService as any).mock.calls[0][0];- const registerRoute = vi.fn();- const registerHttpRoute = vi.fn();-- await service.start({ registerRoute, registerHttpRoute });-- expect(registerRoute).toHaveBeenCalledWith(expect.objectContaining({- method: "GET",- path: "/api/openviking/recall-traces",- }));- expect(registerRoute).toHaveBeenCalledWith(expect.objectContaining({- method: "GET",- path: "/api/openviking/uri-detail",- }));- expect(registerRoute).toHaveBeenCalledWith(expect.objectContaining({- method: "GET",- path: "/api/openviking/recall-traces/latest-ov-search-list",- }));- expect(registerRoute).toHaveBeenCalledWith(expect.objectContaining({- method: "GET",- path: "/api/openviking/recall-traces/:traceId",- }));- expect(registerHttpRoute).toHaveBeenCalledWith(expect.objectContaining({- path: "/api/openviking/recall-traces",- auth: "plugin",- match: "exact",- }));- expect(registerHttpRoute).toHaveBeenCalledWith(expect.objectContaining({- path: "/api/openviking/uri-detail",- auth: "plugin",- match: "exact",- }));- expect(registerHttpRoute).toHaveBeenCalledWith(expect.objectContaining({- path: "/api/openviking/recall-traces/latest-ov-search-list",- auth: "plugin",- match: "exact",- }));- });-- it("serves latest ov_search list and URI detail recall trace routes", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {- const requestUrl = new URL(url);- if (requestUrl.pathname === "/api/v1/system/status") {- return okResponse({ user: "default" });- }- if (requestUrl.pathname === "/api/v1/search/find") {- const body = JSON.parse(String(init?.body ?? "{}"));- return okResponse({- memories: [],- resources: body.context_type === "resource" ? [makeMemory({- uri: "viking://resources/project/spec.md",- abstract: "Project spec abstract",- score: 0.88,- })] : [],- skills: body.context_type === "skill" ? [makeMemory({- uri: "viking://user/skills/project-skill",- abstract: "Project skill abstract",- score: 0.72,- })] : [],- total: 1,- });- }- if (requestUrl.pathname === "/api/v1/content/read") {- expect(requestUrl.searchParams.get("uri")).toBe("viking://resources/project/spec.md");- return okResponse("Full project spec content");- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { tools, api } = setupPlugin(undefined, { traceRecall: true });- contextEnginePlugin.register(api as any);- await tools.get("ov_search")!.execute("tc-search", { query: "project spec" });-- const service = (api.registerService as any).mock.calls[0][0];- const routes: Array<{ path: string; handler: (request?: { query?: Record<string, unknown> }) => Promise<any> }> = [];- await service.start({- registerRoute: (route: { path: string; handler: (request?: { query?: Record<string, unknown> }) => Promise<any> }) => {- routes.push(route);- },- });-- const latest = routes.find((route) => route.path === "/api/openviking/recall-traces/latest-ov-search-list");- expect(latest).toBeDefined();- const latestResult = await latest!.handler({ query: { limit: "5" } });- expect(latestResult.status).toBe(200);- expect(latestResult.body.ok).toBe(true);- expect(latestResult.body.items.map((item: any) => item.uri)).toContain("viking://resources/project/spec.md");- expect(latestResult.body.items.map((item: any) => item.uri)).toContain("viking://user/skills/project-skill");- expect(latestResult.body.items[0].detailUrl).toContain("/api/openviking/uri-detail");-- const detail = routes.find((route) => route.path === "/api/openviking/uri-detail");- expect(detail).toBeDefined();- const detailResult = await detail!.handler({- query: {- uri: "viking://resources/project/spec.md",- traceId: latestResult.body.trace.traceId,- contentLimit: "4",- },- });- expect(detailResult.status).toBe(200);- expect(detailResult.body.uriType).toBe("resource");- expect(detailResult.body.abstractPreview).toContain("Project spec abstract");- expect(detailResult.body.content.text).toBe("Full");- expect(detailResult.body.content.hasMore).toBe(true);- });-- it("applies enabledTools and disabledTools to runtime tool registration", () => {- const { tools, api } = setupPlugin(undefined, {- enabledTools: ["resource_query", "memory"],- disabledTools: ["memory_forget"],- });- contextEnginePlugin.register(api as any);-- expect(tools.get("ov_search")).toBeDefined();- expect(tools.get("ov_read")).toBeDefined();- expect(tools.get("ov_multi_read")).toBeDefined();- expect(tools.get("ov_list")).toBeDefined();- expect(tools.get("memory_recall")).toBeDefined();- expect(tools.get("memory_store")).toBeDefined();- expect(tools.get("memory_forget")).toBeUndefined();- expect(tools.get("add_skill")).toBeUndefined();- expect(tools.get("add_resource")).toBeUndefined();- });-- it("registers ov_read and ov_multi_read tools for original evidence retrieval", () => {- const { tools, api } = setupPlugin();- contextEnginePlugin.register(api as any);-- const read = tools.get("ov_read");- expect(read).toBeDefined();- expect(read!.description).toContain("Read the full original content");- expect(read!.description).toContain("after ov_search");- expect(read!.description).toContain("Do not use filesystem read/cat");- expect((read!.parameters as any).properties).toHaveProperty("uri");+ expect(props).toHaveProperty("uri");+ expect(props.uri.description).toContain("Exact viking:// URI");const multiRead = tools.get("ov_multi_read");expect(multiRead).toBeDefined();@@ -1337,7 +853,7 @@ describe("Tool: add_resource, add_skill, and ov_search (registration)", () => {describe("Tool: ov_search (behavioral)", () => {it("searches resources and skills by default when no uri is provided", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "default" });}@@ -1346,7 +862,7 @@ describe("Tool: ov_search (behavioral)", () => {}if (url.endsWith("/api/v1/search/find")) {const body = JSON.parse(String(init?.body ?? "{}"));- if (body.context_type === "resource") {+ if (body.target_uri === "viking://resources") {return okResponse({memories: [],resources: [@@ -1366,7 +882,6 @@ describe("Tool: ov_search (behavioral)", () => {total: 1,});}- expect(body.context_type).toBe("skill");return okResponse({memories: [],resources: [],@@ -1388,32 +903,32 @@ describe("Tool: ov_search (behavioral)", () => {}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const search = tools.get("ov_search")!;const result = await search.execute("tc1", { query: "OpenViking install" }) as ToolResult;expect(result.content[0]!.text).toContain("no");expect(result.content[0]!.text).toContain("type");- expect(result.content[0]!.text).toContain("Use ov_read on exact hit URIs");- expect(result.content[0]!.text).toContain("Use ov_list on a hit's parent URI");expect(result.content[0]!.text).toContain("resource");expect(result.content[0]!.text).toContain("skill");+ expect(result.content[0]!.text).toContain("not local file paths");+ expect(result.content[0]!.text).toContain("ov_read");+ expect(result.content[0]!.text).toContain("Use ov_list on a hit's parent URI");expect(result.details.resources).toHaveLength(1);expect(result.details.skills).toHaveLength(1);- const findBodies = fetchMock.mock.calls+ const findBodies = openVikingTransport.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);- expect(findBodies.map((body) => body.context_type).sort()).toEqual(["resource", "skill"]);- expect(findBodies.every((body) => body.target_uri === undefined)).toBe(true);+ 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);});- it("records ov_search recall traces when traceRecall is enabled", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ it("returns partial results when one default scope search fails", async () => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "default" });}@@ -1422,305 +937,218 @@ 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") {+ return okResponse({+ memories: [],+ resources: [+ {+ context_type: "resource",+ uri: "viking://resources/openviking-readme/README.md",+ level: 2,+ score: 0.82,+ category: "",+ match_reason: "",+ relations: [],+ abstract: "OpenViking install guide",+ overview: null,+ },+ ],+ skills: [],+ total: 1,+ });+ }+ throw new Error("skills search unavailable");+ }+ return okResponse({});+ });++ const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);+ const search = tools.get("ov_search")!;+ const result = await search.execute("tc1", { query: "OpenViking install" }) as ToolResult;++ expect(result.details.resources).toHaveLength(1);+ expect(result.details.skills).toHaveLength(0);+ expect(result.content[0]!.text).toContain("resource");+ });++ it("renders memory hits when explicit uri returns memories", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {+ if (url.endsWith("/api/v1/search/find")) {return okResponse({- memories: [],- resources: body.context_type === "resource" ? [+ memories: [{- context_type: "resource",- uri: "viking://resources/trace-design.md",+ context_type: "memory",+ uri: "viking://user/default/memories/preferences/theme.md",level: 2,- score: 0.88,- category: "",+ score: 0.91,+ category: "preferences",match_reason: "",relations: [],- abstract: "Trace design note",+ abstract: "User prefers dark theme",overview: null,},- ] : [],- skills: body.context_type === "skill" ? [makeMemory({- uri: "viking://user/skills/trace-skill",- abstract: "Trace skill",- score: 0.75,- })] : [],+ ],+ resources: [],+ skills: [],total: 1,});}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);- const { tools, api } = setupPlugin(undefined, { traceRecall: true });+ const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);- await tools.get("ov_search")!.execute("tc-search", { query: "trace design" });-- const result = await tools.get("ov_recall_trace")!.execute("tc-trace", {- source: "ov_search",- limit: 10,+ const search = tools.get("ov_search")!;+ const result = await search.execute("tc1", {+ query: "theme",+ uri: "viking://user/default/memories",}) as ToolResult;- expect(result.content[0]!.text).toContain("ov_search");- expect(result.content[0]!.text).toContain("trace design");- 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");+ expect(result.details.memories).toHaveLength(1);+ expect(result.content[0]!.text).toContain("memory");+ expect(result.content[0]!.text).toContain("User prefers dark theme");});- it("includes selected trace content only when includeContent is requested", async () => {- const fetchMock = vi.fn(async (url: string) => {- const requestUrl = new URL(url);- if (requestUrl.pathname === "/api/v1/search/find") {- return okResponse({- memories: [],- resources: [makeMemory({- uri: "viking://resources/project/spec.md",- abstract: "Recall trace design spec",- score: 0.88,- })],- skills: [],- total: 1,- });- }- if (requestUrl.pathname === "/api/v1/content/read") {- expect(requestUrl.searchParams.get("uri")).toBe("viking://resources/project/spec.md");- return okResponse("Full trace content with operational details");+ it("reads an OpenViking URI through ov_read instead of filesystem semantics", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {+ if (url.includes("/api/v1/content/read")) {+ expect(url).toContain(encodeURIComponent("viking://resources/openviking-readme/README.md#chunk-1"));+ return okResponse("# README\nOpenViking install guide");}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);- const { tools, factoryTools, commands, api } = setupPlugin(undefined, { traceRecall: true });- contextEnginePlugin.register(api as any);- await tools.get("ov_search")!.execute("tc-search", { query: "trace design", uri: "viking://resources" });-- const traceTool = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });- const result = await traceTool.execute("tc-trace", { source: "ov_search", includeContent: true }) as ToolResult;- const entry = (result.details.entries as any[])[0];- expect(entry.selected[0].contentPreview).toContain("Full trace content");-- await commands.get("ov-recall-trace")!.handler({- args: "--source ov_search --include-content",- commandBody: "",- sessionId: "test-session",- });- expect(fetchMock.mock.calls.filter(([calledUrl]) => String(calledUrl).includes("/api/v1/content/read")).length).toBeGreaterThanOrEqual(2);- });-- it("queries recorded traces from memory without calling OpenViking find again", async () => {- const fetchMock = vi.fn(async (url: string) => {- const requestUrl = new URL(url);- if (requestUrl.pathname === "/api/v1/search/find") {- return okResponse({- memories: [],- resources: [makeMemory({- uri: "viking://resources/project/spec.md",- abstract: "Recall trace design spec",- score: 0.88,- })],- skills: [],- total: 1,- });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { tools, factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);- await tools.get("ov_search")!.execute("tc-search", {- query: "trace design",- uri: "viking://resources",- limit: 3,- });-- fetchMock.mockClear();- const traceTool = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });- const result = await traceTool.execute("tc-trace", {- source: "ov_search",- limit: 10,+ const read = tools.get("ov_read")!;+ const result = await read.execute("tc1", {+ uri: "viking://resources/openviking-readme/README.md#chunk-1",}) as ToolResult;- expect(result.content[0]!.text).toContain("ov_search");- expect(result.content[0]!.text).toContain("trace design");- expect(result.content[0]!.text).toContain("viking://resources/project/spec.md");- expect(result.details.count).toBe(1);- expect(fetchMock.mock.calls.some(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))).toBe(false);- });-- it("bounds stored trace query text by traceRecallQueryMaxChars", async () => {- const fetchMock = vi.fn(async (url: string) => {- const requestUrl = new URL(url);- if (requestUrl.pathname === "/api/v1/search/find") {- return okResponse({ memories: [], resources: [], skills: [], total: 0 });- }- return okResponse({});- });- vi.stubGlobal("fetch", fetchMock);-- const { tools, factoryTools, api } = setupPlugin(undefined, {- traceRecall: true,- traceRecallQueryMaxChars: 200,- });- contextEnginePlugin.register(api as any);- await tools.get("ov_search")!.execute("tc-search-long-query", {- query: "q".repeat(500),- uri: "viking://resources",- });-- const trace = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });- const result = await trace.execute("tc-trace", { source: "ov_search", limit: 10 }) as ToolResult;- const entry = (result.details.entries as any[])[0];-- expect(entry.trigger.query).toHaveLength(200);- expect(entry.trigger.queryTruncated).toBe(true);+ expect(result.content[0]!.text).toContain("--- START OF viking://resources/openviking-readme/README.md#chunk-1 ---");+ expect(result.content[0]!.text).toContain("# README");+ expect(result.content[0]!.text).toContain("--- END OF viking://resources/openviking-readme/README.md#chunk-1 ---");+ expect(result.details.action).toBe("read");+ expect(result.details.uri).toBe("viking://resources/openviking-readme/README.md#chunk-1");});- it("records explicit memory_recall traces without duplicate default target searches", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ it("reads multiple OpenViking URIs and preserves per-URI failures", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {const requestUrl = new URL(url);- if (requestUrl.pathname === "/api/v1/system/status") {- return okResponse({ user: "default" });- }- if (requestUrl.pathname === "/api/v1/search/find") {- const body = JSON.parse(String(init?.body ?? "{}"));- expect(body.context_type).toBe("memory");- expect(body.target_uri).toBeUndefined();- return okResponse({- memories: [makeMemory({- uri: "viking://user/default/memories/backend-pref",- abstract: "Backend preference",- score: 0.91,- })],- resources: [],- skills: [],- total: 1,- });- }if (requestUrl.pathname === "/api/v1/content/read") {- return okResponse("Full backend memory content");+ const uri = requestUrl.searchParams.get("uri");+ if (uri === "viking://resources/guide/missing.md") {+ return new Response(JSON.stringify({ status: "error", message: "not found" }), {+ status: 404,+ headers: { "Content-Type": "application/json" },+ });+ }+ return okResponse(`content for ${uri}`);}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);- const { factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);- const recall = factoryTools.get("memory_recall")!({ sessionId: "test-session", agentId: "main" });- await recall.execute("tc-recall", { query: "backend preference", limit: 1, scoreThreshold: 0.2 });-- const findBodies = fetchMock.mock.calls- .filter(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))- .map(([, fetchInit]) => JSON.parse(String((fetchInit as RequestInit).body)));- expect(findBodies).toHaveLength(1);- expect(findBodies[0]).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;- expect(result.content[0]!.text).toContain("memory_recall");- expect(result.content[0]!.text).toContain("backend preference");+ const multiRead = tools.get("ov_multi_read")!;+ const result = await multiRead.execute("tc-ov-multi-read", {+ uris: [+ "viking://resources/guide/.overview.md",+ "viking://resources/guide/missing.md",+ ],+ }) as ToolResult;- const entry = (result.details.entries as any[])[0];- expect(entry.resourceTypes).toEqual(["user", "agent"]);- 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",- injected: true,- }),- ]));+ expect(result.content[0]!.text).toContain("Multi-read results for 2 OpenViking resources");+ expect(result.content[0]!.text).toContain("--- START OF viking://resources/guide/.overview.md ---");+ expect(result.content[0]!.text).toContain("content for viking://resources/guide/.overview.md");+ expect(result.content[0]!.text).toContain("--- START OF viking://resources/guide/missing.md ---");+ expect(result.content[0]!.text).toContain("ERROR:");+ expect(result.details).toMatchObject({+ action: "multi_read",+ count: 2,+ success_count: 1,+ });});- it("records archive search traces with displayed archive matches", async () => {- const fetchMock = vi.fn(async (url: string) => {+ it("lists an OpenViking directory through the fs ls endpoint", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {const requestUrl = new URL(url);- if (requestUrl.pathname === "/api/v1/search/grep") {- return okResponse({- matches: [{- line: 12,- uri: "viking://user/sessions/test-session/history/archive_001#L12",- content: "discussion about recall traces",- }],- count: 1,- });+ if (requestUrl.pathname === "/api/v1/fs/ls") {+ expect(requestUrl.searchParams.get("uri")).toBe("viking://resources/guide");+ expect(requestUrl.searchParams.get("recursive")).toBe("true");+ expect(requestUrl.searchParams.get("simple")).toBe("false");+ expect(requestUrl.searchParams.get("node_limit")).toBe("5");+ return okResponse([+ {+ name: ".overview.md",+ uri: "viking://resources/guide/.overview.md",+ isDir: false,+ abstract: "Guide overview",+ },+ {+ name: "step-2.md",+ uri: "viking://resources/guide/step-2.md",+ isDir: false,+ abstract: "Second step",+ },+ ]);}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);- const { factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);- const archiveSearch = factoryTools.get("ov_archive_search")!({ sessionId: "test-session", agentId: "main" });- await archiveSearch.execute("tc-archive", { query: "recall traces" });-- const trace = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });- const result = await trace.execute("tc-trace", { source: "ov_archive_search", limit: 10 }) as ToolResult;+ const list = tools.get("ov_list")!;+ const result = await list.execute("tc-ov-list", {+ uri: "viking://resources/guide",+ recursive: true,+ limit: 5,+ }) as ToolResult;- expect(result.content[0]!.text).toContain("ov_archive_search");- expect(result.content[0]!.text).toContain("recall traces");- expect(result.content[0]!.text).toContain("archive_001");- const entry = (result.details.entries as any[])[0];- expect(entry.operationType).toBe("archive_grep");- expect(entry.trigger.derivedKeywords).toEqual(["recall traces"]);- expect(entry.searches[0]).toMatchObject({- targetUriResolved: "viking://user/sessions/test-session/history",- total: 1,- caseInsensitive: true,+ expect(result.content[0]!.text).toContain("Listed 2 OpenViking entries");+ expect(result.content[0]!.text).toContain("viking://resources/guide/.overview.md");+ expect(result.content[0]!.text).toContain("Second step");+ expect(result.details).toMatchObject({+ action: "listed",+ uri: "viking://resources/guide",+ recursive: true,+ simple: false,+ count: 2,});- expect(entry.searches[0].durationMs).toBeGreaterThanOrEqual(0);- expect(entry.selected).toEqual(expect.arrayContaining([- expect.objectContaining({- uri: "viking://user/sessions/test-session/history/archive_001#L12",- abstractPreview: "discussion about recall traces",- displayed: true,- }),- ]));});- 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" });- }- if (url.includes("/api/v1/fs/ls")) {- return okResponse([]);- }- if (url.endsWith("/api/v1/search/find")) {- return okResponse({ memories: [], resources: [], skills: [], total: 0 });+ it("passes simple list mode through to OpenViking", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/fs/ls") {+ expect(requestUrl.searchParams.get("simple")).toBe("true");+ return okResponse(["viking://resources/guide/step-1.md"]);}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);- const { factoryTools, api } = setupPlugin(undefined, { peer_role: "assistant" });+ const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);- const search = factoryTools.get("ov_search")!({- sessionId: "runtime-session",- agentId: "worker",- });-- await search.execute("tc-ov-search-peer", { query: "OpenViking install" }) as ToolResult;+ const list = tools.get("ov_list")!;+ const result = await list.execute("tc-ov-list-simple", {+ uri: "viking://resources/guide",+ simple: true,+ }) as ToolResult;- const findRequests = fetchMock.mock.calls- .filter((call) => String(call[0]).endsWith("/api/v1/search/find"))- .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");- }+ expect(result.content[0]!.text).toContain("viking://resources/guide/step-1.md");+ expect(result.details.simple).toBe(true);});- it("returns partial results when one default scope search fails", async () => {- const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {+ it("prints full URIs in ov_search rows so ov_read does not receive display-truncated paths", async () => {+ const longUri = "viking://resources/harness-paper/2._OpenCompass司南_面向大模型时代的罗盘全面开放与分布式的评测体系/2.3_解决思路.md";+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {if (url.endsWith("/api/v1/system/status")) {return okResponse({ user: "default" });}@@ -1729,19 +1157,19 @@ describe("Tool: ov_search (behavioral)", () => {}if (url.endsWith("/api/v1/search/find")) {const body = JSON.parse(String(init?.body ?? "{}"));- if (body.context_type === "resource") {+ if (body.target_uri === "viking://resources") {return okResponse({memories: [],resources: [{context_type: "resource",- uri: "viking://resources/openviking-readme/README.md",+ uri: longUri,level: 2,- score: 0.82,+ score: 0.92,category: "",match_reason: "",relations: [],- abstract: "OpenViking install guide",+ abstract: "OpenCompass evaluation details",overview: null,},],@@ -1749,283 +1177,810 @@ describe("Tool: ov_search (behavioral)", () => {total: 1,});}- throw new Error("skills search unavailable");+ return okResponse({ memories: [], resources: [], skills: [], total: 0 });}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const search = tools.get("ov_search")!;- const result = await search.execute("tc1", { query: "OpenViking install" }) as ToolResult;+ const result = await search.execute("tc-long-uri", { query: "OpenCompass" }) as ToolResult;- expect(result.details.resources).toHaveLength(1);- expect(result.details.skills).toHaveLength(0);- expect(result.content[0]!.text).toContain("resource");+ expect(result.content[0]!.text).toContain(longUri);+ expect(result.content[0]!.text).not.toContain("viking://resources/harness-paper/2._OpenCompass司南_面向大模型时代的罗盘全面开放与分布式...");});- it("renders memory hits when explicit uri returns memories", async () => {- const fetchMock = vi.fn(async (url: string) => {- if (url.endsWith("/api/v1/search/find")) {+ it("uses runtime ovSearchLimit and targetUri as ov_search defaults", async () => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/system/status") {+ return okResponse({ user: "default" });+ }+ if (requestUrl.pathname === "/api/v1/search/find") {return okResponse({- memories: [+ memories: [],+ resources: [{- context_type: "memory",- uri: "viking://user/default/memories/preferences/theme.md",+ context_type: "resource",+ uri: "viking://resources/runtime-default/doc.md",level: 2,- score: 0.91,- category: "preferences",+ score: 0.88,+ category: "",match_reason: "",relations: [],- abstract: "User prefers dark theme",+ abstract: "Runtime default search result",overview: null,},],- resources: [],skills: [],total: 1,});}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);- const { tools, api } = setupPlugin();+ const { factoryTools, commands, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);- const search = tools.get("ov_search")!;- const result = await search.execute("tc1", {- query: "theme",- uri: "viking://user/default/memories",- }) as ToolResult;-- expect(result.details.memories).toHaveLength(1);- expect(result.content[0]!.text).toContain("memory");- expect(result.content[0]!.text).toContain("User prefers dark theme");- });+ const command = commands.get("ov-query-config");+ expect(command).toBeDefined();+ await command!.handler({+ args: "set --scope session --ovSearchLimit 3 --targetUri viking://resources/runtime-default",+ commandBody: "",+ sessionId: "runtime-search-session",+ agentId: "main",+ });++ const search = factoryTools.get("ov_search")!({ sessionId: "runtime-search-session", agentId: "main" });+ const result = await search.execute("tc-runtime-ov-search", {+ query: "runtime default",+ }) as ToolResult;++ expect(result.details.resources).toHaveLength(1);+ const findCalls = openVikingTransport.mock.calls.filter(([calledUrl]) =>+ String(calledUrl).includes("/api/v1/search/find")+ );+ expect(findCalls).toHaveLength(1);+ const body = JSON.parse(String((findCalls[0]![1] as RequestInit).body));+ expect(body.target_uri).toBe("viking://resources/runtime-default");+ expect(body.limit).toBe(3);+ });++ it("rejects display-truncated ov_read URIs before calling OpenViking", async () => {+ const readMock = vi.fn().mockResolvedValue("content");+ const { tools, api } = setupPlugin({ read: readMock });+ contextEnginePlugin.register(api as any);+ const read = tools.get("ov_read")!;++ await expect(read.execute("tc-truncated-uri", {+ uri: "viking://resources/harness-paper/2._OpenCompass司南_面向大模型时代的罗盘全面开放与分布式的评测体系/2.3_解决思...",+ })).rejects.toThrow("truncated display URI");+ expect(readMock).not.toHaveBeenCalled();+ });+});++describe("OpenViking import command parsing", () => {+ it("tokenizes quoted args", () => {+ expect(tokenizeCommandArgs(`./README.md --reason "project docs" --wait`)).toEqual([+ "./README.md",+ "--reason",+ "project docs",+ "--wait",+ ]);+ });++ it("preserves Windows path backslashes in slash-command args", () => {+ expect(+ parseAddSkillCommandArgs(String.raw`C:\Users\alice\skill-dir --wait`),+ ).toMatchObject({+ source: String.raw`C:\Users\alice\skill-dir`,+ wait: true,+ });+ });++ it("parses add-resource flags", () => {+ expect(+ parseAddResourceCommandArgs(+ `./README.md --to viking://resources/readme --reason "project docs" --instruction='summarize APIs' --wait`,+ ),+ ).toMatchObject({+ source: "./README.md",+ to: "viking://resources/readme",+ reason: "project docs",+ instruction: "summarize APIs",+ wait: true,+ });+ });++ it("keeps unquoted space-containing import sources intact", () => {+ expect(+ parseAddResourceCommandArgs(+ `My Docs/README.md --to viking://resources/readme`,+ ),+ ).toMatchObject({+ source: "My Docs/README.md",+ to: "viking://resources/readme",+ });+ });++ it("rejects resource import with both to and parent", () => {+ expect(() =>+ parseAddResourceCommandArgs("./README.md --to viking://resources/a --parent viking://resources"),+ ).toThrow("Cannot specify both");+ });++ it("parses add-skill flags", () => {+ expect(parseAddSkillCommandArgs("./skills/demo --wait --timeout=30")).toMatchObject({+ source: "./skills/demo",+ wait: true,+ timeout: 30,+ });+ });++ it("rejects resource-only flags for skill imports", () => {+ expect(() =>+ parseAddSkillCommandArgs("./skills/demo --to viking://resources/nope"),+ ).toThrow("resource-only");+ });+});++describe("OpenViking ov_search command parsing", () => {+ it("parses ov_search query and flags", () => {+ expect(parseOVSearchCommandArgs(`"OpenViking install" --uri viking://resources --limit=3`)).toMatchObject({+ query: "OpenViking install",+ uri: "viking://resources",+ limit: 3,+ });+ });++ it("keeps multi-word unquoted slash-command queries intact", () => {+ expect(parseOVSearchCommandArgs(`OpenViking install --uri viking://resources`)).toMatchObject({+ query: "OpenViking install",+ uri: "viking://resources",+ });+ });});-describe("Tool: ov_read and ov_multi_read (behavioral)", () => {- it("reads full content for one exact OpenViking URI", async () => {- const fetchMock = vi.fn(async (url: string) => {+describe("Tool: ov_recall_trace", () => {+ it("registers recall trace query tool and slash command", () => {+ const { tools, commands, api } = setupPlugin(undefined, { traceRecall: true });+ contextEnginePlugin.register(api as any);++ const tool = tools.get("ov_recall_trace");+ expect(tool).toBeDefined();+ expect(tool!.description).toContain("recall trace");+ const props = (tool!.parameters as any).properties;+ expect(props).toHaveProperty("traceId");+ expect(props).toHaveProperty("sessionId");+ expect(props).toHaveProperty("source");+ expect(props).toHaveProperty("resourceTypes");+ expect(props).toHaveProperty("includeContent");+ expect(props).toHaveProperty("limit");++ expect(commands.get("ov-recall-trace")).toMatchObject({+ acceptsArgs: true,+ description: expect.stringContaining("recall trace"),+ });+ });++ it("includes selected content only when includeContent is requested", async () => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/search/find") {+ return okResponse({+ memories: [],+ resources: [makeMemory({+ uri: "viking://resources/project/spec.md",+ abstract: "Recall trace design spec",+ score: 0.88,+ })],+ skills: [],+ total: 1,+ });+ }if (requestUrl.pathname === "/api/v1/content/read") {- expect(requestUrl.searchParams.get("uri")).toBe("viking://resources/guide/step-1.md");- return okResponse("# Step 1\nDo the first thing.");+ expect(requestUrl.searchParams.get("uri")).toBe("viking://resources/project/spec.md");+ return okResponse("Full trace content with operational details");}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);-- const { tools, api } = setupPlugin();+ const { tools, factoryTools, commands, api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);- const read = tools.get("ov_read")!;- const result = await read.execute("tc-ov-read", {- uri: "viking://resources/guide/step-1.md",- }) as ToolResult;+ await tools.get("ov_search")!.execute("tc-search", { query: "trace design", uri: "viking://resources" });- expect(result.content[0]!.text).toContain("--- START OF viking://resources/guide/step-1.md ---");- expect(result.content[0]!.text).toContain("# Step 1");- expect(result.content[0]!.text).toContain("--- END OF viking://resources/guide/step-1.md ---");- expect(result.details).toMatchObject({- action: "read",- uri: "viking://resources/guide/step-1.md",- chars: 28,+ const traceTool = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });+ const result = await traceTool.execute("tc-trace", { source: "ov_search", includeContent: true }) as ToolResult;+ const entry = (result.details.entries as any[])[0];+ expect(entry.selected[0].contentPreview).toContain("Full trace content");++ await commands.get("ov-recall-trace")!.handler({+ args: "--source ov_search --include-content",+ commandBody: "",+ sessionId: "test-session",});+ expect(openVikingTransport.mock.calls.filter(([calledUrl]) => String(calledUrl).includes("/api/v1/content/read")).length).toBeGreaterThanOrEqual(2);});- it("reads multiple OpenViking URIs and preserves per-URI failures", async () => {- const fetchMock = vi.fn(async (url: string) => {+ it("registers recall trace gateway route when a route adapter is available", async () => {+ const { api } = setupPlugin(undefined, { traceRecall: true });+ contextEnginePlugin.register(api as any);+ const service = (api.registerService as any).mock.calls[0][0];+ const registerRoute = vi.fn();++ await service.start({ registerRoute });++ expect(registerRoute).toHaveBeenCalledWith(expect.objectContaining({+ method: "GET",+ path: "/api/openviking/recall-traces",+ }));+ expect(registerRoute).toHaveBeenCalledWith(expect.objectContaining({+ method: "GET",+ path: "/api/openviking/recall-traces/:traceId",+ }));+ expect(registerRoute).toHaveBeenCalledWith(expect.objectContaining({+ method: "GET",+ path: "/api/openviking/uri-detail",+ }));+ expect(registerRoute).toHaveBeenCalledWith(expect.objectContaining({+ method: "GET",+ path: "/api/openviking/recall-traces/latest-ov-search-list",+ }));+ });++ it("registers recall trace HTTP routes through the OpenClaw plugin API", () => {+ const { api } = setupPlugin(undefined, { traceRecall: true });++ contextEnginePlugin.register(api as any);++ expect(api.registerHttpRoute).toHaveBeenCalledWith(expect.objectContaining({+ path: "/api/openviking/recall-traces",+ auth: "plugin",+ match: "exact",+ }));+ expect(api.registerHttpRoute).toHaveBeenCalledWith(expect.objectContaining({+ path: "/api/openviking/recall-traces",+ auth: "plugin",+ match: "prefix",+ }));+ expect(api.registerHttpRoute).toHaveBeenCalledWith(expect.objectContaining({+ path: "/api/openviking/uri-detail",+ auth: "plugin",+ match: "exact",+ }));+ expect(api.registerHttpRoute).toHaveBeenCalledWith(expect.objectContaining({+ path: "/api/openviking/recall-traces/latest-ov-search-list",+ auth: "plugin",+ match: "exact",+ }));+ });++ it("serves URI detail through the gateway route without rerunning search", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {const requestUrl = new URL(url);if (requestUrl.pathname === "/api/v1/content/read") {- const uri = requestUrl.searchParams.get("uri");- if (uri === "viking://resources/guide/missing.md") {- return new Response(JSON.stringify({ status: "error", message: "not found" }), {- status: 404,- headers: { "Content-Type": "application/json" },+ expect(requestUrl.searchParams.get("uri")).toBe("viking://resources/project/spec.md");+ return okResponse("0123456789abcdefghijklmnopqrstuvwxyz");+ }+ if (requestUrl.pathname === "/api/v1/search/find") {+ throw new Error("uri detail must not call find");+ }+ return okResponse({});+ });++ const { api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);+ const service = (api.registerService as any).mock.calls[0][0];+ const routes = new Map<string, any>();+ await service.start({ registerRoute: (route: any) => routes.set(route.path, route) });++ const response = await routes.get("/api/openviking/uri-detail")!.handler({+ query: {+ uri: "viking://resources/project/spec.md",+ includeContent: "true",+ offset: "10",+ contentLimit: "5",+ agentId: "main",+ },+ }) as { status: number; body: any };++ expect(response.status).toBe(200);+ expect(response.body.ok).toBe(true);+ expect(response.body.uriType).toBe("resource");+ expect(response.body.content.text).toBe("abcde");+ expect(response.body.content.hasMore).toBe(true);+ expect(openVikingTransport.mock.calls.filter(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))).toHaveLength(0);+ });++ it("serves latest ov_search simplified list from trace data", async () => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/search/find") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ if (body.target_uri === "viking://resources") {+ return okResponse({+ memories: [],+ resources: [makeMemory({+ uri: "viking://resources/project/spec.md",+ abstract: "Project spec abstract",+ score: 0.91,+ })],+ skills: [],+ total: 1,});}- return okResponse(`content for ${uri}`);+ return okResponse({+ memories: [],+ resources: [],+ skills: [makeMemory({+ uri: "viking://user/skills/debugger",+ abstract: "Debugger skill",+ score: 0.83,+ })],+ total: 1,+ });}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);- const { tools, api } = setupPlugin();+ const { factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);- const multiRead = tools.get("ov_multi_read")!;- const result = await multiRead.execute("tc-ov-multi-read", {- uris: [- "viking://resources/guide/.overview.md",- "viking://resources/guide/missing.md",- ],+ const searchTool = factoryTools.get("ov_search")!({ sessionId: "route-session", agentId: "main" });+ await searchTool.execute("tc-route-search", { query: "project spec", limit: 3 });++ const service = (api.registerService as any).mock.calls[0][0];+ const routes = new Map<string, any>();+ await service.start({ registerRoute: (route: any) => routes.set(route.path, route) });++ const response = await routes.get("/api/openviking/recall-traces/latest-ov-search-list")!.handler({+ query: {+ sessionId: "route-session",+ limit: "5",+ includeSkills: "false",+ },+ }) as { status: number; body: any };++ expect(response.status).toBe(200);+ expect(response.body.ok).toBe(true);+ expect(response.body.trace.triggerQuery).toBe("project spec");+ expect(response.body.items).toHaveLength(1);+ expect(response.body.items[0]).toMatchObject({+ uri: "viking://resources/project/spec.md",+ abstractPreview: "Project spec abstract",+ resultType: "resource",+ source: "selected",+ targetUri: "viking://resources",+ });+ expect(response.body.items[0].detailUrl).toContain("/api/openviking/uri-detail?uri=viking%3A%2F%2Fresources%2Fproject%2Fspec.md");+ expect(response.body.items.some((item: any) => item.resultType === "skill")).toBe(false);+ });++ it("filters recall trace gateway route by sessionKey aliases", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/search/find") {+ return okResponse({+ memories: [],+ resources: [makeMemory({+ uri: "viking://resources/project/session-key-spec.md",+ abstract: "Session key specific result",+ score: 0.9,+ })],+ skills: [],+ total: 1,+ });+ }+ return okResponse({});+ });++ const { factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);+ const searchTool = factoryTools.get("ov_search")!({+ sessionId: "route-session-by-key",+ sessionKey: "agent:main:route-session-by-key",+ agentId: "main",+ });+ await searchTool.execute("tc-route-search", { query: "session key route", limit: 3 });++ const otherSearchTool = factoryTools.get("ov_search")!({+ sessionId: "route-session-other-key",+ sessionKey: "agent:main:route-session-other-key",+ agentId: "main",+ });+ await otherSearchTool.execute("tc-route-search-other", { query: "other route", limit: 3 });++ const service = (api.registerService as any).mock.calls[0][0];+ const routes = new Map<string, any>();+ await service.start({ registerRoute: (route: any) => routes.set(route.path, route) });++ const response = await routes.get("/api/openviking/recall-traces")!.handler({+ query: {+ sessionkey: "agent:main:route-session-by-key",+ turn: "all",+ limit: "5",+ },+ }) as { status: number; body: any };++ expect(response.status).toBe(200);+ expect(response.body.entries).toHaveLength(1);+ expect(response.body.entries[0]).toMatchObject({+ source: "ov_search",+ sessionKey: "agent:main:route-session-by-key",+ });+ });++ it("does not combine explicit trace sessionKey filter with derived ovSessionId", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/search/find") {+ return okResponse({+ memories: [],+ resources: [makeMemory({+ uri: "viking://resources/project/session-key-history.md",+ abstract: "Session key history result",+ score: 0.9,+ })],+ skills: [],+ total: 1,+ });+ }+ return okResponse({});+ });++ const { factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);+ const sessionKey = "agent:main:historic-session-key";+ const searchTool = factoryTools.get("ov_search")!({+ sessionId: "11111111-1111-4111-8111-111111111111",+ sessionKey,+ agentId: "main",+ });+ await searchTool.execute("tc-route-search", { query: "historical route", limit: 3 });++ const traceTool = factoryTools.get("ov_recall_trace")!({+ sessionKey,+ agentId: "main",+ });+ const result = await traceTool.execute("tc-trace", {+ turn: "all",+ sessionKey,+ limit: 5,}) as ToolResult;- expect(result.content[0]!.text).toContain("Multi-read results for 2 OpenViking resources");- expect(result.content[0]!.text).toContain("--- START OF viking://resources/guide/.overview.md ---");- expect(result.content[0]!.text).toContain("content for viking://resources/guide/.overview.md");- expect(result.content[0]!.text).toContain("--- START OF viking://resources/guide/missing.md ---");- expect(result.content[0]!.text).toContain("ERROR:");- expect(result.details).toMatchObject({- action: "multi_read",- count: 2,- success_count: 1,+ expect(result.details.count).toBe(1);+ expect((result.details.entries as any[])[0]).toMatchObject({+ sessionKey,+ ovSessionId: "11111111-1111-4111-8111-111111111111",+ trigger: { query: "historical route" },+ });+ });++ it("uses outer sessionKey as the default trace identity without derived ovSessionId", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/search/find") {+ return okResponse({+ memories: [],+ resources: [makeMemory({+ uri: "viking://resources/project/web-session-history.md",+ abstract: "Web session history result",+ score: 0.9,+ })],+ skills: [],+ total: 1,+ });+ }+ return okResponse({});+ });++ const { factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);+ const sessionKey = "agent:main:web-c6592a8e-5448-4622-9e7f-31a07447eee7";+ const searchTool = factoryTools.get("ov_search")!({+ sessionId: "22222222-2222-4222-8222-222222222222",+ sessionKey,+ agentId: "main",+ });+ await searchTool.execute("tc-route-search", { query: "web session route", limit: 3 });++ const traceTool = factoryTools.get("ov_recall_trace")!({+ sessionKey,+ agentId: "main",+ });+ const result = await traceTool.execute("tc-trace", {+ turn: "all",+ limit: 5,+ }) as ToolResult;++ expect(result.details.count).toBe(1);+ expect((result.details.entries as any[])[0]).toMatchObject({+ sessionKey,+ ovSessionId: "22222222-2222-4222-8222-222222222222",+ trigger: { query: "web session route" },+ });+ });++ it("falls back to derived ovSessionId for legacy traces missing sessionKey", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/search/find") {+ return okResponse({+ memories: [],+ resources: [makeMemory({+ uri: "viking://resources/project/legacy-trace.md",+ abstract: "Legacy trace result",+ score: 0.9,+ })],+ skills: [],+ total: 1,+ });+ }+ return okResponse({});+ });++ const { factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);+ const sessionKey = "agent:main:legacy-session-key-only";+ const ovSessionId = openClawSessionToOvStorageId(undefined, sessionKey);+ const searchTool = factoryTools.get("ov_search")!({+ ovSessionId,+ agentId: "main",+ });+ await searchTool.execute("tc-legacy-search", { query: "legacy route", limit: 3 });++ const traceTool = factoryTools.get("ov_recall_trace")!({+ sessionKey,+ agentId: "main",+ });+ const result = await traceTool.execute("tc-trace", {+ turn: "all",+ limit: 5,+ }) as ToolResult;++ expect(result.details.count).toBe(1);+ expect((result.details.entries as any[])[0]).toMatchObject({+ ovSessionId,+ trigger: { query: "legacy route" },});+ expect((result.details.entries as any[])[0].sessionKey).toBeUndefined();+ });++ it("queries recorded traces from memory without calling OpenViking find", async () => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/search/find") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ if (body.target_uri === "viking://resources") {+ return okResponse({+ memories: [],+ resources: [makeMemory({+ uri: "viking://resources/project/spec.md",+ abstract: "Recall trace design spec",+ score: 0.88,+ })],+ skills: [],+ total: 1,+ });+ }+ return okResponse({ memories: [], resources: [], skills: [], total: 0 });+ }+ return okResponse({});+ });++ const { tools, factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);++ await tools.get("ov_search")!.execute("tc-search", {+ query: "trace design",+ uri: "viking://resources",+ limit: 3,+ });++ openVikingTransport.mockClear();+ const traceTool = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });+ const result = await traceTool.execute("tc-trace", {+ source: "ov_search",+ limit: 10,+ }) as ToolResult;++ expect(result.content[0]!.text).toContain("ov_search");+ expect(result.content[0]!.text).toContain("trace design");+ expect(result.content[0]!.text).toContain("viking://resources/project/spec.md");+ expect(result.details.count).toBe(1);+ expect(openVikingTransport.mock.calls.some(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))).toBe(false);});-});-describe("Tool: ov_list (behavioral)", () => {- it("lists an OpenViking directory through the fs ls endpoint", async () => {- const fetchMock = vi.fn(async (url: string) => {+ it("bounds stored trace query text by traceRecallQueryMaxChars", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {const requestUrl = new URL(url);- if (requestUrl.pathname === "/api/v1/fs/ls") {- expect(requestUrl.searchParams.get("uri")).toBe("viking://resources/guide");- expect(requestUrl.searchParams.get("recursive")).toBe("true");- expect(requestUrl.searchParams.get("simple")).toBe("false");- expect(requestUrl.searchParams.get("node_limit")).toBe("5");- return okResponse([- {- name: ".overview.md",- uri: "viking://resources/guide/.overview.md",- isDir: false,- abstract: "Guide overview",- },- {- name: "step-2.md",- uri: "viking://resources/guide/step-2.md",- isDir: false,- abstract: "Second step",- },- ]);+ if (requestUrl.pathname === "/api/v1/search/find") {+ return okResponse({ memories: [], resources: [], skills: [], total: 0 });}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);- const { tools, api } = setupPlugin();+ const { tools, factoryTools, api } = setupPlugin(undefined, {+ traceRecall: true,+ traceRecallQueryMaxChars: 200,+ });+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);- const list = tools.get("ov_list")!;- const result = await list.execute("tc-ov-list", {- uri: "viking://resources/guide",- recursive: true,- limit: 5,- }) as ToolResult;- expect(result.content[0]!.text).toContain("Listed 2 OpenViking entries");- expect(result.content[0]!.text).toContain("viking://resources/guide/.overview.md");- expect(result.content[0]!.text).toContain("Second step");- expect(result.details).toMatchObject({- action: "listed",- uri: "viking://resources/guide",- recursive: true,- simple: false,- count: 2,+ await tools.get("ov_search")!.execute("tc-search-long-query", {+ query: "q".repeat(500),+ uri: "viking://resources",});++ const trace = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });+ const result = await trace.execute("tc-trace", { source: "ov_search", limit: 10 }) as ToolResult;+ const entry = (result.details.entries as any[])[0];++ expect(entry.trigger.query).toHaveLength(200);+ expect(entry.trigger.queryTruncated).toBe(true);});- it("passes simple list mode through to OpenViking", async () => {- const fetchMock = vi.fn(async (url: string) => {+ it("records explicit memory_recall traces with selected injected memories", async () => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {const requestUrl = new URL(url);- if (requestUrl.pathname === "/api/v1/fs/ls") {- expect(requestUrl.searchParams.get("simple")).toBe("true");- return okResponse(["viking://resources/guide/step-1.md"]);+ if (requestUrl.pathname === "/api/v1/system/status") {+ return okResponse({ user: "default" });+ }+ if (requestUrl.pathname === "/api/v1/search/find") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ const memories = String(body.context_type ?? "") === "memory"+ ? [makeMemory({ uri: "viking://user/default/memories/high", abstract: "Backend preference", score: 0.91 })]+ : [];+ return okResponse({ memories, resources: [], skills: [], total: memories.length });+ }+ if (requestUrl.pathname === "/api/v1/content/read") {+ return okResponse("Full backend memory content");}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);- const { tools, api } = setupPlugin();+ const { factoryTools, api } = setupPlugin(undefined, {+ traceRecall: true,+ recallResources: false,+ recallTargetTypes: ["user"],+ });+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);- const list = tools.get("ov_list")!;- const result = await list.execute("tc-ov-list-simple", {- uri: "viking://resources/guide",- simple: true,- }) as ToolResult;+ const recall = factoryTools.get("memory_recall")!({ sessionId: "test-session", agentId: "main" });+ await recall.execute("tc-recall", { query: "backend preference", limit: 1, scoreThreshold: 0.2 });- expect(result.content[0]!.text).toContain("viking://resources/guide/step-1.md");- expect(result.details.simple).toBe(true);- });-});+ const trace = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });+ const result = await trace.execute("tc-trace", { source: "memory_recall", limit: 10 }) as ToolResult;-describe("OpenViking import command parsing", () => {- it("tokenizes quoted args", () => {- expect(tokenizeCommandArgs(`./README.md --reason "project docs" --wait`)).toEqual([- "./README.md",- "--reason",- "project docs",- "--wait",- ]);+ expect(result.content[0]!.text).toContain("memory_recall");+ expect(result.content[0]!.text).toContain("backend preference");+ expect(result.content[0]!.text).toContain("viking://user/default/memories/high");+ const entry = (result.details.entries as any[])[0];+ expect(entry.selected).toEqual(expect.arrayContaining([+ expect.objectContaining({ uri: "viking://user/default/memories/high", injected: true }),+ ]));});- it("preserves Windows path backslashes in slash-command args", () => {- expect(- parseAddSkillCommandArgs(String.raw`C:\Users\alice\skill-dir --wait`),- ).toMatchObject({- source: String.raw`C:\Users\alice\skill-dir`,- wait: true,+ it("defaults explicit memory_recall to backward-compatible user and agent memory recall", async () => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/search/find") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ const memories = String(body.context_type ?? "") === "memory"+ ? [makeMemory({ uri: "viking://user/default/memories/project-docs", abstract: "User memory docs", score: 0.9 })]+ : [];+ return okResponse({ memories, resources: [], skills: [], total: memories.length });+ }+ if (requestUrl.pathname === "/api/v1/content/read") {+ return okResponse("Full resource content");+ }+ return okResponse({});});++ const { factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);+ const recall = factoryTools.get("memory_recall")!({ sessionId: "test-session", agentId: "main" });+ await recall.execute("tc-recall-resource", { query: "project docs", limit: 1, scoreThreshold: 0.2 });++ const findBodies = openVikingTransport.mock.calls+ .filter(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))+ .map(([, init]) => JSON.parse(String((init as RequestInit).body)));+ 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;+ const entry = (result.details.entries as any[])[0];+ expect(entry.resourceTypes).toEqual(["user"]);+ expect(entry.searches.map((search: any) => search.resourceType)).toEqual(["user"]);+ expect(entry.searches[0].targetUriResolved).toBeUndefined();});- it("parses add-resource flags", () => {- expect(- parseAddResourceCommandArgs(- `./README.md --to viking://resources/readme --reason "project docs" --instruction='summarize APIs' --wait`,- ),- ).toMatchObject({- source: "./README.md",- to: "viking://resources/readme",- reason: "project docs",- instruction: "summarize APIs",- wait: true,+ it("allows explicit memory_recall resourceTypes to opt into user recall", async () => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/search/find") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ const memories = String(body.context_type ?? "") === "memory"+ ? [makeMemory({ uri: "viking://user/default/memories/preference", abstract: "User preference", score: 0.9 })]+ : [];+ return okResponse({ memories, resources: [], skills: [], total: memories.length });+ }+ if (requestUrl.pathname === "/api/v1/content/read") {+ return okResponse("Full user preference content");+ }+ return okResponse({});});- });- it("keeps unquoted space-containing import sources intact", () => {- expect(- parseAddResourceCommandArgs(- `My Docs/README.md --to viking://resources/readme`,- ),- ).toMatchObject({- source: "My Docs/README.md",- to: "viking://resources/readme",+ const { factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);+ const recall = factoryTools.get("memory_recall")!({ sessionId: "test-session", agentId: "main" });+ await recall.execute("tc-recall-user", {+ query: "user preference",+ limit: 1,+ scoreThreshold: 0.2,+ resourceTypes: ["user"],});- });- it("rejects resource import with both to and parent", () => {- expect(() =>- parseAddResourceCommandArgs("./README.md --to viking://resources/a --parent viking://resources"),- ).toThrow("Cannot specify both");+ const findBodies = openVikingTransport.mock.calls+ .filter(([calledUrl]) => String(calledUrl).includes("/api/v1/search/find"))+ .map(([, init]) => JSON.parse(String((init as RequestInit).body)));+ 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;+ const entry = (result.details.entries as any[])[0];+ expect(entry.resourceTypes).toEqual(["user"]);+ expect(entry.searches[0]).toMatchObject({ resourceType: "user" });+ expect(entry.searches[0].targetUriResolved).toBeUndefined();});- it("parses add-skill flags", () => {- expect(parseAddSkillCommandArgs("./skills/demo --wait --timeout=30")).toMatchObject({- source: "./skills/demo",- wait: true,- timeout: 30,+ it("records archive search traces with displayed archive matches", async () => {+ const openVikingTransport = vi.fn(async (url: string) => {+ const requestUrl = new URL(url);+ if (requestUrl.pathname === "/api/v1/search/grep") {+ return okResponse({+ matches: [{+ line: 12,+ uri: "viking://session/test-session/history/archive_001#L12",+ content: "discussion about recall traces",+ }],+ count: 1,+ });+ }+ return okResponse({});});- });- it("rejects resource-only flags for skill imports", () => {- expect(() =>- parseAddSkillCommandArgs("./skills/demo --to viking://resources/nope"),- ).toThrow("resource-only");- });-});+ const { factoryTools, api } = setupPlugin(undefined, { traceRecall: true });+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);+ const archiveSearch = factoryTools.get("ov_archive_search")!({ sessionId: "test-session", agentId: "main" });+ await archiveSearch.execute("tc-archive", { query: "recall traces" });-describe("OpenViking ov_search command parsing", () => {- it("parses ov_search query and flags", () => {- expect(parseOVSearchCommandArgs(`"OpenViking install" --uri viking://resources --limit=3`)).toMatchObject({- query: "OpenViking install",- uri: "viking://resources",- limit: 3,- });- });+ const trace = factoryTools.get("ov_recall_trace")!({ sessionId: "test-session" });+ const result = await trace.execute("tc-trace", { source: "ov_archive_search", limit: 10 }) as ToolResult;- it("keeps multi-word unquoted slash-command queries intact", () => {- expect(parseOVSearchCommandArgs(`OpenViking install --uri viking://resources`)).toMatchObject({- query: "OpenViking install",- uri: "viking://resources",- });+ expect(result.content[0]!.text).toContain("ov_archive_search");+ expect(result.content[0]!.text).toContain("recall traces");+ expect(result.content[0]!.text).toContain("archive_001");+ const entry = (result.details.entries as any[])[0];+ expect(entry.operationType).toBe("archive_grep");+ expect(entry.selected).toEqual(expect.arrayContaining([+ expect.objectContaining({ uri: "viking://session/test-session/history/archive_001#L12", displayed: true }),+ ]));});});@@ -2036,10 +1991,36 @@ describe("Plugin registration", () => {expect(api.registerTool).toHaveBeenCalledTimes(14);});- it("registers all 15 tools when add_resource is explicitly enabled", () => {- const { api } = setupPlugin(undefined, { enableAddResourceTool: true });+ it("registers only resource query tools when enabledTools is resource_query", () => {+ const { tools, api } = setupPlugin(undefined, { enabledTools: ["resource_query"] });+ contextEnginePlugin.register(api as any);+ expect(api.registerTool).toHaveBeenCalledTimes(4);+ expect([...tools.keys()].sort()).toEqual(["ov_list", "ov_multi_read", "ov_read", "ov_search"]);+ });++ it("does not register memory tools when disabledTools includes memory group", () => {+ const { tools, api } = setupPlugin(undefined, { disabledTools: ["memory"] });+ contextEnginePlugin.register(api as any);+ expect(tools.get("ov_search")).toBeDefined();+ expect(tools.get("ov_read")).toBeDefined();+ expect(tools.get("memory_recall")).toBeUndefined();+ expect(tools.get("memory_store")).toBeUndefined();+ expect(tools.get("memory_forget")).toBeUndefined();+ });++ it("keeps add_resource opt-in even when all tools are enabled", () => {+ const { tools, api } = setupPlugin(undefined, { enabledTools: ["all"] });+ contextEnginePlugin.register(api as any);+ expect(tools.get("add_resource")).toBeUndefined();+ });++ it("registers add_resource only when both selected and explicitly enabled", () => {+ const { tools, api } = setupPlugin(undefined, {+ enabledTools: ["add_resource"],+ enableAddResourceTool: true,+ });contextEnginePlugin.register(api as any);- expect(api.registerTool).toHaveBeenCalledTimes(15);+ expect([...tools.keys()]).toEqual(["add_resource"]);});it("registers add and search commands", () => {@@ -2057,10 +2038,6 @@ describe("Plugin registration", () => {acceptsArgs: true,description: "Search OpenViking resources and skills.",});- expect(commands.get("ov-recall-trace")).toMatchObject({- acceptsArgs: true,- description: "Query OpenViking recall trace records.",- });});it("add and search commands return usage errors when args are missing", async () => {@@ -2083,16 +2060,41 @@ describe("Plugin registration", () => {expect(search.text).toContain("Usage: /ov-search");});+ it("search command propagates agent identity when command ctx includes it", async () => {+ const openVikingTransport = vi.fn(async (url: string, init?: RequestInit) => {+ if (url.endsWith("/api/v1/search/find")) {+ return okResponse({ memories: [], resources: [], skills: [], total: 0 });+ }+ return okResponse({});+ });++ const { commands, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;+ contextEnginePlugin.register(api as any);++ await commands.get("ov-search")!.handler({+ args: "test query --uri viking://resources",+ commandBody: "/ov-search",+ agentId: "worker",+ sessionId: "session-1",+ sessionKey: "agent:worker:session-1",+ });++ const [, init] = openVikingTransport.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/search/find")) as [string, RequestInit];+ const headers = new Headers(init.headers);+ expect(headers.get("X-OpenViking-Actor-Peer")).toBe("worker");+ });+it("search command propagates configured tenant headers", async () => {- const fetchMock = vi.fn(async (url: string) => {+ const openVikingTransport = vi.fn(async (url: string) => {if (url.endsWith("/api/v1/search/find")) {return okResponse({ memories: [], resources: [], skills: [], total: 0 });}return okResponse({});});- vi.stubGlobal("fetch", fetchMock);const { commands, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;api.pluginConfig = {...api.pluginConfig,accountId: "acct-shared",@@ -2108,19 +2110,20 @@ describe("Plugin registration", () => {sessionKey: "agent:worker:session-1",});- const [, init] = fetchMock.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/search/find")) as [string, RequestInit];+ const [, init] = openVikingTransport.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/search/find")) as [string, RequestInit];const headers = new Headers(init.headers);expect(headers.get("X-OpenViking-Account")).toBe("acct-shared");expect(headers.get("X-OpenViking-User")).toBe("alice");+ expect(headers.get("X-OpenViking-Actor-Peer")).toBe("worker");});it("add_resource propagates configured tenant headers", async () => {- const fetchMock = vi.fn(async () =>+ const openVikingTransport = vi.fn(async () =>okResponse({ root_uri: "viking://resources/shared-docs", status: "success" }),);- vi.stubGlobal("fetch", fetchMock);const { tools, api } = setupPlugin(undefined, { enableAddResourceTool: true });+ (api as any).openVikingTransport = openVikingTransport;api.pluginConfig = {...api.pluginConfig,accountId: "acct-shared",@@ -2135,7 +2138,7 @@ describe("Plugin registration", () => {wait: true,});- const [, init] = fetchMock.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/resources")) as [string, RequestInit];+ const [, init] = openVikingTransport.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/resources")) as [string, RequestInit];const headers = new Headers(init.headers);expect(headers.get("X-OpenViking-Account")).toBe("acct-shared");expect(headers.get("X-OpenViking-User")).toBe("alice");@@ -2146,14 +2149,14 @@ describe("Plugin registration", () => {const filePath = join(tempDir, "大秦-TOP20.xlsx");await writeFile(filePath, "spreadsheet bytes");- const fetchMock = vi+ const openVikingTransport = vi.fn().mockResolvedValueOnce(okResponse({ temp_file_id: "upload_sheet.xlsx" })).mockResolvedValueOnce(okResponse({ root_uri: "viking://resources/sheet", status: "success" }));- vi.stubGlobal("fetch", fetchMock);try {const { tools, api } = setupPlugin(undefined, { enableAddResourceTool: true });+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const tool = tools.get("add_resource")!;@@ -2163,9 +2166,9 @@ describe("Plugin registration", () => {}) as ToolResult;expect(result.content[0]!.text).toContain("Imported OpenViking resource");- expect(fetchMock.mock.calls[0]![0]).toBe("http://127.0.0.1:1933/api/v1/resources/temp_upload");- expect(fetchMock.mock.calls[1]![0]).toBe("http://127.0.0.1:1933/api/v1/resources");- const body = JSON.parse(String(fetchMock.mock.calls[1]![1]!.body));+ expect(openVikingTransport.mock.calls[0]![0]).toBe("http://127.0.0.1:1933/api/v1/resources/temp_upload");+ expect(openVikingTransport.mock.calls[1]![0]).toBe("http://127.0.0.1:1933/api/v1/resources");+ const body = JSON.parse(String(openVikingTransport.mock.calls[1]![1]!.body));expect(body).toMatchObject({temp_file_id: "upload_sheet.xlsx",wait: true,@@ -2176,12 +2179,12 @@ describe("Plugin registration", () => {});it("add_skill posts skill imports to the skills API", async () => {- const fetchMock = vi.fn(async () =>+ const openVikingTransport = vi.fn(async () =>okResponse({ uri: "viking://user/skills/demo", name: "demo" }),);- vi.stubGlobal("fetch", fetchMock);const { tools, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;contextEnginePlugin.register(api as any);const tool = tools.get("add_skill")!;@@ -2192,7 +2195,7 @@ describe("Plugin registration", () => {}) as ToolResult;expect(result.content[0]!.text).toContain("Imported OpenViking skill");- const [url, init] = fetchMock.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/skills")) as [string, RequestInit];+ const [url, init] = openVikingTransport.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/skills")) as [string, RequestInit];expect(url).toBe("http://127.0.0.1:1933/api/v1/skills");const body = JSON.parse(String(init.body));expect(body).toMatchObject({@@ -2203,10 +2206,10 @@ describe("Plugin registration", () => {});it("slash commands honor bypassSessionPatterns", async () => {- const fetchMock = vi.fn(async () => okResponse({}));- vi.stubGlobal("fetch", fetchMock);+ const openVikingTransport = vi.fn(async () => okResponse({}));const { commands, api } = setupPlugin();+ (api as any).openVikingTransport = openVikingTransport;api.pluginConfig = {...api.pluginConfig,bypassSessionPatterns: ["agent:bypass:*"],@@ -2220,7 +2223,7 @@ describe("Plugin registration", () => {});expect(search.text).toContain("bypassed for this session");- expect(fetchMock).not.toHaveBeenCalled();+ expect(openVikingTransport).not.toHaveBeenCalled();});it("registers service with id 'openviking'", () => {