Skip to content

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

feat(openclaw-plugin): add unified ov_import and ov_search (#1369)

x__dot23f0775ab5b9
diff --git a/examples/openclaw-plugin/DISCUSSION-ov-import.md b/examples/openclaw-plugin/DISCUSSION-ov-import.md
new file mode 100644
index 000000000..1975b55fa
--- /dev/null
+++ b/examples/openclaw-plugin/DISCUSSION-ov-import.md
@@ -0,0 +1,600 @@
+# [RFC] OpenClaw Plugin 支持通过 OpenViking 导入/查询 Resource 与 Skill
+
+## 背景
+
+当前 `examples/openclaw-plugin` 已经承担 OpenClaw 与 OpenViking 的 context-engine 集成,包括 session context、memory recall/store/forget、archive expand,以及 local/remote OpenViking runtime 管理。
+
+随着 OpenViking 的 resource 和 skill 能力完善,OpenClaw 侧也需要一个自然入口,让用户可以在 OpenClaw 对话或显式命令中把外部资料导入到 OpenViking:
+
+- Resource:项目文档、代码仓库、网页、PDF、Markdown、本地目录等,落到 `viking://resources/...`
+- Skill:`SKILL.md`、skill 目录、raw skill 内容或 MCP tool dict,落到 `viking://agent/skills/...`
+
+本 RFC 讨论 OpenClaw plugin 侧的导入入口、HTTP 对接方式、安全边界和测试方案。
+
+## 目标
+
+1. 在 OpenClaw 中支持通过插件导入 OpenViking resource。
+2. 在 OpenClaw 中支持通过插件导入 OpenViking skill。
+3. 为简化使用,对外合并为一个统一入口:
+ - LLM tool:`ov_import`
+ - slash command:`/ov-import`
+4. 通过参数 `kind: "resource" | "skill"` 区分导入类型,默认 `resource`。
+5. 保持 HTTP server 的本地路径安全边界:不把本地路径直接发给 OpenViking 服务端。
+6. 底层仍复用 `OpenVikingClient.addResource()` / `OpenVikingClient.addSkill()`,避免在 resource 和 skill 之间复制上传逻辑。
+7. 导入后提供检索入口,让用户能在 OpenClaw 内确认和消费已导入 resource 与 skill。
+
+## 非目标
+
+- 不改变 OpenViking 服务端 resource/skill API。
+- 不新增 OpenViking parser 类型。
+- 不依赖插件侧自动猜测所有输入类型。
+- slash command 暂不支持复杂 raw `SKILL.md` 多行内容或 MCP dict JSON;这些能力通过 LLM tool 的 `data` 参数支持。
+
+## 当前 OpenViking 支持的 Resource 输入
+
+OpenViking resource 侧当前支持多类输入源:
+
+- 远程 URL:`http://`、`https://`
+- Git 仓库 URL:`git@`、`ssh://`、`git://`,以及常见 Git hosting URL
+- 飞书/Lark 文档 URL
+- 本地文件、本地目录、`.zip`
+- raw text content
+
+常见文件 parser 覆盖:
+
+- 文档/文本:`.txt`、`.text`、`.md`、`.markdown`、`.mdown`、`.mkd`、`.pdf`、`.html`、`.htm`
+- Office/电子书:`.docx`、`.doc`、`.pptx`、`.xlsx`、`.xls`、`.xlsm`、`.epub`
+- 图片:`.png`、`.jpg`、`.jpeg`、`.gif`、`.bmp`、`.webp`、`.svg`
+- 音频:`.mp3`、`.wav`、`.ogg`、`.flac`、`.aac`、`.m4a`、`.opus`
+- 视频:`.mp4`、`.avi`、`.mov`、`.mkv`、`.webm`、`.flv`、`.wmv`
+- 目录导入还会把常见代码、文档、配置扩展名作为 text 处理,例如 `.py`、`.js`、`.ts`、`.go`、`.rs`、`.java`、`.cpp`、`.json`、`.yaml`、`.toml`、`.csv`、`.rst`、`.proto`、`.tf`、`.vue`
+
+补充说明:media parser 当前主要复制原始文件并提取基础元数据;后续向量化主要依赖摘要。
+
+## 当前 OpenViking 支持的 Skill 输入
+
+OpenViking 当前已经有独立的 skill 导入链路:
+
+- HTTP API:`POST /api/v1/skills`
+- Service 层:`ResourceService.add_skill(...)`
+- Processor:`SkillProcessor.process_skill(...)`
+- 存储位置:`viking://agent/skills/{skill_name}`
+
+支持的输入形态包括:
+
+- 本地 `SKILL.md` 文件
+- 包含 `SKILL.md` 的 skill 目录
+- zip 包,解压后按目录/文件处理
+- raw `SKILL.md` 字符串内容
+- dict 格式的 skill 数据
+- MCP tool dict,会通过 `mcp_to_skill()` 转成 skill
+
+HTTP 安全边界是:直接通过 HTTP 调 `/api/v1/skills` 时,不能传宿主本地路径;本地文件/目录需要先上传到 `/api/v1/resources/temp_upload`,再把返回的 `temp_file_id` 传给 `/api/v1/skills`。
+
+## 设计方案
+
+### 1. 对外合并为一个入口
+
+为简化用户和 LLM 的使用成本,对外只暴露一个导入入口:
+
+- LLM tool:`ov_import`
+- slash command:`/ov-import`
+
+使用 `kind` 参数区分导入类型:
+
+```ts
+kind?: "resource" | "skill";
+```
+
+默认:
+
+```ts
+kind = "resource";
+```
+
+这样最常见的 resource 导入不需要额外指定类型:
+
+```text
+/ov-import ./README.md --to viking://resources/openviking-readme --wait
+```
+
+导入 skill 时显式指定:
+
+```text
+/ov-import ./skills/install-openviking-memory --kind skill --wait
+```
+
+### 2. 为什么不拆成两个入口
+
+最初也可以设计为:
+
+- `ov_resource_import`
+- `ov_skill_import`
+
+但讨论后更倾向统一入口,原因是:
+
+- 用户只需要记一个命令:`/ov-import`
+- LLM 只需要学习一个工具:`ov_import`
+- 默认 resource 符合更常见的导入场景
+- `kind=skill` 仍然是显式选择,不依赖完全自动猜测
+- 底层实现仍然区分 resource 与 skill,不牺牲语义清晰度
+
+换句话说:对外入口合并,对内处理分流。
+
+### 3. LLM Tool 参数设计
+
+新增工具:
+
+```text
+ov_import
+```
+
+参数:
+
+```ts
+{
+ kind?: "resource" | "skill"; // default: resource
+
+ // resource 或 skill path 模式共用
+ source?: string; // local path, directory path, public URL, Git URL
+
+ // skill 专用:raw SKILL.md 或 MCP tool dict
+ data?: unknown;
+
+ // resource 专用
+ to?: string;
+ parent?: string;
+ reason?: string;
+ instruction?: string;
+
+ // 通用
+ wait?: boolean;
+ timeout?: number;
+}
+```
+
+校验规则:
+
+- `kind` 为空时按 `resource`。
+- `kind=resource`:
+ - 必须提供 `source`
+ - `source` 可为本地路径、目录、远程 URL 或 Git URL
+ - `to` 与 `parent` 互斥
+ - 忽略或拒绝 `data`
+- `kind=skill`:
+ - 必须提供 `source` 或 `data`
+ - `source` 可为本地 `SKILL.md`、skill 目录或 zip
+ - `data` 可为 raw `SKILL.md` 或 MCP tool dict
+ - 拒绝 resource-only 参数:`to`、`parent`、`reason`、`instruction`
+
+工具描述中应明确:只有当用户明确要求导入、添加或索引 OpenViking resource/skill 时才调用,避免模型误触发。
+
+### 4. Resource 导入路径设置
+
+Resource 的导入路径由 `to` 或 `parent` 控制,二者互斥:
+
+- `to`:精确指定最终 resource URI。
+- `parent`:只指定父目录,由 OpenViking 根据源文件名、目录名、URL 或仓库名生成子路径。
+- 二者都不传:由 OpenViking 在 `viking://resources/...` 下按默认规则生成路径。
+
+推荐用户在希望得到稳定引用 URI 时使用 `to`:
+
+```text
+/ov-import ./README.md --to viking://resources/openviking-readme --wait
+```
+
+结果会尽量落到:
+
+```text
+viking://resources/openviking-readme
+```
+
+如果只想把资源放到某个集合下,可使用 `parent`:
+
+```text
+/ov-import ./README.md --parent viking://resources/docs --wait
+```
+
+结果会落在类似:
+
+```text
+viking://resources/docs/README
+```
+
+### 5. Slash Command 参数设计
+
+新增命令:
+
+```text
+/ov-import <source> [--kind resource|skill] [--to URI] [--parent URI] [--reason TEXT] [--instruction TEXT] [--wait] [--timeout SEC]
+```
+
+默认 resource:
+
+```text
+/ov-import ./README.md --to viking://resources/openviking-readme --wait
+```
+
+导入远程 resource:
+
+```text
+/ov-import https://github.com/volcengine/OpenViking --to viking://resources/openviking-repo --reason "OpenViking source docs"
+```
+
+导入 skill:
+
+```text
+/ov-import ./skills/install-openviking-memory --kind skill --wait
+/ov-import ./SKILL.md --kind skill --wait
+```
+
+Slash command 暂不支持 raw multi-line `SKILL.md` 或 MCP dict JSON;如果需要导入这些结构化数据,使用 LLM tool 的 `data` 参数。
+
+目录导入的高级过滤参数暂不放进 v1 对外入口。后续可以按需增加:
+
+```ts
+strict?: boolean;
+ignoreDirs?: string;
+include?: string;
+exclude?: string;
+preserveStructure?: boolean;
+```
+
+### 6. Client 层实现
+
+在 `OpenVikingClient` 增加底层方法:
+
+- `uploadTempFile(filePath)`
+- `zipDirectoryForUpload(dirPath)`
+- `addResource(input)`
+- `addSkill(input)`
+
+`ov_import` 工具和 `/ov-import` 命令根据 `kind` 分流:
+
+```ts
+if (kind === "skill") {
+ return client.addSkill(...);
+}
+return client.addResource(...);
+```
+
+本地文件/目录流程:
+
+```text
+local file/dir
+ -> if dir: zip locally
+ -> POST /api/v1/resources/temp_upload
+ -> POST /api/v1/resources or /api/v1/skills with temp_file_id
+```
+
+远程 resource 流程:
+
+```text
+remote URL / Git URL
+ -> POST /api/v1/resources with path
+```
+
+Skill raw data 流程:
+
+```text
+raw SKILL.md or MCP dict
+ -> POST /api/v1/skills with data
+```
+
+### 7. 安全边界
+
+保持 OpenViking HTTP server 当前安全模型:
+
+- 插件不把本地文件系统路径直接发送给服务端。
+- 本地文件必须先走 `/api/v1/resources/temp_upload`。
+- 本地目录先在插件侧打 zip,再上传。
+- zip 使用纯 JavaScript 实现,避免依赖系统 `zip` 命令。
+- resource 的 `to` 与 `parent` 保持互斥,沿用服务端约束。
+
+### 8. 导入后的检索入口:ov_search
+
+只提供 `ov_import` 会让体验不闭环:用户可以把 resource 或 skill 导入 OpenViking,但在 OpenClaw 内不一定知道如何检索、读取或验证导入结果。
+
+因此建议同时讨论一个轻量检索入口:
+
+- LLM tool:`ov_search`
+- slash command:`/ov-search`
+
+`ov_search` 的目标不是替代 OpenViking CLI 的全部能力,而是提供最小闭环:
+
+1. 导入 resource 或 skill。
+2. 返回 resource 的 `root_uri` 或 skill 的 `uri`。
+3. 用户或 LLM 可以立刻按返回 URI 检索。
+
+#### ov_import 返回建议
+
+`ov_import` 导入 resource 后,结果中应包含:
+
+- `root_uri`
+- `status`
+- `queue_status`(如果 `wait=true`)
+- warnings/errors
+- 下一步检索建议
+
+示例:
+
+```text
+Imported OpenViking resource: viking://resources/openviking-readme
+Processing: completed
+Try: /ov-search "OpenViking install" --uri viking://resources/openviking-readme
+```
+
+`ov_import` 导入 skill 后也应返回 skill URI,并给出 skill 检索建议:
+
+```text
+Imported OpenViking skill: viking://agent/skills/install-openviking-memory
+Processing: completed
+Try: /ov-search "<query>" --uri viking://agent/skills
+```
+
+#### ov_search 参数设计
+
+v1 建议保持简洁:
+
+```ts
+{
+ query: string;
+ uri?: string; // default: search resources and skills
+ limit?: number; // default: plugin config or 10
+}
+```
+
+示例命令:
+
+```text
+/ov-search "OpenViking install" --uri viking://resources/openviking-readme
+/ov-search "API usage" --uri viking://resources
+/ov-search "<query>" --uri viking://agent/skills
+```
+
+对应 LLM tool 示例:
+
+```ts
+{
+ query: "OpenViking install",
+ uri: "viking://resources/openviking-readme",
+ limit: 5
+}
+```
+
+#### ov_search 返回结果
+
+`ov_search` 应尽量贴近 OpenViking 当前 `/api/v1/search/find` 的返回结构。OpenViking search 的 raw HTTP 返回外层是:
+
+```ts
+{
+ status: "ok",
+ result: {
+ memories: MatchedContext[];
+ resources: MatchedContext[];
+ skills: MatchedContext[];
+ total: number;
+ query_plan?: unknown;
+ provenance?: unknown; // include_provenance=true 时才可能出现
+ }
+}
+```
+
+其中 `MatchedContext` 当前包含:
+
+```ts
+{
+ context_type: "memory" | "resource" | "skill";
+ uri: string;
+ level: number;
+ score: number;
+ category: string;
+ match_reason: string;
+ relations: Array<{
+ uri: string;
+ abstract: string;
+ }>;
+ abstract: string;
+ overview?: string | null;
+}
+```
+
+因此 `ov_search` 建议也返回两层结果:
+
+1. 用户可读的 `content.text`
+2. 保留 OpenViking 分桶结构的 `details`
+
+有结果时的用户可见文本示例:
+
+```text
+Found 4 OpenViking results for "OpenViking install"
+
+Resources
+1. viking://resources/openviking-readme/README.md
+ OpenViking installation guide and setup commands...
+ score: 0.82
+
+2. viking://resources/openviking-readme/INSTALL.md
+ Plugin install flow for OpenClaw and OpenViking...
+ score: 0.76
+
+Skills
+1. viking://agent/skills/install-openviking-memory
+ Install and operate OpenViking memory integration...
+ score: 0.69
+```
+
+对应结构化返回建议:
+
+```ts
+{
+ content: [
+ {
+ type: "text",
+ text: "Found 4 OpenViking results..."
+ }
+ ],
+ details: {
+ action: "searched",
+ query: "OpenViking install",
+ uri: "viking://resources/openviking-readme",
+ total: 4,
+ memories: [],
+ resources: [
+ {
+ context_type: "resource",
+ uri: "viking://resources/openviking-readme/README.md",
+ level: 2,
+ score: 0.82,
+ category: "",
+ match_reason: "...",
+ relations: [],
+ abstract: "OpenViking installation guide and setup commands...",
+ overview: "..."
+ }
+ ],
+ skills: [
+ {
+ context_type: "skill",
+ uri: "viking://agent/skills/install-openviking-memory",
+ level: 0,
+ score: 0.69,
+ category: "",
+ match_reason: "...",
+ relations: [],
+ abstract: "Install and operate OpenViking memory integration...",
+ overview: "..."
+ }
+ ]
+ }
+}
+```
+
+无结果时:
+
+```text
+No OpenViking resource or skill results found for "OpenViking install".
+```
+
+对应结构化返回:
+
+```ts
+{
+ action: "searched",
+ query: "OpenViking install",
+ uri: "viking://resources/openviking-readme",
+ total: 0,
+ memories: [],
+ resources: [],
+ skills: []
+}
+```
+
+v1 应检索 `resources` 和 `skills`,所以用户可见文本按分桶展示 `resources` 和 `skills`;`details` 中保留 OpenViking 原始的 `memories/resources/skills/total` 结构。由于 v1 不检索 memory,`memories` 通常为空数组。
+
+v1 建议只返回检索结果摘要和 URI,不直接返回完整文件内容。原因:
+
+- 避免把大文档直接塞进上下文。
+- 用户或 LLM 可以基于 URI 再决定是否需要后续 `/ov-read` 或未来的 `ov_read`。
+- 保持 `ov_search` 作为导入后的最小消费闭环,而不是完整文件浏览器。
+
+#### 是否同时检索 memory/resource/skill
+
+`memory_recall` 当前偏向长期记忆,不适合作为 resource/skill 导入后的默认消费入口。`ov_search` v1 应检索:
+
+```ts
+uris = ["viking://resources", "viking://agent/skills"]
+```
+
+后续如果希望统一上下文检索 memory/resource/skill,可扩展:
+
+```ts
+targetTypes?: Array<"memory" | "resource" | "skill">;
+```
+
+但 v1 不建议一开始加入 memory,避免和既有 `memory_recall` 职责重叠。
+
+#### 读取与树形查看
+
+`ov_search` 只解决“查到相关上下文”的问题。若用户需要更明确的文件浏览能力,后续可以再讨论:
+
+- `/ov-read <uri>`
+- `/ov-tree <uri>`
+
+v1 暂不加入,避免把导入 RFC 扩展成完整 OpenViking CLI replica。
+
+## 测试计划
+
+### Unit tests
+
+覆盖 `OpenVikingClient`:
+
+- `addResource`
+ - 远程 URL 直接 POST `path`
+ - 本地文件先 temp upload
+ - 本地目录先 zip 再 temp upload
+ - `wait=true` 保留 `queue_status`
+ - OpenViking error response 透传为可读错误
+- `addSkill`
+ - 本地 `SKILL.md` 先 temp upload
+ - skill 目录先 zip 再 temp upload
+ - raw `SKILL.md` 通过 `data` 直传
+ - MCP tool dict 通过 `data` 直传
+
+覆盖 `ov_import`:
+
+- 注册单个 tool:`ov_import`
+- 注册单个 command:`/ov-import`
+- `kind` 默认 `resource`
+- `kind=skill` 正确分流到 `addSkill`
+- `--kind skill`
+- quoted args
+- `--flag`
+- `--key value`
+- `--key=value`
+- `--to` 与 `--parent` 冲突
+- `kind=skill` 时拒绝 `to`、`parent`、`reason`、`instruction`
+
+覆盖 `ov_search`:
+
+- 注册单个 tool:`ov_search`
+- 注册单个 command:`/ov-search`
+- 未指定 `uri` 时默认检索 `viking://resources` 和 `viking://agent/skills`
+- 指定 `--uri` 时只检索该范围
+- OpenViking error response 透传为可读错误
+- 查询为空时返回 usage error
+
+### Manual smoke
+
+```text
+/ov-import ./README.md --to viking://resources/openviking-readme --wait
+/ov-search "OpenViking install" --uri viking://resources/openviking-readme
+/ov-import ./skills/install-openviking-memory --kind skill --wait
+/ov-search "install OpenViking memory" --uri viking://agent/skills
+```
+
+以及自然语言触发:
+
+```text
+把 ./README.md 导入 OpenViking resource,目标是 viking://resources/openviking-readme,并等待处理完成。
+```
+
+```text
+把 ./skills/install-openviking-memory 作为 OpenViking skill 导入。
+```
+
+## 待讨论问题
+
+1. `ov_import` 是否应默认 `wait=false`?
+ - 当前建议默认不等待,只有用户显式要求“等待处理完成”或传 `wait=true` 时才等待。
+2. `kind=skill` 时 resource-only 参数应直接报错,还是静默忽略?
+ - 当前建议直接报错,避免用户误以为 `to/parent` 对 skill 生效。
+3. 是否需要插件侧自动识别 skill?
+ - 可选增强:当本地文件名为 `SKILL.md` 或目录包含 `SKILL.md` 时自动设置 `kind=skill`。
+ - 但当前建议先使用显式 `--kind skill`,默认 resource,行为更可解释。
+4. 导入本地大目录前是否需要确认机制?
+ - 当前方案先不加确认;后续可基于文件数量/zip 大小增加保护。
+5. `ov_search` v1 是否默认检索 `viking://resources` 和 `viking://agent/skills`?
+ - 当前建议是。memory 仍交给既有 `memory_recall`,避免职责重叠。
+6. 是否需要在 v1 同时提供 `/ov-read` 或 `/ov-tree`?
+ - 当前建议不加,先用 `ov_search` 完成导入后的最小消费闭环。
diff --git a/examples/openclaw-plugin/README.md b/examples/openclaw-plugin/README.md
index 46007e0cb..c99593a77 100644
--- a/examples/openclaw-plugin/README.md
+++ b/examples/openclaw-plugin/README.md
@@ -20,7 +20,7 @@ In the current implementation, the plugin plays four roles at once:
- `context-engine`: implements `assemble`, `afterTurn`, and `compact`
- hook layer: handles `before_prompt_build`, `session_start`, `session_end`, `agent_end`, and `before_reset`
-- tool provider: registers `memory_recall`, `memory_store`, `memory_forget`, and `ov_archive_expand`
+- tool provider: registers memory/archive tools plus OpenViking resource and skill import tools
- runtime manager: starts and monitors an OpenViking subprocess in `local` mode
## Overall Architecture
@@ -131,12 +131,14 @@ So `afterTurn()` is closer to “incremental append plus threshold-triggered asy
## Tools and Expandability
-Beyond automatic behavior, the plugin exposes four tools directly:
+Beyond automatic behavior, the plugin exposes six tools directly:
- `memory_recall`: explicit long-term memory search
- `memory_store`: write text into an OpenViking session and trigger commit
- `memory_forget`: delete by URI, or search first and remove a single strong match
- `ov_archive_expand`: expand a concrete archive back into raw messages
+- `ov_import`: import a resource or skill; defaults to resource and uses `kind: "skill"` for skills
+- `ov_search`: search OpenViking resources and skills, especially after importing them
They serve different roles:
@@ -144,9 +146,31 @@ They serve different roles:
- `memory_recall` gives the model an explicit follow-up search path
- `memory_store` is for immediately persisting clearly important information
- `ov_archive_expand` is the “go back to archive detail” escape hatch when summaries are not enough
+- `ov_import` lets the agent complete explicit import requests without asking the user to remember slash commands
+- `ov_search` closes the loop after import by letting the user or agent confirm and consume resources and skills
`ov_archive_expand` is especially important because `assemble()` normally returns archive summaries and indexes, not the full raw transcript.
+### Resource and Skill Import
+
+Resource and skill imports are intentionally separate because they land in different OpenViking namespaces and use different server APIs:
+
+- resources go through `/api/v1/resources` and land under `viking://resources/...`
+- skills go through `/api/v1/skills` and land under `viking://agent/skills/...`
+
+The plugin also registers explicit slash commands for manual imports:
+
+```text
+/ov-import ./README.md --to viking://resources/openviking-readme --wait
+/ov-import ./skills/install-openviking-memory --kind skill --wait
+/ov-search "OpenViking install" --uri viking://resources/openviking-readme
+/ov-search "memory install skill" --uri viking://agent/skills
+```
+
+Resource import supports remote URLs, Git URLs, local files, local directories, and uploaded zip files. OpenViking's built-in parsers cover common documents and media such as Markdown, text, PDF, HTML, Word, PowerPoint, Excel, EPUB, images, audio, and video. Directory imports also accept common code, documentation, and config file extensions such as `.py`, `.js`, `.ts`, `.go`, `.rs`, `.java`, `.cpp`, `.json`, `.yaml`, `.toml`, `.csv`, `.rst`, `.proto`, `.tf`, and `.vue`.
+
+For HTTP safety, the plugin never sends a direct local filesystem path to the OpenViking server. Local files and directories are first uploaded through `/api/v1/resources/temp_upload`; directories are zipped locally with a pure JavaScript zip implementation before upload.
+
## Local / Remote Runtime Modes
![Runtime modes and routing behavior](./images/openclaw-plugin-runtime-routing.png)
diff --git a/examples/openclaw-plugin/README_CN.md b/examples/openclaw-plugin/README_CN.md
index ced61b4a7..ca463ada5 100644
--- a/examples/openclaw-plugin/README_CN.md
+++ b/examples/openclaw-plugin/README_CN.md
@@ -20,7 +20,7 @@
- `context-engine`:实现 `assemble`、`afterTurn`、`compact`
- Hook 层:接管 `before_prompt_build`、`session_start`、`session_end`、`agent_end`、`before_reset`
-- Tool 提供者:注册 `memory_recall`、`memory_store`、`memory_forget`、`ov_archive_expand`
+- Tool 提供者:注册 memory/archive 工具,以及 OpenViking resource 和 skill 导入工具
- 运行时管理器:在 `local` 模式下拉起并监控 OpenViking 子进程
## 总体架构
@@ -131,12 +131,14 @@ Session 是这套设计的主轴。当前实现里,它覆盖了“历史组装
## 工具层与可展开能力
-这套插件除了自动行为,还直接暴露了 4 个工具:
+这套插件除了自动行为,还直接暴露了 6 个工具:
- `memory_recall`:显式检索长期记忆
- `memory_store`:把文本写入 OpenViking session 并立即触发 commit
- `memory_forget`:按 URI 删除,或先搜索再删除唯一高置信候选
- `ov_archive_expand`:展开某个 archive 的原始消息
+- `ov_import`:导入 resource 或 skill;默认 resource,导入 skill 时使用 `kind: "skill"`
+- `ov_search`:检索 OpenViking resources 和 skills,尤其用于导入后的确认和消费
它们各自的作用不同:
@@ -144,9 +146,31 @@ Session 是这套设计的主轴。当前实现里,它覆盖了“历史组装
- `memory_recall` 给模型一个显式补查入口。
- `memory_store` 适合把一段明确的重要信息立刻落入记忆管线。
- `ov_archive_expand` 负责在 summary 不够细时回到 archive 级原文。
+- `ov_import` 让 agent 在用户明确提出导入需求时直接完成操作,不要求用户记住 slash command。
+- `ov_search` 补齐导入后的使用闭环,让用户或 agent 可以确认并消费 resources 和 skills。
其中 `ov_archive_expand` 是 `assemble()` 的重要补充,因为 `assemble()` 默认给的是压缩后的索引和摘要,而不是完整历史正文。
+### Resource 与 Skill 导入
+
+Resource 和 skill 保持两个入口,因为它们落在不同 OpenViking 命名空间,并使用不同服务端 API:
+
+- resource 走 `/api/v1/resources`,落到 `viking://resources/...`
+- skill 走 `/api/v1/skills`,落到 `viking://agent/skills/...`
+
+插件也提供显式 slash command,方便手动导入:
+
+```text
+/ov-import ./README.md --to viking://resources/openviking-readme --wait
+/ov-import ./skills/install-openviking-memory --kind skill --wait
+/ov-search "OpenViking install" --uri viking://resources/openviking-readme
+/ov-search "memory install skill" --uri viking://agent/skills
+```
+
+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 实现打包后再上传。
+
## Local / Remote 运行模式
![运行模式与路由解析](./images/openclaw-plugin-runtime-routing.png)
diff --git a/examples/openclaw-plugin/client.ts b/examples/openclaw-plugin/client.ts
index 5d2bae044..c8d4a5796 100644
--- a/examples/openclaw-plugin/client.ts
+++ b/examples/openclaw-plugin/client.ts
@@ -1,5 +1,12 @@
-import { createHash } from "node:crypto";
+import { createHash, randomUUID } from "node:crypto";
import type { spawn } from "node:child_process";
+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";
export type FindResultItem = {
uri: string;
@@ -106,6 +113,50 @@ export type SessionArchiveResult = {
messages: OVMessage[];
};
+export type AddResourceInput = {
+ pathOrUrl: string;
+ to?: string;
+ parent?: string;
+ reason?: string;
+ instruction?: string;
+ wait?: boolean;
+ timeout?: number;
+ strict?: boolean;
+ ignoreDirs?: string;
+ include?: string;
+ exclude?: string;
+ preserveStructure?: boolean;
+};
+
+export type AddResourceResult = {
+ status?: string;
+ root_uri?: string;
+ temp_uri?: string;
+ source_path?: string;
+ warnings?: string[];
+ errors?: string[];
+ queue_status?: unknown;
+ meta?: unknown;
+};
+
+export type AddSkillInput = {
+ path?: string;
+ data?: unknown;
+ wait?: boolean;
+ timeout?: number;
+};
+
+export type AddSkillResult = {
+ status?: string;
+ uri?: string;
+ name?: string;
+ auxiliary_files?: number;
+ queue_status?: unknown;
+};
+
+const DEFAULT_WAIT_REQUEST_TIMEOUT_MS = 120_000;
+const WAIT_REQUEST_TIMEOUT_BUFFER_MS = 5_000;
+
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -123,6 +174,7 @@ const MEMORY_URI_PATTERNS = [
];
const USER_STRUCTURE_DIRS = new Set(["memories"]);
const AGENT_STRUCTURE_DIRS = new Set(["memories", "skills", "instructions", "workspaces"]);
+const REMOTE_RESOURCE_PREFIXES = ["http://", "https://", "git@", "ssh://", "git://"];
function md5Short(input: string): string {
return createHash("md5").update(input).digest("hex").slice(0, 12);
@@ -132,6 +184,30 @@ export function isMemoryUri(uri: string): boolean {
return MEMORY_URI_PATTERNS.some((pattern) => pattern.test(uri));
}
+function isRemoteResourceSource(source: string): boolean {
+ return REMOTE_RESOURCE_PREFIXES.some((prefix) => source.startsWith(prefix));
+}
+
+function toBlobPart(value: Buffer): ArrayBuffer {
+ return value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength) as ArrayBuffer;
+}
+
+function resolveWaitRequestTimeoutMs(defaultTimeoutMs: number, waitTimeoutSeconds?: number): number {
+ const requestedMs =
+ typeof waitTimeoutSeconds === "number" && Number.isFinite(waitTimeoutSeconds) && waitTimeoutSeconds > 0
+ ? Math.ceil(waitTimeoutSeconds * 1000) + WAIT_REQUEST_TIMEOUT_BUFFER_MS
+ : DEFAULT_WAIT_REQUEST_TIMEOUT_MS;
+ return Math.max(defaultTimeoutMs, requestedMs);
+}
+
+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 class OpenVikingClient {
private spaceCache = new Map<string, Partial<Record<ScopeName, string>>>();
private identityCache = new Map<string, RuntimeIdentity>();
@@ -177,10 +253,15 @@ export class OpenVikingClient {
);
}
- private async request<T>(path: string, init: RequestInit = {}, agentId?: string): Promise<T> {
+ private async request<T>(
+ path: string,
+ init: RequestInit = {},
+ agentId?: string,
+ requestTimeoutMs?: number,
+ ): Promise<T> {
const effectiveAgentId = agentId ?? this.defaultAgentId;
const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
+ const timer = setTimeout(() => controller.abort(), requestTimeoutMs ?? this.timeoutMs);
try {
const headers = new Headers(init.headers ?? {});
if (this.apiKey) {
@@ -191,7 +272,7 @@ export class OpenVikingClient {
if (effectiveAgentId) {
headers.set("X-OpenViking-Agent", effectiveAgentId);
}
- if (init.body && !headers.has("Content-Type")) {
+ if (init.body && !(init.body instanceof FormData) && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
@@ -375,6 +456,176 @@ export class OpenVikingClient {
);
}
+ async uploadTempFile(filePath: string, agentId?: 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 result = await this.request<{ temp_file_id: string }>(
+ "/api/v1/resources/temp_upload",
+ { method: "POST", body: form },
+ agentId,
+ );
+ if (!result.temp_file_id) {
+ throw new Error("OpenViking temp upload did not return temp_file_id");
+ }
+ return result.temp_file_id;
+ }
+
+ async 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).replace(/\\/g, "/");
+ 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 addResource(input: AddResourceInput, agentId?: string): Promise<AddResourceResult> {
+ const pathOrUrl = input.pathOrUrl.trim();
+ if (!pathOrUrl) {
+ throw new Error("pathOrUrl is required");
+ }
+ if (input.to && input.parent) {
+ throw new Error("Cannot specify both 'to' and 'parent'.");
+ }
+
+ const body: Record<string, unknown> = {
+ to: input.to,
+ parent: input.parent,
+ reason: input.reason ?? "",
+ instruction: input.instruction ?? "",
+ wait: input.wait ?? false,
+ timeout: input.timeout,
+ strict: input.strict ?? false,
+ ignore_dirs: input.ignoreDirs,
+ include: input.include,
+ exclude: input.exclude,
+ };
+ if (typeof input.preserveStructure === "boolean") {
+ body.preserve_structure = input.preserveStructure;
+ }
+
+ let cleanupPath: string | undefined;
+ const requestTimeoutMs =
+ input.wait ? resolveWaitRequestTimeoutMs(this.timeoutMs, input.timeout) : undefined;
+ try {
+ if (isRemoteResourceSource(pathOrUrl)) {
+ body.path = pathOrUrl;
+ } 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}`);
+ }
+ body.temp_file_id = await this.uploadTempFile(uploadPath, agentId);
+ }
+ return this.request<AddResourceResult>(
+ "/api/v1/resources",
+ { method: "POST", body: JSON.stringify(body) },
+ agentId,
+ requestTimeoutMs,
+ );
+ } finally {
+ await cleanupUploadTempPath(cleanupPath);
+ }
+ }
+
+ async addSkill(input: AddSkillInput, agentId?: string): Promise<AddSkillResult> {
+ const hasPath = typeof input.path === "string" && input.path.trim().length > 0;
+ const hasData = input.data !== undefined && input.data !== null;
+ if (hasPath === hasData) {
+ throw new Error("Provide exactly one of 'path' or 'data' for skill import.");
+ }
+
+ const body: Record<string, unknown> = {
+ wait: input.wait ?? false,
+ timeout: input.timeout,
+ };
+ let cleanupPath: string | 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()) {
+ throw new Error(`Path is not a file or directory: ${skillPath}`);
+ }
+ body.temp_file_id = await this.uploadTempFile(uploadPath, agentId);
+ } else {
+ body.data = input.data;
+ }
+ return this.request<AddSkillResult>(
+ "/api/v1/skills",
+ { method: "POST", body: JSON.stringify(body) },
+ agentId,
+ requestTimeoutMs,
+ );
+ } finally {
+ await cleanupUploadTempPath(cleanupPath);
+ }
+ }
+
async addSessionMessage(
sessionId: string,
role: string,
diff --git a/examples/openclaw-plugin/index.ts b/examples/openclaw-plugin/index.ts
index 849501402..d128f9ebe 100644
--- a/examples/openclaw-plugin/index.ts
+++ b/examples/openclaw-plugin/index.ts
@@ -5,7 +5,17 @@ import { Type } from "@sinclair/typebox";
import { memoryOpenVikingConfigSchema } from "./config.js";
import { OpenVikingClient, localClientCache, localClientPendingPromises, isMemoryUri } from "./client.js";
-import type { FindResultItem, PendingClientEntry, CommitSessionResult, OVMessage } from "./client.js";
+import type {
+ AddResourceInput,
+ AddResourceResult,
+ AddSkillInput,
+ AddSkillResult,
+ FindResult,
+ FindResultItem,
+ PendingClientEntry,
+ CommitSessionResult,
+ OVMessage,
+} from "./client.js";
import { formatMessageFaithful } from "./context-engine.js";
import {
compileSessionPatterns,
@@ -85,6 +95,48 @@ type ToolContext = {
agentId?: 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 OvImportKind = "resource" | "skill";
+
+type OvImportInput = {
+ kind?: OvImportKind;
+ source?: string;
+ data?: unknown;
+ to?: string;
+ parent?: string;
+ reason?: string;
+ instruction?: string;
+ wait?: boolean;
+ timeout?: number;
+};
+
+type OvSearchInput = {
+ query: string;
+ uri?: string;
+ limit?: number;
+};
+
type OpenClawPluginApi = {
pluginConfig?: unknown;
logger: PluginLogger;
@@ -95,6 +147,7 @@ type OpenClawPluginApi = {
opts?: { name?: string; names?: string[] },
): void;
};
+ registerCommand?: (command: CommandDefinition) => void;
registerService: (service: {
id: string;
start: (ctx?: unknown) => void | Promise<void>;
@@ -163,6 +216,169 @@ export function prepareRecallQuery(rawText: string): PreparedRecallQuery {
};
}
+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;
+}
+
+function parseImportKind(value: string | undefined): OvImportKind {
+ if (!value) {
+ return "resource";
+ }
+ if (value === "resource" || value === "skill") {
+ return value;
+ }
+ throw new Error("--kind must be resource or skill");
+}
+
+export function parseOvImportCommandArgs(args: string): OvImportInput {
+ const parsed = parseFlagArgs(args);
+ const kind = parseImportKind(getStringFlag(parsed.flags, "kind"));
+ const source =
+ parsed.positionals.length <= 1 ? parsed.positionals[0] : parsed.positionals.join(" ").trim();
+ if (!source) {
+ throw new Error("Usage: /ov-import <source> [--kind resource|skill] [--to URI] [--parent URI] [--wait]");
+ }
+ const to = getStringFlag(parsed.flags, "to");
+ const parent = getStringFlag(parsed.flags, "parent");
+ if (to && parent) {
+ throw new Error("Cannot specify both --to and --parent.");
+ }
+ if (kind === "skill" && (to || parent || parsed.flags.has("reason") || parsed.flags.has("instruction"))) {
+ throw new Error("--to, --parent, --reason, and --instruction are resource-only options.");
+ }
+ return {
+ kind,
+ 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 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) {
@@ -419,6 +635,299 @@ const contextEnginePlugin = {
},
});
+ 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, agentId?: string) => {
+ const client = await getClient();
+ const result = await client.addResource(input, agentId);
+ return {
+ content: [{ type: "text" as const, text: formatResourceImportText(result) }],
+ details: {
+ action: "resource_imported",
+ ...result,
+ },
+ };
+ };
+
+ const importSkill = async (input: AddSkillInput, agentId?: string) => {
+ const client = await getClient();
+ const result = await client.addSkill(input, agentId);
+ return {
+ content: [{ type: "text" as const, text: formatSkillImportText(result) }],
+ details: {
+ action: "skill_imported",
+ ...result,
+ },
+ };
+ };
+
+ const executeImport = async (input: OvImportInput, agentId?: string) => {
+ const kind = input.kind ?? "resource";
+ if (kind === "skill") {
+ if (input.to || input.parent || input.reason || input.instruction) {
+ throw new Error("to, parent, reason, and instruction are resource-only options.");
+ }
+ return importSkill({
+ path: input.source,
+ data: input.data,
+ wait: input.wait,
+ timeout: input.timeout,
+ }, agentId);
+ }
+ if (input.data !== undefined && input.data !== null) {
+ throw new Error("data is only supported for skill imports.");
+ }
+ return importResource({
+ pathOrUrl: input.source ?? "",
+ to: input.to,
+ parent: input.parent,
+ reason: input.reason,
+ instruction: input.instruction,
+ wait: input.wait,
+ timeout: input.timeout,
+ }, agentId);
+ };
+
+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 formatSearchRows = (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 truncateUri = (value: string, maxChars = 84): string => {
+ if (value.length <= maxChars) {
+ return value;
+ }
+ return `${value.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 }) => truncateUri(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)} ${truncateUri(item.uri).padEnd(uriWidth)} ${String(item.level ?? "").padEnd(levelWidth)} ${score.padEnd(scoreWidth)} ${summary}`;
+ }),
+ ];
+ };
+
+ const formatSearchText = (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}`,
+ "",
+ ...formatSearchRows(result),
+ ].filter((line, index, all) => line || (all[index - 1] && all[index + 1]));
+ return lines.join("\n");
+ };
+
+ const searchOpenViking = async (input: OvSearchInput, agentId?: string) => {
+ const query = input.query.trim();
+ if (!query) {
+ throw new Error("query is required");
+ }
+ const limit = Math.max(1, Math.floor(input.limit ?? 10));
+ const client = await getClient();
+ let result: FindResult;
+ if (input.uri) {
+ result = await client.find(query, { targetUri: input.uri, limit }, agentId);
+ } else {
+ const [resourcesSettled, skillsSettled] = await Promise.allSettled([
+ client.find(query, { targetUri: "viking://resources", limit }, agentId),
+ client.find(query, { targetUri: "viking://agent/skills", limit }, agentId),
+ ]);
+ const successful = [
+ resourcesSettled.status === "fulfilled" ? resourcesSettled.value : null,
+ skillsSettled.status === "fulfilled" ? skillsSettled.value : null,
+ ].filter((value): value is FindResult => value !== null);
+ if (successful.length === 0) {
+ const firstError = resourcesSettled.status === "rejected" ? resourcesSettled.reason : skillsSettled.reason;
+ 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);
+ }
+ return {
+ content: [{ type: "text" as const, text: formatSearchText(query, input.uri, result) }],
+ details: {
+ action: "searched",
+ query,
+ uri: input.uri,
+ memories: result.memories ?? [],
+ resources: result.resources ?? [],
+ skills: result.skills ?? [],
+ total: result.total ?? 0,
+ },
+ };
+ };
+
+ api.registerTool(
+ (ctx: ToolContext) => ({
+ name: "ov_import",
+ label: "Import (OpenViking)",
+ description:
+ "Import an OpenViking resource or skill only when the user explicitly asks to import, add, or index one. " +
+ "Defaults to resource; set kind=skill for SKILL.md, skill directories, raw skill content, or MCP tool dicts.",
+ parameters: Type.Object({
+ kind: Type.Optional(Type.Union([Type.Literal("resource"), Type.Literal("skill")], { description: "Import kind. Default: resource" })),
+ source: Type.Optional(Type.String({ description: "Local path, directory path, public URL, or Git URL" })),
+ data: Type.Optional(Type.Any({ description: "Skill only: raw SKILL.md content or MCP tool dict" })),
+ to: Type.Optional(Type.String({ description: "Resource only: exact target URI, e.g. viking://resources/project-docs" })),
+ parent: Type.Optional(Type.String({ description: "Resource only: parent URI under viking://resources" })),
+ reason: Type.Optional(Type.String({ description: "Resource only: reason or note for adding this resource" })),
+ instruction: Type.Optional(Type.String({ description: "Resource only: 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("ov_import");
+ }
+ rememberSessionAgentId(ctx);
+ const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
+ return executeImport({
+ kind: params.kind === "skill" ? "skill" : "resource",
+ source: typeof params.source === "string" ? params.source : undefined,
+ data: params.data,
+ 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,
+ }, agentId);
+ },
+ }),
+ { name: "ov_import" },
+ );
+
+ api.registerTool(
+ (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.",
+ 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 (isBypassedSession(ctx)) {
+ return makeBypassedToolResult("ov_search");
+ }
+ rememberSessionAgentId(ctx);
+ const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey);
+ 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,
+ }, agentId);
+ },
+ }),
+ { name: "ov_search" },
+ );
+
+ api.registerCommand?.({
+ name: "ov-import",
+ description: "Import a resource or skill into OpenViking.",
+ acceptsArgs: true,
+ handler: async (ctx: PluginCommandContext) => {
+ try {
+ if (isBypassedSession(ctx)) {
+ const bypassed = makeBypassedToolResult("ov_import");
+ return { text: bypassed.content[0]!.text, details: bypassed.details };
+ }
+ rememberSessionAgentId(ctx);
+ const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey, ctx.ovSessionId);
+ const input = parseOvImportCommandArgs(ctx.args ?? "");
+ const result = await executeImport(input, agentId);
+ return { text: result.content[0]!.text, details: result.details };
+ } catch (err) {
+ return { text: `OpenViking import failed: ${err instanceof Error ? err.message : String(err)}` };
+ }
+ },
+ });
+
+ 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 };
+ }
+ rememberSessionAgentId(ctx);
+ const agentId = resolveAgentId(ctx.sessionId, ctx.sessionKey, ctx.ovSessionId);
+ const input = parseOvSearchCommandArgs(ctx.args ?? "");
+ const result = await searchOpenViking(input, agentId);
+ return { text: result.content[0]!.text, details: result.details };
+ } catch (err) {
+ return { text: `OpenViking search failed: ${err instanceof Error ? err.message : String(err)}` };
+ }
+ },
+ });
+
api.registerTool(
(ctx: ToolContext) => ({
name: "memory_recall",
diff --git a/examples/openclaw-plugin/package-lock.json b/examples/openclaw-plugin/package-lock.json
index 556103a5b..fc346146e 100644
--- a/examples/openclaw-plugin/package-lock.json
+++ b/examples/openclaw-plugin/package-lock.json
@@ -1,18 +1,22 @@
{
"name": "@openclaw/openviking",
- "version": "2026.2.6-3",
+ "version": "2026.3.25",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@openclaw/openviking",
- "version": "2026.2.6-3",
+ "version": "2026.3.25",
"dependencies": {
- "@sinclair/typebox": "0.34.48"
+ "@sinclair/typebox": "0.34.48",
+ "fflate": "^0.8.2"
},
"devDependencies": {
"@types/node": "^25.3.5",
"vitest": "^4.1.0"
+ },
+ "engines": {
+ "openclaw": ">=2026.3.7"
}
},
"node_modules/@emnapi/core": {
@@ -599,6 +603,12 @@
}
}
},
+ "node_modules/fflate": {
+ "version": "0.8.2",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz",
+ "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==",
+ "license": "MIT"
+ },
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
diff --git a/examples/openclaw-plugin/package.json b/examples/openclaw-plugin/package.json
index 5dd464750..36b062e2b 100644
--- a/examples/openclaw-plugin/package.json
+++ b/examples/openclaw-plugin/package.json
@@ -11,7 +11,8 @@
"openclaw": ">=2026.3.7"
},
"dependencies": {
- "@sinclair/typebox": "0.34.48"
+ "@sinclair/typebox": "0.34.48",
+ "fflate": "^0.8.2"
},
"openclaw": {
"extensions": [
diff --git a/examples/openclaw-plugin/tests/ut/client.test.ts b/examples/openclaw-plugin/tests/ut/client.test.ts
index 8b55aefc2..96f91bd24 100644
--- a/examples/openclaw-plugin/tests/ut/client.test.ts
+++ b/examples/openclaw-plugin/tests/ut/client.test.ts
@@ -1,6 +1,29 @@
-import { describe, expect, it } from "vitest";
+import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
-import { isMemoryUri } from "../../client.js";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { OpenVikingClient, isMemoryUri } from "../../client.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" },
+ });
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
describe("isMemoryUri", () => {
it("returns true for valid user memory URI", () => {
@@ -47,3 +70,218 @@ describe("isMemoryUri", () => {
expect(isMemoryUri("viking://memories/abc")).toBe(false);
});
});
+
+describe("OpenVikingClient resource and skill import", () => {
+ it("addResource posts remote URL as path", async () => {
+ const fetchMock = 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 result = await client.addResource({
+ pathOrUrl: "https://example.com/docs",
+ to: "viking://resources/site",
+ wait: true,
+ });
+
+ expect(result.root_uri).toBe("viking://resources/site");
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
+ expect(JSON.parse(String(init.body))).toMatchObject({
+ path: "https://example.com/docs",
+ to: "viking://resources/site",
+ wait: true,
+ });
+ });
+
+ it("addResource uploads local file before posting temp_file_id", async () => {
+ const tempDir = await mkdtemp(join(tmpdir(), "ov-client-test-"));
+ const filePath = join(tempDir, "resource.md");
+ await writeFile(filePath, "# Demo\n");
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(okResponse({ temp_file_id: "upload_resource.md" }))
+ .mockResolvedValueOnce(okResponse({
+ root_uri: "viking://resources/demo",
+ status: "success",
+ queue_status: { completed: true },
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);
+ 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({
+ 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
+ .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);
+ 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({
+ 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
+ .fn()
+ .mockResolvedValueOnce(okResponse({ temp_file_id: "upload_skill.md" }))
+ .mockResolvedValueOnce(okResponse({ uri: "viking://agent/skills/demo", name: "demo" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);
+ const result = await client.addSkill({ path: filePath, wait: true });
+
+ expect(result.uri).toBe("viking://agent/skills/demo");
+ expect(JSON.parse(String((fetchMock.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
+ .fn()
+ .mockResolvedValueOnce(okResponse({ temp_file_id: "upload_skill.zip" }))
+ .mockResolvedValueOnce(okResponse({ uri: "viking://agent/skills/demo", name: "demo" }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);
+ await client.addSkill({ path: dirPath, wait: true });
+
+ expect(JSON.parse(String((fetchMock.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(
+ okResponse({ uri: "viking://agent/skills/inline", name: "inline" }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);
+ await client.addSkill({ data });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(String((fetchMock.mock.calls[0]![1] as RequestInit).body))).toMatchObject({
+ data,
+ wait: false,
+ });
+ });
+
+ it("addSkill posts MCP tool dict directly", async () => {
+ const data = {
+ name: "demo_tool",
+ description: "demo",
+ inputSchema: { type: "object", properties: {} },
+ };
+ const fetchMock = vi.fn().mockResolvedValue(
+ okResponse({ uri: "viking://agent/skills/demo-tool", name: "demo-tool" }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);
+ await client.addSkill({ data });
+
+ expect(JSON.parse(String((fetchMock.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 client = new OpenVikingClient("http://127.0.0.1:1933", "", "agent", 5000);
+ await expect(client.addResource({ pathOrUrl: "https://example.com/bad" })).rejects.toThrow(
+ "OpenViking request failed [INVALID_ARGUMENT]: bad 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) => {
+ 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 pending = client.addResource({
+ pathOrUrl: "https://example.com/docs",
+ wait: true,
+ timeout: 60,
+ });
+
+ await vi.advanceTimersByTimeAsync(20_000);
+
+ await expect(pending).resolves.toMatchObject({
+ root_uri: "viking://resources/site",
+ status: "success",
+ });
+ });
+
+ 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) => {
+ 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 pending = client.addResource({
+ pathOrUrl: "https://example.com/docs",
+ wait: false,
+ });
+ const assertion = expect(pending).rejects.toThrow(/aborted/i);
+
+ await vi.advanceTimersByTimeAsync(15_001);
+
+ await assertion;
+ });
+});
diff --git a/examples/openclaw-plugin/tests/ut/tools.test.ts b/examples/openclaw-plugin/tests/ut/tools.test.ts
index a1fd7d48e..fb5edbd96 100644
--- a/examples/openclaw-plugin/tests/ut/tools.test.ts
+++ b/examples/openclaw-plugin/tests/ut/tools.test.ts
@@ -1,21 +1,53 @@
-import { describe, expect, it, vi, beforeAll } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import contextEnginePlugin from "../../index.js";
+import contextEnginePlugin, {
+ parseOvImportCommandArgs,
+ parseOvSearchCommandArgs,
+ tokenizeCommandArgs,
+} from "../../index.js";
import type { FindResultItem } from "../../client.js";
type ToolDef = {
name: string;
+ description: string;
+ parameters?: unknown;
execute: (toolCallId: string, params: Record<string, unknown>) => Promise<unknown>;
};
+type CommandDef = {
+ name: string;
+ description: string;
+ acceptsArgs?: boolean;
+ handler: (ctx: {
+ args?: string;
+ commandBody: string;
+ sessionKey?: string;
+ sessionId?: string;
+ agentId?: string;
+ ovSessionId?: string;
+ }) => Promise<{ text: string }>;
+};
+
type ToolResult = {
content: Array<{ type: string; text: string }>;
details: Record<string, unknown>;
};
+function okResponse(result: unknown): Response {
+ return new Response(JSON.stringify({ status: "ok", result }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
function setupPlugin(clientOverrides?: Record<string, unknown>) {
const tools = new Map<string, ToolDef>();
const factoryTools = new Map<string, (ctx: Record<string, unknown>) => ToolDef>();
+ const commands = new Map<string, CommandDef>();
const mockClient = {
find: vi.fn().mockResolvedValue({ memories: [], total: 0 }),
@@ -71,6 +103,10 @@ function setupPlugin(clientOverrides?: Record<string, unknown>) {
tools.set(tool.name, tool);
}
}),
+ registerCommand: vi.fn((command: unknown) => {
+ const cmd = command as CommandDef;
+ commands.set(cmd.name, cmd);
+ }),
registerService: vi.fn(),
registerContextEngine: vi.fn(),
on: vi.fn(),
@@ -96,7 +132,7 @@ function setupPlugin(clientOverrides?: Record<string, unknown>) {
// 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, mockClient, api };
+ return { tools, factoryTools, commands, mockClient, api };
}
function makeMemory(overrides?: Partial<FindResultItem>): FindResultItem {
@@ -193,11 +229,360 @@ describe("Tool: ov_archive_expand (behavioral)", () => {
});
});
+describe("Tool: ov_import and ov_search (registration)", () => {
+ it("registers unified import tool with expected parameters", () => {
+ const { tools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const tool = tools.get("ov_import");
+ expect(tool).toBeDefined();
+ expect(tool!.description).toContain("explicitly asks");
+ const props = (tool!.parameters as any).properties;
+ expect(props).toHaveProperty("kind");
+ expect(props).toHaveProperty("source");
+ expect(props).toHaveProperty("data");
+ expect(props).toHaveProperty("to");
+ expect(props).toHaveProperty("parent");
+ expect(props).toHaveProperty("wait");
+ });
+
+ it("registers search tool with natural-language trigger guidance", () => {
+ const { tools, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const tool = tools.get("ov_search");
+ expect(tool).toBeDefined();
+ expect(tool!.description).toContain("Search OpenViking resources and skills");
+ expect(tool!.description).toContain("Use after importing");
+ const props = (tool!.parameters as any).properties;
+ expect(props).toHaveProperty("query");
+ expect(props).toHaveProperty("uri");
+ expect(props).toHaveProperty("limit");
+ });
+});
+
+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) => {
+ 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")) {
+ 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,
+ });
+ }
+ return okResponse({
+ memories: [],
+ resources: [],
+ skills: [
+ {
+ context_type: "skill",
+ uri: "viking://agent/skills/install-openviking-memory",
+ level: 0,
+ score: 0.7,
+ category: "",
+ match_reason: "",
+ relations: [],
+ abstract: "Install OpenViking memory integration",
+ overview: null,
+ },
+ ],
+ total: 1,
+ });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { tools, api } = setupPlugin();
+ 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("resource");
+ expect(result.content[0]!.text).toContain("skill");
+ expect(result.details.resources).toHaveLength(1);
+ expect(result.details.skills).toHaveLength(1);
+
+ const findBodies = fetchMock.mock.calls
+ .filter((call) => String(call[0]).endsWith("/api/v1/search/find"))
+ .map((call) => JSON.parse(String((call[1] as RequestInit).body)));
+ expect(findBodies.some((body) => body.target_uri === "viking://resources")).toBe(true);
+ expect(findBodies.some((body) => String(body.target_uri).startsWith("viking://agent/") && String(body.target_uri).endsWith("/skills"))).toBe(true);
+ });
+
+ it("returns partial results when one default scope search fails", 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")) {
+ 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({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { tools, api } = setupPlugin();
+ 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 fetchMock = vi.fn(async (url: string) => {
+ if (url.endsWith("/api/v1/search/find")) {
+ return okResponse({
+ memories: [
+ {
+ context_type: "memory",
+ uri: "viking://user/default/memories/preferences/theme.md",
+ level: 2,
+ score: 0.91,
+ category: "preferences",
+ match_reason: "",
+ relations: [],
+ abstract: "User prefers dark theme",
+ overview: null,
+ },
+ ],
+ resources: [],
+ skills: [],
+ total: 1,
+ });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { tools, api } = setupPlugin();
+ 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");
+ });
+});
+
+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(
+ parseOvImportCommandArgs(String.raw`C:\Users\alice\skill-dir --kind skill --wait`),
+ ).toMatchObject({
+ kind: "skill",
+ source: String.raw`C:\Users\alice\skill-dir`,
+ wait: true,
+ });
+ });
+
+ it("parses ov-import resource flags with resource default", () => {
+ expect(
+ parseOvImportCommandArgs(
+ `./README.md --to viking://resources/readme --reason "project docs" --instruction='summarize APIs' --wait`,
+ ),
+ ).toMatchObject({
+ kind: "resource",
+ source: "./README.md",
+ to: "viking://resources/readme",
+ reason: "project docs",
+ instruction: "summarize APIs",
+ wait: true,
+ });
+ });
+
+ it("keeps unquoted space-containing import sources intact", () => {
+ expect(
+ parseOvImportCommandArgs(
+ `My Docs/README.md --to viking://resources/readme`,
+ ),
+ ).toMatchObject({
+ kind: "resource",
+ source: "My Docs/README.md",
+ to: "viking://resources/readme",
+ });
+ });
+
+ it("rejects resource import with both to and parent", () => {
+ expect(() =>
+ parseOvImportCommandArgs("./README.md --to viking://resources/a --parent viking://resources"),
+ ).toThrow("Cannot specify both");
+ });
+
+ it("parses ov-import skill flags", () => {
+ expect(parseOvImportCommandArgs("./skills/demo --kind skill --wait --timeout=30")).toMatchObject({
+ kind: "skill",
+ source: "./skills/demo",
+ wait: true,
+ timeout: 30,
+ });
+ });
+
+ it("rejects resource-only flags for skill imports", () => {
+ expect(() =>
+ parseOvImportCommandArgs("./skills/demo --kind skill --to viking://resources/nope"),
+ ).toThrow("resource-only");
+ });
+});
+
+describe("OpenViking 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("Plugin registration", () => {
- it("registers all 4 tools", () => {
+ it("registers all 6 tools", () => {
const { api } = setupPlugin();
contextEnginePlugin.register(api as any);
- expect(api.registerTool).toHaveBeenCalledTimes(4);
+ expect(api.registerTool).toHaveBeenCalledTimes(6);
+ });
+
+ it("registers import and search commands", () => {
+ const { commands, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ expect(commands.get("ov-import")).toMatchObject({
+ acceptsArgs: true,
+ description: "Import a resource or skill into OpenViking.",
+ });
+ expect(commands.get("ov-search")).toMatchObject({
+ acceptsArgs: true,
+ description: "Search OpenViking resources and skills.",
+ });
+ });
+
+ it("import and search commands return usage errors when args are missing", async () => {
+ const { commands, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+ const resource = await commands.get("ov-import")!.handler({
+ args: "",
+ commandBody: "/ov-import",
+ });
+ const search = await commands.get("ov-search")!.handler({
+ args: "",
+ commandBody: "/ov-search",
+ });
+ expect(resource.text).toContain("Usage: /ov-import");
+ expect(search.text).toContain("Usage: /ov-search");
+ });
+
+ it("search command propagates agent identity when command ctx includes it", async () => {
+ const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
+ if (url.endsWith("/api/v1/search/find")) {
+ return okResponse({ memories: [], resources: [], skills: [], total: 0 });
+ }
+ return okResponse({});
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { commands, api } = setupPlugin();
+ contextEnginePlugin.register(api as any);
+
+ await commands.get("ov-search")!.handler({
+ args: "test query --uri viking://resources",
+ commandBody: "/ov-search",
+ agentId: "worker",
+ sessionId: "session-1",
+ sessionKey: "agent:worker:session-1",
+ });
+
+ const [, init] = fetchMock.mock.calls.find((call) => String(call[0]).endsWith("/api/v1/search/find")) as [string, RequestInit];
+ const headers = new Headers(init.headers);
+ expect(headers.get("X-OpenViking-Agent")).toBe("worker");
+ });
+
+ it("slash commands honor bypassSessionPatterns", async () => {
+ const fetchMock = vi.fn(async () => okResponse({}));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const { commands, api } = setupPlugin();
+ api.pluginConfig = {
+ ...api.pluginConfig,
+ bypassSessionPatterns: ["agent:bypass:*"],
+ };
+ contextEnginePlugin.register(api as any);
+
+ const search = await commands.get("ov-search")!.handler({
+ args: "test query --uri viking://resources",
+ commandBody: "/ov-search",
+ sessionKey: "agent:bypass:session-1",
+ });
+
+ expect(search.text).toContain("bypassed for this session");
+ expect(fetchMock).not.toHaveBeenCalled();
});
it("registers service with id 'openviking'", () => {